xref: /openbsd-src/sbin/iked/ikev2.c (revision 1a8dbaac879b9f3335ad7fb25429ce63ac1d6bac)
1 /*	$OpenBSD: ikev2.c,v 1.267 2020/10/09 08:59:15 tobhe Exp $	*/
2 
3 /*
4  * Copyright (c) 2019 Tobias Heider <tobias.heider@stusta.de>
5  * Copyright (c) 2010-2013 Reyk Floeter <reyk@openbsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/param.h>	/* roundup */
21 #include <sys/queue.h>
22 #include <sys/socket.h>
23 #include <sys/uio.h>
24 
25 #include <netinet/in.h>
26 #include <netinet/ip_ipsp.h>
27 #include <arpa/inet.h>
28 
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <syslog.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <signal.h>
35 #include <errno.h>
36 #include <err.h>
37 #include <event.h>
38 
39 #include <openssl/sha.h>
40 #include <openssl/evp.h>
41 #include <openssl/x509.h>
42 
43 #include "iked.h"
44 #include "ikev2.h"
45 #include "eap.h"
46 #include "dh.h"
47 #include "chap_ms.h"
48 
49 void	 ikev2_info(struct iked *, int);
50 void	 ikev2_info_sa(struct iked *, int, const char *, struct iked_sa *);
51 void	 ikev2_info_csa(struct iked *, int, const char *, struct iked_childsa *);
52 void	 ikev2_info_flow(struct iked *, int, const char *, struct iked_flow *);
53 void	 ikev2_log_established(struct iked_sa *);
54 void	 ikev2_log_proposal(struct iked_sa *, struct iked_proposals *);
55 void	 ikev2_log_cert_info(const char *, struct iked_id *);
56 
57 void	 ikev2_run(struct privsep *, struct privsep_proc *, void *);
58 void	 ikev2_shutdown(struct privsep_proc *);
59 int	 ikev2_dispatch_parent(int, struct privsep_proc *, struct imsg *);
60 int	 ikev2_dispatch_cert(int, struct privsep_proc *, struct imsg *);
61 int	 ikev2_dispatch_control(int, struct privsep_proc *, struct imsg *);
62 
63 struct iked_sa *
64 	 ikev2_getimsgdata(struct iked *, struct imsg *, struct iked_sahdr *,
65 	    uint8_t *, uint8_t **, size_t *);
66 
67 void	 ikev2_recv(struct iked *, struct iked_message *);
68 int	 ikev2_ike_auth_compatible(struct iked_sa *, uint8_t, uint8_t);
69 int	 ikev2_ike_auth_recv(struct iked *, struct iked_sa *,
70 	    struct iked_message *);
71 int	 ikev2_ike_auth(struct iked *, struct iked_sa *);
72 int	 ikev2_auth_verify(struct iked *, struct iked_sa *);
73 
74 void	 ikev2_init_recv(struct iked *, struct iked_message *,
75 	    struct ike_header *);
76 void	 ikev2_init_ike_sa_timeout(struct iked *, void *);
77 int	 ikev2_init_ike_sa_peer(struct iked *, struct iked_policy *,
78 	    struct iked_addr *, struct iked_message *);
79 int	 ikev2_init_ike_auth(struct iked *, struct iked_sa *);
80 int	 ikev2_init_auth(struct iked *, struct iked_message *);
81 int	 ikev2_init_done(struct iked *, struct iked_sa *);
82 
83 int	 ikev2_record_dstid(struct iked *, struct iked_sa *);
84 
85 void	 ikev2_enable_timer(struct iked *, struct iked_sa *);
86 void	 ikev2_disable_timer(struct iked *, struct iked_sa *);
87 
88 void	 ikev2_resp_recv(struct iked *, struct iked_message *,
89 	    struct ike_header *);
90 int	 ikev2_resp_ike_sa_init(struct iked *, struct iked_message *);
91 int	 ikev2_resp_ike_eap(struct iked *, struct iked_sa *,
92 	    struct iked_message *);
93 int	 ikev2_resp_ike_eap_mschap(struct iked *, struct iked_sa *,
94 	    struct iked_message *);
95 int	 ikev2_resp_ike_auth(struct iked *, struct iked_sa *);
96 int	 ikev2_send_auth_failed(struct iked *, struct iked_sa *);
97 int	 ikev2_send_error(struct iked *, struct iked_sa *,
98 	    struct iked_message *, uint8_t);
99 int	 ikev2_send_init_error(struct iked *, struct iked_message *);
100 
101 int	 ikev2_handle_certreq(struct iked*, struct iked_message *);
102 ssize_t	 ikev2_handle_delete(struct iked *, struct iked_message *,
103 	    struct ibuf *, struct ikev2_payload **, uint8_t *);
104 
105 int	 ikev2_send_create_child_sa(struct iked *, struct iked_sa *,
106 	    struct iked_spi *, uint8_t);
107 int	 ikev2_ikesa_enable(struct iked *, struct iked_sa *, struct iked_sa *);
108 void	 ikev2_ikesa_delete(struct iked *, struct iked_sa *, int);
109 int	 ikev2_nonce_cmp(struct ibuf *, struct ibuf *);
110 int	 ikev2_init_create_child_sa(struct iked *, struct iked_message *);
111 int	 ikev2_resp_create_child_sa(struct iked *, struct iked_message *);
112 void	 ikev2_ike_sa_rekey(struct iked *, void *);
113 void	 ikev2_ike_sa_rekey_timeout(struct iked *, void *);
114 void	 ikev2_ike_sa_rekey_schedule(struct iked *, struct iked_sa *);
115 void	 ikev2_ike_sa_rekey_schedule_fast(struct iked *, struct iked_sa *);
116 void	 ikev2_ike_sa_alive(struct iked *, void *);
117 void	 ikev2_ike_sa_keepalive(struct iked *, void *);
118 
119 int	 ikev2_sa_negotiate_common(struct iked *, struct iked_sa *, struct iked_message *);
120 int	 ikev2_sa_initiator(struct iked *, struct iked_sa *,
121 	    struct iked_sa *, struct iked_message *);
122 int	 ikev2_sa_responder(struct iked *, struct iked_sa *, struct iked_sa *,
123 	    struct iked_message *);
124 int	 ikev2_sa_initiator_dh(struct iked_sa *, struct iked_message *,
125 	    unsigned int, struct iked_sa *);
126 int	 ikev2_sa_responder_dh(struct iked_kex *, struct iked_proposals *,
127 	    struct iked_message *, unsigned int);
128 void	 ikev2_sa_cleanup_dh(struct iked_sa *);
129 int	 ikev2_sa_keys(struct iked *, struct iked_sa *, struct ibuf *);
130 int	 ikev2_sa_tag(struct iked_sa *, struct iked_id *);
131 int	 ikev2_set_sa_proposal(struct iked_sa *, struct iked_policy *,
132 	    unsigned int);
133 
134 int	 ikev2_childsa_negotiate(struct iked *, struct iked_sa *,
135 	    struct iked_kex *, struct iked_proposals *, int, int, int);
136 int	 ikev2_childsa_delete_proposed(struct iked *, struct iked_sa *,
137 	    struct iked_proposals *);
138 int	 ikev2_valid_proposal(struct iked_proposal *,
139 	    struct iked_transform **, struct iked_transform **, int *);
140 
141 int	 ikev2_handle_notifies(struct iked *, struct iked_message *);
142 
143 ssize_t	 ikev2_add_proposals(struct iked *, struct iked_sa *, struct ibuf *,
144 	    struct iked_proposals *, uint8_t, int, int, int);
145 ssize_t	 ikev2_add_cp(struct iked *, struct iked_sa *, struct ibuf *);
146 ssize_t	 ikev2_add_transform(struct ibuf *,
147 	    uint8_t, uint8_t, uint16_t, uint16_t);
148 ssize_t	 ikev2_add_ts(struct ibuf *, struct ikev2_payload **, ssize_t,
149 	    struct iked_sa *, int);
150 ssize_t	 ikev2_add_certreq(struct ibuf *, struct ikev2_payload **, ssize_t,
151 	    struct ibuf *, uint8_t);
152 ssize_t	 ikev2_add_ipcompnotify(struct iked *, struct ibuf *,
153 	    struct ikev2_payload **, ssize_t, struct iked_sa *, int);
154 ssize_t	 ikev2_add_ts_payload(struct ibuf *, unsigned int, struct iked_sa *);
155 ssize_t	 ikev2_add_error(struct iked *, struct ibuf *, struct iked_message *);
156 int	 ikev2_add_data(struct ibuf *, void *, size_t);
157 int	 ikev2_add_buf(struct ibuf *buf, struct ibuf *);
158 
159 int	 ikev2_cp_setaddr(struct iked *, struct iked_sa *, sa_family_t);
160 int	 ikev2_cp_fixaddr(struct iked_sa *, struct iked_addr *,
161 	    struct iked_addr *);
162 
163 ssize_t	 ikev2_add_sighashnotify(struct ibuf *, struct ikev2_payload **,
164 	    ssize_t);
165 ssize_t	 ikev2_add_nat_detection(struct iked *, struct ibuf *,
166 	    struct ikev2_payload **, struct iked_message *, ssize_t);
167 ssize_t	 ikev2_add_notify(struct ibuf *, struct ikev2_payload **, ssize_t,
168 	    uint16_t);
169 ssize_t	 ikev2_add_mobike(struct ibuf *, struct ikev2_payload **, ssize_t);
170 ssize_t	 ikev2_add_fragmentation(struct ibuf *, struct ikev2_payload **,
171 	    ssize_t);
172 ssize_t	 ikev2_add_transport_mode(struct iked *, struct ibuf *,
173 	    struct ikev2_payload **, ssize_t, struct iked_sa *);
174 int	 ikev2_update_sa_addresses(struct iked *, struct iked_sa *);
175 int	 ikev2_resp_informational(struct iked *, struct iked_sa *,
176 	    struct iked_message *);
177 
178 void	ikev2_ctl_reset_id(struct iked *, struct imsg *, unsigned int);
179 void	ikev2_ctl_show_sa(struct iked *);
180 
181 static struct privsep_proc procs[] = {
182 	{ "parent",	PROC_PARENT,	ikev2_dispatch_parent },
183 	{ "certstore",	PROC_CERT,	ikev2_dispatch_cert },
184 	{ "control",	PROC_CONTROL,	ikev2_dispatch_control }
185 };
186 
187 pid_t
188 ikev2(struct privsep *ps, struct privsep_proc *p)
189 {
190 	return (proc_run(ps, p, procs, nitems(procs), ikev2_run, NULL));
191 }
192 
193 void
194 ikev2_run(struct privsep *ps, struct privsep_proc *p, void *arg)
195 {
196 	/*
197 	 * pledge in the ikev2 process:
198 	 * stdio - for malloc and basic I/O including events.
199 	 * inet - for sendto with specified peer address.
200 	 * recvfd - for PFKEYv2 and the listening UDP sockets.
201 	 * In theory, recvfd could be dropped after getting the fds once.
202 	 */
203 	p->p_shutdown = ikev2_shutdown;
204 	if (pledge("stdio inet recvfd", NULL) == -1)
205 		fatal("pledge");
206 }
207 
208 void
209 ikev2_shutdown(struct privsep_proc *p)
210 {
211 	struct iked		*env = p->p_env;
212 
213 	ibuf_release(env->sc_certreq);
214 	env->sc_certreq = NULL;
215 }
216 
217 int
218 ikev2_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
219 {
220 	struct iked		*env = p->p_env;
221 	struct iked_policy	*pol;
222 
223 	switch (imsg->hdr.type) {
224 	case IMSG_CTL_RESET:
225 		return (config_getreset(env, imsg));
226 	case IMSG_CTL_COUPLE:
227 	case IMSG_CTL_DECOUPLE:
228 		return (config_getcoupled(env, imsg->hdr.type));
229 	case IMSG_CTL_ACTIVE:
230 	case IMSG_CTL_PASSIVE:
231 		if (config_getmode(env, imsg->hdr.type) == -1)
232 			return (0);	/* ignore error */
233 		timer_del(env, &env->sc_inittmr);
234 		TAILQ_FOREACH(pol, &env->sc_policies, pol_entry) {
235 			if (policy_generate_ts(pol) == -1)
236 				fatalx("%s: too many traffic selectors", __func__);
237 		}
238 		if (!env->sc_passive) {
239 			timer_set(env, &env->sc_inittmr, ikev2_init_ike_sa,
240 			    NULL);
241 			timer_add(env, &env->sc_inittmr,
242 			    IKED_INITIATOR_INITIAL);
243 		}
244 		return (0);
245 	case IMSG_UDP_SOCKET:
246 		return (config_getsocket(env, imsg, ikev2_msg_cb));
247 	case IMSG_PFKEY_SOCKET:
248 		return (config_getpfkey(env, imsg));
249 	case IMSG_CFG_POLICY:
250 		return (config_getpolicy(env, imsg));
251 	case IMSG_CFG_FLOW:
252 		return (config_getflow(env, imsg));
253 	case IMSG_CFG_USER:
254 		return (config_getuser(env, imsg));
255 	case IMSG_COMPILE:
256 		return (config_getcompile(env));
257 	case IMSG_CTL_STATIC:
258 		return (config_getstatic(env, imsg));
259 	case IMSG_CERT_PARTIAL_CHAIN:
260 		return(config_getcertpartialchain(env, imsg));
261 	default:
262 		break;
263 	}
264 
265 	return (-1);
266 }
267 
268 int
269 ikev2_dispatch_cert(int fd, struct privsep_proc *p, struct imsg *imsg)
270 {
271 	struct iked		*env = p->p_env;
272 	struct iked_sahdr	 sh;
273 	struct iked_sa		*sa;
274 	uint8_t			 type;
275 	uint8_t			*ptr;
276 	size_t			 len;
277 	struct iked_id		*id = NULL;
278 	int			 ignore = 0;
279 
280 	switch (imsg->hdr.type) {
281 	case IMSG_CERTREQ:
282 		IMSG_SIZE_CHECK(imsg, &type);
283 
284 		ptr = imsg->data;
285 		memcpy(&type, ptr, sizeof(type));
286 		ptr += sizeof(type);
287 
288 		ibuf_release(env->sc_certreq);
289 		env->sc_certreqtype = type;
290 		env->sc_certreq = ibuf_new(ptr,
291 		    IMSG_DATA_SIZE(imsg) - sizeof(type));
292 
293 		log_debug("%s: updated local CERTREQ type %s length %zu",
294 		    __func__, print_map(type, ikev2_cert_map),
295 		    ibuf_length(env->sc_certreq));
296 
297 		break;
298 	case IMSG_CERTVALID:
299 	case IMSG_CERTINVALID:
300 		/* Ignore invalid or unauthenticated SAs */
301 		if ((sa = ikev2_getimsgdata(env, imsg,
302 		    &sh, &type, &ptr, &len)) == NULL ||
303 		    sa->sa_state < IKEV2_STATE_EAP)
304 			break;
305 
306 		if (sh.sh_initiator)
307 			id = &sa->sa_rcert;
308 		else
309 			id = &sa->sa_icert;
310 
311 		id->id_type = type;
312 		id->id_offset = 0;
313 		ibuf_release(id->id_buf);
314 		id->id_buf = NULL;
315 
316 		if (len > 0 && (id->id_buf = ibuf_new(ptr, len)) == NULL) {
317 			log_debug("%s: failed to get cert payload",
318 			    __func__);
319 			break;
320 		}
321 
322 		if (imsg->hdr.type == IMSG_CERTVALID) {
323 			if (sa->sa_peerauth.id_type && ikev2_auth_verify(env, sa))
324 				break;
325 
326 			log_debug("%s: peer certificate is valid", __func__);
327 			sa_stateflags(sa, IKED_REQ_CERTVALID);
328 
329 			if (ikev2_ike_auth(env, sa) != 0)
330 				log_debug("%s: failed to send ike auth", __func__);
331 		} else {
332 			log_warnx("%s: peer certificate is invalid",
333 				SPI_SA(sa, __func__));
334 			ikev2_send_auth_failed(env, sa);
335 		}
336 		break;
337 	case IMSG_CERT:
338 		if ((sa = ikev2_getimsgdata(env, imsg,
339 		    &sh, &type, &ptr, &len)) == NULL) {
340 			log_debug("%s: invalid cert reply", __func__);
341 			break;
342 		}
343 
344 		/*
345 		 * Ignore the message if we already got a valid certificate.
346 		 * This might happen if the peer sent multiple CERTREQs.
347 		 */
348 		if (sa->sa_stateflags & IKED_REQ_CERT ||
349 		    type == IKEV2_CERT_NONE)
350 			ignore = 1;
351 
352 		log_debug("%s: cert type %s length %zu, %s", __func__,
353 		    print_map(type, ikev2_cert_map), len,
354 		    ignore ? "ignored" : "ok");
355 
356 		if (ignore)
357 			break;
358 
359 		if (sh.sh_initiator)
360 			id = &sa->sa_icert;
361 		else
362 			id = &sa->sa_rcert;
363 
364 		id->id_type = type;
365 		id->id_offset = 0;
366 		ibuf_release(id->id_buf);
367 		id->id_buf = NULL;
368 
369 		if (len <= 0 || (id->id_buf = ibuf_new(ptr, len)) == NULL) {
370 			log_debug("%s: failed to get cert payload",
371 			    __func__);
372 			break;
373 		}
374 
375 		sa_stateflags(sa, IKED_REQ_CERT);
376 
377 		if (ikev2_ike_auth(env, sa) != 0)
378 			log_debug("%s: failed to send ike auth", __func__);
379 		break;
380 	case IMSG_AUTH:
381 		if ((sa = ikev2_getimsgdata(env, imsg,
382 		    &sh, &type, &ptr, &len)) == NULL) {
383 			log_debug("%s: invalid auth reply", __func__);
384 			break;
385 		}
386 		if (sa_stateok(sa, IKEV2_STATE_VALID)) {
387 			log_warnx("%s: ignoring AUTH in state %s",
388 			    SPI_SA(sa, __func__),
389 			    print_map(sa->sa_state, ikev2_state_map));
390 			break;
391 		}
392 
393 		log_debug("%s: AUTH type %d len %zu", __func__, type, len);
394 
395 		id = &sa->sa_localauth;
396 		id->id_type = type;
397 		id->id_offset = 0;
398 		ibuf_release(id->id_buf);
399 		id->id_buf = NULL;
400 
401 		if (type != IKEV2_AUTH_NONE) {
402 			if (len <= 0 ||
403 			    (id->id_buf = ibuf_new(ptr, len)) == NULL) {
404 				log_debug("%s: failed to get auth payload",
405 				    __func__);
406 				break;
407 			}
408 		}
409 
410 		sa_stateflags(sa, IKED_REQ_AUTH);
411 
412 		if (ikev2_ike_auth(env, sa) != 0)
413 			log_debug("%s: failed to send ike auth", __func__);
414 		break;
415 	default:
416 		return (-1);
417 	}
418 
419 	return (0);
420 }
421 
422 int
423 ikev2_dispatch_control(int fd, struct privsep_proc *p, struct imsg *imsg)
424 {
425 	struct iked		*env = p->p_env;
426 
427 	switch (imsg->hdr.type) {
428 	case IMSG_CTL_RESET_ID:
429 		ikev2_ctl_reset_id(env, imsg, imsg->hdr.type);
430 		break;
431 	case IMSG_CTL_SHOW_SA:
432 		ikev2_ctl_show_sa(env);
433 		break;
434 	default:
435 		return (-1);
436 	}
437 
438 	return (0);
439 }
440 
441 /* try to delete established SA if no other exchange is active */
442 int
443 ikev2_ike_sa_delete(struct iked *env, struct iked_sa *sa)
444 {
445 	if (sa->sa_state != IKEV2_STATE_ESTABLISHED)
446 		return (-1);
447 	if (sa->sa_stateflags & (IKED_REQ_CHILDSA|IKED_REQ_INF))
448 		return (-1);
449 	ikev2_disable_timer(env, sa);
450 	ikev2_ike_sa_setreason(sa, "reset sa control message");
451 	ikev2_ikesa_delete(env, sa, 1);
452 	timer_add(env, &sa->sa_timer, 0);
453 	return (0);
454 }
455 
456 void
457 ikev2_ctl_reset_id(struct iked *env, struct imsg *imsg, unsigned int type)
458 {
459 	struct iked_sa			*sa;
460 	char				*reset_id = NULL;
461 	char				 sa_id[IKED_ID_SIZE];
462 
463 	if ((reset_id = get_string(imsg->data, IMSG_DATA_SIZE(imsg))) == NULL)
464 		return;
465 
466 	log_debug("%s: %s %d", __func__, reset_id, type);
467 	RB_FOREACH(sa, iked_sas, &env->sc_sas) {
468 		if (ikev2_print_id(IKESA_DSTID(sa), sa_id, sizeof(sa_id)) == -1)
469 			continue;
470 		if (strcmp(reset_id, sa_id) != 0)
471 			continue;
472 		if (sa->sa_state == IKEV2_STATE_CLOSED)
473 			continue;
474 		if (sa->sa_state == IKEV2_STATE_ESTABLISHED)
475 			ikev2_disable_timer(env, sa);
476 		log_info("%s: IKE SA %p id %s ispi %s rspi %s", __func__,
477 		    sa, sa_id,
478 		    print_spi(sa->sa_hdr.sh_ispi, 8),
479 		    print_spi(sa->sa_hdr.sh_rspi, 8));
480 		ikev2_ike_sa_setreason(sa, "reset control message");
481 		ikev2_ikesa_delete(env, sa, 1);
482 		/* default IKED_IKE_SA_DELETE_TIMEOUT is 120s, so switch to 6s */
483 		timer_add(env, &sa->sa_timer, 3 * IKED_RETRANSMIT_TIMEOUT);
484 	}
485 	free(reset_id);
486 }
487 
488 void
489 ikev2_ctl_show_sa(struct iked *env)
490 {
491 	ikev2_info(env, 0);
492 }
493 
494 struct iked_sa *
495 ikev2_getimsgdata(struct iked *env, struct imsg *imsg, struct iked_sahdr *sh,
496     uint8_t *type, uint8_t **buf, size_t *size)
497 {
498 	uint8_t		*ptr;
499 	size_t		 len;
500 	struct iked_sa	*sa;
501 
502 	ptr = imsg->data;
503 	len = IMSG_DATA_SIZE(imsg);
504 	if (len < sizeof(*sh))
505 		fatalx("ikev2_getimsgdata: length too small for sh");
506 	memcpy(sh, ptr, sizeof(*sh));
507 	len -= sizeof(*sh);
508 	ptr += sizeof(*sh);
509 	if (len < sizeof(*type))
510 		fatalx("ikev2_getimsgdata: length too small for type");
511 	memcpy(type, ptr, sizeof(*type));
512 	len -= sizeof(*type);
513 	ptr += sizeof(*type);
514 
515 	sa = sa_lookup(env, sh->sh_ispi, sh->sh_rspi, sh->sh_initiator);
516 
517 	log_debug("%s: imsg %d rspi %s ispi %s initiator %d sa %s"
518 	    " type %d data length %zd",
519 	    __func__, imsg->hdr.type,
520 	    print_spi(sh->sh_rspi, 8),
521 	    print_spi(sh->sh_ispi, 8),
522 	    sh->sh_initiator,
523 	    sa == NULL ? "invalid" : "valid", *type, len);
524 
525 	if (sa == NULL)
526 		return (NULL);
527 
528 	*buf = ptr;
529 	*size = len;
530 
531 	return (sa);
532 }
533 
534 static time_t
535 gettime(void)
536 {
537 	struct timeval tv;
538 	gettimeofday(&tv, NULL);
539 	return tv.tv_sec;
540 }
541 
542 void
543 ikev2_recv(struct iked *env, struct iked_message *msg)
544 {
545 	struct ike_header	*hdr;
546 	struct iked_sa		*sa;
547 	unsigned int		 initiator, flag = 0;
548 	int			 r;
549 
550 	hdr = ibuf_seek(msg->msg_data, msg->msg_offset, sizeof(*hdr));
551 
552 	if (hdr == NULL || ibuf_size(msg->msg_data) <
553 	    (betoh32(hdr->ike_length) - msg->msg_offset))
554 		return;
555 
556 	initiator = (hdr->ike_flags & IKEV2_FLAG_INITIATOR) ? 0 : 1;
557 	msg->msg_response = (hdr->ike_flags & IKEV2_FLAG_RESPONSE) ? 1 : 0;
558 	msg->msg_sa = sa_lookup(env,
559 	    betoh64(hdr->ike_ispi), betoh64(hdr->ike_rspi),
560 	    initiator);
561 	msg->msg_msgid = betoh32(hdr->ike_msgid);
562 	if (policy_lookup(env, msg, NULL) != 0)
563 		return;
564 
565 	logit(hdr->ike_exchange == IKEV2_EXCHANGE_INFORMATIONAL ?
566 	    LOG_DEBUG : LOG_INFO,
567 	    "%srecv %s %s %u peer %s local %s, %ld bytes, policy '%s'",
568 	    SPI_IH(hdr),
569 	    print_map(hdr->ike_exchange, ikev2_exchange_map),
570 	    msg->msg_response ? "res" : "req",
571 	    msg->msg_msgid,
572 	    print_host((struct sockaddr *)&msg->msg_peer, NULL, 0),
573 	    print_host((struct sockaddr *)&msg->msg_local, NULL, 0),
574 	    ibuf_length(msg->msg_data),
575 	    msg->msg_policy->pol_name);
576 	log_debug("%s: ispi %s rspi %s", __func__,
577 	    print_spi(betoh64(hdr->ike_ispi), 8),
578 	    print_spi(betoh64(hdr->ike_rspi), 8));
579 
580 	if ((sa = msg->msg_sa) == NULL)
581 		goto done;
582 
583 	sa->sa_last_recvd = gettime();
584 
585 	if (hdr->ike_exchange == IKEV2_EXCHANGE_CREATE_CHILD_SA)
586 		flag = IKED_REQ_CHILDSA;
587 	if (hdr->ike_exchange == IKEV2_EXCHANGE_INFORMATIONAL)
588 		flag = IKED_REQ_INF;
589 
590 	if (hdr->ike_exchange != IKEV2_EXCHANGE_IKE_SA_INIT &&
591 	    hdr->ike_nextpayload != IKEV2_PAYLOAD_SK &&
592 	    hdr->ike_nextpayload != IKEV2_PAYLOAD_SKF)
593 		return;
594 
595 	if (msg->msg_response) {
596 		if (msg->msg_msgid > sa->sa_reqid)
597 			return;
598 		if (hdr->ike_exchange != IKEV2_EXCHANGE_INFORMATIONAL &&
599 		    !ikev2_msg_lookup(env, &sa->sa_requests, msg, hdr) &&
600 		    sa->sa_fragments.frag_count == 0)
601 			return;
602 		if (flag) {
603 			if ((sa->sa_stateflags & flag) == 0)
604 				return;
605 			/*
606 			 * We have initiated this exchange, even if
607 			 * we are not the initiator of the IKE SA.
608 			 */
609 			initiator = 1;
610 		}
611 		/*
612 		 * There's no need to keep the request (fragments) around
613 		 */
614 		ikev2_msg_lookup_dispose_all(env, &sa->sa_requests, msg, hdr);
615 	} else {
616 		/*
617 		 * IKE_SA_INIT is special since it always uses the message id 0.
618 		 * Even when the message was rejected, and the new message has
619 		 * different proposals, the id will be the same.  To discern
620 		 * retransmits and new messages, the RFC suggests to compare the
621 		 * the messages.
622 		 */
623 		if (sa->sa_state == IKEV2_STATE_CLOSED && sa->sa_1stmsg &&
624 		    hdr->ike_exchange == IKEV2_EXCHANGE_IKE_SA_INIT &&
625 		    msg->msg_msgid == 0 &&
626 		    (ibuf_length(msg->msg_data) != ibuf_length(sa->sa_1stmsg) ||
627 		    memcmp(ibuf_data(msg->msg_data), ibuf_data(sa->sa_1stmsg),
628 		    ibuf_length(sa->sa_1stmsg)) != 0)) {
629 			ikev2_ike_sa_setreason(sa, NULL);
630 			sa_free(env, sa);
631 			msg->msg_sa = sa = NULL;
632 			goto done;
633 		}
634 		if (msg->msg_msgid < sa->sa_msgid)
635 			return;
636 		if (flag)
637 			initiator = 0;
638 		/*
639 		 * See if we have responded to this request before
640 		 */
641 		if ((r = ikev2_msg_lookup_retransmit_all(env, &sa->sa_responses,
642 		    msg, hdr, sa)) != 0) {
643 			if (r == -1) {
644 				log_warn("%s: failed to retransmit a "
645 				    "response", __func__);
646 				ikev2_ike_sa_setreason(sa,
647 				    "retransmitting response failed");
648 				sa_free(env, sa);
649 			}
650 			return;
651 		} else if (sa->sa_msgid_set && msg->msg_msgid == sa->sa_msgid) {
652 			/*
653 			 * Response is being worked on, most likely we're
654 			 * waiting for the CA process to get back to us
655 			 */
656 			return;
657 		}
658 		sa->sa_msgid_current = msg->msg_msgid;
659 	}
660 
661 	if (sa_address(sa, &sa->sa_peer, (struct sockaddr *)&msg->msg_peer)
662 	    == -1 ||
663 	    sa_address(sa, &sa->sa_local, (struct sockaddr *)&msg->msg_local)
664 	    == -1)
665 		return;
666 
667 	sa->sa_fd = msg->msg_fd;
668 
669 	log_debug("%s: updated SA to peer %s local %s", __func__,
670 	    print_host((struct sockaddr *)&sa->sa_peer.addr, NULL, 0),
671 	    print_host((struct sockaddr *)&sa->sa_local.addr, NULL, 0));
672 
673 done:
674 	if (initiator)
675 		ikev2_init_recv(env, msg, hdr);
676 	else
677 		ikev2_resp_recv(env, msg, hdr);
678 
679 	if (sa != NULL && !msg->msg_response && msg->msg_valid) {
680 		/*
681 		 * If it's a valid request, make sure to update the peer's
682 		 * message ID and dispose of all previous responses.
683 		 * We need to set sa_msgid_set in order to distinguish between
684 		 * "last msgid was 0" and "msgid not set yet".
685 		 */
686 		sa->sa_msgid = sa->sa_msgid_current;
687 		sa->sa_msgid_set = 1;
688 		ikev2_msg_prevail(env, &sa->sa_responses, msg);
689 	}
690 
691 	if (sa != NULL && sa->sa_state == IKEV2_STATE_CLOSED) {
692 		log_debug("%s: closing SA", __func__);
693 		ikev2_ike_sa_setreason(sa, "closed");
694 		sa_free(env, sa);
695 	}
696 }
697 
698 int
699 ikev2_ike_auth_compatible(struct iked_sa *sa, uint8_t policy, uint8_t wire)
700 {
701 	if (wire == IKEV2_AUTH_SIG_ANY)		/* internal, not on wire */
702 		return (-1);
703 	if (policy == wire || policy == IKEV2_AUTH_NONE)
704 		return (0);
705 	switch (policy) {
706 	case IKEV2_AUTH_SIG_ANY:
707 		switch (wire) {
708 		case IKEV2_AUTH_SIG:
709 		case IKEV2_AUTH_RSA_SIG:
710 		case IKEV2_AUTH_ECDSA_256:
711 		case IKEV2_AUTH_ECDSA_384:
712 		case IKEV2_AUTH_ECDSA_521:
713 			return (0);
714 		}
715 		break;
716 	case IKEV2_AUTH_SIG:
717 	case IKEV2_AUTH_RSA_SIG:
718 	case IKEV2_AUTH_ECDSA_256:
719 	case IKEV2_AUTH_ECDSA_384:
720 	case IKEV2_AUTH_ECDSA_521:
721 		switch (wire) {
722 		/*
723 		 * XXX Maybe we need an indication saying:
724 		 * XXX Accept AUTH_SIG as long as its DSA?
725 		 */
726 		case IKEV2_AUTH_SIG:
727 			if (sa->sa_sigsha2)
728 				return (0);
729 		}
730 		break;
731 	}
732 	return (-1);
733 }
734 
735 int
736 ikev2_auth_verify(struct iked *env, struct iked_sa *sa)
737 {
738 	struct iked_auth	 ikeauth;
739 	struct ibuf		*authmsg;
740 	int			 ret;
741 
742 	memcpy(&ikeauth, &sa->sa_policy->pol_auth,
743 	    sizeof(ikeauth));
744 
745 	if (sa->sa_policy->pol_auth.auth_eap &&
746 	    sa->sa_eapmsk != NULL) {
747 		/*
748 		 * The initiator EAP auth is a PSK derived
749 		 * from the EAP-specific MSK
750 		 */
751 		ikeauth.auth_method = IKEV2_AUTH_SHARED_KEY_MIC;
752 
753 		/* Copy session key as PSK */
754 		memcpy(ikeauth.auth_data,
755 		    ibuf_data(sa->sa_eapmsk),
756 		    ibuf_size(sa->sa_eapmsk));
757 		ikeauth.auth_length = ibuf_size(sa->sa_eapmsk);
758 	}
759 
760 	if (ikev2_ike_auth_compatible(sa,
761 	    ikeauth.auth_method, sa->sa_peerauth.id_type) < 0) {
762 		log_warnx("%s: unexpected auth method %s, was "
763 		    "expecting %s", SPI_SA(sa, __func__),
764 		    print_map(sa->sa_peerauth.id_type,
765 		    ikev2_auth_map),
766 		    print_map(ikeauth.auth_method,
767 		    ikev2_auth_map));
768 		return (-1);
769 	}
770 	ikeauth.auth_method = sa->sa_peerauth.id_type;
771 
772 	if ((authmsg = ikev2_msg_auth(env, sa,
773 	    sa->sa_hdr.sh_initiator)) == NULL) {
774 		log_debug("%s: failed to get auth data",
775 		    __func__);
776 		return (-1);
777 	}
778 
779 	ret = ikev2_msg_authverify(env, sa, &ikeauth,
780 	    ibuf_data(sa->sa_peerauth.id_buf),
781 	    ibuf_length(sa->sa_peerauth.id_buf),
782 	    authmsg);
783 	ibuf_release(authmsg);
784 	if (ret != 0) {
785 		log_info("%s: ikev2_msg_authverify failed",
786 		    SPI_SA(sa, __func__));
787 		ikev2_send_auth_failed(env, sa);
788 		return (-1);
789 	}
790 	if (sa->sa_eapmsk != NULL) {
791 		if ((authmsg = ikev2_msg_auth(env, sa,
792 		    !sa->sa_hdr.sh_initiator)) == NULL) {
793 			log_debug("%s: failed to get auth data",
794 			    __func__);
795 			return (-1);
796 		}
797 
798 		/* XXX 2nd AUTH for EAP messages */
799 		ret = ikev2_msg_authsign(env, sa, &ikeauth, authmsg);
800 		ibuf_release(authmsg);
801 		if (ret != 0) {
802 			ikev2_send_auth_failed(env, sa);
803 			return (-1);
804 		}
805 
806 		/* ikev2_msg_authverify verified AUTH */
807 		sa_stateflags(sa, IKED_REQ_AUTHVALID);
808 		sa_stateflags(sa, IKED_REQ_EAPVALID);
809 		sa_state(env, sa, IKEV2_STATE_EAP_SUCCESS);
810 	}
811 
812 	return (0);
813 }
814 
815 int
816 ikev2_ike_auth_recv(struct iked *env, struct iked_sa *sa,
817     struct iked_message *msg)
818 {
819 	struct iked_id		*id;
820 	struct ibuf		*authmsg;
821 	struct iked_policy	*old;
822 	uint8_t			*cert = NULL;
823 	size_t			 certlen = 0;
824 	int			 certtype = IKEV2_CERT_NONE;
825 
826 	/* The AUTH payload indicates if the responder wants EAP or not */
827 	if (msg->msg_auth.id_type != IKEV2_AUTH_NONE &&
828 	    !sa_stateok(sa, IKEV2_STATE_EAP))
829 		sa_state(env, sa, IKEV2_STATE_AUTH_REQUEST);
830 
831 	if (!sa->sa_hdr.sh_initiator &&
832 	    !sa_stateok(sa, IKEV2_STATE_AUTH_REQUEST) &&
833 	    sa->sa_policy->pol_auth.auth_eap)
834 		sa_state(env, sa, IKEV2_STATE_EAP);
835 
836 	if (sa->sa_hdr.sh_initiator)
837 		id = &sa->sa_rid;
838 	else
839 		id = &sa->sa_iid;
840 
841 	/* try to relookup the policy based on the peerid */
842 	if (msg->msg_id.id_type && !sa->sa_hdr.sh_initiator) {
843 		old = sa->sa_policy;
844 
845 		sa->sa_policy = NULL;
846 		if (policy_lookup(env, msg, &sa->sa_proposals) != 0 ||
847 		    msg->msg_policy == NULL) {
848 			log_info("%s: no compatible policy found",
849 			    SPI_SA(sa, __func__));
850 			ikev2_send_auth_failed(env, sa);
851 			TAILQ_REMOVE(&old->pol_sapeers, sa, sa_peer_entry);
852 			if (old->pol_flags & IKED_POLICY_REFCNT)
853 				policy_unref(env, old);
854 			return (-1);
855 		}
856 		if (msg->msg_policy != old) {
857 			/* Clean up old policy */
858 			TAILQ_REMOVE(&old->pol_sapeers, sa, sa_peer_entry);
859 			if (old->pol_flags & IKED_POLICY_REFCNT)
860 				policy_unref(env, old);
861 
862 			/* Update SA with new policy*/
863 			if (sa_new(env, sa->sa_hdr.sh_ispi,
864 			    sa->sa_hdr.sh_rspi, 0, msg->msg_policy) != sa) {
865 				log_warnx("%s: failed to update SA",
866 				    SPI_SA(sa, __func__));
867 				ikev2_send_auth_failed(env, sa);
868 				return (-1);
869 			}
870 		} else {
871 			/* restore */
872 			msg->msg_policy = sa->sa_policy = old;
873 		}
874 		if (ikev2_handle_certreq(env, msg) != 0)
875 			return (-1);
876 	}
877 
878 	/* AUTH payload is required for non-EAP */
879 	if (!msg->msg_auth.id_type &&
880 	    !sa->sa_policy->pol_auth.auth_eap) {
881 		/* get dstid */
882 		if (msg->msg_id.id_type) {
883 			memcpy(id, &msg->msg_id, sizeof(*id));
884 			bzero(&msg->msg_id, sizeof(msg->msg_id));
885 		}
886 		log_debug("%s: missing auth payload", SPI_SA(sa, __func__));
887 		ikev2_send_auth_failed(env, sa);
888 		return (-1);
889 	}
890 
891 	if (msg->msg_id.id_type) {
892 		memcpy(id, &msg->msg_id, sizeof(*id));
893 		bzero(&msg->msg_id, sizeof(msg->msg_id));
894 
895 		if (!sa->sa_hdr.sh_initiator) {
896 			if ((authmsg = ikev2_msg_auth(env, sa,
897 			    !sa->sa_hdr.sh_initiator)) == NULL) {
898 				log_debug("%s: failed to get response "
899 				    "auth data", __func__);
900 				return (-1);
901 			}
902 
903 			ca_setauth(env, sa, authmsg, PROC_CERT);
904 			ibuf_release(authmsg);
905 		}
906 	}
907 
908 	if (!TAILQ_EMPTY(&msg->msg_proposals)) {
909 		if (proposals_negotiate(&sa->sa_proposals,
910 		    &sa->sa_policy->pol_proposals, &msg->msg_proposals,
911 		    0) != 0) {
912 			log_info("%s: no proposal chosen", __func__);
913 			msg->msg_error = IKEV2_N_NO_PROPOSAL_CHOSEN;
914 			return (-1);
915 		} else
916 			sa_stateflags(sa, IKED_REQ_SA);
917 	}
918 
919 	if (msg->msg_auth.id_type) {
920 		memcpy(&sa->sa_peerauth, &msg->msg_auth, sizeof(sa->sa_peerauth));
921 		bzero(&msg->msg_auth, sizeof(msg->msg_auth));
922 	}
923 
924 	/* For EAP and PSK AUTH can be verified without the CA process*/
925 	if ((sa->sa_policy->pol_auth.auth_eap &&
926 	    sa->sa_eapmsk != NULL) ||
927 	    sa->sa_policy->pol_auth.auth_method == IKEV2_AUTH_SHARED_KEY_MIC)
928 		ikev2_auth_verify(env, sa);
929 	/* For CERT and Pubkey AUTH the CA process must find a matching key */
930 	else if (sa->sa_peerauth.id_type) {
931 		if (msg->msg_cert.id_type) {
932 			certtype = msg->msg_cert.id_type;
933 			cert = ibuf_data(msg->msg_cert.id_buf);
934 			certlen = ibuf_length(msg->msg_cert.id_buf);
935 			bzero(&msg->msg_cert, sizeof(msg->msg_cert));
936 		}
937 		if (ca_setcert(env, &sa->sa_hdr, id, certtype, cert, certlen, PROC_CERT) == -1)
938 			return (-1);
939 	}
940 
941 	return ikev2_ike_auth(env, sa);
942 }
943 
944 int
945 ikev2_ike_auth(struct iked *env, struct iked_sa *sa)
946 {
947 	/* Attempt state transition */
948 	if (sa->sa_state == IKEV2_STATE_EAP_SUCCESS)
949 		sa_state(env, sa, IKEV2_STATE_EAP_VALID);
950 	else if (sa->sa_state == IKEV2_STATE_AUTH_SUCCESS)
951 		sa_state(env, sa, IKEV2_STATE_VALID);
952 
953 	if (sa->sa_hdr.sh_initiator) {
954 		if (sa_stateok(sa, IKEV2_STATE_AUTH_SUCCESS))
955 			return (ikev2_init_done(env, sa));
956 		/* AUTH exchange is awaiting response from CA process, ignore */
957 		else if (sa_stateok(sa, IKEV2_STATE_AUTH_REQUEST))
958 			return (0);
959 		else
960 			return (ikev2_init_ike_auth(env, sa));
961 	}
962 	return (ikev2_resp_ike_auth(env, sa));
963 }
964 
965 void
966 ikev2_init_recv(struct iked *env, struct iked_message *msg,
967     struct ike_header *hdr)
968 {
969 	struct iked_sa		*sa;
970 	in_port_t		 port;
971 	struct iked_socket	*sock;
972 	struct iked_policy	*pol;
973 
974 	if (ikev2_msg_valid_ike_sa(env, hdr, msg) == -1) {
975 		log_debug("%s: unknown SA", __func__);
976 		return;
977 	}
978 	sa = msg->msg_sa;
979 
980 	switch (hdr->ike_exchange) {
981 	case IKEV2_EXCHANGE_IKE_SA_INIT:
982 		/* Update the SPIs */
983 		if ((sa = sa_new(env,
984 		    betoh64(hdr->ike_ispi), betoh64(hdr->ike_rspi), 1,
985 		    NULL)) == NULL || sa != msg->msg_sa) {
986 			log_debug("%s: invalid new SA", __func__);
987 			if (sa) {
988 				ikev2_ike_sa_setreason(sa, "invalid new SA");
989 				sa_free(env, sa);
990 			}
991 			return;
992 		}
993 		break;
994 	case IKEV2_EXCHANGE_IKE_AUTH:
995 	case IKEV2_EXCHANGE_CREATE_CHILD_SA:
996 	case IKEV2_EXCHANGE_INFORMATIONAL:
997 		break;
998 	default:
999 		log_debug("%s: unsupported exchange: %s", __func__,
1000 		    print_map(hdr->ike_exchange, ikev2_exchange_map));
1001 		return;
1002 	}
1003 
1004 	if (ikev2_pld_parse(env, hdr, msg, msg->msg_offset) != 0) {
1005 		log_debug("%s: failed to parse message", __func__);
1006 		return;
1007 	}
1008 
1009 	if (sa->sa_fragments.frag_count != 0)
1010 		return;
1011 
1012 	if (!ikev2_msg_frompeer(msg))
1013 		return;
1014 
1015 	if (ikev2_handle_notifies(env, msg) != 0)
1016 		return;
1017 
1018 	if (msg->msg_nat_detected && sa->sa_natt == 0 &&
1019 	    (sock = ikev2_msg_getsocket(env,
1020 	    sa->sa_local.addr_af, 1)) != NULL) {
1021 		/*
1022 		 * Update address information and use the NAT-T
1023 		 * port and socket, if available.
1024 		 */
1025 		port = htons(socket_getport(
1026 		    (struct sockaddr *)&sock->sock_addr));
1027 		sa->sa_local.addr_port = port;
1028 		sa->sa_peer.addr_port = port;
1029 		(void)socket_af((struct sockaddr *)&sa->sa_local.addr, port);
1030 		(void)socket_af((struct sockaddr *)&sa->sa_peer.addr, port);
1031 
1032 		msg->msg_fd = sa->sa_fd = sock->sock_fd;
1033 		msg->msg_sock = sock;
1034 		sa->sa_natt = 1;
1035 		sa->sa_udpencap = 1;
1036 
1037 		log_debug("%s: detected NAT, enabling UDP encapsulation,"
1038 		    " updated SA to peer %s local %s", __func__,
1039 		    print_host((struct sockaddr *)&sa->sa_peer.addr, NULL, 0),
1040 		    print_host((struct sockaddr *)&sa->sa_local.addr, NULL, 0));
1041 	}
1042 
1043 	switch (hdr->ike_exchange) {
1044 	case IKEV2_EXCHANGE_IKE_SA_INIT:
1045 		if (ibuf_length(msg->msg_cookie)) {
1046 			pol = sa->sa_policy;
1047 			if (ikev2_init_ike_sa_peer(env, pol,
1048 			    &pol->pol_peer, msg) != 0)
1049 				log_warnx("%s: failed to initiate a "
1050 				    "IKE_SA_INIT exchange", SPI_SA(sa,
1051 				    __func__));
1052 			break;
1053 		}
1054 		if (ikev2_handle_certreq(env, msg) != 0)
1055 			return;
1056 
1057 		(void)ikev2_init_auth(env, msg);
1058 		break;
1059 	case IKEV2_EXCHANGE_IKE_AUTH:
1060 		if (msg->msg_flags & IKED_MSG_FLAGS_AUTHENTICATION_FAILED) {
1061 			log_debug("%s: AUTHENTICATION_FAILED, closing SA",
1062 			    __func__);
1063 			ikev2_log_cert_info(SPI_SA(sa, __func__),
1064 			    sa->sa_hdr.sh_initiator ? &sa->sa_rcert
1065 			    : &sa->sa_icert);
1066 			ikev2_ike_sa_setreason(sa,
1067 			    "authentication failed notification from peer");
1068 			sa_state(env, sa, IKEV2_STATE_CLOSED);
1069 			msg->msg_sa = NULL;
1070 			return;
1071 		}
1072 
1073 		(void)ikev2_ike_auth_recv(env, sa, msg);
1074 		break;
1075 	case IKEV2_EXCHANGE_CREATE_CHILD_SA:
1076 		(void)ikev2_init_create_child_sa(env, msg);
1077 		break;
1078 	case IKEV2_EXCHANGE_INFORMATIONAL:
1079 		sa->sa_stateflags &= ~IKED_REQ_INF;
1080 		break;
1081 	default:
1082 		log_debug("%s: exchange %s not implemented", __func__,
1083 		    print_map(hdr->ike_exchange, ikev2_exchange_map));
1084 		break;
1085 	}
1086 }
1087 
1088 void
1089 ikev2_init_ike_sa(struct iked *env, void *arg)
1090 {
1091 	struct iked_policy	*pol;
1092 
1093 	TAILQ_FOREACH(pol, &env->sc_policies, pol_entry) {
1094 		if ((pol->pol_flags & IKED_POLICY_ACTIVE) == 0)
1095 			continue;
1096 		if (!TAILQ_EMPTY(&pol->pol_sapeers)) {
1097 			log_debug("%s: \"%s\" is already active",
1098 			    __func__, pol->pol_name);
1099 			continue;
1100 		}
1101 
1102 		log_info("%s: initiating \"%s\"", __func__, pol->pol_name);
1103 
1104 		if (ikev2_init_ike_sa_peer(env, pol, &pol->pol_peer, NULL))
1105 			log_debug("%s: failed to initiate with peer %s",
1106 			    __func__,
1107 			    print_host((struct sockaddr *)&pol->pol_peer.addr,
1108 			    NULL, 0));
1109 	}
1110 
1111 	timer_set(env, &env->sc_inittmr, ikev2_init_ike_sa, NULL);
1112 	timer_add(env, &env->sc_inittmr, IKED_INITIATOR_INTERVAL);
1113 }
1114 
1115 void
1116 ikev2_init_ike_sa_timeout(struct iked *env, void *arg)
1117 {
1118 	struct iked_sa	 *sa = arg;
1119 
1120 	log_debug("%s: ispi %s rspi %s", __func__,
1121 	    print_spi(sa->sa_hdr.sh_ispi, 8),
1122 	    print_spi(sa->sa_hdr.sh_rspi, 8));
1123 
1124 	ikev2_ike_sa_setreason(sa, "SA_INIT timeout");
1125 	sa_free(env, sa);
1126 }
1127 
1128 int
1129 ikev2_init_ike_sa_peer(struct iked *env, struct iked_policy *pol,
1130     struct iked_addr *peer, struct iked_message *retry)
1131 {
1132 	struct sockaddr_storage		 ss;
1133 	struct iked_message		 req;
1134 	struct ike_header		*hdr;
1135 	struct ikev2_payload		*pld;
1136 	struct ikev2_keyexchange	*ke;
1137 	struct ikev2_notify		*n;
1138 	struct iked_sa			*sa = NULL;
1139 	struct ibuf			*buf, *cookie = NULL;
1140 	struct group			*group;
1141 	ssize_t				 len;
1142 	int				 ret = -1;
1143 	struct iked_socket		*sock;
1144 	in_port_t			 port;
1145 
1146 	if ((sock = ikev2_msg_getsocket(env, peer->addr_af, 0)) == NULL)
1147 		return (-1);
1148 
1149 	if (retry != NULL) {
1150 		sa = retry->msg_sa;
1151 		cookie = retry->msg_cookie;
1152 		sa_state(env, sa, IKEV2_STATE_INIT);
1153 	}
1154 
1155 	/* Create a new initiator SA */
1156 	if (sa == NULL &&
1157 	    (sa = sa_new(env, 0, 0, 1, pol)) == NULL)
1158 		return (-1);
1159 
1160 	/* Pick peer's DH group if asked */
1161 	if (pol->pol_peerdh > 0 && sa->sa_dhgroup == NULL &&
1162 	    (sa->sa_dhgroup = group_get(pol->pol_peerdh)) == NULL) {
1163 		log_warnx("%s: invalid peer DH group %u", SPI_SA(sa, __func__),
1164 		    pol->pol_peerdh);
1165 		goto closeonly;
1166 	}
1167 	sa->sa_reqid = 0;
1168 
1169 	if (ikev2_sa_initiator(env, sa, NULL, NULL) == -1)
1170 		goto closeonly;
1171 
1172 	if (pol->pol_local.addr.ss_family == AF_UNSPEC) {
1173 		if (socket_getaddr(sock->sock_fd, &ss) == -1)
1174 			goto closeonly;
1175 	} else
1176 		memcpy(&ss, &pol->pol_local.addr, pol->pol_local.addr.ss_len);
1177 
1178 	if ((buf = ikev2_msg_init(env, &req, &peer->addr, peer->addr.ss_len,
1179 	    &ss, ss.ss_len, 0)) == NULL)
1180 		goto done;
1181 
1182 	/* Inherit the port from the 1st send socket */
1183 	port = htons(socket_getport((struct sockaddr *)&sock->sock_addr));
1184 	(void)socket_af((struct sockaddr *)&req.msg_local, port);
1185 	(void)socket_af((struct sockaddr *)&req.msg_peer, port);
1186 
1187 	req.msg_fd = sock->sock_fd;
1188 	req.msg_sa = sa;
1189 	req.msg_sock = sock;
1190 	req.msg_msgid = ikev2_msg_id(env, sa);
1191 
1192 	/* IKE header */
1193 	if ((hdr = ikev2_add_header(buf, sa, req.msg_msgid,
1194 	    cookie == NULL ? IKEV2_PAYLOAD_SA : IKEV2_PAYLOAD_NOTIFY,
1195 	    IKEV2_EXCHANGE_IKE_SA_INIT, 0)) == NULL)
1196 		goto done;
1197 
1198 	/* Reflect COOKIE */
1199 	if (cookie) {
1200 		if ((pld = ikev2_add_payload(buf)) == NULL)
1201 			goto done;
1202 		if ((n = ibuf_advance(buf, sizeof(*n))) == NULL)
1203 			goto done;
1204 		n->n_protoid = IKEV2_SAPROTO_NONE;
1205 		n->n_spisize = 0;
1206 		n->n_type = htobe16(IKEV2_N_COOKIE);
1207 		if (ikev2_add_buf(buf, cookie) == -1)
1208 			goto done;
1209 		len = sizeof(*n) + ibuf_size(cookie);
1210 
1211 		log_debug("%s: added cookie, len %zu", __func__,
1212 		    ibuf_size(cookie));
1213 		print_hex(ibuf_data(cookie), 0, ibuf_size(cookie));
1214 
1215 		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_SA) == -1)
1216 			goto done;
1217 	}
1218 
1219 	/* SA payload */
1220 	if ((pld = ikev2_add_payload(buf)) == NULL)
1221 		goto done;
1222 	if ((len = ikev2_add_proposals(env, sa, buf, &pol->pol_proposals,
1223 	    IKEV2_SAPROTO_IKE, sa->sa_hdr.sh_initiator, 0, 0)) == -1)
1224 		goto done;
1225 
1226 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_KE) == -1)
1227 		goto done;
1228 
1229 	/* KE payload */
1230 	if ((pld = ikev2_add_payload(buf)) == NULL)
1231 		goto done;
1232 	if ((ke = ibuf_advance(buf, sizeof(*ke))) == NULL)
1233 		goto done;
1234 	if ((group = sa->sa_dhgroup) == NULL) {
1235 		log_debug("%s: invalid dh", __func__);
1236 		goto done;
1237 	}
1238 	ke->kex_dhgroup = htobe16(group->id);
1239 	if (ikev2_add_buf(buf, sa->sa_dhiexchange) == -1)
1240 		goto done;
1241 	len = sizeof(*ke) + dh_getlen(group);
1242 
1243 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONCE) == -1)
1244 		goto done;
1245 
1246 	/* NONCE payload */
1247 	if ((pld = ikev2_add_payload(buf)) == NULL)
1248 		goto done;
1249 	if (ikev2_add_buf(buf, sa->sa_inonce) == -1)
1250 		goto done;
1251 	len = ibuf_size(sa->sa_inonce);
1252 
1253 	/* Fragmentation Notify */
1254 	if (env->sc_frag) {
1255 		if ((len = ikev2_add_fragmentation(buf, &pld, len))
1256 		    == -1)
1257 			goto done;
1258 	}
1259 
1260 	if (env->sc_nattmode != NATT_DISABLE) {
1261 		if (ntohs(port) == env->sc_nattport) {
1262 			/* Enforce NAT-T on the initiator side */
1263 			log_debug("%s: enforcing NAT-T", __func__);
1264 			req.msg_natt = sa->sa_natt = sa->sa_udpencap = 1;
1265 		}
1266 		if ((len = ikev2_add_nat_detection(env, buf, &pld, &req, len))
1267 		    == -1)
1268 			goto done;
1269 	}
1270 
1271 	if ((len = ikev2_add_sighashnotify(buf, &pld, len)) == -1)
1272 		goto done;
1273 
1274 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
1275 		goto done;
1276 
1277 	if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
1278 		goto done;
1279 
1280 	(void)ikev2_pld_parse(env, hdr, &req, 0);
1281 
1282 	ibuf_release(sa->sa_1stmsg);
1283 	if ((sa->sa_1stmsg = ibuf_dup(buf)) == NULL) {
1284 		log_debug("%s: failed to copy 1st message", __func__);
1285 		goto done;
1286 	}
1287 
1288 	if ((ret = ikev2_msg_send(env, &req)) == 0)
1289 		sa_state(env, sa, IKEV2_STATE_SA_INIT);
1290 
1291 	/* Setup exchange timeout. */
1292 	timer_set(env, &sa->sa_timer, ikev2_init_ike_sa_timeout, sa);
1293 	timer_add(env, &sa->sa_timer, IKED_IKE_SA_EXCHANGE_TIMEOUT);
1294 
1295  done:
1296 	ikev2_msg_cleanup(env, &req);
1297  closeonly:
1298 	if (ret == -1) {
1299 		log_debug("%s: closing SA", __func__);
1300 		ikev2_ike_sa_setreason(sa, "failed to send SA_INIT");
1301 		sa_free(env, sa);
1302 	}
1303 
1304 	return (ret);
1305 }
1306 
1307 int
1308 ikev2_init_auth(struct iked *env, struct iked_message *msg)
1309 {
1310 	struct iked_sa			*sa = msg->msg_sa;
1311 	struct ibuf			*authmsg;
1312 
1313 	if (sa == NULL)
1314 		return (-1);
1315 
1316 	if (ikev2_sa_initiator(env, sa, NULL, msg) == -1) {
1317 		log_debug("%s: failed to get IKE keys", __func__);
1318 		return (-1);
1319 	}
1320 
1321 	if ((authmsg = ikev2_msg_auth(env, sa,
1322 	    !sa->sa_hdr.sh_initiator)) == NULL) {
1323 		log_debug("%s: failed to get auth data", __func__);
1324 		return (-1);
1325 	}
1326 
1327 	if (ca_setauth(env, sa, authmsg, PROC_CERT) == -1) {
1328 		log_debug("%s: failed to get cert", __func__);
1329 		ibuf_release(authmsg);
1330 		return (-1);
1331 	}
1332 	ibuf_release(authmsg);
1333 
1334 	return (ikev2_init_ike_auth(env, sa));
1335 }
1336 
1337 int
1338 ikev2_init_ike_auth(struct iked *env, struct iked_sa *sa)
1339 {
1340 	struct iked_policy		*pol = sa->sa_policy;
1341 	struct ikev2_payload		*pld;
1342 	struct ikev2_cert		*cert;
1343 	struct ikev2_auth		*auth;
1344 	struct iked_id			*id, *certid;
1345 	struct ibuf			*e = NULL;
1346 	uint8_t				 firstpayload;
1347 	int				 ret = -1;
1348 	ssize_t				 len;
1349 
1350 	if (!sa_stateok(sa, IKEV2_STATE_SA_INIT))
1351 		return (0);
1352 
1353 	if (!sa->sa_localauth.id_type) {
1354 		log_debug("%s: no local auth", __func__);
1355 		return (-1);
1356 	}
1357 
1358 	/* New encrypted message buffer */
1359 	if ((e = ibuf_static()) == NULL)
1360 		goto done;
1361 
1362 	id = &sa->sa_iid;
1363 	certid = &sa->sa_icert;
1364 
1365 	/* ID payload */
1366 	if ((pld = ikev2_add_payload(e)) == NULL)
1367 		goto done;
1368 	firstpayload = IKEV2_PAYLOAD_IDi;
1369 	if (ibuf_cat(e, id->id_buf) != 0)
1370 		goto done;
1371 	len = ibuf_size(id->id_buf);
1372 
1373 	/* CERT payload */
1374 	if ((sa->sa_stateinit & IKED_REQ_CERT) &&
1375 	    (certid->id_type != IKEV2_CERT_NONE)) {
1376 		if (ikev2_next_payload(pld, len,
1377 		    IKEV2_PAYLOAD_CERT) == -1)
1378 			goto done;
1379 		if ((pld = ikev2_add_payload(e)) == NULL)
1380 			goto done;
1381 		if ((cert = ibuf_advance(e, sizeof(*cert))) == NULL)
1382 			goto done;
1383 		cert->cert_type = certid->id_type;
1384 		if (ibuf_cat(e, certid->id_buf) != 0)
1385 			goto done;
1386 		len = ibuf_size(certid->id_buf) + sizeof(*cert);
1387 
1388 		/* CERTREQ payload(s) */
1389 		if ((len = ikev2_add_certreq(e, &pld,
1390 		    len, env->sc_certreq, env->sc_certreqtype)) == -1)
1391 			goto done;
1392 
1393 		if (env->sc_certreqtype != pol->pol_certreqtype &&
1394 		    (len = ikev2_add_certreq(e, &pld,
1395 		    len, NULL, pol->pol_certreqtype)) == -1)
1396 			goto done;
1397 	}
1398 
1399 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_AUTH) == -1)
1400 		goto done;
1401 
1402 	/* AUTH payload */
1403 	if ((pld = ikev2_add_payload(e)) == NULL)
1404 		goto done;
1405 	if ((auth = ibuf_advance(e, sizeof(*auth))) == NULL)
1406 		goto done;
1407 	auth->auth_method = sa->sa_localauth.id_type;
1408 	if (ibuf_cat(e, sa->sa_localauth.id_buf) != 0)
1409 		goto done;
1410 	len = ibuf_size(sa->sa_localauth.id_buf) + sizeof(*auth);
1411 
1412 	/* CP payload */
1413 	if (sa->sa_cp) {
1414 		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_CP) == -1)
1415 			goto done;
1416 
1417 		if ((pld = ikev2_add_payload(e)) == NULL)
1418 			goto done;
1419 		if ((len = ikev2_add_cp(env, sa, e)) == -1)
1420 			goto done;
1421 	}
1422 
1423 	if ((pol->pol_flags & IKED_POLICY_IPCOMP) &&
1424 	    (len = ikev2_add_ipcompnotify(env, e, &pld, len, sa, 1)) == -1)
1425 		goto done;
1426 	if ((pol->pol_flags & IKED_POLICY_TRANSPORT) &&
1427 	    (len = ikev2_add_transport_mode(env, e, &pld, len, sa)) == -1)
1428 		goto done;
1429 
1430 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_SA) == -1)
1431 		goto done;
1432 
1433 	/* SA payload */
1434 	if ((pld = ikev2_add_payload(e)) == NULL)
1435 		goto done;
1436 	if ((len = ikev2_add_proposals(env, sa, e, &pol->pol_proposals, 0,
1437 	    sa->sa_hdr.sh_initiator, 0, 1)) == -1)
1438 		goto done;
1439 
1440 	if ((len = ikev2_add_ts(e, &pld, len, sa, 0)) == -1)
1441 		goto done;
1442 
1443 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
1444 		goto done;
1445 
1446 	ret = ikev2_msg_send_encrypt(env, sa, &e,
1447 	    IKEV2_EXCHANGE_IKE_AUTH, firstpayload, 0);
1448 
1449  done:
1450 	ibuf_release(e);
1451 
1452 	return (ret);
1453 }
1454 
1455 void
1456 ikev2_enable_timer(struct iked *env, struct iked_sa *sa)
1457 {
1458 	sa->sa_last_recvd = gettime();
1459 	timer_set(env, &sa->sa_timer, ikev2_ike_sa_alive, sa);
1460 	if (env->sc_alive_timeout > 0)
1461 		timer_add(env, &sa->sa_timer, env->sc_alive_timeout);
1462 	timer_set(env, &sa->sa_keepalive, ikev2_ike_sa_keepalive, sa);
1463 	if (sa->sa_usekeepalive)
1464 		timer_add(env, &sa->sa_keepalive,
1465 		    IKED_IKE_SA_KEEPALIVE_TIMEOUT);
1466 	timer_set(env, &sa->sa_rekey, ikev2_ike_sa_rekey, sa);
1467 	if (sa->sa_policy->pol_rekey)
1468 		ikev2_ike_sa_rekey_schedule(env, sa);
1469 }
1470 
1471 void
1472 ikev2_reset_alive_timer(struct iked *env)
1473 {
1474 	struct iked_sa			*sa;
1475 
1476 	RB_FOREACH(sa, iked_sas, &env->sc_sas) {
1477 		if (sa->sa_state != IKEV2_STATE_ESTABLISHED)
1478 			continue;
1479 		timer_del(env, &sa->sa_timer);
1480 		if (env->sc_alive_timeout > 0)
1481 			timer_add(env, &sa->sa_timer, env->sc_alive_timeout);
1482 	}
1483 }
1484 
1485 void
1486 ikev2_disable_timer(struct iked *env, struct iked_sa *sa)
1487 {
1488 	timer_del(env, &sa->sa_timer);
1489 	timer_del(env, &sa->sa_keepalive);
1490 	timer_del(env, &sa->sa_rekey);
1491 }
1492 
1493 int
1494 ikev2_init_done(struct iked *env, struct iked_sa *sa)
1495 {
1496 	int		 ret;
1497 
1498 	if (!sa_stateok(sa, IKEV2_STATE_VALID))
1499 		return (0);	/* ignored */
1500 
1501 	ret = ikev2_childsa_negotiate(env, sa, &sa->sa_kex, &sa->sa_proposals,
1502 	    sa->sa_hdr.sh_initiator, 0, 0);
1503 	if (ret == 0)
1504 		ret = ikev2_childsa_enable(env, sa);
1505 	if (ret == 0) {
1506 		sa_state(env, sa, IKEV2_STATE_ESTABLISHED);
1507 		/* Delete exchange timeout. */
1508 		timer_del(env, &sa->sa_timer);
1509 		ikev2_enable_timer(env, sa);
1510 		ikev2_log_established(sa);
1511 		ikev2_record_dstid(env, sa);
1512 	}
1513 
1514 	if (ret)
1515 		ikev2_childsa_delete(env, sa, 0, 0, NULL, 1);
1516 	return (ret);
1517 }
1518 
1519 int
1520 ikev2_policy2id(struct iked_static_id *polid, struct iked_id *id, int srcid)
1521 {
1522 	struct ikev2_id		 hdr;
1523 	struct iked_static_id	 localpid;
1524 	char			 idstr[IKED_ID_SIZE];
1525 	struct in_addr		 in4;
1526 	struct in6_addr		 in6;
1527 	X509_NAME		*name = NULL;
1528 	uint8_t			*p;
1529 	int			 len;
1530 
1531 	/* Fixup the local Id if not specified */
1532 	if (srcid && polid->id_type == 0) {
1533 		polid = &localpid;
1534 		bzero(polid, sizeof(*polid));
1535 
1536 		/* Create a default local ID based on our FQDN */
1537 		polid->id_type = IKEV2_ID_FQDN;
1538 		if (gethostname((char *)polid->id_data,
1539 		    sizeof(polid->id_data)) != 0)
1540 			return (-1);
1541 		polid->id_offset = 0;
1542 		polid->id_length =
1543 		    strlen((char *)polid->id_data); /* excluding NUL */
1544 	}
1545 
1546 	if (!polid->id_length)
1547 		return (-1);
1548 
1549 	/* Create an IKEv2 ID payload */
1550 	bzero(&hdr, sizeof(hdr));
1551 	hdr.id_type = id->id_type = polid->id_type;
1552 	id->id_offset = sizeof(hdr);
1553 
1554 	ibuf_free(id->id_buf);
1555 	if ((id->id_buf = ibuf_new(&hdr, sizeof(hdr))) == NULL)
1556 		return (-1);
1557 
1558 	switch (id->id_type) {
1559 	case IKEV2_ID_IPV4:
1560 		if (inet_pton(AF_INET, (char *)polid->id_data, &in4) != 1 ||
1561 		    ibuf_add(id->id_buf, &in4, sizeof(in4)) != 0) {
1562 			ibuf_release(id->id_buf);
1563 			id->id_buf = NULL;
1564 			return (-1);
1565 		}
1566 		break;
1567 	case IKEV2_ID_IPV6:
1568 		if (inet_pton(AF_INET6, (char *)polid->id_data, &in6) != 1 ||
1569 		    ibuf_add(id->id_buf, &in6, sizeof(in6)) != 0) {
1570 			ibuf_release(id->id_buf);
1571 			id->id_buf = NULL;
1572 			return (-1);
1573 		}
1574 		break;
1575 	case IKEV2_ID_ASN1_DN:
1576 		/* policy has ID in string-format, convert to ASN1 */
1577 		if ((name = ca_x509_name_parse(polid->id_data)) == NULL ||
1578 		    (len = i2d_X509_NAME(name, NULL)) < 0 ||
1579 		    (p = ibuf_reserve(id->id_buf, len)) == NULL ||
1580 		    (i2d_X509_NAME(name, &p)) < 0) {
1581 			if (name)
1582 				X509_NAME_free(name);
1583 			ibuf_release(id->id_buf);
1584 			id->id_buf = NULL;
1585 			return (-1);
1586 		}
1587 		X509_NAME_free(name);
1588 		break;
1589 	default:
1590 		if (ibuf_add(id->id_buf,
1591 		    polid->id_data, polid->id_length) != 0) {
1592 			ibuf_release(id->id_buf);
1593 			id->id_buf = NULL;
1594 			return (-1);
1595 		}
1596 		break;
1597 	}
1598 
1599 	if (ikev2_print_id(id, idstr, sizeof(idstr)) == -1)
1600 		return (-1);
1601 
1602 	log_debug("%s: %s %s length %zu", __func__,
1603 	    srcid ? "srcid" : "dstid",
1604 	    idstr, ibuf_size(id->id_buf));
1605 
1606 	return (0);
1607 }
1608 
1609 struct ike_header *
1610 ikev2_add_header(struct ibuf *buf, struct iked_sa *sa,
1611     uint32_t msgid, uint8_t nextpayload,
1612     uint8_t exchange, uint8_t flags)
1613 {
1614 	struct ike_header	*hdr;
1615 
1616 	if ((hdr = ibuf_advance(buf, sizeof(*hdr))) == NULL) {
1617 		log_debug("%s: failed to add header", __func__);
1618 		return (NULL);
1619 	}
1620 
1621 	hdr->ike_ispi = htobe64(sa->sa_hdr.sh_ispi);
1622 	hdr->ike_rspi = htobe64(sa->sa_hdr.sh_rspi);
1623 	hdr->ike_nextpayload = nextpayload;
1624 	hdr->ike_version = IKEV2_VERSION;
1625 	hdr->ike_exchange = exchange;
1626 	hdr->ike_msgid = htobe32(msgid);
1627 	hdr->ike_length = htobe32(sizeof(*hdr));
1628 	hdr->ike_flags = flags;
1629 
1630 	if (sa->sa_hdr.sh_initiator)
1631 		hdr->ike_flags |= IKEV2_FLAG_INITIATOR;
1632 
1633 	return (hdr);
1634 }
1635 
1636 int
1637 ikev2_set_header(struct ike_header *hdr, size_t length)
1638 {
1639 	uint32_t	 hdrlength = sizeof(*hdr) + length;
1640 
1641 	if (hdrlength > UINT32_MAX) {
1642 		log_debug("%s: message too long", __func__);
1643 		return (-1);
1644 	}
1645 
1646 	hdr->ike_length = htobe32(sizeof(*hdr) + length);
1647 
1648 	return (0);
1649 }
1650 
1651 struct ikev2_payload *
1652 ikev2_add_payload(struct ibuf *buf)
1653 {
1654 	struct ikev2_payload	*pld;
1655 
1656 	if ((pld = ibuf_advance(buf, sizeof(*pld))) == NULL) {
1657 		log_debug("%s: failed to add payload", __func__);
1658 		return (NULL);
1659 	}
1660 
1661 	pld->pld_nextpayload = IKEV2_PAYLOAD_NONE;
1662 	pld->pld_length = sizeof(*pld);
1663 
1664 	return (pld);
1665 }
1666 
1667 ssize_t
1668 ikev2_add_ts_payload(struct ibuf *buf, unsigned int type, struct iked_sa *sa)
1669 {
1670 	struct iked_policy	*pol = sa->sa_policy;
1671 	struct ikev2_tsp	*tsp;
1672 	struct ikev2_ts		*ts;
1673 	struct iked_addr	*addr;
1674 	struct iked_addr	 pooladdr;
1675 	uint8_t			*ptr;
1676 	size_t			 len = 0;
1677 	uint32_t		 av[4], bv[4], mv[4];
1678 	struct sockaddr_in	*in4;
1679 	struct sockaddr_in6	*in6;
1680 	struct iked_tss		*tss;
1681 	struct iked_ts		*tsi;
1682 
1683 	bzero(&pooladdr, sizeof(pooladdr));
1684 
1685 	if ((tsp = ibuf_advance(buf, sizeof(*tsp))) == NULL)
1686 		return (-1);
1687 	len = sizeof(*tsp);
1688 
1689 	if (type == IKEV2_PAYLOAD_TSi) {
1690 		if (sa->sa_hdr.sh_initiator) {
1691 			tss = &pol->pol_tssrc;
1692 			tsp->tsp_count = pol->pol_tssrc_count;
1693 		} else {
1694 			tss = &pol->pol_tsdst;
1695 			tsp->tsp_count = pol->pol_tsdst_count;
1696 		}
1697 	} else if (type == IKEV2_PAYLOAD_TSr) {
1698 		if (sa->sa_hdr.sh_initiator) {
1699 			tss = &pol->pol_tsdst;
1700 			tsp->tsp_count = pol->pol_tsdst_count;
1701 		} else {
1702 			tss = &pol->pol_tssrc;
1703 			tsp->tsp_count = pol->pol_tssrc_count;
1704 		}
1705 	} else
1706 		return (-1);
1707 
1708 	TAILQ_FOREACH(tsi, tss, ts_entry) {
1709 		if ((ts = ibuf_advance(buf, sizeof(*ts))) == NULL)
1710 			return (-1);
1711 
1712 		addr = &tsi->ts_addr;
1713 
1714 		/* patch remote address (if configured to 0.0.0.0) */
1715 		if ((type == IKEV2_PAYLOAD_TSi && !sa->sa_hdr.sh_initiator) ||
1716 		    (type == IKEV2_PAYLOAD_TSr && sa->sa_hdr.sh_initiator)) {
1717 			if (ikev2_cp_fixaddr(sa, addr, &pooladdr) != -1)
1718 				addr = &pooladdr;
1719 		}
1720 
1721 		ts->ts_protoid = tsi->ts_ipproto;
1722 
1723 		if (addr->addr_port) {
1724 			ts->ts_startport = addr->addr_port;
1725 			ts->ts_endport = addr->addr_port;
1726 		} else {
1727 			ts->ts_startport = 0;
1728 			ts->ts_endport = 0xffff;
1729 		}
1730 
1731 		switch (addr->addr_af) {
1732 		case AF_INET:
1733 			ts->ts_type = IKEV2_TS_IPV4_ADDR_RANGE;
1734 			ts->ts_length = htobe16(sizeof(*ts) + 8);
1735 
1736 			if ((ptr = ibuf_advance(buf, 8)) == NULL)
1737 				return (-1);
1738 
1739 			in4 = (struct sockaddr_in *)&addr->addr;
1740 			if (addr->addr_net) {
1741 				/* Convert IPv4 network to address range */
1742 				mv[0] = prefixlen2mask(addr->addr_mask);
1743 				av[0] = in4->sin_addr.s_addr & mv[0];
1744 				bv[0] = in4->sin_addr.s_addr | ~mv[0];
1745 			} else
1746 				av[0] = bv[0] = in4->sin_addr.s_addr;
1747 
1748 			memcpy(ptr, &av[0], 4);
1749 			memcpy(ptr + 4, &bv[0], 4);
1750 			break;
1751 		case AF_INET6:
1752 			ts->ts_type = IKEV2_TS_IPV6_ADDR_RANGE;
1753 			ts->ts_length = htobe16(sizeof(*ts) + 32);
1754 
1755 			if ((ptr = ibuf_advance(buf, 32)) == NULL)
1756 				return (-1);
1757 
1758 			in6 = (struct sockaddr_in6 *)&addr->addr;
1759 
1760 			memcpy(&av, &in6->sin6_addr.s6_addr, 16);
1761 			memcpy(&bv, &in6->sin6_addr.s6_addr, 16);
1762 			if (addr->addr_net) {
1763 				/* Convert IPv6 network to address range */
1764 				prefixlen2mask6(addr->addr_mask, mv);
1765 				av[0] &= mv[0];
1766 				av[1] &= mv[1];
1767 				av[2] &= mv[2];
1768 				av[3] &= mv[3];
1769 				bv[0] |= ~mv[0];
1770 				bv[1] |= ~mv[1];
1771 				bv[2] |= ~mv[2];
1772 				bv[3] |= ~mv[3];
1773 			}
1774 
1775 			memcpy(ptr, &av, 16);
1776 			memcpy(ptr + 16, &bv, 16);
1777 			break;
1778 		}
1779 
1780 		len += betoh16(ts->ts_length);
1781 	}
1782 
1783 	return (len);
1784 }
1785 
1786 ssize_t
1787 ikev2_add_ts(struct ibuf *e, struct ikev2_payload **pld, ssize_t len,
1788     struct iked_sa *sa, int reverse)
1789 {
1790 	if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_TSi) == -1)
1791 		return (-1);
1792 
1793 	/* TSi payload */
1794 	if ((*pld = ikev2_add_payload(e)) == NULL)
1795 		return (-1);
1796 	if ((len = ikev2_add_ts_payload(e, reverse ? IKEV2_PAYLOAD_TSr :
1797 	    IKEV2_PAYLOAD_TSi, sa)) == -1)
1798 		return (-1);
1799 
1800 	if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_TSr) == -1)
1801 		return (-1);
1802 
1803 	/* TSr payload */
1804 	if ((*pld = ikev2_add_payload(e)) == NULL)
1805 		return (-1);
1806 	if ((len = ikev2_add_ts_payload(e, reverse ? IKEV2_PAYLOAD_TSi :
1807 	    IKEV2_PAYLOAD_TSr, sa)) == -1)
1808 		return (-1);
1809 
1810 	return (len);
1811 }
1812 
1813 
1814 ssize_t
1815 ikev2_add_certreq(struct ibuf *e, struct ikev2_payload **pld, ssize_t len,
1816     struct ibuf *certreq, uint8_t type)
1817 {
1818 	struct ikev2_cert	*cert;
1819 
1820 	if (type == IKEV2_CERT_NONE)
1821 		return (len);
1822 
1823 	if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_CERTREQ) == -1)
1824 		return (-1);
1825 
1826 	/* CERTREQ payload */
1827 	if ((*pld = ikev2_add_payload(e)) == NULL)
1828 		return (-1);
1829 
1830 	if ((cert = ibuf_advance(e, sizeof(*cert))) == NULL)
1831 		return (-1);
1832 
1833 	cert->cert_type = type;
1834 	len = sizeof(*cert);
1835 
1836 	if (certreq != NULL && cert->cert_type == IKEV2_CERT_X509_CERT) {
1837 		if (ikev2_add_buf(e, certreq) == -1)
1838 			return (-1);
1839 		len += ibuf_size(certreq);
1840 	}
1841 
1842 	log_debug("%s: type %s length %zd", __func__,
1843 	    print_map(type, ikev2_cert_map), len);
1844 
1845 	return (len);
1846 }
1847 
1848 ssize_t
1849 ikev2_add_ipcompnotify(struct iked *env, struct ibuf *e,
1850     struct ikev2_payload **pld, ssize_t len, struct iked_sa *sa,
1851     int initiator)
1852 {
1853 	struct iked_childsa		 csa;
1854 	struct iked_ipcomp		*ic;
1855 	struct ikev2_notify		*n;
1856 	uint8_t				*ptr;
1857 	uint16_t			 cpi;
1858 	uint32_t			 spi;
1859 	uint8_t				 transform;
1860 
1861 	/* we only support deflate */
1862 	transform = IKEV2_IPCOMP_DEFLATE;
1863 	ic = initiator ? &sa->sa_ipcompi : &sa->sa_ipcompr;
1864 
1865 	if (initiator) {
1866 		bzero(&csa, sizeof(csa));
1867 		csa.csa_saproto = IKEV2_SAPROTO_IPCOMP;
1868 		csa.csa_ikesa = sa;
1869 		csa.csa_local = &sa->sa_peer;
1870 		csa.csa_peer = &sa->sa_local;
1871 		if (pfkey_sa_init(env->sc_pfkey, &csa, &spi) == -1)
1872 			return (-1);
1873 		ic->ic_cpi_in = spi;
1874 	} else {
1875 		spi = ic->ic_cpi_in;
1876 		/* make sure IPCOMP CPIs are not reused */
1877 		ic->ic_transform = 0;
1878 		ic->ic_cpi_in = 0;
1879 		ic->ic_cpi_out = 0;
1880 	}
1881 	log_debug("%s: ic_cpi_in 0x%04x", __func__, spi);
1882 
1883 	/*
1884 	 * We get spi == 0 if the kernel does not support IPcomp,
1885 	 * so just return the length of the current payload.
1886 	 */
1887 	if (spi == 0)
1888 		return (len);
1889 	cpi = htobe16((uint16_t)spi);
1890 	if (*pld)
1891 		if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_NOTIFY) == -1)
1892 			return (-1);
1893 	if ((*pld = ikev2_add_payload(e)) == NULL)
1894 		return (-1);
1895 	len = sizeof(*n) + sizeof(cpi) + sizeof(transform);
1896 	if ((ptr = ibuf_advance(e, len)) == NULL)
1897 		return (-1);
1898 	n = (struct ikev2_notify *)ptr;
1899 	n->n_protoid = 0;
1900 	n->n_spisize = 0;
1901 	n->n_type = htobe16(IKEV2_N_IPCOMP_SUPPORTED);
1902 	ptr += sizeof(*n);
1903 	memcpy(ptr, &cpi, sizeof(cpi));
1904 	ptr += sizeof(cpi);
1905 	memcpy(ptr, &transform, sizeof(transform));
1906 
1907 	return (len);
1908 }
1909 
1910 ssize_t
1911 ikev2_add_notify(struct ibuf *e, struct ikev2_payload **pld, ssize_t len,
1912     uint16_t notify)
1913 {
1914 	struct ikev2_notify		*n;
1915 
1916 	if (*pld)
1917 		if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_NOTIFY) == -1)
1918 			return (-1);
1919 	if ((*pld = ikev2_add_payload(e)) == NULL)
1920 		return (-1);
1921 	len = sizeof(*n);
1922 	if ((n = ibuf_advance(e, len)) == NULL)
1923 		return (-1);
1924 	n->n_protoid = 0;
1925 	n->n_spisize = 0;
1926 	n->n_type = htobe16(notify);
1927 	log_debug("%s: done", __func__);
1928 
1929 	return (len);
1930 }
1931 
1932 ssize_t
1933 ikev2_add_mobike(struct ibuf *e, struct ikev2_payload **pld, ssize_t len)
1934 {
1935 	return ikev2_add_notify(e, pld, len, IKEV2_N_MOBIKE_SUPPORTED);
1936 }
1937 
1938 ssize_t
1939 ikev2_add_fragmentation(struct ibuf *buf, struct ikev2_payload **pld,
1940     ssize_t len)
1941 {
1942 	return ikev2_add_notify(buf, pld, len, IKEV2_N_FRAGMENTATION_SUPPORTED);
1943 }
1944 
1945 ssize_t
1946 ikev2_add_sighashnotify(struct ibuf *e, struct ikev2_payload **pld,
1947     ssize_t len)
1948 {
1949 	struct ikev2_notify		*n;
1950 	uint8_t				*ptr;
1951 	size_t				 i;
1952 	uint16_t			 hash, signature_hashes[] = {
1953 		IKEV2_SIGHASH_SHA2_256,
1954 		IKEV2_SIGHASH_SHA2_384,
1955 		IKEV2_SIGHASH_SHA2_512
1956 	};
1957 
1958 	if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_NOTIFY) == -1)
1959 		return (-1);
1960 
1961 	/* XXX signature_hashes are hardcoded for now */
1962 	len = sizeof(*n) + nitems(signature_hashes) * sizeof(hash);
1963 
1964 	/* NOTIFY payload */
1965 	if ((*pld = ikev2_add_payload(e)) == NULL)
1966 		return (-1);
1967 	if ((ptr = ibuf_advance(e, len)) == NULL)
1968 		return (-1);
1969 
1970 	n = (struct ikev2_notify *)ptr;
1971 	n->n_protoid = 0;
1972 	n->n_spisize = 0;
1973 	n->n_type = htobe16(IKEV2_N_SIGNATURE_HASH_ALGORITHMS);
1974 	ptr += sizeof(*n);
1975 
1976 	for (i = 0; i < nitems(signature_hashes); i++) {
1977 		hash = htobe16(signature_hashes[i]);
1978 		memcpy(ptr, &hash, sizeof(hash));
1979 		ptr += sizeof(hash);
1980 	}
1981 
1982 	return (len);
1983 }
1984 
1985 ssize_t
1986 ikev2_add_transport_mode(struct iked *env, struct ibuf *e,
1987     struct ikev2_payload **pld, ssize_t len, struct iked_sa *sa)
1988 {
1989 	return ikev2_add_notify(e, pld, len, IKEV2_N_USE_TRANSPORT_MODE);
1990 }
1991 
1992 int
1993 ikev2_next_payload(struct ikev2_payload *pld, size_t length,
1994     uint8_t nextpayload)
1995 {
1996 	size_t	 pldlength = sizeof(*pld) + length;
1997 
1998 	if (pldlength > UINT16_MAX) {
1999 		log_debug("%s: payload too long", __func__);
2000 		return (-1);
2001 	}
2002 
2003 	log_debug("%s: length %zu nextpayload %s",
2004 	    __func__, pldlength, print_map(nextpayload, ikev2_payload_map));
2005 
2006 	pld->pld_length = htobe16(pldlength);
2007 	pld->pld_nextpayload = nextpayload;
2008 
2009 	return (0);
2010 }
2011 
2012 ssize_t
2013 ikev2_nat_detection(struct iked *env, struct iked_message *msg,
2014     void *ptr, size_t len, unsigned int type)
2015 {
2016 	EVP_MD_CTX		 ctx;
2017 	struct ike_header	*hdr;
2018 	uint8_t			 md[SHA_DIGEST_LENGTH];
2019 	unsigned int		 mdlen = sizeof(md);
2020 	struct iked_sa		*sa = msg->msg_sa;
2021 	struct sockaddr_in	*in4;
2022 	struct sockaddr_in6	*in6;
2023 	ssize_t			 ret = -1;
2024 	struct sockaddr		*src, *dst, *ss;
2025 	uint64_t		 rspi, ispi;
2026 	struct ibuf		*buf;
2027 	int			 frompeer = 0;
2028 	uint32_t		 rnd;
2029 
2030 	if (ptr == NULL)
2031 		return (mdlen);
2032 
2033 	if (ikev2_msg_frompeer(msg)) {
2034 		buf = msg->msg_parent->msg_data;
2035 		if ((hdr = ibuf_seek(buf, 0, sizeof(*hdr))) == NULL)
2036 			return (-1);
2037 		ispi = hdr->ike_ispi;
2038 		rspi = hdr->ike_rspi;
2039 		frompeer = 1;
2040 		src = (struct sockaddr *)&msg->msg_peer;
2041 		dst = (struct sockaddr *)&msg->msg_local;
2042 	} else {
2043 		ispi = htobe64(sa->sa_hdr.sh_ispi);
2044 		rspi = htobe64(sa->sa_hdr.sh_rspi);
2045 		frompeer = 0;
2046 		src = (struct sockaddr *)&msg->msg_local;
2047 		dst = (struct sockaddr *)&msg->msg_peer;
2048 	}
2049 
2050 	EVP_MD_CTX_init(&ctx);
2051 	EVP_DigestInit_ex(&ctx, EVP_sha1(), NULL);
2052 
2053 	switch (type) {
2054 	case IKEV2_N_NAT_DETECTION_SOURCE_IP:
2055 		log_debug("%s: %s source %s %s %s", __func__,
2056 		    frompeer ? "peer" : "local",
2057 		    print_spi(betoh64(ispi), 8),
2058 		    print_spi(betoh64(rspi), 8),
2059 		    print_host(src, NULL, 0));
2060 		ss = src;
2061 		break;
2062 	case IKEV2_N_NAT_DETECTION_DESTINATION_IP:
2063 		log_debug("%s: %s destination %s %s %s", __func__,
2064 		    frompeer ? "peer" : "local",
2065 		    print_spi(betoh64(ispi), 8),
2066 		    print_spi(betoh64(rspi), 8),
2067 		    print_host(dst, NULL, 0));
2068 		ss = dst;
2069 		break;
2070 	default:
2071 		goto done;
2072 	}
2073 
2074 	EVP_DigestUpdate(&ctx, &ispi, sizeof(ispi));
2075 	EVP_DigestUpdate(&ctx, &rspi, sizeof(rspi));
2076 
2077 	switch (ss->sa_family) {
2078 	case AF_INET:
2079 		in4 = (struct sockaddr_in *)ss;
2080 		EVP_DigestUpdate(&ctx, &in4->sin_addr.s_addr,
2081 		    sizeof(in4->sin_addr.s_addr));
2082 		EVP_DigestUpdate(&ctx, &in4->sin_port,
2083 		    sizeof(in4->sin_port));
2084 		break;
2085 	case AF_INET6:
2086 		in6 = (struct sockaddr_in6 *)ss;
2087 		EVP_DigestUpdate(&ctx, &in6->sin6_addr.s6_addr,
2088 		    sizeof(in6->sin6_addr.s6_addr));
2089 		EVP_DigestUpdate(&ctx, &in6->sin6_port,
2090 		    sizeof(in6->sin6_port));
2091 		break;
2092 	default:
2093 		goto done;
2094 	}
2095 
2096 	if (env->sc_nattmode == NATT_FORCE) {
2097 		/* Enforce NAT-T/UDP-encapsulation by distorting the digest */
2098 		rnd = arc4random();
2099 		EVP_DigestUpdate(&ctx, &rnd, sizeof(rnd));
2100 	}
2101 
2102 	EVP_DigestFinal_ex(&ctx, md, &mdlen);
2103 
2104 	if (len < mdlen)
2105 		goto done;
2106 
2107 	memcpy(ptr, md, mdlen);
2108 	ret = mdlen;
2109  done:
2110 	EVP_MD_CTX_cleanup(&ctx);
2111 
2112 	return (ret);
2113 }
2114 
2115 ssize_t
2116 ikev2_add_nat_detection(struct iked *env, struct ibuf *buf,
2117     struct ikev2_payload **pld, struct iked_message *msg, ssize_t len)
2118 {
2119 	struct ikev2_notify		*n;
2120 	uint8_t			*ptr;
2121 
2122 	/* *pld is NULL if there is no previous payload */
2123 	if (*pld != NULL) {
2124 		if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_NOTIFY) == -1)
2125 			return (-1);
2126 	}
2127 	/* NAT-T notify payloads */
2128 	if ((*pld = ikev2_add_payload(buf)) == NULL)
2129 		return (-1);
2130 	if ((n = ibuf_advance(buf, sizeof(*n))) == NULL)
2131 		return (-1);
2132 	n->n_type = htobe16(IKEV2_N_NAT_DETECTION_SOURCE_IP);
2133 	len = ikev2_nat_detection(env, msg, NULL, 0, 0);
2134 	if ((ptr = ibuf_advance(buf, len)) == NULL)
2135 		return (-1);
2136 	if ((len = ikev2_nat_detection(env, msg, ptr, len,
2137 	    betoh16(n->n_type))) == -1)
2138 		return (-1);
2139 	len += sizeof(*n);
2140 
2141 	if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_NOTIFY) == -1)
2142 		return (-1);
2143 
2144 	if ((*pld = ikev2_add_payload(buf)) == NULL)
2145 		return (-1);
2146 	if ((n = ibuf_advance(buf, sizeof(*n))) == NULL)
2147 		return (-1);
2148 	n->n_type = htobe16(IKEV2_N_NAT_DETECTION_DESTINATION_IP);
2149 	len = ikev2_nat_detection(env, msg, NULL, 0, 0);
2150 	if ((ptr = ibuf_advance(buf, len)) == NULL)
2151 		return (-1);
2152 	if ((len = ikev2_nat_detection(env, msg, ptr, len,
2153 	    betoh16(n->n_type))) == -1)
2154 		return (-1);
2155 	len += sizeof(*n);
2156 	return (len);
2157 }
2158 
2159 ssize_t
2160 ikev2_add_cp(struct iked *env, struct iked_sa *sa, struct ibuf *buf)
2161 {
2162 	struct iked_policy	*pol = sa->sa_policy;
2163 	struct ikev2_cp		*cp;
2164 	struct ikev2_cfg	*cfg;
2165 	struct iked_cfg		*ikecfg;
2166 	unsigned int		 i;
2167 	uint32_t		 mask4;
2168 	size_t			 len;
2169 	struct sockaddr_in	*in4;
2170 	struct sockaddr_in6	*in6;
2171 	uint8_t			 prefixlen;
2172 
2173 	if ((cp = ibuf_advance(buf, sizeof(*cp))) == NULL)
2174 		return (-1);
2175 	len = sizeof(*cp);
2176 
2177 	switch (sa->sa_cp) {
2178 	case IKEV2_CP_REQUEST:
2179 		cp->cp_type = IKEV2_CP_REPLY;
2180 		break;
2181 	case IKEV2_CP_REPLY:
2182 	case IKEV2_CP_SET:
2183 	case IKEV2_CP_ACK:
2184 		/* Not yet supported */
2185 		return (-1);
2186 	}
2187 
2188 	for (i = 0; i < pol->pol_ncfg; i++) {
2189 		ikecfg = &pol->pol_cfg[i];
2190 		if (ikecfg->cfg_action != cp->cp_type)
2191 			continue;
2192 
2193 		if ((cfg = ibuf_advance(buf, sizeof(*cfg))) == NULL)
2194 			return (-1);
2195 
2196 		cfg->cfg_type = htobe16(ikecfg->cfg_type);
2197 		len += sizeof(*cfg);
2198 
2199 		switch (ikecfg->cfg_type) {
2200 		case IKEV2_CFG_INTERNAL_IP4_ADDRESS:
2201 		case IKEV2_CFG_INTERNAL_IP4_NETMASK:
2202 		case IKEV2_CFG_INTERNAL_IP4_DNS:
2203 		case IKEV2_CFG_INTERNAL_IP4_NBNS:
2204 		case IKEV2_CFG_INTERNAL_IP4_DHCP:
2205 		case IKEV2_CFG_INTERNAL_IP4_SERVER:
2206 			/* 4 bytes IPv4 address */
2207 			in4 = (ikecfg->cfg.address.addr_mask != 32 &&
2208 			    (ikecfg->cfg_type ==
2209 			    IKEV2_CFG_INTERNAL_IP4_ADDRESS) &&
2210 			    sa->sa_addrpool &&
2211 			    sa->sa_addrpool->addr_af == AF_INET) ?
2212 			    (struct sockaddr_in *)&sa->sa_addrpool->addr :
2213 			    (struct sockaddr_in *)&ikecfg->cfg.address.addr;
2214 			cfg->cfg_length = htobe16(4);
2215 			if (ibuf_add(buf, &in4->sin_addr.s_addr, 4) == -1)
2216 				return (-1);
2217 			len += 4;
2218 			break;
2219 		case IKEV2_CFG_INTERNAL_IP4_SUBNET:
2220 			/* 4 bytes IPv4 address + 4 bytes IPv4 mask + */
2221 			in4 = (struct sockaddr_in *)&ikecfg->cfg.address.addr;
2222 			mask4 = prefixlen2mask(ikecfg->cfg.address.addr_mask);
2223 			cfg->cfg_length = htobe16(8);
2224 			if (ibuf_add(buf, &in4->sin_addr.s_addr, 4) == -1)
2225 				return (-1);
2226 			if (ibuf_add(buf, &mask4, 4) == -1)
2227 				return (-1);
2228 			len += 8;
2229 			break;
2230 		case IKEV2_CFG_INTERNAL_IP6_DNS:
2231 		case IKEV2_CFG_INTERNAL_IP6_NBNS:
2232 		case IKEV2_CFG_INTERNAL_IP6_DHCP:
2233 		case IKEV2_CFG_INTERNAL_IP6_SERVER:
2234 			/* 16 bytes IPv6 address */
2235 			in6 = (struct sockaddr_in6 *)&ikecfg->cfg.address.addr;
2236 			cfg->cfg_length = htobe16(16);
2237 			if (ibuf_add(buf, &in6->sin6_addr.s6_addr, 16) == -1)
2238 				return (-1);
2239 			len += 16;
2240 			break;
2241 		case IKEV2_CFG_INTERNAL_IP6_ADDRESS:
2242 		case IKEV2_CFG_INTERNAL_IP6_SUBNET:
2243 			/* 16 bytes IPv6 address + 1 byte prefix length */
2244 			in6 = (ikecfg->cfg.address.addr_mask != 128 &&
2245 			    (ikecfg->cfg_type ==
2246 			    IKEV2_CFG_INTERNAL_IP6_ADDRESS) &&
2247 			    sa->sa_addrpool6 &&
2248 			    sa->sa_addrpool6->addr_af == AF_INET6) ?
2249 			    (struct sockaddr_in6 *)&sa->sa_addrpool6->addr :
2250 			    (struct sockaddr_in6 *)&ikecfg->cfg.address.addr;
2251 			cfg->cfg_length = htobe16(17);
2252 			if (ibuf_add(buf, &in6->sin6_addr.s6_addr, 16) == -1)
2253 				return (-1);
2254 			if (ikecfg->cfg.address.addr_net)
2255 				prefixlen = ikecfg->cfg.address.addr_mask;
2256 			else
2257 				prefixlen = 128;
2258 			if (ibuf_add(buf, &prefixlen, 1) == -1)
2259 				return (-1);
2260 			len += 16 + 1;
2261 			break;
2262 		case IKEV2_CFG_APPLICATION_VERSION:
2263 			/* Reply with an empty string (non-NUL terminated) */
2264 			cfg->cfg_length = 0;
2265 			break;
2266 		}
2267 	}
2268 
2269 	return (len);
2270 }
2271 
2272 ssize_t
2273 ikev2_add_proposals(struct iked *env, struct iked_sa *sa, struct ibuf *buf,
2274     struct iked_proposals *proposals, uint8_t protoid, int initiator,
2275     int sendikespi, int skipdh)
2276 {
2277 	struct ikev2_sa_proposal	*sap = NULL;
2278 	struct iked_transform		*xform;
2279 	struct iked_proposal		*prop;
2280 	struct iked_childsa		 csa;
2281 	ssize_t				 length = 0, saplength, xflen;
2282 	uint64_t			 spi64;
2283 	uint32_t			 spi32, spi = 0;
2284 	unsigned int			 i, xfi, nxforms;
2285 
2286 	TAILQ_FOREACH(prop, proposals, prop_entry) {
2287 		if ((protoid && prop->prop_protoid != protoid) ||
2288 		    (!protoid && prop->prop_protoid == IKEV2_SAPROTO_IKE))
2289 			continue;
2290 
2291 		if (protoid != IKEV2_SAPROTO_IKE && initiator) {
2292 			if (spi == 0) {
2293 				bzero(&csa, sizeof(csa));
2294 				csa.csa_ikesa = sa;
2295 				csa.csa_saproto = prop->prop_protoid;
2296 				csa.csa_local = &sa->sa_peer;
2297 				csa.csa_peer = &sa->sa_local;
2298 
2299 				if (pfkey_sa_init(env->sc_pfkey, &csa, &spi) == -1)
2300 					return (-1);
2301 			}
2302 
2303 			prop->prop_localspi.spi = spi;
2304 			prop->prop_localspi.spi_size = 4;
2305 			prop->prop_localspi.spi_protoid = prop->prop_protoid;
2306 		}
2307 
2308 		if ((sap = ibuf_advance(buf, sizeof(*sap))) == NULL) {
2309 			log_debug("%s: failed to add proposal", __func__);
2310 			return (-1);
2311 		}
2312 
2313 		if (sendikespi) {
2314 			/* Special case for IKE SA rekeying */
2315 			prop->prop_localspi.spi = initiator ?
2316 			    sa->sa_hdr.sh_ispi : sa->sa_hdr.sh_rspi;
2317 			prop->prop_localspi.spi_size = 8;
2318 			prop->prop_localspi.spi_protoid = IKEV2_SAPROTO_IKE;
2319 		}
2320 
2321 		/*
2322 		 * RFC 7296: 1.2. The Initial Exchanges
2323 		 * IKE_AUTH messages do not contain KE/N payloads, thus
2324 		 * SA payloads cannot contain groups.
2325 		 */
2326 		if (skipdh) {
2327 			nxforms = 0;
2328 			for (i = 0; i < prop->prop_nxforms; i++) {
2329 				xform = prop->prop_xforms + i;
2330 				if (xform->xform_type == IKEV2_XFORMTYPE_DH)
2331 					continue;
2332 				nxforms++;
2333 			}
2334 		} else
2335 			nxforms = prop->prop_nxforms;
2336 
2337 		sap->sap_more = IKEV1_PAYLOAD_PROPOSAL;
2338 		sap->sap_proposalnr = prop->prop_id;
2339 		sap->sap_protoid = prop->prop_protoid;
2340 		sap->sap_spisize = prop->prop_localspi.spi_size;
2341 		sap->sap_transforms = nxforms;
2342 		saplength = sizeof(*sap);
2343 
2344 		switch (prop->prop_localspi.spi_size) {
2345 		case 4:
2346 			spi32 = htobe32(prop->prop_localspi.spi);
2347 			if (ibuf_add(buf, &spi32, sizeof(spi32)) != 0)
2348 				return (-1);
2349 			saplength += 4;
2350 			break;
2351 		case 8:
2352 			spi64 = htobe64(prop->prop_localspi.spi);
2353 			if (ibuf_add(buf, &spi64, sizeof(spi64)) != 0)
2354 				return (-1);
2355 			saplength += 8;
2356 			break;
2357 		default:
2358 			break;
2359 		}
2360 
2361 		for (i = 0, xfi = 0; i < prop->prop_nxforms; i++) {
2362 			xform = prop->prop_xforms + i;
2363 
2364 			if (skipdh && xform->xform_type == IKEV2_XFORMTYPE_DH)
2365 				continue;
2366 
2367 			if ((xflen = ikev2_add_transform(buf,
2368 			    xfi == nxforms - 1 ?
2369 			    IKEV2_XFORM_LAST : IKEV2_XFORM_MORE,
2370 			    xform->xform_type, xform->xform_id,
2371 			    xform->xform_length)) == -1)
2372 				return (-1);
2373 
2374 			xfi++;
2375 			saplength += xflen;
2376 		}
2377 
2378 		sap->sap_length = htobe16(saplength);
2379 		length += saplength;
2380 	}
2381 	if (sap != NULL)
2382 		sap->sap_more = IKEV1_PAYLOAD_NONE;
2383 
2384 	log_debug("%s: length %zd", __func__, length);
2385 
2386 	return (length);
2387 }
2388 
2389 ssize_t
2390 ikev2_add_transform(struct ibuf *buf,
2391     uint8_t more, uint8_t type, uint16_t id, uint16_t length)
2392 {
2393 	struct ikev2_transform	*xfrm;
2394 	struct ikev2_attribute	*attr;
2395 
2396 	if ((xfrm = ibuf_advance(buf, sizeof(*xfrm))) == NULL) {
2397 		log_debug("%s: failed to add transform", __func__);
2398 		return (-1);
2399 	}
2400 	xfrm->xfrm_more = more;
2401 	xfrm->xfrm_type = type;
2402 	xfrm->xfrm_id = htobe16(id);
2403 
2404 	if (length) {
2405 		xfrm->xfrm_length = htobe16(sizeof(*xfrm) + sizeof(*attr));
2406 
2407 		if ((attr = ibuf_advance(buf, sizeof(*attr))) == NULL) {
2408 			log_debug("%s: failed to add attribute", __func__);
2409 			return (-1);
2410 		}
2411 		attr->attr_type = htobe16(IKEV2_ATTRAF_TV |
2412 		    IKEV2_ATTRTYPE_KEY_LENGTH);
2413 		attr->attr_length = htobe16(length);
2414 	} else
2415 		xfrm->xfrm_length = htobe16(sizeof(*xfrm));
2416 
2417 	return (betoh16(xfrm->xfrm_length));
2418 }
2419 
2420 int
2421 ikev2_add_data(struct ibuf *buf, void *data, size_t length)
2422 {
2423 	void	*msgbuf;
2424 
2425 	if ((msgbuf = ibuf_advance(buf, length)) == NULL) {
2426 		log_debug("%s: failed", __func__);
2427 		return (-1);
2428 	}
2429 	memcpy(msgbuf, data, length);
2430 
2431 	return (0);
2432 }
2433 
2434 int
2435 ikev2_add_buf(struct ibuf *buf, struct ibuf *data)
2436 {
2437 	void	*msgbuf;
2438 
2439 	if ((msgbuf = ibuf_advance(buf, ibuf_size(data))) == NULL) {
2440 		log_debug("%s: failed", __func__);
2441 		return (-1);
2442 	}
2443 	memcpy(msgbuf, ibuf_data(data), ibuf_size(data));
2444 
2445 	return (0);
2446 }
2447 
2448 int
2449 ikev2_resp_informational(struct iked *env, struct iked_sa *sa,
2450     struct iked_message *msg)
2451 {
2452 	struct ikev2_notify		*n;
2453 	struct ikev2_payload		*pld = NULL;
2454 	struct ike_header		*hdr;
2455 	struct ibuf			*buf = NULL;
2456 	ssize_t				 len = 0;
2457 	int				 ret = -1;
2458 	int				 oflags = 0;
2459 	uint8_t				 firstpayload = IKEV2_PAYLOAD_NONE;
2460 
2461 	if (!sa_stateok(sa, IKEV2_STATE_AUTH_REQUEST) ||
2462 	    msg->msg_responded || msg->msg_error)
2463 		goto done;
2464 
2465 	if ((buf = ibuf_static()) == NULL)
2466 		goto done;
2467 
2468 	if ((len = ikev2_handle_delete(env, msg, buf, &pld,
2469 	    &firstpayload)) == -1)
2470 		goto done;
2471 
2472 	/*
2473 	 * Include NAT_DETECTION notification on UPDATE_SA_ADDRESSES or if
2474 	 * the peer did include them, too (RFC 455, 3.8).
2475 	 */
2476 	if (sa->sa_mobike &&
2477 	    (msg->msg_update_sa_addresses || msg->msg_natt_rcvd)) {
2478 		/*
2479 		 * XXX workaround so ikev2_msg_frompeer() fails for
2480 		 * XXX ikev2_nat_detection(), and the correct src/dst are
2481 		 * XXX used for the nat detection payload.
2482 		 */
2483 		if (msg->msg_parent == NULL)
2484 			goto done;
2485 		if ((hdr = ibuf_seek(msg->msg_parent->msg_data, 0,
2486 		    sizeof(*hdr))) == NULL)
2487 			goto done;
2488 		oflags = hdr->ike_flags;
2489 		if (sa->sa_hdr.sh_initiator)
2490 			hdr->ike_flags |= IKEV2_FLAG_INITIATOR;
2491 		else
2492 			hdr->ike_flags &= ~IKEV2_FLAG_INITIATOR;
2493 		/* NAT-T notify payloads */
2494 		len = ikev2_add_nat_detection(env, buf, &pld, msg, len);
2495 		hdr->ike_flags = oflags;	/* XXX undo workaround */
2496 		if (len == -1)
2497 			goto done;
2498 		firstpayload = IKEV2_PAYLOAD_NOTIFY;
2499 	}
2500 	/* Reflect COOKIE2 */
2501 	if (msg->msg_cookie2) {
2502 		/* *pld is NULL if there is no previous payload */
2503 		if (pld != NULL) {
2504 			if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NOTIFY) == -1)
2505 				goto done;
2506 		}
2507 		if ((pld = ikev2_add_payload(buf)) == NULL)
2508 			goto done;
2509 		if ((n = ibuf_advance(buf, sizeof(*n))) == NULL)
2510 			goto done;
2511 		n->n_protoid = IKEV2_SAPROTO_IKE;
2512 		n->n_spisize = 0;
2513 		n->n_type = htobe16(IKEV2_N_COOKIE2);
2514 		if (ikev2_add_buf(buf, msg->msg_cookie2) == -1)
2515 			goto done;
2516 		len = sizeof(*n) + ibuf_size(msg->msg_cookie2);
2517 		log_debug("%s: added cookie2", __func__);
2518 		if (firstpayload == IKEV2_PAYLOAD_NONE)
2519 			firstpayload = IKEV2_PAYLOAD_NOTIFY;
2520 	}
2521 	/* add terminator, if there is already a payload */
2522 	if (firstpayload != IKEV2_PAYLOAD_NONE)
2523 		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
2524 			goto done;
2525 	ret = ikev2_msg_send_encrypt(env, sa, &buf,
2526 	    IKEV2_EXCHANGE_INFORMATIONAL, firstpayload, 1);
2527 	if (ret != -1)
2528 		msg->msg_responded = 1;
2529 	if (msg->msg_flags & IKED_MSG_FLAGS_AUTHENTICATION_FAILED) {
2530 		log_debug("%s: AUTHENTICATION_FAILED, closing SA",
2531 		    __func__);
2532 		ikev2_log_cert_info(SPI_SA(sa, __func__),
2533 		    sa->sa_hdr.sh_initiator ? &sa->sa_rcert : &sa->sa_icert);
2534 		ikev2_ike_sa_setreason(sa,
2535 		    "authentication failed notification from peer");
2536 		sa_state(env, sa, IKEV2_STATE_CLOSED);
2537 	}
2538  done:
2539 	ibuf_release(buf);
2540 	return (ret);
2541 }
2542 
2543 void
2544 ikev2_resp_recv(struct iked *env, struct iked_message *msg,
2545     struct ike_header *hdr)
2546 {
2547 	struct iked_sa		*sa;
2548 
2549 	switch (hdr->ike_exchange) {
2550 	case IKEV2_EXCHANGE_IKE_SA_INIT:
2551 		if (msg->msg_sa != NULL) {
2552 			log_debug("%s: SA already exists", __func__);
2553 			return;
2554 		}
2555 		if ((msg->msg_sa = sa_new(env,
2556 		    betoh64(hdr->ike_ispi), betoh64(hdr->ike_rspi),
2557 		    0, msg->msg_policy)) == NULL) {
2558 			log_debug("%s: failed to get new SA", __func__);
2559 			return;
2560 		}
2561 		/* Setup exchange timeout. */
2562 		timer_set(env, &msg->msg_sa->sa_timer,
2563 		    ikev2_init_ike_sa_timeout, msg->msg_sa);
2564 		timer_add(env, &msg->msg_sa->sa_timer,
2565 		    IKED_IKE_SA_EXCHANGE_TIMEOUT);
2566 		break;
2567 	case IKEV2_EXCHANGE_IKE_AUTH:
2568 		if (ikev2_msg_valid_ike_sa(env, hdr, msg) == -1)
2569 			return;
2570 		if (sa_stateok(msg->msg_sa, IKEV2_STATE_VALID)) {
2571 			log_debug("%s: already authenticated", __func__);
2572 			return;
2573 		}
2574 		break;
2575 	case IKEV2_EXCHANGE_CREATE_CHILD_SA:
2576 	case IKEV2_EXCHANGE_INFORMATIONAL:
2577 		if (ikev2_msg_valid_ike_sa(env, hdr, msg) == -1)
2578 			return;
2579 		break;
2580 	default:
2581 		log_debug("%s: unsupported exchange: %s", __func__,
2582 		    print_map(hdr->ike_exchange, ikev2_exchange_map));
2583 		return;
2584 	}
2585 
2586 	if (ikev2_pld_parse(env, hdr, msg, msg->msg_offset) != 0) {
2587 		log_info("%s: failed to parse message",
2588 		    SPI_SA(msg->msg_sa, __func__));
2589 		return;
2590 	}
2591 
2592 	if (!ikev2_msg_frompeer(msg))
2593 		return;
2594 
2595 	if (ikev2_handle_notifies(env, msg) != 0)
2596 		return;
2597 
2598 	if ((sa = msg->msg_sa) == NULL)
2599 		return;
2600 
2601 	if (sa->sa_fragments.frag_count != 0)
2602 		return;
2603 
2604 	msg->msg_valid = 1;
2605 
2606 	if (msg->msg_natt && sa->sa_natt == 0) {
2607 		log_debug("%s: NAT-T message received, updated SA", __func__);
2608 		sa->sa_natt = 1;
2609 	}
2610 
2611 	switch (hdr->ike_exchange) {
2612 	case IKEV2_EXCHANGE_IKE_SA_INIT:
2613 		if (ikev2_sa_responder(env, sa, NULL, msg) != 0) {
2614 			log_info("%s: failed to negotiate IKE SA",
2615 			    SPI_SA(sa, __func__));
2616 			if (msg->msg_error == 0)
2617 				msg->msg_error = IKEV2_N_NO_PROPOSAL_CHOSEN;
2618 			ikev2_send_init_error(env, msg);
2619 			ikev2_ike_sa_setreason(sa, "no proposal chosen");
2620 			sa_state(env, sa, IKEV2_STATE_CLOSED);
2621 			return;
2622 		}
2623 		if (ikev2_resp_ike_sa_init(env, msg) != 0) {
2624 			log_debug("%s: failed to send init response", __func__);
2625 			ikev2_ike_sa_setreason(sa, "SA_INIT reponse failed");
2626 			sa_state(env, sa, IKEV2_STATE_CLOSED);
2627 			return;
2628 		}
2629 		break;
2630 	case IKEV2_EXCHANGE_IKE_AUTH:
2631 		if (!sa_stateok(sa, IKEV2_STATE_SA_INIT)) {
2632 			log_debug("%s: state mismatch", __func__);
2633 			ikev2_ike_sa_setreason(sa, "state mismatch IKE_AUTH");
2634 			sa_state(env, sa, IKEV2_STATE_CLOSED);
2635 			return;
2636 		}
2637 
2638 		/* Handle EAP authentication */
2639 		if (msg->msg_eap.eam_found) {
2640 			if (ikev2_resp_ike_eap(env, sa, msg)) {
2641 				log_info("%s: failed eap response",
2642 				    SPI_SA(sa, __func__));
2643 				ikev2_ike_sa_setreason(sa, "EAP failed");
2644 				sa_state(env, sa, IKEV2_STATE_CLOSED);
2645 				return;
2646 			}
2647 			return;
2648 		}
2649 
2650 		if (ikev2_ike_auth_recv(env, sa, msg) != 0) {
2651 			log_debug("%s: failed to send auth response", __func__);
2652 			ikev2_send_error(env, sa, msg, hdr->ike_exchange);
2653 			ikev2_ike_sa_setreason(sa, "IKE_AUTH failed");
2654 			sa_state(env, sa, IKEV2_STATE_CLOSED);
2655 			return;
2656 		}
2657 		break;
2658 	case IKEV2_EXCHANGE_CREATE_CHILD_SA:
2659 		if (ikev2_resp_create_child_sa(env, msg) != 0) {
2660 			if (msg->msg_error == 0)
2661 				msg->msg_error = IKEV2_N_NO_PROPOSAL_CHOSEN;
2662 			ikev2_send_error(env, sa, msg, hdr->ike_exchange);
2663 		}
2664 		break;
2665 	case IKEV2_EXCHANGE_INFORMATIONAL:
2666 		if (msg->msg_update_sa_addresses)
2667 			ikev2_update_sa_addresses(env, sa);
2668 		(void)ikev2_resp_informational(env, sa, msg);
2669 		break;
2670 	default:
2671 		break;
2672 	}
2673 }
2674 
2675 ssize_t
2676 ikev2_handle_delete(struct iked *env, struct iked_message *msg,
2677     struct ibuf *resp, struct ikev2_payload **pld, uint8_t *firstpayload)
2678 {
2679 	struct iked_childsa	**peersas = NULL;
2680 	struct iked_sa		*sa = msg->msg_sa;
2681 	struct ikev2_delete	*localdel;
2682 	struct ibuf		*spibuf = NULL;
2683 	uint64_t		*localspi = NULL;
2684 	uint64_t		 spi64, spi = 0;
2685 	uint32_t		 spi32;
2686 	uint8_t			*buf;
2687 	size_t			 found = 0, failed = 0;
2688 	int			 ret = -1;
2689 	size_t			 i, sz, cnt, len;
2690 
2691 	if (!msg->msg_del_protoid)
2692 		return (0);
2693 
2694 	sz = msg->msg_del_spisize;
2695 
2696 	switch (sz) {
2697 	case 4:
2698 	case 8:
2699 		break;
2700 	case 0:
2701 		if (msg->msg_del_protoid != IKEV2_SAPROTO_IKE) {
2702 			log_debug("%s: invalid SPI size", __func__);
2703 			goto done;
2704 		}
2705 		ikev2_ikesa_recv_delete(env, sa);
2706 		return (0);
2707 	default:
2708 		log_info("%s: error: invalid SPI size", __func__);
2709 		goto done;
2710 	}
2711 
2712 	cnt = msg->msg_del_cnt;
2713 	len = ibuf_length(msg->msg_del_buf);
2714 
2715 	if ((len / sz) != cnt) {
2716 		log_debug("%s: invalid payload length %zu/%zu != %zu",
2717 		    __func__, len, sz, cnt);
2718 		return (-1);
2719 	}
2720 
2721 	if (((peersas = calloc(cnt, sizeof(struct iked_childsa *))) == NULL ||
2722 	     (localspi = calloc(cnt, sizeof(uint64_t))) == NULL)) {
2723 		log_warn("%s", __func__);
2724 		goto done;
2725 	}
2726 
2727 	buf = ibuf_data(msg->msg_del_buf);
2728 	for (i = 0; i < cnt; i++) {
2729 		switch (sz) {
2730 		case 4:
2731 			memcpy(&spi32, buf + (i * sz), sizeof(spi32));
2732 			spi = betoh32(spi32);
2733 			break;
2734 		case 8:
2735 			memcpy(&spi64, buf + (i * sz), sizeof(spi64));
2736 			spi = betoh64(spi64);
2737 			break;
2738 		}
2739 
2740 		log_debug("%s: spi %s", __func__, print_spi(spi, sz));
2741 
2742 		if (peersas == NULL || sa == NULL)
2743 			continue;
2744 
2745 		if ((peersas[i] = childsa_lookup(sa, spi,
2746 		    msg->msg_del_protoid)) == NULL) {
2747 			log_warnx("%s: CHILD SA doesn't exist for spi %s",
2748 			    SPI_SA(sa, __func__),
2749 			    print_spi(spi, sz));
2750 			continue;
2751 		}
2752 
2753 		if (ikev2_childsa_delete(env, sa, msg->msg_del_protoid, spi,
2754 		    &localspi[i], 0) == -1)
2755 			failed++;
2756 		else {
2757 			found++;
2758 
2759 			/* append SPI to log buffer */
2760 			if (ibuf_strlen(spibuf))
2761 				ibuf_strcat(&spibuf, ", ");
2762 			ibuf_strcat(&spibuf, print_spi(spi, sz));
2763 		}
2764 
2765 		/*
2766 		 * Flows are left in the require mode so that it would be
2767 		 * possible to quickly negotiate a new Child SA
2768 		 */
2769 	}
2770 
2771 	if (resp == NULL) {
2772 		ret = 0;
2773 		goto done;
2774 	}
2775 
2776 	/* Response to the INFORMATIONAL with Delete payload */
2777 	if (found) {
2778 		if ((*pld = ikev2_add_payload(resp)) == NULL)
2779 			goto done;
2780 		*firstpayload = IKEV2_PAYLOAD_DELETE;
2781 
2782 		if ((localdel = ibuf_advance(resp, sizeof(*localdel))) == NULL)
2783 			goto done;
2784 
2785 		localdel->del_protoid = msg->msg_del_protoid;
2786 		localdel->del_spisize = sz;
2787 		localdel->del_nspi = htobe16(found);
2788 		ret = sizeof(*localdel);
2789 
2790 		for (i = 0; i < cnt; i++) {
2791 			if (localspi[i] == 0)	/* happens if found < cnt */
2792 				continue;
2793 			switch (sz) {
2794 			case 4:
2795 				spi32 = htobe32(localspi[i]);
2796 				if (ibuf_add(resp, &spi32, sizeof(spi32)) != 0)
2797 					goto done;
2798 				ret += sizeof(spi32);
2799 				break;
2800 			case 8:
2801 				spi64 = htobe64(localspi[i]);
2802 				if (ibuf_add(resp, &spi64, sizeof(spi64)) != 0)
2803 					goto done;
2804 				ret += sizeof(spi64);
2805 				break;
2806 			}
2807 		}
2808 		log_info("%sdeleted %zu SPI%s: %.*s",
2809 		    SPI_SA(sa, NULL), found,
2810 		    found == 1 ? "" : "s",
2811 		    spibuf ? ibuf_strlen(spibuf) : 0,
2812 		    spibuf ? (char *)ibuf_data(spibuf) : "");
2813 	} else {
2814 		/* XXX should we send an INVALID_SPI notification? */
2815 		ret = 0;
2816 	}
2817 
2818  done:
2819 	free(localspi);
2820 	free(peersas);
2821 	ibuf_release(spibuf);
2822 
2823 	return (ret);
2824 }
2825 
2826 int
2827 ikev2_handle_notifies(struct iked *env, struct iked_message *msg)
2828 {
2829 	struct iked_ipcomp	*ic;
2830 	struct iked_sa		*sa;
2831 	uint16_t		 group;
2832 
2833 	if ((sa = msg->msg_sa) == NULL)
2834 		return (-1);
2835 
2836 	if (msg->msg_flags & IKED_MSG_FLAGS_CHILD_SA_NOT_FOUND)
2837 		sa->sa_stateflags &= ~IKED_REQ_CHILDSA;
2838 
2839 	if ((msg->msg_flags & IKED_MSG_FLAGS_FRAGMENTATION) && env->sc_frag) {
2840 		log_debug("%s: fragmentation enabled", __func__);
2841 		sa->sa_frag = 1;
2842 	}
2843 
2844 	if ((msg->msg_flags & IKED_MSG_FLAGS_MOBIKE) && env->sc_mobike) {
2845 		log_debug("%s: mobike enabled", __func__);
2846 		sa->sa_mobike = 1;
2847 		/* enforce natt */
2848 		sa->sa_natt = 1;
2849 	}
2850 
2851 	if ((msg->msg_flags & IKED_MSG_FLAGS_NO_ADDITIONAL_SAS)
2852 	    && sa->sa_stateflags & IKED_REQ_CHILDSA) {
2853 		/* This makes sense for Child SAs only atm */
2854 		ikev2_disable_rekeying(env, sa);
2855 		sa->sa_stateflags &= ~IKED_REQ_CHILDSA;
2856 	}
2857 
2858 	if (msg->msg_flags & IKED_MSG_FLAGS_INVALID_KE) {
2859 		/* XXX chould also happen for PFS */
2860 		group = betoh16(msg->msg_group);
2861 		if (!sa->sa_hdr.sh_initiator) {
2862 			log_debug("%s: not an initiator", __func__);
2863 			ikev2_ike_sa_setreason(sa,
2864 			    "received invalid KE as responder");
2865 			sa_state(env, sa, IKEV2_STATE_CLOSED);
2866 			msg->msg_sa = NULL;
2867 			return (-1);
2868 		}
2869 		if (group_getid(group) == NULL) {
2870 			log_debug("%s: unable to select DH group %u", __func__,
2871 			    group);
2872 			ikev2_ike_sa_setreason(sa,
2873 			    "unable to select DH group");
2874 			sa_state(env, sa, IKEV2_STATE_CLOSED);
2875 			msg->msg_sa = NULL;
2876 			return (-1);
2877 		}
2878 		msg->msg_policy->pol_peerdh = group;
2879 		log_debug("%s: responder selected DH group %u", __func__,
2880 		    group);
2881 		ikev2_ike_sa_setreason(sa,
2882 		    "reinitiating with new DH group");
2883 		sa_state(env, sa, IKEV2_STATE_CLOSED);
2884 		msg->msg_sa = NULL;
2885 
2886 		/*
2887 		 * XXX should also happen for PFS so we have to check state.
2888 		 */
2889 		timer_set(env, &env->sc_inittmr, ikev2_init_ike_sa, NULL);
2890 		timer_add(env, &env->sc_inittmr, IKED_INITIATOR_INITIAL);
2891 		return (-1);
2892 	}
2893 
2894 	if (msg->msg_flags & IKED_MSG_FLAGS_IPCOMP_SUPPORTED) {
2895 		/* we only support deflate */
2896 		if ((msg->msg_policy->pol_flags & IKED_POLICY_IPCOMP) &&
2897 		    (msg->msg_transform == IKEV2_IPCOMP_DEFLATE)) {
2898 			ic = msg->msg_response ?
2899 			    &sa->sa_ipcompi :
2900 			    &sa->sa_ipcompr;
2901 			ic->ic_transform = msg->msg_transform;
2902 			ic->ic_cpi_out = betoh16(msg->msg_cpi);
2903 		}
2904 	}
2905 
2906 	if (msg->msg_nat_detected & IKED_MSG_NAT_DST_IP) {
2907 		/* Send keepalive, since we are behind a NAT-gw */
2908 		sa->sa_usekeepalive = 1;
2909 	}
2910 
2911 	/* Signature hash algorithm */
2912 	if (msg->msg_flags & IKED_MSG_FLAGS_SIGSHA2)
2913 		sa->sa_sigsha2 = 1;
2914 	if (msg->msg_flags & IKED_MSG_FLAGS_USE_TRANSPORT)
2915 		sa->sa_use_transport_mode = 1;
2916 
2917 	if ((msg->msg_flags & IKED_MSG_FLAGS_TEMPORARY_FAILURE)
2918 	    && sa->sa_nexti != NULL)
2919 		sa->sa_tmpfail = 1;
2920 	return (0);
2921 }
2922 
2923 int
2924 ikev2_resp_ike_sa_init(struct iked *env, struct iked_message *msg)
2925 {
2926 	struct iked_message		 resp;
2927 	struct ike_header		*hdr;
2928 	struct ikev2_payload		*pld;
2929 	struct ikev2_keyexchange	*ke;
2930 	struct iked_sa			*sa = msg->msg_sa;
2931 	struct ibuf			*buf;
2932 	struct group			*group;
2933 	ssize_t				 len;
2934 	int				 ret = -1;
2935 
2936 	if (sa->sa_hdr.sh_initiator) {
2937 		log_debug("%s: called by initiator", __func__);
2938 		return (-1);
2939 	}
2940 	if (msg->msg_nat_detected && sa->sa_udpencap == 0) {
2941 		log_debug("%s: detected NAT, enabling UDP encapsulation",
2942 		    __func__);
2943 		sa->sa_udpencap = 1;
2944 	}
2945 
2946 	if ((buf = ikev2_msg_init(env, &resp,
2947 	    &msg->msg_peer, msg->msg_peerlen,
2948 	    &msg->msg_local, msg->msg_locallen, 1)) == NULL)
2949 		goto done;
2950 
2951 	resp.msg_sa = sa;
2952 	resp.msg_fd = msg->msg_fd;
2953 	resp.msg_natt = msg->msg_natt;
2954 	resp.msg_msgid = 0;
2955 
2956 	/* IKE header */
2957 	if ((hdr = ikev2_add_header(buf, sa, resp.msg_msgid,
2958 	    IKEV2_PAYLOAD_SA, IKEV2_EXCHANGE_IKE_SA_INIT,
2959 	    IKEV2_FLAG_RESPONSE)) == NULL)
2960 		goto done;
2961 
2962 	/* SA payload */
2963 	if ((pld = ikev2_add_payload(buf)) == NULL)
2964 		goto done;
2965 	if ((len = ikev2_add_proposals(env, sa, buf, &sa->sa_proposals,
2966 	    IKEV2_SAPROTO_IKE, sa->sa_hdr.sh_initiator, 0, 0)) == -1)
2967 		goto done;
2968 
2969 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_KE) == -1)
2970 		goto done;
2971 
2972 	/* KE payload */
2973 	if ((pld = ikev2_add_payload(buf)) == NULL)
2974 		goto done;
2975 	if ((ke = ibuf_advance(buf, sizeof(*ke))) == NULL)
2976 		goto done;
2977 	if ((group = sa->sa_dhgroup) == NULL) {
2978 		log_debug("%s: invalid dh", __func__);
2979 		goto done;
2980 	}
2981 	ke->kex_dhgroup = htobe16(group->id);
2982 	if (ikev2_add_buf(buf, sa->sa_dhrexchange) == -1)
2983 		goto done;
2984 	len = sizeof(*ke) + dh_getlen(group);
2985 
2986 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONCE) == -1)
2987 		goto done;
2988 
2989 	/* NONCE payload */
2990 	if ((pld = ikev2_add_payload(buf)) == NULL)
2991 		goto done;
2992 	if (ikev2_add_buf(buf, sa->sa_rnonce) == -1)
2993 		goto done;
2994 	len = ibuf_size(sa->sa_rnonce);
2995 
2996 	/* Fragmentation Notify*/
2997 	if (sa->sa_frag) {
2998 		if ((len = ikev2_add_fragmentation(buf, &pld, len))
2999 		    == -1)
3000 			goto done;
3001 	}
3002 
3003 	if ((env->sc_nattmode != NATT_DISABLE) &&
3004 	    msg->msg_local.ss_family != AF_UNSPEC) {
3005 		if ((len = ikev2_add_nat_detection(env, buf, &pld, &resp, len))
3006 		    == -1)
3007 			goto done;
3008 	}
3009 	if (sa->sa_statevalid & IKED_REQ_CERT) {
3010 		/* CERTREQ payload(s) */
3011 		if ((len = ikev2_add_certreq(buf, &pld,
3012 		    len, env->sc_certreq, env->sc_certreqtype)) == -1)
3013 			goto done;
3014 
3015 		if (env->sc_certreqtype != sa->sa_policy->pol_certreqtype &&
3016 		    (len = ikev2_add_certreq(buf, &pld,
3017 		    len, NULL, sa->sa_policy->pol_certreqtype)) == -1)
3018 			goto done;
3019 	}
3020 
3021 	if (sa->sa_sigsha2 &&
3022 	    (len = ikev2_add_sighashnotify(buf, &pld, len)) == -1)
3023 		goto done;
3024 
3025 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
3026 		goto done;
3027 
3028 	if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
3029 		goto done;
3030 
3031 	(void)ikev2_pld_parse(env, hdr, &resp, 0);
3032 
3033 	ibuf_release(sa->sa_2ndmsg);
3034 	if ((sa->sa_2ndmsg = ibuf_dup(buf)) == NULL) {
3035 		log_debug("%s: failed to copy 2nd message", __func__);
3036 		goto done;
3037 	}
3038 
3039 	ret = ikev2_msg_send(env, &resp);
3040 
3041  done:
3042 	ikev2_msg_cleanup(env, &resp);
3043 
3044 	return (ret);
3045 }
3046 
3047 int
3048 ikev2_send_auth_failed(struct iked *env, struct iked_sa *sa)
3049 {
3050 	char				 dstid[IKED_ID_SIZE];
3051 	struct ikev2_notify		*n;
3052 	struct ibuf			*buf = NULL;
3053 	int				 ret = -1, exchange, response;
3054 
3055 	if (ikev2_print_id(IKESA_DSTID(sa), dstid, sizeof(dstid)) == -1)
3056 		bzero(dstid, sizeof(dstid));
3057 	log_info("%s: authentication failed for %s",
3058 	    SPI_SA(sa, __func__), dstid);
3059 
3060 	/* Log certificate information */
3061 	ikev2_log_cert_info(SPI_SA(sa, __func__),
3062 	    sa->sa_hdr.sh_initiator ? &sa->sa_rcert : &sa->sa_icert);
3063 
3064 	/* Notify payload */
3065 	if ((buf = ibuf_static()) == NULL)
3066 		goto done;
3067 	if ((n = ibuf_advance(buf, sizeof(*n))) == NULL)
3068 		goto done;
3069 	n->n_protoid = IKEV2_SAPROTO_IKE;
3070 	n->n_spisize = 0;
3071 	n->n_type = htobe16(IKEV2_N_AUTHENTICATION_FAILED);
3072 	if (sa->sa_hdr.sh_initiator) {
3073 		exchange = IKEV2_EXCHANGE_INFORMATIONAL;
3074 		response = 0;
3075 	} else {
3076 		exchange = IKEV2_EXCHANGE_IKE_AUTH;
3077 		response = 1;
3078 	}
3079 	ret = ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_NOTIFY,
3080 	    exchange, response);
3081 	if (exchange == IKEV2_EXCHANGE_INFORMATIONAL)
3082 		sa->sa_stateflags |= IKED_REQ_INF;
3083  done:
3084 	ibuf_release(buf);
3085 
3086 	/* cleanup SA after timeout */
3087 	sa_state(env, sa, IKEV2_STATE_CLOSING);
3088 	timer_del(env, &sa->sa_timer);
3089 	timer_set(env, &sa->sa_timer, ikev2_ike_sa_timeout, sa);
3090 	timer_add(env, &sa->sa_timer, IKED_IKE_SA_DELETE_TIMEOUT);
3091 	config_free_fragments(&sa->sa_fragments);
3092 	ikev2_ike_sa_setreason(sa, "authentication failed");
3093 
3094 	return (ret);
3095 }
3096 
3097 ssize_t
3098 ikev2_add_error(struct iked *env, struct ibuf *buf, struct iked_message *msg)
3099 {
3100 	struct ikev2_notify		*n;
3101 	struct iked_spi			*rekey;
3102 	uint16_t			 group;
3103 	uint32_t			 spi32;
3104 	uint64_t			 spi64;
3105 	size_t				 len;
3106 	uint8_t				*ptr;
3107 
3108 	switch (msg->msg_error) {
3109 	case IKEV2_N_CHILD_SA_NOT_FOUND:
3110 		break;
3111 	case IKEV2_N_NO_PROPOSAL_CHOSEN:
3112 		ikev2_log_proposal(msg->msg_sa, &msg->msg_proposals);
3113 		break;
3114 	case IKEV2_N_INVALID_KE_PAYLOAD:
3115 		break;
3116 	default:
3117 		return (-1);
3118 	}
3119 	log_info("%s: %s", SPI_SA(msg->msg_sa, __func__),
3120 	    print_map(msg->msg_error, ikev2_n_map));
3121 	len = sizeof(*n);
3122 	if ((ptr = ibuf_advance(buf, len)) == NULL)
3123 		return (-1);
3124 	n = (struct ikev2_notify *)ptr;
3125 	n->n_type = htobe16(msg->msg_error);
3126 	switch (msg->msg_error) {
3127 	case IKEV2_N_CHILD_SA_NOT_FOUND:
3128 		rekey = &msg->msg_rekey;
3129 		switch (rekey->spi_size) {
3130 		case 4:
3131 			spi32 = htobe32(rekey->spi);
3132 			if (ibuf_add(buf, &spi32, sizeof(spi32)) != 0)
3133 				return (-1);
3134 			len += sizeof(spi32);
3135 			break;
3136 		case 8:
3137 			spi64 = htobe64(rekey->spi);
3138 			if (ibuf_add(buf, &spi64, sizeof(spi64)) != 0)
3139 				return (-1);
3140 			len += sizeof(spi64);
3141 			break;
3142 		default:
3143 			log_debug("%s: invalid SPI size %d", __func__,
3144 			    rekey->spi_size);
3145 			return (-1);
3146 		}
3147 		n->n_protoid = rekey->spi_protoid;
3148 		n->n_spisize = rekey->spi_size;
3149 		break;
3150 	case IKEV2_N_INVALID_KE_PAYLOAD:
3151 		group = htobe16(msg->msg_dhgroup);
3152 		if (ibuf_add(buf, &group, sizeof(group)) != 0)
3153 			return (-1);
3154 		len += sizeof(group);
3155 		n->n_protoid = 0;
3156 		n->n_spisize = 0;
3157 		break;
3158 	default:
3159 		n->n_protoid = 0;
3160 		n->n_spisize = 0;
3161 		break;
3162 	}
3163 	log_debug("%s: done", __func__);
3164 
3165 	return (len);
3166 }
3167 
3168 int
3169 ikev2_record_dstid(struct iked *env, struct iked_sa *sa)
3170 {
3171 	struct iked_sa *osa;
3172 
3173 	osa = sa_dstid_lookup(env, sa);
3174 	if (osa == sa)
3175 		return (0);
3176 	if (osa != NULL) {
3177 		sa_dstid_remove(env, osa);
3178 		if (env->sc_enforcesingleikesa &&
3179 		    osa->sa_state < IKEV2_STATE_CLOSING) {
3180 			log_info("%sreplaced by IKESA %s (identical DSTID)",
3181 			    SPI_SA(osa, NULL),
3182 			    print_spi(sa->sa_hdr.sh_ispi, 8));
3183 			if (osa->sa_state == IKEV2_STATE_ESTABLISHED)
3184 				ikev2_disable_timer(env, osa);
3185 			ikev2_ike_sa_setreason(osa, "sa replaced");
3186 			ikev2_ikesa_delete(env, osa, 1);
3187 			timer_add(env, &osa->sa_timer,
3188 			    3 * IKED_RETRANSMIT_TIMEOUT);
3189 		}
3190 	}
3191 	osa = sa_dstid_insert(env, sa);
3192 	if (osa != NULL) {
3193 		/* XXX how can this fail */
3194 		log_info("%s: could not replace old IKESA %s",
3195 		    SPI_SA(sa, __func__),
3196 		    print_spi(osa->sa_hdr.sh_ispi, 8));
3197 		return (-1);
3198 	}
3199 	return (0);
3200 }
3201 
3202 int
3203 ikev2_send_error(struct iked *env, struct iked_sa *sa,
3204     struct iked_message *msg, uint8_t exchange)
3205 {
3206 	struct ibuf			*buf = NULL;
3207 	int				 ret = -1;
3208 
3209 	if (msg->msg_error == 0)
3210 		return (0);
3211 	if ((buf = ibuf_static()) == NULL)
3212 		goto done;
3213 	if (ikev2_add_error(env, buf, msg) == 0)
3214 		goto done;
3215 	ret = ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_NOTIFY,
3216 	    exchange, 1);
3217  done:
3218 	ibuf_release(buf);
3219 	return (ret);
3220 }
3221 
3222 /*
3223  * Variant of ikev2_send_error() that can be used before encryption
3224  * is enabled. Based on ikev2_resp_ike_sa_init() code.
3225  */
3226 int
3227 ikev2_send_init_error(struct iked *env, struct iked_message *msg)
3228 {
3229 	struct iked_message		 resp;
3230 	struct ike_header		*hdr;
3231 	struct ikev2_payload		*pld;
3232 	struct iked_sa			*sa = msg->msg_sa;
3233 	struct ibuf			*buf;
3234 	ssize_t				 len = 0;
3235 	int				 ret = -1;
3236 
3237 	if (sa->sa_hdr.sh_initiator) {
3238 		log_debug("%s: called by initiator", __func__);
3239 		return (-1);
3240 	}
3241 	if (msg->msg_error == 0)
3242 		return (0);
3243 
3244 	if ((buf = ikev2_msg_init(env, &resp,
3245 	    &msg->msg_peer, msg->msg_peerlen,
3246 	    &msg->msg_local, msg->msg_locallen, 1)) == NULL)
3247 		goto done;
3248 
3249 	resp.msg_sa = sa;
3250 	resp.msg_fd = msg->msg_fd;
3251 	resp.msg_natt = msg->msg_natt;
3252 	resp.msg_msgid = 0;
3253 
3254 	/* IKE header */
3255 	if ((hdr = ikev2_add_header(buf, sa, resp.msg_msgid,
3256 	    IKEV2_PAYLOAD_NOTIFY, IKEV2_EXCHANGE_IKE_SA_INIT,
3257 	    IKEV2_FLAG_RESPONSE)) == NULL)
3258 		goto done;
3259 
3260 	/* NOTIFY payload */
3261 	if ((pld = ikev2_add_payload(buf)) == NULL)
3262 		goto done;
3263 	if ((len = ikev2_add_error(env, buf, msg)) == 0)
3264 		goto done;
3265 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
3266 		goto done;
3267 	if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
3268 		goto done;
3269 
3270 	(void)ikev2_pld_parse(env, hdr, &resp, 0);
3271 	ret = ikev2_msg_send(env, &resp);
3272 
3273  done:
3274 	ikev2_msg_cleanup(env, &resp);
3275 
3276 	return (ret);
3277 }
3278 
3279 int
3280 ikev2_handle_certreq(struct iked* env, struct iked_message *msg)
3281 {
3282 	struct iked_certreq	*cr;
3283 	struct iked_sa		*sa;
3284 	uint8_t			 crtype;
3285 	uint8_t	more;
3286 
3287 	if ((sa = msg->msg_sa) == NULL)
3288 		return (-1);
3289 
3290 	/* Ignore CERTREQ when policy uses PSK authentication */
3291 	if (sa->sa_policy->pol_auth.auth_method == IKEV2_AUTH_SHARED_KEY_MIC)
3292 		return (0);
3293 
3294 	if (sa->sa_hdr.sh_initiator)
3295 		sa->sa_stateinit |= IKED_REQ_CERT;
3296 	else
3297 		sa->sa_statevalid |= IKED_REQ_CERT;
3298 
3299 	/*
3300 	 * If we have to send a local certificate but did not receive an
3301 	 * optional CERTREQ, use our own certreq to find a local certificate.
3302 	 * We could alternatively extract the CA from the peer certificate
3303 	 * to find a matching local one.
3304 	 */
3305 	if (SIMPLEQ_EMPTY(&msg->msg_certreqs)) {
3306 		if (sa->sa_policy->pol_certreqtype)
3307 			crtype = sa->sa_policy->pol_certreqtype;
3308 		else
3309 			crtype = env->sc_certreqtype;
3310 		ca_setreq(env, sa, &sa->sa_policy->pol_localid,
3311 		    crtype, 0, ibuf_data(env->sc_certreq),
3312 		    ibuf_size(env->sc_certreq), PROC_CERT);
3313 	} else {
3314 		while ((cr = SIMPLEQ_FIRST(&msg->msg_certreqs))) {
3315 			if (SIMPLEQ_NEXT(cr, cr_entry) != NULL)
3316 				more = 1;
3317 			else
3318 				more = 0;
3319 
3320 			ca_setreq(env, sa, &sa->sa_policy->pol_localid,
3321 			    cr->cr_type, more, ibuf_data(cr->cr_data),
3322 			    ibuf_length(cr->cr_data),
3323 			    PROC_CERT);
3324 
3325 			ibuf_release(cr->cr_data);
3326 			SIMPLEQ_REMOVE_HEAD(&msg->msg_certreqs, cr_entry);
3327 			free(cr);
3328 		}
3329 	}
3330 
3331 	return (0);
3332 }
3333 
3334 int
3335 ikev2_resp_ike_eap_mschap(struct iked *env, struct iked_sa *sa,
3336     struct iked_message *msg)
3337 {
3338 	uint8_t			 successmsg[EAP_MSCHAP_SUCCESS_SZ];
3339 	uint8_t			 ntresponse[EAP_MSCHAP_NTRESPONSE_SZ];
3340 	struct eap_msg		*eap = &msg->msg_eap;
3341 	struct iked_user	*usr;
3342 	uint8_t			*pass;
3343 	char			*name = NULL;
3344 	size_t			 passlen;
3345 	int			 ret;
3346 
3347 	switch (eap->eam_state) {
3348 	case EAP_STATE_IDENTITY:
3349 		sa->sa_eapid = eap->eam_identity;
3350 		return (eap_challenge_request(env, sa, eap->eam_id));
3351 	case EAP_STATE_MSCHAPV2_CHALLENGE:
3352 		if (eap->eam_user) {
3353 			name = eap->eam_user;
3354 		} else if (sa->sa_eapid) {
3355 			name = sa->sa_eapid;
3356 		}
3357 		if (name == NULL) {
3358 			log_info("%s: invalid response name",
3359 			    SPI_SA(sa, __func__));
3360 			return (-1);
3361 		}
3362 		if ((usr = user_lookup(env, name)) == NULL) {
3363 			log_info("%s: unknown user '%s'", SPI_SA(sa, __func__),
3364 			    name);
3365 			return (-1);
3366 		}
3367 
3368 		if ((pass = string2unicode(usr->usr_pass, &passlen)) == NULL)
3369 			return (-1);
3370 
3371 		mschap_nt_response(ibuf_data(sa->sa_eap.id_buf),
3372 		    eap->eam_challenge, usr->usr_name, strlen(usr->usr_name),
3373 		    pass, passlen, ntresponse);
3374 
3375 		if (memcmp(ntresponse, eap->eam_ntresponse,
3376 		    sizeof(ntresponse)) != 0) {
3377 			log_info("%s: '%s' authentication failed",
3378 			   SPI_SA(sa, __func__), usr->usr_name);
3379 			free(pass);
3380 
3381 			/* XXX should we send an EAP failure packet? */
3382 			return (-1);
3383 		}
3384 
3385 		bzero(&successmsg, sizeof(successmsg));
3386 
3387 		mschap_auth_response(pass, passlen,
3388 		    ntresponse, ibuf_data(sa->sa_eap.id_buf),
3389 		    eap->eam_challenge, usr->usr_name, strlen(usr->usr_name),
3390 		    successmsg);
3391 		if ((sa->sa_eapmsk = ibuf_new(NULL, MSCHAP_MSK_SZ)) == NULL) {
3392 			log_info("%s: failed to get MSK", SPI_SA(sa, __func__));
3393 			free(pass);
3394 			return (-1);
3395 		}
3396 		mschap_msk(pass, passlen, ntresponse,
3397 		    ibuf_data(sa->sa_eapmsk));
3398 		free(pass);
3399 
3400 		log_info("%s: '%s' authenticated", __func__, usr->usr_name);
3401 
3402 		ret = eap_mschap_challenge(env, sa, eap->eam_id, eap->eam_msrid,
3403 		    successmsg, EAP_MSCHAP_SUCCESS_SZ);
3404 		if (ret == 0)
3405 			sa_state(env, sa, IKEV2_STATE_AUTH_SUCCESS);
3406 		break;
3407 	case EAP_STATE_MSCHAPV2_SUCCESS:
3408 		return (eap_mschap_success(env, sa, eap->eam_id));
3409 	case EAP_STATE_SUCCESS:
3410 		if (!sa_stateok(sa, IKEV2_STATE_AUTH_SUCCESS))
3411 			return (-1);
3412 		return (eap_success(env, sa, msg->msg_eap.eam_id));
3413 	default:
3414 		log_info("%s: eap ignored.", __func__);
3415 		break;
3416 	}
3417 	return 0;
3418 }
3419 
3420 int
3421 ikev2_resp_ike_eap(struct iked *env, struct iked_sa *sa,
3422     struct iked_message *msg)
3423 {
3424 	if (!sa_stateok(sa, IKEV2_STATE_EAP))
3425 		return (-1);
3426 
3427 	switch (sa->sa_policy->pol_auth.auth_eap) {
3428 	case EAP_TYPE_MSCHAP_V2:
3429 		return ikev2_resp_ike_eap_mschap(env, sa, msg);
3430 	}
3431 	return -1;
3432 }
3433 
3434 int
3435 ikev2_resp_ike_auth(struct iked *env, struct iked_sa *sa)
3436 {
3437 	struct ikev2_payload		*pld;
3438 	struct ikev2_cert		*cert;
3439 	struct ikev2_auth		*auth;
3440 	struct iked_id			*id, *certid;
3441 	struct ibuf			*e = NULL;
3442 	uint8_t				 firstpayload;
3443 	int				 ret = -1;
3444 	ssize_t				 len;
3445 
3446 	if (sa == NULL)
3447 		return (-1);
3448 
3449 	if (sa->sa_state == IKEV2_STATE_EAP)
3450 		return (eap_identity_request(env, sa));
3451 
3452 	if (!sa_stateok(sa, IKEV2_STATE_VALID))
3453 		return (0);	/* ignore */
3454 
3455 	if (ikev2_cp_setaddr(env, sa, AF_INET) < 0 ||
3456 	    ikev2_cp_setaddr(env, sa, AF_INET6) < 0)
3457 		return (-1);
3458 
3459 	if (ikev2_childsa_negotiate(env, sa, &sa->sa_kex, &sa->sa_proposals,
3460 	    sa->sa_hdr.sh_initiator, 0, 0) < 0)
3461 		return (-1);
3462 
3463 	/* New encrypted message buffer */
3464 	if ((e = ibuf_static()) == NULL)
3465 		goto done;
3466 
3467 	if (!sa->sa_localauth.id_type) {
3468 		/* Downgrade the state */
3469 		sa_state(env, sa, IKEV2_STATE_AUTH_SUCCESS);
3470 	}
3471 
3472 	if (sa->sa_hdr.sh_initiator) {
3473 		id = &sa->sa_iid;
3474 		certid = &sa->sa_icert;
3475 	} else {
3476 		id = &sa->sa_rid;
3477 		certid = &sa->sa_rcert;
3478 	}
3479 
3480 	if (sa->sa_state != IKEV2_STATE_EAP_VALID) {
3481 		/* ID payload */
3482 		if ((pld = ikev2_add_payload(e)) == NULL)
3483 			goto done;
3484 		firstpayload = IKEV2_PAYLOAD_IDr;
3485 		if (ibuf_cat(e, id->id_buf) != 0)
3486 			goto done;
3487 		len = ibuf_size(id->id_buf);
3488 
3489 		/* CERT payload */
3490 		if ((sa->sa_statevalid & IKED_REQ_CERT) &&
3491 		    (certid->id_type != IKEV2_CERT_NONE)) {
3492 			if (ikev2_next_payload(pld, len,
3493 			    IKEV2_PAYLOAD_CERT) == -1)
3494 				goto done;
3495 
3496 			if ((pld = ikev2_add_payload(e)) == NULL)
3497 				goto done;
3498 			if ((cert = ibuf_advance(e, sizeof(*cert))) == NULL)
3499 				goto done;
3500 			cert->cert_type = certid->id_type;
3501 			if (ibuf_cat(e, certid->id_buf) != 0)
3502 				goto done;
3503 			len = ibuf_size(certid->id_buf) + sizeof(*cert);
3504 		}
3505 
3506 		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_AUTH) == -1)
3507 			goto done;
3508 	} else
3509 		firstpayload = IKEV2_PAYLOAD_AUTH;
3510 
3511 	/* AUTH payload */
3512 	if ((pld = ikev2_add_payload(e)) == NULL)
3513 		goto done;
3514 	if ((auth = ibuf_advance(e, sizeof(*auth))) == NULL)
3515 		goto done;
3516 	auth->auth_method = sa->sa_localauth.id_type;
3517 	if (ibuf_cat(e, sa->sa_localauth.id_buf) != 0)
3518 		goto done;
3519 	len = ibuf_size(sa->sa_localauth.id_buf) + sizeof(*auth);
3520 
3521 	/* CP payload */
3522 	if (sa->sa_cp) {
3523 		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_CP) == -1)
3524 			goto done;
3525 
3526 		if ((pld = ikev2_add_payload(e)) == NULL)
3527 			goto done;
3528 		if ((len = ikev2_add_cp(env, sa, e)) == -1)
3529 			goto done;
3530 	}
3531 
3532 	if (sa->sa_ipcompr.ic_transform &&
3533 	    (len = ikev2_add_ipcompnotify(env, e, &pld, len, sa, 0)) == -1)
3534 		goto done;
3535 	if (sa->sa_used_transport_mode &&
3536 	    (len = ikev2_add_transport_mode(env, e, &pld, len, sa)) == -1)
3537 		goto done;
3538 
3539 	/* MOBIKE */
3540 	if (sa->sa_mobike &&
3541 	    (len = ikev2_add_mobike(e, &pld, len)) == -1)
3542 		goto done;
3543 
3544 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_SA) == -1)
3545 		goto done;
3546 
3547 	/* SA payload */
3548 	if ((pld = ikev2_add_payload(e)) == NULL)
3549 		goto done;
3550 	if ((len = ikev2_add_proposals(env, sa, e, &sa->sa_proposals, 0,
3551 	    sa->sa_hdr.sh_initiator, 0, 1)) == -1)
3552 		goto done;
3553 
3554 	if ((len = ikev2_add_ts(e, &pld, len, sa, 0)) == -1)
3555 		goto done;
3556 
3557 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
3558 		goto done;
3559 
3560 	ret = ikev2_msg_send_encrypt(env, sa, &e,
3561 	    IKEV2_EXCHANGE_IKE_AUTH, firstpayload, 1);
3562 	if (ret == 0)
3563 		ret = ikev2_childsa_enable(env, sa);
3564 	if (ret == 0) {
3565 		sa_state(env, sa, IKEV2_STATE_ESTABLISHED);
3566 		/* Delete exchange timeout. */
3567 		timer_del(env, &sa->sa_timer);
3568 		ikev2_enable_timer(env, sa);
3569 		ikev2_log_established(sa);
3570 		ikev2_record_dstid(env, sa);
3571 	}
3572 
3573  done:
3574 	if (ret)
3575 		ikev2_childsa_delete(env, sa, 0, 0, NULL, 1);
3576 	ibuf_release(e);
3577 	return (ret);
3578 }
3579 
3580 int
3581 ikev2_send_ike_e(struct iked *env, struct iked_sa *sa, struct ibuf *buf,
3582     uint8_t firstpayload, uint8_t exchange, int response)
3583 {
3584 	struct ikev2_payload		*pld;
3585 	struct ibuf			*e = NULL;
3586 	int				 ret = -1;
3587 
3588 	/* New encrypted message buffer */
3589 	if ((e = ibuf_static()) == NULL)
3590 		goto done;
3591 
3592 	if ((pld = ikev2_add_payload(e)) == NULL)
3593 		goto done;
3594 
3595 	if (buf) {
3596 		if (ibuf_cat(e, buf) != 0)
3597 			goto done;
3598 
3599 		if (ikev2_next_payload(pld, ibuf_size(buf),
3600 		    IKEV2_PAYLOAD_NONE) == -1)
3601 			goto done;
3602 	}
3603 
3604 	ret = ikev2_msg_send_encrypt(env, sa, &e, exchange, firstpayload,
3605 	    response);
3606 
3607  done:
3608 	ibuf_release(e);
3609 
3610 	return (ret);
3611 }
3612 
3613 int
3614 ikev2_set_sa_proposal(struct iked_sa *sa, struct iked_policy *pol,
3615     unsigned int proto)
3616 {
3617 	struct iked_proposal		*prop, *copy;
3618 	struct iked_transform		*xform;
3619 	unsigned int			 i;
3620 
3621 	/* create copy of the policy proposals */
3622 	config_free_proposals(&sa->sa_proposals, proto);
3623 	TAILQ_FOREACH(prop, &pol->pol_proposals, prop_entry) {
3624 		if (proto != 0 && prop->prop_protoid != proto)
3625 			continue;
3626 		if ((copy = config_add_proposal(&sa->sa_proposals,
3627 		    prop->prop_id, prop->prop_protoid)) == NULL)
3628 			return (-1);
3629 		for (i = 0; i < prop->prop_nxforms; i++) {
3630 			xform = &prop->prop_xforms[i];
3631 			if (config_add_transform(copy, xform->xform_type,
3632 			    xform->xform_id, xform->xform_length,
3633 			    xform->xform_keylength) == NULL)
3634 				return (-1);
3635 		}
3636 	}
3637 	return (0);
3638 }
3639 
3640 int
3641 ikev2_send_create_child_sa(struct iked *env, struct iked_sa *sa,
3642     struct iked_spi *rekey, uint8_t protoid)
3643 {
3644 	struct iked_policy		*pol = sa->sa_policy;
3645 	struct iked_childsa		*csa = NULL, *csb = NULL;
3646 	struct ikev2_notify		*n;
3647 	struct ikev2_payload		*pld = NULL;
3648 	struct ikev2_keyexchange	*ke;
3649 	struct group			*group;
3650 	struct ibuf			*e = NULL, *nonce = NULL;
3651 	uint8_t				*ptr;
3652 	uint8_t				 firstpayload;
3653 	uint32_t			 spi;
3654 	ssize_t				 len = 0;
3655 	int				 initiator, ret = -1;
3656 
3657 	if (rekey)
3658 		log_debug("%s: rekeying %s spi %s", __func__,
3659 		    print_map(rekey->spi_protoid, ikev2_saproto_map),
3660 		    print_spi(rekey->spi, rekey->spi_size));
3661 	else
3662 		log_debug("%s: creating new CHILD SAs", __func__);
3663 
3664 	/* XXX cannot initiate multiple concurrent CREATE_CHILD_SA exchanges */
3665 	if (sa->sa_stateflags & (IKED_REQ_CHILDSA|IKED_REQ_INF)) {
3666 		log_debug("%s: another exchange already active",
3667 		    __func__);
3668 		return (-1);
3669 	}
3670 
3671 	ibuf_release(sa->sa_simult);
3672 	sa->sa_simult = NULL;
3673 	sa->sa_rekeyspi = 0;	/* clear rekey spi */
3674 	initiator = sa->sa_hdr.sh_initiator ? 1 : 0;
3675 
3676 	if (rekey &&
3677 	    ((csa = childsa_lookup(sa, rekey->spi,
3678 	    rekey->spi_protoid)) == NULL ||
3679 	    (csb = csa->csa_peersa) == NULL)) {
3680 		log_debug("%s: CHILD SA %s wasn't found", __func__,
3681 		    print_spi(rekey->spi, rekey->spi_size));
3682 		goto done;
3683 	}
3684 
3685 	/* Generate new nonce */
3686 	if ((nonce = ibuf_random(IKED_NONCE_SIZE)) == NULL)
3687 		goto done;
3688 
3689 	/* Update initiator nonce */
3690 	ibuf_release(sa->sa_inonce);
3691 	sa->sa_inonce = nonce;
3692 
3693 	if ((e = ibuf_static()) == NULL)
3694 		goto done;
3695 
3696 	if ((pol->pol_flags & IKED_POLICY_IPCOMP) &&
3697 	    (len = ikev2_add_ipcompnotify(env, e, &pld, 0, sa, 1)) == -1)
3698 		goto done;
3699 	if ((pol->pol_flags & IKED_POLICY_TRANSPORT) &&
3700 	    (len = ikev2_add_transport_mode(env, e, &pld, len, sa)) == -1)
3701 		goto done;
3702 
3703 	if (pld) {
3704 		firstpayload = IKEV2_PAYLOAD_NOTIFY;
3705 		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_SA) == -1)
3706 			goto done;
3707 	} else
3708 		firstpayload = IKEV2_PAYLOAD_SA;
3709 
3710 	/* SA payload */
3711 	if ((pld = ikev2_add_payload(e)) == NULL)
3712 		goto done;
3713 
3714 	/*
3715 	 * We need to reset the sa_proposal. Otherwise it would be
3716 	 * left over from the IKE_AUTH exchange and would not contain
3717 	 * any DH groups (e.g. for ESP child SAs).
3718 	 */
3719 	if (ikev2_set_sa_proposal(sa, pol, protoid) < 0) {
3720 		log_debug("%s: ikev2_set_sa_proposal failed", __func__);
3721 		goto done;
3722 	}
3723 
3724 	if ((len = ikev2_add_proposals(env, sa, e, &sa->sa_proposals,
3725 	    protoid, 1, 0, 0)) == -1)
3726 		goto done;
3727 
3728 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONCE) == -1)
3729 		goto done;
3730 
3731 	/* NONCE payload */
3732 	if ((pld = ikev2_add_payload(e)) == NULL)
3733 		goto done;
3734 	if (ikev2_add_buf(e, nonce) == -1)
3735 		goto done;
3736 	len = ibuf_size(nonce);
3737 
3738 	if (config_findtransform(&pol->pol_proposals, IKEV2_XFORMTYPE_DH,
3739 	    protoid)) {
3740 		log_debug("%s: enable PFS", __func__);
3741 		ikev2_sa_cleanup_dh(sa);
3742 		if (ikev2_sa_initiator_dh(sa, NULL, protoid, NULL) < 0) {
3743 			log_debug("%s: failed to setup DH", __func__);
3744 			goto done;
3745 		}
3746 		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_KE) == -1)
3747 			goto done;
3748 
3749 		/* KE payload */
3750 		if ((pld = ikev2_add_payload(e)) == NULL)
3751 			goto done;
3752 		if ((ke = ibuf_advance(e, sizeof(*ke))) == NULL)
3753 			goto done;
3754 		if ((group = sa->sa_dhgroup) == NULL) {
3755 			log_debug("%s: invalid dh", __func__);
3756 			goto done;
3757 		}
3758 		ke->kex_dhgroup = htobe16(group->id);
3759 		if (ikev2_add_buf(e, sa->sa_dhiexchange) == -1)
3760 			goto done;
3761 		len = sizeof(*ke) + dh_getlen(group);
3762 	}
3763 
3764 	if ((len = ikev2_add_ts(e, &pld, len, sa, !initiator)) == -1)
3765 		goto done;
3766 
3767 	if (rekey) {
3768 		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NOTIFY) == -1)
3769 			goto done;
3770 
3771 		/* REKEY_SA notification */
3772 		if ((pld = ikev2_add_payload(e)) == NULL)
3773 			goto done;
3774 		if ((n = ibuf_advance(e, sizeof(*n))) == NULL)
3775 			goto done;
3776 		n->n_type = htobe16(IKEV2_N_REKEY_SA);
3777 		n->n_protoid = rekey->spi_protoid;
3778 		n->n_spisize = rekey->spi_size;
3779 		if ((ptr = ibuf_advance(e, rekey->spi_size)) == NULL)
3780 			goto done;
3781 		len = rekey->spi_size;
3782 		spi = htobe32((uint32_t)csa->csa_peerspi);
3783 		memcpy(ptr, &spi, rekey->spi_size);
3784 		len += sizeof(*n);
3785 	}
3786 
3787 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
3788 		goto done;
3789 
3790 	ret = ikev2_msg_send_encrypt(env, sa, &e,
3791 	    IKEV2_EXCHANGE_CREATE_CHILD_SA, firstpayload, 0);
3792 	if (ret == 0) {
3793 		if (rekey) {
3794 			csa->csa_rekey = 1;
3795 			csb->csa_rekey = 1;
3796 			/*
3797 			 * Remember the peer spi of the rekeyed
3798 			 * SA for ikev2_init_create_child_sa().
3799 			 */
3800 			sa->sa_rekeyspi = csa->csa_peerspi;
3801 		}
3802 		sa->sa_stateflags |= IKED_REQ_CHILDSA;
3803 	}
3804 
3805 done:
3806 	ibuf_release(e);
3807 	return (ret);
3808 }
3809 
3810 void
3811 ikev2_ike_sa_rekey(struct iked *env, void *arg)
3812 {
3813 	struct iked_sa			*sa = arg;
3814 	struct iked_sa			*nsa = NULL;
3815 	struct ikev2_payload		*pld = NULL;
3816 	struct ikev2_keyexchange	*ke;
3817 	struct group			*group;
3818 	struct ibuf			*e = NULL, *nonce = NULL;
3819 	ssize_t				 len = 0;
3820 	int				 ret = -1;
3821 
3822 	log_debug("%s: IKE SA %p ispi %s rspi %s", __func__, sa,
3823 	    print_spi(sa->sa_hdr.sh_ispi, 8),
3824 	    print_spi(sa->sa_hdr.sh_rspi, 8));
3825 
3826 	if (sa->sa_nexti) {
3827 		log_debug("%s: already rekeying", __func__);
3828 		goto done;
3829 	}
3830 
3831 	if (sa->sa_stateflags & (IKED_REQ_CHILDSA|IKED_REQ_INF)) {
3832 		/*
3833 		 * We cannot initiate multiple concurrent CREATE_CHILD_SA
3834 		 * exchanges, so retry again fast.
3835 		 */
3836 		log_info("%s: busy, delaying rekey", SPI_SA(sa, __func__));
3837 		ikev2_ike_sa_rekey_schedule_fast(env, sa);
3838 		return;
3839 	}
3840 
3841 	/* We need to make sure the rekeying finishes in time */
3842 	timer_set(env, &sa->sa_rekey, ikev2_ike_sa_rekey_timeout, sa);
3843 	timer_add(env, &sa->sa_rekey, IKED_IKE_SA_REKEY_TIMEOUT);
3844 
3845 	if ((nsa = sa_new(env, 0, 0, 1, sa->sa_policy)) == NULL) {
3846 		log_debug("%s: failed to get new SA", __func__);
3847 		goto done;
3848 	}
3849 
3850 	if (ikev2_sa_initiator(env, nsa, sa, NULL)) {
3851 		log_debug("%s: failed to setup DH", __func__);
3852 		goto done;
3853 	}
3854 	sa_state(env, nsa, IKEV2_STATE_AUTH_SUCCESS);
3855 	nonce = nsa->sa_inonce;
3856 
3857 	if ((e = ibuf_static()) == NULL)
3858 		goto done;
3859 
3860 	/* SA payload */
3861 	if ((pld = ikev2_add_payload(e)) == NULL)
3862 		goto done;
3863 
3864 	/* just reuse the old IKE SA proposals */
3865 	if ((len = ikev2_add_proposals(env, nsa, e, &sa->sa_proposals,
3866 	    IKEV2_SAPROTO_IKE, 1, 1, 0)) == -1)
3867 		goto done;
3868 
3869 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONCE) == -1)
3870 		goto done;
3871 
3872 	/* NONCE payload */
3873 	if ((pld = ikev2_add_payload(e)) == NULL)
3874 		goto done;
3875 	if (ikev2_add_buf(e, nonce) == -1)
3876 		goto done;
3877 	len = ibuf_size(nonce);
3878 
3879 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_KE) == -1)
3880 		goto done;
3881 
3882 	/* KE payload */
3883 	if ((pld = ikev2_add_payload(e)) == NULL)
3884 		goto done;
3885 	if ((ke = ibuf_advance(e, sizeof(*ke))) == NULL)
3886 		goto done;
3887 	if ((group = nsa->sa_dhgroup) == NULL) {
3888 		log_debug("%s: invalid dh", __func__);
3889 		goto done;
3890 	}
3891 	ke->kex_dhgroup = htobe16(group->id);
3892 	if (ikev2_add_buf(e, nsa->sa_dhiexchange) == -1)
3893 		goto done;
3894 	len = sizeof(*ke) + dh_getlen(group);
3895 
3896 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
3897 		goto done;
3898 
3899 	ret = ikev2_msg_send_encrypt(env, sa, &e,
3900 	    IKEV2_EXCHANGE_CREATE_CHILD_SA, IKEV2_PAYLOAD_SA, 0);
3901 	if (ret == 0) {
3902 		sa->sa_stateflags |= IKED_REQ_CHILDSA;
3903 		sa->sa_nexti = nsa;
3904 		nsa->sa_previ = sa;
3905 		sa->sa_tmpfail = 0;
3906 		nsa = NULL;
3907 	}
3908 done:
3909 	if (nsa) {
3910 		ikev2_ike_sa_setreason(nsa, "failed to send CREATE_CHILD_SA");
3911 		sa_free(env, nsa);
3912 	}
3913 	ibuf_release(e);
3914 
3915 	if (ret == 0)
3916 		log_debug("%s: create child SA sent", __func__);
3917 	else
3918 		log_debug("%s: could not send create child SA", __func__);
3919 	/* XXX should we try again in case of ret != 0 ? */
3920 }
3921 
3922 int
3923 ikev2_nonce_cmp(struct ibuf *a, struct ibuf *b)
3924 {
3925 	size_t				alen, blen, len;
3926 	int				ret;
3927 
3928 	alen = ibuf_length(a);
3929 	blen = ibuf_length(b);
3930 	len = MIN(alen, blen);
3931 	ret = memcmp(ibuf_data(a), ibuf_data(b), len);
3932 	if (ret == 0)
3933 		ret = (alen < blen ? -1 : 1);
3934 	return (ret);
3935 }
3936 
3937 int
3938 ikev2_init_create_child_sa(struct iked *env, struct iked_message *msg)
3939 {
3940 	struct iked_childsa		*csa = NULL;
3941 	struct iked_proposal		*prop;
3942 	struct iked_sa			*sa = msg->msg_sa;
3943 	struct iked_sa			*nsa, *dsa;
3944 	struct iked_spi			*spi;
3945 	struct ikev2_delete		*del;
3946 	struct ibuf			*buf = NULL;
3947 	struct ibuf			*ni, *nr;
3948 	uint32_t			 spi32;
3949 	int				 pfs = 0, ret = -1;
3950 
3951 	if (!ikev2_msg_frompeer(msg) ||
3952 	    (sa->sa_stateflags & (IKED_REQ_CHILDSA|IKED_REQ_INF)) == 0)
3953 		return (0);
3954 
3955 	if (sa->sa_nexti != NULL && sa->sa_tmpfail) {
3956 		sa->sa_stateflags &= ~IKED_REQ_CHILDSA;
3957 		ikev2_ike_sa_setreason(sa->sa_nexti, "tmpfail");
3958 		sa_free(env, sa->sa_nexti);
3959 		sa->sa_nexti = NULL;
3960 		timer_set(env, &sa->sa_rekey, ikev2_ike_sa_rekey, sa);
3961 		ikev2_ike_sa_rekey_schedule_fast(env, sa);
3962 		log_info("%s: IKESA rekey delayed", SPI_SA(sa, __func__));
3963 		return (0);
3964 	}
3965 
3966 	if (msg->msg_prop == NULL ||
3967 	    TAILQ_EMPTY(&msg->msg_proposals)) {
3968 		log_debug("%s: no proposal specified", __func__);
3969 		return (-1);
3970 	}
3971 
3972 	if (proposals_negotiate(&sa->sa_proposals, &sa->sa_proposals,
3973 	    &msg->msg_proposals, 1) != 0) {
3974 		log_debug("%s: no proposal chosen", __func__);
3975 		return (-1);
3976 	}
3977 
3978 	TAILQ_FOREACH(prop, &sa->sa_proposals, prop_entry) {
3979 		if (prop->prop_protoid == msg->msg_prop->prop_protoid)
3980 			break;
3981 	}
3982 	if (prop == NULL) {
3983 		log_debug("%s: failed to find %s proposals", __func__,
3984 		    print_map(msg->msg_prop->prop_protoid, ikev2_saproto_map));
3985 		return (-1);
3986 	}
3987 
3988 	/* IKE SA rekeying */
3989 	if (prop->prop_protoid == IKEV2_SAPROTO_IKE) {
3990 		if (sa->sa_nexti == NULL) {
3991 			log_debug("%s: missing IKE SA for rekeying", __func__);
3992 			return (-1);
3993 		}
3994 		/* Update the responder SPI */
3995 		/* XXX sa_new() is just a lookup, so nsa == sa->sa_nexti */
3996 		spi = &msg->msg_prop->prop_peerspi;
3997 		if ((nsa = sa_new(env, sa->sa_nexti->sa_hdr.sh_ispi,
3998 		    spi->spi, 1, NULL)) == NULL || nsa != sa->sa_nexti) {
3999 			log_debug("%s: invalid rekey SA", __func__);
4000 			if (nsa) {
4001 				ikev2_ike_sa_setreason(nsa,
4002 				    "invalid SA for rekey");
4003 				sa_free(env, nsa);
4004 			}
4005 			ikev2_ike_sa_setreason(sa->sa_nexti, "invalid SA nexti");
4006 			sa_free(env, sa->sa_nexti);
4007 			sa->sa_nexti = NULL;	/* reset by sa_free */
4008 			return (-1);
4009 		}
4010 		if (ikev2_sa_initiator(env, nsa, sa, msg) == -1) {
4011 			log_debug("%s: failed to get IKE keys", __func__);
4012 			return (-1);
4013 		}
4014 		sa->sa_stateflags &= ~IKED_REQ_CHILDSA;
4015 		if (sa->sa_nextr) {
4016 			/*
4017 			 * Resolve simultaneous IKE SA rekeying by
4018 			 * deleting the SA with the lowest NONCE.
4019 			 */
4020 			log_info("%s: resolving simultaneous IKE SA rekeying",
4021 			    SPI_SA(sa, __func__));
4022 			/* ni: minimum nonce of sa_nexti */
4023 			if (ikev2_nonce_cmp(sa->sa_nexti->sa_inonce,
4024 			    sa->sa_nexti->sa_rnonce) < 0)
4025 				ni = sa->sa_nexti->sa_inonce;
4026 			else
4027 				ni = sa->sa_nexti->sa_rnonce;
4028 			/* nr: minimum nonce of sa_nextr */
4029 			if (ikev2_nonce_cmp(sa->sa_nextr->sa_inonce,
4030 			    sa->sa_nextr->sa_rnonce) < 0)
4031 				nr = sa->sa_nextr->sa_inonce;
4032 			else
4033 				nr = sa->sa_nextr->sa_rnonce;
4034 			/* delete SA with minumum nonce */
4035 			if (ikev2_nonce_cmp(ni, nr) < 0) {
4036 				dsa = sa->sa_nexti;
4037 				nsa = sa->sa_nextr;
4038 			} else {
4039 				dsa = sa->sa_nextr;
4040 				nsa = sa->sa_nexti;
4041 			}
4042 			/* unlink sa_nextr */
4043 			sa->sa_nextr->sa_prevr = NULL;
4044 			sa->sa_nextr = NULL;
4045 			/* Setup address, socket and NAT information */
4046 			sa_state(env, dsa, IKEV2_STATE_CLOSING);
4047 			sa_address(dsa, &dsa->sa_peer,
4048 			    (struct sockaddr *)&sa->sa_peer.addr);
4049 			sa_address(dsa, &dsa->sa_local,
4050 			    (struct sockaddr *)&sa->sa_local.addr);
4051 			dsa->sa_fd = sa->sa_fd;
4052 			dsa->sa_natt = sa->sa_natt;
4053 			dsa->sa_udpencap = sa->sa_udpencap;
4054 			ikev2_ike_sa_setreason(dsa,
4055 			    "resolving simultaneous rekeying");
4056 			ikev2_ikesa_delete(env, dsa, dsa->sa_hdr.sh_initiator);
4057 		}
4058 		/* unlink sa_nexti */
4059 		sa->sa_nexti->sa_previ = NULL;
4060 		sa->sa_nexti = NULL;
4061 		return (ikev2_ikesa_enable(env, sa, nsa));
4062 	}
4063 
4064 	/* Child SA rekeying */
4065 	if (sa->sa_rekeyspi &&
4066 	    (csa = childsa_lookup(sa, sa->sa_rekeyspi, prop->prop_protoid))
4067 	    != NULL) {
4068 		log_debug("%s: rekeying CHILD SA old %s spi %s", __func__,
4069 		    print_spi(csa->csa_spi.spi, csa->csa_spi.spi_size),
4070 		    print_spi(prop->prop_peerspi.spi,
4071 		    prop->prop_peerspi.spi_size));
4072 	}
4073 
4074 	/* check KE payload for PFS */
4075 	if (ibuf_length(msg->msg_ke)) {
4076 		log_debug("%s: using PFS", __func__);
4077 		if (ikev2_sa_initiator_dh(sa, msg, prop->prop_protoid, NULL) < 0) {
4078 			log_debug("%s: failed to setup DH", __func__);
4079 			return (ret);
4080 		}
4081 		if (sa->sa_dhpeer == NULL) {
4082 			log_debug("%s: no peer DH", __func__);
4083 			return (ret);
4084 		}
4085 		pfs = 1;
4086 		/* XXX check group against policy ? */
4087 		/* XXX should proposals_negotiate do this? */
4088 	}
4089 
4090 	/* Update responder's nonce */
4091 	if (!ibuf_length(msg->msg_nonce)) {
4092 		log_debug("%s: responder didn't send nonce", __func__);
4093 		return (-1);
4094 	}
4095 	ibuf_release(sa->sa_rnonce);
4096 	sa->sa_rnonce = ibuf_dup(msg->msg_nonce);
4097 
4098 	if (csa && (ni = sa->sa_simult) != NULL) {
4099 		log_info("%s: resolving simultaneous CHILD SA rekeying",
4100 		    SPI_SA(sa, __func__));
4101 		/* set nr to minimum nonce for exchange initiated by peer */
4102 		if (ikev2_nonce_cmp(sa->sa_inonce, sa->sa_rnonce) < 0)
4103 			nr = sa->sa_inonce;
4104 		else
4105 			nr = sa->sa_rnonce;
4106 		/*
4107 		 * If the exchange initated by us has smaller nonce,
4108 		 * then we have to delete our SAs.
4109 		 */
4110 		if (ikev2_nonce_cmp(ni, nr) < 0) {
4111 			ret = ikev2_childsa_delete_proposed(env, sa,
4112 			    &sa->sa_proposals);
4113 			goto done;
4114 		}
4115 	}
4116 
4117 	if (ikev2_childsa_negotiate(env, sa, &sa->sa_kex, &sa->sa_proposals, 1,
4118 	    pfs, !csa)) {
4119 		log_debug("%s: failed to get CHILD SAs", __func__);
4120 		return (-1);
4121 	}
4122 
4123 	if (csa) {
4124 		/* Child SA rekeying */
4125 
4126 		if ((buf = ibuf_static()) == NULL)
4127 			goto done;
4128 
4129 		if ((del = ibuf_advance(buf, sizeof(*del))) == NULL)
4130 			goto done;
4131 
4132 		del->del_protoid = prop->prop_protoid;
4133 		del->del_spisize = sizeof(spi32);
4134 		del->del_nspi = htobe16(1);
4135 
4136 		spi32 = htobe32(csa->csa_spi.spi);
4137 		if (ibuf_add(buf, &spi32, sizeof(spi32)))
4138 			goto done;
4139 
4140 		if (ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_DELETE,
4141 		    IKEV2_EXCHANGE_INFORMATIONAL, 0))
4142 			goto done;
4143 
4144 		sa->sa_stateflags |= IKED_REQ_INF;
4145 	}
4146 
4147 	ret = ikev2_childsa_enable(env, sa);
4148 
4149 done:
4150 	sa->sa_stateflags &= ~IKED_REQ_CHILDSA;
4151 
4152 	if (ret)
4153 		ikev2_childsa_delete(env, sa, 0, 0, NULL, 1);
4154 	else if (csa) {
4155 		/* delete the rekeyed SA pair */
4156 		ikev2_childsa_delete(env, sa, csa->csa_saproto,
4157 		    csa->csa_peerspi, NULL, 0);
4158 	}
4159 	ibuf_release(buf);
4160 	return (ret);
4161 }
4162 
4163 int
4164 ikev2_ikesa_enable(struct iked *env, struct iked_sa *sa, struct iked_sa *nsa)
4165 {
4166 	struct iked_childsa		*csa, *csatmp, *ipcomp;
4167 	struct iked_flow		*flow, *flowtmp;
4168 	struct iked_proposal		*prop, *proptmp;
4169 
4170 	log_debug("%s: IKE SA %p ispi %s rspi %s replaced"
4171 	    " by SA %p ispi %s rspi %s ",
4172 	    __func__, sa,
4173 	    print_spi(sa->sa_hdr.sh_ispi, 8),
4174 	    print_spi(sa->sa_hdr.sh_rspi, 8),
4175 	    nsa,
4176 	    print_spi(nsa->sa_hdr.sh_ispi, 8),
4177 	    print_spi(nsa->sa_hdr.sh_rspi, 8));
4178 
4179 	/* Transfer socket and NAT information */
4180 	nsa->sa_fd = sa->sa_fd;
4181 	nsa->sa_natt = sa->sa_natt;
4182 	nsa->sa_udpencap = sa->sa_udpencap;
4183 	nsa->sa_usekeepalive = sa->sa_usekeepalive;
4184 	nsa->sa_mobike = sa->sa_mobike;
4185 	nsa->sa_frag = sa->sa_frag;
4186 
4187 	/* Transfer old addresses */
4188 	memcpy(&nsa->sa_local, &sa->sa_local, sizeof(nsa->sa_local));
4189 	memcpy(&nsa->sa_peer, &sa->sa_peer, sizeof(nsa->sa_peer));
4190 	memcpy(&nsa->sa_peer_loaded, &sa->sa_peer_loaded,
4191 	    sizeof(nsa->sa_peer_loaded));
4192 
4193 	/* Transfer all Child SAs and flows from the old IKE SA */
4194 	TAILQ_FOREACH_SAFE(flow, &sa->sa_flows, flow_entry, flowtmp) {
4195 		TAILQ_REMOVE(&sa->sa_flows, flow, flow_entry);
4196 		TAILQ_INSERT_TAIL(&nsa->sa_flows, flow,
4197 		    flow_entry);
4198 		flow->flow_ikesa = nsa;
4199 		flow->flow_local = &nsa->sa_local;
4200 		flow->flow_peer = &nsa->sa_peer;
4201 	}
4202 	TAILQ_FOREACH_SAFE(csa, &sa->sa_childsas, csa_entry, csatmp) {
4203 		TAILQ_REMOVE(&sa->sa_childsas, csa, csa_entry);
4204 		TAILQ_INSERT_TAIL(&nsa->sa_childsas, csa,
4205 		    csa_entry);
4206 		csa->csa_ikesa = nsa;
4207 		if (csa->csa_dir == IPSP_DIRECTION_IN) {
4208 			csa->csa_local = &nsa->sa_peer;
4209 			csa->csa_peer = &nsa->sa_local;
4210 		} else {
4211 			csa->csa_local = &nsa->sa_local;
4212 			csa->csa_peer = &nsa->sa_peer;
4213 		}
4214 		if ((ipcomp = csa->csa_bundled) != NULL) {
4215 			ipcomp->csa_ikesa = nsa;
4216 			ipcomp->csa_local = csa->csa_local;
4217 			ipcomp->csa_peer = csa->csa_peer;
4218 		}
4219 	}
4220 	/* Transfer all non-IKE proposals */
4221 	TAILQ_FOREACH_SAFE(prop, &sa->sa_proposals, prop_entry, proptmp) {
4222 		if (prop->prop_protoid == IKEV2_SAPROTO_IKE)
4223 			continue;
4224 		TAILQ_REMOVE(&sa->sa_proposals, prop, prop_entry);
4225 		TAILQ_INSERT_TAIL(&nsa->sa_proposals, prop,
4226 		    prop_entry);
4227 	}
4228 
4229 	/* Preserve ID information */
4230 	ibuf_release(nsa->sa_iid.id_buf);
4231 	ibuf_release(nsa->sa_rid.id_buf);
4232 	ibuf_release(nsa->sa_icert.id_buf);
4233 	ibuf_release(nsa->sa_rcert.id_buf);
4234 	if (sa->sa_hdr.sh_initiator == nsa->sa_hdr.sh_initiator) {
4235 		nsa->sa_iid = sa->sa_iid;
4236 		nsa->sa_rid = sa->sa_rid;
4237 		nsa->sa_icert = sa->sa_icert;
4238 		nsa->sa_rcert = sa->sa_rcert;
4239 	} else {
4240 		/* initiator and responder role swapped */
4241 		nsa->sa_iid = sa->sa_rid;
4242 		nsa->sa_rid = sa->sa_iid;
4243 		nsa->sa_icert = sa->sa_rcert;
4244 		nsa->sa_rcert = sa->sa_icert;
4245 	}
4246 	/* duplicate the actual buffer */
4247 	nsa->sa_iid.id_buf = ibuf_dup(nsa->sa_iid.id_buf);
4248 	nsa->sa_rid.id_buf = ibuf_dup(nsa->sa_rid.id_buf);
4249 	nsa->sa_icert.id_buf = ibuf_dup(nsa->sa_icert.id_buf);
4250 	nsa->sa_rcert.id_buf = ibuf_dup(nsa->sa_rcert.id_buf);
4251 
4252 	/* Transfer sa_addrpool address */
4253 	if (sa->sa_addrpool) {
4254 		RB_REMOVE(iked_addrpool, &env->sc_addrpool, sa);
4255 		nsa->sa_addrpool = sa->sa_addrpool;
4256 		sa->sa_addrpool = NULL;
4257 		RB_INSERT(iked_addrpool, &env->sc_addrpool, nsa);
4258 	}
4259 	if (sa->sa_addrpool6) {
4260 		RB_REMOVE(iked_addrpool6, &env->sc_addrpool6, sa);
4261 		nsa->sa_addrpool6 = sa->sa_addrpool6;
4262 		sa->sa_addrpool6 = NULL;
4263 		RB_INSERT(iked_addrpool6, &env->sc_addrpool6, nsa);
4264 	}
4265 	/* Transfer other attributes */
4266         if (sa->sa_dstid_entry_valid) {
4267 		sa_dstid_remove(env, sa);
4268 		sa_dstid_insert(env, nsa);
4269 	}
4270 	if (sa->sa_tag) {
4271 		nsa->sa_tag = sa->sa_tag;
4272 		sa->sa_tag = NULL;
4273 	}
4274 	if (sa->sa_eapid) {
4275 		nsa->sa_eapid = sa->sa_eapid;
4276 		sa->sa_eapid = NULL;
4277 	}
4278 	log_info("%srekeyed as new IKESA %s",
4279 	    SPI_SA(sa, NULL), print_spi(nsa->sa_hdr.sh_ispi, 8));
4280 	sa_state(env, nsa, IKEV2_STATE_ESTABLISHED);
4281 	ikev2_enable_timer(env, nsa);
4282 
4283 	nsa->sa_stateflags = nsa->sa_statevalid; /* XXX */
4284 
4285 	/* unregister DPD keep alive timer & rekey first */
4286 	if (sa->sa_state == IKEV2_STATE_ESTABLISHED)
4287 		ikev2_disable_timer(env, sa);
4288 
4289 	ikev2_ike_sa_setreason(sa, "SA rekeyed");
4290 	ikev2_ikesa_delete(env, sa, nsa->sa_hdr.sh_initiator);
4291 	return (0);
4292 }
4293 
4294 void
4295 ikev2_ikesa_delete(struct iked *env, struct iked_sa *sa, int initiator)
4296 {
4297 	struct ibuf			*buf = NULL;
4298 	struct ikev2_delete		*del;
4299 
4300 	if (initiator) {
4301 		/* XXX: Can not have simultaneous INFORMATIONAL exchanges */
4302 		if (sa->sa_stateflags & IKED_REQ_INF)
4303 			goto done;
4304 		/* Send PAYLOAD_DELETE */
4305 		if ((buf = ibuf_static()) == NULL)
4306 			goto done;
4307 		if ((del = ibuf_advance(buf, sizeof(*del))) == NULL)
4308 			goto done;
4309 		del->del_protoid = IKEV2_SAPROTO_IKE;
4310 		del->del_spisize = 0;
4311 		del->del_nspi = 0;
4312 		if (ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_DELETE,
4313 		    IKEV2_EXCHANGE_INFORMATIONAL, 0) == -1)
4314 			goto done;
4315 		sa->sa_stateflags |= IKED_REQ_INF;
4316 		log_info("%s: sent delete, closing SA", SPI_SA(sa, __func__));
4317 done:
4318 		ibuf_release(buf);
4319 		sa_state(env, sa, IKEV2_STATE_CLOSED);
4320 	} else {
4321 		sa_state(env, sa, IKEV2_STATE_CLOSING);
4322 	}
4323 
4324 	/* Remove IKE-SA after timeout, e.g. if we don't get a delete */
4325 	timer_set(env, &sa->sa_timer, ikev2_ike_sa_timeout, sa);
4326 	timer_add(env, &sa->sa_timer, IKED_IKE_SA_DELETE_TIMEOUT);
4327 	ikev2_ike_sa_setreason(sa, "deleting SA");
4328 }
4329 
4330 void
4331 ikev2_ikesa_recv_delete(struct iked *env, struct iked_sa *sa)
4332 {
4333 	log_info("%s: received delete", SPI_SA(sa, __func__));
4334 	if (sa->sa_nexti) {
4335 		/*
4336 		 * We initiated rekeying, but since sa_nexti is still set
4337 		 * we have to assume that the the peer did not receive our
4338 		 * rekey message. So remove the initiated SA and -- if
4339 		 * sa_nextr is set -- keep the responder SA instead.
4340 		 */
4341 		if (sa->sa_nextr) {
4342 			log_debug("%s: resolving simultaneous IKE SA rekeying",
4343 			    SPI_SA(sa, __func__));
4344 			ikev2_ikesa_enable(env, sa, sa->sa_nextr);
4345 			/* unlink sa_nextr */
4346 			sa->sa_nextr->sa_prevr = NULL;
4347 			sa->sa_nextr = NULL;
4348 		}
4349 		ikev2_ike_sa_setreason(sa->sa_nexti,
4350 		    "received delete (simultaneous rekeying)");
4351 		sa_free(env, sa->sa_nexti);
4352 		sa->sa_nexti = NULL;	/* reset by sa_free */
4353 	}
4354 	ikev2_ike_sa_setreason(sa, "received delete");
4355 	sa_state(env, sa, IKEV2_STATE_CLOSED);
4356 }
4357 
4358 int
4359 ikev2_resp_create_child_sa(struct iked *env, struct iked_message *msg)
4360 {
4361 	struct iked_childsa		*csa = NULL;
4362 	struct iked_proposal		*prop;
4363 	struct iked_proposals		 proposals;
4364 	struct iked_kex			*kex, *kextmp = NULL;
4365 	struct iked_sa			*nsa = NULL, *sa = msg->msg_sa;
4366 	struct iked_spi			*spi, *rekey = &msg->msg_rekey;
4367 	struct ikev2_keyexchange	*ke;
4368 	struct ikev2_payload		*pld = NULL;
4369 	struct ibuf			*e = NULL, *nonce = NULL;
4370 	uint8_t				 firstpayload;
4371 	ssize_t				 len = 0;
4372 	int				 initiator, protoid, rekeying = 1;
4373 	int				 ret = -1;
4374 	int				 pfs = 0;
4375 
4376 	initiator = sa->sa_hdr.sh_initiator ? 1 : 0;
4377 
4378 	if (!ikev2_msg_frompeer(msg) || msg->msg_prop == NULL)
4379 		return (0);
4380 
4381 	TAILQ_INIT(&proposals);
4382 
4383 	if ((protoid = rekey->spi_protoid) == 0) {
4384 		/*
4385 		 * If REKEY_SA notification is not present, then it's either
4386 		 * IKE SA rekeying or the client wants to create additional
4387 		 * CHILD SAs
4388 		 */
4389 		if (msg->msg_prop->prop_protoid == IKEV2_SAPROTO_IKE) {
4390 			protoid = rekey->spi_protoid = IKEV2_SAPROTO_IKE;
4391 			if (sa->sa_hdr.sh_initiator)
4392 				rekey->spi = sa->sa_hdr.sh_rspi;
4393 			else
4394 				rekey->spi = sa->sa_hdr.sh_ispi;
4395 			rekey->spi_size = 8;
4396 		} else {
4397 			protoid = msg->msg_prop->prop_protoid;
4398 			rekeying = 0;
4399 		}
4400 	}
4401 
4402 	if (rekeying)
4403 		log_debug("%s: rekey %s spi %s", __func__,
4404 		    print_map(rekey->spi_protoid, ikev2_saproto_map),
4405 		    print_spi(rekey->spi, rekey->spi_size));
4406 	else
4407 		log_debug("%s: creating new %s SA", __func__,
4408 		    print_map(protoid, ikev2_saproto_map));
4409 
4410 	if (protoid == IKEV2_SAPROTO_IKE) {
4411 		if ((sa->sa_stateflags & IKED_REQ_CHILDSA)
4412 		    && !(sa->sa_nexti)) {
4413 			log_debug("%s: Ignore IKE SA rekey: waiting for Child "
4414 			    "SA response.", __func__);
4415 			/* Ignore, don't send error */
4416 			msg->msg_valid = 0;
4417 			return (0);
4418 		}
4419 
4420 		/* IKE SA rekeying */
4421 		spi = &msg->msg_prop->prop_peerspi;
4422 
4423 		if ((nsa = sa_new(env, spi->spi, 0, 0,
4424 		    msg->msg_policy)) == NULL) {
4425 			log_debug("%s: failed to get new SA", __func__);
4426 			return (ret);
4427 		}
4428 
4429 		if (ikev2_sa_responder(env, nsa, sa, msg)) {
4430 			log_debug("%s: failed to get IKE SA keys", __func__);
4431 			return (ret);
4432 		}
4433 
4434 		sa_state(env, nsa, IKEV2_STATE_AUTH_SUCCESS);
4435 
4436 		nonce = nsa->sa_rnonce;
4437 		kex = &nsa->sa_kex;
4438 	} else {
4439 		/* Child SA creating/rekeying */
4440 
4441 		if ((kex = kextmp = calloc(1, sizeof(*kextmp))) == NULL) {
4442 			log_debug("%s: calloc kex", __func__);
4443 			goto fail;
4444 		}
4445 
4446 		if (proposals_negotiate(&proposals,
4447 		    &sa->sa_policy->pol_proposals, &msg->msg_proposals,
4448 		    1) != 0) {
4449 			log_info("%s: no proposal chosen", __func__);
4450 			msg->msg_error = IKEV2_N_NO_PROPOSAL_CHOSEN;
4451 			goto fail;
4452 		}
4453 
4454 		/* check KE payload for PFS */
4455 		if (ibuf_length(msg->msg_parent->msg_ke)) {
4456 			log_debug("%s: using PFS", __func__);
4457 			if (ikev2_sa_responder_dh(kex, &proposals,
4458 			    msg->msg_parent, protoid) < 0) {
4459 				log_debug("%s: failed to setup DH", __func__);
4460 				goto fail;
4461 			}
4462 			pfs = 1;
4463 			/* XXX check group against policy ? */
4464 		}
4465 
4466 		/* Update peer SPI */
4467 		TAILQ_FOREACH(prop, &proposals, prop_entry) {
4468 			if (prop->prop_protoid == protoid)
4469 				break;
4470 		}
4471 		if (prop == NULL) {
4472 			log_debug("%s: failed to find %s proposals", __func__,
4473 			    print_map(protoid, ikev2_saproto_map));
4474 			goto fail;
4475 		} else
4476 			prop->prop_peerspi = msg->msg_prop->prop_peerspi;
4477 
4478 		/* Set rekeying flags on Child SAs */
4479 		if (rekeying) {
4480 			if ((csa = childsa_lookup(sa, rekey->spi,
4481 			    rekey->spi_protoid)) == NULL) {
4482 				log_info("%s: CHILD SA %s wasn't found",
4483 				    SPI_SA(sa, __func__),
4484 				    print_spi(rekey->spi, rekey->spi_size));
4485 				msg->msg_error = IKEV2_N_CHILD_SA_NOT_FOUND;
4486 				goto fail;
4487 			}
4488 			if (!csa->csa_loaded || !csa->csa_peersa ||
4489 			    !csa->csa_peersa->csa_loaded) {
4490 				log_info("%s: CHILD SA %s is not loaded"
4491 				    " or no peer SA", SPI_SA(sa, __func__),
4492 				    print_spi(rekey->spi, rekey->spi_size));
4493 				msg->msg_error = IKEV2_N_CHILD_SA_NOT_FOUND;
4494 				goto fail;
4495 			}
4496 			csa->csa_rekey = 1;
4497 			csa->csa_peersa->csa_rekey = 1;
4498 		}
4499 
4500 		/* Update initiator's nonce */
4501 		if (!ibuf_length(msg->msg_nonce)) {
4502 			log_debug("%s: initiator didn't send nonce", __func__);
4503 			goto fail;
4504 		}
4505 		ibuf_release(kex->kex_inonce);
4506 		kex->kex_inonce = ibuf_dup(msg->msg_nonce);
4507 
4508 		/* Generate new responder's nonce */
4509 		if ((nonce = ibuf_random(IKED_NONCE_SIZE)) == NULL)
4510 			goto fail;
4511 
4512 		/* Update responder's nonce */
4513 		ibuf_release(kex->kex_rnonce);
4514 		kex->kex_rnonce = nonce;
4515 
4516 		if (ikev2_childsa_negotiate(env, sa, kex, &proposals, 0,
4517 		    pfs, !rekeying)) {
4518 			log_debug("%s: failed to get CHILD SAs", __func__);
4519 			goto fail;
4520 		}
4521 
4522 		if (rekeying && (sa->sa_stateflags & IKED_REQ_CHILDSA) &&
4523 		    csa && (sa->sa_rekeyspi == csa->csa_peerspi)) {
4524 			log_info("%s: simultaneous rekeying for CHILD SA %s/%s",
4525 			    SPI_SA(sa, __func__),
4526 			    print_spi(rekey->spi, rekey->spi_size),
4527 			    print_spi(sa->sa_rekeyspi, rekey->spi_size));
4528 			ibuf_release(sa->sa_simult);
4529 			if (ikev2_nonce_cmp(kex->kex_inonce, nonce) < 0)
4530 				sa->sa_simult = ibuf_dup(kex->kex_inonce);
4531 			else
4532 				sa->sa_simult = ibuf_dup(nonce);
4533 		}
4534 	}
4535 
4536 	if ((e = ibuf_static()) == NULL)
4537 		goto done;
4538 
4539 	if (!nsa && sa->sa_ipcompr.ic_transform &&
4540 	    (len = ikev2_add_ipcompnotify(env, e, &pld, 0, sa, 0)) == -1)
4541 		goto done;
4542 	if (!nsa && sa->sa_used_transport_mode &&
4543 	    (len = ikev2_add_transport_mode(env, e, &pld, len, sa)) == -1)
4544 		goto done;
4545 
4546 	if (pld) {
4547 		firstpayload = IKEV2_PAYLOAD_NOTIFY;
4548 		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_SA) == -1)
4549 			goto done;
4550 	} else
4551 		firstpayload = IKEV2_PAYLOAD_SA;
4552 
4553 	/* SA payload */
4554 	if ((pld = ikev2_add_payload(e)) == NULL)
4555 		goto done;
4556 
4557 	if ((len = ikev2_add_proposals(env, nsa ? nsa : sa, e,
4558 		nsa ? &nsa->sa_proposals : &proposals,
4559 		protoid, 0, nsa ? 1 : 0, 0)) == -1)
4560 		goto done;
4561 
4562 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONCE) == -1)
4563 		goto done;
4564 
4565 	/* NONCE payload */
4566 	if ((pld = ikev2_add_payload(e)) == NULL)
4567 		goto done;
4568 	if (ikev2_add_buf(e, nonce) == -1)
4569 		goto done;
4570 	len = ibuf_size(nonce);
4571 
4572 	if (protoid == IKEV2_SAPROTO_IKE || pfs) {
4573 
4574 		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_KE) == -1)
4575 			goto done;
4576 
4577 		/* KE payload */
4578 		if ((pld = ikev2_add_payload(e)) == NULL)
4579 			goto done;
4580 		if ((ke = ibuf_advance(e, sizeof(*ke))) == NULL)
4581 			goto done;
4582 		if (kex->kex_dhgroup == NULL) {
4583 			log_debug("%s: invalid dh", __func__);
4584 			goto done;
4585 		}
4586 		ke->kex_dhgroup = htobe16(kex->kex_dhgroup->id);
4587 		if (ikev2_add_buf(e, kex->kex_dhrexchange) == -1)
4588 			goto done;
4589 		len = sizeof(*ke) + dh_getlen(kex->kex_dhgroup);
4590 	}
4591 
4592 	if (protoid != IKEV2_SAPROTO_IKE)
4593 		if ((len = ikev2_add_ts(e, &pld, len, sa, initiator)) == -1)
4594 			goto done;
4595 
4596 	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
4597 		goto done;
4598 
4599 	if ((ret = ikev2_msg_send_encrypt(env, sa, &e,
4600 	    IKEV2_EXCHANGE_CREATE_CHILD_SA, firstpayload, 1)) == -1)
4601 		goto done;
4602 
4603 	if (protoid == IKEV2_SAPROTO_IKE) {
4604 		/*
4605 		 * If we also have initiated rekeying for this IKE SA, then
4606 		 * sa_nexti is already set. In this case don't enable the new SA
4607 		 * immediately, but record it in sa_nextr, until the exchange
4608 		 * for sa_nexti completes in ikev2_init_create_child_sa() and
4609 		 * the 'winner' can be selected by comparing nonces.
4610 		 */
4611 		if (sa->sa_nexti) {
4612 			log_info("%s: simultaneous IKE SA rekeying",
4613 			    SPI_SA(sa, __func__));
4614 			sa->sa_nextr = nsa;
4615 			nsa->sa_prevr = sa;	/* backpointer */
4616 			ret = 0;
4617 		} else
4618 			ret = ikev2_ikesa_enable(env, sa, nsa);
4619 	} else
4620 		ret = ikev2_childsa_enable(env, sa);
4621 
4622  done:
4623 	if (ret && protoid != IKEV2_SAPROTO_IKE)
4624 		ikev2_childsa_delete(env, sa, 0, 0, NULL, 1);
4625 	ibuf_release(e);
4626 	config_free_proposals(&proposals, 0);
4627 	config_free_kex(kextmp);
4628 	return (ret);
4629 
4630  fail:
4631 	config_free_proposals(&proposals, 0);
4632 	config_free_kex(kextmp);
4633 	return (-1);
4634 }
4635 
4636 void
4637 ikev2_ike_sa_setreason(struct iked_sa *sa, char *reason)
4638 {
4639 	/* allow update only if reason is reset to NULL */
4640 	if (reason == NULL || sa->sa_reason == NULL)
4641 		sa->sa_reason = reason;
4642 }
4643 
4644 void
4645 ikev2_ike_sa_timeout(struct iked *env, void *arg)
4646 {
4647 	struct iked_sa			*sa = arg;
4648 
4649 	log_debug("%s: closing SA", __func__);
4650 	ikev2_ike_sa_setreason(sa, "timeout");
4651 	sa_free(env, sa);
4652 }
4653 
4654 void
4655 ikev2_ike_sa_rekey_timeout(struct iked *env, void *arg)
4656 {
4657 	struct iked_sa			*sa = arg;
4658 
4659 	log_debug("%s: closing SA", __func__);
4660 	ikev2_ike_sa_setreason(sa, "rekey timeout");
4661 	sa_free(env, sa);
4662 }
4663 
4664 void
4665 ikev2_ike_sa_rekey_schedule(struct iked *env, struct iked_sa *sa)
4666 {
4667 	timer_add(env, &sa->sa_rekey, (sa->sa_policy->pol_rekey * 850 +
4668 	    arc4random_uniform(100)) / 1000);
4669 }
4670 
4671 /* rekey delayed, so re-try after short delay (1% of configured) */
4672 void
4673 ikev2_ike_sa_rekey_schedule_fast(struct iked *env, struct iked_sa *sa)
4674 {
4675 	int timeout = sa->sa_policy->pol_rekey / 100; /* 1% */
4676 
4677 	if (timeout > 60)
4678 		timeout = 60;	/* max */
4679 	else if (timeout < 4)
4680 		timeout = 4;	/* min */
4681 	timer_add(env, &sa->sa_rekey, timeout);
4682 }
4683 
4684 void
4685 ikev2_ike_sa_alive(struct iked *env, void *arg)
4686 {
4687 	struct iked_sa			*sa = arg;
4688 	struct iked_childsa		*csa = NULL;
4689 	uint64_t			 last_used, diff;
4690 	int				 foundin = 0, foundout = 0;
4691 	int				 ikeidle = 0;
4692 
4693 	if (env->sc_alive_timeout == 0)
4694 		return;
4695 
4696 	/* check for incoming traffic on any child SA */
4697 	TAILQ_FOREACH(csa, &sa->sa_childsas, csa_entry) {
4698 		if (!csa->csa_loaded)
4699 			continue;
4700 		if (pfkey_sa_last_used(env->sc_pfkey, csa, &last_used) != 0)
4701 			continue;
4702 		diff = (uint32_t)(gettime() - last_used);
4703 		log_debug("%s: %s CHILD SA spi %s last used %llu second(s) ago",
4704 		    __func__,
4705 		    csa->csa_dir == IPSP_DIRECTION_IN ? "incoming" : "outgoing",
4706 		    print_spi(csa->csa_spi.spi, csa->csa_spi.spi_size), diff);
4707 		if (diff < env->sc_alive_timeout) {
4708 			if (csa->csa_dir == IPSP_DIRECTION_IN) {
4709 				foundin = 1;
4710 				break;
4711 			} else {
4712 				foundout = 1;
4713 			}
4714 		}
4715 	}
4716 
4717 	diff = (uint32_t)(gettime() - sa->sa_last_recvd);
4718 	if (diff >= IKED_IKE_SA_LAST_RECVD_TIMEOUT) {
4719 		ikeidle = 1;
4720 		log_debug("%s: IKE SA %p ispi %s rspi %s last received %llu"
4721 		    " second(s) ago", __func__, sa,
4722 		    print_spi(sa->sa_hdr.sh_ispi, 8),
4723 		    print_spi(sa->sa_hdr.sh_rspi, 8), diff);
4724 	}
4725 
4726 	/*
4727 	 * send probe if any outgoing SA has been used, but no incoming
4728 	 * SA, or if we haven't received an IKE message. but only if we
4729 	 * are not already waiting for an answer.
4730 	 */
4731 	if (((!foundin && foundout) || ikeidle) &&
4732 	    (sa->sa_stateflags & (IKED_REQ_CHILDSA|IKED_REQ_INF)) == 0) {
4733 		log_debug("%s: sending alive check", __func__);
4734 		ikev2_send_ike_e(env, sa, NULL, IKEV2_PAYLOAD_NONE,
4735 		    IKEV2_EXCHANGE_INFORMATIONAL, 0);
4736 		sa->sa_stateflags |= IKED_REQ_INF;
4737 	}
4738 
4739 	/* re-register */
4740 	timer_add(env, &sa->sa_timer, env->sc_alive_timeout);
4741 }
4742 
4743 void
4744 ikev2_ike_sa_keepalive(struct iked *env, void *arg)
4745 {
4746 	struct iked_sa			*sa = arg;
4747 	uint8_t				 marker = 0xff;
4748 
4749 	if (sendtofrom(sa->sa_fd, &marker, sizeof(marker), 0,
4750 	    (struct sockaddr *)&sa->sa_peer.addr, sa->sa_peer.addr.ss_len,
4751 	    (struct sockaddr *)&sa->sa_local.addr, sa->sa_local.addr.ss_len)
4752 	    == -1)
4753 		log_warn("%s: sendtofrom: peer %s local %s", __func__,
4754 		    print_host((struct sockaddr *)&sa->sa_peer.addr, NULL, 0),
4755 		    print_host((struct sockaddr *)&sa->sa_local.addr, NULL, 0));
4756 	else
4757 		log_debug("%s: peer %s local %s", __func__,
4758 		    print_host((struct sockaddr *)&sa->sa_peer.addr, NULL, 0),
4759 		    print_host((struct sockaddr *)&sa->sa_local.addr, NULL, 0));
4760 	timer_add(env, &sa->sa_keepalive, IKED_IKE_SA_KEEPALIVE_TIMEOUT);
4761 }
4762 
4763 int
4764 ikev2_send_informational(struct iked *env, struct iked_message *msg)
4765 {
4766 	struct iked_message		 resp;
4767 	struct ike_header		*hdr;
4768 	struct ikev2_payload		*pld;
4769 	struct ikev2_notify		*n;
4770 	struct iked_sa			*sa = msg->msg_sa, sah;
4771 	struct ibuf			*buf, *e = NULL;
4772 	int				 ret = -1;
4773 
4774 	if (msg->msg_error == 0)
4775 		return (0);
4776 
4777 	if ((buf = ikev2_msg_init(env, &resp,
4778 	    &msg->msg_peer, msg->msg_peerlen,
4779 	    &msg->msg_local, msg->msg_locallen, 0)) == NULL)
4780 		goto done;
4781 
4782 	/* New encrypted message buffer */
4783 	if ((e = ibuf_static()) == NULL)
4784 		goto done;
4785 
4786 	/* NOTIFY payload */
4787 	if ((pld = ikev2_add_payload(e)) == NULL)
4788 		goto done;
4789 
4790 	if ((n = ibuf_advance(e, sizeof(*n))) == NULL)
4791 		goto done;
4792 	n->n_protoid = IKEV2_SAPROTO_IKE;	/* XXX ESP etc. */
4793 	n->n_spisize = 0;
4794 	n->n_type = htobe16(msg->msg_error);
4795 
4796 	switch (msg->msg_error) {
4797 	case IKEV2_N_INVALID_IKE_SPI:
4798 		break;
4799 	case IKEV2_N_NO_PROPOSAL_CHOSEN:
4800 		ikev2_log_proposal(msg->msg_sa, &msg->msg_proposals);
4801 		break;
4802 	default:
4803 		log_warnx("%s: unsupported notification %s", SPI_SA(sa,
4804 		    __func__), print_map(msg->msg_error, ikev2_n_map));
4805 		goto done;
4806 	}
4807 	log_info("%s: %s", SPI_SA(sa, __func__),
4808 	    print_map(msg->msg_error, ikev2_n_map));
4809 
4810 	if (ikev2_next_payload(pld, sizeof(*n), IKEV2_PAYLOAD_NONE) == -1)
4811 		goto done;
4812 
4813 	if (sa != NULL && msg->msg_e) {
4814 		resp.msg_msgid = ikev2_msg_id(env, sa);
4815 
4816 		/* IKE header */
4817 		if ((hdr = ikev2_add_header(buf, sa, resp.msg_msgid,
4818 		    IKEV2_PAYLOAD_SK, IKEV2_EXCHANGE_INFORMATIONAL,
4819 		    0)) == NULL)
4820 			goto done;
4821 
4822 		if ((pld = ikev2_add_payload(buf)) == NULL)
4823 			goto done;
4824 
4825 		/* Encrypt message and add as an E payload */
4826 		if ((e = ikev2_msg_encrypt(env, sa, e, buf)) == NULL) {
4827 			log_debug("%s: encryption failed", __func__);
4828 			goto done;
4829 		}
4830 		if (ibuf_cat(buf, e) != 0)
4831 			goto done;
4832 		if (ikev2_next_payload(pld, ibuf_size(e),
4833 		    IKEV2_PAYLOAD_NOTIFY) == -1)
4834 			goto done;
4835 
4836 		if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
4837 			goto done;
4838 
4839 		/* Add integrity checksum (HMAC) */
4840 		if (ikev2_msg_integr(env, sa, buf) != 0) {
4841 			log_debug("%s: integrity checksum failed", __func__);
4842 			goto done;
4843 		}
4844 	} else {
4845 		if ((hdr = ibuf_seek(msg->msg_data, 0, sizeof(*hdr))) == NULL)
4846 			goto done;
4847 
4848 		bzero(&sah, sizeof(sah));
4849 		sah.sa_hdr.sh_rspi = betoh64(hdr->ike_rspi);
4850 		sah.sa_hdr.sh_ispi = betoh64(hdr->ike_ispi);
4851 		sah.sa_hdr.sh_initiator =
4852 		    hdr->ike_flags & IKEV2_FLAG_INITIATOR ? 0 : 1;
4853 
4854 		resp.msg_msgid = ikev2_msg_id(env, &sah);
4855 
4856 		/* IKE header */
4857 		if ((hdr = ikev2_add_header(buf, &sah, resp.msg_msgid,
4858 		    IKEV2_PAYLOAD_NOTIFY, IKEV2_EXCHANGE_INFORMATIONAL,
4859 		    0)) == NULL)
4860 			goto done;
4861 		if (ibuf_cat(buf, e) != 0)
4862 			goto done;
4863 		if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
4864 			goto done;
4865 	}
4866 
4867 	resp.msg_data = buf;
4868 	resp.msg_fd = msg->msg_fd;
4869 	TAILQ_INIT(&resp.msg_proposals);
4870 
4871 	ret = ikev2_msg_send(env, &resp);
4872 
4873  done:
4874 	ibuf_release(e);
4875 	ikev2_msg_cleanup(env, &resp);
4876 
4877 	return (ret);
4878 }
4879 
4880 ssize_t
4881 ikev2_psk(struct iked_sa *sa, uint8_t *data, size_t length,
4882     uint8_t **pskptr)
4883 {
4884 	uint8_t		*psk;
4885 	size_t		 psklen = -1;
4886 
4887 	if (hash_setkey(sa->sa_prf, data, length) == NULL)
4888 		return (-1);
4889 
4890 	if ((psk = calloc(1, hash_keylength(sa->sa_prf))) == NULL)
4891 		return (-1);
4892 
4893 	hash_init(sa->sa_prf);
4894 	hash_update(sa->sa_prf, IKEV2_KEYPAD, strlen(IKEV2_KEYPAD));
4895 	hash_final(sa->sa_prf, psk, &psklen);
4896 
4897 	*pskptr = psk;
4898 	return (psklen);
4899 }
4900 
4901 int
4902 ikev2_sa_initiator_dh(struct iked_sa *sa, struct iked_message *msg,
4903     unsigned int proto, struct iked_sa *osa)
4904 {
4905 	struct iked_policy	*pol = sa->sa_policy;
4906 	struct iked_transform	*xform;
4907 	struct iked_proposals	*proposals;
4908 
4909 	proposals = osa ? &osa->sa_proposals : &pol->pol_proposals;
4910 
4911 	if (sa->sa_dhgroup == NULL) {
4912 		if ((xform = config_findtransform(proposals,
4913 		    IKEV2_XFORMTYPE_DH, proto)) == NULL) {
4914 			log_debug("%s: did not find dh transform", __func__);
4915 			return (-1);
4916 		}
4917 		if ((sa->sa_dhgroup =
4918 		    group_get(xform->xform_id)) == NULL) {
4919 			log_debug("%s: invalid dh %d", __func__,
4920 			    xform->xform_id);
4921 			return (-1);
4922 		}
4923 	}
4924 
4925 	if (!ibuf_length(sa->sa_dhiexchange)) {
4926 		if ((sa->sa_dhiexchange = ibuf_new(NULL,
4927 		    dh_getlen(sa->sa_dhgroup))) == NULL) {
4928 			log_info("%s: failed to alloc dh exchange",
4929 			    SPI_SA(sa, __func__));
4930 			return (-1);
4931 		}
4932 		if (dh_create_exchange(sa->sa_dhgroup,
4933 		    sa->sa_dhiexchange->buf) == -1) {
4934 			log_debug("%s: failed to get dh exchange", __func__);
4935 			return (-1);
4936 		}
4937 	}
4938 
4939 	/* Initial message */
4940 	if (msg == NULL)
4941 		return (0);
4942 
4943 	if (!ibuf_length(sa->sa_dhrexchange)) {
4944 		if (!ibuf_length(msg->msg_ke)) {
4945 			log_debug("%s: invalid peer dh exchange", __func__);
4946 			return (-1);
4947 		}
4948 		if ((ssize_t)ibuf_length(msg->msg_ke) !=
4949 		    dh_getlen(sa->sa_dhgroup)) {
4950 			log_info("%s: invalid dh length, size %d",
4951 			    SPI_SA(msg->msg_sa, __func__),
4952 			    dh_getlen(sa->sa_dhgroup) * 8);
4953 			return (-1);
4954 		}
4955 		if ((sa->sa_dhrexchange = ibuf_dup(msg->msg_ke)) == NULL) {
4956 			log_debug("%s: failed to copy dh exchange", __func__);
4957 			return (-1);
4958 		}
4959 	}
4960 
4961 	/* Set a pointer to the peer exchange */
4962 	sa->sa_dhpeer = sa->sa_dhrexchange;
4963 	return (0);
4964 }
4965 
4966 int
4967 ikev2_sa_negotiate_common(struct iked *env, struct iked_sa *sa, struct iked_message *msg)
4968 {
4969 	struct iked_transform	*xform;
4970 
4971 	/* XXX we need a better way to get this */
4972 	if (proposals_negotiate(&sa->sa_proposals,
4973 	    &msg->msg_policy->pol_proposals, &msg->msg_proposals, 0) != 0) {
4974 		log_info("%s: proposals_negotiate", __func__);
4975 		return (-1);
4976 	}
4977 	if (sa_stateok(sa, IKEV2_STATE_SA_INIT))
4978 		sa_stateflags(sa, IKED_REQ_SA);
4979 
4980 	if (sa->sa_encr == NULL) {
4981 		if ((xform = config_findtransform(&sa->sa_proposals,
4982 		    IKEV2_XFORMTYPE_ENCR, 0)) == NULL) {
4983 			log_info("%s: did not find encr transform",
4984 			    SPI_SA(sa, __func__));
4985 			return (-1);
4986 		}
4987 		if ((sa->sa_encr = cipher_new(xform->xform_type,
4988 		    xform->xform_id, xform->xform_length)) == NULL) {
4989 			log_info("%s: failed to get encr",
4990 			    SPI_SA(sa, __func__));
4991 			return (-1);
4992 		}
4993 	}
4994 
4995 	/* For AEAD ciphers integrity is implicit */
4996 	if (sa->sa_encr->encr_authid && sa->sa_integr == NULL) {
4997 		if ((sa->sa_integr = hash_new(IKEV2_XFORMTYPE_INTEGR,
4998 		    sa->sa_encr->encr_authid)) == NULL) {
4999 			log_info("%s: failed to get AEAD integr",
5000 			    SPI_SA(sa, __func__));
5001 			return (-1);
5002 		}
5003 	}
5004 
5005 	if (sa->sa_prf == NULL) {
5006 		if ((xform = config_findtransform(&sa->sa_proposals,
5007 		    IKEV2_XFORMTYPE_PRF, 0)) == NULL) {
5008 			log_info("%s: did not find prf transform",
5009 			    SPI_SA(sa, __func__));
5010 			return (-1);
5011 		}
5012 		if ((sa->sa_prf =
5013 		    hash_new(xform->xform_type, xform->xform_id)) == NULL) {
5014 			log_info("%s: failed to get prf", SPI_SA(sa, __func__));
5015 			return (-1);
5016 		}
5017 	}
5018 
5019 	if (sa->sa_integr == NULL) {
5020 		if ((xform = config_findtransform(&sa->sa_proposals,
5021 		    IKEV2_XFORMTYPE_INTEGR, 0)) == NULL) {
5022 			log_info("%s: did not find integr transform",
5023 			    SPI_SA(sa, __func__));
5024 			return (-1);
5025 		}
5026 		if ((sa->sa_integr =
5027 		    hash_new(xform->xform_type, xform->xform_id)) == NULL) {
5028 			log_info("%s: failed to get integr",
5029 			    SPI_SA(sa, __func__));
5030 			return (-1);
5031 		}
5032 	}
5033 
5034 	return (0);
5035 }
5036 
5037 int
5038 ikev2_sa_initiator(struct iked *env, struct iked_sa *sa,
5039     struct iked_sa *osa, struct iked_message *msg)
5040 {
5041 	if (ikev2_sa_initiator_dh(sa, msg, 0, osa) < 0)
5042 		return (-1);
5043 
5044 	if (!ibuf_length(sa->sa_inonce)) {
5045 		if ((sa->sa_inonce = ibuf_random(IKED_NONCE_SIZE)) == NULL) {
5046 			log_info("%s: failed to get local nonce",
5047 			    SPI_SA(sa, __func__));
5048 			return (-1);
5049 		}
5050 	}
5051 
5052 	/* Initial message */
5053 	if (msg == NULL)
5054 		return (0);
5055 
5056 	if (!ibuf_length(sa->sa_rnonce)) {
5057 		if (!ibuf_length(msg->msg_nonce)) {
5058 			log_info("%s: invalid peer nonce",
5059 			    SPI_SA(sa, __func__));
5060 			return (-1);
5061 		}
5062 		if ((sa->sa_rnonce = ibuf_dup(msg->msg_nonce)) == NULL) {
5063 			log_info("%s: failed to get peer nonce",
5064 			    SPI_SA(sa, __func__));
5065 			return (-1);
5066 		}
5067 	}
5068 
5069 	if (ikev2_sa_negotiate_common(env, sa, msg) != 0)
5070 		return (-1);
5071 
5072 	ibuf_release(sa->sa_2ndmsg);
5073 	if ((sa->sa_2ndmsg = ibuf_dup(msg->msg_data)) == NULL) {
5074 		log_info("%s: failed to copy 2nd message",
5075 		    SPI_SA(sa, __func__));
5076 		return (-1);
5077 	}
5078 
5079 	return (ikev2_sa_keys(env, sa, osa ? osa->sa_key_d : NULL));
5080 }
5081 
5082 int
5083 ikev2_sa_responder_dh(struct iked_kex *kex, struct iked_proposals *proposals,
5084     struct iked_message *msg, unsigned int proto)
5085 {
5086 	struct iked_transform	*xform;
5087 
5088 	if (kex->kex_dhgroup == NULL) {
5089 		if ((xform = config_findtransform(proposals,
5090 		    IKEV2_XFORMTYPE_DH, proto)) == NULL) {
5091 			log_info("%s: did not find dh transform",
5092 			    SPI_SA(msg->msg_sa, __func__));
5093 			return (-1);
5094 		}
5095 		if ((kex->kex_dhgroup =
5096 		    group_get(xform->xform_id)) == NULL) {
5097 			log_debug("%s: invalid dh %d",
5098 			    SPI_SA(msg->msg_sa, __func__), xform->xform_id);
5099 			return (-1);
5100 		}
5101 	}
5102 
5103 	/* Look for dhgroup mismatch during an IKE SA negotiation */
5104 	if (msg->msg_dhgroup != kex->kex_dhgroup->id) {
5105 		log_info("%s: want dh %s, KE has %s",
5106 		    SPI_SA(msg->msg_sa, __func__),
5107 		    print_map(kex->kex_dhgroup->id, ikev2_xformdh_map),
5108 		    print_map(msg->msg_dhgroup, ikev2_xformdh_map));
5109 		msg->msg_error = IKEV2_N_INVALID_KE_PAYLOAD;
5110 		msg->msg_dhgroup = kex->kex_dhgroup->id;
5111 		return (-1);
5112 	}
5113 
5114 	if (!ibuf_length(kex->kex_dhrexchange)) {
5115 		if ((kex->kex_dhrexchange = ibuf_new(NULL,
5116 		    dh_getlen(kex->kex_dhgroup))) == NULL) {
5117 			log_info("%s: failed to alloc dh exchange",
5118 			    SPI_SA(msg->msg_sa, __func__));
5119 			return (-1);
5120 		}
5121 		if (dh_create_exchange(kex->kex_dhgroup,
5122 		    kex->kex_dhrexchange->buf) == -1) {
5123 			log_info("%s: failed to get dh exchange",
5124 			    SPI_SA(msg->msg_sa ,__func__));
5125 			return (-1);
5126 		}
5127 	}
5128 
5129 	if (!ibuf_length(kex->kex_dhiexchange)) {
5130 		if ((kex->kex_dhiexchange = ibuf_dup(msg->msg_ke)) == NULL ||
5131 		    ((ssize_t)ibuf_length(kex->kex_dhiexchange) !=
5132 		    dh_getlen(kex->kex_dhgroup))) {
5133 			/* XXX send notification to peer */
5134 			log_info("%s: invalid dh, size %d",
5135 			    SPI_SA(msg->msg_sa, __func__),
5136 			    dh_getlen(kex->kex_dhgroup) * 8);
5137 			return (-1);
5138 		}
5139 	}
5140 
5141 	/* Set a pointer to the peer exchange */
5142 	kex->kex_dhpeer = kex->kex_dhiexchange;
5143 	return (0);
5144 }
5145 
5146 int
5147 ikev2_sa_responder(struct iked *env, struct iked_sa *sa, struct iked_sa *osa,
5148     struct iked_message *msg)
5149 {
5150 	struct iked_policy	*old;
5151 
5152 	/* re-lookup policy based on 'msg' (unless IKESA is rekeyed) */
5153 	if (osa == NULL) {
5154 		old = sa->sa_policy;
5155 		sa->sa_policy = NULL;
5156 		if (policy_lookup(env, msg, &msg->msg_proposals) != 0 ||
5157 		    msg->msg_policy == NULL) {
5158 			sa->sa_policy = old;
5159 			log_info("%s: no proposal chosen", __func__);
5160 			msg->msg_error = IKEV2_N_NO_PROPOSAL_CHOSEN;
5161 			return (-1);
5162 		}
5163 		/* move sa to new policy */
5164 		sa->sa_policy = msg->msg_policy;
5165 		TAILQ_REMOVE(&old->pol_sapeers, sa, sa_peer_entry);
5166 		TAILQ_INSERT_TAIL(&sa->sa_policy->pol_sapeers,
5167 		    sa, sa_peer_entry);
5168 		if (old->pol_flags & IKED_POLICY_REFCNT)
5169 			policy_unref(env, old);
5170 		if (sa->sa_policy->pol_flags & IKED_POLICY_REFCNT)
5171 			policy_ref(env, sa->sa_policy);
5172 	}
5173 
5174 	sa_state(env, sa, IKEV2_STATE_SA_INIT);
5175 
5176 	ibuf_release(sa->sa_1stmsg);
5177 	if ((sa->sa_1stmsg = ibuf_dup(msg->msg_data)) == NULL) {
5178 		log_debug("%s: failed to copy 1st message", __func__);
5179 		return (-1);
5180 	}
5181 
5182 	if (!ibuf_length(sa->sa_rnonce) &&
5183 	    (sa->sa_rnonce = ibuf_random(IKED_NONCE_SIZE)) == NULL) {
5184 		log_debug("%s: failed to get local nonce", __func__);
5185 		return (-1);
5186 	}
5187 
5188 	if (!ibuf_length(sa->sa_inonce) &&
5189 	    ((ibuf_length(msg->msg_nonce) < IKED_NONCE_MIN) ||
5190 	    (sa->sa_inonce = ibuf_dup(msg->msg_nonce)) == NULL)) {
5191 		log_debug("%s: failed to get peer nonce", __func__);
5192 		return (-1);
5193 	}
5194 
5195 	if (ikev2_sa_negotiate_common(env, sa, msg) != 0)
5196 		return (-1);
5197 
5198 	if (ikev2_sa_responder_dh(&sa->sa_kex, &sa->sa_proposals, msg, 0) < 0)
5199 		return (-1);
5200 
5201 	return (ikev2_sa_keys(env, sa, osa ? osa->sa_key_d : NULL));
5202 }
5203 
5204 int
5205 ikev2_sa_keys(struct iked *env, struct iked_sa *sa, struct ibuf *key)
5206 {
5207 	struct iked_hash	*prf, *integr;
5208 	struct iked_cipher	*encr;
5209 	struct group		*group;
5210 	struct ibuf		*ninr, *dhsecret, *skeyseed, *s, *t;
5211 	size_t			 nonceminlen, ilen, rlen, tmplen;
5212 	uint64_t		 ispi, rspi;
5213 	int			 ret = -1;
5214 	int			 isaead = 0;
5215 
5216 	ninr = dhsecret = skeyseed = s = t = NULL;
5217 
5218 	if ((encr = sa->sa_encr) == NULL ||
5219 	    (prf = sa->sa_prf) == NULL ||
5220 	    (integr = sa->sa_integr) == NULL ||
5221 	    (group = sa->sa_dhgroup) == NULL) {
5222 		log_info("%s: failed to get key input data",
5223 		    SPI_SA(sa, __func__));
5224 		return (-1);
5225 	}
5226 
5227 	/* For AEADs no auth keys are required (see RFC 5282) */
5228 	isaead = !!integr->hash_isaead;
5229 
5230 	if (prf->hash_fixedkey)
5231 		nonceminlen = prf->hash_fixedkey;
5232 	else
5233 		nonceminlen = IKED_NONCE_MIN;
5234 
5235 	/* Nonces need a minimal size and should have an even length */
5236 	if (ibuf_length(sa->sa_inonce) < nonceminlen ||
5237 	    (ibuf_length(sa->sa_inonce) % 2) != 0 ||
5238 	    ibuf_length(sa->sa_rnonce) < nonceminlen ||
5239 	    (ibuf_length(sa->sa_rnonce) % 2) != 0) {
5240 		log_info("%s: invalid nonces", SPI_SA(sa, __func__));
5241 		return (-1);
5242 	}
5243 
5244 	if (prf->hash_fixedkey) {
5245 		/* Half of the key bits must come from Ni, and half from Nr */
5246 		ilen = prf->hash_fixedkey / 2;
5247 		rlen = prf->hash_fixedkey / 2;
5248 	} else {
5249 		/* Most PRF functions accept a variable-length key */
5250 		ilen = ibuf_length(sa->sa_inonce);
5251 		rlen = ibuf_length(sa->sa_rnonce);
5252 	}
5253 
5254 	/*
5255 	 *  Depending on whether we're generating new keying material
5256 	 *  or rekeying existing SA the algorithm is different. If the
5257 	 *  "key" argument is not specified a concatenation of nonces
5258 	 *  (Ni | Nr) is used as a PRF key, otherwise a "key" buffer
5259 	 *  is used and PRF is performed on the concatenation of DH
5260 	 *  exchange result and nonces (g^ir | Ni | Nr).  See sections
5261 	 *  2.14 and 2.18 of RFC7296 for more information.
5262 	 */
5263 
5264 	/*
5265 	 *  Generate g^ir
5266 	 */
5267 	if ((dhsecret = ibuf_new(NULL, dh_secretlen(group))) == NULL) {
5268 		log_debug("%s: failed to alloc dh secret", __func__);
5269 		goto done;
5270 	}
5271 	if (dh_create_shared(group, dhsecret->buf,
5272 	    sa->sa_dhpeer->buf) == -1) {
5273 		log_info("%s: failed to get dh secret"
5274 		    " group %d secret %zu exchange %zu",
5275 		    SPI_SA(sa, __func__),
5276 		    group->id, ibuf_length(dhsecret),
5277 		    ibuf_length(sa->sa_dhpeer));
5278 		goto done;
5279 	}
5280 
5281 	log_debug("%s: DHSECRET with %zu bytes", SPI_SA(sa, __func__),
5282 	    ibuf_length(dhsecret));
5283 	print_hex(dhsecret->buf, 0, ibuf_length(dhsecret));
5284 
5285 	if (!key) {
5286 		/*
5287 		 * Set PRF key to generate SKEEYSEED = prf(Ni | Nr, g^ir)
5288 		 */
5289 		if ((ninr = ibuf_new(sa->sa_inonce->buf, ilen)) == NULL ||
5290 		    ibuf_add(ninr, sa->sa_rnonce->buf, rlen) != 0) {
5291 			log_info("%s: failed to get nonce key buffer",
5292 			    SPI_SA(sa, __func__));
5293 			goto done;
5294 		}
5295 		key = ninr;
5296 	} else {
5297 		/*
5298 		 * Set PRF key to generate SKEEYSEED = prf(key, g^ir | Ni | Nr)
5299 		 */
5300 		if (ibuf_add(dhsecret, sa->sa_inonce->buf, ilen) != 0 ||
5301 		    ibuf_add(dhsecret, sa->sa_rnonce->buf, rlen) != 0) {
5302 			log_info("%s: failed to get nonce key buffer",
5303 			    SPI_SA(sa, __func__));
5304 			goto done;
5305 		}
5306 	}
5307 
5308 	if ((hash_setkey(prf, key->buf, ibuf_length(key))) == NULL) {
5309 		log_info("%s: failed to set prf key", SPI_SA(sa, __func__));
5310 		goto done;
5311 	}
5312 
5313 	if ((skeyseed = ibuf_new(NULL, hash_keylength(prf))) == NULL) {
5314 		log_info("%s: failed to get SKEYSEED buffer",
5315 		    SPI_SA(sa, __func__));
5316 		goto done;
5317 	}
5318 
5319 	tmplen = 0;
5320 	hash_init(prf);
5321 	hash_update(prf, dhsecret->buf, ibuf_length(dhsecret));
5322 	hash_final(prf, skeyseed->buf, &tmplen);
5323 
5324 	log_debug("%s: SKEYSEED with %zu bytes", __func__, tmplen);
5325 	print_hex(skeyseed->buf, 0, tmplen);
5326 
5327 	if (ibuf_setsize(skeyseed, tmplen) == -1) {
5328 		log_info("%s: failed to set keymaterial length",
5329 		    SPI_SA(sa, __func__));
5330 		goto done;
5331 	}
5332 
5333 	/*
5334 	 * Now generate the key material
5335 	 *
5336 	 * S = Ni | Nr | SPIi | SPIr
5337 	 */
5338 
5339 	/* S = Ni | Nr | SPIi | SPIr */
5340 	ilen = ibuf_length(sa->sa_inonce);
5341 	rlen = ibuf_length(sa->sa_rnonce);
5342 	ispi = htobe64(sa->sa_hdr.sh_ispi);
5343 	rspi = htobe64(sa->sa_hdr.sh_rspi);
5344 
5345 	if ((s = ibuf_new(sa->sa_inonce->buf, ilen)) == NULL ||
5346 	    ibuf_add(s, sa->sa_rnonce->buf, rlen) != 0 ||
5347 	    ibuf_add(s, &ispi, sizeof(ispi)) != 0 ||
5348 	    ibuf_add(s, &rspi, sizeof(rspi)) != 0) {
5349 		log_info("%s: failed to set S buffer",
5350 		    SPI_SA(sa, __func__));
5351 		goto done;
5352 	}
5353 
5354 	log_debug("%s: S with %zu bytes", SPI_SA(sa, __func__), ibuf_length(s));
5355 	print_hex(s->buf, 0, ibuf_length(s));
5356 
5357 	/*
5358 	 * Get the size of the key material we need and the number
5359 	 * of rounds we need to run the prf+ function.
5360 	 */
5361 	ilen = hash_length(prf) +			/* SK_d */
5362 	    (isaead ? 0 : hash_keylength(integr)) +	/* SK_ai */
5363 	    (isaead ? 0 : hash_keylength(integr)) +	/* SK_ar */
5364 	    cipher_keylength(encr) +			/* SK_ei */
5365 	    cipher_keylength(encr) +			/* SK_er */
5366 	    hash_keylength(prf) +			/* SK_pi */
5367 	    hash_keylength(prf);			/* SK_pr */
5368 
5369 	if ((t = ikev2_prfplus(prf, skeyseed, s, ilen)) == NULL) {
5370 		log_info("%s: failed to get IKE SA key material",
5371 		    SPI_SA(sa, __func__));
5372 		goto done;
5373 	}
5374 
5375 	/* ibuf_get() returns a new buffer from the next read offset */
5376 	if ((sa->sa_key_d = ibuf_get(t, hash_length(prf))) == NULL ||
5377 	    (!isaead &&
5378 	    (sa->sa_key_iauth = ibuf_get(t, hash_keylength(integr))) == NULL) ||
5379 	    (!isaead &&
5380 	    (sa->sa_key_rauth = ibuf_get(t, hash_keylength(integr))) == NULL) ||
5381 	    (sa->sa_key_iencr = ibuf_get(t, cipher_keylength(encr))) == NULL ||
5382 	    (sa->sa_key_rencr = ibuf_get(t, cipher_keylength(encr))) == NULL ||
5383 	    (sa->sa_key_iprf = ibuf_get(t, hash_length(prf))) == NULL ||
5384 	    (sa->sa_key_rprf = ibuf_get(t, hash_length(prf))) == NULL) {
5385 		log_debug("%s: failed to get SA keys", SPI_SA(sa, __func__));
5386 		goto done;
5387 	}
5388 
5389 	log_debug("%s: SK_d with %zu bytes", __func__,
5390 	    ibuf_length(sa->sa_key_d));
5391 	print_hex(sa->sa_key_d->buf, 0, ibuf_length(sa->sa_key_d));
5392 	if (!isaead) {
5393 		log_debug("%s: SK_ai with %zu bytes", __func__,
5394 		    ibuf_length(sa->sa_key_iauth));
5395 		print_hex(sa->sa_key_iauth->buf, 0,
5396 		    ibuf_length(sa->sa_key_iauth));
5397 		log_debug("%s: SK_ar with %zu bytes", __func__,
5398 		    ibuf_length(sa->sa_key_rauth));
5399 		print_hex(sa->sa_key_rauth->buf, 0,
5400 		    ibuf_length(sa->sa_key_rauth));
5401 	}
5402 	log_debug("%s: SK_ei with %zu bytes", __func__,
5403 	    ibuf_length(sa->sa_key_iencr));
5404 	print_hex(sa->sa_key_iencr->buf, 0, ibuf_length(sa->sa_key_iencr));
5405 	log_debug("%s: SK_er with %zu bytes", __func__,
5406 	    ibuf_length(sa->sa_key_rencr));
5407 	print_hex(sa->sa_key_rencr->buf, 0, ibuf_length(sa->sa_key_rencr));
5408 	log_debug("%s: SK_pi with %zu bytes", __func__,
5409 	    ibuf_length(sa->sa_key_iprf));
5410 	print_hex(sa->sa_key_iprf->buf, 0, ibuf_length(sa->sa_key_iprf));
5411 	log_debug("%s: SK_pr with %zu bytes", __func__,
5412 	    ibuf_length(sa->sa_key_rprf));
5413 	print_hex(sa->sa_key_rprf->buf, 0, ibuf_length(sa->sa_key_rprf));
5414 
5415 	ret = 0;
5416 
5417  done:
5418 	ibuf_release(ninr);
5419 	ibuf_release(dhsecret);
5420 	ibuf_release(skeyseed);
5421 	ibuf_release(s);
5422 	ibuf_release(t);
5423 
5424 	return (ret);
5425 }
5426 
5427 void
5428 ikev2_sa_cleanup_dh(struct iked_sa *sa)
5429 {
5430 	ibuf_release(sa->sa_dhiexchange);
5431 	ibuf_release(sa->sa_dhrexchange);
5432 	group_free(sa->sa_dhgroup);
5433 	sa->sa_dhiexchange = NULL;
5434 	sa->sa_dhrexchange = NULL;
5435 	sa->sa_dhgroup = NULL;
5436 }
5437 
5438 struct ibuf *
5439 ikev2_prfplus(struct iked_hash *prf, struct ibuf *key, struct ibuf *seed,
5440     size_t keymatlen)
5441 {
5442 	struct ibuf	*t = NULL, *t1 = NULL, *t2 = NULL;
5443 	size_t		 rlen, i, hashlen = 0;
5444 	uint8_t		 pad = 0;
5445 
5446 	/*
5447 	 * prf+ (K, S) = T1 | T2 | T3 | T4 | ...
5448 	 *
5449 	 * T1 = prf (K, S | 0x01)
5450 	 * T2 = prf (K, T1 | S | 0x02)
5451 	 * T3 = prf (K, T2 | S | 0x03)
5452 	 * T4 = prf (K, T3 | S | 0x04)
5453 	 */
5454 
5455 	if ((hash_setkey(prf, ibuf_data(key), ibuf_size(key))) == NULL) {
5456 		log_debug("%s: failed to set prf+ key", __func__);
5457 		goto fail;
5458 	}
5459 
5460 	if ((t = ibuf_new(NULL, 0)) == NULL) {
5461 		log_debug("%s: failed to get T buffer", __func__);
5462 		goto fail;
5463 	}
5464 
5465 	rlen = roundup(keymatlen, hash_length(prf)) / hash_length(prf);
5466 	if (rlen > 255)
5467 		fatalx("ikev2_prfplus: key material too large");
5468 
5469 	for (i = 0; i < rlen; i++) {
5470 		if (t1 != NULL) {
5471 			t2 = ibuf_new(t1->buf, ibuf_length(t1));
5472 			ibuf_release(t1);
5473 		} else
5474 			t2 = ibuf_new(NULL, 0);
5475 		t1 = ibuf_new(NULL, hash_keylength(prf));
5476 
5477 		ibuf_add(t2, seed->buf, ibuf_length(seed));
5478 		pad = i + 1;
5479 		ibuf_add(t2, &pad, 1);
5480 
5481 		hash_init(prf);
5482 		hash_update(prf, t2->buf, ibuf_length(t2));
5483 		hash_final(prf, t1->buf, &hashlen);
5484 
5485 		if (hashlen != hash_length(prf))
5486 			fatalx("ikev2_prfplus: hash length mismatch");
5487 
5488 		ibuf_release(t2);
5489 		ibuf_add(t, t1->buf, ibuf_length(t1));
5490 
5491 		log_debug("%s: T%d with %zu bytes", __func__,
5492 		    pad, ibuf_length(t1));
5493 		print_hex(t1->buf, 0, ibuf_length(t1));
5494 	}
5495 
5496 	log_debug("%s: Tn with %zu bytes", __func__, ibuf_length(t));
5497 	print_hex(t->buf, 0, ibuf_length(t));
5498 
5499 	ibuf_release(t1);
5500 
5501 	return (t);
5502 
5503  fail:
5504 	ibuf_release(t1);
5505 	ibuf_release(t);
5506 
5507 	return (NULL);
5508 }
5509 
5510 int
5511 ikev2_sa_tag(struct iked_sa *sa, struct iked_id *id)
5512 {
5513 	char	*format, *domain = NULL, *idrepl = NULL;
5514 	char	 idstr[IKED_ID_SIZE];
5515 	int	 ret = -1;
5516 	size_t	 len;
5517 
5518 	free(sa->sa_tag);
5519 	sa->sa_tag = NULL;
5520 	format = sa->sa_policy->pol_tag;
5521 
5522 	len = IKED_TAG_SIZE;
5523 	if ((sa->sa_tag = calloc(1, len)) == NULL) {
5524 		log_debug("%s: calloc", __func__);
5525 		goto fail;
5526 	}
5527 	if (strlcpy(sa->sa_tag, format, len) >= len) {
5528 		log_debug("%s: tag too long", __func__);
5529 		goto fail;
5530 	}
5531 
5532 	if (ikev2_print_id(id, idstr, sizeof(idstr)) == -1) {
5533 		log_debug("%s: invalid id", __func__);
5534 		goto fail;
5535 	}
5536 
5537 	/* ASN.1 DER IDs are too long, use the CN part instead */
5538 	if ((id->id_type == IKEV2_ID_ASN1_DN) &&
5539 	    (idrepl = strstr(idstr, "CN=")) != NULL) {
5540 		domain = strstr(idrepl, "emailAddress=");
5541 		idrepl[strcspn(idrepl, "/")] = '\0';
5542 	} else
5543 		idrepl = idstr;
5544 
5545 	if (strstr(format, "$id") != NULL) {
5546 		if (expand_string(sa->sa_tag, len, "$id", idrepl) != 0) {
5547 			log_debug("%s: failed to expand tag", __func__);
5548 			goto fail;
5549 		}
5550 	}
5551 
5552 	if (strstr(format, "$eapid") != NULL && sa->sa_eapid != NULL) {
5553 		if (expand_string(sa->sa_tag, len, "$eapid",
5554 		    sa->sa_eapid) != 0) {
5555 			log_debug("%s: failed to expand tag", __func__);
5556 			goto fail;
5557 		}
5558 	}
5559 
5560 	if (strstr(format, "$name") != NULL) {
5561 		if (expand_string(sa->sa_tag, len, "$name",
5562 		    sa->sa_policy->pol_name) != 0) {
5563 			log_debug("%s: failed to expand tag", __func__);
5564 			goto fail;
5565 		}
5566 	}
5567 
5568 	if (strstr(format, "$domain") != NULL) {
5569 		if (id->id_type == IKEV2_ID_FQDN)
5570 			domain = strchr(idrepl, '.');
5571 		else if (id->id_type == IKEV2_ID_UFQDN)
5572 			domain = strchr(idrepl, '@');
5573 		else if (*idstr == '/' && domain != NULL)
5574 			domain = strchr(domain, '@');
5575 		else
5576 			domain = NULL;
5577 		if (domain == NULL || strlen(domain) < 2) {
5578 			log_debug("%s: no valid domain in ID %s",
5579 			    __func__, idstr);
5580 			goto fail;
5581 		}
5582 		domain++;
5583 		if (expand_string(sa->sa_tag, len, "$domain", domain) != 0) {
5584 			log_debug("%s: failed to expand tag", __func__);
5585 			goto fail;
5586 		}
5587 	}
5588 
5589 	log_debug("%s: %s (%zu)", __func__, sa->sa_tag, strlen(sa->sa_tag));
5590 
5591 	ret = 0;
5592  fail:
5593 	if (ret != 0) {
5594 		free(sa->sa_tag);
5595 		sa->sa_tag = NULL;
5596 	}
5597 
5598 	return (ret);
5599 }
5600 
5601 int
5602 ikev2_childsa_delete_proposed(struct iked *env, struct iked_sa *sa,
5603     struct iked_proposals *proposals)
5604 {
5605 	struct ibuf			*buf = NULL;
5606 	struct iked_proposal		*prop;
5607 	struct ikev2_delete		*del;
5608 	uint32_t			 spi32;
5609 	uint8_t				 protoid = 0;
5610 	int				 ret = -1, count;
5611 
5612 	if (!sa_stateok(sa, IKEV2_STATE_VALID))
5613 		return (-1);
5614 
5615 	count = 0;
5616 	TAILQ_FOREACH(prop, proposals, prop_entry) {
5617 		if (ikev2_valid_proposal(prop, NULL, NULL, NULL) != 0)
5618 			continue;
5619 		protoid = prop->prop_protoid;
5620 		count++;
5621 	}
5622 	if (count == 0)
5623 		return (0);
5624 	if ((buf = ibuf_static()) == NULL)
5625 		return (-1);
5626 	if ((del = ibuf_advance(buf, sizeof(*del))) == NULL)
5627 		goto done;
5628 	/* XXX we assume all have the same protoid */
5629 	del->del_protoid = protoid;
5630 	del->del_spisize = 4;
5631 	del->del_nspi = htobe16(count);
5632 
5633 	TAILQ_FOREACH(prop, proposals, prop_entry) {
5634 		if (ikev2_valid_proposal(prop, NULL, NULL, NULL) != 0)
5635 			continue;
5636 		spi32 = htobe32(prop->prop_localspi.spi);
5637 		if (ibuf_add(buf, &spi32, sizeof(spi32)))
5638 			goto done;
5639 	}
5640 
5641 	if (ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_DELETE,
5642 	    IKEV2_EXCHANGE_INFORMATIONAL, 0) == -1)
5643 		goto done;
5644 	sa->sa_stateflags |= IKED_REQ_INF;
5645 	ret = 0;
5646  done:
5647 	ibuf_release(buf);
5648 
5649 	return (ret);
5650 }
5651 
5652 int
5653 ikev2_childsa_negotiate(struct iked *env, struct iked_sa *sa,
5654     struct iked_kex *kex, struct iked_proposals *proposals, int initiator,
5655     int pfs, int acquired)
5656 {
5657 	struct iked_proposal	*prop;
5658 	struct iked_transform	*xform, *encrxf = NULL, *integrxf = NULL;
5659 	struct iked_childsa	*csa = NULL, *csb = NULL;
5660 	struct iked_childsa	*csa2 = NULL, *csb2 = NULL;
5661 	struct iked_flow	*flow, *saflow, *flowa, *flowb;
5662 	struct iked_ipcomp	*ic;
5663 	struct ibuf		*keymat = NULL, *seed = NULL, *dhsecret = NULL;
5664 	struct group		*group;
5665 	uint32_t		 spi = 0;
5666 	unsigned int		 i;
5667 	size_t			 ilen = 0;
5668 	int			 esn, skip, ret = -1;
5669 
5670 	if (!sa_stateok(sa, IKEV2_STATE_VALID))
5671 		return (-1);
5672 
5673 	if (ikev2_sa_tag(sa, IKESA_DSTID(sa)) == -1)
5674 		return (-1);
5675 
5676 	ic = initiator ? &sa->sa_ipcompi : &sa->sa_ipcompr;
5677 	if (ic->ic_transform == 0 || ic->ic_cpi_out == 0 ||
5678 	    (initiator && ic->ic_cpi_in == 0))
5679 		ic = NULL;
5680 
5681 	/* reset state */
5682 	sa->sa_used_transport_mode = 0;
5683 
5684 	/* We need to determine the key material length first */
5685 	TAILQ_FOREACH(prop, proposals, prop_entry) {
5686 		if (prop->prop_protoid == IKEV2_SAPROTO_IKE)
5687 			continue;
5688 		log_debug("%s: proposal %d", __func__, prop->prop_id);
5689 		for (i = 0; i < prop->prop_nxforms; i++) {
5690 			xform = prop->prop_xforms + i;
5691 			xform->xform_keylength =
5692 			    keylength_xf(prop->prop_protoid,
5693 			    xform->xform_type, xform->xform_id);
5694 
5695 			switch (xform->xform_type) {
5696 			case IKEV2_XFORMTYPE_ENCR:
5697 			case IKEV2_XFORMTYPE_INTEGR:
5698 				if (xform->xform_length)
5699 					xform->xform_keylength =
5700 					    xform->xform_length;
5701 				xform->xform_keylength +=
5702 				    noncelength_xf(xform->xform_type,
5703 				    xform->xform_id);
5704 				ilen += xform->xform_keylength / 8;
5705 				break;
5706 			}
5707 		}
5708 	}
5709 
5710 	/* double key material length for inbound/outbound */
5711 	ilen *= 2;
5712 
5713 	log_debug("%s: key material length %zu", __func__, ilen);
5714 
5715 	if ((seed = ibuf_new(NULL, 0)) == NULL) {
5716 		log_debug("%s: failed to setup IKE SA key material", __func__);
5717 		goto done;
5718 	}
5719 	if (pfs) {
5720 		log_debug("%s: using PFS", __func__);
5721 		if (kex->kex_dhpeer == NULL ||
5722 		    ibuf_length(kex->kex_dhpeer) == 0 ||
5723 		    (group = kex->kex_dhgroup) == NULL) {
5724 			log_debug("%s: no dh group for pfs", __func__);
5725 			goto done;
5726 		}
5727 		if ((dhsecret = ibuf_new(NULL, dh_secretlen(group))) == NULL) {
5728 			log_debug("%s: failed to alloc dh secret", __func__);
5729 			goto done;
5730 		}
5731 		if (dh_create_shared(group, dhsecret->buf,
5732 		    kex->kex_dhpeer->buf) == -1) {
5733 			log_debug("%s: failed to get dh secret"
5734 			    " group %d len %d secretlen %d secret %zu"
5735 			    " exchange %zu", __func__, group->id,
5736 			    dh_getlen(group), dh_secretlen(group),
5737 			    ibuf_length(dhsecret),
5738 			    ibuf_length(kex->kex_dhpeer));
5739 			goto done;
5740 		}
5741 		if (ibuf_cat(seed, dhsecret) != 0) {
5742 			log_debug("%s: failed to set dh secret", __func__);
5743 			goto done;
5744 		}
5745 	}
5746 	if (ibuf_cat(seed, kex->kex_inonce) != 0 ||
5747 	    ibuf_cat(seed, kex->kex_rnonce) != 0 ||
5748 	    (keymat = ikev2_prfplus(sa->sa_prf,
5749 	    sa->sa_key_d, seed, ilen)) == NULL) {
5750 		log_debug("%s: failed to get IKE SA key material", __func__);
5751 		goto done;
5752 	}
5753 
5754 	/* Create the new flows */
5755 	TAILQ_FOREACH(prop, proposals, prop_entry) {
5756 		if (ikev2_valid_proposal(prop, NULL, NULL, NULL) != 0)
5757 			continue;
5758 
5759 		RB_FOREACH(flow, iked_flows, &sa->sa_policy->pol_flows) {
5760 
5761 			if ((flowa = calloc(1, sizeof(*flowa))) == NULL) {
5762 				log_debug("%s: failed to get flow", __func__);
5763 				goto done;
5764 			}
5765 
5766 			memcpy(flowa, flow, sizeof(*flow));
5767 			flowa->flow_dir = IPSP_DIRECTION_OUT;
5768 			flowa->flow_saproto = ic ? IKEV2_SAPROTO_IPCOMP :
5769 			    prop->prop_protoid;
5770 			flowa->flow_rdomain = sa->sa_policy->pol_rdomain;
5771 			flowa->flow_local = &sa->sa_local;
5772 			flowa->flow_peer = &sa->sa_peer;
5773 			flowa->flow_ikesa = sa;
5774 			ikev2_cp_fixaddr(sa, &flow->flow_dst, &flowa->flow_dst);
5775 
5776 			skip = 0;
5777 			TAILQ_FOREACH(saflow, &sa->sa_flows, flow_entry) {
5778 				if (flow_equal(saflow, flowa)) {
5779 					skip = 1;
5780 					break;
5781 				}
5782 			}
5783 			if (skip) {
5784 				flow_free(flowa);
5785 				continue;
5786 			}
5787 
5788 			if ((flowb = calloc(1, sizeof(*flowb))) == NULL) {
5789 				log_debug("%s: failed to get flow", __func__);
5790 				flow_free(flowa);
5791 				goto done;
5792 			}
5793 
5794 			memcpy(flowb, flowa, sizeof(*flow));
5795 
5796 			flowb->flow_dir = IPSP_DIRECTION_IN;
5797 			memcpy(&flowb->flow_src, &flow->flow_dst,
5798 			    sizeof(flow->flow_dst));
5799 			memcpy(&flowb->flow_dst, &flow->flow_src,
5800 			    sizeof(flow->flow_src));
5801 			ikev2_cp_fixaddr(sa, &flow->flow_dst, &flowb->flow_src);
5802 
5803 			TAILQ_INSERT_TAIL(&sa->sa_flows, flowa, flow_entry);
5804 			TAILQ_INSERT_TAIL(&sa->sa_flows, flowb, flow_entry);
5805 		}
5806 	}
5807 
5808 	/* create the CHILD SAs using the key material */
5809 	TAILQ_FOREACH(prop, proposals, prop_entry) {
5810 		if (ikev2_valid_proposal(prop, &encrxf, &integrxf, &esn) != 0)
5811 			continue;
5812 
5813 		spi = 0;
5814 
5815 		if ((csa = calloc(1, sizeof(*csa))) == NULL) {
5816 			log_debug("%s: failed to get CHILD SA", __func__);
5817 			goto done;
5818 		}
5819 
5820 		csa->csa_saproto = prop->prop_protoid;
5821 		csa->csa_ikesa = sa;
5822 		csa->csa_spi.spi_protoid = prop->prop_protoid;
5823 		csa->csa_esn = esn;
5824 		csa->csa_acquired = acquired;
5825 		csa->csa_transport = sa->sa_use_transport_mode;
5826 		sa->sa_used_transport_mode = sa->sa_use_transport_mode;
5827 
5828 		/* Set up responder's SPIs */
5829 		if (initiator) {
5830 			csa->csa_dir = IPSP_DIRECTION_OUT;
5831 			csa->csa_local = &sa->sa_local;
5832 			csa->csa_peer = &sa->sa_peer;
5833 			csa->csa_peerspi = prop->prop_localspi.spi;
5834 			csa->csa_spi.spi = prop->prop_peerspi.spi;
5835 			csa->csa_spi.spi_size = prop->prop_peerspi.spi_size;
5836 		} else {
5837 			csa->csa_dir = IPSP_DIRECTION_IN;
5838 			csa->csa_local = &sa->sa_peer;
5839 			csa->csa_peer = &sa->sa_local;
5840 
5841 			if ((ret = pfkey_sa_init(env->sc_pfkey, csa,
5842 			    &spi)) != 0)
5843 				goto done;
5844 			csa->csa_allocated = 1;
5845 
5846 			csa->csa_peerspi = prop->prop_peerspi.spi;
5847 			csa->csa_spi.spi = prop->prop_localspi.spi = spi;
5848 			csa->csa_spi.spi_size = 4;
5849 		}
5850 
5851 		if (encrxf && (csa->csa_encrkey = ibuf_get(keymat,
5852 		    encrxf->xform_keylength / 8)) == NULL) {
5853 			log_debug("%s: failed to get CHILD SA encryption key",
5854 			    __func__);
5855 			goto done;
5856 		}
5857 		if (integrxf && (csa->csa_integrkey = ibuf_get(keymat,
5858 		    integrxf->xform_keylength / 8)) == NULL) {
5859 			log_debug("%s: failed to get CHILD SA integrity key",
5860 			    __func__);
5861 			goto done;
5862 		}
5863 		if (encrxf)
5864 			csa->csa_encrid = encrxf->xform_id;
5865 		if (integrxf)
5866 			csa->csa_integrid = integrxf->xform_id;
5867 
5868 		if ((csb = calloc(1, sizeof(*csb))) == NULL) {
5869 			log_debug("%s: failed to get CHILD SA", __func__);
5870 			goto done;
5871 		}
5872 
5873 		memcpy(csb, csa, sizeof(*csb));
5874 
5875 		/* Set up initiator's SPIs */
5876 		csb->csa_spi.spi = csa->csa_peerspi;
5877 		csb->csa_peerspi = csa->csa_spi.spi;
5878 		csb->csa_allocated = csa->csa_allocated ? 0 : 1;
5879 		csb->csa_dir = csa->csa_dir == IPSP_DIRECTION_IN ?
5880 		    IPSP_DIRECTION_OUT : IPSP_DIRECTION_IN;
5881 		csb->csa_local = csa->csa_peer;
5882 		csb->csa_peer = csa->csa_local;
5883 
5884 		if (encrxf && (csb->csa_encrkey = ibuf_get(keymat,
5885 		    encrxf->xform_keylength / 8)) == NULL) {
5886 			log_debug("%s: failed to get CHILD SA encryption key",
5887 			    __func__);
5888 			goto done;
5889 		}
5890 		if (integrxf && (csb->csa_integrkey = ibuf_get(keymat,
5891 		    integrxf->xform_keylength / 8)) == NULL) {
5892 			log_debug("%s: failed to get CHILD SA integrity key",
5893 			    __func__);
5894 			goto done;
5895 		}
5896 
5897 		if (ic && prop->prop_protoid == IKEV2_SAPROTO_ESP) {
5898 			/* add IPCOMP SAs */
5899 			if ((csa2 = calloc(1, sizeof(*csa2))) == NULL) {
5900 				log_debug("%s: failed to get CHILD SA", __func__);
5901 				goto done;
5902 			}
5903 			if ((csb2 = calloc(1, sizeof(*csb2))) == NULL) {
5904 				log_debug("%s: failed to get CHILD SA", __func__);
5905 				goto done;
5906 			}
5907 
5908 			csa2->csa_saproto = IKEV2_SAPROTO_IPCOMP;
5909 			csa2->csa_ikesa = csa->csa_ikesa;
5910 			csa2->csa_dir = csa->csa_dir;
5911 			csa2->csa_local = csa->csa_local;
5912 			csa2->csa_peer = csa->csa_peer;
5913 			if (initiator) {
5914 				csa2->csa_spi.spi = ic->ic_cpi_out;
5915 				csa2->csa_peerspi = ic->ic_cpi_in;
5916 				csa2->csa_allocated = 0;
5917 				/* make sure IPCOMP CPIs are not reused */
5918 				ic->ic_transform = 0;
5919 				ic->ic_cpi_in = ic->ic_cpi_out = 0;
5920 			} else {
5921 				if ((ret = pfkey_sa_init(env->sc_pfkey, csa2,
5922 				    &spi)) != 0)
5923 					goto done;
5924 				ic->ic_cpi_in = spi;
5925 				csa2->csa_spi.spi = ic->ic_cpi_in;
5926 				csa2->csa_peerspi = ic->ic_cpi_out;
5927 				csa2->csa_allocated = 1;
5928 			}
5929 			csa2->csa_spi.spi_size = 2;
5930 
5931 			memcpy(csb2, csa2, sizeof(*csb2));
5932 			csb2->csa_spi.spi = csa2->csa_peerspi;
5933 			csb2->csa_peerspi = csa2->csa_spi.spi;
5934 			csb2->csa_allocated = csa2->csa_allocated ? 0 : 1;
5935 			csb2->csa_dir = csa2->csa_dir == IPSP_DIRECTION_IN ?
5936 			    IPSP_DIRECTION_OUT : IPSP_DIRECTION_IN;
5937 			csb2->csa_local = csa2->csa_peer;
5938 			csb2->csa_peer = csa2->csa_local;
5939 
5940 			/* link IPComp and ESP SAs, switch ESP to transport */
5941 			csa->csa_transport = 1;
5942 			csa->csa_bundled = csa2;
5943 			csa2->csa_bundled = csa;
5944 			csb->csa_transport = 1;
5945 			csb->csa_bundled = csb2;
5946 			csb2->csa_bundled = csb;
5947 			csa2 = NULL;
5948 			csb2 = NULL;
5949 
5950 			ic = NULL;
5951 		}
5952 
5953 		TAILQ_INSERT_TAIL(&sa->sa_childsas, csa, csa_entry);
5954 		TAILQ_INSERT_TAIL(&sa->sa_childsas, csb, csa_entry);
5955 
5956 		csa->csa_peersa = csb;
5957 		csb->csa_peersa = csa;
5958 		csa = NULL;
5959 		csb = NULL;
5960 	}
5961 
5962 	ret = 0;
5963  done:
5964 	sa->sa_use_transport_mode = 0;		/* reset state after use */
5965 	ibuf_release(dhsecret);
5966 	ibuf_release(keymat);
5967 	ibuf_release(seed);
5968 	childsa_free(csa);
5969 	childsa_free(csb);
5970 	childsa_free(csa2);
5971 	childsa_free(csb2);
5972 
5973 	return (ret);
5974 }
5975 
5976 int
5977 ikev2_childsa_enable(struct iked *env, struct iked_sa *sa)
5978 {
5979 	struct iked_childsa	*csa, *ocsa, *ipcomp;
5980 	struct iked_flow	*flow, *oflow;
5981 	int			 peer_changed, reload;
5982 	struct ibuf		*spibuf = NULL;
5983 	struct ibuf		*flowbuf = NULL;
5984 	char			*buf;
5985 
5986 	TAILQ_FOREACH(csa, &sa->sa_childsas, csa_entry) {
5987 		if (csa->csa_rekey || csa->csa_loaded)
5988 			continue;
5989 
5990 		ipcomp = csa->csa_bundled;
5991 		if (ipcomp && ipcomp->csa_loaded) {
5992 			log_info("%s: IPCOMP SA for CHILD SA spi %s"
5993 			    " already loaded", __func__,
5994 			    print_spi(csa->csa_spi.spi, csa->csa_spi.spi_size));
5995 			continue;
5996 		}
5997 
5998 		if (pfkey_sa_add(env->sc_pfkey, csa, NULL) != 0) {
5999 			log_debug("%s: failed to load CHILD SA spi %s",
6000 			    __func__, print_spi(csa->csa_spi.spi,
6001 			    csa->csa_spi.spi_size));
6002 			return (-1);
6003 		}
6004 		if (ipcomp) {
6005 			if (pfkey_sa_add(env->sc_pfkey, ipcomp, csa) != 0) {
6006 				log_debug("%s: failed to load IPCOMP spi %s",
6007 				    __func__, print_spi(ipcomp->csa_spi.spi,
6008 				    ipcomp->csa_spi.spi_size));
6009 				ipcomp = NULL;
6010 			}
6011 		}
6012 
6013 		if ((ocsa = RB_FIND(iked_activesas, &env->sc_activesas, csa))
6014 		    != NULL) {
6015 			log_debug("%s: replaced CHILD SA %p with %p spi %s",
6016 			    __func__, ocsa, csa, print_spi(ocsa->csa_spi.spi,
6017 			    ocsa->csa_spi.spi_size));
6018 			ocsa->csa_loaded = 0;
6019 			ocsa->csa_rekey = 1;	/* prevent re-loading */
6020 			RB_REMOVE(iked_activesas, &env->sc_activesas, ocsa);
6021 		}
6022 
6023 		RB_INSERT(iked_activesas, &env->sc_activesas, csa);
6024 
6025 		log_debug("%s: loaded CHILD SA spi %s", __func__,
6026 		    print_spi(csa->csa_spi.spi, csa->csa_spi.spi_size));
6027 
6028 		/* append SPI to log buffer */
6029 		if (ibuf_strlen(spibuf))
6030 			ibuf_strcat(&spibuf, ", ");
6031 		ibuf_strcat(&spibuf, print_spi(csa->csa_spi.spi,
6032 		    csa->csa_spi.spi_size));
6033 		if (ipcomp) {
6034 			ibuf_strcat(&spibuf, "(");
6035 			ibuf_strcat(&spibuf, print_spi(ipcomp->csa_spi.spi,
6036 			    ipcomp->csa_spi.spi_size));
6037 			ibuf_strcat(&spibuf, ")");
6038 		}
6039 	}
6040 
6041 	peer_changed = (memcmp(&sa->sa_peer_loaded, &sa->sa_peer,
6042 	    sizeof(sa->sa_peer_loaded)) != 0);
6043 
6044 	TAILQ_FOREACH(flow, &sa->sa_flows, flow_entry) {
6045 		/* re-load the flow if the peer for the flow has changed */
6046 		reload = 0;
6047 		if (flow->flow_loaded) {
6048 			if (!peer_changed) {
6049 				log_debug("%s: flow already loaded %p",
6050 				    __func__, flow);
6051 				continue;
6052 			}
6053 			RB_REMOVE(iked_flows, &env->sc_activeflows, flow);
6054 			(void)pfkey_flow_delete(env->sc_pfkey, flow);
6055 			flow->flow_loaded = 0; /* we did RB_REMOVE */
6056 			reload = 1;
6057 		}
6058 
6059 		if (pfkey_flow_add(env->sc_pfkey, flow) != 0) {
6060 			log_debug("%s: failed to load flow", __func__);
6061 			return (-1);
6062 		}
6063 
6064 		if ((oflow = RB_FIND(iked_flows, &env->sc_activeflows, flow))
6065 		    != NULL) {
6066 			log_debug("%s: replaced old flow %p with %p",
6067 			    __func__, oflow, flow);
6068 			oflow->flow_loaded = 0;
6069 			RB_REMOVE(iked_flows, &env->sc_activeflows, oflow);
6070 		}
6071 
6072 		RB_INSERT(iked_flows, &env->sc_activeflows, flow);
6073 
6074 		log_debug("%s: %sloaded flow %p", __func__,
6075 		    reload ? "re" : "", flow);
6076 
6077 		/* append flow to log buffer */
6078 		if (flow->flow_dir == IPSP_DIRECTION_OUT &&
6079 		    asprintf(&buf, "%s-%s/%d=%s/%d(%u)%s",
6080 		    print_map(flow->flow_saproto, ikev2_saproto_map),
6081 		    print_host((struct sockaddr *)&flow->flow_src.addr, NULL, 0),
6082 		    flow->flow_src.addr_mask,
6083 		    print_host((struct sockaddr *)&flow->flow_dst.addr, NULL, 0),
6084 		    flow->flow_dst.addr_mask,
6085 		    flow->flow_ipproto,
6086 		    reload ? "-R" : "") != -1) {
6087 			if (ibuf_strlen(flowbuf))
6088 				ibuf_strcat(&flowbuf, ", ");
6089 			ibuf_strcat(&flowbuf, buf);
6090 			free(buf);
6091 		}
6092 	}
6093 
6094 	/* remember the current address for ikev2_update_sa_addresses()  */
6095 	if (peer_changed) {
6096 		memcpy(&sa->sa_peer_loaded, &sa->sa_peer,
6097 		    sizeof(sa->sa_peer_loaded));
6098 		log_debug("%s: remember SA peer %s", __func__,
6099 		    print_host((struct sockaddr *)&sa->sa_peer_loaded.addr,
6100 		    NULL, 0));
6101 	}
6102 
6103 	if (ibuf_strlen(spibuf))
6104 		log_info("%s: loaded SPIs: %.*s", SPI_SA(sa, __func__),
6105 		    ibuf_strlen(spibuf), ibuf_data(spibuf));
6106 	if (ibuf_strlen(flowbuf))
6107 		log_info("%s: loaded flows: %.*s", SPI_SA(sa, __func__),
6108 		    ibuf_strlen(flowbuf), ibuf_data(flowbuf));
6109 	ibuf_release(spibuf);
6110 	ibuf_release(flowbuf);
6111 	return (0);
6112 }
6113 
6114 int
6115 ikev2_childsa_delete(struct iked *env, struct iked_sa *sa, uint8_t saproto,
6116     uint64_t spi, uint64_t *spiptr, int cleanup)
6117 {
6118 	struct iked_childsa	*csa, *csatmp = NULL, *ipcomp;
6119 	uint64_t		 peerspi = 0;
6120 	int			 found = 0;
6121 
6122 	TAILQ_FOREACH_SAFE(csa, &sa->sa_childsas, csa_entry, csatmp) {
6123 		if ((saproto && csa->csa_saproto != saproto) ||
6124 		    (spi && (csa->csa_spi.spi != spi &&
6125 			     csa->csa_peerspi != spi)) ||
6126 		    (cleanup && csa->csa_loaded))
6127 			continue;
6128 
6129 		if (csa->csa_loaded)
6130 			RB_REMOVE(iked_activesas, &env->sc_activesas, csa);
6131 
6132 		if (pfkey_sa_delete(env->sc_pfkey, csa) != 0)
6133 			log_info("%s: failed to delete CHILD SA spi %s",
6134 			    SPI_SA(sa, __func__), print_spi(csa->csa_spi.spi,
6135 			    csa->csa_spi.spi_size));
6136 		else
6137 			log_debug("%s: deleted CHILD SA spi %s",
6138 			    SPI_SA(sa, __func__), print_spi(csa->csa_spi.spi,
6139 			    csa->csa_spi.spi_size));
6140 		found++;
6141 
6142 		if (spi && csa->csa_spi.spi == spi)
6143 			peerspi = csa->csa_peerspi;
6144 
6145 		ipcomp = csa->csa_bundled;
6146 		if (ipcomp) {
6147 			if (ipcomp->csa_loaded) {
6148 				if (pfkey_sa_delete(env->sc_pfkey, ipcomp) != 0)
6149 					log_info("%s: failed to delete IPCOMP"
6150 					    " SA spi %s", SPI_SA(sa, __func__),
6151 					    print_spi(ipcomp->csa_spi.spi,
6152 					    ipcomp->csa_spi.spi_size));
6153 				else
6154 					log_debug("%s: deleted IPCOMP SA spi %s",
6155 					    SPI_SA(sa, __func__),
6156 					    print_spi(ipcomp->csa_spi.spi,
6157 					    ipcomp->csa_spi.spi_size));
6158 			}
6159 			childsa_free(ipcomp);
6160 		}
6161 		TAILQ_REMOVE(&sa->sa_childsas, csa, csa_entry);
6162 		childsa_free(csa);
6163 	}
6164 
6165 	if (spiptr)
6166 		*spiptr = peerspi;
6167 
6168 	return (found ? 0 : -1);
6169 }
6170 
6171 int
6172 ikev2_valid_proposal(struct iked_proposal *prop,
6173     struct iked_transform **exf, struct iked_transform **ixf, int *esn)
6174 {
6175 	struct iked_transform	*xform, *encrxf, *integrxf;
6176 	unsigned int		 i, doesn = 0;
6177 
6178 	switch (prop->prop_protoid) {
6179 	case IKEV2_SAPROTO_ESP:
6180 	case IKEV2_SAPROTO_AH:
6181 		break;
6182 	default:
6183 		return (-1);
6184 	}
6185 
6186 	encrxf = integrxf = NULL;
6187 	for (i = 0; i < prop->prop_nxforms; i++) {
6188 		xform = prop->prop_xforms + i;
6189 		if (xform->xform_type == IKEV2_XFORMTYPE_ENCR)
6190 			encrxf = xform;
6191 		else if (xform->xform_type == IKEV2_XFORMTYPE_INTEGR)
6192 			integrxf = xform;
6193 		else if (xform->xform_type == IKEV2_XFORMTYPE_ESN &&
6194 		    xform->xform_id == IKEV2_XFORMESN_ESN)
6195 			doesn = 1;
6196 	}
6197 
6198 	if (prop->prop_protoid == IKEV2_SAPROTO_IKE) {
6199 		if (encrxf == NULL || integrxf == NULL)
6200 			return (-1);
6201 	} else if (prop->prop_protoid == IKEV2_SAPROTO_AH) {
6202 		if (integrxf == NULL)
6203 			return (-1);
6204 	} else if (prop->prop_protoid == IKEV2_SAPROTO_ESP) {
6205 		if (encrxf == NULL)
6206 			return (-1);
6207 	}
6208 
6209 	if (exf)
6210 		*exf = encrxf;
6211 	if (ixf)
6212 		*ixf = integrxf;
6213 	if (esn)
6214 		*esn = doesn;
6215 
6216 	return (0);
6217 }
6218 
6219 /* return 0 if processed, -1 if busy */
6220 int
6221 ikev2_child_sa_acquire(struct iked *env, struct iked_flow *acquire)
6222 {
6223 	struct iked_flow	*flow;
6224 	struct iked_sa		*sa;
6225 	struct iked_policy	 pol, *p = NULL;
6226 
6227 	if (env->sc_passive)
6228 		return (0);
6229 
6230 	/* First try to find an active flow with IKE SA */
6231 	flow = RB_FIND(iked_flows, &env->sc_activeflows, acquire);
6232 	if (!flow) {
6233 		/* Otherwise try to find a matching policy */
6234 		bzero(&pol, sizeof(pol));
6235 		pol.pol_af = acquire->flow_peer->addr_af;
6236 		memcpy(&pol.pol_peer, acquire->flow_peer,
6237 		    sizeof(pol.pol_peer));
6238 
6239 		RB_INIT(&pol.pol_flows);
6240 		RB_INSERT(iked_flows, &pol.pol_flows, acquire);
6241 		pol.pol_nflows = 1;
6242 
6243 		if ((p = policy_test(env, &pol)) == NULL) {
6244 			log_warnx("%s: flow wasn't found", __func__);
6245 			return (0);
6246 		}
6247 
6248 		log_debug("%s: found matching policy '%s'", __func__,
6249 		    p->pol_name);
6250 
6251 		if (ikev2_init_ike_sa_peer(env, p,
6252 		    &p->pol_peer, NULL) != 0)
6253 			log_warnx("%s: failed to initiate a "
6254 			    "IKE_SA_INIT exchange for policy '%s'",
6255 			    __func__, p->pol_name);
6256 	} else {
6257 		log_debug("%s: found active flow", __func__);
6258 
6259 		if ((sa = flow->flow_ikesa) == NULL) {
6260 			log_warnx("%s: flow without SA", __func__);
6261 			return (0);
6262 		}
6263 		if (sa->sa_stateflags & (IKED_REQ_CHILDSA|IKED_REQ_INF))
6264 			return (-1);	/* busy, retry later */
6265 		if (ikev2_send_create_child_sa(env, sa, NULL,
6266 		    flow->flow_saproto) != 0)
6267 			log_warnx("%s: failed to initiate a "
6268 			    "CREATE_CHILD_SA exchange", SPI_SA(sa, __func__));
6269 	}
6270 	return (0);
6271 }
6272 
6273 void
6274 ikev2_disable_rekeying(struct iked *env, struct iked_sa *sa)
6275 {
6276 	struct iked_childsa		*csa;
6277 
6278 	TAILQ_FOREACH(csa, &sa->sa_childsas, csa_entry) {
6279 		csa->csa_persistent = 1;
6280 		csa->csa_rekey = 0;
6281 	}
6282 
6283 	(void)ikev2_childsa_delete(env, sa, 0, 0, NULL, 1);
6284 }
6285 
6286 /* return 0 if processed, -1 if busy */
6287 int
6288 ikev2_child_sa_rekey(struct iked *env, struct iked_spi *rekey)
6289 {
6290 	struct iked_childsa		*csa, key;
6291 	struct iked_sa			*sa;
6292 
6293 	key.csa_spi = *rekey;
6294 	csa = RB_FIND(iked_activesas, &env->sc_activesas, &key);
6295 	if (!csa)
6296 		return (0);
6297 
6298 	if (csa->csa_rekey)	/* See if it's already taken care of */
6299 		return (0);
6300 	if (csa->csa_acquired)	/* Don't rekey, wait for hard expire */
6301 		return (0);
6302 	if ((sa = csa->csa_ikesa) == NULL) {
6303 		log_warnx("%s: SA %s doesn't have a parent SA", __func__,
6304 		    print_spi(rekey->spi, rekey->spi_size));
6305 		return (0);
6306 	}
6307 	if (!sa_stateok(sa, IKEV2_STATE_ESTABLISHED)) {
6308 		log_warnx("%s: SA %s is not established", __func__,
6309 		    print_spi(rekey->spi, rekey->spi_size));
6310 		return (0);
6311 	}
6312 	if (sa->sa_stateflags & (IKED_REQ_CHILDSA|IKED_REQ_INF))
6313 		return (-1);	/* busy, retry later */
6314 	if (sa->sa_tmpfail)
6315 		return (-1);	/* peer is busy, retry later */
6316 	if (csa->csa_allocated)	/* Peer SPI died first, get the local one */
6317 		rekey->spi = csa->csa_peerspi;
6318 	if (ikev2_send_create_child_sa(env, sa, rekey, rekey->spi_protoid))
6319 		log_warnx("%s: failed to initiate a CREATE_CHILD_SA exchange",
6320 		    SPI_SA(sa, __func__));
6321 	return (0);
6322 }
6323 
6324 /* return 0 if processed, -1 if busy */
6325 int
6326 ikev2_child_sa_drop(struct iked *env, struct iked_spi *drop)
6327 {
6328 	struct ibuf			*buf = NULL;
6329 	struct iked_childsa		*csa, key;
6330 	struct iked_sa			*sa;
6331 	struct ikev2_delete		*del;
6332 	uint32_t			 spi32;
6333 
6334 	key.csa_spi = *drop;
6335 	csa = RB_FIND(iked_activesas, &env->sc_activesas, &key);
6336 	if (!csa || csa->csa_rekey)
6337 		return (0);
6338 
6339 	sa = csa->csa_ikesa;
6340 	if (sa && (sa->sa_stateflags & (IKED_REQ_CHILDSA|IKED_REQ_INF))) {
6341 		/* XXXX might loop, should we add a counter? */
6342 		log_debug("%s: parent SA busy", __func__);
6343 		return (-1);	/* busy, retry later */
6344 	}
6345 
6346 	RB_REMOVE(iked_activesas, &env->sc_activesas, csa);
6347 	csa->csa_loaded = 0;
6348 	csa->csa_rekey = 1;	/* prevent re-loading */
6349 	if (sa == NULL) {
6350 		log_debug("%s: failed to find a parent SA", __func__);
6351 		return (0);
6352 	}
6353 
6354 	if (csa->csa_allocated)
6355 		spi32 = htobe32(csa->csa_spi.spi);
6356 	else
6357 		spi32 = htobe32(csa->csa_peerspi);
6358 
6359 	if (ikev2_childsa_delete(env, sa, csa->csa_saproto,
6360 	    csa->csa_peerspi, NULL, 0))
6361 		log_debug("%s: failed to delete CHILD SA %s", __func__,
6362 		    print_spi(csa->csa_peerspi, drop->spi_size));
6363 
6364 	/* Send PAYLOAD_DELETE */
6365 
6366 	if ((buf = ibuf_static()) == NULL)
6367 		return (0);
6368 	if ((del = ibuf_advance(buf, sizeof(*del))) == NULL)
6369 		goto done;
6370 	del->del_protoid = drop->spi_protoid;
6371 	del->del_spisize = 4;
6372 	del->del_nspi = htobe16(1);
6373 	if (ibuf_add(buf, &spi32, sizeof(spi32)))
6374 		goto done;
6375 
6376 	if (ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_DELETE,
6377 	    IKEV2_EXCHANGE_INFORMATIONAL, 0) == -1)
6378 		goto done;
6379 
6380 	sa->sa_stateflags |= IKED_REQ_INF;
6381 
6382 done:
6383 	ibuf_release(buf);
6384 	return (0);
6385 }
6386 
6387 int
6388 ikev2_print_static_id(struct iked_static_id *id, char *idstr, size_t idstrlen)
6389 {
6390 	struct iked_id	idp;
6391 	int		ret = -1;
6392 
6393 	bzero(&idp, sizeof(idp));
6394 	if ((idp.id_buf = ibuf_new(id->id_data, id->id_length)) == NULL) {
6395 		bzero(idstr, idstrlen);
6396 		return (-1);
6397 	}
6398 	idp.id_type = id->id_type;
6399 	idp.id_offset = id->id_offset;
6400 	if (ikev2_print_id(&idp, idstr, idstrlen) == -1) {
6401 		bzero(idstr, idstrlen);
6402 		goto done;
6403 	}
6404 	ret = 0;
6405  done:
6406 	ibuf_release(idp.id_buf);
6407 	return (ret);
6408 }
6409 
6410 int
6411 ikev2_print_id(struct iked_id *id, char *idstr, size_t idstrlen)
6412 {
6413 	uint8_t				 buf[BUFSIZ], *ptr;
6414 	struct sockaddr_in		*s4;
6415 	struct sockaddr_in6		*s6;
6416 	char				*str;
6417 	ssize_t				 len;
6418 	int				 i;
6419 	const char			*type;
6420 
6421 	bzero(buf, sizeof(buf));
6422 	bzero(idstr, idstrlen);
6423 
6424 	if (id->id_buf == NULL)
6425 		return (-1);
6426 
6427 	len = ibuf_size(id->id_buf);
6428 	ptr = ibuf_data(id->id_buf);
6429 
6430 	if (len <= id->id_offset)
6431 		return (-1);
6432 
6433 	len -= id->id_offset;
6434 	ptr += id->id_offset;
6435 
6436 	type = print_map(id->id_type, ikev2_id_map);
6437 
6438 	if (strlcpy(idstr, type, idstrlen) >= idstrlen ||
6439 	    strlcat(idstr, "/", idstrlen) >= idstrlen)
6440 		return (-1);
6441 
6442 	idstr += strlen(idstr);
6443 	idstrlen -= strlen(idstr);
6444 
6445 	switch (id->id_type) {
6446 	case IKEV2_ID_IPV4:
6447 		s4 = (struct sockaddr_in *)buf;
6448 		s4->sin_family = AF_INET;
6449 		s4->sin_len = sizeof(*s4);
6450 		memcpy(&s4->sin_addr.s_addr, ptr, len);
6451 
6452 		if (print_host((struct sockaddr *)s4,
6453 		    idstr, idstrlen) == NULL)
6454 			return (-1);
6455 		break;
6456 	case IKEV2_ID_FQDN:
6457 	case IKEV2_ID_UFQDN:
6458 		if (len >= (ssize_t)sizeof(buf))
6459 			return (-1);
6460 
6461 		if ((str = get_string(ptr, len)) == NULL)
6462 			return (-1);
6463 
6464 		if (strlcpy(idstr, str, idstrlen) >= idstrlen) {
6465 			free(str);
6466 			return (-1);
6467 		}
6468 		free(str);
6469 		break;
6470 	case IKEV2_ID_IPV6:
6471 		s6 = (struct sockaddr_in6 *)buf;
6472 		s6->sin6_family = AF_INET6;
6473 		s6->sin6_len = sizeof(*s6);
6474 		memcpy(&s6->sin6_addr, ptr, len);
6475 
6476 		if (print_host((struct sockaddr *)s6,
6477 		    idstr, idstrlen) == NULL)
6478 			return (-1);
6479 		break;
6480 	case IKEV2_ID_ASN1_DN:
6481 		if ((str = ca_asn1_name(ptr, len)) == NULL)
6482 			return (-1);
6483 		if (strlcpy(idstr, str, idstrlen) >= idstrlen) {
6484 			free(str);
6485 			return (-1);
6486 		}
6487 		free(str);
6488 		break;
6489 	default:
6490 		/* XXX test */
6491 		for (i = 0; i < ((ssize_t)idstrlen - 1) && i < len; i++)
6492 			snprintf(idstr + i, idstrlen - i,
6493 			    "%02x", ptr[i]);
6494 		break;
6495 	}
6496 
6497 	return (0);
6498 }
6499 
6500 /*
6501  * If we have an IKEV2_CP_REQUEST for IKEV2_CFG_INTERNAL_IP4_ADDRESS and
6502  * if a network(pool) is configured, then select an address from that pool
6503  * and remember it in the sa_addrpool attribute.
6504  */
6505 int
6506 ikev2_cp_setaddr(struct iked *env, struct iked_sa *sa, sa_family_t family)
6507 {
6508 	struct iked_cfg		*ikecfg = NULL;
6509 	struct iked_policy	*pol = sa->sa_policy;
6510 	struct sockaddr_in	*in4 = NULL, *cfg4 = NULL;
6511 	struct sockaddr_in6	*in6 = NULL, *cfg6 = NULL;
6512 	struct iked_sa		 key;
6513 	struct iked_addr	 addr;
6514 	uint32_t		 mask, host, lower, upper, start, nhost;
6515 	size_t			 i;
6516 
6517 	switch (family) {
6518 	case AF_INET:
6519 		if (sa->sa_addrpool)
6520 			return (0);
6521 		break;
6522 	case AF_INET6:
6523 		if (sa->sa_addrpool6)
6524 			return (0);
6525 		break;
6526 	default:
6527 		return (-1);
6528 	}
6529 	if (pol->pol_ncfg == 0)
6530 		return (0);
6531 	/* check for an address pool config (address w/ prefixlen != 32) */
6532 	bzero(&addr, sizeof(addr));
6533 	for (i = 0; i < pol->pol_ncfg; i++) {
6534 		ikecfg = &pol->pol_cfg[i];
6535 		if (family == AF_INET &&
6536 		    ikecfg->cfg_type == IKEV2_CFG_INTERNAL_IP4_ADDRESS &&
6537 		    ikecfg->cfg.address.addr_mask != 32) {
6538 			addr.addr_af = AF_INET;
6539 			break;
6540 		}
6541 		if (family == AF_INET6 &&
6542 		    ikecfg->cfg_type == IKEV2_CFG_INTERNAL_IP6_ADDRESS &&
6543 		    ikecfg->cfg.address.addr_mask != 128) {
6544 			addr.addr_af = AF_INET6;
6545 			break;
6546 		}
6547 	}
6548 	if (i == pol->pol_ncfg)
6549 		return (0);
6550 
6551 	/*
6552 	 * failure: pool configured, but not requested.
6553 	 * If we continue, we might end up with flows where 0.0.0.0 is NOT
6554 	 * replaced with an address from the pool with ikev2_cp_fixaddr().
6555 	 */
6556 	if (sa->sa_cp != IKEV2_CP_REQUEST) {
6557 		log_debug("%s: pool configured, but IKEV2_CP_REQUEST missing",
6558 		    __func__);
6559 		return (-1);
6560 	}
6561 
6562 	switch (addr.addr_af) {
6563 	case AF_INET:
6564 		cfg4 = (struct sockaddr_in *)&ikecfg->cfg.address.addr;
6565 		in4 = (struct sockaddr_in *)&addr.addr;
6566 		in4->sin_family = AF_INET;
6567 		in4->sin_len = sizeof(*in4);
6568 		mask = prefixlen2mask(ikecfg->cfg.address.addr_mask);
6569 		lower = ntohl(cfg4->sin_addr.s_addr & ~mask);
6570 		key.sa_addrpool = &addr;
6571 		break;
6572 	case AF_INET6:
6573 		cfg6 = (struct sockaddr_in6 *)&ikecfg->cfg.address.addr;
6574 		in6 = (struct sockaddr_in6 *)&addr.addr;
6575 		in6->sin6_family = AF_INET6;
6576 		in6->sin6_len = sizeof(*in6);
6577 		/* truncate prefixlen to get a 32-bit space */
6578 		mask = (ikecfg->cfg.address.addr_mask >= 96)
6579 		    ? prefixlen2mask(ikecfg->cfg.address.addr_mask - 96)
6580 		    : prefixlen2mask(0);
6581 		memcpy(&lower, &cfg6->sin6_addr.s6_addr[12], sizeof(uint32_t));
6582 		lower = ntohl(lower & ~mask);
6583 		key.sa_addrpool6 = &addr;
6584 		break;
6585 	default:
6586 		return (-1);
6587 	}
6588 
6589 	if (lower == 0)
6590 		lower = 1;
6591 	/* Note that start, upper and host are in HOST byte order */
6592 	upper = ntohl(~mask);
6593 	/* Randomly select start from [lower, upper-1] */
6594 	start = arc4random_uniform(upper - lower) + lower;
6595 
6596 	for (host = start;;) {
6597 		log_debug("%s: mask %x start %x lower %x host %x upper %x",
6598 		    __func__, mask, start, lower, host, upper);
6599 		switch (addr.addr_af) {
6600 		case AF_INET:
6601 			in4->sin_addr.s_addr =
6602 			    (cfg4->sin_addr.s_addr & mask) | htonl(host);
6603 			break;
6604 		case AF_INET6:
6605 			memcpy(in6, cfg6, sizeof(*in6));
6606 			memcpy(&nhost, &cfg6->sin6_addr.s6_addr[12],
6607 			    sizeof(uint32_t));
6608 			nhost = (nhost & mask) | htonl(host);
6609 			memcpy(&in6->sin6_addr.s6_addr[12], &nhost,
6610 			    sizeof(uint32_t));
6611 			break;
6612 		}
6613 		if ((addr.addr_af == AF_INET &&
6614 		    !RB_FIND(iked_addrpool, &env->sc_addrpool, &key)) ||
6615 		    (addr.addr_af == AF_INET6 &&
6616 		    !RB_FIND(iked_addrpool6, &env->sc_addrpool6, &key)))
6617 			break;
6618 		/* try next address */
6619 		host++;
6620 		/* but skip broadcast and network address */
6621 		if (host >= upper || host < lower)
6622 			host = lower;
6623 		if (host == start) {
6624 			log_warnx("%s: address pool exhausted", __func__);
6625 			return (-1);		/* exhausted */
6626 		}
6627 	}
6628 
6629 	switch (addr.addr_af) {
6630 	case AF_INET:
6631 		if (!key.sa_addrpool)
6632 			return (-1);			/* cannot happen? */
6633 		if ((sa->sa_addrpool = calloc(1, sizeof(addr))) == NULL)
6634 			return (-1);
6635 		memcpy(sa->sa_addrpool, &addr, sizeof(addr));
6636 		RB_INSERT(iked_addrpool, &env->sc_addrpool, sa);
6637 		break;
6638 	case AF_INET6:
6639 		if (!key.sa_addrpool6)
6640 			return (-1);			/* cannot happen? */
6641 		if ((sa->sa_addrpool6 = calloc(1, sizeof(addr))) == NULL)
6642 			return (-1);
6643 		memcpy(sa->sa_addrpool6, &addr, sizeof(addr));
6644 		RB_INSERT(iked_addrpool6, &env->sc_addrpool6, sa);
6645 		break;
6646 	default:
6647 		return (-1);
6648 	}
6649 	return (0);
6650 }
6651 
6652 /*
6653  * if 'addr' is 'UNSPECIFIED' replace it with sa_addrpool from
6654  * the ip-pool and store the result in 'patched'.
6655  */
6656 int
6657 ikev2_cp_fixaddr(struct iked_sa *sa, struct iked_addr *addr,
6658     struct iked_addr *patched)
6659 {
6660 	struct sockaddr_in	*in4;
6661 	struct sockaddr_in6	*in6;
6662 
6663 	switch (addr->addr_af) {
6664 	case AF_INET:
6665 		if (sa->sa_addrpool == NULL)
6666 			return (-1);
6667 		in4 = (struct sockaddr_in *)&addr->addr;
6668 		if (in4->sin_addr.s_addr)
6669 			return (-1);
6670 		memcpy(patched, sa->sa_addrpool, sizeof(*patched));
6671 		break;
6672 	case AF_INET6:
6673 		if (sa->sa_addrpool6 == NULL)
6674 			return (-1);
6675 		in6 = (struct sockaddr_in6 *)&addr->addr;
6676 		if (!IN6_IS_ADDR_UNSPECIFIED(&in6->sin6_addr))
6677 			return (-1);
6678 		memcpy(patched, sa->sa_addrpool6, sizeof(*patched));
6679 		break;
6680 	}
6681 	return (0);
6682 }
6683 
6684 int
6685 ikev2_update_sa_addresses(struct iked *env, struct iked_sa *sa)
6686 {
6687 	struct iked_childsa	*csa, *ipcomp;
6688 	struct iked_flow	*flow, *oflow;
6689 	struct iked_message	*msg;
6690 
6691 	if (!sa_stateok(sa, IKEV2_STATE_ESTABLISHED))
6692 		return -1;
6693 
6694 	log_info("%s: old %s new %s", SPI_SA(sa, __func__),
6695 	    print_host((struct sockaddr *)&sa->sa_peer_loaded.addr, NULL, 0),
6696 	    print_host((struct sockaddr *)&sa->sa_peer.addr, NULL, 0));
6697 
6698 	TAILQ_FOREACH(csa, &sa->sa_childsas, csa_entry) {
6699 		if (!csa->csa_loaded)
6700 			continue;
6701 		if (pfkey_sa_update_addresses(env->sc_pfkey, csa) != 0)
6702 			log_debug("%s: failed to update sa", __func__);
6703 		if ((ipcomp = csa->csa_bundled) != NULL &&
6704 		    ipcomp->csa_loaded)
6705 			if (pfkey_sa_update_addresses(env->sc_pfkey, ipcomp)
6706 			     != 0)
6707 				log_debug("%s: failed to update sa", __func__);
6708 	}
6709 
6710 	/* delete and re-add flows */
6711 	TAILQ_FOREACH(flow, &sa->sa_flows, flow_entry) {
6712 		if (flow->flow_loaded) {
6713 			RB_REMOVE(iked_flows, &env->sc_activeflows, flow);
6714 			(void)pfkey_flow_delete(env->sc_pfkey, flow);
6715 			flow->flow_loaded = 0;
6716 		}
6717 		if (pfkey_flow_add(env->sc_pfkey, flow) != 0)
6718 			log_debug("%s: failed to add flow %p", __func__, flow);
6719 		if (!flow->flow_loaded)
6720 			continue;
6721 		if ((oflow = RB_FIND(iked_flows, &env->sc_activeflows, flow))
6722 		    != NULL) {
6723 			log_debug("%s: replaced old flow %p with %p",
6724 			    __func__, oflow, flow);
6725 			oflow->flow_loaded = 0;
6726 			RB_REMOVE(iked_flows, &env->sc_activeflows, oflow);
6727 		}
6728 		RB_INSERT(iked_flows, &env->sc_activeflows, flow);
6729 	}
6730 
6731 	/* update pending requests and responses */
6732 	TAILQ_FOREACH(msg, &sa->sa_requests, msg_entry) {
6733 		msg->msg_local = sa->sa_local.addr;
6734 		msg->msg_locallen = sa->sa_local.addr.ss_len;
6735 		msg->msg_peer = sa->sa_peer.addr;
6736 		msg->msg_peerlen = sa->sa_peer.addr.ss_len;
6737 	}
6738 	TAILQ_FOREACH(msg, &sa->sa_responses, msg_entry) {
6739 		msg->msg_local = sa->sa_local.addr;
6740 		msg->msg_locallen = sa->sa_local.addr.ss_len;
6741 		msg->msg_peer = sa->sa_peer.addr;
6742 		msg->msg_peerlen = sa->sa_peer.addr.ss_len;
6743 	}
6744 
6745 	/* Update sa_peer_loaded, to match in-kernel information */
6746 	memcpy(&sa->sa_peer_loaded, &sa->sa_peer, sizeof(sa->sa_peer_loaded));
6747 
6748 	return 0;
6749 }
6750 
6751 void
6752 ikev2_info_sa(struct iked *env, int dolog, const char *msg, struct iked_sa *sa)
6753 {
6754 	char		 idstr[IKED_ID_SIZE];
6755 	char		*buf;
6756 	int		 buflen;
6757 
6758 	if (ikev2_print_id(IKESA_DSTID(sa), idstr, sizeof(idstr)) == -1)
6759 		bzero(idstr, sizeof(idstr));
6760 
6761 	buflen = asprintf(&buf,
6762 	    "%s: %p rspi %s ispi %s %s->%s<%s>[%s] %s %c%s%s nexti %p pol %p\n",
6763 	    msg, sa,
6764 	    print_spi(sa->sa_hdr.sh_rspi, 8),
6765 	    print_spi(sa->sa_hdr.sh_ispi, 8),
6766 	    print_host((struct sockaddr *)&sa->sa_local.addr, NULL, 0),
6767 	    print_host((struct sockaddr *)&sa->sa_peer.addr, NULL, 0),
6768 	    idstr,
6769 	    sa->sa_addrpool ?
6770 	    print_host((struct sockaddr *)&sa->sa_addrpool->addr, NULL, 0) : "",
6771 	    print_map(sa->sa_state, ikev2_state_map),
6772 	    sa->sa_hdr.sh_initiator ? 'i' : 'r',
6773 	    sa->sa_natt ? " natt" : "",
6774 	    sa->sa_udpencap ? " udpecap" : "",
6775 	    sa->sa_nexti, sa->sa_policy);
6776 
6777 	if (buflen == -1 || buf == NULL)
6778 		return;
6779 
6780 	if (dolog) {
6781 		if (buflen > 1)
6782 			buf[buflen - 1] = '\0';
6783 		log_debug("%s", buf);
6784 	} else
6785 		proc_compose(&env->sc_ps, PROC_CONTROL, IMSG_CTL_SHOW_SA,
6786 		    buf, buflen + 1);
6787 	free(buf);
6788 }
6789 
6790 void
6791 ikev2_info_csa(struct iked *env, int dolog, const char *msg, struct iked_childsa *csa)
6792 {
6793 	char		*buf;
6794 	int		 buflen;
6795 
6796 	buflen = asprintf(&buf,
6797 	    "%s: %p %s %s %s %s -> %s (%s%s%s%s) B=%p P=%p @%p\n", msg, csa,
6798 	    print_map(csa->csa_saproto, ikev2_saproto_map),
6799 	    print_spi(csa->csa_spi.spi, csa->csa_spi.spi_size),
6800 	    csa->csa_dir == IPSP_DIRECTION_IN ? "in" : "out",
6801 	    print_host((struct sockaddr *)&csa->csa_local->addr, NULL, 0),
6802 	    print_host((struct sockaddr *)&csa->csa_peer->addr, NULL, 0),
6803 	    csa->csa_loaded ? "L" : "",
6804 	    csa->csa_rekey ? "R" : "",
6805 	    csa->csa_allocated ? "A" : "",
6806 	    csa->csa_persistent ? "P" : "",
6807 	    csa->csa_bundled,
6808 	    csa->csa_peersa,
6809 	    csa->csa_ikesa);
6810 
6811 	if (buflen == -1 || buf == NULL)
6812 		return;
6813 
6814 	if (dolog) {
6815 		if (buflen > 1)
6816 			buf[buflen - 1] = '\0';
6817 		log_debug("%s", buf);
6818 	} else
6819 		proc_compose(&env->sc_ps, PROC_CONTROL, IMSG_CTL_SHOW_SA,
6820 		    buf, buflen + 1);
6821 	free(buf);
6822 }
6823 
6824 void
6825 ikev2_info_flow(struct iked *env, int dolog, const char *msg, struct iked_flow *flow)
6826 {
6827 	char		*buf;
6828 	int		buflen;
6829 
6830 	buflen = asprintf(&buf,
6831 	    "%s: %p %s %s %s/%d -> %s/%d [%u]@%d (%s) @%p\n", msg, flow,
6832 	    print_map(flow->flow_saproto, ikev2_saproto_map),
6833 	    flow->flow_dir == IPSP_DIRECTION_IN ? "in" : "out",
6834 	    print_host((struct sockaddr *)&flow->flow_src.addr, NULL, 0),
6835 	    flow->flow_src.addr_mask,
6836 	    print_host((struct sockaddr *)&flow->flow_dst.addr, NULL, 0),
6837 	    flow->flow_dst.addr_mask,
6838 	    flow->flow_ipproto,
6839 	    flow->flow_rdomain,
6840 	    flow->flow_loaded ? "L" : "",
6841 	    flow->flow_ikesa);
6842 
6843 	if (buflen == -1 || buf == NULL)
6844 		return;
6845 
6846 	if (dolog) {
6847 		if (buflen > 1)
6848 			buf[buflen - 1] = '\0';
6849 		log_debug("%s", buf);
6850 	} else
6851 		proc_compose(&env->sc_ps, PROC_CONTROL, IMSG_CTL_SHOW_SA,
6852 		    buf, buflen + 1);
6853 	free(buf);
6854 }
6855 
6856 void
6857 ikev2_info(struct iked *env, int dolog)
6858 {
6859 	struct iked_sa			*sa;
6860 	struct iked_childsa		*csa, *ipcomp;
6861 	struct iked_flow		*flow;
6862 
6863 	log_debug("%s: called", __func__);
6864 
6865 	RB_FOREACH(sa, iked_sas, &env->sc_sas) {
6866 		ikev2_info_sa(env, dolog, "iked_sas", sa);
6867 		TAILQ_FOREACH(csa, &sa->sa_childsas, csa_entry) {
6868 			ikev2_info_csa(env, dolog, "  sa_childsas", csa);
6869 			if ((ipcomp = csa->csa_bundled) != NULL)
6870 				ikev2_info_csa(env, dolog, "             ",
6871 				    ipcomp);
6872 		}
6873 		TAILQ_FOREACH(flow, &sa->sa_flows, flow_entry) {
6874 			ikev2_info_flow(env, dolog, "  sa_flows", flow);
6875 		}
6876 	}
6877 	RB_FOREACH(csa, iked_activesas, &env->sc_activesas) {
6878 		ikev2_info_csa(env, dolog, "iked_activesas", csa);
6879 		if ((ipcomp = csa->csa_bundled) != NULL)
6880 			ikev2_info_csa(env, dolog, "              ", ipcomp);
6881 	}
6882 	RB_FOREACH(flow, iked_flows, &env->sc_activeflows) {
6883 		ikev2_info_flow(env, dolog, "iked_flows", flow);
6884 	}
6885 	RB_FOREACH(sa, iked_dstid_sas, &env->sc_dstid_sas) {
6886 		ikev2_info_sa(env, dolog, "iked_dstid_sas", sa);
6887 	}
6888 	if (dolog)
6889 		return;
6890 	/* Send empty reply to indicate end of information. */
6891 	proc_compose(&env->sc_ps, PROC_CONTROL, IMSG_CTL_SHOW_SA, NULL, 0);
6892 }
6893 
6894 const char *
6895 ikev2_ikesa_info(uint64_t spi, const char *msg)
6896 {
6897 	static char buf[1024];
6898 	const char *spistr;
6899 
6900 	spistr = print_spi(spi, 8);
6901 	if (msg)
6902 		snprintf(buf, sizeof(buf), "spi=%s: %s", spistr, msg);
6903 	else
6904 		snprintf(buf, sizeof(buf), "spi=%s: ", spistr);
6905 	return buf;
6906 }
6907 
6908 void
6909 ikev2_log_established(struct iked_sa *sa)
6910 {
6911 	char dstid[IKED_ID_SIZE], srcid[IKED_ID_SIZE];
6912 
6913 	if (ikev2_print_id(IKESA_DSTID(sa), dstid, sizeof(dstid)) == -1)
6914 		bzero(dstid, sizeof(dstid));
6915 	if (ikev2_print_id(IKESA_SRCID(sa), srcid, sizeof(srcid)) == -1)
6916 		bzero(srcid, sizeof(srcid));
6917 	log_info(
6918 	    "%sestablished peer %s[%s] local %s[%s]%s%s%s%s policy '%s'%s",
6919 	    SPI_SA(sa, NULL),
6920 	    print_host((struct sockaddr *)&sa->sa_peer.addr, NULL, 0), dstid,
6921 	    print_host((struct sockaddr *)&sa->sa_local.addr, NULL, 0), srcid,
6922 	    sa->sa_addrpool ? " assigned " : "",
6923 	    sa->sa_addrpool ?
6924 	    print_host((struct sockaddr *)&sa->sa_addrpool->addr, NULL, 0) : "",
6925 	    sa->sa_addrpool6 ? " assigned " : "",
6926 	    sa->sa_addrpool6 ?
6927 	    print_host((struct sockaddr *)&sa->sa_addrpool6->addr, NULL, 0) : "",
6928 	    sa->sa_policy ? sa->sa_policy->pol_name : "",
6929 	    sa->sa_hdr.sh_initiator ? " as initiator" : " as responder");
6930 }
6931 
6932 void
6933 ikev2_log_cert_info(const char *msg, struct iked_id *certid)
6934 {
6935 	X509		*cert = NULL;
6936 	BIO		*rawcert = NULL;
6937 
6938 	if (certid->id_type != IKEV2_CERT_X509_CERT ||
6939 	    certid->id_buf == NULL)
6940 		return;
6941 	if ((rawcert = BIO_new_mem_buf(ibuf_data(certid->id_buf),
6942 	    ibuf_length(certid->id_buf))) == NULL ||
6943 	    (cert = d2i_X509_bio(rawcert, NULL)) == NULL)
6944 		goto out;
6945 	ca_cert_info(msg, cert);
6946 out:
6947 	if (cert)
6948 		X509_free(cert);
6949 	if (rawcert)
6950 		BIO_free(rawcert);
6951 }
6952 
6953 void
6954 ikev2_log_proposal(struct iked_sa *sa, struct iked_proposals *proposals)
6955 {
6956 	struct iked_proposal	*prop;
6957 	struct iked_transform	*xform;
6958 	unsigned int		 i;
6959 	char			 lenstr[20];
6960 
6961 	TAILQ_FOREACH(prop, proposals, prop_entry) {
6962 		for (i = 0; i < prop->prop_nxforms; i++) {
6963 			xform = &prop->prop_xforms[i];
6964 			if (xform->xform_keylength)
6965 				snprintf(lenstr, sizeof(lenstr), "-%u",
6966 				    xform->xform_keylength);
6967 			else
6968 				lenstr[0] = '\0';
6969 			log_info("%s: %s #%u %s=%s%s",
6970 			    sa ? SPI_SA(sa, __func__) : __func__,
6971 			    print_map(prop->prop_protoid, ikev2_saproto_map),
6972 			    prop->prop_id,
6973 			    print_map(xform->xform_type, ikev2_xformtype_map),
6974 			    xform->xform_map ?
6975 			    print_map(xform->xform_id, xform->xform_map)
6976 			    : "UNKNOWN",
6977 			    lenstr);
6978 		}
6979 	}
6980 }
6981