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