2 * Copyright 2015-2020 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
14 #if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) || \
15 (defined(__VMS) && defined(__DECC) && __CRTL_VER >= 80300000)
22 # include <sys/stat.h>
25 * Make sure that the processing of symbol names is treated the same as when
26 * libcrypto is built. This is done automatically for public headers (see
27 * include/openssl/__DECC_INCLUDE_PROLOGUE.H and __DECC_INCLUDE_EPILOGUE.H),
28 * but not for internal headers.
32 # pragma names as_is,shortened
35 # include "internal/o_dir.h"
38 # pragma names restore
41 # include <openssl/evp.h>
42 # include <openssl/pem.h>
43 # include <openssl/x509.h>
47 # define PATH_MAX 4096
52 # define MAX_COLLISIONS 256
54 # if defined(OPENSSL_SYS_VXWORKS)
56 * VxWorks has no symbolic links
59 # define lstat(path, buf) stat(path, buf)
61 int symlink(const char *target, const char *linkpath)
67 ssize_t readlink(const char *pathname, char *buf, size_t bufsiz)
74 typedef struct hentry_st {
75 struct hentry_st *next;
77 unsigned short old_id;
78 unsigned char need_symlink;
79 unsigned char digest[EVP_MAX_MD_SIZE];
82 typedef struct bucket_st {
83 struct bucket_st *next;
84 HENTRY *first_entry, *last_entry;
87 unsigned short num_needed;
91 /* Keep in sync with |suffixes|, below. */
92 TYPE_CERT=0, TYPE_CRL=1
96 HASH_OLD, HASH_NEW, HASH_BOTH
100 static int evpmdsize;
101 static const EVP_MD *evpmd;
102 static int remove_links = 1;
103 static int verbose = 0;
104 static BUCKET *hash_table[257];
106 static const char *suffixes[] = { "", "r" };
107 static const char *extensions[] = { "pem", "crt", "cer", "crl" };
110 static void bit_set(unsigned char *set, unsigned int bit)
112 set[bit >> 3] |= 1 << (bit & 0x7);
115 static int bit_isset(unsigned char *set, unsigned int bit)
117 return set[bit >> 3] & (1 << (bit & 0x7));
122 * Process an entry; return number of errors.
124 static int add_entry(enum Type type, unsigned int hash, const char *filename,
125 const unsigned char *digest, int need_symlink,
126 unsigned short old_id)
128 static BUCKET nilbucket;
129 static HENTRY nilhentry;
131 HENTRY *ep, *found = NULL;
132 unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table);
134 for (bp = hash_table[ndx]; bp; bp = bp->next)
135 if (bp->type == type && bp->hash == hash)
138 bp = app_malloc(sizeof(*bp), "hash bucket");
140 bp->next = hash_table[ndx];
143 hash_table[ndx] = bp;
146 for (ep = bp->first_entry; ep; ep = ep->next) {
147 if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) {
149 "%s: warning: skipping duplicate %s in %s\n",
151 type == TYPE_CERT ? "certificate" : "CRL", filename);
154 if (strcmp(filename, ep->filename) == 0) {
162 if (bp->num_needed >= MAX_COLLISIONS) {
164 "%s: error: hash table overflow for %s\n",
165 opt_getprog(), filename);
168 ep = app_malloc(sizeof(*ep), "collision bucket");
171 ep->filename = OPENSSL_strdup(filename);
173 bp->last_entry->next = ep;
174 if (bp->first_entry == NULL)
175 bp->first_entry = ep;
179 if (old_id < ep->old_id)
181 if (need_symlink && !ep->need_symlink) {
182 ep->need_symlink = 1;
184 memcpy(ep->digest, digest, evpmdsize);
190 * Check if a symlink goes to the right spot; return 0 if okay.
191 * This can be -1 if bad filename, or an error count.
193 static int handle_symlink(const char *filename, const char *fullpath)
195 unsigned int hash = 0;
198 char linktarget[PATH_MAX], *endptr;
201 for (i = 0; i < 8; i++) {
206 hash += OPENSSL_hexchar2int(ch);
208 if (filename[i++] != '.')
210 for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--) {
211 const char *suffix = suffixes[type];
212 if (strncasecmp(suffix, &filename[i], strlen(suffix)) == 0)
215 i += strlen(suffixes[type]);
217 id = strtoul(&filename[i], &endptr, 10);
221 n = readlink(fullpath, linktarget, sizeof(linktarget));
222 if (n < 0 || n >= (int)sizeof(linktarget))
226 return add_entry(type, hash, linktarget, NULL, 0, id);
230 * process a file, return number of errors.
232 static int do_file(const char *filename, const char *fullpath, enum Hash h)
234 STACK_OF (X509_INFO) *inf = NULL;
236 X509_NAME *name = NULL;
239 unsigned char digest[EVP_MAX_MD_SIZE];
243 /* Does it end with a recognized extension? */
244 if ((ext = strrchr(filename, '.')) == NULL)
246 for (i = 0; i < OSSL_NELEM(extensions); i++) {
247 if (strcasecmp(extensions[i], ext + 1) == 0)
250 if (i >= OSSL_NELEM(extensions))
253 /* Does it have X.509 data in it? */
254 if ((b = BIO_new_file(fullpath, "r")) == NULL) {
255 BIO_printf(bio_err, "%s: error: skipping %s, cannot open file\n",
256 opt_getprog(), filename);
260 inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
265 if (sk_X509_INFO_num(inf) != 1) {
267 "%s: warning: skipping %s,"
268 "it does not contain exactly one certificate or CRL\n",
269 opt_getprog(), filename);
270 /* This is not an error. */
273 x = sk_X509_INFO_value(inf, 0);
274 if (x->x509 != NULL) {
276 name = X509_get_subject_name(x->x509);
277 if (!X509_digest(x->x509, evpmd, digest, NULL)) {
278 BIO_printf(bio_err, "out of memory\n");
282 } else if (x->crl != NULL) {
284 name = X509_CRL_get_issuer(x->crl);
285 if (!X509_CRL_digest(x->crl, evpmd, digest, NULL)) {
286 BIO_printf(bio_err, "out of memory\n");
295 if ((h == HASH_NEW) || (h == HASH_BOTH))
296 errs += add_entry(type, X509_NAME_hash(name), filename, digest, 1, ~0);
297 if ((h == HASH_OLD) || (h == HASH_BOTH))
298 errs += add_entry(type, X509_NAME_hash_old(name), filename, digest, 1, ~0);
302 sk_X509_INFO_pop_free(inf, X509_INFO_free);
306 static void str_free(char *s)
311 static int ends_with_dirsep(const char *path)
314 path += strlen(path) - 1;
316 if (*path == ']' || *path == '>' || *path == ':')
318 # elif defined _WIN32
326 * Process a directory; return number of errors found.
328 static int do_dir(const char *dirname, enum Hash h)
332 OPENSSL_DIR_CTX *d = NULL;
334 unsigned char idmask[MAX_COLLISIONS / 8];
335 int n, numfiles, nextid, buflen, errs = 0;
338 const char *filename;
339 char *buf, *copy = NULL;
340 STACK_OF(OPENSSL_STRING) *files = NULL;
342 if (app_access(dirname, W_OK) < 0) {
343 BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
346 buflen = strlen(dirname);
347 pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
348 buflen += NAME_MAX + 1 + 1;
349 buf = app_malloc(buflen, "filename buffer");
352 BIO_printf(bio_out, "Doing %s\n", dirname);
354 if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
355 BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
359 while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
360 if ((copy = OPENSSL_strdup(filename)) == NULL
361 || sk_OPENSSL_STRING_push(files, copy) == 0) {
363 BIO_puts(bio_err, "out of memory\n");
369 sk_OPENSSL_STRING_sort(files);
371 numfiles = sk_OPENSSL_STRING_num(files);
372 for (n = 0; n < numfiles; ++n) {
373 filename = sk_OPENSSL_STRING_value(files, n);
374 if (BIO_snprintf(buf, buflen, "%s%s%s",
375 dirname, pathsep, filename) >= buflen)
377 if (lstat(buf, &st) < 0)
379 if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
381 errs += do_file(filename, buf, h);
384 for (i = 0; i < OSSL_NELEM(hash_table); i++) {
385 for (bp = hash_table[i]; bp; bp = nextbp) {
388 memset(idmask, 0, (bp->num_needed + 7) / 8);
389 for (ep = bp->first_entry; ep; ep = ep->next)
390 if (ep->old_id < bp->num_needed)
391 bit_set(idmask, ep->old_id);
393 for (ep = bp->first_entry; ep; ep = nextep) {
395 if (ep->old_id < bp->num_needed) {
396 /* Link exists, and is used as-is */
397 BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash,
398 suffixes[bp->type], ep->old_id);
400 BIO_printf(bio_out, "link %s -> %s\n",
402 } else if (ep->need_symlink) {
403 /* New link needed (it may replace something) */
404 while (bit_isset(idmask, nextid))
407 BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
408 dirname, pathsep, &n, bp->hash,
409 suffixes[bp->type], nextid);
411 BIO_printf(bio_out, "link %s -> %s\n",
412 ep->filename, &buf[n]);
413 if (unlink(buf) < 0 && errno != ENOENT) {
415 "%s: Can't unlink %s, %s\n",
416 opt_getprog(), buf, strerror(errno));
419 if (symlink(ep->filename, buf) < 0) {
421 "%s: Can't symlink %s, %s\n",
422 opt_getprog(), ep->filename,
426 bit_set(idmask, nextid);
427 } else if (remove_links) {
428 /* Link to be deleted */
429 BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
430 dirname, pathsep, &n, bp->hash,
431 suffixes[bp->type], ep->old_id);
433 BIO_printf(bio_out, "unlink %s\n",
435 if (unlink(buf) < 0 && errno != ENOENT) {
437 "%s: Can't unlink %s, %s\n",
438 opt_getprog(), buf, strerror(errno));
442 OPENSSL_free(ep->filename);
447 hash_table[i] = NULL;
451 sk_OPENSSL_STRING_pop_free(files, str_free);
456 typedef enum OPTION_choice {
457 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
458 OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE
461 const OPTIONS rehash_options[] = {
462 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert-directory...]\n"},
463 {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
464 {"help", OPT_HELP, '-', "Display this summary"},
465 {"h", OPT_HELP, '-', "Display this summary"},
466 {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
467 {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
468 {"n", OPT_N, '-', "Do not remove existing links"},
469 {"v", OPT_VERBOSE, '-', "Verbose output"},
474 int rehash_main(int argc, char **argv)
476 const char *env, *prog;
480 enum Hash h = HASH_NEW;
482 prog = opt_init(argc, argv, rehash_options);
483 while ((o = opt_next()) != OPT_EOF) {
487 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
490 opt_help(rehash_options);
506 argc = opt_num_rest();
510 evpmdsize = EVP_MD_size(evpmd);
513 while (*argv != NULL)
514 errs += do_dir(*argv++, h);
515 } else if ((env = getenv(X509_get_default_cert_dir_env())) != NULL) {
516 char lsc[2] = { LIST_SEPARATOR_CHAR, '\0' };
517 m = OPENSSL_strdup(env);
518 for (e = strtok(m, lsc); e != NULL; e = strtok(NULL, lsc))
519 errs += do_dir(e, h);
522 errs += do_dir(X509_get_default_cert_dir(), h);
530 const OPTIONS rehash_options[] = {
534 int rehash_main(int argc, char **argv)
536 BIO_printf(bio_err, "Not available; use c_rehash script\n");
540 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */