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