rehash.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /*
  2. * Copyright 2015-2021 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 (bp->last_entry)
  147. bp->last_entry->next = ep;
  148. if (bp->first_entry == NULL)
  149. bp->first_entry = ep;
  150. bp->last_entry = ep;
  151. }
  152. if (old_id < ep->old_id)
  153. ep->old_id = old_id;
  154. if (need_symlink && !ep->need_symlink) {
  155. ep->need_symlink = 1;
  156. bp->num_needed++;
  157. memcpy(ep->digest, digest, evpmdsize);
  158. }
  159. return 0;
  160. }
  161. /*
  162. * Check if a symlink goes to the right spot; return 0 if okay.
  163. * This can be -1 if bad filename, or an error count.
  164. */
  165. static int handle_symlink(const char *filename, const char *fullpath)
  166. {
  167. unsigned int hash = 0;
  168. int i, type, id;
  169. unsigned char ch;
  170. char linktarget[PATH_MAX], *endptr;
  171. ossl_ssize_t n;
  172. for (i = 0; i < 8; i++) {
  173. ch = filename[i];
  174. if (!isxdigit(ch))
  175. return -1;
  176. hash <<= 4;
  177. hash += OPENSSL_hexchar2int(ch);
  178. }
  179. if (filename[i++] != '.')
  180. return -1;
  181. for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--) {
  182. const char *suffix = suffixes[type];
  183. if (strncasecmp(suffix, &filename[i], strlen(suffix)) == 0)
  184. break;
  185. }
  186. i += strlen(suffixes[type]);
  187. id = strtoul(&filename[i], &endptr, 10);
  188. if (*endptr != '\0')
  189. return -1;
  190. n = readlink(fullpath, linktarget, sizeof(linktarget));
  191. if (n < 0 || n >= (int)sizeof(linktarget))
  192. return -1;
  193. linktarget[n] = 0;
  194. return add_entry(type, hash, linktarget, NULL, 0, id);
  195. }
  196. /*
  197. * process a file, return number of errors.
  198. */
  199. static int do_file(const char *filename, const char *fullpath, enum Hash h)
  200. {
  201. STACK_OF (X509_INFO) *inf = NULL;
  202. X509_INFO *x;
  203. const X509_NAME *name = NULL;
  204. BIO *b;
  205. const char *ext;
  206. unsigned char digest[EVP_MAX_MD_SIZE];
  207. int type, errs = 0;
  208. size_t i;
  209. /* Does it end with a recognized extension? */
  210. if ((ext = strrchr(filename, '.')) == NULL)
  211. goto end;
  212. for (i = 0; i < OSSL_NELEM(extensions); i++) {
  213. if (strcasecmp(extensions[i], ext + 1) == 0)
  214. break;
  215. }
  216. if (i >= OSSL_NELEM(extensions))
  217. goto end;
  218. /* Does it have X.509 data in it? */
  219. if ((b = BIO_new_file(fullpath, "r")) == NULL) {
  220. BIO_printf(bio_err, "%s: error: skipping %s, cannot open file\n",
  221. opt_getprog(), filename);
  222. errs++;
  223. goto end;
  224. }
  225. inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
  226. BIO_free(b);
  227. if (inf == NULL)
  228. goto end;
  229. if (sk_X509_INFO_num(inf) != 1) {
  230. BIO_printf(bio_err,
  231. "%s: warning: skipping %s,"
  232. "it does not contain exactly one certificate or CRL\n",
  233. opt_getprog(), filename);
  234. /* This is not an error. */
  235. goto end;
  236. }
  237. x = sk_X509_INFO_value(inf, 0);
  238. if (x->x509 != NULL) {
  239. type = TYPE_CERT;
  240. name = X509_get_subject_name(x->x509);
  241. if (!X509_digest(x->x509, evpmd, digest, NULL)) {
  242. BIO_printf(bio_err, "out of memory\n");
  243. ++errs;
  244. goto end;
  245. }
  246. } else if (x->crl != NULL) {
  247. type = TYPE_CRL;
  248. name = X509_CRL_get_issuer(x->crl);
  249. if (!X509_CRL_digest(x->crl, evpmd, digest, NULL)) {
  250. BIO_printf(bio_err, "out of memory\n");
  251. ++errs;
  252. goto end;
  253. }
  254. } else {
  255. ++errs;
  256. goto end;
  257. }
  258. if (name != NULL) {
  259. if (h == HASH_NEW || h == HASH_BOTH) {
  260. int ok;
  261. unsigned long hash_value =
  262. X509_NAME_hash_ex(name,
  263. app_get0_libctx(), app_get0_propq(), &ok);
  264. if (ok) {
  265. errs += add_entry(type, hash_value, filename, digest, 1, ~0);
  266. } else {
  267. BIO_printf(bio_err, "%s: error calculating SHA1 hash value\n",
  268. opt_getprog());
  269. errs++;
  270. }
  271. }
  272. if ((h == HASH_OLD) || (h == HASH_BOTH))
  273. errs += add_entry(type, X509_NAME_hash_old(name),
  274. filename, digest, 1, ~0);
  275. }
  276. end:
  277. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  278. return errs;
  279. }
  280. static void str_free(char *s)
  281. {
  282. OPENSSL_free(s);
  283. }
  284. static int ends_with_dirsep(const char *path)
  285. {
  286. if (*path != '\0')
  287. path += strlen(path) - 1;
  288. # if defined __VMS
  289. if (*path == ']' || *path == '>' || *path == ':')
  290. return 1;
  291. # elif defined _WIN32
  292. if (*path == '\\')
  293. return 1;
  294. # endif
  295. return *path == '/';
  296. }
  297. /*
  298. * Process a directory; return number of errors found.
  299. */
  300. static int do_dir(const char *dirname, enum Hash h)
  301. {
  302. BUCKET *bp, *nextbp;
  303. HENTRY *ep, *nextep;
  304. OPENSSL_DIR_CTX *d = NULL;
  305. struct stat st;
  306. unsigned char idmask[MAX_COLLISIONS / 8];
  307. int n, numfiles, nextid, buflen, errs = 0;
  308. size_t i;
  309. const char *pathsep;
  310. const char *filename;
  311. char *buf, *copy = NULL;
  312. STACK_OF(OPENSSL_STRING) *files = NULL;
  313. if (app_access(dirname, W_OK) < 0) {
  314. BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
  315. return 1;
  316. }
  317. buflen = strlen(dirname);
  318. pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
  319. buflen += NAME_MAX + 1 + 1;
  320. buf = app_malloc(buflen, "filename buffer");
  321. if (verbose)
  322. BIO_printf(bio_out, "Doing %s\n", dirname);
  323. if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
  324. BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
  325. errs = 1;
  326. goto err;
  327. }
  328. while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
  329. if ((copy = OPENSSL_strdup(filename)) == NULL
  330. || sk_OPENSSL_STRING_push(files, copy) == 0) {
  331. OPENSSL_free(copy);
  332. BIO_puts(bio_err, "out of memory\n");
  333. errs = 1;
  334. goto err;
  335. }
  336. }
  337. OPENSSL_DIR_end(&d);
  338. sk_OPENSSL_STRING_sort(files);
  339. numfiles = sk_OPENSSL_STRING_num(files);
  340. for (n = 0; n < numfiles; ++n) {
  341. filename = sk_OPENSSL_STRING_value(files, n);
  342. if (BIO_snprintf(buf, buflen, "%s%s%s",
  343. dirname, pathsep, filename) >= buflen)
  344. continue;
  345. if (lstat(buf, &st) < 0)
  346. continue;
  347. if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
  348. continue;
  349. errs += do_file(filename, buf, h);
  350. }
  351. for (i = 0; i < OSSL_NELEM(hash_table); i++) {
  352. for (bp = hash_table[i]; bp; bp = nextbp) {
  353. nextbp = bp->next;
  354. nextid = 0;
  355. memset(idmask, 0, (bp->num_needed + 7) / 8);
  356. for (ep = bp->first_entry; ep; ep = ep->next)
  357. if (ep->old_id < bp->num_needed)
  358. bit_set(idmask, ep->old_id);
  359. for (ep = bp->first_entry; ep; ep = nextep) {
  360. nextep = ep->next;
  361. if (ep->old_id < bp->num_needed) {
  362. /* Link exists, and is used as-is */
  363. BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash,
  364. suffixes[bp->type], ep->old_id);
  365. if (verbose)
  366. BIO_printf(bio_out, "link %s -> %s\n",
  367. ep->filename, buf);
  368. } else if (ep->need_symlink) {
  369. /* New link needed (it may replace something) */
  370. while (bit_isset(idmask, nextid))
  371. nextid++;
  372. BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
  373. dirname, pathsep, &n, bp->hash,
  374. suffixes[bp->type], nextid);
  375. if (verbose)
  376. BIO_printf(bio_out, "link %s -> %s\n",
  377. ep->filename, &buf[n]);
  378. if (unlink(buf) < 0 && errno != ENOENT) {
  379. BIO_printf(bio_err,
  380. "%s: Can't unlink %s, %s\n",
  381. opt_getprog(), buf, strerror(errno));
  382. errs++;
  383. }
  384. if (symlink(ep->filename, buf) < 0) {
  385. BIO_printf(bio_err,
  386. "%s: Can't symlink %s, %s\n",
  387. opt_getprog(), ep->filename,
  388. strerror(errno));
  389. errs++;
  390. }
  391. bit_set(idmask, nextid);
  392. } else if (remove_links) {
  393. /* Link to be deleted */
  394. BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
  395. dirname, pathsep, &n, bp->hash,
  396. suffixes[bp->type], ep->old_id);
  397. if (verbose)
  398. BIO_printf(bio_out, "unlink %s\n",
  399. &buf[n]);
  400. if (unlink(buf) < 0 && errno != ENOENT) {
  401. BIO_printf(bio_err,
  402. "%s: Can't unlink %s, %s\n",
  403. opt_getprog(), buf, strerror(errno));
  404. errs++;
  405. }
  406. }
  407. OPENSSL_free(ep->filename);
  408. OPENSSL_free(ep);
  409. }
  410. OPENSSL_free(bp);
  411. }
  412. hash_table[i] = NULL;
  413. }
  414. err:
  415. sk_OPENSSL_STRING_pop_free(files, str_free);
  416. OPENSSL_free(buf);
  417. return errs;
  418. }
  419. typedef enum OPTION_choice {
  420. OPT_COMMON,
  421. OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE,
  422. OPT_PROV_ENUM
  423. } OPTION_CHOICE;
  424. const OPTIONS rehash_options[] = {
  425. {OPT_HELP_STR, 1, '-', "Usage: %s [options] [directory...]\n"},
  426. OPT_SECTION("General"),
  427. {"help", OPT_HELP, '-', "Display this summary"},
  428. {"h", OPT_HELP, '-', "Display this summary"},
  429. {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
  430. {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
  431. {"n", OPT_N, '-', "Do not remove existing links"},
  432. OPT_SECTION("Output"),
  433. {"v", OPT_VERBOSE, '-', "Verbose output"},
  434. OPT_PROV_OPTIONS,
  435. OPT_PARAMETERS(),
  436. {"directory", 0, 0, "One or more directories to process (optional)"},
  437. {NULL}
  438. };
  439. int rehash_main(int argc, char **argv)
  440. {
  441. const char *env, *prog;
  442. char *e, *m;
  443. int errs = 0;
  444. OPTION_CHOICE o;
  445. enum Hash h = HASH_NEW;
  446. prog = opt_init(argc, argv, rehash_options);
  447. while ((o = opt_next()) != OPT_EOF) {
  448. switch (o) {
  449. case OPT_EOF:
  450. case OPT_ERR:
  451. BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
  452. goto end;
  453. case OPT_HELP:
  454. opt_help(rehash_options);
  455. goto end;
  456. case OPT_COMPAT:
  457. h = HASH_BOTH;
  458. break;
  459. case OPT_OLD:
  460. h = HASH_OLD;
  461. break;
  462. case OPT_N:
  463. remove_links = 0;
  464. break;
  465. case OPT_VERBOSE:
  466. verbose = 1;
  467. break;
  468. case OPT_PROV_CASES:
  469. if (!opt_provider(o))
  470. goto end;
  471. break;
  472. }
  473. }
  474. /* Optional arguments are directories to scan. */
  475. argc = opt_num_rest();
  476. argv = opt_rest();
  477. evpmd = EVP_sha1();
  478. evpmdsize = EVP_MD_get_size(evpmd);
  479. if (*argv != NULL) {
  480. while (*argv != NULL)
  481. errs += do_dir(*argv++, h);
  482. } else if ((env = getenv(X509_get_default_cert_dir_env())) != NULL) {
  483. char lsc[2] = { LIST_SEPARATOR_CHAR, '\0' };
  484. m = OPENSSL_strdup(env);
  485. for (e = strtok(m, lsc); e != NULL; e = strtok(NULL, lsc))
  486. errs += do_dir(e, h);
  487. OPENSSL_free(m);
  488. } else {
  489. errs += do_dir(X509_get_default_cert_dir(), h);
  490. }
  491. end:
  492. return errs;
  493. }
  494. #else
  495. const OPTIONS rehash_options[] = {
  496. {NULL}
  497. };
  498. int rehash_main(int argc, char **argv)
  499. {
  500. BIO_printf(bio_err, "Not available; use c_rehash script\n");
  501. return 1;
  502. }
  503. #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */