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