rehash.c 16 KB

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