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