Since return is inconsistent, I removed unnecessary parentheses and
[openssl.git] / apps / rehash.c
1 /*
2  * Copyright 2015-2017 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2013-2014 Timo Teräs <timo.teras@gmail.com>
4  *
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
9  */
10
11 #include "apps.h"
12
13 #if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) || \
14     (defined(__VMS) && defined(__DECC) && __CRTL_VER >= 80300000)
15 # include <unistd.h>
16 # include <stdio.h>
17 # include <limits.h>
18 # include <errno.h>
19 # include <string.h>
20 # include <ctype.h>
21 # include <sys/stat.h>
22
23 /*
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.
28  */
29 # ifdef __VMS
30 #  pragma names save
31 #  pragma names as_is,shortened
32 # endif
33
34 # include "internal/o_dir.h"
35
36 # ifdef __VMS
37 #  pragma names restore
38 # endif
39
40 # include <openssl/evp.h>
41 # include <openssl/pem.h>
42 # include <openssl/x509.h>
43
44
45 # ifndef PATH_MAX
46 #  define PATH_MAX 4096
47 # endif
48 # ifndef NAME_MAX
49 #  define NAME_MAX 255
50 # endif
51 # define MAX_COLLISIONS  256
52
53 typedef struct hentry_st {
54     struct hentry_st *next;
55     char *filename;
56     unsigned short old_id;
57     unsigned char need_symlink;
58     unsigned char digest[EVP_MAX_MD_SIZE];
59 } HENTRY;
60
61 typedef struct bucket_st {
62     struct bucket_st *next;
63     HENTRY *first_entry, *last_entry;
64     unsigned int hash;
65     unsigned short type;
66     unsigned short num_needed;
67 } BUCKET;
68
69 enum Type {
70     /* Keep in sync with |suffixes|, below. */
71     TYPE_CERT=0, TYPE_CRL=1
72 };
73
74 enum Hash {
75     HASH_OLD, HASH_NEW, HASH_BOTH
76 };
77
78
79 static int evpmdsize;
80 static const EVP_MD *evpmd;
81 static int remove_links = 1;
82 static int verbose = 0;
83 static BUCKET *hash_table[257];
84
85 static const char *suffixes[] = { "", "r" };
86 static const char *extensions[] = { "pem", "crt", "cer", "crl" };
87
88
89 static void bit_set(unsigned char *set, unsigned int bit)
90 {
91     set[bit >> 3] |= 1 << (bit & 0x7);
92 }
93
94 static int bit_isset(unsigned char *set, unsigned int bit)
95 {
96     return set[bit >> 3] & (1 << (bit & 0x7));
97 }
98
99
100 /*
101  * Process an entry; return number of errors.
102  */
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)
106 {
107     static BUCKET nilbucket;
108     static HENTRY nilhentry;
109     BUCKET *bp;
110     HENTRY *ep, *found = NULL;
111     unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table);
112
113     for (bp = hash_table[ndx]; bp; bp = bp->next)
114         if (bp->type == type && bp->hash == hash)
115             break;
116     if (bp == NULL) {
117         bp = app_malloc(sizeof(*bp), "hash bucket");
118         *bp = nilbucket;
119         bp->next = hash_table[ndx];
120         bp->type = type;
121         bp->hash = hash;
122         hash_table[ndx] = bp;
123     }
124
125     for (ep = bp->first_entry; ep; ep = ep->next) {
126         if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) {
127             BIO_printf(bio_err,
128                        "%s: skipping duplicate %s in %s\n", opt_getprog(),
129                        type == TYPE_CERT ? "certificate" : "CRL", filename);
130             return 1;
131         }
132         if (strcmp(filename, ep->filename) == 0) {
133             found = ep;
134             if (digest == NULL)
135                 break;
136         }
137     }
138     ep = found;
139     if (ep == NULL) {
140         if (bp->num_needed >= MAX_COLLISIONS) {
141             BIO_printf(bio_err,
142                        "%s: hash table overflow for %s\n",
143                        opt_getprog(), filename);
144             return 1;
145         }
146         ep = app_malloc(sizeof(*ep), "collision bucket");
147         *ep = nilhentry;
148         ep->old_id = ~0;
149         ep->filename = OPENSSL_strdup(filename);
150         if (bp->last_entry)
151             bp->last_entry->next = ep;
152         if (bp->first_entry == NULL)
153             bp->first_entry = ep;
154         bp->last_entry = ep;
155     }
156
157     if (old_id < ep->old_id)
158         ep->old_id = old_id;
159     if (need_symlink && !ep->need_symlink) {
160         ep->need_symlink = 1;
161         bp->num_needed++;
162         memcpy(ep->digest, digest, evpmdsize);
163     }
164     return 0;
165 }
166
167 /*
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.
170  */
171 static int handle_symlink(const char *filename, const char *fullpath)
172 {
173     unsigned int hash = 0;
174     int i, type, id;
175     unsigned char ch;
176     char linktarget[PATH_MAX], *endptr;
177     ossl_ssize_t n;
178
179     for (i = 0; i < 8; i++) {
180         ch = filename[i];
181         if (!isxdigit(ch))
182             return -1;
183         hash <<= 4;
184         hash += OPENSSL_hexchar2int(ch);
185     }
186     if (filename[i++] != '.')
187         return -1;
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)
191             break;
192     }
193     i += strlen(suffixes[type]);
194
195     id = strtoul(&filename[i], &endptr, 10);
196     if (*endptr != '\0')
197         return -1;
198
199     n = readlink(fullpath, linktarget, sizeof(linktarget));
200     if (n < 0 || n >= (int)sizeof(linktarget))
201         return -1;
202     linktarget[n] = 0;
203
204     return add_entry(type, hash, linktarget, NULL, 0, id);
205 }
206
207 /*
208  * process a file, return number of errors.
209  */
210 static int do_file(const char *filename, const char *fullpath, enum Hash h)
211 {
212     STACK_OF (X509_INFO) *inf = NULL;
213     X509_INFO *x;
214     X509_NAME *name = NULL;
215     BIO *b;
216     const char *ext;
217     unsigned char digest[EVP_MAX_MD_SIZE];
218     int type, errs = 0;
219     size_t i;
220
221     /* Does it end with a recognized extension? */
222     if ((ext = strrchr(filename, '.')) == NULL)
223         goto end;
224     for (i = 0; i < OSSL_NELEM(extensions); i++) {
225         if (strcasecmp(extensions[i], ext + 1) == 0)
226             break;
227     }
228     if (i >= OSSL_NELEM(extensions))
229         goto end;
230
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);
235         errs++;
236         goto end;
237     }
238     inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
239     BIO_free(b);
240     if (inf == NULL)
241         goto end;
242
243     if (sk_X509_INFO_num(inf) != 1) {
244         BIO_printf(bio_err,
245                    "%s: skipping %s,"
246                    "it does not contain exactly one certificate or CRL\n",
247                    opt_getprog(), filename);
248         /* This is not an error. */
249         goto end;
250     }
251     x = sk_X509_INFO_value(inf, 0);
252     if (x->x509 != NULL) {
253         type = TYPE_CERT;
254         name = X509_get_subject_name(x->x509);
255         X509_digest(x->x509, evpmd, digest, NULL);
256     } else if (x->crl != NULL) {
257         type = TYPE_CRL;
258         name = X509_CRL_get_issuer(x->crl);
259         X509_CRL_digest(x->crl, evpmd, digest, NULL);
260     } else {
261         ++errs;
262         goto end;
263     }
264     if (name != 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);
269     }
270
271 end:
272     sk_X509_INFO_pop_free(inf, X509_INFO_free);
273     return errs;
274 }
275
276 static void str_free(char *s)
277 {
278     OPENSSL_free(s);
279 }
280
281 static int ends_with_dirsep(const char *path)
282 {
283     if (*path != '\0')
284         path += strlen(path) - 1;
285 # if defined __VMS
286     if (*path == ']' || *path == '>' || *path == ':')
287         return 1;
288 # elif defined _WIN32
289     if (*path == '\\')
290         return 1;
291 # endif
292     return *path == '/';
293 }
294
295 static int massage_filename(char *name)
296 {
297 # ifdef __VMS
298     char *p = strchr(name, ';');
299     char *q = p;
300
301     if (q != NULL) {
302         for (q++; *q != '\0'; q++) {
303             if (!isdigit((unsigned char)*q))
304                 return 1;
305         }
306     }
307
308     *p = '\0';
309 # endif
310     return 1;
311 }
312
313 /*
314  * Process a directory; return number of errors found.
315  */
316 static int do_dir(const char *dirname, enum Hash h)
317 {
318     BUCKET *bp, *nextbp;
319     HENTRY *ep, *nextep;
320     OPENSSL_DIR_CTX *d = NULL;
321     struct stat st;
322     unsigned char idmask[MAX_COLLISIONS / 8];
323     int n, numfiles, nextid, buflen, errs = 0;
324     size_t i;
325     const char *pathsep;
326     const char *filename;
327     char *buf, *copy;
328     STACK_OF(OPENSSL_STRING) *files = NULL;
329
330     if (app_access(dirname, W_OK) < 0) {
331         BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
332         return 1;
333     }
334     buflen = strlen(dirname);
335     pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
336     buflen += NAME_MAX + 1 + 1;
337     buf = app_malloc(buflen, "filename buffer");
338
339     if (verbose)
340         BIO_printf(bio_out, "Doing %s\n", dirname);
341
342     if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
343         BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
344         exit(1);
345     }
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");
351             exit(1);
352         }
353     }
354     OPENSSL_DIR_end(&d);
355     sk_OPENSSL_STRING_sort(files);
356
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)
362             continue;
363         if (lstat(buf, &st) < 0)
364             continue;
365         if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
366             continue;
367         errs += do_file(filename, buf, h);
368     }
369     sk_OPENSSL_STRING_pop_free(files, str_free);
370
371     for (i = 0; i < OSSL_NELEM(hash_table); i++) {
372         for (bp = hash_table[i]; bp; bp = nextbp) {
373             nextbp = bp->next;
374             nextid = 0;
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);
379
380             for (ep = bp->first_entry; ep; ep = nextep) {
381                 nextep = ep->next;
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);
386                     if (verbose)
387                         BIO_printf(bio_out, "link %s -> %s\n",
388                                    ep->filename, buf);
389                 } else if (ep->need_symlink) {
390                     /* New link needed (it may replace something) */
391                     while (bit_isset(idmask, nextid))
392                         nextid++;
393
394                     BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
395                                  dirname, pathsep, &n, bp->hash,
396                                  suffixes[bp->type], nextid);
397                     if (verbose)
398                         BIO_printf(bio_out, "link %s -> %s\n",
399                                    ep->filename, &buf[n]);
400                     if (unlink(buf) < 0 && errno != ENOENT) {
401                         BIO_printf(bio_err,
402                                    "%s: Can't unlink %s, %s\n",
403                                    opt_getprog(), buf, strerror(errno));
404                         errs++;
405                     }
406                     if (symlink(ep->filename, buf) < 0) {
407                         BIO_printf(bio_err,
408                                    "%s: Can't symlink %s, %s\n",
409                                    opt_getprog(), ep->filename,
410                                    strerror(errno));
411                         errs++;
412                     }
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);
419                     if (verbose)
420                         BIO_printf(bio_out, "unlink %s\n",
421                                    &buf[n]);
422                     if (unlink(buf) < 0 && errno != ENOENT) {
423                         BIO_printf(bio_err,
424                                    "%s: Can't unlink %s, %s\n",
425                                    opt_getprog(), buf, strerror(errno));
426                         errs++;
427                     }
428                 }
429                 OPENSSL_free(ep->filename);
430                 OPENSSL_free(ep);
431             }
432             OPENSSL_free(bp);
433         }
434         hash_table[i] = NULL;
435     }
436
437     OPENSSL_free(buf);
438     return errs;
439 }
440
441 typedef enum OPTION_choice {
442     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
443     OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE
444 } OPTION_CHOICE;
445
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"},
455     {NULL}
456 };
457
458
459 int rehash_main(int argc, char **argv)
460 {
461     const char *env, *prog;
462     char *e, *m;
463     int errs = 0;
464     OPTION_CHOICE o;
465     enum Hash h = HASH_NEW;
466
467     prog = opt_init(argc, argv, rehash_options);
468     while ((o = opt_next()) != OPT_EOF) {
469         switch (o) {
470         case OPT_EOF:
471         case OPT_ERR:
472             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
473             goto end;
474         case OPT_HELP:
475             opt_help(rehash_options);
476             goto end;
477         case OPT_COMPAT:
478             h = HASH_BOTH;
479             break;
480         case OPT_OLD:
481             h = HASH_OLD;
482             break;
483         case OPT_N:
484             remove_links = 0;
485             break;
486         case OPT_VERBOSE:
487             verbose = 1;
488             break;
489         }
490     }
491     argc = opt_num_rest();
492     argv = opt_rest();
493
494     evpmd = EVP_sha1();
495     evpmdsize = EVP_MD_size(evpmd);
496
497     if (*argv != NULL) {
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);
504         OPENSSL_free(m);
505     } else {
506         errs += do_dir("/etc/ssl/certs", h);
507     }
508
509  end:
510     return errs;
511 }
512
513 #else
514 const OPTIONS rehash_options[] = {
515     {NULL}
516 };
517
518 int rehash_main(int argc, char **argv)
519 {
520     BIO_printf(bio_err, "Not available; use c_rehash script\n");
521     return 1;
522 }
523
524 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */