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