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