rehash.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /*
  2. * C implementation based on the original Perl and shell versions
  3. *
  4. * Copyright (c) 2013-2014 Timo Teräs <timo.teras@iki.fi>
  5. */
  6. /* ====================================================================
  7. * Copyright (c) 2015 The OpenSSL Project. All rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. *
  13. * 1. Redistributions of source code must retain the above copyright
  14. * notice, this list of conditions and the following disclaimer.
  15. *
  16. * 2. Redistributions in binary form must reproduce the above copyright
  17. * notice, this list of conditions and the following disclaimer in
  18. * the documentation and/or other materials provided with the
  19. * distribution.
  20. *
  21. * 3. All advertising materials mentioning features or use of this
  22. * software must display the following acknowledgment:
  23. * "This product includes software developed by the OpenSSL Project
  24. * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  25. *
  26. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  27. * endorse or promote products derived from this software without
  28. * prior written permission. For written permission, please contact
  29. * licensing@OpenSSL.org.
  30. *
  31. * 5. Products derived from this software may not be called "OpenSSL"
  32. * nor may "OpenSSL" appear in their names without prior written
  33. * permission of the OpenSSL Project.
  34. *
  35. * 6. Redistributions of any form whatsoever must retain the following
  36. * acknowledgment:
  37. * "This product includes software developed by the OpenSSL Project
  38. * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  41. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  43. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  44. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  45. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  46. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  47. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  48. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  49. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  50. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  51. * OF THE POSSIBILITY OF SUCH DAMAGE.
  52. * ====================================================================
  53. *
  54. * This product includes cryptographic software written by Eric Young
  55. * (eay@cryptsoft.com). This product includes software written by Tim
  56. * Hudson (tjh@cryptsoft.com).
  57. *
  58. */
  59. #include "apps.h"
  60. #if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__)
  61. # include <unistd.h>
  62. # include <stdio.h>
  63. # include <limits.h>
  64. # include <errno.h>
  65. # include <string.h>
  66. # include <ctype.h>
  67. # include <sys/stat.h>
  68. # include "internal/o_dir.h"
  69. # include <openssl/evp.h>
  70. # include <openssl/pem.h>
  71. # include <openssl/x509.h>
  72. # ifndef NAME_MAX
  73. # define NAME_MAX 255
  74. # endif
  75. # define MAX_COLLISIONS 256
  76. typedef struct hentry_st {
  77. struct hentry_st *next;
  78. char *filename;
  79. unsigned short old_id;
  80. unsigned char need_symlink;
  81. unsigned char digest[EVP_MAX_MD_SIZE];
  82. } HENTRY;
  83. typedef struct bucket_st {
  84. struct bucket_st *next;
  85. HENTRY *first_entry, *last_entry;
  86. unsigned int hash;
  87. unsigned short type;
  88. unsigned short num_needed;
  89. } BUCKET;
  90. enum Type {
  91. /* Keep in sync with |suffixes|, below. */
  92. TYPE_CERT=0, TYPE_CRL=1
  93. };
  94. enum Hash {
  95. HASH_OLD, HASH_NEW, HASH_BOTH
  96. };
  97. static int evpmdsize;
  98. static const EVP_MD *evpmd;
  99. static int remove_links = 1;
  100. static int verbose = 0;
  101. static BUCKET *hash_table[257];
  102. static const char *suffixes[] = { "", "r" };
  103. static const char *extensions[] = { "pem", "crt", "cer", "crl" };
  104. static void bit_set(unsigned char *set, unsigned int bit)
  105. {
  106. set[bit >> 3] |= 1 << (bit & 0x7);
  107. }
  108. static int bit_isset(unsigned char *set, unsigned int bit)
  109. {
  110. return set[bit >> 3] & (1 << (bit & 0x7));
  111. }
  112. /*
  113. * Process an entry; return number of errors.
  114. */
  115. static int add_entry(enum Type type, unsigned int hash, const char *filename,
  116. const unsigned char *digest, int need_symlink,
  117. unsigned short old_id)
  118. {
  119. static BUCKET nilbucket;
  120. static HENTRY nilhentry;
  121. BUCKET *bp;
  122. HENTRY *ep, *found = NULL;
  123. unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table);
  124. for (bp = hash_table[ndx]; bp; bp = bp->next)
  125. if (bp->type == type && bp->hash == hash)
  126. break;
  127. if (bp == NULL) {
  128. bp = app_malloc(sizeof(*bp), "hash bucket");
  129. *bp = nilbucket;
  130. bp->next = hash_table[ndx];
  131. bp->type = type;
  132. bp->hash = hash;
  133. hash_table[ndx] = bp;
  134. }
  135. for (ep = bp->first_entry; ep; ep = ep->next) {
  136. if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) {
  137. BIO_printf(bio_err,
  138. "%s: skipping duplicate certificate in %s\n",
  139. opt_getprog(), filename);
  140. return 1;
  141. }
  142. if (strcmp(filename, ep->filename) == 0) {
  143. found = ep;
  144. if (digest == NULL)
  145. break;
  146. }
  147. }
  148. ep = found;
  149. if (ep == NULL) {
  150. if (bp->num_needed >= MAX_COLLISIONS) {
  151. BIO_printf(bio_err,
  152. "%s: hash table overflow for %s\n",
  153. opt_getprog(), filename);
  154. return 1;
  155. }
  156. ep = app_malloc(sizeof(*ep), "collision bucket");
  157. *ep = nilhentry;
  158. ep->old_id = ~0;
  159. ep->filename = OPENSSL_strdup(filename);
  160. if (bp->last_entry)
  161. bp->last_entry->next = ep;
  162. if (bp->first_entry == NULL)
  163. bp->first_entry = ep;
  164. bp->last_entry = ep;
  165. }
  166. if (old_id < ep->old_id)
  167. ep->old_id = old_id;
  168. if (need_symlink && !ep->need_symlink) {
  169. ep->need_symlink = 1;
  170. bp->num_needed++;
  171. memcpy(ep->digest, digest, evpmdsize);
  172. }
  173. return 0;
  174. }
  175. /*
  176. * Check if a symlink goes to the right spot; return 0 if okay.
  177. * This can be -1 if bad filename, or an error count.
  178. */
  179. static int handle_symlink(const char *filename, const char *fullpath)
  180. {
  181. unsigned int hash = 0;
  182. int i, type, id;
  183. unsigned char ch;
  184. char linktarget[PATH_MAX], *endptr;
  185. ssize_t n;
  186. for (i = 0; i < 8; i++) {
  187. ch = filename[i];
  188. if (!isxdigit(ch))
  189. return -1;
  190. hash <<= 4;
  191. hash += app_hex(ch);
  192. }
  193. if (filename[i++] != '.')
  194. return -1;
  195. for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--)
  196. if (strcasecmp(suffixes[type], &filename[i]) == 0)
  197. break;
  198. i += strlen(suffixes[type]);
  199. id = strtoul(&filename[i], &endptr, 10);
  200. if (*endptr != '\0')
  201. return -1;
  202. n = readlink(fullpath, linktarget, sizeof(linktarget));
  203. if (n < 0 || n >= (int)sizeof(linktarget))
  204. return -1;
  205. linktarget[n] = 0;
  206. return add_entry(type, hash, linktarget, NULL, 0, id);
  207. }
  208. /*
  209. * process a file, return number of errors.
  210. */
  211. static int do_file(const char *filename, const char *fullpath, enum Hash h)
  212. {
  213. STACK_OF (X509_INFO) *inf = NULL;
  214. X509_INFO *x;
  215. X509_NAME *name = NULL;
  216. BIO *b;
  217. const char *ext;
  218. unsigned char digest[EVP_MAX_MD_SIZE];
  219. int type, errs = 0;
  220. size_t i;
  221. /* Does it end with a recognized extension? */
  222. if ((ext = strrchr(filename, '.')) == NULL)
  223. goto end;
  224. for (i = 0; i < OSSL_NELEM(extensions); i++) {
  225. if (strcasecmp(extensions[i], ext + 1) == 0)
  226. break;
  227. }
  228. if (i >= OSSL_NELEM(extensions))
  229. goto end;
  230. /* Does it have X.509 data in it? */
  231. if ((b = BIO_new_file(fullpath, "r")) == NULL) {
  232. BIO_printf(bio_err, "%s: skipping %s, cannot open file\n",
  233. opt_getprog(), filename);
  234. errs++;
  235. goto end;
  236. }
  237. inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
  238. BIO_free(b);
  239. if (inf == NULL)
  240. goto end;
  241. if (sk_X509_INFO_num(inf) != 1) {
  242. BIO_printf(bio_err,
  243. "%s: skipping %s,"
  244. "it does not contain exactly one certificate or CRL\n",
  245. opt_getprog(), filename);
  246. /* This is not an error. */
  247. goto end;
  248. }
  249. x = sk_X509_INFO_value(inf, 0);
  250. if (x->x509) {
  251. type = TYPE_CERT;
  252. name = X509_get_subject_name(x->x509);
  253. X509_digest(x->x509, evpmd, digest, NULL);
  254. } else if (x->crl) {
  255. type = TYPE_CRL;
  256. name = X509_CRL_get_issuer(x->crl);
  257. X509_CRL_digest(x->crl, evpmd, digest, NULL);
  258. } else {
  259. ++errs;
  260. goto end;
  261. }
  262. if (name) {
  263. if ((h == HASH_NEW) || (h == HASH_BOTH))
  264. errs += add_entry(type, X509_NAME_hash(name), filename, digest, 1, ~0);
  265. if ((h == HASH_OLD) || (h == HASH_BOTH))
  266. errs += add_entry(type, X509_NAME_hash_old(name), filename, digest, 1, ~0);
  267. }
  268. end:
  269. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  270. return errs;
  271. }
  272. /*
  273. * Process a directory; return number of errors found.
  274. */
  275. static int do_dir(const char *dirname, enum Hash h)
  276. {
  277. BUCKET *bp, *nextbp;
  278. HENTRY *ep, *nextep;
  279. OPENSSL_DIR_CTX *d = NULL;
  280. struct stat st;
  281. unsigned char idmask[MAX_COLLISIONS / 8];
  282. int n, nextid, buflen, errs = 0;
  283. size_t i;
  284. const char *pathsep;
  285. const char *filename;
  286. char *buf;
  287. if (app_access(dirname, W_OK) < 0) {
  288. BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
  289. return 1;
  290. }
  291. buflen = strlen(dirname);
  292. pathsep = (buflen && dirname[buflen - 1] == '/') ? "" : "/";
  293. buflen += NAME_MAX + 1 + 1;
  294. buf = app_malloc(buflen, "filename buffer");
  295. if (verbose)
  296. BIO_printf(bio_out, "Doing %s\n", dirname);
  297. while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
  298. if (snprintf(buf, buflen, "%s%s%s",
  299. dirname, pathsep, filename) >= buflen)
  300. continue;
  301. if (lstat(buf, &st) < 0)
  302. continue;
  303. if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
  304. continue;
  305. errs += do_file(filename, buf, h);
  306. }
  307. OPENSSL_DIR_end(&d);
  308. for (i = 0; i < OSSL_NELEM(hash_table); i++) {
  309. for (bp = hash_table[i]; bp; bp = nextbp) {
  310. nextbp = bp->next;
  311. nextid = 0;
  312. memset(idmask, 0, (bp->num_needed + 7) / 8);
  313. for (ep = bp->first_entry; ep; ep = ep->next)
  314. if (ep->old_id < bp->num_needed)
  315. bit_set(idmask, ep->old_id);
  316. for (ep = bp->first_entry; ep; ep = nextep) {
  317. nextep = ep->next;
  318. if (ep->old_id < bp->num_needed) {
  319. /* Link exists, and is used as-is */
  320. snprintf(buf, buflen, "%08x.%s%d", bp->hash,
  321. suffixes[bp->type], ep->old_id);
  322. if (verbose)
  323. BIO_printf(bio_out, "link %s -> %s\n",
  324. ep->filename, buf);
  325. } else if (ep->need_symlink) {
  326. /* New link needed (it may replace something) */
  327. while (bit_isset(idmask, nextid))
  328. nextid++;
  329. snprintf(buf, buflen, "%s%s%n%08x.%s%d",
  330. dirname, pathsep, &n, bp->hash,
  331. suffixes[bp->type], nextid);
  332. if (verbose)
  333. BIO_printf(bio_out, "link %s -> %s\n",
  334. ep->filename, &buf[n]);
  335. if (unlink(buf) < 0 && errno != ENOENT) {
  336. BIO_printf(bio_err,
  337. "%s: Can't unlink %s, %s\n",
  338. opt_getprog(), buf, strerror(errno));
  339. errs++;
  340. }
  341. if (symlink(ep->filename, buf) < 0) {
  342. BIO_printf(bio_err,
  343. "%s: Can't symlink %s, %s\n",
  344. opt_getprog(), ep->filename,
  345. strerror(errno));
  346. errs++;
  347. }
  348. } else if (remove_links) {
  349. /* Link to be deleted */
  350. snprintf(buf, buflen, "%s%s%n%08x.%s%d",
  351. dirname, pathsep, &n, bp->hash,
  352. suffixes[bp->type], ep->old_id);
  353. if (verbose)
  354. BIO_printf(bio_out, "unlink %s\n",
  355. &buf[n]);
  356. if (unlink(buf) < 0 && errno != ENOENT) {
  357. BIO_printf(bio_err,
  358. "%s: Can't unlink %s, %s\n",
  359. opt_getprog(), buf, strerror(errno));
  360. errs++;
  361. }
  362. }
  363. OPENSSL_free(ep->filename);
  364. OPENSSL_free(ep);
  365. }
  366. OPENSSL_free(bp);
  367. }
  368. hash_table[i] = NULL;
  369. }
  370. OPENSSL_free(buf);
  371. return errs;
  372. }
  373. typedef enum OPTION_choice {
  374. OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
  375. OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE
  376. } OPTION_CHOICE;
  377. OPTIONS rehash_options[] = {
  378. {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert-directory...]\n"},
  379. {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
  380. {"help", OPT_HELP, '-', "Display this summary"},
  381. {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
  382. {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
  383. {"n", OPT_N, '-', "Do not remove existing links"},
  384. {"v", OPT_VERBOSE, '-', "Verbose output"},
  385. {NULL}
  386. };
  387. int rehash_main(int argc, char **argv)
  388. {
  389. const char *env, *prog;
  390. char *e, *m;
  391. int errs = 0;
  392. OPTION_CHOICE o;
  393. enum Hash h = HASH_NEW;
  394. prog = opt_init(argc, argv, rehash_options);
  395. while ((o = opt_next()) != OPT_EOF) {
  396. switch (o) {
  397. case OPT_EOF:
  398. case OPT_ERR:
  399. BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
  400. goto end;
  401. case OPT_HELP:
  402. opt_help(rehash_options);
  403. goto end;
  404. case OPT_COMPAT:
  405. h = HASH_BOTH;
  406. break;
  407. case OPT_OLD:
  408. h = HASH_OLD;
  409. break;
  410. case OPT_N:
  411. remove_links = 0;
  412. break;
  413. case OPT_VERBOSE:
  414. verbose = 1;
  415. break;
  416. }
  417. }
  418. argc = opt_num_rest();
  419. argv = opt_rest();
  420. evpmd = EVP_sha1();
  421. evpmdsize = EVP_MD_size(evpmd);
  422. if (*argv) {
  423. while (*argv)
  424. errs += do_dir(*argv++, h);
  425. } else if ((env = getenv("SSL_CERT_DIR")) != NULL) {
  426. m = OPENSSL_strdup(env);
  427. for (e = strtok(m, ":"); e != NULL; e = strtok(NULL, ":"))
  428. errs += do_dir(e, h);
  429. OPENSSL_free(m);
  430. } else {
  431. errs += do_dir("/etc/ssl/certs", h);
  432. }
  433. end:
  434. return errs;
  435. }
  436. #else
  437. OPTIONS rehash_options[] = {
  438. {NULL}
  439. };
  440. int rehash_main(int argc, char **argv)
  441. {
  442. BIO_printf(bio_err, "Not available; use c_rehash script\n");
  443. return (1);
  444. }
  445. #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */