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