2 * Copyright 2015-2017 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2013-2014 Timo Teräs <timo.teras@gmail.com>
5 * Licensed under the OpenSSL license (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
13 #if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) || \
14 (defined(__VMS) && defined(__DECC) && __CRTL_VER >= 80300000)
21 # include <sys/stat.h>
24 * Make sure that the processing of symbol names is treated the same as when
25 * libcrypto is built. This is done automatically for public headers (see
26 * include/openssl/__DECC_INCLUDE_PROLOGUE.H and __DECC_INCLUDE_EPILOGUE.H),
27 * but not for internal headers.
31 # pragma names as_is,shortened
34 # include "internal/o_dir.h"
37 # pragma names restore
40 # include <openssl/evp.h>
41 # include <openssl/pem.h>
42 # include <openssl/x509.h>
46 # define PATH_MAX 4096
51 # define MAX_COLLISIONS 256
53 typedef struct hentry_st {
54 struct hentry_st *next;
56 unsigned short old_id;
57 unsigned char need_symlink;
58 unsigned char digest[EVP_MAX_MD_SIZE];
61 typedef struct bucket_st {
62 struct bucket_st *next;
63 HENTRY *first_entry, *last_entry;
66 unsigned short num_needed;
70 /* Keep in sync with |suffixes|, below. */
71 TYPE_CERT=0, TYPE_CRL=1
75 HASH_OLD, HASH_NEW, HASH_BOTH
80 static const EVP_MD *evpmd;
81 static int remove_links = 1;
82 static int verbose = 0;
83 static BUCKET *hash_table[257];
85 static const char *suffixes[] = { "", "r" };
86 static const char *extensions[] = { "pem", "crt", "cer", "crl" };
89 static void bit_set(unsigned char *set, unsigned int bit)
91 set[bit >> 3] |= 1 << (bit & 0x7);
94 static int bit_isset(unsigned char *set, unsigned int bit)
96 return set[bit >> 3] & (1 << (bit & 0x7));
101 * Process an entry; return number of errors.
103 static int add_entry(enum Type type, unsigned int hash, const char *filename,
104 const unsigned char *digest, int need_symlink,
105 unsigned short old_id)
107 static BUCKET nilbucket;
108 static HENTRY nilhentry;
110 HENTRY *ep, *found = NULL;
111 unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table);
113 for (bp = hash_table[ndx]; bp; bp = bp->next)
114 if (bp->type == type && bp->hash == hash)
117 bp = app_malloc(sizeof(*bp), "hash bucket");
119 bp->next = hash_table[ndx];
122 hash_table[ndx] = bp;
125 for (ep = bp->first_entry; ep; ep = ep->next) {
126 if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) {
128 "%s: skipping duplicate %s in %s\n", opt_getprog(),
129 type == TYPE_CERT ? "certificate" : "CRL", filename);
132 if (strcmp(filename, ep->filename) == 0) {
140 if (bp->num_needed >= MAX_COLLISIONS) {
142 "%s: hash table overflow for %s\n",
143 opt_getprog(), filename);
146 ep = app_malloc(sizeof(*ep), "collision bucket");
149 ep->filename = OPENSSL_strdup(filename);
151 bp->last_entry->next = ep;
152 if (bp->first_entry == NULL)
153 bp->first_entry = ep;
157 if (old_id < ep->old_id)
159 if (need_symlink && !ep->need_symlink) {
160 ep->need_symlink = 1;
162 memcpy(ep->digest, digest, evpmdsize);
168 * Check if a symlink goes to the right spot; return 0 if okay.
169 * This can be -1 if bad filename, or an error count.
171 static int handle_symlink(const char *filename, const char *fullpath)
173 unsigned int hash = 0;
176 char linktarget[PATH_MAX], *endptr;
179 for (i = 0; i < 8; i++) {
184 hash += OPENSSL_hexchar2int(ch);
186 if (filename[i++] != '.')
188 for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--) {
189 const char *suffix = suffixes[type];
190 if (strncasecmp(suffix, &filename[i], strlen(suffix)) == 0)
193 i += strlen(suffixes[type]);
195 id = strtoul(&filename[i], &endptr, 10);
199 n = readlink(fullpath, linktarget, sizeof(linktarget));
200 if (n < 0 || n >= (int)sizeof(linktarget))
204 return add_entry(type, hash, linktarget, NULL, 0, id);
208 * process a file, return number of errors.
210 static int do_file(const char *filename, const char *fullpath, enum Hash h)
212 STACK_OF (X509_INFO) *inf = NULL;
214 X509_NAME *name = NULL;
217 unsigned char digest[EVP_MAX_MD_SIZE];
221 /* Does it end with a recognized extension? */
222 if ((ext = strrchr(filename, '.')) == NULL)
224 for (i = 0; i < OSSL_NELEM(extensions); i++) {
225 if (strcasecmp(extensions[i], ext + 1) == 0)
228 if (i >= OSSL_NELEM(extensions))
231 /* Does it have X.509 data in it? */
232 if ((b = BIO_new_file(fullpath, "r")) == NULL) {
233 BIO_printf(bio_err, "%s: skipping %s, cannot open file\n",
234 opt_getprog(), filename);
238 inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
243 if (sk_X509_INFO_num(inf) != 1) {
246 "it does not contain exactly one certificate or CRL\n",
247 opt_getprog(), filename);
248 /* This is not an error. */
251 x = sk_X509_INFO_value(inf, 0);
252 if (x->x509 != NULL) {
254 name = X509_get_subject_name(x->x509);
255 X509_digest(x->x509, evpmd, digest, NULL);
256 } else if (x->crl != NULL) {
258 name = X509_CRL_get_issuer(x->crl);
259 X509_CRL_digest(x->crl, evpmd, digest, NULL);
265 if ((h == HASH_NEW) || (h == HASH_BOTH))
266 errs += add_entry(type, X509_NAME_hash(name), filename, digest, 1, ~0);
267 if ((h == HASH_OLD) || (h == HASH_BOTH))
268 errs += add_entry(type, X509_NAME_hash_old(name), filename, digest, 1, ~0);
272 sk_X509_INFO_pop_free(inf, X509_INFO_free);
276 static void str_free(char *s)
281 static int ends_with_dirsep(const char *path)
284 path += strlen(path) - 1;
286 if (*path == ']' || *path == '>' || *path == ':')
288 # elif defined _WIN32
295 static int massage_filename(char *name)
298 char *p = strchr(name, ';');
302 for (q++; *q != '\0'; q++) {
303 if (!isdigit((unsigned char)*q))
314 * Process a directory; return number of errors found.
316 static int do_dir(const char *dirname, enum Hash h)
320 OPENSSL_DIR_CTX *d = NULL;
322 unsigned char idmask[MAX_COLLISIONS / 8];
323 int n, numfiles, nextid, buflen, errs = 0;
326 const char *filename;
328 STACK_OF(OPENSSL_STRING) *files = NULL;
330 if (app_access(dirname, W_OK) < 0) {
331 BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
334 buflen = strlen(dirname);
335 pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
336 buflen += NAME_MAX + 1 + 1;
337 buf = app_malloc(buflen, "filename buffer");
340 BIO_printf(bio_out, "Doing %s\n", dirname);
342 if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
343 BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
346 while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
347 if ((copy = strdup(filename)) == NULL
348 || !massage_filename(copy)
349 || sk_OPENSSL_STRING_push(files, copy) == 0) {
350 BIO_puts(bio_err, "out of memory\n");
355 sk_OPENSSL_STRING_sort(files);
357 numfiles = sk_OPENSSL_STRING_num(files);
358 for (n = 0; n < numfiles; ++n) {
359 filename = sk_OPENSSL_STRING_value(files, n);
360 if (BIO_snprintf(buf, buflen, "%s%s%s",
361 dirname, pathsep, filename) >= buflen)
363 if (lstat(buf, &st) < 0)
365 if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
367 errs += do_file(filename, buf, h);
369 sk_OPENSSL_STRING_pop_free(files, str_free);
371 for (i = 0; i < OSSL_NELEM(hash_table); i++) {
372 for (bp = hash_table[i]; bp; bp = nextbp) {
375 memset(idmask, 0, (bp->num_needed + 7) / 8);
376 for (ep = bp->first_entry; ep; ep = ep->next)
377 if (ep->old_id < bp->num_needed)
378 bit_set(idmask, ep->old_id);
380 for (ep = bp->first_entry; ep; ep = nextep) {
382 if (ep->old_id < bp->num_needed) {
383 /* Link exists, and is used as-is */
384 BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash,
385 suffixes[bp->type], ep->old_id);
387 BIO_printf(bio_out, "link %s -> %s\n",
389 } else if (ep->need_symlink) {
390 /* New link needed (it may replace something) */
391 while (bit_isset(idmask, nextid))
394 BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
395 dirname, pathsep, &n, bp->hash,
396 suffixes[bp->type], nextid);
398 BIO_printf(bio_out, "link %s -> %s\n",
399 ep->filename, &buf[n]);
400 if (unlink(buf) < 0 && errno != ENOENT) {
402 "%s: Can't unlink %s, %s\n",
403 opt_getprog(), buf, strerror(errno));
406 if (symlink(ep->filename, buf) < 0) {
408 "%s: Can't symlink %s, %s\n",
409 opt_getprog(), ep->filename,
413 bit_set(idmask, nextid);
414 } else if (remove_links) {
415 /* Link to be deleted */
416 BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
417 dirname, pathsep, &n, bp->hash,
418 suffixes[bp->type], ep->old_id);
420 BIO_printf(bio_out, "unlink %s\n",
422 if (unlink(buf) < 0 && errno != ENOENT) {
424 "%s: Can't unlink %s, %s\n",
425 opt_getprog(), buf, strerror(errno));
429 OPENSSL_free(ep->filename);
434 hash_table[i] = NULL;
441 typedef enum OPTION_choice {
442 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
443 OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE
446 const OPTIONS rehash_options[] = {
447 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert-directory...]\n"},
448 {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
449 {"help", OPT_HELP, '-', "Display this summary"},
450 {"h", OPT_HELP, '-', "Display this summary"},
451 {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
452 {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
453 {"n", OPT_N, '-', "Do not remove existing links"},
454 {"v", OPT_VERBOSE, '-', "Verbose output"},
459 int rehash_main(int argc, char **argv)
461 const char *env, *prog;
465 enum Hash h = HASH_NEW;
467 prog = opt_init(argc, argv, rehash_options);
468 while ((o = opt_next()) != OPT_EOF) {
472 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
475 opt_help(rehash_options);
491 argc = opt_num_rest();
495 evpmdsize = EVP_MD_size(evpmd);
498 while (*argv != NULL)
499 errs += do_dir(*argv++, h);
500 } else if ((env = getenv("SSL_CERT_DIR")) != NULL) {
501 m = OPENSSL_strdup(env);
502 for (e = strtok(m, ":"); e != NULL; e = strtok(NULL, ":"))
503 errs += do_dir(e, h);
506 errs += do_dir("/etc/ssl/certs", h);
514 const OPTIONS rehash_options[] = {
518 int rehash_main(int argc, char **argv)
520 BIO_printf(bio_err, "Not available; use c_rehash script\n");
524 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */