include source root directory via -I for libnonfips.a
[oweals/openssl.git] / apps / rehash.c
1 /*
2  * Copyright 2015-2020 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2013-2014 Timo Teräs <timo.teras@gmail.com>
4  *
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
9  */
10
11 #include "apps.h"
12 #include "progs.h"
13
14 #if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) || \
15     (defined(__VMS) && defined(__DECC) && __CRTL_VER >= 80300000)
16 # include <unistd.h>
17 # include <stdio.h>
18 # include <limits.h>
19 # include <errno.h>
20 # include <string.h>
21 # include <ctype.h>
22 # include <sys/stat.h>
23
24 /*
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.
29  */
30 # ifdef __VMS
31 #  pragma names save
32 #  pragma names as_is,shortened
33 # endif
34
35 # include "internal/o_dir.h"
36
37 # ifdef __VMS
38 #  pragma names restore
39 # endif
40
41 # include <openssl/evp.h>
42 # include <openssl/pem.h>
43 # include <openssl/x509.h>
44
45 DEFINE_STACK_OF(X509_INFO)
46 DEFINE_STACK_OF_STRING()
47
48 # ifndef PATH_MAX
49 #  define PATH_MAX 4096
50 # endif
51 # ifndef NAME_MAX
52 #  define NAME_MAX 255
53 # endif
54 # define MAX_COLLISIONS  256
55
56 # if defined(OPENSSL_SYS_VXWORKS)
57 /*
58  * VxWorks has no symbolic links
59  */
60
61 #  define lstat(path, buf) stat(path, buf)
62
63 int symlink(const char *target, const char *linkpath)
64 {
65     errno = ENOSYS;
66     return -1;
67 }
68
69 ssize_t readlink(const char *pathname, char *buf, size_t bufsiz)
70 {
71     errno = ENOSYS;
72     return -1;
73 }
74 # endif
75
76 typedef struct hentry_st {
77     struct hentry_st *next;
78     char *filename;
79     unsigned short old_id;
80     unsigned char need_symlink;
81     unsigned char digest[EVP_MAX_MD_SIZE];
82 } HENTRY;
83
84 typedef struct bucket_st {
85     struct bucket_st *next;
86     HENTRY *first_entry, *last_entry;
87     unsigned int hash;
88     unsigned short type;
89     unsigned short num_needed;
90 } BUCKET;
91
92 enum Type {
93     /* Keep in sync with |suffixes|, below. */
94     TYPE_CERT=0, TYPE_CRL=1
95 };
96
97 enum Hash {
98     HASH_OLD, HASH_NEW, HASH_BOTH
99 };
100
101
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];
107
108 static const char *suffixes[] = { "", "r" };
109 static const char *extensions[] = { "pem", "crt", "cer", "crl" };
110
111
112 static void bit_set(unsigned char *set, unsigned int bit)
113 {
114     set[bit >> 3] |= 1 << (bit & 0x7);
115 }
116
117 static int bit_isset(unsigned char *set, unsigned int bit)
118 {
119     return set[bit >> 3] & (1 << (bit & 0x7));
120 }
121
122
123 /*
124  * Process an entry; return number of errors.
125  */
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)
129 {
130     static BUCKET nilbucket;
131     static HENTRY nilhentry;
132     BUCKET *bp;
133     HENTRY *ep, *found = NULL;
134     unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table);
135
136     for (bp = hash_table[ndx]; bp; bp = bp->next)
137         if (bp->type == type && bp->hash == hash)
138             break;
139     if (bp == NULL) {
140         bp = app_malloc(sizeof(*bp), "hash bucket");
141         *bp = nilbucket;
142         bp->next = hash_table[ndx];
143         bp->type = type;
144         bp->hash = hash;
145         hash_table[ndx] = bp;
146     }
147
148     for (ep = bp->first_entry; ep; ep = ep->next) {
149         if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) {
150             BIO_printf(bio_err,
151                        "%s: warning: skipping duplicate %s in %s\n",
152                        opt_getprog(),
153                        type == TYPE_CERT ? "certificate" : "CRL", filename);
154             return 0;
155         }
156         if (strcmp(filename, ep->filename) == 0) {
157             found = ep;
158             if (digest == NULL)
159                 break;
160         }
161     }
162     ep = found;
163     if (ep == NULL) {
164         if (bp->num_needed >= MAX_COLLISIONS) {
165             BIO_printf(bio_err,
166                        "%s: error: hash table overflow for %s\n",
167                        opt_getprog(), filename);
168             return 1;
169         }
170         ep = app_malloc(sizeof(*ep), "collision bucket");
171         *ep = nilhentry;
172         ep->old_id = ~0;
173         ep->filename = OPENSSL_strdup(filename);
174         if (bp->last_entry)
175             bp->last_entry->next = ep;
176         if (bp->first_entry == NULL)
177             bp->first_entry = ep;
178         bp->last_entry = ep;
179     }
180
181     if (old_id < ep->old_id)
182         ep->old_id = old_id;
183     if (need_symlink && !ep->need_symlink) {
184         ep->need_symlink = 1;
185         bp->num_needed++;
186         memcpy(ep->digest, digest, evpmdsize);
187     }
188     return 0;
189 }
190
191 /*
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.
194  */
195 static int handle_symlink(const char *filename, const char *fullpath)
196 {
197     unsigned int hash = 0;
198     int i, type, id;
199     unsigned char ch;
200     char linktarget[PATH_MAX], *endptr;
201     ossl_ssize_t n;
202
203     for (i = 0; i < 8; i++) {
204         ch = filename[i];
205         if (!isxdigit(ch))
206             return -1;
207         hash <<= 4;
208         hash += OPENSSL_hexchar2int(ch);
209     }
210     if (filename[i++] != '.')
211         return -1;
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)
215             break;
216     }
217     i += strlen(suffixes[type]);
218
219     id = strtoul(&filename[i], &endptr, 10);
220     if (*endptr != '\0')
221         return -1;
222
223     n = readlink(fullpath, linktarget, sizeof(linktarget));
224     if (n < 0 || n >= (int)sizeof(linktarget))
225         return -1;
226     linktarget[n] = 0;
227
228     return add_entry(type, hash, linktarget, NULL, 0, id);
229 }
230
231 /*
232  * process a file, return number of errors.
233  */
234 static int do_file(const char *filename, const char *fullpath, enum Hash h)
235 {
236     STACK_OF (X509_INFO) *inf = NULL;
237     X509_INFO *x;
238     const X509_NAME *name = NULL;
239     BIO *b;
240     const char *ext;
241     unsigned char digest[EVP_MAX_MD_SIZE];
242     int type, errs = 0;
243     size_t i;
244
245     /* Does it end with a recognized extension? */
246     if ((ext = strrchr(filename, '.')) == NULL)
247         goto end;
248     for (i = 0; i < OSSL_NELEM(extensions); i++) {
249         if (strcasecmp(extensions[i], ext + 1) == 0)
250             break;
251     }
252     if (i >= OSSL_NELEM(extensions))
253         goto end;
254
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);
259         errs++;
260         goto end;
261     }
262     inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
263     BIO_free(b);
264     if (inf == NULL)
265         goto end;
266
267     if (sk_X509_INFO_num(inf) != 1) {
268         BIO_printf(bio_err,
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. */
273         goto end;
274     }
275     x = sk_X509_INFO_value(inf, 0);
276     if (x->x509 != NULL) {
277         type = TYPE_CERT;
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");
281             ++errs;
282             goto end;
283         }
284     } else if (x->crl != NULL) {
285         type = TYPE_CRL;
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");
289             ++errs;
290             goto end;
291         }
292     } else {
293         ++errs;
294         goto end;
295     }
296     if (name != NULL) {
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);
301     }
302
303 end:
304     sk_X509_INFO_pop_free(inf, X509_INFO_free);
305     return errs;
306 }
307
308 static void str_free(char *s)
309 {
310     OPENSSL_free(s);
311 }
312
313 static int ends_with_dirsep(const char *path)
314 {
315     if (*path != '\0')
316         path += strlen(path) - 1;
317 # if defined __VMS
318     if (*path == ']' || *path == '>' || *path == ':')
319         return 1;
320 # elif defined _WIN32
321     if (*path == '\\')
322         return 1;
323 # endif
324     return *path == '/';
325 }
326
327 /*
328  * Process a directory; return number of errors found.
329  */
330 static int do_dir(const char *dirname, enum Hash h)
331 {
332     BUCKET *bp, *nextbp;
333     HENTRY *ep, *nextep;
334     OPENSSL_DIR_CTX *d = NULL;
335     struct stat st;
336     unsigned char idmask[MAX_COLLISIONS / 8];
337     int n, numfiles, nextid, buflen, errs = 0;
338     size_t i;
339     const char *pathsep;
340     const char *filename;
341     char *buf, *copy = NULL;
342     STACK_OF(OPENSSL_STRING) *files = NULL;
343
344     if (app_access(dirname, W_OK) < 0) {
345         BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
346         return 1;
347     }
348     buflen = strlen(dirname);
349     pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
350     buflen += NAME_MAX + 1 + 1;
351     buf = app_malloc(buflen, "filename buffer");
352
353     if (verbose)
354         BIO_printf(bio_out, "Doing %s\n", dirname);
355
356     if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
357         BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
358         errs = 1;
359         goto err;
360     }
361     while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
362         if ((copy = OPENSSL_strdup(filename)) == NULL
363                 || sk_OPENSSL_STRING_push(files, copy) == 0) {
364             OPENSSL_free(copy);
365             BIO_puts(bio_err, "out of memory\n");
366             errs = 1;
367             goto err;
368         }
369     }
370     OPENSSL_DIR_end(&d);
371     sk_OPENSSL_STRING_sort(files);
372
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)
378             continue;
379         if (lstat(buf, &st) < 0)
380             continue;
381         if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
382             continue;
383         errs += do_file(filename, buf, h);
384     }
385
386     for (i = 0; i < OSSL_NELEM(hash_table); i++) {
387         for (bp = hash_table[i]; bp; bp = nextbp) {
388             nextbp = bp->next;
389             nextid = 0;
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);
394
395             for (ep = bp->first_entry; ep; ep = nextep) {
396                 nextep = ep->next;
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);
401                     if (verbose)
402                         BIO_printf(bio_out, "link %s -> %s\n",
403                                    ep->filename, buf);
404                 } else if (ep->need_symlink) {
405                     /* New link needed (it may replace something) */
406                     while (bit_isset(idmask, nextid))
407                         nextid++;
408
409                     BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
410                                  dirname, pathsep, &n, bp->hash,
411                                  suffixes[bp->type], nextid);
412                     if (verbose)
413                         BIO_printf(bio_out, "link %s -> %s\n",
414                                    ep->filename, &buf[n]);
415                     if (unlink(buf) < 0 && errno != ENOENT) {
416                         BIO_printf(bio_err,
417                                    "%s: Can't unlink %s, %s\n",
418                                    opt_getprog(), buf, strerror(errno));
419                         errs++;
420                     }
421                     if (symlink(ep->filename, buf) < 0) {
422                         BIO_printf(bio_err,
423                                    "%s: Can't symlink %s, %s\n",
424                                    opt_getprog(), ep->filename,
425                                    strerror(errno));
426                         errs++;
427                     }
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);
434                     if (verbose)
435                         BIO_printf(bio_out, "unlink %s\n",
436                                    &buf[n]);
437                     if (unlink(buf) < 0 && errno != ENOENT) {
438                         BIO_printf(bio_err,
439                                    "%s: Can't unlink %s, %s\n",
440                                    opt_getprog(), buf, strerror(errno));
441                         errs++;
442                     }
443                 }
444                 OPENSSL_free(ep->filename);
445                 OPENSSL_free(ep);
446             }
447             OPENSSL_free(bp);
448         }
449         hash_table[i] = NULL;
450     }
451
452  err:
453     sk_OPENSSL_STRING_pop_free(files, str_free);
454     OPENSSL_free(buf);
455     return errs;
456 }
457
458 typedef enum OPTION_choice {
459     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
460     OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE,
461     OPT_PROV_ENUM
462 } OPTION_CHOICE;
463
464 const OPTIONS rehash_options[] = {
465     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [directory...]\n"},
466
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"},
473
474     OPT_SECTION("Output"),
475     {"v", OPT_VERBOSE, '-', "Verbose output"},
476
477     OPT_PROV_OPTIONS,
478
479     OPT_PARAMETERS(),
480     {"directory", 0, 0, "One or more directories to process (optional)"},
481     {NULL}
482 };
483
484
485 int rehash_main(int argc, char **argv)
486 {
487     const char *env, *prog;
488     char *e, *m;
489     int errs = 0;
490     OPTION_CHOICE o;
491     enum Hash h = HASH_NEW;
492
493     prog = opt_init(argc, argv, rehash_options);
494     while ((o = opt_next()) != OPT_EOF) {
495         switch (o) {
496         case OPT_EOF:
497         case OPT_ERR:
498             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
499             goto end;
500         case OPT_HELP:
501             opt_help(rehash_options);
502             goto end;
503         case OPT_COMPAT:
504             h = HASH_BOTH;
505             break;
506         case OPT_OLD:
507             h = HASH_OLD;
508             break;
509         case OPT_N:
510             remove_links = 0;
511             break;
512         case OPT_VERBOSE:
513             verbose = 1;
514             break;
515         case OPT_PROV_CASES:
516             if (!opt_provider(o))
517                 goto end;
518             break;
519         }
520     }
521     argc = opt_num_rest();
522     argv = opt_rest();
523
524     evpmd = EVP_sha1();
525     evpmdsize = EVP_MD_size(evpmd);
526
527     if (*argv != NULL) {
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);
535         OPENSSL_free(m);
536     } else {
537         errs += do_dir(X509_get_default_cert_dir(), h);
538     }
539
540  end:
541     return errs;
542 }
543
544 #else
545 const OPTIONS rehash_options[] = {
546     {NULL}
547 };
548
549 int rehash_main(int argc, char **argv)
550 {
551     BIO_printf(bio_err, "Not available; use c_rehash script\n");
552     return 1;
553 }
554
555 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */