2
0

rehash.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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 OpenSSL license (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. 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. errs += add_entry(type, X509_NAME_hash(name), filename, digest, 1, ~0);
  261. if ((h == HASH_OLD) || (h == HASH_BOTH))
  262. errs += add_entry(type, X509_NAME_hash_old(name), filename, digest, 1, ~0);
  263. }
  264. end:
  265. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  266. return errs;
  267. }
  268. static void str_free(char *s)
  269. {
  270. OPENSSL_free(s);
  271. }
  272. static int ends_with_dirsep(const char *path)
  273. {
  274. if (*path != '\0')
  275. path += strlen(path) - 1;
  276. # if defined __VMS
  277. if (*path == ']' || *path == '>' || *path == ':')
  278. return 1;
  279. # elif defined _WIN32
  280. if (*path == '\\')
  281. return 1;
  282. # endif
  283. return *path == '/';
  284. }
  285. /*
  286. * Process a directory; return number of errors found.
  287. */
  288. static int do_dir(const char *dirname, enum Hash h)
  289. {
  290. BUCKET *bp, *nextbp;
  291. HENTRY *ep, *nextep;
  292. OPENSSL_DIR_CTX *d = NULL;
  293. struct stat st;
  294. unsigned char idmask[MAX_COLLISIONS / 8];
  295. int n, numfiles, nextid, buflen, errs = 0;
  296. size_t i;
  297. const char *pathsep;
  298. const char *filename;
  299. char *buf, *copy = NULL;
  300. STACK_OF(OPENSSL_STRING) *files = NULL;
  301. if (app_access(dirname, W_OK) < 0) {
  302. BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
  303. return 1;
  304. }
  305. buflen = strlen(dirname);
  306. pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
  307. buflen += NAME_MAX + 1 + 1;
  308. buf = app_malloc(buflen, "filename buffer");
  309. if (verbose)
  310. BIO_printf(bio_out, "Doing %s\n", dirname);
  311. if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
  312. BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
  313. errs = 1;
  314. goto err;
  315. }
  316. while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
  317. if ((copy = OPENSSL_strdup(filename)) == NULL
  318. || sk_OPENSSL_STRING_push(files, copy) == 0) {
  319. OPENSSL_free(copy);
  320. BIO_puts(bio_err, "out of memory\n");
  321. errs = 1;
  322. goto err;
  323. }
  324. }
  325. OPENSSL_DIR_end(&d);
  326. sk_OPENSSL_STRING_sort(files);
  327. numfiles = sk_OPENSSL_STRING_num(files);
  328. for (n = 0; n < numfiles; ++n) {
  329. filename = sk_OPENSSL_STRING_value(files, n);
  330. if (BIO_snprintf(buf, buflen, "%s%s%s",
  331. dirname, pathsep, filename) >= buflen)
  332. continue;
  333. if (lstat(buf, &st) < 0)
  334. continue;
  335. if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
  336. continue;
  337. errs += do_file(filename, buf, h);
  338. }
  339. for (i = 0; i < OSSL_NELEM(hash_table); i++) {
  340. for (bp = hash_table[i]; bp; bp = nextbp) {
  341. nextbp = bp->next;
  342. nextid = 0;
  343. memset(idmask, 0, (bp->num_needed + 7) / 8);
  344. for (ep = bp->first_entry; ep; ep = ep->next)
  345. if (ep->old_id < bp->num_needed)
  346. bit_set(idmask, ep->old_id);
  347. for (ep = bp->first_entry; ep; ep = nextep) {
  348. nextep = ep->next;
  349. if (ep->old_id < bp->num_needed) {
  350. /* Link exists, and is used as-is */
  351. BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash,
  352. suffixes[bp->type], ep->old_id);
  353. if (verbose)
  354. BIO_printf(bio_out, "link %s -> %s\n",
  355. ep->filename, buf);
  356. } else if (ep->need_symlink) {
  357. /* New link needed (it may replace something) */
  358. while (bit_isset(idmask, nextid))
  359. nextid++;
  360. BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
  361. dirname, pathsep, &n, bp->hash,
  362. suffixes[bp->type], nextid);
  363. if (verbose)
  364. BIO_printf(bio_out, "link %s -> %s\n",
  365. ep->filename, &buf[n]);
  366. if (unlink(buf) < 0 && errno != ENOENT) {
  367. BIO_printf(bio_err,
  368. "%s: Can't unlink %s, %s\n",
  369. opt_getprog(), buf, strerror(errno));
  370. errs++;
  371. }
  372. if (symlink(ep->filename, buf) < 0) {
  373. BIO_printf(bio_err,
  374. "%s: Can't symlink %s, %s\n",
  375. opt_getprog(), ep->filename,
  376. strerror(errno));
  377. errs++;
  378. }
  379. bit_set(idmask, nextid);
  380. } else if (remove_links) {
  381. /* Link to be deleted */
  382. BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
  383. dirname, pathsep, &n, bp->hash,
  384. suffixes[bp->type], ep->old_id);
  385. if (verbose)
  386. BIO_printf(bio_out, "unlink %s\n",
  387. &buf[n]);
  388. if (unlink(buf) < 0 && errno != ENOENT) {
  389. BIO_printf(bio_err,
  390. "%s: Can't unlink %s, %s\n",
  391. opt_getprog(), buf, strerror(errno));
  392. errs++;
  393. }
  394. }
  395. OPENSSL_free(ep->filename);
  396. OPENSSL_free(ep);
  397. }
  398. OPENSSL_free(bp);
  399. }
  400. hash_table[i] = NULL;
  401. }
  402. err:
  403. sk_OPENSSL_STRING_pop_free(files, str_free);
  404. OPENSSL_free(buf);
  405. return errs;
  406. }
  407. typedef enum OPTION_choice {
  408. OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
  409. OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE
  410. } OPTION_CHOICE;
  411. const OPTIONS rehash_options[] = {
  412. {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert-directory...]\n"},
  413. {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
  414. {"help", OPT_HELP, '-', "Display this summary"},
  415. {"h", OPT_HELP, '-', "Display this summary"},
  416. {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
  417. {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
  418. {"n", OPT_N, '-', "Do not remove existing links"},
  419. {"v", OPT_VERBOSE, '-', "Verbose output"},
  420. {NULL}
  421. };
  422. int rehash_main(int argc, char **argv)
  423. {
  424. const char *env, *prog;
  425. char *e, *m;
  426. int errs = 0;
  427. OPTION_CHOICE o;
  428. enum Hash h = HASH_NEW;
  429. prog = opt_init(argc, argv, rehash_options);
  430. while ((o = opt_next()) != OPT_EOF) {
  431. switch (o) {
  432. case OPT_EOF:
  433. case OPT_ERR:
  434. BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
  435. goto end;
  436. case OPT_HELP:
  437. opt_help(rehash_options);
  438. goto end;
  439. case OPT_COMPAT:
  440. h = HASH_BOTH;
  441. break;
  442. case OPT_OLD:
  443. h = HASH_OLD;
  444. break;
  445. case OPT_N:
  446. remove_links = 0;
  447. break;
  448. case OPT_VERBOSE:
  449. verbose = 1;
  450. break;
  451. }
  452. }
  453. argc = opt_num_rest();
  454. argv = opt_rest();
  455. evpmd = EVP_sha1();
  456. evpmdsize = EVP_MD_size(evpmd);
  457. if (*argv != NULL) {
  458. while (*argv != NULL)
  459. errs += do_dir(*argv++, h);
  460. } else if ((env = getenv(X509_get_default_cert_dir_env())) != NULL) {
  461. char lsc[2] = { LIST_SEPARATOR_CHAR, '\0' };
  462. m = OPENSSL_strdup(env);
  463. for (e = strtok(m, lsc); e != NULL; e = strtok(NULL, lsc))
  464. errs += do_dir(e, h);
  465. OPENSSL_free(m);
  466. } else {
  467. errs += do_dir(X509_get_default_cert_dir(), h);
  468. }
  469. end:
  470. return errs;
  471. }
  472. #else
  473. const OPTIONS rehash_options[] = {
  474. {NULL}
  475. };
  476. int rehash_main(int argc, char **argv)
  477. {
  478. BIO_printf(bio_err, "Not available; use c_rehash script\n");
  479. return 1;
  480. }
  481. #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */