xref: /openbsd/lib/libcrypto/x509/by_dir.c (revision 787e4c65)
1 /* $OpenBSD: by_dir.c,v 1.48 2024/08/31 10:19:17 tb Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 
59 #include <errno.h>
60 #include <stdio.h>
61 #include <string.h>
62 #include <time.h>
63 #include <unistd.h>
64 
65 #include <openssl/opensslconf.h>
66 
67 #include <openssl/err.h>
68 #include <openssl/x509.h>
69 
70 #include "x509_local.h"
71 
72 typedef struct lookup_dir_hashes_st {
73 	unsigned long hash;
74 	int suffix;
75 } BY_DIR_HASH;
76 
77 typedef struct lookup_dir_entry_st {
78 	char *dir;
79 	int dir_type;
80 	STACK_OF(BY_DIR_HASH) *hashes;
81 } BY_DIR_ENTRY;
82 
83 typedef struct lookup_dir_st {
84 	BUF_MEM *buffer;
85 	STACK_OF(BY_DIR_ENTRY) *dirs;
86 } BY_DIR;
87 
88 DECLARE_STACK_OF(BY_DIR_HASH)
89 DECLARE_STACK_OF(BY_DIR_ENTRY)
90 
91 static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl,
92     char **ret);
93 static int new_dir(X509_LOOKUP *lu);
94 static void free_dir(X509_LOOKUP *lu);
95 static int add_cert_dir(BY_DIR *ctx, const char *dir, int type);
96 static int get_cert_by_subject(X509_LOOKUP *xl, int type, X509_NAME *name,
97     X509_OBJECT *ret);
98 
99 static const X509_LOOKUP_METHOD x509_dir_lookup = {
100 	.name = "Load certs from files in a directory",
101 	.new_item = new_dir,
102 	.free = free_dir,
103 	.ctrl = dir_ctrl,
104 	.get_by_subject = get_cert_by_subject,
105 };
106 
107 const X509_LOOKUP_METHOD *
X509_LOOKUP_hash_dir(void)108 X509_LOOKUP_hash_dir(void)
109 {
110 	return &x509_dir_lookup;
111 }
112 LCRYPTO_ALIAS(X509_LOOKUP_hash_dir);
113 
114 static int
dir_ctrl(X509_LOOKUP * ctx,int cmd,const char * argp,long argl,char ** retp)115 dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl,
116     char **retp)
117 {
118 	BY_DIR *ld = ctx->method_data;
119 	int ret = 0;
120 
121 	switch (cmd) {
122 	case X509_L_ADD_DIR:
123 		if (argl == X509_FILETYPE_DEFAULT) {
124 			ret = add_cert_dir(ld, X509_get_default_cert_dir(),
125 			    X509_FILETYPE_PEM);
126 			if (!ret) {
127 				X509error(X509_R_LOADING_CERT_DIR);
128 			}
129 		} else
130 			ret = add_cert_dir(ld, argp, (int)argl);
131 		break;
132 	}
133 	return ret;
134 }
135 
136 static int
new_dir(X509_LOOKUP * lu)137 new_dir(X509_LOOKUP *lu)
138 {
139 	BY_DIR *a;
140 
141 	if ((a = malloc(sizeof(*a))) == NULL) {
142 		X509error(ERR_R_MALLOC_FAILURE);
143 		return 0;
144 	}
145 	if ((a->buffer = BUF_MEM_new()) == NULL) {
146 		X509error(ERR_R_MALLOC_FAILURE);
147 		free(a);
148 		return 0;
149 	}
150 	a->dirs = NULL;
151 	lu->method_data = a;
152 	return 1;
153 }
154 
155 static void
by_dir_hash_free(BY_DIR_HASH * hash)156 by_dir_hash_free(BY_DIR_HASH *hash)
157 {
158 	free(hash);
159 }
160 
161 static int
by_dir_hash_cmp(const BY_DIR_HASH * const * a,const BY_DIR_HASH * const * b)162 by_dir_hash_cmp(const BY_DIR_HASH * const *a,
163     const BY_DIR_HASH * const *b)
164 {
165 	if ((*a)->hash > (*b)->hash)
166 		return 1;
167 	if ((*a)->hash < (*b)->hash)
168 		return -1;
169 	return 0;
170 }
171 
172 static void
by_dir_entry_free(BY_DIR_ENTRY * ent)173 by_dir_entry_free(BY_DIR_ENTRY *ent)
174 {
175 	free(ent->dir);
176 	sk_BY_DIR_HASH_pop_free(ent->hashes, by_dir_hash_free);
177 	free(ent);
178 }
179 
180 static void
free_dir(X509_LOOKUP * lu)181 free_dir(X509_LOOKUP *lu)
182 {
183 	BY_DIR *a;
184 
185 	a = lu->method_data;
186 	sk_BY_DIR_ENTRY_pop_free(a->dirs, by_dir_entry_free);
187 	BUF_MEM_free(a->buffer);
188 	free(a);
189 }
190 
191 static int
add_cert_dir(BY_DIR * ctx,const char * dir,int type)192 add_cert_dir(BY_DIR *ctx, const char *dir, int type)
193 {
194 	int j;
195 	const char *s, *ss, *p;
196 	ptrdiff_t len;
197 
198 	if (dir == NULL || !*dir) {
199 		X509error(X509_R_INVALID_DIRECTORY);
200 		return 0;
201 	}
202 
203 	s = dir;
204 	p = s;
205 	do {
206 		if ((*p == ':') || (*p == '\0')) {
207 			BY_DIR_ENTRY *ent;
208 
209 			ss = s;
210 			s = p + 1;
211 			len = p - ss;
212 			if (len == 0)
213 				continue;
214 			for (j = 0; j < sk_BY_DIR_ENTRY_num(ctx->dirs); j++) {
215 				ent = sk_BY_DIR_ENTRY_value(ctx->dirs, j);
216 				if (strlen(ent->dir) == (size_t)len &&
217 				    strncmp(ent->dir, ss, (size_t)len) == 0)
218 					break;
219 			}
220 			if (j < sk_BY_DIR_ENTRY_num(ctx->dirs))
221 				continue;
222 			if (ctx->dirs == NULL) {
223 				ctx->dirs = sk_BY_DIR_ENTRY_new_null();
224 				if (ctx->dirs == NULL) {
225 					X509error(ERR_R_MALLOC_FAILURE);
226 					return 0;
227 				}
228 			}
229 			ent = malloc(sizeof(*ent));
230 			if (ent == NULL) {
231 				X509error(ERR_R_MALLOC_FAILURE);
232 				return 0;
233 			}
234 			ent->dir_type = type;
235 			ent->hashes = sk_BY_DIR_HASH_new(by_dir_hash_cmp);
236 			ent->dir = strndup(ss, (size_t)len);
237 			if (ent->dir == NULL || ent->hashes == NULL) {
238 				X509error(ERR_R_MALLOC_FAILURE);
239 				by_dir_entry_free(ent);
240 				return 0;
241 			}
242 			if (!sk_BY_DIR_ENTRY_push(ctx->dirs, ent)) {
243 				X509error(ERR_R_MALLOC_FAILURE);
244 				by_dir_entry_free(ent);
245 				return 0;
246 			}
247 		}
248 	} while (*p++ != '\0');
249 	return 1;
250 }
251 
252 static int
get_cert_by_subject(X509_LOOKUP * xl,int type,X509_NAME * name,X509_OBJECT * ret)253 get_cert_by_subject(X509_LOOKUP *xl, int type, X509_NAME *name,
254     X509_OBJECT *ret)
255 {
256 	BY_DIR *ctx;
257 	union	{
258 		struct	{
259 			X509 st_x509;
260 			X509_CINF st_x509_cinf;
261 		} x509;
262 		struct	{
263 			X509_CRL st_crl;
264 			X509_CRL_INFO st_crl_info;
265 		} crl;
266 	} data;
267 	int ok = 0;
268 	int i, j, k;
269 	unsigned long h;
270 	BUF_MEM *b = NULL;
271 	X509_OBJECT stmp, *tmp;
272 	const char *postfix="";
273 
274 	if (name == NULL)
275 		return 0;
276 
277 	stmp.type = type;
278 	if (type == X509_LU_X509) {
279 		data.x509.st_x509.cert_info = &data.x509.st_x509_cinf;
280 		data.x509.st_x509_cinf.subject = name;
281 		stmp.data.x509 = &data.x509.st_x509;
282 		postfix="";
283 	} else if (type == X509_LU_CRL) {
284 		data.crl.st_crl.crl = &data.crl.st_crl_info;
285 		data.crl.st_crl_info.issuer = name;
286 		stmp.data.crl = &data.crl.st_crl;
287 		postfix="r";
288 	} else {
289 		X509error(X509_R_WRONG_LOOKUP_TYPE);
290 		goto finish;
291 	}
292 
293 	if ((b = BUF_MEM_new()) == NULL) {
294 		X509error(ERR_R_BUF_LIB);
295 		goto finish;
296 	}
297 
298 	ctx = xl->method_data;
299 
300 	h = X509_NAME_hash(name);
301 	for (i = 0; i < sk_BY_DIR_ENTRY_num(ctx->dirs); i++) {
302 		BY_DIR_ENTRY *ent;
303 		int idx;
304 		BY_DIR_HASH htmp, *hent;
305 
306 		ent = sk_BY_DIR_ENTRY_value(ctx->dirs, i);
307 		j = strlen(ent->dir) + 1 + 8 + 6 + 1 + 1;
308 		if (!BUF_MEM_grow(b, j)) {
309 			X509error(ERR_R_MALLOC_FAILURE);
310 			goto finish;
311 		}
312 		if (type == X509_LU_CRL) {
313 			htmp.hash = h;
314 			CRYPTO_r_lock(CRYPTO_LOCK_X509_STORE);
315 			idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp);
316 			if (idx >= 0) {
317 				hent = sk_BY_DIR_HASH_value(ent->hashes, idx);
318 				k = hent->suffix;
319 			} else {
320 				hent = NULL;
321 				k = 0;
322 			}
323 			CRYPTO_r_unlock(CRYPTO_LOCK_X509_STORE);
324 		} else {
325 			k = 0;
326 			hent = NULL;
327 		}
328 		for (;;) {
329 			(void) snprintf(b->data, b->max, "%s/%08lx.%s%d",
330 			    ent->dir, h, postfix, k);
331 			/*
332 			 * Found one. Attempt to load it. This could fail for
333 			 * any number of reasons from the file can't be opened,
334 			 * the file contains garbage, etc. Clear the error stack
335 			 * to avoid exposing the lower level error. These all
336 			 * boil down to "we could not find CA/CRL".
337 			 */
338 			if (type == X509_LU_X509) {
339 				if ((X509_load_cert_file(xl, b->data,
340 				    ent->dir_type)) == 0) {
341 					ERR_clear_error();
342 					break;
343 				}
344 			} else if (type == X509_LU_CRL) {
345 				if ((X509_load_crl_file(xl, b->data,
346 				    ent->dir_type)) == 0) {
347 					ERR_clear_error();
348 					break;
349 				}
350 			}
351 			/* The lack of a CA or CRL will be caught higher up. */
352 			k++;
353 		}
354 
355 		/* we have added it to the cache so now pull it out again */
356 		CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
357 		j = sk_X509_OBJECT_find(xl->store_ctx->objs, &stmp);
358 		tmp = sk_X509_OBJECT_value(xl->store_ctx->objs, j);
359 		CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
360 
361 		/* If a CRL, update the last file suffix added for this */
362 		if (type == X509_LU_CRL) {
363 			CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
364 			/*
365 			 * Look for entry again in case another thread added
366 			 * an entry first.
367 			 */
368 			if (hent == NULL) {
369 				htmp.hash = h;
370 				idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp);
371 				hent = sk_BY_DIR_HASH_value(ent->hashes, idx);
372 			}
373 			if (hent == NULL) {
374 				hent = malloc(sizeof(*hent));
375 				if (hent == NULL) {
376 					X509error(ERR_R_MALLOC_FAILURE);
377 					CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
378 					ok = 0;
379 					goto finish;
380 				}
381 				hent->hash = h;
382 				hent->suffix = k;
383 				if (!sk_BY_DIR_HASH_push(ent->hashes, hent)) {
384 					X509error(ERR_R_MALLOC_FAILURE);
385 					CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
386 					free(hent);
387 					ok = 0;
388 					goto finish;
389 				}
390 			} else if (hent->suffix < k)
391 				hent->suffix = k;
392 
393 			CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
394 
395 		}
396 
397 		if (tmp != NULL) {
398 			ok = 1;
399 			ret->type = tmp->type;
400 			memcpy(&ret->data, &tmp->data, sizeof(ret->data));
401 			goto finish;
402 		}
403 	}
404 finish:
405 	BUF_MEM_free(b);
406 	return ok;
407 }
408