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_STRING()
48 # define PATH_MAX 4096
53 # define MAX_COLLISIONS 256
55 # if defined(OPENSSL_SYS_VXWORKS)
57 * VxWorks has no symbolic links
60 # define lstat(path, buf) stat(path, buf)
62 int symlink(const char *target, const char *linkpath)
68 ssize_t readlink(const char *pathname, char *buf, size_t bufsiz)
75 typedef struct hentry_st {
76 struct hentry_st *next;
78 unsigned short old_id;
79 unsigned char need_symlink;
80 unsigned char digest[EVP_MAX_MD_SIZE];
83 typedef struct bucket_st {
84 struct bucket_st *next;
85 HENTRY *first_entry, *last_entry;
88 unsigned short num_needed;
92 /* Keep in sync with |suffixes|, below. */
93 TYPE_CERT=0, TYPE_CRL=1
97 HASH_OLD, HASH_NEW, HASH_BOTH
101 static int evpmdsize;
102 static const EVP_MD *evpmd;
103 static int remove_links = 1;
104 static int verbose = 0;
105 static BUCKET *hash_table[257];
107 static const char *suffixes[] = { "", "r" };
108 static const char *extensions[] = { "pem", "crt", "cer", "crl" };
111 static void bit_set(unsigned char *set, unsigned int bit)
113 set[bit >> 3] |= 1 << (bit & 0x7);
116 static int bit_isset(unsigned char *set, unsigned int bit)
118 return set[bit >> 3] & (1 << (bit & 0x7));
123 * Process an entry; return number of errors.
125 static int add_entry(enum Type type, unsigned int hash, const char *filename,
126 const unsigned char *digest, int need_symlink,
127 unsigned short old_id)
129 static BUCKET nilbucket;
130 static HENTRY nilhentry;
132 HENTRY *ep, *found = NULL;
133 unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table);
135 for (bp = hash_table[ndx]; bp; bp = bp->next)
136 if (bp->type == type && bp->hash == hash)
139 bp = app_malloc(sizeof(*bp), "hash bucket");
141 bp->next = hash_table[ndx];
144 hash_table[ndx] = bp;
147 for (ep = bp->first_entry; ep; ep = ep->next) {
148 if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) {
150 "%s: warning: skipping duplicate %s in %s\n",
152 type == TYPE_CERT ? "certificate" : "CRL", filename);
155 if (strcmp(filename, ep->filename) == 0) {
163 if (bp->num_needed >= MAX_COLLISIONS) {
165 "%s: error: hash table overflow for %s\n",
166 opt_getprog(), filename);
169 ep = app_malloc(sizeof(*ep), "collision bucket");
172 ep->filename = OPENSSL_strdup(filename);
174 bp->last_entry->next = ep;
175 if (bp->first_entry == NULL)
176 bp->first_entry = ep;
180 if (old_id < ep->old_id)
182 if (need_symlink && !ep->need_symlink) {
183 ep->need_symlink = 1;
185 memcpy(ep->digest, digest, evpmdsize);
191 * Check if a symlink goes to the right spot; return 0 if okay.
192 * This can be -1 if bad filename, or an error count.
194 static int handle_symlink(const char *filename, const char *fullpath)
196 unsigned int hash = 0;
199 char linktarget[PATH_MAX], *endptr;
202 for (i = 0; i < 8; i++) {
207 hash += OPENSSL_hexchar2int(ch);
209 if (filename[i++] != '.')
211 for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--) {
212 const char *suffix = suffixes[type];
213 if (strncasecmp(suffix, &filename[i], strlen(suffix)) == 0)
216 i += strlen(suffixes[type]);
218 id = strtoul(&filename[i], &endptr, 10);
222 n = readlink(fullpath, linktarget, sizeof(linktarget));
223 if (n < 0 || n >= (int)sizeof(linktarget))
227 return add_entry(type, hash, linktarget, NULL, 0, id);
231 * process a file, return number of errors.
233 static int do_file(const char *filename, const char *fullpath, enum Hash h)
235 STACK_OF (X509_INFO) *inf = NULL;
237 const X509_NAME *name = NULL;
240 unsigned char digest[EVP_MAX_MD_SIZE];
244 /* Does it end with a recognized extension? */
245 if ((ext = strrchr(filename, '.')) == NULL)
247 for (i = 0; i < OSSL_NELEM(extensions); i++) {
248 if (strcasecmp(extensions[i], ext + 1) == 0)
251 if (i >= OSSL_NELEM(extensions))
254 /* Does it have X.509 data in it? */
255 if ((b = BIO_new_file(fullpath, "r")) == NULL) {
256 BIO_printf(bio_err, "%s: error: skipping %s, cannot open file\n",
257 opt_getprog(), filename);
261 inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
266 if (sk_X509_INFO_num(inf) != 1) {
268 "%s: warning: skipping %s,"
269 "it does not contain exactly one certificate or CRL\n",
270 opt_getprog(), filename);
271 /* This is not an error. */
274 x = sk_X509_INFO_value(inf, 0);
275 if (x->x509 != NULL) {
277 name = X509_get_subject_name(x->x509);
278 if (!X509_digest(x->x509, evpmd, digest, NULL)) {
279 BIO_printf(bio_err, "out of memory\n");
283 } else if (x->crl != NULL) {
285 name = X509_CRL_get_issuer(x->crl);
286 if (!X509_CRL_digest(x->crl, evpmd, digest, NULL)) {
287 BIO_printf(bio_err, "out of memory\n");
296 if ((h == HASH_NEW) || (h == HASH_BOTH))
297 errs += add_entry(type, X509_NAME_hash(name), filename, digest, 1, ~0);
298 if ((h == HASH_OLD) || (h == HASH_BOTH))
299 errs += add_entry(type, X509_NAME_hash_old(name), filename, digest, 1, ~0);
303 sk_X509_INFO_pop_free(inf, X509_INFO_free);
307 static void str_free(char *s)
312 static int ends_with_dirsep(const char *path)
315 path += strlen(path) - 1;
317 if (*path == ']' || *path == '>' || *path == ':')
319 # elif defined _WIN32
327 * Process a directory; return number of errors found.
329 static int do_dir(const char *dirname, enum Hash h)
333 OPENSSL_DIR_CTX *d = NULL;
335 unsigned char idmask[MAX_COLLISIONS / 8];
336 int n, numfiles, nextid, buflen, errs = 0;
339 const char *filename;
340 char *buf, *copy = NULL;
341 STACK_OF(OPENSSL_STRING) *files = NULL;
343 if (app_access(dirname, W_OK) < 0) {
344 BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
347 buflen = strlen(dirname);
348 pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
349 buflen += NAME_MAX + 1 + 1;
350 buf = app_malloc(buflen, "filename buffer");
353 BIO_printf(bio_out, "Doing %s\n", dirname);
355 if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
356 BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
360 while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
361 if ((copy = OPENSSL_strdup(filename)) == NULL
362 || sk_OPENSSL_STRING_push(files, copy) == 0) {
364 BIO_puts(bio_err, "out of memory\n");
370 sk_OPENSSL_STRING_sort(files);
372 numfiles = sk_OPENSSL_STRING_num(files);
373 for (n = 0; n < numfiles; ++n) {
374 filename = sk_OPENSSL_STRING_value(files, n);
375 if (BIO_snprintf(buf, buflen, "%s%s%s",
376 dirname, pathsep, filename) >= buflen)
378 if (lstat(buf, &st) < 0)
380 if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
382 errs += do_file(filename, buf, h);
385 for (i = 0; i < OSSL_NELEM(hash_table); i++) {
386 for (bp = hash_table[i]; bp; bp = nextbp) {
389 memset(idmask, 0, (bp->num_needed + 7) / 8);
390 for (ep = bp->first_entry; ep; ep = ep->next)
391 if (ep->old_id < bp->num_needed)
392 bit_set(idmask, ep->old_id);
394 for (ep = bp->first_entry; ep; ep = nextep) {
396 if (ep->old_id < bp->num_needed) {
397 /* Link exists, and is used as-is */
398 BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash,
399 suffixes[bp->type], ep->old_id);
401 BIO_printf(bio_out, "link %s -> %s\n",
403 } else if (ep->need_symlink) {
404 /* New link needed (it may replace something) */
405 while (bit_isset(idmask, nextid))
408 BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
409 dirname, pathsep, &n, bp->hash,
410 suffixes[bp->type], nextid);
412 BIO_printf(bio_out, "link %s -> %s\n",
413 ep->filename, &buf[n]);
414 if (unlink(buf) < 0 && errno != ENOENT) {
416 "%s: Can't unlink %s, %s\n",
417 opt_getprog(), buf, strerror(errno));
420 if (symlink(ep->filename, buf) < 0) {
422 "%s: Can't symlink %s, %s\n",
423 opt_getprog(), ep->filename,
427 bit_set(idmask, nextid);
428 } else if (remove_links) {
429 /* Link to be deleted */
430 BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
431 dirname, pathsep, &n, bp->hash,
432 suffixes[bp->type], ep->old_id);
434 BIO_printf(bio_out, "unlink %s\n",
436 if (unlink(buf) < 0 && errno != ENOENT) {
438 "%s: Can't unlink %s, %s\n",
439 opt_getprog(), buf, strerror(errno));
443 OPENSSL_free(ep->filename);
448 hash_table[i] = NULL;
452 sk_OPENSSL_STRING_pop_free(files, str_free);
457 typedef enum OPTION_choice {
458 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
459 OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE,
463 const OPTIONS rehash_options[] = {
464 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [directory...]\n"},
466 OPT_SECTION("General"),
467 {"help", OPT_HELP, '-', "Display this summary"},
468 {"h", OPT_HELP, '-', "Display this summary"},
469 {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
470 {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
471 {"n", OPT_N, '-', "Do not remove existing links"},
473 OPT_SECTION("Output"),
474 {"v", OPT_VERBOSE, '-', "Verbose output"},
479 {"directory", 0, 0, "One or more directories to process (optional)"},
484 int rehash_main(int argc, char **argv)
486 const char *env, *prog;
490 enum Hash h = HASH_NEW;
492 prog = opt_init(argc, argv, rehash_options);
493 while ((o = opt_next()) != OPT_EOF) {
497 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
500 opt_help(rehash_options);
515 if (!opt_provider(o))
520 argc = opt_num_rest();
524 evpmdsize = EVP_MD_size(evpmd);
527 while (*argv != NULL)
528 errs += do_dir(*argv++, h);
529 } else if ((env = getenv(X509_get_default_cert_dir_env())) != NULL) {
530 char lsc[2] = { LIST_SEPARATOR_CHAR, '\0' };
531 m = OPENSSL_strdup(env);
532 for (e = strtok(m, lsc); e != NULL; e = strtok(NULL, lsc))
533 errs += do_dir(e, h);
536 errs += do_dir(X509_get_default_cert_dir(), h);
544 const OPTIONS rehash_options[] = {
548 int rehash_main(int argc, char **argv)
550 BIO_printf(bio_err, "Not available; use c_rehash script\n");
554 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */