Do not set a nonzero default max_early_data
[openssl.git] / apps / rehash.c
1 /*
2  * Copyright 2015-2018 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 #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
46 # ifndef PATH_MAX
47 #  define PATH_MAX 4096
48 # endif
49 # ifndef NAME_MAX
50 #  define NAME_MAX 255
51 # endif
52 # define MAX_COLLISIONS  256
53
54 typedef struct hentry_st {
55     struct hentry_st *next;
56     char *filename;
57     unsigned short old_id;
58     unsigned char need_symlink;
59     unsigned char digest[EVP_MAX_MD_SIZE];
60 } HENTRY;
61
62 typedef struct bucket_st {
63     struct bucket_st *next;
64     HENTRY *first_entry, *last_entry;
65     unsigned int hash;
66     unsigned short type;
67     unsigned short num_needed;
68 } BUCKET;
69
70 enum Type {
71     /* Keep in sync with |suffixes|, below. */
72     TYPE_CERT=0, TYPE_CRL=1
73 };
74
75 enum Hash {
76     HASH_OLD, HASH_NEW, HASH_BOTH
77 };
78
79
80 static int evpmdsize;
81 static const EVP_MD *evpmd;
82 static int remove_links = 1;
83 static int verbose = 0;
84 static BUCKET *hash_table[257];
85
86 static const char *suffixes[] = { "", "r" };
87 static const char *extensions[] = { "pem", "crt", "cer", "crl" };
88
89
90 static void bit_set(unsigned char *set, unsigned int bit)
91 {
92     set[bit >> 3] |= 1 << (bit & 0x7);
93 }
94
95 static int bit_isset(unsigned char *set, unsigned int bit)
96 {
97     return set[bit >> 3] & (1 << (bit & 0x7));
98 }
99
100
101 /*
102  * Process an entry; return number of errors.
103  */
104 static int add_entry(enum Type type, unsigned int hash, const char *filename,
105                       const unsigned char *digest, int need_symlink,
106                       unsigned short old_id)
107 {
108     static BUCKET nilbucket;
109     static HENTRY nilhentry;
110     BUCKET *bp;
111     HENTRY *ep, *found = NULL;
112     unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table);
113
114     for (bp = hash_table[ndx]; bp; bp = bp->next)
115         if (bp->type == type && bp->hash == hash)
116             break;
117     if (bp == NULL) {
118         bp = app_malloc(sizeof(*bp), "hash bucket");
119         *bp = nilbucket;
120         bp->next = hash_table[ndx];
121         bp->type = type;
122         bp->hash = hash;
123         hash_table[ndx] = bp;
124     }
125
126     for (ep = bp->first_entry; ep; ep = ep->next) {
127         if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) {
128             BIO_printf(bio_err,
129                        "%s: skipping duplicate %s in %s\n", opt_getprog(),
130                        type == TYPE_CERT ? "certificate" : "CRL", filename);
131             return 1;
132         }
133         if (strcmp(filename, ep->filename) == 0) {
134             found = ep;
135             if (digest == NULL)
136                 break;
137         }
138     }
139     ep = found;
140     if (ep == NULL) {
141         if (bp->num_needed >= MAX_COLLISIONS) {
142             BIO_printf(bio_err,
143                        "%s: hash table overflow for %s\n",
144                        opt_getprog(), filename);
145             return 1;
146         }
147         ep = app_malloc(sizeof(*ep), "collision bucket");
148         *ep = nilhentry;
149         ep->old_id = ~0;
150         ep->filename = OPENSSL_strdup(filename);
151         if (bp->last_entry)
152             bp->last_entry->next = ep;
153         if (bp->first_entry == NULL)
154             bp->first_entry = ep;
155         bp->last_entry = ep;
156     }
157
158     if (old_id < ep->old_id)
159         ep->old_id = old_id;
160     if (need_symlink && !ep->need_symlink) {
161         ep->need_symlink = 1;
162         bp->num_needed++;
163         memcpy(ep->digest, digest, evpmdsize);
164     }
165     return 0;
166 }
167
168 /*
169  * Check if a symlink goes to the right spot; return 0 if okay.
170  * This can be -1 if bad filename, or an error count.
171  */
172 static int handle_symlink(const char *filename, const char *fullpath)
173 {
174     unsigned int hash = 0;
175     int i, type, id;
176     unsigned char ch;
177     char linktarget[PATH_MAX], *endptr;
178     ossl_ssize_t n;
179
180     for (i = 0; i < 8; i++) {
181         ch = filename[i];
182         if (!isxdigit(ch))
183             return -1;
184         hash <<= 4;
185         hash += OPENSSL_hexchar2int(ch);
186     }
187     if (filename[i++] != '.')
188         return -1;
189     for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--) {
190         const char *suffix = suffixes[type];
191         if (strncasecmp(suffix, &filename[i], strlen(suffix)) == 0)
192             break;
193     }
194     i += strlen(suffixes[type]);
195
196     id = strtoul(&filename[i], &endptr, 10);
197     if (*endptr != '\0')
198         return -1;
199
200     n = readlink(fullpath, linktarget, sizeof(linktarget));
201     if (n < 0 || n >= (int)sizeof(linktarget))
202         return -1;
203     linktarget[n] = 0;
204
205     return add_entry(type, hash, linktarget, NULL, 0, id);
206 }
207
208 /*
209  * process a file, return number of errors.
210  */
211 static int do_file(const char *filename, const char *fullpath, enum Hash h)
212 {
213     STACK_OF (X509_INFO) *inf = NULL;
214     X509_INFO *x;
215     X509_NAME *name = NULL;
216     BIO *b;
217     const char *ext;
218     unsigned char digest[EVP_MAX_MD_SIZE];
219     int type, errs = 0;
220     size_t i;
221
222     /* Does it end with a recognized extension? */
223     if ((ext = strrchr(filename, '.')) == NULL)
224         goto end;
225     for (i = 0; i < OSSL_NELEM(extensions); i++) {
226         if (strcasecmp(extensions[i], ext + 1) == 0)
227             break;
228     }
229     if (i >= OSSL_NELEM(extensions))
230         goto end;
231
232     /* Does it have X.509 data in it? */
233     if ((b = BIO_new_file(fullpath, "r")) == NULL) {
234         BIO_printf(bio_err, "%s: skipping %s, cannot open file\n",
235                    opt_getprog(), filename);
236         errs++;
237         goto end;
238     }
239     inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
240     BIO_free(b);
241     if (inf == NULL)
242         goto end;
243
244     if (sk_X509_INFO_num(inf) != 1) {
245         BIO_printf(bio_err,
246                    "%s: skipping %s,"
247                    "it does not contain exactly one certificate or CRL\n",
248                    opt_getprog(), filename);
249         /* This is not an error. */
250         goto end;
251     }
252     x = sk_X509_INFO_value(inf, 0);
253     if (x->x509 != NULL) {
254         type = TYPE_CERT;
255         name = X509_get_subject_name(x->x509);
256         X509_digest(x->x509, evpmd, digest, NULL);
257     } else if (x->crl != NULL) {
258         type = TYPE_CRL;
259         name = X509_CRL_get_issuer(x->crl);
260         X509_CRL_digest(x->crl, evpmd, digest, NULL);
261     } else {
262         ++errs;
263         goto end;
264     }
265     if (name != NULL) {
266         if ((h == HASH_NEW) || (h == HASH_BOTH))
267             errs += add_entry(type, X509_NAME_hash(name), filename, digest, 1, ~0);
268         if ((h == HASH_OLD) || (h == HASH_BOTH))
269             errs += add_entry(type, X509_NAME_hash_old(name), filename, digest, 1, ~0);
270     }
271
272 end:
273     sk_X509_INFO_pop_free(inf, X509_INFO_free);
274     return errs;
275 }
276
277 static void str_free(char *s)
278 {
279     OPENSSL_free(s);
280 }
281
282 static int ends_with_dirsep(const char *path)
283 {
284     if (*path != '\0')
285         path += strlen(path) - 1;
286 # if defined __VMS
287     if (*path == ']' || *path == '>' || *path == ':')
288         return 1;
289 # elif defined _WIN32
290     if (*path == '\\')
291         return 1;
292 # endif
293     return *path == '/';
294 }
295
296 static int massage_filename(char *name)
297 {
298 # ifdef __VMS
299     char *p = strchr(name, ';');
300     char *q = p;
301
302     if (q != NULL) {
303         for (q++; *q != '\0'; q++) {
304             if (!isdigit((unsigned char)*q))
305                 return 1;
306         }
307     }
308
309     *p = '\0';
310 # endif
311     return 1;
312 }
313
314 /*
315  * Process a directory; return number of errors found.
316  */
317 static int do_dir(const char *dirname, enum Hash h)
318 {
319     BUCKET *bp, *nextbp;
320     HENTRY *ep, *nextep;
321     OPENSSL_DIR_CTX *d = NULL;
322     struct stat st;
323     unsigned char idmask[MAX_COLLISIONS / 8];
324     int n, numfiles, nextid, buflen, errs = 0;
325     size_t i;
326     const char *pathsep;
327     const char *filename;
328     char *buf, *copy;
329     STACK_OF(OPENSSL_STRING) *files = NULL;
330
331     if (app_access(dirname, W_OK) < 0) {
332         BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
333         return 1;
334     }
335     buflen = strlen(dirname);
336     pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
337     buflen += NAME_MAX + 1 + 1;
338     buf = app_malloc(buflen, "filename buffer");
339
340     if (verbose)
341         BIO_printf(bio_out, "Doing %s\n", dirname);
342
343     if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
344         BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
345         exit(1);
346     }
347     while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
348         if ((copy = strdup(filename)) == NULL
349                 || !massage_filename(copy)
350                 || sk_OPENSSL_STRING_push(files, copy) == 0) {
351             BIO_puts(bio_err, "out of memory\n");
352             exit(1);
353         }
354     }
355     OPENSSL_DIR_end(&d);
356     sk_OPENSSL_STRING_sort(files);
357
358     numfiles = sk_OPENSSL_STRING_num(files);
359     for (n = 0; n < numfiles; ++n) {
360         filename = sk_OPENSSL_STRING_value(files, n);
361         if (BIO_snprintf(buf, buflen, "%s%s%s",
362                          dirname, pathsep, filename) >= buflen)
363             continue;
364         if (lstat(buf, &st) < 0)
365             continue;
366         if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
367             continue;
368         errs += do_file(filename, buf, h);
369     }
370     sk_OPENSSL_STRING_pop_free(files, str_free);
371
372     for (i = 0; i < OSSL_NELEM(hash_table); i++) {
373         for (bp = hash_table[i]; bp; bp = nextbp) {
374             nextbp = bp->next;
375             nextid = 0;
376             memset(idmask, 0, (bp->num_needed + 7) / 8);
377             for (ep = bp->first_entry; ep; ep = ep->next)
378                 if (ep->old_id < bp->num_needed)
379                     bit_set(idmask, ep->old_id);
380
381             for (ep = bp->first_entry; ep; ep = nextep) {
382                 nextep = ep->next;
383                 if (ep->old_id < bp->num_needed) {
384                     /* Link exists, and is used as-is */
385                     BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash,
386                                  suffixes[bp->type], ep->old_id);
387                     if (verbose)
388                         BIO_printf(bio_out, "link %s -> %s\n",
389                                    ep->filename, buf);
390                 } else if (ep->need_symlink) {
391                     /* New link needed (it may replace something) */
392                     while (bit_isset(idmask, nextid))
393                         nextid++;
394
395                     BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
396                                  dirname, pathsep, &n, bp->hash,
397                                  suffixes[bp->type], nextid);
398                     if (verbose)
399                         BIO_printf(bio_out, "link %s -> %s\n",
400                                    ep->filename, &buf[n]);
401                     if (unlink(buf) < 0 && errno != ENOENT) {
402                         BIO_printf(bio_err,
403                                    "%s: Can't unlink %s, %s\n",
404                                    opt_getprog(), buf, strerror(errno));
405                         errs++;
406                     }
407                     if (symlink(ep->filename, buf) < 0) {
408                         BIO_printf(bio_err,
409                                    "%s: Can't symlink %s, %s\n",
410                                    opt_getprog(), ep->filename,
411                                    strerror(errno));
412                         errs++;
413                     }
414                     bit_set(idmask, nextid);
415                 } else if (remove_links) {
416                     /* Link to be deleted */
417                     BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
418                                  dirname, pathsep, &n, bp->hash,
419                                  suffixes[bp->type], ep->old_id);
420                     if (verbose)
421                         BIO_printf(bio_out, "unlink %s\n",
422                                    &buf[n]);
423                     if (unlink(buf) < 0 && errno != ENOENT) {
424                         BIO_printf(bio_err,
425                                    "%s: Can't unlink %s, %s\n",
426                                    opt_getprog(), buf, strerror(errno));
427                         errs++;
428                     }
429                 }
430                 OPENSSL_free(ep->filename);
431                 OPENSSL_free(ep);
432             }
433             OPENSSL_free(bp);
434         }
435         hash_table[i] = NULL;
436     }
437
438     OPENSSL_free(buf);
439     return errs;
440 }
441
442 typedef enum OPTION_choice {
443     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
444     OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE
445 } OPTION_CHOICE;
446
447 const OPTIONS rehash_options[] = {
448     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert-directory...]\n"},
449     {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
450     {"help", OPT_HELP, '-', "Display this summary"},
451     {"h", OPT_HELP, '-', "Display this summary"},
452     {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
453     {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
454     {"n", OPT_N, '-', "Do not remove existing links"},
455     {"v", OPT_VERBOSE, '-', "Verbose output"},
456     {NULL}
457 };
458
459
460 int rehash_main(int argc, char **argv)
461 {
462     const char *env, *prog;
463     char *e, *m;
464     int errs = 0;
465     OPTION_CHOICE o;
466     enum Hash h = HASH_NEW;
467
468     prog = opt_init(argc, argv, rehash_options);
469     while ((o = opt_next()) != OPT_EOF) {
470         switch (o) {
471         case OPT_EOF:
472         case OPT_ERR:
473             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
474             goto end;
475         case OPT_HELP:
476             opt_help(rehash_options);
477             goto end;
478         case OPT_COMPAT:
479             h = HASH_BOTH;
480             break;
481         case OPT_OLD:
482             h = HASH_OLD;
483             break;
484         case OPT_N:
485             remove_links = 0;
486             break;
487         case OPT_VERBOSE:
488             verbose = 1;
489             break;
490         }
491     }
492     argc = opt_num_rest();
493     argv = opt_rest();
494
495     evpmd = EVP_sha1();
496     evpmdsize = EVP_MD_size(evpmd);
497
498     if (*argv != NULL) {
499         while (*argv != NULL)
500             errs += do_dir(*argv++, h);
501     } else if ((env = getenv("SSL_CERT_DIR")) != NULL) {
502         m = OPENSSL_strdup(env);
503         for (e = strtok(m, ":"); e != NULL; e = strtok(NULL, ":"))
504             errs += do_dir(e, h);
505         OPENSSL_free(m);
506     } else {
507         errs += do_dir("/etc/ssl/certs", h);
508     }
509
510  end:
511     return errs;
512 }
513
514 #else
515 const OPTIONS rehash_options[] = {
516     {NULL}
517 };
518
519 int rehash_main(int argc, char **argv)
520 {
521     BIO_printf(bio_err, "Not available; use c_rehash script\n");
522     return 1;
523 }
524
525 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */