Fix corruption when searching for CRLs in hashed directories
[openssl.git] / crypto / x509 / by_dir.c
1 /*
2  * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 #if defined (__TANDEM) && defined (_SPT_MODEL_)
11   /*
12    * These definitions have to come first in SPT due to scoping of the
13    * declarations in c99 associated with SPT use of stat.
14    */
15 # include <sys/types.h>
16 # include <sys/stat.h>
17 #endif
18
19 #include "internal/e_os.h"
20 #include "internal/cryptlib.h"
21 #include <stdio.h>
22 #include <time.h>
23 #include <errno.h>
24 #include <sys/types.h>
25
26 #ifndef OPENSSL_NO_POSIX_IO
27 # include <sys/stat.h>
28 #endif
29
30 #include <openssl/x509.h>
31 #include "crypto/x509.h"
32 #include "x509_local.h"
33
34 struct lookup_dir_hashes_st {
35     unsigned long hash;
36     int suffix;
37 };
38
39 struct lookup_dir_entry_st {
40     char *dir;
41     int dir_type;
42     STACK_OF(BY_DIR_HASH) *hashes;
43 };
44
45 typedef struct lookup_dir_st {
46     BUF_MEM *buffer;
47     STACK_OF(BY_DIR_ENTRY) *dirs;
48     CRYPTO_RWLOCK *lock;
49 } BY_DIR;
50
51 static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl,
52                     char **retp);
53
54 static int new_dir(X509_LOOKUP *lu);
55 static void free_dir(X509_LOOKUP *lu);
56 static int add_cert_dir(BY_DIR *ctx, const char *dir, int type);
57 static int get_cert_by_subject(X509_LOOKUP *xl, X509_LOOKUP_TYPE type,
58                                const X509_NAME *name, X509_OBJECT *ret);
59 static int get_cert_by_subject_ex(X509_LOOKUP *xl, X509_LOOKUP_TYPE type,
60                                   const X509_NAME *name, X509_OBJECT *ret,
61                                   OSSL_LIB_CTX *libctx, const char *propq);
62 static X509_LOOKUP_METHOD x509_dir_lookup = {
63     "Load certs from files in a directory",
64     new_dir,                         /* new_item */
65     free_dir,                        /* free */
66     NULL,                            /* init */
67     NULL,                            /* shutdown */
68     dir_ctrl,                        /* ctrl */
69     get_cert_by_subject,             /* get_by_subject */
70     NULL,                            /* get_by_issuer_serial */
71     NULL,                            /* get_by_fingerprint */
72     NULL,                            /* get_by_alias */
73     get_cert_by_subject_ex,          /* get_by_subject_ex */
74     NULL,                            /* ctrl_ex */
75 };
76
77 X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir(void)
78 {
79     return &x509_dir_lookup;
80 }
81
82 static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl,
83                     char **retp)
84 {
85     int ret = 0;
86     BY_DIR *ld = (BY_DIR *)ctx->method_data;
87
88     switch (cmd) {
89     case X509_L_ADD_DIR:
90         if (argl == X509_FILETYPE_DEFAULT) {
91             /* If SSL_CERT_PATH is provided and non-empty, use that. */
92             const char *dir = ossl_safe_getenv(X509_get_default_cert_path_env());
93
94             /* Fallback to SSL_CERT_DIR. */
95             if (dir == NULL)
96                 dir = ossl_safe_getenv(X509_get_default_cert_dir_env());
97
98             /* Fallback to built-in default. */
99             if (dir == NULL)
100                 dir = X509_get_default_cert_dir();
101
102             ret = add_cert_dir(ld, dir, X509_FILETYPE_PEM);
103             if (!ret) {
104                 ERR_raise(ERR_LIB_X509, X509_R_LOADING_CERT_DIR);
105             }
106         } else
107             ret = add_cert_dir(ld, argp, (int)argl);
108         break;
109     }
110     return ret;
111 }
112
113 static int new_dir(X509_LOOKUP *lu)
114 {
115     BY_DIR *a = OPENSSL_malloc(sizeof(*a));
116
117     if (a == NULL)
118         return 0;
119
120     if ((a->buffer = BUF_MEM_new()) == NULL) {
121         ERR_raise(ERR_LIB_X509, ERR_R_BN_LIB);
122         goto err;
123     }
124     a->dirs = NULL;
125     a->lock = CRYPTO_THREAD_lock_new();
126     if (a->lock == NULL) {
127         BUF_MEM_free(a->buffer);
128         ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
129         goto err;
130     }
131     lu->method_data = a;
132     return 1;
133
134  err:
135     OPENSSL_free(a);
136     return 0;
137 }
138
139 static void by_dir_hash_free(BY_DIR_HASH *hash)
140 {
141     OPENSSL_free(hash);
142 }
143
144 static int by_dir_hash_cmp(const BY_DIR_HASH *const *a,
145                            const BY_DIR_HASH *const *b)
146 {
147     if ((*a)->hash > (*b)->hash)
148         return 1;
149     if ((*a)->hash < (*b)->hash)
150         return -1;
151     return 0;
152 }
153
154 static void by_dir_entry_free(BY_DIR_ENTRY *ent)
155 {
156     OPENSSL_free(ent->dir);
157     sk_BY_DIR_HASH_pop_free(ent->hashes, by_dir_hash_free);
158     OPENSSL_free(ent);
159 }
160
161 static void free_dir(X509_LOOKUP *lu)
162 {
163     BY_DIR *a = (BY_DIR *)lu->method_data;
164
165     sk_BY_DIR_ENTRY_pop_free(a->dirs, by_dir_entry_free);
166     BUF_MEM_free(a->buffer);
167     CRYPTO_THREAD_lock_free(a->lock);
168     OPENSSL_free(a);
169 }
170
171 static int add_cert_dir(BY_DIR *ctx, const char *dir, int type)
172 {
173     int j;
174     size_t len;
175     const char *s, *ss, *p;
176
177     if (dir == NULL || *dir == '\0') {
178         ERR_raise(ERR_LIB_X509, X509_R_INVALID_DIRECTORY);
179         return 0;
180     }
181
182     s = dir;
183     p = s;
184     do {
185         if ((*p == LIST_SEPARATOR_CHAR) || (*p == '\0')) {
186             BY_DIR_ENTRY *ent;
187
188             ss = s;
189             s = p + 1;
190             len = p - ss;
191             if (len == 0)
192                 continue;
193             for (j = 0; j < sk_BY_DIR_ENTRY_num(ctx->dirs); j++) {
194                 ent = sk_BY_DIR_ENTRY_value(ctx->dirs, j);
195                 if (strlen(ent->dir) == len && strncmp(ent->dir, ss, len) == 0)
196                     break;
197             }
198             if (j < sk_BY_DIR_ENTRY_num(ctx->dirs))
199                 continue;
200             if (ctx->dirs == NULL) {
201                 ctx->dirs = sk_BY_DIR_ENTRY_new_null();
202                 if (!ctx->dirs) {
203                     ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
204                     return 0;
205                 }
206             }
207             ent = OPENSSL_malloc(sizeof(*ent));
208             if (ent == NULL)
209                 return 0;
210             ent->dir_type = type;
211             ent->hashes = sk_BY_DIR_HASH_new(by_dir_hash_cmp);
212             ent->dir = OPENSSL_strndup(ss, len);
213             if (ent->dir == NULL || ent->hashes == NULL) {
214                 by_dir_entry_free(ent);
215                 return 0;
216             }
217             if (!sk_BY_DIR_ENTRY_push(ctx->dirs, ent)) {
218                 by_dir_entry_free(ent);
219                 ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
220                 return 0;
221             }
222         }
223     } while (*p++ != '\0');
224     return 1;
225 }
226
227 static int get_cert_by_subject_ex(X509_LOOKUP *xl, X509_LOOKUP_TYPE type,
228                                   const X509_NAME *name, X509_OBJECT *ret,
229                                   OSSL_LIB_CTX *libctx, const char *propq)
230 {
231     BY_DIR *ctx;
232     union {
233         X509 st_x509;
234         X509_CRL crl;
235     } data;
236     int ok = 0;
237     int i, j, k;
238     unsigned long h;
239     BUF_MEM *b = NULL;
240     X509_OBJECT stmp, *tmp;
241     const char *postfix = "";
242
243     if (name == NULL)
244         return 0;
245
246     stmp.type = type;
247     if (type == X509_LU_X509) {
248         data.st_x509.cert_info.subject = (X509_NAME *)name; /* won't modify it */
249         stmp.data.x509 = &data.st_x509;
250     } else if (type == X509_LU_CRL) {
251         data.crl.crl.issuer = (X509_NAME *)name; /* won't modify it */
252         stmp.data.crl = &data.crl;
253         postfix = "r";
254     } else {
255         ERR_raise(ERR_LIB_X509, X509_R_WRONG_LOOKUP_TYPE);
256         goto finish;
257     }
258
259     if ((b = BUF_MEM_new()) == NULL) {
260         ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
261         goto finish;
262     }
263
264     ctx = (BY_DIR *)xl->method_data;
265     h = X509_NAME_hash_ex(name, libctx, propq, &i);
266     if (i == 0)
267         goto finish;
268     for (i = 0; i < sk_BY_DIR_ENTRY_num(ctx->dirs); i++) {
269         BY_DIR_ENTRY *ent;
270         int idx;
271         BY_DIR_HASH htmp, *hent;
272
273         ent = sk_BY_DIR_ENTRY_value(ctx->dirs, i);
274         j = strlen(ent->dir) + 1 + 8 + 6 + 1 + 1;
275         if (!BUF_MEM_grow(b, j)) {
276             ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
277             goto finish;
278         }
279         if (type == X509_LU_CRL && ent->hashes) {
280             htmp.hash = h;
281             if (!CRYPTO_THREAD_read_lock(ctx->lock))
282                 goto finish;
283             idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp);
284             if (idx >= 0) {
285                 hent = sk_BY_DIR_HASH_value(ent->hashes, idx);
286                 k = hent->suffix;
287             } else {
288                 hent = NULL;
289                 k = 0;
290             }
291             CRYPTO_THREAD_unlock(ctx->lock);
292         } else {
293             k = 0;
294             hent = NULL;
295         }
296         for (;;) {
297             char c = '/';
298
299 #ifdef OPENSSL_SYS_VMS
300             c = ent->dir[strlen(ent->dir) - 1];
301             if (c != ':' && c != '>' && c != ']') {
302                 /*
303                  * If no separator is present, we assume the directory
304                  * specifier is a logical name, and add a colon.  We really
305                  * should use better VMS routines for merging things like
306                  * this, but this will do for now... -- Richard Levitte
307                  */
308                 c = ':';
309             } else {
310                 c = '\0';
311             }
312
313             if (c == '\0') {
314                 /*
315                  * This is special.  When c == '\0', no directory separator
316                  * should be added.
317                  */
318                 BIO_snprintf(b->data, b->max,
319                              "%s%08lx.%s%d", ent->dir, h, postfix, k);
320             } else
321 #endif
322             {
323                 BIO_snprintf(b->data, b->max,
324                              "%s%c%08lx.%s%d", ent->dir, c, h, postfix, k);
325             }
326 #ifndef OPENSSL_NO_POSIX_IO
327 # ifdef _WIN32
328 #  define stat _stat
329 # endif
330             {
331                 struct stat st;
332                 if (stat(b->data, &st) < 0)
333                     break;
334             }
335 #endif
336             /* found one. */
337             if (type == X509_LU_X509) {
338                 if ((X509_load_cert_file_ex(xl, b->data, ent->dir_type, libctx,
339                                             propq)) == 0)
340                     break;
341             } else if (type == X509_LU_CRL) {
342                 if ((X509_load_crl_file(xl, b->data, ent->dir_type)) == 0)
343                     break;
344             }
345             /* else case will caught higher up */
346             k++;
347         }
348
349         /*
350          * we have added it to the cache so now pull it out again
351          */
352         X509_STORE_lock(xl->store_ctx);
353         j = sk_X509_OBJECT_find(xl->store_ctx->objs, &stmp);
354         tmp = sk_X509_OBJECT_value(xl->store_ctx->objs, j);
355         X509_STORE_unlock(xl->store_ctx);
356
357         /*
358          * If a CRL, update the last file suffix added for this.
359          * We don't need to add an entry if k is 0 as this is the initial value.
360          * This avoids the need for a write lock and sort operation in the
361          * simple case where no CRL is present for a hash.
362          */
363         if (type == X509_LU_CRL && k > 0) {
364             if (!CRYPTO_THREAD_write_lock(ctx->lock))
365                 goto finish;
366             /*
367              * Look for entry again in case another thread added an entry
368              * first.
369              */
370             if (hent == NULL) {
371                 htmp.hash = h;
372                 idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp);
373                 hent = sk_BY_DIR_HASH_value(ent->hashes, idx);
374             }
375             if (hent == NULL) {
376                 hent = OPENSSL_malloc(sizeof(*hent));
377                 if (hent == NULL) {
378                     CRYPTO_THREAD_unlock(ctx->lock);
379                     ok = 0;
380                     goto finish;
381                 }
382                 hent->hash = h;
383                 hent->suffix = k;
384                 if (!sk_BY_DIR_HASH_push(ent->hashes, hent)) {
385                     CRYPTO_THREAD_unlock(ctx->lock);
386                     OPENSSL_free(hent);
387                     ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
388                     ok = 0;
389                     goto finish;
390                 }
391
392                 /*
393                  * Ensure stack is sorted so that subsequent sk_BY_DIR_HASH_find
394                  * will not mutate the stack and therefore require a write lock.
395                  */
396                 sk_BY_DIR_HASH_sort(ent->hashes);
397             } else if (hent->suffix < k) {
398                 hent->suffix = k;
399             }
400
401             CRYPTO_THREAD_unlock(ctx->lock);
402
403         }
404
405         if (tmp != NULL) {
406             ok = 1;
407             ret->type = tmp->type;
408             memcpy(&ret->data, &tmp->data, sizeof(ret->data));
409
410             /*
411              * Clear any errors that might have been raised processing empty
412              * or malformed files.
413              */
414             ERR_clear_error();
415
416             goto finish;
417         }
418     }
419  finish:
420     BUF_MEM_free(b);
421     return ok;
422 }
423
424 static int get_cert_by_subject(X509_LOOKUP *xl, X509_LOOKUP_TYPE type,
425                                const X509_NAME *name, X509_OBJECT *ret)
426 {
427     return get_cert_by_subject_ex(xl, type, name, ret, NULL, NULL);
428 }