rehash.c 15 KB

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