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

Line Branch Exec Source
1
/*	$OpenBSD: ikev2.c,v 1.155 2017/06/01 15:23:43 sthen 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_getlen(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 secret %zu exchange %zu", __func__,
4301
		    group->id, dh_getlen(group), ibuf_length(dhsecret),
4302
		    ibuf_length(sa->sa_dhpeer));
4303
		goto done;
4304
	}
4305
4306
	if (!key) {
4307
		/*
4308
		 * Set PRF key to generate SKEEYSEED = prf(Ni | Nr, g^ir)
4309
		 */
4310
		if ((ninr = ibuf_new(sa->sa_inonce->buf, ilen)) == NULL ||
4311
		    ibuf_add(ninr, sa->sa_rnonce->buf, rlen) != 0) {
4312
			log_debug("%s: failed to get nonce key buffer",
4313
			    __func__);
4314
			goto done;
4315
		}
4316
		key = ninr;
4317
	} else {
4318
		/*
4319
		 * Set PRF key to generate SKEEYSEED = prf(key, g^ir | Ni | Nr)
4320
		 */
4321
		if (ibuf_add(dhsecret, sa->sa_inonce->buf, ilen) != 0 ||
4322
		    ibuf_add(dhsecret, sa->sa_rnonce->buf, rlen) != 0) {
4323
			log_debug("%s: failed to get nonce key buffer",
4324
			    __func__);
4325
			goto done;
4326
		}
4327
	}
4328
4329
	if ((hash_setkey(prf, key->buf, ibuf_length(key))) == NULL) {
4330
		log_debug("%s: failed to set prf key", __func__);
4331
		goto done;
4332
	}
4333
4334
	if ((skeyseed = ibuf_new(NULL, hash_length(prf))) == NULL) {
4335
		log_debug("%s: failed to get SKEYSEED buffer", __func__);
4336
		goto done;
4337
	}
4338
4339
	tmplen = 0;
4340
	hash_init(prf);
4341
	hash_update(prf, dhsecret->buf, ibuf_length(dhsecret));
4342
	hash_final(prf, skeyseed->buf, &tmplen);
4343
4344
	log_debug("%s: SKEYSEED with %zu bytes", __func__, tmplen);
4345
	print_hex(skeyseed->buf, 0, tmplen);
4346
4347
	if (ibuf_setsize(skeyseed, tmplen) == -1) {
4348
		log_debug("%s: failed to set keymaterial length", __func__);
4349
		goto done;
4350
	}
4351
4352
	/*
4353
	 * Now generate the key material
4354
	 *
4355
	 * S = Ni | Nr | SPIi | SPIr
4356
	 */
4357
4358
	/* S = Ni | Nr | SPIi | SPIr */
4359
	ilen = ibuf_length(sa->sa_inonce);
4360
	rlen = ibuf_length(sa->sa_rnonce);
4361
	ispi = htobe64(sa->sa_hdr.sh_ispi);
4362
	rspi = htobe64(sa->sa_hdr.sh_rspi);
4363
4364
	if ((s = ibuf_new(sa->sa_inonce->buf, ilen)) == NULL ||
4365
	    ibuf_add(s, sa->sa_rnonce->buf, rlen) != 0 ||
4366
	    ibuf_add(s, &ispi, sizeof(ispi)) != 0 ||
4367
	    ibuf_add(s, &rspi, sizeof(rspi)) != 0) {
4368
		log_debug("%s: failed to set S buffer", __func__);
4369
		goto done;
4370
	}
4371
4372
	log_debug("%s: S with %zu bytes", __func__, ibuf_length(s));
4373
	print_hex(s->buf, 0, ibuf_length(s));
4374
4375
	/*
4376
	 * Get the size of the key material we need and the number
4377
	 * of rounds we need to run the prf+ function.
4378
	 */
4379
	ilen = hash_length(prf) +	/* SK_d */
4380
	    hash_keylength(integr) +	/* SK_ai */
4381
	    hash_keylength(integr) +	/* SK_ar */
4382
	    cipher_keylength(encr) +	/* SK_ei */
4383
	    cipher_keylength(encr) +	/* SK_er */
4384
	    hash_keylength(prf) +	/* SK_pi */
4385
	    hash_keylength(prf);	/* SK_pr */
4386
4387
	if ((t = ikev2_prfplus(prf, skeyseed, s, ilen)) == NULL) {
4388
		log_debug("%s: failed to get IKE SA key material", __func__);
4389
		goto done;
4390
	}
4391
4392
	/* ibuf_get() returns a new buffer from the next read offset */
4393
	if ((sa->sa_key_d = ibuf_get(t, hash_length(prf))) == NULL ||
4394
	    (sa->sa_key_iauth = ibuf_get(t, hash_keylength(integr))) == NULL ||
4395
	    (sa->sa_key_rauth = ibuf_get(t, hash_keylength(integr))) == NULL ||
4396
	    (sa->sa_key_iencr = ibuf_get(t, cipher_keylength(encr))) == NULL ||
4397
	    (sa->sa_key_rencr = ibuf_get(t, cipher_keylength(encr))) == NULL ||
4398
	    (sa->sa_key_iprf = ibuf_get(t, hash_length(prf))) == NULL ||
4399
	    (sa->sa_key_rprf = ibuf_get(t, hash_length(prf))) == NULL) {
4400
		log_debug("%s: failed to get SA keys", __func__);
4401
		goto done;
4402
	}
4403
4404
	log_debug("%s: SK_d with %zu bytes", __func__,
4405
	    ibuf_length(sa->sa_key_d));
4406
	print_hex(sa->sa_key_d->buf, 0, ibuf_length(sa->sa_key_d));
4407
	log_debug("%s: SK_ai with %zu bytes", __func__,
4408
	    ibuf_length(sa->sa_key_iauth));
4409
	print_hex(sa->sa_key_iauth->buf, 0, ibuf_length(sa->sa_key_iauth));
4410
	log_debug("%s: SK_ar with %zu bytes", __func__,
4411
	    ibuf_length(sa->sa_key_rauth));
4412
	print_hex(sa->sa_key_rauth->buf, 0, ibuf_length(sa->sa_key_rauth));
4413
	log_debug("%s: SK_ei with %zu bytes", __func__,
4414
	    ibuf_length(sa->sa_key_iencr));
4415
	print_hex(sa->sa_key_iencr->buf, 0, ibuf_length(sa->sa_key_iencr));
4416
	log_debug("%s: SK_er with %zu bytes", __func__,
4417
	    ibuf_length(sa->sa_key_rencr));
4418
	print_hex(sa->sa_key_rencr->buf, 0, ibuf_length(sa->sa_key_rencr));
4419
	log_debug("%s: SK_pi with %zu bytes", __func__,
4420
	    ibuf_length(sa->sa_key_iprf));
4421
	print_hex(sa->sa_key_iprf->buf, 0, ibuf_length(sa->sa_key_iprf));
4422
	log_debug("%s: SK_pr with %zu bytes", __func__,
4423
	    ibuf_length(sa->sa_key_rprf));
4424
	print_hex(sa->sa_key_rprf->buf, 0, ibuf_length(sa->sa_key_rprf));
4425
4426
	ret = 0;
4427
4428
 done:
4429
	ibuf_release(ninr);
4430
	ibuf_release(dhsecret);
4431
	ibuf_release(skeyseed);
4432
	ibuf_release(s);
4433
	ibuf_release(t);
4434
4435
	return (ret);
4436
}
4437
4438
void
4439
ikev2_sa_cleanup_dh(struct iked_sa *sa)
4440
{
4441
	ibuf_release(sa->sa_dhiexchange);
4442
	ibuf_release(sa->sa_dhrexchange);
4443
	group_free(sa->sa_dhgroup);
4444
	sa->sa_dhiexchange = NULL;
4445
	sa->sa_dhrexchange = NULL;
4446
	sa->sa_dhgroup = NULL;
4447
}
4448
4449
struct ibuf *
4450
ikev2_prfplus(struct iked_hash *prf, struct ibuf *key, struct ibuf *seed,
4451
    size_t keymatlen)
4452
{
4453
	struct ibuf	*t = NULL, *t1 = NULL, *t2 = NULL;
4454
	size_t		 rlen, i, hashlen = 0;
4455
	uint8_t		 pad = 0;
4456
4457
	/*
4458
	 * prf+ (K, S) = T1 | T2 | T3 | T4 | ...
4459
	 *
4460
	 * T1 = prf (K, S | 0x01)
4461
	 * T2 = prf (K, T1 | S | 0x02)
4462
	 * T3 = prf (K, T2 | S | 0x03)
4463
	 * T4 = prf (K, T3 | S | 0x04)
4464
	 */
4465
4466
	if ((hash_setkey(prf, ibuf_data(key), ibuf_size(key))) == NULL) {
4467
		log_debug("%s: failed to set prf+ key", __func__);
4468
		goto fail;
4469
	}
4470
4471
	if ((t = ibuf_new(NULL, 0)) == NULL) {
4472
		log_debug("%s: failed to get T buffer", __func__);
4473
		goto fail;
4474
	}
4475
4476
	rlen = roundup(keymatlen, hash_length(prf)) / hash_length(prf);
4477
	if (rlen > 255)
4478
		fatalx("ikev2_prfplus: key material too large");
4479
4480
	for (i = 0; i < rlen; i++) {
4481
		if (t1 != NULL) {
4482
			t2 = ibuf_new(t1->buf, ibuf_length(t1));
4483
			ibuf_release(t1);
4484
		} else
4485
			t2 = ibuf_new(NULL, 0);
4486
		t1 = ibuf_new(NULL, hash_length(prf));
4487
4488
		ibuf_add(t2, seed->buf, ibuf_length(seed));
4489
		pad = i + 1;
4490
		ibuf_add(t2, &pad, 1);
4491
4492
		hash_init(prf);
4493
		hash_update(prf, t2->buf, ibuf_length(t2));
4494
		hash_final(prf, t1->buf, &hashlen);
4495
4496
		if (hashlen != hash_length(prf))
4497
			fatalx("ikev2_prfplus: hash length mismatch");
4498
4499
		ibuf_release(t2);
4500
		ibuf_add(t, t1->buf, ibuf_length(t1));
4501
4502
		log_debug("%s: T%d with %zu bytes", __func__,
4503
		    pad, ibuf_length(t1));
4504
		print_hex(t1->buf, 0, ibuf_length(t1));
4505
	}
4506
4507
	log_debug("%s: Tn with %zu bytes", __func__, ibuf_length(t));
4508
	print_hex(t->buf, 0, ibuf_length(t));
4509
4510
	ibuf_release(t1);
4511
4512
	return (t);
4513
4514
 fail:
4515
	ibuf_release(t1);
4516
	ibuf_release(t);
4517
4518
	return (NULL);
4519
}
4520
4521
int
4522
ikev2_sa_tag(struct iked_sa *sa, struct iked_id *id)
4523
{
4524
	char	*format, *domain = NULL, *idrepl = NULL;
4525
	char	 idstr[IKED_ID_SIZE];
4526
	int	 ret = -1;
4527
	size_t	 len;
4528
4529
	free(sa->sa_tag);
4530
	sa->sa_tag = NULL;
4531
	format = sa->sa_policy->pol_tag;
4532
4533
	len = IKED_TAG_SIZE;
4534
	if ((sa->sa_tag = calloc(1, len)) == NULL) {
4535
		log_debug("%s: calloc", __func__);
4536
		goto fail;
4537
	}
4538
	if (strlcpy(sa->sa_tag, format, len) >= len) {
4539
		log_debug("%s: tag too long", __func__);
4540
		goto fail;
4541
	}
4542
4543
	if (ikev2_print_id(id, idstr, sizeof(idstr)) == -1) {
4544
		log_debug("%s: invalid id", __func__);
4545
		goto fail;
4546
	}
4547
4548
	/* ASN.1 DER IDs are too long, use the CN part instead */
4549
	if ((id->id_type == IKEV2_ID_ASN1_DN) &&
4550
	    (idrepl = strstr(idstr, "CN=")) != NULL) {
4551
		domain = strstr(idrepl, "emailAddress=");
4552
		idrepl[strcspn(idrepl, "/")] = '\0';
4553
	} else
4554
		idrepl = idstr;
4555
4556
	if (strstr(format, "$id") != NULL) {
4557
		if (expand_string(sa->sa_tag, len, "$id", idrepl) != 0) {
4558
			log_debug("%s: failed to expand tag", __func__);
4559
			goto fail;
4560
		}
4561
	}
4562
4563
	if (strstr(format, "$eapid") != NULL && sa->sa_eapid != NULL) {
4564
		if (expand_string(sa->sa_tag, len, "$eapid",
4565
		    sa->sa_eapid) != 0) {
4566
			log_debug("%s: failed to expand tag", __func__);
4567
			goto fail;
4568
		}
4569
	}
4570
4571
	if (strstr(format, "$name") != NULL) {
4572
		if (expand_string(sa->sa_tag, len, "$name",
4573
		    sa->sa_policy->pol_name) != 0) {
4574
			log_debug("%s: failed to expand tag", __func__);
4575
			goto fail;
4576
		}
4577
	}
4578
4579
	if (strstr(format, "$domain") != NULL) {
4580
		if (id->id_type == IKEV2_ID_FQDN)
4581
			domain = strchr(idrepl, '.');
4582
		else if (id->id_type == IKEV2_ID_UFQDN)
4583
			domain = strchr(idrepl, '@');
4584
		else if (*idstr == '/' && domain != NULL)
4585
			domain = strchr(domain, '@');
4586
		else
4587
			domain = NULL;
4588
		if (domain == NULL || strlen(domain) < 2) {
4589
			log_debug("%s: no valid domain in ID %s",
4590
			    __func__, idstr);
4591
			goto fail;
4592
		}
4593
		domain++;
4594
		if (expand_string(sa->sa_tag, len, "$domain", domain) != 0) {
4595
			log_debug("%s: failed to expand tag", __func__);
4596
			goto fail;
4597
		}
4598
	}
4599
4600
	log_debug("%s: %s (%zu)", __func__, sa->sa_tag, strlen(sa->sa_tag));
4601
4602
	ret = 0;
4603
 fail:
4604
	if (ret != 0) {
4605
		free(sa->sa_tag);
4606
		sa->sa_tag = NULL;
4607
	}
4608
4609
	return (ret);
4610
}
4611
4612
int
4613
ikev2_childsa_delete_proposed(struct iked *env, struct iked_sa *sa,
4614
    struct iked_proposals *proposals)
4615
{
4616
	struct ibuf			*buf = NULL;
4617
	struct iked_proposal		*prop;
4618
	struct ikev2_delete		*del;
4619
	uint32_t			 spi32;
4620
	uint8_t				 protoid = 0;
4621
	int				 ret = -1, count;
4622
4623
	if (!sa_stateok(sa, IKEV2_STATE_VALID))
4624
		return (-1);
4625
4626
	count = 0;
4627
	TAILQ_FOREACH(prop, proposals, prop_entry) {
4628
		if (ikev2_valid_proposal(prop, NULL, NULL, NULL) != 0)
4629
			continue;
4630
		protoid = prop->prop_protoid;
4631
		count++;
4632
	}
4633
	if (count == 0)
4634
		return (0);
4635
	if ((buf = ibuf_static()) == NULL)
4636
		return (-1);
4637
	if ((del = ibuf_advance(buf, sizeof(*del))) == NULL)
4638
		goto done;
4639
	/* XXX we assume all have the same protoid */
4640
	del->del_protoid = protoid;
4641
	del->del_spisize = 4;
4642
	del->del_nspi = htobe16(count);
4643
4644
	TAILQ_FOREACH(prop, proposals, prop_entry) {
4645
		if (ikev2_valid_proposal(prop, NULL, NULL, NULL) != 0)
4646
			continue;
4647
		spi32 = htobe32(prop->prop_localspi.spi);
4648
		if (ibuf_add(buf, &spi32, sizeof(spi32)))
4649
			goto done;
4650
	}
4651
4652
	if (ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_DELETE,
4653
	    IKEV2_EXCHANGE_INFORMATIONAL, 0) == -1)
4654
		goto done;
4655
	sa->sa_stateflags |= IKED_REQ_INF;
4656
	ret = 0;
4657
 done:
4658
	ibuf_release(buf);
4659
4660
	return (ret);
4661
}
4662
4663
int
4664
ikev2_childsa_negotiate(struct iked *env, struct iked_sa *sa,
4665
    struct iked_kex *kex, struct iked_proposals *proposals, int initiator,
4666
    int pfs, int acquired)
4667
{
4668
	struct iked_proposal	*prop;
4669
	struct iked_transform	*xform, *encrxf = NULL, *integrxf = NULL;
4670
	struct iked_childsa	*csa, *csb;
4671
	struct iked_flow	*flow, *saflow, *flowa, *flowb;
4672
	struct ibuf		*keymat = NULL, *seed = NULL, *dhsecret = NULL;
4673
	struct group		*group;
4674
	uint32_t		 spi = 0;
4675
	unsigned int		 i;
4676
	size_t			 ilen = 0;
4677
	int			 esn, skip, ret = -1;
4678
4679
	if (!sa_stateok(sa, IKEV2_STATE_VALID))
4680
		return (-1);
4681
4682
	if (ikev2_sa_tag(sa, IKESA_DSTID(sa)) == -1)
4683
		return (-1);
4684
4685
	/* We need to determine the key material length first */
4686
	TAILQ_FOREACH(prop, proposals, prop_entry) {
4687
		if (prop->prop_protoid == IKEV2_SAPROTO_IKE)
4688
			continue;
4689
		log_debug("%s: proposal %d", __func__, prop->prop_id);
4690
		for (i = 0; i < prop->prop_nxforms; i++) {
4691
			xform = prop->prop_xforms + i;
4692
			xform->xform_keylength =
4693
			    keylength_xf(prop->prop_protoid,
4694
			    xform->xform_type, xform->xform_id);
4695
4696
			switch (xform->xform_type) {
4697
			case IKEV2_XFORMTYPE_ENCR:
4698
			case IKEV2_XFORMTYPE_INTEGR:
4699
				if (xform->xform_length)
4700
					xform->xform_keylength =
4701
					    xform->xform_length;
4702
				xform->xform_keylength +=
4703
				    noncelength_xf(xform->xform_type,
4704
				    xform->xform_id);
4705
				ilen += xform->xform_keylength / 8;
4706
				break;
4707
			}
4708
		}
4709
	}
4710
4711
	/* double key material length for inbound/outbound */
4712
	ilen *= 2;
4713
4714
	log_debug("%s: key material length %zu", __func__, ilen);
4715
4716
	if ((seed = ibuf_new(NULL, 0)) == NULL) {
4717
		log_debug("%s: failed to setup IKE SA key material", __func__);
4718
		goto done;
4719
	}
4720
	if (pfs) {
4721
		log_debug("%s: using PFS", __func__);
4722
		if (kex->kex_dhpeer == NULL ||
4723
		    ibuf_length(kex->kex_dhpeer) == 0 ||
4724
		    (group = kex->kex_dhgroup) == NULL) {
4725
			log_debug("%s: no dh group for pfs", __func__);
4726
			goto done;
4727
		}
4728
		if ((dhsecret = ibuf_new(NULL, dh_getlen(group))) == NULL) {
4729
			log_debug("%s: failed to alloc dh secret", __func__);
4730
			goto done;
4731
		}
4732
		if (dh_create_shared(group, dhsecret->buf,
4733
		    kex->kex_dhpeer->buf) == -1) {
4734
			log_debug("%s: failed to get dh secret"
4735
			    " group %d len %d secret %zu exchange %zu",
4736
			    __func__, group->id, dh_getlen(group),
4737
			    ibuf_length(dhsecret),
4738
			    ibuf_length(kex->kex_dhpeer));
4739
			goto done;
4740
		}
4741
		if (ibuf_cat(seed, dhsecret) != 0) {
4742
			log_debug("%s: failed to set dh secret", __func__);
4743
			goto done;
4744
		}
4745
	}
4746
	if (ibuf_cat(seed, kex->kex_inonce) != 0 ||
4747
	    ibuf_cat(seed, kex->kex_rnonce) != 0 ||
4748
	    (keymat = ikev2_prfplus(sa->sa_prf,
4749
	    sa->sa_key_d, seed, ilen)) == NULL) {
4750
		log_debug("%s: failed to get IKE SA key material", __func__);
4751
		goto done;
4752
	}
4753
4754
	/* Create the new flows */
4755
	TAILQ_FOREACH(prop, proposals, prop_entry) {
4756
		if (ikev2_valid_proposal(prop, NULL, NULL, NULL) != 0)
4757
			continue;
4758
4759
		RB_FOREACH(flow, iked_flows, &sa->sa_policy->pol_flows) {
4760
4761
			if ((flowa = calloc(1, sizeof(*flowa))) == NULL) {
4762
				log_debug("%s: failed to get flow", __func__);
4763
				goto done;
4764
			}
4765
4766
			memcpy(flowa, flow, sizeof(*flow));
4767
			flowa->flow_dir = IPSP_DIRECTION_OUT;
4768
			flowa->flow_saproto = prop->prop_protoid;
4769
			flowa->flow_local = &sa->sa_local;
4770
			flowa->flow_peer = &sa->sa_peer;
4771
			flowa->flow_ikesa = sa;
4772
			ikev2_cp_fixaddr(sa, &flow->flow_dst, &flowa->flow_dst);
4773
4774
			skip = 0;
4775
			TAILQ_FOREACH(saflow, &sa->sa_flows, flow_entry) {
4776
				if (flow_equal(saflow, flowa)) {
4777
					skip = 1;
4778
					break;
4779
				}
4780
			}
4781
			if (skip) {
4782
				flow_free(flowa);
4783
				continue;
4784
			}
4785
4786
			if ((flowb = calloc(1, sizeof(*flowb))) == NULL) {
4787
				log_debug("%s: failed to get flow", __func__);
4788
				flow_free(flowa);
4789
				goto done;
4790
			}
4791
4792
			memcpy(flowb, flowa, sizeof(*flow));
4793
4794
			flowb->flow_dir = IPSP_DIRECTION_IN;
4795
			memcpy(&flowb->flow_src, &flow->flow_dst,
4796
			    sizeof(flow->flow_dst));
4797
			memcpy(&flowb->flow_dst, &flow->flow_src,
4798
			    sizeof(flow->flow_src));
4799
			ikev2_cp_fixaddr(sa, &flow->flow_dst, &flowb->flow_src);
4800
4801
			TAILQ_INSERT_TAIL(&sa->sa_flows, flowa, flow_entry);
4802
			TAILQ_INSERT_TAIL(&sa->sa_flows, flowb, flow_entry);
4803
		}
4804
	}
4805
4806
	/* create the CHILD SAs using the key material */
4807
	TAILQ_FOREACH(prop, proposals, prop_entry) {
4808
		if (ikev2_valid_proposal(prop, &encrxf, &integrxf, &esn) != 0)
4809
			continue;
4810
4811
		spi = 0;
4812
4813
		if ((csa = calloc(1, sizeof(*csa))) == NULL) {
4814
			log_debug("%s: failed to get CHILD SA", __func__);
4815
			goto done;
4816
		}
4817
4818
		csa->csa_saproto = prop->prop_protoid;
4819
		csa->csa_ikesa = sa;
4820
		csa->csa_spi.spi_protoid = prop->prop_protoid;
4821
		csa->csa_esn = esn;
4822
		csa->csa_acquired = acquired;
4823
4824
		/* Set up responder's SPIs */
4825
		if (initiator) {
4826
			csa->csa_dir = IPSP_DIRECTION_OUT;
4827
			csa->csa_local = &sa->sa_local;
4828
			csa->csa_peer = &sa->sa_peer;
4829
			csa->csa_peerspi = prop->prop_localspi.spi;
4830
			csa->csa_spi.spi = prop->prop_peerspi.spi;
4831
			csa->csa_spi.spi_size = prop->prop_peerspi.spi_size;
4832
		} else {
4833
			csa->csa_dir = IPSP_DIRECTION_IN;
4834
			csa->csa_local = &sa->sa_peer;
4835
			csa->csa_peer = &sa->sa_local;
4836
4837
			if ((ret = pfkey_sa_init(env->sc_pfkey, csa,
4838
			    &spi)) != 0)
4839
				goto done;
4840
			csa->csa_allocated = 1;
4841
4842
			csa->csa_peerspi = prop->prop_peerspi.spi;
4843
			csa->csa_spi.spi = prop->prop_localspi.spi = spi;
4844
			csa->csa_spi.spi_size = 4;
4845
		}
4846
4847
		if (encrxf && (csa->csa_encrkey = ibuf_get(keymat,
4848
		    encrxf->xform_keylength / 8)) == NULL) {
4849
			log_debug("%s: failed to get CHILD SA encryption key",
4850
			    __func__);
4851
			childsa_free(csa);
4852
			goto done;
4853
		}
4854
		if (integrxf && (csa->csa_integrkey = ibuf_get(keymat,
4855
		    integrxf->xform_keylength / 8)) == NULL) {
4856
			log_debug("%s: failed to get CHILD SA integrity key",
4857
			    __func__);
4858
			childsa_free(csa);
4859
			goto done;
4860
		}
4861
		if (encrxf)
4862
			csa->csa_encrid = encrxf->xform_id;
4863
		if (integrxf)
4864
			csa->csa_integrid = integrxf->xform_id;
4865
4866
		if ((csb = calloc(1, sizeof(*csb))) == NULL) {
4867
			log_debug("%s: failed to get CHILD SA", __func__);
4868
			childsa_free(csa);
4869
			goto done;
4870
		}
4871
4872
		memcpy(csb, csa, sizeof(*csb));
4873
4874
		/* Set up initiator's SPIs */
4875
		csb->csa_spi.spi = csa->csa_peerspi;
4876
		csb->csa_peerspi = csa->csa_spi.spi;
4877
		csb->csa_allocated = csa->csa_allocated ? 0 : 1;
4878
		csb->csa_dir = csa->csa_dir == IPSP_DIRECTION_IN ?
4879
		    IPSP_DIRECTION_OUT : IPSP_DIRECTION_IN;
4880
		csb->csa_local = csa->csa_peer;
4881
		csb->csa_peer = csa->csa_local;
4882
4883
		if (encrxf && (csb->csa_encrkey = ibuf_get(keymat,
4884
		    encrxf->xform_keylength / 8)) == NULL) {
4885
			log_debug("%s: failed to get CHILD SA encryption key",
4886
			    __func__);
4887
			childsa_free(csa);
4888
			childsa_free(csb);
4889
			goto done;
4890
		}
4891
		if (integrxf && (csb->csa_integrkey = ibuf_get(keymat,
4892
		    integrxf->xform_keylength / 8)) == NULL) {
4893
			log_debug("%s: failed to get CHILD SA integrity key",
4894
			    __func__);
4895
			childsa_free(csa);
4896
			childsa_free(csb);
4897
			goto done;
4898
		}
4899
4900
		TAILQ_INSERT_TAIL(&sa->sa_childsas, csa, csa_entry);
4901
		TAILQ_INSERT_TAIL(&sa->sa_childsas, csb, csa_entry);
4902
4903
		csa->csa_peersa = csb;
4904
		csb->csa_peersa = csa;
4905
	}
4906
4907
	ret = 0;
4908
 done:
4909
	ibuf_release(dhsecret);
4910
	ibuf_release(keymat);
4911
	ibuf_release(seed);
4912
4913
	return (ret);
4914
}
4915
4916
/* free a replaced IPCOMP SA */
4917
void
4918
ikev2_ipcomp_csa_free(struct iked *env, struct iked_childsa *csa)
4919
{
4920
	if (csa->csa_children)
4921
		fatalx("ikev2_ipcomp_csa_free: has children");
4922
	if (csa->csa_ikesa)
4923
		TAILQ_REMOVE(&csa->csa_ikesa->sa_childsas, csa,
4924
		    csa_entry);
4925
	if (csa->csa_loaded) {
4926
		log_debug("%s: csa %p loaded: calling pfkey_sa_delete",
4927
		    __func__, csa);
4928
		pfkey_sa_delete(env->sc_pfkey, csa);
4929
		RB_REMOVE(iked_activesas, &env->sc_activesas, csa);
4930
	}
4931
	childsa_free(csa);
4932
}
4933
4934
int
4935
ikev2_ipcomp_enable(struct iked *env, struct iked_sa *sa)
4936
{
4937
	struct iked_childsa	*other, *nother, *csa = NULL, *csb = NULL;
4938
	struct iked_flow	*flow, *flowa = NULL, *flowb = NULL;
4939
	struct iked_flow	*nflow, *oflow;
4940
4941
	if ((csa = calloc(1, sizeof(*csa))) == NULL ||
4942
	    (csb = calloc(1, sizeof(*csb))) == NULL ||
4943
	    (flowa = calloc(1, sizeof(*flowa))) == NULL ||
4944
	    (flowb = calloc(1, sizeof(*flowb))) == NULL) {
4945
		free(csa);
4946
		free(csb);
4947
		free(flowa);
4948
		free(flowb);
4949
		return (-1);
4950
	}
4951
4952
	/* switch ESP SAs to transport mode */
4953
	TAILQ_FOREACH(other, &sa->sa_childsas, csa_entry) {
4954
		if (!other->csa_rekey && !other->csa_loaded &&
4955
		    other->csa_saproto == IKEV2_SAPROTO_ESP) {
4956
			other->csa_transport = 1;
4957
			if (other->csa_dir == IPSP_DIRECTION_OUT) {
4958
				other->csa_parent = csa;
4959
				csa->csa_children++;
4960
			} else {
4961
				other->csa_parent = csb;
4962
				csb->csa_children++;
4963
			}
4964
		}
4965
	}
4966
4967
	/* install IPCOMP SAs */
4968
	csa->csa_ikesa = sa;
4969
	csa->csa_saproto = IKEV2_SAPROTO_IPCOMP;
4970
	csa->csa_spi.spi_size = 2;
4971
	csa->csa_spi.spi = sa->sa_cpi_out;
4972
	csa->csa_peerspi = sa->sa_cpi_in;
4973
	csa->csa_dir = IPSP_DIRECTION_OUT;
4974
	csa->csa_local = &sa->sa_local;
4975
	csa->csa_peer = &sa->sa_peer;
4976
4977
	memcpy(csb, csa, sizeof(*csb));
4978
	csb->csa_spi.spi = csa->csa_peerspi;
4979
	csb->csa_peerspi = csa->csa_spi.spi;
4980
	csb->csa_dir = IPSP_DIRECTION_IN;
4981
	csb->csa_local = csa->csa_peer;
4982
	csb->csa_peer = csa->csa_local;
4983
	csb->csa_allocated = 1;
4984
4985
	/* remove old replaced IPCOMP SAs */
4986
	TAILQ_FOREACH_SAFE(other, &sa->sa_childsas, csa_entry, nother) {
4987
		if (other->csa_saproto != IKEV2_SAPROTO_IPCOMP ||
4988
		    other->csa_children != 0)
4989
			continue;
4990
		if (other->csa_dir == csa->csa_dir &&
4991
		    IKED_ADDR_EQ(other->csa_local, csa->csa_local) &&
4992
		    IKED_ADDR_EQ(other->csa_peer, csa->csa_peer)) {
4993
			log_debug("%s: csa %p replaces %p",
4994
			    __func__, csa, other);
4995
			ikev2_ipcomp_csa_free(env, other);
4996
		} else if (other->csa_dir == csb->csa_dir &&
4997
		    IKED_ADDR_EQ(other->csa_local, csb->csa_local) &&
4998
		    IKED_ADDR_EQ(other->csa_peer, csb->csa_peer)) {
4999
			log_debug("%s: csa %p replaces %p",
5000
			    __func__, csb, other);
5001
			ikev2_ipcomp_csa_free(env, other);
5002
		}
5003
	}
5004
5005
	TAILQ_INSERT_TAIL(&sa->sa_childsas, csa, csa_entry);
5006
	TAILQ_INSERT_TAIL(&sa->sa_childsas, csb, csa_entry);
5007
5008
	csa->csa_peersa = csb;
5009
	csb->csa_peersa = csa;
5010
5011
	/* redirect flows to IPCOMP */
5012
	/* XXX expensive? should be merged into ikev2_childsa_negotiate() */
5013
	TAILQ_FOREACH_SAFE(flow, &sa->sa_flows, flow_entry, nflow) {
5014
		if (flow->flow_loaded || flow->flow_ipcomp ||
5015
		    flow->flow_saproto != IKEV2_SAPROTO_ESP)
5016
			continue;
5017
		TAILQ_FOREACH(oflow, &sa->sa_flows, flow_entry)
5018
			if (flow != oflow &&
5019
			    IKED_ADDR_EQ(&oflow->flow_src, &flow->flow_src) &&
5020
			    IKED_ADDR_EQ(&oflow->flow_dst, &flow->flow_dst) &&
5021
			    oflow->flow_dir == flow->flow_dir &&
5022
			    oflow->flow_saproto == IKEV2_SAPROTO_IPCOMP)
5023
				break;
5024
		if (oflow != NULL) {
5025
			log_debug("%s: keeping oflow %p, indentical to flow %p",
5026
			    __func__, oflow, flow);
5027
			TAILQ_REMOVE(&sa->sa_flows, flow, flow_entry);
5028
			flow_free(flow);
5029
		} else {
5030
			log_debug("%s: flow %p saproto %d -> %d", __func__,
5031
			    flow, flow->flow_saproto, IKEV2_SAPROTO_IPCOMP);
5032
			flow->flow_saproto = IKEV2_SAPROTO_IPCOMP;
5033
		}
5034
	}
5035
5036
	/* setup ESP flows for gateways */
5037
	flowa->flow_ipcomp = 1;
5038
	flowa->flow_dir = IPSP_DIRECTION_OUT;
5039
	flowa->flow_saproto = IKEV2_SAPROTO_ESP;
5040
	flowa->flow_local = &sa->sa_local;
5041
	flowa->flow_peer = &sa->sa_peer;
5042
	memcpy(&flowa->flow_src, &sa->sa_local, sizeof(sa->sa_local));
5043
	memcpy(&flowa->flow_dst, &sa->sa_peer, sizeof(sa->sa_peer));
5044
	socket_setport((struct sockaddr *)&flowa->flow_src.addr, 0);
5045
	socket_setport((struct sockaddr *)&flowa->flow_dst.addr, 0);
5046
	flowa->flow_src.addr_port = flowa->flow_dst.addr_port = 0;
5047
	flowa->flow_src.addr_mask = flowa->flow_dst.addr_mask =
5048
	    (sa->sa_local.addr_af == AF_INET) ? 32 : 128;
5049
	flowa->flow_ikesa = sa;
5050
5051
	/* skip if flow already exists */
5052
	TAILQ_FOREACH(flow, &sa->sa_flows, flow_entry) {
5053
		if (flow_equal(flow, flowa)) {
5054
			free(flowa);
5055
			free(flowb);
5056
			goto done;
5057
		}
5058
	}
5059
5060
	memcpy(flowb, flowa, sizeof(*flowb));
5061
	flowb->flow_dir = IPSP_DIRECTION_IN;
5062
	memcpy(&flowb->flow_dst, &flowa->flow_src, sizeof(flowa->flow_src));
5063
	memcpy(&flowb->flow_src, &flowa->flow_dst, sizeof(flowa->flow_dst));
5064
5065
	TAILQ_INSERT_TAIL(&sa->sa_flows, flowa, flow_entry);
5066
	TAILQ_INSERT_TAIL(&sa->sa_flows, flowb, flow_entry);
5067
5068
 done:
5069
	/* make sure IPCOMP CPIs are not reused */
5070
	sa->sa_ipcomp = 0;
5071
	sa->sa_cpi_in = sa->sa_cpi_out = 0;
5072
5073
	return (0);
5074
}
5075
5076
int
5077
ikev2_childsa_enable(struct iked *env, struct iked_sa *sa)
5078
{
5079
	struct iked_childsa	*csa, *ocsa;
5080
	struct iked_flow	*flow, *oflow;
5081
5082
	if (sa->sa_ipcomp && sa->sa_cpi_in && sa->sa_cpi_out &&
5083
	    ikev2_ipcomp_enable(env, sa) == -1)
5084
		return (-1);
5085
5086
	TAILQ_FOREACH(csa, &sa->sa_childsas, csa_entry) {
5087
		if (csa->csa_rekey || csa->csa_loaded)
5088
			continue;
5089
5090
		if (pfkey_sa_add(env->sc_pfkey, csa, NULL) != 0) {
5091
			log_debug("%s: failed to load CHILD SA spi %s",
5092
			    __func__, print_spi(csa->csa_spi.spi,
5093
			    csa->csa_spi.spi_size));
5094
			return (-1);
5095
		}
5096
5097
		if ((ocsa = RB_FIND(iked_activesas, &env->sc_activesas, csa))
5098
		    != NULL) {
5099
			log_debug("%s: replaced CHILD SA %p with %p spi %s",
5100
			    __func__, ocsa, csa, print_spi(ocsa->csa_spi.spi,
5101
			    ocsa->csa_spi.spi_size));
5102
			ocsa->csa_loaded = 0;
5103
			ocsa->csa_rekey = 1;	/* prevent re-loading */
5104
			RB_REMOVE(iked_activesas, &env->sc_activesas, ocsa);
5105
		}
5106
5107
		RB_INSERT(iked_activesas, &env->sc_activesas, csa);
5108
5109
		log_debug("%s: loaded CHILD SA spi %s", __func__,
5110
		    print_spi(csa->csa_spi.spi, csa->csa_spi.spi_size));
5111
	}
5112
5113
	TAILQ_FOREACH(flow, &sa->sa_flows, flow_entry) {
5114
		if (flow->flow_loaded)
5115
			continue;
5116
5117
		if (pfkey_flow_add(env->sc_pfkey, flow) != 0) {
5118
			log_debug("%s: failed to load flow", __func__);
5119
			return (-1);
5120
		}
5121
5122
		if ((oflow = RB_FIND(iked_flows, &env->sc_activeflows, flow))
5123
		    != NULL) {
5124
			log_debug("%s: replaced old flow %p with %p",
5125
			    __func__, oflow, flow);
5126
			oflow->flow_loaded = 0;
5127
			RB_REMOVE(iked_flows, &env->sc_activeflows, oflow);
5128
		}
5129
5130
		RB_INSERT(iked_flows, &env->sc_activeflows, flow);
5131
5132
		log_debug("%s: loaded flow %p", __func__, flow);
5133
	}
5134
5135
	return (0);
5136
}
5137
5138
int
5139
ikev2_childsa_delete(struct iked *env, struct iked_sa *sa, uint8_t saproto,
5140
    uint64_t spi, uint64_t *spiptr, int cleanup)
5141
{
5142
	struct iked_childsa	*csa, *nextcsa = NULL;
5143
	uint64_t		 peerspi = 0;
5144
	int			 found = 0, ipcomp = 0;
5145
5146
	for (csa = TAILQ_FIRST(&sa->sa_childsas); csa != NULL; csa = nextcsa) {
5147
		nextcsa = TAILQ_NEXT(csa, csa_entry);
5148
5149
		if ((saproto && csa->csa_saproto != saproto) ||
5150
		    (spi && (csa->csa_spi.spi != spi &&
5151
			     csa->csa_peerspi != spi)) ||
5152
		    (cleanup && csa->csa_loaded))
5153
			continue;
5154
5155
		if (csa->csa_loaded)
5156
			RB_REMOVE(iked_activesas, &env->sc_activesas, csa);
5157
5158
		if (pfkey_sa_delete(env->sc_pfkey, csa) != 0)
5159
			log_debug("%s: failed to delete CHILD SA spi %s",
5160
			    __func__, print_spi(csa->csa_spi.spi,
5161
			    csa->csa_spi.spi_size));
5162
		else
5163
			log_debug("%s: deleted CHILD SA spi %s", __func__,
5164
			    print_spi(csa->csa_spi.spi,
5165
			    csa->csa_spi.spi_size));
5166
		found++;
5167
5168
		if (spi && csa->csa_spi.spi == spi)
5169
			peerspi = csa->csa_peerspi;
5170
5171
		if (csa->csa_parent && csa->csa_parent->csa_children == 1)
5172
			ipcomp = 1;
5173
		TAILQ_REMOVE(&sa->sa_childsas, csa, csa_entry);
5174
		childsa_free(csa);
5175
	}
5176
5177
	/* lookup and delete matching IPcomp SAs */
5178
	if (ipcomp) {
5179
		for (csa = TAILQ_FIRST(&sa->sa_childsas); csa != NULL;
5180
		    csa = nextcsa) {
5181
			nextcsa = TAILQ_NEXT(csa, csa_entry);
5182
			if (csa->csa_saproto == IKEV2_SAPROTO_IPCOMP &&
5183
			    csa->csa_children == 0)
5184
				ikev2_ipcomp_csa_free(env, csa);
5185
		}
5186
	}
5187
5188
	if (spiptr)
5189
		*spiptr = peerspi;
5190
5191
	return (found ? 0 : -1);
5192
}
5193
5194
int
5195
ikev2_valid_proposal(struct iked_proposal *prop,
5196
    struct iked_transform **exf, struct iked_transform **ixf, int *esn)
5197
{
5198
	struct iked_transform	*xform, *encrxf, *integrxf;
5199
	unsigned int		 i, doesn = 0;
5200
5201
	switch (prop->prop_protoid) {
5202
	case IKEV2_SAPROTO_ESP:
5203
	case IKEV2_SAPROTO_AH:
5204
		break;
5205
	default:
5206
		return (-1);
5207
	}
5208
5209
	encrxf = integrxf = NULL;
5210
	for (i = 0; i < prop->prop_nxforms; i++) {
5211
		xform = prop->prop_xforms + i;
5212
		if (xform->xform_type == IKEV2_XFORMTYPE_ENCR)
5213
			encrxf = xform;
5214
		else if (xform->xform_type == IKEV2_XFORMTYPE_INTEGR)
5215
			integrxf = xform;
5216
		else if (xform->xform_type == IKEV2_XFORMTYPE_ESN &&
5217
		    xform->xform_id == IKEV2_XFORMESN_ESN)
5218
			doesn = 1;
5219
	}
5220
5221
	if (prop->prop_protoid == IKEV2_SAPROTO_IKE) {
5222
		if (encrxf == NULL || integrxf == NULL)
5223
			return (-1);
5224
	} else if (prop->prop_protoid == IKEV2_SAPROTO_AH) {
5225
		if (integrxf == NULL)
5226
			return (-1);
5227
	} else if (prop->prop_protoid == IKEV2_SAPROTO_ESP) {
5228
		if (encrxf == NULL)
5229
			return (-1);
5230
	}
5231
5232
	if (exf)
5233
		*exf = encrxf;
5234
	if (ixf)
5235
		*ixf = integrxf;
5236
	if (esn)
5237
		*esn = doesn;
5238
5239
	return (0);
5240
}
5241
5242
/* return 0 if processed, -1 if busy */
5243
int
5244
ikev2_acquire_sa(struct iked *env, struct iked_flow *acquire)
5245
{
5246
	struct iked_flow	*flow;
5247
	struct iked_sa		*sa;
5248
	struct iked_policy	 pol, *p = NULL;
5249
5250
	if (env->sc_passive)
5251
		return (0);
5252
5253
	/* First try to find an active flow with IKE SA */
5254
	flow = RB_FIND(iked_flows, &env->sc_activeflows, acquire);
5255
	if (!flow) {
5256
		/* Otherwise try to find a matching policy */
5257
		bzero(&pol, sizeof(pol));
5258
		pol.pol_af = acquire->flow_peer->addr_af;
5259
		memcpy(&pol.pol_peer, acquire->flow_peer,
5260
		    sizeof(pol.pol_peer));
5261
5262
		RB_INIT(&pol.pol_flows);
5263
		RB_INSERT(iked_flows, &pol.pol_flows, acquire);
5264
		pol.pol_nflows = 1;
5265
5266
		if ((p = policy_test(env, &pol)) == NULL) {
5267
			log_warnx("%s: flow wasn't found", __func__);
5268
			return (0);
5269
		}
5270
5271
		log_debug("%s: found matching policy '%s'", __func__,
5272
		    p->pol_name);
5273
5274
		if (ikev2_init_ike_sa_peer(env, p,
5275
		    acquire->flow_peer, NULL) != 0)
5276
			log_warnx("%s: failed to initiate a "
5277
			    "IKE_SA_INIT exchange", __func__);
5278
	} else {
5279
		log_debug("%s: found active flow", __func__);
5280
5281
		if ((sa = flow->flow_ikesa) == NULL) {
5282
			log_warnx("%s: flow without SA", __func__);
5283
			return (0);
5284
		}
5285
		if (sa->sa_stateflags & IKED_REQ_CHILDSA)
5286
			return (-1);	/* busy, retry later */
5287
		if (ikev2_send_create_child_sa(env, sa, NULL,
5288
		    flow->flow_saproto) != 0)
5289
			log_warnx("%s: failed to initiate a "
5290
			    "CREATE_CHILD_SA exchange", __func__);
5291
	}
5292
	return (0);
5293
}
5294
5295
void
5296
ikev2_disable_rekeying(struct iked *env, struct iked_sa *sa)
5297
{
5298
	struct iked_childsa		*csa;
5299
5300
	TAILQ_FOREACH(csa, &sa->sa_childsas, csa_entry) {
5301
		csa->csa_persistent = 1;
5302
		csa->csa_rekey = 0;
5303
	}
5304
5305
	(void)ikev2_childsa_delete(env, sa, 0, 0, NULL, 1);
5306
}
5307
5308
/* return 0 if processed, -1 if busy */
5309
int
5310
ikev2_rekey_sa(struct iked *env, struct iked_spi *rekey)
5311
{
5312
	struct iked_childsa		*csa, key;
5313
	struct iked_sa			*sa;
5314
5315
	key.csa_spi = *rekey;
5316
	csa = RB_FIND(iked_activesas, &env->sc_activesas, &key);
5317
	if (!csa)
5318
		return (0);
5319
5320
	if (csa->csa_rekey)	/* See if it's already taken care of */
5321
		return (0);
5322
	if (csa->csa_acquired)	/* Don't rekey, wait for hard expire */
5323
		return (0);
5324
	if (csa->csa_saproto == IKEV2_SAPROTO_IPCOMP)	/* no rekey */
5325
		return (0);
5326
	if ((sa = csa->csa_ikesa) == NULL) {
5327
		log_warnx("%s: SA %s doesn't have a parent SA", __func__,
5328
		    print_spi(rekey->spi, rekey->spi_size));
5329
		return (0);
5330
	}
5331
	if (!sa_stateok(sa, IKEV2_STATE_ESTABLISHED)) {
5332
		log_warnx("%s: SA %s is not established", __func__,
5333
		    print_spi(rekey->spi, rekey->spi_size));
5334
		return (0);
5335
	}
5336
	if (sa->sa_stateflags & IKED_REQ_CHILDSA)
5337
		return (-1);	/* busy, retry later */
5338
	if (csa->csa_allocated)	/* Peer SPI died first, get the local one */
5339
		rekey->spi = csa->csa_peerspi;
5340
	if (ikev2_send_create_child_sa(env, sa, rekey, rekey->spi_protoid))
5341
		log_warnx("%s: failed to initiate a CREATE_CHILD_SA exchange",
5342
		    __func__);
5343
	return (0);
5344
}
5345
5346
/* return 0 if processed, -1 if busy */
5347
int
5348
ikev2_drop_sa(struct iked *env, struct iked_spi *drop)
5349
{
5350
	struct ibuf			*buf = NULL;
5351
	struct iked_childsa		*csa, key;
5352
	struct iked_sa			*sa;
5353
	struct ikev2_delete		*del;
5354
	uint32_t			 spi32;
5355
	int				 acquired;
5356
5357
	key.csa_spi = *drop;
5358
	csa = RB_FIND(iked_activesas, &env->sc_activesas, &key);
5359
	if (!csa || csa->csa_rekey)
5360
		return (0);
5361
5362
	sa = csa->csa_ikesa;
5363
	if (csa->csa_saproto != IKEV2_SAPROTO_IPCOMP &&
5364
	    sa && (sa->sa_stateflags & IKED_REQ_CHILDSA)) {
5365
		/* XXXX might loop, should we add a counter? */
5366
		log_debug("%s: parent SA busy", __func__);
5367
		return (-1);	/* busy, retry later */
5368
	}
5369
5370
	RB_REMOVE(iked_activesas, &env->sc_activesas, csa);
5371
	csa->csa_loaded = 0;
5372
	csa->csa_rekey = 1;	/* prevent re-loading */
5373
	if (sa == NULL) {
5374
		log_debug("%s: failed to find a parent SA", __func__);
5375
		return (0);
5376
	}
5377
	if (csa->csa_saproto == IKEV2_SAPROTO_IPCOMP) {
5378
		/* matching Child SAs (e.g. ESP) should have expired by now */
5379
		if (csa->csa_children == 0)
5380
			ikev2_ipcomp_csa_free(env, csa);
5381
		return (0);
5382
	}
5383
5384
	if (csa->csa_allocated)
5385
		spi32 = htobe32(csa->csa_spi.spi);
5386
	else
5387
		spi32 = htobe32(csa->csa_peerspi);
5388
	acquired = csa->csa_acquired;
5389
5390
	if (ikev2_childsa_delete(env, sa, csa->csa_saproto,
5391
	    csa->csa_peerspi, NULL, 0))
5392
		log_debug("%s: failed to delete CHILD SA %s", __func__,
5393
		    print_spi(csa->csa_peerspi, drop->spi_size));
5394
5395
	/* Send PAYLOAD_DELETE */
5396
5397
	if ((buf = ibuf_static()) == NULL)
5398
		return (0);
5399
	if ((del = ibuf_advance(buf, sizeof(*del))) == NULL)
5400
		goto done;
5401
	del->del_protoid = drop->spi_protoid;
5402
	del->del_spisize = 4;
5403
	del->del_nspi = htobe16(1);
5404
	if (ibuf_add(buf, &spi32, sizeof(spi32)))
5405
		goto done;
5406
5407
	if (ikev2_send_ike_e(env, sa, buf, IKEV2_PAYLOAD_DELETE,
5408
	    IKEV2_EXCHANGE_INFORMATIONAL, 0) == -1)
5409
		goto done;
5410
5411
	sa->sa_stateflags |= IKED_REQ_INF;
5412
5413
	/* Don't automatically re-initiate Child SAs that have been acquired */
5414
	if (acquired)
5415
		goto done;
5416
5417
	/* Initiate Child SA creation */
5418
	if (ikev2_send_create_child_sa(env, sa, NULL, drop->spi_protoid))
5419
		log_warnx("%s: failed to initiate a CREATE_CHILD_SA exchange",
5420
		    __func__);
5421
5422
done:
5423
	ibuf_release(buf);
5424
	return (0);
5425
}
5426
5427
int
5428
ikev2_print_id(struct iked_id *id, char *idstr, size_t idstrlen)
5429
{
5430
	uint8_t				 buf[BUFSIZ], *ptr;
5431
	struct sockaddr_in		*s4;
5432
	struct sockaddr_in6		*s6;
5433
	char				*str;
5434
	ssize_t				 len;
5435
	int				 i;
5436
	const char			*type;
5437
5438
	bzero(buf, sizeof(buf));
5439
	bzero(idstr, idstrlen);
5440
5441
	if (id->id_buf == NULL)
5442
		return (-1);
5443
5444
	len = ibuf_size(id->id_buf);
5445
	ptr = ibuf_data(id->id_buf);
5446
5447
	if (len <= id->id_offset)
5448
		return (-1);
5449
5450
	len -= id->id_offset;
5451
	ptr += id->id_offset;
5452
5453
	type = print_map(id->id_type, ikev2_id_map);
5454
5455
	if (strlcpy(idstr, type, idstrlen) >= idstrlen ||
5456
	    strlcat(idstr, "/", idstrlen) >= idstrlen)
5457
		return (-1);
5458
5459
	idstr += strlen(idstr);
5460
	idstrlen -= strlen(idstr);
5461
5462
	switch (id->id_type) {
5463
	case IKEV2_ID_IPV4:
5464
		s4 = (struct sockaddr_in *)buf;
5465
		s4->sin_family = AF_INET;
5466
		s4->sin_len = sizeof(*s4);
5467
		memcpy(&s4->sin_addr.s_addr, ptr, len);
5468
5469
		if (print_host((struct sockaddr *)s4,
5470
		    idstr, idstrlen) == NULL)
5471
			return (-1);
5472
		break;
5473
	case IKEV2_ID_FQDN:
5474
	case IKEV2_ID_UFQDN:
5475
		if (len >= (ssize_t)sizeof(buf))
5476
			return (-1);
5477
5478
		if ((str = get_string(ptr, len)) == NULL)
5479
			return (-1);
5480
5481
		if (strlcpy(idstr, str, idstrlen) >= idstrlen) {
5482
			free(str);
5483
			return (-1);
5484
		}
5485
		free(str);
5486
		break;
5487
	case IKEV2_ID_IPV6:
5488
		s6 = (struct sockaddr_in6 *)buf;
5489
		s6->sin6_family = AF_INET6;
5490
		s6->sin6_len = sizeof(*s6);
5491
		memcpy(&s6->sin6_addr, ptr, len);
5492
5493
		if (print_host((struct sockaddr *)s6,
5494
		    idstr, idstrlen) == NULL)
5495
			return (-1);
5496
		break;
5497
	case IKEV2_ID_ASN1_DN:
5498
		if ((str = ca_asn1_name(ptr, len)) == NULL)
5499
			return (-1);
5500
		if (strlcpy(idstr, str, idstrlen) >= idstrlen) {
5501
			free(str);
5502
			return (-1);
5503
		}
5504
		free(str);
5505
		break;
5506
	default:
5507
		/* XXX test */
5508
		for (i = 0; i < ((ssize_t)idstrlen - 1) && i < len; i++)
5509
			snprintf(idstr + i, idstrlen - i,
5510
			    "%02x", ptr[i]);
5511
		break;
5512
	}
5513
5514
	return (0);
5515
}
5516
5517
/*
5518
 * If we have an IKEV2_CP_REQUEST for IKEV2_CFG_INTERNAL_IP4_ADDRESS and
5519
 * if a network(pool) is configured, then select an address from that pool
5520
 * and remember it in the sa_addrpool attribute.
5521
 */
5522
int
5523
ikev2_cp_setaddr(struct iked *env, struct iked_sa *sa, sa_family_t family)
5524
{
5525
	struct iked_cfg		*ikecfg = NULL;
5526
	struct iked_policy	*pol = sa->sa_policy;
5527
	struct sockaddr_in	*in4 = NULL, *cfg4 = NULL;
5528
	struct sockaddr_in6	*in6 = NULL, *cfg6 = NULL;
5529
	struct iked_sa		 key;
5530
	struct iked_addr	 addr;
5531
	uint32_t		 mask, host, lower, upper, start, nhost;
5532
	size_t			 i;
5533
5534
	switch (family) {
5535
		case AF_INET:
5536
			if (sa->sa_addrpool)
5537
				return (0);
5538
			break;
5539
		case AF_INET6:
5540
			if (sa->sa_addrpool6)
5541
				return (0);
5542
			break;
5543
		default:
5544
			return (-1);
5545
	}
5546
	if (pol->pol_ncfg == 0)
5547
		return (0);
5548
	/* check for an address pool config (address w/ prefixlen != 32) */
5549
	bzero(&addr, sizeof(addr));
5550
	for (i = 0; i < pol->pol_ncfg; i++) {
5551
		ikecfg = &pol->pol_cfg[i];
5552
		if (family == AF_INET &&
5553
		    ikecfg->cfg_type == IKEV2_CFG_INTERNAL_IP4_ADDRESS &&
5554
		    ikecfg->cfg.address.addr_mask != 32) {
5555
			addr.addr_af = AF_INET;
5556
			break;
5557
		}
5558
		if (family == AF_INET6 &&
5559
		    ikecfg->cfg_type == IKEV2_CFG_INTERNAL_IP6_ADDRESS &&
5560
		    ikecfg->cfg.address.addr_mask != 128) {
5561
			addr.addr_af = AF_INET6;
5562
			break;
5563
		}
5564
	}
5565
	if (i == pol->pol_ncfg)
5566
		return (0);
5567
5568
	/*
5569
	 * failure: pool configured, but not requested.
5570
	 * If we continue, we might end up with flows where 0.0.0.0 is NOT
5571
	 * replaced with an address from the pool with ikev2_cp_fixaddr().
5572
	 */
5573
	if (sa->sa_cp != IKEV2_CP_REQUEST) {
5574
		log_debug("%s: pool configured, but IKEV2_CP_REQUEST missing",
5575
		    __func__);
5576
		return (-1);
5577
	}
5578
5579
	switch (addr.addr_af) {
5580
	case AF_INET:
5581
		cfg4 = (struct sockaddr_in *)&ikecfg->cfg.address.addr;
5582
		in4 = (struct sockaddr_in *)&addr.addr;
5583
		in4->sin_family = AF_INET;
5584
		in4->sin_len = sizeof(*in4);
5585
		mask = prefixlen2mask(ikecfg->cfg.address.addr_mask);
5586
		lower = ntohl(cfg4->sin_addr.s_addr & ~mask);
5587
		key.sa_addrpool = &addr;
5588
		break;
5589
	case AF_INET6:
5590
		cfg6 = (struct sockaddr_in6 *)&ikecfg->cfg.address.addr;
5591
		in6 = (struct sockaddr_in6 *)&addr.addr;
5592
		in6->sin6_family = AF_INET6;
5593
		in6->sin6_len = sizeof(*in6);
5594
		/* truncate prefixlen to get a 32-bit space */
5595
		mask = (ikecfg->cfg.address.addr_mask >= 96)
5596
		    ? prefixlen2mask(ikecfg->cfg.address.addr_mask - 96)
5597
		    : prefixlen2mask(0);
5598
		memcpy(&lower, &cfg6->sin6_addr.s6_addr[12], sizeof(uint32_t));
5599
		lower = ntohl(lower & ~mask);
5600
		key.sa_addrpool6 = &addr;
5601
		break;
5602
	default:
5603
		return (-1);
5604
	}
5605
5606
	if (lower == 0)
5607
		lower = 1;
5608
	/* Note that start, upper and host are in HOST byte order */
5609
	upper = ntohl(~mask);
5610
	/* Randomly select start from [lower, upper-1] */
5611
	start = arc4random_uniform(upper - lower) + lower;
5612
5613
	for (host = start;;) {
5614
		log_debug("%s: mask %x start %x lower %x host %x upper %x",
5615
		    __func__, mask, start, lower, host, upper);
5616
		switch (addr.addr_af) {
5617
		case AF_INET:
5618
			in4->sin_addr.s_addr =
5619
			    (cfg4->sin_addr.s_addr & mask) | htonl(host);
5620
			break;
5621
		case AF_INET6:
5622
			memcpy(in6, cfg6, sizeof(*in6));
5623
			nhost = htonl(host);
5624
			memcpy(&in6->sin6_addr.s6_addr[12], &nhost,
5625
			    sizeof(uint32_t));
5626
			break;
5627
		}
5628
		if ((addr.addr_af == AF_INET &&
5629
		    !RB_FIND(iked_addrpool, &env->sc_addrpool, &key)) ||
5630
		    (addr.addr_af == AF_INET6 &&
5631
		    !RB_FIND(iked_addrpool6, &env->sc_addrpool6, &key)))
5632
			break;
5633
		/* try next address */
5634
		host++;
5635
		/* but skip broadcast and network address */
5636
		if (host >= upper || host < lower)
5637
			host = lower;
5638
		if (host == start) {
5639
			log_warnx("%s: address pool exhausted", __func__);
5640
			return (-1);		/* exhausted */
5641
		}
5642
	}
5643
5644
	switch (addr.addr_af) {
5645
	case AF_INET:
5646
		if (!key.sa_addrpool)
5647
			return (-1);			/* cannot happen? */
5648
		if ((sa->sa_addrpool = calloc(1, sizeof(addr))) == NULL)
5649
			return (-1);
5650
		memcpy(sa->sa_addrpool, &addr, sizeof(addr));
5651
		RB_INSERT(iked_addrpool, &env->sc_addrpool, sa);
5652
		break;
5653
	case AF_INET6:
5654
		if (!key.sa_addrpool6)
5655
			return (-1);			/* cannot happen? */
5656
		if ((sa->sa_addrpool6 = calloc(1, sizeof(addr))) == NULL)
5657
			return (-1);
5658
		memcpy(sa->sa_addrpool6, &addr, sizeof(addr));
5659
		RB_INSERT(iked_addrpool6, &env->sc_addrpool6, sa);
5660
		break;
5661
	default:
5662
		return (-1);
5663
	}
5664
	return (0);
5665
}
5666
5667
/*
5668
 * if 'addr' is 'UNSPECIFIED' replace it with sa_addrpool from
5669
 * the ip-pool and store the result in 'patched'.
5670
 */
5671
int
5672
ikev2_cp_fixaddr(struct iked_sa *sa, struct iked_addr *addr,
5673
    struct iked_addr *patched)
5674
{
5675
	struct sockaddr_in	*in4;
5676
	struct sockaddr_in6	*in6;
5677
5678
	switch (addr->addr_af) {
5679
	case AF_INET:
5680
		if (sa->sa_addrpool == NULL)
5681
			return (-1);
5682
		in4 = (struct sockaddr_in *)&addr->addr;
5683
		if (in4->sin_addr.s_addr)
5684
			return (-1);
5685
		memcpy(patched, sa->sa_addrpool, sizeof(*patched));
5686
		break;
5687
	case AF_INET6:
5688
		if (sa->sa_addrpool6 == NULL)
5689
			return (-1);
5690
		in6 = (struct sockaddr_in6 *)&addr->addr;
5691
		if (!IN6_IS_ADDR_UNSPECIFIED(&in6->sin6_addr))
5692
			return (-1);
5693
		memcpy(patched, sa->sa_addrpool6, sizeof(*patched));
5694
		break;
5695
	}
5696
	return (0);
5697
}