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