GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: sbin/iked/ikev2.c Lines: 0 2954 0.0 %
Date: 2017-11-13 Branches: 0 2083 0.0 %

Line Branch Exec Source
1
/*	$OpenBSD: ikev2.c,v 1.157 2017/11/08 09:35:19 patrick Exp $	*/
2
3
/*
4
 * Copyright (c) 2010-2013 Reyk Floeter <reyk@openbsd.org>
5
 *
6
 * Permission to use, copy, modify, and distribute this software for any
7
 * purpose with or without fee is hereby granted, provided that the above
8
 * copyright notice and this permission notice appear in all copies.
9
 *
10
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
 */
18
19
#include <sys/param.h>	/* roundup */
20
#include <sys/queue.h>
21
#include <sys/socket.h>
22
#include <sys/wait.h>
23
#include <sys/uio.h>
24
25
#include <netinet/in.h>
26
#include <netinet/ip_ipsp.h>
27
#include <arpa/inet.h>
28
29
#include <stdlib.h>
30
#include <stdio.h>
31
#include <unistd.h>
32
#include <string.h>
33
#include <signal.h>
34
#include <errno.h>
35
#include <err.h>
36
#include <pwd.h>
37
#include <event.h>
38
39
#include <openssl/sha.h>
40
#include <openssl/evp.h>
41
#include <openssl/x509.h>
42
43
#include "iked.h"
44
#include "ikev2.h"
45
#include "eap.h"
46
#include "dh.h"
47
48
void	 ikev2_run(struct privsep *, struct privsep_proc *, void *);
49
int	 ikev2_dispatch_parent(int, struct privsep_proc *, struct imsg *);
50
int	 ikev2_dispatch_cert(int, struct privsep_proc *, struct imsg *);
51
52
struct iked_sa *
53
	 ikev2_getimsgdata(struct iked *, struct imsg *, struct iked_sahdr *,
54
	    uint8_t *, uint8_t **, size_t *);
55
56
void	 ikev2_recv(struct iked *, struct iked_message *);
57
int	 ikev2_ike_auth_compatible(struct iked_sa *, uint8_t, uint8_t);
58
int	 ikev2_ike_auth_recv(struct iked *, struct iked_sa *,
59
	    struct iked_message *);
60
int	 ikev2_ike_auth(struct iked *, struct iked_sa *);
61
62
void	 ikev2_init_recv(struct iked *, struct iked_message *,
63
	    struct ike_header *);
64
void	 ikev2_init_ike_sa_timeout(struct iked *, void *);
65
int	 ikev2_init_ike_sa_peer(struct iked *, struct iked_policy *,
66
	    struct iked_addr *, struct iked_message *);
67
int	 ikev2_init_ike_auth(struct iked *, struct iked_sa *);
68
int	 ikev2_init_auth(struct iked *, struct iked_message *);
69
int	 ikev2_init_done(struct iked *, struct iked_sa *);
70
71
void	 ikev2_resp_recv(struct iked *, struct iked_message *,
72
	    struct ike_header *);
73
int	 ikev2_resp_ike_sa_init(struct iked *, struct iked_message *);
74
int	 ikev2_resp_ike_auth(struct iked *, struct iked_sa *);
75
int	 ikev2_resp_ike_eap(struct iked *, struct iked_sa *, struct ibuf *);
76
int	 ikev2_send_auth_failed(struct iked *, struct iked_sa *);
77
int	 ikev2_send_error(struct iked *, struct iked_sa *,
78
	    struct iked_message *, uint8_t);
79
80
int	 ikev2_send_create_child_sa(struct iked *, struct iked_sa *,
81
	    struct iked_spi *, uint8_t);
82
int	 ikev2_ikesa_enable(struct iked *, struct iked_sa *, struct iked_sa *);
83
void	 ikev2_ikesa_delete(struct iked *, struct iked_sa *, int);
84
int	 ikev2_nonce_cmp(struct ibuf *, struct ibuf *);
85
int	 ikev2_init_create_child_sa(struct iked *, struct iked_message *);
86
int	 ikev2_resp_create_child_sa(struct iked *, struct iked_message *);
87
void	 ikev2_ike_sa_rekey(struct iked *, void *);
88
void	 ikev2_ike_sa_rekey_timeout(struct iked *, void *);
89
void	 ikev2_ike_sa_rekey_schedule(struct iked *, struct iked_sa *);
90
void	 ikev2_ike_sa_alive(struct iked *, void *);
91
void	 ikev2_ike_sa_keepalive(struct iked *, void *);
92
93
int	 ikev2_sa_initiator(struct iked *, struct iked_sa *,
94
	    struct iked_sa *, struct iked_message *);
95
int	 ikev2_sa_responder(struct iked *, struct iked_sa *, struct iked_sa *,
96
	    struct iked_message *);
97
int	 ikev2_sa_initiator_dh(struct iked_sa *, struct iked_message *,
98
	    unsigned int);
99
int	 ikev2_sa_responder_dh(struct iked_kex *, struct iked_proposals *,
100
	    struct iked_message *, unsigned int);
101
void	 ikev2_sa_cleanup_dh(struct iked_sa *);
102
int	 ikev2_sa_keys(struct iked *, struct iked_sa *, struct ibuf *);
103
int	 ikev2_sa_tag(struct iked_sa *, struct iked_id *);
104
int	 ikev2_set_sa_proposal(struct iked_sa *, struct iked_policy *,
105
	    unsigned int);
106
107
int	 ikev2_childsa_negotiate(struct iked *, struct iked_sa *,
108
	    struct iked_kex *, struct iked_proposals *, int, int, int);
109
int	 ikev2_childsa_delete_proposed(struct iked *, struct iked_sa *,
110
	    struct iked_proposals *);
111
int	 ikev2_match_proposals(struct iked_proposal *, struct iked_proposal *,
112
	    struct iked_transform **, int);
113
int	 ikev2_valid_proposal(struct iked_proposal *,
114
	    struct iked_transform **, struct iked_transform **, int *);
115
116
ssize_t	 ikev2_add_proposals(struct iked *, struct iked_sa *, struct ibuf *,
117
	    struct iked_proposals *, uint8_t, int, int);
118
ssize_t	 ikev2_add_cp(struct iked *, struct iked_sa *, struct ibuf *);
119
ssize_t	 ikev2_add_transform(struct ibuf *,
120
	    uint8_t, uint8_t, uint16_t, uint16_t);
121
ssize_t	 ikev2_add_ts(struct ibuf *, struct ikev2_payload **, ssize_t,
122
	    struct iked_sa *, int);
123
ssize_t	 ikev2_add_certreq(struct ibuf *, struct ikev2_payload **, ssize_t,
124
	    struct ibuf *, uint8_t);
125
ssize_t	 ikev2_add_ipcompnotify(struct iked *, struct ibuf *,
126
	    struct ikev2_payload **, ssize_t, struct iked_sa *);
127
ssize_t	 ikev2_add_ts_payload(struct ibuf *, unsigned int, struct iked_sa *);
128
int	 ikev2_add_data(struct ibuf *, void *, size_t);
129
int	 ikev2_add_buf(struct ibuf *buf, struct ibuf *);
130
131
int	 ikev2_ipcomp_enable(struct iked *, struct iked_sa *);
132
void	 ikev2_ipcomp_csa_free(struct iked *, struct iked_childsa *);
133
134
int	 ikev2_cp_setaddr(struct iked *, struct iked_sa *, sa_family_t);
135
int	 ikev2_cp_fixaddr(struct iked_sa *, struct iked_addr *,
136
	    struct iked_addr *);
137
138
ssize_t	ikev2_add_sighashnotify(struct ibuf *, struct ikev2_payload **,
139
	    ssize_t);
140
ssize_t ikev2_add_nat_detection(struct iked *, struct ibuf *,
141
	    struct ikev2_payload **, struct iked_message *, ssize_t);
142
143
static struct privsep_proc procs[] = {
144
	{ "parent",	PROC_PARENT,	ikev2_dispatch_parent },
145
	{ "certstore",	PROC_CERT,	ikev2_dispatch_cert }
146
};
147
148
pid_t
149
ikev2(struct privsep *ps, struct privsep_proc *p)
150
{
151
	return (proc_run(ps, p, procs, nitems(procs), ikev2_run, NULL));
152
}
153
154
void
155
ikev2_run(struct privsep *ps, struct privsep_proc *p, void *arg)
156
{
157
	/*
158
	 * pledge in the ikev2 process:
159
	 * stdio - for malloc and basic I/O including events.
160
	 * inet - for sendto with specified peer address.
161
	 * recvfd - for PFKEYv2 and the listening UDP sockets.
162
	 * In theory, recvfd could be dropped after getting the fds once.
163
	 */
164
	if (pledge("stdio inet recvfd flock rpath cpath wpath", NULL) == -1)
165
		fatal("pledge");
166
}
167
168
int
169
ikev2_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
170
{
171
	struct iked		*env = p->p_env;
172
173
	switch (imsg->hdr.type) {
174
	case IMSG_CTL_RESET:
175
		return (config_getreset(env, imsg));
176
	case IMSG_CTL_COUPLE:
177
	case IMSG_CTL_DECOUPLE:
178
		return (config_getcoupled(env, imsg->hdr.type));
179
	case IMSG_CTL_ACTIVE:
180
	case IMSG_CTL_PASSIVE:
181
		if (config_getmode(env, imsg->hdr.type) == -1)
182
			return (0);	/* ignore error */
183
		if (env->sc_passive)
184
			timer_del(env, &env->sc_inittmr);
185
		else {
186
			timer_set(env, &env->sc_inittmr, ikev2_init_ike_sa,
187
			    NULL);
188
			timer_add(env, &env->sc_inittmr,
189
			    IKED_INITIATOR_INITIAL);
190
		}
191
		return (0);
192
	case IMSG_UDP_SOCKET:
193
		return (config_getsocket(env, imsg, ikev2_msg_cb));
194
	case IMSG_PFKEY_SOCKET:
195
		return (config_getpfkey(env, imsg));
196
	case IMSG_CFG_POLICY:
197
		return (config_getpolicy(env, imsg));
198
	case IMSG_CFG_FLOW:
199
		return (config_getflow(env, imsg));
200
	case IMSG_CFG_USER:
201
		return (config_getuser(env, imsg));
202
	case IMSG_COMPILE:
203
		return (config_getcompile(env, imsg));
204
	default:
205
		break;
206
	}
207
208
	return (-1);
209
}
210
211
int
212
ikev2_dispatch_cert(int fd, struct privsep_proc *p, struct imsg *imsg)
213
{
214
	struct iked		*env = p->p_env;
215
	struct iked_sahdr	 sh;
216
	struct iked_sa		*sa;
217
	uint8_t			 type;
218
	uint8_t			*ptr;
219
	size_t			 len;
220
	struct iked_id		*id = NULL;
221
	int			 ignore = 0;
222
223
	switch (imsg->hdr.type) {
224
	case IMSG_CERTREQ:
225
		IMSG_SIZE_CHECK(imsg, &type);
226
227
		ptr = imsg->data;
228
		memcpy(&type, ptr, sizeof(type));
229
		ptr += sizeof(type);
230
231
		ibuf_release(env->sc_certreq);
232
		env->sc_certreqtype = type;
233
		env->sc_certreq = ibuf_new(ptr,
234
		    IMSG_DATA_SIZE(imsg) - sizeof(type));
235
236
		log_debug("%s: updated local CERTREQ type %s length %zu",
237
		    __func__, print_map(type, ikev2_cert_map),
238
		    ibuf_length(env->sc_certreq));
239
240
		break;
241
	case IMSG_CERTVALID:
242
	case IMSG_CERTINVALID:
243
		if (IMSG_DATA_SIZE(imsg) < sizeof(type) + sizeof(sh))
244
			fatalx("bad length imsg received");
245
246
		memcpy(&sh, imsg->data, sizeof(sh));
247
		memcpy(&type, (uint8_t *)imsg->data + sizeof(sh),
248
		    sizeof(type));
249
250
		/* Ignore invalid or unauthenticated SAs */
251
		if ((sa = sa_lookup(env,
252
		    sh.sh_ispi, sh.sh_rspi, sh.sh_initiator)) == NULL ||
253
		    sa->sa_state < IKEV2_STATE_EAP)
254
			break;
255
256
		if (imsg->hdr.type == IMSG_CERTVALID) {
257
			log_debug("%s: peer certificate is valid", __func__);
258
			sa_stateflags(sa, IKED_REQ_CERTVALID);
259
		} else {
260
			log_warnx("%s: peer certificate is invalid", __func__);
261
			ikev2_send_auth_failed(env, sa);
262
			break;
263
		}
264
		if (ikev2_ike_auth(env, sa) != 0)
265
			log_debug("%s: failed to send ike auth", __func__);
266
		break;
267
	case IMSG_CERT:
268
		if ((sa = ikev2_getimsgdata(env, imsg,
269
		    &sh, &type, &ptr, &len)) == NULL) {
270
			log_debug("%s: invalid cert reply", __func__);
271
			break;
272
		}
273
274
		/*
275
		 * Ignore the message if we already got a valid certificate.
276
		 * This might happen if the peer sent multiple CERTREQs.
277
		 */
278
		if (sa->sa_stateflags & IKED_REQ_CERT ||
279
		    type == IKEV2_CERT_NONE)
280
			ignore = 1;
281
282
		log_debug("%s: cert type %s length %zu, %s", __func__,
283
		    print_map(type, ikev2_cert_map), len,
284
		    ignore ? "ignored" : "ok");
285
286
		if (ignore)
287
			break;
288
289
		if (sh.sh_initiator)
290
			id = &sa->sa_icert;
291
		else
292
			id = &sa->sa_rcert;
293
294
		id->id_type = type;
295
		id->id_offset = 0;
296
		ibuf_release(id->id_buf);
297
		id->id_buf = NULL;
298
299
		if (len <= 0 || (id->id_buf = ibuf_new(ptr, len)) == NULL) {
300
			log_debug("%s: failed to get cert payload",
301
			    __func__);
302
			break;
303
		}
304
305
		sa_stateflags(sa, IKED_REQ_CERT);
306
307
		if (ikev2_ike_auth(env, sa) != 0)
308
			log_debug("%s: failed to send ike auth", __func__);
309
		break;
310
	case IMSG_AUTH:
311
		if ((sa = ikev2_getimsgdata(env, imsg,
312
		    &sh, &type, &ptr, &len)) == NULL) {
313
			log_debug("%s: invalid auth reply", __func__);
314
			break;
315
		}
316
		if (sa_stateok(sa, IKEV2_STATE_VALID)) {
317
			log_warnx("%s: ignoring AUTH in state %s", __func__,
318
			    print_map(sa->sa_state, ikev2_state_map));
319
			break;
320
		}
321
322
		log_debug("%s: AUTH type %d len %zu", __func__, type, len);
323
324
		id = &sa->sa_localauth;
325
		id->id_type = type;
326
		id->id_offset = 0;
327
		ibuf_release(id->id_buf);
328
		id->id_buf = NULL;
329
330
		if (type != IKEV2_AUTH_NONE) {
331
			if (len <= 0 ||
332
			    (id->id_buf = ibuf_new(ptr, len)) == NULL) {
333
				log_debug("%s: failed to get auth payload",
334
				    __func__);
335
				break;
336
			}
337
		}
338
339
		sa_stateflags(sa, IKED_REQ_AUTH);
340
341
		if (ikev2_ike_auth(env, sa) != 0)
342
			log_debug("%s: failed to send ike auth", __func__);
343
		break;
344
	default:
345
		return (-1);
346
	}
347
348
	return (0);
349
}
350
351
struct iked_sa *
352
ikev2_getimsgdata(struct iked *env, struct imsg *imsg, struct iked_sahdr *sh,
353
    uint8_t *type, uint8_t **buf, size_t *size)
354
{
355
	uint8_t		*ptr;
356
	size_t		 len;
357
	struct iked_sa	*sa;
358
359
	IMSG_SIZE_CHECK(imsg, sh);
360
361
	ptr = imsg->data;
362
	len = IMSG_DATA_SIZE(imsg) - sizeof(*sh) - sizeof(*type);
363
	memcpy(sh, ptr, sizeof(*sh));
364
	memcpy(type, ptr + sizeof(*sh), sizeof(*type));
365
366
	sa = sa_lookup(env, sh->sh_ispi, sh->sh_rspi, sh->sh_initiator);
367
368
	log_debug("%s: imsg %d rspi %s ispi %s initiator %d sa %s"
369
	    " type %d data length %zd",
370
	    __func__, imsg->hdr.type,
371
	    print_spi(sh->sh_rspi, 8),
372
	    print_spi(sh->sh_ispi, 8),
373
	    sh->sh_initiator,
374
	    sa == NULL ? "invalid" : "valid", *type, len);
375
376
	if (sa == NULL)
377
		return (NULL);
378
379
	*buf = ptr + sizeof(*sh) + sizeof(*type);
380
	*size = len;
381
382
	return (sa);
383
}
384
385
void
386
ikev2_recv(struct iked *env, struct iked_message *msg)
387
{
388
	struct ike_header	*hdr;
389
	struct iked_message	*m;
390
	struct iked_sa		*sa;
391
	unsigned int		 initiator, flag = 0;
392
393
	hdr = ibuf_seek(msg->msg_data, msg->msg_offset, sizeof(*hdr));
394
395
	if (hdr == NULL || ibuf_size(msg->msg_data) <
396
	    (betoh32(hdr->ike_length) - msg->msg_offset))
397
		return;
398
399
	initiator = (hdr->ike_flags & IKEV2_FLAG_INITIATOR) ? 0 : 1;
400
	msg->msg_response = (hdr->ike_flags & IKEV2_FLAG_RESPONSE) ? 1 : 0;
401
	msg->msg_sa = sa_lookup(env,
402
	    betoh64(hdr->ike_ispi), betoh64(hdr->ike_rspi),
403
	    initiator);
404
	msg->msg_msgid = betoh32(hdr->ike_msgid);
405
	if (policy_lookup(env, msg) != 0)
406
		return;
407
408
	log_info("%s: %s %s from %s %s to %s policy '%s' id %u, %ld bytes",
409
	    __func__, print_map(hdr->ike_exchange, ikev2_exchange_map),
410
	    msg->msg_response ? "response" : "request",
411
	    initiator ? "responder" : "initiator",
412
	    print_host((struct sockaddr *)&msg->msg_peer, NULL, 0),
413
	    print_host((struct sockaddr *)&msg->msg_local, NULL, 0),
414
	    msg->msg_policy->pol_name, msg->msg_msgid,
415
	    ibuf_length(msg->msg_data));
416
	log_debug("%s: ispi %s rspi %s", __func__,
417
	    print_spi(betoh64(hdr->ike_ispi), 8),
418
	    print_spi(betoh64(hdr->ike_rspi), 8));
419
420
	if ((sa = msg->msg_sa) == NULL)
421
		goto done;
422
423
	if (hdr->ike_exchange == IKEV2_EXCHANGE_CREATE_CHILD_SA)
424
		flag = IKED_REQ_CHILDSA;
425
	if (hdr->ike_exchange == IKEV2_EXCHANGE_INFORMATIONAL)
426
		flag = IKED_REQ_INF;
427
428
	if (msg->msg_response) {
429
		if (msg->msg_msgid > sa->sa_reqid)
430
			return;
431
		if (hdr->ike_exchange != IKEV2_EXCHANGE_INFORMATIONAL &&
432
		    !ikev2_msg_lookup(env, &sa->sa_requests, msg, hdr))
433
			return;
434
		if (flag) {
435
			if ((sa->sa_stateflags & flag) == 0)
436
				return;
437
			/*
438
			 * We have initiated this exchange, even if
439
			 * we are not the initiator of the IKE SA.
440
			 */
441
			initiator = 1;
442
		}
443
		/*
444
		 * There's no need to keep the request around anymore
445
		 */
446
		if ((m = ikev2_msg_lookup(env, &sa->sa_requests, msg, hdr)))
447
			ikev2_msg_dispose(env, &sa->sa_requests, m);
448
	} else {
449
		if (msg->msg_msgid < sa->sa_msgid)
450
			return;
451
		if (flag)
452
			initiator = 0;
453
		/*
454
		 * See if we have responded to this request before
455
		 */
456
		if ((m = ikev2_msg_lookup(env, &sa->sa_responses, msg, hdr))) {
457
			if (ikev2_msg_retransmit_response(env, sa, m)) {
458
				log_warn("%s: failed to retransmit a "
459
				    "response", __func__);
460
				sa_free(env, sa);
461
			}
462
			return;
463
		} else if (sa->sa_msgid_set && msg->msg_msgid == sa->sa_msgid) {
464
			/*
465
			 * Response is being worked on, most likely we're
466
			 * waiting for the CA process to get back to us
467
			 */
468
			return;
469
		}
470
		/*
471
		 * If it's a new request, make sure to update the peer's
472
		 * message ID and dispose of all previous responses.
473
		 * We need to set sa_msgid_set in order to distinguish between
474
		 * "last msgid was 0" and "msgid not set yet".
475
		 */
476
		sa->sa_msgid = msg->msg_msgid;
477
		sa->sa_msgid_set = 1;
478
		ikev2_msg_prevail(env, &sa->sa_responses, msg);
479
	}
480
481
	if (sa_address(sa, &sa->sa_peer, &msg->msg_peer) == -1 ||
482
	    sa_address(sa, &sa->sa_local, &msg->msg_local) == -1)
483
		return;
484
485
	sa->sa_fd = msg->msg_fd;
486
487
	log_debug("%s: updated SA to peer %s local %s", __func__,
488
	    print_host((struct sockaddr *)&sa->sa_peer.addr, NULL, 0),
489
	    print_host((struct sockaddr *)&sa->sa_local.addr, NULL, 0));
490
491
done:
492
	if (initiator)
493
		ikev2_init_recv(env, msg, hdr);
494
	else
495
		ikev2_resp_recv(env, msg, hdr);
496
497
	if (sa != NULL && sa->sa_state == IKEV2_STATE_CLOSED) {
498
		log_debug("%s: closing SA", __func__);
499
		sa_free(env, sa);
500
	}
501
}
502
503
int
504
ikev2_ike_auth_compatible(struct iked_sa *sa, uint8_t policy, uint8_t wire)
505
{
506
	if (wire == IKEV2_AUTH_SIG_ANY)		/* internal, not on wire */
507
		return (-1);
508
	if (policy == wire || policy == IKEV2_AUTH_NONE)
509
		return (0);
510
	switch (policy) {
511
	case IKEV2_AUTH_SIG_ANY:
512
		switch (wire) {
513
		case IKEV2_AUTH_SIG:
514
		case IKEV2_AUTH_RSA_SIG:
515
		case IKEV2_AUTH_ECDSA_256:
516
		case IKEV2_AUTH_ECDSA_384:
517
		case IKEV2_AUTH_ECDSA_521:
518
			return (0);
519
		}
520
		break;
521
	case IKEV2_AUTH_SIG:
522
	case IKEV2_AUTH_RSA_SIG:
523
	case IKEV2_AUTH_ECDSA_256:
524
	case IKEV2_AUTH_ECDSA_384:
525
	case IKEV2_AUTH_ECDSA_521:
526
		switch (wire) {
527
		/*
528
		 * XXX Maybe we need an indication saying:
529
		 * XXX Accept AUTH_SIG as long as its DSA?
530
		 */
531
		case IKEV2_AUTH_SIG:
532
			if (sa->sa_sigsha2)
533
				return (0);
534
		}
535
		break;
536
	}
537
	return (-1);
538
}
539
540
int
541
ikev2_ike_auth_recv(struct iked *env, struct iked_sa *sa,
542
    struct iked_message *msg)
543
{
544
	struct iked_id		*id, *certid;
545
	struct ibuf		*authmsg;
546
	struct iked_auth	 ikeauth;
547
	struct iked_policy	*policy = sa->sa_policy;
548
	int			 ret = -1;
549
550
	if (sa->sa_hdr.sh_initiator) {
551
		id = &sa->sa_rid;
552
		certid = &sa->sa_rcert;
553
	} else {
554
		id = &sa->sa_iid;
555
		certid = &sa->sa_icert;
556
	}
557
	/* try to relookup the policy based on the peerid */
558
	if (msg->msg_id.id_type && !sa->sa_hdr.sh_initiator) {
559
		struct iked_policy	*old = sa->sa_policy;
560
561
		sa->sa_policy = NULL;
562
		if (policy_lookup(env, msg) == 0 && msg->msg_policy &&
563
		    msg->msg_policy != old) {
564
			/* move sa to new policy */
565
			policy = sa->sa_policy = msg->msg_policy;
566
			TAILQ_REMOVE(&old->pol_sapeers, sa, sa_peer_entry);
567
			TAILQ_INSERT_TAIL(&policy->pol_sapeers,
568
			    sa, sa_peer_entry);
569
			if (old->pol_flags & IKED_POLICY_REFCNT)
570
				policy_unref(env, old);
571
			if (policy->pol_flags & IKED_POLICY_REFCNT)
572
				policy_ref(env, policy);
573
		} else {
574
			/* restore */
575
			msg->msg_policy = sa->sa_policy = old;
576
		}
577
	}
578
579
	if (msg->msg_id.id_type) {
580
		memcpy(id, &msg->msg_id, sizeof(*id));
581
		bzero(&msg->msg_id, sizeof(msg->msg_id));
582
583
		if (!sa->sa_hdr.sh_initiator) {
584
			if ((authmsg = ikev2_msg_auth(env, sa,
585
			    !sa->sa_hdr.sh_initiator)) == NULL) {
586
				log_debug("%s: failed to get response "
587
				    "auth data", __func__);
588
				return (-1);
589
			}
590
591
			ca_setauth(env, sa, authmsg, PROC_CERT);
592
			ibuf_release(authmsg);
593
		}
594
	}
595
596
	if (msg->msg_cert.id_type) {
597
		memcpy(certid, &msg->msg_cert, sizeof(*certid));
598
		bzero(&msg->msg_cert, sizeof(msg->msg_cert));
599
600
		ca_setcert(env, &sa->sa_hdr,
601
		    id, certid->id_type,
602
		    ibuf_data(certid->id_buf),
603
		    ibuf_length(certid->id_buf), PROC_CERT);
604
	}
605
606
	if (msg->msg_auth.id_type) {
607
		memcpy(&ikeauth, &policy->pol_auth, sizeof(ikeauth));
608
609
		if (policy->pol_auth.auth_eap && sa->sa_eapmsk != NULL) {
610
			/*
611
			 * The initiator EAP auth is a PSK derived
612
			 * from the EAP-specific MSK
613
			 */
614
			ikeauth.auth_method = IKEV2_AUTH_SHARED_KEY_MIC;
615
616
			/* Copy session key as PSK */
617
			memcpy(ikeauth.auth_data, ibuf_data(sa->sa_eapmsk),
618
			    ibuf_size(sa->sa_eapmsk));
619
			ikeauth.auth_length = ibuf_size(sa->sa_eapmsk);
620
		}
621
622
		if (ikev2_ike_auth_compatible(sa,
623
		    ikeauth.auth_method, msg->msg_auth.id_type) < 0) {
624
			log_warnx("%s: unexpected auth method %s, was "
625
			    "expecting %s", __func__,
626
			    print_map(msg->msg_auth.id_type, ikev2_auth_map),
627
			    print_map(ikeauth.auth_method, ikev2_auth_map));
628
			return (-1);
629
		}
630
		ikeauth.auth_method = msg->msg_auth.id_type;
631
632
		if ((authmsg = ikev2_msg_auth(env, sa,
633
		    sa->sa_hdr.sh_initiator)) == NULL) {
634
			log_debug("%s: failed to get auth data", __func__);
635
			return (-1);
636
		}
637
638
		ret = ikev2_msg_authverify(env, sa, &ikeauth,
639
		    ibuf_data(msg->msg_auth.id_buf),
640
		    ibuf_length(msg->msg_auth.id_buf),
641
		    authmsg);
642
		ibuf_release(authmsg);
643
644
		if (ret != 0) {
645
			log_debug("%s: ikev2_msg_authverify failed", __func__);
646
			ikev2_send_auth_failed(env, sa);
647
			return (-1);
648
		}
649
650
		if (sa->sa_eapmsk != NULL) {
651
			if ((authmsg = ikev2_msg_auth(env, sa,
652
			    !sa->sa_hdr.sh_initiator)) == NULL) {
653
				log_debug("%s: failed to get auth data",
654
				    __func__);
655
				return (-1);
656
			}
657
658
			/* XXX 2nd AUTH for EAP messages */
659
			ret = ikev2_msg_authsign(env, sa, &ikeauth, authmsg);
660
			ibuf_release(authmsg);
661
662
			if (ret != 0) {
663
				/* XXX */
664
				return (-1);
665
			}
666
667
			/* ikev2_msg_authverify verified AUTH */
668
			sa_stateflags(sa, IKED_REQ_AUTHVALID);
669
			sa_stateflags(sa, IKED_REQ_EAPVALID);
670
671
			sa_state(env, sa, IKEV2_STATE_EAP_SUCCESS);
672
		}
673
	}
674
675
	if (!TAILQ_EMPTY(&msg->msg_proposals)) {
676
		if (ikev2_sa_negotiate(&sa->sa_proposals,
677
		    &sa->sa_policy->pol_proposals, &msg->msg_proposals,
678
		    0) != 0) {
679
			log_info("%s: no proposal chosen", __func__);
680
			msg->msg_error = IKEV2_N_NO_PROPOSAL_CHOSEN;
681
			return (-1);
682
		} else
683
			sa_stateflags(sa, IKED_REQ_SA);
684
	}
685
686
	return ikev2_ike_auth(env, sa);
687
}
688
689
int
690
ikev2_ike_auth(struct iked *env, struct iked_sa *sa)
691
{
692
	struct iked_policy	*pol = sa->sa_policy;
693
	uint8_t			 certreqtype;
694
695
	/* Attempt state transition */
696
	if (sa->sa_state == IKEV2_STATE_EAP_SUCCESS)
697
		sa_state(env, sa, IKEV2_STATE_EAP_VALID);
698
	else if (sa->sa_state == IKEV2_STATE_AUTH_SUCCESS)
699
		sa_state(env, sa, IKEV2_STATE_VALID);
700
701
	if (sa->sa_hdr.sh_initiator) {
702
		if (sa_stateok(sa, IKEV2_STATE_AUTH_SUCCESS))
703
			return (ikev2_init_done(env, sa));
704
		else
705
			return (ikev2_init_ike_auth(env, sa));
706
	}
707
708
	/*
709
	 * If we have to send a local certificate but did not receive an
710
	 * optional CERTREQ, use our own certreq to find a local certificate.
711
	 * We could alternatively extract the CA from the peer certificate
712
	 * to find a matching local one.
713
	 */
714
	if (sa->sa_statevalid & IKED_REQ_CERT) {
715
		if ((sa->sa_stateflags & IKED_REQ_CERTREQ) == 0) {
716
			log_debug("%s: no CERTREQ, using default", __func__);
717
			if (pol->pol_certreqtype)
718
				certreqtype = pol->pol_certreqtype;
719
			else
720
				certreqtype = env->sc_certreqtype;
721
			return (ca_setreq(env, sa,
722
			    &pol->pol_localid, certreqtype,
723
			    ibuf_data(env->sc_certreq),
724
			    ibuf_size(env->sc_certreq), PROC_CERT));
725
		} else if ((sa->sa_stateflags & IKED_REQ_CERT) == 0)
726
			return (0);	/* ignored, wait for cert */
727
	}
728
729
	return (ikev2_resp_ike_auth(env, sa));
730
}
731
732
void
733
ikev2_init_recv(struct iked *env, struct iked_message *msg,
734
    struct ike_header *hdr)
735
{
736
	struct iked_sa		*sa;
737
	in_port_t		 port;
738
	struct iked_socket	*sock;
739
	struct iked_policy	*pol;
740
741
	if (ikev2_msg_valid_ike_sa(env, hdr, msg) == -1) {
742
		log_debug("%s: unknown SA", __func__);
743
		return;
744
	}
745
	sa = msg->msg_sa;
746
747
	switch (hdr->ike_exchange) {
748
	case IKEV2_EXCHANGE_IKE_SA_INIT:
749
		/* Update the SPIs */
750
		if ((sa = sa_new(env,
751
		    betoh64(hdr->ike_ispi), betoh64(hdr->ike_rspi), 1,
752
		    NULL)) == NULL || sa != msg->msg_sa) {
753
			log_debug("%s: invalid new SA", __func__);
754
			if (sa)
755
				sa_free(env, sa);
756
		}
757
		break;
758
	case IKEV2_EXCHANGE_IKE_AUTH:
759
	case IKEV2_EXCHANGE_CREATE_CHILD_SA:
760
		if (ikev2_msg_valid_ike_sa(env, hdr, msg) == -1)
761
			return;
762
		break;
763
	case IKEV2_EXCHANGE_INFORMATIONAL:
764
		break;
765
	default:
766
		log_debug("%s: unsupported exchange: %s", __func__,
767
		    print_map(hdr->ike_exchange, ikev2_exchange_map));
768
		return;
769
	}
770
771
	if (ikev2_pld_parse(env, hdr, msg, msg->msg_offset) != 0) {
772
		log_debug("%s: failed to parse message", __func__);
773
		return;
774
	}
775
776
	if (!ikev2_msg_frompeer(msg))
777
		return;
778
779
	if (sa->sa_udpencap && sa->sa_natt == 0 &&
780
	    (sock = ikev2_msg_getsocket(env,
781
	    sa->sa_local.addr_af, 1)) != NULL) {
782
		/*
783
		 * Update address information and use the NAT-T
784
		 * port and socket, if available.
785
		 */
786
		port = htons(socket_getport(
787
		    (struct sockaddr *)&sock->sock_addr));
788
		sa->sa_local.addr_port = port;
789
		sa->sa_peer.addr_port = port;
790
		(void)socket_af((struct sockaddr *)&sa->sa_local.addr, port);
791
		(void)socket_af((struct sockaddr *)&sa->sa_peer.addr, port);
792
793
		msg->msg_fd = sa->sa_fd = sock->sock_fd;
794
		msg->msg_sock = sock;
795
		sa->sa_natt = 1;
796
797
		log_debug("%s: NAT detected, updated SA to "
798
		    "peer %s local %s", __func__,
799
		    print_host((struct sockaddr *)&sa->sa_peer.addr, NULL, 0),
800
		    print_host((struct sockaddr *)&sa->sa_local.addr, NULL, 0));
801
	}
802
803
	switch (hdr->ike_exchange) {
804
	case IKEV2_EXCHANGE_IKE_SA_INIT:
805
		if (ibuf_length(msg->msg_cookie)) {
806
			pol = sa->sa_policy;
807
			if (ikev2_init_ike_sa_peer(env, pol,
808
			    &pol->pol_peer, msg) != 0)
809
				log_warnx("%s: failed to initiate a "
810
				    "IKE_SA_INIT exchange", __func__);
811
			break;
812
		}
813
		(void)ikev2_init_auth(env, msg);
814
		break;
815
	case IKEV2_EXCHANGE_IKE_AUTH:
816
		(void)ikev2_ike_auth_recv(env, sa, msg);
817
		break;
818
	case IKEV2_EXCHANGE_CREATE_CHILD_SA:
819
		(void)ikev2_init_create_child_sa(env, msg);
820
		break;
821
	case IKEV2_EXCHANGE_INFORMATIONAL:
822
		sa->sa_stateflags &= ~IKED_REQ_INF;
823
		break;
824
	default:
825
		log_debug("%s: exchange %s not implemented", __func__,
826
		    print_map(hdr->ike_exchange, ikev2_exchange_map));
827
		break;
828
	}
829
}
830
831
void
832
ikev2_init_ike_sa(struct iked *env, void *arg)
833
{
834
	struct iked_policy	*pol;
835
836
	TAILQ_FOREACH(pol, &env->sc_policies, pol_entry) {
837
		if ((pol->pol_flags & IKED_POLICY_ACTIVE) == 0)
838
			continue;
839
		if (!TAILQ_EMPTY(&pol->pol_sapeers)) {
840
			log_debug("%s: \"%s\" is already active",
841
			    __func__, pol->pol_name);
842
			continue;
843
		}
844
845
		log_debug("%s: initiating \"%s\"", __func__, pol->pol_name);
846
847
		if (ikev2_init_ike_sa_peer(env, pol, &pol->pol_peer, NULL))
848
			log_debug("%s: failed to initiate with peer %s",
849
			    __func__,
850
			    print_host((struct sockaddr *)&pol->pol_peer.addr,
851
			    NULL, 0));
852
	}
853
854
	timer_set(env, &env->sc_inittmr, ikev2_init_ike_sa, NULL);
855
	timer_add(env, &env->sc_inittmr, IKED_INITIATOR_INTERVAL);
856
}
857
858
void
859
ikev2_init_ike_sa_timeout(struct iked *env, void *arg)
860
{
861
	struct iked_sa	 *sa = arg;
862
863
	log_debug("%s: ispi %s rspi %s", __func__,
864
	    print_spi(sa->sa_hdr.sh_ispi, 8),
865
	    print_spi(sa->sa_hdr.sh_rspi, 8));
866
867
	sa_free(env, sa);
868
}
869
870
int
871
ikev2_init_ike_sa_peer(struct iked *env, struct iked_policy *pol,
872
    struct iked_addr *peer, struct iked_message *retry)
873
{
874
	struct sockaddr_storage		 ss;
875
	struct iked_message		 req;
876
	struct ike_header		*hdr;
877
	struct ikev2_payload		*pld;
878
	struct ikev2_keyexchange	*ke;
879
	struct ikev2_notify		*n;
880
	struct iked_sa			*sa = NULL;
881
	struct ibuf			*buf, *cookie = NULL;
882
	struct group			*group;
883
	ssize_t				 len;
884
	int				 ret = -1;
885
	struct iked_socket		*sock;
886
	in_port_t			 port;
887
888
	if ((sock = ikev2_msg_getsocket(env, peer->addr_af, 0)) == NULL)
889
		return (-1);
890
891
	if (retry != NULL) {
892
		sa = retry->msg_sa;
893
		cookie = retry->msg_cookie;
894
		sa_state(env, sa, IKEV2_STATE_INIT);
895
	}
896
897
	/* Create a new initiator SA */
898
	if (sa == NULL &&
899
	    (sa = sa_new(env, 0, 0, 1, pol)) == NULL)
900
		return (-1);
901
902
	/* Pick peer's DH group if asked */
903
	if (pol->pol_peerdh > 0 && sa->sa_dhgroup == NULL &&
904
	    (sa->sa_dhgroup = group_get(pol->pol_peerdh)) == NULL) {
905
		log_warnx("%s: invalid peer DH group %u", __func__,
906
		    pol->pol_peerdh);
907
		goto closeonly;
908
	}
909
	sa->sa_reqid = 0;
910
911
	if (ikev2_sa_initiator(env, sa, NULL, NULL) == -1)
912
		goto closeonly;
913
914
	if (pol->pol_local.addr.ss_family == AF_UNSPEC) {
915
		if (socket_getaddr(sock->sock_fd, &ss) == -1)
916
			goto closeonly;
917
	} else
918
		memcpy(&ss, &pol->pol_local.addr, pol->pol_local.addr.ss_len);
919
920
	if ((buf = ikev2_msg_init(env, &req, &peer->addr, peer->addr.ss_len,
921
	    &ss, ss.ss_len, 0)) == NULL)
922
		goto done;
923
924
	/* Inherit the port from the 1st send socket */
925
	port = htons(socket_getport((struct sockaddr *)&sock->sock_addr));
926
	(void)socket_af((struct sockaddr *)&req.msg_local, port);
927
	(void)socket_af((struct sockaddr *)&req.msg_peer, port);
928
929
	req.msg_fd = sock->sock_fd;
930
	req.msg_sa = sa;
931
	req.msg_sock = sock;
932
	req.msg_msgid = ikev2_msg_id(env, sa);
933
934
	/* IKE header */
935
	if ((hdr = ikev2_add_header(buf, sa, req.msg_msgid,
936
	    cookie == NULL ? IKEV2_PAYLOAD_SA : IKEV2_PAYLOAD_NOTIFY,
937
	    IKEV2_EXCHANGE_IKE_SA_INIT, 0)) == NULL)
938
		goto done;
939
940
	/* Reflect COOKIE */
941
	if (cookie) {
942
		if ((pld = ikev2_add_payload(buf)) == NULL)
943
			goto done;
944
		if ((n = ibuf_advance(buf, sizeof(*n))) == NULL)
945
			goto done;
946
		n->n_protoid = IKEV2_SAPROTO_NONE;
947
		n->n_spisize = 0;
948
		n->n_type = htobe16(IKEV2_N_COOKIE);
949
		if (ikev2_add_buf(buf, cookie) == -1)
950
			goto done;
951
		len = sizeof(*n) + ibuf_size(cookie);
952
953
		log_debug("%s: added cookie, len %zu", __func__,
954
		    ibuf_size(cookie));
955
		print_hex(ibuf_data(cookie), 0, ibuf_size(cookie));
956
957
		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_SA) == -1)
958
			goto done;
959
	}
960
961
	/* SA payload */
962
	if ((pld = ikev2_add_payload(buf)) == NULL)
963
		goto done;
964
	if ((len = ikev2_add_proposals(env, sa, buf, &pol->pol_proposals,
965
	    IKEV2_SAPROTO_IKE, sa->sa_hdr.sh_initiator, 0)) == -1)
966
		goto done;
967
968
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_KE) == -1)
969
		goto done;
970
971
	/* KE payload */
972
	if ((pld = ikev2_add_payload(buf)) == NULL)
973
		goto done;
974
	if ((ke = ibuf_advance(buf, sizeof(*ke))) == NULL)
975
		goto done;
976
	if ((group = sa->sa_dhgroup) == NULL) {
977
		log_debug("%s: invalid dh", __func__);
978
		goto done;
979
	}
980
	ke->kex_dhgroup = htobe16(group->id);
981
	if (ikev2_add_buf(buf, sa->sa_dhiexchange) == -1)
982
		goto done;
983
	len = sizeof(*ke) + dh_getlen(group);
984
985
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONCE) == -1)
986
		goto done;
987
988
	/* NONCE payload */
989
	if ((pld = ikev2_add_payload(buf)) == NULL)
990
		goto done;
991
	if (ikev2_add_buf(buf, sa->sa_inonce) == -1)
992
		goto done;
993
	len = ibuf_size(sa->sa_inonce);
994
995
	if ((env->sc_opts & IKED_OPT_NONATT) == 0) {
996
		if (ntohs(port) == IKED_NATT_PORT) {
997
			/* Enforce NAT-T on the initiator side */
998
			log_debug("%s: enforcing NAT-T", __func__);
999
			req.msg_natt = sa->sa_natt = 1;
1000
		}
1001
		if ((len = ikev2_add_nat_detection(env, buf, &pld, &req, len))
1002
		    == -1)
1003
			goto done;
1004
	}
1005
1006
	if ((len = ikev2_add_sighashnotify(buf, &pld, len)) == -1)
1007
		goto done;
1008
1009
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
1010
		goto done;
1011
1012
	if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
1013
		goto done;
1014
1015
	(void)ikev2_pld_parse(env, hdr, &req, 0);
1016
1017
	ibuf_release(sa->sa_1stmsg);
1018
	if ((sa->sa_1stmsg = ibuf_dup(buf)) == NULL) {
1019
		log_debug("%s: failed to copy 1st message", __func__);
1020
		goto done;
1021
	}
1022
1023
	if ((ret = ikev2_msg_send(env, &req)) == 0)
1024
		sa_state(env, sa, IKEV2_STATE_SA_INIT);
1025
1026
	/* Setup exchange timeout. */
1027
	timer_set(env, &sa->sa_timer, ikev2_init_ike_sa_timeout, sa);
1028
	timer_add(env, &sa->sa_timer, IKED_IKE_SA_EXCHANGE_TIMEOUT);
1029
1030
 done:
1031
	ikev2_msg_cleanup(env, &req);
1032
 closeonly:
1033
	if (ret == -1) {
1034
		log_debug("%s: closing SA", __func__);
1035
		sa_free(env, sa);
1036
	}
1037
1038
	return (ret);
1039
}
1040
1041
int
1042
ikev2_init_auth(struct iked *env, struct iked_message *msg)
1043
{
1044
	struct iked_sa			*sa = msg->msg_sa;
1045
	struct ibuf			*authmsg;
1046
1047
	if (sa == NULL)
1048
		return (-1);
1049
1050
	if (ikev2_sa_initiator(env, sa, NULL, msg) == -1) {
1051
		log_debug("%s: failed to get IKE keys", __func__);
1052
		return (-1);
1053
	}
1054
1055
	if ((authmsg = ikev2_msg_auth(env, sa,
1056
	    !sa->sa_hdr.sh_initiator)) == NULL) {
1057
		log_debug("%s: failed to get auth data", __func__);
1058
		return (-1);
1059
	}
1060
1061
	if (ca_setauth(env, sa, authmsg, PROC_CERT) == -1) {
1062
		log_debug("%s: failed to get cert", __func__);
1063
		return (-1);
1064
	}
1065
1066
	return (ikev2_init_ike_auth(env, sa));
1067
}
1068
1069
int
1070
ikev2_init_ike_auth(struct iked *env, struct iked_sa *sa)
1071
{
1072
	struct iked_policy		*pol = sa->sa_policy;
1073
	struct ikev2_payload		*pld;
1074
	struct ikev2_cert		*cert;
1075
	struct ikev2_auth		*auth;
1076
	struct iked_id			*id, *certid;
1077
	struct ibuf			*e = NULL;
1078
	uint8_t				 firstpayload;
1079
	int				 ret = -1;
1080
	ssize_t				 len;
1081
1082
	if (!sa_stateok(sa, IKEV2_STATE_SA_INIT))
1083
		return (0);
1084
1085
	if (!sa->sa_localauth.id_type) {
1086
		log_debug("%s: no local auth", __func__);
1087
		return (-1);
1088
	}
1089
1090
	/* New encrypted message buffer */
1091
	if ((e = ibuf_static()) == NULL)
1092
		goto done;
1093
1094
	id = &sa->sa_iid;
1095
	certid = &sa->sa_icert;
1096
1097
	/* ID payload */
1098
	if ((pld = ikev2_add_payload(e)) == NULL)
1099
		goto done;
1100
	firstpayload = IKEV2_PAYLOAD_IDi;
1101
	if (ibuf_cat(e, id->id_buf) != 0)
1102
		goto done;
1103
	len = ibuf_size(id->id_buf);
1104
1105
	/* CERT payload */
1106
	if ((sa->sa_stateinit & IKED_REQ_CERT) &&
1107
	    (certid->id_type != IKEV2_CERT_NONE)) {
1108
		if (ikev2_next_payload(pld, len,
1109
		    IKEV2_PAYLOAD_CERT) == -1)
1110
			goto done;
1111
		if ((pld = ikev2_add_payload(e)) == NULL)
1112
			goto done;
1113
		if ((cert = ibuf_advance(e, sizeof(*cert))) == NULL)
1114
			goto done;
1115
		cert->cert_type = certid->id_type;
1116
		if (ibuf_cat(e, certid->id_buf) != 0)
1117
			goto done;
1118
		len = ibuf_size(certid->id_buf) + sizeof(*cert);
1119
1120
		/* CERTREQ payload(s) */
1121
		if ((len = ikev2_add_certreq(e, &pld,
1122
		    len, env->sc_certreq, env->sc_certreqtype)) == -1)
1123
			goto done;
1124
1125
		if (env->sc_certreqtype != pol->pol_certreqtype &&
1126
		    (len = ikev2_add_certreq(e, &pld,
1127
		    len, NULL, pol->pol_certreqtype)) == -1)
1128
			goto done;
1129
	}
1130
1131
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_AUTH) == -1)
1132
		goto done;
1133
1134
	/* AUTH payload */
1135
	if ((pld = ikev2_add_payload(e)) == NULL)
1136
		goto done;
1137
	if ((auth = ibuf_advance(e, sizeof(*auth))) == NULL)
1138
		goto done;
1139
	auth->auth_method = sa->sa_localauth.id_type;
1140
	if (ibuf_cat(e, sa->sa_localauth.id_buf) != 0)
1141
		goto done;
1142
	len = ibuf_size(sa->sa_localauth.id_buf) + sizeof(*auth);
1143
1144
	/* CP payload */
1145
	if (sa->sa_cp) {
1146
		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_CP) == -1)
1147
			goto done;
1148
1149
		if ((pld = ikev2_add_payload(e)) == NULL)
1150
			goto done;
1151
		if ((len = ikev2_add_cp(env, sa, e)) == -1)
1152
			goto done;
1153
	}
1154
1155
	/* compression */
1156
	if ((pol->pol_flags & IKED_POLICY_IPCOMP) &&
1157
	    (len = ikev2_add_ipcompnotify(env, e, &pld, len, sa)) == -1)
1158
		goto done;
1159
1160
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_SA) == -1)
1161
		goto done;
1162
1163
	/* SA payload */
1164
	if ((pld = ikev2_add_payload(e)) == NULL)
1165
		goto done;
1166
	if ((len = ikev2_add_proposals(env, sa, e, &pol->pol_proposals, 0,
1167
	    sa->sa_hdr.sh_initiator, 0)) == -1)
1168
		goto done;
1169
1170
	if ((len = ikev2_add_ts(e, &pld, len, sa, 0)) == -1)
1171
		goto done;
1172
1173
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
1174
		goto done;
1175
1176
	ret = ikev2_msg_send_encrypt(env, sa, &e,
1177
	    IKEV2_EXCHANGE_IKE_AUTH, firstpayload, 0);
1178
1179
 done:
1180
	ibuf_release(e);
1181
1182
	return (ret);
1183
}
1184
1185
int
1186
ikev2_init_done(struct iked *env, struct iked_sa *sa)
1187
{
1188
	int		 ret;
1189
1190
	if (!sa_stateok(sa, IKEV2_STATE_VALID))
1191
		return (0);	/* ignored */
1192
1193
	ret = ikev2_childsa_negotiate(env, sa, &sa->sa_kex, &sa->sa_proposals,
1194
	    sa->sa_hdr.sh_initiator, 0, 0);
1195
	if (ret == 0)
1196
		ret = ikev2_childsa_enable(env, sa);
1197
	if (ret == 0) {
1198
		sa_state(env, sa, IKEV2_STATE_ESTABLISHED);
1199
		/* Delete exchange timeout. */
1200
		timer_del(env, &sa->sa_timer);
1201
		timer_set(env, &sa->sa_timer, ikev2_ike_sa_alive, sa);
1202
		timer_add(env, &sa->sa_timer, IKED_IKE_SA_ALIVE_TIMEOUT);
1203
		timer_set(env, &sa->sa_keepalive, ikev2_ike_sa_keepalive, sa);
1204
		if (sa->sa_usekeepalive)
1205
			timer_add(env, &sa->sa_keepalive,
1206
			    IKED_IKE_SA_KEEPALIVE_TIMEOUT);
1207
		timer_set(env, &sa->sa_rekey, ikev2_ike_sa_rekey, sa);
1208
		if (sa->sa_policy->pol_rekey)
1209
			ikev2_ike_sa_rekey_schedule(env, sa);
1210
	}
1211
1212
	if (ret)
1213
		ikev2_childsa_delete(env, sa, 0, 0, NULL, 1);
1214
	return (ret);
1215
}
1216
1217
int
1218
ikev2_policy2id(struct iked_static_id *polid, struct iked_id *id, int srcid)
1219
{
1220
	struct ikev2_id		 hdr;
1221
	struct iked_static_id	 localpid;
1222
	char			 idstr[IKED_ID_SIZE];
1223
	struct in_addr		 in4;
1224
	struct in6_addr		 in6;
1225
	X509_NAME		*name = NULL;
1226
	uint8_t			*p;
1227
	int			 len;
1228
1229
	/* Fixup the local Id if not specified */
1230
	if (srcid && polid->id_type == 0) {
1231
		polid = &localpid;
1232
		bzero(polid, sizeof(*polid));
1233
1234
		/* Create a default local ID based on our FQDN */
1235
		polid->id_type = IKEV2_ID_FQDN;
1236
		if (gethostname((char *)polid->id_data,
1237
		    sizeof(polid->id_data)) != 0)
1238
			return (-1);
1239
		polid->id_offset = 0;
1240
		polid->id_length =
1241
		    strlen((char *)polid->id_data); /* excluding NUL */
1242
	}
1243
1244
	if (!polid->id_length)
1245
		return (-1);
1246
1247
	/* Create an IKEv2 ID payload */
1248
	bzero(&hdr, sizeof(hdr));
1249
	hdr.id_type = id->id_type = polid->id_type;
1250
	id->id_offset = sizeof(hdr);
1251
1252
	if ((id->id_buf = ibuf_new(&hdr, sizeof(hdr))) == NULL)
1253
		return (-1);
1254
1255
	switch (id->id_type) {
1256
	case IKEV2_ID_IPV4:
1257
		if (inet_pton(AF_INET, (char *)polid->id_data, &in4) != 1 ||
1258
		    ibuf_add(id->id_buf, &in4, sizeof(in4)) != 0) {
1259
			ibuf_release(id->id_buf);
1260
			id->id_buf = NULL;
1261
			return (-1);
1262
		}
1263
		break;
1264
	case IKEV2_ID_IPV6:
1265
		if (inet_pton(AF_INET6, (char *)polid->id_data, &in6) != 1 ||
1266
		    ibuf_add(id->id_buf, &in6, sizeof(in6)) != 0) {
1267
			ibuf_release(id->id_buf);
1268
			id->id_buf = NULL;
1269
			return (-1);
1270
		}
1271
		break;
1272
	case IKEV2_ID_ASN1_DN:
1273
		/* policy has ID in string-format, convert to ASN1 */
1274
		if ((name = ca_x509_name_parse(polid->id_data)) == NULL ||
1275
		    (len = i2d_X509_NAME(name, NULL)) < 0 ||
1276
		    (p = ibuf_reserve(id->id_buf, len)) == NULL ||
1277
		    (i2d_X509_NAME(name, &p)) < 0) {
1278
			if (name)
1279
				X509_NAME_free(name);
1280
			ibuf_release(id->id_buf);
1281
			id->id_buf = NULL;
1282
			return (-1);
1283
		}
1284
		X509_NAME_free(name);
1285
		break;
1286
	default:
1287
		if (ibuf_add(id->id_buf,
1288
		    polid->id_data, polid->id_length) != 0) {
1289
			ibuf_release(id->id_buf);
1290
			id->id_buf = NULL;
1291
			return (-1);
1292
		}
1293
		break;
1294
	}
1295
1296
	if (ikev2_print_id(id, idstr, sizeof(idstr)) == -1)
1297
		return (-1);
1298
1299
	log_debug("%s: %s %s length %zu", __func__,
1300
	    srcid ? "srcid" : "dstid",
1301
	    idstr, ibuf_size(id->id_buf));
1302
1303
	return (0);
1304
}
1305
1306
struct ike_header *
1307
ikev2_add_header(struct ibuf *buf, struct iked_sa *sa,
1308
    uint32_t msgid, uint8_t nextpayload,
1309
    uint8_t exchange, uint8_t flags)
1310
{
1311
	struct ike_header	*hdr;
1312
1313
	if ((hdr = ibuf_advance(buf, sizeof(*hdr))) == NULL) {
1314
		log_debug("%s: failed to add header", __func__);
1315
		return (NULL);
1316
	}
1317
1318
	hdr->ike_ispi = htobe64(sa->sa_hdr.sh_ispi);
1319
	hdr->ike_rspi = htobe64(sa->sa_hdr.sh_rspi);
1320
	hdr->ike_nextpayload = nextpayload;
1321
	hdr->ike_version = IKEV2_VERSION;
1322
	hdr->ike_exchange = exchange;
1323
	hdr->ike_msgid = htobe32(msgid);
1324
	hdr->ike_length = htobe32(sizeof(*hdr));
1325
	hdr->ike_flags = flags;
1326
1327
	if (sa->sa_hdr.sh_initiator)
1328
		hdr->ike_flags |= IKEV2_FLAG_INITIATOR;
1329
1330
	return (hdr);
1331
}
1332
1333
int
1334
ikev2_set_header(struct ike_header *hdr, size_t length)
1335
{
1336
	uint32_t	 hdrlength = sizeof(*hdr) + length;
1337
1338
	if (hdrlength > UINT32_MAX) {
1339
		log_debug("%s: message too long", __func__);
1340
		return (-1);
1341
	}
1342
1343
	hdr->ike_length = htobe32(sizeof(*hdr) + length);
1344
1345
	return (0);
1346
}
1347
1348
struct ikev2_payload *
1349
ikev2_add_payload(struct ibuf *buf)
1350
{
1351
	struct ikev2_payload	*pld;
1352
1353
	if ((pld = ibuf_advance(buf, sizeof(*pld))) == NULL) {
1354
		log_debug("%s: failed to add payload", __func__);
1355
		return (NULL);
1356
	}
1357
1358
	pld->pld_nextpayload = IKEV2_PAYLOAD_NONE;
1359
	pld->pld_length = sizeof(*pld);
1360
1361
	return (pld);
1362
}
1363
1364
ssize_t
1365
ikev2_add_ts_payload(struct ibuf *buf, unsigned int type, struct iked_sa *sa)
1366
{
1367
	struct iked_policy	*pol = sa->sa_policy;
1368
	struct ikev2_tsp	*tsp;
1369
	struct ikev2_ts		*ts;
1370
	struct iked_flow	*flow;
1371
	struct iked_addr	*addr;
1372
	struct iked_addr	 pooladdr;
1373
	uint8_t			*ptr;
1374
	size_t			 len = 0;
1375
	uint32_t		 av[4], bv[4], mv[4];
1376
	struct sockaddr_in	*in4;
1377
	struct sockaddr_in6	*in6;
1378
1379
	if ((tsp = ibuf_advance(buf, sizeof(*tsp))) == NULL)
1380
		return (-1);
1381
	tsp->tsp_count = pol->pol_nflows;
1382
	len = sizeof(*tsp);
1383
1384
	RB_FOREACH(flow, iked_flows, &pol->pol_flows) {
1385
		if ((ts = ibuf_advance(buf, sizeof(*ts))) == NULL)
1386
			return (-1);
1387
1388
		if (type == IKEV2_PAYLOAD_TSi) {
1389
			if (sa->sa_hdr.sh_initiator)
1390
				addr = &flow->flow_src;
1391
			else
1392
				addr = &flow->flow_dst;
1393
		} else if (type == IKEV2_PAYLOAD_TSr) {
1394
			if (sa->sa_hdr.sh_initiator)
1395
				addr = &flow->flow_dst;
1396
			else
1397
				addr = &flow->flow_src;
1398
		} else
1399
			return (-1);
1400
1401
		/* patch remote address (if configured to 0.0.0.0) */
1402
		if ((type == IKEV2_PAYLOAD_TSi && !sa->sa_hdr.sh_initiator) ||
1403
		    (type == IKEV2_PAYLOAD_TSr && sa->sa_hdr.sh_initiator)) {
1404
			if (ikev2_cp_fixaddr(sa, addr, &pooladdr) != -1)
1405
				addr = &pooladdr;
1406
		}
1407
1408
		ts->ts_protoid = flow->flow_ipproto;
1409
1410
		if (addr->addr_port) {
1411
			ts->ts_startport = addr->addr_port;
1412
			ts->ts_endport = addr->addr_port;
1413
		} else {
1414
			ts->ts_startport = 0;
1415
			ts->ts_endport = 0xffff;
1416
		}
1417
1418
		switch (addr->addr_af) {
1419
		case AF_INET:
1420
			ts->ts_type = IKEV2_TS_IPV4_ADDR_RANGE;
1421
			ts->ts_length = htobe16(sizeof(*ts) + 8);
1422
1423
			if ((ptr = ibuf_advance(buf, 8)) == NULL)
1424
				return (-1);
1425
1426
			in4 = (struct sockaddr_in *)&addr->addr;
1427
			if (addr->addr_net) {
1428
				/* Convert IPv4 network to address range */
1429
				mv[0] = prefixlen2mask(addr->addr_mask);
1430
				av[0] = in4->sin_addr.s_addr & mv[0];
1431
				bv[0] = in4->sin_addr.s_addr | ~mv[0];
1432
			} else
1433
				av[0] = bv[0] = in4->sin_addr.s_addr;
1434
1435
			memcpy(ptr, &av[0], 4);
1436
			memcpy(ptr + 4, &bv[0], 4);
1437
			break;
1438
		case AF_INET6:
1439
			ts->ts_type = IKEV2_TS_IPV6_ADDR_RANGE;
1440
			ts->ts_length = htobe16(sizeof(*ts) + 32);
1441
1442
			if ((ptr = ibuf_advance(buf, 32)) == NULL)
1443
				return (-1);
1444
1445
			in6 = (struct sockaddr_in6 *)&addr->addr;
1446
1447
			memcpy(&av, &in6->sin6_addr.s6_addr, 16);
1448
			memcpy(&bv, &in6->sin6_addr.s6_addr, 16);
1449
			if (addr->addr_net) {
1450
				/* Convert IPv6 network to address range */
1451
				prefixlen2mask6(addr->addr_mask, mv);
1452
				av[0] &= mv[0];
1453
				av[1] &= mv[1];
1454
				av[2] &= mv[2];
1455
				av[3] &= mv[3];
1456
				bv[0] |= ~mv[0];
1457
				bv[1] |= ~mv[1];
1458
				bv[2] |= ~mv[2];
1459
				bv[3] |= ~mv[3];
1460
			}
1461
1462
			memcpy(ptr, &av, 16);
1463
			memcpy(ptr + 16, &bv, 16);
1464
			break;
1465
		}
1466
1467
		len += betoh16(ts->ts_length);
1468
	}
1469
1470
	return (len);
1471
}
1472
1473
ssize_t
1474
ikev2_add_ts(struct ibuf *e, struct ikev2_payload **pld, ssize_t len,
1475
    struct iked_sa *sa, int reverse)
1476
{
1477
	if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_TSi) == -1)
1478
		return (-1);
1479
1480
	/* TSi payload */
1481
	if ((*pld = ikev2_add_payload(e)) == NULL)
1482
		return (-1);
1483
	if ((len = ikev2_add_ts_payload(e, reverse ? IKEV2_PAYLOAD_TSr :
1484
	    IKEV2_PAYLOAD_TSi, sa)) == -1)
1485
		return (-1);
1486
1487
	if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_TSr) == -1)
1488
		return (-1);
1489
1490
	/* TSr payload */
1491
	if ((*pld = ikev2_add_payload(e)) == NULL)
1492
		return (-1);
1493
	if ((len = ikev2_add_ts_payload(e, reverse ? IKEV2_PAYLOAD_TSi :
1494
	    IKEV2_PAYLOAD_TSr, sa)) == -1)
1495
		return (-1);
1496
1497
	return (len);
1498
}
1499
1500
1501
ssize_t
1502
ikev2_add_certreq(struct ibuf *e, struct ikev2_payload **pld, ssize_t len,
1503
    struct ibuf *certreq, uint8_t type)
1504
{
1505
	struct ikev2_cert	*cert;
1506
1507
	if (type == IKEV2_CERT_NONE)
1508
		return (len);
1509
1510
	if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_CERTREQ) == -1)
1511
		return (-1);
1512
1513
	/* CERTREQ payload */
1514
	if ((*pld = ikev2_add_payload(e)) == NULL)
1515
		return (-1);
1516
1517
	if ((cert = ibuf_advance(e, sizeof(*cert))) == NULL)
1518
		return (-1);
1519
1520
	cert->cert_type = type;
1521
	len = sizeof(*cert);
1522
1523
	if (certreq != NULL && cert->cert_type == IKEV2_CERT_X509_CERT) {
1524
		if (ikev2_add_buf(e, certreq) == -1)
1525
			return (-1);
1526
		len += ibuf_size(certreq);
1527
	}
1528
1529
	log_debug("%s: type %s length %zd", __func__,
1530
	    print_map(type, ikev2_cert_map), len);
1531
1532
	return (len);
1533
}
1534
1535
ssize_t
1536
ikev2_add_ipcompnotify(struct iked *env, struct ibuf *e,
1537
    struct ikev2_payload **pld, ssize_t len, struct iked_sa *sa)
1538
{
1539
	struct iked_childsa		 csa;
1540
	struct ikev2_notify		*n;
1541
	uint8_t				*ptr;
1542
	uint16_t			 cpi;
1543
	uint32_t			 spi;
1544
	uint8_t				 transform;
1545
1546
	/* we only support deflate */
1547
	transform = IKEV2_IPCOMP_DEFLATE;
1548
1549
	bzero(&csa, sizeof(csa));
1550
	csa.csa_saproto = IKEV2_SAPROTO_IPCOMP;
1551
	csa.csa_ikesa = sa;
1552
	csa.csa_local = &sa->sa_peer;
1553
	csa.csa_peer = &sa->sa_local;
1554
1555
	if (pfkey_sa_init(env->sc_pfkey, &csa, &spi) == -1)
1556
		return (-1);
1557
	/*
1558
	 * We get spi == 0 if the kernel does not support IPcomp,
1559
	 * so just return the length of the current payload.
1560
	 */
1561
	if (spi == 0)
1562
		return (len);
1563
	cpi = htobe16((uint16_t)spi);
1564
	if (*pld)
1565
		if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_NOTIFY) == -1)
1566
			return (-1);
1567
	if ((*pld = ikev2_add_payload(e)) == NULL)
1568
		return (-1);
1569
	len = sizeof(*n) + sizeof(cpi) + sizeof(transform);
1570
	if ((ptr = ibuf_advance(e, len)) == NULL)
1571
		return (-1);
1572
	n = (struct ikev2_notify *)ptr;
1573
	n->n_protoid = 0;
1574
	n->n_spisize = 0;
1575
	n->n_type = htobe16(IKEV2_N_IPCOMP_SUPPORTED);
1576
	ptr += sizeof(*n);
1577
	memcpy(ptr, &cpi, sizeof(cpi));
1578
	ptr += sizeof(cpi);
1579
	memcpy(ptr, &transform, sizeof(transform));
1580
1581
	sa->sa_cpi_in = spi;	/* already on host byte order */
1582
	log_debug("%s: sa_cpi_in 0x%04x", __func__, sa->sa_cpi_in);
1583
1584
	return (len);
1585
}
1586
1587
ssize_t
1588
ikev2_add_sighashnotify(struct ibuf *e, struct ikev2_payload **pld,
1589
    ssize_t len)
1590
{
1591
	struct ikev2_notify		*n;
1592
	uint8_t				*ptr;
1593
	size_t				 i;
1594
	uint16_t			 hash, signature_hashes[] = {
1595
		IKEV2_SIGHASH_SHA2_256,
1596
		IKEV2_SIGHASH_SHA2_384,
1597
		IKEV2_SIGHASH_SHA2_512
1598
	};
1599
1600
	if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_NOTIFY) == -1)
1601
		return (-1);
1602
1603
	/* XXX signature_hashes are hardcoded for now */
1604
	len = sizeof(*n) + nitems(signature_hashes) * sizeof(hash);
1605
1606
	/* NOTIFY payload */
1607
	if ((*pld = ikev2_add_payload(e)) == NULL)
1608
		return (-1);
1609
	if ((ptr = ibuf_advance(e, len)) == NULL)
1610
		return (-1);
1611
1612
	n = (struct ikev2_notify *)ptr;
1613
	n->n_protoid = 0;
1614
	n->n_spisize = 0;
1615
	n->n_type = htobe16(IKEV2_N_SIGNATURE_HASH_ALGORITHMS);
1616
	ptr += sizeof(*n);
1617
1618
	for (i = 0; i < nitems(signature_hashes); i++) {
1619
		hash = htobe16(signature_hashes[i]);
1620
		memcpy(ptr, &hash, sizeof(hash));
1621
		ptr += sizeof(hash);
1622
	}
1623
1624
	return (len);
1625
}
1626
1627
int
1628
ikev2_next_payload(struct ikev2_payload *pld, size_t length,
1629
    uint8_t nextpayload)
1630
{
1631
	size_t	 pldlength = sizeof(*pld) + length;
1632
1633
	if (pldlength > UINT16_MAX) {
1634
		log_debug("%s: payload too long", __func__);
1635
		return (-1);
1636
	}
1637
1638
	log_debug("%s: length %zu nextpayload %s",
1639
	    __func__, pldlength, print_map(nextpayload, ikev2_payload_map));
1640
1641
	pld->pld_length = htobe16(pldlength);
1642
	pld->pld_nextpayload = nextpayload;
1643
1644
	return (0);
1645
}
1646
1647
ssize_t
1648
ikev2_nat_detection(struct iked *env, struct iked_message *msg,
1649
    void *ptr, size_t len, unsigned int type)
1650
{
1651
	EVP_MD_CTX		 ctx;
1652
	struct ike_header	*hdr;
1653
	uint8_t			 md[SHA_DIGEST_LENGTH];
1654
	unsigned int		 mdlen = sizeof(md);
1655
	struct iked_sa		*sa = msg->msg_sa;
1656
	struct sockaddr_in	*in4;
1657
	struct sockaddr_in6	*in6;
1658
	ssize_t			 ret = -1;
1659
	struct sockaddr		*src, *dst, *ss;
1660
	uint64_t		 rspi, ispi;
1661
	struct ibuf		*buf;
1662
	int			 frompeer = 0;
1663
	uint32_t		 rnd;
1664
1665
	if (ptr == NULL)
1666
		return (mdlen);
1667
1668
	if (ikev2_msg_frompeer(msg)) {
1669
		buf = msg->msg_parent->msg_data;
1670
		if ((hdr = ibuf_seek(buf, 0, sizeof(*hdr))) == NULL)
1671
			return (-1);
1672
		ispi = hdr->ike_ispi;
1673
		rspi = hdr->ike_rspi;
1674
		frompeer = 1;
1675
		src = (struct sockaddr *)&msg->msg_peer;
1676
		dst = (struct sockaddr *)&msg->msg_local;
1677
	} else {
1678
		ispi = htobe64(sa->sa_hdr.sh_ispi);
1679
		rspi = htobe64(sa->sa_hdr.sh_rspi);
1680
		frompeer = 0;
1681
		src = (struct sockaddr *)&msg->msg_local;
1682
		dst = (struct sockaddr *)&msg->msg_peer;
1683
	}
1684
1685
	EVP_MD_CTX_init(&ctx);
1686
	EVP_DigestInit_ex(&ctx, EVP_sha1(), NULL);
1687
1688
	switch (type) {
1689
	case IKEV2_N_NAT_DETECTION_SOURCE_IP:
1690
		log_debug("%s: %s source %s %s %s", __func__,
1691
		    frompeer ? "peer" : "local",
1692
		    print_spi(betoh64(ispi), 8),
1693
		    print_spi(betoh64(rspi), 8),
1694
		    print_host(src, NULL, 0));
1695
		ss = src;
1696
		break;
1697
	case IKEV2_N_NAT_DETECTION_DESTINATION_IP:
1698
		log_debug("%s: %s destination %s %s %s", __func__,
1699
		    frompeer ? "peer" : "local",
1700
		    print_spi(betoh64(ispi), 8),
1701
		    print_spi(betoh64(rspi), 8),
1702
		    print_host(dst, NULL, 0));
1703
		ss = dst;
1704
		break;
1705
	default:
1706
		goto done;
1707
	}
1708
1709
	EVP_DigestUpdate(&ctx, &ispi, sizeof(ispi));
1710
	EVP_DigestUpdate(&ctx, &rspi, sizeof(rspi));
1711
1712
	switch (ss->sa_family) {
1713
	case AF_INET:
1714
		in4 = (struct sockaddr_in *)ss;
1715
		EVP_DigestUpdate(&ctx, &in4->sin_addr.s_addr,
1716
		    sizeof(in4->sin_addr.s_addr));
1717
		EVP_DigestUpdate(&ctx, &in4->sin_port,
1718
		    sizeof(in4->sin_port));
1719
		break;
1720
	case AF_INET6:
1721
		in6 = (struct sockaddr_in6 *)ss;
1722
		EVP_DigestUpdate(&ctx, &in6->sin6_addr.s6_addr,
1723
		    sizeof(in6->sin6_addr.s6_addr));
1724
		EVP_DigestUpdate(&ctx, &in6->sin6_port,
1725
		    sizeof(in6->sin6_port));
1726
		break;
1727
	default:
1728
		goto done;
1729
	}
1730
1731
	if (env->sc_opts & IKED_OPT_NATT) {
1732
		/* Enforce NAT-T/UDP-encapsulation by distorting the digest */
1733
		rnd = arc4random();
1734
		EVP_DigestUpdate(&ctx, &rnd, sizeof(rnd));
1735
	}
1736
1737
	EVP_DigestFinal_ex(&ctx, md, &mdlen);
1738
1739
	if (len < mdlen)
1740
		goto done;
1741
1742
	memcpy(ptr, md, mdlen);
1743
	ret = mdlen;
1744
 done:
1745
	EVP_MD_CTX_cleanup(&ctx);
1746
1747
	return (ret);
1748
}
1749
1750
ssize_t
1751
ikev2_add_nat_detection(struct iked *env, struct ibuf *buf,
1752
    struct ikev2_payload **pld, struct iked_message *msg, ssize_t len)
1753
{
1754
	struct ikev2_notify		*n;
1755
	uint8_t			*ptr;
1756
1757
	/* *pld is NULL if there is no previous payload */
1758
	if (*pld != NULL) {
1759
		if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_NOTIFY) == -1)
1760
			return (-1);
1761
	}
1762
	/* NAT-T notify payloads */
1763
	if ((*pld = ikev2_add_payload(buf)) == NULL)
1764
		return (-1);
1765
	if ((n = ibuf_advance(buf, sizeof(*n))) == NULL)
1766
		return (-1);
1767
	n->n_type = htobe16(IKEV2_N_NAT_DETECTION_SOURCE_IP);
1768
	len = ikev2_nat_detection(env, msg, NULL, 0, 0);
1769
	if ((ptr = ibuf_advance(buf, len)) == NULL)
1770
		return (-1);
1771
	if ((len = ikev2_nat_detection(env, msg, ptr, len,
1772
	    betoh16(n->n_type))) == -1)
1773
		return (-1);
1774
	len += sizeof(*n);
1775
1776
	if (ikev2_next_payload(*pld, len, IKEV2_PAYLOAD_NOTIFY) == -1)
1777
		return (-1);
1778
1779
	if ((*pld = ikev2_add_payload(buf)) == NULL)
1780
		return (-1);
1781
	if ((n = ibuf_advance(buf, sizeof(*n))) == NULL)
1782
		return (-1);
1783
	n->n_type = htobe16(IKEV2_N_NAT_DETECTION_DESTINATION_IP);
1784
	len = ikev2_nat_detection(env, msg, NULL, 0, 0);
1785
	if ((ptr = ibuf_advance(buf, len)) == NULL)
1786
		return (-1);
1787
	if ((len = ikev2_nat_detection(env, msg, ptr, len,
1788
	    betoh16(n->n_type))) == -1)
1789
		return (-1);
1790
	len += sizeof(*n);
1791
	return (len);
1792
}
1793
1794
ssize_t
1795
ikev2_add_cp(struct iked *env, struct iked_sa *sa, struct ibuf *buf)
1796
{
1797
	struct iked_policy	*pol = sa->sa_policy;
1798
	struct ikev2_cp		*cp;
1799
	struct ikev2_cfg	*cfg;
1800
	struct iked_cfg		*ikecfg;
1801
	unsigned int		 i;
1802
	uint32_t		 mask4;
1803
	size_t			 len;
1804
	struct sockaddr_in	*in4;
1805
	struct sockaddr_in6	*in6;
1806
	uint8_t			 prefixlen;
1807
1808
	if ((cp = ibuf_advance(buf, sizeof(*cp))) == NULL)
1809
		return (-1);
1810
	len = sizeof(*cp);
1811
1812
	switch (sa->sa_cp) {
1813
	case IKEV2_CP_REQUEST:
1814
		cp->cp_type = IKEV2_CP_REPLY;
1815
		break;
1816
	case IKEV2_CP_REPLY:
1817
	case IKEV2_CP_SET:
1818
	case IKEV2_CP_ACK:
1819
		/* Not yet supported */
1820
		return (-1);
1821
	}
1822
1823
	for (i = 0; i < pol->pol_ncfg; i++) {
1824
		ikecfg = &pol->pol_cfg[i];
1825
		if (ikecfg->cfg_action != cp->cp_type)
1826
			continue;
1827
1828
		if ((cfg = ibuf_advance(buf, sizeof(*cfg))) == NULL)
1829
			return (-1);
1830
1831
		cfg->cfg_type = htobe16(ikecfg->cfg_type);
1832
		len += sizeof(*cfg);
1833
1834
		switch (ikecfg->cfg_type) {
1835
		case IKEV2_CFG_INTERNAL_IP4_ADDRESS:
1836
		case IKEV2_CFG_INTERNAL_IP4_NETMASK:
1837
		case IKEV2_CFG_INTERNAL_IP4_DNS:
1838
		case IKEV2_CFG_INTERNAL_IP4_NBNS:
1839
		case IKEV2_CFG_INTERNAL_IP4_DHCP:
1840
		case IKEV2_CFG_INTERNAL_IP4_SERVER:
1841
			/* 4 bytes IPv4 address */
1842
			in4 = (ikecfg->cfg.address.addr_mask != 32 &&
1843
			    (ikecfg->cfg_type ==
1844
			    IKEV2_CFG_INTERNAL_IP4_ADDRESS) &&
1845
			    sa->sa_addrpool &&
1846
			    sa->sa_addrpool->addr_af == AF_INET) ?
1847
			    (struct sockaddr_in *)&sa->sa_addrpool->addr :
1848
			    (struct sockaddr_in *)&ikecfg->cfg.address.addr;
1849
			cfg->cfg_length = htobe16(4);
1850
			if (ibuf_add(buf, &in4->sin_addr.s_addr, 4) == -1)
1851
				return (-1);
1852
			len += 4;
1853
			break;
1854
		case IKEV2_CFG_INTERNAL_IP4_SUBNET:
1855
			/* 4 bytes IPv4 address + 4 bytes IPv4 mask + */
1856
			in4 = (struct sockaddr_in *)&ikecfg->cfg.address.addr;
1857
			mask4 = prefixlen2mask(ikecfg->cfg.address.addr_mask);
1858
			cfg->cfg_length = htobe16(8);
1859
			if (ibuf_add(buf, &in4->sin_addr.s_addr, 4) == -1)
1860
				return (-1);
1861
			if (ibuf_add(buf, &mask4, 4) == -1)
1862
				return (-1);
1863
			len += 8;
1864
			break;
1865
		case IKEV2_CFG_INTERNAL_IP6_DNS:
1866
		case IKEV2_CFG_INTERNAL_IP6_NBNS:
1867
		case IKEV2_CFG_INTERNAL_IP6_DHCP:
1868
		case IKEV2_CFG_INTERNAL_IP6_SERVER:
1869
			/* 16 bytes IPv6 address */
1870
			in6 = (struct sockaddr_in6 *)&ikecfg->cfg.address;
1871
			cfg->cfg_length = htobe16(16);
1872
			if (ibuf_add(buf, &in6->sin6_addr.s6_addr, 16) == -1)
1873
				return (-1);
1874
			len += 16;
1875
			break;
1876
		case IKEV2_CFG_INTERNAL_IP6_ADDRESS:
1877
		case IKEV2_CFG_INTERNAL_IP6_SUBNET:
1878
			/* 16 bytes IPv6 address + 1 byte prefix length */
1879
			in6 = (ikecfg->cfg.address.addr_mask != 128 &&
1880
			    (ikecfg->cfg_type ==
1881
			    IKEV2_CFG_INTERNAL_IP6_ADDRESS) &&
1882
			    sa->sa_addrpool6 &&
1883
			    sa->sa_addrpool6->addr_af == AF_INET6) ?
1884
			    (struct sockaddr_in6 *)&sa->sa_addrpool6->addr :
1885
			    (struct sockaddr_in6 *)&ikecfg->cfg.address.addr;
1886
			cfg->cfg_length = htobe16(17);
1887
			if (ibuf_add(buf, &in6->sin6_addr.s6_addr, 16) == -1)
1888
				return (-1);
1889
			if (ikecfg->cfg.address.addr_net)
1890
				prefixlen = ikecfg->cfg.address.addr_mask;
1891
			else
1892
				prefixlen = 128;
1893
			if (ibuf_add(buf, &prefixlen, 1) == -1)
1894
				return (-1);
1895
			len += 16 + 1;
1896
			break;
1897
		case IKEV2_CFG_APPLICATION_VERSION:
1898
			/* Reply with an empty string (non-NUL terminated) */
1899
			cfg->cfg_length = 0;
1900
			break;
1901
		}
1902
	}
1903
1904
	return (len);
1905
}
1906
1907
ssize_t
1908
ikev2_add_proposals(struct iked *env, struct iked_sa *sa, struct ibuf *buf,
1909
    struct iked_proposals *proposals, uint8_t protoid, int initiator,
1910
    int sendikespi)
1911
{
1912
	struct ikev2_sa_proposal	*sap;
1913
	struct iked_transform		*xform;
1914
	struct iked_proposal		*prop;
1915
	struct iked_childsa		 csa;
1916
	ssize_t				 length = 0, saplength, xflen;
1917
	uint64_t			 spi64;
1918
	uint32_t			 spi32, spi;
1919
	unsigned int			 i;
1920
1921
	TAILQ_FOREACH(prop, proposals, prop_entry) {
1922
		if ((protoid && prop->prop_protoid != protoid) ||
1923
		    (!protoid && prop->prop_protoid == IKEV2_SAPROTO_IKE))
1924
			continue;
1925
1926
		if (protoid != IKEV2_SAPROTO_IKE && initiator) {
1927
			bzero(&csa, sizeof(csa));
1928
			csa.csa_ikesa = sa;
1929
			csa.csa_saproto = prop->prop_protoid;
1930
			csa.csa_local = &sa->sa_peer;
1931
			csa.csa_peer = &sa->sa_local;
1932
1933
			if (pfkey_sa_init(env->sc_pfkey, &csa, &spi) == -1)
1934
				return (-1);
1935
1936
			prop->prop_localspi.spi = spi;
1937
			prop->prop_localspi.spi_size = 4;
1938
			prop->prop_localspi.spi_protoid = prop->prop_protoid;
1939
		}
1940
1941
		if ((sap = ibuf_advance(buf, sizeof(*sap))) == NULL) {
1942
			log_debug("%s: failed to add proposal", __func__);
1943
			return (-1);
1944
		}
1945
1946
		if (sendikespi) {
1947
			/* Special case for IKE SA rekeying */
1948
			prop->prop_localspi.spi = initiator ?
1949
			    sa->sa_hdr.sh_ispi : sa->sa_hdr.sh_rspi;
1950
			prop->prop_localspi.spi_size = 8;
1951
			prop->prop_localspi.spi_protoid = IKEV2_SAPROTO_IKE;
1952
		}
1953
1954
		sap->sap_proposalnr = prop->prop_id;
1955
		sap->sap_protoid = prop->prop_protoid;
1956
		sap->sap_spisize = prop->prop_localspi.spi_size;
1957
		sap->sap_transforms = prop->prop_nxforms;
1958
		saplength = sizeof(*sap);
1959
1960
		switch (prop->prop_localspi.spi_size) {
1961
		case 4:
1962
			spi32 = htobe32(prop->prop_localspi.spi);
1963
			if (ibuf_add(buf, &spi32, sizeof(spi32)) != 0)
1964
				return (-1);
1965
			saplength += 4;
1966
			break;
1967
		case 8:
1968
			spi64 = htobe64(prop->prop_localspi.spi);
1969
			if (ibuf_add(buf, &spi64, sizeof(spi64)) != 0)
1970
				return (-1);
1971
			saplength += 8;
1972
			break;
1973
		default:
1974
			break;
1975
		}
1976
1977
		for (i = 0; i < prop->prop_nxforms; i++) {
1978
			xform = prop->prop_xforms + i;
1979
1980
			if ((xflen = ikev2_add_transform(buf,
1981
			    i == prop->prop_nxforms - 1 ?
1982
			    IKEV2_XFORM_LAST : IKEV2_XFORM_MORE,
1983
			    xform->xform_type, xform->xform_id,
1984
			    xform->xform_length)) == -1)
1985
				return (-1);
1986
1987
			saplength += xflen;
1988
		}
1989
1990
		sap->sap_length = htobe16(saplength);
1991
		length += saplength;
1992
	}
1993
1994
	log_debug("%s: length %zd", __func__, length);
1995
1996
	return (length);
1997
}
1998
1999
ssize_t
2000
ikev2_add_transform(struct ibuf *buf,
2001
    uint8_t more, uint8_t type, uint16_t id, uint16_t length)
2002
{
2003
	struct ikev2_transform	*xfrm;
2004
	struct ikev2_attribute	*attr;
2005
2006
	if ((xfrm = ibuf_advance(buf, sizeof(*xfrm))) == NULL) {
2007
		log_debug("%s: failed to add transform", __func__);
2008
		return (-1);
2009
	}
2010
	xfrm->xfrm_more = more;
2011
	xfrm->xfrm_type = type;
2012
	xfrm->xfrm_id = htobe16(id);
2013
2014
	if (length) {
2015
		xfrm->xfrm_length = htobe16(sizeof(*xfrm) + sizeof(*attr));
2016
2017
		if ((attr = ibuf_advance(buf, sizeof(*attr))) == NULL) {
2018
			log_debug("%s: failed to add attribute", __func__);
2019
			return (-1);
2020
		}
2021
		attr->attr_type = htobe16(IKEV2_ATTRAF_TV |
2022
		    IKEV2_ATTRTYPE_KEY_LENGTH);
2023
		attr->attr_length = htobe16(length);
2024
	} else
2025
		xfrm->xfrm_length = htobe16(sizeof(*xfrm));
2026
2027
	return (betoh16(xfrm->xfrm_length));
2028
}
2029
2030
int
2031
ikev2_add_data(struct ibuf *buf, void *data, size_t length)
2032
{
2033
	void	*msgbuf;
2034
2035
	if ((msgbuf = ibuf_advance(buf, length)) == NULL) {
2036
		log_debug("%s: failed", __func__);
2037
		return (-1);
2038
	}
2039
	memcpy(msgbuf, data, length);
2040
2041
	return (0);
2042
}
2043
2044
int
2045
ikev2_add_buf(struct ibuf *buf, struct ibuf *data)
2046
{
2047
	void	*msgbuf;
2048
2049
	if ((msgbuf = ibuf_advance(buf, ibuf_size(data))) == NULL) {
2050
		log_debug("%s: failed", __func__);
2051
		return (-1);
2052
	}
2053
	memcpy(msgbuf, ibuf_data(data), ibuf_size(data));
2054
2055
	return (0);
2056
}
2057
2058
void
2059
ikev2_resp_recv(struct iked *env, struct iked_message *msg,
2060
    struct ike_header *hdr)
2061
{
2062
	struct iked_sa		*sa;
2063
2064
	switch (hdr->ike_exchange) {
2065
	case IKEV2_EXCHANGE_IKE_SA_INIT:
2066
		if (msg->msg_sa != NULL) {
2067
			log_debug("%s: SA already exists", __func__);
2068
			return;
2069
		}
2070
		if ((msg->msg_sa = sa_new(env,
2071
		    betoh64(hdr->ike_ispi), betoh64(hdr->ike_rspi),
2072
		    0, msg->msg_policy)) == NULL) {
2073
			log_debug("%s: failed to get new SA", __func__);
2074
			return;
2075
		}
2076
		/* Setup exchange timeout. */
2077
		timer_set(env, &msg->msg_sa->sa_timer,
2078
		    ikev2_init_ike_sa_timeout, msg->msg_sa);
2079
		timer_add(env, &msg->msg_sa->sa_timer,
2080
		    IKED_IKE_SA_EXCHANGE_TIMEOUT);
2081
		break;
2082
	case IKEV2_EXCHANGE_IKE_AUTH:
2083
		if (ikev2_msg_valid_ike_sa(env, hdr, msg) == -1)
2084
			return;
2085
		if (sa_stateok(msg->msg_sa, IKEV2_STATE_VALID)) {
2086
			log_debug("%s: already authenticated", __func__);
2087
			return;
2088
		}
2089
		break;
2090
	case IKEV2_EXCHANGE_CREATE_CHILD_SA:
2091
		if (ikev2_msg_valid_ike_sa(env, hdr, msg) == -1)
2092
			return;
2093
		break;
2094
	case IKEV2_EXCHANGE_INFORMATIONAL:
2095
		if (ikev2_msg_valid_ike_sa(env, hdr, msg) == -1)
2096
			return;
2097
		break;
2098
	default:
2099
		log_debug("%s: unsupported exchange: %s", __func__,
2100
		    print_map(hdr->ike_exchange, ikev2_exchange_map));
2101
		return;
2102
	}
2103
2104
	if (ikev2_pld_parse(env, hdr, msg, msg->msg_offset) != 0) {
2105
		log_debug("%s: failed to parse message", __func__);
2106
		return;
2107
	}
2108
2109
	if (!ikev2_msg_frompeer(msg))
2110
		return;
2111
2112
	if ((sa = msg->msg_sa) == NULL)
2113
		return;
2114
2115
	if (msg->msg_natt && sa->sa_natt == 0) {
2116
		log_debug("%s: NAT-T message received, updated SA", __func__);
2117
		sa->sa_natt = 1;
2118
	}
2119
2120
	switch (hdr->ike_exchange) {
2121
	case IKEV2_EXCHANGE_IKE_SA_INIT:
2122
		if (ikev2_sa_responder(env, sa, NULL, msg) != 0) {
2123
			log_debug("%s: failed to get IKE SA keys", __func__);
2124
			sa_state(env, sa, IKEV2_STATE_CLOSED);
2125
			return;
2126
		}
2127
		if (ikev2_resp_ike_sa_init(env, msg) != 0) {
2128
			log_debug("%s: failed to send init response", __func__);
2129
			sa_state(env, sa, IKEV2_STATE_CLOSED);
2130
			return;
2131
		}
2132
		break;
2133
	case IKEV2_EXCHANGE_IKE_AUTH:
2134
		if (!sa_stateok(sa, IKEV2_STATE_SA_INIT)) {
2135
			log_debug("%s: state mismatch", __func__);
2136
			sa_state(env, sa, IKEV2_STATE_CLOSED);
2137
			return;
2138
		}
2139
2140
		if (!sa_stateok(sa, IKEV2_STATE_AUTH_REQUEST) &&
2141
		    sa->sa_policy->pol_auth.auth_eap)
2142
			sa_state(env, sa, IKEV2_STATE_EAP);
2143
2144
		if (ikev2_ike_auth_recv(env, sa, msg) != 0) {
2145
			log_debug("%s: failed to send auth response", __func__);
2146
			sa_state(env, sa, IKEV2_STATE_CLOSED);
2147
			return;
2148
		}
2149
		break;
2150
	case IKEV2_EXCHANGE_CREATE_CHILD_SA:
2151
		if (ikev2_resp_create_child_sa(env, msg) != 0)
2152
			ikev2_send_error(env, sa, msg, hdr->ike_exchange);
2153
		break;
2154
	case IKEV2_EXCHANGE_INFORMATIONAL:
2155
		if (sa_stateok(sa, IKEV2_STATE_AUTH_REQUEST) &&
2156
		    !msg->msg_responded && !msg->msg_error) {
2157
			(void)ikev2_send_ike_e(env, sa, NULL,
2158
			    IKEV2_PAYLOAD_NONE, IKEV2_EXCHANGE_INFORMATIONAL,
2159
			    1);
2160
			msg->msg_responded = 1;
2161
		}
2162
		break;
2163
	default:
2164
		break;
2165
	}
2166
}
2167
2168
int
2169
ikev2_resp_ike_sa_init(struct iked *env, struct iked_message *msg)
2170
{
2171
	struct iked_message		 resp;
2172
	struct ike_header		*hdr;
2173
	struct ikev2_payload		*pld;
2174
	struct ikev2_keyexchange	*ke;
2175
	struct iked_sa			*sa = msg->msg_sa;
2176
	struct ibuf			*buf;
2177
	struct group			*group;
2178
	ssize_t				 len;
2179
	int				 ret = -1;
2180
2181
	if (sa->sa_hdr.sh_initiator) {
2182
		log_debug("%s: called by initiator", __func__);
2183
		return (-1);
2184
	}
2185
2186
	if ((buf = ikev2_msg_init(env, &resp,
2187
	    &msg->msg_peer, msg->msg_peerlen,
2188
	    &msg->msg_local, msg->msg_locallen, 1)) == NULL)
2189
		goto done;
2190
2191
	resp.msg_sa = sa;
2192
	resp.msg_fd = msg->msg_fd;
2193
	resp.msg_natt = msg->msg_natt;
2194
	resp.msg_msgid = 0;
2195
2196
	/* IKE header */
2197
	if ((hdr = ikev2_add_header(buf, sa, resp.msg_msgid,
2198
	    IKEV2_PAYLOAD_SA, IKEV2_EXCHANGE_IKE_SA_INIT,
2199
	    IKEV2_FLAG_RESPONSE)) == NULL)
2200
		goto done;
2201
2202
	/* SA payload */
2203
	if ((pld = ikev2_add_payload(buf)) == NULL)
2204
		goto done;
2205
	if ((len = ikev2_add_proposals(env, sa, buf, &sa->sa_proposals,
2206
	    IKEV2_SAPROTO_IKE, sa->sa_hdr.sh_initiator, 0)) == -1)
2207
		goto done;
2208
2209
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_KE) == -1)
2210
		goto done;
2211
2212
	/* KE payload */
2213
	if ((pld = ikev2_add_payload(buf)) == NULL)
2214
		goto done;
2215
	if ((ke = ibuf_advance(buf, sizeof(*ke))) == NULL)
2216
		goto done;
2217
	if ((group = sa->sa_dhgroup) == NULL) {
2218
		log_debug("%s: invalid dh", __func__);
2219
		goto done;
2220
	}
2221
	ke->kex_dhgroup = htobe16(group->id);
2222
	if (ikev2_add_buf(buf, sa->sa_dhrexchange) == -1)
2223
		goto done;
2224
	len = sizeof(*ke) + dh_getlen(group);
2225
2226
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONCE) == -1)
2227
		goto done;
2228
2229
	/* NONCE payload */
2230
	if ((pld = ikev2_add_payload(buf)) == NULL)
2231
		goto done;
2232
	if (ikev2_add_buf(buf, sa->sa_rnonce) == -1)
2233
		goto done;
2234
	len = ibuf_size(sa->sa_rnonce);
2235
2236
	if ((env->sc_opts & IKED_OPT_NONATT) == 0 &&
2237
	    msg->msg_local.ss_family != AF_UNSPEC) {
2238
		if ((len = ikev2_add_nat_detection(env, buf, &pld, &resp, len))
2239
		    == -1)
2240
			goto done;
2241
	}
2242
	if (sa->sa_statevalid & IKED_REQ_CERT) {
2243
		/* CERTREQ payload(s) */
2244
		if ((len = ikev2_add_certreq(buf, &pld,
2245
		    len, env->sc_certreq, env->sc_certreqtype)) == -1)
2246
			goto done;
2247
2248
		if (env->sc_certreqtype != sa->sa_policy->pol_certreqtype &&
2249
		    (len = ikev2_add_certreq(buf, &pld,
2250
		    len, NULL, sa->sa_policy->pol_certreqtype)) == -1)
2251
			goto done;
2252
	}
2253
2254
	if (sa->sa_sigsha2 &&
2255
	    (len = ikev2_add_sighashnotify(buf, &pld, len)) == -1)
2256
		goto done;
2257
2258
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
2259
		goto done;
2260
2261
	if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
2262
		goto done;
2263
2264
	(void)ikev2_pld_parse(env, hdr, &resp, 0);
2265
2266
	ibuf_release(sa->sa_2ndmsg);
2267
	if ((sa->sa_2ndmsg = ibuf_dup(buf)) == NULL) {
2268
		log_debug("%s: failed to copy 2nd message", __func__);
2269
		goto done;
2270
	}
2271
2272
	resp.msg_sa = NULL;	/* Don't save the response */
2273
	ret = ikev2_msg_send(env, &resp);
2274
2275
 done:
2276
	ikev2_msg_cleanup(env, &resp);
2277
2278
	return (ret);
2279
}
2280
2281
int
2282
ikev2_send_auth_failed(struct iked *env, struct iked_sa *sa)
2283
{
2284
	struct ikev2_notify		*n;
2285
	struct ibuf			*buf = NULL;
2286
	int				 ret = -1, exchange, response;
2287
2288
	/* Notify payload */
2289
	if ((buf = ibuf_static()) == NULL)
2290
		goto done;
2291
	if ((n = ibuf_advance(buf, sizeof(*n))) == NULL)
2292
		goto done;
2293
	n->n_protoid = IKEV2_SAPROTO_IKE;
2294
	n->n_spisize = 0;
2295
	n->n_type = htobe16(IKEV2_N_AUTHENTICATION_FAILED);
2296
	if (sa->sa_hdr.sh_initiator) {
2297
		exchange = IKEV2_EXCHANGE_INFORMATIONAL;
2298
		response = 0;
2299
	} else {
2300
		exchange = IKEV2_EXCHANGE_IKE_AUTH;
2301
		response = 1;
2302
	}
2303
	ret = ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_NOTIFY,
2304
	    exchange, response);
2305
	if (exchange == IKEV2_EXCHANGE_INFORMATIONAL)
2306
		sa->sa_stateflags |= IKED_REQ_INF;
2307
 done:
2308
	ibuf_release(buf);
2309
2310
	/* cleanup SA after timeout */
2311
	sa_state(env, sa, IKEV2_STATE_CLOSING);
2312
	timer_del(env, &sa->sa_timer);
2313
	timer_set(env, &sa->sa_timer, ikev2_ike_sa_timeout, sa);
2314
	timer_add(env, &sa->sa_timer, IKED_IKE_SA_DELETE_TIMEOUT);
2315
2316
	return (ret);
2317
}
2318
2319
int
2320
ikev2_send_error(struct iked *env, struct iked_sa *sa,
2321
    struct iked_message *msg, uint8_t exchange)
2322
{
2323
	struct ikev2_notify		*n;
2324
	struct ibuf			*buf = NULL;
2325
	int				 ret = -1;
2326
2327
	switch (msg->msg_error) {
2328
	case IKEV2_N_NO_PROPOSAL_CHOSEN:
2329
		break;
2330
	case 0:
2331
		return (0);
2332
	default:
2333
		return (-1);
2334
	}
2335
	/* Notify payload */
2336
	if ((buf = ibuf_static()) == NULL)
2337
		goto done;
2338
	if ((n = ibuf_advance(buf, sizeof(*n))) == NULL)
2339
		goto done;
2340
	n->n_protoid = 0;
2341
	n->n_spisize = 0;
2342
	n->n_type = htobe16(msg->msg_error);
2343
2344
	ret = ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_NOTIFY,
2345
	    exchange, 1);
2346
 done:
2347
	ibuf_release(buf);
2348
	return (ret);
2349
}
2350
2351
int
2352
ikev2_resp_ike_auth(struct iked *env, struct iked_sa *sa)
2353
{
2354
	struct ikev2_payload		*pld;
2355
	struct ikev2_cert		*cert;
2356
	struct ikev2_auth		*auth;
2357
	struct iked_id			*id, *certid;
2358
	struct ibuf			*e = NULL;
2359
	uint8_t				 firstpayload;
2360
	int				 ret = -1;
2361
	ssize_t				 len;
2362
2363
	if (sa == NULL)
2364
		return (-1);
2365
2366
	if (sa->sa_state == IKEV2_STATE_EAP)
2367
		return (ikev2_resp_ike_eap(env, sa, NULL));
2368
2369
	if (!sa_stateok(sa, IKEV2_STATE_VALID))
2370
		return (0);	/* ignore */
2371
2372
	if (ikev2_cp_setaddr(env, sa, AF_INET) < 0 ||
2373
	    ikev2_cp_setaddr(env, sa, AF_INET6) < 0)
2374
		return (-1);
2375
2376
	if (ikev2_childsa_negotiate(env, sa, &sa->sa_kex, &sa->sa_proposals,
2377
	    sa->sa_hdr.sh_initiator, 0, 0) < 0)
2378
		return (-1);
2379
2380
	/* New encrypted message buffer */
2381
	if ((e = ibuf_static()) == NULL)
2382
		goto done;
2383
2384
	if (!sa->sa_localauth.id_type) {
2385
		/* Downgrade the state */
2386
		sa_state(env, sa, IKEV2_STATE_AUTH_SUCCESS);
2387
	}
2388
2389
	if (sa->sa_hdr.sh_initiator) {
2390
		id = &sa->sa_iid;
2391
		certid = &sa->sa_icert;
2392
	} else {
2393
		id = &sa->sa_rid;
2394
		certid = &sa->sa_rcert;
2395
	}
2396
2397
	if (sa->sa_state != IKEV2_STATE_EAP_VALID) {
2398
		/* ID payload */
2399
		if ((pld = ikev2_add_payload(e)) == NULL)
2400
			goto done;
2401
		firstpayload = IKEV2_PAYLOAD_IDr;
2402
		if (ibuf_cat(e, id->id_buf) != 0)
2403
			goto done;
2404
		len = ibuf_size(id->id_buf);
2405
2406
		/* CERT payload */
2407
		if ((sa->sa_statevalid & IKED_REQ_CERT) &&
2408
		    (certid->id_type != IKEV2_CERT_NONE)) {
2409
			if (ikev2_next_payload(pld, len,
2410
			    IKEV2_PAYLOAD_CERT) == -1)
2411
				goto done;
2412
2413
			if ((pld = ikev2_add_payload(e)) == NULL)
2414
				goto done;
2415
			if ((cert = ibuf_advance(e, sizeof(*cert))) == NULL)
2416
				goto done;
2417
			cert->cert_type = certid->id_type;
2418
			if (ibuf_cat(e, certid->id_buf) != 0)
2419
				goto done;
2420
			len = ibuf_size(certid->id_buf) + sizeof(*cert);
2421
		}
2422
2423
		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_AUTH) == -1)
2424
			goto done;
2425
	} else
2426
		firstpayload = IKEV2_PAYLOAD_AUTH;
2427
2428
	/* AUTH payload */
2429
	if ((pld = ikev2_add_payload(e)) == NULL)
2430
		goto done;
2431
	if ((auth = ibuf_advance(e, sizeof(*auth))) == NULL)
2432
		goto done;
2433
	auth->auth_method = sa->sa_localauth.id_type;
2434
	if (ibuf_cat(e, sa->sa_localauth.id_buf) != 0)
2435
		goto done;
2436
	len = ibuf_size(sa->sa_localauth.id_buf) + sizeof(*auth);
2437
2438
	/* CP payload */
2439
	if (sa->sa_cp) {
2440
		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_CP) == -1)
2441
			goto done;
2442
2443
		if ((pld = ikev2_add_payload(e)) == NULL)
2444
			goto done;
2445
		if ((len = ikev2_add_cp(env, sa, e)) == -1)
2446
			goto done;
2447
	}
2448
2449
	/* compression */
2450
	if (sa->sa_ipcomp &&
2451
	    (len = ikev2_add_ipcompnotify(env, e, &pld, len, sa)) == -1)
2452
		goto done;
2453
2454
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_SA) == -1)
2455
		goto done;
2456
2457
	/* SA payload */
2458
	if ((pld = ikev2_add_payload(e)) == NULL)
2459
		goto done;
2460
	if ((len = ikev2_add_proposals(env, sa, e, &sa->sa_proposals, 0,
2461
	    sa->sa_hdr.sh_initiator, 0)) == -1)
2462
		goto done;
2463
2464
	if ((len = ikev2_add_ts(e, &pld, len, sa, 0)) == -1)
2465
		goto done;
2466
2467
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
2468
		goto done;
2469
2470
	ret = ikev2_msg_send_encrypt(env, sa, &e,
2471
	    IKEV2_EXCHANGE_IKE_AUTH, firstpayload, 1);
2472
	if (ret == 0)
2473
		ret = ikev2_childsa_enable(env, sa);
2474
	if (ret == 0) {
2475
		sa_state(env, sa, IKEV2_STATE_ESTABLISHED);
2476
		/* Delete exchange timeout. */
2477
		timer_del(env, &sa->sa_timer);
2478
		timer_set(env, &sa->sa_timer, ikev2_ike_sa_alive, sa);
2479
		timer_add(env, &sa->sa_timer, IKED_IKE_SA_ALIVE_TIMEOUT);
2480
		timer_set(env, &sa->sa_keepalive, ikev2_ike_sa_keepalive, sa);
2481
		if (sa->sa_usekeepalive)
2482
			timer_add(env, &sa->sa_keepalive,
2483
			    IKED_IKE_SA_KEEPALIVE_TIMEOUT);
2484
		timer_set(env, &sa->sa_rekey, ikev2_ike_sa_rekey, sa);
2485
		if (sa->sa_policy->pol_rekey)
2486
			ikev2_ike_sa_rekey_schedule(env, sa);
2487
	}
2488
2489
 done:
2490
	if (ret)
2491
		ikev2_childsa_delete(env, sa, 0, 0, NULL, 1);
2492
	ibuf_release(e);
2493
	return (ret);
2494
}
2495
2496
int
2497
ikev2_resp_ike_eap(struct iked *env, struct iked_sa *sa, struct ibuf *eapmsg)
2498
{
2499
	struct ikev2_payload		*pld;
2500
	struct ikev2_cert		*cert;
2501
	struct ikev2_auth		*auth;
2502
	struct iked_id			*id, *certid;
2503
	struct ibuf			*e = NULL;
2504
	uint8_t				 firstpayload;
2505
	int				 ret = -1;
2506
	ssize_t				 len = 0;
2507
2508
	/* Responder only */
2509
	if (sa->sa_hdr.sh_initiator)
2510
		return (-1);
2511
2512
	/* Check if "ca" has done it's job yet */
2513
	if (!sa->sa_localauth.id_type)
2514
		return (0);
2515
2516
	/* New encrypted message buffer */
2517
	if ((e = ibuf_static()) == NULL)
2518
		goto done;
2519
2520
	id = &sa->sa_rid;
2521
	certid = &sa->sa_rcert;
2522
2523
	/* ID payload */
2524
	if ((pld = ikev2_add_payload(e)) == NULL)
2525
		goto done;
2526
	firstpayload = IKEV2_PAYLOAD_IDr;
2527
	if (ibuf_cat(e, id->id_buf) != 0)
2528
		goto done;
2529
	len = ibuf_size(id->id_buf);
2530
2531
	if ((sa->sa_statevalid & IKED_REQ_CERT) &&
2532
	    (certid->id_type != IKEV2_CERT_NONE)) {
2533
		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_CERT) == -1)
2534
			goto done;
2535
2536
		/* CERT payload */
2537
		if ((pld = ikev2_add_payload(e)) == NULL)
2538
			goto done;
2539
		if ((cert = ibuf_advance(e, sizeof(*cert))) == NULL)
2540
			goto done;
2541
		cert->cert_type = certid->id_type;
2542
		if (ibuf_cat(e, certid->id_buf) != 0)
2543
			goto done;
2544
		len = ibuf_size(certid->id_buf) + sizeof(*cert);
2545
	}
2546
2547
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_AUTH) == -1)
2548
		goto done;
2549
2550
	/* AUTH payload */
2551
	if ((pld = ikev2_add_payload(e)) == NULL)
2552
		goto done;
2553
	if ((auth = ibuf_advance(e, sizeof(*auth))) == NULL)
2554
		goto done;
2555
	auth->auth_method = sa->sa_localauth.id_type;
2556
	if (ibuf_cat(e, sa->sa_localauth.id_buf) != 0)
2557
		goto done;
2558
	len = ibuf_size(sa->sa_localauth.id_buf) + sizeof(*auth);
2559
2560
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_EAP) == -1)
2561
		goto done;
2562
2563
	/* EAP payload */
2564
	if ((pld = ikev2_add_payload(e)) == NULL)
2565
		goto done;
2566
	if ((len = eap_identity_request(e)) == -1)
2567
		goto done;
2568
2569
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
2570
		goto done;
2571
2572
	ret = ikev2_msg_send_encrypt(env, sa, &e,
2573
	    IKEV2_EXCHANGE_IKE_AUTH, firstpayload, 1);
2574
2575
 done:
2576
	ibuf_release(e);
2577
2578
	return (ret);
2579
}
2580
2581
int
2582
ikev2_send_ike_e(struct iked *env, struct iked_sa *sa, struct ibuf *buf,
2583
    uint8_t firstpayload, uint8_t exchange, int response)
2584
{
2585
	struct ikev2_payload		*pld;
2586
	struct ibuf			*e = NULL;
2587
	int				 ret = -1;
2588
2589
	/* New encrypted message buffer */
2590
	if ((e = ibuf_static()) == NULL)
2591
		goto done;
2592
2593
	if ((pld = ikev2_add_payload(e)) == NULL)
2594
		goto done;
2595
2596
	if (buf) {
2597
		if (ibuf_cat(e, buf) != 0)
2598
			goto done;
2599
2600
		if (ikev2_next_payload(pld, ibuf_size(buf),
2601
		    IKEV2_PAYLOAD_NONE) == -1)
2602
			goto done;
2603
	}
2604
2605
	ret = ikev2_msg_send_encrypt(env, sa, &e, exchange, firstpayload,
2606
	    response);
2607
2608
 done:
2609
	ibuf_release(e);
2610
2611
	return (ret);
2612
}
2613
2614
int
2615
ikev2_set_sa_proposal(struct iked_sa *sa, struct iked_policy *pol,
2616
    unsigned int proto)
2617
{
2618
	struct iked_proposal		*prop, *copy;
2619
	struct iked_transform		*xform;
2620
	unsigned int			 i;
2621
2622
	/* create copy of the policy proposals */
2623
	config_free_proposals(&sa->sa_proposals, proto);
2624
	TAILQ_FOREACH(prop, &pol->pol_proposals, prop_entry) {
2625
		if (proto != 0 && prop->prop_protoid != proto)
2626
			continue;
2627
		if ((copy = config_add_proposal(&sa->sa_proposals,
2628
		    prop->prop_id, prop->prop_protoid)) == NULL)
2629
			return (-1);
2630
		for (i = 0; i < prop->prop_nxforms; i++) {
2631
			xform = &prop->prop_xforms[i];
2632
			if (config_add_transform(copy, xform->xform_type,
2633
			    xform->xform_id, xform->xform_length,
2634
			    xform->xform_keylength) == NULL)
2635
				return (-1);
2636
		}
2637
	}
2638
	return (0);
2639
}
2640
2641
int
2642
ikev2_send_create_child_sa(struct iked *env, struct iked_sa *sa,
2643
    struct iked_spi *rekey, uint8_t protoid)
2644
{
2645
	struct iked_policy		*pol = sa->sa_policy;
2646
	struct iked_childsa		*csa = NULL, *csb = NULL;
2647
	struct ikev2_notify		*n;
2648
	struct ikev2_payload		*pld = NULL;
2649
	struct ikev2_keyexchange	*ke;
2650
	struct group			*group;
2651
	struct ibuf			*e = NULL, *nonce = NULL;
2652
	uint8_t				*ptr;
2653
	uint8_t				 firstpayload;
2654
	uint32_t			 spi;
2655
	ssize_t				 len = 0;
2656
	int				 initiator, ret = -1;
2657
2658
	if (rekey)
2659
		log_debug("%s: rekeying %s spi %s", __func__,
2660
		    print_map(rekey->spi_protoid, ikev2_saproto_map),
2661
		    print_spi(rekey->spi, rekey->spi_size));
2662
	else
2663
		log_debug("%s: creating new CHILD SAs", __func__);
2664
2665
	/* XXX cannot initiate multiple concurrent CREATE_CHILD_SA exchanges */
2666
	if (sa->sa_stateflags & IKED_REQ_CHILDSA) {
2667
		log_debug("%s: another CREATE_CHILD_SA exchange already active",
2668
		    __func__);
2669
		return (-1);
2670
	}
2671
2672
	sa->sa_rekeyspi = 0;	/* clear rekey spi */
2673
	initiator = sa->sa_hdr.sh_initiator ? 1 : 0;
2674
2675
	if (rekey &&
2676
	    ((csa = childsa_lookup(sa, rekey->spi,
2677
	    rekey->spi_protoid)) == NULL ||
2678
	    (csb = csa->csa_peersa) == NULL)) {
2679
		log_debug("%s: CHILD SA %s wasn't found", __func__,
2680
		    print_spi(rekey->spi, rekey->spi_size));
2681
		goto done;
2682
	}
2683
2684
	/* Generate new nonce */
2685
	if ((nonce = ibuf_random(IKED_NONCE_SIZE)) == NULL)
2686
		goto done;
2687
2688
	/* Update initiator nonce */
2689
	ibuf_release(sa->sa_inonce);
2690
	sa->sa_inonce = nonce;
2691
2692
	if ((e = ibuf_static()) == NULL)
2693
		goto done;
2694
2695
	/* compression */
2696
	if ((pol->pol_flags & IKED_POLICY_IPCOMP) &&
2697
	    (len = ikev2_add_ipcompnotify(env, e, &pld, 0, sa)) == -1)
2698
		goto done;
2699
2700
	if (pld) {
2701
		firstpayload = IKEV2_PAYLOAD_NOTIFY;
2702
		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_SA) == -1)
2703
			goto done;
2704
	} else
2705
		firstpayload = IKEV2_PAYLOAD_SA;
2706
2707
	/* SA payload */
2708
	if ((pld = ikev2_add_payload(e)) == NULL)
2709
		goto done;
2710
2711
	/*
2712
	 * We need to reset the sa_proposal. Otherwise it would be
2713
	 * left over from the IKE_AUTH exchange and would not contain
2714
	 * any DH groups (e.g. for ESP child SAs).
2715
	 */
2716
	if (ikev2_set_sa_proposal(sa, pol, protoid) < 0) {
2717
		log_debug("%s: ikev2_set_sa_proposal failed", __func__);
2718
		goto done;
2719
	}
2720
2721
	if ((len = ikev2_add_proposals(env, sa, e, &sa->sa_proposals,
2722
	    protoid, 1, 0)) == -1)
2723
		goto done;
2724
2725
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONCE) == -1)
2726
		goto done;
2727
2728
	/* NONCE payload */
2729
	if ((pld = ikev2_add_payload(e)) == NULL)
2730
		goto done;
2731
	if (ikev2_add_buf(e, nonce) == -1)
2732
		goto done;
2733
	len = ibuf_size(nonce);
2734
2735
	if (config_findtransform(&pol->pol_proposals, IKEV2_XFORMTYPE_DH,
2736
	    protoid)) {
2737
		log_debug("%s: enable PFS", __func__);
2738
		ikev2_sa_cleanup_dh(sa);
2739
		if (ikev2_sa_initiator_dh(sa, NULL, protoid) < 0) {
2740
			log_debug("%s: failed to setup DH", __func__);
2741
			goto done;
2742
		}
2743
		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_KE) == -1)
2744
			goto done;
2745
2746
		/* KE payload */
2747
		if ((pld = ikev2_add_payload(e)) == NULL)
2748
			goto done;
2749
		if ((ke = ibuf_advance(e, sizeof(*ke))) == NULL)
2750
			goto done;
2751
		if ((group = sa->sa_dhgroup) == NULL) {
2752
			log_debug("%s: invalid dh", __func__);
2753
			goto done;
2754
		}
2755
		ke->kex_dhgroup = htobe16(group->id);
2756
		if (ikev2_add_buf(e, sa->sa_dhiexchange) == -1)
2757
			goto done;
2758
		len = sizeof(*ke) + dh_getlen(group);
2759
	}
2760
2761
	if ((len = ikev2_add_ts(e, &pld, len, sa, !initiator)) == -1)
2762
		goto done;
2763
2764
	if (rekey) {
2765
		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NOTIFY) == -1)
2766
			goto done;
2767
2768
		/* REKEY_SA notification */
2769
		if ((pld = ikev2_add_payload(e)) == NULL)
2770
			goto done;
2771
		if ((n = ibuf_advance(e, sizeof(*n))) == NULL)
2772
			goto done;
2773
		n->n_type = htobe16(IKEV2_N_REKEY_SA);
2774
		n->n_protoid = rekey->spi_protoid;
2775
		n->n_spisize = rekey->spi_size;
2776
		if ((ptr = ibuf_advance(e, rekey->spi_size)) == NULL)
2777
			goto done;
2778
		len = rekey->spi_size;
2779
		spi = htobe32((uint32_t)csa->csa_peerspi);
2780
		memcpy(ptr, &spi, rekey->spi_size);
2781
		len += sizeof(*n);
2782
	}
2783
2784
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
2785
		goto done;
2786
2787
	ret = ikev2_msg_send_encrypt(env, sa, &e,
2788
	    IKEV2_EXCHANGE_CREATE_CHILD_SA, firstpayload, 0);
2789
	if (ret == 0) {
2790
		if (rekey) {
2791
			csa->csa_rekey = 1;
2792
			csb->csa_rekey = 1;
2793
			/*
2794
			 * Remember the peer spi of the rekeyed
2795
			 * SA for ikev2_init_create_child_sa().
2796
			 */
2797
			sa->sa_rekeyspi = csa->csa_peerspi;
2798
		}
2799
		sa->sa_stateflags |= IKED_REQ_CHILDSA;
2800
	}
2801
2802
done:
2803
	ibuf_release(e);
2804
	return (ret);
2805
}
2806
2807
void
2808
ikev2_ike_sa_rekey(struct iked *env, void *arg)
2809
{
2810
	struct iked_sa			*sa = arg;
2811
	struct iked_sa			*nsa = NULL;
2812
	struct ikev2_payload		*pld = NULL;
2813
	struct ikev2_keyexchange	*ke;
2814
	struct group			*group;
2815
	struct ibuf			*e = NULL, *nonce = NULL;
2816
	ssize_t				 len = 0;
2817
	int				 ret = -1;
2818
2819
	log_debug("%s: IKE SA %p ispi %s rspi %s", __func__, sa,
2820
	    print_spi(sa->sa_hdr.sh_ispi, 8),
2821
	    print_spi(sa->sa_hdr.sh_rspi, 8));
2822
2823
	if (sa->sa_nexti) {
2824
		log_debug("%s: already rekeying", __func__);
2825
		goto done;
2826
	}
2827
2828
	if (sa->sa_stateflags & IKED_REQ_CHILDSA) {
2829
		/*
2830
		 * We cannot initiate multiple concurrent CREATE_CHILD_SA
2831
		 * exchanges, so retry in one minute.
2832
		 */
2833
		timer_add(env, &sa->sa_rekey, 60);
2834
		return;
2835
	}
2836
2837
	/* We need to make sure the rekeying finishes in time */
2838
	timer_set(env, &sa->sa_rekey, ikev2_ike_sa_rekey_timeout, sa);
2839
	timer_add(env, &sa->sa_rekey, IKED_IKE_SA_REKEY_TIMEOUT);
2840
2841
	if ((nsa = sa_new(env, 0, 0, 1, sa->sa_policy)) == NULL) {
2842
		log_debug("%s: failed to get new SA", __func__);
2843
		goto done;
2844
	}
2845
2846
	if (ikev2_sa_initiator(env, nsa, sa, NULL)) {
2847
		log_debug("%s: failed to setup DH", __func__);
2848
		goto done;
2849
	}
2850
	sa_state(env, nsa, IKEV2_STATE_AUTH_SUCCESS);
2851
	nonce = nsa->sa_inonce;
2852
2853
	if ((e = ibuf_static()) == NULL)
2854
		goto done;
2855
2856
	/* SA payload */
2857
	if ((pld = ikev2_add_payload(e)) == NULL)
2858
		goto done;
2859
2860
	/* just reuse the old IKE SA proposals */
2861
	if ((len = ikev2_add_proposals(env, nsa, e, &sa->sa_proposals,
2862
	    IKEV2_SAPROTO_IKE, 1, 1)) == -1)
2863
		goto done;
2864
2865
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONCE) == -1)
2866
		goto done;
2867
2868
	/* NONCE payload */
2869
	if ((pld = ikev2_add_payload(e)) == NULL)
2870
		goto done;
2871
	if (ikev2_add_buf(e, nonce) == -1)
2872
		goto done;
2873
	len = ibuf_size(nonce);
2874
2875
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_KE) == -1)
2876
		goto done;
2877
2878
	/* KE payload */
2879
	if ((pld = ikev2_add_payload(e)) == NULL)
2880
		goto done;
2881
	if ((ke = ibuf_advance(e, sizeof(*ke))) == NULL)
2882
		goto done;
2883
	if ((group = nsa->sa_dhgroup) == NULL) {
2884
		log_debug("%s: invalid dh", __func__);
2885
		goto done;
2886
	}
2887
	ke->kex_dhgroup = htobe16(group->id);
2888
	if (ikev2_add_buf(e, nsa->sa_dhiexchange) == -1)
2889
		goto done;
2890
	len = sizeof(*ke) + dh_getlen(group);
2891
2892
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
2893
		goto done;
2894
2895
	ret = ikev2_msg_send_encrypt(env, sa, &e,
2896
	    IKEV2_EXCHANGE_CREATE_CHILD_SA, IKEV2_PAYLOAD_SA, 0);
2897
	if (ret == 0) {
2898
		sa->sa_stateflags |= IKED_REQ_CHILDSA;
2899
		sa->sa_nexti = nsa;
2900
		nsa = NULL;
2901
	}
2902
done:
2903
	if (nsa)
2904
		sa_free(env, nsa);
2905
	ibuf_release(e);
2906
2907
	if (ret == 0)
2908
		log_debug("%s: create child SA sent", __func__);
2909
	else
2910
		log_debug("%s: could not send create child SA", __func__);
2911
	/* XXX should we try again in case of ret != 0 ? */
2912
}
2913
2914
int
2915
ikev2_nonce_cmp(struct ibuf *a, struct ibuf *b)
2916
{
2917
	size_t				alen, blen, len;
2918
	int				ret;
2919
2920
	alen = ibuf_length(a);
2921
	blen = ibuf_length(b);
2922
	len = MIN(alen, blen);
2923
	ret = memcmp(ibuf_data(a), ibuf_data(b), len);
2924
	if (ret == 0)
2925
		ret = (alen < blen ? -1 : 1);
2926
	return (ret);
2927
}
2928
2929
int
2930
ikev2_init_create_child_sa(struct iked *env, struct iked_message *msg)
2931
{
2932
	struct iked_childsa		*csa = NULL;
2933
	struct iked_proposal		*prop;
2934
	struct iked_sa			*sa = msg->msg_sa;
2935
	struct iked_sa			*nsa, *dsa;
2936
	struct iked_spi			*spi;
2937
	struct ikev2_delete		*del;
2938
	struct ibuf			*buf = NULL;
2939
	struct ibuf			*ni, *nr;
2940
	uint32_t			 spi32;
2941
	int				 pfs = 0, ret = -1;
2942
2943
	if (!ikev2_msg_frompeer(msg) ||
2944
	    (sa->sa_stateflags & IKED_REQ_CHILDSA) == 0)
2945
		return (0);
2946
2947
	if (msg->msg_prop == NULL ||
2948
	    TAILQ_EMPTY(&msg->msg_proposals)) {
2949
		log_debug("%s: no proposal specified", __func__);
2950
		return (-1);
2951
	}
2952
2953
	if (ikev2_sa_negotiate(&sa->sa_proposals, &sa->sa_proposals,
2954
	    &msg->msg_proposals, 1) != 0) {
2955
		log_debug("%s: no proposal chosen", __func__);
2956
		return (-1);
2957
	}
2958
2959
	TAILQ_FOREACH(prop, &sa->sa_proposals, prop_entry) {
2960
		if (prop->prop_protoid == msg->msg_prop->prop_protoid)
2961
			break;
2962
	}
2963
	if (prop == NULL) {
2964
		log_debug("%s: failed to find %s proposals", __func__,
2965
		    print_map(msg->msg_prop->prop_protoid, ikev2_saproto_map));
2966
		return (-1);
2967
	}
2968
2969
	/* IKE SA rekeying */
2970
	if (prop->prop_protoid == IKEV2_SAPROTO_IKE) {
2971
		if (sa->sa_nexti == NULL) {
2972
			log_debug("%s: missing IKE SA for rekeying", __func__);
2973
			return (-1);
2974
		}
2975
		/* Update the responder SPI */
2976
		/* XXX sa_new() is just a lookup, so nsa == sa->sa_nexti */
2977
		spi = &msg->msg_prop->prop_peerspi;
2978
		if ((nsa = sa_new(env, sa->sa_nexti->sa_hdr.sh_ispi,
2979
		    spi->spi, 1, NULL)) == NULL || nsa != sa->sa_nexti) {
2980
			log_debug("%s: invalid rekey SA", __func__);
2981
			if (nsa)
2982
				sa_free(env, nsa);
2983
			sa_free(env, sa->sa_nexti);
2984
			sa->sa_nexti = NULL;
2985
			return (-1);
2986
		}
2987
		if (ikev2_sa_initiator(env, nsa, sa, msg) == -1) {
2988
			log_debug("%s: failed to get IKE keys", __func__);
2989
			return (-1);
2990
		}
2991
		sa->sa_stateflags &= ~IKED_REQ_CHILDSA;
2992
		if (sa->sa_nextr) {
2993
			/*
2994
			 * Resolve simultaneous IKE SA rekeying by
2995
			 * deleting the SA with the lowest NONCE.
2996
			 */
2997
			log_debug("%s: resolving simultaneous IKE SA rekeying",
2998
			    __func__);
2999
			/* ni: minimum nonce of sa_nexti */
3000
			if (ikev2_nonce_cmp(sa->sa_nexti->sa_inonce,
3001
			    sa->sa_nexti->sa_rnonce) < 0)
3002
				ni = sa->sa_nexti->sa_inonce;
3003
			else
3004
				ni = sa->sa_nexti->sa_rnonce;
3005
			/* nr: minimum nonce of sa_nextr */
3006
			if (ikev2_nonce_cmp(sa->sa_nextr->sa_inonce,
3007
			    sa->sa_nextr->sa_rnonce) < 0)
3008
				nr = sa->sa_nextr->sa_inonce;
3009
			else
3010
				nr = sa->sa_nextr->sa_rnonce;
3011
			/* delete SA with minumum nonce */
3012
			if (ikev2_nonce_cmp(ni, nr) < 0) {
3013
				dsa = sa->sa_nexti;
3014
				nsa = sa->sa_nextr;
3015
			} else {
3016
				dsa = sa->sa_nextr;
3017
				nsa = sa->sa_nexti;
3018
			}
3019
			/* Setup address, socket and NAT information */
3020
			sa_state(env, dsa, IKEV2_STATE_CLOSING);
3021
			sa_address(dsa, &dsa->sa_peer, &sa->sa_peer.addr);
3022
			sa_address(dsa, &dsa->sa_local, &sa->sa_local.addr);
3023
			dsa->sa_fd = sa->sa_fd;
3024
			dsa->sa_natt = sa->sa_natt;
3025
			dsa->sa_udpencap = sa->sa_udpencap;
3026
			ikev2_ikesa_delete(env, dsa, dsa->sa_hdr.sh_initiator);
3027
		}
3028
		sa->sa_nexti = sa->sa_nextr = NULL;
3029
		return (ikev2_ikesa_enable(env, sa, nsa));
3030
	}
3031
3032
	/* Child SA rekeying */
3033
	if (sa->sa_rekeyspi &&
3034
	    (csa = childsa_lookup(sa, sa->sa_rekeyspi, prop->prop_protoid))
3035
	    != NULL) {
3036
		log_debug("%s: rekeying CHILD SA old %s spi %s", __func__,
3037
		    print_spi(csa->csa_spi.spi, csa->csa_spi.spi_size),
3038
		    print_spi(prop->prop_peerspi.spi,
3039
		    prop->prop_peerspi.spi_size));
3040
	}
3041
3042
	/* check KE payload for PFS */
3043
	if (ibuf_length(msg->msg_ke)) {
3044
		log_debug("%s: using PFS", __func__);
3045
		if (ikev2_sa_initiator_dh(sa, msg, prop->prop_protoid) < 0) {
3046
			log_debug("%s: failed to setup DH", __func__);
3047
			return (ret);
3048
		}
3049
		if (sa->sa_dhpeer == NULL) {
3050
			log_debug("%s: no peer DH", __func__);
3051
			return (ret);
3052
		}
3053
		pfs = 1;
3054
		/* XXX check group against policy ? */
3055
		/* XXX should ikev2_sa_negotiate do this? */
3056
	}
3057
3058
	/* Update responder's nonce */
3059
	if (!ibuf_length(msg->msg_nonce)) {
3060
		log_debug("%s: responder didn't send nonce", __func__);
3061
		return (-1);
3062
	}
3063
	ibuf_release(sa->sa_rnonce);
3064
	sa->sa_rnonce = ibuf_dup(msg->msg_nonce);
3065
3066
	if (csa && (ni = sa->sa_simult) != NULL) {
3067
		log_debug("%s: resolving simultaneous CHILD SA rekeying",
3068
		    __func__);
3069
		/* set nr to minimum nonce for exchange initiated by peer */
3070
		if (ikev2_nonce_cmp(sa->sa_inonce, sa->sa_rnonce) < 0)
3071
			nr = sa->sa_inonce;
3072
		else
3073
			nr = sa->sa_rnonce;
3074
		/*
3075
		 * If the exchange initated by us has smaller nonce,
3076
		 * then we have to delete our SAs.
3077
		 */
3078
		if (ikev2_nonce_cmp(ni, nr) < 0) {
3079
			ret = ikev2_childsa_delete_proposed(env, sa,
3080
			    &sa->sa_proposals);
3081
			goto done;
3082
		}
3083
	}
3084
3085
	if (ikev2_childsa_negotiate(env, sa, &sa->sa_kex, &sa->sa_proposals, 1,
3086
	    pfs, !csa)) {
3087
		log_debug("%s: failed to get CHILD SAs", __func__);
3088
		return (-1);
3089
	}
3090
3091
	if (csa) {
3092
		/* Child SA rekeying */
3093
3094
		if ((buf = ibuf_static()) == NULL)
3095
			goto done;
3096
3097
		if ((del = ibuf_advance(buf, sizeof(*del))) == NULL)
3098
			goto done;
3099
3100
		del->del_protoid = prop->prop_protoid;
3101
		del->del_spisize = sizeof(spi32);
3102
		del->del_nspi = htobe16(1);
3103
3104
		spi32 = htobe32(csa->csa_spi.spi);
3105
		if (ibuf_add(buf, &spi32, sizeof(spi32)))
3106
			goto done;
3107
3108
		if (ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_DELETE,
3109
		    IKEV2_EXCHANGE_INFORMATIONAL, 0))
3110
			goto done;
3111
3112
		sa->sa_stateflags |= IKED_REQ_INF;
3113
	}
3114
3115
	ret = ikev2_childsa_enable(env, sa);
3116
3117
done:
3118
	sa->sa_stateflags &= ~IKED_REQ_CHILDSA;
3119
	ibuf_release(sa->sa_simult);
3120
	sa->sa_simult = NULL;
3121
3122
	if (ret)
3123
		ikev2_childsa_delete(env, sa, 0, 0, NULL, 1);
3124
	else if (csa) {
3125
		/* delete the rekeyed SA pair */
3126
		ikev2_childsa_delete(env, sa, csa->csa_saproto,
3127
		    csa->csa_peerspi, NULL, 0);
3128
	}
3129
	ibuf_release(buf);
3130
	return (ret);
3131
}
3132
3133
int
3134
ikev2_ikesa_enable(struct iked *env, struct iked_sa *sa, struct iked_sa *nsa)
3135
{
3136
	struct iked_childsa		*csa, *nextcsa;
3137
	struct iked_flow		*flow, *nextflow;
3138
	struct iked_proposal		*prop, *nextprop;
3139
3140
	log_debug("%s: IKE SA %p ispi %s rspi %s replaced"
3141
	    " by SA %p ispi %s rspi %s ",
3142
	    __func__, sa,
3143
	    print_spi(sa->sa_hdr.sh_ispi, 8),
3144
	    print_spi(sa->sa_hdr.sh_rspi, 8),
3145
	    nsa,
3146
	    print_spi(nsa->sa_hdr.sh_ispi, 8),
3147
	    print_spi(nsa->sa_hdr.sh_rspi, 8));
3148
3149
	/* Transfer socket and NAT information */
3150
	nsa->sa_fd = sa->sa_fd;
3151
	nsa->sa_natt = sa->sa_natt;
3152
	nsa->sa_udpencap = sa->sa_udpencap;
3153
	nsa->sa_usekeepalive = sa->sa_usekeepalive;
3154
3155
	/* Transfer old addresses */
3156
	memcpy(&nsa->sa_local, &sa->sa_local, sizeof(nsa->sa_local));
3157
	memcpy(&nsa->sa_peer, &sa->sa_peer, sizeof(nsa->sa_peer));
3158
3159
	/* Transfer all Child SAs and flows from the old IKE SA */
3160
	for (flow = TAILQ_FIRST(&sa->sa_flows); flow != NULL;
3161
	     flow = nextflow) {
3162
		nextflow = TAILQ_NEXT(flow, flow_entry);
3163
		TAILQ_REMOVE(&sa->sa_flows, flow, flow_entry);
3164
		TAILQ_INSERT_TAIL(&nsa->sa_flows, flow,
3165
		    flow_entry);
3166
		flow->flow_ikesa = nsa;
3167
		flow->flow_local = &nsa->sa_local;
3168
		flow->flow_peer = &nsa->sa_peer;
3169
	}
3170
	for (csa = TAILQ_FIRST(&sa->sa_childsas); csa != NULL;
3171
	     csa = nextcsa) {
3172
		nextcsa = TAILQ_NEXT(csa, csa_entry);
3173
		TAILQ_REMOVE(&sa->sa_childsas, csa, csa_entry);
3174
		TAILQ_INSERT_TAIL(&nsa->sa_childsas, csa,
3175
		    csa_entry);
3176
		csa->csa_ikesa = nsa;
3177
		if (csa->csa_dir == IPSP_DIRECTION_IN) {
3178
			csa->csa_local = &nsa->sa_peer;
3179
			csa->csa_peer = &nsa->sa_local;
3180
		} else {
3181
			csa->csa_local = &nsa->sa_local;
3182
			csa->csa_peer = &nsa->sa_peer;
3183
		}
3184
	}
3185
	/* Transfer all non-IKE proposals */
3186
	for (prop = TAILQ_FIRST(&sa->sa_proposals); prop != NULL;
3187
	     prop = nextprop) {
3188
		nextprop = TAILQ_NEXT(prop, prop_entry);
3189
		if (prop->prop_protoid == IKEV2_SAPROTO_IKE)
3190
			continue;
3191
		TAILQ_REMOVE(&sa->sa_proposals, prop, prop_entry);
3192
		TAILQ_INSERT_TAIL(&nsa->sa_proposals, prop,
3193
		    prop_entry);
3194
	}
3195
3196
	/* Preserve ID information */
3197
	if (sa->sa_hdr.sh_initiator == nsa->sa_hdr.sh_initiator) {
3198
		nsa->sa_iid = sa->sa_iid;
3199
		nsa->sa_rid = sa->sa_rid;
3200
		nsa->sa_icert = sa->sa_icert;
3201
		nsa->sa_rcert = sa->sa_rcert;
3202
	} else {
3203
		/* initiator and responder role swapped */
3204
		nsa->sa_iid = sa->sa_rid;
3205
		nsa->sa_rid = sa->sa_iid;
3206
		nsa->sa_icert = sa->sa_rcert;
3207
		nsa->sa_rcert = sa->sa_icert;
3208
	}
3209
	/* duplicate the actual buffer */
3210
	nsa->sa_iid.id_buf = ibuf_dup(nsa->sa_iid.id_buf);
3211
	nsa->sa_rid.id_buf = ibuf_dup(nsa->sa_rid.id_buf);
3212
	nsa->sa_icert.id_buf = ibuf_dup(nsa->sa_icert.id_buf);
3213
	nsa->sa_rcert.id_buf = ibuf_dup(nsa->sa_rcert.id_buf);
3214
3215
	/* Transfer sa_addrpool address */
3216
	if (sa->sa_addrpool) {
3217
		RB_REMOVE(iked_addrpool, &env->sc_addrpool, sa);
3218
		nsa->sa_addrpool = sa->sa_addrpool;
3219
		sa->sa_addrpool = NULL;
3220
		RB_INSERT(iked_addrpool, &env->sc_addrpool, nsa);
3221
	}
3222
	if (sa->sa_addrpool6) {
3223
		RB_REMOVE(iked_addrpool6, &env->sc_addrpool6, sa);
3224
		nsa->sa_addrpool6 = sa->sa_addrpool6;
3225
		sa->sa_addrpool6 = NULL;
3226
		RB_INSERT(iked_addrpool6, &env->sc_addrpool6, nsa);
3227
	}
3228
	/* Transfer other attributes */
3229
	if (sa->sa_tag) {
3230
		nsa->sa_tag = sa->sa_tag;
3231
		sa->sa_tag = NULL;
3232
	}
3233
3234
	log_debug("%s: activating new IKE SA", __func__);
3235
	sa_state(env, nsa, IKEV2_STATE_ESTABLISHED);
3236
	timer_set(env, &nsa->sa_timer, ikev2_ike_sa_alive, nsa);
3237
	timer_add(env, &nsa->sa_timer, IKED_IKE_SA_ALIVE_TIMEOUT);
3238
	timer_set(env, &nsa->sa_keepalive, ikev2_ike_sa_keepalive, nsa);
3239
	if (nsa->sa_usekeepalive)
3240
		timer_add(env, &nsa->sa_keepalive,
3241
		    IKED_IKE_SA_KEEPALIVE_TIMEOUT);
3242
	timer_set(env, &nsa->sa_rekey, ikev2_ike_sa_rekey, nsa);
3243
	if (nsa->sa_policy->pol_rekey)
3244
		ikev2_ike_sa_rekey_schedule(env, nsa);
3245
	nsa->sa_stateflags = nsa->sa_statevalid; /* XXX */
3246
3247
	/* unregister DPD keep alive timer & rekey first */
3248
	if (sa->sa_state == IKEV2_STATE_ESTABLISHED) {
3249
		timer_del(env, &sa->sa_rekey);
3250
		timer_del(env, &sa->sa_keepalive);
3251
		timer_del(env, &sa->sa_timer);
3252
	}
3253
3254
	ikev2_ikesa_delete(env, sa, nsa->sa_hdr.sh_initiator);
3255
	return (0);
3256
}
3257
3258
void
3259
ikev2_ikesa_delete(struct iked *env, struct iked_sa *sa, int initiator)
3260
{
3261
	struct ibuf			*buf = NULL;
3262
	struct ikev2_delete		*del;
3263
3264
	if (initiator) {
3265
		/* Send PAYLOAD_DELETE */
3266
		if ((buf = ibuf_static()) == NULL)
3267
			goto done;
3268
		if ((del = ibuf_advance(buf, sizeof(*del))) == NULL)
3269
			goto done;
3270
		del->del_protoid = IKEV2_SAPROTO_IKE;
3271
		del->del_spisize = 0;
3272
		del->del_nspi = 0;
3273
		if (ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_DELETE,
3274
		    IKEV2_EXCHANGE_INFORMATIONAL, 0) == -1)
3275
			goto done;
3276
		log_debug("%s: sent delete, closing SA", __func__);
3277
done:
3278
		ibuf_release(buf);
3279
		sa_state(env, sa, IKEV2_STATE_CLOSED);
3280
	} else {
3281
		sa_state(env, sa, IKEV2_STATE_CLOSING);
3282
	}
3283
3284
	/* Remove IKE-SA after timeout, e.g. if we don't get a delete */
3285
	timer_set(env, &sa->sa_timer, ikev2_ike_sa_timeout, sa);
3286
	timer_add(env, &sa->sa_timer, IKED_IKE_SA_DELETE_TIMEOUT);
3287
}
3288
3289
void
3290
ikev2_ikesa_recv_delete(struct iked *env, struct iked_sa *sa)
3291
{
3292
	if (sa->sa_nexti) {
3293
		/*
3294
		 * We initiated rekeying, but since sa_nexti is still set
3295
		 * we have to assume that the the peer did not receive our
3296
		 * rekey message. So remove the initiated SA and -- if
3297
		 * sa_nextr is set -- keep the responder SA instead.
3298
		 */
3299
		if (sa->sa_nextr) {
3300
			log_debug("%s: resolving simultaneous IKE SA rekeying",
3301
			    __func__);
3302
			ikev2_ikesa_enable(env, sa, sa->sa_nextr);
3303
		}
3304
		sa_free(env, sa->sa_nexti);
3305
		sa->sa_nextr = sa->sa_nexti = NULL;
3306
	}
3307
	sa_state(env, sa, IKEV2_STATE_CLOSED);
3308
}
3309
3310
int
3311
ikev2_resp_create_child_sa(struct iked *env, struct iked_message *msg)
3312
{
3313
	struct iked_childsa		*csa = NULL;
3314
	struct iked_proposal		*prop;
3315
	struct iked_proposals		 proposals;
3316
	struct iked_kex			*kex, *kextmp = NULL;
3317
	struct iked_sa			*nsa = NULL, *sa = msg->msg_sa;
3318
	struct iked_spi			*spi, *rekey = &msg->msg_rekey;
3319
	struct ikev2_keyexchange	*ke;
3320
	struct ikev2_payload		*pld = NULL;
3321
	struct ibuf			*e = NULL, *nonce = NULL;
3322
	uint8_t				 firstpayload;
3323
	ssize_t				 len = 0;
3324
	int				 initiator, protoid, rekeying = 1;
3325
	int				 ret = -1;
3326
	int				 pfs = 0;
3327
3328
	initiator = sa->sa_hdr.sh_initiator ? 1 : 0;
3329
3330
	if (!ikev2_msg_frompeer(msg) || msg->msg_prop == NULL)
3331
		return (0);
3332
3333
	TAILQ_INIT(&proposals);
3334
3335
	if ((protoid = rekey->spi_protoid) == 0) {
3336
		/*
3337
		 * If REKEY_SA notification is not present, then it's either
3338
		 * IKE SA rekeying or the client wants to create additional
3339
		 * CHILD SAs
3340
		 */
3341
		if (msg->msg_prop->prop_protoid == IKEV2_SAPROTO_IKE) {
3342
			protoid = rekey->spi_protoid = IKEV2_SAPROTO_IKE;
3343
			if (sa->sa_hdr.sh_initiator)
3344
				rekey->spi = sa->sa_hdr.sh_rspi;
3345
			else
3346
				rekey->spi = sa->sa_hdr.sh_ispi;
3347
			rekey->spi_size = 8;
3348
		} else {
3349
			protoid = msg->msg_prop->prop_protoid;
3350
			rekeying = 0;
3351
		}
3352
	}
3353
3354
	if (rekeying)
3355
		log_debug("%s: rekey %s spi %s", __func__,
3356
		    print_map(rekey->spi_protoid, ikev2_saproto_map),
3357
		    print_spi(rekey->spi, rekey->spi_size));
3358
	else
3359
		log_debug("%s: creating new %s SA", __func__,
3360
		    print_map(protoid, ikev2_saproto_map));
3361
3362
	if (protoid == IKEV2_SAPROTO_IKE) {
3363
		/* IKE SA rekeying */
3364
		spi = &msg->msg_prop->prop_peerspi;
3365
3366
		if ((nsa = sa_new(env, spi->spi, 0, 0,
3367
		    msg->msg_policy)) == NULL) {
3368
			log_debug("%s: failed to get new SA", __func__);
3369
			return (ret);
3370
		}
3371
3372
		if (ikev2_sa_responder(env, nsa, sa, msg)) {
3373
			log_debug("%s: failed to get IKE SA keys", __func__);
3374
			return (ret);
3375
		}
3376
3377
		sa_state(env, nsa, IKEV2_STATE_AUTH_SUCCESS);
3378
3379
		nonce = nsa->sa_rnonce;
3380
		kex = &nsa->sa_kex;
3381
	} else {
3382
		/* Child SA creating/rekeying */
3383
3384
		if ((kex = kextmp = calloc(1, sizeof(*kextmp))) == NULL) {
3385
			log_debug("%s: calloc kex", __func__);
3386
			goto fail;
3387
		}
3388
3389
		if (ikev2_sa_negotiate(&proposals,
3390
		    &sa->sa_policy->pol_proposals, &msg->msg_proposals,
3391
		    1) != 0) {
3392
			log_info("%s: no proposal chosen", __func__);
3393
			msg->msg_error = IKEV2_N_NO_PROPOSAL_CHOSEN;
3394
			goto fail;
3395
		}
3396
3397
		/* check KE payload for PFS */
3398
		if (ibuf_length(msg->msg_parent->msg_ke)) {
3399
			log_debug("%s: using PFS", __func__);
3400
			if (ikev2_sa_responder_dh(kex, &proposals,
3401
			    msg->msg_parent, protoid) < 0) {
3402
				log_debug("%s: failed to setup DH", __func__);
3403
				goto fail;
3404
			}
3405
			pfs = 1;
3406
			/* XXX check group against policy ? */
3407
		}
3408
3409
		/* Update peer SPI */
3410
		TAILQ_FOREACH(prop, &proposals, prop_entry) {
3411
			if (prop->prop_protoid == protoid)
3412
				break;
3413
		}
3414
		if (prop == NULL) {
3415
			log_debug("%s: failed to find %s proposals", __func__,
3416
			    print_map(protoid, ikev2_saproto_map));
3417
			goto fail;
3418
		} else
3419
			prop->prop_peerspi = msg->msg_prop->prop_peerspi;
3420
3421
		/* Set rekeying flags on Child SAs */
3422
		if (rekeying) {
3423
			if ((csa = childsa_lookup(sa, rekey->spi,
3424
			    rekey->spi_protoid)) == NULL) {
3425
				log_debug("%s: CHILD SA %s wasn't found",
3426
				    __func__, print_spi(rekey->spi,
3427
					rekey->spi_size));
3428
				/* XXX send notification to peer */
3429
				goto fail;
3430
			}
3431
			if (!csa->csa_loaded || !csa->csa_peersa ||
3432
			    !csa->csa_peersa->csa_loaded) {
3433
				log_debug("%s: SA is not loaded or no peer SA",
3434
				    __func__);
3435
				/* XXX send notification to peer */
3436
				goto fail;
3437
			}
3438
			csa->csa_rekey = 1;
3439
			csa->csa_peersa->csa_rekey = 1;
3440
		}
3441
3442
		/* Update initiator's nonce */
3443
		if (!ibuf_length(msg->msg_nonce)) {
3444
			log_debug("%s: initiator didn't send nonce", __func__);
3445
			goto fail;
3446
		}
3447
		ibuf_release(kex->kex_inonce);
3448
		kex->kex_inonce = ibuf_dup(msg->msg_nonce);
3449
3450
		/* Generate new responder's nonce */
3451
		if ((nonce = ibuf_random(IKED_NONCE_SIZE)) == NULL)
3452
			goto fail;
3453
3454
		/* Update responder's nonce */
3455
		ibuf_release(kex->kex_rnonce);
3456
		kex->kex_rnonce = nonce;
3457
3458
		if (ikev2_childsa_negotiate(env, sa, kex, &proposals, 0,
3459
		    pfs, !rekeying)) {
3460
			log_debug("%s: failed to get CHILD SAs", __func__);
3461
			goto fail;
3462
		}
3463
3464
		if (rekeying && (sa->sa_stateflags & IKED_REQ_CHILDSA) &&
3465
		    csa && (sa->sa_rekeyspi == csa->csa_peerspi)) {
3466
			log_debug("%s: simultanous rekeying for CHILD SA %s/%s",
3467
			    __func__,
3468
			    print_spi(rekey->spi, rekey->spi_size),
3469
			    print_spi(sa->sa_rekeyspi, rekey->spi_size));
3470
			ibuf_release(sa->sa_simult);
3471
			if (ikev2_nonce_cmp(kex->kex_inonce, nonce) < 0)
3472
				sa->sa_simult = ibuf_dup(kex->kex_inonce);
3473
			else
3474
				sa->sa_simult = ibuf_dup(nonce);
3475
		}
3476
	}
3477
3478
	if ((e = ibuf_static()) == NULL)
3479
		goto done;
3480
3481
	/* compression (unless IKE rekeying) */
3482
	if (!nsa && sa->sa_ipcomp &&
3483
	    (len = ikev2_add_ipcompnotify(env, e, &pld, 0, sa)) == -1)
3484
		goto done;
3485
3486
	if (pld) {
3487
		firstpayload = IKEV2_PAYLOAD_NOTIFY;
3488
		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_SA) == -1)
3489
			goto done;
3490
	} else
3491
		firstpayload = IKEV2_PAYLOAD_SA;
3492
3493
	/* SA payload */
3494
	if ((pld = ikev2_add_payload(e)) == NULL)
3495
		goto done;
3496
3497
	if ((len = ikev2_add_proposals(env, nsa ? nsa : sa, e,
3498
		nsa ? &nsa->sa_proposals : &proposals,
3499
		protoid, 0, nsa ? 1 : 0)) == -1)
3500
		goto done;
3501
3502
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONCE) == -1)
3503
		goto done;
3504
3505
	/* NONCE payload */
3506
	if ((pld = ikev2_add_payload(e)) == NULL)
3507
		goto done;
3508
	if (ikev2_add_buf(e, nonce) == -1)
3509
		goto done;
3510
	len = ibuf_size(nonce);
3511
3512
	if (protoid == IKEV2_SAPROTO_IKE || pfs) {
3513
3514
		if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_KE) == -1)
3515
			goto done;
3516
3517
		/* KE payload */
3518
		if ((pld = ikev2_add_payload(e)) == NULL)
3519
			goto done;
3520
		if ((ke = ibuf_advance(e, sizeof(*ke))) == NULL)
3521
			goto done;
3522
		if (kex->kex_dhgroup == NULL) {
3523
			log_debug("%s: invalid dh", __func__);
3524
			goto done;
3525
		}
3526
		ke->kex_dhgroup = htobe16(kex->kex_dhgroup->id);
3527
		if (ikev2_add_buf(e, kex->kex_dhrexchange) == -1)
3528
			goto done;
3529
		len = sizeof(*ke) + dh_getlen(kex->kex_dhgroup);
3530
	}
3531
3532
	if (protoid != IKEV2_SAPROTO_IKE)
3533
		if ((len = ikev2_add_ts(e, &pld, len, sa, initiator)) == -1)
3534
			goto done;
3535
3536
	if (ikev2_next_payload(pld, len, IKEV2_PAYLOAD_NONE) == -1)
3537
		goto done;
3538
3539
	if ((ret = ikev2_msg_send_encrypt(env, sa, &e,
3540
	    IKEV2_EXCHANGE_CREATE_CHILD_SA, firstpayload, 1)) == -1)
3541
		goto done;
3542
3543
	if (protoid == IKEV2_SAPROTO_IKE) {
3544
		/*
3545
		 * If we also have initiated rekeying for this IKE SA, then
3546
		 * sa_nexti is already set. In this case don't enable the new SA
3547
		 * immediately, but record it in sa_nextr, until the exchange
3548
		 * for sa_nexti completes in ikev2_init_create_child_sa() and
3549
		 * the 'winner' can be selected by comparing nonces.
3550
		 */
3551
		if (sa->sa_nexti) {
3552
			log_debug("%s: simultaneous IKE SA rekeying", __func__);
3553
			sa->sa_nextr = nsa;
3554
			ret = 0;
3555
		} else
3556
			ret = ikev2_ikesa_enable(env, sa, nsa);
3557
	} else
3558
		ret = ikev2_childsa_enable(env, sa);
3559
3560
 done:
3561
	if (ret && protoid != IKEV2_SAPROTO_IKE)
3562
		ikev2_childsa_delete(env, sa, 0, 0, NULL, 1);
3563
	ibuf_release(e);
3564
	config_free_proposals(&proposals, 0);
3565
	config_free_kex(kextmp);
3566
	return (ret);
3567
3568
 fail:
3569
	config_free_proposals(&proposals, 0);
3570
	config_free_kex(kextmp);
3571
	return (-1);
3572
}
3573
3574
void
3575
ikev2_ike_sa_timeout(struct iked *env, void *arg)
3576
{
3577
	struct iked_sa			*sa = arg;
3578
3579
	log_debug("%s: closing SA", __func__);
3580
	sa_free(env, sa);
3581
}
3582
3583
void
3584
ikev2_ike_sa_rekey_timeout(struct iked *env, void *arg)
3585
{
3586
	struct iked_sa			*sa = arg;
3587
3588
	log_debug("%s: closing SA", __func__);
3589
	sa_free(env, sa);
3590
}
3591
3592
void
3593
ikev2_ike_sa_rekey_schedule(struct iked *env, struct iked_sa *sa)
3594
{
3595
	timer_add(env, &sa->sa_rekey, (sa->sa_policy->pol_rekey * 850 +
3596
	    arc4random_uniform(100)) / 1000);
3597
}
3598
3599
void
3600
ikev2_ike_sa_alive(struct iked *env, void *arg)
3601
{
3602
	struct iked_sa			*sa = arg;
3603
	struct iked_childsa		*csa = NULL;
3604
	struct timeval			 tv;
3605
	uint64_t			 last_used, diff;
3606
	int				 foundin = 0, foundout = 0;
3607
3608
	/* check for incoming traffic on any child SA */
3609
	TAILQ_FOREACH(csa, &sa->sa_childsas, csa_entry) {
3610
		if (!csa->csa_loaded ||
3611
		    csa->csa_saproto == IKEV2_SAPROTO_IPCOMP)
3612
			continue;
3613
		if (pfkey_sa_last_used(env->sc_pfkey, csa, &last_used) != 0)
3614
			continue;
3615
		gettimeofday(&tv, NULL);
3616
		diff = (uint32_t)(tv.tv_sec - last_used);
3617
		log_debug("%s: %s CHILD SA spi %s last used %llu second(s) ago",
3618
		    __func__,
3619
		    csa->csa_dir == IPSP_DIRECTION_IN ? "incoming" : "outgoing",
3620
		    print_spi(csa->csa_spi.spi, csa->csa_spi.spi_size), diff);
3621
		if (diff < IKED_IKE_SA_ALIVE_TIMEOUT) {
3622
			if (csa->csa_dir == IPSP_DIRECTION_IN) {
3623
				foundin = 1;
3624
				break;
3625
			} else {
3626
				foundout = 1;
3627
			}
3628
		}
3629
	}
3630
3631
	/* send probe if any outging SA has been used, but no incoming SA */
3632
	if (!foundin && foundout) {
3633
		log_debug("%s: sending alive check", __func__);
3634
		ikev2_send_ike_e(env, sa, NULL, IKEV2_PAYLOAD_NONE,
3635
		    IKEV2_EXCHANGE_INFORMATIONAL, 0);
3636
		sa->sa_stateflags |= IKED_REQ_INF;
3637
	}
3638
3639
	/* re-register */
3640
	timer_add(env, &sa->sa_timer, IKED_IKE_SA_ALIVE_TIMEOUT);
3641
}
3642
3643
void
3644
ikev2_ike_sa_keepalive(struct iked *env, void *arg)
3645
{
3646
	struct iked_sa			*sa = arg;
3647
	uint8_t				 marker = 0xff;
3648
3649
	if (sendtofrom(sa->sa_fd, &marker, sizeof(marker), 0,
3650
	    (struct sockaddr *)&sa->sa_peer.addr, sa->sa_peer.addr.ss_len,
3651
	    (struct sockaddr *)&sa->sa_local.addr, sa->sa_local.addr.ss_len)
3652
	    == -1)
3653
		log_warn("%s: sendtofrom: peer %s local %s", __func__,
3654
		    print_host((struct sockaddr *)&sa->sa_peer.addr, NULL, 0),
3655
		    print_host((struct sockaddr *)&sa->sa_local.addr, NULL, 0));
3656
	else
3657
		log_debug("%s: peer %s local %s", __func__,
3658
		    print_host((struct sockaddr *)&sa->sa_peer.addr, NULL, 0),
3659
		    print_host((struct sockaddr *)&sa->sa_local.addr, NULL, 0));
3660
	timer_add(env, &sa->sa_keepalive, IKED_IKE_SA_KEEPALIVE_TIMEOUT);
3661
}
3662
3663
int
3664
ikev2_send_informational(struct iked *env, struct iked_message *msg)
3665
{
3666
	struct iked_message		 resp;
3667
	struct ike_header		*hdr;
3668
	struct ikev2_payload		*pld;
3669
	struct ikev2_notify		*n;
3670
	struct iked_sa			*sa = msg->msg_sa, sah;
3671
	struct ibuf			*buf, *e = NULL;
3672
	int				 ret = -1;
3673
3674
	if (msg->msg_error == 0)
3675
		return (0);
3676
3677
	if ((buf = ikev2_msg_init(env, &resp,
3678
	    &msg->msg_peer, msg->msg_peerlen,
3679
	    &msg->msg_local, msg->msg_locallen, 0)) == NULL)
3680
		goto done;
3681
3682
	/* New encrypted message buffer */
3683
	if ((e = ibuf_static()) == NULL)
3684
		goto done;
3685
3686
	/* NOTIFY payload */
3687
	if ((pld = ikev2_add_payload(e)) == NULL)
3688
		goto done;
3689
3690
	if ((n = ibuf_advance(e, sizeof(*n))) == NULL)
3691
		goto done;
3692
	n->n_protoid = IKEV2_SAPROTO_IKE;	/* XXX ESP etc. */
3693
	n->n_spisize = 0;
3694
	n->n_type = htobe16(msg->msg_error);
3695
3696
	switch (msg->msg_error) {
3697
	case IKEV2_N_INVALID_IKE_SPI:
3698
	case IKEV2_N_NO_PROPOSAL_CHOSEN:
3699
		break;
3700
	default:
3701
		log_debug("%s: unsupported notification %s", __func__,
3702
		    print_map(msg->msg_error, ikev2_n_map));
3703
		goto done;
3704
	}
3705
3706
	if (ikev2_next_payload(pld, sizeof(*n), IKEV2_PAYLOAD_NONE) == -1)
3707
		goto done;
3708
3709
	if (sa != NULL && msg->msg_e) {
3710
		resp.msg_msgid = ikev2_msg_id(env, sa);
3711
3712
		/* IKE header */
3713
		if ((hdr = ikev2_add_header(buf, sa, resp.msg_msgid,
3714
		    IKEV2_PAYLOAD_SK, IKEV2_EXCHANGE_INFORMATIONAL,
3715
		    0)) == NULL)
3716
			goto done;
3717
3718
		if ((pld = ikev2_add_payload(buf)) == NULL)
3719
			goto done;
3720
3721
		/* Encrypt message and add as an E payload */
3722
		if ((e = ikev2_msg_encrypt(env, sa, e)) == NULL) {
3723
			log_debug("%s: encryption failed", __func__);
3724
			goto done;
3725
		}
3726
		if (ibuf_cat(buf, e) != 0)
3727
			goto done;
3728
		if (ikev2_next_payload(pld, ibuf_size(e),
3729
		    IKEV2_PAYLOAD_NOTIFY) == -1)
3730
			goto done;
3731
3732
		if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
3733
			goto done;
3734
3735
		/* Add integrity checksum (HMAC) */
3736
		if (ikev2_msg_integr(env, sa, buf) != 0) {
3737
			log_debug("%s: integrity checksum failed", __func__);
3738
			goto done;
3739
		}
3740
	} else {
3741
		if ((hdr = ibuf_seek(msg->msg_data, 0, sizeof(*hdr))) == NULL)
3742
			goto done;
3743
3744
		bzero(&sah, sizeof(sah));
3745
		sah.sa_hdr.sh_rspi = betoh64(hdr->ike_rspi);
3746
		sah.sa_hdr.sh_ispi = betoh64(hdr->ike_ispi);
3747
		sah.sa_hdr.sh_initiator =
3748
		    hdr->ike_flags & IKEV2_FLAG_INITIATOR ? 0 : 1;
3749
3750
		resp.msg_msgid = ikev2_msg_id(env, &sah);
3751
3752
		/* IKE header */
3753
		if ((hdr = ikev2_add_header(buf, &sah, resp.msg_msgid,
3754
		    IKEV2_PAYLOAD_NOTIFY, IKEV2_EXCHANGE_INFORMATIONAL,
3755
		    0)) == NULL)
3756
			goto done;
3757
		if (ibuf_cat(buf, e) != 0)
3758
			goto done;
3759
		if (ikev2_set_header(hdr, ibuf_size(buf) - sizeof(*hdr)) == -1)
3760
			goto done;
3761
	}
3762
3763
	resp.msg_data = buf;
3764
	resp.msg_fd = msg->msg_fd;
3765
	TAILQ_INIT(&resp.msg_proposals);
3766
3767
	ret = ikev2_msg_send(env, &resp);
3768
3769
 done:
3770
	ibuf_release(e);
3771
	ikev2_msg_cleanup(env, &resp);
3772
3773
	return (ret);
3774
}
3775
3776
ssize_t
3777
ikev2_psk(struct iked_sa *sa, uint8_t *data, size_t length,
3778
    uint8_t **pskptr)
3779
{
3780
	uint8_t		*psk;
3781
	size_t		 psklen = -1;
3782
3783
	if (hash_setkey(sa->sa_prf, data, length) == NULL)
3784
		return (-1);
3785
3786
	if ((psk = calloc(1, hash_keylength(sa->sa_prf))) == NULL)
3787
		return (-1);
3788
3789
	hash_init(sa->sa_prf);
3790
	hash_update(sa->sa_prf, IKEV2_KEYPAD, strlen(IKEV2_KEYPAD));
3791
	hash_final(sa->sa_prf, psk, &psklen);
3792
3793
	*pskptr = psk;
3794
	return (psklen);
3795
}
3796
3797
int
3798
ikev2_match_proposals(struct iked_proposal *local, struct iked_proposal *peer,
3799
    struct iked_transform **xforms, int rekey)
3800
{
3801
	struct iked_transform	*tpeer, *tlocal;
3802
	unsigned int		 i, j, type, score, requiredh = 0;
3803
	uint8_t			 protoid = peer->prop_protoid;
3804
3805
	for (i = 0; i < peer->prop_nxforms; i++) {
3806
		tpeer = peer->prop_xforms + i;
3807
		for (j = 0; j < local->prop_nxforms; j++) {
3808
			tlocal = local->prop_xforms + j;
3809
3810
			/*
3811
			 * We require a DH group for ESP if there is any
3812
			 * local proposal with DH enabled.
3813
			 */
3814
			if (rekey && requiredh == 0 &&
3815
			    protoid == IKEV2_SAPROTO_ESP &&
3816
			    tlocal->xform_type == IKEV2_XFORMTYPE_DH)
3817
				requiredh = 1;
3818
3819
			/* Compare peer and local proposals */
3820
			if (tpeer->xform_type != tlocal->xform_type ||
3821
			    tpeer->xform_id != tlocal->xform_id ||
3822
			    tpeer->xform_length != tlocal->xform_length)
3823
				continue;
3824
			if (tpeer->xform_type > IKEV2_XFORMTYPE_MAX)
3825
				continue;
3826
			type = tpeer->xform_type;
3827
3828
			if (xforms[type] == NULL || tlocal->xform_score <
3829
			    xforms[type]->xform_score) {
3830
				xforms[type] = tlocal;
3831
			} else
3832
				continue;
3833
3834
			print_debug("%s: xform %d <-> %d (%d): %s %s "
3835
			    "(keylength %d <-> %d)", __func__,
3836
			    peer->prop_id, local->prop_id, tlocal->xform_score,
3837
			    print_map(type, ikev2_xformtype_map),
3838
			    print_map(tpeer->xform_id, tpeer->xform_map),
3839
			    tpeer->xform_keylength, tlocal->xform_keylength);
3840
			if (tpeer->xform_length)
3841
				print_debug(" %d", tpeer->xform_length);
3842
			print_debug("\n");
3843
		}
3844
	}
3845
3846
	for (i = score = 0; i < IKEV2_XFORMTYPE_MAX; i++) {
3847
		if (protoid == IKEV2_SAPROTO_IKE && xforms[i] == NULL &&
3848
		    (i == IKEV2_XFORMTYPE_ENCR || i == IKEV2_XFORMTYPE_PRF ||
3849
		     i == IKEV2_XFORMTYPE_INTEGR || i == IKEV2_XFORMTYPE_DH)) {
3850
			score = 0;
3851
			break;
3852
		} else if (protoid == IKEV2_SAPROTO_AH && xforms[i] == NULL &&
3853
		    (i == IKEV2_XFORMTYPE_INTEGR || i == IKEV2_XFORMTYPE_ESN)) {
3854
			score = 0;
3855
			break;
3856
		} else if (protoid == IKEV2_SAPROTO_ESP && xforms[i] == NULL &&
3857
		    (i == IKEV2_XFORMTYPE_ENCR || i == IKEV2_XFORMTYPE_ESN ||
3858
		    (requiredh && i == IKEV2_XFORMTYPE_DH))) {
3859
			score = 0;
3860
			break;
3861
		} else if (xforms[i] == NULL)
3862
			continue;
3863
3864
		score += xforms[i]->xform_score;
3865
	}
3866
3867
	return (score);
3868
}
3869
3870
/*
3871
 * The 'rekey' parameter indicates a CREATE_CHILD_SA exchange where
3872
 * an extra group is necessary for PFS. For the initial IKE_AUTH exchange
3873
 * the ESP SA proposal never includes an explicit DH group.
3874
 */
3875
int
3876
ikev2_sa_negotiate(struct iked_proposals *result, struct iked_proposals *local,
3877
    struct iked_proposals *peer, int rekey)
3878
{
3879
	struct iked_proposal	*ppeer = NULL, *plocal, *prop, vpeer, vlocal;
3880
	struct iked_transform	 chosen[IKEV2_XFORMTYPE_MAX];
3881
	struct iked_transform	*valid[IKEV2_XFORMTYPE_MAX];
3882
	struct iked_transform	*match[IKEV2_XFORMTYPE_MAX];
3883
	unsigned int		 i, score, chosen_score = 0;
3884
	uint8_t			 protoid = 0;
3885
3886
	bzero(valid, sizeof(valid));
3887
	bzero(&vlocal, sizeof(vlocal));
3888
	bzero(&vpeer, sizeof(vpeer));
3889
3890
	if (TAILQ_EMPTY(peer)) {
3891
		log_debug("%s: peer did not send %s proposals", __func__,
3892
		    print_map(protoid, ikev2_saproto_map));
3893
		return (-1);
3894
	}
3895
3896
	TAILQ_FOREACH(plocal, local, prop_entry) {
3897
		TAILQ_FOREACH(ppeer, peer, prop_entry) {
3898
			if (ppeer->prop_protoid != plocal->prop_protoid)
3899
				continue;
3900
			bzero(match, sizeof(match));
3901
			score = ikev2_match_proposals(plocal, ppeer, match,
3902
			    rekey);
3903
			log_debug("%s: score %d", __func__, score);
3904
			if (score && (!chosen_score || score < chosen_score)) {
3905
				chosen_score = score;
3906
				for (i = 0; i < IKEV2_XFORMTYPE_MAX; i++) {
3907
					if ((valid[i] = match[i]))
3908
						memcpy(&chosen[i], match[i],
3909
						    sizeof(chosen[0]));
3910
				}
3911
				memcpy(&vpeer, ppeer, sizeof(vpeer));
3912
				memcpy(&vlocal, plocal, sizeof(vlocal));
3913
			}
3914
		}
3915
		if (chosen_score != 0)
3916
			break;
3917
	}
3918
3919
	if (chosen_score == 0)
3920
		return (-1);
3921
	else if (result == NULL)
3922
		return (0);
3923
3924
	(void)config_free_proposals(result, vpeer.prop_protoid);
3925
	prop = config_add_proposal(result, vpeer.prop_id, vpeer.prop_protoid);
3926
3927
	if (vpeer.prop_localspi.spi_size) {
3928
		prop->prop_localspi.spi_size = vpeer.prop_localspi.spi_size;
3929
		prop->prop_peerspi = vpeer.prop_peerspi;
3930
	}
3931
	if (vlocal.prop_localspi.spi_size) {
3932
		prop->prop_localspi.spi_size = vlocal.prop_localspi.spi_size;
3933
		prop->prop_localspi.spi = vlocal.prop_localspi.spi;
3934
	}
3935
3936
	for (i = 0; i < IKEV2_XFORMTYPE_MAX; i++) {
3937
		if (valid[i] == NULL)
3938
			continue;
3939
		print_debug("%s: score %d: %s %s", __func__,
3940
		    chosen[i].xform_score, print_map(i, ikev2_xformtype_map),
3941
		    print_map(chosen[i].xform_id, chosen[i].xform_map));
3942
		if (chosen[i].xform_length)
3943
			print_debug(" %d", chosen[i].xform_length);
3944
		print_debug("\n");
3945
3946
		if (config_add_transform(prop, chosen[i].xform_type,
3947
		    chosen[i].xform_id, chosen[i].xform_length,
3948
		    chosen[i].xform_keylength) == NULL)
3949
			break;
3950
	}
3951
3952
	return (0);
3953
}
3954
3955
int
3956
ikev2_sa_initiator_dh(struct iked_sa *sa, struct iked_message *msg,
3957
    unsigned int proto)
3958
{
3959
	struct iked_policy	*pol = sa->sa_policy;
3960
	struct iked_transform	*xform;
3961
3962
	if (sa->sa_dhgroup == NULL) {
3963
		if ((xform = config_findtransform(&pol->pol_proposals,
3964
		    IKEV2_XFORMTYPE_DH, proto)) == NULL) {
3965
			log_debug("%s: did not find dh transform", __func__);
3966
			return (-1);
3967
		}
3968
		if ((sa->sa_dhgroup =
3969
		    group_get(xform->xform_id)) == NULL) {
3970
			log_debug("%s: invalid dh %d", __func__,
3971
			    xform->xform_id);
3972
			return (-1);
3973
		}
3974
	}
3975
3976
	if (!ibuf_length(sa->sa_dhiexchange)) {
3977
		if ((sa->sa_dhiexchange = ibuf_new(NULL,
3978
		    dh_getlen(sa->sa_dhgroup))) == NULL) {
3979
			log_debug("%s: failed to alloc dh exchange", __func__);
3980
			return (-1);
3981
		}
3982
		if (dh_create_exchange(sa->sa_dhgroup,
3983
		    sa->sa_dhiexchange->buf) == -1) {
3984
			log_debug("%s: failed to get dh exchange", __func__);
3985
			return (-1);
3986
		}
3987
	}
3988
3989
	/* Initial message */
3990
	if (msg == NULL)
3991
		return (0);
3992
3993
	if (!ibuf_length(sa->sa_dhrexchange)) {
3994
		if (!ibuf_length(msg->msg_ke)) {
3995
			log_debug("%s: invalid peer dh exchange", __func__);
3996
			return (-1);
3997
		}
3998
		if ((ssize_t)ibuf_length(msg->msg_ke) !=
3999
		    dh_getlen(sa->sa_dhgroup)) {
4000
			log_debug("%s: invalid dh length, size %d", __func__,
4001
			    dh_getlen(sa->sa_dhgroup) * 8);
4002
			return (-1);
4003
		}
4004
		if ((sa->sa_dhrexchange = ibuf_dup(msg->msg_ke)) == NULL) {
4005
			log_debug("%s: failed to copy dh exchange", __func__);
4006
			return (-1);
4007
		}
4008
	}
4009
4010
	/* Set a pointer to the peer exchange */
4011
	sa->sa_dhpeer = sa->sa_dhrexchange;
4012
	return (0);
4013
}
4014
4015
int
4016
ikev2_sa_initiator(struct iked *env, struct iked_sa *sa,
4017
    struct iked_sa *osa, struct iked_message *msg)
4018
{
4019
	struct iked_transform	*xform;
4020
4021
	if (ikev2_sa_initiator_dh(sa, msg, 0) < 0)
4022
		return (-1);
4023
4024
	if (!ibuf_length(sa->sa_inonce)) {
4025
		if ((sa->sa_inonce = ibuf_random(IKED_NONCE_SIZE)) == NULL) {
4026
			log_debug("%s: failed to get local nonce", __func__);
4027
			return (-1);
4028
		}
4029
	}
4030
4031
	/* Initial message */
4032
	if (msg == NULL)
4033
		return (0);
4034
4035
	if (!ibuf_length(sa->sa_rnonce)) {
4036
		if (!ibuf_length(msg->msg_nonce)) {
4037
			log_debug("%s: invalid peer nonce", __func__);
4038
			return (-1);
4039
		}
4040
		if ((sa->sa_rnonce = ibuf_dup(msg->msg_nonce)) == NULL) {
4041
			log_debug("%s: failed to get peer nonce", __func__);
4042
			return (-1);
4043
		}
4044
	}
4045
4046
	/* XXX we need a better way to get this */
4047
	if (ikev2_sa_negotiate(&sa->sa_proposals,
4048
	    &msg->msg_policy->pol_proposals, &msg->msg_proposals, 0) != 0) {
4049
		log_info("%s: no proposal chosen", __func__);
4050
		msg->msg_error = IKEV2_N_NO_PROPOSAL_CHOSEN;
4051
		return (-1);
4052
	} else if (sa_stateok(sa, IKEV2_STATE_SA_INIT))
4053
		sa_stateflags(sa, IKED_REQ_SA);
4054
4055
	if (sa->sa_encr == NULL) {
4056
		if ((xform = config_findtransform(&sa->sa_proposals,
4057
		    IKEV2_XFORMTYPE_ENCR, 0)) == NULL) {
4058
			log_debug("%s: did not find encr transform", __func__);
4059
			return (-1);
4060
		}
4061
		if ((sa->sa_encr = cipher_new(xform->xform_type,
4062
		    xform->xform_id, xform->xform_length)) == NULL) {
4063
			log_debug("%s: failed to get encr", __func__);
4064
			return (-1);
4065
		}
4066
	}
4067
4068
	if (sa->sa_prf == NULL) {
4069
		if ((xform = config_findtransform(&sa->sa_proposals,
4070
		    IKEV2_XFORMTYPE_PRF, 0)) == NULL) {
4071
			log_debug("%s: did not find prf transform", __func__);
4072
			return (-1);
4073
		}
4074
		if ((sa->sa_prf =
4075
		    hash_new(xform->xform_type, xform->xform_id)) == NULL) {
4076
			log_debug("%s: failed to get prf", __func__);
4077
			return (-1);
4078
		}
4079
	}
4080
4081
	if (sa->sa_integr == NULL) {
4082
		if ((xform = config_findtransform(&sa->sa_proposals,
4083
		    IKEV2_XFORMTYPE_INTEGR, 0)) == NULL) {
4084
			log_debug("%s: did not find integr transform",
4085
			    __func__);
4086
			return (-1);
4087
		}
4088
		if ((sa->sa_integr =
4089
		    hash_new(xform->xform_type, xform->xform_id)) == NULL) {
4090
			log_debug("%s: failed to get integr", __func__);
4091
			return (-1);
4092
		}
4093
	}
4094
4095
	ibuf_release(sa->sa_2ndmsg);
4096
	if ((sa->sa_2ndmsg = ibuf_dup(msg->msg_data)) == NULL) {
4097
		log_debug("%s: failed to copy 2nd message", __func__);
4098
		return (-1);
4099
	}
4100
4101
	return (ikev2_sa_keys(env, sa, osa ? osa->sa_key_d : NULL));
4102
}
4103
4104
int
4105
ikev2_sa_responder_dh(struct iked_kex *kex, struct iked_proposals *proposals,
4106
    struct iked_message *msg, unsigned int proto)
4107
{
4108
	struct iked_transform	*xform;
4109
4110
	if (kex->kex_dhgroup == NULL) {
4111
		if ((xform = config_findtransform(proposals,
4112
		    IKEV2_XFORMTYPE_DH, proto)) == NULL) {
4113
			log_debug("%s: did not find dh transform", __func__);
4114
			return (-1);
4115
		}
4116
		if ((kex->kex_dhgroup =
4117
		    group_get(xform->xform_id)) == NULL) {
4118
			log_debug("%s: invalid dh %d", __func__,
4119
			    xform->xform_id);
4120
			return (-1);
4121
		}
4122
	}
4123
4124
	if (!ibuf_length(kex->kex_dhrexchange)) {
4125
		if ((kex->kex_dhrexchange = ibuf_new(NULL,
4126
		    dh_getlen(kex->kex_dhgroup))) == NULL) {
4127
			log_debug("%s: failed to alloc dh exchange", __func__);
4128
			return (-1);
4129
		}
4130
		if (dh_create_exchange(kex->kex_dhgroup,
4131
		    kex->kex_dhrexchange->buf) == -1) {
4132
			log_debug("%s: failed to get dh exchange", __func__);
4133
			return (-1);
4134
		}
4135
	}
4136
4137
	if (!ibuf_length(kex->kex_dhiexchange)) {
4138
		if ((kex->kex_dhiexchange = ibuf_dup(msg->msg_ke)) == NULL ||
4139
		    ((ssize_t)ibuf_length(kex->kex_dhiexchange) !=
4140
		    dh_getlen(kex->kex_dhgroup))) {
4141
			/* XXX send notification to peer */
4142
			log_debug("%s: invalid dh, size %d", __func__,
4143
			    dh_getlen(kex->kex_dhgroup) * 8);
4144
			return (-1);
4145
		}
4146
	}
4147
4148
	/* Set a pointer to the peer exchange */
4149
	kex->kex_dhpeer = kex->kex_dhiexchange;
4150
	return (0);
4151
}
4152
4153
int
4154
ikev2_sa_responder(struct iked *env, struct iked_sa *sa, struct iked_sa *osa,
4155
    struct iked_message *msg)
4156
{
4157
	struct iked_transform	*xform;
4158
4159
	sa_state(env, sa, IKEV2_STATE_SA_INIT);
4160
4161
	ibuf_release(sa->sa_1stmsg);
4162
	if ((sa->sa_1stmsg = ibuf_dup(msg->msg_data)) == NULL) {
4163
		log_debug("%s: failed to copy 1st message", __func__);
4164
		return (-1);
4165
	}
4166
4167
	if (!ibuf_length(sa->sa_rnonce) &&
4168
	    (sa->sa_rnonce = ibuf_random(IKED_NONCE_SIZE)) == NULL) {
4169
		log_debug("%s: failed to get local nonce", __func__);
4170
		return (-1);
4171
	}
4172
4173
	if (!ibuf_length(sa->sa_inonce) &&
4174
	    ((ibuf_length(msg->msg_nonce) < IKED_NONCE_MIN) ||
4175
	    (sa->sa_inonce = ibuf_dup(msg->msg_nonce)) == NULL)) {
4176
		log_debug("%s: failed to get peer nonce", __func__);
4177
		return (-1);
4178
	}
4179
4180
	/* XXX we need a better way to get this */
4181
	if (ikev2_sa_negotiate(&sa->sa_proposals,
4182
	    &msg->msg_policy->pol_proposals, &msg->msg_proposals, 0) != 0) {
4183
		log_info("%s: no proposal chosen", __func__);
4184
		msg->msg_error = IKEV2_N_NO_PROPOSAL_CHOSEN;
4185
		return (-1);
4186
	} else if (sa_stateok(sa, IKEV2_STATE_SA_INIT))
4187
		sa_stateflags(sa, IKED_REQ_SA);
4188
4189
	if (sa->sa_encr == NULL) {
4190
		if ((xform = config_findtransform(&sa->sa_proposals,
4191
		    IKEV2_XFORMTYPE_ENCR, 0)) == NULL) {
4192
			log_debug("%s: did not find encr transform", __func__);
4193
			return (-1);
4194
		}
4195
		if ((sa->sa_encr = cipher_new(xform->xform_type,
4196
		    xform->xform_id, xform->xform_length)) == NULL) {
4197
			log_debug("%s: failed to get encr", __func__);
4198
			return (-1);
4199
		}
4200
	}
4201
4202
	if (sa->sa_prf == NULL) {
4203
		if ((xform = config_findtransform(&sa->sa_proposals,
4204
		    IKEV2_XFORMTYPE_PRF, 0)) == NULL) {
4205
			log_debug("%s: did not find prf transform", __func__);
4206
			return (-1);
4207
		}
4208
		if ((sa->sa_prf =
4209
		    hash_new(xform->xform_type, xform->xform_id)) == NULL) {
4210
			log_debug("%s: failed to get prf", __func__);
4211
			return (-1);
4212
		}
4213
	}
4214
4215
	if (sa->sa_integr == NULL) {
4216
		if ((xform = config_findtransform(&sa->sa_proposals,
4217
		    IKEV2_XFORMTYPE_INTEGR, 0)) == NULL) {
4218
			log_debug("%s: did not find integr transform",
4219
			    __func__);
4220
			return (-1);
4221
		}
4222
		if ((sa->sa_integr =
4223
		    hash_new(xform->xform_type, xform->xform_id)) == NULL) {
4224
			log_debug("%s: failed to get integr", __func__);
4225
			return (-1);
4226
		}
4227
	}
4228
4229
	if (ikev2_sa_responder_dh(&sa->sa_kex, &sa->sa_proposals, msg, 0) < 0)
4230
		return (-1);
4231
4232
	return (ikev2_sa_keys(env, sa, osa ? osa->sa_key_d : NULL));
4233
}
4234
4235
int
4236
ikev2_sa_keys(struct iked *env, struct iked_sa *sa, struct ibuf *key)
4237
{
4238
	struct iked_hash	*prf, *integr;
4239
	struct iked_cipher	*encr;
4240
	struct group		*group;
4241
	struct ibuf		*ninr, *dhsecret, *skeyseed, *s, *t;
4242
	size_t			 nonceminlen, ilen, rlen, tmplen;
4243
	uint64_t		 ispi, rspi;
4244
	int			 ret = -1;
4245
4246
	ninr = dhsecret = skeyseed = s = t = NULL;
4247
4248
	if ((encr = sa->sa_encr) == NULL ||
4249
	    (prf = sa->sa_prf) == NULL ||
4250
	    (integr = sa->sa_integr) == NULL ||
4251
	    (group = sa->sa_dhgroup) == NULL) {
4252
		log_debug("%s: failed to get key input data", __func__);
4253
		return (-1);
4254
	}
4255
4256
	if (prf->hash_fixedkey)
4257
		nonceminlen = prf->hash_fixedkey;
4258
	else
4259
		nonceminlen = IKED_NONCE_MIN;
4260
4261
	/* Nonces need a minimal size and should have an even length */
4262
	if (ibuf_length(sa->sa_inonce) < nonceminlen ||
4263
	    (ibuf_length(sa->sa_inonce) % 2) != 0 ||
4264
	    ibuf_length(sa->sa_rnonce) < nonceminlen ||
4265
	    (ibuf_length(sa->sa_rnonce) % 2) != 0) {
4266
		log_debug("%s: invalid nonces", __func__);
4267
		return (-1);
4268
	}
4269
4270
	if (prf->hash_fixedkey) {
4271
		/* Half of the key bits must come from Ni, and half from Nr */
4272
		ilen = prf->hash_fixedkey / 2;
4273
		rlen = prf->hash_fixedkey / 2;
4274
	} else {
4275
		/* Most PRF functions accept a variable-length key */
4276
		ilen = ibuf_length(sa->sa_inonce);
4277
		rlen = ibuf_length(sa->sa_rnonce);
4278
	}
4279
4280
	/*
4281
	 *  Depending on whether we're generating new keying material
4282
	 *  or rekeying existing SA the algorithm is different. If the
4283
	 *  "key" argument is not specified a concatenation of nonces
4284
	 *  (Ni | Nr) is used as a PRF key, otherwise a "key" buffer
4285
	 *  is used and PRF is performed on the concatenation of DH
4286
	 *  exchange result and nonces (g^ir | Ni | Nr).  See sections
4287
	 *  2.14 and 2.18 of RFC5996 for more information.
4288
	 */
4289
4290
	/*
4291
	 *  Generate g^ir
4292
	 */
4293
	if ((dhsecret = ibuf_new(NULL, dh_secretlen(group))) == NULL) {
4294
		log_debug("%s: failed to alloc dh secret", __func__);
4295
		goto done;
4296
	}
4297
	if (dh_create_shared(group, dhsecret->buf,
4298
	    sa->sa_dhpeer->buf) == -1) {
4299
		log_debug("%s: failed to get dh secret"
4300
		    " group %d len %d secretlen %d secret %zu exchange %zu",
4301
		     __func__,
4302
		    group->id, dh_getlen(group), dh_secretlen(group),
4303
		    ibuf_length(dhsecret), ibuf_length(sa->sa_dhpeer));
4304
		goto done;
4305
	}
4306
4307
	log_debug("%s: DHSECRET with %zu bytes", __func__,
4308
	    ibuf_length(dhsecret));
4309
	print_hex(dhsecret->buf, 0, ibuf_length(dhsecret));
4310
4311
	if (!key) {
4312
		/*
4313
		 * Set PRF key to generate SKEEYSEED = prf(Ni | Nr, g^ir)
4314
		 */
4315
		if ((ninr = ibuf_new(sa->sa_inonce->buf, ilen)) == NULL ||
4316
		    ibuf_add(ninr, sa->sa_rnonce->buf, rlen) != 0) {
4317
			log_debug("%s: failed to get nonce key buffer",
4318
			    __func__);
4319
			goto done;
4320
		}
4321
		key = ninr;
4322
	} else {
4323
		/*
4324
		 * Set PRF key to generate SKEEYSEED = prf(key, g^ir | Ni | Nr)
4325
		 */
4326
		if (ibuf_add(dhsecret, sa->sa_inonce->buf, ilen) != 0 ||
4327
		    ibuf_add(dhsecret, sa->sa_rnonce->buf, rlen) != 0) {
4328
			log_debug("%s: failed to get nonce key buffer",
4329
			    __func__);
4330
			goto done;
4331
		}
4332
	}
4333
4334
	if ((hash_setkey(prf, key->buf, ibuf_length(key))) == NULL) {
4335
		log_debug("%s: failed to set prf key", __func__);
4336
		goto done;
4337
	}
4338
4339
	if ((skeyseed = ibuf_new(NULL, hash_length(prf))) == NULL) {
4340
		log_debug("%s: failed to get SKEYSEED buffer", __func__);
4341
		goto done;
4342
	}
4343
4344
	tmplen = 0;
4345
	hash_init(prf);
4346
	hash_update(prf, dhsecret->buf, ibuf_length(dhsecret));
4347
	hash_final(prf, skeyseed->buf, &tmplen);
4348
4349
	log_debug("%s: SKEYSEED with %zu bytes", __func__, tmplen);
4350
	print_hex(skeyseed->buf, 0, tmplen);
4351
4352
	if (ibuf_setsize(skeyseed, tmplen) == -1) {
4353
		log_debug("%s: failed to set keymaterial length", __func__);
4354
		goto done;
4355
	}
4356
4357
	/*
4358
	 * Now generate the key material
4359
	 *
4360
	 * S = Ni | Nr | SPIi | SPIr
4361
	 */
4362
4363
	/* S = Ni | Nr | SPIi | SPIr */
4364
	ilen = ibuf_length(sa->sa_inonce);
4365
	rlen = ibuf_length(sa->sa_rnonce);
4366
	ispi = htobe64(sa->sa_hdr.sh_ispi);
4367
	rspi = htobe64(sa->sa_hdr.sh_rspi);
4368
4369
	if ((s = ibuf_new(sa->sa_inonce->buf, ilen)) == NULL ||
4370
	    ibuf_add(s, sa->sa_rnonce->buf, rlen) != 0 ||
4371
	    ibuf_add(s, &ispi, sizeof(ispi)) != 0 ||
4372
	    ibuf_add(s, &rspi, sizeof(rspi)) != 0) {
4373
		log_debug("%s: failed to set S buffer", __func__);
4374
		goto done;
4375
	}
4376
4377
	log_debug("%s: S with %zu bytes", __func__, ibuf_length(s));
4378
	print_hex(s->buf, 0, ibuf_length(s));
4379
4380
	/*
4381
	 * Get the size of the key material we need and the number
4382
	 * of rounds we need to run the prf+ function.
4383
	 */
4384
	ilen = hash_length(prf) +	/* SK_d */
4385
	    hash_keylength(integr) +	/* SK_ai */
4386
	    hash_keylength(integr) +	/* SK_ar */
4387
	    cipher_keylength(encr) +	/* SK_ei */
4388
	    cipher_keylength(encr) +	/* SK_er */
4389
	    hash_keylength(prf) +	/* SK_pi */
4390
	    hash_keylength(prf);	/* SK_pr */
4391
4392
	if ((t = ikev2_prfplus(prf, skeyseed, s, ilen)) == NULL) {
4393
		log_debug("%s: failed to get IKE SA key material", __func__);
4394
		goto done;
4395
	}
4396
4397
	/* ibuf_get() returns a new buffer from the next read offset */
4398
	if ((sa->sa_key_d = ibuf_get(t, hash_length(prf))) == NULL ||
4399
	    (sa->sa_key_iauth = ibuf_get(t, hash_keylength(integr))) == NULL ||
4400
	    (sa->sa_key_rauth = ibuf_get(t, hash_keylength(integr))) == NULL ||
4401
	    (sa->sa_key_iencr = ibuf_get(t, cipher_keylength(encr))) == NULL ||
4402
	    (sa->sa_key_rencr = ibuf_get(t, cipher_keylength(encr))) == NULL ||
4403
	    (sa->sa_key_iprf = ibuf_get(t, hash_length(prf))) == NULL ||
4404
	    (sa->sa_key_rprf = ibuf_get(t, hash_length(prf))) == NULL) {
4405
		log_debug("%s: failed to get SA keys", __func__);
4406
		goto done;
4407
	}
4408
4409
	log_debug("%s: SK_d with %zu bytes", __func__,
4410
	    ibuf_length(sa->sa_key_d));
4411
	print_hex(sa->sa_key_d->buf, 0, ibuf_length(sa->sa_key_d));
4412
	log_debug("%s: SK_ai with %zu bytes", __func__,
4413
	    ibuf_length(sa->sa_key_iauth));
4414
	print_hex(sa->sa_key_iauth->buf, 0, ibuf_length(sa->sa_key_iauth));
4415
	log_debug("%s: SK_ar with %zu bytes", __func__,
4416
	    ibuf_length(sa->sa_key_rauth));
4417
	print_hex(sa->sa_key_rauth->buf, 0, ibuf_length(sa->sa_key_rauth));
4418
	log_debug("%s: SK_ei with %zu bytes", __func__,
4419
	    ibuf_length(sa->sa_key_iencr));
4420
	print_hex(sa->sa_key_iencr->buf, 0, ibuf_length(sa->sa_key_iencr));
4421
	log_debug("%s: SK_er with %zu bytes", __func__,
4422
	    ibuf_length(sa->sa_key_rencr));
4423
	print_hex(sa->sa_key_rencr->buf, 0, ibuf_length(sa->sa_key_rencr));
4424
	log_debug("%s: SK_pi with %zu bytes", __func__,
4425
	    ibuf_length(sa->sa_key_iprf));
4426
	print_hex(sa->sa_key_iprf->buf, 0, ibuf_length(sa->sa_key_iprf));
4427
	log_debug("%s: SK_pr with %zu bytes", __func__,
4428
	    ibuf_length(sa->sa_key_rprf));
4429
	print_hex(sa->sa_key_rprf->buf, 0, ibuf_length(sa->sa_key_rprf));
4430
4431
	ret = 0;
4432
4433
 done:
4434
	ibuf_release(ninr);
4435
	ibuf_release(dhsecret);
4436
	ibuf_release(skeyseed);
4437
	ibuf_release(s);
4438
	ibuf_release(t);
4439
4440
	return (ret);
4441
}
4442
4443
void
4444
ikev2_sa_cleanup_dh(struct iked_sa *sa)
4445
{
4446
	ibuf_release(sa->sa_dhiexchange);
4447
	ibuf_release(sa->sa_dhrexchange);
4448
	group_free(sa->sa_dhgroup);
4449
	sa->sa_dhiexchange = NULL;
4450
	sa->sa_dhrexchange = NULL;
4451
	sa->sa_dhgroup = NULL;
4452
}
4453
4454
struct ibuf *
4455
ikev2_prfplus(struct iked_hash *prf, struct ibuf *key, struct ibuf *seed,
4456
    size_t keymatlen)
4457
{
4458
	struct ibuf	*t = NULL, *t1 = NULL, *t2 = NULL;
4459
	size_t		 rlen, i, hashlen = 0;
4460
	uint8_t		 pad = 0;
4461
4462
	/*
4463
	 * prf+ (K, S) = T1 | T2 | T3 | T4 | ...
4464
	 *
4465
	 * T1 = prf (K, S | 0x01)
4466
	 * T2 = prf (K, T1 | S | 0x02)
4467
	 * T3 = prf (K, T2 | S | 0x03)
4468
	 * T4 = prf (K, T3 | S | 0x04)
4469
	 */
4470
4471
	if ((hash_setkey(prf, ibuf_data(key), ibuf_size(key))) == NULL) {
4472
		log_debug("%s: failed to set prf+ key", __func__);
4473
		goto fail;
4474
	}
4475
4476
	if ((t = ibuf_new(NULL, 0)) == NULL) {
4477
		log_debug("%s: failed to get T buffer", __func__);
4478
		goto fail;
4479
	}
4480
4481
	rlen = roundup(keymatlen, hash_length(prf)) / hash_length(prf);
4482
	if (rlen > 255)
4483
		fatalx("ikev2_prfplus: key material too large");
4484
4485
	for (i = 0; i < rlen; i++) {
4486
		if (t1 != NULL) {
4487
			t2 = ibuf_new(t1->buf, ibuf_length(t1));
4488
			ibuf_release(t1);
4489
		} else
4490
			t2 = ibuf_new(NULL, 0);
4491
		t1 = ibuf_new(NULL, hash_length(prf));
4492
4493
		ibuf_add(t2, seed->buf, ibuf_length(seed));
4494
		pad = i + 1;
4495
		ibuf_add(t2, &pad, 1);
4496
4497
		hash_init(prf);
4498
		hash_update(prf, t2->buf, ibuf_length(t2));
4499
		hash_final(prf, t1->buf, &hashlen);
4500
4501
		if (hashlen != hash_length(prf))
4502
			fatalx("ikev2_prfplus: hash length mismatch");
4503
4504
		ibuf_release(t2);
4505
		ibuf_add(t, t1->buf, ibuf_length(t1));
4506
4507
		log_debug("%s: T%d with %zu bytes", __func__,
4508
		    pad, ibuf_length(t1));
4509
		print_hex(t1->buf, 0, ibuf_length(t1));
4510
	}
4511
4512
	log_debug("%s: Tn with %zu bytes", __func__, ibuf_length(t));
4513
	print_hex(t->buf, 0, ibuf_length(t));
4514
4515
	ibuf_release(t1);
4516
4517
	return (t);
4518
4519
 fail:
4520
	ibuf_release(t1);
4521
	ibuf_release(t);
4522
4523
	return (NULL);
4524
}
4525
4526
int
4527
ikev2_sa_tag(struct iked_sa *sa, struct iked_id *id)
4528
{
4529
	char	*format, *domain = NULL, *idrepl = NULL;
4530
	char	 idstr[IKED_ID_SIZE];
4531
	int	 ret = -1;
4532
	size_t	 len;
4533
4534
	free(sa->sa_tag);
4535
	sa->sa_tag = NULL;
4536
	format = sa->sa_policy->pol_tag;
4537
4538
	len = IKED_TAG_SIZE;
4539
	if ((sa->sa_tag = calloc(1, len)) == NULL) {
4540
		log_debug("%s: calloc", __func__);
4541
		goto fail;
4542
	}
4543
	if (strlcpy(sa->sa_tag, format, len) >= len) {
4544
		log_debug("%s: tag too long", __func__);
4545
		goto fail;
4546
	}
4547
4548
	if (ikev2_print_id(id, idstr, sizeof(idstr)) == -1) {
4549
		log_debug("%s: invalid id", __func__);
4550
		goto fail;
4551
	}
4552
4553
	/* ASN.1 DER IDs are too long, use the CN part instead */
4554
	if ((id->id_type == IKEV2_ID_ASN1_DN) &&
4555
	    (idrepl = strstr(idstr, "CN=")) != NULL) {
4556
		domain = strstr(idrepl, "emailAddress=");
4557
		idrepl[strcspn(idrepl, "/")] = '\0';
4558
	} else
4559
		idrepl = idstr;
4560
4561
	if (strstr(format, "$id") != NULL) {
4562
		if (expand_string(sa->sa_tag, len, "$id", idrepl) != 0) {
4563
			log_debug("%s: failed to expand tag", __func__);
4564
			goto fail;
4565
		}
4566
	}
4567
4568
	if (strstr(format, "$eapid") != NULL && sa->sa_eapid != NULL) {
4569
		if (expand_string(sa->sa_tag, len, "$eapid",
4570
		    sa->sa_eapid) != 0) {
4571
			log_debug("%s: failed to expand tag", __func__);
4572
			goto fail;
4573
		}
4574
	}
4575
4576
	if (strstr(format, "$name") != NULL) {
4577
		if (expand_string(sa->sa_tag, len, "$name",
4578
		    sa->sa_policy->pol_name) != 0) {
4579
			log_debug("%s: failed to expand tag", __func__);
4580
			goto fail;
4581
		}
4582
	}
4583
4584
	if (strstr(format, "$domain") != NULL) {
4585
		if (id->id_type == IKEV2_ID_FQDN)
4586
			domain = strchr(idrepl, '.');
4587
		else if (id->id_type == IKEV2_ID_UFQDN)
4588
			domain = strchr(idrepl, '@');
4589
		else if (*idstr == '/' && domain != NULL)
4590
			domain = strchr(domain, '@');
4591
		else
4592
			domain = NULL;
4593
		if (domain == NULL || strlen(domain) < 2) {
4594
			log_debug("%s: no valid domain in ID %s",
4595
			    __func__, idstr);
4596
			goto fail;
4597
		}
4598
		domain++;
4599
		if (expand_string(sa->sa_tag, len, "$domain", domain) != 0) {
4600
			log_debug("%s: failed to expand tag", __func__);
4601
			goto fail;
4602
		}
4603
	}
4604
4605
	log_debug("%s: %s (%zu)", __func__, sa->sa_tag, strlen(sa->sa_tag));
4606
4607
	ret = 0;
4608
 fail:
4609
	if (ret != 0) {
4610
		free(sa->sa_tag);
4611
		sa->sa_tag = NULL;
4612
	}
4613
4614
	return (ret);
4615
}
4616
4617
int
4618
ikev2_childsa_delete_proposed(struct iked *env, struct iked_sa *sa,
4619
    struct iked_proposals *proposals)
4620
{
4621
	struct ibuf			*buf = NULL;
4622
	struct iked_proposal		*prop;
4623
	struct ikev2_delete		*del;
4624
	uint32_t			 spi32;
4625
	uint8_t				 protoid = 0;
4626
	int				 ret = -1, count;
4627
4628
	if (!sa_stateok(sa, IKEV2_STATE_VALID))
4629
		return (-1);
4630
4631
	count = 0;
4632
	TAILQ_FOREACH(prop, proposals, prop_entry) {
4633
		if (ikev2_valid_proposal(prop, NULL, NULL, NULL) != 0)
4634
			continue;
4635
		protoid = prop->prop_protoid;
4636
		count++;
4637
	}
4638
	if (count == 0)
4639
		return (0);
4640
	if ((buf = ibuf_static()) == NULL)
4641
		return (-1);
4642
	if ((del = ibuf_advance(buf, sizeof(*del))) == NULL)
4643
		goto done;
4644
	/* XXX we assume all have the same protoid */
4645
	del->del_protoid = protoid;
4646
	del->del_spisize = 4;
4647
	del->del_nspi = htobe16(count);
4648
4649
	TAILQ_FOREACH(prop, proposals, prop_entry) {
4650
		if (ikev2_valid_proposal(prop, NULL, NULL, NULL) != 0)
4651
			continue;
4652
		spi32 = htobe32(prop->prop_localspi.spi);
4653
		if (ibuf_add(buf, &spi32, sizeof(spi32)))
4654
			goto done;
4655
	}
4656
4657
	if (ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_DELETE,
4658
	    IKEV2_EXCHANGE_INFORMATIONAL, 0) == -1)
4659
		goto done;
4660
	sa->sa_stateflags |= IKED_REQ_INF;
4661
	ret = 0;
4662
 done:
4663
	ibuf_release(buf);
4664
4665
	return (ret);
4666
}
4667
4668
int
4669
ikev2_childsa_negotiate(struct iked *env, struct iked_sa *sa,
4670
    struct iked_kex *kex, struct iked_proposals *proposals, int initiator,
4671
    int pfs, int acquired)
4672
{
4673
	struct iked_proposal	*prop;
4674
	struct iked_transform	*xform, *encrxf = NULL, *integrxf = NULL;
4675
	struct iked_childsa	*csa, *csb;
4676
	struct iked_flow	*flow, *saflow, *flowa, *flowb;
4677
	struct ibuf		*keymat = NULL, *seed = NULL, *dhsecret = NULL;
4678
	struct group		*group;
4679
	uint32_t		 spi = 0;
4680
	unsigned int		 i;
4681
	size_t			 ilen = 0;
4682
	int			 esn, skip, ret = -1;
4683
4684
	if (!sa_stateok(sa, IKEV2_STATE_VALID))
4685
		return (-1);
4686
4687
	if (ikev2_sa_tag(sa, IKESA_DSTID(sa)) == -1)
4688
		return (-1);
4689
4690
	/* We need to determine the key material length first */
4691
	TAILQ_FOREACH(prop, proposals, prop_entry) {
4692
		if (prop->prop_protoid == IKEV2_SAPROTO_IKE)
4693
			continue;
4694
		log_debug("%s: proposal %d", __func__, prop->prop_id);
4695
		for (i = 0; i < prop->prop_nxforms; i++) {
4696
			xform = prop->prop_xforms + i;
4697
			xform->xform_keylength =
4698
			    keylength_xf(prop->prop_protoid,
4699
			    xform->xform_type, xform->xform_id);
4700
4701
			switch (xform->xform_type) {
4702
			case IKEV2_XFORMTYPE_ENCR:
4703
			case IKEV2_XFORMTYPE_INTEGR:
4704
				if (xform->xform_length)
4705
					xform->xform_keylength =
4706
					    xform->xform_length;
4707
				xform->xform_keylength +=
4708
				    noncelength_xf(xform->xform_type,
4709
				    xform->xform_id);
4710
				ilen += xform->xform_keylength / 8;
4711
				break;
4712
			}
4713
		}
4714
	}
4715
4716
	/* double key material length for inbound/outbound */
4717
	ilen *= 2;
4718
4719
	log_debug("%s: key material length %zu", __func__, ilen);
4720
4721
	if ((seed = ibuf_new(NULL, 0)) == NULL) {
4722
		log_debug("%s: failed to setup IKE SA key material", __func__);
4723
		goto done;
4724
	}
4725
	if (pfs) {
4726
		log_debug("%s: using PFS", __func__);
4727
		if (kex->kex_dhpeer == NULL ||
4728
		    ibuf_length(kex->kex_dhpeer) == 0 ||
4729
		    (group = kex->kex_dhgroup) == NULL) {
4730
			log_debug("%s: no dh group for pfs", __func__);
4731
			goto done;
4732
		}
4733
		if ((dhsecret = ibuf_new(NULL, dh_secretlen(group))) == NULL) {
4734
			log_debug("%s: failed to alloc dh secret", __func__);
4735
			goto done;
4736
		}
4737
		if (dh_create_shared(group, dhsecret->buf,
4738
		    kex->kex_dhpeer->buf) == -1) {
4739
			log_debug("%s: failed to get dh secret"
4740
			    " group %d len %d secretlen %d secret %zu"
4741
			    " exchange %zu", __func__, group->id,
4742
			    dh_getlen(group), dh_secretlen(group),
4743
			    ibuf_length(dhsecret),
4744
			    ibuf_length(kex->kex_dhpeer));
4745
			goto done;
4746
		}
4747
		if (ibuf_cat(seed, dhsecret) != 0) {
4748
			log_debug("%s: failed to set dh secret", __func__);
4749
			goto done;
4750
		}
4751
	}
4752
	if (ibuf_cat(seed, kex->kex_inonce) != 0 ||
4753
	    ibuf_cat(seed, kex->kex_rnonce) != 0 ||
4754
	    (keymat = ikev2_prfplus(sa->sa_prf,
4755
	    sa->sa_key_d, seed, ilen)) == NULL) {
4756
		log_debug("%s: failed to get IKE SA key material", __func__);
4757
		goto done;
4758
	}
4759
4760
	/* Create the new flows */
4761
	TAILQ_FOREACH(prop, proposals, prop_entry) {
4762
		if (ikev2_valid_proposal(prop, NULL, NULL, NULL) != 0)
4763
			continue;
4764
4765
		RB_FOREACH(flow, iked_flows, &sa->sa_policy->pol_flows) {
4766
4767
			if ((flowa = calloc(1, sizeof(*flowa))) == NULL) {
4768
				log_debug("%s: failed to get flow", __func__);
4769
				goto done;
4770
			}
4771
4772
			memcpy(flowa, flow, sizeof(*flow));
4773
			flowa->flow_dir = IPSP_DIRECTION_OUT;
4774
			flowa->flow_saproto = prop->prop_protoid;
4775
			flowa->flow_local = &sa->sa_local;
4776
			flowa->flow_peer = &sa->sa_peer;
4777
			flowa->flow_ikesa = sa;
4778
			ikev2_cp_fixaddr(sa, &flow->flow_dst, &flowa->flow_dst);
4779
4780
			skip = 0;
4781
			TAILQ_FOREACH(saflow, &sa->sa_flows, flow_entry) {
4782
				if (flow_equal(saflow, flowa)) {
4783
					skip = 1;
4784
					break;
4785
				}
4786
			}
4787
			if (skip) {
4788
				flow_free(flowa);
4789
				continue;
4790
			}
4791
4792
			if ((flowb = calloc(1, sizeof(*flowb))) == NULL) {
4793
				log_debug("%s: failed to get flow", __func__);
4794
				flow_free(flowa);
4795
				goto done;
4796
			}
4797
4798
			memcpy(flowb, flowa, sizeof(*flow));
4799
4800
			flowb->flow_dir = IPSP_DIRECTION_IN;
4801
			memcpy(&flowb->flow_src, &flow->flow_dst,
4802
			    sizeof(flow->flow_dst));
4803
			memcpy(&flowb->flow_dst, &flow->flow_src,
4804
			    sizeof(flow->flow_src));
4805
			ikev2_cp_fixaddr(sa, &flow->flow_dst, &flowb->flow_src);
4806
4807
			TAILQ_INSERT_TAIL(&sa->sa_flows, flowa, flow_entry);
4808
			TAILQ_INSERT_TAIL(&sa->sa_flows, flowb, flow_entry);
4809
		}
4810
	}
4811
4812
	/* create the CHILD SAs using the key material */
4813
	TAILQ_FOREACH(prop, proposals, prop_entry) {
4814
		if (ikev2_valid_proposal(prop, &encrxf, &integrxf, &esn) != 0)
4815
			continue;
4816
4817
		spi = 0;
4818
4819
		if ((csa = calloc(1, sizeof(*csa))) == NULL) {
4820
			log_debug("%s: failed to get CHILD SA", __func__);
4821
			goto done;
4822
		}
4823
4824
		csa->csa_saproto = prop->prop_protoid;
4825
		csa->csa_ikesa = sa;
4826
		csa->csa_spi.spi_protoid = prop->prop_protoid;
4827
		csa->csa_esn = esn;
4828
		csa->csa_acquired = acquired;
4829
4830
		/* Set up responder's SPIs */
4831
		if (initiator) {
4832
			csa->csa_dir = IPSP_DIRECTION_OUT;
4833
			csa->csa_local = &sa->sa_local;
4834
			csa->csa_peer = &sa->sa_peer;
4835
			csa->csa_peerspi = prop->prop_localspi.spi;
4836
			csa->csa_spi.spi = prop->prop_peerspi.spi;
4837
			csa->csa_spi.spi_size = prop->prop_peerspi.spi_size;
4838
		} else {
4839
			csa->csa_dir = IPSP_DIRECTION_IN;
4840
			csa->csa_local = &sa->sa_peer;
4841
			csa->csa_peer = &sa->sa_local;
4842
4843
			if ((ret = pfkey_sa_init(env->sc_pfkey, csa,
4844
			    &spi)) != 0)
4845
				goto done;
4846
			csa->csa_allocated = 1;
4847
4848
			csa->csa_peerspi = prop->prop_peerspi.spi;
4849
			csa->csa_spi.spi = prop->prop_localspi.spi = spi;
4850
			csa->csa_spi.spi_size = 4;
4851
		}
4852
4853
		if (encrxf && (csa->csa_encrkey = ibuf_get(keymat,
4854
		    encrxf->xform_keylength / 8)) == NULL) {
4855
			log_debug("%s: failed to get CHILD SA encryption key",
4856
			    __func__);
4857
			childsa_free(csa);
4858
			goto done;
4859
		}
4860
		if (integrxf && (csa->csa_integrkey = ibuf_get(keymat,
4861
		    integrxf->xform_keylength / 8)) == NULL) {
4862
			log_debug("%s: failed to get CHILD SA integrity key",
4863
			    __func__);
4864
			childsa_free(csa);
4865
			goto done;
4866
		}
4867
		if (encrxf)
4868
			csa->csa_encrid = encrxf->xform_id;
4869
		if (integrxf)
4870
			csa->csa_integrid = integrxf->xform_id;
4871
4872
		if ((csb = calloc(1, sizeof(*csb))) == NULL) {
4873
			log_debug("%s: failed to get CHILD SA", __func__);
4874
			childsa_free(csa);
4875
			goto done;
4876
		}
4877
4878
		memcpy(csb, csa, sizeof(*csb));
4879
4880
		/* Set up initiator's SPIs */
4881
		csb->csa_spi.spi = csa->csa_peerspi;
4882
		csb->csa_peerspi = csa->csa_spi.spi;
4883
		csb->csa_allocated = csa->csa_allocated ? 0 : 1;
4884
		csb->csa_dir = csa->csa_dir == IPSP_DIRECTION_IN ?
4885
		    IPSP_DIRECTION_OUT : IPSP_DIRECTION_IN;
4886
		csb->csa_local = csa->csa_peer;
4887
		csb->csa_peer = csa->csa_local;
4888
4889
		if (encrxf && (csb->csa_encrkey = ibuf_get(keymat,
4890
		    encrxf->xform_keylength / 8)) == NULL) {
4891
			log_debug("%s: failed to get CHILD SA encryption key",
4892
			    __func__);
4893
			childsa_free(csa);
4894
			childsa_free(csb);
4895
			goto done;
4896
		}
4897
		if (integrxf && (csb->csa_integrkey = ibuf_get(keymat,
4898
		    integrxf->xform_keylength / 8)) == NULL) {
4899
			log_debug("%s: failed to get CHILD SA integrity key",
4900
			    __func__);
4901
			childsa_free(csa);
4902
			childsa_free(csb);
4903
			goto done;
4904
		}
4905
4906
		TAILQ_INSERT_TAIL(&sa->sa_childsas, csa, csa_entry);
4907
		TAILQ_INSERT_TAIL(&sa->sa_childsas, csb, csa_entry);
4908
4909
		csa->csa_peersa = csb;
4910
		csb->csa_peersa = csa;
4911
	}
4912
4913
	ret = 0;
4914
 done:
4915
	ibuf_release(dhsecret);
4916
	ibuf_release(keymat);
4917
	ibuf_release(seed);
4918
4919
	return (ret);
4920
}
4921
4922
/* free a replaced IPCOMP SA */
4923
void
4924
ikev2_ipcomp_csa_free(struct iked *env, struct iked_childsa *csa)
4925
{
4926
	if (csa->csa_children)
4927
		fatalx("ikev2_ipcomp_csa_free: has children");
4928
	if (csa->csa_ikesa)
4929
		TAILQ_REMOVE(&csa->csa_ikesa->sa_childsas, csa,
4930
		    csa_entry);
4931
	if (csa->csa_loaded) {
4932
		log_debug("%s: csa %p loaded: calling pfkey_sa_delete",
4933
		    __func__, csa);
4934
		pfkey_sa_delete(env->sc_pfkey, csa);
4935
		RB_REMOVE(iked_activesas, &env->sc_activesas, csa);
4936
	}
4937
	childsa_free(csa);
4938
}
4939
4940
int
4941
ikev2_ipcomp_enable(struct iked *env, struct iked_sa *sa)
4942
{
4943
	struct iked_childsa	*other, *nother, *csa = NULL, *csb = NULL;
4944
	struct iked_flow	*flow, *flowa = NULL, *flowb = NULL;
4945
	struct iked_flow	*flowc = NULL, *flowd = NULL;
4946
	struct iked_flow	*nflow, *oflow;
4947
4948
	if ((csa = calloc(1, sizeof(*csa))) == NULL ||
4949
	    (csb = calloc(1, sizeof(*csb))) == NULL ||
4950
	    (flowa = calloc(1, sizeof(*flowa))) == NULL ||
4951
	    (flowb = calloc(1, sizeof(*flowb))) == NULL ||
4952
	    (flowc = calloc(1, sizeof(*flowc))) == NULL ||
4953
	    (flowd = calloc(1, sizeof(*flowd))) == NULL) {
4954
		free(csa);
4955
		free(csb);
4956
		free(flowa);
4957
		free(flowb);
4958
		free(flowc);
4959
		free(flowd);
4960
		return (-1);
4961
	}
4962
4963
	/* switch ESP SAs to transport mode */
4964
	TAILQ_FOREACH(other, &sa->sa_childsas, csa_entry) {
4965
		if (!other->csa_rekey && !other->csa_loaded &&
4966
		    other->csa_saproto == IKEV2_SAPROTO_ESP) {
4967
			other->csa_transport = 1;
4968
			if (other->csa_dir == IPSP_DIRECTION_OUT) {
4969
				other->csa_parent = csa;
4970
				csa->csa_children++;
4971
			} else {
4972
				other->csa_parent = csb;
4973
				csb->csa_children++;
4974
			}
4975
		}
4976
	}
4977
4978
	/* install IPCOMP SAs */
4979
	csa->csa_ikesa = sa;
4980
	csa->csa_saproto = IKEV2_SAPROTO_IPCOMP;
4981
	csa->csa_spi.spi_size = 2;
4982
	csa->csa_spi.spi = sa->sa_cpi_out;
4983
	csa->csa_peerspi = sa->sa_cpi_in;
4984
	csa->csa_dir = IPSP_DIRECTION_OUT;
4985
	csa->csa_local = &sa->sa_local;
4986
	csa->csa_peer = &sa->sa_peer;
4987
4988
	memcpy(csb, csa, sizeof(*csb));
4989
	csb->csa_spi.spi = csa->csa_peerspi;
4990
	csb->csa_peerspi = csa->csa_spi.spi;
4991
	csb->csa_dir = IPSP_DIRECTION_IN;
4992
	csb->csa_local = csa->csa_peer;
4993
	csb->csa_peer = csa->csa_local;
4994
	csb->csa_allocated = 1;
4995
4996
	/* remove old replaced IPCOMP SAs */
4997
	TAILQ_FOREACH_SAFE(other, &sa->sa_childsas, csa_entry, nother) {
4998
		if (other->csa_saproto != IKEV2_SAPROTO_IPCOMP ||
4999
		    other->csa_children != 0)
5000
			continue;
5001
		if (other->csa_dir == csa->csa_dir &&
5002
		    IKED_ADDR_EQ(other->csa_local, csa->csa_local) &&
5003
		    IKED_ADDR_EQ(other->csa_peer, csa->csa_peer)) {
5004
			log_debug("%s: csa %p replaces %p",
5005
			    __func__, csa, other);
5006
			ikev2_ipcomp_csa_free(env, other);
5007
		} else if (other->csa_dir == csb->csa_dir &&
5008
		    IKED_ADDR_EQ(other->csa_local, csb->csa_local) &&
5009
		    IKED_ADDR_EQ(other->csa_peer, csb->csa_peer)) {
5010
			log_debug("%s: csa %p replaces %p",
5011
			    __func__, csb, other);
5012
			ikev2_ipcomp_csa_free(env, other);
5013
		}
5014
	}
5015
5016
	TAILQ_INSERT_TAIL(&sa->sa_childsas, csa, csa_entry);
5017
	TAILQ_INSERT_TAIL(&sa->sa_childsas, csb, csa_entry);
5018
5019
	csa->csa_peersa = csb;
5020
	csb->csa_peersa = csa;
5021
5022
	/* redirect flows to IPCOMP */
5023
	/* XXX expensive? should be merged into ikev2_childsa_negotiate() */
5024
	TAILQ_FOREACH_SAFE(flow, &sa->sa_flows, flow_entry, nflow) {
5025
		if (flow->flow_loaded || flow->flow_ipcomp ||
5026
		    flow->flow_saproto != IKEV2_SAPROTO_ESP)
5027
			continue;
5028
		TAILQ_FOREACH(oflow, &sa->sa_flows, flow_entry)
5029
			if (flow != oflow &&
5030
			    IKED_ADDR_EQ(&oflow->flow_src, &flow->flow_src) &&
5031
			    IKED_ADDR_EQ(&oflow->flow_dst, &flow->flow_dst) &&
5032
			    oflow->flow_dir == flow->flow_dir &&
5033
			    oflow->flow_saproto == IKEV2_SAPROTO_IPCOMP)
5034
				break;
5035
		if (oflow != NULL) {
5036
			log_debug("%s: keeping oflow %p, indentical to flow %p",
5037
			    __func__, oflow, flow);
5038
			TAILQ_REMOVE(&sa->sa_flows, flow, flow_entry);
5039
			flow_free(flow);
5040
		} else {
5041
			log_debug("%s: flow %p saproto %d -> %d", __func__,
5042
			    flow, flow->flow_saproto, IKEV2_SAPROTO_IPCOMP);
5043
			flow->flow_saproto = IKEV2_SAPROTO_IPCOMP;
5044
		}
5045
	}
5046
5047
	/* setup ESP flows for gateways (IPCOMP) */
5048
	flowa->flow_ipcomp = 1;
5049
	flowa->flow_ipproto = IPPROTO_IPCOMP;
5050
	flowa->flow_dir = IPSP_DIRECTION_OUT;
5051
	flowa->flow_saproto = IKEV2_SAPROTO_ESP;
5052
	flowa->flow_local = &sa->sa_local;
5053
	flowa->flow_peer = &sa->sa_peer;
5054
	memcpy(&flowa->flow_src, &sa->sa_local, sizeof(sa->sa_local));
5055
	memcpy(&flowa->flow_dst, &sa->sa_peer, sizeof(sa->sa_peer));
5056
	socket_setport((struct sockaddr *)&flowa->flow_src.addr, 0);
5057
	socket_setport((struct sockaddr *)&flowa->flow_dst.addr, 0);
5058
	flowa->flow_src.addr_port = flowa->flow_dst.addr_port = 0;
5059
	flowa->flow_src.addr_mask = flowa->flow_dst.addr_mask =
5060
	    (sa->sa_local.addr_af == AF_INET) ? 32 : 128;
5061
	flowa->flow_ikesa = sa;
5062
5063
	/* matching incoming flow */
5064
	memcpy(flowb, flowa, sizeof(*flowb));
5065
	flowb->flow_dir = IPSP_DIRECTION_IN;
5066
	memcpy(&flowb->flow_dst, &flowa->flow_src, sizeof(flowa->flow_src));
5067
	memcpy(&flowb->flow_src, &flowa->flow_dst, sizeof(flowa->flow_dst));
5068
5069
	/* setup ESP flows for gateways (IPIP) */
5070
	memcpy(flowc, flowa, sizeof(*flowc));
5071
	flowc->flow_ipproto = IPPROTO_IPIP;
5072
5073
	/* matching incoming flow */
5074
	memcpy(flowd, flowb, sizeof(*flowd));
5075
	flowd->flow_ipproto = IPPROTO_IPIP;
5076
5077
	/* skip if flows already exists */
5078
	TAILQ_FOREACH(flow, &sa->sa_flows, flow_entry) {
5079
		if (flow_equal(flow, flowa) || flow_equal(flow, flowb) ||
5080
		    flow_equal(flow, flowc) || flow_equal(flow, flowd)) {
5081
			free(flowa);
5082
			free(flowb);
5083
			free(flowc);
5084
			free(flowd);
5085
			goto done;
5086
		}
5087
	}
5088
5089
	TAILQ_INSERT_TAIL(&sa->sa_flows, flowa, flow_entry);
5090
	TAILQ_INSERT_TAIL(&sa->sa_flows, flowb, flow_entry);
5091
	TAILQ_INSERT_TAIL(&sa->sa_flows, flowc, flow_entry);
5092
	TAILQ_INSERT_TAIL(&sa->sa_flows, flowd, flow_entry);
5093
5094
 done:
5095
	/* make sure IPCOMP CPIs are not reused */
5096
	sa->sa_ipcomp = 0;
5097
	sa->sa_cpi_in = sa->sa_cpi_out = 0;
5098
5099
	return (0);
5100
}
5101
5102
int
5103
ikev2_childsa_enable(struct iked *env, struct iked_sa *sa)
5104
{
5105
	struct iked_childsa	*csa, *ocsa;
5106
	struct iked_flow	*flow, *oflow;
5107
5108
	if (sa->sa_ipcomp && sa->sa_cpi_in && sa->sa_cpi_out &&
5109
	    ikev2_ipcomp_enable(env, sa) == -1)
5110
		return (-1);
5111
5112
	TAILQ_FOREACH(csa, &sa->sa_childsas, csa_entry) {
5113
		if (csa->csa_rekey || csa->csa_loaded)
5114
			continue;
5115
5116
		if (pfkey_sa_add(env->sc_pfkey, csa, NULL) != 0) {
5117
			log_debug("%s: failed to load CHILD SA spi %s",
5118
			    __func__, print_spi(csa->csa_spi.spi,
5119
			    csa->csa_spi.spi_size));
5120
			return (-1);
5121
		}
5122
5123
		if ((ocsa = RB_FIND(iked_activesas, &env->sc_activesas, csa))
5124
		    != NULL) {
5125
			log_debug("%s: replaced CHILD SA %p with %p spi %s",
5126
			    __func__, ocsa, csa, print_spi(ocsa->csa_spi.spi,
5127
			    ocsa->csa_spi.spi_size));
5128
			ocsa->csa_loaded = 0;
5129
			ocsa->csa_rekey = 1;	/* prevent re-loading */
5130
			RB_REMOVE(iked_activesas, &env->sc_activesas, ocsa);
5131
		}
5132
5133
		RB_INSERT(iked_activesas, &env->sc_activesas, csa);
5134
5135
		log_debug("%s: loaded CHILD SA spi %s", __func__,
5136
		    print_spi(csa->csa_spi.spi, csa->csa_spi.spi_size));
5137
	}
5138
5139
	TAILQ_FOREACH(flow, &sa->sa_flows, flow_entry) {
5140
		if (flow->flow_loaded)
5141
			continue;
5142
5143
		if (pfkey_flow_add(env->sc_pfkey, flow) != 0) {
5144
			log_debug("%s: failed to load flow", __func__);
5145
			return (-1);
5146
		}
5147
5148
		if ((oflow = RB_FIND(iked_flows, &env->sc_activeflows, flow))
5149
		    != NULL) {
5150
			log_debug("%s: replaced old flow %p with %p",
5151
			    __func__, oflow, flow);
5152
			oflow->flow_loaded = 0;
5153
			RB_REMOVE(iked_flows, &env->sc_activeflows, oflow);
5154
		}
5155
5156
		RB_INSERT(iked_flows, &env->sc_activeflows, flow);
5157
5158
		log_debug("%s: loaded flow %p", __func__, flow);
5159
	}
5160
5161
	return (0);
5162
}
5163
5164
int
5165
ikev2_childsa_delete(struct iked *env, struct iked_sa *sa, uint8_t saproto,
5166
    uint64_t spi, uint64_t *spiptr, int cleanup)
5167
{
5168
	struct iked_childsa	*csa, *nextcsa = NULL;
5169
	uint64_t		 peerspi = 0;
5170
	int			 found = 0, ipcomp = 0;
5171
5172
	for (csa = TAILQ_FIRST(&sa->sa_childsas); csa != NULL; csa = nextcsa) {
5173
		nextcsa = TAILQ_NEXT(csa, csa_entry);
5174
5175
		if ((saproto && csa->csa_saproto != saproto) ||
5176
		    (spi && (csa->csa_spi.spi != spi &&
5177
			     csa->csa_peerspi != spi)) ||
5178
		    (cleanup && csa->csa_loaded))
5179
			continue;
5180
5181
		if (csa->csa_loaded)
5182
			RB_REMOVE(iked_activesas, &env->sc_activesas, csa);
5183
5184
		if (pfkey_sa_delete(env->sc_pfkey, csa) != 0)
5185
			log_debug("%s: failed to delete CHILD SA spi %s",
5186
			    __func__, print_spi(csa->csa_spi.spi,
5187
			    csa->csa_spi.spi_size));
5188
		else
5189
			log_debug("%s: deleted CHILD SA spi %s", __func__,
5190
			    print_spi(csa->csa_spi.spi,
5191
			    csa->csa_spi.spi_size));
5192
		found++;
5193
5194
		if (spi && csa->csa_spi.spi == spi)
5195
			peerspi = csa->csa_peerspi;
5196
5197
		if (csa->csa_parent && csa->csa_parent->csa_children == 1)
5198
			ipcomp = 1;
5199
		TAILQ_REMOVE(&sa->sa_childsas, csa, csa_entry);
5200
		childsa_free(csa);
5201
	}
5202
5203
	/* lookup and delete matching IPcomp SAs */
5204
	if (ipcomp) {
5205
		for (csa = TAILQ_FIRST(&sa->sa_childsas); csa != NULL;
5206
		    csa = nextcsa) {
5207
			nextcsa = TAILQ_NEXT(csa, csa_entry);
5208
			if (csa->csa_saproto == IKEV2_SAPROTO_IPCOMP &&
5209
			    csa->csa_children == 0)
5210
				ikev2_ipcomp_csa_free(env, csa);
5211
		}
5212
	}
5213
5214
	if (spiptr)
5215
		*spiptr = peerspi;
5216
5217
	return (found ? 0 : -1);
5218
}
5219
5220
int
5221
ikev2_valid_proposal(struct iked_proposal *prop,
5222
    struct iked_transform **exf, struct iked_transform **ixf, int *esn)
5223
{
5224
	struct iked_transform	*xform, *encrxf, *integrxf;
5225
	unsigned int		 i, doesn = 0;
5226
5227
	switch (prop->prop_protoid) {
5228
	case IKEV2_SAPROTO_ESP:
5229
	case IKEV2_SAPROTO_AH:
5230
		break;
5231
	default:
5232
		return (-1);
5233
	}
5234
5235
	encrxf = integrxf = NULL;
5236
	for (i = 0; i < prop->prop_nxforms; i++) {
5237
		xform = prop->prop_xforms + i;
5238
		if (xform->xform_type == IKEV2_XFORMTYPE_ENCR)
5239
			encrxf = xform;
5240
		else if (xform->xform_type == IKEV2_XFORMTYPE_INTEGR)
5241
			integrxf = xform;
5242
		else if (xform->xform_type == IKEV2_XFORMTYPE_ESN &&
5243
		    xform->xform_id == IKEV2_XFORMESN_ESN)
5244
			doesn = 1;
5245
	}
5246
5247
	if (prop->prop_protoid == IKEV2_SAPROTO_IKE) {
5248
		if (encrxf == NULL || integrxf == NULL)
5249
			return (-1);
5250
	} else if (prop->prop_protoid == IKEV2_SAPROTO_AH) {
5251
		if (integrxf == NULL)
5252
			return (-1);
5253
	} else if (prop->prop_protoid == IKEV2_SAPROTO_ESP) {
5254
		if (encrxf == NULL)
5255
			return (-1);
5256
	}
5257
5258
	if (exf)
5259
		*exf = encrxf;
5260
	if (ixf)
5261
		*ixf = integrxf;
5262
	if (esn)
5263
		*esn = doesn;
5264
5265
	return (0);
5266
}
5267
5268
/* return 0 if processed, -1 if busy */
5269
int
5270
ikev2_acquire_sa(struct iked *env, struct iked_flow *acquire)
5271
{
5272
	struct iked_flow	*flow;
5273
	struct iked_sa		*sa;
5274
	struct iked_policy	 pol, *p = NULL;
5275
5276
	if (env->sc_passive)
5277
		return (0);
5278
5279
	/* First try to find an active flow with IKE SA */
5280
	flow = RB_FIND(iked_flows, &env->sc_activeflows, acquire);
5281
	if (!flow) {
5282
		/* Otherwise try to find a matching policy */
5283
		bzero(&pol, sizeof(pol));
5284
		pol.pol_af = acquire->flow_peer->addr_af;
5285
		memcpy(&pol.pol_peer, acquire->flow_peer,
5286
		    sizeof(pol.pol_peer));
5287
5288
		RB_INIT(&pol.pol_flows);
5289
		RB_INSERT(iked_flows, &pol.pol_flows, acquire);
5290
		pol.pol_nflows = 1;
5291
5292
		if ((p = policy_test(env, &pol)) == NULL) {
5293
			log_warnx("%s: flow wasn't found", __func__);
5294
			return (0);
5295
		}
5296
5297
		log_debug("%s: found matching policy '%s'", __func__,
5298
		    p->pol_name);
5299
5300
		if (ikev2_init_ike_sa_peer(env, p,
5301
		    acquire->flow_peer, NULL) != 0)
5302
			log_warnx("%s: failed to initiate a "
5303
			    "IKE_SA_INIT exchange", __func__);
5304
	} else {
5305
		log_debug("%s: found active flow", __func__);
5306
5307
		if ((sa = flow->flow_ikesa) == NULL) {
5308
			log_warnx("%s: flow without SA", __func__);
5309
			return (0);
5310
		}
5311
		if (sa->sa_stateflags & IKED_REQ_CHILDSA)
5312
			return (-1);	/* busy, retry later */
5313
		if (ikev2_send_create_child_sa(env, sa, NULL,
5314
		    flow->flow_saproto) != 0)
5315
			log_warnx("%s: failed to initiate a "
5316
			    "CREATE_CHILD_SA exchange", __func__);
5317
	}
5318
	return (0);
5319
}
5320
5321
void
5322
ikev2_disable_rekeying(struct iked *env, struct iked_sa *sa)
5323
{
5324
	struct iked_childsa		*csa;
5325
5326
	TAILQ_FOREACH(csa, &sa->sa_childsas, csa_entry) {
5327
		csa->csa_persistent = 1;
5328
		csa->csa_rekey = 0;
5329
	}
5330
5331
	(void)ikev2_childsa_delete(env, sa, 0, 0, NULL, 1);
5332
}
5333
5334
/* return 0 if processed, -1 if busy */
5335
int
5336
ikev2_rekey_sa(struct iked *env, struct iked_spi *rekey)
5337
{
5338
	struct iked_childsa		*csa, key;
5339
	struct iked_sa			*sa;
5340
5341
	key.csa_spi = *rekey;
5342
	csa = RB_FIND(iked_activesas, &env->sc_activesas, &key);
5343
	if (!csa)
5344
		return (0);
5345
5346
	if (csa->csa_rekey)	/* See if it's already taken care of */
5347
		return (0);
5348
	if (csa->csa_acquired)	/* Don't rekey, wait for hard expire */
5349
		return (0);
5350
	if (csa->csa_saproto == IKEV2_SAPROTO_IPCOMP)	/* no rekey */
5351
		return (0);
5352
	if ((sa = csa->csa_ikesa) == NULL) {
5353
		log_warnx("%s: SA %s doesn't have a parent SA", __func__,
5354
		    print_spi(rekey->spi, rekey->spi_size));
5355
		return (0);
5356
	}
5357
	if (!sa_stateok(sa, IKEV2_STATE_ESTABLISHED)) {
5358
		log_warnx("%s: SA %s is not established", __func__,
5359
		    print_spi(rekey->spi, rekey->spi_size));
5360
		return (0);
5361
	}
5362
	if (sa->sa_stateflags & IKED_REQ_CHILDSA)
5363
		return (-1);	/* busy, retry later */
5364
	if (csa->csa_allocated)	/* Peer SPI died first, get the local one */
5365
		rekey->spi = csa->csa_peerspi;
5366
	if (ikev2_send_create_child_sa(env, sa, rekey, rekey->spi_protoid))
5367
		log_warnx("%s: failed to initiate a CREATE_CHILD_SA exchange",
5368
		    __func__);
5369
	return (0);
5370
}
5371
5372
/* return 0 if processed, -1 if busy */
5373
int
5374
ikev2_drop_sa(struct iked *env, struct iked_spi *drop)
5375
{
5376
	struct ibuf			*buf = NULL;
5377
	struct iked_childsa		*csa, key;
5378
	struct iked_sa			*sa;
5379
	struct ikev2_delete		*del;
5380
	uint32_t			 spi32;
5381
	int				 acquired;
5382
5383
	key.csa_spi = *drop;
5384
	csa = RB_FIND(iked_activesas, &env->sc_activesas, &key);
5385
	if (!csa || csa->csa_rekey)
5386
		return (0);
5387
5388
	sa = csa->csa_ikesa;
5389
	if (csa->csa_saproto != IKEV2_SAPROTO_IPCOMP &&
5390
	    sa && (sa->sa_stateflags & IKED_REQ_CHILDSA)) {
5391
		/* XXXX might loop, should we add a counter? */
5392
		log_debug("%s: parent SA busy", __func__);
5393
		return (-1);	/* busy, retry later */
5394
	}
5395
5396
	RB_REMOVE(iked_activesas, &env->sc_activesas, csa);
5397
	csa->csa_loaded = 0;
5398
	csa->csa_rekey = 1;	/* prevent re-loading */
5399
	if (sa == NULL) {
5400
		log_debug("%s: failed to find a parent SA", __func__);
5401
		return (0);
5402
	}
5403
	if (csa->csa_saproto == IKEV2_SAPROTO_IPCOMP) {
5404
		/* matching Child SAs (e.g. ESP) should have expired by now */
5405
		if (csa->csa_children == 0)
5406
			ikev2_ipcomp_csa_free(env, csa);
5407
		return (0);
5408
	}
5409
5410
	if (csa->csa_allocated)
5411
		spi32 = htobe32(csa->csa_spi.spi);
5412
	else
5413
		spi32 = htobe32(csa->csa_peerspi);
5414
	acquired = csa->csa_acquired;
5415
5416
	if (ikev2_childsa_delete(env, sa, csa->csa_saproto,
5417
	    csa->csa_peerspi, NULL, 0))
5418
		log_debug("%s: failed to delete CHILD SA %s", __func__,
5419
		    print_spi(csa->csa_peerspi, drop->spi_size));
5420
5421
	/* Send PAYLOAD_DELETE */
5422
5423
	if ((buf = ibuf_static()) == NULL)
5424
		return (0);
5425
	if ((del = ibuf_advance(buf, sizeof(*del))) == NULL)
5426
		goto done;
5427
	del->del_protoid = drop->spi_protoid;
5428
	del->del_spisize = 4;
5429
	del->del_nspi = htobe16(1);
5430
	if (ibuf_add(buf, &spi32, sizeof(spi32)))
5431
		goto done;
5432
5433
	if (ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_DELETE,
5434
	    IKEV2_EXCHANGE_INFORMATIONAL, 0) == -1)
5435
		goto done;
5436
5437
	sa->sa_stateflags |= IKED_REQ_INF;
5438
5439
	/* Don't automatically re-initiate Child SAs that have been acquired */
5440
	if (acquired)
5441
		goto done;
5442
5443
	/* Initiate Child SA creation */
5444
	if (ikev2_send_create_child_sa(env, sa, NULL, drop->spi_protoid))
5445
		log_warnx("%s: failed to initiate a CREATE_CHILD_SA exchange",
5446
		    __func__);
5447
5448
done:
5449
	ibuf_release(buf);
5450
	return (0);
5451
}
5452
5453
int
5454
ikev2_print_id(struct iked_id *id, char *idstr, size_t idstrlen)
5455
{
5456
	uint8_t				 buf[BUFSIZ], *ptr;
5457
	struct sockaddr_in		*s4;
5458
	struct sockaddr_in6		*s6;
5459
	char				*str;
5460
	ssize_t				 len;
5461
	int				 i;
5462
	const char			*type;
5463
5464
	bzero(buf, sizeof(buf));
5465
	bzero(idstr, idstrlen);
5466
5467
	if (id->id_buf == NULL)
5468
		return (-1);
5469
5470
	len = ibuf_size(id->id_buf);
5471
	ptr = ibuf_data(id->id_buf);
5472
5473
	if (len <= id->id_offset)
5474
		return (-1);
5475
5476
	len -= id->id_offset;
5477
	ptr += id->id_offset;
5478
5479
	type = print_map(id->id_type, ikev2_id_map);
5480
5481
	if (strlcpy(idstr, type, idstrlen) >= idstrlen ||
5482
	    strlcat(idstr, "/", idstrlen) >= idstrlen)
5483
		return (-1);
5484
5485
	idstr += strlen(idstr);
5486
	idstrlen -= strlen(idstr);
5487
5488
	switch (id->id_type) {
5489
	case IKEV2_ID_IPV4:
5490
		s4 = (struct sockaddr_in *)buf;
5491
		s4->sin_family = AF_INET;
5492
		s4->sin_len = sizeof(*s4);
5493
		memcpy(&s4->sin_addr.s_addr, ptr, len);
5494
5495
		if (print_host((struct sockaddr *)s4,
5496
		    idstr, idstrlen) == NULL)
5497
			return (-1);
5498
		break;
5499
	case IKEV2_ID_FQDN:
5500
	case IKEV2_ID_UFQDN:
5501
		if (len >= (ssize_t)sizeof(buf))
5502
			return (-1);
5503
5504
		if ((str = get_string(ptr, len)) == NULL)
5505
			return (-1);
5506
5507
		if (strlcpy(idstr, str, idstrlen) >= idstrlen) {
5508
			free(str);
5509
			return (-1);
5510
		}
5511
		free(str);
5512
		break;
5513
	case IKEV2_ID_IPV6:
5514
		s6 = (struct sockaddr_in6 *)buf;
5515
		s6->sin6_family = AF_INET6;
5516
		s6->sin6_len = sizeof(*s6);
5517
		memcpy(&s6->sin6_addr, ptr, len);
5518
5519
		if (print_host((struct sockaddr *)s6,
5520
		    idstr, idstrlen) == NULL)
5521
			return (-1);
5522
		break;
5523
	case IKEV2_ID_ASN1_DN:
5524
		if ((str = ca_asn1_name(ptr, len)) == NULL)
5525
			return (-1);
5526
		if (strlcpy(idstr, str, idstrlen) >= idstrlen) {
5527
			free(str);
5528
			return (-1);
5529
		}
5530
		free(str);
5531
		break;
5532
	default:
5533
		/* XXX test */
5534
		for (i = 0; i < ((ssize_t)idstrlen - 1) && i < len; i++)
5535
			snprintf(idstr + i, idstrlen - i,
5536
			    "%02x", ptr[i]);
5537
		break;
5538
	}
5539
5540
	return (0);
5541
}
5542
5543
/*
5544
 * If we have an IKEV2_CP_REQUEST for IKEV2_CFG_INTERNAL_IP4_ADDRESS and
5545
 * if a network(pool) is configured, then select an address from that pool
5546
 * and remember it in the sa_addrpool attribute.
5547
 */
5548
int
5549
ikev2_cp_setaddr(struct iked *env, struct iked_sa *sa, sa_family_t family)
5550
{
5551
	struct iked_cfg		*ikecfg = NULL;
5552
	struct iked_policy	*pol = sa->sa_policy;
5553
	struct sockaddr_in	*in4 = NULL, *cfg4 = NULL;
5554
	struct sockaddr_in6	*in6 = NULL, *cfg6 = NULL;
5555
	struct iked_sa		 key;
5556
	struct iked_addr	 addr;
5557
	uint32_t		 mask, host, lower, upper, start, nhost;
5558
	size_t			 i;
5559
5560
	switch (family) {
5561
		case AF_INET:
5562
			if (sa->sa_addrpool)
5563
				return (0);
5564
			break;
5565
		case AF_INET6:
5566
			if (sa->sa_addrpool6)
5567
				return (0);
5568
			break;
5569
		default:
5570
			return (-1);
5571
	}
5572
	if (pol->pol_ncfg == 0)
5573
		return (0);
5574
	/* check for an address pool config (address w/ prefixlen != 32) */
5575
	bzero(&addr, sizeof(addr));
5576
	for (i = 0; i < pol->pol_ncfg; i++) {
5577
		ikecfg = &pol->pol_cfg[i];
5578
		if (family == AF_INET &&
5579
		    ikecfg->cfg_type == IKEV2_CFG_INTERNAL_IP4_ADDRESS &&
5580
		    ikecfg->cfg.address.addr_mask != 32) {
5581
			addr.addr_af = AF_INET;
5582
			break;
5583
		}
5584
		if (family == AF_INET6 &&
5585
		    ikecfg->cfg_type == IKEV2_CFG_INTERNAL_IP6_ADDRESS &&
5586
		    ikecfg->cfg.address.addr_mask != 128) {
5587
			addr.addr_af = AF_INET6;
5588
			break;
5589
		}
5590
	}
5591
	if (i == pol->pol_ncfg)
5592
		return (0);
5593
5594
	/*
5595
	 * failure: pool configured, but not requested.
5596
	 * If we continue, we might end up with flows where 0.0.0.0 is NOT
5597
	 * replaced with an address from the pool with ikev2_cp_fixaddr().
5598
	 */
5599
	if (sa->sa_cp != IKEV2_CP_REQUEST) {
5600
		log_debug("%s: pool configured, but IKEV2_CP_REQUEST missing",
5601
		    __func__);
5602
		return (-1);
5603
	}
5604
5605
	switch (addr.addr_af) {
5606
	case AF_INET:
5607
		cfg4 = (struct sockaddr_in *)&ikecfg->cfg.address.addr;
5608
		in4 = (struct sockaddr_in *)&addr.addr;
5609
		in4->sin_family = AF_INET;
5610
		in4->sin_len = sizeof(*in4);
5611
		mask = prefixlen2mask(ikecfg->cfg.address.addr_mask);
5612
		lower = ntohl(cfg4->sin_addr.s_addr & ~mask);
5613
		key.sa_addrpool = &addr;
5614
		break;
5615
	case AF_INET6:
5616
		cfg6 = (struct sockaddr_in6 *)&ikecfg->cfg.address.addr;
5617
		in6 = (struct sockaddr_in6 *)&addr.addr;
5618
		in6->sin6_family = AF_INET6;
5619
		in6->sin6_len = sizeof(*in6);
5620
		/* truncate prefixlen to get a 32-bit space */
5621
		mask = (ikecfg->cfg.address.addr_mask >= 96)
5622
		    ? prefixlen2mask(ikecfg->cfg.address.addr_mask - 96)
5623
		    : prefixlen2mask(0);
5624
		memcpy(&lower, &cfg6->sin6_addr.s6_addr[12], sizeof(uint32_t));
5625
		lower = ntohl(lower & ~mask);
5626
		key.sa_addrpool6 = &addr;
5627
		break;
5628
	default:
5629
		return (-1);
5630
	}
5631
5632
	if (lower == 0)
5633
		lower = 1;
5634
	/* Note that start, upper and host are in HOST byte order */
5635
	upper = ntohl(~mask);
5636
	/* Randomly select start from [lower, upper-1] */
5637
	start = arc4random_uniform(upper - lower) + lower;
5638
5639
	for (host = start;;) {
5640
		log_debug("%s: mask %x start %x lower %x host %x upper %x",
5641
		    __func__, mask, start, lower, host, upper);
5642
		switch (addr.addr_af) {
5643
		case AF_INET:
5644
			in4->sin_addr.s_addr =
5645
			    (cfg4->sin_addr.s_addr & mask) | htonl(host);
5646
			break;
5647
		case AF_INET6:
5648
			memcpy(in6, cfg6, sizeof(*in6));
5649
			nhost = htonl(host);
5650
			memcpy(&in6->sin6_addr.s6_addr[12], &nhost,
5651
			    sizeof(uint32_t));
5652
			break;
5653
		}
5654
		if ((addr.addr_af == AF_INET &&
5655
		    !RB_FIND(iked_addrpool, &env->sc_addrpool, &key)) ||
5656
		    (addr.addr_af == AF_INET6 &&
5657
		    !RB_FIND(iked_addrpool6, &env->sc_addrpool6, &key)))
5658
			break;
5659
		/* try next address */
5660
		host++;
5661
		/* but skip broadcast and network address */
5662
		if (host >= upper || host < lower)
5663
			host = lower;
5664
		if (host == start) {
5665
			log_warnx("%s: address pool exhausted", __func__);
5666
			return (-1);		/* exhausted */
5667
		}
5668
	}
5669
5670
	switch (addr.addr_af) {
5671
	case AF_INET:
5672
		if (!key.sa_addrpool)
5673
			return (-1);			/* cannot happen? */
5674
		if ((sa->sa_addrpool = calloc(1, sizeof(addr))) == NULL)
5675
			return (-1);
5676
		memcpy(sa->sa_addrpool, &addr, sizeof(addr));
5677
		RB_INSERT(iked_addrpool, &env->sc_addrpool, sa);
5678
		break;
5679
	case AF_INET6:
5680
		if (!key.sa_addrpool6)
5681
			return (-1);			/* cannot happen? */
5682
		if ((sa->sa_addrpool6 = calloc(1, sizeof(addr))) == NULL)
5683
			return (-1);
5684
		memcpy(sa->sa_addrpool6, &addr, sizeof(addr));
5685
		RB_INSERT(iked_addrpool6, &env->sc_addrpool6, sa);
5686
		break;
5687
	default:
5688
		return (-1);
5689
	}
5690
	return (0);
5691
}
5692
5693
/*
5694
 * if 'addr' is 'UNSPECIFIED' replace it with sa_addrpool from
5695
 * the ip-pool and store the result in 'patched'.
5696
 */
5697
int
5698
ikev2_cp_fixaddr(struct iked_sa *sa, struct iked_addr *addr,
5699
    struct iked_addr *patched)
5700
{
5701
	struct sockaddr_in	*in4;
5702
	struct sockaddr_in6	*in6;
5703
5704
	switch (addr->addr_af) {
5705
	case AF_INET:
5706
		if (sa->sa_addrpool == NULL)
5707
			return (-1);
5708
		in4 = (struct sockaddr_in *)&addr->addr;
5709
		if (in4->sin_addr.s_addr)
5710
			return (-1);
5711
		memcpy(patched, sa->sa_addrpool, sizeof(*patched));
5712
		break;
5713
	case AF_INET6:
5714
		if (sa->sa_addrpool6 == NULL)
5715
			return (-1);
5716
		in6 = (struct sockaddr_in6 *)&addr->addr;
5717
		if (!IN6_IS_ADDR_UNSPECIFIED(&in6->sin6_addr))
5718
			return (-1);
5719
		memcpy(patched, sa->sa_addrpool6, sizeof(*patched));
5720
		break;
5721
	}
5722
	return (0);
5723
}