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