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 Apache License 2.0 (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>
45 DEFINE_STACK_OF(X509_INFO)
46 DEFINE_STACK_OF_STRING()
49 # define PATH_MAX 4096
54 # define MAX_COLLISIONS 256
56 # if defined(OPENSSL_SYS_VXWORKS)
58 * VxWorks has no symbolic links
61 # define lstat(path, buf) stat(path, buf)
63 int symlink(const char *target, const char *linkpath)
69 ssize_t readlink(const char *pathname, char *buf, size_t bufsiz)
76 typedef struct hentry_st {
77 struct hentry_st *next;
79 unsigned short old_id;
80 unsigned char need_symlink;
81 unsigned char digest[EVP_MAX_MD_SIZE];
84 typedef struct bucket_st {
85 struct bucket_st *next;
86 HENTRY *first_entry, *last_entry;
89 unsigned short num_needed;
93 /* Keep in sync with |suffixes|, below. */
94 TYPE_CERT=0, TYPE_CRL=1
98 HASH_OLD, HASH_NEW, HASH_BOTH
102 static int evpmdsize;
103 static const EVP_MD *evpmd;
104 static int remove_links = 1;
105 static int verbose = 0;
106 static BUCKET *hash_table[257];
108 static const char *suffixes[] = { "", "r" };
109 static const char *extensions[] = { "pem", "crt", "cer", "crl" };
112 static void bit_set(unsigned char *set, unsigned int bit)
114 set[bit >> 3] |= 1 << (bit & 0x7);
117 static int bit_isset(unsigned char *set, unsigned int bit)
119 return set[bit >> 3] & (1 << (bit & 0x7));
124 * Process an entry; return number of errors.
126 static int add_entry(enum Type type, unsigned int hash, const char *filename,
127 const unsigned char *digest, int need_symlink,
128 unsigned short old_id)
130 static BUCKET nilbucket;
131 static HENTRY nilhentry;
133 HENTRY *ep, *found = NULL;
134 unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table);
136 for (bp = hash_table[ndx]; bp; bp = bp->next)
137 if (bp->type == type && bp->hash == hash)
140 bp = app_malloc(sizeof(*bp), "hash bucket");
142 bp->next = hash_table[ndx];
145 hash_table[ndx] = bp;
148 for (ep = bp->first_entry; ep; ep = ep->next) {
149 if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) {
151 "%s: warning: skipping duplicate %s in %s\n",
153 type == TYPE_CERT ? "certificate" : "CRL", filename);
156 if (strcmp(filename, ep->filename) == 0) {
164 if (bp->num_needed >= MAX_COLLISIONS) {
166 "%s: error: hash table overflow for %s\n",
167 opt_getprog(), filename);
170 ep = app_malloc(sizeof(*ep), "collision bucket");
173 ep->filename = OPENSSL_strdup(filename);
175 bp->last_entry->next = ep;
176 if (bp->first_entry == NULL)
177 bp->first_entry = ep;
181 if (old_id < ep->old_id)
183 if (need_symlink && !ep->need_symlink) {
184 ep->need_symlink = 1;
186 memcpy(ep->digest, digest, evpmdsize);
192 * Check if a symlink goes to the right spot; return 0 if okay.
193 * This can be -1 if bad filename, or an error count.
195 static int handle_symlink(const char *filename, const char *fullpath)
197 unsigned int hash = 0;
200 char linktarget[PATH_MAX], *endptr;
203 for (i = 0; i < 8; i++) {
208 hash += OPENSSL_hexchar2int(ch);
210 if (filename[i++] != '.')
212 for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--) {
213 const char *suffix = suffixes[type];
214 if (strncasecmp(suffix, &filename[i], strlen(suffix)) == 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 const 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: error: 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) {
269 "%s: warning: skipping %s,"
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);
276 if (x->x509 != NULL) {
278 name = X509_get_subject_name(x->x509);
279 if (!X509_digest(x->x509, evpmd, digest, NULL)) {
280 BIO_printf(bio_err, "out of memory\n");
284 } else if (x->crl != NULL) {
286 name = X509_CRL_get_issuer(x->crl);
287 if (!X509_CRL_digest(x->crl, evpmd, digest, NULL)) {
288 BIO_printf(bio_err, "out of memory\n");
297 if ((h == HASH_NEW) || (h == HASH_BOTH))
298 errs += add_entry(type, X509_NAME_hash(name), filename, digest, 1, ~0);
299 if ((h == HASH_OLD) || (h == HASH_BOTH))
300 errs += add_entry(type, X509_NAME_hash_old(name), filename, digest, 1, ~0);
304 sk_X509_INFO_pop_free(inf, X509_INFO_free);
308 static void str_free(char *s)
313 static int ends_with_dirsep(const char *path)
316 path += strlen(path) - 1;
318 if (*path == ']' || *path == '>' || *path == ':')
320 # elif defined _WIN32
328 * Process a directory; return number of errors found.
330 static int do_dir(const char *dirname, enum Hash h)
334 OPENSSL_DIR_CTX *d = NULL;
336 unsigned char idmask[MAX_COLLISIONS / 8];
337 int n, numfiles, nextid, buflen, errs = 0;
340 const char *filename;
341 char *buf, *copy = NULL;
342 STACK_OF(OPENSSL_STRING) *files = NULL;
344 if (app_access(dirname, W_OK) < 0) {
345 BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
348 buflen = strlen(dirname);
349 pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
350 buflen += NAME_MAX + 1 + 1;
351 buf = app_malloc(buflen, "filename buffer");
354 BIO_printf(bio_out, "Doing %s\n", dirname);
356 if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
357 BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
361 while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
362 if ((copy = OPENSSL_strdup(filename)) == NULL
363 || sk_OPENSSL_STRING_push(files, copy) == 0) {
365 BIO_puts(bio_err, "out of memory\n");
371 sk_OPENSSL_STRING_sort(files);
373 numfiles = sk_OPENSSL_STRING_num(files);
374 for (n = 0; n < numfiles; ++n) {
375 filename = sk_OPENSSL_STRING_value(files, n);
376 if (BIO_snprintf(buf, buflen, "%s%s%s",
377 dirname, pathsep, filename) >= buflen)
379 if (lstat(buf, &st) < 0)
381 if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
383 errs += do_file(filename, buf, h);
386 for (i = 0; i < OSSL_NELEM(hash_table); i++) {
387 for (bp = hash_table[i]; bp; bp = nextbp) {
390 memset(idmask, 0, (bp->num_needed + 7) / 8);
391 for (ep = bp->first_entry; ep; ep = ep->next)
392 if (ep->old_id < bp->num_needed)
393 bit_set(idmask, ep->old_id);
395 for (ep = bp->first_entry; ep; ep = nextep) {
397 if (ep->old_id < bp->num_needed) {
398 /* Link exists, and is used as-is */
399 BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash,
400 suffixes[bp->type], ep->old_id);
402 BIO_printf(bio_out, "link %s -> %s\n",
404 } else if (ep->need_symlink) {
405 /* New link needed (it may replace something) */
406 while (bit_isset(idmask, nextid))
409 BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
410 dirname, pathsep, &n, bp->hash,
411 suffixes[bp->type], nextid);
413 BIO_printf(bio_out, "link %s -> %s\n",
414 ep->filename, &buf[n]);
415 if (unlink(buf) < 0 && errno != ENOENT) {
417 "%s: Can't unlink %s, %s\n",
418 opt_getprog(), buf, strerror(errno));
421 if (symlink(ep->filename, buf) < 0) {
423 "%s: Can't symlink %s, %s\n",
424 opt_getprog(), ep->filename,
428 bit_set(idmask, nextid);
429 } else if (remove_links) {
430 /* Link to be deleted */
431 BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
432 dirname, pathsep, &n, bp->hash,
433 suffixes[bp->type], ep->old_id);
435 BIO_printf(bio_out, "unlink %s\n",
437 if (unlink(buf) < 0 && errno != ENOENT) {
439 "%s: Can't unlink %s, %s\n",
440 opt_getprog(), buf, strerror(errno));
444 OPENSSL_free(ep->filename);
449 hash_table[i] = NULL;
453 sk_OPENSSL_STRING_pop_free(files, str_free);
458 typedef enum OPTION_choice {
459 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
460 OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE,
464 const OPTIONS rehash_options[] = {
465 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [directory...]\n"},
467 OPT_SECTION("General"),
468 {"help", OPT_HELP, '-', "Display this summary"},
469 {"h", OPT_HELP, '-', "Display this summary"},
470 {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
471 {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
472 {"n", OPT_N, '-', "Do not remove existing links"},
474 OPT_SECTION("Output"),
475 {"v", OPT_VERBOSE, '-', "Verbose output"},
480 {"directory", 0, 0, "One or more directories to process (optional)"},
485 int rehash_main(int argc, char **argv)
487 const char *env, *prog;
491 enum Hash h = HASH_NEW;
493 prog = opt_init(argc, argv, rehash_options);
494 while ((o = opt_next()) != OPT_EOF) {
498 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
501 opt_help(rehash_options);
516 if (!opt_provider(o))
521 argc = opt_num_rest();
525 evpmdsize = EVP_MD_size(evpmd);
528 while (*argv != NULL)
529 errs += do_dir(*argv++, h);
530 } else if ((env = getenv(X509_get_default_cert_dir_env())) != NULL) {
531 char lsc[2] = { LIST_SEPARATOR_CHAR, '\0' };
532 m = OPENSSL_strdup(env);
533 for (e = strtok(m, lsc); e != NULL; e = strtok(NULL, lsc))
534 errs += do_dir(e, h);
537 errs += do_dir(X509_get_default_cert_dir(), h);
545 const OPTIONS rehash_options[] = {
549 int rehash_main(int argc, char **argv)
551 BIO_printf(bio_err, "Not available; use c_rehash script\n");
555 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */