Adjust the general fill-column in doc/dir-locals.example.el
[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 /*
128  * Process an entry; return number of errors.
129  */
130 static int add_entry(enum Type type, unsigned int hash, const char *filename,
131                       const unsigned char *digest, int need_symlink,
132                       unsigned short old_id)
133 {
134     static BUCKET nilbucket;
135     static HENTRY nilhentry;
136     BUCKET *bp;
137     HENTRY *ep, *found = NULL;
138     unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table);
139
140     for (bp = hash_table[ndx]; bp; bp = bp->next)
141         if (bp->type == type && bp->hash == hash)
142             break;
143     if (bp == NULL) {
144         bp = app_malloc(sizeof(*bp), "hash bucket");
145         *bp = nilbucket;
146         bp->next = hash_table[ndx];
147         bp->type = type;
148         bp->hash = hash;
149         hash_table[ndx] = bp;
150     }
151
152     for (ep = bp->first_entry; ep; ep = ep->next) {
153         if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) {
154             BIO_printf(bio_err,
155                        "%s: skipping duplicate certificate in %s\n",
156                        opt_getprog(), filename);
157             return 1;
158         }
159         if (strcmp(filename, ep->filename) == 0) {
160             found = ep;
161             if (digest == NULL)
162                 break;
163         }
164     }
165     ep = found;
166     if (ep == NULL) {
167         if (bp->num_needed >= MAX_COLLISIONS) {
168             BIO_printf(bio_err,
169                        "%s: hash table overflow for %s\n",
170                        opt_getprog(), filename);
171             return 1;
172         }
173         ep = app_malloc(sizeof(*ep), "collision bucket");
174         *ep = nilhentry;
175         ep->old_id = ~0;
176         ep->filename = BUF_strdup(filename);
177         if (bp->last_entry)
178             bp->last_entry->next = ep;
179         if (bp->first_entry == NULL)
180             bp->first_entry = ep;
181         bp->last_entry = ep;
182     }
183
184     if (old_id < ep->old_id)
185         ep->old_id = old_id;
186     if (need_symlink && !ep->need_symlink) {
187         ep->need_symlink = 1;
188         bp->num_needed++;
189         memcpy(ep->digest, digest, evpmdsize);
190     }
191     return 0;
192 }
193
194 /*
195  * Check if a symlink goes to the right spot; return 0 if okay.
196  * This can be -1 if bad filename, or an error count.
197  */
198 static int handle_symlink(const char *filename, const char *fullpath)
199 {
200     unsigned int hash = 0;
201     int i, type, id;
202     unsigned char ch;
203     char linktarget[NAME_MAX], *endptr;
204     ssize_t n;
205
206     for (i = 0; i < 8; i++) {
207         ch = filename[i];
208         if (!isxdigit(ch))
209             return -1;
210         hash <<= 4;
211         hash += app_hex(ch);
212     }
213     if (filename[i++] != '.')
214         return -1;
215     for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--)
216         if (strcasecmp(suffixes[type], &filename[i]) == 0)
217             break;
218     i += strlen(suffixes[type]);
219
220     id = strtoul(&filename[i], &endptr, 10);
221     if (*endptr != '\0')
222         return -1;
223
224     n = readlink(fullpath, linktarget, sizeof(linktarget));
225     if (n < 0 || n >= (int)sizeof(linktarget))
226         return -1;
227     linktarget[n] = 0;
228
229     return add_entry(type, hash, linktarget, NULL, 0, id);
230 }
231
232 /*
233  * process a file, return number of errors.
234  */
235 static int do_file(const char *filename, const char *fullpath, enum Hash h)
236 {
237     STACK_OF (X509_INFO) *inf = NULL;
238     X509_INFO *x;
239     X509_NAME *name = NULL;
240     BIO *b;
241     const char *ext;
242     unsigned char digest[EVP_MAX_MD_SIZE];
243     int i, type, errs = 0;
244
245     /* Does it end with a recognized extension? */
246     if ((ext = strrchr(filename, '.')) == NULL)
247         goto end;
248     for (i = 0; i < (int)OSSL_NELEM(extensions); i++) {
249         if (strcasecmp(extensions[i], ext + 1) == 0)
250             break;
251     }
252     if (i >= (int)OSSL_NELEM(extensions))
253         goto end;
254
255     /* Does it have X.509 data in it? */
256     if ((b = BIO_new_file(fullpath, "r")) == NULL) {
257         BIO_printf(bio_err, "%s: skipping %s, cannot open file\n",
258                    opt_getprog(), filename);
259         errs++;
260         goto end;
261     }
262     inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
263     BIO_free(b);
264     if (inf == NULL)
265         goto end;
266
267     if (sk_X509_INFO_num(inf) != 1) {
268         BIO_printf(bio_err,
269                    "%s: skipping %s,"
270                    "it does not contain exactly one certificate or CRL\n",
271                    opt_getprog(), filename);
272         /* This is not an error. */
273         goto end;
274     }
275     x = sk_X509_INFO_value(inf, 0);
276     if (x->x509) {
277         type = TYPE_CERT;
278         name = X509_get_subject_name(x->x509);
279         X509_digest(x->x509, evpmd, digest, NULL);
280     } else if (x->crl) {
281         type = TYPE_CRL;
282         name = X509_CRL_get_issuer(x->crl);
283         X509_CRL_digest(x->crl, evpmd, digest, NULL);
284     }
285     if (name) {
286         if ((h == HASH_NEW) || (h == HASH_BOTH))
287             errs += add_entry(type, X509_NAME_hash(name), filename, digest, 1, ~0);
288         if ((h == HASH_OLD) || (h == HASH_BOTH))
289             errs += add_entry(type, X509_NAME_hash_old(name), filename, digest, 1, ~0);
290     }
291
292 end:
293     sk_X509_INFO_pop_free(inf, X509_INFO_free);
294     return errs;
295 }
296
297 /*
298  * Process a directory; return number of errors found.
299  */
300 static int do_dir(const char *dirname, enum Hash h)
301 {
302     BUCKET *bp, *nextbp;
303     HENTRY *ep, *nextep;
304     OPENSSL_DIR_CTX *d = NULL;
305     struct stat st;
306     unsigned char idmask[MAX_COLLISIONS / 8];
307     int i, n, nextid, buflen, errs = 0;
308     const char *pathsep;
309     const char *filename;
310     char *buf;
311
312     buflen = strlen(dirname);
313     pathsep = (buflen && dirname[buflen - 1] == '/') ? "" : "/";
314     buflen += NAME_MAX + 2;
315     buf = app_malloc(buflen, "filename buffer");
316
317     if (verbose)
318         BIO_printf(bio_out, "Doing %s\n", dirname);
319
320     while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
321         if (snprintf(buf, buflen, "%s%s%s",
322                     dirname, pathsep, filename) >= buflen)
323             continue;
324         if (lstat(buf, &st) < 0)
325             continue;
326         if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
327             continue;
328         errs += do_file(filename, buf, h);
329     }
330     OPENSSL_DIR_end(&d);
331
332     for (i = 0; i < (int)OSSL_NELEM(hash_table); i++) {
333         for (bp = hash_table[i]; bp; bp = nextbp) {
334             nextbp = bp->next;
335             nextid = 0;
336             memset(idmask, 0, (bp->num_needed + 7) / 8);
337             for (ep = bp->first_entry; ep; ep = ep->next)
338                 if (ep->old_id < bp->num_needed)
339                     bit_set(idmask, ep->old_id);
340
341             for (ep = bp->first_entry; ep; ep = nextep) {
342                 nextep = ep->next;
343                 if (ep->old_id < bp->num_needed) {
344                     /* Link exists, and is used as-is */
345                     snprintf(buf, buflen, "%08x.%s%d", bp->hash,
346                              suffixes[bp->type], ep->old_id);
347                     if (verbose)
348                         BIO_printf(bio_out, "link %s -> %s\n",
349                                    ep->filename, buf);
350                 } else if (ep->need_symlink) {
351                     /* New link needed (it may replace something) */
352                     while (bit_isset(idmask, nextid))
353                         nextid++;
354
355                     snprintf(buf, buflen, "%s%s%n%08x.%s%d",
356                              dirname, pathsep, &n, bp->hash,
357                              suffixes[bp->type], nextid);
358                     if (verbose)
359                         BIO_printf(bio_out, "link %s -> %s\n",
360                                    ep->filename, &buf[n]);
361                     if (unlink(buf) < 0 && errno != ENOENT) {
362                         BIO_printf(bio_err,
363                                    "%s: Can't unlink %s, %s\n",
364                                    opt_getprog(), buf, strerror(errno));
365                         errs++;
366                     }
367                     if (symlink(ep->filename, buf) < 0) {
368                         BIO_printf(bio_err,
369                                    "%s: Can't symlink %s, %s\n",
370                                    opt_getprog(), ep->filename,
371                                    strerror(errno));
372                         errs++;
373                     }
374                 } else if (remove_links) {
375                     /* Link to be deleted */
376                     snprintf(buf, buflen, "%s%s%n%08x.%s%d",
377                              dirname, pathsep, &n, bp->hash,
378                              suffixes[bp->type], ep->old_id);
379                     if (verbose)
380                         BIO_printf(bio_out, "unlink %s\n",
381                                    &buf[n]);
382                     if (unlink(buf) < 0 && errno != ENOENT) {
383                         BIO_printf(bio_err,
384                                    "%s: Can't unlink %s, %s\n",
385                                    opt_getprog(), buf, strerror(errno));
386                         errs++;
387                     }
388                 }
389                 OPENSSL_free(ep->filename);
390                 OPENSSL_free(ep);
391             }
392             OPENSSL_free(bp);
393         }
394         hash_table[i] = NULL;
395     }
396
397     OPENSSL_free(buf);
398     return errs;
399 }
400
401 typedef enum OPTION_choice {
402     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
403     OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE
404 } OPTION_CHOICE;
405
406 OPTIONS rehash_options[] = {
407     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert-directory...]\n"},
408     {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
409     {"help", OPT_HELP, '-', "Display this summary"},
410     {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
411     {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
412     {"n", OPT_N, '-', "Do not remove existing links"},
413     {"v", OPT_VERBOSE, '-', "Verbose output"},
414     {NULL}
415 };
416
417
418 int rehash_main(int argc, char **argv)
419 {
420     const char *env, *prog;
421     char *e, *m;
422     int errs = 0;
423     OPTION_CHOICE o;
424     enum Hash h = HASH_NEW;
425
426     prog = opt_init(argc, argv, rehash_options);
427     while ((o = opt_next()) != OPT_EOF) {
428         switch (o) {
429         case OPT_EOF:
430         case OPT_ERR:
431             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
432             goto end;
433         case OPT_HELP:
434             opt_help(rehash_options);
435             goto end;
436         case OPT_COMPAT:
437             h = HASH_BOTH;
438             break;
439         case OPT_OLD:
440             h = HASH_OLD;
441             break;
442         case OPT_N:
443             remove_links = 0;
444             break;
445         case OPT_VERBOSE:
446             verbose = 1;
447             break;
448         }
449     }
450     argc = opt_num_rest();
451     argv = opt_rest();
452
453     evpmd = EVP_sha1();
454     evpmdsize = EVP_MD_size(evpmd);
455
456     if (*argv) {
457         while (*argv)
458             errs += do_dir(*argv++, h);
459     } else if ((env = getenv("SSL_CERT_DIR")) != NULL) {
460         m = BUF_strdup(env);
461         for (e = strtok(m, ":"); e != NULL; e = strtok(NULL, ":"))
462             errs += do_dir(e, h);
463         OPENSSL_free(m);
464     } else {
465         errs += do_dir("/etc/ssl/certs", h);
466     }
467
468  end:
469     return errs;
470 }
471
472 #else
473 OPTIONS rehash_options[] = {
474     {NULL}
475 };
476
477 int rehash_main(int argc, char **argv)
478 {
479     BIO_printf(bio_err, "Not available; use c_rehash script\n");
480     return (1);
481 }
482
483 #endif