xref: /openbsd-src/sbin/iked/ikev2_msg.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
1 /*	$OpenBSD: ikev2_msg.c,v 1.20 2012/06/27 15:36:36 mikeb Exp $	*/
2 /*	$vantronix: ikev2.c,v 1.101 2010/06/03 07:57:33 reyk Exp $	*/
3 
4 /*
5  * Copyright (c) 2010 Reyk Floeter <reyk@vantronix.net>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/param.h>
21 #include <sys/types.h>
22 #include <sys/queue.h>
23 #include <sys/socket.h>
24 #include <sys/wait.h>
25 #include <sys/uio.h>
26 
27 #include <netinet/in.h>
28 #include <netinet/ip_ipsp.h>
29 #include <arpa/inet.h>
30 
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <unistd.h>
34 #include <string.h>
35 #include <getopt.h>
36 #include <signal.h>
37 #include <errno.h>
38 #include <err.h>
39 #include <pwd.h>
40 #include <event.h>
41 
42 #include <openssl/sha.h>
43 #include <openssl/evp.h>
44 
45 #include "iked.h"
46 #include "ikev2.h"
47 #include "eap.h"
48 #include "dh.h"
49 
50 void	 ikev2_msg_response_timeout(struct iked *, void *);
51 void	 ikev2_msg_retransmit_timeout(struct iked *, void *);
52 
53 void
54 ikev2_msg_cb(int fd, short event, void *arg)
55 {
56 	struct iked_socket	*sock = arg;
57 	struct iked		*env = sock->sock_env;
58 	struct iked_message	 msg;
59 	struct ike_header	 hdr;
60 	u_int32_t		 natt = 0x00000000;
61 	u_int8_t		 buf[IKED_MSGBUF_MAX];
62 	ssize_t			 len;
63 	off_t			 off;
64 	struct iovec		 iov[2];
65 
66 	bzero(&msg, sizeof(msg));
67 	bzero(buf, sizeof(buf));
68 
69 	msg.msg_peerlen = sizeof(msg.msg_peer);
70 	msg.msg_locallen = sizeof(msg.msg_local);
71 	msg.msg_parent = &msg;
72 	memcpy(&msg.msg_local, &sock->sock_addr, sizeof(sock->sock_addr));
73 
74 	if ((len = recvfromto(fd, buf, sizeof(buf), 0,
75 	    (struct sockaddr *)&msg.msg_peer, &msg.msg_peerlen,
76 	    (struct sockaddr *)&msg.msg_local, &msg.msg_locallen)) <
77 	    (ssize_t)sizeof(natt))
78 		return;
79 
80 	if (socket_getport(&msg.msg_local) == IKED_NATT_PORT) {
81 		if (bcmp(&natt, buf, sizeof(natt)) != 0)
82 			return;
83 		msg.msg_natt = 1;
84 		off = sizeof(natt);
85 	} else
86 		off = 0;
87 
88 	if ((size_t)(len - off) <= sizeof(hdr))
89 		return;
90 	memcpy(&hdr, buf + off, sizeof(hdr));
91 
92 	if ((msg.msg_data = ibuf_new(buf + off, len - off)) == NULL)
93 		return;
94 
95 	if (hdr.ike_version == IKEV1_VERSION) {
96 		iov[0].iov_base = &msg;
97 		iov[0].iov_len = sizeof(msg);
98 		iov[1].iov_base = buf;
99 		iov[1].iov_len = len;
100 
101 		proc_composev_imsg(env, PROC_IKEV1, IMSG_IKE_MESSAGE, -1,
102 		    iov, 2);
103 		goto done;
104 	}
105 	TAILQ_INIT(&msg.msg_proposals);
106 
107 	msg.msg_fd = fd;
108 	ikev2_recv(env, &msg);
109 
110  done:
111 	ikev2_msg_cleanup(env, &msg);
112 }
113 
114 struct ibuf *
115 ikev2_msg_init(struct iked *env, struct iked_message *msg,
116     struct sockaddr_storage *peer, socklen_t peerlen,
117     struct sockaddr_storage *local, socklen_t locallen, int response)
118 {
119 	bzero(msg, sizeof(*msg));
120 	memcpy(&msg->msg_peer, peer, peerlen);
121 	msg->msg_peerlen = peerlen;
122 	memcpy(&msg->msg_local, local, locallen);
123 	msg->msg_locallen = locallen;
124 	msg->msg_response = response ? 1 : 0;
125 	msg->msg_fd = -1;
126 	msg->msg_data = ibuf_static();
127 	msg->msg_e = 0;
128 	msg->msg_parent = msg;	/* has to be set */
129 	TAILQ_INIT(&msg->msg_proposals);
130 
131 	return (msg->msg_data);
132 }
133 
134 struct iked_message *
135 ikev2_msg_copy(struct iked *env, struct iked_message *msg)
136 {
137 	struct iked_message		*m = NULL;
138 	struct ibuf			*buf;
139 
140 	if ((m = malloc(sizeof(*m))) == NULL ||
141 	    (buf = ikev2_msg_init(env, m, &msg->msg_peer, msg->msg_peerlen,
142 	     &msg->msg_local, msg->msg_locallen, msg->msg_response)) == NULL ||
143 	    ibuf_add(buf, ibuf_data(msg->msg_data), ibuf_size(msg->msg_data)))
144 		return (NULL);
145 
146 	m->msg_fd = msg->msg_fd;
147 	m->msg_msgid = msg->msg_msgid;
148 	m->msg_offset = msg->msg_offset;
149 	m->msg_sa = msg->msg_sa;
150 
151 	return (m);
152 }
153 
154 void
155 ikev2_msg_cleanup(struct iked *env, struct iked_message *msg)
156 {
157 	if (msg == msg->msg_parent) {
158 		ibuf_release(msg->msg_nonce);
159 		ibuf_release(msg->msg_ke);
160 		ibuf_release(msg->msg_auth.id_buf);
161 		ibuf_release(msg->msg_id.id_buf);
162 		ibuf_release(msg->msg_cert.id_buf);
163 
164 		config_free_proposals(&msg->msg_proposals, 0);
165 	}
166 
167 	if (msg->msg_data != NULL) {
168 		ibuf_release(msg->msg_data);
169 		msg->msg_data = NULL;
170 	}
171 }
172 
173 int
174 ikev2_msg_valid_ike_sa(struct iked *env, struct ike_header *oldhdr,
175     struct iked_message *msg)
176 {
177 #if 0
178 	/* XXX Disabled, see comment below */
179 	struct iked_message		 resp;
180 	struct ike_header		*hdr;
181 	struct ikev2_payload		*pld;
182 	struct ikev2_notify		*n;
183 	struct ibuf			*buf;
184 	struct iked_sa			 sa;
185 #endif
186 
187 	if (msg->msg_sa != NULL && msg->msg_policy != NULL)
188 		return (0);
189 
190 #if 0
191 	/*
192 	 * XXX Sending INVALID_IKE_SPIs notifications is disabled
193 	 * XXX because it is not mandatory and ignored by most
194 	 * XXX implementations.  We might want to enable it in
195 	 * XXX combination with a rate-limitation to avoid DoS situations.
196 	 */
197 
198 	/* Fail without error message */
199 	if (msg->msg_response || msg->msg_policy == NULL)
200 		return (-1);
201 
202 	/* Invalid IKE SA, return notification */
203 	if ((buf = ikev2_msg_init(env, &resp,
204 	    &msg->msg_peer, msg->msg_peerlen,
205 	    &msg->msg_local, msg->msg_locallen, 1)) == NULL)
206 		goto done;
207 
208 	resp.msg_fd = msg->msg_fd;
209 
210 	bzero(&sa, sizeof(sa));
211 	if ((oldhdr->ike_flags & IKEV2_FLAG_INITIATOR) == 0)
212 		sa.sa_hdr.sh_initiator = 1;
213 	sa.sa_hdr.sh_ispi = betoh64(oldhdr->ike_ispi);
214 	sa.sa_hdr.sh_rspi = betoh64(oldhdr->ike_rspi);
215 
216 	resp.msg_msgid = betoh32(oldhdr->ike_msgid);
217 
218 	/* IKE header */
219 	if ((hdr = ikev2_add_header(buf, &sa, resp.msg_msgid,
220 	    IKEV2_PAYLOAD_NOTIFY, IKEV2_EXCHANGE_INFORMATIONAL,
221 	    IKEV2_FLAG_RESPONSE)) == NULL)
222 		goto done;
223 
224 	/* SA payload */
225 	if ((pld = ikev2_add_payload(buf)) == NULL)
226 		goto done;
227 	if ((n = ibuf_advance(buf, sizeof(*n))) == NULL)
228 		goto done;
229 	n->n_protoid = IKEV2_SAPROTO_IKE;
230 	n->n_spisize = 0;
231 	n->n_type = htobe16(IKEV2_N_INVALID_IKE_SPI);
232 
233 	if (ikev2_next_payload(pld, sizeof(*n), IKEV2_PAYLOAD_NONE) == -1)
234 		goto done;
235 
236 	if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
237 		goto done;
238 
239 	(void)ikev2_pld_parse(env, hdr, &resp, 0);
240 	(void)ikev2_msg_send(env, &resp);
241 
242  done:
243 	ikev2_msg_cleanup(env, &resp);
244 #endif
245 
246 	/* Always fail */
247 	return (-1);
248 }
249 
250 int
251 ikev2_msg_send(struct iked *env, struct iked_message *msg)
252 {
253 	struct iked_sa		*sa = msg->msg_sa;
254 	struct ibuf		*buf = msg->msg_data;
255 	u_int32_t		 natt = 0x00000000;
256 	struct ike_header	*hdr;
257 	struct iked_message	*m;
258 
259 	if (buf == NULL || (hdr = ibuf_seek(msg->msg_data,
260 	    msg->msg_offset, sizeof(*hdr))) == NULL)
261 		return (-1);
262 
263 	log_info("%s: %s from %s to %s, %ld bytes", __func__,
264 	    print_map(hdr->ike_exchange, ikev2_exchange_map),
265 	    print_host(&msg->msg_local, NULL, 0),
266 	    print_host(&msg->msg_peer, NULL, 0),
267 	    ibuf_length(buf));
268 
269 	if (msg->msg_natt || (msg->msg_sa && msg->msg_sa->sa_natt)) {
270 		if (ibuf_prepend(buf, &natt, sizeof(natt)) == -1) {
271 			log_debug("%s: failed to set NAT-T", __func__);
272 			return (-1);
273 		}
274 		msg->msg_offset += sizeof(natt);
275 	}
276 
277 	if ((sendto(msg->msg_fd, ibuf_data(buf), ibuf_size(buf), 0,
278 	    (struct sockaddr *)&msg->msg_peer, msg->msg_peerlen)) == -1) {
279 		log_warn("%s: sendto", __func__);
280 		return (-1);
281 	}
282 
283 	if (!sa)
284 		return (0);
285 
286 	if ((m = ikev2_msg_copy(env, msg)) == NULL) {
287 		log_debug("%s: failed to copy a message", __func__);
288 		return (-1);
289 	}
290 	m->msg_exchange = hdr->ike_exchange;
291 
292 	if (hdr->ike_flags & IKEV2_FLAG_RESPONSE) {
293 		TAILQ_INSERT_TAIL(&sa->sa_responses, m, msg_entry);
294 		timer_initialize(env, &m->msg_timer,
295 		    ikev2_msg_response_timeout, m);
296 		timer_register(env, &m->msg_timer, IKED_RESPONSE_TIMEOUT);
297 	} else {
298 		TAILQ_INSERT_TAIL(&sa->sa_requests, m, msg_entry);
299 		timer_initialize(env, &m->msg_timer,
300 		    ikev2_msg_retransmit_timeout, m);
301 		timer_register(env, &m->msg_timer, IKED_RETRANSMIT_TIMEOUT);
302 	}
303 
304 	return (0);
305 }
306 
307 u_int32_t
308 ikev2_msg_id(struct iked *env, struct iked_sa *sa)
309 {
310 	u_int32_t		id = sa->sa_reqid;
311 
312 	if (++sa->sa_reqid == UINT32_MAX) {
313 		/* XXX we should close and renegotiate the connection now */
314 		log_debug("%s: IKEv2 message sequence overflow", __func__);
315 	}
316 	return (id);
317 }
318 
319 struct ibuf *
320 ikev2_msg_encrypt(struct iked *env, struct iked_sa *sa, struct ibuf *src)
321 {
322 	size_t			 len, ivlen, encrlen, integrlen, blocklen,
323 				    outlen;
324 	u_int8_t		*buf, pad = 0, *ptr;
325 	struct ibuf		*integr, *encr, *dst = NULL, *out = NULL;
326 
327 	buf = ibuf_data(src);
328 	len = ibuf_size(src);
329 
330 	log_debug("%s: decrypted length %d", __func__, len);
331 	print_hex(buf, 0, len);
332 
333 	if (sa == NULL ||
334 	    sa->sa_encr == NULL ||
335 	    sa->sa_integr == NULL) {
336 		log_debug("%s: invalid SA", __func__);
337 		goto done;
338 	}
339 
340 	if (sa->sa_hdr.sh_initiator) {
341 		encr = sa->sa_key_iencr;
342 		integr = sa->sa_key_iauth;
343 	} else {
344 		encr = sa->sa_key_rencr;
345 		integr = sa->sa_key_rauth;
346 	}
347 
348 	blocklen = cipher_length(sa->sa_encr);
349 	ivlen = cipher_ivlength(sa->sa_encr);
350 	integrlen = hash_length(sa->sa_integr);
351 	encrlen = roundup(len + sizeof(pad), blocklen);
352 	pad = encrlen - (len + sizeof(pad));
353 
354 	/*
355 	 * Pad the payload and encrypt it
356 	 */
357 	if (pad) {
358 		if ((ptr = ibuf_advance(src, pad)) == NULL)
359 			goto done;
360 		arc4random_buf(ptr, pad);
361 	}
362 	if (ibuf_add(src, &pad, sizeof(pad)) != 0)
363 		goto done;
364 
365 	log_debug("%s: padded length %d", __func__, ibuf_size(src));
366 	print_hex(ibuf_data(src), 0, ibuf_size(src));
367 
368 	cipher_setkey(sa->sa_encr, encr->buf, ibuf_length(encr));
369 	cipher_setiv(sa->sa_encr, NULL, 0);	/* new IV */
370 	cipher_init_encrypt(sa->sa_encr);
371 
372 	if ((dst = ibuf_dup(sa->sa_encr->encr_iv)) == NULL)
373 		goto done;
374 
375 	if ((out = ibuf_new(NULL,
376 	    cipher_outlength(sa->sa_encr, encrlen))) == NULL)
377 		goto done;
378 
379 	outlen = ibuf_size(out);
380 	cipher_update(sa->sa_encr,
381 	    ibuf_data(src), encrlen, ibuf_data(out), &outlen);
382 
383 	if (outlen && ibuf_add(dst, ibuf_data(out), outlen) != 0)
384 		goto done;
385 
386 	if ((ptr = ibuf_advance(dst, integrlen)) == NULL)
387 		goto done;
388 	bzero(ptr, integrlen);
389 
390 	log_debug("%s: length %d, padding %d, output length %d",
391 	    __func__, len + sizeof(pad), pad, ibuf_size(dst));
392 	print_hex(ibuf_data(dst), 0, ibuf_size(dst));
393 
394 	ibuf_release(src);
395 	ibuf_release(out);
396 	return (dst);
397  done:
398 	ibuf_release(src);
399 	ibuf_release(out);
400 	ibuf_release(dst);
401 	return (NULL);
402 }
403 
404 int
405 ikev2_msg_integr(struct iked *env, struct iked_sa *sa, struct ibuf *src)
406 {
407 	int			 ret = -1;
408 	size_t			 integrlen, tmplen;
409 	struct ibuf		*integr, *prf, *tmp = NULL;
410 	u_int8_t		*ptr;
411 
412 	log_debug("%s: message length %d", __func__, ibuf_size(src));
413 	print_hex(ibuf_data(src), 0, ibuf_size(src));
414 
415 	if (sa == NULL ||
416 	    sa->sa_integr == NULL) {
417 		log_debug("%s: invalid SA", __func__);
418 		return (-1);
419 	}
420 
421 	if (sa->sa_hdr.sh_initiator) {
422 		integr = sa->sa_key_iauth;
423 		prf = sa->sa_key_iprf;
424 	} else {
425 		integr = sa->sa_key_rauth;
426 		prf = sa->sa_key_rprf;
427 	}
428 
429 	integrlen = hash_length(sa->sa_integr);
430 
431 	log_debug("%s: integrity checksum length %d", __func__,
432 	    integrlen);
433 
434 	/*
435 	 * Validate packet checksum
436 	 */
437 	if ((tmp = ibuf_new(NULL, hash_keylength(sa->sa_integr))) == NULL)
438 		goto done;
439 
440 	hash_setkey(sa->sa_integr, ibuf_data(integr), ibuf_size(integr));
441 	hash_init(sa->sa_integr);
442 	hash_update(sa->sa_integr, ibuf_data(src),
443 	    ibuf_size(src) - integrlen);
444 	hash_final(sa->sa_integr, ibuf_data(tmp), &tmplen);
445 
446 	if (tmplen != integrlen) {
447 		log_debug("%s: hash failure", __func__);
448 		goto done;
449 	}
450 
451 	if ((ptr = ibuf_seek(src,
452 	    ibuf_size(src) - integrlen, integrlen)) == NULL)
453 		goto done;
454 	memcpy(ptr, ibuf_data(tmp), tmplen);
455 
456 	print_hex(ibuf_data(tmp), 0, ibuf_size(tmp));
457 
458 	ret = 0;
459  done:
460 	ibuf_release(tmp);
461 
462 	return (ret);
463 }
464 
465 struct ibuf *
466 ikev2_msg_decrypt(struct iked *env, struct iked_sa *sa,
467     struct ibuf *msg, struct ibuf *src)
468 {
469 	ssize_t			 ivlen, encrlen, integrlen, blocklen,
470 				    outlen, tmplen;
471 	u_int8_t		 pad = 0, *ptr;
472 	struct ibuf		*integr, *encr, *tmp = NULL, *out = NULL;
473 	off_t			 ivoff, encroff, integroff;
474 
475 	if (sa == NULL ||
476 	    sa->sa_encr == NULL ||
477 	    sa->sa_integr == NULL) {
478 		log_debug("%s: invalid SA", __func__);
479 		print_hex(ibuf_data(src), 0, ibuf_size(src));
480 		goto done;
481 	}
482 
483 	if (!sa->sa_hdr.sh_initiator) {
484 		encr = sa->sa_key_iencr;
485 		integr = sa->sa_key_iauth;
486 	} else {
487 		encr = sa->sa_key_rencr;
488 		integr = sa->sa_key_rauth;
489 	}
490 
491 	blocklen = cipher_length(sa->sa_encr);
492 	ivlen = cipher_ivlength(sa->sa_encr);
493 	ivoff = 0;
494 	integrlen = hash_length(sa->sa_integr);
495 	integroff = ibuf_size(src) - integrlen;
496 	encroff = ivlen;
497 	encrlen = ibuf_size(src) - integrlen - ivlen;
498 
499 	if (encrlen < 0 || integroff < 0) {
500 		log_debug("%s: invalid integrity value", __func__);
501 		goto done;
502 	}
503 
504 	log_debug("%s: IV length %d", __func__, ivlen);
505 	print_hex(ibuf_data(src), 0, ivlen);
506 	log_debug("%s: encrypted payload length %d", __func__, encrlen);
507 	print_hex(ibuf_data(src), encroff, encrlen);
508 	log_debug("%s: integrity checksum length %d", __func__, integrlen);
509 	print_hex(ibuf_data(src), integroff, integrlen);
510 
511 	/*
512 	 * Validate packet checksum
513 	 */
514 	if ((tmp = ibuf_new(NULL, ibuf_length(integr))) == NULL)
515 		goto done;
516 
517 	hash_setkey(sa->sa_integr, integr->buf, ibuf_length(integr));
518 	hash_init(sa->sa_integr);
519 	hash_update(sa->sa_integr, ibuf_data(msg),
520 	    ibuf_size(msg) - integrlen);
521 	hash_final(sa->sa_integr, tmp->buf, &tmplen);
522 
523 	if (memcmp(tmp->buf, ibuf_data(src) + integroff, integrlen) != 0) {
524 		log_debug("%s: integrity check failed", __func__);
525 		goto done;
526 	}
527 
528 	log_debug("%s: integrity check succeeded", __func__);
529 	print_hex(tmp->buf, 0, tmplen);
530 
531 	ibuf_release(tmp);
532 	tmp = NULL;
533 
534 	/*
535 	 * Decrypt the payload and strip any padding
536 	 */
537 	if ((encrlen % blocklen) != 0) {
538 		log_debug("%s: unaligned encrypted payload", __func__);
539 		goto done;
540 	}
541 
542 	cipher_setkey(sa->sa_encr, encr->buf, ibuf_length(encr));
543 	cipher_setiv(sa->sa_encr, ibuf_data(src) + ivoff, ivlen);
544 	cipher_init_decrypt(sa->sa_encr);
545 
546 	if ((out = ibuf_new(NULL, cipher_outlength(sa->sa_encr,
547 	    encrlen))) == NULL)
548 		goto done;
549 
550 	if ((outlen = ibuf_length(out)) != 0) {
551 		cipher_update(sa->sa_encr, ibuf_data(src) + encroff, encrlen,
552 		    ibuf_data(out), &outlen);
553 
554 		ptr = ibuf_seek(out, outlen - 1, 1);
555 		pad = *ptr;
556 	}
557 
558 	log_debug("%s: decrypted payload length %d/%d padding %d",
559 	    __func__, outlen, encrlen, pad);
560 	print_hex(ibuf_data(out), 0, ibuf_size(out));
561 
562 	if (ibuf_setsize(out, outlen) != 0)
563 		goto done;
564 
565 	ibuf_release(src);
566 	return (out);
567  done:
568 	ibuf_release(tmp);
569 	ibuf_release(out);
570 	ibuf_release(src);
571 	return (NULL);
572 }
573 
574 int
575 ikev2_msg_send_encrypt(struct iked *env, struct iked_sa *sa, struct ibuf **ep,
576     u_int8_t exchange, u_int8_t firstpayload, int response)
577 {
578 	struct iked_message		 resp;
579 	struct ike_header		*hdr;
580 	struct ikev2_payload		*pld;
581 	struct ibuf			*buf, *e = *ep;
582 	int				 ret = -1;
583 
584 	if ((buf = ikev2_msg_init(env, &resp, &sa->sa_peer.addr,
585 	    sa->sa_peer.addr.ss_len, &sa->sa_local.addr,
586 	    sa->sa_local.addr.ss_len, response)) == NULL)
587 		goto done;
588 
589 	resp.msg_msgid = response ? sa->sa_msgid : ikev2_msg_id(env, sa);
590 
591 	/* IKE header */
592 	if ((hdr = ikev2_add_header(buf, sa, resp.msg_msgid, IKEV2_PAYLOAD_SK,
593 	    exchange, response ? IKEV2_FLAG_RESPONSE : 0)) == NULL)
594 		goto done;
595 
596 	if ((pld = ikev2_add_payload(buf)) == NULL)
597 		goto done;
598 
599 	/* Encrypt message and add as an E payload */
600 	if ((e = ikev2_msg_encrypt(env, sa, e)) == NULL) {
601 		log_debug("%s: encryption failed", __func__);
602 		goto done;
603 	}
604 	if (ibuf_cat(buf, e) != 0)
605 		goto done;
606 	if (ikev2_next_payload(pld, ibuf_size(e), firstpayload) == -1)
607 		goto done;
608 
609 	if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
610 		goto done;
611 
612 	/* Add integrity checksum (HMAC) */
613 	if (ikev2_msg_integr(env, sa, buf) != 0) {
614 		log_debug("%s: integrity checksum failed", __func__);
615 		goto done;
616 	}
617 
618 	resp.msg_data = buf;
619 	resp.msg_sa = sa;
620 	resp.msg_fd = sa->sa_fd;
621 	TAILQ_INIT(&resp.msg_proposals);
622 
623 	(void)ikev2_pld_parse(env, hdr, &resp, 0);
624 
625 	ret = ikev2_msg_send(env, &resp);
626 
627  done:
628 	/* e is cleaned up by the calling function */
629 	*ep = e;
630 	ikev2_msg_cleanup(env, &resp);
631 
632 	return (ret);
633 }
634 
635 struct ibuf *
636 ikev2_msg_auth(struct iked *env, struct iked_sa *sa, int response)
637 {
638 	struct ibuf		*authmsg = NULL, *nonce, *prfkey, *buf;
639 	u_int8_t		*ptr;
640 	struct iked_id		*id;
641 	size_t			 tmplen;
642 
643 	/*
644 	 * Create the payload to be signed/MAC'ed for AUTH
645 	 */
646 
647 	if (!response) {
648 		if ((nonce = sa->sa_rnonce) == NULL ||
649 		    (sa->sa_iid.id_type == 0) ||
650 		    (prfkey = sa->sa_key_iprf) == NULL ||
651 		    (buf = sa->sa_1stmsg) == NULL)
652 			return (NULL);
653 		id = &sa->sa_iid;
654 	} else {
655 		if ((nonce = sa->sa_inonce) == NULL ||
656 		    (sa->sa_rid.id_type == 0) ||
657 		    (prfkey = sa->sa_key_rprf) == NULL ||
658 		    (buf = sa->sa_2ndmsg) == NULL)
659 			return (NULL);
660 		id = &sa->sa_rid;
661 	}
662 
663 	if ((authmsg = ibuf_dup(buf)) == NULL)
664 		return (NULL);
665 	if (ibuf_cat(authmsg, nonce) != 0)
666 		goto fail;
667 
668 	if ((hash_setkey(sa->sa_prf, ibuf_data(prfkey),
669 	    ibuf_size(prfkey))) == NULL)
670 		goto fail;
671 
672 	if ((ptr = ibuf_advance(authmsg,
673 	    hash_length(sa->sa_prf))) == NULL)
674 		goto fail;
675 
676 	hash_init(sa->sa_prf);
677 	hash_update(sa->sa_prf, ibuf_data(id->id_buf), ibuf_size(id->id_buf));
678 	hash_final(sa->sa_prf, ptr, &tmplen);
679 
680 	if (tmplen != hash_length(sa->sa_prf))
681 		goto fail;
682 
683 	log_debug("%s: %s auth data length %d",
684 	    __func__, response ? "responder" : "initiator",
685 	    ibuf_size(authmsg));
686 	print_hex(ibuf_data(authmsg), 0, ibuf_size(authmsg));
687 
688 	return (authmsg);
689 
690  fail:
691 	ibuf_release(authmsg);
692 	return (NULL);
693 }
694 
695 int
696 ikev2_msg_authverify(struct iked *env, struct iked_sa *sa,
697     struct iked_auth *auth, u_int8_t *buf, size_t len, struct ibuf *authmsg)
698 {
699 	u_int8_t			*key, *psk = NULL;
700 	ssize_t				 keylen;
701 	struct iked_id			*id;
702 	struct iked_dsa			*dsa = NULL;
703 	int				 ret = -1;
704 	u_int8_t			 keytype;
705 
706 	if (sa->sa_hdr.sh_initiator)
707 		id = &sa->sa_rcert;
708 	else
709 		id = &sa->sa_icert;
710 
711 	if ((dsa = dsa_verify_new(auth->auth_method, sa->sa_prf)) == NULL) {
712 		log_debug("%s: invalid auth method", __func__);
713 		return (-1);
714 	}
715 
716 	switch (auth->auth_method) {
717 	case IKEV2_AUTH_SHARED_KEY_MIC:
718 		if (!auth->auth_length) {
719 			log_debug("%s: no pre-shared key found", __func__);
720 			goto done;
721 		}
722 		if ((keylen = ikev2_psk(sa, auth->auth_data,
723 		    auth->auth_length, &psk)) == -1) {
724 			log_debug("%s: failed to get PSK", __func__);
725 			goto done;
726 		}
727 		key = psk;
728 		keytype = 0;
729 		break;
730 	default:
731 		if (!id->id_type || !ibuf_length(id->id_buf)) {
732 			log_debug("%s: no cert found", __func__);
733 			goto done;
734 		}
735 		key = ibuf_data(id->id_buf);
736 		keylen = ibuf_size(id->id_buf);
737 		keytype = id->id_type;
738 		break;
739 	}
740 
741 	log_debug("%s: method %s keylen %d type %s", __func__,
742 	    print_map(auth->auth_method, ikev2_auth_map), keylen,
743 	    print_map(id->id_type, ikev2_cert_map));
744 
745 	if (dsa_setkey(dsa, key, keylen, keytype) == NULL ||
746 	    dsa_init(dsa) != 0 ||
747 	    dsa_update(dsa, ibuf_data(authmsg), ibuf_size(authmsg))) {
748 		log_debug("%s: failed to compute digital signature", __func__);
749 		goto done;
750 	}
751 
752 	if ((ret = dsa_verify_final(dsa, buf, len)) == 0) {
753 		log_debug("%s: authentication successful", __func__);
754 		sa_state(env, sa, IKEV2_STATE_AUTH_SUCCESS);
755 
756 		if (!sa->sa_policy->pol_auth.auth_eap &&
757 		    auth->auth_method == IKEV2_AUTH_SHARED_KEY_MIC)
758 			sa_state(env, sa, IKEV2_STATE_VALID);
759 	} else {
760 		log_debug("%s: authentication failed", __func__);
761 		sa_state(env, sa, IKEV2_STATE_AUTH_REQUEST);
762 	}
763 
764  done:
765 	if (psk != NULL)
766 		free(psk);
767 	dsa_free(dsa);
768 
769 	return (ret);
770 }
771 
772 int
773 ikev2_msg_authsign(struct iked *env, struct iked_sa *sa,
774     struct iked_auth *auth, struct ibuf *authmsg)
775 {
776 	u_int8_t			*key, *psk = NULL;
777 	ssize_t				 keylen;
778 	struct iked_hash		*prf = sa->sa_prf;
779 	struct iked_id			*id;
780 	struct iked_dsa			*dsa = NULL;
781 	struct ibuf			*buf;
782 	int				 ret = -1;
783 	u_int8_t			 keytype;
784 
785 	if (sa->sa_hdr.sh_initiator)
786 		id = &sa->sa_icert;
787 	else
788 		id = &sa->sa_rcert;
789 
790 	if ((dsa = dsa_sign_new(auth->auth_method, prf)) == NULL) {
791 		log_debug("%s: invalid auth method", __func__);
792 		return (-1);
793 	}
794 
795 	switch (auth->auth_method) {
796 	case IKEV2_AUTH_SHARED_KEY_MIC:
797 		if (!auth->auth_length) {
798 			log_debug("%s: no pre-shared key found", __func__);
799 			goto done;
800 		}
801 		if ((keylen = ikev2_psk(sa, auth->auth_data,
802 		    auth->auth_length, &psk)) == -1) {
803 			log_debug("%s: failed to get PSK", __func__);
804 			goto done;
805 		}
806 		key = psk;
807 		keytype = 0;
808 		break;
809 	default:
810 		if (id == NULL) {
811 			log_debug("%s: no cert found", __func__);
812 			goto done;
813 		}
814 		key = ibuf_data(id->id_buf);
815 		keylen = ibuf_size(id->id_buf);
816 		keytype = id->id_type;
817 		break;
818 	}
819 
820 	if (dsa_setkey(dsa, key, keylen, keytype) == NULL ||
821 	    dsa_init(dsa) != 0 ||
822 	    dsa_update(dsa, ibuf_data(authmsg), ibuf_size(authmsg))) {
823 		log_debug("%s: failed to compute digital signature", __func__);
824 		goto done;
825 	}
826 
827 	ibuf_release(sa->sa_localauth.id_buf);
828 	sa->sa_localauth.id_buf = NULL;
829 
830 	if ((buf = ibuf_new(NULL, dsa_length(dsa))) == NULL) {
831 		log_debug("%s: failed to get auth buffer", __func__);
832 		goto done;
833 	}
834 
835 	if ((ret = dsa_sign_final(dsa,
836 	    ibuf_data(buf), ibuf_size(buf))) == -1) {
837 		log_debug("%s: failed to create auth signature", __func__);
838 		ibuf_release(buf);
839 		goto done;
840 	}
841 
842 	sa->sa_localauth.id_type = auth->auth_method;
843 	sa->sa_localauth.id_buf = buf;
844 
845 	ret = 0;
846  done:
847 	if (psk != NULL)
848 		free(psk);
849 	dsa_free(dsa);
850 
851 	return (ret);
852 }
853 
854 int
855 ikev2_msg_frompeer(struct iked_message *msg)
856 {
857 	struct iked_sa		*sa = msg->msg_sa;
858 	struct ike_header	*hdr;
859 
860 	msg = msg->msg_parent;
861 
862 	if (sa == NULL ||
863 	    (hdr = ibuf_seek(msg->msg_data, 0, sizeof(*hdr))) == NULL)
864 		return (0);
865 
866 	if (!sa->sa_hdr.sh_initiator &&
867 	    (hdr->ike_flags & IKEV2_FLAG_INITIATOR))
868 		return (1);
869 	else if (sa->sa_hdr.sh_initiator &&
870 	    (hdr->ike_flags & IKEV2_FLAG_INITIATOR) == 0)
871 		return (1);
872 
873 	return (0);
874 }
875 
876 struct iked_socket *
877 ikev2_msg_getsocket(struct iked *env, int af)
878 {
879 	switch (af) {
880 	case AF_INET:
881 		return (env->sc_sock4);
882 	case AF_INET6:
883 		return (env->sc_sock6);
884 	}
885 
886 	log_debug("%s: af socket %d not available", __func__, af);
887 	return (NULL);
888 }
889 
890 void
891 ikev2_msg_prevail(struct iked *env, struct iked_msgqueue *queue,
892     struct iked_message *msg)
893 {
894 	struct iked_message	*m, *mtmp;
895 
896 	TAILQ_FOREACH_SAFE(m, queue, msg_entry, mtmp) {
897 		if (m->msg_msgid < msg->msg_msgid)
898 			ikev2_msg_dispose(env, queue, m);
899 	}
900 }
901 
902 void
903 ikev2_msg_dispose(struct iked *env, struct iked_msgqueue *queue,
904     struct iked_message *msg)
905 {
906 	TAILQ_REMOVE(queue, msg, msg_entry);
907 	timer_deregister(env, &msg->msg_timer);
908 	ikev2_msg_cleanup(env, msg);
909 	free(msg);
910 }
911 
912 void
913 ikev2_msg_flushqueue(struct iked *env, struct iked_msgqueue *queue)
914 {
915 	struct iked_message	*m = NULL;
916 
917 	while ((m = TAILQ_FIRST(queue)) != NULL)
918 		ikev2_msg_dispose(env, queue, m);
919 }
920 
921 struct iked_message *
922 ikev2_msg_lookup(struct iked *env, struct iked_msgqueue *queue,
923     struct iked_message *msg, struct ike_header *hdr)
924 {
925 	struct iked_message	*m = NULL;
926 
927 	TAILQ_FOREACH(m, queue, msg_entry) {
928 		if (m->msg_msgid == msg->msg_msgid &&
929 		    m->msg_exchange == hdr->ike_exchange)
930 			break;
931 	}
932 
933 	return (m);
934 }
935 
936 int
937 ikev2_msg_retransmit_response(struct iked *env, struct iked_sa *sa,
938     struct iked_message *msg)
939 {
940 	if ((sendto(msg->msg_fd, ibuf_data(msg->msg_data),
941 	    ibuf_size(msg->msg_data), 0, (struct sockaddr *)&msg->msg_peer,
942 	    msg->msg_peerlen)) == -1) {
943 		log_warn("%s: sendto", __func__);
944 		sa_free(env, sa);
945 		return (-1);
946 	}
947 
948 	timer_register(env, &msg->msg_timer, IKED_RESPONSE_TIMEOUT);
949 	return (0);
950 }
951 
952 void
953 ikev2_msg_response_timeout(struct iked *env, void *arg)
954 {
955 	struct iked_message	*msg = arg;
956 	struct iked_sa		*sa = msg->msg_sa;
957 
958 	ikev2_msg_dispose(env, &sa->sa_responses, msg);
959 }
960 
961 void
962 ikev2_msg_retransmit_timeout(struct iked *env, void *arg)
963 {
964 	struct iked_message	*msg = arg;
965 	struct iked_sa		*sa = msg->msg_sa;
966 
967 	if (msg->msg_tries < IKED_RETRANSMIT_TRIES) {
968 		if ((sendto(msg->msg_fd, ibuf_data(msg->msg_data),
969 		    ibuf_size(msg->msg_data), 0,
970 		    (struct sockaddr *)&msg->msg_peer,
971 		    msg->msg_peerlen)) == -1) {
972 			log_warn("%s: sendto", __func__);
973 			sa_free(env, sa);
974 			return;
975 		}
976 		/* Exponential timeout */
977 		timer_register(env, &msg->msg_timer,
978 		    IKED_RETRANSMIT_TIMEOUT * (2 << (msg->msg_tries++)));
979 	} else {
980 		log_debug("%s: retransmit limit reached", __func__);
981 		sa_free(env, sa);
982 	}
983 }
984