GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: sbin/iked/ikev2.c Lines: 0 2629 0.0 %
Date: 2016-12-06 Branches: 0 2056 0.0 %

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