rehash.c 15 KB

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