rehash.c 15 KB

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