xref: /openbsd/sbin/iked/ikev2_msg.c (revision 37e80bc6)
1 /*	$OpenBSD: ikev2_msg.c,v 1.93 2023/05/30 08:41:15 claudio 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 <arpa/inet.h>
27 
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <syslog.h>
31 #include <unistd.h>
32 #include <string.h>
33 #include <signal.h>
34 #include <endian.h>
35 #include <errno.h>
36 #include <err.h>
37 #include <event.h>
38 
39 #include <openssl/sha.h>
40 #include <openssl/evp.h>
41 
42 #include "iked.h"
43 #include "ikev2.h"
44 #include "eap.h"
45 #include "dh.h"
46 
47 void	 ikev1_recv(struct iked *, struct iked_message *);
48 void	 ikev2_msg_response_timeout(struct iked *, void *);
49 void	 ikev2_msg_retransmit_timeout(struct iked *, void *);
50 int	 ikev2_check_frag_oversize(struct iked_sa *, struct ibuf *);
51 int	 ikev2_send_encrypted_fragments(struct iked *, struct iked_sa *,
52 	    struct ibuf *, uint8_t, uint8_t, int);
53 int	 ikev2_msg_encrypt_prepare(struct iked_sa *, struct ikev2_payload *,
54 	    struct ibuf*, struct ibuf *, struct ike_header *, uint8_t, int);
55 
56 void
57 ikev2_msg_cb(int fd, short event, void *arg)
58 {
59 	struct iked_socket	*sock = arg;
60 	struct iked		*env = sock->sock_env;
61 	struct iked_message	 msg;
62 	struct ike_header	 hdr;
63 	uint32_t		 natt = 0x00000000;
64 	uint8_t			 buf[IKED_MSGBUF_MAX];
65 	ssize_t			 len;
66 	off_t			 off;
67 
68 	bzero(&msg, sizeof(msg));
69 	bzero(buf, sizeof(buf));
70 
71 	msg.msg_peerlen = sizeof(msg.msg_peer);
72 	msg.msg_locallen = sizeof(msg.msg_local);
73 	msg.msg_parent = &msg;
74 	memcpy(&msg.msg_local, &sock->sock_addr, sizeof(sock->sock_addr));
75 
76 	if ((len = recvfromto(fd, buf, sizeof(buf), 0,
77 	    (struct sockaddr *)&msg.msg_peer, &msg.msg_peerlen,
78 	    (struct sockaddr *)&msg.msg_local, &msg.msg_locallen)) <
79 	    (ssize_t)sizeof(natt))
80 		return;
81 
82 	if (socket_getport((struct sockaddr *)&msg.msg_local) ==
83 	    env->sc_nattport) {
84 		if (memcmp(&natt, buf, sizeof(natt)) != 0)
85 			return;
86 		msg.msg_natt = 1;
87 		off = sizeof(natt);
88 	} else
89 		off = 0;
90 
91 	if ((size_t)(len - off) <= sizeof(hdr))
92 		return;
93 	memcpy(&hdr, buf + off, sizeof(hdr));
94 
95 	if ((msg.msg_data = ibuf_new(buf + off, len - off)) == NULL)
96 		return;
97 
98 	TAILQ_INIT(&msg.msg_proposals);
99 	SIMPLEQ_INIT(&msg.msg_certreqs);
100 	msg.msg_fd = fd;
101 
102 	if (hdr.ike_version == IKEV1_VERSION)
103 		ikev1_recv(env, &msg);
104 	else
105 		ikev2_recv(env, &msg);
106 
107 	ikev2_msg_cleanup(env, &msg);
108 }
109 
110 void
111 ikev1_recv(struct iked *env, struct iked_message *msg)
112 {
113 	struct ike_header	*hdr;
114 
115 	if (ibuf_size(msg->msg_data) <= sizeof(*hdr)) {
116 		log_debug("%s: short message", __func__);
117 		return;
118 	}
119 
120 	hdr = (struct ike_header *)ibuf_data(msg->msg_data);
121 
122 	log_debug("%s: header ispi %s rspi %s"
123 	    " nextpayload %u version 0x%02x exchange %u flags 0x%02x"
124 	    " msgid %u length %u", __func__,
125 	    print_spi(betoh64(hdr->ike_ispi), 8),
126 	    print_spi(betoh64(hdr->ike_rspi), 8),
127 	    hdr->ike_nextpayload,
128 	    hdr->ike_version,
129 	    hdr->ike_exchange,
130 	    hdr->ike_flags,
131 	    betoh32(hdr->ike_msgid),
132 	    betoh32(hdr->ike_length));
133 
134 	log_debug("%s: IKEv1 not supported", __func__);
135 }
136 
137 struct ibuf *
138 ikev2_msg_init(struct iked *env, struct iked_message *msg,
139     struct sockaddr_storage *peer, socklen_t peerlen,
140     struct sockaddr_storage *local, socklen_t locallen, int response)
141 {
142 	bzero(msg, sizeof(*msg));
143 	memcpy(&msg->msg_peer, peer, peerlen);
144 	msg->msg_peerlen = peerlen;
145 	memcpy(&msg->msg_local, local, locallen);
146 	msg->msg_locallen = locallen;
147 	msg->msg_response = response ? 1 : 0;
148 	msg->msg_fd = -1;
149 	msg->msg_data = ibuf_static();
150 	msg->msg_e = 0;
151 	msg->msg_parent = msg;	/* has to be set */
152 	TAILQ_INIT(&msg->msg_proposals);
153 
154 	return (msg->msg_data);
155 }
156 
157 struct iked_message *
158 ikev2_msg_copy(struct iked *env, struct iked_message *msg)
159 {
160 	struct iked_message		*m = NULL;
161 	struct ibuf			*buf;
162 	size_t				 len;
163 	void				*ptr;
164 
165 	if (ibuf_size(msg->msg_data) < msg->msg_offset)
166 		return (NULL);
167 	len = ibuf_size(msg->msg_data) - msg->msg_offset;
168 
169 	if ((m = malloc(sizeof(*m))) == NULL)
170 		return (NULL);
171 
172 	if ((ptr = ibuf_seek(msg->msg_data, msg->msg_offset, len)) == NULL ||
173 	    (buf = ikev2_msg_init(env, m, &msg->msg_peer, msg->msg_peerlen,
174 	     &msg->msg_local, msg->msg_locallen, msg->msg_response)) == NULL ||
175 	    ibuf_add(buf, ptr, len)) {
176 		free(m);
177 		return (NULL);
178 	}
179 
180 	m->msg_fd = msg->msg_fd;
181 	m->msg_msgid = msg->msg_msgid;
182 	m->msg_offset = msg->msg_offset;
183 	m->msg_sa = msg->msg_sa;
184 
185 	return (m);
186 }
187 
188 void
189 ikev2_msg_cleanup(struct iked *env, struct iked_message *msg)
190 {
191 	struct iked_certreq	*cr;
192 
193 	if (msg == msg->msg_parent) {
194 		ibuf_free(msg->msg_nonce);
195 		ibuf_free(msg->msg_ke);
196 		ibuf_free(msg->msg_auth.id_buf);
197 		ibuf_free(msg->msg_peerid.id_buf);
198 		ibuf_free(msg->msg_localid.id_buf);
199 		ibuf_free(msg->msg_cert.id_buf);
200 		ibuf_free(msg->msg_cookie);
201 		ibuf_free(msg->msg_cookie2);
202 		ibuf_free(msg->msg_del_buf);
203 		free(msg->msg_eap.eam_user);
204 		free(msg->msg_cp_addr);
205 		free(msg->msg_cp_addr6);
206 		free(msg->msg_cp_dns);
207 
208 		msg->msg_nonce = NULL;
209 		msg->msg_ke = NULL;
210 		msg->msg_auth.id_buf = NULL;
211 		msg->msg_peerid.id_buf = NULL;
212 		msg->msg_localid.id_buf = NULL;
213 		msg->msg_cert.id_buf = NULL;
214 		msg->msg_cookie = NULL;
215 		msg->msg_cookie2 = NULL;
216 		msg->msg_del_buf = NULL;
217 		msg->msg_eap.eam_user = NULL;
218 		msg->msg_cp_addr = NULL;
219 		msg->msg_cp_addr6 = NULL;
220 		msg->msg_cp_dns = NULL;
221 
222 		config_free_proposals(&msg->msg_proposals, 0);
223 		while ((cr = SIMPLEQ_FIRST(&msg->msg_certreqs))) {
224 			ibuf_free(cr->cr_data);
225 			SIMPLEQ_REMOVE_HEAD(&msg->msg_certreqs, cr_entry);
226 			free(cr);
227 		}
228 	}
229 
230 	if (msg->msg_data != NULL) {
231 		ibuf_free(msg->msg_data);
232 		msg->msg_data = NULL;
233 	}
234 }
235 
236 int
237 ikev2_msg_valid_ike_sa(struct iked *env, struct ike_header *oldhdr,
238     struct iked_message *msg)
239 {
240 	if (msg->msg_sa != NULL && msg->msg_policy != NULL) {
241 		if (msg->msg_sa->sa_state == IKEV2_STATE_CLOSED)
242 			return (-1);
243 		/*
244 		 * Only permit informational requests from initiator
245 		 * on closing SAs (for DELETE).
246 		 */
247 		if (msg->msg_sa->sa_state == IKEV2_STATE_CLOSING) {
248 			if (((oldhdr->ike_flags &
249 			    (IKEV2_FLAG_INITIATOR|IKEV2_FLAG_RESPONSE)) ==
250 			    IKEV2_FLAG_INITIATOR) &&
251 			    (oldhdr->ike_exchange ==
252 			    IKEV2_EXCHANGE_INFORMATIONAL))
253 				return (0);
254 			return (-1);
255 		}
256 		return (0);
257 	}
258 
259 	/* Always fail */
260 	return (-1);
261 }
262 
263 int
264 ikev2_msg_send(struct iked *env, struct iked_message *msg)
265 {
266 	struct iked_sa		*sa = msg->msg_sa;
267 	struct ibuf		*buf = msg->msg_data;
268 	uint32_t		 natt = 0x00000000;
269 	int			 isnatt = 0;
270 	uint8_t			 exchange, flags;
271 	struct ike_header	*hdr;
272 	struct iked_message	*m;
273 
274 	if (buf == NULL || (hdr = ibuf_seek(msg->msg_data,
275 	    msg->msg_offset, sizeof(*hdr))) == NULL)
276 		return (-1);
277 
278 	isnatt = (msg->msg_natt || (sa && sa->sa_natt));
279 
280 	exchange = hdr->ike_exchange;
281 	flags = hdr->ike_flags;
282 	logit(exchange == IKEV2_EXCHANGE_INFORMATIONAL ?  LOG_DEBUG : LOG_INFO,
283 	    "%ssend %s %s %u peer %s local %s, %zu bytes%s",
284 	    SPI_IH(hdr),
285 	    print_map(exchange, ikev2_exchange_map),
286 	    (flags & IKEV2_FLAG_RESPONSE) ? "res" : "req",
287 	    betoh32(hdr->ike_msgid),
288 	    print_host((struct sockaddr *)&msg->msg_peer, NULL, 0),
289 	    print_host((struct sockaddr *)&msg->msg_local, NULL, 0),
290 	    ibuf_length(buf), isnatt ? ", NAT-T" : "");
291 
292 	if (isnatt) {
293 		struct ibuf *new;
294 		if ((new = ibuf_new(&natt, sizeof(natt))) == NULL) {
295 			log_debug("%s: failed to set NAT-T", __func__);
296 			return (-1);
297 		}
298 		if (ibuf_cat(new, buf) == -1) {
299 			ibuf_free(new);
300 			log_debug("%s: failed to set NAT-T", __func__);
301 			return (-1);
302 		}
303 		ibuf_free(buf);
304 		buf = msg->msg_data = new;
305 	}
306 
307 	if (sendtofrom(msg->msg_fd, ibuf_data(buf), ibuf_size(buf), 0,
308 	    (struct sockaddr *)&msg->msg_peer, msg->msg_peerlen,
309 	    (struct sockaddr *)&msg->msg_local, msg->msg_locallen) == -1) {
310 		log_warn("%s: sendtofrom", __func__);
311 		if (sa != NULL && errno == EADDRNOTAVAIL) {
312 			sa_state(env, sa, IKEV2_STATE_CLOSING);
313 			timer_del(env, &sa->sa_timer);
314 			timer_set(env, &sa->sa_timer,
315 			    ikev2_ike_sa_timeout, sa);
316 			timer_add(env, &sa->sa_timer,
317 			    IKED_IKE_SA_DELETE_TIMEOUT);
318 		}
319 		ikestat_inc(env, ikes_msg_send_failures);
320 	} else
321 		ikestat_inc(env, ikes_msg_sent);
322 
323 	if (sa == NULL)
324 		return (0);
325 
326 	if ((m = ikev2_msg_copy(env, msg)) == NULL) {
327 		log_debug("%s: failed to copy a message", __func__);
328 		return (-1);
329 	}
330 	m->msg_exchange = exchange;
331 
332 	if (flags & IKEV2_FLAG_RESPONSE) {
333 		if (ikev2_msg_enqueue(env, &sa->sa_responses, m,
334 		    IKED_RESPONSE_TIMEOUT) != 0) {
335 			ikev2_msg_cleanup(env, m);
336 			free(m);
337 			return (-1);
338 		}
339 	} else {
340 		if (ikev2_msg_enqueue(env, &sa->sa_requests, m,
341 		    IKED_RETRANSMIT_TIMEOUT) != 0) {
342 			ikev2_msg_cleanup(env, m);
343 			free(m);
344 			return (-1);
345 		}
346 	}
347 
348 	return (0);
349 }
350 
351 uint32_t
352 ikev2_msg_id(struct iked *env, struct iked_sa *sa)
353 {
354 	uint32_t		id = sa->sa_reqid;
355 
356 	if (++sa->sa_reqid == UINT32_MAX) {
357 		/* XXX we should close and renegotiate the connection now */
358 		log_debug("%s: IKEv2 message sequence overflow", __func__);
359 	}
360 	return (id);
361 }
362 
363 /*
364  * Calculate the final sizes of the IKEv2 header and the encrypted payload
365  * header.  This must be done before encryption to make sure the correct
366  * headers are authenticated.
367  */
368 int
369 ikev2_msg_encrypt_prepare(struct iked_sa *sa, struct ikev2_payload *pld,
370     struct ibuf *buf, struct ibuf *e, struct ike_header *hdr,
371     uint8_t firstpayload, int fragmentation)
372 {
373 	size_t	 len, ivlen, encrlen, integrlen, blocklen, pldlen, outlen;
374 
375 	if (sa == NULL ||
376 	    sa->sa_encr == NULL ||
377 	    sa->sa_integr == NULL) {
378 		log_debug("%s: invalid SA", __func__);
379 		return (-1);
380 	}
381 
382 	len = ibuf_size(e);
383 	blocklen = cipher_length(sa->sa_encr);
384 	integrlen = hash_length(sa->sa_integr);
385 	ivlen = cipher_ivlength(sa->sa_encr);
386 	encrlen = roundup(len + 1, blocklen);
387 	outlen = cipher_outlength(sa->sa_encr, encrlen);
388 	pldlen = ivlen + outlen + integrlen;
389 
390 	if (ikev2_next_payload(pld,
391 	    pldlen + (fragmentation ? sizeof(struct ikev2_frag_payload) : 0),
392 	    firstpayload) == -1)
393 		return (-1);
394 	if (ikev2_set_header(hdr, ibuf_size(buf) + pldlen - sizeof(*hdr)) == -1)
395 		return (-1);
396 
397 	return (0);
398 }
399 
400 struct ibuf *
401 ikev2_msg_encrypt(struct iked *env, struct iked_sa *sa, struct ibuf *src,
402     struct ibuf *aad)
403 {
404 	size_t			 len, encrlen, integrlen, blocklen,
405 				    outlen;
406 	uint8_t			*buf, pad = 0, *ptr;
407 	struct ibuf		*encr, *dst = NULL, *out = NULL;
408 
409 	buf = ibuf_data(src);
410 	len = ibuf_size(src);
411 
412 	log_debug("%s: decrypted length %zu", __func__, len);
413 	print_hex(buf, 0, len);
414 
415 	if (sa == NULL ||
416 	    sa->sa_encr == NULL ||
417 	    sa->sa_integr == NULL) {
418 		log_debug("%s: invalid SA", __func__);
419 		goto done;
420 	}
421 
422 	if (sa->sa_hdr.sh_initiator)
423 		encr = sa->sa_key_iencr;
424 	else
425 		encr = sa->sa_key_rencr;
426 
427 	blocklen = cipher_length(sa->sa_encr);
428 	integrlen = hash_length(sa->sa_integr);
429 	encrlen = roundup(len + sizeof(pad), blocklen);
430 	pad = encrlen - (len + sizeof(pad));
431 
432 	/*
433 	 * Pad the payload and encrypt it
434 	 */
435 	if (pad) {
436 		if ((ptr = ibuf_reserve(src, pad)) == NULL)
437 			goto done;
438 		arc4random_buf(ptr, pad);
439 	}
440 	if (ibuf_add(src, &pad, sizeof(pad)) != 0)
441 		goto done;
442 
443 	log_debug("%s: padded length %zu", __func__, ibuf_size(src));
444 	print_hex(ibuf_data(src), 0, ibuf_size(src));
445 
446 	cipher_setkey(sa->sa_encr, encr->buf, ibuf_length(encr));
447 	cipher_setiv(sa->sa_encr, NULL, 0);	/* XXX ivlen */
448 	if (cipher_init_encrypt(sa->sa_encr) == -1) {
449 		log_info("%s: error initiating cipher.", __func__);
450 		goto done;
451 	}
452 
453 	if ((dst = ibuf_dup(sa->sa_encr->encr_iv)) == NULL)
454 		goto done;
455 
456 	if ((out = ibuf_new(NULL,
457 	    cipher_outlength(sa->sa_encr, encrlen))) == NULL)
458 		goto done;
459 
460 	outlen = ibuf_size(out);
461 
462 	/* Add AAD for AEAD ciphers */
463 	if (sa->sa_integr->hash_isaead)
464 		cipher_aad(sa->sa_encr, ibuf_data(aad),
465 		    ibuf_length(aad), &outlen);
466 
467 	if (cipher_update(sa->sa_encr, ibuf_data(src), encrlen,
468 	    ibuf_data(out), &outlen) == -1) {
469 		log_info("%s: error updating cipher.", __func__);
470 		goto done;
471 	}
472 
473 	if (cipher_final(sa->sa_encr) == -1) {
474 		log_info("%s: encryption failed.", __func__);
475 		goto done;
476 	}
477 
478 	if (outlen && ibuf_add(dst, ibuf_data(out), outlen) != 0)
479 		goto done;
480 
481 	if ((ptr = ibuf_reserve(dst, integrlen)) == NULL)
482 		goto done;
483 	explicit_bzero(ptr, integrlen);
484 
485 	log_debug("%s: length %zu, padding %d, output length %zu",
486 	    __func__, len + sizeof(pad), pad, ibuf_size(dst));
487 	print_hex(ibuf_data(dst), 0, ibuf_size(dst));
488 
489 	ibuf_free(src);
490 	ibuf_free(out);
491 	return (dst);
492  done:
493 	ibuf_free(src);
494 	ibuf_free(out);
495 	ibuf_free(dst);
496 	return (NULL);
497 }
498 
499 int
500 ikev2_msg_integr(struct iked *env, struct iked_sa *sa, struct ibuf *src)
501 {
502 	int			 ret = -1;
503 	size_t			 integrlen, tmplen;
504 	struct ibuf		*integr, *tmp = NULL;
505 	uint8_t			*ptr;
506 
507 	log_debug("%s: message length %zu", __func__, ibuf_size(src));
508 	print_hex(ibuf_data(src), 0, ibuf_size(src));
509 
510 	if (sa == NULL ||
511 	    sa->sa_encr == NULL ||
512 	    sa->sa_integr == NULL) {
513 		log_debug("%s: invalid SA", __func__);
514 		return (-1);
515 	}
516 
517 	integrlen = hash_length(sa->sa_integr);
518 	log_debug("%s: integrity checksum length %zu", __func__,
519 	    integrlen);
520 
521 	/*
522 	 * Validate packet checksum
523 	 */
524 	if ((tmp = ibuf_new(NULL, hash_keylength(sa->sa_integr))) == NULL)
525 		goto done;
526 
527 	if (!sa->sa_integr->hash_isaead) {
528 		if (sa->sa_hdr.sh_initiator)
529 			integr = sa->sa_key_iauth;
530 		else
531 			integr = sa->sa_key_rauth;
532 
533 		hash_setkey(sa->sa_integr, ibuf_data(integr),
534 		    ibuf_size(integr));
535 		hash_init(sa->sa_integr);
536 		hash_update(sa->sa_integr, ibuf_data(src),
537 		    ibuf_size(src) - integrlen);
538 		hash_final(sa->sa_integr, ibuf_data(tmp), &tmplen);
539 
540 		if (tmplen != integrlen) {
541 			log_debug("%s: hash failure", __func__);
542 			goto done;
543 		}
544 	} else {
545 		/* Append AEAD tag */
546 		if (cipher_gettag(sa->sa_encr, ibuf_data(tmp), ibuf_size(tmp)))
547 			goto done;
548 	}
549 
550 	if ((ptr = ibuf_seek(src,
551 	    ibuf_size(src) - integrlen, integrlen)) == NULL)
552 		goto done;
553 	memcpy(ptr, ibuf_data(tmp), integrlen);
554 
555 	print_hex(ibuf_data(tmp), 0, ibuf_size(tmp));
556 
557 	ret = 0;
558  done:
559 	ibuf_free(tmp);
560 
561 	return (ret);
562 }
563 
564 struct ibuf *
565 ikev2_msg_decrypt(struct iked *env, struct iked_sa *sa,
566     struct ibuf *msg, struct ibuf *src)
567 {
568 	ssize_t			 ivlen, encrlen, integrlen, blocklen,
569 				    outlen, tmplen;
570 	uint8_t			 pad = 0, *ptr, *integrdata;
571 	struct ibuf		*integr, *encr, *tmp = NULL, *out = NULL;
572 	off_t			 ivoff, encroff, integroff;
573 
574 	if (sa == NULL ||
575 	    sa->sa_encr == NULL ||
576 	    sa->sa_integr == NULL) {
577 		log_debug("%s: invalid SA", __func__);
578 		print_hex(ibuf_data(src), 0, ibuf_size(src));
579 		goto done;
580 	}
581 
582 	if (!sa->sa_hdr.sh_initiator) {
583 		encr = sa->sa_key_iencr;
584 		integr = sa->sa_key_iauth;
585 	} else {
586 		encr = sa->sa_key_rencr;
587 		integr = sa->sa_key_rauth;
588 	}
589 
590 	blocklen = cipher_length(sa->sa_encr);
591 	ivlen = cipher_ivlength(sa->sa_encr);
592 	ivoff = 0;
593 	integrlen = hash_length(sa->sa_integr);
594 	integroff = ibuf_size(src) - integrlen;
595 	encroff = ivlen;
596 	encrlen = ibuf_size(src) - integrlen - ivlen;
597 
598 	if (encrlen < 0 || integroff < 0) {
599 		log_debug("%s: invalid integrity value", __func__);
600 		goto done;
601 	}
602 
603 	log_debug("%s: IV length %zd", __func__, ivlen);
604 	print_hex(ibuf_data(src), 0, ivlen);
605 	log_debug("%s: encrypted payload length %zd", __func__, encrlen);
606 	print_hex(ibuf_data(src), encroff, encrlen);
607 	log_debug("%s: integrity checksum length %zd", __func__, integrlen);
608 	print_hex(ibuf_data(src), integroff, integrlen);
609 
610 	/*
611 	 * Validate packet checksum
612 	 */
613 	if (!sa->sa_integr->hash_isaead) {
614 		if ((tmp = ibuf_new(NULL, hash_keylength(sa->sa_integr))) == NULL)
615 			goto done;
616 
617 		hash_setkey(sa->sa_integr, integr->buf, ibuf_length(integr));
618 		hash_init(sa->sa_integr);
619 		hash_update(sa->sa_integr, ibuf_data(msg),
620 		    ibuf_size(msg) - integrlen);
621 		hash_final(sa->sa_integr, tmp->buf, &tmplen);
622 
623 		integrdata = ibuf_seek(src, integroff, integrlen);
624 		if (integrdata == NULL)
625 			goto done;
626 		if (memcmp(tmp->buf, integrdata, integrlen) != 0) {
627 			log_debug("%s: integrity check failed", __func__);
628 			goto done;
629 		}
630 
631 		log_debug("%s: integrity check succeeded", __func__);
632 		print_hex(tmp->buf, 0, tmplen);
633 
634 		ibuf_free(tmp);
635 		tmp = NULL;
636 	}
637 
638 	/*
639 	 * Decrypt the payload and strip any padding
640 	 */
641 	if ((encrlen % blocklen) != 0) {
642 		log_debug("%s: unaligned encrypted payload", __func__);
643 		goto done;
644 	}
645 
646 	cipher_setkey(sa->sa_encr, encr->buf, ibuf_length(encr));
647 	cipher_setiv(sa->sa_encr, ibuf_data(src) + ivoff, ivlen);
648 	if (cipher_init_decrypt(sa->sa_encr) == -1) {
649 		log_info("%s: error initiating cipher.", __func__);
650 		goto done;
651 	}
652 
653 	/* Set AEAD tag */
654 	if (sa->sa_integr->hash_isaead) {
655 		integrdata = ibuf_seek(src, integroff, integrlen);
656 		if (integrdata == NULL)
657 			goto done;
658 		if (cipher_settag(sa->sa_encr, integrdata, integrlen)) {
659 			log_info("%s: failed to set tag.", __func__);
660 			goto done;
661 		}
662 	}
663 
664 	if ((out = ibuf_new(NULL, cipher_outlength(sa->sa_encr,
665 	    encrlen))) == NULL)
666 		goto done;
667 
668 	/*
669 	 * Add additional authenticated data for AEAD ciphers
670 	 */
671 	if (sa->sa_integr->hash_isaead) {
672 		log_debug("%s: AAD length %zu", __func__, ibuf_length(msg) - ibuf_length(src));
673 		print_hex(ibuf_data(msg), 0, ibuf_length(msg) - ibuf_length(src));
674 		cipher_aad(sa->sa_encr, ibuf_data(msg),
675 		    ibuf_length(msg) - ibuf_length(src), &outlen);
676 	}
677 
678 	if ((outlen = ibuf_length(out)) != 0) {
679 		if (cipher_update(sa->sa_encr, ibuf_data(src) + encroff,
680 		    encrlen, ibuf_data(out), &outlen) == -1) {
681 			log_info("%s: error updating cipher.", __func__);
682 			goto done;
683 		}
684 
685 		ptr = ibuf_seek(out, outlen - 1, 1);
686 		pad = *ptr;
687 	}
688 
689 	if (cipher_final(sa->sa_encr) == -1) {
690 		log_info("%s: decryption failed.", __func__);
691 		goto done;
692 	}
693 
694 	log_debug("%s: decrypted payload length %zd/%zd padding %d",
695 	    __func__, outlen, encrlen, pad);
696 	print_hex(ibuf_data(out), 0, ibuf_size(out));
697 
698 	/* Strip padding and padding length */
699 	if (ibuf_setsize(out, outlen - pad - 1) != 0)
700 		goto done;
701 
702 	ibuf_free(src);
703 	return (out);
704  done:
705 	ibuf_free(tmp);
706 	ibuf_free(out);
707 	ibuf_free(src);
708 	return (NULL);
709 }
710 
711 int
712 ikev2_check_frag_oversize(struct iked_sa *sa, struct ibuf *buf) {
713 	size_t		len = ibuf_length(buf);
714 	sa_family_t	sa_fam;
715 	size_t		max;
716 	size_t		ivlen, integrlen, blocklen;
717 
718 	if (sa == NULL ||
719 	    sa->sa_encr == NULL ||
720 	    sa->sa_integr == NULL) {
721 		log_debug("%s: invalid SA", __func__);
722 		return (-1);
723 	}
724 
725 	sa_fam = ((struct sockaddr *)&sa->sa_local.addr)->sa_family;
726 
727 	max = sa_fam == AF_INET ? IKEV2_MAXLEN_IPV4_FRAG
728 	    : IKEV2_MAXLEN_IPV6_FRAG;
729 
730 	blocklen = cipher_length(sa->sa_encr);
731 	ivlen = cipher_ivlength(sa->sa_encr);
732 	integrlen = hash_length(sa->sa_integr);
733 
734 	/* Estimated maximum packet size (with 0 < padding < blocklen) */
735 	return ((len + ivlen + blocklen + integrlen) >= max) && sa->sa_frag;
736 }
737 
738 int
739 ikev2_msg_send_encrypt(struct iked *env, struct iked_sa *sa, struct ibuf **ep,
740     uint8_t exchange, uint8_t firstpayload, int response)
741 {
742 	struct iked_message		 resp;
743 	struct ike_header		*hdr;
744 	struct ikev2_payload		*pld;
745 	struct ibuf			*buf, *e = *ep;
746 	int				 ret = -1;
747 
748 	/* Check if msg needs to be fragmented */
749 	if (ikev2_check_frag_oversize(sa, e)) {
750 		return ikev2_send_encrypted_fragments(env, sa, e, exchange,
751 		    firstpayload, response);
752 	}
753 
754 	if ((buf = ikev2_msg_init(env, &resp, &sa->sa_peer.addr,
755 	    sa->sa_peer.addr.ss_len, &sa->sa_local.addr,
756 	    sa->sa_local.addr.ss_len, response)) == NULL)
757 		goto done;
758 
759 	resp.msg_msgid = response ? sa->sa_msgid_current : ikev2_msg_id(env, sa);
760 
761 	/* IKE header */
762 	if ((hdr = ikev2_add_header(buf, sa, resp.msg_msgid, IKEV2_PAYLOAD_SK,
763 	    exchange, response ? IKEV2_FLAG_RESPONSE : 0)) == NULL)
764 		goto done;
765 
766 	if ((pld = ikev2_add_payload(buf)) == NULL)
767 		goto done;
768 
769 	if (ikev2_msg_encrypt_prepare(sa, pld, buf, e, hdr, firstpayload, 0) == -1)
770 		goto done;
771 
772 	/* Encrypt message and add as an E payload */
773 	if ((e = ikev2_msg_encrypt(env, sa, e, buf)) == NULL) {
774 		log_debug("%s: encryption failed", __func__);
775 		goto done;
776 	}
777 	if (ibuf_cat(buf, e) != 0)
778 		goto done;
779 
780 	/* Add integrity checksum (HMAC) */
781 	if (ikev2_msg_integr(env, sa, buf) != 0) {
782 		log_debug("%s: integrity checksum failed", __func__);
783 		goto done;
784 	}
785 
786 	resp.msg_data = buf;
787 	resp.msg_sa = sa;
788 	resp.msg_fd = sa->sa_fd;
789 	TAILQ_INIT(&resp.msg_proposals);
790 
791 	(void)ikev2_pld_parse(env, hdr, &resp, 0);
792 
793 	ret = ikev2_msg_send(env, &resp);
794 
795  done:
796 	/* e is cleaned up by the calling function */
797 	*ep = e;
798 	ikev2_msg_cleanup(env, &resp);
799 
800 	return (ret);
801 }
802 
803 int
804 ikev2_send_encrypted_fragments(struct iked *env, struct iked_sa *sa,
805     struct ibuf *in, uint8_t exchange, uint8_t firstpayload, int response) {
806 	struct iked_message		 resp;
807 	struct ibuf			*buf, *e = NULL;
808 	struct ike_header		*hdr;
809 	struct ikev2_payload		*pld;
810 	struct ikev2_frag_payload	*frag;
811 	sa_family_t			 sa_fam;
812 	size_t				 ivlen, integrlen, blocklen;
813 	size_t				 max_len, left,  offset=0;
814 	size_t				 frag_num = 1, frag_total;
815 	uint8_t				*data;
816 	uint32_t			 msgid;
817 	int				 ret = -1;
818 
819 	if (sa == NULL ||
820 	    sa->sa_encr == NULL ||
821 	    sa->sa_integr == NULL) {
822 		log_debug("%s: invalid SA", __func__);
823 		ikestat_inc(env, ikes_frag_send_failures);
824 		return ret;
825 	}
826 
827 	sa_fam = ((struct sockaddr *)&sa->sa_local.addr)->sa_family;
828 
829 	left = ibuf_length(in);
830 
831 	/* Calculate max allowed size of a fragments payload */
832 	blocklen = cipher_length(sa->sa_encr);
833 	ivlen = cipher_ivlength(sa->sa_encr);
834 	integrlen = hash_length(sa->sa_integr);
835 	max_len = (sa_fam == AF_INET ? IKEV2_MAXLEN_IPV4_FRAG
836 	    : IKEV2_MAXLEN_IPV6_FRAG)
837 	    - ivlen - blocklen - integrlen;
838 
839 	/* Total number of fragments to send */
840 	frag_total = (left / max_len) + 1;
841 
842 	msgid = response ? sa->sa_msgid_current : ikev2_msg_id(env, sa);
843 
844 	while (frag_num <= frag_total) {
845 		if ((buf = ikev2_msg_init(env, &resp, &sa->sa_peer.addr,
846 		    sa->sa_peer.addr.ss_len, &sa->sa_local.addr,
847 		    sa->sa_local.addr.ss_len, response)) == NULL)
848 			goto done;
849 
850 		resp.msg_msgid = msgid;
851 
852 		/* IKE header */
853 		if ((hdr = ikev2_add_header(buf, sa, resp.msg_msgid,
854 		    IKEV2_PAYLOAD_SKF, exchange, response ? IKEV2_FLAG_RESPONSE
855 		    : 0)) == NULL)
856 			goto done;
857 
858 		/* Payload header */
859 		if ((pld = ikev2_add_payload(buf)) == NULL)
860 			goto done;
861 
862 		/* Fragment header */
863 		if ((frag = ibuf_reserve(buf, sizeof(*frag))) == NULL) {
864 			log_debug("%s: failed to add SKF fragment header",
865 			    __func__);
866 			goto done;
867 		}
868 		frag->frag_num = htobe16(frag_num);
869 		frag->frag_total = htobe16(frag_total);
870 
871 		/* Encrypt message and add as an E payload */
872 		data = ibuf_seek(in, offset, 0);
873 		if ((e = ibuf_new(data, MINIMUM(left, max_len))) == NULL) {
874 			goto done;
875 		}
876 
877 		if (ikev2_msg_encrypt_prepare(sa, pld, buf, e, hdr,
878 		    firstpayload, 1) == -1)
879 			goto done;
880 
881 		if ((e = ikev2_msg_encrypt(env, sa, e, buf)) == NULL) {
882 			log_debug("%s: encryption failed", __func__);
883 			goto done;
884 		}
885 		if (ibuf_cat(buf, e) != 0)
886 			goto done;
887 
888 		/* Add integrity checksum (HMAC) */
889 		if (ikev2_msg_integr(env, sa, buf) != 0) {
890 			log_debug("%s: integrity checksum failed", __func__);
891 			goto done;
892 		}
893 
894 		log_debug("%s: Fragment %zu of %zu has size of %zu bytes.",
895 		    __func__, frag_num, frag_total,
896 		    ibuf_size(buf) - sizeof(*hdr));
897 		print_hex(ibuf_data(buf), 0,  ibuf_size(buf));
898 
899 		resp.msg_data = buf;
900 		resp.msg_sa = sa;
901 		resp.msg_fd = sa->sa_fd;
902 		TAILQ_INIT(&resp.msg_proposals);
903 
904 		if (ikev2_msg_send(env, &resp) == -1)
905 			goto done;
906 
907 		ikestat_inc(env, ikes_frag_sent);
908 
909 		offset += MINIMUM(left, max_len);
910 		left -= MINIMUM(left, max_len);
911 		frag_num++;
912 
913 		/* MUST be zero after first fragment */
914 		firstpayload = 0;
915 
916 		ikev2_msg_cleanup(env, &resp);
917 		ibuf_free(e);
918 		e = NULL;
919 	}
920 
921 	return 0;
922 done:
923 	ikev2_msg_cleanup(env, &resp);
924 	ibuf_free(e);
925 	ikestat_inc(env, ikes_frag_send_failures);
926 	return ret;
927 }
928 
929 struct ibuf *
930 ikev2_msg_auth(struct iked *env, struct iked_sa *sa, int response)
931 {
932 	struct ibuf		*authmsg = NULL, *nonce, *prfkey, *buf;
933 	uint8_t			*ptr;
934 	struct iked_id		*id;
935 	size_t			 tmplen;
936 
937 	/*
938 	 * Create the payload to be signed/MAC'ed for AUTH
939 	 */
940 
941 	if (!response) {
942 		if ((nonce = sa->sa_rnonce) == NULL ||
943 		    (sa->sa_iid.id_type == 0) ||
944 		    (prfkey = sa->sa_key_iprf) == NULL ||
945 		    (buf = sa->sa_1stmsg) == NULL)
946 			return (NULL);
947 		id = &sa->sa_iid;
948 	} else {
949 		if ((nonce = sa->sa_inonce) == NULL ||
950 		    (sa->sa_rid.id_type == 0) ||
951 		    (prfkey = sa->sa_key_rprf) == NULL ||
952 		    (buf = sa->sa_2ndmsg) == NULL)
953 			return (NULL);
954 		id = &sa->sa_rid;
955 	}
956 
957 	if ((authmsg = ibuf_dup(buf)) == NULL)
958 		return (NULL);
959 	if (ibuf_cat(authmsg, nonce) != 0)
960 		goto fail;
961 
962 	if ((hash_setkey(sa->sa_prf, ibuf_data(prfkey),
963 	    ibuf_size(prfkey))) == NULL)
964 		goto fail;
965 
966 	/* require non-truncating hash */
967 	if (hash_keylength(sa->sa_prf) != hash_length(sa->sa_prf))
968 		goto fail;
969 
970 	if ((ptr = ibuf_reserve(authmsg, hash_keylength(sa->sa_prf))) == NULL)
971 		goto fail;
972 
973 	hash_init(sa->sa_prf);
974 	hash_update(sa->sa_prf, ibuf_data(id->id_buf), ibuf_size(id->id_buf));
975 	hash_final(sa->sa_prf, ptr, &tmplen);
976 
977 	if (tmplen != hash_length(sa->sa_prf))
978 		goto fail;
979 
980 	log_debug("%s: %s auth data length %zu",
981 	    __func__, response ? "responder" : "initiator",
982 	    ibuf_size(authmsg));
983 	print_hex(ibuf_data(authmsg), 0, ibuf_size(authmsg));
984 
985 	return (authmsg);
986 
987  fail:
988 	ibuf_free(authmsg);
989 	return (NULL);
990 }
991 
992 int
993 ikev2_msg_authverify(struct iked *env, struct iked_sa *sa,
994     struct iked_auth *auth, uint8_t *buf, size_t len, struct ibuf *authmsg)
995 {
996 	uint8_t				*key, *psk = NULL;
997 	ssize_t				 keylen;
998 	struct iked_id			*id;
999 	struct iked_dsa			*dsa = NULL;
1000 	int				 ret = -1;
1001 	uint8_t				 keytype;
1002 
1003 	if (sa->sa_hdr.sh_initiator)
1004 		id = &sa->sa_rcert;
1005 	else
1006 		id = &sa->sa_icert;
1007 
1008 	if ((dsa = dsa_verify_new(auth->auth_method, sa->sa_prf)) == NULL) {
1009 		log_debug("%s: invalid auth method", __func__);
1010 		return (-1);
1011 	}
1012 
1013 	switch (auth->auth_method) {
1014 	case IKEV2_AUTH_SHARED_KEY_MIC:
1015 		if (!auth->auth_length) {
1016 			log_debug("%s: no pre-shared key found", __func__);
1017 			goto done;
1018 		}
1019 		if ((keylen = ikev2_psk(sa, auth->auth_data,
1020 		    auth->auth_length, &psk)) == -1) {
1021 			log_debug("%s: failed to get PSK", __func__);
1022 			goto done;
1023 		}
1024 		key = psk;
1025 		keytype = 0;
1026 		break;
1027 	default:
1028 		if (!id->id_type || !ibuf_length(id->id_buf)) {
1029 			log_debug("%s: no cert found", __func__);
1030 			goto done;
1031 		}
1032 		key = ibuf_data(id->id_buf);
1033 		keylen = ibuf_size(id->id_buf);
1034 		keytype = id->id_type;
1035 		break;
1036 	}
1037 
1038 	log_debug("%s: method %s keylen %zd type %s", __func__,
1039 	    print_map(auth->auth_method, ikev2_auth_map), keylen,
1040 	    print_map(id->id_type, ikev2_cert_map));
1041 
1042 	if (dsa_setkey(dsa, key, keylen, keytype) == NULL ||
1043 	    dsa_init(dsa, buf, len) != 0 ||
1044 	    dsa_update(dsa, ibuf_data(authmsg), ibuf_size(authmsg))) {
1045 		log_debug("%s: failed to compute digital signature", __func__);
1046 		goto done;
1047 	}
1048 
1049 	if ((ret = dsa_verify_final(dsa, buf, len)) == 0) {
1050 		log_debug("%s: authentication successful", __func__);
1051 		sa_state(env, sa, IKEV2_STATE_AUTH_SUCCESS);
1052 		sa_stateflags(sa, IKED_REQ_AUTHVALID);
1053 	} else {
1054 		log_debug("%s: authentication failed", __func__);
1055 		sa_state(env, sa, IKEV2_STATE_AUTH_REQUEST);
1056 	}
1057 
1058  done:
1059 	free(psk);
1060 	dsa_free(dsa);
1061 
1062 	return (ret);
1063 }
1064 
1065 int
1066 ikev2_msg_authsign(struct iked *env, struct iked_sa *sa,
1067     struct iked_auth *auth, struct ibuf *authmsg)
1068 {
1069 	uint8_t				*key, *psk = NULL;
1070 	ssize_t				 keylen, siglen;
1071 	struct iked_hash		*prf = sa->sa_prf;
1072 	struct iked_id			*id;
1073 	struct iked_dsa			*dsa = NULL;
1074 	struct ibuf			*buf;
1075 	int				 ret = -1;
1076 	uint8_t			 keytype;
1077 
1078 	if (sa->sa_hdr.sh_initiator)
1079 		id = &sa->sa_icert;
1080 	else
1081 		id = &sa->sa_rcert;
1082 
1083 	if ((dsa = dsa_sign_new(auth->auth_method, prf)) == NULL) {
1084 		log_debug("%s: invalid auth method", __func__);
1085 		return (-1);
1086 	}
1087 
1088 	switch (auth->auth_method) {
1089 	case IKEV2_AUTH_SHARED_KEY_MIC:
1090 		if (!auth->auth_length) {
1091 			log_debug("%s: no pre-shared key found", __func__);
1092 			goto done;
1093 		}
1094 		if ((keylen = ikev2_psk(sa, auth->auth_data,
1095 		    auth->auth_length, &psk)) == -1) {
1096 			log_debug("%s: failed to get PSK", __func__);
1097 			goto done;
1098 		}
1099 		key = psk;
1100 		keytype = 0;
1101 		break;
1102 	default:
1103 		if (id == NULL) {
1104 			log_debug("%s: no cert found", __func__);
1105 			goto done;
1106 		}
1107 		key = ibuf_data(id->id_buf);
1108 		keylen = ibuf_size(id->id_buf);
1109 		keytype = id->id_type;
1110 		break;
1111 	}
1112 
1113 	if (dsa_setkey(dsa, key, keylen, keytype) == NULL ||
1114 	    dsa_init(dsa, NULL, 0) != 0 ||
1115 	    dsa_update(dsa, ibuf_data(authmsg), ibuf_size(authmsg))) {
1116 		log_debug("%s: failed to compute digital signature", __func__);
1117 		goto done;
1118 	}
1119 
1120 	ibuf_free(sa->sa_localauth.id_buf);
1121 	sa->sa_localauth.id_buf = NULL;
1122 
1123 	if ((buf = ibuf_new(NULL, dsa_length(dsa))) == NULL) {
1124 		log_debug("%s: failed to get auth buffer", __func__);
1125 		goto done;
1126 	}
1127 
1128 	if ((siglen = dsa_sign_final(dsa,
1129 	    ibuf_data(buf), ibuf_size(buf))) < 0) {
1130 		log_debug("%s: failed to create auth signature", __func__);
1131 		ibuf_free(buf);
1132 		goto done;
1133 	}
1134 
1135 	if (ibuf_setsize(buf, siglen) < 0) {
1136 		log_debug("%s: failed to set auth signature size to %zd",
1137 		    __func__, siglen);
1138 		ibuf_free(buf);
1139 		goto done;
1140 	}
1141 
1142 	sa->sa_localauth.id_type = auth->auth_method;
1143 	sa->sa_localauth.id_buf = buf;
1144 
1145 	ret = 0;
1146  done:
1147 	free(psk);
1148 	dsa_free(dsa);
1149 
1150 	return (ret);
1151 }
1152 
1153 int
1154 ikev2_msg_frompeer(struct iked_message *msg)
1155 {
1156 	struct iked_sa		*sa = msg->msg_sa;
1157 	struct ike_header	*hdr;
1158 
1159 	msg = msg->msg_parent;
1160 
1161 	if (sa == NULL ||
1162 	    (hdr = ibuf_seek(msg->msg_data, 0, sizeof(*hdr))) == NULL)
1163 		return (0);
1164 
1165 	if (!sa->sa_hdr.sh_initiator &&
1166 	    (hdr->ike_flags & IKEV2_FLAG_INITIATOR))
1167 		return (1);
1168 	else if (sa->sa_hdr.sh_initiator &&
1169 	    (hdr->ike_flags & IKEV2_FLAG_INITIATOR) == 0)
1170 		return (1);
1171 
1172 	return (0);
1173 }
1174 
1175 struct iked_socket *
1176 ikev2_msg_getsocket(struct iked *env, int af, int natt)
1177 {
1178 	switch (af) {
1179 	case AF_INET:
1180 		return (env->sc_sock4[natt ? 1 : 0]);
1181 	case AF_INET6:
1182 		return (env->sc_sock6[natt ? 1 : 0]);
1183 	}
1184 
1185 	log_debug("%s: af socket %d not available", __func__, af);
1186 	return (NULL);
1187 }
1188 
1189 int
1190 ikev2_msg_enqueue(struct iked *env, struct iked_msgqueue *queue,
1191     struct iked_message *msg, int timeout)
1192 {
1193 	struct iked_msg_retransmit *mr;
1194 
1195 	if ((mr = ikev2_msg_lookup(env, queue, msg, msg->msg_exchange)) ==
1196 	    NULL) {
1197 		if ((mr = calloc(1, sizeof(*mr))) == NULL)
1198 			return (-1);
1199 		TAILQ_INIT(&mr->mrt_frags);
1200 		mr->mrt_tries = 0;
1201 
1202 		timer_set(env, &mr->mrt_timer, msg->msg_response ?
1203 		    ikev2_msg_response_timeout : ikev2_msg_retransmit_timeout,
1204 		    mr);
1205 		timer_add(env, &mr->mrt_timer, timeout);
1206 
1207 		TAILQ_INSERT_TAIL(queue, mr, mrt_entry);
1208 	}
1209 
1210 	TAILQ_INSERT_TAIL(&mr->mrt_frags, msg, msg_entry);
1211 
1212 	return 0;
1213 }
1214 
1215 void
1216 ikev2_msg_prevail(struct iked *env, struct iked_msgqueue *queue,
1217     struct iked_message *msg)
1218 {
1219 	struct iked_msg_retransmit	*mr, *mrtmp;
1220 
1221 	TAILQ_FOREACH_SAFE(mr, queue, mrt_entry, mrtmp) {
1222 		if (TAILQ_FIRST(&mr->mrt_frags)->msg_msgid < msg->msg_msgid)
1223 			ikev2_msg_dispose(env, queue, mr);
1224 	}
1225 }
1226 
1227 void
1228 ikev2_msg_dispose(struct iked *env, struct iked_msgqueue *queue,
1229     struct iked_msg_retransmit *mr)
1230 {
1231 	struct iked_message	*m;
1232 
1233 	while ((m = TAILQ_FIRST(&mr->mrt_frags)) != NULL) {
1234 		TAILQ_REMOVE(&mr->mrt_frags, m, msg_entry);
1235 		ikev2_msg_cleanup(env, m);
1236 		free(m);
1237 	}
1238 
1239 	timer_del(env, &mr->mrt_timer);
1240 	TAILQ_REMOVE(queue, mr, mrt_entry);
1241 	free(mr);
1242 }
1243 
1244 void
1245 ikev2_msg_flushqueue(struct iked *env, struct iked_msgqueue *queue)
1246 {
1247 	struct iked_msg_retransmit	*mr = NULL;
1248 
1249 	while ((mr = TAILQ_FIRST(queue)) != NULL)
1250 		ikev2_msg_dispose(env, queue, mr);
1251 }
1252 
1253 struct iked_msg_retransmit *
1254 ikev2_msg_lookup(struct iked *env, struct iked_msgqueue *queue,
1255     struct iked_message *msg, uint8_t exchange)
1256 {
1257 	struct iked_msg_retransmit	*mr = NULL;
1258 
1259 	TAILQ_FOREACH(mr, queue, mrt_entry) {
1260 		if (TAILQ_FIRST(&mr->mrt_frags)->msg_msgid ==
1261 		    msg->msg_msgid &&
1262 		    TAILQ_FIRST(&mr->mrt_frags)->msg_exchange == exchange)
1263 			break;
1264 	}
1265 
1266 	return (mr);
1267 }
1268 
1269 int
1270 ikev2_msg_retransmit_response(struct iked *env, struct iked_sa *sa,
1271     struct iked_message *msg, uint8_t exchange)
1272 {
1273 	struct iked_msg_retransmit	*mr = NULL;
1274 	struct iked_message	*m = NULL;
1275 
1276 	if ((mr = ikev2_msg_lookup(env, &sa->sa_responses, msg, exchange))
1277 	    == NULL)
1278 		return (-2);	/* not found */
1279 
1280 	TAILQ_FOREACH(m, &mr->mrt_frags, msg_entry) {
1281 		if (sendtofrom(m->msg_fd, ibuf_data(m->msg_data),
1282 		    ibuf_size(m->msg_data), 0,
1283 		    (struct sockaddr *)&m->msg_peer, m->msg_peerlen,
1284 		    (struct sockaddr *)&m->msg_local, m->msg_locallen) == -1) {
1285 			log_warn("%s: sendtofrom", __func__);
1286 			ikestat_inc(env, ikes_msg_send_failures);
1287 			return (-1);
1288 		}
1289 		log_info("%sretransmit %s res %u local %s peer %s",
1290 		    SPI_SA(sa, NULL),
1291 		    print_map(exchange, ikev2_exchange_map),
1292 		    m->msg_msgid,
1293 		    print_host((struct sockaddr *)&m->msg_local, NULL, 0),
1294 		    print_host((struct sockaddr *)&m->msg_peer, NULL, 0));
1295 	}
1296 
1297 	timer_add(env, &mr->mrt_timer, IKED_RESPONSE_TIMEOUT);
1298 	ikestat_inc(env, ikes_retransmit_response);
1299 	return (0);
1300 }
1301 
1302 void
1303 ikev2_msg_response_timeout(struct iked *env, void *arg)
1304 {
1305 	struct iked_msg_retransmit	*mr = arg;
1306 	struct iked_sa		*sa;
1307 
1308 	sa = TAILQ_FIRST(&mr->mrt_frags)->msg_sa;
1309 	ikev2_msg_dispose(env, &sa->sa_responses, mr);
1310 }
1311 
1312 void
1313 ikev2_msg_retransmit_timeout(struct iked *env, void *arg)
1314 {
1315 	struct iked_msg_retransmit *mr = arg;
1316 	struct iked_message	*msg = TAILQ_FIRST(&mr->mrt_frags);
1317 	struct iked_sa		*sa = msg->msg_sa;
1318 
1319 	if (mr->mrt_tries < IKED_RETRANSMIT_TRIES) {
1320 		TAILQ_FOREACH(msg, &mr->mrt_frags, msg_entry) {
1321 			if (sendtofrom(msg->msg_fd, ibuf_data(msg->msg_data),
1322 			    ibuf_size(msg->msg_data), 0,
1323 			    (struct sockaddr *)&msg->msg_peer, msg->msg_peerlen,
1324 			    (struct sockaddr *)&msg->msg_local,
1325 			    msg->msg_locallen) == -1) {
1326 				log_warn("%s: sendtofrom", __func__);
1327 				ikev2_ike_sa_setreason(sa, "retransmit failed");
1328 				sa_free(env, sa);
1329 				ikestat_inc(env, ikes_msg_send_failures);
1330 				return;
1331 			}
1332 			log_info("%sretransmit %d %s req %u peer %s "
1333 			    "local %s", SPI_SA(sa, NULL), mr->mrt_tries + 1,
1334 			    print_map(msg->msg_exchange, ikev2_exchange_map),
1335 			    msg->msg_msgid,
1336 			    print_host((struct sockaddr *)&msg->msg_peer, NULL, 0),
1337 			    print_host((struct sockaddr *)&msg->msg_local, NULL, 0));
1338 		}
1339 		/* Exponential timeout */
1340 		timer_add(env, &mr->mrt_timer,
1341 		    IKED_RETRANSMIT_TIMEOUT * (2 << (mr->mrt_tries++)));
1342 		ikestat_inc(env, ikes_retransmit_request);
1343 	} else {
1344 		log_debug("%s: retransmit limit reached for req %u",
1345 		    __func__, msg->msg_msgid);
1346 		ikev2_ike_sa_setreason(sa, "retransmit limit reached");
1347 		ikestat_inc(env, ikes_retransmit_limit);
1348 		sa_free(env, sa);
1349 	}
1350 }
1351