source: rtems-libbsd/freebsd/crypto/openssl/apps/rehash.c @ 0a699e7

5-freebsd-126-freebsd-12
Last change on this file since 0a699e7 was 0a699e7, checked in by Christian Mauderer <christian.mauderer@…>, on 03/28/19 at 06:13:59

bin/openssl: Import from FreeBSD.

  • Property mode set to 100644
File size: 15.1 KB
Line 
1#include <machine/rtems-bsd-user-space.h>
2
3/*
4 * Copyright 2015-2019 The OpenSSL Project Authors. All Rights Reserved.
5 * Copyright (c) 2013-2014 Timo TerÀs <timo.teras@gmail.com>
6 *
7 * Licensed under the OpenSSL license (the "License").  You may not use
8 * this file except in compliance with the License.  You can obtain a copy
9 * in the file LICENSE in the source distribution or at
10 * https://www.openssl.org/source/license.html
11 */
12
13#include "apps.h"
14#include "progs.h"
15
16#if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) || \
17    (defined(__VMS) && defined(__DECC) && __CRTL_VER >= 80300000)
18# include <unistd.h>
19# include <stdio.h>
20# include <limits.h>
21# include <errno.h>
22# include <string.h>
23# include <ctype.h>
24# include <sys/stat.h>
25
26/*
27 * Make sure that the processing of symbol names is treated the same as when
28 * libcrypto is built.  This is done automatically for public headers (see
29 * include/openssl/__DECC_INCLUDE_PROLOGUE.H and __DECC_INCLUDE_EPILOGUE.H),
30 * but not for internal headers.
31 */
32# ifdef __VMS
33#  pragma names save
34#  pragma names as_is,shortened
35# endif
36
37# include "internal/o_dir.h"
38
39# ifdef __VMS
40#  pragma names restore
41# endif
42
43# include <openssl/evp.h>
44# include <openssl/pem.h>
45# include <openssl/x509.h>
46
47
48# ifndef PATH_MAX
49#  define PATH_MAX 4096
50# endif
51# ifndef NAME_MAX
52#  define NAME_MAX 255
53# endif
54# define MAX_COLLISIONS  256
55
56# if defined(OPENSSL_SYS_VXWORKS)
57/*
58 * VxWorks has no symbolic links
59 */
60
61#  define lstat(path, buf) stat(path, buf)
62
63int symlink(const char *target, const char *linkpath)
64{
65    errno = ENOSYS;
66    return -1;
67}
68
69ssize_t readlink(const char *pathname, char *buf, size_t bufsiz)
70{
71    errno = ENOSYS;
72    return -1;
73}
74# endif
75
76typedef 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
84typedef struct bucket_st {
85    struct bucket_st *next;
86    HENTRY *first_entry, *last_entry;
87    unsigned int hash;
88    unsigned short type;
89    unsigned short num_needed;
90} BUCKET;
91
92enum Type {
93    /* Keep in sync with |suffixes|, below. */
94    TYPE_CERT=0, TYPE_CRL=1
95};
96
97enum Hash {
98    HASH_OLD, HASH_NEW, HASH_BOTH
99};
100
101
102static int evpmdsize;
103static const EVP_MD *evpmd;
104static int remove_links = 1;
105static int verbose = 0;
106static BUCKET *hash_table[257];
107
108static const char *suffixes[] = { "", "r" };
109static const char *extensions[] = { "pem", "crt", "cer", "crl" };
110
111
112static void bit_set(unsigned char *set, unsigned int bit)
113{
114    set[bit >> 3] |= 1 << (bit & 0x7);
115}
116
117static int bit_isset(unsigned char *set, unsigned int bit)
118{
119    return set[bit >> 3] & (1 << (bit & 0x7));
120}
121
122
123/*
124 * Process an entry; return number of errors.
125 */
126static int add_entry(enum Type type, unsigned int hash, const char *filename,
127                      const unsigned char *digest, int need_symlink,
128                      unsigned short old_id)
129{
130    static BUCKET nilbucket;
131    static HENTRY nilhentry;
132    BUCKET *bp;
133    HENTRY *ep, *found = NULL;
134    unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table);
135
136    for (bp = hash_table[ndx]; bp; bp = bp->next)
137        if (bp->type == type && bp->hash == hash)
138            break;
139    if (bp == NULL) {
140        bp = app_malloc(sizeof(*bp), "hash bucket");
141        *bp = nilbucket;
142        bp->next = hash_table[ndx];
143        bp->type = type;
144        bp->hash = hash;
145        hash_table[ndx] = bp;
146    }
147
148    for (ep = bp->first_entry; ep; ep = ep->next) {
149        if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) {
150            BIO_printf(bio_err,
151                       "%s: warning: skipping duplicate %s in %s\n",
152                       opt_getprog(),
153                       type == TYPE_CERT ? "certificate" : "CRL", filename);
154            return 0;
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            BIO_printf(bio_err,
166                       "%s: error: hash table overflow for %s\n",
167                       opt_getprog(), filename);
168            return 1;
169        }
170        ep = app_malloc(sizeof(*ep), "collision bucket");
171        *ep = nilhentry;
172        ep->old_id = ~0;
173        ep->filename = OPENSSL_strdup(filename);
174        if (bp->last_entry)
175            bp->last_entry->next = ep;
176        if (bp->first_entry == NULL)
177            bp->first_entry = ep;
178        bp->last_entry = ep;
179    }
180
181    if (old_id < ep->old_id)
182        ep->old_id = old_id;
183    if (need_symlink && !ep->need_symlink) {
184        ep->need_symlink = 1;
185        bp->num_needed++;
186        memcpy(ep->digest, digest, evpmdsize);
187    }
188    return 0;
189}
190
191/*
192 * Check if a symlink goes to the right spot; return 0 if okay.
193 * This can be -1 if bad filename, or an error count.
194 */
195static int handle_symlink(const char *filename, const char *fullpath)
196{
197    unsigned int hash = 0;
198    int i, type, id;
199    unsigned char ch;
200    char linktarget[PATH_MAX], *endptr;
201    ossl_ssize_t n;
202
203    for (i = 0; i < 8; i++) {
204        ch = filename[i];
205        if (!isxdigit(ch))
206            return -1;
207        hash <<= 4;
208        hash += OPENSSL_hexchar2int(ch);
209    }
210    if (filename[i++] != '.')
211        return -1;
212    for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--) {
213        const char *suffix = suffixes[type];
214        if (strncasecmp(suffix, &filename[i], strlen(suffix)) == 0)
215            break;
216    }
217    i += strlen(suffixes[type]);
218
219    id = strtoul(&filename[i], &endptr, 10);
220    if (*endptr != '\0')
221        return -1;
222
223    n = readlink(fullpath, linktarget, sizeof(linktarget));
224    if (n < 0 || n >= (int)sizeof(linktarget))
225        return -1;
226    linktarget[n] = 0;
227
228    return add_entry(type, hash, linktarget, NULL, 0, id);
229}
230
231/*
232 * process a file, return number of errors.
233 */
234static int do_file(const char *filename, const char *fullpath, enum Hash h)
235{
236    STACK_OF (X509_INFO) *inf = NULL;
237    X509_INFO *x;
238    X509_NAME *name = NULL;
239    BIO *b;
240    const char *ext;
241    unsigned char digest[EVP_MAX_MD_SIZE];
242    int type, errs = 0;
243    size_t i;
244
245    /* Does it end with a recognized extension? */
246    if ((ext = strrchr(filename, '.')) == NULL)
247        goto end;
248    for (i = 0; i < OSSL_NELEM(extensions); i++) {
249        if (strcasecmp(extensions[i], ext + 1) == 0)
250            break;
251    }
252    if (i >= 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: error: 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: warning: 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 != NULL) {
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 != NULL) {
281        type = TYPE_CRL;
282        name = X509_CRL_get_issuer(x->crl);
283        X509_CRL_digest(x->crl, evpmd, digest, NULL);
284    } else {
285        ++errs;
286        goto end;
287    }
288    if (name != NULL) {
289        if ((h == HASH_NEW) || (h == HASH_BOTH))
290            errs += add_entry(type, X509_NAME_hash(name), filename, digest, 1, ~0);
291        if ((h == HASH_OLD) || (h == HASH_BOTH))
292            errs += add_entry(type, X509_NAME_hash_old(name), filename, digest, 1, ~0);
293    }
294
295end:
296    sk_X509_INFO_pop_free(inf, X509_INFO_free);
297    return errs;
298}
299
300static void str_free(char *s)
301{
302    OPENSSL_free(s);
303}
304
305static int ends_with_dirsep(const char *path)
306{
307    if (*path != '\0')
308        path += strlen(path) - 1;
309# if defined __VMS
310    if (*path == ']' || *path == '>' || *path == ':')
311        return 1;
312# elif defined _WIN32
313    if (*path == '\\')
314        return 1;
315# endif
316    return *path == '/';
317}
318
319/*
320 * Process a directory; return number of errors found.
321 */
322static int do_dir(const char *dirname, enum Hash h)
323{
324    BUCKET *bp, *nextbp;
325    HENTRY *ep, *nextep;
326    OPENSSL_DIR_CTX *d = NULL;
327    struct stat st;
328    unsigned char idmask[MAX_COLLISIONS / 8];
329    int n, numfiles, nextid, buflen, errs = 0;
330    size_t i;
331    const char *pathsep;
332    const char *filename;
333    char *buf, *copy = NULL;
334    STACK_OF(OPENSSL_STRING) *files = NULL;
335
336    if (app_access(dirname, W_OK) < 0) {
337        BIO_printf(bio_err, "Skipping %s, can't write\n", dirname);
338        return 1;
339    }
340    buflen = strlen(dirname);
341    pathsep = (buflen && !ends_with_dirsep(dirname)) ? "/": "";
342    buflen += NAME_MAX + 1 + 1;
343    buf = app_malloc(buflen, "filename buffer");
344
345    if (verbose)
346        BIO_printf(bio_out, "Doing %s\n", dirname);
347
348    if ((files = sk_OPENSSL_STRING_new_null()) == NULL) {
349        BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname);
350        errs = 1;
351        goto err;
352    }
353    while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) {
354        if ((copy = OPENSSL_strdup(filename)) == NULL
355                || sk_OPENSSL_STRING_push(files, copy) == 0) {
356            OPENSSL_free(copy);
357            BIO_puts(bio_err, "out of memory\n");
358            errs = 1;
359            goto err;
360        }
361    }
362    OPENSSL_DIR_end(&d);
363    sk_OPENSSL_STRING_sort(files);
364
365    numfiles = sk_OPENSSL_STRING_num(files);
366    for (n = 0; n < numfiles; ++n) {
367        filename = sk_OPENSSL_STRING_value(files, n);
368        if (BIO_snprintf(buf, buflen, "%s%s%s",
369                         dirname, pathsep, filename) >= buflen)
370            continue;
371        if (lstat(buf, &st) < 0)
372            continue;
373        if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0)
374            continue;
375        errs += do_file(filename, buf, h);
376    }
377
378    for (i = 0; i < OSSL_NELEM(hash_table); i++) {
379        for (bp = hash_table[i]; bp; bp = nextbp) {
380            nextbp = bp->next;
381            nextid = 0;
382            memset(idmask, 0, (bp->num_needed + 7) / 8);
383            for (ep = bp->first_entry; ep; ep = ep->next)
384                if (ep->old_id < bp->num_needed)
385                    bit_set(idmask, ep->old_id);
386
387            for (ep = bp->first_entry; ep; ep = nextep) {
388                nextep = ep->next;
389                if (ep->old_id < bp->num_needed) {
390                    /* Link exists, and is used as-is */
391                    BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash,
392                                 suffixes[bp->type], ep->old_id);
393                    if (verbose)
394                        BIO_printf(bio_out, "link %s -> %s\n",
395                                   ep->filename, buf);
396                } else if (ep->need_symlink) {
397                    /* New link needed (it may replace something) */
398                    while (bit_isset(idmask, nextid))
399                        nextid++;
400
401                    BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
402                                 dirname, pathsep, &n, bp->hash,
403                                 suffixes[bp->type], nextid);
404                    if (verbose)
405                        BIO_printf(bio_out, "link %s -> %s\n",
406                                   ep->filename, &buf[n]);
407                    if (unlink(buf) < 0 && errno != ENOENT) {
408                        BIO_printf(bio_err,
409                                   "%s: Can't unlink %s, %s\n",
410                                   opt_getprog(), buf, strerror(errno));
411                        errs++;
412                    }
413                    if (symlink(ep->filename, buf) < 0) {
414                        BIO_printf(bio_err,
415                                   "%s: Can't symlink %s, %s\n",
416                                   opt_getprog(), ep->filename,
417                                   strerror(errno));
418                        errs++;
419                    }
420                    bit_set(idmask, nextid);
421                } else if (remove_links) {
422                    /* Link to be deleted */
423                    BIO_snprintf(buf, buflen, "%s%s%n%08x.%s%d",
424                                 dirname, pathsep, &n, bp->hash,
425                                 suffixes[bp->type], ep->old_id);
426                    if (verbose)
427                        BIO_printf(bio_out, "unlink %s\n",
428                                   &buf[n]);
429                    if (unlink(buf) < 0 && errno != ENOENT) {
430                        BIO_printf(bio_err,
431                                   "%s: Can't unlink %s, %s\n",
432                                   opt_getprog(), buf, strerror(errno));
433                        errs++;
434                    }
435                }
436                OPENSSL_free(ep->filename);
437                OPENSSL_free(ep);
438            }
439            OPENSSL_free(bp);
440        }
441        hash_table[i] = NULL;
442    }
443
444 err:
445    sk_OPENSSL_STRING_pop_free(files, str_free);
446    OPENSSL_free(buf);
447    return errs;
448}
449
450typedef enum OPTION_choice {
451    OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
452    OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE
453} OPTION_CHOICE;
454
455const OPTIONS rehash_options[] = {
456    {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert-directory...]\n"},
457    {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
458    {"help", OPT_HELP, '-', "Display this summary"},
459    {"h", OPT_HELP, '-', "Display this summary"},
460    {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"},
461    {"old", OPT_OLD, '-', "Use old-style hash to generate links"},
462    {"n", OPT_N, '-', "Do not remove existing links"},
463    {"v", OPT_VERBOSE, '-', "Verbose output"},
464    {NULL}
465};
466
467
468int rehash_main(int argc, char **argv)
469{
470    const char *env, *prog;
471    char *e, *m;
472    int errs = 0;
473    OPTION_CHOICE o;
474    enum Hash h = HASH_NEW;
475
476    prog = opt_init(argc, argv, rehash_options);
477    while ((o = opt_next()) != OPT_EOF) {
478        switch (o) {
479        case OPT_EOF:
480        case OPT_ERR:
481            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
482            goto end;
483        case OPT_HELP:
484            opt_help(rehash_options);
485            goto end;
486        case OPT_COMPAT:
487            h = HASH_BOTH;
488            break;
489        case OPT_OLD:
490            h = HASH_OLD;
491            break;
492        case OPT_N:
493            remove_links = 0;
494            break;
495        case OPT_VERBOSE:
496            verbose = 1;
497            break;
498        }
499    }
500    argc = opt_num_rest();
501    argv = opt_rest();
502
503    evpmd = EVP_sha1();
504    evpmdsize = EVP_MD_size(evpmd);
505
506    if (*argv != NULL) {
507        while (*argv != NULL)
508            errs += do_dir(*argv++, h);
509    } else if ((env = getenv(X509_get_default_cert_dir_env())) != NULL) {
510        char lsc[2] = { LIST_SEPARATOR_CHAR, '\0' };
511        m = OPENSSL_strdup(env);
512        for (e = strtok(m, lsc); e != NULL; e = strtok(NULL, lsc))
513            errs += do_dir(e, h);
514        OPENSSL_free(m);
515    } else {
516        errs += do_dir(X509_get_default_cert_dir(), h);
517    }
518
519 end:
520    return errs;
521}
522
523#else
524const OPTIONS rehash_options[] = {
525    {NULL}
526};
527
528int rehash_main(int argc, char **argv)
529{
530    BIO_printf(bio_err, "Not available; use c_rehash script\n");
531    return 1;
532}
533
534#endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */
Note: See TracBrowser for help on using the repository browser.