2
0

rehash.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. /*
  2. * Copyright 2015-2022 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. /*
  303. * Process a directory; return number of errors found.
  304. */
  305. static int do_dir(const char *dirname, enum Hash h)
  306. {
  307. BUCKET *bp, *nextbp;
  308. HENTRY *ep, *nextep;
  309. OPENSSL_DIR_CTX *d = NULL;
  310. struct stat st;
  311. unsigned char idmask[MAX_COLLISIONS / 8];
  312. int n, numfiles, nextid, buflen, errs = 0;
  313. size_t i;
  314. const char *pathsep;
  315. const char *filename;
  316. char *buf, *copy = NULL;
  317. STACK_OF(OPENSSL_STRING) *files = NULL;
  318. if (app_access(dirname, W_OK) < 0) {
  319. BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
  320. return 1;
  321. }
  322. buflen = strlen(dirname);
  323. pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
  324. buflen += NAME_MAX + 1 + 1;
  325. buf = app_malloc(buflen, "filename buffer");
  326. if (verbose)
  327. BIO_printf(bio_out, "Doing %s\n", dirname);
  328. if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
  329. BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
  330. errs = 1;
  331. goto err;
  332. }
  333. while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
  334. if ((copy = OPENSSL_strdup(filename)) == NULL
  335. || sk_OPENSSL_STRING_push(files, copy) == 0) {
  336. OPENSSL_free(copy);
  337. BIO_puts(bio_err, "out of memory\n");
  338. errs = 1;
  339. goto err;
  340. }
  341. }
  342. OPENSSL_DIR_end(&d);
  343. sk_OPENSSL_STRING_sort(files);
  344. numfiles = sk_OPENSSL_STRING_num(files);
  345. for (n = 0; n < numfiles; ++n) {
  346. filename = sk_OPENSSL_STRING_value(files, n);
  347. if (BIO_snprintf(buf, buflen, "%s%s%s",
  348. dirname, pathsep, filename) >= buflen)
  349. continue;
  350. if (lstat(buf, &st) < 0)
  351. continue;
  352. if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
  353. continue;
  354. errs += do_file(filename, buf, h);
  355. }
  356. for (i = 0; i < OSSL_NELEM(hash_table); i++) {
  357. for (bp = hash_table[i]; bp; bp = nextbp) {
  358. nextbp = bp->next;
  359. nextid = 0;
  360. memset(idmask, 0, (bp->num_needed + 7) / 8);
  361. for (ep = bp->first_entry; ep; ep = ep->next)
  362. if (ep->old_id < bp->num_needed)
  363. bit_set(idmask, ep->old_id);
  364. for (ep = bp->first_entry; ep; ep = nextep) {
  365. nextep = ep->next;
  366. if (ep->old_id < bp->num_needed) {
  367. /* Link exists, and is used as-is */
  368. BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash,
  369. suffixes[bp->type], ep->old_id);
  370. if (verbose)
  371. BIO_printf(bio_out, "link %s -> %s\n",
  372. ep->filename, buf);
  373. } else if (ep->need_symlink) {
  374. /* New link needed (it may replace something) */
  375. while (bit_isset(idmask, nextid))
  376. nextid++;
  377. BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
  378. dirname, pathsep, &n, bp->hash,
  379. suffixes[bp->type], nextid);
  380. if (verbose)
  381. BIO_printf(bio_out, "link %s -> %s\n",
  382. ep->filename, &buf[n]);
  383. if (unlink(buf) < 0 && errno != ENOENT) {
  384. BIO_printf(bio_err,
  385. "%s: Can't unlink %s, %s\n",
  386. opt_getprog(), buf, strerror(errno));
  387. errs++;
  388. }
  389. if (symlink(ep->filename, buf) < 0) {
  390. BIO_printf(bio_err,
  391. "%s: Can't symlink %s, %s\n",
  392. opt_getprog(), ep->filename,
  393. strerror(errno));
  394. errs++;
  395. }
  396. bit_set(idmask, nextid);
  397. } else if (remove_links) {
  398. /* Link to be deleted */
  399. BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
  400. dirname, pathsep, &n, bp->hash,
  401. suffixes[bp->type], ep->old_id);
  402. if (verbose)
  403. BIO_printf(bio_out, "unlink %s\n",
  404. &buf[n]);
  405. if (unlink(buf) < 0 && errno != ENOENT) {
  406. BIO_printf(bio_err,
  407. "%s: Can't unlink %s, %s\n",
  408. opt_getprog(), buf, strerror(errno));
  409. errs++;
  410. }
  411. }
  412. OPENSSL_free(ep->filename);
  413. OPENSSL_free(ep);
  414. }
  415. OPENSSL_free(bp);
  416. }
  417. hash_table[i] = NULL;
  418. }
  419. err:
  420. sk_OPENSSL_STRING_pop_free(files, str_free);
  421. OPENSSL_free(buf);
  422. return errs;
  423. }
  424. typedef enum OPTION_choice {
  425. OPT_COMMON,
  426. OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE,
  427. OPT_PROV_ENUM
  428. } OPTION_CHOICE;
  429. const OPTIONS rehash_options[] = {
  430. {OPT_HELP_STR, 1, '-', "Usage: %s [options] [directory...]\n"},
  431. OPT_SECTION("General"),
  432. {"help", OPT_HELP, '-', "Display this summary"},
  433. {"h", OPT_HELP, '-', "Display this summary"},
  434. {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
  435. {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
  436. {"n", OPT_N, '-', "Do not remove existing links"},
  437. OPT_SECTION("Output"),
  438. {"v", OPT_VERBOSE, '-', "Verbose output"},
  439. OPT_PROV_OPTIONS,
  440. OPT_PARAMETERS(),
  441. {"directory", 0, 0, "One or more directories to process (optional)"},
  442. {NULL}
  443. };
  444. int rehash_main(int argc, char **argv)
  445. {
  446. const char *env, *prog;
  447. char *e, *m;
  448. int errs = 0;
  449. OPTION_CHOICE o;
  450. enum Hash h = HASH_NEW;
  451. prog = opt_init(argc, argv, rehash_options);
  452. while ((o = opt_next()) != OPT_EOF) {
  453. switch (o) {
  454. case OPT_EOF:
  455. case OPT_ERR:
  456. BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
  457. goto end;
  458. case OPT_HELP:
  459. opt_help(rehash_options);
  460. goto end;
  461. case OPT_COMPAT:
  462. h = HASH_BOTH;
  463. break;
  464. case OPT_OLD:
  465. h = HASH_OLD;
  466. break;
  467. case OPT_N:
  468. remove_links = 0;
  469. break;
  470. case OPT_VERBOSE:
  471. verbose = 1;
  472. break;
  473. case OPT_PROV_CASES:
  474. if (!opt_provider(o))
  475. goto end;
  476. break;
  477. }
  478. }
  479. /* Optional arguments are directories to scan. */
  480. argc = opt_num_rest();
  481. argv = opt_rest();
  482. evpmd = EVP_sha1();
  483. evpmdsize = EVP_MD_get_size(evpmd);
  484. if (*argv != NULL) {
  485. while (*argv != NULL)
  486. errs += do_dir(*argv++, h);
  487. } else if ((env = getenv(X509_get_default_cert_dir_env())) != NULL) {
  488. char lsc[2] = { LIST_SEPARATOR_CHAR, '\0' };
  489. m = OPENSSL_strdup(env);
  490. for (e = strtok(m, lsc); e != NULL; e = strtok(NULL, lsc))
  491. errs += do_dir(e, h);
  492. OPENSSL_free(m);
  493. } else {
  494. errs += do_dir(X509_get_default_cert_dir(), h);
  495. }
  496. end:
  497. return errs;
  498. }
  499. #else
  500. const OPTIONS rehash_options[] = {
  501. {NULL}
  502. };
  503. int rehash_main(int argc, char **argv)
  504. {
  505. BIO_printf(bio_err, "Not available; use c_rehash script\n");
  506. return 1;
  507. }
  508. #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */