2 * C implementation based on the original Perl and shell versions
4 * Copyright (c) 2013-2014 Timo Teräs <timo.teras@iki.fi>
6 /* ====================================================================
7 * Copyright (c) 2015 The OpenSSL Project. All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in
18 * the documentation and/or other materials provided with the
21 * 3. All advertising materials mentioning features or use of this
22 * software must display the following acknowledgment:
23 * "This product includes software developed by the OpenSSL Project
24 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
26 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27 * endorse or promote products derived from this software without
28 * prior written permission. For written permission, please contact
29 * licensing@OpenSSL.org.
31 * 5. Products derived from this software may not be called "OpenSSL"
32 * nor may "OpenSSL" appear in their names without prior written
33 * permission of the OpenSSL Project.
35 * 6. Redistributions of any form whatsoever must retain the following
37 * "This product includes software developed by the OpenSSL Project
38 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
40 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
44 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51 * OF THE POSSIBILITY OF SUCH DAMAGE.
52 * ====================================================================
54 * This product includes cryptographic software written by Eric Young
55 * (eay@cryptsoft.com). This product includes software written by Tim
56 * Hudson (tjh@cryptsoft.com).
62 #if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__)
69 # include <sys/stat.h>
71 # include "internal/o_dir.h"
72 # include <openssl/evp.h>
73 # include <openssl/pem.h>
74 # include <openssl/x509.h>
77 # define MAX_COLLISIONS 256
79 typedef struct hentry_st {
80 struct hentry_st *next;
82 unsigned short old_id;
83 unsigned char need_symlink;
84 unsigned char digest[EVP_MAX_MD_SIZE];
87 typedef struct bucket_st {
88 struct bucket_st *next;
89 HENTRY *first_entry, *last_entry;
92 unsigned short num_needed;
96 /* Keep in sync with |suffixes|, below. */
97 TYPE_CERT=0, TYPE_CRL=1
101 HASH_OLD, HASH_NEW, HASH_BOTH
105 static int evpmdsize;
106 static const EVP_MD *evpmd;
107 static int remove_links = 1;
108 static int verbose = 0;
109 static BUCKET *hash_table[257];
111 static const char *suffixes[] = { "", "r" };
112 static const char *extensions[] = { "pem", "crt", "cer", "crl" };
115 static void bit_set(unsigned char *set, unsigned int bit)
117 set[bit >> 3] |= 1 << (bit & 0x7);
120 static int bit_isset(unsigned char *set, unsigned int bit)
122 return set[bit >> 3] & (1 << (bit & 0x7));
127 * Process an entry; return number of errors.
129 static int add_entry(enum Type type, unsigned int hash, const char *filename,
130 const unsigned char *digest, int need_symlink,
131 unsigned short old_id)
133 static BUCKET nilbucket;
134 static HENTRY nilhentry;
136 HENTRY *ep, *found = NULL;
137 unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table);
139 for (bp = hash_table[ndx]; bp; bp = bp->next)
140 if (bp->type == type && bp->hash == hash)
143 bp = app_malloc(sizeof(*bp), "hash bucket");
145 bp->next = hash_table[ndx];
148 hash_table[ndx] = bp;
151 for (ep = bp->first_entry; ep; ep = ep->next) {
152 if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) {
154 "%s: skipping duplicate certificate in %s\n",
155 opt_getprog(), filename);
158 if (strcmp(filename, ep->filename) == 0) {
166 if (bp->num_needed >= MAX_COLLISIONS) {
168 "%s: hash table overflow for %s\n",
169 opt_getprog(), filename);
172 ep = app_malloc(sizeof(*ep), "collision bucket");
175 ep->filename = BUF_strdup(filename);
177 bp->last_entry->next = ep;
178 if (bp->first_entry == NULL)
179 bp->first_entry = ep;
183 if (old_id < ep->old_id)
185 if (need_symlink && !ep->need_symlink) {
186 ep->need_symlink = 1;
188 memcpy(ep->digest, digest, evpmdsize);
194 * Check if a symlink goes to the right spot; return 0 if okay.
195 * This can be -1 if bad filename, or an error count.
197 static int handle_symlink(const char *filename, const char *fullpath)
199 unsigned int hash = 0;
202 char linktarget[NAME_MAX], *endptr;
205 for (i = 0; i < 8; i++) {
212 if (filename[i++] != '.')
214 for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--)
215 if (strcasecmp(suffixes[type], &filename[i]) == 0)
217 i += strlen(suffixes[type]);
219 id = strtoul(&filename[i], &endptr, 10);
223 n = readlink(fullpath, linktarget, sizeof(linktarget));
224 if (n < 0 || n >= (int)sizeof(linktarget))
228 return add_entry(type, hash, linktarget, NULL, 0, id);
232 * process a file, return number of errors.
234 static int do_file(const char *filename, const char *fullpath, enum Hash h)
236 STACK_OF (X509_INFO) *inf = NULL;
238 X509_NAME *name = NULL;
241 unsigned char digest[EVP_MAX_MD_SIZE];
245 /* Does it end with a recognized extension? */
246 if ((ext = strrchr(filename, '.')) == NULL)
248 for (i = 0; i < OSSL_NELEM(extensions); i++) {
249 if (strcasecmp(extensions[i], ext + 1) == 0)
252 if (i >= OSSL_NELEM(extensions))
255 /* Does it have X.509 data in it? */
256 if ((b = BIO_new_file(fullpath, "r")) == NULL) {
257 BIO_printf(bio_err, "%s: skipping %s, cannot open file\n",
258 opt_getprog(), filename);
262 inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
267 if (sk_X509_INFO_num(inf) != 1) {
270 "it does not contain exactly one certificate or CRL\n",
271 opt_getprog(), filename);
272 /* This is not an error. */
275 x = sk_X509_INFO_value(inf, 0);
278 name = X509_get_subject_name(x->x509);
279 X509_digest(x->x509, evpmd, digest, NULL);
282 name = X509_CRL_get_issuer(x->crl);
283 X509_CRL_digest(x->crl, evpmd, digest, NULL);
289 if ((h == HASH_NEW) || (h == HASH_BOTH))
290 errs += add_entry(type, X509_NAME_hash(name), filename, digest, 1, ~0);
291 if ((h == HASH_OLD) || (h == HASH_BOTH))
292 errs += add_entry(type, X509_NAME_hash_old(name), filename, digest, 1, ~0);
296 sk_X509_INFO_pop_free(inf, X509_INFO_free);
301 * Process a directory; return number of errors found.
303 static int do_dir(const char *dirname, enum Hash h)
307 OPENSSL_DIR_CTX *d = NULL;
309 unsigned char idmask[MAX_COLLISIONS / 8];
310 int n, nextid, buflen, errs = 0;
313 const char *filename;
316 if (app_access(dirname, W_OK) < 0) {
317 BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
320 buflen = strlen(dirname);
321 pathsep = (buflen && dirname[buflen - 1] == '/') ? "" : "/";
322 buflen += NAME_MAX + 2;
323 buf = app_malloc(buflen, "filename buffer");
326 BIO_printf(bio_out, "Doing %s\n", dirname);
328 while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
329 if (snprintf(buf, buflen, "%s%s%s",
330 dirname, pathsep, filename) >= buflen)
332 if (lstat(buf, &st) < 0)
334 if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
336 errs += do_file(filename, buf, h);
340 for (i = 0; i < OSSL_NELEM(hash_table); i++) {
341 for (bp = hash_table[i]; bp; bp = nextbp) {
344 memset(idmask, 0, (bp->num_needed + 7) / 8);
345 for (ep = bp->first_entry; ep; ep = ep->next)
346 if (ep->old_id < bp->num_needed)
347 bit_set(idmask, ep->old_id);
349 for (ep = bp->first_entry; ep; ep = nextep) {
351 if (ep->old_id < bp->num_needed) {
352 /* Link exists, and is used as-is */
353 snprintf(buf, buflen, "%08x.%s%d", bp->hash,
354 suffixes[bp->type], ep->old_id);
356 BIO_printf(bio_out, "link %s -> %s\n",
358 } else if (ep->need_symlink) {
359 /* New link needed (it may replace something) */
360 while (bit_isset(idmask, nextid))
363 snprintf(buf, buflen, "%s%s%n%08x.%s%d",
364 dirname, pathsep, &n, bp->hash,
365 suffixes[bp->type], nextid);
367 BIO_printf(bio_out, "link %s -> %s\n",
368 ep->filename, &buf[n]);
369 if (unlink(buf) < 0 && errno != ENOENT) {
371 "%s: Can't unlink %s, %s\n",
372 opt_getprog(), buf, strerror(errno));
375 if (symlink(ep->filename, buf) < 0) {
377 "%s: Can't symlink %s, %s\n",
378 opt_getprog(), ep->filename,
382 } else if (remove_links) {
383 /* Link to be deleted */
384 snprintf(buf, buflen, "%s%s%n%08x.%s%d",
385 dirname, pathsep, &n, bp->hash,
386 suffixes[bp->type], ep->old_id);
388 BIO_printf(bio_out, "unlink %s\n",
390 if (unlink(buf) < 0 && errno != ENOENT) {
392 "%s: Can't unlink %s, %s\n",
393 opt_getprog(), buf, strerror(errno));
397 OPENSSL_free(ep->filename);
402 hash_table[i] = NULL;
409 typedef enum OPTION_choice {
410 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
411 OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE
414 OPTIONS rehash_options[] = {
415 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert-directory...]\n"},
416 {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
417 {"help", OPT_HELP, '-', "Display this summary"},
418 {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
419 {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
420 {"n", OPT_N, '-', "Do not remove existing links"},
421 {"v", OPT_VERBOSE, '-', "Verbose output"},
426 int rehash_main(int argc, char **argv)
428 const char *env, *prog;
432 enum Hash h = HASH_NEW;
434 prog = opt_init(argc, argv, rehash_options);
435 while ((o = opt_next()) != OPT_EOF) {
439 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
442 opt_help(rehash_options);
458 argc = opt_num_rest();
462 evpmdsize = EVP_MD_size(evpmd);
466 errs += do_dir(*argv++, h);
467 } else if ((env = getenv("SSL_CERT_DIR")) != NULL) {
469 for (e = strtok(m, ":"); e != NULL; e = strtok(NULL, ":"))
470 errs += do_dir(e, h);
473 errs += do_dir("/etc/ssl/certs", h);
481 OPTIONS rehash_options[] = {
485 int rehash_main(int argc, char **argv)
487 BIO_printf(bio_err, "Not available; use c_rehash script\n");
491 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */