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