Add a note and better error if using Ed25519/Ed448 in dgst
[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 /*
297  * Process a directory; return number of errors found.
298  */
299 static int do_dir(const char *dirname, enum Hash h)
300 {
301     BUCKET *bp, *nextbp;
302     HENTRY *ep, *nextep;
303     OPENSSL_DIR_CTX *d = NULL;
304     struct stat st;
305     unsigned char idmask[MAX_COLLISIONS / 8];
306     int n, numfiles, nextid, buflen, errs = 0;
307     size_t i;
308     const char *pathsep;
309     const char *filename;
310     char *buf, *copy;
311     STACK_OF(OPENSSL_STRING) *files = NULL;
312
313     if (app_access(dirname, W_OK) < 0) {
314         BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
315         return 1;
316     }
317     buflen = strlen(dirname);
318     pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
319     buflen += NAME_MAX + 1 + 1;
320     buf = app_malloc(buflen, "filename buffer");
321
322     if (verbose)
323         BIO_printf(bio_out, "Doing %s\n", dirname);
324
325     if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
326         BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
327         exit(1);
328     }
329     while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
330         if ((copy = strdup(filename)) == NULL
331                 || sk_OPENSSL_STRING_push(files, copy) == 0) {
332             BIO_puts(bio_err, "out of memory\n");
333             exit(1);
334         }
335     }
336     OPENSSL_DIR_end(&d);
337     sk_OPENSSL_STRING_sort(files);
338
339     numfiles = sk_OPENSSL_STRING_num(files);
340     for (n = 0; n < numfiles; ++n) {
341         filename = sk_OPENSSL_STRING_value(files, n);
342         if (BIO_snprintf(buf, buflen, "%s%s%s",
343                          dirname, pathsep, filename) >= buflen)
344             continue;
345         if (lstat(buf, &st) < 0)
346             continue;
347         if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
348             continue;
349         errs += do_file(filename, buf, h);
350     }
351     sk_OPENSSL_STRING_pop_free(files, str_free);
352
353     for (i = 0; i < OSSL_NELEM(hash_table); i++) {
354         for (bp = hash_table[i]; bp; bp = nextbp) {
355             nextbp = bp->next;
356             nextid = 0;
357             memset(idmask, 0, (bp->num_needed + 7) / 8);
358             for (ep = bp->first_entry; ep; ep = ep->next)
359                 if (ep->old_id < bp->num_needed)
360                     bit_set(idmask, ep->old_id);
361
362             for (ep = bp->first_entry; ep; ep = nextep) {
363                 nextep = ep->next;
364                 if (ep->old_id < bp->num_needed) {
365                     /* Link exists, and is used as-is */
366                     BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash,
367                                  suffixes[bp->type], ep->old_id);
368                     if (verbose)
369                         BIO_printf(bio_out, "link %s -> %s\n",
370                                    ep->filename, buf);
371                 } else if (ep->need_symlink) {
372                     /* New link needed (it may replace something) */
373                     while (bit_isset(idmask, nextid))
374                         nextid++;
375
376                     BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
377                                  dirname, pathsep, &n, bp->hash,
378                                  suffixes[bp->type], nextid);
379                     if (verbose)
380                         BIO_printf(bio_out, "link %s -> %s\n",
381                                    ep->filename, &buf[n]);
382                     if (unlink(buf) < 0 && errno != ENOENT) {
383                         BIO_printf(bio_err,
384                                    "%s: Can't unlink %s, %s\n",
385                                    opt_getprog(), buf, strerror(errno));
386                         errs++;
387                     }
388                     if (symlink(ep->filename, buf) < 0) {
389                         BIO_printf(bio_err,
390                                    "%s: Can't symlink %s, %s\n",
391                                    opt_getprog(), ep->filename,
392                                    strerror(errno));
393                         errs++;
394                     }
395                     bit_set(idmask, nextid);
396                 } else if (remove_links) {
397                     /* Link to be deleted */
398                     BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
399                                  dirname, pathsep, &n, bp->hash,
400                                  suffixes[bp->type], ep->old_id);
401                     if (verbose)
402                         BIO_printf(bio_out, "unlink %s\n",
403                                    &buf[n]);
404                     if (unlink(buf) < 0 && errno != ENOENT) {
405                         BIO_printf(bio_err,
406                                    "%s: Can't unlink %s, %s\n",
407                                    opt_getprog(), buf, strerror(errno));
408                         errs++;
409                     }
410                 }
411                 OPENSSL_free(ep->filename);
412                 OPENSSL_free(ep);
413             }
414             OPENSSL_free(bp);
415         }
416         hash_table[i] = NULL;
417     }
418
419     OPENSSL_free(buf);
420     return errs;
421 }
422
423 typedef enum OPTION_choice {
424     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
425     OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE
426 } OPTION_CHOICE;
427
428 const OPTIONS rehash_options[] = {
429     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert-directory...]\n"},
430     {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
431     {"help", OPT_HELP, '-', "Display this summary"},
432     {"h", OPT_HELP, '-', "Display this summary"},
433     {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
434     {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
435     {"n", OPT_N, '-', "Do not remove existing links"},
436     {"v", OPT_VERBOSE, '-', "Verbose output"},
437     {NULL}
438 };
439
440
441 int rehash_main(int argc, char **argv)
442 {
443     const char *env, *prog;
444     char *e, *m;
445     int errs = 0;
446     OPTION_CHOICE o;
447     enum Hash h = HASH_NEW;
448
449     prog = opt_init(argc, argv, rehash_options);
450     while ((o = opt_next()) != OPT_EOF) {
451         switch (o) {
452         case OPT_EOF:
453         case OPT_ERR:
454             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
455             goto end;
456         case OPT_HELP:
457             opt_help(rehash_options);
458             goto end;
459         case OPT_COMPAT:
460             h = HASH_BOTH;
461             break;
462         case OPT_OLD:
463             h = HASH_OLD;
464             break;
465         case OPT_N:
466             remove_links = 0;
467             break;
468         case OPT_VERBOSE:
469             verbose = 1;
470             break;
471         }
472     }
473     argc = opt_num_rest();
474     argv = opt_rest();
475
476     evpmd = EVP_sha1();
477     evpmdsize = EVP_MD_size(evpmd);
478
479     if (*argv != NULL) {
480         while (*argv != NULL)
481             errs += do_dir(*argv++, h);
482     } else if ((env = getenv("SSL_CERT_DIR")) != NULL) {
483         m = OPENSSL_strdup(env);
484         for (e = strtok(m, ":"); e != NULL; e = strtok(NULL, ":"))
485             errs += do_dir(e, h);
486         OPENSSL_free(m);
487     } else {
488         errs += do_dir("/etc/ssl/certs", h);
489     }
490
491  end:
492     return errs;
493 }
494
495 #else
496 const OPTIONS rehash_options[] = {
497     {NULL}
498 };
499
500 int rehash_main(int argc, char **argv)
501 {
502     BIO_printf(bio_err, "Not available; use c_rehash script\n");
503     return 1;
504 }
505
506 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */