2 * Copyright 2015-2023 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2013-2014 Timo Teräs <timo.teras@gmail.com>
5 * Licensed under the Apache License 2.0 (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
14 #if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) || \
15 (defined(__VMS) && defined(__DECC) && __CRTL_VER >= 80300000)
22 # include <sys/stat.h>
25 * Make sure that the processing of symbol names is treated the same as when
26 * libcrypto is built. This is done automatically for public headers (see
27 * include/openssl/__DECC_INCLUDE_PROLOGUE.H and __DECC_INCLUDE_EPILOGUE.H),
28 * but not for internal headers.
32 # pragma names as_is,shortened
35 # include "internal/o_dir.h"
38 # pragma names restore
41 # include <openssl/evp.h>
42 # include <openssl/pem.h>
43 # include <openssl/x509.h>
46 # define PATH_MAX 4096
48 # define MAX_COLLISIONS 256
50 # if defined(OPENSSL_SYS_VXWORKS)
52 * VxWorks has no symbolic links
55 # define lstat(path, buf) stat(path, buf)
57 int symlink(const char *target
, const char *linkpath
)
63 ssize_t
readlink(const char *pathname
, char *buf
, size_t bufsiz
)
70 typedef struct hentry_st
{
71 struct hentry_st
*next
;
73 unsigned short old_id
;
74 unsigned char need_symlink
;
75 unsigned char digest
[EVP_MAX_MD_SIZE
];
78 typedef struct bucket_st
{
79 struct bucket_st
*next
;
80 HENTRY
*first_entry
, *last_entry
;
83 unsigned short num_needed
;
87 /* Keep in sync with |suffixes|, below. */
88 TYPE_CERT
=0, TYPE_CRL
=1
92 HASH_OLD
, HASH_NEW
, HASH_BOTH
97 static const EVP_MD
*evpmd
;
98 static int remove_links
= 1;
99 static int verbose
= 0;
100 static BUCKET
*hash_table
[257];
102 static const char *suffixes
[] = { "", "r" };
103 static const char *extensions
[] = { "pem", "crt", "cer", "crl" };
106 static void bit_set(unsigned char *set
, unsigned int bit
)
108 set
[bit
>> 3] |= 1 << (bit
& 0x7);
111 static int bit_isset(unsigned char *set
, unsigned int bit
)
113 return set
[bit
>> 3] & (1 << (bit
& 0x7));
118 * Process an entry; return number of errors.
120 static int add_entry(enum Type type
, unsigned int hash
, const char *filename
,
121 const unsigned char *digest
, int need_symlink
,
122 unsigned short old_id
)
124 static BUCKET nilbucket
;
125 static HENTRY nilhentry
;
127 HENTRY
*ep
, *found
= NULL
;
128 unsigned int ndx
= (type
+ hash
) % OSSL_NELEM(hash_table
);
130 for (bp
= hash_table
[ndx
]; bp
; bp
= bp
->next
)
131 if (bp
->type
== type
&& bp
->hash
== hash
)
134 bp
= app_malloc(sizeof(*bp
), "hash bucket");
136 bp
->next
= hash_table
[ndx
];
139 hash_table
[ndx
] = bp
;
142 for (ep
= bp
->first_entry
; ep
; ep
= ep
->next
) {
143 if (digest
&& memcmp(digest
, ep
->digest
, evpmdsize
) == 0) {
145 "%s: warning: skipping duplicate %s in %s\n",
147 type
== TYPE_CERT
? "certificate" : "CRL", filename
);
150 if (strcmp(filename
, ep
->filename
) == 0) {
158 if (bp
->num_needed
>= MAX_COLLISIONS
) {
160 "%s: error: hash table overflow for %s\n",
161 opt_getprog(), filename
);
164 ep
= app_malloc(sizeof(*ep
), "collision bucket");
167 ep
->filename
= OPENSSL_strdup(filename
);
168 if (ep
->filename
== NULL
) {
171 BIO_printf(bio_err
, "out of memory\n");
175 bp
->last_entry
->next
= ep
;
176 if (bp
->first_entry
== NULL
)
177 bp
->first_entry
= ep
;
181 if (old_id
< ep
->old_id
)
183 if (need_symlink
&& !ep
->need_symlink
) {
184 ep
->need_symlink
= 1;
186 memcpy(ep
->digest
, digest
, evpmdsize
);
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.
195 static int handle_symlink(const char *filename
, const char *fullpath
)
197 unsigned int hash
= 0;
200 char linktarget
[PATH_MAX
], *endptr
;
203 for (i
= 0; i
< 8; i
++) {
208 hash
+= OPENSSL_hexchar2int(ch
);
210 if (filename
[i
++] != '.')
212 for (type
= OSSL_NELEM(suffixes
) - 1; type
> 0; type
--) {
213 const char *suffix
= suffixes
[type
];
214 if (OPENSSL_strncasecmp(suffix
, &filename
[i
], strlen(suffix
)) == 0)
217 i
+= strlen(suffixes
[type
]);
219 id
= strtoul(&filename
[i
], &endptr
, 10);
223 n
= readlink(fullpath
, linktarget
, sizeof(linktarget
));
224 if (n
< 0 || n
>= (int)sizeof(linktarget
))
228 return add_entry(type
, hash
, linktarget
, NULL
, 0, id
);
232 * process a file, return number of errors.
234 static int do_file(const char *filename
, const char *fullpath
, enum Hash h
)
236 STACK_OF (X509_INFO
) *inf
= NULL
;
238 const X509_NAME
*name
= NULL
;
241 unsigned char digest
[EVP_MAX_MD_SIZE
];
245 /* Does it end with a recognized extension? */
246 if ((ext
= strrchr(filename
, '.')) == NULL
)
248 for (i
= 0; i
< OSSL_NELEM(extensions
); i
++) {
249 if (OPENSSL_strcasecmp(extensions
[i
], ext
+ 1) == 0)
252 if (i
>= OSSL_NELEM(extensions
))
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
);
262 inf
= PEM_X509_INFO_read_bio(b
, NULL
, NULL
, NULL
);
267 if (sk_X509_INFO_num(inf
) != 1) {
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. */
275 x
= sk_X509_INFO_value(inf
, 0);
276 if (x
->x509
!= NULL
) {
278 name
= X509_get_subject_name(x
->x509
);
279 if (!X509_digest(x
->x509
, evpmd
, digest
, NULL
)) {
280 BIO_printf(bio_err
, "out of memory\n");
284 } else if (x
->crl
!= NULL
) {
286 name
= X509_CRL_get_issuer(x
->crl
);
287 if (!X509_CRL_digest(x
->crl
, evpmd
, digest
, NULL
)) {
288 BIO_printf(bio_err
, "out of memory\n");
297 if (h
== HASH_NEW
|| h
== HASH_BOTH
) {
299 unsigned long hash_value
=
300 X509_NAME_hash_ex(name
,
301 app_get0_libctx(), app_get0_propq(), &ok
);
304 errs
+= add_entry(type
, hash_value
, filename
, digest
, 1, ~0);
306 BIO_printf(bio_err
, "%s: error calculating SHA1 hash value\n",
311 if ((h
== HASH_OLD
) || (h
== HASH_BOTH
))
312 errs
+= add_entry(type
, X509_NAME_hash_old(name
),
313 filename
, digest
, 1, ~0);
317 sk_X509_INFO_pop_free(inf
, X509_INFO_free
);
321 static void str_free(char *s
)
326 static int ends_with_dirsep(const char *path
)
329 path
+= strlen(path
) - 1;
331 if (*path
== ']' || *path
== '>' || *path
== ':')
333 # elif defined _WIN32
340 static int sk_strcmp(const char * const *a
, const char * const *b
)
342 return strcmp(*a
, *b
);
346 * Process a directory; return number of errors found.
348 static int do_dir(const char *dirname
, enum Hash h
)
352 OPENSSL_DIR_CTX
*d
= NULL
;
354 unsigned char idmask
[MAX_COLLISIONS
/ 8];
355 int n
, numfiles
, nextid
, dirlen
, buflen
, errs
= 0;
356 size_t i
, fname_max_len
= 20; /* maximum length of "%08x.r%d" */
357 const char *pathsep
= "";
358 const char *filename
;
359 char *buf
= NULL
, *copy
= NULL
;
360 STACK_OF(OPENSSL_STRING
) *files
= NULL
;
362 if (app_access(dirname
, W_OK
) < 0) {
363 BIO_printf(bio_err
, "Skipping %s, can't write\n", dirname
);
366 dirlen
= strlen(dirname
);
367 if (dirlen
!= 0 && !ends_with_dirsep(dirname
)) {
373 BIO_printf(bio_out
, "Doing %s\n", dirname
);
375 if ((files
= sk_OPENSSL_STRING_new(sk_strcmp
)) == NULL
) {
376 BIO_printf(bio_err
, "Skipping %s, out of memory\n", dirname
);
380 while ((filename
= OPENSSL_DIR_read(&d
, dirname
)) != NULL
) {
381 size_t fname_len
= strlen(filename
);
383 if ((copy
= OPENSSL_strdup(filename
)) == NULL
384 || sk_OPENSSL_STRING_push(files
, copy
) == 0) {
387 BIO_puts(bio_err
, "out of memory\n");
391 if (fname_len
> fname_max_len
)
392 fname_max_len
= fname_len
;
395 sk_OPENSSL_STRING_sort(files
);
397 buflen
= dirlen
+ fname_max_len
+ 1;
398 buf
= app_malloc(buflen
, "filename buffer");
400 numfiles
= sk_OPENSSL_STRING_num(files
);
401 for (n
= 0; n
< numfiles
; ++n
) {
402 filename
= sk_OPENSSL_STRING_value(files
, n
);
403 if (BIO_snprintf(buf
, buflen
, "%s%s%s",
404 dirname
, pathsep
, filename
) >= buflen
)
406 if (lstat(buf
, &st
) < 0)
408 if (S_ISLNK(st
.st_mode
) && handle_symlink(filename
, buf
) == 0)
410 errs
+= do_file(filename
, buf
, h
);
413 for (i
= 0; i
< OSSL_NELEM(hash_table
); i
++) {
414 for (bp
= hash_table
[i
]; bp
; bp
= nextbp
) {
417 memset(idmask
, 0, (bp
->num_needed
+ 7) / 8);
418 for (ep
= bp
->first_entry
; ep
; ep
= ep
->next
)
419 if (ep
->old_id
< bp
->num_needed
)
420 bit_set(idmask
, ep
->old_id
);
422 for (ep
= bp
->first_entry
; ep
; ep
= nextep
) {
424 if (ep
->old_id
< bp
->num_needed
) {
425 /* Link exists, and is used as-is */
426 BIO_snprintf(buf
, buflen
, "%08x.%s%d", bp
->hash
,
427 suffixes
[bp
->type
], ep
->old_id
);
429 BIO_printf(bio_out
, "link %s -> %s\n",
431 } else if (ep
->need_symlink
) {
432 /* New link needed (it may replace something) */
433 while (bit_isset(idmask
, nextid
))
436 BIO_snprintf(buf
, buflen
, "%s%s%08x.%s%d",
437 dirname
, pathsep
, bp
->hash
,
438 suffixes
[bp
->type
], nextid
);
440 BIO_printf(bio_out
, "link %s -> %s\n",
441 ep
->filename
, &buf
[dirlen
]);
442 if (unlink(buf
) < 0 && errno
!= ENOENT
) {
444 "%s: Can't unlink %s, %s\n",
445 opt_getprog(), buf
, strerror(errno
));
448 if (symlink(ep
->filename
, buf
) < 0) {
450 "%s: Can't symlink %s, %s\n",
451 opt_getprog(), ep
->filename
,
455 bit_set(idmask
, nextid
);
456 } else if (remove_links
) {
457 /* Link to be deleted */
458 BIO_snprintf(buf
, buflen
, "%s%s%08x.%s%d",
459 dirname
, pathsep
, bp
->hash
,
460 suffixes
[bp
->type
], ep
->old_id
);
462 BIO_printf(bio_out
, "unlink %s\n",
464 if (unlink(buf
) < 0 && errno
!= ENOENT
) {
466 "%s: Can't unlink %s, %s\n",
467 opt_getprog(), buf
, strerror(errno
));
471 OPENSSL_free(ep
->filename
);
476 hash_table
[i
] = NULL
;
480 sk_OPENSSL_STRING_pop_free(files
, str_free
);
485 typedef enum OPTION_choice
{
487 OPT_COMPAT
, OPT_OLD
, OPT_N
, OPT_VERBOSE
,
491 const OPTIONS rehash_options
[] = {
492 {OPT_HELP_STR
, 1, '-', "Usage: %s [options] [directory...]\n"},
494 OPT_SECTION("General"),
495 {"help", OPT_HELP
, '-', "Display this summary"},
496 {"h", OPT_HELP
, '-', "Display this summary"},
497 {"compat", OPT_COMPAT
, '-', "Create both new- and old-style hash links"},
498 {"old", OPT_OLD
, '-', "Use old-style hash to generate links"},
499 {"n", OPT_N
, '-', "Do not remove existing links"},
501 OPT_SECTION("Output"),
502 {"v", OPT_VERBOSE
, '-', "Verbose output"},
507 {"directory", 0, 0, "One or more directories to process (optional)"},
512 int rehash_main(int argc
, char **argv
)
514 const char *env
, *prog
;
518 enum Hash h
= HASH_NEW
;
520 prog
= opt_init(argc
, argv
, rehash_options
);
521 while ((o
= opt_next()) != OPT_EOF
) {
525 BIO_printf(bio_err
, "%s: Use -help for summary.\n", prog
);
528 opt_help(rehash_options
);
543 if (!opt_provider(o
))
549 /* Optional arguments are directories to scan. */
550 argc
= opt_num_rest();
554 evpmdsize
= EVP_MD_get_size(evpmd
);
557 while (*argv
!= NULL
)
558 errs
+= do_dir(*argv
++, h
);
559 } else if ((env
= getenv(X509_get_default_cert_dir_env())) != NULL
) {
560 char lsc
[2] = { LIST_SEPARATOR_CHAR
, '\0' };
561 m
= OPENSSL_strdup(env
);
562 for (e
= strtok(m
, lsc
); e
!= NULL
; e
= strtok(NULL
, lsc
))
563 errs
+= do_dir(e
, h
);
566 errs
+= do_dir(X509_get_default_cert_dir(), h
);
574 const OPTIONS rehash_options
[] = {
578 int rehash_main(int argc
, char **argv
)
580 BIO_printf(bio_err
, "Not available; use c_rehash script\n");
584 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */