rehash.c 16 KB

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