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