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