xref: /openbsd/sbin/iked/ca.c (revision 3fdfc9aa)
1 /*	$OpenBSD: ca.c,v 1.101 2024/02/13 12:25:11 tobhe Exp $	*/
2 
3 /*
4  * Copyright (c) 2010-2013 Reyk Floeter <reyk@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/queue.h>
20 #include <sys/socket.h>
21 #include <sys/uio.h>
22 
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <unistd.h>
26 #include <dirent.h>
27 #include <string.h>
28 #include <signal.h>
29 #include <syslog.h>
30 #include <errno.h>
31 #include <err.h>
32 #include <event.h>
33 
34 #include <openssl/bio.h>
35 #include <openssl/err.h>
36 #include <openssl/ssl.h>
37 #include <openssl/x509.h>
38 #include <openssl/x509v3.h>
39 #include <openssl/pem.h>
40 #include <openssl/evp.h>
41 #include <openssl/sha.h>
42 #include <openssl/rsa.h>
43 
44 #include "iked.h"
45 #include "ikev2.h"
46 
47 void	 ca_run(struct privsep *, struct privsep_proc *, void *);
48 void	 ca_shutdown(void);
49 void	 ca_reset(struct iked *);
50 int	 ca_reload(struct iked *);
51 
52 int	 ca_cert_local(struct iked *, X509 *);
53 int	 ca_getreq(struct iked *, struct imsg *);
54 int	 ca_getcert(struct iked *, struct imsg *);
55 int	 ca_getauth(struct iked *, struct imsg *);
56 X509	*ca_by_subjectpubkey(X509_STORE *, uint8_t *, size_t);
57 X509	*ca_by_issuer(X509_STORE *, X509_NAME *, struct iked_static_id *);
58 X509	*ca_by_subjectaltname(X509_STORE *, struct iked_static_id *);
59 void	 ca_store_certs_info(const char *, X509_STORE *);
60 int	 ca_subjectpubkey_digest(X509 *, uint8_t *, unsigned int *);
61 int	 ca_x509_subject_cmp(X509 *, struct iked_static_id *);
62 int	 ca_validate_pubkey(struct iked *, struct iked_static_id *,
63 	    void *, size_t, struct iked_id *);
64 int	 ca_validate_cert(struct iked *, struct iked_static_id *,
65 	    void *, size_t, STACK_OF(X509) *, X509 **);
66 EVP_PKEY *
67 	 ca_bytes_to_pkey(uint8_t *, size_t);
68 int	 ca_privkey_to_method(struct iked_id *);
69 struct ibuf *
70 	 ca_x509_serialize(X509 *);
71 int	 ca_x509_subjectaltname_do(X509 *, int, const char *,
72 	    struct iked_static_id *, struct iked_id *);
73 int	 ca_x509_subjectaltname_cmp(X509 *, struct iked_static_id *);
74 int	 ca_x509_subjectaltname_log(X509 *, const char *);
75 int	 ca_x509_subjectaltname_get(X509 *cert, struct iked_id *);
76 int	 ca_dispatch_parent(int, struct privsep_proc *, struct imsg *);
77 int	 ca_dispatch_ikev2(int, struct privsep_proc *, struct imsg *);
78 int	 ca_dispatch_control(int, struct privsep_proc *, struct imsg *);
79 void	 ca_store_info(struct iked *, struct imsg *, const char *, X509_STORE *);
80 
81 static struct privsep_proc procs[] = {
82 	{ "parent",	PROC_PARENT,	ca_dispatch_parent },
83 	{ "ikev2",	PROC_IKEV2,	ca_dispatch_ikev2 },
84 	{ "control",	PROC_CONTROL,	ca_dispatch_control }
85 };
86 
87 struct ca_store {
88 	X509_STORE	*ca_cas;
89 	X509_LOOKUP	*ca_calookup;
90 
91 	X509_STORE	*ca_certs;
92 	X509_LOOKUP	*ca_certlookup;
93 
94 	struct iked_id	 ca_privkey;
95 	struct iked_id	 ca_pubkey;
96 
97 	uint8_t		 ca_privkey_method;
98 };
99 
100 void
caproc(struct privsep * ps,struct privsep_proc * p)101 caproc(struct privsep *ps, struct privsep_proc *p)
102 {
103 	proc_run(ps, p, procs, nitems(procs), ca_run, NULL);
104 }
105 
106 void
ca_run(struct privsep * ps,struct privsep_proc * p,void * arg)107 ca_run(struct privsep *ps, struct privsep_proc *p, void *arg)
108 {
109 	struct iked	*env = iked_env;
110 	struct ca_store	*store;
111 
112 	/*
113 	 * pledge in the ca process:
114 	 * stdio - for malloc and basic I/O including events.
115 	 * rpath - for certificate files.
116 	 * recvfd - for ocsp sockets.
117 	 */
118 	if (pledge("stdio rpath recvfd", NULL) == -1)
119 		fatal("pledge");
120 
121 	if ((store = calloc(1, sizeof(*store))) == NULL)
122 		fatal("%s: failed to allocate cert store", __func__);
123 
124 	env->sc_priv = store;
125 	p->p_shutdown = ca_shutdown;
126 }
127 
128 void
ca_shutdown(void)129 ca_shutdown(void)
130 {
131 	struct iked		*env = iked_env;
132 	struct ca_store		*store;
133 
134 	ibuf_free(env->sc_certreq);
135 	if ((store = env->sc_priv) == NULL)
136 		return;
137 	X509_STORE_free(store->ca_cas);
138 	X509_STORE_free(store->ca_certs);
139 	ibuf_free(store->ca_pubkey.id_buf);
140 	ibuf_free(store->ca_privkey.id_buf);
141 	free(store);
142 }
143 
144 void
ca_getkey(struct privsep * ps,struct iked_id * key,enum imsg_type type)145 ca_getkey(struct privsep *ps, struct iked_id *key, enum imsg_type type)
146 {
147 	struct iked	*env = iked_env;
148 	struct ca_store	*store = env->sc_priv;
149 	struct iked_id	*id = NULL;
150 	const char	*name;
151 
152 	if (store == NULL)
153 		fatalx("%s: invalid store", __func__);
154 
155 	if (type == IMSG_PRIVKEY) {
156 		name = "private";
157 		id = &store->ca_privkey;
158 
159 		store->ca_privkey_method = ca_privkey_to_method(key);
160 		if (store->ca_privkey_method == IKEV2_AUTH_NONE)
161 			fatalx("ca: failed to get auth method for privkey");
162 	} else if (type == IMSG_PUBKEY) {
163 		name = "public";
164 		id = &store->ca_pubkey;
165 	} else
166 		fatalx("%s: invalid type %d", __func__, type);
167 
168 	log_debug("%s: received %s key type %s length %zd", __func__,
169 	    name, print_map(key->id_type, ikev2_cert_map),
170 	    ibuf_length(key->id_buf));
171 
172 	/* clear old key and copy new one */
173 	ibuf_free(id->id_buf);
174 	memcpy(id, key, sizeof(*id));
175 }
176 
177 void
ca_reset(struct iked * env)178 ca_reset(struct iked *env)
179 {
180 	struct ca_store	*store = env->sc_priv;
181 
182 	if (store->ca_privkey.id_type == IKEV2_ID_NONE ||
183 	    store->ca_pubkey.id_type == IKEV2_ID_NONE)
184 		fatalx("ca_reset: keys not loaded");
185 
186 	X509_STORE_free(store->ca_cas);
187 	X509_STORE_free(store->ca_certs);
188 
189 	if ((store->ca_cas = X509_STORE_new()) == NULL)
190 		fatalx("ca_reset: failed to get ca store");
191 	if ((store->ca_calookup = X509_STORE_add_lookup(store->ca_cas,
192 	    X509_LOOKUP_file())) == NULL)
193 		fatalx("ca_reset: failed to add ca lookup");
194 
195 	if ((store->ca_certs = X509_STORE_new()) == NULL)
196 		fatalx("ca_reset: failed to get cert store");
197 	if ((store->ca_certlookup = X509_STORE_add_lookup(store->ca_certs,
198 	    X509_LOOKUP_file())) == NULL)
199 		fatalx("ca_reset: failed to add cert lookup");
200 
201 	if (ca_reload(env) != 0)
202 		fatal("ca_reset: reload");
203 }
204 
205 int
ca_certbundle_add(struct ibuf * buf,struct iked_id * id)206 ca_certbundle_add(struct ibuf *buf, struct iked_id *id)
207 {
208 	uint8_t		 type = id->id_type;
209 	size_t		 len = ibuf_size(id->id_buf);
210 	void		*val = ibuf_data(id->id_buf);
211 
212 	if (buf == NULL ||
213 	    ibuf_add(buf, &type, sizeof(type)) != 0 ||
214 	    ibuf_add(buf, &len, sizeof(len)) != 0 ||
215 	    ibuf_add(buf, val, len) != 0)
216 		return -1;
217 	return 0;
218 }
219 
220 /*
221  * decode cert bundle to cert and untrusted intermediate CAs.
222  * datap/lenp point to bundle on input and to decoded cert output
223  */
224 static int
ca_decode_cert_bundle(struct iked * env,struct iked_sahdr * sh,uint8_t ** datap,size_t * lenp,STACK_OF (X509)** untrustedp)225 ca_decode_cert_bundle(struct iked *env, struct iked_sahdr *sh,
226   uint8_t **datap, size_t *lenp, STACK_OF(X509)	**untrustedp)
227 {
228 	STACK_OF(X509)		*untrusted = NULL;
229 	X509			*cert;
230 	BIO			*rawcert = NULL;
231 	uint8_t			*certdata = NULL;
232 	size_t			 certlen = 0;
233 	uint8_t			 datatype;
234 	size_t			 datalen = 0;
235 	uint8_t			*ptr;
236 	size_t			 len;
237 	int			 ret = -1;
238 
239 	log_debug("%s: decoding cert bundle", SPI_SH(sh, __func__));
240 
241 	ptr = *datap;
242 	len = *lenp;
243 	*untrustedp = NULL;
244 
245 	/* allocate stack for intermediate CAs */
246 	if ((untrusted = sk_X509_new_null()) == NULL)
247 		goto done;
248 
249 	/* parse TLV, see ca_certbundle_add() */
250 	while (len > 0) {
251 		/* Type */
252 		if (len < sizeof(datatype)) {
253 			log_debug("%s: short data (type)",
254 			    SPI_SH(sh, __func__));
255 			goto done;
256 		}
257 		memcpy(&datatype, ptr, sizeof(datatype));
258 		ptr += sizeof(datatype);
259 		len -= sizeof(datatype);
260 
261 		/* Only X509 certs/CAs are supported */
262 		if (datatype != IKEV2_CERT_X509_CERT) {
263 			log_info("%s: unsupported data type: %s",
264 			    SPI_SH(sh, __func__),
265 			    print_map(datatype, ikev2_cert_map));
266 			goto done;
267 		}
268 
269 		/* Length */
270 		if (len < sizeof(datalen)) {
271 			log_info("%s: short data (len)",
272 			    SPI_SH(sh, __func__));
273 			goto done;
274 		}
275 		memcpy(&datalen, ptr, sizeof(datalen));
276 		ptr += sizeof(datalen);
277 		len -= sizeof(datalen);
278 
279 		/* Value */
280 		if (len < datalen) {
281 			log_info("%s: short len %zu < datalen %zu",
282 			    SPI_SH(sh, __func__), len, datalen);
283 			goto done;
284 		}
285 
286 		if (certdata == NULL) {
287 			/* First entry is cert */
288 			certdata = ptr;
289 			certlen = datalen;
290 		} else {
291 			/* All other entries are intermediate CAs */
292 			rawcert = BIO_new_mem_buf(ptr, datalen);
293 			if (rawcert == NULL)
294 				goto done;
295 			cert = d2i_X509_bio(rawcert, NULL);
296 			BIO_free(rawcert);
297 			if (cert == NULL) {
298 				log_warnx("%s: cannot parse CA",
299 				    SPI_SH(sh, __func__));
300 				ca_sslerror(__func__);
301 				goto done;
302 			}
303 			if (!sk_X509_push(untrusted, cert)) {
304 				log_warnx("%s: cannot store CA",
305 				    SPI_SH(sh, __func__));
306 				X509_free(cert);
307 				goto done;
308 			}
309 		}
310 		ptr += datalen;
311 		len -= datalen;
312 	}
313 	log_debug("%s: decoded cert bundle", SPI_SH(sh, __func__));
314 	*datap = certdata;
315 	*lenp = certlen;
316 	*untrustedp = untrusted;
317 	untrusted = NULL;
318 	ret = 0;
319 
320  done:
321 	if (ret != 0)
322 		log_info("%s: failed to decode cert bundle",
323 		    SPI_SH(sh, __func__));
324 	sk_X509_free(untrusted);
325 	return ret;
326 }
327 
328 int
ca_dispatch_parent(int fd,struct privsep_proc * p,struct imsg * imsg)329 ca_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
330 {
331 	struct iked		*env = iked_env;
332 	unsigned int		 mode;
333 
334 	switch (imsg->hdr.type) {
335 	case IMSG_CTL_ACTIVE:
336 	case IMSG_CTL_PASSIVE:
337 		/*
338 		 * send back to indicate we have processed
339 		 * all messages from parent.
340 		 */
341 		proc_compose(&env->sc_ps, PROC_PARENT, imsg->hdr.type, NULL, 0);
342 		break;
343 	case IMSG_CTL_RESET:
344 		IMSG_SIZE_CHECK(imsg, &mode);
345 		memcpy(&mode, imsg->data, sizeof(mode));
346 		if (mode == RESET_ALL || mode == RESET_CA) {
347 			log_debug("%s: config reset", __func__);
348 			ca_reset(env);
349 		}
350 		break;
351 	case IMSG_OCSP_FD:
352 		ocsp_receive_fd(env, imsg);
353 		break;
354 	case IMSG_OCSP_CFG:
355 		config_getocsp(env, imsg);
356 		break;
357 	case IMSG_PRIVKEY:
358 	case IMSG_PUBKEY:
359 		config_getkey(env, imsg);
360 		break;
361 	case IMSG_CTL_STATIC:
362 		config_getstatic(env, imsg);
363 		break;
364 	default:
365 		return (-1);
366 	}
367 
368 	return (0);
369 }
370 
371 int
ca_dispatch_ikev2(int fd,struct privsep_proc * p,struct imsg * imsg)372 ca_dispatch_ikev2(int fd, struct privsep_proc *p, struct imsg *imsg)
373 {
374 	struct iked	*env = iked_env;
375 
376 	switch (imsg->hdr.type) {
377 	case IMSG_CERTREQ:
378 		ca_getreq(env, imsg);
379 		break;
380 	case IMSG_CERT:
381 		ca_getcert(env, imsg);
382 		break;
383 	case IMSG_AUTH:
384 		ca_getauth(env, imsg);
385 		break;
386 	default:
387 		return (-1);
388 	}
389 
390 	return (0);
391 }
392 
393 int
ca_dispatch_control(int fd,struct privsep_proc * p,struct imsg * imsg)394 ca_dispatch_control(int fd, struct privsep_proc *p, struct imsg *imsg)
395 {
396 	struct iked	*env = iked_env;
397 	struct ca_store	*store = env->sc_priv;
398 
399 	switch (imsg->hdr.type) {
400 	case IMSG_CTL_SHOW_CERTSTORE:
401 		ca_store_info(env, imsg, "CA", store->ca_cas);
402 		ca_store_info(env, imsg, "CERT", store->ca_certs);
403 		/* Send empty reply to indicate end of information. */
404 		proc_compose_imsg(&env->sc_ps, PROC_CONTROL, -1,
405 		    IMSG_CTL_SHOW_CERTSTORE, imsg->hdr.peerid,
406 		    -1, NULL, 0);
407 		break;
408 	default:
409 		return (-1);
410 	}
411 
412 	return (0);
413 }
414 
415 int
ca_setcert(struct iked * env,struct iked_sahdr * sh,struct iked_id * id,uint8_t type,uint8_t * data,size_t len,enum privsep_procid procid)416 ca_setcert(struct iked *env, struct iked_sahdr *sh, struct iked_id *id,
417     uint8_t type, uint8_t *data, size_t len, enum privsep_procid procid)
418 {
419 	struct iovec		iov[4];
420 	int			iovcnt = 0;
421 	struct iked_static_id	idb;
422 
423 	/* Must send the cert and a valid Id to the ca process */
424 	if (procid == PROC_CERT) {
425 		if (id == NULL || id->id_type == IKEV2_ID_NONE ||
426 		    ibuf_size(id->id_buf) > IKED_ID_SIZE)
427 			return (-1);
428 		bzero(&idb, sizeof(idb));
429 
430 		/* Convert to a static Id */
431 		idb.id_type = id->id_type;
432 		idb.id_offset = id->id_offset;
433 		idb.id_length = ibuf_size(id->id_buf);
434 		memcpy(&idb.id_data, ibuf_data(id->id_buf),
435 		    ibuf_size(id->id_buf));
436 
437 		iov[iovcnt].iov_base = &idb;
438 		iov[iovcnt].iov_len = sizeof(idb);
439 		iovcnt++;
440 	}
441 
442 	iov[iovcnt].iov_base = sh;
443 	iov[iovcnt].iov_len = sizeof(*sh);
444 	iovcnt++;
445 	iov[iovcnt].iov_base = &type;
446 	iov[iovcnt].iov_len = sizeof(type);
447 	iovcnt++;
448 	if (data != NULL) {
449 		iov[iovcnt].iov_base = data;
450 		iov[iovcnt].iov_len = len;
451 		iovcnt++;
452 	}
453 
454 	if (proc_composev(&env->sc_ps, procid, IMSG_CERT, iov, iovcnt) == -1)
455 		return (-1);
456 	return (0);
457 }
458 
459 static int
ca_setscert(struct iked * env,struct iked_sahdr * sh,uint8_t type,X509 * cert)460 ca_setscert(struct iked *env, struct iked_sahdr *sh, uint8_t type, X509 *cert)
461 {
462 	struct iovec		iov[3];
463 	int			iovcnt = 0;
464 	struct ibuf		*buf;
465 	int			ret;
466 
467 	if ((buf = ca_x509_serialize(cert)) == NULL)
468 		return (-1);
469 
470 	iov[iovcnt].iov_base = sh;
471 	iov[iovcnt].iov_len = sizeof(*sh);
472 	iovcnt++;
473 	iov[iovcnt].iov_base = &type;
474 	iov[iovcnt].iov_len = sizeof(type);
475 	iovcnt++;
476 	iov[iovcnt].iov_base = ibuf_data(buf);
477 	iov[iovcnt].iov_len = ibuf_size(buf);
478 	iovcnt++;
479 
480 	ret = proc_composev(&env->sc_ps, PROC_IKEV2, IMSG_SCERT, iov, iovcnt);
481 	ibuf_free(buf);
482 	return (ret);
483 }
484 
485 int
ca_setreq(struct iked * env,struct iked_sa * sa,struct iked_static_id * localid,uint8_t type,uint8_t more,uint8_t * data,size_t len,enum privsep_procid procid)486 ca_setreq(struct iked *env, struct iked_sa *sa,
487     struct iked_static_id *localid, uint8_t type, uint8_t more, uint8_t *data,
488     size_t len, enum privsep_procid procid)
489 {
490 	struct iovec		iov[5];
491 	int			iovcnt = 0;
492 	struct iked_static_id	idb;
493 	struct iked_id		id;
494 	int			ret = -1;
495 
496 	/* Convert to a static Id */
497 	bzero(&id, sizeof(id));
498 	if (ikev2_policy2id(localid, &id, 1) != 0)
499 		return (-1);
500 
501 	if (ibuf_size(id.id_buf) > IKED_ID_SIZE)
502 		return (-1);
503 	bzero(&idb, sizeof(idb));
504 	idb.id_type = id.id_type;
505 	idb.id_offset = id.id_offset;
506 	idb.id_length = ibuf_size(id.id_buf);
507 	memcpy(&idb.id_data, ibuf_data(id.id_buf), ibuf_size(id.id_buf));
508 	iov[iovcnt].iov_base = &idb;
509 	iov[iovcnt].iov_len = sizeof(idb);
510 	iovcnt++;
511 
512 	iov[iovcnt].iov_base = &sa->sa_hdr;
513 	iov[iovcnt].iov_len = sizeof(sa->sa_hdr);
514 	iovcnt++;
515 	iov[iovcnt].iov_base = &type;
516 	iov[iovcnt].iov_len = sizeof(type);
517 	iovcnt++;
518 	iov[iovcnt].iov_base = &more;
519 	iov[iovcnt].iov_len = sizeof(more);
520 	iovcnt++;
521 	if (data != NULL) {
522 		iov[iovcnt].iov_base = data;
523 		iov[iovcnt].iov_len = len;
524 		iovcnt++;
525 	}
526 
527 	if (proc_composev(&env->sc_ps, procid, IMSG_CERTREQ, iov, iovcnt) == -1)
528 		goto done;
529 
530 	sa_stateflags(sa, IKED_REQ_CERTREQ);
531 
532 	ret = 0;
533  done:
534 	ibuf_free(id.id_buf);
535 	return (ret);
536 }
537 
538 static int
auth_sig_compatible(uint8_t type)539 auth_sig_compatible(uint8_t type)
540 {
541 	switch (type) {
542 	case IKEV2_AUTH_RSA_SIG:
543 	case IKEV2_AUTH_ECDSA_256:
544 	case IKEV2_AUTH_ECDSA_384:
545 	case IKEV2_AUTH_ECDSA_521:
546 	case IKEV2_AUTH_SIG_ANY:
547 		return (1);
548 	}
549 	return (0);
550 }
551 
552 int
ca_setauth(struct iked * env,struct iked_sa * sa,struct ibuf * authmsg,enum privsep_procid id)553 ca_setauth(struct iked *env, struct iked_sa *sa,
554     struct ibuf *authmsg, enum privsep_procid id)
555 {
556 	struct iovec		 iov[3];
557 	int			 iovcnt = 3;
558 	struct iked_policy	*policy = sa->sa_policy;
559 	uint8_t			 type = policy->pol_auth.auth_method;
560 
561 	if (id == PROC_CERT) {
562 		/* switch encoding to IKEV2_AUTH_SIG if SHA2 is supported */
563 		if (sa->sa_sigsha2 && auth_sig_compatible(type)) {
564 			log_debug("%s: switching %s to SIG", __func__,
565 			    print_map(type, ikev2_auth_map));
566 			type = IKEV2_AUTH_SIG;
567 		} else if (!sa->sa_sigsha2 && type == IKEV2_AUTH_SIG_ANY) {
568 			log_debug("%s: switching SIG to RSA_SIG(*)", __func__);
569 			/* XXX ca might auto-switch to ECDSA */
570 			type = IKEV2_AUTH_RSA_SIG;
571 		} else if (type == IKEV2_AUTH_SIG) {
572 			log_debug("%s: using SIG (RFC7427)", __func__);
573 		}
574 	}
575 
576 	if (type == IKEV2_AUTH_SHARED_KEY_MIC) {
577 		sa->sa_stateflags |= IKED_REQ_AUTH;
578 		return (ikev2_msg_authsign(env, sa,
579 		    &policy->pol_auth, authmsg));
580 	}
581 
582 	iov[0].iov_base = &sa->sa_hdr;
583 	iov[0].iov_len = sizeof(sa->sa_hdr);
584 	iov[1].iov_base = &type;
585 	iov[1].iov_len = sizeof(type);
586 	if (type == IKEV2_AUTH_NONE)
587 		iovcnt--;
588 	else {
589 		iov[2].iov_base = ibuf_data(authmsg);
590 		iov[2].iov_len = ibuf_size(authmsg);
591 		log_debug("%s: auth length %zu", __func__, ibuf_size(authmsg));
592 	}
593 
594 	if (proc_composev(&env->sc_ps, id, IMSG_AUTH, iov, iovcnt) == -1)
595 		return (-1);
596 	return (0);
597 }
598 
599 int
ca_getcert(struct iked * env,struct imsg * imsg)600 ca_getcert(struct iked *env, struct imsg *imsg)
601 {
602 	struct ca_store		*store = env->sc_priv;
603 	X509			*issuer = NULL, *cert;
604 	STACK_OF(X509)		*untrusted = NULL;
605 	EVP_PKEY		*certkey;
606 	struct iked_sahdr	 sh;
607 	uint8_t			 type;
608 	uint8_t			*ptr;
609 	size_t			 len;
610 	struct iked_static_id	 id;
611 	unsigned int		 i;
612 	struct iovec		 iov[3];
613 	int			 iovcnt = 3, cmd, ret = 0;
614 	struct iked_id		 key;
615 
616 	ptr = (uint8_t *)imsg->data;
617 	len = IMSG_DATA_SIZE(imsg);
618 	i = sizeof(id) + sizeof(sh) + sizeof(type);
619 	if (len < i)
620 		return (-1);
621 
622 	memcpy(&id, ptr, sizeof(id));
623 	if (id.id_type == IKEV2_ID_NONE)
624 		return (-1);
625 	memcpy(&sh, ptr + sizeof(id), sizeof(sh));
626 	memcpy(&type, ptr + sizeof(id) + sizeof(sh), sizeof(uint8_t));
627 
628 	ptr += i;
629 	len -= i;
630 
631 	bzero(&key, sizeof(key));
632 
633 	if (type == IKEV2_CERT_BUNDLE &&
634 	    ca_decode_cert_bundle(env, &sh, &ptr, &len, &untrusted) == 0)
635 		type = IKEV2_CERT_X509_CERT;
636 
637 	switch (type) {
638 	case IKEV2_CERT_X509_CERT:
639 		/* Look in local cert storage first */
640 		cert = ca_by_subjectaltname(store->ca_certs, &id);
641 		if (cert) {
642 			log_debug("%s: found local cert", __func__);
643 			if ((certkey = X509_get0_pubkey(cert)) != NULL) {
644 				ret = ca_pubkey_serialize(certkey, &key);
645 				if (ret == 0) {
646 					ptr = ibuf_data(key.id_buf);
647 					len = ibuf_size(key.id_buf);
648 					type = key.id_type;
649 					break;
650 				}
651 			}
652 		}
653 		if (env->sc_ocsp_url == NULL)
654 			ret = ca_validate_cert(env, &id, ptr, len, untrusted, NULL);
655 		else {
656 			ret = ca_validate_cert(env, &id, ptr, len, untrusted, &issuer);
657 			if (ret == 0) {
658 				ret = ocsp_validate_cert(env, ptr, len, sh,
659 				    type, issuer);
660 				X509_free(issuer);
661 				if (ret == 0) {
662 					sk_X509_free(untrusted);
663 					return (0);
664 				}
665 			} else
666 				X509_free(issuer);
667 		}
668 		break;
669 	case IKEV2_CERT_RSA_KEY:
670 	case IKEV2_CERT_ECDSA:
671 		ret = ca_validate_pubkey(env, &id, ptr, len, NULL);
672 		break;
673 	case IKEV2_CERT_NONE:
674 		/* Fallback to public key */
675 		ret = ca_validate_pubkey(env, &id, NULL, 0, &key);
676 		if (ret == 0) {
677 			ptr = ibuf_data(key.id_buf);
678 			len = ibuf_size(key.id_buf);
679 			type = key.id_type;
680 		}
681 		break;
682 	default:
683 		log_debug("%s: unsupported cert type %d", __func__, type);
684 		ret = -1;
685 		break;
686 	}
687 
688 	if (ret == 0)
689 		cmd = IMSG_CERTVALID;
690 	else
691 		cmd = IMSG_CERTINVALID;
692 
693 	iov[0].iov_base = &sh;
694 	iov[0].iov_len = sizeof(sh);
695 	iov[1].iov_base = &type;
696 	iov[1].iov_len = sizeof(type);
697 	iov[2].iov_base = ptr;
698 	iov[2].iov_len = len;
699 
700 	ret = proc_composev(&env->sc_ps, PROC_IKEV2, cmd, iov, iovcnt);
701 	ibuf_free(key.id_buf);
702 	sk_X509_free(untrusted);
703 
704 	return (ret);
705 }
706 
707 static unsigned int
ca_chain_by_issuer(struct ca_store * store,X509_NAME * subject,struct iked_static_id * id,X509 ** dst,size_t dstlen)708 ca_chain_by_issuer(struct ca_store *store, X509_NAME *subject,
709     struct iked_static_id *id, X509 **dst, size_t dstlen)
710 {
711 	STACK_OF(X509_OBJECT)	*h;
712 	X509_OBJECT		*xo;
713 	X509			*cert;
714 	int			i;
715 	unsigned int		n;
716 	X509_NAME		*issuer, *subj;
717 
718         if (subject == NULL || dstlen == 0)
719 		return (0);
720 
721 	if ((cert = ca_by_issuer(store->ca_certs, subject, id)) != NULL) {
722 		*dst = cert;
723 		return (1);
724 	}
725 
726 	h = X509_STORE_get0_objects(store->ca_cas);
727 	for (i = 0; i < sk_X509_OBJECT_num(h); i++) {
728 		xo = sk_X509_OBJECT_value(h, i);
729 		if (X509_OBJECT_get_type(xo) != X509_LU_X509)
730 			continue;
731 		cert = X509_OBJECT_get0_X509(xo);
732 		if ((issuer = X509_get_issuer_name(cert)) == NULL)
733 			continue;
734 		if (X509_NAME_cmp(subject, issuer) == 0) {
735 			if ((subj = X509_get_subject_name(cert)) == NULL)
736 				continue;
737 			/* Skip root CAs */
738 			if (X509_NAME_cmp(subj, issuer) == 0)
739 				continue;
740 			n = ca_chain_by_issuer(store, subj, id,
741 			    dst + 1, dstlen - 1);
742 			if (n > 0) {
743 				*dst = cert;
744 				return (n + 1);
745 			}
746 		}
747 	}
748 
749 	return (0);
750 }
751 
752 int
ca_getreq(struct iked * env,struct imsg * imsg)753 ca_getreq(struct iked *env, struct imsg *imsg)
754 {
755 	struct ca_store		*store = env->sc_priv;
756 	struct iked_sahdr	 sh;
757 	uint8_t			 type, more;
758 	uint8_t			*ptr;
759 	size_t			 len;
760 	unsigned int		 i;
761 	X509			*ca = NULL, *cert = NULL;
762 	X509			*chain[IKED_SCERT_MAX + 1];
763 	size_t			 chain_len = 0;
764 	struct ibuf		*buf;
765 	struct iked_static_id	 id;
766 	char			 idstr[IKED_ID_SIZE];
767 	X509_NAME		*subj;
768 	char			*subj_name;
769 
770 	ptr = (uint8_t *)imsg->data;
771 	len = IMSG_DATA_SIZE(imsg);
772 	i = sizeof(id) + sizeof(type) + sizeof(sh) + sizeof(more);
773 	if (len < i)
774 		return (-1);
775 
776 	memcpy(&id, ptr, sizeof(id));
777 	if (id.id_type == IKEV2_ID_NONE)
778 		return (-1);
779 	memcpy(&sh, ptr + sizeof(id), sizeof(sh));
780 	memcpy(&type, ptr + sizeof(id) + sizeof(sh), sizeof(type));
781 	memcpy(&more, ptr + sizeof(id) + sizeof(sh) + sizeof(type), sizeof(more));
782 
783 	ptr += i;
784 	len -= i;
785 
786 	switch (type) {
787 	case IKEV2_CERT_RSA_KEY:
788 	case IKEV2_CERT_ECDSA:
789 		/*
790 		 * Find a local raw public key that matches the type
791 		 * received in the CERTREQ payoad
792 		 */
793 		if (store->ca_pubkey.id_type != type ||
794 		    store->ca_pubkey.id_buf == NULL)
795 			goto fallback;
796 
797 		buf = ibuf_dup(store->ca_pubkey.id_buf);
798 		log_debug("%s: using local public key of type %s", __func__,
799 		    print_map(type, ikev2_cert_map));
800 		break;
801 	case IKEV2_CERT_X509_CERT:
802 		if (len == 0 || len % SHA_DIGEST_LENGTH) {
803 			log_info("%s: invalid CERTREQ data.",
804 			    SPI_SH(&sh, __func__));
805 			return (-1);
806 		}
807 
808 		/*
809 		 * Find a local certificate signed by any of the CAs
810 		 * received in the CERTREQ payload
811 		 */
812 		for (i = 0; i < len; i += SHA_DIGEST_LENGTH) {
813 			if ((ca = ca_by_subjectpubkey(store->ca_cas, ptr + i,
814 			    SHA_DIGEST_LENGTH)) == NULL)
815 				continue;
816 			subj = X509_get_subject_name(ca);
817 			if (subj == NULL)
818 				return (-1);
819 			subj_name = X509_NAME_oneline(subj, NULL, 0);
820 			if (subj_name == NULL)
821 				return (-1);
822 			log_debug("%s: found CA %s", __func__, subj_name);
823 			OPENSSL_free(subj_name);
824 
825 			chain_len = ca_chain_by_issuer(store, subj, &id,
826 			    chain, nitems(chain));
827 			if (chain_len > 0) {
828 				cert = chain[chain_len - 1];
829 				if (!ca_cert_local(env, cert)) {
830 					log_info("%s: found cert with matching "
831 					    "ID but without matching key.",
832 					    SPI_SH(&sh, __func__));
833 					continue;
834 				}
835 				break;
836 			}
837 		}
838 
839 		for (i = chain_len; i >= 2; i--)
840 			ca_setscert(env, &sh, type, chain[i - 2]);
841 
842 		/* Fallthrough */
843 	case IKEV2_CERT_NONE:
844  fallback:
845 		/*
846 		 * If no certificate or key matching any of the trust-anchors
847 		 * was found and this was the last CERTREQ, try to find one with
848 		 * subjectAltName matching the ID
849 		 */
850 		if (cert == NULL && more)
851 			return (0);
852 
853 		if (cert == NULL)
854 			cert = ca_by_subjectaltname(store->ca_certs, &id);
855 
856 		/* Set type if coming from fallback */
857 		if (cert != NULL)
858 			type = IKEV2_CERT_X509_CERT;
859 
860 		/* If there is no matching certificate use local raw pubkey */
861 		if (cert == NULL) {
862 			if (ikev2_print_static_id(&id, idstr, sizeof(idstr)) == -1)
863 				return (-1);
864 			log_info("%s: no valid local certificate found for %s",
865 			    SPI_SH(&sh, __func__), idstr);
866 			ca_store_certs_info(SPI_SH(&sh, __func__),
867 			    store->ca_certs);
868 			if (store->ca_pubkey.id_buf == NULL)
869 				return (-1);
870 			buf = ibuf_dup(store->ca_pubkey.id_buf);
871 			type = store->ca_pubkey.id_type;
872 			log_info("%s: using local public key of type %s",
873 			    SPI_SH(&sh, __func__),
874 			    print_map(type, ikev2_cert_map));
875 			break;
876 		}
877 
878 		subj = X509_get_subject_name(cert);
879 		if (subj == NULL)
880 			return (-1);
881 		subj_name = X509_NAME_oneline(subj, NULL, 0);
882 		if (subj_name == NULL)
883 			return (-1);
884 		log_debug("%s: found local certificate %s", __func__,
885 		    subj_name);
886 		OPENSSL_free(subj_name);
887 
888 		if ((buf = ca_x509_serialize(cert)) == NULL)
889 			return (-1);
890 		break;
891 	default:
892 		log_warnx("%s: unknown cert type requested",
893 		    SPI_SH(&sh, __func__));
894 		return (-1);
895 	}
896 
897 	ca_setcert(env, &sh, NULL, type,
898 	    ibuf_data(buf), ibuf_size(buf), PROC_IKEV2);
899 	ibuf_free(buf);
900 
901 	return (0);
902 }
903 
904 int
ca_getauth(struct iked * env,struct imsg * imsg)905 ca_getauth(struct iked *env, struct imsg *imsg)
906 {
907 	struct ca_store		*store = env->sc_priv;
908 	struct iked_sahdr	 sh;
909 	uint8_t			 method;
910 	uint8_t			*ptr;
911 	size_t			 len;
912 	unsigned int		 i;
913 	int			 ret = -1;
914 	struct iked_sa		 sa;
915 	struct iked_policy	 policy;
916 	struct iked_id		*id;
917 	struct ibuf		*authmsg;
918 
919 	ptr = (uint8_t *)imsg->data;
920 	len = IMSG_DATA_SIZE(imsg);
921 	i = sizeof(method) + sizeof(sh);
922 	if (len <= i)
923 		return (-1);
924 
925 	memcpy(&sh, ptr, sizeof(sh));
926 	memcpy(&method, ptr + sizeof(sh), sizeof(uint8_t));
927 	if (method == IKEV2_AUTH_SHARED_KEY_MIC)
928 		return (-1);
929 
930 	ptr += i;
931 	len -= i;
932 
933 	if ((authmsg = ibuf_new(ptr, len)) == NULL)
934 		return (-1);
935 
936 	/*
937 	 * Create fake SA and policy
938 	 */
939 	bzero(&sa, sizeof(sa));
940 	bzero(&policy, sizeof(policy));
941 	memcpy(&sa.sa_hdr, &sh, sizeof(sh));
942 	sa.sa_policy = &policy;
943 	if (sh.sh_initiator)
944 		id = &sa.sa_icert;
945 	else
946 		id = &sa.sa_rcert;
947 	memcpy(id, &store->ca_privkey, sizeof(*id));
948 	policy.pol_auth.auth_method = method == IKEV2_AUTH_SIG ?
949 	    method : store->ca_privkey_method;
950 
951 	if (ikev2_msg_authsign(env, &sa, &policy.pol_auth, authmsg) != 0) {
952 		log_debug("%s: AUTH sign failed", __func__);
953 		policy.pol_auth.auth_method = IKEV2_AUTH_NONE;
954 	}
955 
956 	ret = ca_setauth(env, &sa, sa.sa_localauth.id_buf, PROC_IKEV2);
957 
958 	ibuf_free(sa.sa_localauth.id_buf);
959 	sa.sa_localauth.id_buf = NULL;
960 	ibuf_free(authmsg);
961 
962 	return (ret);
963 }
964 
965 int
ca_reload(struct iked * env)966 ca_reload(struct iked *env)
967 {
968 	struct ca_store		*store = env->sc_priv;
969 	uint8_t			 md[EVP_MAX_MD_SIZE];
970 	char			 file[PATH_MAX];
971 	struct iovec		 iov[2];
972 	struct dirent		*entry;
973 	STACK_OF(X509_OBJECT)	*h;
974 	X509_OBJECT		*xo;
975 	X509			*x509;
976 	DIR			*dir;
977 	int			 i, iovcnt = 0;
978 	unsigned int		 len;
979 	X509_NAME		*subj;
980 	char			*subj_name;
981 
982 	/*
983 	 * Load CAs
984 	 */
985 	if ((dir = opendir(IKED_CA_DIR)) == NULL)
986 		return (-1);
987 
988 	while ((entry = readdir(dir)) != NULL) {
989 		if ((entry->d_type != DT_REG) &&
990 		    (entry->d_type != DT_LNK))
991 			continue;
992 
993 		if (snprintf(file, sizeof(file), "%s%s",
994 		    IKED_CA_DIR, entry->d_name) < 0)
995 			continue;
996 
997 		if (!X509_load_cert_file(store->ca_calookup, file,
998 		    X509_FILETYPE_PEM)) {
999 			log_warn("%s: failed to load ca file %s", __func__,
1000 			    entry->d_name);
1001 			ca_sslerror(__func__);
1002 			continue;
1003 		}
1004 		log_debug("%s: loaded ca file %s", __func__, entry->d_name);
1005 	}
1006 	closedir(dir);
1007 
1008 	/*
1009 	 * Load CRLs for the CAs
1010 	 */
1011 	if ((dir = opendir(IKED_CRL_DIR)) == NULL)
1012 		return (-1);
1013 
1014 	while ((entry = readdir(dir)) != NULL) {
1015 		if ((entry->d_type != DT_REG) &&
1016 		    (entry->d_type != DT_LNK))
1017 			continue;
1018 
1019 		if (snprintf(file, sizeof(file), "%s%s",
1020 		    IKED_CRL_DIR, entry->d_name) < 0)
1021 			continue;
1022 
1023 		if (!X509_load_crl_file(store->ca_calookup, file,
1024 		    X509_FILETYPE_PEM)) {
1025 			log_warn("%s: failed to load crl file %s", __func__,
1026 			    entry->d_name);
1027 			ca_sslerror(__func__);
1028 			continue;
1029 		}
1030 
1031 		/* Only enable CRL checks if we actually loaded a CRL */
1032 		X509_STORE_set_flags(store->ca_cas, X509_V_FLAG_CRL_CHECK);
1033 
1034 		log_debug("%s: loaded crl file %s", __func__, entry->d_name);
1035 	}
1036 	closedir(dir);
1037 
1038 	/*
1039 	 * Save CAs signatures for the IKEv2 CERTREQ
1040 	 */
1041 	ibuf_free(env->sc_certreq);
1042 	if ((env->sc_certreq = ibuf_new(NULL, 0)) == NULL)
1043 		return (-1);
1044 
1045 	h = X509_STORE_get0_objects(store->ca_cas);
1046 	for (i = 0; i < sk_X509_OBJECT_num(h); i++) {
1047 		xo = sk_X509_OBJECT_value(h, i);
1048 		if (X509_OBJECT_get_type(xo) != X509_LU_X509)
1049 			continue;
1050 
1051 		x509 = X509_OBJECT_get0_X509(xo);
1052 		len = sizeof(md);
1053 		ca_subjectpubkey_digest(x509, md, &len);
1054 		subj = X509_get_subject_name(x509);
1055 		if (subj == NULL)
1056 			return (-1);
1057 		subj_name = X509_NAME_oneline(subj, NULL, 0);
1058 		if (subj_name == NULL)
1059 			return (-1);
1060 		log_debug("%s: %s", __func__, subj_name);
1061 		OPENSSL_free(subj_name);
1062 
1063 		if (ibuf_add(env->sc_certreq, md, len) != 0) {
1064 			ibuf_free(env->sc_certreq);
1065 			env->sc_certreq = NULL;
1066 			return (-1);
1067 		}
1068 	}
1069 
1070 	if (ibuf_size(env->sc_certreq)) {
1071 		env->sc_certreqtype = IKEV2_CERT_X509_CERT;
1072 		iov[0].iov_base = &env->sc_certreqtype;
1073 		iov[0].iov_len = sizeof(env->sc_certreqtype);
1074 		iovcnt++;
1075 		iov[1].iov_base = ibuf_data(env->sc_certreq);
1076 		iov[1].iov_len = ibuf_size(env->sc_certreq);
1077 		iovcnt++;
1078 
1079 		log_debug("%s: loaded %zu ca certificate%s", __func__,
1080 		    ibuf_size(env->sc_certreq) / SHA_DIGEST_LENGTH,
1081 		    ibuf_size(env->sc_certreq) == SHA_DIGEST_LENGTH ?
1082 		    "" : "s");
1083 
1084 		(void)proc_composev(&env->sc_ps, PROC_IKEV2, IMSG_CERTREQ,
1085 		    iov, iovcnt);
1086 	}
1087 
1088 	/*
1089 	 * Load certificates
1090 	 */
1091 	if ((dir = opendir(IKED_CERT_DIR)) == NULL)
1092 		return (-1);
1093 
1094 	while ((entry = readdir(dir)) != NULL) {
1095 		if ((entry->d_type != DT_REG) &&
1096 		    (entry->d_type != DT_LNK))
1097 			continue;
1098 
1099 		if (snprintf(file, sizeof(file), "%s%s",
1100 		    IKED_CERT_DIR, entry->d_name) < 0)
1101 			continue;
1102 
1103 		if (!X509_load_cert_file(store->ca_certlookup, file,
1104 		    X509_FILETYPE_PEM)) {
1105 			log_warn("%s: failed to load cert file %s", __func__,
1106 			    entry->d_name);
1107 			ca_sslerror(__func__);
1108 			continue;
1109 		}
1110 		log_debug("%s: loaded cert file %s", __func__, entry->d_name);
1111 	}
1112 	closedir(dir);
1113 
1114 	h = X509_STORE_get0_objects(store->ca_certs);
1115 	for (i = 0; i < sk_X509_OBJECT_num(h); i++) {
1116 		xo = sk_X509_OBJECT_value(h, i);
1117 		if (X509_OBJECT_get_type(xo) != X509_LU_X509)
1118 			continue;
1119 
1120 		x509 = X509_OBJECT_get0_X509(xo);
1121 
1122 		(void)ca_validate_cert(env, NULL, x509, 0, NULL, NULL);
1123 	}
1124 
1125 	if (!env->sc_certreqtype)
1126 		env->sc_certreqtype = store->ca_pubkey.id_type;
1127 
1128 	log_debug("%s: local cert type %s", __func__,
1129 	    print_map(env->sc_certreqtype, ikev2_cert_map));
1130 
1131 	iov[0].iov_base = &env->sc_certreqtype;
1132 	iov[0].iov_len = sizeof(env->sc_certreqtype);
1133 	if (iovcnt == 0)
1134 		iovcnt++;
1135 	(void)proc_composev(&env->sc_ps, PROC_IKEV2, IMSG_CERTREQ, iov, iovcnt);
1136 
1137 	return (0);
1138 }
1139 
1140 X509 *
ca_by_subjectpubkey(X509_STORE * ctx,uint8_t * sig,size_t siglen)1141 ca_by_subjectpubkey(X509_STORE *ctx, uint8_t *sig, size_t siglen)
1142 {
1143 	STACK_OF(X509_OBJECT)	*h;
1144 	X509_OBJECT		*xo;
1145 	X509			*ca;
1146 	int			 i;
1147 	unsigned int		 len;
1148 	uint8_t			 md[EVP_MAX_MD_SIZE];
1149 
1150 	h = X509_STORE_get0_objects(ctx);
1151 
1152 	for (i = 0; i < sk_X509_OBJECT_num(h); i++) {
1153 		xo = sk_X509_OBJECT_value(h, i);
1154 		if (X509_OBJECT_get_type(xo) != X509_LU_X509)
1155 			continue;
1156 
1157 		ca = X509_OBJECT_get0_X509(xo);
1158 		len = sizeof(md);
1159 		ca_subjectpubkey_digest(ca, md, &len);
1160 
1161 		if (len == siglen && memcmp(md, sig, len) == 0)
1162 			return (ca);
1163 	}
1164 
1165 	return (NULL);
1166 }
1167 
1168 X509 *
ca_by_issuer(X509_STORE * ctx,X509_NAME * subject,struct iked_static_id * id)1169 ca_by_issuer(X509_STORE *ctx, X509_NAME *subject, struct iked_static_id *id)
1170 {
1171 	STACK_OF(X509_OBJECT)	*h;
1172 	X509_OBJECT		*xo;
1173 	X509			*cert;
1174 	int			 i;
1175 	X509_NAME		*issuer;
1176 
1177 	if (subject == NULL)
1178 		return (NULL);
1179 
1180 	h = X509_STORE_get0_objects(ctx);
1181 	for (i = 0; i < sk_X509_OBJECT_num(h); i++) {
1182 		xo = sk_X509_OBJECT_value(h, i);
1183 		if (X509_OBJECT_get_type(xo) != X509_LU_X509)
1184 			continue;
1185 
1186 		cert = X509_OBJECT_get0_X509(xo);
1187 		if ((issuer = X509_get_issuer_name(cert)) == NULL)
1188 			continue;
1189 		else if (X509_NAME_cmp(subject, issuer) == 0) {
1190 			switch (id->id_type) {
1191 			case IKEV2_ID_ASN1_DN:
1192 				if (ca_x509_subject_cmp(cert, id) == 0)
1193 					return (cert);
1194 				break;
1195 			default:
1196 				if (ca_x509_subjectaltname_cmp(cert, id) == 0)
1197 					return (cert);
1198 				break;
1199 			}
1200 		}
1201 	}
1202 
1203 	return (NULL);
1204 }
1205 
1206 X509 *
ca_by_subjectaltname(X509_STORE * ctx,struct iked_static_id * id)1207 ca_by_subjectaltname(X509_STORE *ctx, struct iked_static_id *id)
1208 {
1209 	STACK_OF(X509_OBJECT)	*h;
1210 	X509_OBJECT		*xo;
1211 	X509			*cert;
1212 	int			 i;
1213 
1214 	h = X509_STORE_get0_objects(ctx);
1215 	for (i = 0; i < sk_X509_OBJECT_num(h); i++) {
1216 		xo = sk_X509_OBJECT_value(h, i);
1217 		if (X509_OBJECT_get_type(xo) != X509_LU_X509)
1218 			continue;
1219 
1220 		cert = X509_OBJECT_get0_X509(xo);
1221 		switch (id->id_type) {
1222 		case IKEV2_ID_ASN1_DN:
1223 			if (ca_x509_subject_cmp(cert, id) == 0)
1224 				return (cert);
1225 			break;
1226 		default:
1227 			if (ca_x509_subjectaltname_cmp(cert, id) == 0)
1228 				return (cert);
1229 			break;
1230 		}
1231 	}
1232 
1233 	return (NULL);
1234 }
1235 
1236 void
ca_store_certs_info(const char * msg,X509_STORE * ctx)1237 ca_store_certs_info(const char *msg, X509_STORE *ctx)
1238 {
1239 	STACK_OF(X509_OBJECT)	*h;
1240 	X509_OBJECT		*xo;
1241 	X509			*cert;
1242 	int			 i;
1243 
1244 	h = X509_STORE_get0_objects(ctx);
1245 	for (i = 0; i < sk_X509_OBJECT_num(h); i++) {
1246 		xo = sk_X509_OBJECT_value(h, i);
1247 		if (X509_OBJECT_get_type(xo) != X509_LU_X509)
1248 			continue;
1249 		cert = X509_OBJECT_get0_X509(xo);
1250 		ca_cert_info(msg, cert);
1251 	}
1252 }
1253 
1254 int
ca_cert_local(struct iked * env,X509 * cert)1255 ca_cert_local(struct iked *env, X509  *cert)
1256 {
1257 	struct ca_store	*store = env->sc_priv;
1258 	EVP_PKEY	*certkey = NULL, *localpub = NULL;
1259 	int		 ret = 0;
1260 
1261 	if ((localpub = ca_bytes_to_pkey(ibuf_data(store->ca_pubkey.id_buf),
1262 	    ibuf_size(store->ca_pubkey.id_buf))) == NULL)
1263 		goto done;
1264 
1265 	if ((certkey = X509_get0_pubkey(cert)) == NULL) {
1266 		log_info("%s: no public key in cert", __func__);
1267 		goto done;
1268 	}
1269 
1270 	if (EVP_PKEY_cmp(certkey, localpub) != 1) {
1271 		log_debug("%s: certificate key mismatch", __func__);
1272 		goto done;
1273 	}
1274 
1275 	ret = 1;
1276  done:
1277 	EVP_PKEY_free(localpub);
1278 
1279 	return (ret);
1280 }
1281 
1282 void
ca_cert_info(const char * msg,X509 * cert)1283 ca_cert_info(const char *msg, X509 *cert)
1284 {
1285 	ASN1_INTEGER	*asn1_serial;
1286 	BUF_MEM		*memptr;
1287 	BIO		*rawserial = NULL;
1288 	char		 buf[BUFSIZ];
1289 	X509_NAME	*name;
1290 
1291 	if ((asn1_serial = X509_get_serialNumber(cert)) == NULL ||
1292 	    (rawserial = BIO_new(BIO_s_mem())) == NULL ||
1293 	    i2a_ASN1_INTEGER(rawserial, asn1_serial) <= 0)
1294 		goto out;
1295 
1296 	name = X509_get_issuer_name(cert);
1297 	if (name != NULL &&
1298 	    X509_NAME_oneline(name, buf, sizeof(buf)))
1299 		log_info("%s: issuer: %s", msg, buf);
1300 	BIO_get_mem_ptr(rawserial, &memptr);
1301 	if (memptr->data != NULL && memptr->length < INT32_MAX)
1302 		log_info("%s: serial: %.*s", msg, (int)memptr->length,
1303 		    memptr->data);
1304 	name = X509_get_subject_name(cert);
1305 	if (name != NULL &&
1306 	    X509_NAME_oneline(name, buf, sizeof(buf)))
1307 		log_info("%s: subject: %s", msg, buf);
1308 	ca_x509_subjectaltname_log(cert, msg);
1309 out:
1310 	BIO_free(rawserial);
1311 }
1312 
1313 int
ca_subjectpubkey_digest(X509 * x509,uint8_t * md,unsigned int * size)1314 ca_subjectpubkey_digest(X509 *x509, uint8_t *md, unsigned int *size)
1315 {
1316 	EVP_PKEY	*pkey;
1317 	uint8_t		*buf = NULL;
1318 	int		 buflen;
1319 
1320 	if (*size < SHA_DIGEST_LENGTH)
1321 		return (-1);
1322 
1323 	/*
1324 	 * Generate a SHA-1 digest of the Subject Public Key Info
1325 	 * element in the X.509 certificate, an ASN.1 sequence
1326 	 * that includes the public key type (eg. RSA) and the
1327 	 * public key value (see 3.7 of RFC7296).
1328 	 */
1329 	if ((pkey = X509_get0_pubkey(x509)) == NULL)
1330 		return (-1);
1331 	buflen = i2d_PUBKEY(pkey, &buf);
1332 	if (buflen == 0)
1333 		return (-1);
1334 	if (!EVP_Digest(buf, buflen, md, size, EVP_sha1(), NULL)) {
1335 		OPENSSL_free(buf);
1336 		return (-1);
1337 	}
1338 	OPENSSL_free(buf);
1339 
1340 	return (0);
1341 }
1342 
1343 void
ca_store_info(struct iked * env,struct imsg * imsg,const char * msg,X509_STORE * ctx)1344 ca_store_info(struct iked *env, struct imsg *imsg, const char *msg, X509_STORE *ctx)
1345 {
1346 	STACK_OF(X509_OBJECT)	*h;
1347 	X509_OBJECT		*xo;
1348 	X509			*cert;
1349 	int			 i;
1350 	X509_NAME		*subject;
1351 	char			*name;
1352 	char			*buf;
1353 	int			 buflen;
1354 
1355 	h = X509_STORE_get0_objects(ctx);
1356 	for (i = 0; i < sk_X509_OBJECT_num(h); i++) {
1357 		xo = sk_X509_OBJECT_value(h, i);
1358 		if (X509_OBJECT_get_type(xo) != X509_LU_X509)
1359 			continue;
1360 		cert = X509_OBJECT_get0_X509(xo);
1361 		if ((subject = X509_get_subject_name(cert)) == NULL ||
1362 		    (name = X509_NAME_oneline(subject, NULL, 0)) == NULL)
1363 			continue;
1364 		buflen = asprintf(&buf, "%s: %s\n", msg, name);
1365 		OPENSSL_free(name);
1366 		if (buflen == -1)
1367 			continue;
1368 		proc_compose_imsg(&env->sc_ps, PROC_CONTROL, -1,
1369 		    IMSG_CTL_SHOW_CERTSTORE, imsg->hdr.peerid,
1370 		    -1, buf, buflen + 1);
1371 		free(buf);
1372 	}
1373 }
1374 
1375 struct ibuf *
ca_x509_serialize(X509 * x509)1376 ca_x509_serialize(X509 *x509)
1377 {
1378 	long		 len;
1379 	struct ibuf	*buf;
1380 	uint8_t		*d = NULL;
1381 	BIO		*out;
1382 
1383 	if ((out = BIO_new(BIO_s_mem())) == NULL)
1384 		return (NULL);
1385 	if (!i2d_X509_bio(out, x509)) {
1386 		BIO_free(out);
1387 		return (NULL);
1388 	}
1389 
1390 	len = BIO_get_mem_data(out, &d);
1391 	buf = ibuf_new(d, len);
1392 	BIO_free(out);
1393 
1394 	return (buf);
1395 }
1396 
1397 int
ca_pubkey_serialize(EVP_PKEY * key,struct iked_id * id)1398 ca_pubkey_serialize(EVP_PKEY *key, struct iked_id *id)
1399 {
1400 	RSA		*rsa = NULL;
1401 	EC_KEY		*ec = NULL;
1402 	uint8_t		*d;
1403 	int		 len = 0;
1404 	int		 ret = -1;
1405 
1406 	switch (EVP_PKEY_id(key)) {
1407 	case EVP_PKEY_RSA:
1408 		id->id_type = 0;
1409 		id->id_offset = 0;
1410 		ibuf_free(id->id_buf);
1411 		id->id_buf = NULL;
1412 
1413 		if ((rsa = EVP_PKEY_get0_RSA(key)) == NULL)
1414 			goto done;
1415 		if ((len = i2d_RSAPublicKey(rsa, NULL)) <= 0)
1416 			goto done;
1417 		if ((id->id_buf = ibuf_new(NULL, len)) == NULL)
1418 			goto done;
1419 
1420 		d = ibuf_data(id->id_buf);
1421 		if (i2d_RSAPublicKey(rsa, &d) != len) {
1422 			ibuf_free(id->id_buf);
1423 			id->id_buf = NULL;
1424 			goto done;
1425 		}
1426 
1427 		id->id_type = IKEV2_CERT_RSA_KEY;
1428 		break;
1429 	case EVP_PKEY_EC:
1430 		id->id_type = 0;
1431 		id->id_offset = 0;
1432 		ibuf_free(id->id_buf);
1433 		id->id_buf = NULL;
1434 
1435 		if ((ec = EVP_PKEY_get0_EC_KEY(key)) == NULL)
1436 			goto done;
1437 		if ((len = i2d_EC_PUBKEY(ec, NULL)) <= 0)
1438 			goto done;
1439 		if ((id->id_buf = ibuf_new(NULL, len)) == NULL)
1440 			goto done;
1441 
1442 		d = ibuf_data(id->id_buf);
1443 		if (i2d_EC_PUBKEY(ec, &d) != len) {
1444 			ibuf_free(id->id_buf);
1445 			id->id_buf = NULL;
1446 			goto done;
1447 		}
1448 
1449 		id->id_type = IKEV2_CERT_ECDSA;
1450 		break;
1451 	default:
1452 		log_debug("%s: unsupported key type %d", __func__,
1453 		    EVP_PKEY_id(key));
1454 		return (-1);
1455 	}
1456 
1457 	log_debug("%s: type %s length %d", __func__,
1458 	    print_map(id->id_type, ikev2_cert_map), len);
1459 
1460 	ret = 0;
1461  done:
1462 
1463 	return (ret);
1464 }
1465 
1466 int
ca_privkey_serialize(EVP_PKEY * key,struct iked_id * id)1467 ca_privkey_serialize(EVP_PKEY *key, struct iked_id *id)
1468 {
1469 	RSA		*rsa = NULL;
1470 	EC_KEY		*ec = NULL;
1471 	uint8_t		*d;
1472 	int		 len = 0;
1473 	int		 ret = -1;
1474 
1475 	switch (EVP_PKEY_id(key)) {
1476 	case EVP_PKEY_RSA:
1477 		id->id_type = 0;
1478 		id->id_offset = 0;
1479 		ibuf_free(id->id_buf);
1480 		id->id_buf = NULL;
1481 
1482 		if ((rsa = EVP_PKEY_get0_RSA(key)) == NULL)
1483 			goto done;
1484 		if ((len = i2d_RSAPrivateKey(rsa, NULL)) <= 0)
1485 			goto done;
1486 		if ((id->id_buf = ibuf_new(NULL, len)) == NULL)
1487 			goto done;
1488 
1489 		d = ibuf_data(id->id_buf);
1490 		if (i2d_RSAPrivateKey(rsa, &d) != len) {
1491 			ibuf_free(id->id_buf);
1492 			id->id_buf = NULL;
1493 			goto done;
1494 		}
1495 
1496 		id->id_type = IKEV2_CERT_RSA_KEY;
1497 		break;
1498 	case EVP_PKEY_EC:
1499 		id->id_type = 0;
1500 		id->id_offset = 0;
1501 		ibuf_free(id->id_buf);
1502 		id->id_buf = NULL;
1503 
1504 		if ((ec = EVP_PKEY_get0_EC_KEY(key)) == NULL)
1505 			goto done;
1506 		if ((len = i2d_ECPrivateKey(ec, NULL)) <= 0)
1507 			goto done;
1508 		if ((id->id_buf = ibuf_new(NULL, len)) == NULL)
1509 			goto done;
1510 
1511 		d = ibuf_data(id->id_buf);
1512 		if (i2d_ECPrivateKey(ec, &d) != len) {
1513 			ibuf_free(id->id_buf);
1514 			id->id_buf = NULL;
1515 			goto done;
1516 		}
1517 
1518 		id->id_type = IKEV2_CERT_ECDSA;
1519 		break;
1520 	default:
1521 		log_debug("%s: unsupported key type %d", __func__,
1522 		    EVP_PKEY_id(key));
1523 		return (-1);
1524 	}
1525 
1526 	log_debug("%s: type %s length %d", __func__,
1527 	    print_map(id->id_type, ikev2_cert_map), len);
1528 
1529 	ret = 0;
1530  done:
1531 
1532 	return (ret);
1533 }
1534 
1535 EVP_PKEY *
ca_bytes_to_pkey(uint8_t * data,size_t len)1536 ca_bytes_to_pkey(uint8_t *data, size_t len)
1537 {
1538 	BIO		*rawcert = NULL;
1539 	EVP_PKEY	*localkey = NULL, *out = NULL;
1540 	RSA		*localrsa = NULL;
1541 	EC_KEY		*localec = NULL;
1542 
1543 	if ((rawcert = BIO_new_mem_buf(data, len)) == NULL)
1544 		goto done;
1545 
1546 	if ((localkey = EVP_PKEY_new()) == NULL)
1547 		goto sslerr;
1548 
1549 	if ((localrsa = d2i_RSAPublicKey_bio(rawcert, NULL))) {
1550 		if (EVP_PKEY_set1_RSA(localkey, localrsa) != 1)
1551 			goto sslerr;
1552 	} else if (BIO_reset(rawcert) == 1 &&
1553 	    (localec = d2i_EC_PUBKEY_bio(rawcert, NULL))) {
1554 		if (EVP_PKEY_set1_EC_KEY(localkey, localec) != 1)
1555 			goto sslerr;
1556 	} else {
1557 		log_info("%s: unknown public key type", __func__);
1558 		goto done;
1559 	}
1560 
1561 	out = localkey;
1562 	localkey = NULL;
1563 
1564  sslerr:
1565 	if (out == NULL)
1566 		ca_sslerror(__func__);
1567  done:
1568 	EVP_PKEY_free(localkey);
1569 	RSA_free(localrsa);
1570 	EC_KEY_free(localec);
1571 	BIO_free(rawcert);
1572 
1573 	return (out);
1574 }
1575 
1576 int
ca_privkey_to_method(struct iked_id * privkey)1577 ca_privkey_to_method(struct iked_id *privkey)
1578 {
1579 	BIO		*rawcert = NULL;
1580 	EC_KEY		*ec = NULL;
1581 	const EC_GROUP	*group = NULL;
1582 	uint8_t	 method = IKEV2_AUTH_NONE;
1583 
1584 	switch (privkey->id_type) {
1585 	case IKEV2_CERT_RSA_KEY:
1586 		method = IKEV2_AUTH_RSA_SIG;
1587 		break;
1588 	case IKEV2_CERT_ECDSA:
1589 		if ((rawcert = BIO_new_mem_buf(ibuf_data(privkey->id_buf),
1590 		    ibuf_size(privkey->id_buf))) == NULL)
1591 			goto out;
1592 		if ((ec = d2i_ECPrivateKey_bio(rawcert, NULL)) == NULL)
1593 			goto out;
1594 		if ((group = EC_KEY_get0_group(ec)) == NULL)
1595 			goto out;
1596 		switch (EC_GROUP_get_degree(group)) {
1597 		case 256:
1598 			method = IKEV2_AUTH_ECDSA_256;
1599 			break;
1600 		case 384:
1601 			method = IKEV2_AUTH_ECDSA_384;
1602 			break;
1603 		case 521:
1604 			method = IKEV2_AUTH_ECDSA_521;
1605 			break;
1606 		}
1607 	}
1608 
1609 	log_debug("%s: type %s method %s", __func__,
1610 	    print_map(privkey->id_type, ikev2_cert_map),
1611 	    print_map(method, ikev2_auth_map));
1612 
1613  out:
1614 	EC_KEY_free(ec);
1615 	BIO_free(rawcert);
1616 	return (method);
1617 }
1618 
1619 /*
1620  * Return dynamically allocated buffer containing certificate name.
1621  * The resulting buffer must be freed with OpenSSL_free().
1622  */
1623 char *
ca_asn1_name(uint8_t * asn1,size_t len)1624 ca_asn1_name(uint8_t *asn1, size_t len)
1625 {
1626 	X509_NAME	*name = NULL;
1627 	char		*str = NULL;
1628 	const uint8_t	*p;
1629 
1630 	p = asn1;
1631 	if ((name = d2i_X509_NAME(NULL, &p, len)) == NULL)
1632 		return (NULL);
1633 	str = X509_NAME_oneline(name, NULL, 0);
1634 	X509_NAME_free(name);
1635 
1636 	return (str);
1637 }
1638 
1639 /*
1640  * Copy 'src' to 'dst' until 'marker' is found while unescaping '\'
1641  * characters. The return value tells the caller where to continue
1642  * parsing (might be the end of the string) or NULL on error.
1643  */
1644 static char *
ca_x509_name_unescape(char * src,char * dst,char marker)1645 ca_x509_name_unescape(char *src, char *dst, char marker)
1646 {
1647 	while (*src) {
1648 		if (*src == marker) {
1649 			src++;
1650 			break;
1651 		}
1652 		if (*src == '\\') {
1653 			src++;
1654 			if (!*src) {
1655 				log_warnx("%s: '\\' at end of string",
1656 				    __func__);
1657 				*dst = '\0';
1658 				return (NULL);
1659 			}
1660 		}
1661 		*dst++ = *src++;
1662 	}
1663 	*dst = '\0';
1664 	return (src);
1665 }
1666 /*
1667  * Parse an X509 subject name where 'subject' is in the format
1668  *    /type0=value0/type1=value1/type2=...
1669  * where characters may be escaped by '\'.
1670  * See lib/libssl/src/apps/apps.c:parse_name()
1671  */
1672 void *
ca_x509_name_parse(char * subject)1673 ca_x509_name_parse(char *subject)
1674 {
1675 	char		*cp, *value = NULL, *type = NULL;
1676 	size_t		 maxlen;
1677 	X509_NAME	*name = NULL;
1678 
1679 	if (*subject != '/') {
1680 		log_warnx("%s: leading '/' missing in '%s'", __func__, subject);
1681 		goto err;
1682 	}
1683 
1684 	/* length of subject is upper bound for unescaped type/value */
1685 	maxlen = strlen(subject) + 1;
1686 
1687 	if ((type = calloc(1, maxlen)) == NULL ||
1688 	    (value = calloc(1, maxlen)) == NULL ||
1689 	    (name = X509_NAME_new()) == NULL)
1690 		goto err;
1691 
1692 	cp = subject + 1;
1693 	while (*cp) {
1694 		/* unescape type, terminated by '=' */
1695 		cp = ca_x509_name_unescape(cp, type, '=');
1696 		if (cp == NULL) {
1697 			log_warnx("%s: could not parse type", __func__);
1698 			goto err;
1699 		}
1700 		if (!*cp) {
1701 			log_warnx("%s: missing value", __func__);
1702 			goto err;
1703 		}
1704 		/* unescape value, terminated by '/' */
1705 		cp = ca_x509_name_unescape(cp, value, '/');
1706 		if (cp == NULL) {
1707 			log_warnx("%s: could not parse value", __func__);
1708 			goto err;
1709 		}
1710 		if (!*type || !*value) {
1711 			log_warnx("%s: empty type or value", __func__);
1712 			goto err;
1713 		}
1714 		log_debug("%s: setting '%s' to '%s'", __func__, type, value);
1715 		if (!X509_NAME_add_entry_by_txt(name, type, MBSTRING_ASC,
1716 		    value, -1, -1, 0)) {
1717 			log_warnx("%s: setting '%s' to '%s' failed", __func__,
1718 			    type, value);
1719 			ca_sslerror(__func__);
1720 			goto err;
1721 		}
1722 	}
1723 	free(type);
1724 	free(value);
1725 	return (name);
1726 
1727 err:
1728 	X509_NAME_free(name);
1729 	free(type);
1730 	free(value);
1731 	return (NULL);
1732 }
1733 
1734 int
ca_validate_pubkey(struct iked * env,struct iked_static_id * id,void * data,size_t len,struct iked_id * out)1735 ca_validate_pubkey(struct iked *env, struct iked_static_id *id,
1736     void *data, size_t len, struct iked_id *out)
1737 {
1738 	RSA		*localrsa = NULL;
1739 	EVP_PKEY	*peerkey = NULL, *localkey = NULL;
1740 	int		 ret = -1;
1741 	FILE		*fp = NULL;
1742 	char		 idstr[IKED_ID_SIZE];
1743 	char		 file[PATH_MAX];
1744 	struct iked_id	 idp;
1745 
1746 	switch (id->id_type) {
1747 	case IKEV2_ID_IPV4:
1748 	case IKEV2_ID_FQDN:
1749 	case IKEV2_ID_UFQDN:
1750 	case IKEV2_ID_IPV6:
1751 		break;
1752 	default:
1753 		/* Some types like ASN1_DN will not be mapped to file names */
1754 		log_debug("%s: unsupported public key type %s",
1755 		    __func__, print_map(id->id_type, ikev2_id_map));
1756 		return (-1);
1757 	}
1758 
1759 	bzero(&idp, sizeof(idp));
1760 	if ((idp.id_buf = ibuf_new(id->id_data, id->id_length)) == NULL)
1761 		goto done;
1762 
1763 	idp.id_type = id->id_type;
1764 	idp.id_offset = id->id_offset;
1765 	if (ikev2_print_id(&idp, idstr, sizeof(idstr)) == -1)
1766 		goto done;
1767 
1768 	if (len == 0 && data) {
1769 		/* Data is already an public key */
1770 		peerkey = (EVP_PKEY *)data;
1771 	}
1772 	if (len > 0) {
1773 		if ((peerkey = ca_bytes_to_pkey(data, len)) == NULL)
1774 			goto done;
1775 	}
1776 
1777 	lc_idtype(idstr);
1778 	if (strlcpy(file, IKED_PUBKEY_DIR, sizeof(file)) >= sizeof(file) ||
1779 	    strlcat(file, idstr, sizeof(file)) >= sizeof(file)) {
1780 		log_debug("%s: public key id too long %s", __func__, idstr);
1781 		goto done;
1782 	}
1783 
1784 	if ((fp = fopen(file, "r")) == NULL) {
1785 		/* Log to debug when called from ca_validate_cert */
1786 		logit(len == 0 ? LOG_DEBUG : LOG_INFO,
1787 		    "%s: could not open public key %s", __func__, file);
1788 		goto done;
1789 	}
1790 	localkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL);
1791 	if (localkey == NULL) {
1792 		/* reading PKCS #8 failed, try PEM RSA */
1793 		rewind(fp);
1794 		localrsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);
1795 		fclose(fp);
1796 		if (localrsa == NULL)
1797 			goto sslerr;
1798 		if ((localkey = EVP_PKEY_new()) == NULL)
1799 			goto sslerr;
1800 		if (!EVP_PKEY_set1_RSA(localkey, localrsa))
1801 			goto sslerr;
1802 	} else {
1803 		fclose(fp);
1804 	}
1805 	if (localkey == NULL)
1806 		goto sslerr;
1807 
1808 	if (peerkey && EVP_PKEY_cmp(peerkey, localkey) != 1) {
1809 		log_debug("%s: public key does not match %s", __func__, file);
1810 		goto done;
1811 	}
1812 
1813 	log_debug("%s: valid public key in file %s", __func__, file);
1814 
1815 	if (out && ca_pubkey_serialize(localkey, out))
1816 		goto done;
1817 
1818 	ret = 0;
1819  sslerr:
1820 	if (ret != 0)
1821 		ca_sslerror(__func__);
1822  done:
1823 	ibuf_free(idp.id_buf);
1824 	EVP_PKEY_free(localkey);
1825 	RSA_free(localrsa);
1826 	if (len > 0)
1827 		EVP_PKEY_free(peerkey);
1828 
1829 	return (ret);
1830 }
1831 
1832 int
ca_validate_cert(struct iked * env,struct iked_static_id * id,void * data,size_t len,STACK_OF (X509)* untrusted,X509 ** issuerp)1833 ca_validate_cert(struct iked *env, struct iked_static_id *id,
1834     void *data, size_t len, STACK_OF(X509) *untrusted, X509 **issuerp)
1835 {
1836 	struct ca_store		*store = env->sc_priv;
1837 	X509_STORE_CTX		*csc = NULL;
1838 	X509_VERIFY_PARAM	*param;
1839 	BIO			*rawcert = NULL;
1840 	X509			*cert = NULL;
1841 	EVP_PKEY		*pkey;
1842 	int			 ret = -1, result, error;
1843 	const char		*errstr = "failed";
1844 	X509_NAME		*subj;
1845 	char			*subj_name;
1846 
1847 	if (issuerp)
1848 		*issuerp = NULL;
1849 	if (len == 0) {
1850 		/* Data is already an X509 certificate */
1851 		cert = (X509 *)data;
1852 	} else {
1853 		/* Convert data to X509 certificate */
1854 		if ((rawcert = BIO_new_mem_buf(data, len)) == NULL)
1855 			goto done;
1856 		if ((cert = d2i_X509_bio(rawcert, NULL)) == NULL)
1857 			goto done;
1858 	}
1859 
1860 	/* Certificate needs a valid subjectName */
1861 	if (X509_get_subject_name(cert) == NULL) {
1862 		errstr = "invalid subject";
1863 		goto done;
1864 	}
1865 
1866 	if (id != NULL) {
1867 		if ((pkey = X509_get0_pubkey(cert)) == NULL) {
1868 			errstr = "no public key in cert";
1869 			goto done;
1870 		}
1871 		ret = ca_validate_pubkey(env, id, pkey, 0, NULL);
1872 		if (ret == 0) {
1873 			errstr = "in public key file, ok";
1874 			goto done;
1875 		}
1876 
1877 		switch (id->id_type) {
1878 		case IKEV2_ID_ASN1_DN:
1879 			if (ca_x509_subject_cmp(cert, id) < 0) {
1880 				errstr = "ASN1_DN identifier mismatch";
1881 				goto done;
1882 			}
1883 			break;
1884 		default:
1885 			if (ca_x509_subjectaltname_cmp(cert, id) != 0) {
1886 				errstr = "invalid subjectAltName extension";
1887 				goto done;
1888 			}
1889 			break;
1890 		}
1891 	}
1892 
1893 	csc = X509_STORE_CTX_new();
1894 	if (csc == NULL) {
1895 		errstr = "failed to alloc csc";
1896 		goto done;
1897 	}
1898 	X509_STORE_CTX_init(csc, store->ca_cas, cert, untrusted);
1899 	param = X509_STORE_get0_param(store->ca_cas);
1900 	if (X509_VERIFY_PARAM_get_flags(param) & X509_V_FLAG_CRL_CHECK) {
1901 		X509_STORE_CTX_set_flags(csc, X509_V_FLAG_CRL_CHECK);
1902 		X509_STORE_CTX_set_flags(csc, X509_V_FLAG_CRL_CHECK_ALL);
1903 	}
1904 	if (env->sc_cert_partial_chain)
1905 		X509_STORE_CTX_set_flags(csc, X509_V_FLAG_PARTIAL_CHAIN);
1906 
1907 	result = X509_verify_cert(csc);
1908 	error = X509_STORE_CTX_get_error(csc);
1909 	if (error == 0 && issuerp) {
1910 		if (X509_STORE_CTX_get1_issuer(issuerp, csc, cert) != 1) {
1911 			log_debug("%s: cannot get issuer", __func__);
1912 			*issuerp = NULL;
1913 		}
1914 	}
1915 	X509_STORE_CTX_cleanup(csc);
1916 	if (error != 0) {
1917 		errstr = X509_verify_cert_error_string(error);
1918 		goto done;
1919 	}
1920 
1921 	if (!result) {
1922 		/* XXX should we accept self-signed certificates? */
1923 		errstr = "rejecting self-signed certificate";
1924 		goto done;
1925 	}
1926 
1927 	/* Success */
1928 	ret = 0;
1929 	errstr = "ok";
1930 
1931  done:
1932 	if (cert != NULL) {
1933 		subj = X509_get_subject_name(cert);
1934 		if (subj == NULL)
1935 			goto err;
1936 		subj_name = X509_NAME_oneline(subj, NULL, 0);
1937 		if (subj_name == NULL)
1938 			goto err;
1939 		log_debug("%s: %s %.100s", __func__, subj_name, errstr);
1940 		OPENSSL_free(subj_name);
1941 	}
1942  err:
1943 
1944 	if (len > 0)
1945 		X509_free(cert);
1946 	BIO_free(rawcert);
1947 	X509_STORE_CTX_free(csc);
1948 
1949 	return (ret);
1950 }
1951 
1952 /* check if subject from cert matches the id */
1953 int
ca_x509_subject_cmp(X509 * cert,struct iked_static_id * id)1954 ca_x509_subject_cmp(X509 *cert, struct iked_static_id *id)
1955 {
1956 	X509_NAME	*subject, *idname = NULL;
1957 	const uint8_t	*idptr;
1958 	size_t		 idlen;
1959 	int		 ret = -1;
1960 
1961 	if (id->id_type != IKEV2_ID_ASN1_DN)
1962 		return (-1);
1963 	if ((subject = X509_get_subject_name(cert)) == NULL)
1964 		return (-1);
1965 	if (id->id_length <= id->id_offset)
1966 		return (-1);
1967 	idlen = id->id_length - id->id_offset;
1968 	idptr = id->id_data + id->id_offset;
1969 	if ((idname = d2i_X509_NAME(NULL, &idptr, idlen)) == NULL)
1970 		return (-1);
1971 	if (X509_NAME_cmp(subject, idname) == 0)
1972 		ret = 0;
1973 	X509_NAME_free(idname);
1974 	return (ret);
1975 }
1976 
1977 #define MODE_ALT_LOG	1
1978 #define MODE_ALT_GET	2
1979 #define MODE_ALT_CMP	3
1980 int
ca_x509_subjectaltname_do(X509 * cert,int mode,const char * logmsg,struct iked_static_id * id,struct iked_id * retid)1981 ca_x509_subjectaltname_do(X509 *cert, int mode, const char *logmsg,
1982     struct iked_static_id *id, struct iked_id *retid)
1983 {
1984 	STACK_OF(GENERAL_NAME) *stack = NULL;
1985 	GENERAL_NAME *entry;
1986 	ASN1_STRING *cstr;
1987 	char idstr[IKED_ID_SIZE];
1988 	int idx, ret, i, type, len;
1989 	const uint8_t *data;
1990 
1991 	ret = -1;
1992 	idx = -1;
1993 	while ((stack = X509_get_ext_d2i(cert, NID_subject_alt_name,
1994 	    NULL, &idx)) != NULL) {
1995 		for (i = 0; i < sk_GENERAL_NAME_num(stack); i++) {
1996 			entry = sk_GENERAL_NAME_value(stack, i);
1997 			switch (entry->type) {
1998 			case GEN_DNS:
1999 				cstr = entry->d.dNSName;
2000 				if (ASN1_STRING_type(cstr) != V_ASN1_IA5STRING)
2001 					continue;
2002 				type = IKEV2_ID_FQDN;
2003 				break;
2004 			case GEN_EMAIL:
2005 				cstr = entry->d.rfc822Name;
2006 				if (ASN1_STRING_type(cstr) != V_ASN1_IA5STRING)
2007 					continue;
2008 				type = IKEV2_ID_UFQDN;
2009 				break;
2010 			case GEN_IPADD:
2011 				cstr = entry->d.iPAddress;
2012 				switch (ASN1_STRING_length(cstr)) {
2013 				case 4:
2014 					type = IKEV2_ID_IPV4;
2015 					break;
2016 				case 16:
2017 					type = IKEV2_ID_IPV6;
2018 					break;
2019 				default:
2020 					log_debug("%s: invalid subjectAltName"
2021 					   " IP address", __func__);
2022 					continue;
2023 				}
2024 				break;
2025 			default:
2026 				continue;
2027 			}
2028 			len = ASN1_STRING_length(cstr);
2029 			data = ASN1_STRING_get0_data(cstr);
2030 			if (mode == MODE_ALT_LOG) {
2031 				struct iked_id sanid;
2032 
2033 				bzero(&sanid, sizeof(sanid));
2034 				sanid.id_offset = 0;
2035 				sanid.id_type = type;
2036 				if ((sanid.id_buf = ibuf_new(data, len))
2037 				    == NULL) {
2038 					log_debug("%s: failed to get id buffer",
2039 					    __func__);
2040 					continue;
2041 				}
2042 				ikev2_print_id(&sanid, idstr, sizeof(idstr));
2043 				log_info("%s: altname: %s", logmsg, idstr);
2044 				ibuf_free(sanid.id_buf);
2045 				sanid.id_buf = NULL;
2046 			}
2047 			/* Compare length and data */
2048 			if (mode == MODE_ALT_CMP) {
2049 				if (type == id->id_type &&
2050 				    (len == (id->id_length - id->id_offset)) &&
2051 				    (memcmp(id->id_data + id->id_offset,
2052 				    data, len)) == 0) {
2053 					ret = 0;
2054 					break;
2055 				}
2056 			}
2057 			/* Get first ID */
2058 			if (mode == MODE_ALT_GET) {
2059 				ibuf_free(retid->id_buf);
2060 				if ((retid->id_buf = ibuf_new(data, len)) == NULL) {
2061 					log_debug("%s: failed to get id buffer",
2062 					    __func__);
2063 					ret = -2;
2064 					break;
2065 				}
2066 				retid->id_offset = 0;
2067 				ikev2_print_id(retid, idstr, sizeof(idstr));
2068 				log_debug("%s: %s", __func__, idstr);
2069 				ret = 0;
2070 				break;
2071 			}
2072 		}
2073 		sk_GENERAL_NAME_pop_free(stack, GENERAL_NAME_free);
2074 		if (ret != -1)
2075 			break;
2076 	}
2077 	if (idx == -1)
2078 		log_debug("%s: did not find subjectAltName in certificate",
2079 		    __func__);
2080 	return ret;
2081 }
2082 
2083 int
ca_x509_subjectaltname_log(X509 * cert,const char * logmsg)2084 ca_x509_subjectaltname_log(X509 *cert, const char *logmsg)
2085 {
2086 	return ca_x509_subjectaltname_do(cert, MODE_ALT_LOG, logmsg, NULL, NULL);
2087 }
2088 
2089 int
ca_x509_subjectaltname_cmp(X509 * cert,struct iked_static_id * id)2090 ca_x509_subjectaltname_cmp(X509 *cert, struct iked_static_id *id)
2091 {
2092 	return ca_x509_subjectaltname_do(cert, MODE_ALT_CMP, NULL, id, NULL);
2093 }
2094 
2095 int
ca_x509_subjectaltname_get(X509 * cert,struct iked_id * retid)2096 ca_x509_subjectaltname_get(X509 *cert, struct iked_id *retid)
2097 {
2098 	return ca_x509_subjectaltname_do(cert, MODE_ALT_GET, NULL, NULL, retid);
2099 }
2100 
2101 void
ca_sslerror(const char * caller)2102 ca_sslerror(const char *caller)
2103 {
2104 	unsigned long	 error;
2105 
2106 	while ((error = ERR_get_error()) != 0)
2107 		log_warnx("%s: %s: %.100s", __func__, caller,
2108 		    ERR_error_string(error, NULL));
2109 }
2110