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