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