]> git.ipfire.org Git - thirdparty/openssl.git/blame - apps/rehash.c
Rename all getters to use get/get0 in name
[thirdparty/openssl.git] / apps / rehash.c
CommitLineData
8f6f1441 1/*
4333b89f 2 * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
4602cc85 3 * Copyright (c) 2013-2014 Timo Teräs <timo.teras@gmail.com>
8f6f1441 4 *
dffa7520 5 * Licensed under the Apache License 2.0 (the "License"). You may not use
846e33c7
RS
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
8f6f1441 9 */
846e33c7 10
8f6f1441 11#include "apps.h"
dab2cd68 12#include "progs.h"
8f6f1441 13
6616429d 14#if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) || \
5c80e2af 15 (defined(__VMS) && defined(__DECC) && __CRTL_VER >= 80300000)
8f6f1441
TT
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
2ac915f1
RL
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
8f6f1441 35# include "internal/o_dir.h"
2ac915f1
RL
36
37# ifdef __VMS
38# pragma names restore
39# endif
40
8f6f1441
TT
41# include <openssl/evp.h>
42# include <openssl/pem.h>
43# include <openssl/x509.h>
44
6616429d
RL
45# ifndef PATH_MAX
46# define PATH_MAX 4096
47# endif
c9c84a13
AG
48# ifndef NAME_MAX
49# define NAME_MAX 255
50# endif
8f6f1441
TT
51# define MAX_COLLISIONS 256
52
5c8b7b4c
KT
53# if defined(OPENSSL_SYS_VXWORKS)
54/*
55 * VxWorks has no symbolic links
56 */
57
58# define lstat(path, buf) stat(path, buf)
59
60int symlink(const char *target, const char *linkpath)
61{
62 errno = ENOSYS;
63 return -1;
64}
65
66ssize_t readlink(const char *pathname, char *buf, size_t bufsiz)
67{
68 errno = ENOSYS;
69 return -1;
70}
71# endif
72
8f6f1441
TT
73typedef 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
81typedef 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
89enum Type {
90 /* Keep in sync with |suffixes|, below. */
91 TYPE_CERT=0, TYPE_CRL=1
92};
93
94enum Hash {
95 HASH_OLD, HASH_NEW, HASH_BOTH
96};
97
98
99static int evpmdsize;
100static const EVP_MD *evpmd;
101static int remove_links = 1;
102static int verbose = 0;
103static BUCKET *hash_table[257];
104
105static const char *suffixes[] = { "", "r" };
106static const char *extensions[] = { "pem", "crt", "cer", "crl" };
107
108
109static void bit_set(unsigned char *set, unsigned int bit)
110{
111 set[bit >> 3] |= 1 << (bit & 0x7);
112}
113
114static int bit_isset(unsigned char *set, unsigned int bit)
115{
116 return set[bit >> 3] & (1 << (bit & 0x7));
117}
118
119
ce249fac
RS
120/*
121 * Process an entry; return number of errors.
122 */
123static int add_entry(enum Type type, unsigned int hash, const char *filename,
8f6f1441
TT
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,
e6a833cb
RL
148 "%s: warning: skipping duplicate %s in %s\n",
149 opt_getprog(),
f22ff0eb 150 type == TYPE_CERT ? "certificate" : "CRL", filename);
e6a833cb 151 return 0;
8f6f1441
TT
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) {
ce249fac
RS
161 if (bp->num_needed >= MAX_COLLISIONS) {
162 BIO_printf(bio_err,
e6a833cb 163 "%s: error: hash table overflow for %s\n",
ce249fac
RS
164 opt_getprog(), filename);
165 return 1;
166 }
8f6f1441
TT
167 ep = app_malloc(sizeof(*ep), "collision bucket");
168 *ep = nilhentry;
169 ep->old_id = ~0;
7644a9ae 170 ep->filename = OPENSSL_strdup(filename);
8f6f1441
TT
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 }
ce249fac 185 return 0;
8f6f1441
TT
186}
187
ce249fac
RS
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 */
8f6f1441
TT
192static int handle_symlink(const char *filename, const char *fullpath)
193{
194 unsigned int hash = 0;
195 int i, type, id;
196 unsigned char ch;
e7a68985 197 char linktarget[PATH_MAX], *endptr;
6616429d 198 ossl_ssize_t n;
8f6f1441
TT
199
200 for (i = 0; i < 8; i++) {
201 ch = filename[i];
202 if (!isxdigit(ch))
203 return -1;
204 hash <<= 4;
14f051a0 205 hash += OPENSSL_hexchar2int(ch);
8f6f1441
TT
206 }
207 if (filename[i++] != '.')
208 return -1;
ee8f7858
DSH
209 for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--) {
210 const char *suffix = suffixes[type];
211 if (strncasecmp(suffix, &filename[i], strlen(suffix)) == 0)
8f6f1441 212 break;
ee8f7858 213 }
8f6f1441
TT
214 i += strlen(suffixes[type]);
215
216 id = strtoul(&filename[i], &endptr, 10);
217 if (*endptr != '\0')
218 return -1;
219
220 n = readlink(fullpath, linktarget, sizeof(linktarget));
221 if (n < 0 || n >= (int)sizeof(linktarget))
222 return -1;
223 linktarget[n] = 0;
224
ce249fac 225 return add_entry(type, hash, linktarget, NULL, 0, id);
8f6f1441
TT
226}
227
ce249fac
RS
228/*
229 * process a file, return number of errors.
230 */
8f6f1441
TT
231static int do_file(const char *filename, const char *fullpath, enum Hash h)
232{
ce249fac 233 STACK_OF (X509_INFO) *inf = NULL;
8f6f1441 234 X509_INFO *x;
8cc86b81 235 const X509_NAME *name = NULL;
8f6f1441
TT
236 BIO *b;
237 const char *ext;
238 unsigned char digest[EVP_MAX_MD_SIZE];
8c82de99
BL
239 int type, errs = 0;
240 size_t i;
8f6f1441 241
ce249fac 242 /* Does it end with a recognized extension? */
8f6f1441 243 if ((ext = strrchr(filename, '.')) == NULL)
ce249fac 244 goto end;
8c82de99 245 for (i = 0; i < OSSL_NELEM(extensions); i++) {
8f6f1441
TT
246 if (strcasecmp(extensions[i], ext + 1) == 0)
247 break;
248 }
8c82de99 249 if (i >= OSSL_NELEM(extensions))
ce249fac 250 goto end;
8f6f1441 251
ce249fac
RS
252 /* Does it have X.509 data in it? */
253 if ((b = BIO_new_file(fullpath, "r")) == NULL) {
e6a833cb 254 BIO_printf(bio_err, "%s: error: skipping %s, cannot open file\n",
ce249fac
RS
255 opt_getprog(), filename);
256 errs++;
257 goto end;
258 }
8f6f1441
TT
259 inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
260 BIO_free(b);
261 if (inf == NULL)
ce249fac 262 goto end;
8f6f1441
TT
263
264 if (sk_X509_INFO_num(inf) != 1) {
265 BIO_printf(bio_err,
e6a833cb 266 "%s: warning: skipping %s,"
8f6f1441
TT
267 "it does not contain exactly one certificate or CRL\n",
268 opt_getprog(), filename);
ce249fac 269 /* This is not an error. */
8f6f1441
TT
270 goto end;
271 }
272 x = sk_X509_INFO_value(inf, 0);
2234212c 273 if (x->x509 != NULL) {
8f6f1441
TT
274 type = TYPE_CERT;
275 name = X509_get_subject_name(x->x509);
7e06a675
BE
276 if (!X509_digest(x->x509, evpmd, digest, NULL)) {
277 BIO_printf(bio_err, "out of memory\n");
278 ++errs;
279 goto end;
280 }
2234212c 281 } else if (x->crl != NULL) {
8f6f1441
TT
282 type = TYPE_CRL;
283 name = X509_CRL_get_issuer(x->crl);
7e06a675
BE
284 if (!X509_CRL_digest(x->crl, evpmd, digest, NULL)) {
285 BIO_printf(bio_err, "out of memory\n");
286 ++errs;
287 goto end;
288 }
8c82de99
BL
289 } else {
290 ++errs;
291 goto end;
8f6f1441 292 }
2234212c 293 if (name != NULL) {
bf973d06
DDO
294 if (h == HASH_NEW || h == HASH_BOTH) {
295 int ok;
296 unsigned long hash_value =
297 X509_NAME_hash_ex(name,
298 app_get0_libctx(), app_get0_propq(), &ok);
299
300 if (ok) {
301 errs += add_entry(type, hash_value, filename, digest, 1, ~0);
302 } else {
303 BIO_printf(bio_err, "%s: error calculating SHA1 hash value\n",
304 opt_getprog());
305 errs++;
306 }
307 }
8f6f1441 308 if ((h == HASH_OLD) || (h == HASH_BOTH))
bf973d06
DDO
309 errs += add_entry(type, X509_NAME_hash_old(name),
310 filename, digest, 1, ~0);
8f6f1441
TT
311 }
312
313end:
314 sk_X509_INFO_pop_free(inf, X509_INFO_free);
ce249fac 315 return errs;
8f6f1441
TT
316}
317
b1ffe8db
RS
318static void str_free(char *s)
319{
320 OPENSSL_free(s);
321}
322
5c80e2af
RL
323static int ends_with_dirsep(const char *path)
324{
325 if (*path != '\0')
326 path += strlen(path) - 1;
46958a04 327# if defined __VMS
5c80e2af
RL
328 if (*path == ']' || *path == '>' || *path == ':')
329 return 1;
46958a04 330# elif defined _WIN32
5c80e2af
RL
331 if (*path == '\\')
332 return 1;
333# endif
334 return *path == '/';
335}
336
ce249fac
RS
337/*
338 * Process a directory; return number of errors found.
339 */
8f6f1441
TT
340static int do_dir(const char *dirname, enum Hash h)
341{
342 BUCKET *bp, *nextbp;
343 HENTRY *ep, *nextep;
344 OPENSSL_DIR_CTX *d = NULL;
345 struct stat st;
346 unsigned char idmask[MAX_COLLISIONS / 8];
b1ffe8db 347 int n, numfiles, nextid, buflen, errs = 0;
8c82de99 348 size_t i;
8f6f1441
TT
349 const char *pathsep;
350 const char *filename;
02a7e0a9 351 char *buf, *copy = NULL;
b1ffe8db 352 STACK_OF(OPENSSL_STRING) *files = NULL;
8f6f1441 353
ff2f6bb0
RS
354 if (app_access(dirname, W_OK) < 0) {
355 BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
4c7103a5 356 return 1;
ff2f6bb0 357 }
8f6f1441 358 buflen = strlen(dirname);
5c80e2af 359 pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
c9c84a13
AG
360 buflen += NAME_MAX + 1 + 1;
361 buf = app_malloc(buflen, "filename buffer");
8f6f1441
TT
362
363 if (verbose)
364 BIO_printf(bio_out, "Doing %s\n", dirname);
365
b1ffe8db
RS
366 if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
367 BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
02a7e0a9
TS
368 errs = 1;
369 goto err;
b1ffe8db 370 }
8f6f1441 371 while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
02a7e0a9 372 if ((copy = OPENSSL_strdup(filename)) == NULL
b1ffe8db 373 || sk_OPENSSL_STRING_push(files, copy) == 0) {
02a7e0a9 374 OPENSSL_free(copy);
b1ffe8db 375 BIO_puts(bio_err, "out of memory\n");
02a7e0a9
TS
376 errs = 1;
377 goto err;
b1ffe8db
RS
378 }
379 }
380 OPENSSL_DIR_end(&d);
381 sk_OPENSSL_STRING_sort(files);
382
383 numfiles = sk_OPENSSL_STRING_num(files);
384 for (n = 0; n < numfiles; ++n) {
385 filename = sk_OPENSSL_STRING_value(files, n);
c41048ff
RS
386 if (BIO_snprintf(buf, buflen, "%s%s%s",
387 dirname, pathsep, filename) >= buflen)
8f6f1441
TT
388 continue;
389 if (lstat(buf, &st) < 0)
390 continue;
391 if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
392 continue;
ce249fac 393 errs += do_file(filename, buf, h);
8f6f1441 394 }
8f6f1441 395
8c82de99 396 for (i = 0; i < OSSL_NELEM(hash_table); i++) {
8f6f1441
TT
397 for (bp = hash_table[i]; bp; bp = nextbp) {
398 nextbp = bp->next;
399 nextid = 0;
400 memset(idmask, 0, (bp->num_needed + 7) / 8);
401 for (ep = bp->first_entry; ep; ep = ep->next)
402 if (ep->old_id < bp->num_needed)
403 bit_set(idmask, ep->old_id);
404
405 for (ep = bp->first_entry; ep; ep = nextep) {
406 nextep = ep->next;
407 if (ep->old_id < bp->num_needed) {
408 /* Link exists, and is used as-is */
c41048ff
RS
409 BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash,
410 suffixes[bp->type], ep->old_id);
8f6f1441
TT
411 if (verbose)
412 BIO_printf(bio_out, "link %s -> %s\n",
413 ep->filename, buf);
414 } else if (ep->need_symlink) {
415 /* New link needed (it may replace something) */
416 while (bit_isset(idmask, nextid))
417 nextid++;
418
c41048ff
RS
419 BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
420 dirname, pathsep, &n, bp->hash,
421 suffixes[bp->type], nextid);
8f6f1441
TT
422 if (verbose)
423 BIO_printf(bio_out, "link %s -> %s\n",
424 ep->filename, &buf[n]);
ce249fac 425 if (unlink(buf) < 0 && errno != ENOENT) {
8f6f1441
TT
426 BIO_printf(bio_err,
427 "%s: Can't unlink %s, %s\n",
428 opt_getprog(), buf, strerror(errno));
ce249fac
RS
429 errs++;
430 }
431 if (symlink(ep->filename, buf) < 0) {
8f6f1441
TT
432 BIO_printf(bio_err,
433 "%s: Can't symlink %s, %s\n",
434 opt_getprog(), ep->filename,
435 strerror(errno));
ce249fac
RS
436 errs++;
437 }
3770b877 438 bit_set(idmask, nextid);
8f6f1441
TT
439 } else if (remove_links) {
440 /* Link to be deleted */
c41048ff
RS
441 BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
442 dirname, pathsep, &n, bp->hash,
443 suffixes[bp->type], ep->old_id);
8f6f1441
TT
444 if (verbose)
445 BIO_printf(bio_out, "unlink %s\n",
446 &buf[n]);
ce249fac 447 if (unlink(buf) < 0 && errno != ENOENT) {
8f6f1441
TT
448 BIO_printf(bio_err,
449 "%s: Can't unlink %s, %s\n",
450 opt_getprog(), buf, strerror(errno));
ce249fac
RS
451 errs++;
452 }
8f6f1441
TT
453 }
454 OPENSSL_free(ep->filename);
455 OPENSSL_free(ep);
456 }
457 OPENSSL_free(bp);
458 }
459 hash_table[i] = NULL;
460 }
8f6f1441 461
02a7e0a9
TS
462 err:
463 sk_OPENSSL_STRING_pop_free(files, str_free);
8f6f1441 464 OPENSSL_free(buf);
ce249fac 465 return errs;
8f6f1441
TT
466}
467
468typedef enum OPTION_choice {
b0f96018 469 OPT_COMMON,
6bd4e3f2
P
470 OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE,
471 OPT_PROV_ENUM
8f6f1441
TT
472} OPTION_CHOICE;
473
44c83ebd 474const OPTIONS rehash_options[] = {
92de469f 475 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [directory...]\n"},
5388f986
RS
476
477 OPT_SECTION("General"),
8f6f1441 478 {"help", OPT_HELP, '-', "Display this summary"},
7d959c35 479 {"h", OPT_HELP, '-', "Display this summary"},
8f6f1441
TT
480 {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
481 {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
482 {"n", OPT_N, '-', "Do not remove existing links"},
5388f986
RS
483
484 OPT_SECTION("Output"),
8f6f1441 485 {"v", OPT_VERBOSE, '-', "Verbose output"},
92de469f 486
6bd4e3f2
P
487 OPT_PROV_OPTIONS,
488
92de469f
RS
489 OPT_PARAMETERS(),
490 {"directory", 0, 0, "One or more directories to process (optional)"},
8f6f1441
TT
491 {NULL}
492};
493
494
495int rehash_main(int argc, char **argv)
496{
497 const char *env, *prog;
498 char *e, *m;
ce249fac 499 int errs = 0;
8f6f1441
TT
500 OPTION_CHOICE o;
501 enum Hash h = HASH_NEW;
502
503 prog = opt_init(argc, argv, rehash_options);
504 while ((o = opt_next()) != OPT_EOF) {
505 switch (o) {
506 case OPT_EOF:
507 case OPT_ERR:
508 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
509 goto end;
510 case OPT_HELP:
511 opt_help(rehash_options);
512 goto end;
513 case OPT_COMPAT:
514 h = HASH_BOTH;
515 break;
516 case OPT_OLD:
517 h = HASH_OLD;
518 break;
519 case OPT_N:
520 remove_links = 0;
521 break;
522 case OPT_VERBOSE:
523 verbose = 1;
524 break;
6bd4e3f2
P
525 case OPT_PROV_CASES:
526 if (!opt_provider(o))
527 goto end;
528 break;
8f6f1441
TT
529 }
530 }
021410ea
RS
531
532 /* Optional arguments are directories to scan. */
8f6f1441
TT
533 argc = opt_num_rest();
534 argv = opt_rest();
535
536 evpmd = EVP_sha1();
ed576acd 537 evpmdsize = EVP_MD_get_size(evpmd);
8f6f1441 538
2234212c
PY
539 if (*argv != NULL) {
540 while (*argv != NULL)
ce249fac 541 errs += do_dir(*argv++, h);
362ff3c3
RL
542 } else if ((env = getenv(X509_get_default_cert_dir_env())) != NULL) {
543 char lsc[2] = { LIST_SEPARATOR_CHAR, '\0' };
7644a9ae 544 m = OPENSSL_strdup(env);
362ff3c3 545 for (e = strtok(m, lsc); e != NULL; e = strtok(NULL, lsc))
ce249fac 546 errs += do_dir(e, h);
8f6f1441
TT
547 OPENSSL_free(m);
548 } else {
362ff3c3 549 errs += do_dir(X509_get_default_cert_dir(), h);
8f6f1441
TT
550 }
551
552 end:
ce249fac 553 return errs;
8f6f1441
TT
554}
555
556#else
44c83ebd 557const OPTIONS rehash_options[] = {
62fdf4ee
RS
558 {NULL}
559};
8f6f1441
TT
560
561int rehash_main(int argc, char **argv)
562{
9e0da060 563 BIO_printf(bio_err, "Not available; use c_rehash script\n");
208fb891 564 return 1;
8f6f1441
TT
565}
566
568b8020 567#endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */