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