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