GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: sbin/isakmpd/ipsec.c Lines: 0 1043 0.0 %
Date: 2017-11-07 Branches: 0 688 0.0 %

Line Branch Exec Source
1
/* $OpenBSD: ipsec.c,v 1.147 2017/07/18 06:19:07 mpi Exp $	 */
2
/* $EOM: ipsec.c,v 1.143 2000/12/11 23:57:42 niklas Exp $	 */
3
4
/*
5
 * Copyright (c) 1998, 1999, 2000, 2001 Niklas Hallqvist.  All rights reserved.
6
 * Copyright (c) 2001 Angelos D. Keromytis.  All rights reserved.
7
 * Copyright (c) 2001 Håkan Olsson.  All rights reserved.
8
 *
9
 * Redistribution and use in source and binary forms, with or without
10
 * modification, are permitted provided that the following conditions
11
 * are met:
12
 * 1. Redistributions of source code must retain the above copyright
13
 *    notice, this list of conditions and the following disclaimer.
14
 * 2. Redistributions in binary form must reproduce the above copyright
15
 *    notice, this list of conditions and the following disclaimer in the
16
 *    documentation and/or other materials provided with the distribution.
17
 *
18
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 */
29
30
/*
31
 * This code was written under funding by Ericsson Radio Systems.
32
 */
33
34
#include <sys/types.h>
35
#include <sys/socket.h>
36
#include <netdb.h>
37
#include <netinet/in.h>
38
#include <arpa/inet.h>
39
#include <stdlib.h>
40
#include <string.h>
41
42
#include <net/if.h>
43
#include <net/pfvar.h>
44
45
#include "attribute.h"
46
#include "conf.h"
47
#include "connection.h"
48
#include "constants.h"
49
#include "crypto.h"
50
#include "dh.h"
51
#include "doi.h"
52
#include "dpd.h"
53
#include "exchange.h"
54
#include "hash.h"
55
#include "ike_aggressive.h"
56
#include "ike_auth.h"
57
#include "ike_main_mode.h"
58
#include "ike_quick_mode.h"
59
#include "ipsec.h"
60
#include "ipsec_doi.h"
61
#include "isakmp.h"
62
#include "isakmp_cfg.h"
63
#include "isakmp_fld.h"
64
#include "isakmp_num.h"
65
#include "log.h"
66
#include "message.h"
67
#include "nat_traversal.h"
68
#include "pf_key_v2.h"
69
#include "prf.h"
70
#include "sa.h"
71
#include "timer.h"
72
#include "transport.h"
73
#include "util.h"
74
#include "x509.h"
75
76
extern int acquire_only;
77
78
#define MINIMUM(a, b)	(((a) < (b)) ? (a) : (b))
79
#define MAXIMUM(a, b)	(((a) > (b)) ? (a) : (b))
80
81
/* The replay window size used for all IPsec protocols if not overridden.  */
82
#define DEFAULT_REPLAY_WINDOW 16
83
84
struct ipsec_decode_arg {
85
	struct message *msg;
86
	struct sa      *sa;
87
	struct proto   *proto;
88
};
89
90
/* These variables hold the contacted peers ADT state.  */
91
struct contact {
92
	struct sockaddr *addr;
93
	socklen_t       len;
94
}              *contacts = 0;
95
int             contact_cnt = 0, contact_limit = 0;
96
97
static int      addr_cmp(const void *, const void *);
98
static int      ipsec_add_contact(struct message *);
99
static int      ipsec_contacted(struct message *);
100
static int      ipsec_debug_attribute(u_int16_t, u_int8_t *, u_int16_t,
101
    void *);
102
static void     ipsec_delete_spi(struct sa *, struct proto *, int);
103
static int16_t *ipsec_exchange_script(u_int8_t);
104
static void     ipsec_finalize_exchange(struct message *);
105
static void     ipsec_free_exchange_data(void *);
106
static void     ipsec_free_proto_data(void *);
107
static void     ipsec_free_sa_data(void *);
108
static struct keystate *ipsec_get_keystate(struct message *);
109
static u_int8_t *ipsec_get_spi(size_t *, u_int8_t, struct message *);
110
static int	ipsec_handle_leftover_payload(struct message *, u_int8_t,
111
    struct payload *);
112
static int      ipsec_informational_post_hook(struct message *);
113
static int      ipsec_informational_pre_hook(struct message *);
114
static int      ipsec_initiator(struct message *);
115
static void     ipsec_proto_init(struct proto *, char *);
116
static int      ipsec_responder(struct message *);
117
static void     ipsec_setup_situation(u_int8_t *);
118
static int      ipsec_set_network(u_int8_t *, u_int8_t *, struct sa *);
119
static size_t   ipsec_situation_size(void);
120
static u_int8_t ipsec_spi_size(u_int8_t);
121
static int      ipsec_validate_attribute(u_int16_t, u_int8_t *, u_int16_t,
122
    void *);
123
static int      ipsec_validate_exchange(u_int8_t);
124
static int	ipsec_validate_id_information(u_int8_t, u_int8_t *, u_int8_t *,
125
    size_t, struct exchange *);
126
static int      ipsec_validate_key_information(u_int8_t *, size_t);
127
static int      ipsec_validate_notification(u_int16_t);
128
static int      ipsec_validate_proto(u_int8_t);
129
static int      ipsec_validate_situation(u_int8_t *, size_t *, size_t);
130
static int      ipsec_validate_transform_id(u_int8_t, u_int8_t);
131
static int      ipsec_sa_check_flow(struct sa *, void *);
132
static int      ipsec_sa_check_flow_any(struct sa *, void *);
133
static int      ipsec_sa_tag(struct exchange *, struct sa *, struct sa *);
134
135
static struct doi ipsec_doi = {
136
	{0}, IPSEC_DOI_IPSEC,
137
	sizeof(struct ipsec_exch), sizeof(struct ipsec_sa),
138
	sizeof(struct ipsec_proto),
139
	ipsec_debug_attribute,
140
	ipsec_delete_spi,
141
	ipsec_exchange_script,
142
	ipsec_finalize_exchange,
143
	ipsec_free_exchange_data,
144
	ipsec_free_proto_data,
145
	ipsec_free_sa_data,
146
	ipsec_get_keystate,
147
	ipsec_get_spi,
148
	ipsec_handle_leftover_payload,
149
	ipsec_informational_post_hook,
150
	ipsec_informational_pre_hook,
151
	ipsec_is_attribute_incompatible,
152
	ipsec_proto_init,
153
	ipsec_setup_situation,
154
	ipsec_situation_size,
155
	ipsec_spi_size,
156
	ipsec_validate_attribute,
157
	ipsec_validate_exchange,
158
	ipsec_validate_id_information,
159
	ipsec_validate_key_information,
160
	ipsec_validate_notification,
161
	ipsec_validate_proto,
162
	ipsec_validate_situation,
163
	ipsec_validate_transform_id,
164
	ipsec_initiator,
165
	ipsec_responder,
166
	ipsec_decode_ids
167
};
168
169
int16_t script_quick_mode[] = {
170
	ISAKMP_PAYLOAD_HASH,	/* Initiator -> responder.  */
171
	ISAKMP_PAYLOAD_SA,
172
	ISAKMP_PAYLOAD_NONCE,
173
	EXCHANGE_SCRIPT_SWITCH,
174
	ISAKMP_PAYLOAD_HASH,	/* Responder -> initiator.  */
175
	ISAKMP_PAYLOAD_SA,
176
	ISAKMP_PAYLOAD_NONCE,
177
	EXCHANGE_SCRIPT_SWITCH,
178
	ISAKMP_PAYLOAD_HASH,	/* Initiator -> responder.  */
179
	EXCHANGE_SCRIPT_END
180
};
181
182
int16_t script_new_group_mode[] = {
183
	ISAKMP_PAYLOAD_HASH,	/* Initiator -> responder.  */
184
	ISAKMP_PAYLOAD_SA,
185
	EXCHANGE_SCRIPT_SWITCH,
186
	ISAKMP_PAYLOAD_HASH,	/* Responder -> initiator.  */
187
	ISAKMP_PAYLOAD_SA,
188
	EXCHANGE_SCRIPT_END
189
};
190
191
struct dst_spi_proto_arg {
192
	struct sockaddr *dst;
193
	u_int32_t       spi;
194
	u_int8_t        proto;
195
};
196
197
/*
198
 * Check if SA matches what we are asking for through V_ARG.  It has to
199
 * be a finished phase 2 SA.
200
 * if "proto" arg is 0, match any proto
201
 */
202
static int
203
ipsec_sa_check(struct sa *sa, void *v_arg)
204
{
205
	struct dst_spi_proto_arg *arg = v_arg;
206
	struct proto   *proto;
207
	struct sockaddr *dst, *src;
208
	int             incoming;
209
210
	if (sa->phase != 2 || !(sa->flags & SA_FLAG_READY))
211
		return 0;
212
213
	sa->transport->vtbl->get_dst(sa->transport, &dst);
214
	if (memcmp(sockaddr_addrdata(dst), sockaddr_addrdata(arg->dst),
215
	    sockaddr_addrlen(dst)) == 0)
216
		incoming = 0;
217
	else {
218
		sa->transport->vtbl->get_src(sa->transport, &src);
219
		if (memcmp(sockaddr_addrdata(src), sockaddr_addrdata(arg->dst),
220
		    sockaddr_addrlen(src)) == 0)
221
			incoming = 1;
222
		else
223
			return 0;
224
	}
225
226
	for (proto = TAILQ_FIRST(&sa->protos); proto;
227
	    proto = TAILQ_NEXT(proto, link))
228
		if ((arg->proto == 0 || proto->proto == arg->proto) &&
229
		    memcmp(proto->spi[incoming], &arg->spi, sizeof arg->spi)
230
		    == 0)
231
			return 1;
232
	return 0;
233
}
234
235
/* Find an SA with a "name" of DST, SPI & PROTO.  */
236
struct sa *
237
ipsec_sa_lookup(struct sockaddr *dst, u_int32_t spi, u_int8_t proto)
238
{
239
	struct dst_spi_proto_arg arg;
240
241
	arg.dst = dst;
242
	arg.spi = spi;
243
	arg.proto = proto;
244
	return sa_find(ipsec_sa_check, &arg);
245
}
246
247
/*
248
 * Check if SA matches the flow of another SA in V_ARG.  It has to
249
 * be a finished non-replaced phase 2 SA.
250
 * XXX At some point other selectors will matter here too.
251
 */
252
static int
253
ipsec_sa_check_flow(struct sa *sa, void *v_arg)
254
{
255
	if ((sa->flags & (SA_FLAG_READY | SA_FLAG_REPLACED)) != SA_FLAG_READY)
256
		return 0;
257
258
	return ipsec_sa_check_flow_any(sa, v_arg);
259
}
260
261
static int
262
ipsec_sa_check_flow_any(struct sa *sa, void *v_arg)
263
{
264
	struct sa      *sa2 = v_arg;
265
	struct ipsec_sa *isa = sa->data, *isa2 = sa2->data;
266
267
	if (sa == sa2 || sa->phase != 2 ||
268
	    (sa->flags & SA_FLAG_READY) != SA_FLAG_READY)
269
		return 0;
270
271
	if (isa->tproto != isa2->tproto || isa->sport != isa2->sport ||
272
	    isa->dport != isa2->dport)
273
		return 0;
274
275
	/*
276
	 * If at least one of the IPsec SAs is incomplete, we're done.
277
	 */
278
	if (isa->src_net == NULL || isa2->src_net == NULL ||
279
	    isa->dst_net == NULL || isa2->dst_net == NULL ||
280
	    isa->src_mask == NULL || isa2->src_mask == NULL ||
281
	    isa->dst_mask == NULL || isa2->dst_mask == NULL)
282
		return 0;
283
284
	return isa->src_net->sa_family == isa2->src_net->sa_family &&
285
	    memcmp(sockaddr_addrdata(isa->src_net),
286
	    sockaddr_addrdata(isa2->src_net),
287
	    sockaddr_addrlen(isa->src_net)) == 0 &&
288
	    memcmp(sockaddr_addrdata(isa->src_mask),
289
	    sockaddr_addrdata(isa2->src_mask),
290
	    sockaddr_addrlen(isa->src_mask)) == 0 &&
291
	    memcmp(sockaddr_addrdata(isa->dst_net),
292
	    sockaddr_addrdata(isa2->dst_net),
293
	    sockaddr_addrlen(isa->dst_net)) == 0 &&
294
	    memcmp(sockaddr_addrdata(isa->dst_mask),
295
	    sockaddr_addrdata(isa2->dst_mask),
296
	    sockaddr_addrlen(isa->dst_mask)) == 0;
297
}
298
299
/*
300
 * Construct a PF tag if specified in the configuration.
301
 * It is possible to use variables to expand the tag:
302
 * $id		The string representation of the remote ID
303
 * $domain	The stripped domain part of the ID (for FQDN and UFQDN)
304
 */
305
static int
306
ipsec_sa_tag(struct exchange *exchange, struct sa *sa, struct sa *isakmp_sa)
307
{
308
	char *format, *section;
309
	char *id_string = NULL, *domain = NULL;
310
	int error = -1;
311
	size_t len;
312
313
	sa->tag = NULL;
314
315
	if (exchange->name == NULL ||
316
	    (section = exchange->name) == NULL ||
317
	    (format = conf_get_str(section, "PF-Tag")) == NULL)
318
		return (0);	/* ignore if not present */
319
320
	len = PF_TAG_NAME_SIZE;
321
	if ((sa->tag = calloc(1, len)) == NULL) {
322
		log_error("ipsec_sa_tag: calloc");
323
		goto fail;
324
	}
325
	if (strlcpy(sa->tag, format, len) >= len) {
326
		log_print("ipsec_sa_tag: tag too long");
327
		goto fail;
328
	}
329
	if (isakmp_sa->initiator)
330
		id_string = ipsec_id_string(isakmp_sa->id_r,
331
		    isakmp_sa->id_r_len);
332
	else
333
		id_string = ipsec_id_string(isakmp_sa->id_i,
334
		    isakmp_sa->id_i_len);
335
336
	if (strstr(format, "$id") != NULL) {
337
		if (id_string == NULL) {
338
			log_print("ipsec_sa_tag: cannot get ID");
339
			goto fail;
340
		}
341
		if (expand_string(sa->tag, len, "$id", id_string) != 0) {
342
			log_print("ipsec_sa_tag: failed to expand tag");
343
			goto fail;
344
		}
345
	}
346
347
	if (strstr(format, "$domain") != NULL) {
348
		if (id_string == NULL) {
349
			log_print("ipsec_sa_tag: cannot get ID");
350
			goto fail;
351
		}
352
		if (strncmp(id_string, "fqdn/", strlen("fqdn/")) == 0)
353
			domain = strchr(id_string, '.');
354
		else if (strncmp(id_string, "ufqdn/", strlen("ufqdn/")) == 0)
355
			domain = strchr(id_string, '@');
356
		if (domain == NULL || strlen(domain) < 2) {
357
			log_print("ipsec_sa_tag: no valid domain in ID %s",
358
			    id_string);
359
			goto fail;
360
		}
361
		domain++;
362
		if (expand_string(sa->tag, len, "$domain", domain) != 0) {
363
			log_print("ipsec_sa_tag: failed to expand tag");
364
			goto fail;
365
		}
366
	}
367
368
	LOG_DBG((LOG_SA, 10, "ipsec_sa_tag: tag_len %ld tag \"%s\"",
369
	    strlen(sa->tag), sa->tag));
370
371
	error = 0;
372
 fail:
373
	free(id_string);
374
	if (error != 0) {
375
		free(sa->tag);
376
		sa->tag = NULL;
377
	}
378
379
	return (error);
380
}
381
382
/*
383
 * Do IPsec DOI specific finalizations task for the exchange where MSG was
384
 * the final message.
385
 */
386
static void
387
ipsec_finalize_exchange(struct message *msg)
388
{
389
	struct sa      *isakmp_sa = msg->isakmp_sa;
390
	struct ipsec_sa *isa;
391
	struct exchange *exchange = msg->exchange;
392
	struct ipsec_exch *ie = exchange->data;
393
	struct sa      *sa = 0, *old_sa;
394
	struct proto   *proto, *last_proto = 0;
395
	char           *addr1, *addr2, *mask1, *mask2;
396
397
	switch (exchange->phase) {
398
	case 1:
399
		switch (exchange->type) {
400
		case ISAKMP_EXCH_ID_PROT:
401
		case ISAKMP_EXCH_AGGRESSIVE:
402
			isa = isakmp_sa->data;
403
			isa->hash = ie->hash->type;
404
			isa->prf_type = ie->prf_type;
405
			isa->skeyid_len = ie->skeyid_len;
406
			isa->skeyid_d = ie->skeyid_d;
407
			isa->skeyid_a = ie->skeyid_a;
408
			/* Prevents early free of SKEYID_*.  */
409
			ie->skeyid_a = ie->skeyid_d = 0;
410
411
			/*
412
			 * If a lifetime was negotiated setup the expiration
413
			 * timers.
414
			 */
415
			if (isakmp_sa->seconds)
416
				sa_setup_expirations(isakmp_sa);
417
418
			if (isakmp_sa->flags & SA_FLAG_NAT_T_KEEPALIVE)
419
				nat_t_setup_keepalive(isakmp_sa);
420
			break;
421
		}
422
		break;
423
424
	case 2:
425
		switch (exchange->type) {
426
		case IKE_EXCH_QUICK_MODE:
427
			/*
428
			 * Tell the application(s) about the SPIs and key
429
			 * material.
430
			 */
431
			for (sa = TAILQ_FIRST(&exchange->sa_list); sa;
432
			    sa = TAILQ_NEXT(sa, next)) {
433
				isa = sa->data;
434
435
				if (exchange->initiator) {
436
					/*
437
					 * Initiator is source, responder is
438
					 * destination.
439
					 */
440
					if (ipsec_set_network(ie->id_ci,
441
					    ie->id_cr, sa)) {
442
						log_print(
443
						    "ipsec_finalize_exchange: "
444
						    "ipsec_set_network "
445
						    "failed");
446
						return;
447
					}
448
				} else {
449
					/*
450
					 * Responder is source, initiator is
451
					 * destination.
452
					 */
453
					if (ipsec_set_network(ie->id_cr,
454
					    ie->id_ci, sa)) {
455
						log_print(
456
						    "ipsec_finalize_exchange: "
457
						    "ipsec_set_network "
458
						    "failed");
459
						return;
460
					}
461
				}
462
463
				if (ipsec_sa_tag(exchange, sa, isakmp_sa) == -1)
464
					return;
465
466
				for (proto = TAILQ_FIRST(&sa->protos),
467
				    last_proto = 0; proto;
468
				    proto = TAILQ_NEXT(proto, link)) {
469
					if (pf_key_v2_set_spi(sa, proto,
470
					    0, isakmp_sa) ||
471
					    (last_proto &&
472
					    pf_key_v2_group_spis(sa,
473
						last_proto, proto, 0)) ||
474
					    pf_key_v2_set_spi(sa, proto,
475
						1, isakmp_sa) ||
476
					    (last_proto &&
477
						pf_key_v2_group_spis(sa,
478
						last_proto, proto, 1)))
479
						/*
480
						 * XXX Tear down this
481
						 * exchange.
482
						 */
483
						return;
484
					last_proto = proto;
485
				}
486
487
				if (sockaddr2text(isa->src_net, &addr1, 0))
488
					addr1 = 0;
489
				if (sockaddr2text(isa->src_mask, &mask1, 0))
490
					mask1 = 0;
491
				if (sockaddr2text(isa->dst_net, &addr2, 0))
492
					addr2 = 0;
493
				if (sockaddr2text(isa->dst_mask, &mask2, 0))
494
					mask2 = 0;
495
496
				LOG_DBG((LOG_EXCHANGE, 50,
497
				    "ipsec_finalize_exchange: src %s %s "
498
				    "dst %s %s tproto %u sport %u dport %u",
499
				    addr1 ? addr1 : "<??\?>",
500
				    mask1 ?  mask1 : "<??\?>",
501
				    addr2 ? addr2 : "<??\?>",
502
				    mask2 ? mask2 : "<??\?>",
503
				    isa->tproto, ntohs(isa->sport),
504
				    ntohs(isa->dport)));
505
506
				free(addr1);
507
				free(mask1);
508
				free(addr2);
509
				free(mask2);
510
511
				/*
512
				 * If this is not an SA acquired by the
513
				 * kernel, it needs to have a SPD entry
514
				 * (a.k.a. flow) set up.
515
				 */
516
				if (!(sa->flags & SA_FLAG_ONDEMAND ||
517
				    conf_get_str("General", "Acquire-Only") ||
518
				    acquire_only) &&
519
				    pf_key_v2_enable_sa(sa, isakmp_sa))
520
					/* XXX Tear down this exchange.  */
521
					return;
522
523
				/*
524
				 * Mark elder SAs with the same flow
525
				 * information as replaced.
526
				 */
527
				while ((old_sa = sa_find(ipsec_sa_check_flow,
528
				    sa)) != 0)
529
					sa_mark_replaced(old_sa);
530
			}
531
			break;
532
		}
533
	}
534
}
535
536
/* Set the client addresses in ISA from SRC_ID and DST_ID.  */
537
static int
538
ipsec_set_network(u_int8_t *src_id, u_int8_t *dst_id, struct sa *sa)
539
{
540
	void               *src_net, *dst_net;
541
	void               *src_mask = NULL, *dst_mask = NULL;
542
	struct sockaddr    *addr;
543
	struct proto       *proto;
544
	struct ipsec_proto *iproto;
545
	struct ipsec_sa    *isa = sa->data;
546
	int                 src_af, dst_af;
547
	int                 id;
548
	char               *name, *nat = NULL;
549
	u_int8_t           *nat_id = NULL;
550
	size_t              nat_sz;
551
552
	if ((name = connection_passive_lookup_by_ids(src_id, dst_id)))
553
		nat = conf_get_str(name, "NAT-ID");
554
555
	if (nat) {
556
		if ((nat_id = ipsec_build_id(nat, &nat_sz))) {
557
			LOG_DBG((LOG_EXCHANGE, 50, "ipsec_set_network: SRC-NAT:"
558
			    " src: %s -> %s", name, nat));
559
			src_id = nat_id;
560
		} else
561
			log_print("ipsec_set_network: ipsec_build_id"
562
			    " failed for NAT-ID: %s", nat);
563
	}
564
565
	if (((proto = TAILQ_FIRST(&sa->protos)) != NULL) &&
566
	    ((iproto = proto->data) != NULL) &&
567
	    (iproto->encap_mode == IPSEC_ENCAP_UDP_ENCAP_TRANSPORT ||
568
	    iproto->encap_mode == IPSEC_ENCAP_UDP_ENCAP_TRANSPORT_DRAFT)) {
569
		/*
570
		 * For NAT-T with transport mode, we need to use the ISAKMP's
571
		 * SA addresses for the flow.
572
		 */
573
		sa->transport->vtbl->get_src(sa->transport, &addr);
574
		src_af = addr->sa_family;
575
		src_net = sockaddr_addrdata(addr);
576
577
		sa->transport->vtbl->get_dst(sa->transport, &addr);
578
		dst_af = addr->sa_family;
579
		dst_net = sockaddr_addrdata(addr);
580
	} else {
581
		id = GET_ISAKMP_ID_TYPE(src_id);
582
		src_net = src_id + ISAKMP_ID_DATA_OFF;
583
		switch (id) {
584
		case IPSEC_ID_IPV4_ADDR_SUBNET:
585
			src_mask = (u_int8_t *)src_net + sizeof(struct in_addr);
586
			/* FALLTHROUGH */
587
		case IPSEC_ID_IPV4_ADDR:
588
			src_af = AF_INET;
589
			break;
590
591
		case IPSEC_ID_IPV6_ADDR_SUBNET:
592
			src_mask = (u_int8_t *)src_net +
593
			    sizeof(struct in6_addr);
594
			/* FALLTHROUGH */
595
		case IPSEC_ID_IPV6_ADDR:
596
			src_af = AF_INET6;
597
			break;
598
599
		default:
600
			log_print(
601
			    "ipsec_set_network: ID type %d (%s) not supported",
602
			    id, constant_name(ipsec_id_cst, id));
603
			return -1;
604
		}
605
606
		id = GET_ISAKMP_ID_TYPE(dst_id);
607
		dst_net = dst_id + ISAKMP_ID_DATA_OFF;
608
		switch (id) {
609
		case IPSEC_ID_IPV4_ADDR_SUBNET:
610
			dst_mask = (u_int8_t *)dst_net + sizeof(struct in_addr);
611
			/* FALLTHROUGH */
612
		case IPSEC_ID_IPV4_ADDR:
613
			dst_af = AF_INET;
614
			break;
615
616
		case IPSEC_ID_IPV6_ADDR_SUBNET:
617
			dst_mask = (u_int8_t *)dst_net +
618
			    sizeof(struct in6_addr);
619
			/* FALLTHROUGH */
620
		case IPSEC_ID_IPV6_ADDR:
621
			dst_af = AF_INET6;
622
			break;
623
624
		default:
625
			log_print(
626
			    "ipsec_set_network: ID type %d (%s) not supported",
627
			    id, constant_name(ipsec_id_cst, id));
628
			return -1;
629
		}
630
	}
631
632
	/* Set source address/mask.  */
633
	switch (src_af) {
634
	case AF_INET:
635
		isa->src_net = calloc(1, sizeof(struct sockaddr_in));
636
		if (!isa->src_net)
637
			goto memfail;
638
		isa->src_net->sa_family = AF_INET;
639
		isa->src_net->sa_len = sizeof(struct sockaddr_in);
640
641
		isa->src_mask = calloc(1, sizeof(struct sockaddr_in));
642
		if (!isa->src_mask)
643
			goto memfail;
644
		isa->src_mask->sa_family = AF_INET;
645
		isa->src_mask->sa_len = sizeof(struct sockaddr_in);
646
		break;
647
648
	case AF_INET6:
649
		isa->src_net = calloc(1, sizeof(struct sockaddr_in6));
650
		if (!isa->src_net)
651
			goto memfail;
652
		isa->src_net->sa_family = AF_INET6;
653
		isa->src_net->sa_len = sizeof(struct sockaddr_in6);
654
655
		isa->src_mask = calloc(1, sizeof(struct sockaddr_in6));
656
		if (!isa->src_mask)
657
			goto memfail;
658
		isa->src_mask->sa_family = AF_INET6;
659
		isa->src_mask->sa_len = sizeof(struct sockaddr_in6);
660
		break;
661
	}
662
663
	/* Net */
664
	memcpy(sockaddr_addrdata(isa->src_net), src_net,
665
	    sockaddr_addrlen(isa->src_net));
666
667
	/* Mask */
668
	if (src_mask == NULL)
669
		memset(sockaddr_addrdata(isa->src_mask), 0xff,
670
		    sockaddr_addrlen(isa->src_mask));
671
	else
672
		memcpy(sockaddr_addrdata(isa->src_mask), src_mask,
673
		    sockaddr_addrlen(isa->src_mask));
674
675
	memcpy(&isa->sport,
676
	    src_id + ISAKMP_ID_DOI_DATA_OFF + IPSEC_ID_PORT_OFF,
677
	    IPSEC_ID_PORT_LEN);
678
679
	free(nat_id);
680
681
	/* Set destination address.  */
682
	switch (dst_af) {
683
	case AF_INET:
684
		isa->dst_net = calloc(1, sizeof(struct sockaddr_in));
685
		if (!isa->dst_net)
686
			goto memfail;
687
		isa->dst_net->sa_family = AF_INET;
688
		isa->dst_net->sa_len = sizeof(struct sockaddr_in);
689
690
		isa->dst_mask = calloc(1, sizeof(struct sockaddr_in));
691
		if (!isa->dst_mask)
692
			goto memfail;
693
		isa->dst_mask->sa_family = AF_INET;
694
		isa->dst_mask->sa_len = sizeof(struct sockaddr_in);
695
		break;
696
697
	case AF_INET6:
698
		isa->dst_net = calloc(1, sizeof(struct sockaddr_in6));
699
		if (!isa->dst_net)
700
			goto memfail;
701
		isa->dst_net->sa_family = AF_INET6;
702
		isa->dst_net->sa_len = sizeof(struct sockaddr_in6);
703
704
		isa->dst_mask = calloc(1, sizeof(struct sockaddr_in6));
705
		if (!isa->dst_mask)
706
			goto memfail;
707
		isa->dst_mask->sa_family = AF_INET6;
708
		isa->dst_mask->sa_len = sizeof(struct sockaddr_in6);
709
		break;
710
	}
711
712
	/* Net */
713
	memcpy(sockaddr_addrdata(isa->dst_net), dst_net,
714
	    sockaddr_addrlen(isa->dst_net));
715
716
	/* Mask */
717
	if (dst_mask == NULL)
718
		memset(sockaddr_addrdata(isa->dst_mask), 0xff,
719
		    sockaddr_addrlen(isa->dst_mask));
720
	else
721
		memcpy(sockaddr_addrdata(isa->dst_mask), dst_mask,
722
		    sockaddr_addrlen(isa->dst_mask));
723
724
	memcpy(&isa->tproto, dst_id + ISAKMP_ID_DOI_DATA_OFF +
725
	    IPSEC_ID_PROTO_OFF, IPSEC_ID_PROTO_LEN);
726
	memcpy(&isa->dport,
727
	    dst_id + ISAKMP_ID_DOI_DATA_OFF + IPSEC_ID_PORT_OFF,
728
	    IPSEC_ID_PORT_LEN);
729
	return 0;
730
731
memfail:
732
	log_error("ipsec_set_network: calloc () failed");
733
	return -1;
734
}
735
736
/* Free the DOI-specific exchange data pointed to by VIE.  */
737
static void
738
ipsec_free_exchange_data(void *vie)
739
{
740
	struct ipsec_exch *ie = vie;
741
	struct isakmp_cfg_attr *attr;
742
743
	free(ie->sa_i_b);
744
	free(ie->id_ci);
745
	free(ie->id_cr);
746
	free(ie->g_xi);
747
	free(ie->g_xr);
748
	free(ie->g_xy);
749
	free(ie->skeyid);
750
	free(ie->skeyid_d);
751
	free(ie->skeyid_a);
752
	free(ie->skeyid_e);
753
	free(ie->hash_i);
754
	free(ie->hash_r);
755
	if (ie->group)
756
		group_free(ie->group);
757
	for (attr = LIST_FIRST(&ie->attrs); attr;
758
	    attr = LIST_FIRST(&ie->attrs)) {
759
		LIST_REMOVE(attr, link);
760
		if (attr->length)
761
			free(attr->value);
762
		free(attr);
763
	}
764
}
765
766
/* Free the DOI-specific SA data pointed to by VISA.  */
767
static void
768
ipsec_free_sa_data(void *visa)
769
{
770
	struct ipsec_sa *isa = visa;
771
772
	free(isa->src_net);
773
	free(isa->src_mask);
774
	free(isa->dst_net);
775
	free(isa->dst_mask);
776
	free(isa->skeyid_a);
777
	free(isa->skeyid_d);
778
}
779
780
/* Free the DOI-specific protocol data of an SA pointed to by VIPROTO.  */
781
static void
782
ipsec_free_proto_data(void *viproto)
783
{
784
	struct ipsec_proto *iproto = viproto;
785
	int             i;
786
787
	for (i = 0; i < 2; i++)
788
		free(iproto->keymat[i]);
789
}
790
791
/* Return exchange script based on TYPE.  */
792
static int16_t *
793
ipsec_exchange_script(u_int8_t type)
794
{
795
	switch (type) {
796
	case ISAKMP_EXCH_TRANSACTION:
797
		return script_transaction;
798
	case IKE_EXCH_QUICK_MODE:
799
		return script_quick_mode;
800
	case IKE_EXCH_NEW_GROUP_MODE:
801
		return script_new_group_mode;
802
	}
803
	return 0;
804
}
805
806
/* Initialize this DOI, requires doi_init to already have been called.  */
807
void
808
ipsec_init(void)
809
{
810
	doi_register(&ipsec_doi);
811
}
812
813
/* Given a message MSG, return a suitable IV (or rather keystate).  */
814
static struct keystate *
815
ipsec_get_keystate(struct message *msg)
816
{
817
	struct keystate *ks;
818
	struct hash    *hash;
819
820
	/* If we have already have an IV, use it.  */
821
	if (msg->exchange && msg->exchange->keystate) {
822
		ks = malloc(sizeof *ks);
823
		if (!ks) {
824
			log_error("ipsec_get_keystate: malloc (%lu) failed",
825
			    (unsigned long) sizeof *ks);
826
			return 0;
827
		}
828
		memcpy(ks, msg->exchange->keystate, sizeof *ks);
829
		return ks;
830
	}
831
	/*
832
	 * For phase 2 when no SA yet is setup we need to hash the IV used by
833
	 * the ISAKMP SA concatenated with the message ID, and use that as an
834
	 * IV for further cryptographic operations.
835
         */
836
	if (!msg->isakmp_sa->keystate) {
837
		log_print("ipsec_get_keystate: no keystate in ISAKMP SA %p",
838
		    msg->isakmp_sa);
839
		return 0;
840
	}
841
	ks = crypto_clone_keystate(msg->isakmp_sa->keystate);
842
	if (!ks)
843
		return 0;
844
845
	hash = hash_get(((struct ipsec_sa *)msg->isakmp_sa->data)->hash);
846
	hash->Init(hash->ctx);
847
	LOG_DBG_BUF((LOG_CRYPTO, 80, "ipsec_get_keystate: final phase 1 IV",
848
	    ks->riv, ks->xf->blocksize));
849
	hash->Update(hash->ctx, ks->riv, ks->xf->blocksize);
850
	LOG_DBG_BUF((LOG_CRYPTO, 80, "ipsec_get_keystate: message ID",
851
	    ((u_int8_t *) msg->iov[0].iov_base) + ISAKMP_HDR_MESSAGE_ID_OFF,
852
	    ISAKMP_HDR_MESSAGE_ID_LEN));
853
	hash->Update(hash->ctx, ((u_int8_t *) msg->iov[0].iov_base) +
854
	    ISAKMP_HDR_MESSAGE_ID_OFF, ISAKMP_HDR_MESSAGE_ID_LEN);
855
	hash->Final(hash->digest, hash->ctx);
856
	crypto_init_iv(ks, hash->digest, ks->xf->blocksize);
857
	LOG_DBG_BUF((LOG_CRYPTO, 80, "ipsec_get_keystate: phase 2 IV",
858
	    hash->digest, ks->xf->blocksize));
859
	return ks;
860
}
861
862
static void
863
ipsec_setup_situation(u_int8_t *buf)
864
{
865
	SET_IPSEC_SIT_SIT(buf + ISAKMP_SA_SIT_OFF, IPSEC_SIT_IDENTITY_ONLY);
866
}
867
868
static size_t
869
ipsec_situation_size(void)
870
{
871
	return IPSEC_SIT_SIT_LEN;
872
}
873
874
static u_int8_t
875
ipsec_spi_size(u_int8_t proto)
876
{
877
	return IPSEC_SPI_SIZE;
878
}
879
880
static int
881
ipsec_validate_attribute(u_int16_t type, u_int8_t * value, u_int16_t len,
882
    void *vmsg)
883
{
884
	struct message *msg = vmsg;
885
886
	if (msg->exchange->phase == 1 &&
887
	    (type < IKE_ATTR_ENCRYPTION_ALGORITHM || type > IKE_ATTR_GROUP_ORDER))
888
		return -1;
889
	if (msg->exchange->phase == 2 &&
890
	    (type < IPSEC_ATTR_SA_LIFE_TYPE || type > IPSEC_ATTR_ECN_TUNNEL))
891
		return -1;
892
	return 0;
893
}
894
895
static int
896
ipsec_validate_exchange(u_int8_t exch)
897
{
898
	return exch != IKE_EXCH_QUICK_MODE && exch != IKE_EXCH_NEW_GROUP_MODE;
899
}
900
901
static int
902
ipsec_validate_id_information(u_int8_t type, u_int8_t *extra, u_int8_t *buf,
903
    size_t sz, struct exchange *exchange)
904
{
905
	u_int8_t        proto = GET_IPSEC_ID_PROTO(extra);
906
	u_int16_t       port = GET_IPSEC_ID_PORT(extra);
907
908
	LOG_DBG((LOG_MESSAGE, 40,
909
	    "ipsec_validate_id_information: proto %d port %d type %d",
910
	    proto, port, type));
911
	if (type < IPSEC_ID_IPV4_ADDR || type > IPSEC_ID_KEY_ID)
912
		return -1;
913
914
	switch (type) {
915
	case IPSEC_ID_IPV4_ADDR:
916
		LOG_DBG_BUF((LOG_MESSAGE, 40,
917
		    "ipsec_validate_id_information: IPv4", buf,
918
		    sizeof(struct in_addr)));
919
		break;
920
921
	case IPSEC_ID_IPV6_ADDR:
922
		LOG_DBG_BUF((LOG_MESSAGE, 40,
923
		    "ipsec_validate_id_information: IPv6", buf,
924
		    sizeof(struct in6_addr)));
925
		break;
926
927
	case IPSEC_ID_IPV4_ADDR_SUBNET:
928
		LOG_DBG_BUF((LOG_MESSAGE, 40,
929
		    "ipsec_validate_id_information: IPv4 network/netmask",
930
		    buf, 2 * sizeof(struct in_addr)));
931
		break;
932
933
	case IPSEC_ID_IPV6_ADDR_SUBNET:
934
		LOG_DBG_BUF((LOG_MESSAGE, 40,
935
		    "ipsec_validate_id_information: IPv6 network/netmask",
936
		    buf, 2 * sizeof(struct in6_addr)));
937
		break;
938
939
	default:
940
		break;
941
	}
942
943
	if (exchange->phase == 1 &&
944
	    (proto != IPPROTO_UDP || port != UDP_DEFAULT_PORT) &&
945
	    (proto != 0 || port != 0)) {
946
		/*
947
		 * XXX SSH's ISAKMP tester fails this test (proto 17 - port
948
		 * 0).
949
		 */
950
#ifdef notyet
951
		return -1;
952
#else
953
		log_print("ipsec_validate_id_information: dubious ID "
954
		    "information accepted");
955
#endif
956
	}
957
	/* XXX More checks?  */
958
959
	return 0;
960
}
961
962
static int
963
ipsec_validate_key_information(u_int8_t *buf, size_t sz)
964
{
965
	/* XXX Not implemented yet.  */
966
	return 0;
967
}
968
969
static int
970
ipsec_validate_notification(u_int16_t type)
971
{
972
	return type < IPSEC_NOTIFY_RESPONDER_LIFETIME ||
973
	    type > IPSEC_NOTIFY_INITIAL_CONTACT ? -1 : 0;
974
}
975
976
static int
977
ipsec_validate_proto(u_int8_t proto)
978
{
979
	return proto < IPSEC_PROTO_IPSEC_AH ||
980
	    proto > IPSEC_PROTO_IPCOMP ? -1 : 0;
981
}
982
983
static int
984
ipsec_validate_situation(u_int8_t *buf, size_t *sz, size_t len)
985
{
986
	if (len < IPSEC_SIT_SIT_OFF + IPSEC_SIT_SIT_LEN) {
987
		log_print("ipsec_validate_situation: payload too short: %u",
988
		    (unsigned int) len);
989
		return -1;
990
	}
991
	/* Currently only "identity only" situations are supported.  */
992
	if (GET_IPSEC_SIT_SIT(buf) != IPSEC_SIT_IDENTITY_ONLY)
993
		return 1;
994
995
	*sz = IPSEC_SIT_SIT_LEN;
996
997
	return 0;
998
}
999
1000
static int
1001
ipsec_validate_transform_id(u_int8_t proto, u_int8_t transform_id)
1002
{
1003
	switch (proto) {
1004
	/*
1005
	 * As no unexpected protocols can occur, we just tie the
1006
	 * default case to the first case, in order to silence a GCC
1007
	 * warning.
1008
	 */
1009
	default:
1010
	case ISAKMP_PROTO_ISAKMP:
1011
		return transform_id != IPSEC_TRANSFORM_KEY_IKE;
1012
	case IPSEC_PROTO_IPSEC_AH:
1013
		return transform_id < IPSEC_AH_MD5 ||
1014
		    transform_id > IPSEC_AH_RIPEMD ? -1 : 0;
1015
	case IPSEC_PROTO_IPSEC_ESP:
1016
		return transform_id < IPSEC_ESP_DES_IV64 ||
1017
		    (transform_id > IPSEC_ESP_AES_GMAC &&
1018
		    transform_id < IPSEC_ESP_AES_MARS) ||
1019
		    transform_id > IPSEC_ESP_AES_TWOFISH ? -1 : 0;
1020
	case IPSEC_PROTO_IPCOMP:
1021
		return transform_id < IPSEC_IPCOMP_OUI ||
1022
		    transform_id > IPSEC_IPCOMP_V42BIS ? -1 : 0;
1023
	}
1024
}
1025
1026
static int
1027
ipsec_initiator(struct message *msg)
1028
{
1029
	struct exchange *exchange = msg->exchange;
1030
	int             (**script)(struct message *) = 0;
1031
1032
	/* Check that the SA is coherent with the IKE rules.  */
1033
	if (exchange->type != ISAKMP_EXCH_TRANSACTION &&
1034
	    ((exchange->phase == 1 && exchange->type != ISAKMP_EXCH_ID_PROT &&
1035
	    exchange->type != ISAKMP_EXCH_AGGRESSIVE &&
1036
	    exchange->type != ISAKMP_EXCH_INFO) ||
1037
	    (exchange->phase == 2 && exchange->type != IKE_EXCH_QUICK_MODE &&
1038
	    exchange->type != ISAKMP_EXCH_INFO))) {
1039
		log_print("ipsec_initiator: unsupported exchange type %d "
1040
		    "in phase %d", exchange->type, exchange->phase);
1041
		return -1;
1042
	}
1043
	switch (exchange->type) {
1044
	case ISAKMP_EXCH_ID_PROT:
1045
		script = ike_main_mode_initiator;
1046
		break;
1047
	case ISAKMP_EXCH_AGGRESSIVE:
1048
		script = ike_aggressive_initiator;
1049
		break;
1050
	case ISAKMP_EXCH_TRANSACTION:
1051
		script = isakmp_cfg_initiator;
1052
		break;
1053
	case ISAKMP_EXCH_INFO:
1054
		return message_send_info(msg);
1055
	case IKE_EXCH_QUICK_MODE:
1056
		script = ike_quick_mode_initiator;
1057
		break;
1058
	default:
1059
		log_print("ipsec_initiator: unsupported exchange type %d",
1060
			  exchange->type);
1061
		return -1;
1062
	}
1063
1064
	/* Run the script code for this step.  */
1065
	if (script)
1066
		return script[exchange->step] (msg);
1067
1068
	return 0;
1069
}
1070
1071
/*
1072
 * delete all SA's from addr with the associated proto and SPI's
1073
 *
1074
 * spis[] is an array of SPIs of size 16-octet for proto ISAKMP
1075
 * or 4-octet otherwise.
1076
 */
1077
static void
1078
ipsec_delete_spi_list(struct sockaddr *addr, u_int8_t proto, u_int8_t *spis,
1079
    int nspis, char *type)
1080
{
1081
	struct sa	*sa;
1082
	char		*peer;
1083
	char		 ids[1024];
1084
	int		 i;
1085
1086
	for (i = 0; i < nspis; i++) {
1087
		if (proto == ISAKMP_PROTO_ISAKMP) {
1088
			u_int8_t *spi = spis + i * ISAKMP_HDR_COOKIES_LEN;
1089
1090
			/*
1091
			 * This really shouldn't happen in IPSEC DOI
1092
			 * code, but Cisco VPN 3000 sends ISAKMP DELETE's
1093
			 * this way.
1094
			 */
1095
			sa = sa_lookup_isakmp_sa(addr, spi);
1096
		} else {
1097
			u_int32_t spi = ((u_int32_t *)spis)[i];
1098
1099
			sa = ipsec_sa_lookup(addr, spi, proto);
1100
		}
1101
1102
		if (sa == NULL) {
1103
			LOG_DBG((LOG_SA, 30, "ipsec_delete_spi_list: could "
1104
			    "not locate SA (SPI %08x, proto %u)",
1105
			    ((u_int32_t *)spis)[i], proto));
1106
			continue;
1107
		}
1108
1109
		strlcpy(ids,
1110
		    sa->doi->decode_ids("initiator id: %s, responder id: %s",
1111
		    sa->id_i, sa->id_i_len, sa->id_r, sa->id_r_len, 0),
1112
		    sizeof ids);
1113
		if (sockaddr2text(addr, &peer, 0))
1114
			peer = NULL;
1115
1116
		/* only log deletion of SAs which are not soft expired yet */
1117
		if (sa->soft_death != NULL)
1118
			log_verbose("isakmpd: Peer %s made us delete live SA "
1119
			    "%s for proto %d, %s", peer ? peer : "<unknown>",
1120
			    sa->name ? sa->name : "<unnamed>", proto, ids);
1121
1122
		LOG_DBG((LOG_SA, 30, "ipsec_delete_spi_list: "
1123
		    "%s made us delete SA %p (%d references) for proto %d (%s)",
1124
		    type, sa, sa->refcnt, proto, ids));
1125
		free(peer);
1126
1127
		/* Delete the SA and search for the next */
1128
		sa_free(sa);
1129
	}
1130
}
1131
1132
static int
1133
ipsec_responder(struct message *msg)
1134
{
1135
	struct exchange *exchange = msg->exchange;
1136
	int             (**script)(struct message *) = 0;
1137
	struct payload *p;
1138
	u_int16_t       type;
1139
1140
	/* Check that a new exchange is coherent with the IKE rules.  */
1141
	if (exchange->step == 0 && exchange->type != ISAKMP_EXCH_TRANSACTION &&
1142
	    ((exchange->phase == 1 && exchange->type != ISAKMP_EXCH_ID_PROT &&
1143
	    exchange->type != ISAKMP_EXCH_AGGRESSIVE &&
1144
	    exchange->type != ISAKMP_EXCH_INFO) ||
1145
	    (exchange->phase == 2 && exchange->type != IKE_EXCH_QUICK_MODE &&
1146
	    exchange->type != ISAKMP_EXCH_INFO))) {
1147
		message_drop(msg, ISAKMP_NOTIFY_UNSUPPORTED_EXCHANGE_TYPE,
1148
		    0, 1, 0);
1149
		return -1;
1150
	}
1151
	LOG_DBG((LOG_MISC, 30, "ipsec_responder: phase %d exchange %d step %d",
1152
	    exchange->phase, exchange->type, exchange->step));
1153
	switch (exchange->type) {
1154
	case ISAKMP_EXCH_ID_PROT:
1155
		script = ike_main_mode_responder;
1156
		break;
1157
	case ISAKMP_EXCH_AGGRESSIVE:
1158
		script = ike_aggressive_responder;
1159
		break;
1160
	case ISAKMP_EXCH_TRANSACTION:
1161
		script = isakmp_cfg_responder;
1162
		break;
1163
	case ISAKMP_EXCH_INFO:
1164
		TAILQ_FOREACH(p, &msg->payload[ISAKMP_PAYLOAD_NOTIFY], link) {
1165
			type = GET_ISAKMP_NOTIFY_MSG_TYPE(p->p);
1166
			LOG_DBG((LOG_EXCHANGE, 10,
1167
			    "ipsec_responder: got NOTIFY of type %s",
1168
			    constant_name(isakmp_notify_cst, type)));
1169
1170
			switch (type) {
1171
			case IPSEC_NOTIFY_INITIAL_CONTACT:
1172
				/* Handled by leftover logic. */
1173
				break;
1174
1175
			case ISAKMP_NOTIFY_STATUS_DPD_R_U_THERE:
1176
			case ISAKMP_NOTIFY_STATUS_DPD_R_U_THERE_ACK:
1177
				dpd_handle_notify(msg, p);
1178
				break;
1179
1180
			default:
1181
				p->flags |= PL_MARK;
1182
				break;
1183
			}
1184
		}
1185
1186
		/*
1187
		 * If any DELETEs are in here, let the logic of leftover
1188
		 * payloads deal with them.
1189
		 */
1190
		return 0;
1191
1192
	case IKE_EXCH_QUICK_MODE:
1193
		script = ike_quick_mode_responder;
1194
		break;
1195
1196
	default:
1197
		message_drop(msg, ISAKMP_NOTIFY_UNSUPPORTED_EXCHANGE_TYPE,
1198
		    0, 1, 0);
1199
		return -1;
1200
	}
1201
1202
	/* Run the script code for this step.  */
1203
	if (script)
1204
		return script[exchange->step] (msg);
1205
1206
	/*
1207
	 * XXX So far we don't accept any proposals for exchanges we don't
1208
	 * support.
1209
         */
1210
	if (payload_first(msg, ISAKMP_PAYLOAD_SA)) {
1211
		message_drop(msg, ISAKMP_NOTIFY_NO_PROPOSAL_CHOSEN, 0, 1, 0);
1212
		return -1;
1213
	}
1214
	return 0;
1215
}
1216
1217
static enum hashes
1218
from_ike_hash(u_int16_t hash)
1219
{
1220
	switch (hash) {
1221
		case IKE_HASH_MD5:
1222
		return HASH_MD5;
1223
	case IKE_HASH_SHA:
1224
		return HASH_SHA1;
1225
	case IKE_HASH_SHA2_256:
1226
		return HASH_SHA2_256;
1227
	case IKE_HASH_SHA2_384:
1228
		return HASH_SHA2_384;
1229
	case IKE_HASH_SHA2_512:
1230
		return HASH_SHA2_512;
1231
	}
1232
	return -1;
1233
}
1234
1235
static enum transform
1236
from_ike_crypto(u_int16_t crypto)
1237
{
1238
	/* Coincidentally this is the null operation :-)  */
1239
	return crypto;
1240
}
1241
1242
/*
1243
 * Find out whether the attribute of type TYPE with a LEN length value
1244
 * pointed to by VALUE is incompatible with what we can handle.
1245
 * VMSG is a pointer to the current message.
1246
 */
1247
int
1248
ipsec_is_attribute_incompatible(u_int16_t type, u_int8_t *value, u_int16_t len,
1249
    void *vmsg)
1250
{
1251
	struct message *msg = vmsg;
1252
	u_int16_t dv = decode_16(value);
1253
1254
	if (msg->exchange->phase == 1) {
1255
		switch (type) {
1256
		case IKE_ATTR_ENCRYPTION_ALGORITHM:
1257
			return !crypto_get(from_ike_crypto(dv));
1258
		case IKE_ATTR_HASH_ALGORITHM:
1259
			return !hash_get(from_ike_hash(dv));
1260
		case IKE_ATTR_AUTHENTICATION_METHOD:
1261
			return !ike_auth_get(dv);
1262
		case IKE_ATTR_GROUP_DESCRIPTION:
1263
			return (dv < IKE_GROUP_DESC_MODP_768 ||
1264
			    dv > IKE_GROUP_DESC_MODP_1536) &&
1265
			    (dv < IKE_GROUP_DESC_MODP_2048 ||
1266
			    dv > IKE_GROUP_DESC_MODP_8192);
1267
		case IKE_ATTR_GROUP_TYPE:
1268
			return 1;
1269
		case IKE_ATTR_GROUP_PRIME:
1270
			return 1;
1271
		case IKE_ATTR_GROUP_GENERATOR_1:
1272
			return 1;
1273
		case IKE_ATTR_GROUP_GENERATOR_2:
1274
			return 1;
1275
		case IKE_ATTR_GROUP_CURVE_A:
1276
			return 1;
1277
		case IKE_ATTR_GROUP_CURVE_B:
1278
			return 1;
1279
		case IKE_ATTR_LIFE_TYPE:
1280
			return dv < IKE_DURATION_SECONDS ||
1281
			    dv > IKE_DURATION_KILOBYTES;
1282
		case IKE_ATTR_LIFE_DURATION:
1283
			return len != 2 && len != 4;
1284
		case IKE_ATTR_PRF:
1285
			return 1;
1286
		case IKE_ATTR_KEY_LENGTH:
1287
			/*
1288
			 * Our crypto routines only allows key-lengths which
1289
			 * are multiples of an octet.
1290
			 */
1291
			return dv % 8 != 0;
1292
		case IKE_ATTR_FIELD_SIZE:
1293
			return 1;
1294
		case IKE_ATTR_GROUP_ORDER:
1295
			return 1;
1296
		}
1297
	} else {
1298
		switch (type) {
1299
		case IPSEC_ATTR_SA_LIFE_TYPE:
1300
			return dv < IPSEC_DURATION_SECONDS ||
1301
			    dv > IPSEC_DURATION_KILOBYTES;
1302
		case IPSEC_ATTR_SA_LIFE_DURATION:
1303
			return len != 2 && len != 4;
1304
		case IPSEC_ATTR_GROUP_DESCRIPTION:
1305
			return (dv < IKE_GROUP_DESC_MODP_768 ||
1306
			    dv > IKE_GROUP_DESC_MODP_1536) &&
1307
			    (dv < IKE_GROUP_DESC_MODP_2048 ||
1308
			    IKE_GROUP_DESC_MODP_8192 < dv);
1309
		case IPSEC_ATTR_ENCAPSULATION_MODE:
1310
			return dv != IPSEC_ENCAP_TUNNEL &&
1311
			    dv != IPSEC_ENCAP_TRANSPORT &&
1312
			    dv != IPSEC_ENCAP_UDP_ENCAP_TUNNEL &&
1313
			    dv != IPSEC_ENCAP_UDP_ENCAP_TRANSPORT &&
1314
			    dv != IPSEC_ENCAP_UDP_ENCAP_TUNNEL_DRAFT &&
1315
			    dv != IPSEC_ENCAP_UDP_ENCAP_TRANSPORT_DRAFT;
1316
		case IPSEC_ATTR_AUTHENTICATION_ALGORITHM:
1317
			return dv < IPSEC_AUTH_HMAC_MD5 ||
1318
			    dv > IPSEC_AUTH_HMAC_RIPEMD;
1319
		case IPSEC_ATTR_KEY_LENGTH:
1320
			/*
1321
			 * XXX Blowfish needs '0'. Others appear to disregard
1322
			 * this attr?
1323
			 */
1324
			return 0;
1325
		case IPSEC_ATTR_KEY_ROUNDS:
1326
			return 1;
1327
		case IPSEC_ATTR_COMPRESS_DICTIONARY_SIZE:
1328
			return 1;
1329
		case IPSEC_ATTR_COMPRESS_PRIVATE_ALGORITHM:
1330
			return 1;
1331
		case IPSEC_ATTR_ECN_TUNNEL:
1332
			return 1;
1333
		}
1334
	}
1335
	/* XXX Silence gcc.  */
1336
	return 1;
1337
}
1338
1339
/*
1340
 * Log the attribute of TYPE with a LEN length value pointed to by VALUE
1341
 * in human-readable form.  VMSG is a pointer to the current message.
1342
 */
1343
int
1344
ipsec_debug_attribute(u_int16_t type, u_int8_t *value, u_int16_t len,
1345
    void *vmsg)
1346
{
1347
	struct message *msg = vmsg;
1348
	char            val[20];
1349
1350
	/* XXX Transient solution.  */
1351
	if (len == 2)
1352
		snprintf(val, sizeof val, "%d", decode_16(value));
1353
	else if (len == 4)
1354
		snprintf(val, sizeof val, "%d", decode_32(value));
1355
	else
1356
		snprintf(val, sizeof val, "unrepresentable");
1357
1358
	LOG_DBG((LOG_MESSAGE, 50, "Attribute %s value %s",
1359
	    constant_name(msg->exchange->phase == 1 ? ike_attr_cst :
1360
	    ipsec_attr_cst, type), val));
1361
	return 0;
1362
}
1363
1364
/*
1365
 * Decode the attribute of type TYPE with a LEN length value pointed to by
1366
 * VALUE.  VIDA is a pointer to a context structure where we can find the
1367
 * current message, SA and protocol.
1368
 */
1369
int
1370
ipsec_decode_attribute(u_int16_t type, u_int8_t *value, u_int16_t len,
1371
    void *vida)
1372
{
1373
	struct ipsec_decode_arg *ida = vida;
1374
	struct message *msg = ida->msg;
1375
	struct sa      *sa = ida->sa;
1376
	struct ipsec_sa *isa = sa->data;
1377
	struct proto   *proto = ida->proto;
1378
	struct ipsec_proto *iproto = proto->data;
1379
	struct exchange *exchange = msg->exchange;
1380
	struct ipsec_exch *ie = exchange->data;
1381
	static int      lifetype = 0;
1382
1383
	if (exchange->phase == 1) {
1384
		switch (type) {
1385
		case IKE_ATTR_ENCRYPTION_ALGORITHM:
1386
			/* XXX Errors possible?  */
1387
			exchange->crypto = crypto_get(from_ike_crypto(
1388
			    decode_16(value)));
1389
			break;
1390
		case IKE_ATTR_HASH_ALGORITHM:
1391
			/* XXX Errors possible?  */
1392
			ie->hash = hash_get(from_ike_hash(decode_16(value)));
1393
			break;
1394
		case IKE_ATTR_AUTHENTICATION_METHOD:
1395
			/* XXX Errors possible?  */
1396
			ie->ike_auth = ike_auth_get(decode_16(value));
1397
			break;
1398
		case IKE_ATTR_GROUP_DESCRIPTION:
1399
			isa->group_desc = decode_16(value);
1400
			break;
1401
		case IKE_ATTR_GROUP_TYPE:
1402
			break;
1403
		case IKE_ATTR_GROUP_PRIME:
1404
			break;
1405
		case IKE_ATTR_GROUP_GENERATOR_1:
1406
			break;
1407
		case IKE_ATTR_GROUP_GENERATOR_2:
1408
			break;
1409
		case IKE_ATTR_GROUP_CURVE_A:
1410
			break;
1411
		case IKE_ATTR_GROUP_CURVE_B:
1412
			break;
1413
		case IKE_ATTR_LIFE_TYPE:
1414
			lifetype = decode_16(value);
1415
			return 0;
1416
		case IKE_ATTR_LIFE_DURATION:
1417
			switch (lifetype) {
1418
			case IKE_DURATION_SECONDS:
1419
				switch (len) {
1420
				case 2:
1421
					sa->seconds = decode_16(value);
1422
					break;
1423
				case 4:
1424
					sa->seconds = decode_32(value);
1425
					break;
1426
				default:
1427
					log_print("ipsec_decode_attribute: "
1428
					    "unreasonable lifetime");
1429
				}
1430
				break;
1431
			case IKE_DURATION_KILOBYTES:
1432
				switch (len) {
1433
				case 2:
1434
					sa->kilobytes = decode_16(value);
1435
					break;
1436
				case 4:
1437
					sa->kilobytes = decode_32(value);
1438
					break;
1439
				default:
1440
					log_print("ipsec_decode_attribute: "
1441
					    "unreasonable lifetime");
1442
				}
1443
				break;
1444
			default:
1445
				log_print("ipsec_decode_attribute: unknown "
1446
				    "lifetime type");
1447
			}
1448
			break;
1449
		case IKE_ATTR_PRF:
1450
			break;
1451
		case IKE_ATTR_KEY_LENGTH:
1452
			exchange->key_length = decode_16(value) / 8;
1453
			break;
1454
		case IKE_ATTR_FIELD_SIZE:
1455
			break;
1456
		case IKE_ATTR_GROUP_ORDER:
1457
			break;
1458
		}
1459
	} else {
1460
		switch (type) {
1461
		case IPSEC_ATTR_SA_LIFE_TYPE:
1462
			lifetype = decode_16(value);
1463
			return 0;
1464
		case IPSEC_ATTR_SA_LIFE_DURATION:
1465
			switch (lifetype) {
1466
			case IPSEC_DURATION_SECONDS:
1467
				switch (len) {
1468
				case 2:
1469
					sa->seconds = decode_16(value);
1470
					break;
1471
				case 4:
1472
					sa->seconds = decode_32(value);
1473
					break;
1474
				default:
1475
					log_print("ipsec_decode_attribute: "
1476
					    "unreasonable lifetime");
1477
				}
1478
				break;
1479
			case IPSEC_DURATION_KILOBYTES:
1480
				switch (len) {
1481
				case 2:
1482
					sa->kilobytes = decode_16(value);
1483
					break;
1484
				case 4:
1485
					sa->kilobytes = decode_32(value);
1486
					break;
1487
				default:
1488
					log_print("ipsec_decode_attribute: "
1489
					    "unreasonable lifetime");
1490
				}
1491
				break;
1492
			default:
1493
				log_print("ipsec_decode_attribute: unknown "
1494
				    "lifetime type");
1495
			}
1496
			break;
1497
		case IPSEC_ATTR_GROUP_DESCRIPTION:
1498
			isa->group_desc = decode_16(value);
1499
			break;
1500
		case IPSEC_ATTR_ENCAPSULATION_MODE:
1501
			/*
1502
			 * XXX Multiple protocols must have same
1503
			 * encapsulation mode, no?
1504
			 */
1505
			iproto->encap_mode = decode_16(value);
1506
			break;
1507
		case IPSEC_ATTR_AUTHENTICATION_ALGORITHM:
1508
			iproto->auth = decode_16(value);
1509
			break;
1510
		case IPSEC_ATTR_KEY_LENGTH:
1511
			iproto->keylen = decode_16(value);
1512
			break;
1513
		case IPSEC_ATTR_KEY_ROUNDS:
1514
			iproto->keyrounds = decode_16(value);
1515
			break;
1516
		case IPSEC_ATTR_COMPRESS_DICTIONARY_SIZE:
1517
			break;
1518
		case IPSEC_ATTR_COMPRESS_PRIVATE_ALGORITHM:
1519
			break;
1520
		case IPSEC_ATTR_ECN_TUNNEL:
1521
			break;
1522
		}
1523
	}
1524
	lifetype = 0;
1525
	return 0;
1526
}
1527
1528
/*
1529
 * Walk over the attributes of the transform payload found in BUF, and
1530
 * fill out the fields of the SA attached to MSG.  Also mark the SA as
1531
 * processed.
1532
 */
1533
void
1534
ipsec_decode_transform(struct message *msg, struct sa *sa, struct proto *proto,
1535
    u_int8_t *buf)
1536
{
1537
	struct ipsec_exch *ie = msg->exchange->data;
1538
	struct ipsec_decode_arg ida;
1539
1540
	LOG_DBG((LOG_MISC, 20, "ipsec_decode_transform: transform %d chosen",
1541
	    GET_ISAKMP_TRANSFORM_NO(buf)));
1542
1543
	ida.msg = msg;
1544
	ida.sa = sa;
1545
	ida.proto = proto;
1546
1547
	/* The default IKE lifetime is 8 hours.  */
1548
	if (sa->phase == 1)
1549
		sa->seconds = 28800;
1550
1551
	/* Extract the attributes and stuff them into the SA.  */
1552
	attribute_map(buf + ISAKMP_TRANSFORM_SA_ATTRS_OFF,
1553
	    GET_ISAKMP_GEN_LENGTH(buf) - ISAKMP_TRANSFORM_SA_ATTRS_OFF,
1554
	    ipsec_decode_attribute, &ida);
1555
1556
	/*
1557
	 * If no pseudo-random function was negotiated, it's HMAC.
1558
	 * XXX As PRF_HMAC currently is zero, this is a no-op.
1559
         */
1560
	if (!ie->prf_type)
1561
		ie->prf_type = PRF_HMAC;
1562
}
1563
1564
/*
1565
 * Delete the IPsec SA represented by the INCOMING direction in protocol PROTO
1566
 * of the IKE security association SA.
1567
 */
1568
static void
1569
ipsec_delete_spi(struct sa *sa, struct proto *proto, int incoming)
1570
{
1571
	struct sa *new_sa;
1572
	struct ipsec_proto *iproto;
1573
1574
	if (sa->phase == 1)
1575
		return;
1576
1577
	iproto = proto->data;
1578
	/*
1579
	 * If the SA is using UDP encap and it replaced other SA,
1580
	 * enable the other SA to keep the flow for the other SAs.
1581
	 */
1582
	if ((iproto->encap_mode == IPSEC_ENCAP_UDP_ENCAP_TRANSPORT ||
1583
	    iproto->encap_mode == IPSEC_ENCAP_UDP_ENCAP_TRANSPORT_DRAFT) &&
1584
	    (sa->flags & SA_FLAG_REPLACED) == 0 &&
1585
	    (new_sa = sa_find(ipsec_sa_check_flow_any, sa)) != NULL &&
1586
	    new_sa->flags & SA_FLAG_REPLACED)
1587
		sa_replace(sa, new_sa);
1588
1589
	/*
1590
	 * If the SA was not replaced and was not one acquired through the
1591
	 * kernel (ACQUIRE message), remove the flow associated with it.
1592
	 * We ignore any errors from the disabling of the flow.
1593
	 */
1594
	if (sa->flags & SA_FLAG_READY && !(sa->flags & SA_FLAG_ONDEMAND ||
1595
	    sa->flags & SA_FLAG_REPLACED || acquire_only ||
1596
	    conf_get_str("General", "Acquire-Only")))
1597
		pf_key_v2_disable_sa(sa, incoming);
1598
1599
	/* XXX Error handling?  Is it interesting?  */
1600
	pf_key_v2_delete_spi(sa, proto, incoming);
1601
}
1602
1603
/*
1604
 * Store BUF into the g^x entry of the exchange that message MSG belongs to.
1605
 * PEER is non-zero when the value is our peer's, and zero when it is ours.
1606
 */
1607
static int
1608
ipsec_g_x(struct message *msg, int peer, u_int8_t *buf)
1609
{
1610
	struct exchange *exchange = msg->exchange;
1611
	struct ipsec_exch *ie = exchange->data;
1612
	u_int8_t      **g_x;
1613
	int             initiator = exchange->initiator ^ peer;
1614
	char            header[32];
1615
1616
	g_x = initiator ? &ie->g_xi : &ie->g_xr;
1617
	*g_x = malloc(ie->g_x_len);
1618
	if (!*g_x) {
1619
		log_error("ipsec_g_x: malloc (%lu) failed",
1620
		    (unsigned long)ie->g_x_len);
1621
		return -1;
1622
	}
1623
	memcpy(*g_x, buf, ie->g_x_len);
1624
	snprintf(header, sizeof header, "ipsec_g_x: g^x%c",
1625
	    initiator ? 'i' : 'r');
1626
	LOG_DBG_BUF((LOG_MISC, 80, header, *g_x, ie->g_x_len));
1627
	return 0;
1628
}
1629
1630
/* Generate our DH value.  */
1631
int
1632
ipsec_gen_g_x(struct message *msg)
1633
{
1634
	struct exchange *exchange = msg->exchange;
1635
	struct ipsec_exch *ie = exchange->data;
1636
	u_int8_t       *buf;
1637
1638
	buf = malloc(ISAKMP_KE_SZ + ie->g_x_len);
1639
	if (!buf) {
1640
		log_error("ipsec_gen_g_x: malloc (%lu) failed",
1641
		    ISAKMP_KE_SZ + (unsigned long)ie->g_x_len);
1642
		return -1;
1643
	}
1644
	if (message_add_payload(msg, ISAKMP_PAYLOAD_KEY_EXCH, buf,
1645
	    ISAKMP_KE_SZ + ie->g_x_len, 1)) {
1646
		free(buf);
1647
		return -1;
1648
	}
1649
	if (dh_create_exchange(ie->group, buf + ISAKMP_KE_DATA_OFF)) {
1650
		log_print("ipsec_gen_g_x: dh_create_exchange failed");
1651
		free(buf);
1652
		return -1;
1653
	}
1654
	return ipsec_g_x(msg, 0, buf + ISAKMP_KE_DATA_OFF);
1655
}
1656
1657
/* Save the peer's DH value.  */
1658
int
1659
ipsec_save_g_x(struct message *msg)
1660
{
1661
	struct exchange *exchange = msg->exchange;
1662
	struct ipsec_exch *ie = exchange->data;
1663
	struct payload *kep;
1664
1665
	kep = payload_first(msg, ISAKMP_PAYLOAD_KEY_EXCH);
1666
	kep->flags |= PL_MARK;
1667
	ie->g_x_len = GET_ISAKMP_GEN_LENGTH(kep->p) - ISAKMP_KE_DATA_OFF;
1668
1669
	/* Check that the given length matches the group's expectancy.  */
1670
	if (ie->g_x_len != (size_t) dh_getlen(ie->group)) {
1671
		/* XXX Is this a good notify type?  */
1672
		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 0);
1673
		return -1;
1674
	}
1675
	return ipsec_g_x(msg, 1, kep->p + ISAKMP_KE_DATA_OFF);
1676
}
1677
1678
/*
1679
 * Get a SPI for PROTO and the transport MSG passed over.  Store the
1680
 * size where SZ points.  NB!  A zero return is OK if *SZ is zero.
1681
 */
1682
static u_int8_t *
1683
ipsec_get_spi(size_t *sz, u_int8_t proto, struct message *msg)
1684
{
1685
	struct sockaddr *dst, *src;
1686
	struct transport *transport = msg->transport;
1687
1688
	if (msg->exchange->phase == 1) {
1689
		*sz = 0;
1690
		return 0;
1691
	} else {
1692
		/* We are the destination in the SA we want a SPI for.  */
1693
		transport->vtbl->get_src(transport, &dst);
1694
		/* The peer is the source.  */
1695
		transport->vtbl->get_dst(transport, &src);
1696
		return pf_key_v2_get_spi(sz, proto, src, dst,
1697
		    msg->exchange->seq);
1698
	}
1699
}
1700
1701
/*
1702
 * We have gotten a payload PAYLOAD of type TYPE, which did not get handled
1703
 * by the logic of the exchange MSG takes part in.  Now is the time to deal
1704
 * with such a payload if we know how to, if we don't, return -1, otherwise
1705
 * 0.
1706
 */
1707
int
1708
ipsec_handle_leftover_payload(struct message *msg, u_int8_t type,
1709
    struct payload *payload)
1710
{
1711
	u_int32_t       spisz, nspis;
1712
	struct sockaddr *dst;
1713
	int             reenter = 0;
1714
	u_int8_t       *spis, proto;
1715
	struct sa      *sa;
1716
1717
	switch (type) {
1718
	case ISAKMP_PAYLOAD_DELETE:
1719
		proto = GET_ISAKMP_DELETE_PROTO(payload->p);
1720
		nspis = GET_ISAKMP_DELETE_NSPIS(payload->p);
1721
		spisz = GET_ISAKMP_DELETE_SPI_SZ(payload->p);
1722
1723
		if (nspis == 0) {
1724
			LOG_DBG((LOG_SA, 60, "ipsec_handle_leftover_payload: "
1725
			    "message specified zero SPIs, ignoring"));
1726
			return -1;
1727
		}
1728
		/* verify proper SPI size */
1729
		if ((proto == ISAKMP_PROTO_ISAKMP &&
1730
		    spisz != ISAKMP_HDR_COOKIES_LEN) ||
1731
		    (proto != ISAKMP_PROTO_ISAKMP && spisz != sizeof(u_int32_t))) {
1732
			log_print("ipsec_handle_leftover_payload: invalid SPI "
1733
			    "size %d for proto %d in DELETE payload",
1734
			    spisz, proto);
1735
			return -1;
1736
		}
1737
		spis = calloc(nspis, spisz);
1738
		if (!spis) {
1739
			log_error("ipsec_handle_leftover_payload: malloc "
1740
			    "(%d) failed", nspis * spisz);
1741
			return -1;
1742
		}
1743
		/* extract SPI and get dst address */
1744
		memcpy(spis, payload->p + ISAKMP_DELETE_SPI_OFF, nspis * spisz);
1745
		msg->transport->vtbl->get_dst(msg->transport, &dst);
1746
1747
		ipsec_delete_spi_list(dst, proto, spis, nspis, "DELETE");
1748
1749
		free(spis);
1750
		payload->flags |= PL_MARK;
1751
		return 0;
1752
1753
	case ISAKMP_PAYLOAD_NOTIFY:
1754
		switch (GET_ISAKMP_NOTIFY_MSG_TYPE(payload->p)) {
1755
		case IPSEC_NOTIFY_INITIAL_CONTACT:
1756
			/*
1757
			 * Permit INITIAL-CONTACT if
1758
			 *   - this is not an AGGRESSIVE mode exchange
1759
			 *   - it is protected by an ISAKMP SA
1760
			 *
1761
			 * XXX Instead of the first condition above, we could
1762
			 * XXX permit this only for phase 2. In the last
1763
			 * XXX packet of main-mode, this payload, while
1764
			 * XXX encrypted, is not part of the hash digest.  As
1765
			 * XXX we currently send our own INITIAL-CONTACTs at
1766
			 * XXX this point, this too would need to be changed.
1767
			 */
1768
			if (msg->exchange->type == ISAKMP_EXCH_AGGRESSIVE) {
1769
				log_print("ipsec_handle_leftover_payload: got "
1770
				    "INITIAL-CONTACT in AGGRESSIVE mode");
1771
				return -1;
1772
			}
1773
			if ((msg->exchange->flags & EXCHANGE_FLAG_ENCRYPT)
1774
			    == 0) {
1775
				log_print("ipsec_handle_leftover_payload: got "
1776
				    "INITIAL-CONTACT without ISAKMP SA");
1777
				return -1;
1778
			}
1779
1780
			if ((msg->flags & MSG_AUTHENTICATED) == 0) {
1781
				log_print("ipsec_handle_leftover_payload: "
1782
				    "got unauthenticated INITIAL-CONTACT");
1783
				return -1;
1784
			}
1785
			/*
1786
			 * Find out who is sending this and then delete every
1787
			 * SA that is ready.  Exchanges will timeout
1788
			 * themselves and then the non-ready SAs will
1789
			 * disappear too.
1790
			 */
1791
			msg->transport->vtbl->get_dst(msg->transport, &dst);
1792
			while ((sa = sa_lookup_by_peer(dst, SA_LEN(dst), 0)) != 0) {
1793
				/*
1794
				 * Don't delete the current SA -- we received
1795
				 * the notification over it, so it's obviously
1796
				 * still active. We temporarily need to remove
1797
				 * the SA from the list to avoid an endless
1798
				 * loop, but keep a reference so it won't
1799
				 * disappear meanwhile.
1800
				 */
1801
				if (sa == msg->isakmp_sa) {
1802
					sa_reference(sa);
1803
					sa_remove(sa);
1804
					reenter = 1;
1805
					continue;
1806
				}
1807
				LOG_DBG((LOG_SA, 30,
1808
				    "ipsec_handle_leftover_payload: "
1809
				    "INITIAL-CONTACT made us delete SA %p",
1810
				    sa));
1811
				sa_delete(sa, 0);
1812
			}
1813
1814
			if (reenter) {
1815
				sa_enter(msg->isakmp_sa);
1816
				sa_release(msg->isakmp_sa);
1817
			}
1818
			payload->flags |= PL_MARK;
1819
			return 0;
1820
		}
1821
	}
1822
	return -1;
1823
}
1824
1825
/* Return the encryption keylength in octets of the ESP protocol PROTO.  */
1826
int
1827
ipsec_esp_enckeylength(struct proto *proto)
1828
{
1829
	struct ipsec_proto *iproto = proto->data;
1830
1831
	/* Compute the keylength to use.  */
1832
	switch (proto->id) {
1833
	case IPSEC_ESP_3DES:
1834
		return 24;
1835
	case IPSEC_ESP_CAST:
1836
		if (!iproto->keylen)
1837
			return 16;
1838
		return iproto->keylen / 8;
1839
	case IPSEC_ESP_AES_CTR:
1840
	case IPSEC_ESP_AES_GCM_16:
1841
	case IPSEC_ESP_AES_GMAC:
1842
		if (!iproto->keylen)
1843
			return 20;
1844
		return iproto->keylen / 8 + 4;
1845
	case IPSEC_ESP_AES:
1846
		if (!iproto->keylen)
1847
			return 16;
1848
		/* FALLTHROUGH */
1849
	default:
1850
		return iproto->keylen / 8;
1851
	}
1852
}
1853
1854
/* Return the authentication keylength in octets of the ESP protocol PROTO.  */
1855
int
1856
ipsec_esp_authkeylength(struct proto *proto)
1857
{
1858
	struct ipsec_proto *iproto = proto->data;
1859
1860
	switch (iproto->auth) {
1861
	case IPSEC_AUTH_HMAC_MD5:
1862
		return 16;
1863
	case IPSEC_AUTH_HMAC_SHA:
1864
	case IPSEC_AUTH_HMAC_RIPEMD:
1865
		return 20;
1866
	case IPSEC_AUTH_HMAC_SHA2_256:
1867
		return 32;
1868
	case IPSEC_AUTH_HMAC_SHA2_384:
1869
		return 48;
1870
	case IPSEC_AUTH_HMAC_SHA2_512:
1871
		return 64;
1872
	default:
1873
		return 0;
1874
	}
1875
}
1876
1877
/* Return the authentication keylength in octets of the AH protocol PROTO.  */
1878
int
1879
ipsec_ah_keylength(struct proto *proto)
1880
{
1881
	switch (proto->id) {
1882
		case IPSEC_AH_MD5:
1883
		return 16;
1884
	case IPSEC_AH_SHA:
1885
	case IPSEC_AH_RIPEMD:
1886
		return 20;
1887
	case IPSEC_AH_SHA2_256:
1888
		return 32;
1889
	case IPSEC_AH_SHA2_384:
1890
		return 48;
1891
	case IPSEC_AH_SHA2_512:
1892
		return 64;
1893
	default:
1894
		return -1;
1895
	}
1896
}
1897
1898
/* Return the total keymaterial length of the protocol PROTO.  */
1899
int
1900
ipsec_keymat_length(struct proto *proto)
1901
{
1902
	switch (proto->proto) {
1903
		case IPSEC_PROTO_IPSEC_ESP:
1904
		return ipsec_esp_enckeylength(proto)
1905
		    + ipsec_esp_authkeylength(proto);
1906
	case IPSEC_PROTO_IPSEC_AH:
1907
		return ipsec_ah_keylength(proto);
1908
	default:
1909
		return -1;
1910
	}
1911
}
1912
1913
/* Helper function for ipsec_get_id().  */
1914
static int
1915
ipsec_get_proto_port(char *section, u_int8_t *tproto, u_int16_t *port)
1916
{
1917
	struct protoent	*pe = NULL;
1918
	struct servent	*se;
1919
	char	*pstr;
1920
1921
	pstr = conf_get_str(section, "Protocol");
1922
	if (!pstr) {
1923
		*tproto = 0;
1924
		return 0;
1925
	}
1926
	*tproto = (u_int8_t)atoi(pstr);
1927
	if (!*tproto) {
1928
		pe = getprotobyname(pstr);
1929
		if (pe)
1930
			*tproto = pe->p_proto;
1931
	}
1932
	if (!*tproto) {
1933
		log_print("ipsec_get_proto_port: protocol \"%s\" unknown",
1934
		    pstr);
1935
		return -1;
1936
	}
1937
1938
	pstr = conf_get_str(section, "Port");
1939
	if (!pstr)
1940
		return 0;
1941
	*port = (u_int16_t)atoi(pstr);
1942
	if (!*port) {
1943
		se = getservbyname(pstr,
1944
		    pe ? pe->p_name : (pstr ? pstr : NULL));
1945
		if (se)
1946
			*port = ntohs(se->s_port);
1947
	}
1948
	if (!*port) {
1949
		log_print("ipsec_get_proto_port: port \"%s\" unknown",
1950
		    pstr);
1951
		return -1;
1952
	}
1953
	return 0;
1954
}
1955
1956
/*
1957
 * Out of a named section SECTION in the configuration file find out
1958
 * the network address and mask as well as the ID type.  Put the info
1959
 * in the areas pointed to by ADDR, MASK, TPROTO, PORT, and ID respectively.
1960
 * Return 0 on success and -1 on failure.
1961
 */
1962
int
1963
ipsec_get_id(char *section, int *id, struct sockaddr **addr,
1964
    struct sockaddr **mask, u_int8_t *tproto, u_int16_t *port)
1965
{
1966
	char	*type, *address, *netmask;
1967
	sa_family_t	af = 0;
1968
1969
	type = conf_get_str(section, "ID-type");
1970
	if (!type) {
1971
		log_print("ipsec_get_id: section %s has no \"ID-type\" tag",
1972
		    section);
1973
		return -1;
1974
	}
1975
	*id = constant_value(ipsec_id_cst, type);
1976
	switch (*id) {
1977
	case IPSEC_ID_IPV4_ADDR:
1978
	case IPSEC_ID_IPV4_ADDR_SUBNET:
1979
		af = AF_INET;
1980
		break;
1981
	case IPSEC_ID_IPV6_ADDR:
1982
	case IPSEC_ID_IPV6_ADDR_SUBNET:
1983
		af = AF_INET6;
1984
		break;
1985
	}
1986
	switch (*id) {
1987
	case IPSEC_ID_IPV4_ADDR:
1988
	case IPSEC_ID_IPV6_ADDR: {
1989
		int ret;
1990
1991
		address = conf_get_str(section, "Address");
1992
		if (!address) {
1993
			log_print("ipsec_get_id: section %s has no "
1994
			    "\"Address\" tag", section);
1995
			return -1;
1996
		}
1997
		if (text2sockaddr(address, NULL, addr, af, 0)) {
1998
			log_print("ipsec_get_id: invalid address %s in "
1999
			    "section %s", address, section);
2000
			return -1;
2001
		}
2002
		ret = ipsec_get_proto_port(section, tproto, port);
2003
		if (ret < 0)
2004
			free(*addr);
2005
2006
		return ret;
2007
	}
2008
2009
#ifdef notyet
2010
	case IPSEC_ID_FQDN:
2011
		return -1;
2012
2013
	case IPSEC_ID_USER_FQDN:
2014
		return -1;
2015
#endif
2016
2017
	case IPSEC_ID_IPV4_ADDR_SUBNET:
2018
	case IPSEC_ID_IPV6_ADDR_SUBNET: {
2019
		int ret;
2020
2021
		address = conf_get_str(section, "Network");
2022
		if (!address) {
2023
			log_print("ipsec_get_id: section %s has no "
2024
			    "\"Network\" tag", section);
2025
			return -1;
2026
		}
2027
		if (text2sockaddr(address, NULL, addr, af, 0)) {
2028
			log_print("ipsec_get_id: invalid section %s "
2029
			    "network %s", section, address);
2030
			return -1;
2031
		}
2032
		netmask = conf_get_str(section, "Netmask");
2033
		if (!netmask) {
2034
			log_print("ipsec_get_id: section %s has no "
2035
			    "\"Netmask\" tag", section);
2036
			free(*addr);
2037
			return -1;
2038
		}
2039
		if (text2sockaddr(netmask, NULL, mask, af, 1)) {
2040
			log_print("ipsec_get_id: invalid section %s "
2041
			    "network %s", section, netmask);
2042
			free(*addr);
2043
			return -1;
2044
		}
2045
		ret = ipsec_get_proto_port(section, tproto, port);
2046
		if (ret < 0) {
2047
			free(*mask);
2048
			free(*addr);
2049
		}
2050
		return ret;
2051
	}
2052
2053
#ifdef notyet
2054
	case IPSEC_ID_IPV4_RANGE:
2055
		return -1;
2056
2057
	case IPSEC_ID_IPV6_RANGE:
2058
		return -1;
2059
2060
	case IPSEC_ID_DER_ASN1_DN:
2061
		return -1;
2062
2063
	case IPSEC_ID_DER_ASN1_GN:
2064
		return -1;
2065
2066
	case IPSEC_ID_KEY_ID:
2067
		return -1;
2068
#endif
2069
2070
	default:
2071
		log_print("ipsec_get_id: unknown ID type \"%s\" in "
2072
		    "section %s", type, section);
2073
		return -1;
2074
	}
2075
2076
	return 0;
2077
}
2078
2079
/*
2080
 * XXX I rather want this function to return a status code, and fail if
2081
 * we cannot fit the information in the supplied buffer.
2082
 */
2083
static void
2084
ipsec_decode_id(char *buf, size_t size, u_int8_t *id, size_t id_len,
2085
    int isakmpform)
2086
{
2087
	int             id_type;
2088
	char           *addr = 0, *mask = 0;
2089
	u_int32_t      *idp;
2090
2091
	if (id) {
2092
		if (!isakmpform) {
2093
			/*
2094
			 * Exchanges and SAs dont carry the IDs in ISAKMP
2095
			 * form.
2096
			 */
2097
			id -= ISAKMP_GEN_SZ;
2098
			id_len += ISAKMP_GEN_SZ;
2099
		}
2100
		id_type = GET_ISAKMP_ID_TYPE(id);
2101
		idp = (u_int32_t *) (id + ISAKMP_ID_DATA_OFF);
2102
		switch (id_type) {
2103
		case IPSEC_ID_IPV4_ADDR:
2104
			util_ntoa(&addr, AF_INET, id + ISAKMP_ID_DATA_OFF);
2105
			snprintf(buf, size, "%s", addr);
2106
			break;
2107
2108
		case IPSEC_ID_IPV4_ADDR_SUBNET:
2109
			util_ntoa(&addr, AF_INET, id + ISAKMP_ID_DATA_OFF);
2110
			util_ntoa(&mask, AF_INET, id + ISAKMP_ID_DATA_OFF + 4);
2111
			snprintf(buf, size, "%s/%s", addr, mask);
2112
			break;
2113
2114
		case IPSEC_ID_IPV6_ADDR:
2115
			util_ntoa(&addr, AF_INET6, id + ISAKMP_ID_DATA_OFF);
2116
			snprintf(buf, size, "%s", addr);
2117
			break;
2118
2119
		case IPSEC_ID_IPV6_ADDR_SUBNET:
2120
			util_ntoa(&addr, AF_INET6, id + ISAKMP_ID_DATA_OFF);
2121
			util_ntoa(&mask, AF_INET6, id + ISAKMP_ID_DATA_OFF +
2122
			    sizeof(struct in6_addr));
2123
			snprintf(buf, size, "%s/%s", addr, mask);
2124
			break;
2125
2126
		case IPSEC_ID_FQDN:
2127
		case IPSEC_ID_USER_FQDN:
2128
			/* String is not NUL terminated, be careful */
2129
			id_len -= ISAKMP_ID_DATA_OFF;
2130
			id_len = MINIMUM(id_len, size - 1);
2131
			memcpy(buf, id + ISAKMP_ID_DATA_OFF, id_len);
2132
			buf[id_len] = '\0';
2133
			break;
2134
2135
		case IPSEC_ID_DER_ASN1_DN:
2136
			addr = x509_DN_string(id + ISAKMP_ID_DATA_OFF,
2137
			    id_len - ISAKMP_ID_DATA_OFF);
2138
			if (!addr) {
2139
				snprintf(buf, size, "unparsable ASN1 DN ID");
2140
				return;
2141
			}
2142
			strlcpy(buf, addr, size);
2143
			break;
2144
2145
		default:
2146
			snprintf(buf, size, "<id type unknown: %x>", id_type);
2147
			break;
2148
		}
2149
	} else
2150
		snprintf(buf, size, "<no ipsec id>");
2151
	free(addr);
2152
	free(mask);
2153
}
2154
2155
char *
2156
ipsec_decode_ids(char *fmt, u_int8_t *id1, size_t id1_len, u_int8_t *id2,
2157
    size_t id2_len, int isakmpform)
2158
{
2159
	static char     result[1024];
2160
	char            s_id1[256], s_id2[256];
2161
2162
	ipsec_decode_id(s_id1, sizeof s_id1, id1, id1_len, isakmpform);
2163
	ipsec_decode_id(s_id2, sizeof s_id2, id2, id2_len, isakmpform);
2164
2165
	snprintf(result, sizeof result, fmt, s_id1, s_id2);
2166
	return result;
2167
}
2168
2169
/*
2170
 * Out of a named section SECTION in the configuration file build an
2171
 * ISAKMP ID payload.  Ths payload size should be stashed in SZ.
2172
 * The caller is responsible for freeing the payload.
2173
 */
2174
u_int8_t *
2175
ipsec_build_id(char *section, size_t *sz)
2176
{
2177
	struct sockaddr *addr, *mask;
2178
	u_int8_t       *p;
2179
	int             id, subnet = 0;
2180
	u_int8_t        tproto = 0;
2181
	u_int16_t       port = 0;
2182
2183
	if (ipsec_get_id(section, &id, &addr, &mask, &tproto, &port))
2184
		return 0;
2185
2186
	if (id == IPSEC_ID_IPV4_ADDR_SUBNET || id == IPSEC_ID_IPV6_ADDR_SUBNET)
2187
		subnet = 1;
2188
2189
	*sz = ISAKMP_ID_SZ + sockaddr_addrlen(addr);
2190
	if (subnet)
2191
		*sz += sockaddr_addrlen(mask);
2192
2193
	p = malloc(*sz);
2194
	if (!p) {
2195
		log_print("ipsec_build_id: malloc(%lu) failed",
2196
		    (unsigned long)*sz);
2197
		if (subnet)
2198
			free(mask);
2199
		free(addr);
2200
		return 0;
2201
	}
2202
	SET_ISAKMP_ID_TYPE(p, id);
2203
	SET_ISAKMP_ID_DOI_DATA(p, (unsigned char *)"\000\000\000");
2204
2205
	memcpy(p + ISAKMP_ID_DATA_OFF, sockaddr_addrdata(addr),
2206
	    sockaddr_addrlen(addr));
2207
	if (subnet)
2208
		memcpy(p + ISAKMP_ID_DATA_OFF + sockaddr_addrlen(addr),
2209
		    sockaddr_addrdata(mask), sockaddr_addrlen(mask));
2210
2211
	SET_IPSEC_ID_PROTO(p + ISAKMP_ID_DOI_DATA_OFF, tproto);
2212
	SET_IPSEC_ID_PORT(p + ISAKMP_ID_DOI_DATA_OFF, port);
2213
2214
	if (subnet)
2215
		free(mask);
2216
	free(addr);
2217
	return p;
2218
}
2219
2220
/*
2221
 * copy an ISAKMPD id
2222
 */
2223
int
2224
ipsec_clone_id(u_int8_t **did, size_t *did_len, u_int8_t *id, size_t id_len)
2225
{
2226
	free(*did);
2227
2228
	if (!id_len || !id) {
2229
		*did = 0;
2230
		*did_len = 0;
2231
		return 0;
2232
	}
2233
	*did = malloc(id_len);
2234
	if (!*did) {
2235
		*did_len = 0;
2236
		log_error("ipsec_clone_id: malloc(%lu) failed",
2237
		    (unsigned long)id_len);
2238
		return -1;
2239
	}
2240
	*did_len = id_len;
2241
	memcpy(*did, id, id_len);
2242
2243
	return 0;
2244
}
2245
2246
/*
2247
 * IPsec-specific PROTO initializations.  SECTION is only set if we are the
2248
 * initiator thus only usable there.
2249
 * XXX I want to fix this later.
2250
 */
2251
void
2252
ipsec_proto_init(struct proto *proto, char *section)
2253
{
2254
	struct ipsec_proto *iproto = proto->data;
2255
2256
	if (proto->sa->phase == 2)
2257
		iproto->replay_window = section ? conf_get_num(section,
2258
		    "ReplayWindow", DEFAULT_REPLAY_WINDOW) :
2259
		    DEFAULT_REPLAY_WINDOW;
2260
}
2261
2262
/*
2263
 * Add a notification payload of type INITIAL CONTACT to MSG if this is
2264
 * the first contact we have made to our peer.
2265
 */
2266
int
2267
ipsec_initial_contact(struct message *msg)
2268
{
2269
	u_int8_t *buf;
2270
2271
	if (ipsec_contacted(msg))
2272
		return 0;
2273
2274
	buf = malloc(ISAKMP_NOTIFY_SZ + ISAKMP_HDR_COOKIES_LEN);
2275
	if (!buf) {
2276
		log_error("ike_phase_1_initial_contact: malloc (%d) failed",
2277
		    ISAKMP_NOTIFY_SZ + ISAKMP_HDR_COOKIES_LEN);
2278
		return -1;
2279
	}
2280
	SET_ISAKMP_NOTIFY_DOI(buf, IPSEC_DOI_IPSEC);
2281
	SET_ISAKMP_NOTIFY_PROTO(buf, ISAKMP_PROTO_ISAKMP);
2282
	SET_ISAKMP_NOTIFY_SPI_SZ(buf, ISAKMP_HDR_COOKIES_LEN);
2283
	SET_ISAKMP_NOTIFY_MSG_TYPE(buf, IPSEC_NOTIFY_INITIAL_CONTACT);
2284
	memcpy(buf + ISAKMP_NOTIFY_SPI_OFF, msg->isakmp_sa->cookies,
2285
	    ISAKMP_HDR_COOKIES_LEN);
2286
	if (message_add_payload(msg, ISAKMP_PAYLOAD_NOTIFY, buf,
2287
	    ISAKMP_NOTIFY_SZ + ISAKMP_HDR_COOKIES_LEN, 1)) {
2288
		free(buf);
2289
		return -1;
2290
	}
2291
	return ipsec_add_contact(msg);
2292
}
2293
2294
/*
2295
 * Compare the two contacts pointed to by A and B.  Return negative if
2296
 * *A < *B, 0 if they are equal, and positive if *A is the largest of them.
2297
 */
2298
static int
2299
addr_cmp(const void *a, const void *b)
2300
{
2301
	const struct contact *x = a, *y = b;
2302
	int             minlen = MINIMUM(x->len, y->len);
2303
	int             rv = memcmp(x->addr, y->addr, minlen);
2304
2305
	return rv ? rv : (x->len - y->len);
2306
}
2307
2308
/*
2309
 * Add the peer that MSG is bound to as an address we don't want to send
2310
 * INITIAL CONTACT too from now on.  Do not call this function with a
2311
 * specific address duplicate times. We want fast lookup, speed of insertion
2312
 * is unimportant, if this is to scale.
2313
 */
2314
static int
2315
ipsec_add_contact(struct message *msg)
2316
{
2317
	struct contact *new_contacts;
2318
	struct sockaddr *dst, *addr;
2319
	int             cnt;
2320
2321
	if (contact_cnt == contact_limit) {
2322
		cnt = contact_limit ? 2 * contact_limit : 64;
2323
		new_contacts = reallocarray(contacts, cnt, sizeof contacts[0]);
2324
		if (!new_contacts) {
2325
			log_error("ipsec_add_contact: "
2326
			    "realloc (%p, %lu) failed", contacts,
2327
			    cnt * (unsigned long) sizeof contacts[0]);
2328
			return -1;
2329
		}
2330
		contact_limit = cnt;
2331
		contacts = new_contacts;
2332
	}
2333
	msg->transport->vtbl->get_dst(msg->transport, &dst);
2334
	addr = malloc(SA_LEN(dst));
2335
	if (!addr) {
2336
		log_error("ipsec_add_contact: malloc (%lu) failed",
2337
		    (unsigned long)SA_LEN(dst));
2338
		return -1;
2339
	}
2340
	memcpy(addr, dst, SA_LEN(dst));
2341
	contacts[contact_cnt].addr = addr;
2342
	contacts[contact_cnt++].len = SA_LEN(dst);
2343
2344
	/*
2345
	 * XXX There are better algorithms for already mostly-sorted data like
2346
	 * this, but only qsort is standard.  I will someday do this inline.
2347
         */
2348
	qsort(contacts, contact_cnt, sizeof *contacts, addr_cmp);
2349
	return 0;
2350
}
2351
2352
/* Return true if the recipient of MSG has already been contacted.  */
2353
static int
2354
ipsec_contacted(struct message *msg)
2355
{
2356
	struct contact  contact;
2357
2358
	msg->transport->vtbl->get_dst(msg->transport, &contact.addr);
2359
	contact.len = SA_LEN(contact.addr);
2360
	return contacts ? (bsearch(&contact, contacts, contact_cnt,
2361
	    sizeof *contacts, addr_cmp) != 0) : 0;
2362
}
2363
2364
/* Add a HASH for to MSG.  */
2365
u_int8_t *
2366
ipsec_add_hash_payload(struct message *msg, size_t hashsize)
2367
{
2368
	u_int8_t *buf;
2369
2370
	buf = malloc(ISAKMP_HASH_SZ + hashsize);
2371
	if (!buf) {
2372
		log_error("ipsec_add_hash_payload: malloc (%lu) failed",
2373
		    ISAKMP_HASH_SZ + (unsigned long) hashsize);
2374
		return 0;
2375
	}
2376
	if (message_add_payload(msg, ISAKMP_PAYLOAD_HASH, buf,
2377
	    ISAKMP_HASH_SZ + hashsize, 1)) {
2378
		free(buf);
2379
		return 0;
2380
	}
2381
	return buf;
2382
}
2383
2384
/* Fill in the HASH payload of MSG.  */
2385
int
2386
ipsec_fill_in_hash(struct message *msg)
2387
{
2388
	struct exchange *exchange = msg->exchange;
2389
	struct sa      *isakmp_sa = msg->isakmp_sa;
2390
	struct ipsec_sa *isa = isakmp_sa->data;
2391
	struct hash    *hash = hash_get(isa->hash);
2392
	struct prf     *prf;
2393
	struct payload *payload;
2394
	u_int8_t       *buf;
2395
	u_int32_t       i;
2396
	char            header[80];
2397
2398
	/* If no SKEYID_a, we need not do anything.  */
2399
	if (!isa->skeyid_a)
2400
		return 0;
2401
2402
	payload = payload_first(msg, ISAKMP_PAYLOAD_HASH);
2403
	if (!payload) {
2404
		log_print("ipsec_fill_in_hash: no HASH payload found");
2405
		return -1;
2406
	}
2407
	buf = payload->p;
2408
2409
	/* Allocate the prf and start calculating our HASH(1).  */
2410
	LOG_DBG_BUF((LOG_MISC, 90, "ipsec_fill_in_hash: SKEYID_a",
2411
	    isa->skeyid_a, isa->skeyid_len));
2412
	prf = prf_alloc(isa->prf_type, hash->type, isa->skeyid_a,
2413
	    isa->skeyid_len);
2414
	if (!prf)
2415
		return -1;
2416
2417
	prf->Init(prf->prfctx);
2418
	LOG_DBG_BUF((LOG_MISC, 90, "ipsec_fill_in_hash: message_id",
2419
	    exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
2420
	prf->Update(prf->prfctx, exchange->message_id,
2421
	    ISAKMP_HDR_MESSAGE_ID_LEN);
2422
2423
	/* Loop over all payloads after HASH(1).  */
2424
	for (i = 2; i < msg->iovlen; i++) {
2425
		/* XXX Misleading payload type printouts.  */
2426
		snprintf(header, sizeof header,
2427
		    "ipsec_fill_in_hash: payload %d after HASH(1)", i - 1);
2428
		LOG_DBG_BUF((LOG_MISC, 90, header, msg->iov[i].iov_base,
2429
		    msg->iov[i].iov_len));
2430
		prf->Update(prf->prfctx, msg->iov[i].iov_base,
2431
		    msg->iov[i].iov_len);
2432
	}
2433
	prf->Final(buf + ISAKMP_HASH_DATA_OFF, prf->prfctx);
2434
	prf_free(prf);
2435
	LOG_DBG_BUF((LOG_MISC, 80, "ipsec_fill_in_hash: HASH(1)", buf +
2436
	    ISAKMP_HASH_DATA_OFF, hash->hashsize));
2437
2438
	return 0;
2439
}
2440
2441
/* Add a HASH payload to MSG, if we have an ISAKMP SA we're protected by.  */
2442
static int
2443
ipsec_informational_pre_hook(struct message *msg)
2444
{
2445
	struct sa      *isakmp_sa = msg->isakmp_sa;
2446
	struct ipsec_sa *isa;
2447
	struct hash    *hash;
2448
2449
	if (!isakmp_sa)
2450
		return 0;
2451
	isa = isakmp_sa->data;
2452
	hash = hash_get(isa->hash);
2453
	return ipsec_add_hash_payload(msg, hash->hashsize) == 0;
2454
}
2455
2456
/*
2457
 * Fill in the HASH payload in MSG, if we have an ISAKMP SA we're protected by.
2458
 */
2459
static int
2460
ipsec_informational_post_hook(struct message *msg)
2461
{
2462
	if (!msg->isakmp_sa)
2463
		return 0;
2464
	return ipsec_fill_in_hash(msg);
2465
}
2466
2467
ssize_t
2468
ipsec_id_size(char *section, u_int8_t *id)
2469
{
2470
	char *type, *data;
2471
2472
	type = conf_get_str(section, "ID-type");
2473
	if (!type) {
2474
		log_print("ipsec_id_size: section %s has no \"ID-type\" tag",
2475
		    section);
2476
		return -1;
2477
	}
2478
	*id = constant_value(ipsec_id_cst, type);
2479
	switch (*id) {
2480
	case IPSEC_ID_IPV4_ADDR:
2481
		return sizeof(struct in_addr);
2482
	case IPSEC_ID_IPV4_ADDR_SUBNET:
2483
		return 2 * sizeof(struct in_addr);
2484
	case IPSEC_ID_IPV6_ADDR:
2485
		return sizeof(struct in6_addr);
2486
	case IPSEC_ID_IPV6_ADDR_SUBNET:
2487
		return 2 * sizeof(struct in6_addr);
2488
	case IPSEC_ID_FQDN:
2489
	case IPSEC_ID_USER_FQDN:
2490
	case IPSEC_ID_KEY_ID:
2491
	case IPSEC_ID_DER_ASN1_DN:
2492
	case IPSEC_ID_DER_ASN1_GN:
2493
		data = conf_get_str(section, "Name");
2494
		if (!data) {
2495
			log_print("ipsec_id_size: "
2496
			    "section %s has no \"Name\" tag", section);
2497
			return -1;
2498
		}
2499
		return strlen(data);
2500
	}
2501
	log_print("ipsec_id_size: unrecognized/unsupported ID-type %d (%s)",
2502
	    *id, type);
2503
	return -1;
2504
}
2505
2506
/*
2507
 * Generate a string version of the ID.
2508
 */
2509
char *
2510
ipsec_id_string(u_int8_t *id, size_t id_len)
2511
{
2512
	char           *buf = 0;
2513
	char           *addrstr = 0;
2514
	size_t          len, size;
2515
2516
	/*
2517
	 * XXX Real ugly way of making the offsets correct.  Be aware that id
2518
	 * now will point before the actual buffer and cannot be dereferenced
2519
	 * without an offset larger than or equal to ISAKM_GEN_SZ.
2520
         */
2521
	id -= ISAKMP_GEN_SZ;
2522
2523
	/* This is the actual length of the ID data field.  */
2524
	id_len += ISAKMP_GEN_SZ - ISAKMP_ID_DATA_OFF;
2525
2526
	/*
2527
	 * Conservative allocation.
2528
	 * XXX I think the ASN1 DN case can be thought through to give a better
2529
	 * estimate.
2530
         */
2531
	size = MAXIMUM(sizeof "ipv6/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
2532
	    sizeof "asn1_dn/" + id_len);
2533
	buf = malloc(size);
2534
	if (!buf)
2535
		/* XXX Log?  */
2536
		goto fail;
2537
2538
	switch (GET_ISAKMP_ID_TYPE(id)) {
2539
	case IPSEC_ID_IPV4_ADDR:
2540
		if (id_len < sizeof(struct in_addr))
2541
			goto fail;
2542
		util_ntoa(&addrstr, AF_INET, id + ISAKMP_ID_DATA_OFF);
2543
		if (!addrstr)
2544
			goto fail;
2545
		snprintf(buf, size, "ipv4/%s", addrstr);
2546
		break;
2547
2548
	case IPSEC_ID_IPV6_ADDR:
2549
		if (id_len < sizeof(struct in6_addr))
2550
			goto fail;
2551
		util_ntoa(&addrstr, AF_INET6, id + ISAKMP_ID_DATA_OFF);
2552
		if (!addrstr)
2553
			goto fail;
2554
		snprintf(buf, size, "ipv6/%s", addrstr);
2555
		break;
2556
2557
	case IPSEC_ID_FQDN:
2558
	case IPSEC_ID_USER_FQDN:
2559
		strlcpy(buf, GET_ISAKMP_ID_TYPE(id) == IPSEC_ID_FQDN ?
2560
		    "fqdn/" : "ufqdn/", size);
2561
		len = strlen(buf);
2562
2563
		memcpy(buf + len, id + ISAKMP_ID_DATA_OFF, id_len);
2564
		*(buf + len + id_len) = '\0';
2565
		break;
2566
2567
	case IPSEC_ID_DER_ASN1_DN:
2568
		strlcpy(buf, "asn1_dn/", size);
2569
		len = strlen(buf);
2570
		addrstr = x509_DN_string(id + ISAKMP_ID_DATA_OFF, id_len);
2571
		if (!addrstr)
2572
			goto fail;
2573
		if (size < len + strlen(addrstr) + 1)
2574
			goto fail;
2575
		strlcpy(buf + len, addrstr, size - len);
2576
		break;
2577
2578
	default:
2579
		/* Unknown type.  */
2580
		LOG_DBG((LOG_MISC, 10,
2581
		    "ipsec_id_string: unknown identity type %d\n",
2582
		    GET_ISAKMP_ID_TYPE(id)));
2583
		goto fail;
2584
	}
2585
2586
	free(addrstr);
2587
	return buf;
2588
2589
fail:
2590
	free(buf);
2591
	free(addrstr);
2592
	return 0;
2593
}