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