xref: /openbsd-src/sbin/iked/ikev2_msg.c (revision d13be5d47e4149db2549a9828e244d59dbc43f15)
1 /*	$OpenBSD: ikev2_msg.c,v 1.12 2011/05/09 11:15:18 reyk 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
51 ikev2_msg_cb(int fd, short event, void *arg)
52 {
53 	struct iked_socket	*sock = arg;
54 	struct iked		*env = sock->sock_env;
55 	struct iked_message	 msg;
56 	struct ike_header	 hdr;
57 	u_int32_t		 natt = 0x00000000;
58 	u_int8_t		 buf[IKED_MSGBUF_MAX];
59 	ssize_t			 len;
60 	off_t			 off;
61 	struct iovec		 iov[2];
62 
63 	bzero(&msg, sizeof(msg));
64 	bzero(buf, sizeof(buf));
65 
66 	msg.msg_peerlen = sizeof(msg.msg_peer);
67 	msg.msg_locallen = sizeof(msg.msg_local);
68 	msg.msg_parent = &msg;
69 	memcpy(&msg.msg_local, &sock->sock_addr, sizeof(sock->sock_addr));
70 
71 	if ((len = recvfromto(fd, buf, sizeof(buf), 0,
72 	    (struct sockaddr *)&msg.msg_peer, &msg.msg_peerlen,
73 	    (struct sockaddr *)&msg.msg_local, &msg.msg_locallen)) <
74 	    (ssize_t)sizeof(natt))
75 		return;
76 
77 	if (socket_getport(&msg.msg_local) == IKED_NATT_PORT) {
78 		if (bcmp(&natt, buf, sizeof(natt)) != 0)
79 			return;
80 		msg.msg_natt = 1;
81 		off = sizeof(natt);
82 	} else
83 		off = 0;
84 
85 	if ((size_t)(len - off) <= sizeof(hdr))
86 		return;
87 	memcpy(&hdr, buf + off, sizeof(hdr));
88 
89 	if ((msg.msg_data = ibuf_new(buf + off, len - off)) == NULL)
90 		return;
91 
92 	if (hdr.ike_version == IKEV1_VERSION) {
93 		iov[0].iov_base = &msg;
94 		iov[0].iov_len = sizeof(msg);
95 		iov[1].iov_base = buf;
96 		iov[1].iov_len = len;
97 
98 		proc_composev_imsg(env, PROC_IKEV1, IMSG_IKE_MESSAGE, -1,
99 		    iov, 2);
100 		goto done;
101 	}
102 	TAILQ_INIT(&msg.msg_proposals);
103 
104 	msg.msg_fd = fd;
105 	ikev2_recv(env, &msg);
106 
107  done:
108 	ikev2_msg_cleanup(env, &msg);
109 }
110 
111 struct ibuf *
112 ikev2_msg_init(struct iked *env, struct iked_message *msg,
113     struct sockaddr_storage *peer, socklen_t peerlen,
114     struct sockaddr_storage *local, socklen_t locallen, int response)
115 {
116 	bzero(msg, sizeof(*msg));
117 	memcpy(&msg->msg_peer, peer, peerlen);
118 	msg->msg_peerlen = peerlen;
119 	memcpy(&msg->msg_local, local, locallen);
120 	msg->msg_locallen = locallen;
121 	msg->msg_response = response ? 1 : 0;
122 	msg->msg_fd = -1;
123 	msg->msg_data = ibuf_static();
124 	msg->msg_e = 0;
125 	msg->msg_parent = msg;	/* has to be set */
126 	TAILQ_INIT(&msg->msg_proposals);
127 
128 	return (msg->msg_data);
129 }
130 
131 void
132 ikev2_msg_cleanup(struct iked *env, struct iked_message *msg)
133 {
134 	if (msg == msg->msg_parent) {
135 		ibuf_release(msg->msg_nonce);
136 		ibuf_release(msg->msg_ke);
137 		ibuf_release(msg->msg_auth.id_buf);
138 		ibuf_release(msg->msg_id.id_buf);
139 		ibuf_release(msg->msg_cert.id_buf);
140 
141 		config_free_proposals(&msg->msg_proposals, 0);
142 	}
143 
144 	if (msg->msg_data != NULL) {
145 		ibuf_release(msg->msg_data);
146 		msg->msg_data = NULL;
147 	}
148 }
149 
150 int
151 ikev2_msg_valid_ike_sa(struct iked *env, struct ike_header *oldhdr,
152     struct iked_message *msg)
153 {
154 #if 0
155 	/* XXX Disabled, see comment below */
156 	struct iked_message		 resp;
157 	struct ike_header		*hdr;
158 	struct ikev2_payload		*pld;
159 	struct ikev2_notify		*n;
160 	struct ibuf			*buf;
161 	struct iked_sa			 sa;
162 #endif
163 
164 	if (msg->msg_sa != NULL && msg->msg_policy != NULL)
165 		return (0);
166 
167 #if 0
168 	/*
169 	 * XXX Sending INVALID_IKE_SPIs notifications is disabled
170 	 * XXX because it is not mandatory and ignored by most
171 	 * XXX implementations.  We might want to enable it in
172 	 * XXX combination with a rate-limitation to avoid DoS situations.
173 	 */
174 
175 	/* Fail without error message */
176 	if (msg->msg_response || msg->msg_policy == NULL)
177 		return (-1);
178 
179 	/* Invalid IKE SA, return notification */
180 	if ((buf = ikev2_msg_init(env, &resp,
181 	    &msg->msg_peer, msg->msg_peerlen,
182 	    &msg->msg_local, msg->msg_locallen, 1)) == NULL)
183 		goto done;
184 
185 	bzero(&sa, sizeof(sa));
186 	if ((oldhdr->ike_flags & IKEV2_FLAG_INITIATOR) == 0)
187 		sa.sa_hdr.sh_initiator = 1;
188 	sa.sa_hdr.sh_ispi = betoh64(oldhdr->ike_ispi);
189 	sa.sa_hdr.sh_rspi = betoh64(oldhdr->ike_rspi);
190 
191 	/* IKE header */
192 	if ((hdr = ikev2_add_header(buf, &sa, betoh32(oldhdr->ike_msgid),
193 	    IKEV2_PAYLOAD_NOTIFY, IKEV2_EXCHANGE_INFORMATIONAL,
194 	    IKEV2_FLAG_RESPONSE)) == NULL)
195 		goto done;
196 
197 	/* SA payload */
198 	if ((pld = ikev2_add_payload(buf)) == NULL)
199 		goto done;
200 	if ((n = ibuf_advance(buf, sizeof(*n))) == NULL)
201 		goto done;
202 	n->n_protoid = IKEV2_SAPROTO_IKE;
203 	n->n_spisize = 0;
204 	n->n_type = htobe16(IKEV2_N_INVALID_IKE_SPI);
205 
206 	if (ikev2_next_payload(pld, sizeof(*n), IKEV2_PAYLOAD_NONE) == -1)
207 		goto done;
208 
209 	if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
210 		goto done;
211 
212 	(void)ikev2_pld_parse(env, hdr, &resp, 0);
213 	(void)ikev2_msg_send(env, msg->msg_fd, &resp);
214 
215  done:
216 	ikev2_msg_cleanup(env, &resp);
217 #endif
218 
219 	/* Always fail */
220 	return (-1);
221 }
222 
223 int
224 ikev2_msg_send(struct iked *env, int fd, struct iked_message *msg)
225 {
226 	struct ibuf		*buf = msg->msg_data;
227 	u_int32_t		 natt = 0x00000000;
228 	struct ike_header	*hdr;
229 
230 	if (buf == NULL || (hdr = ibuf_seek(msg->msg_data,
231 	    msg->msg_offset, sizeof(*hdr))) == NULL)
232 		return (-1);
233 
234 	log_info("%s: %s from %s to %s, %ld bytes", __func__,
235 	    print_map(hdr->ike_exchange, ikev2_exchange_map),
236 	    print_host(&msg->msg_local, NULL, 0),
237 	    print_host(&msg->msg_peer, NULL, 0),
238 	    ibuf_length(buf));
239 
240 	if (msg->msg_natt || (msg->msg_sa && msg->msg_sa->sa_natt)) {
241 		if (ibuf_prepend(buf, &natt, sizeof(natt)) == -1) {
242 			log_debug("%s: failed to set NAT-T", __func__);
243 			return (-1);
244 		}
245 	}
246 	if ((sendto(fd, ibuf_data(buf), ibuf_size(buf), 0,
247 	    (struct sockaddr *)&msg->msg_peer, msg->msg_peerlen)) == -1) {
248 		log_warn("%s: sendto", __func__);
249 		return (-1);
250 	}
251 
252 	return (0);
253 }
254 
255 u_int32_t
256 ikev2_msg_id(struct iked *env, struct iked_sa *sa, int response)
257 {
258 	u_int32_t		*id;
259 
260 	id = response ? &sa->sa_msgid : &sa->sa_reqid;
261 	if (++*id == UINT32_MAX) {
262 		/* XXX we should close and renegotiate the connection now */
263 		log_debug("%s: IKEv2 message sequence overflow", __func__);
264 	}
265 	return (*id - 1);
266 }
267 
268 struct ibuf *
269 ikev2_msg_encrypt(struct iked *env, struct iked_sa *sa, struct ibuf *src)
270 {
271 	size_t			 len, ivlen, encrlen, integrlen, blocklen,
272 				    outlen;
273 	u_int8_t		*buf, pad = 0, *ptr;
274 	struct ibuf		*integr, *encr, *dst = NULL, *out = NULL;
275 
276 	buf = ibuf_data(src);
277 	len = ibuf_size(src);
278 
279 	log_debug("%s: decrypted length %d", __func__, len);
280 	print_hex(buf, 0, len);
281 
282 	if (sa == NULL ||
283 	    sa->sa_encr == NULL ||
284 	    sa->sa_integr == NULL) {
285 		log_debug("%s: invalid SA", __func__);
286 		goto done;
287 	}
288 
289 	if (sa->sa_hdr.sh_initiator) {
290 		encr = sa->sa_key_iencr;
291 		integr = sa->sa_key_iauth;
292 	} else {
293 		encr = sa->sa_key_rencr;
294 		integr = sa->sa_key_rauth;
295 	}
296 
297 	blocklen = cipher_length(sa->sa_encr);
298 	ivlen = cipher_ivlength(sa->sa_encr);
299 	integrlen = hash_length(sa->sa_integr);
300 	encrlen = roundup(len + sizeof(pad), blocklen);
301 	pad = encrlen - (len + sizeof(pad));
302 
303 	/*
304 	 * Pad the payload and encrypt it
305 	 */
306 	if (pad) {
307 		if ((ptr = ibuf_advance(src, pad)) == NULL)
308 			goto done;
309 		arc4random_buf(ptr, pad);
310 	}
311 	if (ibuf_add(src, &pad, sizeof(pad)) != 0)
312 		goto done;
313 
314 	log_debug("%s: padded length %d", __func__, ibuf_size(src));
315 	print_hex(ibuf_data(src), 0, ibuf_size(src));
316 
317 	cipher_setkey(sa->sa_encr, encr->buf, ibuf_length(encr));
318 	cipher_setiv(sa->sa_encr, NULL, 0);	/* new IV */
319 	cipher_init_encrypt(sa->sa_encr);
320 
321 	if ((dst = ibuf_dup(sa->sa_encr->encr_iv)) == NULL)
322 		goto done;
323 
324 	if ((out = ibuf_new(NULL,
325 	    cipher_outlength(sa->sa_encr, encrlen))) == NULL)
326 		goto done;
327 
328 	outlen = ibuf_size(out);
329 	cipher_update(sa->sa_encr,
330 	    ibuf_data(src), encrlen, ibuf_data(out), &outlen);
331 
332 	if (outlen && ibuf_add(dst, ibuf_data(out), outlen) != 0)
333 		goto done;
334 
335 	if ((ptr = ibuf_advance(dst, integrlen)) == NULL)
336 		goto done;
337 	bzero(ptr, integrlen);
338 
339 	log_debug("%s: length %d, padding %d, output length %d",
340 	    __func__, len + sizeof(pad), pad, ibuf_size(dst));
341 	print_hex(ibuf_data(dst), 0, ibuf_size(dst));
342 
343 	ibuf_release(src);
344 	ibuf_release(out);
345 	return (dst);
346  done:
347 	ibuf_release(src);
348 	ibuf_release(out);
349 	ibuf_release(dst);
350 	return (NULL);
351 }
352 
353 int
354 ikev2_msg_integr(struct iked *env, struct iked_sa *sa, struct ibuf *src)
355 {
356 	int			 ret = -1;
357 	size_t			 integrlen, tmplen;
358 	struct ibuf		*integr, *prf, *tmp = NULL;
359 	u_int8_t		*ptr;
360 
361 	log_debug("%s: message length %d", __func__, ibuf_size(src));
362 	print_hex(ibuf_data(src), 0, ibuf_size(src));
363 
364 	if (sa == NULL ||
365 	    sa->sa_integr == NULL) {
366 		log_debug("%s: invalid SA", __func__);
367 		return (-1);
368 	}
369 
370 	if (sa->sa_hdr.sh_initiator) {
371 		integr = sa->sa_key_iauth;
372 		prf = sa->sa_key_iprf;
373 	} else {
374 		integr = sa->sa_key_rauth;
375 		prf = sa->sa_key_rprf;
376 	}
377 
378 	integrlen = hash_length(sa->sa_integr);
379 
380 	log_debug("%s: integrity checksum length %d", __func__,
381 	    integrlen);
382 
383 	/*
384 	 * Validate packet checksum
385 	 */
386 	if ((tmp = ibuf_new(NULL, hash_keylength(sa->sa_integr))) == NULL)
387 		goto done;
388 
389 	hash_setkey(sa->sa_integr, ibuf_data(integr), ibuf_size(integr));
390 	hash_init(sa->sa_integr);
391 	hash_update(sa->sa_integr, ibuf_data(src),
392 	    ibuf_size(src) - integrlen);
393 	hash_final(sa->sa_integr, ibuf_data(tmp), &tmplen);
394 
395 	if (tmplen != integrlen) {
396 		log_debug("%s: hash failure", __func__);
397 		goto done;
398 	}
399 
400 	if ((ptr = ibuf_seek(src,
401 	    ibuf_size(src) - integrlen, integrlen)) == NULL)
402 		goto done;
403 	memcpy(ptr, ibuf_data(tmp), tmplen);
404 
405 	print_hex(ibuf_data(tmp), 0, ibuf_size(tmp));
406 
407 	ret = 0;
408  done:
409 	ibuf_release(tmp);
410 
411 	return (ret);
412 }
413 
414 struct ibuf *
415 ikev2_msg_decrypt(struct iked *env, struct iked_sa *sa,
416     struct ibuf *msg, struct ibuf *src)
417 {
418 	ssize_t			 ivlen, encrlen, integrlen, blocklen,
419 				    outlen, tmplen;
420 	u_int8_t		 pad = 0, *ptr;
421 	struct ibuf		*integr, *encr, *tmp = NULL, *out = NULL;
422 	off_t			 ivoff, encroff, integroff;
423 
424 	if (sa == NULL ||
425 	    sa->sa_encr == NULL ||
426 	    sa->sa_integr == NULL) {
427 		log_debug("%s: invalid SA", __func__);
428 		print_hex(ibuf_data(src), 0, ibuf_size(src));
429 		goto done;
430 	}
431 
432 	if (!sa->sa_hdr.sh_initiator) {
433 		encr = sa->sa_key_iencr;
434 		integr = sa->sa_key_iauth;
435 	} else {
436 		encr = sa->sa_key_rencr;
437 		integr = sa->sa_key_rauth;
438 	}
439 
440 	blocklen = cipher_length(sa->sa_encr);
441 	ivlen = cipher_ivlength(sa->sa_encr);
442 	ivoff = 0;
443 	integrlen = hash_length(sa->sa_integr);
444 	integroff = ibuf_size(src) - integrlen;
445 	encroff = ivlen;
446 	encrlen = ibuf_size(src) - integrlen - ivlen;
447 
448 	if (encrlen < 0 || integroff < 0) {
449 		log_debug("%s: invalid integrity value", __func__);
450 		goto done;
451 	}
452 
453 	log_debug("%s: IV length %d", __func__, ivlen);
454 	print_hex(ibuf_data(src), 0, ivlen);
455 	log_debug("%s: encrypted payload length %d", __func__, encrlen);
456 	print_hex(ibuf_data(src), encroff, encrlen);
457 	log_debug("%s: integrity checksum length %d", __func__, integrlen);
458 	print_hex(ibuf_data(src), integroff, integrlen);
459 
460 	/*
461 	 * Validate packet checksum
462 	 */
463 	if ((tmp = ibuf_new(NULL, ibuf_length(integr))) == NULL)
464 		goto done;
465 
466 	hash_setkey(sa->sa_integr, integr->buf, ibuf_length(integr));
467 	hash_init(sa->sa_integr);
468 	hash_update(sa->sa_integr, ibuf_data(msg),
469 	    ibuf_size(msg) - integrlen);
470 	hash_final(sa->sa_integr, tmp->buf, &tmplen);
471 
472 	if (memcmp(tmp->buf, ibuf_data(src) + integroff, integrlen) != 0) {
473 		log_debug("%s: integrity check failed", __func__);
474 		goto done;
475 	}
476 
477 	log_debug("%s: integrity check succeeded", __func__);
478 	print_hex(tmp->buf, 0, tmplen);
479 
480 	ibuf_release(tmp);
481 	tmp = NULL;
482 
483 	/*
484 	 * Decrypt the payload and strip any padding
485 	 */
486 	if ((encrlen % blocklen) != 0) {
487 		log_debug("%s: unaligned encrypted payload", __func__);
488 		goto done;
489 	}
490 
491 	cipher_setkey(sa->sa_encr, encr->buf, ibuf_length(encr));
492 	cipher_setiv(sa->sa_encr, ibuf_data(src) + ivoff, ivlen);
493 	cipher_init_decrypt(sa->sa_encr);
494 
495 	if ((out = ibuf_new(NULL, cipher_outlength(sa->sa_encr,
496 	    encrlen))) == NULL)
497 		goto done;
498 
499 	if ((outlen = ibuf_length(out)) != 0) {
500 		cipher_update(sa->sa_encr, ibuf_data(src) + encroff, encrlen,
501 		    ibuf_data(out), &outlen);
502 
503 		ptr = ibuf_seek(out, outlen - 1, 1);
504 		pad = *ptr;
505 	}
506 
507 	log_debug("%s: decrypted payload length %d/%d padding %d",
508 	    __func__, outlen, encrlen, pad);
509 	print_hex(ibuf_data(out), 0, ibuf_size(out));
510 
511 	if (ibuf_setsize(out, outlen) != 0)
512 		goto done;
513 
514 	ibuf_release(src);
515 	return (out);
516  done:
517 	ibuf_release(tmp);
518 	ibuf_release(out);
519 	ibuf_release(src);
520 	return (NULL);
521 }
522 
523 int
524 ikev2_msg_send_encrypt(struct iked *env, struct iked_sa *sa,
525     struct ibuf **ep, u_int8_t exchange, u_int8_t firstpayload, int response)
526 {
527 	struct iked_message		 resp;
528 	struct ike_header		*hdr;
529 	struct ikev2_payload		*pld;
530 	struct ibuf			*buf, *e = *ep;
531 	int				 ret = -1;
532 
533 	if ((buf = ikev2_msg_init(env, &resp,
534 	    &sa->sa_peer.addr, sa->sa_peer.addr.ss_len,
535 	    &sa->sa_local.addr, sa->sa_local.addr.ss_len, 1)) == NULL)
536 		goto done;
537 
538 	/* IKE header */
539 	if ((hdr = ikev2_add_header(buf, sa,
540 	    ikev2_msg_id(env, sa, response),
541 	    IKEV2_PAYLOAD_E, exchange,
542 	    response ? IKEV2_FLAG_RESPONSE : 0)) == NULL)
543 		goto done;
544 
545 	if ((pld = ikev2_add_payload(buf)) == NULL)
546 		goto done;
547 
548 	/* Encrypt message and add as an E payload */
549 	if ((e = ikev2_msg_encrypt(env, sa, e)) == NULL) {
550 		log_debug("%s: encryption failed", __func__);
551 		goto done;
552 	}
553 	if (ibuf_cat(buf, e) != 0)
554 		goto done;
555 	if (ikev2_next_payload(pld, ibuf_size(e), firstpayload) == -1)
556 		goto done;
557 
558 	if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
559 		goto done;
560 
561 	/* Add integrity checksum (HMAC) */
562 	if (ikev2_msg_integr(env, sa, buf) != 0) {
563 		log_debug("%s: integrity checksum failed", __func__);
564 		goto done;
565 	}
566 
567 	resp.msg_data = buf;
568 	resp.msg_sa = sa;
569 	TAILQ_INIT(&resp.msg_proposals);
570 
571 	(void)ikev2_pld_parse(env, hdr, &resp, 0);
572 
573 	ret = ikev2_msg_send(env, sa->sa_fd, &resp);
574 
575  done:
576 	/* e is cleaned up by the calling function */
577 	*ep = e;
578 	ikev2_msg_cleanup(env, &resp);
579 
580 	return (ret);
581 }
582 
583 struct ibuf *
584 ikev2_msg_auth(struct iked *env, struct iked_sa *sa, int response)
585 {
586 	struct ibuf		*authmsg = NULL, *nonce, *prfkey, *buf;
587 	u_int8_t		*ptr;
588 	struct iked_id		*id;
589 	size_t			 tmplen;
590 
591 	/*
592 	 * Create the payload to be signed/MAC'ed for AUTH
593 	 */
594 
595 	if (!response) {
596 		if ((nonce = sa->sa_rnonce) == NULL ||
597 		    (sa->sa_iid.id_type == 0) ||
598 		    (prfkey = sa->sa_key_iprf) == NULL ||
599 		    (buf = sa->sa_1stmsg) == NULL)
600 			return (NULL);
601 		id = &sa->sa_iid;
602 	} else {
603 		if ((nonce = sa->sa_inonce) == NULL ||
604 		    (sa->sa_rid.id_type == 0) ||
605 		    (prfkey = sa->sa_key_rprf) == NULL ||
606 		    (buf = sa->sa_2ndmsg) == NULL)
607 			return (NULL);
608 		id = &sa->sa_rid;
609 	}
610 
611 	if ((authmsg = ibuf_dup(buf)) == NULL)
612 		return (NULL);
613 	if (ibuf_cat(authmsg, nonce) != 0)
614 		goto fail;
615 
616 	if ((hash_setkey(sa->sa_prf, ibuf_data(prfkey),
617 	    ibuf_size(prfkey))) == NULL)
618 		goto fail;
619 
620 	if ((ptr = ibuf_advance(authmsg,
621 	    hash_length(sa->sa_prf))) == NULL)
622 		goto fail;
623 
624 	hash_init(sa->sa_prf);
625 	hash_update(sa->sa_prf, ibuf_data(id->id_buf), ibuf_size(id->id_buf));
626 	hash_final(sa->sa_prf, ptr, &tmplen);
627 
628 	if (tmplen != hash_length(sa->sa_prf))
629 		goto fail;
630 
631 	log_debug("%s: %s auth data length %d",
632 	    __func__, response ? "responder" : "initiator",
633 	    ibuf_size(authmsg));
634 	print_hex(ibuf_data(authmsg), 0, ibuf_size(authmsg));
635 
636 	return (authmsg);
637 
638  fail:
639 	ibuf_release(authmsg);
640 	return (NULL);
641 }
642 
643 int
644 ikev2_msg_authverify(struct iked *env, struct iked_sa *sa,
645     struct iked_auth *auth, u_int8_t *buf, size_t len, struct ibuf *authmsg)
646 {
647 	u_int8_t			*key, *psk = NULL;
648 	ssize_t				 keylen;
649 	struct iked_id			*id;
650 	struct iked_dsa			*dsa = NULL;
651 	int				 ret = -1;
652 	u_int8_t			 keytype;
653 
654 	if (sa->sa_hdr.sh_initiator)
655 		id = &sa->sa_rcert;
656 	else
657 		id = &sa->sa_icert;
658 
659 	if ((dsa = dsa_verify_new(auth->auth_method, sa->sa_prf)) == NULL) {
660 		log_debug("%s: invalid auth method", __func__);
661 		return (-1);
662 	}
663 
664 	switch (auth->auth_method) {
665 	case IKEV2_AUTH_SHARED_KEY_MIC:
666 		if (!auth->auth_length) {
667 			log_debug("%s: no pre-shared key found", __func__);
668 			goto done;
669 		}
670 		if ((keylen = ikev2_psk(sa, auth->auth_data,
671 		    auth->auth_length, &psk)) == -1) {
672 			log_debug("%s: failed to get PSK", __func__);
673 			goto done;
674 		}
675 		key = psk;
676 		keytype = 0;
677 		break;
678 	default:
679 		if (!id->id_type || !ibuf_length(id->id_buf)) {
680 			log_debug("%s: no cert found", __func__);
681 			goto done;
682 		}
683 		key = ibuf_data(id->id_buf);
684 		keylen = ibuf_size(id->id_buf);
685 		keytype = id->id_type;
686 		break;
687 	}
688 
689 	log_debug("%s: method %s keylen %d type %s", __func__,
690 	    print_map(auth->auth_method, ikev2_auth_map), keylen,
691 	    print_map(id->id_type, ikev2_cert_map));
692 
693 	if (dsa_setkey(dsa, key, keylen, keytype) == NULL ||
694 	    dsa_init(dsa) != 0 ||
695 	    dsa_update(dsa, ibuf_data(authmsg), ibuf_size(authmsg))) {
696 		log_debug("%s: failed to compute digital signature", __func__);
697 		goto done;
698 	}
699 
700 	if ((ret = dsa_verify_final(dsa, buf, len)) == 0) {
701 		log_debug("%s: authentication successful", __func__);
702 		sa_state(env, sa, IKEV2_STATE_AUTH_SUCCESS);
703 
704 		if (!sa->sa_policy->pol_auth.auth_eap &&
705 		    auth->auth_method == IKEV2_AUTH_SHARED_KEY_MIC)
706 			sa_state(env, sa, IKEV2_STATE_VALID);
707 	} else {
708 		log_debug("%s: authentication failed", __func__);
709 		sa_state(env, sa, IKEV2_STATE_AUTH_REQUEST);
710 	}
711 
712  done:
713 	if (psk != NULL)
714 		free(psk);
715 	dsa_free(dsa);
716 
717 	return (ret);
718 }
719 
720 int
721 ikev2_msg_authsign(struct iked *env, struct iked_sa *sa,
722     struct iked_auth *auth, struct ibuf *authmsg)
723 {
724 	u_int8_t			*key, *psk = NULL;
725 	ssize_t				 keylen;
726 	struct iked_hash		*prf = sa->sa_prf;
727 	struct iked_id			*id;
728 	struct iked_dsa			*dsa = NULL;
729 	struct ibuf			*buf;
730 	int				 ret = -1;
731 	u_int8_t			 keytype;
732 
733 	if (sa->sa_hdr.sh_initiator)
734 		id = &sa->sa_icert;
735 	else
736 		id = &sa->sa_rcert;
737 
738 	if ((dsa = dsa_sign_new(auth->auth_method, prf)) == NULL) {
739 		log_debug("%s: invalid auth method", __func__);
740 		return (-1);
741 	}
742 
743 	switch (auth->auth_method) {
744 	case IKEV2_AUTH_SHARED_KEY_MIC:
745 		if (!auth->auth_length) {
746 			log_debug("%s: no pre-shared key found", __func__);
747 			goto done;
748 		}
749 		if ((keylen = ikev2_psk(sa, auth->auth_data,
750 		    auth->auth_length, &psk)) == -1) {
751 			log_debug("%s: failed to get PSK", __func__);
752 			goto done;
753 		}
754 		key = psk;
755 		keytype = 0;
756 		break;
757 	default:
758 		if (id == NULL) {
759 			log_debug("%s: no cert found", __func__);
760 			goto done;
761 		}
762 		key = ibuf_data(id->id_buf);
763 		keylen = ibuf_size(id->id_buf);
764 		keytype = id->id_type;
765 		break;
766 	}
767 
768 	if (dsa_setkey(dsa, key, keylen, keytype) == NULL ||
769 	    dsa_init(dsa) != 0 ||
770 	    dsa_update(dsa, ibuf_data(authmsg), ibuf_size(authmsg))) {
771 		log_debug("%s: failed to compute digital signature", __func__);
772 		goto done;
773 	}
774 
775 	ibuf_release(sa->sa_localauth.id_buf);
776 	sa->sa_localauth.id_buf = NULL;
777 
778 	if ((buf = ibuf_new(NULL, dsa_length(dsa))) == NULL) {
779 		log_debug("%s: failed to get auth buffer", __func__);
780 		goto done;
781 	}
782 
783 	if ((ret = dsa_sign_final(dsa,
784 	    ibuf_data(buf), ibuf_size(buf))) == -1) {
785 		log_debug("%s: failed to create auth signature", __func__);
786 		ibuf_release(buf);
787 		goto done;
788 	}
789 
790 	sa->sa_localauth.id_type = auth->auth_method;
791 	sa->sa_localauth.id_buf = buf;
792 
793 	ret = 0;
794  done:
795 	if (psk != NULL)
796 		free(psk);
797 	dsa_free(dsa);
798 
799 	return (ret);
800 }
801 
802 int
803 ikev2_msg_frompeer(struct iked_message *msg)
804 {
805 	struct iked_sa		*sa = msg->msg_sa;
806 	struct ike_header	*hdr;
807 
808 	msg = msg->msg_parent;
809 
810 	if (sa == NULL ||
811 	    (hdr = ibuf_seek(msg->msg_data, 0, sizeof(*hdr))) == NULL)
812 		return (0);
813 
814 	if (!sa->sa_hdr.sh_initiator &&
815 	    (hdr->ike_flags & IKEV2_FLAG_INITIATOR))
816 		return (1);
817 	else if (sa->sa_hdr.sh_initiator &&
818 	    (hdr->ike_flags & IKEV2_FLAG_INITIATOR) == 0)
819 		return (1);
820 
821 	return (0);
822 }
823 
824 struct iked_socket *
825 ikev2_msg_getsocket(struct iked *env, int af)
826 {
827 	switch (af) {
828 	case AF_INET:
829 		return (env->sc_sock4);
830 	case AF_INET6:
831 		return (env->sc_sock6);
832 	}
833 
834 	log_debug("%s: af socket %d not available", __func__, af);
835 	return (NULL);
836 }
837