rehash.c 16 KB

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