Add support for loading root CAs from Windows crypto API
[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         ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
119         return 0;
120     }
121
122     if ((a->buffer = BUF_MEM_new()) == NULL) {
123         ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
124         goto err;
125     }
126     a->dirs = NULL;
127     a->lock = CRYPTO_THREAD_lock_new();
128     if (a->lock == NULL) {
129         BUF_MEM_free(a->buffer);
130         ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
131         goto err;
132     }
133     lu->method_data = a;
134     return 1;
135
136  err:
137     OPENSSL_free(a);
138     return 0;
139 }
140
141 static void by_dir_hash_free(BY_DIR_HASH *hash)
142 {
143     OPENSSL_free(hash);
144 }
145
146 static int by_dir_hash_cmp(const BY_DIR_HASH *const *a,
147                            const BY_DIR_HASH *const *b)
148 {
149     if ((*a)->hash > (*b)->hash)
150         return 1;
151     if ((*a)->hash < (*b)->hash)
152         return -1;
153     return 0;
154 }
155
156 static void by_dir_entry_free(BY_DIR_ENTRY *ent)
157 {
158     OPENSSL_free(ent->dir);
159     sk_BY_DIR_HASH_pop_free(ent->hashes, by_dir_hash_free);
160     OPENSSL_free(ent);
161 }
162
163 static void free_dir(X509_LOOKUP *lu)
164 {
165     BY_DIR *a = (BY_DIR *)lu->method_data;
166
167     sk_BY_DIR_ENTRY_pop_free(a->dirs, by_dir_entry_free);
168     BUF_MEM_free(a->buffer);
169     CRYPTO_THREAD_lock_free(a->lock);
170     OPENSSL_free(a);
171 }
172
173 static int add_cert_dir(BY_DIR *ctx, const char *dir, int type)
174 {
175     int j;
176     size_t len;
177     const char *s, *ss, *p;
178
179     if (dir == NULL || *dir == '\0') {
180         ERR_raise(ERR_LIB_X509, X509_R_INVALID_DIRECTORY);
181         return 0;
182     }
183
184     s = dir;
185     p = s;
186     do {
187         if ((*p == LIST_SEPARATOR_CHAR) || (*p == '\0')) {
188             BY_DIR_ENTRY *ent;
189
190             ss = s;
191             s = p + 1;
192             len = p - ss;
193             if (len == 0)
194                 continue;
195             for (j = 0; j < sk_BY_DIR_ENTRY_num(ctx->dirs); j++) {
196                 ent = sk_BY_DIR_ENTRY_value(ctx->dirs, j);
197                 if (strlen(ent->dir) == len && strncmp(ent->dir, ss, len) == 0)
198                     break;
199             }
200             if (j < sk_BY_DIR_ENTRY_num(ctx->dirs))
201                 continue;
202             if (ctx->dirs == NULL) {
203                 ctx->dirs = sk_BY_DIR_ENTRY_new_null();
204                 if (!ctx->dirs) {
205                     ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
206                     return 0;
207                 }
208             }
209             ent = OPENSSL_malloc(sizeof(*ent));
210             if (ent == NULL) {
211                 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
212                 return 0;
213             }
214             ent->dir_type = type;
215             ent->hashes = sk_BY_DIR_HASH_new(by_dir_hash_cmp);
216             ent->dir = OPENSSL_strndup(ss, len);
217             if (ent->dir == NULL || ent->hashes == NULL) {
218                 by_dir_entry_free(ent);
219                 return 0;
220             }
221             if (!sk_BY_DIR_ENTRY_push(ctx->dirs, ent)) {
222                 by_dir_entry_free(ent);
223                 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
224                 return 0;
225             }
226         }
227     } while (*p++ != '\0');
228     return 1;
229 }
230
231 static int get_cert_by_subject_ex(X509_LOOKUP *xl, X509_LOOKUP_TYPE type,
232                                   const X509_NAME *name, X509_OBJECT *ret,
233                                   OSSL_LIB_CTX *libctx, const char *propq)
234 {
235     BY_DIR *ctx;
236     union {
237         X509 st_x509;
238         X509_CRL crl;
239     } data;
240     int ok = 0;
241     int i, j, k;
242     unsigned long h;
243     BUF_MEM *b = NULL;
244     X509_OBJECT stmp, *tmp;
245     const char *postfix = "";
246
247     if (name == NULL)
248         return 0;
249
250     stmp.type = type;
251     if (type == X509_LU_X509) {
252         data.st_x509.cert_info.subject = (X509_NAME *)name; /* won't modify it */
253         stmp.data.x509 = &data.st_x509;
254     } else if (type == X509_LU_CRL) {
255         data.crl.crl.issuer = (X509_NAME *)name; /* won't modify it */
256         stmp.data.crl = &data.crl;
257         postfix = "r";
258     } else {
259         ERR_raise(ERR_LIB_X509, X509_R_WRONG_LOOKUP_TYPE);
260         goto finish;
261     }
262
263     if ((b = BUF_MEM_new()) == NULL) {
264         ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
265         goto finish;
266     }
267
268     ctx = (BY_DIR *)xl->method_data;
269     h = X509_NAME_hash_ex(name, libctx, propq, &i);
270     if (i == 0)
271         goto finish;
272     for (i = 0; i < sk_BY_DIR_ENTRY_num(ctx->dirs); i++) {
273         BY_DIR_ENTRY *ent;
274         int idx;
275         BY_DIR_HASH htmp, *hent;
276
277         ent = sk_BY_DIR_ENTRY_value(ctx->dirs, i);
278         j = strlen(ent->dir) + 1 + 8 + 6 + 1 + 1;
279         if (!BUF_MEM_grow(b, j)) {
280             ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
281             goto finish;
282         }
283         if (type == X509_LU_CRL && ent->hashes) {
284             htmp.hash = h;
285             if (!CRYPTO_THREAD_read_lock(ctx->lock))
286                 goto finish;
287             idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp);
288             if (idx >= 0) {
289                 hent = sk_BY_DIR_HASH_value(ent->hashes, idx);
290                 k = hent->suffix;
291             } else {
292                 hent = NULL;
293                 k = 0;
294             }
295             CRYPTO_THREAD_unlock(ctx->lock);
296         } else {
297             k = 0;
298             hent = NULL;
299         }
300         for (;;) {
301             char c = '/';
302
303 #ifdef OPENSSL_SYS_VMS
304             c = ent->dir[strlen(ent->dir) - 1];
305             if (c != ':' && c != '>' && c != ']') {
306                 /*
307                  * If no separator is present, we assume the directory
308                  * specifier is a logical name, and add a colon.  We really
309                  * should use better VMS routines for merging things like
310                  * this, but this will do for now... -- Richard Levitte
311                  */
312                 c = ':';
313             } else {
314                 c = '\0';
315             }
316
317             if (c == '\0') {
318                 /*
319                  * This is special.  When c == '\0', no directory separator
320                  * should be added.
321                  */
322                 BIO_snprintf(b->data, b->max,
323                              "%s%08lx.%s%d", ent->dir, h, postfix, k);
324             } else
325 #endif
326             {
327                 BIO_snprintf(b->data, b->max,
328                              "%s%c%08lx.%s%d", ent->dir, c, h, postfix, k);
329             }
330 #ifndef OPENSSL_NO_POSIX_IO
331 # ifdef _WIN32
332 #  define stat _stat
333 # endif
334             {
335                 struct stat st;
336                 if (stat(b->data, &st) < 0)
337                     break;
338             }
339 #endif
340             /* found one. */
341             if (type == X509_LU_X509) {
342                 if ((X509_load_cert_file_ex(xl, b->data, ent->dir_type, libctx,
343                                             propq)) == 0)
344                     break;
345             } else if (type == X509_LU_CRL) {
346                 if ((X509_load_crl_file(xl, b->data, ent->dir_type)) == 0)
347                     break;
348             }
349             /* else case will caught higher up */
350             k++;
351         }
352
353         /*
354          * we have added it to the cache so now pull it out again
355          */
356         X509_STORE_lock(xl->store_ctx);
357         j = sk_X509_OBJECT_find(xl->store_ctx->objs, &stmp);
358         tmp = sk_X509_OBJECT_value(xl->store_ctx->objs, j);
359         X509_STORE_unlock(xl->store_ctx);
360
361         /* If a CRL, update the last file suffix added for this */
362
363         if (type == X509_LU_CRL) {
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                     ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
380                     ok = 0;
381                     goto finish;
382                 }
383                 hent->hash = h;
384                 hent->suffix = k;
385                 if (!sk_BY_DIR_HASH_push(ent->hashes, hent)) {
386                     CRYPTO_THREAD_unlock(ctx->lock);
387                     OPENSSL_free(hent);
388                     ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
389                     ok = 0;
390                     goto finish;
391                 }
392             } else if (hent->suffix < k) {
393                 hent->suffix = k;
394             }
395
396             CRYPTO_THREAD_unlock(ctx->lock);
397
398         }
399
400         if (tmp != NULL) {
401             ok = 1;
402             ret->type = tmp->type;
403             memcpy(&ret->data, &tmp->data, sizeof(ret->data));
404
405             /*
406              * Clear any errors that might have been raised processing empty
407              * or malformed files.
408              */
409             ERR_clear_error();
410
411             goto finish;
412         }
413     }
414  finish:
415     BUF_MEM_free(b);
416     return ok;
417 }
418
419 static int get_cert_by_subject(X509_LOOKUP *xl, X509_LOOKUP_TYPE type,
420                                const X509_NAME *name, X509_OBJECT *ret)
421 {
422     return get_cert_by_subject_ex(xl, type, name, ret, NULL, NULL);
423 }