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