xref: /openbsd-src/lib/libcrypto/x509/by_dir.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /* $OpenBSD: by_dir.c,v 1.32 2014/07/11 08:44:49 jsing 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 <sys/types.h>
60 
61 #include <errno.h>
62 #include <stdio.h>
63 #include <string.h>
64 #include <time.h>
65 #include <unistd.h>
66 
67 #include <openssl/opensslconf.h>
68 
69 #include <openssl/err.h>
70 #include <openssl/lhash.h>
71 #include <openssl/x509.h>
72 
73 #ifndef OPENSSL_NO_POSIX_IO
74 # include <sys/stat.h>
75 #endif
76 
77 typedef struct lookup_dir_hashes_st {
78 	unsigned long hash;
79 	int suffix;
80 } BY_DIR_HASH;
81 
82 typedef struct lookup_dir_entry_st {
83 	char *dir;
84 	int dir_type;
85 	STACK_OF(BY_DIR_HASH) *hashes;
86 } BY_DIR_ENTRY;
87 
88 typedef struct lookup_dir_st {
89 	BUF_MEM *buffer;
90 	STACK_OF(BY_DIR_ENTRY) *dirs;
91 } BY_DIR;
92 
93 DECLARE_STACK_OF(BY_DIR_HASH)
94 DECLARE_STACK_OF(BY_DIR_ENTRY)
95 
96 static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl,
97     char **ret);
98 static int new_dir(X509_LOOKUP *lu);
99 static void free_dir(X509_LOOKUP *lu);
100 static int add_cert_dir(BY_DIR *ctx, const char *dir, int type);
101 static int get_cert_by_subject(X509_LOOKUP *xl, int type, X509_NAME *name,
102     X509_OBJECT *ret);
103 
104 X509_LOOKUP_METHOD x509_dir_lookup = {
105 	"Load certs from files in a directory",
106 	new_dir,		/* new */
107 	free_dir,		/* free */
108 	NULL, 			/* init */
109 	NULL,			/* shutdown */
110 	dir_ctrl,		/* ctrl */
111 	get_cert_by_subject,	/* get_by_subject */
112 	NULL,			/* get_by_issuer_serial */
113 	NULL,			/* get_by_fingerprint */
114 	NULL,			/* get_by_alias */
115 };
116 
117 X509_LOOKUP_METHOD *
118 X509_LOOKUP_hash_dir(void)
119 {
120 	return (&x509_dir_lookup);
121 }
122 
123 static int
124 dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl,
125     char **retp)
126 {
127 	int ret = 0;
128 	BY_DIR *ld;
129 	char *dir = NULL;
130 
131 	ld = (BY_DIR *)ctx->method_data;
132 
133 	switch (cmd) {
134 	case X509_L_ADD_DIR:
135 		if (argl == X509_FILETYPE_DEFAULT) {
136 			if (issetugid() == 0)
137 				dir = getenv(X509_get_default_cert_dir_env());
138 			if (dir)
139 				ret = add_cert_dir(ld, dir, X509_FILETYPE_PEM);
140 			else
141 				ret = add_cert_dir(ld, X509_get_default_cert_dir(),
142 				    X509_FILETYPE_PEM);
143 			if (!ret) {
144 				X509err(X509_F_DIR_CTRL, X509_R_LOADING_CERT_DIR);
145 			}
146 		} else
147 			ret = add_cert_dir(ld, argp, (int)argl);
148 		break;
149 	}
150 	return (ret);
151 }
152 
153 static int
154 new_dir(X509_LOOKUP *lu)
155 {
156 	BY_DIR *a;
157 
158 	if ((a = malloc(sizeof(BY_DIR))) == NULL)
159 		return (0);
160 	if ((a->buffer = BUF_MEM_new()) == NULL) {
161 		free(a);
162 		return (0);
163 	}
164 	a->dirs = NULL;
165 	lu->method_data = (char *)a;
166 	return (1);
167 }
168 
169 static void
170 by_dir_hash_free(BY_DIR_HASH *hash)
171 {
172 	free(hash);
173 }
174 
175 static int
176 by_dir_hash_cmp(const BY_DIR_HASH * const *a,
177     const BY_DIR_HASH * const *b)
178 {
179 	if ((*a)->hash > (*b)->hash)
180 		return 1;
181 	if ((*a)->hash < (*b)->hash)
182 		return -1;
183 	return 0;
184 }
185 
186 static void
187 by_dir_entry_free(BY_DIR_ENTRY *ent)
188 {
189 	free(ent->dir);
190 	if (ent->hashes)
191 		sk_BY_DIR_HASH_pop_free(ent->hashes, by_dir_hash_free);
192 	free(ent);
193 }
194 
195 static void
196 free_dir(X509_LOOKUP *lu)
197 {
198 	BY_DIR *a;
199 
200 	a = (BY_DIR *)lu->method_data;
201 	if (a->dirs != NULL)
202 		sk_BY_DIR_ENTRY_pop_free(a->dirs, by_dir_entry_free);
203 	if (a->buffer != NULL)
204 		BUF_MEM_free(a->buffer);
205 	free(a);
206 }
207 
208 static int
209 add_cert_dir(BY_DIR *ctx, const char *dir, int type)
210 {
211 	int j, len;
212 	const char *s, *ss, *p;
213 
214 	if (dir == NULL || !*dir) {
215 		X509err(X509_F_ADD_CERT_DIR, X509_R_INVALID_DIRECTORY);
216 		return 0;
217 	}
218 
219 	s = dir;
220 	p = s;
221 	do {
222 		if ((*p == ':') || (*p == '\0')) {
223 			BY_DIR_ENTRY *ent;
224 			ss = s;
225 			s = p + 1;
226 			len = (int)(p - ss);
227 			if (len == 0)
228 				continue;
229 			for (j = 0; j < sk_BY_DIR_ENTRY_num(ctx->dirs); j++) {
230 				ent = sk_BY_DIR_ENTRY_value(ctx->dirs, j);
231 				if (strlen(ent->dir) == (size_t)len &&
232 				    strncmp(ent->dir, ss,
233 				    (unsigned int)len) == 0)
234 					break;
235 			}
236 			if (j < sk_BY_DIR_ENTRY_num(ctx->dirs))
237 				continue;
238 			if (ctx->dirs == NULL) {
239 				ctx->dirs = sk_BY_DIR_ENTRY_new_null();
240 				if (!ctx->dirs) {
241 					X509err(X509_F_ADD_CERT_DIR, ERR_R_MALLOC_FAILURE);
242 					return 0;
243 				}
244 			}
245 			ent = malloc(sizeof(BY_DIR_ENTRY));
246 			if (!ent) {
247 				X509err(X509_F_ADD_CERT_DIR, ERR_R_MALLOC_FAILURE);
248 				return 0;
249 			}
250 			ent->dir_type = type;
251 			ent->hashes = sk_BY_DIR_HASH_new(by_dir_hash_cmp);
252 			ent->dir = strdup(ss);
253 			if (!ent->dir || !ent->hashes) {
254 				X509err(X509_F_ADD_CERT_DIR, ERR_R_MALLOC_FAILURE);
255 				by_dir_entry_free(ent);
256 				return 0;
257 			}
258 			if (!sk_BY_DIR_ENTRY_push(ctx->dirs, ent)) {
259 				X509err(X509_F_ADD_CERT_DIR, ERR_R_MALLOC_FAILURE);
260 				by_dir_entry_free(ent);
261 				return 0;
262 			}
263 		}
264 	} while (*p++ != '\0');
265 	return 1;
266 }
267 
268 static int
269 get_cert_by_subject(X509_LOOKUP *xl, int type, X509_NAME *name,
270     X509_OBJECT *ret)
271 {
272 	BY_DIR *ctx;
273 	union	{
274 		struct	{
275 			X509 st_x509;
276 			X509_CINF st_x509_cinf;
277 		} x509;
278 		struct	{
279 			X509_CRL st_crl;
280 			X509_CRL_INFO st_crl_info;
281 		} crl;
282 	} data;
283 	int ok = 0;
284 	int i, j, k;
285 	unsigned long h;
286 	BUF_MEM *b = NULL;
287 	X509_OBJECT stmp, *tmp;
288 	const char *postfix="";
289 
290 	if (name == NULL)
291 		return (0);
292 
293 	stmp.type = type;
294 	if (type == X509_LU_X509) {
295 		data.x509.st_x509.cert_info = &data.x509.st_x509_cinf;
296 		data.x509.st_x509_cinf.subject = name;
297 		stmp.data.x509 = &data.x509.st_x509;
298 		postfix="";
299 	} else if (type == X509_LU_CRL) {
300 		data.crl.st_crl.crl = &data.crl.st_crl_info;
301 		data.crl.st_crl_info.issuer = name;
302 		stmp.data.crl = &data.crl.st_crl;
303 		postfix="r";
304 	} else {
305 		X509err(X509_F_GET_CERT_BY_SUBJECT, X509_R_WRONG_LOOKUP_TYPE);
306 		goto finish;
307 	}
308 
309 	if ((b = BUF_MEM_new()) == NULL) {
310 		X509err(X509_F_GET_CERT_BY_SUBJECT, ERR_R_BUF_LIB);
311 		goto finish;
312 	}
313 
314 	ctx = (BY_DIR *)xl->method_data;
315 
316 	h = X509_NAME_hash(name);
317 	for (i = 0; i < sk_BY_DIR_ENTRY_num(ctx->dirs); i++) {
318 		BY_DIR_ENTRY *ent;
319 		int idx;
320 		BY_DIR_HASH htmp, *hent;
321 		ent = sk_BY_DIR_ENTRY_value(ctx->dirs, i);
322 		j = strlen(ent->dir) + 1 + 8 + 6 + 1 + 1;
323 		if (!BUF_MEM_grow(b, j)) {
324 			X509err(X509_F_GET_CERT_BY_SUBJECT, ERR_R_MALLOC_FAILURE);
325 			goto finish;
326 		}
327 		if (type == X509_LU_CRL && ent->hashes) {
328 			htmp.hash = h;
329 			CRYPTO_r_lock(CRYPTO_LOCK_X509_STORE);
330 			idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp);
331 			if (idx >= 0) {
332 				hent = sk_BY_DIR_HASH_value(ent->hashes, idx);
333 				k = hent->suffix;
334 			} else {
335 				hent = NULL;
336 				k = 0;
337 			}
338 			CRYPTO_r_unlock(CRYPTO_LOCK_X509_STORE);
339 		} else {
340 			k = 0;
341 			hent = NULL;
342 		}
343 		for (;;) {
344 			(void) snprintf(b->data, b->max, "%s/%08lx.%s%d",
345 			    ent->dir, h, postfix, k);
346 
347 #ifndef OPENSSL_NO_POSIX_IO
348 			{
349 				struct stat st;
350 				if (stat(b->data, &st) < 0)
351 					break;
352 			}
353 #endif
354 			/* found one. */
355 			if (type == X509_LU_X509) {
356 				if ((X509_load_cert_file(xl, b->data,
357 				    ent->dir_type)) == 0)
358 					break;
359 			} else if (type == X509_LU_CRL) {
360 				if ((X509_load_crl_file(xl, b->data,
361 				    ent->dir_type)) == 0)
362 					break;
363 			}
364 			/* else case will caught higher up */
365 			k++;
366 		}
367 
368 		/* we have added it to the cache so now pull it out again */
369 		CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
370 		j = sk_X509_OBJECT_find(xl->store_ctx->objs, &stmp);
371 		if (j != -1)
372 			tmp = sk_X509_OBJECT_value(xl->store_ctx->objs, j);
373 		else
374 			tmp = NULL;
375 		CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
376 
377 		/* If a CRL, update the last file suffix added for this */
378 		if (type == X509_LU_CRL) {
379 			CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
380 			/*
381 			 * Look for entry again in case another thread added
382 			 * an entry first.
383 			 */
384 			if (!hent) {
385 				htmp.hash = h;
386 				idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp);
387 				if (idx >= 0)
388 					hent = sk_BY_DIR_HASH_value(
389 					    ent->hashes, idx);
390 			}
391 			if (!hent) {
392 				hent = malloc(sizeof(BY_DIR_HASH));
393 				if (!hent) {
394 					X509err(X509_F_GET_CERT_BY_SUBJECT, ERR_R_MALLOC_FAILURE);
395 					CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
396 					ok = 0;
397 					goto finish;
398 				}
399 				hent->hash = h;
400 				hent->suffix = k;
401 				if (!sk_BY_DIR_HASH_push(ent->hashes, hent)) {
402 					X509err(X509_F_GET_CERT_BY_SUBJECT, ERR_R_MALLOC_FAILURE);
403 					CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
404 					free(hent);
405 					ok = 0;
406 					goto finish;
407 				}
408 			} else if (hent->suffix < k)
409 				hent->suffix = k;
410 
411 			CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
412 
413 		}
414 
415 		if (tmp != NULL) {
416 			ok = 1;
417 			ret->type = tmp->type;
418 			memcpy(&ret->data, &tmp->data, sizeof(ret->data));
419 			/*
420 			 * If we were going to up the reference count,
421 			 * we would need to do it on a perl 'type' basis
422 			 */
423 	/*		CRYPTO_add(&tmp->data.x509->references,1,
424 				CRYPTO_LOCK_X509);*/
425 			goto finish;
426 		}
427 	}
428 finish:
429 	if (b != NULL)
430 		BUF_MEM_free(b);
431 	return (ok);
432 }
433