Project

General

Profile

Download (107 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * ipsec.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2008 Shrew Soft Inc.
7
 * Copyright (c) 2007-2013 BSD Perimeter
8
 * Copyright (c) 2013-2016 Electric Sheep Fencing
9
 * Copyright (c) 2014-2021 Rubicon Communications, LLC (Netgate)
10
 * All rights reserved.
11
 *
12
 * Licensed under the Apache License, Version 2.0 (the "License");
13
 * you may not use this file except in compliance with the License.
14
 * You may obtain a copy of the License at
15
 *
16
 * http://www.apache.org/licenses/LICENSE-2.0
17
 *
18
 * Unless required by applicable law or agreed to in writing, software
19
 * distributed under the License is distributed on an "AS IS" BASIS,
20
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
 * See the License for the specific language governing permissions and
22
 * limitations under the License.
23
 */
24

    
25
require_once("filter.inc");
26
require_once("auth.inc");
27
require_once("certs.inc");
28
require_once("interfaces.inc");
29

    
30
/* IPsec defines */
31

    
32
global $ipsec_conid_prefix;
33
$ipsec_conid_prefix = 'con';
34

    
35
global $ipsec_conid_separator;
36
$ipsec_conid_separator = '_';
37

    
38
/* Leave plenty of room for dynamically allocated reqids */
39
global $ipsec_reqid_base;
40
$ipsec_reqid_base = 5000;
41

    
42
global $ipsec_loglevels;
43
$ipsec_loglevels = array(
44
	"dmn" => gettext("Daemon"),
45
	"mgr" => gettext("SA Manager"),
46
	"ike" => gettext("IKE SA"),
47
	"chd" => gettext("IKE Child SA"),
48
	"job" => gettext("Job Processing"),
49
	"cfg" => gettext("Configuration backend"),
50
	"knl" => gettext("Kernel Interface"),
51
	"net" => gettext("Networking"),
52
	"asn" => gettext("ASN encoding"),
53
	"enc" => gettext("Message encoding"),
54
	"imc" => gettext("Integrity checker"),
55
	"imv" => gettext("Integrity Verifier"),
56
	"pts" => gettext("Platform Trust Service"),
57
	"tls" => gettext("TLS handler"),
58
	"esp" => gettext("IPsec traffic"),
59
	"lib" => gettext("StrongSwan Lib")
60
);
61

    
62
global $ipsec_log_sevs;
63
$ipsec_log_sevs = array(
64
	'-1' => gettext('Silent'),
65
	'0' => gettext('Audit'),
66
	'1' => gettext('Control'),
67
	'2' => gettext('Diag'),
68
	'3' => gettext('Raw'),
69
	'4' => gettext('Highest')
70
);
71

    
72
global $ipsec_log_cats;
73
$ipsec_log_cats = array(
74
	"dmn" => gettext("Daemon"),
75
	"mgr" => gettext("SA Manager"),
76
	"ike" => gettext("IKE SA"),
77
	"chd" => gettext("IKE Child SA"),
78
	"job" => gettext("Job Processing"),
79
	"cfg" => gettext("Configuration backend"),
80
	"knl" => gettext("Kernel Interface"),
81
	"net" => gettext("Networking"),
82
	"asn" => gettext("ASN encoding"),
83
	"enc" => gettext("Message encoding"),
84
	"imc" => gettext("Integrity checker"),
85
	"imv" => gettext("Integrity Verifier"),
86
	"pts" => gettext("Platform Trust Service"),
87
	"tls" => gettext("TLS handler"),
88
	"esp" => gettext("IPsec traffic"),
89
	"lib" => gettext("StrongSwan Lib")
90
);
91

    
92
/* For PSK tab, different order based on likely user preference */
93
global $ipsec_identifier_list;
94
$ipsec_identifier_list = array(
95
	'none' => array('desc' => 'Automatic based on content', 'mobile' => true),
96
	'email' => array('desc' => gettext('E-mail address'), 'mobile' => true),
97
	'fqdn' => array('desc' => gettext('Fully qualified domain name'), 'mobile' => true),
98
	'userfqdn' => array('desc' => gettext('User fully qualified domain name'), 'mobile' => true),
99
	'keyid' => array('desc' => gettext('KeyID tag'), 'mobile' => true),
100
	'asn1dn' => array('desc' => gettext('ASN.1 distinguished Name'), 'mobile' => true),
101
);
102

    
103
global $my_identifier_list;
104
$my_identifier_list = array(
105
	'myaddress' => array('desc' => gettext('My IP address'), 'mobile' => true),
106
	'address' => array('desc' => gettext('IP address'), 'mobile' => true),
107
	'fqdn' => array('desc' => gettext('Fully qualified domain name'), 'mobile' => true),
108
	'user_fqdn' => array('desc' => gettext('User fully qualified domain name / E-mail'), 'mobile' => true),
109
	'asn1dn' => array('desc' => gettext('ASN.1 distinguished Name'), 'mobile' => true),
110
	'keyid tag' => array('desc' => gettext('KeyID tag'), 'mobile' => true),
111
	'dyn_dns' => array('desc' => gettext('Dynamic DNS'), 'mobile' => true),
112
	'auto' => array('desc' => gettext('Automatic based on content'), 'mobile' => true),
113
);
114

    
115
global $peer_identifier_list;
116
$peer_identifier_list = array(
117
	'any' => array('desc' => gettext('Any'), 'mobile' => true),
118
	'peeraddress' => array('desc' => gettext('Peer IP address'), 'mobile' => false),
119
	'address' => array('desc' => gettext('IP address'), 'mobile' => false),
120
	'fqdn' => array('desc' => gettext('Fully qualified domain name'), 'mobile' => true),
121
	'user_fqdn' => array('desc' => gettext('User fully qualified domain name / E-mail'), 'mobile' => true),
122
	'asn1dn' => array('desc' => gettext('ASN.1 distinguished Name'), 'mobile' => true),
123
	'keyid tag' => array('desc' =>gettext('KeyID tag'), 'mobile' => true),
124
	'auto' => array('desc' => gettext('Automatic based on content'), 'mobile' => true),
125
);
126

    
127
global $ipsec_idhandling;
128
$ipsec_idhandling = array(
129
	'replace' => 'Yes (Replace)', 'no' => 'No', 'never' => 'Never', 'keep' => 'Keep'
130
);
131

    
132
global $p1_ealgos;
133
$p1_ealgos = array(
134
	'aes' => array('name' => 'AES', 'keysel' => array('lo' => 128, 'hi' => 256, 'step' => 64)),
135
	'aes128gcm' => array('name' => 'AES128-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
136
	'aes192gcm' => array('name' => 'AES192-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
137
	'aes256gcm' => array('name' => 'AES256-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
138
	'blowfish' => array('name' => 'Blowfish', 'keysel' => array('lo' => 128, 'hi' => 256, 'step' => 64)),
139
	'3des' => array('name' => '3DES'),
140
	'cast128' => array('name' => 'CAST128')
141
);
142

    
143
global $p2_ealgos;
144
$p2_ealgos = array(
145
	'aes' => array('name' => 'AES', 'keysel' => array('lo' => 128, 'hi' => 256, 'step' => 64)),
146
	'aes128gcm' => array('name' => 'AES128-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
147
	'aes192gcm' => array('name' => 'AES192-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
148
	'aes256gcm' => array('name' => 'AES256-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
149
	'blowfish' => array('name' => 'Blowfish', 'keysel' => array('lo' => 128, 'hi' => 256, 'step' => 64)),
150
	'3des' => array('name' => '3DES'),
151
	'cast128' => array('name' => 'CAST128')
152
);
153

    
154
global $p1_halgos;
155
$p1_halgos = array(
156
	'md5' => 'MD5',
157
	'sha1' => 'SHA1',
158
	'sha256' => 'SHA256',
159
	'sha384' => 'SHA384',
160
	'sha512' => 'SHA512',
161
	'aesxcbc' => 'AES-XCBC'
162
);
163

    
164
global $p1_dhgroups;
165
$p1_dhgroups = array(
166
	1  => '1 (768 bit)',
167
	2  => '2 (1024 bit)',
168
	5  => '5 (1536 bit)',
169
	14 => '14 (2048 bit)',
170
	15 => '15 (3072 bit)',
171
	16 => '16 (4096 bit)',
172
	17 => '17 (6144 bit)',
173
	18 => '18 (8192 bit)',
174
	19 => '19 (nist ecp256)',
175
	20 => '20 (nist ecp384)',
176
	21 => '21 (nist ecp521)',
177
	22 => '22 (1024(sub 160) bit)',
178
	23 => '23 (2048(sub 224) bit)',
179
	24 => '24 (2048(sub 256) bit)',
180
	25 => '25 (nist ecp192)',
181
	26 => '26 (nist ecp224)',
182
	27 => '27 (brainpool ecp224)',
183
	28 => '28 (brainpool ecp256)',
184
	29 => '29 (brainpool ecp384)',
185
	30 => '30 (brainpool ecp512)',
186
	31 => '31 (Elliptic Curve 25519, 256 bit)',
187
	32 => '32 (Elliptic Curve 448, 448 bit)',
188
);
189

    
190
global $p2_halgos;
191
$p2_halgos = array(
192
	'hmac_md5' => 'MD5',
193
	'hmac_sha1' => 'SHA1',
194
	'hmac_sha256' => 'SHA256',
195
	'hmac_sha384' => 'SHA384',
196
	'hmac_sha512' => 'SHA512',
197
	'aesxcbc' => 'AES-XCBC'
198
);
199

    
200
global $p1_authentication_methods;
201
$p1_authentication_methods = array(
202
	'hybrid_cert_server' => array('name' => gettext('Hybrid Certificate + Xauth'), 'mobile' => true),
203
	'xauth_cert_server' => array('name' => gettext('Mutual Certificate + Xauth'), 'mobile' => true),
204
	'xauth_psk_server' => array('name' => gettext('Mutual PSK + Xauth'), 'mobile' => true),
205
	'eap-tls' => array('name' => gettext('EAP-TLS'), 'mobile' => true),
206
	'eap-radius' => array('name' => gettext('EAP-RADIUS'), 'mobile' => true),
207
	'eap-mschapv2' => array('name' => gettext('EAP-MSChapv2'), 'mobile' => true),
208
	'cert' => array('name' => gettext('Mutual Certificate'), 'mobile' => false),
209
	'pkcs11' => array('name' => gettext('Mutual Certificate (PKCS#11)'), 'mobile' => false),
210
	'pre_shared_key' => array('name' => gettext('Mutual PSK'), 'mobile' => false)
211
);
212

    
213
global $ipsec_preshared_key_type;
214
$ipsec_preshared_key_type = array(
215
	'PSK' => 'PSK',
216
	'EAP' => 'EAP'
217
);
218

    
219
global $ipsec_startactions;
220
$ipsec_startactions = array(
221
	'' => gettext('Default'),
222
	'none' => gettext('None (Responder Only)'),
223
	'start' => gettext('Initiate at start (VTI or Tunnel Mode)'),
224
	'trap' => gettext('Initiate on demand (Tunnel mode only)'),
225
);
226

    
227
global $ipsec_closeactions;
228
$ipsec_closeactions = array(
229
	'' => gettext('Default'),
230
	'none' => gettext('Close connection and clear SA'),
231
	'start' => gettext('Restart/Reconnect'),
232
	'trap' => gettext('Close connection and reconnect on demand'),
233
);
234

    
235
global $p2_modes;
236
$p2_modes = array(
237
	'tunnel' => gettext('Tunnel IPv4'),
238
	'tunnel6' => gettext('Tunnel IPv6'),
239
	'transport' => gettext('Transport'),
240
	'vti' => gettext('Routed (VTI)')
241
);
242

    
243
global $p2_protos;
244
$p2_protos = array(
245
	'esp' => 'ESP',
246
	'ah' => 'AH'
247
);
248

    
249
global $p2_pfskeygroups;
250
$p2_pfskeygroups = array(
251
	0 => gettext('off'),
252
	1  => gettext('1 (768 bit)'),
253
	2  => gettext('2 (1024 bit)'),
254
	5  => gettext('5 (1536 bit)'),
255
	14 => gettext('14 (2048 bit)'),
256
	15 => gettext('15 (3072 bit)'),
257
	16 => gettext('16 (4096 bit)'),
258
	17 => gettext('17 (6144 bit)'),
259
	18 => gettext('18 (8192 bit)'),
260
	19 => gettext('19 (nist ecp256)'),
261
	20 => gettext('20 (nist ecp384)'),
262
	21 => gettext('21 (nist ecp521)'),
263
	22 => gettext('22 (1024(sub 160) bit)'),
264
	23 => gettext('23 (2048(sub 224) bit)'),
265
	24 => gettext('24 (2048(sub 256) bit)'),
266
	25 => gettext('25 (nist ecp192)'),
267
	26 => gettext('26 (nist ecp224)'),
268
	27 => gettext('27 (brainpool ecp224)'),
269
	28 => gettext('28 (brainpool ecp256)'),
270
	29 => gettext('29 (brainpool ecp384)'),
271
	30 => gettext('30 (brainpool ecp512)'),
272
	31 => gettext('31 (Elliptic Curve 25519, 256 bit)'),
273
	32 => gettext('32 (Elliptic Curve 448, 448 bit)')
274
);
275

    
276
function ipsec_enabled() {
277
	global $config;
278

    
279
	if (!isset($config['ipsec']) || !is_array($config['ipsec'])) {
280
		return false;
281
	}
282

    
283
	/* Check if we have at least one phase 1 entry. */
284
	if (!isset($config['ipsec']['phase1']) ||
285
	    !is_array($config['ipsec']['phase1']) ||
286
	    empty($config['ipsec']['phase1'])) {
287
		return false;
288
	}
289
	/* Check if at least one phase 1 entry is enabled. */
290
	foreach ($config['ipsec']['phase1'] as $phase1) {
291
		if (!isset($phase1['disabled'])) {
292
			return true;
293
		}
294
	}
295

    
296
	return false;
297
}
298

    
299
/*
300
 * ikeid management functions
301
 */
302

    
303
function ipsec_ikeid_used($ikeid) {
304
	global $config;
305
	init_config_arr(array('ipsec', 'phase1'));
306
	foreach ($config['ipsec']['phase1'] as $ph1ent) {
307
		if ($ikeid == $ph1ent['ikeid']) {
308
			return true;
309
		}
310
	}
311
	return false;
312
}
313

    
314
function ipsec_ikeid_next() {
315
	global $config;
316
	$ikeid = 1;
317
	init_config_arr(array('ipsec', 'phase1'));
318
	$ipsecikeid = lock('ipsecikeids', LOCK_EX);
319
	$ikeids = array();
320

    
321
	foreach ($config['ipsec']['phase1'] as $ph1) {
322
		$keyids[$ph1['ikeid']] = $ph1['ikeid'];
323
	}
324

    
325
	for ($i = 1; $i < 16000; $i++) {
326
		if (!isset($keyids[$i])) {
327
			$keyid = $i;
328
			break;
329
		}
330
	}
331

    
332
	unlock($ipsecreqid);
333
	return $keyid;
334
}
335

    
336
function ipsec_new_reqid() {
337
	global $config;
338
	init_config_arr(array('ipsec', 'phase2'));
339
	$ipsecreqid = lock('ipsecreqids', LOCK_EX);
340
	$keyids = array();
341
	$keyid = 1;
342

    
343
	foreach ($config['ipsec']['phase2'] as $ph2) {
344
		$keyids[$ph2['reqid']] = $ph2['reqid'];
345
	}
346

    
347
	for ($i = 1; $i < 16000; $i++) {
348
		if (!isset($keyids[$i])) {
349
			$keyid = $i;
350
			break;
351
		}
352
	}
353

    
354
	unlock($ipsecreqid);
355
	return $keyid;
356
}
357

    
358
function ipsec_get_phase1($ikeid) {
359
	global $config;
360
	init_config_arr(array('ipsec', 'phase1'));
361

    
362
	foreach ($config['ipsec']['phase1'] as $p1) {
363
		if ($p1['ikeid'] == $ikeid) {
364
			return $p1;
365
		}
366
	}
367
}
368

    
369
function ipsec_get_p1_descr($ikeid) {
370
	global $config;
371
	init_config_arr(array('ipsec', 'phase1'));
372
	$p1 = ipsec_get_phase1($ikeid);
373
	return (!empty($p1['descr'])) ? $p1['descr'] : '';
374
}
375

    
376
/*
377
 * Return phase1 by reference for a given phase2
378
 */
379
function ipsec_lookup_phase1($p2, &$p1ref) {
380
	global $config;
381
	init_config_arr(array('ipsec', 'phase1'));
382

    
383
	foreach ($config['ipsec']['phase1'] as & $p1) {
384
		if ($p1['ikeid'] == $p2['ikeid']) {
385
			$p1ref = $p1;
386
			return true;
387
		}
388
	}
389

    
390
	return false;
391
}
392

    
393
function ipsec_get_phase2($reqid) {
394
	global $config;
395
	init_config_arr(array('ipsec', 'phase2'));
396

    
397
	foreach ($config['ipsec']['phase2'] as $p2) {
398
		if ($p2['reqid'] == $reqid) {
399
			return $p2;
400
		}
401
	}
402
}
403

    
404
function ipsec_get_phase2_by_ikeid($ikeid) {
405
	global $config;
406
	init_config_arr(array('ipsec', 'phase2'));
407
	$results = array();
408
	foreach ($config['ipsec']['phase2'] as $p2) {
409
		if ($p2['ikeid'] == $ikeid) {
410
			$results[] = $p2;
411
		}
412
	}
413
	return $results;
414
}
415

    
416
function ipsec_get_number_of_phase2($ikeid) {
417
	global $config;
418
	return count(ipsec_get_phase2_by_ikeid($ikeid));
419
}
420

    
421
/* Return a nested hash with P1 indexed by ikeid and P2 indexed by reqid */
422
function ipsec_map_config_by_id() {
423
	global $config;
424
	init_config_arr(array('ipsec', 'phase1'));
425
	init_config_arr(array('ipsec', 'phase2'));
426
	$map = array();
427

    
428
	foreach ($config['ipsec']['phase1'] as $p1) {
429
		$map[$p1['ikeid']] = array();
430
		$map[$p1['ikeid']]['p1'] = $p1;
431
	}
432
	foreach ($config['ipsec']['phase2'] as $p2) {
433
		if (!is_array($map[$p2['ikeid']]['p2'])) {
434
			$map[$p2['ikeid']]['p2'] = array();
435
		}
436
		$map[$p2['ikeid']]['p2'][$p2['reqid']] = $p2;
437
	}
438

    
439
	return $map;
440
}
441

    
442
function ipsec_conid($p1 = null, $p2 = null) {
443
	global $ipsec_conid_prefix, $ipsec_conid_separator;
444

    
445
	$conid = NULL;
446
	$have_p1 = (!empty($p1) && is_array($p1));
447
	$have_p2 = (!empty($p2) && is_array($p2));
448

    
449
	if (!$have_p1 && $have_p2) {
450
		$p1 = ipsec_get_phase1($p2['ikeid']);
451
	}
452

    
453
	if (isset($p1['mobile'])) {
454
		return "{$ipsec_conid_prefix}-mobile";
455
	}
456

    
457
	$conid = "{$ipsec_conid_prefix}{$p1['ikeid']}";
458

    
459
	if ($have_p2) {
460
		/* IKEv1 or IKEv2+Split Connections use separate P2 entries
461
		 * so add reqid to ID */
462
		if (($p1['iketype'] != 'ikev2') || isset($p1['splitconn'])) {
463
			$conid .= "{$ipsec_conid_separator}{$p2['reqid']}";
464
		}
465
	}
466

    
467
	return $conid;
468
}
469

    
470
function ipsec_id_by_conid($conid) {
471
	global $config, $ipsec_conid_prefix, $ipsec_conid_separator;
472

    
473
	if ($conid == "{$ipsec_conid_prefix}-mobile") {
474
		init_config_arr(array('ipsec', 'phase1'));
475
		foreach ($config['ipsec']['phase1'] as $p1) {
476
			if (isset($p1['mobile'])) {
477
				$conid = "{$ipsec_conid_prefix}{$p1['ikeid']}";
478
			}
479
		}
480
	}
481

    
482
	if (substr($conid, 0, strlen($ipsec_conid_prefix)) == $ipsec_conid_prefix) {
483
		$conid = substr($conid, strlen($ipsec_conid_prefix));
484
	}
485
	$parts = explode($ipsec_conid_separator, $conid);
486
	if (count($parts) == 1) {
487
		$parts[1] = NULL;
488
	}
489
	return array($parts[0], $parts[1]);
490
}
491

    
492
/*
493
 * Return phase1 local address
494
 */
495
function ipsec_get_phase1_src(& $ph1ent, $gateways_status = false) {
496
	global $interface_ip_arr_cache;
497
	global $interface_sn_arr_cache;
498
	if ($ph1ent['interface']) {
499
		/* get_interface_ip() already calls get_failover_interface so no need for special handling */
500
		$if = $ph1ent['interface'];
501
	} else {
502
		$if = "wan";
503
	}
504

    
505
	/* Fetch gateway status if not passed */
506
	if (!is_array($gateways_status)) {
507
		$gateways_status = return_gateways_status(true);
508
	}
509

    
510
	$ifips = array();
511
	if (in_array($ph1ent['protocol'], array('inet', 'both'))) {
512
		$ip4 = get_interface_ip($if, $gateways_status);
513
		if (!empty($ip4)) {
514
			$ifips[] = $ip4;
515
		}
516
	}
517

    
518
	if (in_array($ph1ent['protocol'], array('inet6', 'both'))) {
519
		/* get correct interface name for 6RD/6to4 interfaces
520
		 * see https://redmine.pfsense.org/issues/11643 */
521
		if (is_stf_interface($ph1ent['interface'])) {
522
			$ip6 = get_interface_ipv6($ph1ent['interface'], false, false, $gateways_status);
523
		} else {
524
			$ip6 = get_interface_ipv6($if, false, false, $gateways_status);
525
		}
526
		if (!empty($ip6)) {
527
			$ifips[] = $ip6;
528
		}
529
	}
530

    
531
	return implode(',', $ifips);
532
}
533

    
534
/*
535
 * Return phase1 local address
536
 */
537
function ipsec_get_phase1_dst(& $ph1ent) {
538
	global $g;
539

    
540
	if (empty($ph1ent['remote-gateway'])) {
541
		return false;
542
	}
543
	$rg = $ph1ent['remote-gateway'];
544
	if (!is_ipaddr($rg)) {
545
		if (!platform_booting()) {
546
			return resolve_retry($rg, $ph1ent['protocol']);
547
		}
548
	}
549
	if (!is_ipaddr($rg)) {
550
		return false;
551
	}
552

    
553
	return $rg;
554
}
555

    
556
/*
557
 * Return phase2 idinfo in cidr format
558
 */
559
function ipsec_idinfo_to_cidr(& $idinfo, $addrbits = false, $mode = "") {
560
	global $config;
561

    
562
	switch ($idinfo['type']) {
563
		case "address":
564
			if ($addrbits) {
565
				if ($mode == "tunnel6") {
566
					return $idinfo['address']."/128";
567
				} elseif (($mode == "vti") && is_ipaddrv4($idinfo['address'])) {
568
					return $idinfo['address']."/30";
569
				} elseif (($mode == "vti") && is_ipaddrv6($idinfo['address'])) {
570
					return $idinfo['address']."/64";
571
				} else {
572
					return $idinfo['address']."/32";
573
				}
574
			} else {
575
				return $idinfo['address'];
576
			}
577
			break; /* NOTREACHED */
578
		case "network":
579
			return "{$idinfo['address']}/{$idinfo['netbits']}";
580
			break; /* NOTREACHED */
581
		case "none":
582
		case "mobile":
583
			return '0.0.0.0/0';
584
			break; /* NOTREACHED */
585
		default:
586
			if (empty($mode) && !empty($idinfo['mode'])) {
587
				$mode = $idinfo['mode'];
588
			}
589

    
590
			if ($mode == "tunnel6") {
591
				$address = get_interface_ipv6($idinfo['type']);
592
				$netbits = get_interface_subnetv6($idinfo['type']);
593
				$address = gen_subnetv6($address, $netbits);
594
				return "{$address}/{$netbits}";
595
			} else {
596
				$address = get_interface_ip($idinfo['type']);
597
				$netbits = get_interface_subnet($idinfo['type']);
598
				$address = gen_subnet($address, $netbits);
599
				return "{$address}/{$netbits}";
600
			}
601
			break; /* NOTREACHED */
602
	}
603
}
604

    
605
/*
606
 * Return phase2 idinfo in address/netmask format
607
 */
608
function ipsec_idinfo_to_subnet(& $idinfo, $addrbits = false) {
609
	global $config;
610

    
611
	switch ($idinfo['type']) {
612
		case "address":
613
			if ($addrbits) {
614
				if ($idinfo['mode'] == "tunnel6") {
615
					return $idinfo['address']."/128";
616
				} else {
617
					return $idinfo['address']."/255.255.255.255";
618
				}
619
			} else {
620
				return $idinfo['address'];
621
			}
622
			break; /* NOTREACHED */
623
		case "none":
624
		case "network":
625
			return $idinfo['address']."/".gen_subnet_mask($idinfo['netbits']);
626
			break; /* NOTREACHED */
627
		case "mobile":
628
			return "0.0.0.0/0";
629
			break; /* NOTREACHED */
630
		default:
631
			if ($idinfo['mode'] == "tunnel6") {
632
				$address = get_interface_ipv6($idinfo['type']);
633
				$netbits = get_interface_subnetv6($idinfo['type']);
634
				$address = gen_subnetv6($address, $netbits);
635
				return $address."/".$netbits;
636
			} else {
637
				$address = get_interface_ip($idinfo['type']);
638
				$netbits = get_interface_subnet($idinfo['type']);
639
				$address = gen_subnet($address, $netbits);
640
				return $address."/".$netbits;
641
			}
642
			break; /* NOTREACHED */
643
	}
644
}
645

    
646
/*
647
 *  Return phase2 idinfo in text format
648
 */
649
function ipsec_idinfo_to_text(& $idinfo) {
650
	global $config;
651

    
652
	switch ($idinfo['type']) {
653
		case "address":
654
			return $idinfo['address'];
655
			break; /* NOTREACHED */
656
		case "network":
657
			return $idinfo['address']."/".$idinfo['netbits'];
658
			break; /* NOTREACHED */
659
		case "mobile":
660
			return gettext("Mobile Client");
661
			break; /* NOTREACHED */
662
		case "none":
663
			return gettext("None");
664
			break; /* NOTREACHED */
665
		default:
666
			if (!empty($config['interfaces'][$idinfo['type']])) {
667
				return convert_friendly_interface_to_friendly_descr($idinfo['type']);
668
			} else {
669
				return strtoupper($idinfo['type']);
670
			}
671
			break; /* NOTREACHED */
672
	}
673
}
674

    
675
/*
676
 * Wrapper to call pfSense_ipsec_list_sa() when IPsec is enabled
677
 */
678
function ipsec_list_sa() {
679
	if (ipsec_enabled()) {
680
		return pfSense_ipsec_list_sa();
681
	}
682
	return array();
683
}
684

    
685
function ipsec_status() {
686
	$cmap = ipsec_map_config_by_id();
687
	$status = ipsec_list_sa();
688

    
689
	/*
690
	Start:
691
	$cmap[$ikeid]['p1'] => Phase 1 config
692
	$cmap[$ikeid]['p2'] => Array of P2 configs indexed by reqid
693

    
694
	End:
695
	$cmap[$ikeid]['p1']['status'] => Array of IKE SA entries and child SAs for this P1
696
	$cmap[$ikeid]['p1']['connected'] => true/false if the P1 is connected
697
	$cmap[$ikeid]['p2'][$reqid]['connected'] => true/false if the P2 is connected
698
		If non-split IKEv2 then mark all as 'true'
699
	*/
700

    
701
	if (!is_array($status)) {
702
		$status = array();
703
	}
704

    
705
	$cmap['connected'] = array(
706
		/* List of connected P1 conid entries (excluding mobile) */
707
		'p1' => array(),
708
		/* List of connected P2 conid entries (excluding mobile) */
709
		'p2' => array(),
710
	);
711
	$cmap['disconnected'] = array(
712
		/* List of disconnected P1 conid entries (excluding mobile) */
713
		'p1' => array(),
714
		/* List of disconnected P2 conid entries (excluding mobile) */
715
		'p2' => array(),
716
	);
717

    
718
	/* First level of array has IKE SA content */
719
	foreach ($status as $ikesa) {
720
		/* If the con-id isn't there it must not be a proper entry */
721
		if (!isset($ikesa['con-id'])) {
722
			continue;
723
		}
724

    
725
		/* Mark this IKE ID as connected and drop the status info underneath the P1 config */
726
		list($ikeid, $reqid) = ipsec_id_by_conid($ikesa['con-id']);
727
		if (!array_key_exists($ikeid, $cmap)) {
728
			// Doesn't match known tunnel
729
			$cmap['connected']['p1'][$ikesa['con-id']] = $ikesa['con-id'];
730
		} else {
731
			/* Track this IKE ID in the connection list */
732
			$cmap['connected']['p1'][$ikeid] = $ikesa['con-id'];
733
			/* Copy the status data. Use an array since it could be connected multiple times. */
734
			if (!is_array($cmap[$ikeid]['status'])) {
735
				$cmap[$ikeid]['status'] = array();
736
			}
737
			$cmap[$ikeid]['status'][] = $ikesa;
738
			$cmap[$ikeid]['p1']['connected'] = true;
739
		}
740

    
741
		/* If there are child SAs under this IKE entry, process them */
742
		if (array_key_exists('child-sas', $ikesa) &&
743
		    is_array($ikesa['child-sas'])) {
744
			foreach ($ikesa['child-sas'] as $childid => $childsa) {
745
				/* Mark this reqid as connected */
746
				list($childikeid, $childreqid) = ipsec_id_by_conid($childsa['name']);
747

    
748
				if ($childreqid != null) {
749
					if (!isset($cmap[$childikeid]['p2'][$childreqid]['mobile'])) {
750
						$cmap['connected']['p2'][$childreqid] = $childsa['name'];
751
						$cmap[$childikeid]['p2'][$childreqid]['connected'] = true;
752
					}
753
				} else {
754
					/* If this is IKEv2 w/o Split, mark all reqids for the P1 as connected */
755
					if ($cmap[$childikeid]['p1']['iketype'] == 'ikev2' &&
756
					    !isset($cmap[$childikeid]['p1']['splitconn'])) {
757
						foreach ($cmap[$ikeid]['p2'] as $p2) {
758
							if (isset($p2['mobile'])) {
759
								continue;
760
							}
761
							$cmap['connected']['p2'][$p2['reqid']] = $childsa['name'];
762
							$cmap[$childikeid]['p2'][$p2['reqid']]['connected'] = true;
763
						}
764
					}
765
				}
766
			}
767
		}
768
	}
769
	if (is_array($cmap)) {
770
		foreach ($cmap as $k => $tunnel) {
771
			if (in_array($k, array('connected', 'disconnected')) ||
772
			    (!array_key_exists('p1', $tunnel) ||
773
			    isset($tunnel['p1']['disabled'])) ||
774
			    isset($tunnel['p1']['mobile'])) {
775
				continue;
776
			}
777
			if (!array_key_exists($tunnel['p1']['ikeid'], $cmap['connected']['p1'])) {
778
				$cmap['disconnected']['p1'][$tunnel['p1']['ikeid']] = ipsec_conid($tunnel['p1']);
779
			}
780
			if (is_array($tunnel['p2'])) {
781
				foreach ($tunnel['p2'] as $p2) {
782
					if (isset($p2['mobile'])) {
783
						continue;
784
					}
785
					if (!array_key_exists($p2['reqid'], $cmap['connected']['p2'])) {
786
						/* This P2 is not connected */
787
						$cmap['disconnected']['p2'][$p2['reqid']] = ipsec_conid($p1['p1'], $p2);
788
					}
789
				}
790
			}
791
		}
792
	}
793
	return $cmap;
794
}
795

    
796
function ipsec_status_button($req = 'post', $act = 'connect', $type = 'ike', $conid, $uniqueid = null, $full = true) {
797
	$btn = '<a href="';
798
	if ($act == 'disconnect') {
799
		$buttonclass = ($type == 'ike') ? 'danger' : 'warning';
800
		$title = gettext("Disconnect");
801
		$icon = 'trash';
802
	} else {
803
		$buttonclass = 'success';
804
		$title = gettext("Connect");
805
		$icon = 'sign-in';
806
	}
807
	if ($full) {
808
		$linkclass = 'btn btn-xs btn-' . htmlspecialchars($buttonclass);
809
	} else {
810
		$linkclass = '';
811
	}
812

    
813
	$title .= " ";
814
	switch ($type) {
815
		case 'all':
816
			$title .= gettext("P1 and P2s");
817
			break;
818
		case 'child':
819
			$title .= gettext("P2");
820
			break;
821
		case 'ike':
822
		default:
823
			$title .= gettext("P1");
824
			break;
825
	}
826

    
827
	if ($req == 'post') {
828
		$btn .= 'status_ipsec.php?act=' . htmlspecialchars($act) .
829
			'&amp;type=' . htmlspecialchars($type) .
830
			'&amp;conid=' . htmlspecialchars($conid);
831
		if (!empty($uniqueid)) {
832
			$btn .= '&amp;uniqueid=' . htmlspecialchars($uniqueid);
833
		}
834
	} else {
835
		$btn .= '#" id="' . 'ipsecstatus-' .
836
			htmlspecialchars($act) . '-' .
837
			htmlspecialchars($type) . '-' .
838
			htmlspecialchars($conid);
839
		if (!empty($uniqueid)) {
840
			$btn .= '-' . htmlspecialchars($uniqueid);
841
		}
842
	}
843

    
844
	$btn .= '"';
845
	if ($full) {
846
		$btn .= ' class="' . htmlspecialchars($linkclass) . '"';
847
	}
848
	$btn .= ' title="' . htmlspecialchars($title) . '"';
849

    
850
	if ($req == 'post') {
851
		$btn .= ' usepost';
852
	}
853
	$btn .= '>';
854
	$btn .= '<i class="fa fa-' . htmlspecialchars($icon);
855
	if ($req == 'post') {
856
		$btn .= ' icon-embed-btn';
857
	}
858
	$btn .= '"></i>';
859

    
860
	if ($full) {
861
		$btn .= ' ' . htmlspecialchars($title);
862
	}
863
	$btn .= '</a>';
864
	return $btn;
865
}
866

    
867
function ipsec_initiate($type = 'ike', $p1 = null, $p2 = null) {
868
	return ipsec_initiate_by_conid($type, ipsec_conid($p1, $p2));
869
}
870

    
871
function ipsec_initiate_by_conid($type = 'ike', $conid) {
872
	if (empty($conid)) {
873
		return false;
874
	}
875
	switch ($type) {
876
		case 'all':
877
			/* Find relevant P2s and initaite all of them */
878
			$cmap = ipsec_map_config_by_id();
879
			list($ikeid, $reqid) = ipsec_id_by_conid($conid);
880
			if (array_key_exists($ikeid, $cmap)) {
881
				if ($cmap[$ikeid]['p1']['iketype'] == 'ikev2' && !isset($cmap[$ikeid]['p1']['splitconn'])) {
882
					/* IKEv2 without split only has one P2, named the same as the the P1 */
883
					ipsec_initiate_by_conid('child', ipsec_conid($cmap[$ikeid]['p1']));
884
				} else {
885
					foreach ($cmap[$ikeid]['p2'] as $p2) {
886
						ipsec_initiate_by_conid('child', ipsec_conid($cmap[$ikeid]['p1'], $p2));
887
					}
888
				}
889
			}
890
			break;
891
		case 'ike':
892
		case 'child':
893
			mwexec_bg("/usr/local/sbin/swanctl --initiate --timeout 5 " . escapeshellarg('--' . $type) . " " . escapeshellarg($conid));
894
			break;
895
		default:
896
			/* Do nothing. Invalid type. */
897
			break;
898
	}
899
	return true;
900
}
901

    
902
function ipsec_terminate($type = 'ike', $p1 = null, $p2 = null, $uniqueid = null) {
903
	return ipsec_terminate_by_conid($type, ipsec_conid($p1, $p2), $uniqueid);
904
}
905

    
906
function ipsec_terminate_by_conid($type = 'ike', $conid = null, $uniqueid = null) {
907
	/* Must have one or the other */
908
	if (($conid === null) && ($uniqueid === null)) {
909
		return false;
910
	}
911
	$selector = '--';
912
	$selector .= ($type == 'ike') ? 'ike' : 'child';
913

    
914
	if (ctype_digit($uniqueid) && ($uniqueid > 0)) {
915
		$selector .= '-id';
916
		$term = $uniqueid;
917
	} else {
918
		$term = $conid;
919
	}
920
	mwexec_bg("/usr/local/sbin/swanctl --terminate --force " . escapeshellarg($selector) . " " . escapeshellarg($term));
921
	return true;
922
}
923

    
924
/*
925
 * Return dump of SPD table
926
 */
927
function ipsec_dump_spd() {
928
	$fd = @popen("/sbin/setkey -DP", "r");
929
	$spd = array();
930
	if ($fd) {
931
		while (!feof($fd)) {
932
			$line = chop(fgets($fd));
933
			if (!$line) {
934
				continue;
935
			}
936
			if ($line == "No SPD entries.") {
937
				break;
938
			}
939
			if ($line[0] != "\t") {
940
				if (is_array($cursp)) {
941
					$spd[] = $cursp;
942
				}
943
				$cursp = array();
944
				$linea = explode(" ", $line);
945
				$cursp['srcid'] = substr($linea[0], 0, strpos($linea[0], "["));
946
				$cursp['dstid'] = substr($linea[1], 0, strpos($linea[1], "["));
947
				$i = 0;
948
			} else if (is_array($cursp)) {
949
				$line = trim($line, "\t\r\n ");
950
				$linea = explode(" ", $line);
951
				switch ($i) {
952
					case 1:
953
						if ($linea[1] == "none")	/* don't show default anti-lockout rule */ {
954
							unset($cursp);
955
						} else {
956
							$cursp['dir'] = $linea[0];
957
						}
958
						break;
959
					case 2:
960
						$upperspec = explode("/", $linea[0]);
961
						$cursp['proto'] = $upperspec[0];
962
						list($cursp['src'], $cursp['dst']) = explode("-", $upperspec[2]);
963
						$cursp['unique'] = substr($upperspec[3], strpos($upperspec[3], ":")+1);
964
						break;
965
					default:
966
						if (substr($linea[0], 0, 4) != 'spid') {
967
							break;
968
						}
969
						$cursp['scope'] = substr($linea[3], strpos($linea[3], "=")+1);
970
						if ($cursp['scope'] == 'ifnet') {
971
							$cursp['ifname'] = substr($linea[4], strpos($linea[4], "=")+1);
972
						}
973
						break;
974
				}
975
			}
976
			$i++;
977
		}
978
		if (is_array($cursp) && count($cursp)) {
979
			$spd[] = $cursp;
980
		}
981
		pclose($fd);
982
	}
983

    
984
	return $spd;
985
}
986

    
987
/*
988
 * Return dump of SAD table
989
 */
990
function ipsec_dump_sad() {
991
	$fd = @popen("/sbin/setkey -D", "r");
992
	$sad = array();
993
	if ($fd) {
994
		while (!feof($fd)) {
995
			$line = chop(fgets($fd));
996
			if (!$line || $line[0] == " ") {
997
				continue;
998
			}
999
			if ($line == "No SAD entries.") {
1000
				break;
1001
			}
1002
			if ($line[0] != "\t") {
1003
				if (is_array($cursa)) {
1004
					$sad[] = $cursa;
1005
				}
1006
				$cursa = array();
1007
				list($cursa['src'], $cursa['dst']) = explode(" ", $line);
1008
			} else {
1009
				$line = trim($line, "\t\n\r ");
1010
				$linea = explode(" ", $line);
1011
				foreach ($linea as $idx => $linee) {
1012
					if ($linee == 'esp' || $linee == 'ah' || $linee[0] == '#') {
1013
						$cursa['proto'] = $linee;
1014
					} else if (substr($linee, 0, 3) == 'spi') {
1015
						$cursa['spi'] = substr($linee, strpos($linee, 'x') + 1, -1);
1016
					} else if (substr($linee, 0, 5) == 'reqid') {
1017
						$cursa['reqid'] = substr($linee, strpos($linee, 'x') + 1, -1);
1018
					} else if (substr($linee, 0, 2) == 'E:') {
1019
						$cursa['ealgo'] = $linea[$idx + 1];
1020
						break;
1021
					} else if (substr($linee, 0, 2) == 'A:') {
1022
						$cursa['aalgo'] = $linea[$idx + 1];
1023
						break;
1024
					} else if (substr($linee, 0, 8) == 'current:') {
1025
						$cursa['data'] = substr($linea[$idx + 1], 0, strpos($linea[$idx + 1], 'bytes') - 1) . ' B';
1026
						break;
1027
					}
1028
				}
1029
			}
1030
		}
1031
		if (is_array($cursa) && count($cursa)) {
1032
			$sad[] = $cursa;
1033
		}
1034
		pclose($fd);
1035
	}
1036

    
1037
	return $sad;
1038
}
1039

    
1040
/*
1041
 * Return dump of mobile user list
1042
 */
1043
function ipsec_dump_mobile() {
1044
	global $g, $config;
1045

    
1046
	if(!isset($config['ipsec']['client']['enable'])) {
1047
		return array();
1048
	}
1049

    
1050
	/* Fetch the pool contents and leases from swanctl. */
1051
	$_gb = exec("/usr/local/sbin/swanctl --list-pools --leases 2>/dev/null", $output, $rc);
1052

    
1053
	if ($rc != 0) {
1054
		log_error(gettext("Unable to find IPsec daemon leases file. Could not display mobile user stats!"));
1055
		return array();
1056
	}
1057

    
1058
	$response = array(
1059
		'pool' => array(),
1060
	);
1061

    
1062
	/* swanctl --list-pools --leases example output, field names can be confirmed by
1063
	 * looking at --raw or --pretty output. */
1064
	/* mobile-pool          10.7.200.0                          0 / 1 / 254 */
1065
	$pool_regex='/^(?P<name>\S+)\s+(?P<base>\S+)\s+(?P<online>\d+) \/ (?P<offline>\d+) \/ (?P<size>\d+)/';
1066
	/*   10.7.200.1                     online   'jimp' */
1067
	$lease_regex='/\s*(?P<host>[\d\.]+)\s+(?P<status>online|offline)\s+\'(?P<id>.*)\'/';
1068
	foreach ($output as $line) {
1069
		if (preg_match($pool_regex, $line, $matches)) {
1070
			$id++;
1071
			$response['pool'][$id] = array(
1072
			    'name'   => $matches['name'],
1073
			    'base'   => $matches['base'],
1074
			    'online' => $matches['online'],
1075
			    'offline'  => $matches['offline'],
1076
			    'size'   => $matches['size'],
1077
			);
1078
		} elseif (preg_match($lease_regex, $line, $matches)) {
1079
			$response['pool'][$id]['lease'][] = array(
1080
			    'host'   => $matches['host'],
1081
			    'status' => $matches['status'],
1082
			    'id'     => $matches['id']
1083
			);
1084
		}
1085
	}
1086

    
1087
	unset($_gb, $output, $rc, $pool_regex);
1088

    
1089
	return $response;
1090
}
1091

    
1092
function ipsec_mobilekey_sort() {
1093
	global $config;
1094

    
1095
	function mobilekeycmp($a, $b) {
1096
		return strcmp($a['ident'][0], $b['ident'][0]);
1097
	}
1098

    
1099
	usort($config['ipsec']['mobilekey'], "mobilekeycmp");
1100
}
1101

    
1102
function ipsec_fixup_ip($ipaddr) {
1103
	if (is_ipaddrv6($ipaddr) || is_subnetv6($ipaddr)) {
1104
		return text_to_compressed_ip6($ipaddr);
1105
	} else {
1106
		return $ipaddr;
1107
	}
1108
}
1109

    
1110
function ipsec_find_id(& $ph1ent, $side = "local", $rgmap = array(), $gateways_status = false) {
1111
	if ($side == "local") {
1112
		$id_type = $ph1ent['myid_type'];
1113
		$id_data = $ph1ent['myid_data'];
1114

    
1115
		$addr = ipsec_get_phase1_src($ph1ent, $gateways_status);
1116
		if (!$addr) {
1117
			return array();
1118
		}
1119
		/* When automatically guessing, use the first address. */
1120
		$addr = explode(',', $addr);
1121
		$addr = $addr[0];
1122
	} elseif ($side == "peer") {
1123
		$id_type = $ph1ent['peerid_type'];
1124
		$id_data = $ph1ent['peerid_data'];
1125

    
1126
		if (isset($ph1ent['mobile'])) {
1127
			$addr = "%any";
1128
		} else {
1129
			$addr = $ph1ent['remote-gateway'];
1130
		}
1131
	} else {
1132
		return array();
1133
	}
1134

    
1135
	$thisid_type = $id_type;
1136
	switch ($thisid_type) {
1137
		case 'myaddress':
1138
			$thisid_type = 'address';
1139
			$thisid_data = $addr;
1140
			break;
1141
		case 'dyn_dns':
1142
			$thisid_type = 'dns';
1143
			$thisid_data = $id_data;
1144
			break;
1145
		case 'peeraddress':
1146
			$thisid_type = 'address';
1147
			$thisid_data = $rgmap[$ph1ent['remote-gateway']];
1148
			break;
1149
		case 'keyid tag':
1150
			$thisid_type = 'keyid';
1151
			$thisid_data = $id_data;
1152
			break;
1153
		case 'user_fqdn':
1154
			$thisid_type = 'userfqdn';
1155
			$thisid_data = $id_data;
1156
			break;
1157
		case 'any':
1158
			$thisid_data = '%any';
1159
			break;
1160
		case 'address':
1161
		case 'fqdn':
1162
		case 'asn1dn':
1163
		case 'auto':
1164
			$thisid_data = $id_data;
1165
			break;
1166
		default:
1167
			break;
1168
	}
1169
	return array($thisid_type, $thisid_data);
1170
}
1171

    
1172
/*
1173
 * Fixup ID type/data to include prefix when necessary, add quotes, etc.
1174
 */
1175
function ipsec_fixup_id($type, $data) {
1176
	/* List of types to pass through as-is without changes or adding prefix */
1177
	$auto_types = array('address', 'auto');
1178
	/* List of types which need the resulting string double quoted. */
1179
	$quote_types = array('keyid', 'asn1dn', 'auto');
1180

    
1181
	/* If the first character of asn1dn type data is not #, then rely on
1182
	 * automatic parsing https://redmine.pfsense.org/issues/4792 */
1183
	if (($type == 'asn1dn') && !empty($data) && ($data[0] != '#')) {
1184
		$auto_types[] = 'asn1dn';
1185
	}
1186

    
1187
	if ($type == 'any') {
1188
		$idstring = "%any";
1189
	} elseif (!in_array($type, $auto_types)) {
1190
		$idstring = "{$type}:{$data}";
1191
	} else {
1192
		$idstring = $data;
1193
	}
1194

    
1195
	if (in_array($type, $quote_types)) {
1196
		$idstring = "\"{$idstring}\"";
1197
	}
1198

    
1199
	return $idstring;
1200
}
1201

    
1202
function ipsec_fixup_network($network) {
1203
	if (substr($network, -3) == '|/0') {
1204
		$result = substr($network, 0, -3);
1205
	} else {
1206
		$tmp = explode('|', $network);
1207
		if (isset($tmp[1])) {
1208
			$result = $tmp[1];
1209
		} else {
1210
			$result = $tmp[0];
1211
		}
1212
		unset($tmp);
1213
	}
1214

    
1215
	return $result;
1216
}
1217

    
1218
function ipsec_get_loglevels() {
1219
	global $config, $ipsec_log_cats;
1220
	$def_loglevel = '1';
1221

    
1222
	$levels = array();
1223

    
1224
	foreach (array_keys($ipsec_log_cats) as $cat) {
1225
		if (isset($config['ipsec']['logging'][$cat])) {
1226
			$levels[$cat] = $config['ipsec']['logging'][$cat];
1227
		} elseif (in_array($cat, array('ike', 'chd', 'cfg'))) {
1228
			$levels[$cat] = "2";
1229
		} else {
1230
			$levels[$cat] = $def_loglevel;
1231
		}
1232
	}
1233
	return $levels;
1234
}
1235

    
1236
function ipsec_vti($p1, $returnaddresses = false, $skipdisabled = true) {
1237
	global $config;
1238
	$is_vti = false;
1239
	$vtisubnet_spec = array();
1240

    
1241
	foreach(ipsec_get_phase2_by_ikeid($p1['ikeid']) as $p2) {
1242
		if ($p2['mode'] == 'vti') {
1243
			if ($skipdisabled && isset($p2['disabled'])) {
1244
				continue;
1245
			} else {
1246
				$is_vti = true;
1247
			}
1248
			if ($returnaddresses) {
1249
				$vtisubnet_spec[] = array(
1250
					'left' => ipsec_idinfo_to_cidr($p2['localid'], true, $p2['mode']),
1251
					'right' => ipsec_idinfo_to_cidr($p2['remoteid'], false, $p2['mode']),
1252
					'descr' => $p2['descr'],
1253
					'reqid' => $p2['reqid'],
1254
				);
1255
			}
1256
		}
1257
	}
1258
	return ($returnaddresses) ? $vtisubnet_spec : $is_vti;
1259
}
1260

    
1261
/* Called when IPsec is reloaded through rc.newipsecdns and similar, gives
1262
 * packages an opportunity to execute custom code when IPsec reloads.
1263
 */
1264
function ipsec_reload_package_hook() {
1265
	global $g, $config;
1266

    
1267
	init_config_arr(array('installedpackages', 'package'));
1268
	foreach ($config['installedpackages']['package'] as $package) {
1269
		if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
1270
			continue;
1271
		}
1272

    
1273
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], 'packagegui');
1274
		if (!empty($pkg_config['include_file']) &&
1275
		    file_exists($pkg_config['include_file'])) {
1276
			require_once($pkg_config['include_file']);
1277
		}
1278
		if (empty($pkg_config['ipsec_reload_function'])) {
1279
			continue;
1280
		}
1281
		$pkg_ipsec_reload = $pkg_config['ipsec_reload_function'];
1282
		if (!function_exists($pkg_ipsec_reload)) {
1283
			continue;
1284
		}
1285
		$pkg_ipsec_reload();
1286
	}
1287
}
1288

    
1289
/****f* certs/ipsec_convert_to_modp
1290
 * NAME
1291
 *   ipsec_convert_to_modp - Take a DH Group number value and return the
1292
 *                           associated name
1293
 * INPUTS
1294
 *   $index: DH group index number to look up
1295
 * RESULT
1296
 *   Returns the Diffie Hellman Group keyword associated with the group number.
1297
 ******/
1298
function ipsec_convert_to_modp($index) {
1299
	$modpmap = array(
1300
		'1' => 'modp768',
1301
		'2' => 'modp1024',
1302
		'5' => 'modp1536',
1303
		'14' => 'modp2048',
1304
		'15' => 'modp3072',
1305
		'16' => 'modp4096',
1306
		'17' => 'modp6144',
1307
		'18' => 'modp8192',
1308
		'19' => 'ecp256',
1309
		'20' => 'ecp384',
1310
		'21' => 'ecp521',
1311
		'22' => 'modp1024s160',
1312
		'23' => 'modp2048s224',
1313
		'24' => 'modp2048s256',
1314
		'25' => 'ecp192',
1315
		'26' => 'ecp224',
1316
		'27' => 'ecp224bp',
1317
		'28' => 'ecp256bp',
1318
		'29' => 'ecp384bp',
1319
		'30' => 'ecp512bp',
1320
		'31' => 'curve25519',
1321
		'32' => 'curve448',
1322
	);
1323

    
1324
	return $modpmap[$index];
1325
}
1326

    
1327
/*
1328
 * Forcefully restart IPsec
1329
 * This is required for when dynamic interfaces reload
1330
 * For all other occasions the normal ipsec_configure()
1331
 * will gracefully reload the settings without restarting
1332
 */
1333
function ipsec_force_reload($interface = "") {
1334
	global $g, $config;
1335

    
1336
	if (!ipsec_enabled()) {
1337
		return;
1338
	}
1339

    
1340
	$ipseccfg = $config['ipsec'];
1341

    
1342
	if (!empty($interface) && is_array($ipseccfg['phase1'])) {
1343
		$found = false;
1344
		$gateways_status = null;
1345
		$realif = array();
1346
		$ifcache = array();
1347
		foreach ($ipseccfg['phase1'] as $ipsec) {
1348
			if (isset($ipsec['disabled'])) {
1349
				continue;
1350
			}
1351
			if ($ipsec['interface'] == $interface) {
1352
				$found = true;
1353
				break;
1354
			} else {
1355
				/* Fetch gateway status just once, and only if needed */
1356
				if (!is_array($gateways_status)) {
1357
					$gateways_status = return_gateways_status(true);
1358
				}
1359
				$fam = (!empty($ipsec['protocol'])) ? $ipsec['protocol'] : 'inet';
1360

    
1361
				/* Find the real active passed interface for this address family, cache the result */
1362
				if (empty($realif) ||
1363
				    empty($realif[$fam])) {
1364
					$realif[$fam] = get_failover_interface($interface, $fam, $gateways_status);
1365
				}
1366

    
1367
				/* Find the real active tunnel interface for this address family, cache the result */
1368
				if (empty($ifcache) ||
1369
				    empty($ifcache[$ipsec['interface']]) ||
1370
				    empty($ifcache[$ipsec['interface']][$fam])) {
1371
					if (!is_array($ifcache[$ipsec['interface']])) {
1372
						$ifcache[$ipsec['interface']] = array();
1373
					}
1374
					$ifcache[$ipsec['interface']][$fam] = get_failover_interface($ipsec['interface'], $fam, $gateways_status);
1375
				}
1376

    
1377
				if ($realif[$fam] == $ifcache[$ipsec['interface']][$fam]) {
1378
					$found = true;
1379
					break;
1380
				}
1381
			}
1382
		}
1383
		if (!$found) {
1384
			log_error(sprintf(gettext("Ignoring IPsec reload since there are no tunnels on interface %s"), $interface));
1385
			return;
1386
		}
1387
	}
1388

    
1389
	/* If we get this far then we need to take action. */
1390
	log_error(gettext("Forcefully reloading IPsec"));
1391
	ipsec_configure();
1392
}
1393

    
1394
/****f* ipsec/ipsec_strongswan_confgen
1395
 * NAME
1396
 *   ipsec_strongswan_confgen - Generate strongswan.conf style formatted output
1397
 *                              From a multi-dimensional array.
1398
 * INPUTS
1399
 *   $confarr: An array of key=value pairs or key=array entries for subsections.
1400
 *   $indent : A string of tabs used when indenting lines.
1401
 * RESULT
1402
 *   Returns a string of key=value pairs with proper indenting, and with named
1403
 *   subsections enclosed in braces.
1404
 * NOTES
1405
 *   Values starting with a "#" (comments) or "include " will be printed
1406
 *   directly without their associated key name.
1407
 ******/
1408
function ipsec_strongswan_confgen($confarr, $indent = "") {
1409
	$confstr = "";
1410
	/* Only process the contents if it's an array. */
1411
	if (is_array($confarr)) {
1412
		foreach ($confarr as $key => $value) {
1413
			if (is_array($value)) {
1414
				/* If the array is empty, do not print anything */
1415
				if (empty($value)) {
1416
					continue;
1417
				}
1418
				/* If this is an array, setup the subsection name
1419
				 * and structure, then call this function
1420
				 * recursively to walk the lower array. */
1421
				$confstr .= "{$indent}{$key} {\n";
1422
				$confstr .= ipsec_strongswan_confgen($value, $indent . "\t");
1423
				$confstr .= "{$indent}}\n";
1424
			} else {
1425
				$confstr .= "{$indent}";
1426
				if ((substr($value, 0 , 1) != '#') &&
1427
				    (substr($value, 0 , 8) != 'include ')) {
1428
					/* Not a comment or include, print the key */
1429
					$confstr .= "{$key} = ";
1430
				}
1431
				$confstr .= "{$value}\n";
1432
			}
1433
		}
1434
	}
1435
	return $confstr;
1436
}
1437

    
1438
global $g, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs;
1439
$ipsec_swanctl_basedir = "{$g['varetc_path']}/ipsec";
1440
$ipsec_swanctl_dirs = array(
1441
	'conf'     => "{$ipsec_swanctl_basedir}/conf.d",
1442
	'certpath' => "{$ipsec_swanctl_basedir}/x509",
1443
	'capath'   => "{$ipsec_swanctl_basedir}/x509ca",
1444
	'aapath'   => "{$ipsec_swanctl_basedir}/x509aa",
1445
	'ocsppath' => "{$ipsec_swanctl_basedir}/x509ocsp",
1446
	'crlpath'  => "{$ipsec_swanctl_basedir}/x509crl",
1447
	'acpath'   => "{$ipsec_swanctl_basedir}/x509ac",
1448
	'rsakeys'  => "{$ipsec_swanctl_basedir}/rsa",
1449
	'eckeys'   => "{$ipsec_swanctl_basedir}/ecdsa",
1450
	'keypath'  => "{$ipsec_swanctl_basedir}/private",
1451
	'pubkpath' => "{$ipsec_swanctl_basedir}/pubkey",
1452
	'blisspath' => "{$ipsec_swanctl_basedir}/bliss",
1453
	'pkcs8path' => "{$ipsec_swanctl_basedir}/pkcs8",
1454
	'pkcs12path' => "{$ipsec_swanctl_basedir}/pkcs12",
1455
);
1456

    
1457
/****f* ipsec/ipsec_create_dirs
1458
 * NAME
1459
 *   ipsec_create_dirs - Create default set of strongSwan configuration directories.
1460
 * INPUTS
1461
 *   None
1462
 * RESULT
1463
 *   Cleans up and creates strongSwan configuration directories and links.
1464
 ******/
1465
function ipsec_create_dirs() {
1466
	global $config, $g, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs;
1467

    
1468
	/* Cleanup base paths to ensure old files are not left behind (#5238) */
1469
	if (!empty($ipsec_swanctl_basedir)) {
1470
		@rmdir_recursive($ipsec_swanctl_basedir, false);
1471
	}
1472
	/* Create directory structure */
1473
	array_map('safe_mkdir', array_values($ipsec_swanctl_dirs));
1474

    
1475
	/* Create and link strongSwan config */
1476
	$ssdpath = "{$g['varetc_path']}/ipsec/strongswan.d";
1477
	if (!file_exists($ssdpath) || !is_link($ssdpath)) {
1478
		if (is_dir($ssdpath) && !is_link($ssdpath)) {
1479
			@rmdir_recursive($ssdpath, false);
1480
		} else {
1481
			@unlink($ssdpath);
1482
		}
1483
		@symlink("/usr/local/etc/strongswan.d",
1484
		    $ssdpath);
1485
	}
1486
	if (!file_exists("/usr/local/etc/strongswan.conf") ||
1487
	    !is_link("/usr/local/etc/strongswan.conf")) {
1488
		@unlink("/usr/local/etc/strongswan.conf");
1489
		@symlink("{$g['varetc_path']}/ipsec/strongswan.conf",
1490
		    "/usr/local/etc/strongswan.conf");
1491
	}
1492
}
1493

    
1494
/****f* ipsec/ipsec_setup_gwifs
1495
 * NAME
1496
 *   ipsec_setup_gwifs - Setup IPsec-related interfaces and gateways
1497
 * INPUTS
1498
 *   None
1499
 * RESULT
1500
 *   Sets up VTI interfaces and gateways, populates ipsecpinghosts
1501
 ******/
1502
function ipsec_setup_gwifs($gateways_status = false) {
1503
	global $g, $a_phase1, $a_phase2, $rgmap, $filterdns_list,
1504
		$aggressive_mode_psk, $mobile_ipsec_auth, $ifacesuse,
1505
		$ipsecpinghostsactive;
1506
	/* resolve all local, peer addresses and setup pings */
1507
	/* Fetch gateway status if not passed */
1508
	if (!is_array($gateways_status)) {
1509
		$gateways_status = return_gateways_status(true);
1510
	}
1511

    
1512
	unset($iflist);
1513
	if (is_array($a_phase1) && count($a_phase1)) {
1514
		$ipsecpinghosts = array();
1515
		/* step through each phase1 entry */
1516
		foreach ($a_phase1 as $ph1ent) {
1517
			if (isset($ph1ent['disabled'])) {
1518
				continue;
1519
			}
1520
			if (substr($ph1ent['interface'], 0, 4) == "_vip") {
1521
				$vpninterface = get_configured_vip_interface($ph1ent['interface']);
1522
				$ifacesuse[] = get_real_interface($vpninterface);
1523
			} else {
1524
				$vpninterface = get_failover_interface($ph1ent['interface'], 'all', $gateways_status);
1525
				if (substr($vpninterface, 0, 4) == "_vip") {
1526
					$vpninterface = get_configured_vip_interface($vpninterface);
1527
					$ifacesuse[] = get_real_interface($vpninterface);
1528
				} elseif (!empty($vpninterface)) {
1529
					$ifacesuse[] = $vpninterface;
1530
				}
1531
			}
1532
			if ($ph1ent['mode'] == "aggressive" && ($ph1ent['authentication_method'] == "pre_shared_key" || $ph1ent['authentication_method'] == "xauth_psk_server")) {
1533
				$aggressive_mode_psk = true;
1534
			}
1535

    
1536
			$ikeid = $ph1ent['ikeid'];
1537

    
1538
			$local_spec = ipsec_get_phase1_src($ph1ent, $gateways_status);
1539
			/* When automatically guessing, use the first address. */
1540
			$local_spec  = explode(',', $local_spec);
1541
			$local_spec  = $local_spec[0];
1542
			if (!is_ipaddr($local_spec)) {
1543
				log_error(sprintf(gettext("IPsec ERROR: Could not find phase 1 source for connection %s. Omitting from configuration file."), $ph1ent['descr']));
1544
				continue;
1545
			}
1546

    
1547
			if (isset($ph1ent['mobile'])) {
1548
				$mobile_ipsec_auth = $ph1ent['authentication_method'];
1549
				continue;
1550
			}
1551

    
1552
			/* see if this tunnel has a hostname for the remote-gateway. If so,
1553
			   try to resolve it now and add it to the list for filterdns */
1554
			$rg = $ph1ent['remote-gateway'];
1555
			if (!is_ipaddr($rg)) {
1556
				$filterdns_list[] = "{$rg}";
1557
				add_hostname_to_watch($rg);
1558
				if (!platform_booting()) {
1559
					$rg = resolve_retry($rg, $ph1ent['protocol']);
1560
				}
1561
				if (!is_ipaddr($rg)) {
1562
					continue;
1563
				}
1564
			}
1565
			if (!isset($ph1ent['gw_duplicates']) && array_search($rg, $rgmap)) {
1566
				log_error(sprintf(gettext("The remote gateway %s already exists on another phase 1 entry"), $rg));
1567
				continue;
1568
			}
1569
			$rgmap[$ph1ent['remote-gateway']] = $rg;
1570

    
1571
			$is_vti = false;
1572
			if (is_array($a_phase2)) {
1573
				/* step through each phase2 entry */
1574
				foreach ($a_phase2 as $ph2ent) {
1575
					if ($ph2ent['ikeid'] != $ph1ent['ikeid']) {
1576
						continue;
1577
					}
1578
					if ($ph2ent['mode'] == 'vti') {
1579
						$is_vti = true;
1580
					}
1581
					if (isset($ph2ent['disabled']) || ($ikeid != $ph2ent['ikeid'])) {
1582
						continue;
1583
					}
1584

    
1585
					/* add an ipsec pinghosts entry */
1586
					if ($ph2ent['pinghost']) {
1587
						if (!is_array($iflist)) {
1588
							$iflist = get_configured_interface_list();
1589
						}
1590
						$srcip = null;
1591
						$local_subnet = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
1592
						if (is_ipaddrv6($ph2ent['pinghost'])) {
1593
							foreach ($iflist as $ifent => $ifname) {
1594
								$interface_ip = get_interface_ipv6($ifent);
1595
								if (!is_ipaddrv6($interface_ip)) {
1596
									continue;
1597
								}
1598
								if (ip_in_subnet($interface_ip, $local_subnet)) {
1599
									$srcip = $interface_ip;
1600
									break;
1601
								}
1602
							}
1603
						} else {
1604
							foreach ($iflist as $ifent => $ifname) {
1605
								$interface_ip = get_interface_ip($ifent, $gateways_status);
1606
								if (!is_ipaddrv4($interface_ip)) {
1607
									continue;
1608
								}
1609
								if ($local_subnet == "0.0.0.0/0" || ip_in_subnet($interface_ip, $local_subnet)) {
1610
									$srcip = $interface_ip;
1611
									break;
1612
								}
1613
							}
1614
						}
1615
						/* if no valid src IP was found in configured interfaces, try the vips */
1616
						if (is_null($srcip)) {
1617
							$viplist = get_configured_vip_list();
1618
							foreach ($viplist as $vip => $address) {
1619
								if (ip_in_subnet($address, $local_subnet)) {
1620
									$srcip = $address;
1621
									break;
1622
								}
1623
							}
1624
						}
1625
						$dstip = $ph2ent['pinghost'];
1626
						$family = "inet" . (is_ipaddrv6($dstip)) ? "6" : "";
1627
						if (is_ipaddr($srcip)) {
1628
							$ipsecpinghosts[] = "{$srcip}|{$dstip}|3|||||{$family}|\n";
1629
							$ipsecpinghostsactive = true;
1630
						}
1631
					}
1632
				}
1633
			}
1634
			if ($is_vti) {
1635
				interface_ipsec_vti_configure($ph1ent, $gateways_status);
1636
			}
1637
		}
1638
		@file_put_contents("{$g['vardb_path']}/ipsecpinghosts", $ipsecpinghosts);
1639
		unset($ipsecpinghosts);
1640
	}
1641
	unset($iflist);
1642
}
1643

    
1644
/****f* ipsec/ipsec_logging_config
1645
 * NAME
1646
 *   ipsec_logging_config - Generate an array containing strongSwan logging
1647
 *                          values.
1648
 * INPUTS
1649
 *   None
1650
 * RESULT
1651
 *   Returns an array which can be merged into the strongswan daemon logging
1652
 *   values so that each logging category is represented, even those not listed
1653
 *   in config.xml.
1654
 ******/
1655
function ipsec_logging_config() {
1656
	global $config, $ipsec_log_cats, $ipsec_log_sevs;
1657
	$logcfg = array();
1658
	$log_levels = ipsec_get_loglevels();
1659
	foreach (array_keys($ipsec_log_cats) as $cat) {
1660
		if (is_numeric($log_levels[$cat]) &&
1661
		    in_array(intval($log_levels[$cat]), array_keys($ipsec_log_sevs), true)) {
1662
			$logcfg[$cat] = $log_levels[$cat];
1663
		}
1664
	}
1665
	return $logcfg;
1666
}
1667

    
1668
/****f* ipsec/ipsec_setup_strongswan
1669
 * NAME
1670
 *   ipsec_setup_strongswan - Generate the strongswan.conf configuration file.
1671
 * INPUTS
1672
 *   None
1673
 * RESULT
1674
 *   Determines strongswan.conf values and crafts the configuration file in the
1675
 *   appropriate format.
1676
 * NOTES
1677
 *   Called from ipsec_configure()
1678
 ******/
1679
function ipsec_setup_strongswan() {
1680
	global $config, $g, $mobile_ipsec_auth, $a_client, $a_phase2, $aggressive_mode_psk, $ifacesuse;
1681

    
1682
	/* strongswan.conf array */
1683
	$ssconf = array();
1684
	$ssconf[] = "# Automatically generated config file - DO NOT MODIFY. Changes will be overwritten.";
1685
	$ssconf['starter'] = array();
1686
	$ssconf['starter']['load_warning'] = "no";
1687

    
1688
	$ssconf['charon'] = array();
1689
	$ssconf['charon'][] = '# number of worker threads in charon';
1690
	$ssconf['charon']['threads'] = '16';
1691
	$ssconf['charon']['ikesa_table_size'] = '32';
1692
	$ssconf['charon']['ikesa_table_segments'] = '4';
1693
	$ssconf['charon']['init_limit_half_open'] = '1000';
1694
	$ssconf['charon']['install_routes'] = 'no';
1695
	$ssconf['charon']['load_modular'] = 'yes';
1696
	$ssconf['charon']['ignore_acquire_ts'] = 'yes';
1697

    
1698
	if ($aggressive_mode_psk) {
1699
		$stronconf = '';
1700
		if (file_exists("{$g['varetc_path']}/ipsec/strongswan.conf")) {
1701
			$stronconf = file_get_contents("{$g['varetc_path']}/ipsec/strongswan.conf");
1702
		}
1703
		log_error("WARNING: Setting i_dont_care_about_security_and_use_aggressive_mode_psk option because a phase 1 is configured using aggressive mode with pre-shared keys. This is not a secure configuration.");
1704
		$restart = (!empty($stronconf) && strpos($stronconf, 'i_dont_care_about_security_and_use_aggressive_mode_psk') === FALSE);
1705
		unset($stronconf);
1706
		$ssconf['charon']['i_dont_care_about_security_and_use_aggressive_mode_psk'] = "yes";
1707
	}
1708

    
1709
	if (isset($config['ipsec']['acceptunencryptedmainmode'])) {
1710
		$ssconf['charon']['accept_unencrypted_mainmode_messages'] = "yes";
1711
	}
1712

    
1713
	if (isset($config['ipsec']['maxexchange'])) {
1714
		$ssconf['charon']['max_ikev1_exchanges'] = $config['ipsec']['maxexchange'];
1715
	}
1716

    
1717
	$unity_enabled = isset($config['ipsec']['unityplugin']) ? 'yes' : 'no';
1718
	$ssconf['charon']['cisco_unity'] = $unity_enabled;
1719

    
1720
	if (isset($config['ipsec']['enableinterfacesuse']) && !empty($ifacesuse)) {
1721
		$ssconf['charon']['interfaces_use'] = implode(',', array_unique($ifacesuse));
1722
	}
1723

    
1724
	if (isset($config['ipsec']['makebeforebreak'])) {
1725
		$ssconf['charon']['make_before_break'] = "yes";
1726
	}
1727

    
1728
	if (isset($config['ipsec']['port'])) {
1729
		$ssconf['charon']['port'] = $config['ipsec']['port'];
1730
	}
1731

    
1732
	if (isset($config['ipsec']['port_nat_t'])) {
1733
		$ssconf['charon']['port_nat_t'] = $config['ipsec']['port_nat_t'];
1734
	}
1735

    
1736
	$ssconf['charon']['syslog'] = array();
1737
	$ssconf['charon']['syslog']['identifier'] = 'charon';
1738
	$ssconf['charon']['syslog'][] = "# log everything under daemon since it ends up in the same place regardless with our syslog.conf";
1739
	$ssconf['charon']['syslog']['daemon'] = array();
1740
	$ssconf['charon']['syslog']['daemon']['ike_name'] = 'yes';
1741
	$ssconf['charon']['syslog']['daemon'] = array_merge($ssconf['charon']['syslog']['daemon'], ipsec_logging_config());
1742
	$ssconf['charon']['syslog'][] = '# disable logging under auth so logs aren\'t duplicated';
1743
	$ssconf['charon']['syslog']['auth'] = array();
1744
	$ssconf['charon']['syslog']['auth']['default'] = -1;
1745

    
1746
	$ssconf['charon']['plugins'] = array();
1747
	$ssconf['charon']['plugins'][] = "# Load defaults";
1748
	$ssconf['charon']['plugins'][] = "include {$g['varetc_path']}/ipsec/strongswan.d/charon/*.conf";
1749
	$ssconf['charon']['plugins']['unity'] = array('load' => $unity_enabled);
1750
	$ssconf['charon']['plugins']['curve25519'] = array('load' => "yes");
1751

    
1752
	if (isset($config['ipsec']['pkcs11support'])) {
1753
		$ssconf['charon']['plugins']['pkcs11'] = array();
1754
		$ssconf['charon']['plugins']['pkcs11']['load'] = "yes";
1755
		$ssconf['charon']['plugins']['pkcs11']['modules'] = array();
1756
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc'] = array();
1757
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc']['load_certs'] = "yes";
1758
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc']['path'] = "/usr/local/lib/opensc-pkcs11.so";
1759
	}
1760

    
1761
	/* Find RADIUS servers designated for Mobile IPsec user auth */
1762
	$radius_servers = array();
1763
	foreach (explode(',', $config['ipsec']['client']['user_source']) as $user_source) {
1764
		$auth_server = auth_get_authserver($user_source);
1765
		$nice_user_source = strtolower(preg_replace('/[\s\.]+/', '_', $user_source));
1766
		if ($auth_server && ($auth_server['type'] === 'radius')) {
1767
			$radius_servers[$nice_user_source] = array();
1768
			$radius_servers[$nice_user_source]['address'] = $auth_server['host'];
1769
			$radius_servers[$nice_user_source]['secret'] = "\"{$auth_server['radius_secret']}\"";
1770
			$radius_servers[$nice_user_source]['auth_port'] = empty($auth_server['radius_auth_port']) ? 1812 : $auth_server['radius_auth_port'];;
1771
			$radius_servers[$nice_user_source]['acct_port'] = empty($auth_server['radius_acct_port']) ? 1813 : $auth_server['radius_acct_port'];
1772
		}
1773
	}
1774

    
1775
	/* Generate an eap-radius config section if appropriate */
1776
	if (count($radius_servers) && ($mobile_ipsec_auth === "eap-radius")) {
1777
		$ssconf['charon']['plugins']['eap-radius'] = array();
1778
		$ssconf['charon']['plugins']['eap-radius']['load'] = "2";
1779
		$ssconf['charon']['plugins']['eap-radius']['class_group'] = "yes";
1780
		$ssconf['charon']['plugins']['eap-radius']['eap_start'] = "no";
1781
		/* Activate RADIUS accounting only if it was selected on the IPsec Mobile Clients tab */
1782
		if ($auth_server && isset($auth_server['radius_acct_port']) &&
1783
		    (is_array($a_client) && ($a_client['radiusaccounting'] == "enabled"))) {
1784
			$ssconf['charon']['plugins']['eap-radius']['accounting'] = "yes";
1785
			$ssconf['charon']['plugins']['eap-radius']['accounting_close_on_timeout'] = "no";
1786
		}
1787
		/* advanced parameters, see https://redmine.pfsense.org/issues/11211 */
1788
		if (isset($a_client['radius_retransmit_base'])) {
1789
			$ssconf['charon']['plugins']['eap-radius']['retransmit_base'] = $a_client['radius_retransmit_base'];
1790
		}
1791
		if (isset($a_client['radius_retransmit_timeout'])) {
1792
			$ssconf['charon']['plugins']['eap-radius']['retransmit_timeout'] = $a_client['radius_retransmit_timeout'];
1793
		}
1794
		if (isset($a_client['radius_retransmit_tries'])) {
1795
			$ssconf['charon']['plugins']['eap-radius']['retransmit_tries'] = $a_client['radius_retransmit_tries'];
1796
		}
1797
		if (isset($a_client['radius_sockets'])) {
1798
			$ssconf['charon']['plugins']['eap-radius']['sockets'] = $a_client['radius_sockets'];
1799
		}
1800
		$ssconf['charon']['plugins']['eap-radius']['servers'] = $radius_servers;
1801
	}
1802

    
1803
	if (is_array($a_client) && isset($a_client['enable'])) {
1804
		if ($a_client['user_source'] != "none") {
1805
			$ssconf['charon']['plugins']['xauth-generic'] = array();
1806
			$ssconf['charon']['plugins']['xauth-generic']['script'] = "/etc/inc/ipsec.auth-user.php";
1807
			$authcfgs = array();
1808
			foreach (explode(",", $a_client['user_source']) as $authcfg) {
1809
				$authcfgs[] = ($authcfg == "system") ? "Local Database" : $authcfg;
1810
			}
1811
			$ssconf['charon']['plugins']['xauth-generic']['authcfg'] = implode(",", $authcfgs);
1812
		}
1813

    
1814
		$ssconf['charon']['plugins']['attr'] = array();
1815

    
1816
		$rightdnsservers = array();
1817
		if (!empty($a_client['dns_server1'])) {
1818
			$rightdnsservers[] = $a_client['dns_server1'];
1819
		}
1820
		if (!empty($a_client['dns_server2'])) {
1821
			$rightdnsservers[] = $a_client['dns_server2'];
1822
		}
1823
		if (!empty($a_client['dns_server3'])) {
1824
			$rightdnsservers[] = $a_client['dns_server3'];
1825
		}
1826
		if (!empty($a_client['dns_server4'])) {
1827
			$rightdnsservers[] = $a_client['dns_server4'];
1828
		}
1829
		if (count($rightdnsservers)) {
1830
			$ssconf['charon']['plugins']['attr']['dns'] = implode(',', $rightdnsservers);
1831
		}
1832

    
1833
		$cfgservers = array();
1834
		if (!empty($a_client['wins_server1'])) {
1835
			$cfgservers[] = $a_client['wins_server1'];
1836
		}
1837
		if (!empty($a_client['wins_server2'])) {
1838
			$cfgservers[] = $a_client['wins_server2'];
1839
		}
1840
		if (!empty($cfgservers)) {
1841
			$ssconf['charon']['plugins']['attr']['nbns'] = implode(',', $cfgservers);
1842
		}
1843
		unset($cfgservers);
1844

    
1845
		$net_list = array();
1846
		if (isset($a_client['net_list']) && is_array($a_phase2)) {
1847
			foreach ($a_phase2 as $ph2ent) {
1848
				if (isset($ph2ent['disabled']) ||
1849
				    !isset($ph2ent['mobile'])) {
1850
					continue;
1851
				}
1852
				$nlent = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
1853
				if (is_subnet($nlent)) {
1854
					$net_list[] = $nlent;
1855
				}
1856
				unset($nlent);
1857
			}
1858
		}
1859

    
1860
		if (!empty($net_list)) {
1861
			$ssconf['charon']['plugins']['attr']['subnet'] = implode(',', $net_list);
1862
			$ssconf['charon']['plugins']['attr']['split-include'] = implode(',', $net_list);
1863
		}
1864

    
1865
		if (!empty($a_client['dns_domain'])) {
1866
			$ssconf['charon']['plugins']['attr'][] = "# Search domain and default domain";
1867
			$ssconf['charon']['plugins']['attr']['27674'] = "\"{$a_client['dns_domain']}\"";
1868
			if (empty($a_client['dns_split'])) {
1869
				$ssconf['charon']['plugins']['attr']['27675'] = "\"{$a_client['dns_domain']}\"";
1870
			}
1871
		}
1872

    
1873
		if (!empty($a_client['dns_split'])) {
1874
			$ssconf['charon']['plugins']['attr'][] = "# Split DNS";
1875
			$ssconf['charon']['plugins']['attr']['28675'] = "\"{$a_client['dns_split']}\"";
1876
		}
1877

    
1878
		if (!empty($a_client['login_banner'])) {
1879
			$ssconf['charon']['plugins']['attr'][] = "# Login Banner";
1880
			$ssconf['charon']['plugins']['attr']['28672'] = "\"{$a_client['login_banner']}\"";
1881
		}
1882

    
1883
		if (isset($a_client['save_passwd'])) {
1884
			$ssconf['charon']['plugins']['attr'][] = "# Save Xauth Password";
1885
			$ssconf['charon']['plugins']['attr']['28673'] = "1";
1886
		}
1887

    
1888
		if ($a_client['pfs_group']) {
1889
			$ssconf['charon']['plugins']['attr'][] = "# Phase2 PFS Group";
1890
			$ssconf['charon']['plugins']['attr']['28679'] = "\"{$a_client['pfs_group']}\"";
1891
		}
1892
	}
1893

    
1894
	@file_put_contents("{$g['varetc_path']}/ipsec/strongswan.conf", ipsec_strongswan_confgen($ssconf));
1895
}
1896

    
1897
/****f* ipsec/ipsec_setup_pools
1898
 * NAME
1899
 *   ipsec_setup_pools - Generate primary mobile pool configuration for swanctl
1900
  * INPUTS
1901
 *   None
1902
 * RESULT
1903
 *   Adds configured mobile pool settings to $scconf
1904
 * NOTES
1905
 *   These values were formerly in strongswan.conf but may now be configured in
1906
 *   pools, making future expansion to support multiple pools possible.
1907
 ******/
1908
function ipsec_setup_pools() {
1909
	global $config, $g, $mobile_ipsec_auth, $a_client, $a_phase2, $scconf;
1910
	if (!is_array($a_client) || !isset($a_client['enable'])) {
1911
		return;
1912
	}
1913
	if (($mobile_ipsec_auth == "eap-radius") && empty($a_client['pool_address']) &&
1914
	    empty($a_client['pool_address_v6'])) {
1915
		return;
1916
	}
1917

    
1918
	/* Keep the comment in the array to ensure the entry makes it into the
1919
	 * config in all cases.
1920
	 * See https://redmine.pfsense.org/issues/11891 */
1921
	$scconf['mobile-pool'] = array("# Mobile pool settings template");
1922
	$scconf['pools'] = array();
1923
	$pool_common =& $scconf['mobile-pool'];
1924

    
1925
	if (!empty($a_client['pool_address'])) {
1926
		$scconf['pools']['mobile-pool-v4 : mobile-pool'] = array();
1927
		$v4pool =& $scconf['pools']['mobile-pool-v4 : mobile-pool'];
1928
		$v4pool['addrs'] = "{$a_client['pool_address']}/{$a_client['pool_netbits']}";
1929
	}
1930
	if (!empty($a_client['pool_address_v6'])) {
1931
		$scconf['pools']['mobile-pool-v6 : mobile-pool'] = array();
1932
		$v6pool =& $scconf['pools']['mobile-pool-v6 : mobile-pool'];
1933
		$v6pool['addrs'] = "{$a_client['pool_address_v6']}/{$a_client['pool_netbits_v6']}";
1934
	}
1935

    
1936
	return;
1937
}
1938

    
1939
/****f* ipsec/ipsec_setup_userpools
1940
 * NAME
1941
 *   ipsec_setup_userpools - Generate per-user custom pool settings for swanctl
1942
  * INPUTS
1943
 *   None
1944
 * RESULT
1945
 *   Adds configured per-user pool settings to $scconf using the primary mobile
1946
 *   pool as a base configuration.
1947
 * NOTES
1948
 *   Given this new flexible format, it is now possible to override any valid
1949
 *   pool setting, so future expansion of per-user settings is possible.
1950
 ******/
1951
function ipsec_setup_userpools() {
1952
	global $config, $scconf;
1953
	$a_mobilekey = $config['ipsec']['mobilekey'];
1954

    
1955
	/* Do not waste time if we do not have all the necessary information. */
1956
	if (!is_array($a_mobilekey) ||
1957
	    empty($a_mobilekey) ||
1958
	    !is_array($scconf['connections']) ||
1959
	    !is_array($scconf['con-mobile-defaults']) ||
1960
	    !is_array($scconf['pools']) ||
1961
	    !is_array($scconf['mobile-pool'])) {
1962
		return;
1963
	}
1964

    
1965
	$suffix = 1;
1966
	foreach ($a_mobilekey as $mkent) {
1967
		if (($mkent['type'] != "EAP") ||
1968
		    !isset($mkent['ident_type']) ||
1969
		    !isset($mkent['pool_address']) ||
1970
		    !isset($mkent['pool_netbits']) ||
1971
		    (strlen($mkent['pool_address']) < 1) ||
1972
		    !is_ipaddr($mkent['pool_address'])) {
1973
			continue;
1974
		}
1975
		/* The name of just this pool */
1976
		$upbase = "mobile-userpool-{$suffix}";
1977
		/* The full connection name including a reference to the primary
1978
		 * mobile connection */
1979
		$upconn = "con-{$upbase} : con-mobile-defaults";
1980
		/* The full pool name including a reference to the primary
1981
		 * mobile pool */
1982
		$upname = "{$upbase} : mobile-pool";
1983

    
1984
		$scconf['connections'][$upconn] = array();
1985
		$scconf['pools'][$upname] = array();
1986

    
1987
		$clientid = (in_array($mkent['ident_type'], array('auto', 'none'))) ? "\"{$mkent['ident']}\"" : "{$mkent['ident_type']}:{$mkent['ident']}";
1988
		$clienteapid = ($ph1ent['authentication_method'] == "eap-mschapv2") ? $clientid : '%any';
1989

    
1990
		/* Craft a cloned connection with the ID information to match */
1991
		$scconf['connections'][$upconn]['remote'] = array();
1992
		$scconf['connections'][$upconn]['remote']['id'] = $clientid;
1993
		$scconf['connections'][$upconn]['remote']['eap_id'] = $clienteapid;
1994
		$scconf['connections'][$upconn]['pools'] = $upbase;
1995

    
1996
		/* Craft a cloned pool with pool settings to override for this user */
1997
		$scconf['pools'][$upname]['addrs'] = "{$mkent['pool_address']}/{$mkent['pool_netbits']}";
1998
		if (isset($mkent['dns_address']) && strlen($mkent['dns_address']) > 0 && is_ipaddr($mkent['dns_address'])) {
1999
			$scconf['pools'][$upname]['dns'] = $mkent['dns_address'];
2000
		}
2001
		$suffix++;
2002
	}
2003
	return;
2004
}
2005

    
2006
/****f* ipsec/ipsec_setup_bypass
2007
 * NAME
2008
 *   ipsec_setup_bypass - Generate a bypass connection for LAN-LAN and custom rules traffic
2009
 * INPUTS
2010
 *   None
2011
 * RESULT
2012
 *   Sets up a bypass connection to prevent local traffic from being caught by
2013
 *   IPsec policies.
2014
 ******/
2015
function ipsec_setup_bypass($gateways_status) {
2016
	global $config, $scconf;
2017

    
2018
	$scconf['connections']['bypass'] = array();
2019
	/* Prevents the connection from being considered for remote peers */
2020
	$scconf['connections']['bypass']['remote_addrs'] = "127.0.0.1";
2021
	$scconf['connections']['bypass']['children'] = array();
2022

    
2023
	/* Locate the LAN IPv4 and IPv6 subnets */
2024
	$bypassnets = array();
2025
	if ($config['interfaces']['lan']) {
2026
		$lanip = get_interface_ip("lan", $gateways_status);
2027
		if (!empty($lanip) && is_ipaddrv4($lanip)) {
2028
			$lansn = get_interface_subnet("lan");
2029
			$lansa = gen_subnetv4($lanip, $lansn);
2030
			if (!empty($lansa) && !empty($lansn)) {
2031
				$bypassnets[] = "{$lansa}/{$lansn}";
2032
			}
2033
		}
2034
		$lanip6 = get_interface_ipv6("lan", $gateways_status);
2035
		if (!empty($lanip6) && is_ipaddrv6($lanip6)) {
2036
			$lansn6 = get_interface_subnetv6("lan");
2037
			$lansa6 = gen_subnetv6($lanip6, $lansn6);
2038
			if (!empty($lansa6) && !empty($lansn6)) {
2039
				$bypassnets[] = "{$lansa6}/{$lansn6}";
2040
			}
2041
		}
2042
	}
2043
	/* If we have viable targets, setup a bypass LAN connection */
2044
	if (!empty($bypassnets) && !isset($config['ipsec']['noshuntlaninterfaces'])) {
2045
		$bypass = implode(',', $bypassnets);
2046
		$scconf['connections']['bypass']['children']['bypasslan'] = array();
2047
		$scconf['connections']['bypass']['children']['bypasslan']['local_ts'] = $bypass;
2048
		$scconf['connections']['bypass']['children']['bypasslan']['remote_ts'] = $bypass;
2049
		$scconf['connections']['bypass']['children']['bypasslan']['mode'] = "pass";
2050
		$scconf['connections']['bypass']['children']['bypasslan']['start_action'] = "trap";
2051
	}
2052

    
2053
	/* Setup custom bypass rules */
2054
	if ((isset($config['ipsec']['ipsecbypass']) && $config['ipsec']['bypassrules']) &&
2055
	    is_array($config['ipsec']['bypassrules'])) {
2056
		foreach ($config['ipsec']['bypassrules']['rule'] as $id => $rule) {
2057
			$scconf['connections']['bypass']['children']["rule{$id}"] = array();
2058
			$scconf['connections']['bypass']['children']["rule{$id}"]["local_ts"] = $rule['source'] .
2059
			       	"/" . $rule['srcmask'];
2060
			$scconf['connections']['bypass']['children']["rule{$id}"]["remote_ts"] = $rule['destination'] .
2061
			       	"/" . $rule['dstmask'];
2062
			$scconf['connections']['bypass']['children']["rule{$id}"]["mode"] = "pass";
2063
			$scconf['connections']['bypass']['children']["rule{$id}"]["start_action"] = "trap";
2064
		}
2065
	}
2066

    
2067
	return;
2068
}
2069

    
2070
/****f* ipsec/ipsec_setup_routes
2071
 * NAME
2072
 *   ipsec_setup_routes - Setup OS routing table static routes for remote peers.
2073
 *                        This ensures that IPsec connections are routed out of
2074
 *                        the expected interface on egress.
2075
 * INPUTS
2076
 *   $interface : The interface upon which routes will be configured.
2077
 *   $family    : The address family ('inet' or 'inet6')
2078
 *   $sourcehost: The local source address used for initiating connections.
2079
 *   $duplicates: If the ipsec tunnel allows duplicates remote peers
2080
 * RESULT
2081
 *   Static routes in the OS routing table for IPsec peers
2082
 ******/
2083
function ipsec_setup_routes($interface, $family, $sourcehost, $duplicates) {
2084
	if (substr($interface, 0, 4) == "_vip") {
2085
		$vpninterface = get_configured_vip_interface($interface);
2086
		if (substr($vpninterface, 0, 4) == "_vip") {
2087
			// vips are nested if its a ipalias with a carp parent
2088
			$vpninterface = get_configured_vip_interface($vpninterface);
2089
		}
2090
		$ifacesuse = get_real_interface($vpninterface);
2091
	} else {
2092
		$ifacesuse = get_failover_interface($interface);
2093
		if (substr($ifacesuse, 0, 4) == "_vip") {
2094
			$vpninterface = get_configured_vip_interface($ifacesuse);
2095
			$ifacesuse = get_real_interface($vpninterface);
2096
		} else {
2097
			$vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse);
2098
		}
2099
	}
2100
	if ($family == 'inet' && !empty($ifacesuse) &&
2101
	    interface_has_gateway($vpninterface)) {
2102
		$gatewayip = get_interface_gateway($vpninterface);
2103
		$interfaceip = get_interface_ip($vpninterface);
2104
		$subnet_bits = get_interface_subnet($vpninterface);
2105
		$subnet_ip = gen_subnetv4($interfaceip, $subnet_bits);
2106
		/*
2107
		 * if the remote gateway is in the local subnet, then don't add
2108
		 * a route
2109
		 */
2110
		if (is_ipaddrv4($sourcehost) &&
2111
		    !ip_in_subnet($sourcehost, "{$subnet_ip}/{$subnet_bits}") &&
2112
		    is_ipaddrv4($gatewayip) && !$duplicates) {
2113
			route_add_or_change($sourcehost, $gatewayip);
2114
		}
2115
	} else if ($family == 'inet6' && !empty($ifacesuse) &&
2116
	    interface_has_gatewayv6($vpninterface)) {
2117
		$gatewayip = get_interface_gateway_v6($vpninterface);
2118
		$interfaceip = get_interface_ipv6($vpninterface);
2119
		$subnet_bits = get_interface_subnetv6($vpninterface);
2120
		$subnet_ip = gen_subnetv6($interfaceip, $subnet_bits);
2121
		/*
2122
		 * if the remote gateway is in the local subnet, then don't add
2123
		 * a route
2124
		 */
2125
		if (is_ipaddrv6($sourcehost) &&
2126
		    !ip_in_subnet($sourcehost, "{$subnet_ip}/{$subnet_bits}") &&
2127
		    is_ipaddrv6($gatewayip) && !$duplicates) {
2128
			route_add_or_change($sourcehost, $gatewayip);
2129
		}
2130
	}
2131
	return $ifacesuse;
2132
}
2133

    
2134
/****f* ipsec/ipsec_setup_authentication
2135
 * NAME
2136
 *   ipsec_setup_authentication - Generate an array with local/remote
2137
 *                                authentication information for a given IPsec
2138
 *                                Phase 1.
2139
 * INPUTS
2140
 *   $ph1ent: An IPsec Phase 1 configuration
2141
 *   $conn  : A swanctl connection array corresponding to the IPsec Phase 1.
2142
 * RESULT
2143
 *   Populates $conn with local and remote arrays containing authentication
2144
 *   details.
2145
 ******/
2146
function ipsec_setup_authentication(& $ph1ent, & $conn, $gateways_status = false) {
2147
	global $rgmap, $ipsec_swanctl_dirs, $config;
2148
	$local = array();
2149
	$remote = array();
2150
	$remote2 = array();
2151

    
2152
	/* Fetch gateway status if not passed */
2153
	if (!is_array($gateways_status)) {
2154
		$gateways_status = return_gateways_status(true);
2155
	}
2156

    
2157
	list($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local', array(), $gateways_status);
2158
	$localid = ipsec_fixup_id($myid_type, $myid_data);
2159
	if (!empty($localid)) {
2160
		$local['id'] = $localid;
2161
	}
2162

    
2163
	// Only specify peer ID if we are not dealing with mobile PSK
2164
	if (!(isset($ph1ent['mobile']) &&
2165
	    in_array($ph1ent['authentication_method'], array("pre_shared_key", "xauth_psk_server")))) {
2166
		list ($remoteid_type, $remoteid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap, $gateways_status);
2167
		$remoteid = ipsec_fixup_id($remoteid_type, $remoteid_data);
2168
	}
2169
	if (!empty($remoteid)) {
2170
		$remote['id'] = $remoteid;
2171
	}
2172

    
2173
	if (!empty($ph1ent['caref'])) {
2174
		$ca = lookup_ca($ph1ent['caref']);
2175
		if ($ca) {
2176
			/* Get hash value to use for filename */
2177
			$ca_details = openssl_x509_parse(base64_decode($ca['crt']));
2178
			$cafn = "{$ipsec_swanctl_dirs['capath']}/{$ca_details['hash']}.0";
2179
		}
2180
	}
2181

    
2182
	$authentication = "";
2183
	switch ($ph1ent['authentication_method']) {
2184
		case 'eap-mschapv2':
2185
			if (isset($ph1ent['mobile'])) {
2186
				$local['auth'] = "pubkey";
2187
				$remote['eap_id'] = "%any";
2188
				$remote['auth'] = "eap-mschapv2";
2189
			}
2190
			break;
2191
		case 'eap-tls':
2192
			if (isset($ph1ent['mobile'])) {
2193
				$local['auth'] = "pubkey";
2194
				$remote['eap_id'] = "%any";
2195
			} else {
2196
				$local['auth'] = "eap-tls";
2197
			}
2198
			$remote['auth'] = "eap-tls";
2199
			break;
2200
		case 'eap-radius':
2201
			if (isset($ph1ent['mobile'])) {
2202
				$local['auth'] = "pubkey";
2203
				$remote['eap_id'] = "%any";
2204
			} else {
2205
				$local['auth'] = "eap-radius";
2206
			}
2207
			if (($config['ipsec']['client']['group_source'] == 'enabled') &&
2208
			    !empty($config['ipsec']['client']['auth_groups'])) {
2209
				$remote['groups'] = $config['ipsec']['client']['auth_groups'];
2210
			}
2211
			$remote['auth'] = "eap-radius";
2212
			break;
2213
		case 'xauth_cert_server':
2214
			$local['auth'] = "pubkey";
2215
			$remote['auth'] = "pubkey";
2216
			$remote2['auth'] = "xauth-generic";
2217
			break;
2218
		case 'xauth_psk_server':
2219
			$local['auth'] = "psk";
2220
			$remote['auth'] = "psk";
2221
			$remote2['auth'] = "xauth-generic";
2222
			break;
2223
		case 'pre_shared_key':
2224
			$local['auth'] = "psk";
2225
			$remote['auth'] = "psk";
2226
			break;
2227
		case 'cert':
2228
		case 'pkcs11':
2229
			$local['auth'] = "pubkey";
2230
			$remote['auth'] = "pubkey";
2231
			break;
2232
		case 'hybrid_cert_server':
2233
			$local['auth'] = "pubkey";
2234
			$remote['auth'] = "xauth-generic";
2235
			break;
2236
	}
2237
	if (in_array($ph1ent['authentication_method'], array('eap-mschapv2', 'eap-tls', 'eap-radius', 'xauth_cert_server', 'cert', 'hybrid_cert_server')) &&
2238
	    !empty($ph1ent['certref'])) {
2239
		$local['cert'] = array('file' => "{$ipsec_swanctl_dirs['certpath']}/cert-{$ph1ent['ikeid']}.crt");
2240
		$conn['send_cert'] = "always";
2241
	}
2242
	if ($ph1ent['authentication_method'] == 'pkcs11') {
2243
		$local['cert'] = array('handle' => "{$ph1ent['pkcs11certref']}");
2244
		$conn['send_cert'] = "always";
2245
	}
2246
	if (in_array($ph1ent['authentication_method'], array('eap-tls', 'xauth_cert_server', 'cert', 'pkcs11')) &&
2247
	    isset($cafn)) {
2248
		$remote['cacerts'] = $cafn;
2249
		if (isset($config['ipsec']['strictcrlpolicy'])) {
2250
			$remote['revocation'] = "strict";
2251
		}
2252
	}
2253

    
2254
	$conn['local'] = $local;
2255
	/* If there is data for a second remote auth round, setup two remote
2256
	 * arrays with unique names, otherwise setup a single remote. */
2257
	if (empty($remote2)) {
2258
		$conn['remote'] = $remote;
2259
	} else {
2260
		$conn['remote-1'] = $remote;
2261
		$conn['remote-2'] = $remote2;
2262
	}
2263
}
2264

    
2265
/****f* ipsec/ipsec_setup_proposal_algo
2266
 * NAME
2267
 *   ipsec_setup_proposal_algo - Form a single proposal algorithm string
2268
 * INPUTS
2269
 *   $ealg_id: Encryption algorithm ID
2270
 *   $keylen : Key length for the encryption algorithm
2271
 *   $halgo  : Hash algorithm
2272
 *   $modp   : DH Group number
2273
 * RESULT
2274
 *   Returns a string using the available information to form a single proposal
2275
 *   algorithm definition.
2276
 * NOTES
2277
 *   Values left empty will not be added to the string. Some combinations may
2278
 *   require one or more parts to be omitted.
2279
 ******/
2280
function ipsec_setup_proposal_algo($ealg_id, $keylen, $halgo, $prfalgo, $modp) {
2281
	$palgo = "";
2282

    
2283
	/* Add the encryption algorithm (if present) */
2284
	if (!empty($ealg_id)) {
2285
		$palgo .= "{$ealg_id}";
2286
	}
2287

    
2288
	/* Add the key length (if present) */
2289
	if (!empty($keylen)) {
2290
		$palgo .= "{$keylen}";
2291
	}
2292

    
2293
	/* Add the hash algorithm (if present) */
2294
	if (!empty($halgo)) {
2295
		/* If there is some content in the propsal already, add a
2296
		 * separator */
2297
		if (!empty($palgo)) {
2298
			$palgo .= "-";
2299
		}
2300
		$halgo = str_replace('hmac_', '', $halgo);
2301
		$palgo .= "{$halgo}";
2302
	}
2303

    
2304
	if (!empty($prfalgo)) {
2305
		$palgo .= "-prf{$prfalgo}";
2306
	}
2307

    
2308
	/* Convert the DH group to its keyword and add (if present) */
2309
	$modp = ipsec_convert_to_modp($modp);
2310
	if (!empty($modp)) {
2311
		$palgo .= "-{$modp}";
2312
	}
2313

    
2314
	return $palgo;
2315
}
2316

    
2317
/****f* ipsec/ipsec_setup_proposal_entry
2318
 * NAME
2319
 *   ipsec_setup_proposal_entry - Generate a full proposal string for an IPsec
2320
 *                                Phase 2 configuration.
2321
 * INPUTS
2322
 *   $ph2ent  : An IPsec Phase 2 configuration
2323
 *   $algo_arr: An array in which all proposal algorithms are collected
2324
 *   $ealg_id : Encryption algorithm ID
2325
 *   $keylen  : Key length for the encryption algorithm
2326
 * RESULT
2327
 *   Returns a string containing all proposal elements, and merges the entries
2328
 *   to $algo_arr as well.
2329
 ******/
2330
function ipsec_setup_proposal_entry(& $ph2ent, & $algo_arr, $ealg_id, $keylen) {
2331
	global $config, $p2_ealgos;
2332
	$proposal = array();
2333

    
2334
	/* If multiple hash algorithms are present, loop through and add them all. */
2335
	if (!empty($ph2ent['hash-algorithm-option']) && is_array($ph2ent['hash-algorithm-option']) 
2336
	    && !strpos($ealg_id, "gcm")) {
2337
		foreach ($ph2ent['hash-algorithm-option'] as $halgo) {
2338
			$proposal[] = ipsec_setup_proposal_algo($ealg_id, $keylen, $halgo, false, $ph2ent['pfsgroup']);
2339
		}
2340
	} else {
2341
		$proposal[] = ipsec_setup_proposal_algo($ealg_id, $keylen, false, false, $ph2ent['pfsgroup']);
2342
	}
2343

    
2344
	/* Add to master list */
2345
	$algo_arr = array_merge($algo_arr, $proposal);
2346
	return implode(',', $proposal);
2347
}
2348

    
2349
function ipsec_get_ifname($p1, $reqid = 0) {
2350
	global $config;
2351
	$ifname = "ipsec";
2352
	if ($reqid > 0) {
2353
		$ifname .= "{$reqid}";
2354
	} else {
2355
		$p2s = ipsec_get_phase2_by_ikeid($p1['ikeid']);
2356
		if (!empty($p2s)) {
2357
			$ifname .= $p2s[0]['reqid'];
2358
		}
2359
	}
2360
	return $ifname;
2361
}
2362

    
2363
function ipsec_get_ifname_by_conf($p1 = array(), $p2 = array()) {
2364
	global $config;
2365
	$have_p1 = (!empty($p1) && is_array($p1));
2366
	$have_p2 = (!empty($p2) && is_array($p2));
2367
	$reqid = null;
2368

    
2369
	if (!$have_p1 && $have_p2) {
2370
		$p1 = ipsec_get_phase1($p2['ikeid']);
2371
	}
2372

    
2373
	if ($have_p2) {
2374
		$reqid = $p2['reqid'];
2375
	}
2376

    
2377
	return ipsec_get_ifname($p1, $reqid);
2378
}
2379

    
2380
/****f* ipsec/ipsec_setup_vtireq
2381
 * NAME
2382
 *   ipsec_setup_vtireq - Setup a VTI type IPsec request
2383
 * INPUTS
2384
 *   $child                : A swanctl child array
2385
 *   $ipsec_vti_cleanup_ifs: An array of VTI interface names for later cleanup
2386
 *   $p1                   : The IKE config under which this child exists
2387
 *   $reqid                : The reqid of the P2 if known, otherwise the first P2 reqid for this P1 is looked up.
2388
 * RESULT
2389
 *   Sets up VTI-specific values for a request.
2390
 ******/
2391
function ipsec_setup_vtireq(& $child, & $ipsec_vti_cleanup_ifs, $p1, $reqid = 0) {
2392
	global $ipsec_reqid_base;
2393
	if ($reqid > 0) {
2394
		$child['reqid'] = $ipsec_reqid_base + $reqid;
2395
	} else {
2396
		$p2s = ipsec_get_phase2_by_ikeid($p1['ikeid']);
2397
		if (!empty($p2s)) {
2398
			$reqid = $p2s[0]['reqid'];
2399
			$child['reqid'] = $ipsec_reqid_base + $reqid;
2400
		} else {
2401
			return false;
2402
		}
2403
	}
2404
	/* This interface will be a valid IPsec interface, so remove it from the cleanup list. */
2405
	$ipsec_vti_cleanup_ifs = array_diff($ipsec_vti_cleanup_ifs, array(ipsec_get_ifname($p1, $reqid)));
2406
	$child['local_ts'] .= ",0.0.0.0/0,::/0";
2407
	$child['remote_ts'] .= ",0.0.0.0/0,::/0";
2408
	return true;
2409
}
2410

    
2411
/****f* ipsec/ipsec_setup_tunnels
2412
 * NAME
2413
 *   ipsec_setup_tunnels - Configure all P1/P2 entries as swanctl connections
2414
 * INPUTS
2415
 *   None
2416
 * RESULT
2417
 *   Sets up a swanctl array for all connections in the configuration along with
2418
 *   their children, authentication, etc.
2419
 ******/
2420
function ipsec_setup_tunnels($gateways_status = false) {
2421
	global $aggressive_mode_psk, $a_client, $config,
2422
		$filterdns_list, $g, $ifacesuse, $ipsec_idhandling, $ipsec_log_cats,
2423
		$ipsec_log_sevs, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs,
2424
		$ipseccfg, $mobile_ipsec_auth, $natfilterrules, $p1_ealgos,
2425
		$p2_ealgos, $rgmap, $sa, $sn, $scconf, $conn, $tunnels,
2426
		$ipsec_vti_cleanup_ifs, $conn_defaults;
2427

    
2428
	/* Fetch gateway status if not passed */
2429
	if (!is_array($gateways_status)) {
2430
		$gateways_status = return_gateways_status(true);
2431
	}
2432

    
2433
	foreach ($tunnels as $ph1ent) {
2434
		/* Skip disabled entries */
2435
		if (isset($ph1ent['disabled'])) {
2436
			continue;
2437
		}
2438
		/* If the local source is invalid, skip this entry. */
2439
		$local_spec = ipsec_get_phase1_src($ph1ent, $gateways_status);
2440
		if (!$local_spec) {
2441
			continue;
2442
		}
2443

    
2444
		/* Determine the name of this connection, either con-mobile for
2445
		 * mobile clients, or a name based on the IKE ID otherwise. */
2446
		if (isset($ph1ent['mobile'])) {
2447
			$cname = "con-mobile";
2448
			/* Start with common default values */
2449
			$scconf["{$cname}-defaults"] = $conn_defaults;
2450
			/* Array reference to make things easier */
2451
			$conn =& $scconf["{$cname}-defaults"];
2452
			$scconf['connections']["{$cname} : {$cname}-defaults"] = array("# Stub to load con-mobile-defaults");
2453
		} else {
2454
			$cname = ipsec_conid($ph1ent);
2455
			/* Start with common default values */
2456
			$scconf['connections'][$cname] = $conn_defaults;
2457
			$descr = "# P1 (ikeid {$ph1ent['ikeid']})";
2458
			if (!empty($ph1ent['descr'])) {
2459
				$descr .= ": {$ph1ent['descr']}";
2460
			}
2461
			array_unshift($scconf['connections'][$cname], $descr);
2462
			/* Array reference to make things easier */
2463
			$conn =& $scconf['connections'][$cname];
2464
		}
2465

    
2466
		/* Common parameters for all children */
2467
		$child_params = array();
2468
		if (!empty($ph1ent['closeaction'])) {
2469
			$child_params['close_action'] = $ph1ent['closeaction'];
2470
		}
2471

    
2472
		$ikeid = $ph1ent['ikeid'];
2473

    
2474
		$carpbackup = false;
2475
		if ((substr($ph1ent['interface'], 0, 4) == "_vip") &&
2476
		    in_array(get_carp_bind_status($ph1ent['interface']), array('BACKUP', 'INIT'))) {
2477
			$carpbackup = true;
2478
		}
2479

    
2480
		/* "trap" adds policies to start a tunnel when interesting
2481
		 * traffic is observed by the host. */
2482
		$start_action = "trap";
2483
		if ($carpbackup) {
2484
			$start_action = "none";
2485
		}
2486

    
2487
		/* Set the IKE version appropriately (empty = IKEv1) */
2488
		switch ($ph1ent['iketype']) {
2489
			case 'auto':
2490
				$ikeversion = 0;
2491
				break;
2492
			case 'ikev2':
2493
				$ikeversion = 2;
2494
				break;
2495
			case 'ikev1':
2496
			default:
2497
				$ikeversion = 1;
2498
				break;
2499
		}
2500
		$conn['version'] = $ikeversion;
2501

    
2502
		/* For IKEv1 or auto, setup aggressive mode if configured */
2503
		if ($ikeversion != 2){
2504
			$conn['aggressive'] = ($ph1ent['mode'] == "aggressive") ? "yes" : "no";
2505
		}
2506

    
2507
		if (isset($ph1ent['mobile'])) {
2508
			/* Mobile tunnels allow 'any' as a peer */
2509
			$remote_spec = "0.0.0.0/0,::/0";
2510
			/* Mobile tunnels cannot start automatically */
2511
			$start_action = 'none';
2512
		} else {
2513
			$remote_spec = $ph1ent['remote-gateway'];
2514
			$sourcehost = (is_ipaddr($remote_spec)) ? $remote_spec : $rgmap[$remote_spec];
2515
			$ifacesuse = ipsec_setup_routes($ph1ent['interface'], $ph1ent['protocol'], $sourcehost, isset($ph1ent['gw_duplicates']));
2516
		}
2517

    
2518
		/* Setup IKE proposals */
2519
		if (is_array($ph1ent['encryption']['item'])) {
2520
			$ciphers = array();
2521
			foreach($ph1ent['encryption']['item'] as $p1enc) {
2522
				if (!is_array($p1enc['encryption-algorithm']) ||
2523
						empty($p1enc['encryption-algorithm']['name']) ||
2524
						empty($p1enc['hash-algorithm'])) {
2525
					continue;
2526
				}
2527
				if ($ph1ent['prfselect_enable'] != 'yes') {
2528
					$p1enc['prf-algorithm'] = false;
2529
				}
2530
				$ciphers[] = ipsec_setup_proposal_algo($p1enc['encryption-algorithm']['name'],
2531
									$p1enc['encryption-algorithm']['keylen'],
2532
									$p1enc['hash-algorithm'],
2533
									$p1enc['prf-algorithm'],
2534
									$p1enc['dhgroup']);
2535
			}
2536
			$conn['proposals'] = implode(",", $ciphers);
2537
		}
2538

    
2539
		/* Configure DPD values. The DPD action is a per-child parameter,
2540
		 * not per-connection like the delay and timeout. */
2541
		if ($ph1ent['dpd_delay'] && $ph1ent['dpd_maxfail']) {
2542
			if ($start_action == "trap") {
2543
				$child_params['dpd_action'] = "trap";
2544
			} else {
2545
				$child_params['dpd_action'] = "clear";
2546
			}
2547
			$conn['dpd_delay'] = "{$ph1ent['dpd_delay']}s";
2548
			$conn['dpd_timeout'] =  $ph1ent['dpd_delay'] * ($ph1ent['dpd_maxfail'] + 1) . "s";
2549

    
2550
			/* Adjust dpd_action if the close_action is explicitly set */
2551
			if (!empty($child_params['close_action'])) {
2552
				switch ($ph1ent['closeaction']) {
2553
					case 'trap':
2554
						$child_params['dpd_action'] = 'trap';
2555
						break;
2556
					case 'start':
2557
						$child_params['dpd_action'] = 'restart';
2558
						break;
2559
					case 'none':
2560
					default:
2561
						$child_params['dpd_action'] = 'clear';
2562
				}
2563
			}
2564
		} else {
2565
			$child_params['dpd_action'] = "clear";
2566
		}
2567

    
2568
		/* Rekey (IKEv2 or Auto only, not supported by IKEv1) */
2569
		if (($ikeversion == 0) || ($ikeversion == 2)) {
2570
			$conn['rekey_time'] = ipsec_get_rekey_time($ph1ent) . "s";
2571
		}
2572

    
2573
		/* Reauth (Any) */
2574
		$conn['reauth_time'] = ipsec_get_reauth_time($ph1ent) . "s";
2575

    
2576
		/* Over Time */
2577
		$conn['over_time'] = ipsec_get_over_time($ph1ent) . "s";
2578

    
2579
		/* Rand Time */
2580
		$conn['rand_time'] = ipsec_get_rand_time($ph1ent) . "s";
2581

    
2582
		/* NAT Traversal */
2583
		$conn['encap'] = ($ph1ent['nat_traversal'] == 'force') ? "yes" : "no";
2584

    
2585
		/* MOBIKE support */
2586
		$conn['mobike'] = ($ph1ent['mobike'] == 'on') ? "yes" : "no";
2587

    
2588
		/* TFC Padding */
2589
		if (isset($ph1ent['tfc_enable'])) {
2590
			$conn['tfc_padding'] = (isset($ph1ent['tfc_bytes']) && is_numericint($ph1ent['tfc_bytes'])) ? $ph1ent['tfc_bytes'] : "mtu";
2591
		}
2592

    
2593
		/* Custom Ports */
2594
		if (isset($ph1ent['ikeport'])) {
2595
			/* For a connection without encapsulation, do not set local_port */
2596
			$conn['remote_port'] = $ph1ent['ikeport'];
2597
		} elseif (isset($ph1ent['nattport'])) {
2598
			/* For an encapsulated connection,
2599
			 * set local_port to the server NAT-T port value or default (4500) */
2600
			$conn['local_port'] = isset($config['ipsec']['port_nat_t']) ? $config['ipsec']['port_nat_t'] : 4500;
2601
			$conn['remote_port'] = $ph1ent['nattport'];
2602
		}
2603

    
2604
		/* Arrays for P2s/children */
2605
		$children = array();
2606
		$remote_ts_spec = array();
2607
		$local_ts_spec = array();
2608
		$reqids = array();
2609
		$has_vti = false;
2610
		$ealgoAHsp2arr = array();
2611
		$ealgoESPsp2arr = array();
2612

    
2613
		foreach ($ph1ent['p2'] as $ph2ent) {
2614
			/* If this entry is disabled, or cannot be configured, skip. */
2615
			if (isset($ph2ent['disabled']) ||
2616
			    (isset($ph2ent['mobile']) && !isset($a_client['enable']))) {
2617
				continue;
2618
			}
2619
			$child = array();
2620
			$local_ts = "";
2621
			$remote_ts = "";
2622
			if (($ph2ent['mode'] == 'tunnel') or ($ph2ent['mode'] == 'tunnel6')) {
2623
				/* Normal tunnel child config */
2624
				$child['mode'] = "tunnel";
2625
				$child['policies'] = "yes";
2626

    
2627
				$localid_type = $ph2ent['localid']['type'];
2628
				$localsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
2629

    
2630
				/* Do not print localid in some cases, such as a pure-psk or psk/xauth single phase2 mobile tunnel */
2631
				if (($localid_type == "none" || $localid_type == "mobile") &&
2632
				    isset($ph1ent['mobile']) && (ipsec_get_number_of_phase2($ikeid) == 1)) {
2633
					$local_spec = '0.0.0.0/0,::/0';
2634
				} else {
2635
					if ($localid_type != "address") {
2636
						$localid_type = "subnet";
2637
					}
2638
					// Don't let an empty subnet into config, it can cause parse errors. Ticket #2201.
2639
					if (!is_ipaddr($localsubnet_data) && !is_subnet($localsubnet_data) && ($localsubnet_data != "0.0.0.0/0")) {
2640
						log_error("Invalid IPsec Phase 2 \"{$ph2ent['descr']}\" - {$ph2ent['localid']['type']} has no subnet.");
2641
						continue;
2642
					}
2643
					if (!empty($ph2ent['natlocalid'])) {
2644
						$natlocalsubnet_data = ipsec_idinfo_to_cidr($ph2ent['natlocalid'], false, $ph2ent['mode']);
2645
						if ($ph2ent['natlocalid']['type'] != "address") {
2646
							if (is_subnet($natlocalsubnet_data)) {
2647
								$localsubnet_data = "{$natlocalsubnet_data}|{$localsubnet_data}";
2648
							}
2649
						} else {
2650
							if (is_ipaddr($natlocalsubnet_data)) {
2651
								$localsubnet_data = "{$natlocalsubnet_data}|{$localsubnet_data}";
2652
							}
2653
						}
2654
						$natfilterrules = true;
2655
					}
2656
				}
2657

    
2658
				$local_ts = $localsubnet_data;
2659

    
2660
				if (!isset($ph2ent['mobile'])) {
2661
					$remote_ts = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
2662
				} else if (!empty($a_client['pool_address'])) {
2663
					$remote_ts = "{$a_client['pool_address']}/{$a_client['pool_netbits']}";
2664
				}
2665

    
2666
			} elseif ($ph2ent['mode'] == 'vti') {
2667
				/* VTI-specific child config */
2668
				$child['policies'] = "no";
2669
				/* VTI cannot use trap policies, so start automatically instead */
2670
				$start_action = 'start';
2671
				if ($carpbackup) {
2672
					$start_action = "none";
2673
				}
2674
				if ($child_params['dpd_action'] == "trap") {
2675
					$child_params['dpd_action'] = "restart";
2676
				}
2677
				$localid_type = $ph2ent['localid']['type'];
2678
				$localsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
2679
				$local_ts = $localsubnet_data;
2680
				$remote_ts = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
2681
				$has_vti = true;
2682
			} else {
2683
				/* Transport mode child config */
2684
				$child['mode'] = "transport";
2685
				$child['policies'] = "yes";
2686

    
2687
				if ((($ph1ent['authentication_method'] == "xauth_psk_server") ||
2688
				    ($ph1ent['authentication_method'] == "pre_shared_key")) &&
2689
				    isset($ph1ent['mobile'])) {
2690
					$local_spec = "0.0.0.0/0,::/0";
2691
				} else {
2692
					$local_ts = ipsec_get_phase1_src($ph1ent, $gateways_status);
2693
				}
2694

    
2695
				if (!isset($ph2ent['mobile'])) {
2696
					$remote_ts = $remote_spec;
2697
				}
2698
			}
2699

    
2700
			if (!empty($local_ts)) {
2701
				$local_ts_spec[] = $local_ts;
2702
			}
2703
			if (!empty($remote_ts)) {
2704
				$remote_ts_spec[] = $remote_ts;
2705
			}
2706

    
2707
			/* If a PFS group is configured on the Mobile Clients tab,
2708
			 * and this is a mobile P2, use it here. */
2709
			if (isset($a_client['pfs_group']) && isset($ph2ent['mobile'])) {
2710
				$ph2ent['pfsgroup'] = $a_client['pfs_group'];
2711
			}
2712

    
2713
			$reqids[] = $ph2ent['reqid'];
2714

    
2715
			if (!empty($ph2ent['lifetime'])) {
2716
				$child['life_time'] = ipsec_get_life_time($ph2ent) . "s";
2717
				/* Rekey at 90% of lifetime */
2718
				$child['rekey_time'] = ipsec_get_rekey_time($ph2ent) . "s";
2719
				/* Random rekey fuzz time */
2720
				$child['rand_time'] = ipsec_get_rand_time($ph2ent) . "s";
2721
			}
2722

    
2723
			/* Set Child SA Start Action based on user preference, except
2724
			 * for invalid combinations such as 'trap' on VTI */
2725
			if (!isset($ph2ent['mobile']) && !$carpbackup &&
2726
			    !(($ph2ent['mode'] == 'vti') && ($ph1ent['startaction'] == 'trap'))) {
2727
				$start_action = !empty($ph1ent['startaction']) ? $ph1ent['startaction'] : $start_action;
2728
			}
2729
			$child['start_action'] = $start_action;
2730

    
2731
			/* Setup child SA proposals */
2732
			$proposal = array();
2733
			$ph2ent_ealgos = array();
2734
			$ph2ent_ealgos_aead = array();
2735
			if ($ph2ent['protocol'] == 'esp') {
2736
				if (is_array($ph2ent['encryption-algorithm-option'])) {
2737
					foreach ($ph2ent['encryption-algorithm-option'] as $ealg) {
2738
						if (strpos($ealg['name'], "gcm")) {
2739
							/* put AEAD ciphers on top, 
2740
							*  see https://redmine.pfsense.org/issues/11078 */
2741
							$ph2ent_ealgos_aead[] = $ealg;
2742
						} else {
2743
							$ph2ent_ealgos[] = $ealg;
2744
						}
2745
					}
2746
					$ph2ent_ealgos = array_merge(array_reverse($ph2ent_ealgos_aead), $ph2ent_ealgos);
2747
					foreach ($ph2ent_ealgos as $ealg) {
2748
						$ealg_id = $ealg['name'];
2749
						$ealg_kl = $ealg['keylen'];
2750

    
2751
						if (!empty($ealg_kl) && $ealg_kl == "auto") {
2752
							if (empty($p2_ealgos) || !is_array($p2_ealgos)) {
2753
								require_once("ipsec.inc");
2754
							}
2755
							$key_hi = $p2_ealgos[$ealg_id]['keysel']['hi'];
2756
							$key_lo = $p2_ealgos[$ealg_id]['keysel']['lo'];
2757
							$key_step = $p2_ealgos[$ealg_id]['keysel']['step'];
2758
							/* XXX: in some cases where include ordering is suspect these variables
2759
							 * are somehow 0 and we enter this loop forever and timeout after 900
2760
							 * seconds wrecking bootup */
2761
							if ($key_hi != 0 and $key_lo != 0 and $key_step != 0) {
2762
								for ($keylen = $key_hi; $keylen >= $key_lo; $keylen -= $key_step) {
2763
									$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoESPsp2arr, $ealg_id, $keylen);
2764
								}
2765
							}
2766
						} else {
2767
							$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoESPsp2arr, $ealg_id, $ealg_kl);
2768
						}
2769
					}
2770
				}
2771
			} else if ($ph2ent['protocol'] == 'ah') {
2772
				$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoAHsp2arr, '', '');
2773
			}
2774

    
2775
			/* Not mobile, and IKEv1 or Split Connections active */
2776
			if (!isset($ph1ent['mobile']) && (($ikeversion == 1) || isset($ph1ent['splitconn']))) {
2777
				if (!empty($remote_ts)) {
2778
					/* Setup child sub-connections using unique names */
2779
					$subconname = ipsec_conid($ph1ent, $ph2ent);
2780
					$children[$subconname] = $child;
2781

    
2782
					$descr = "# P2 (reqid {$ph2ent['reqid']})";
2783
					if (!empty($ph2ent['descr'])) {
2784
						$descr .= ": {$ph2ent['descr']}";
2785
					}
2786
					array_unshift($children[$subconname], $descr);
2787
					$children[$subconname]['local_ts'] = $local_ts;
2788
					$children[$subconname]['remote_ts'] = $remote_ts;
2789
					if ($has_vti) {
2790
						ipsec_setup_vtireq($children[$subconname], $ipsec_vti_cleanup_ifs, $ph1ent, $ph2ent['reqid']);
2791
					}
2792
					if (!empty($ph2ent['protocol']) && !empty($proposal)) {
2793
						$children[$subconname][$ph2ent['protocol'] . '_proposals'] = implode(',', $proposal);
2794
					}
2795
				} else {
2796
					log_error(sprintf(gettext("No phase2 specifications for tunnel with ikeid = %s"), $ikeid));
2797
				}
2798
			} else {
2799
				/* TODO: Fix this to nicely merge all P2 params for single child case */
2800
				if (!is_array($children[$cname])) {
2801
					$children[$cname] = array();
2802
				}
2803
				$children[$cname] = array_merge($children[$cname], $child);
2804

    
2805
				$descr = "# P2 (reqid {$ph2ent['reqid']})";
2806
				if (!empty($ph2ent['descr'])) {
2807
					$descr .= ": {$ph2ent['descr']}";
2808
				}
2809
				array_unshift($children[$cname], $descr);
2810
			}
2811
		}
2812

    
2813
		$conn['local_addrs'] = $local_spec;
2814
		$conn['remote_addrs'] = $remote_spec;
2815

    
2816
		$pools = array();
2817
		if (isset($ph1ent['mobile'])) {
2818
			if (($ph1ent['authentication_method'] == 'eap-radius') && 
2819
			    empty($a_client['pool_address']) && empty($a_client['pool_address_v6'])) {
2820
				$pools[] = "radius";
2821
			} else {
2822
				if (!empty($a_client['pool_address'])) {
2823
					$pools[] = "mobile-pool-v4";
2824
				}
2825
				if (!empty($a_client['pool_address_v6'])) {
2826
					$pools[] = "mobile-pool-v6";
2827
				}
2828
				if (isset($a_client['radius_ip_priority_enable'])) {
2829
					$pools[] .= "radius";
2830
				}
2831
			}
2832
		}
2833
		if (!empty($pools)) {
2834
			$conn['pools'] = implode(', ', $pools);
2835
		}
2836

    
2837
		/* For IKEv2 without Split Connections, setup combined sets of
2838
		 * local/remote traffic selectors and propsals */
2839
		if (!(!isset($ph1ent['mobile']) && (($ikeversion == 1) || isset($ph1ent['splitconn'])))) {
2840
			if (!isset($ph1ent['mobile']) && !empty($remote_ts_spec)) {
2841
				$children[$cname]['remote_ts'] = implode(",", $remote_ts_spec);
2842
			}
2843
			if (!empty($local_ts_spec)) {
2844
				$children[$cname]['local_ts'] = implode(",", $local_ts_spec);
2845
			}
2846
			if ($has_vti) {
2847
				ipsec_setup_vtireq($children[$cname], $ipsec_vti_cleanup_ifs, $ph1ent);
2848
			}
2849
			if (!empty($ealgoAHsp2arr)) {
2850
				$halgos = array();
2851
				$halgos_sha = array();
2852
				foreach ($ealgoAHsp2arr as $halg) {
2853
					if (strstr($halg, "sha")) {
2854
						/* put SHA ciphers on top, 
2855
						*  see https://redmine.pfsense.org/issues/12323 */
2856
						$halgos_sha[] = $halg;
2857
					} else {
2858
						$halgos[] = $halg;
2859
					}
2860
				}
2861
				$ealgoAHsp2arr = array_merge(array_reverse($halgos_sha), $halgos);
2862
				$children[$cname]['ah_proposals'] = implode(',', array_unique($ealgoAHsp2arr));
2863
			}
2864
			if (!empty($ealgoESPsp2arr)) {
2865
				$children[$cname]['esp_proposals'] = implode(',', array_unique($ealgoESPsp2arr));
2866
			}
2867
		}
2868

    
2869
		/* Setup connection authentication */
2870
		ipsec_setup_authentication($ph1ent, $conn, $gateways_status);
2871

    
2872
		/* Add children to this connection, including default child parameters */
2873
		if (count($children)) {
2874
			foreach($children as $name => $child) {
2875
				$conn['children'][$name] = array_merge($child, $child_params);
2876
			}
2877
		}
2878
		unset ($ph2ent);
2879
	}
2880

    
2881
	return;
2882
}
2883

    
2884
/****f* ipsec/ipsec_setup_secrets
2885
 * NAME
2886
 *   ipsec_setup_secrets - Setup swanctl authentication secrets
2887
 * INPUTS
2888
 *   None
2889
 * RESULT
2890
 *   Returns a swanctl array containing secrets (PSKs, certs, etc) and writes out
2891
 *   necessary CA, CRL, and certificate data.
2892
 ******/
2893
function ipsec_setup_secrets($gateways_status = false) {
2894
	global $config, $a_phase1, $ipsec_swanctl_dirs, $ipseccfg, $rgmap, $scconf;
2895

    
2896
	$suffix = 0;
2897

    
2898
	/* Fetch gateway status if not passed */
2899
	if (!is_array($gateways_status)) {
2900
		$gateways_status = return_gateways_status(true);
2901
	}
2902

    
2903
	$vpncas = array();
2904
	if (is_array($a_phase1) && count($a_phase1)) {
2905
		foreach ($a_phase1 as $ph1ent) {
2906
			if (isset($ph1ent['disabled'])) {
2907
				continue;
2908
			}
2909

    
2910
			if (isset($ph1ent['mobile'])) {
2911
				if ($ph1ent['authentication_method'] == 'pre_shared_key') {
2912
					$mobilepsk = true;
2913
				} elseif ($ph1ent['authentication_method'] == 'eap-mschapv2') {
2914
					$mobileeap = true;
2915
				}
2916
			}
2917

    
2918
			if (strstr($ph1ent['authentication_method'], 'cert') ||
2919
			    in_array($ph1ent['authentication_method'], array('eap-mschapv2', 'eap-tls', 'eap-radius'))) {
2920
				/* Write certificate and private key, point to private key */
2921
				$certline = '';
2922

    
2923
				$ikeid = $ph1ent['ikeid'];
2924
				$cert = lookup_cert($ph1ent['certref']);
2925

    
2926
				if (!$cert) {
2927
					log_error(sprintf(gettext("Error: Invalid phase1 certificate reference for %s"), $ph1ent['name']));
2928
					continue;
2929
				}
2930

    
2931
				/* add signing CA cert chain of server cert
2932
				 * to the list of CAs to write
2933
				 */
2934
				$cachain = ca_chain_array($cert);
2935
				if ($cachain && is_array($cachain)) {
2936
					foreach ($cachain as $cacrt) {
2937
						$vpncas[$cacrt['refid']] = $cacrt;
2938
					}
2939
				}
2940

    
2941
				@chmod($ipsec_swanctl_dirs['certpath'], 0600);
2942

    
2943
				$ph1keyfile = "{$ipsec_swanctl_dirs['keypath']}/cert-{$ikeid}.key";
2944
				if (!file_put_contents($ph1keyfile, base64_decode($cert['prv']))) {
2945
					log_error(sprintf(gettext("Error: Cannot write phase1 key file for %s"), $ph1ent['name']));
2946
					continue;
2947
				}
2948
				@chmod($ph1keyfile, 0600);
2949

    
2950
				$ph1certfile = "{$ipsec_swanctl_dirs['certpath']}/cert-{$ikeid}.crt";
2951
				if (!file_put_contents($ph1certfile, base64_decode($cert['crt']))) {
2952
					log_error(sprintf(gettext("Error: Cannot write phase1 certificate file for %s"), $ph1ent['name']));
2953
					@unlink($ph1keyfile);
2954
					continue;
2955
				}
2956
				@chmod($ph1certfile, 0600);
2957

    
2958
				$scconf['secrets']['private-' . $suffix++] = array('file' => $ph1keyfile);
2959
			} else if (strstr($ph1ent['authentication_method'], 'pkcs11')) {
2960
				$p11_id = array();
2961
				$output = shell_exec('/usr/local/bin/pkcs15-tool -c');
2962
				preg_match_all('/ID\s+: (.*)/', $output, $p11_id);
2963
				if (!empty($ph1ent['pkcs11certref']) && in_array($ph1ent['pkcs11certref'], $p11_id[1])) {
2964
					$scconf['secrets']['token-' . $suffix++] = array(
2965
						'handle' => $ph1ent['pkcs11certref'],
2966
						'pin' => $ph1ent['pkcs11pin'],
2967
					);
2968
				} else {
2969
					log_error(sprintf(gettext("Error: Invalid phase1 PKCS#11 certificate reference or PKCS#11 is not present for %s"), $ph1ent['name']));
2970
					continue;
2971
				}
2972
			} else {
2973
				/* Setup pre-shared keys */
2974
				list($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local', array(), $gateways_status);
2975
				list($peerid_type, $peerid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap, $gateways_status);
2976
				$myid = trim($myid_data);
2977

    
2978
				if (empty($peerid_data)) {
2979
					continue;
2980
				}
2981

    
2982
				$myid = isset($ph1ent['mobile']) ? ipsec_fixup_id($myid_type, trim($myid_data)) : "%any";
2983
				$peerid = ($peerid_data != 'allusers') ? ipsec_fixup_id($peerid_type, trim($peerid_data)) : '';
2984

    
2985
				if (!empty($ph1ent['pre-shared-key'])) {
2986
					$scconf['secrets']['ike-' . $suffix++] = array(
2987
						'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
2988
						'id-0' => $myid,
2989
						'id-1' => $peerid,
2990
					);
2991
					if (isset($ph1ent['mobile'])) {
2992
						$scconf['secrets']['ike-' . $suffix++] = array(
2993
							'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
2994
							'id-0' => $myid,
2995
							'id-1' => '%any',
2996
						);
2997
						$scconf['secrets']['ike-' . $suffix++] = array(
2998
							'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
2999
						);
3000
					}
3001
				}
3002
			}
3003

    
3004
			/* if the client authenticates with a cert add the
3005
			 * client cert CA chain to the list of CAs to write
3006
			 */
3007
			if (in_array($ph1ent['authentication_method'],
3008
			    array('cert', 'eap-tls', 'xauth_cert_server', 'pkcs11'))) {
3009
				if (!empty($ph1ent['caref']) && !array_key_exists($ph1ent['caref'], $vpncas)) {
3010
					$thisca = lookup_ca($ph1ent['caref']);
3011
					$vpncas[$ph1ent['caref']] = $thisca;
3012
					/* follow chain up to root */
3013
					$cachain = ca_chain_array($thisca);
3014
					if ($cachain and is_array($cachain)) {
3015
						foreach ($cachain as $cacrt) {
3016
							$vpncas[$cacrt['refid']] = $cacrt;
3017
						}
3018
					}
3019
				}
3020
			}
3021
		}
3022
	}
3023

    
3024
	/* Write the required CAs */
3025
	foreach ($vpncas as $carefid => $cadata) {
3026
		$cacrt = base64_decode($cadata['crt']);
3027
		$cacrtattrs = openssl_x509_parse($cacrt);
3028
		if (!is_array($cacrtattrs) || !isset($cacrtattrs['hash'])) {
3029
			log_error(sprintf(gettext("Error: Invalid certificate hash info for %s"), $cadata['descr']));
3030
			continue;
3031
		}
3032
		$cafilename = "{$ipsec_swanctl_dirs['capath']}/{$cacrtattrs['hash']}.0";
3033
		if (!@file_put_contents($cafilename, $cacrt)) {
3034
				log_error(sprintf(gettext("Error: Cannot write IPsec CA file for %s"), $cadata['descr']));
3035
				continue;
3036
		}
3037
	}
3038

    
3039
	/* write out CRL files */
3040
	if (is_array($config['crl']) && count($config['crl']) && !empty($vpncas)) {
3041
		foreach ($config['crl'] as $crl) {
3042
			if (!isset($crl['text'])) {
3043
				log_error(sprintf(gettext("Warning: Missing CRL data for %s"), $crl['descr']));
3044
				continue;
3045
			}
3046
			$fpath = "{$ipsec_swanctl_dirs['crlpath']}/{$crl['refid']}.crl";
3047
			if (!@file_put_contents($fpath, base64_decode($crl['text']))) {
3048
				log_error(sprintf(gettext("Error: Cannot write IPsec CRL file for %s"), $crl['descr']));
3049
				continue;
3050
			}
3051
		}
3052
	}
3053

    
3054
	/* Add user PSKs */
3055
	if ($mobilepsk && is_array($config['system']) && is_array($config['system']['user'])) {
3056
		foreach ($config['system']['user'] as $user) {
3057
			if (!empty($user['ipsecpsk'])) {
3058
				$scconf['secrets']['ike-' . $suffix++] = array(
3059
					'secret' => '0s' . base64_encode(trim($user['ipsecpsk'])),
3060
					'id-0' => $myid,
3061
					'id-1' => $user['name'],
3062
				);
3063
			}
3064
		}
3065
		unset($user);
3066
	}
3067

    
3068
	/* add PSKs/EAPs for mobile clients */
3069
	if (is_array($ipseccfg['mobilekey'])) {
3070
		foreach ($ipseccfg['mobilekey'] as $key) {
3071
			if (($mobileeap && ($key['type'] == 'EAP')) ||
3072
			    ($key['type'] == 'PSK')) {
3073
				if (($key['ident'] == 'allusers') ||
3074
				    ($key['ident'] == 'any')) {
3075
					$key['ident'] = '%any';
3076
				}
3077
				$userkeyprefix = (strtolower($key['type']) == 'eap') ? 'eap' : 'ike';
3078
				$scconf['secrets'][$userkeyprefix . '-' . $suffix++] = array(
3079
					'secret' => '0s' . base64_encode(trim($key['pre-shared-key'])),
3080
					'id-0' => $key['ident'],
3081
				);
3082
			}
3083
		}
3084
		unset($key);
3085
	}
3086
	return;
3087
}
3088

    
3089
/****f* ipsec/ipsec_configure
3090
 * NAME
3091
 *   ipsec_configure - Configure IPsec
3092
 * INPUTS
3093
 *   $restart: Boolean (default false), whether or not to restart the IPsec
3094
 *             daemons.
3095
 * RESULT
3096
 *   IPsec-related configuration files are written, daemon is started or stopped
3097
 *   appropriately.
3098
 ******/
3099
function ipsec_configure($restart = false) {
3100
	global $aggressive_mode_psk, $a_client, $a_phase1, $a_phase2, $config,
3101
		$filterdns_list, $g, $ifacesuse, $ipsec_idhandling, $ipsec_log_cats,
3102
		$ipsec_log_sevs, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs,
3103
		$ipseccfg, $mobile_ipsec_auth, $natfilterrules, $p1_ealgos,
3104
		$p2_ealgos, $rgmap, $sa, $sn, $scconf, $tunnels, $mobile_configured,
3105
		$ipsec_vti_cleanup_ifs, $conn_defaults, $pool_addrs;
3106

    
3107
	/* service may have been enabled, disabled, or otherwise changed in a
3108
	 *way requiring rule updates */
3109
	filter_configure();
3110

    
3111
	if (!ipsec_enabled()) {
3112
		/* IPsec is disabled */
3113
		/* Stop charon */
3114
		mwexec("/usr/local/sbin/strongswanrc stop");
3115
		/* Stop dynamic monitoring */
3116
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3117
		/* Wait for process to die */
3118
		sleep(2);
3119
		/* Stop PC/SC Smart Card Services */
3120
		killbyname("pcscd");
3121
		/* Shutdown enc0 interface*/
3122
		mwexec("/sbin/ifconfig enc0 down");
3123
		ipsec_gre_default_mtu(); 
3124
		return 0;
3125
	} else {
3126
		/* Startup enc0 interface */
3127
		mwexec("/sbin/ifconfig enc0 up");
3128
		/* PC/SC daemon must be started before strongswan */
3129
		if (isset($config['ipsec']['pkcs11support']) && !isvalidproc("pcscd")) {
3130
			if (platform_booting()) {
3131
				echo gettext("Starting PC/SC Smart Card Services...");
3132
			}
3133
			mwexec_bg("/usr/local/sbin/pcscd");
3134
			if (platform_booting()) {
3135
				echo gettext("done.\n");
3136
			}
3137
		} elseif (!isset($config['ipsec']['pkcs11support']) && isvalidproc("pcscd")) {
3138
			/* strongswan must be stopped first, otherwise it will flood the logs */
3139
			mwexec("/usr/local/sbin/strongswanrc stop");
3140
			killbyname("pcscd");
3141
		}
3142
	}
3143

    
3144
	if (platform_booting()) {
3145
		echo gettext("Configuring IPsec VPN... ");
3146
	}
3147

    
3148
	$ipsecstartlock = lock('ipsec', LOCK_EX);
3149

    
3150
	/* Prepare automatic ping_hosts.sh data */
3151
	unlink_if_exists("{$g['vardb_path']}/ipsecpinghosts");
3152
	touch("{$g['vardb_path']}/ipsecpinghosts");
3153
	$ipsecpinghostsactive = false;
3154

    
3155
	/* Populate convenience variables */
3156
	$syscfg = $config['system'];
3157
	init_config_arr(array('ipsec', 'phase1'));
3158
	$ipseccfg = $config['ipsec'];
3159
	$a_phase1 = $config['ipsec']['phase1'];
3160
	init_config_arr(array('ipsec', 'phase2'));
3161
	$a_phase2 = $config['ipsec']['phase2'];
3162
	init_config_arr(array('ipsec', 'client'));
3163
	$a_client = $config['ipsec']['client'];
3164

    
3165
	$mobile_configured = false;
3166

    
3167

    
3168
	/* Setup a single structured array to process, to avoid repeatedly
3169
	 * looping through the arrays to locate entries later. */
3170
	$tunnels = array();
3171
	foreach ($a_phase1 as $p1) {
3172
		if (empty($p1)) {
3173
			continue;
3174
		}
3175
		if (isset($p1['mobile']) && !isset($p1['disabled'])) {
3176
			$mobile_configured = true;
3177
		}
3178
		$tunnels[$p1['ikeid']] = $p1;
3179
		$tunnels[$p1['ikeid']]['p2'] = array();
3180
	}
3181
	foreach ($a_phase2 as $p2) {
3182
		$tunnels[$p2['ikeid']]['p2'][] = $p2;
3183
	}
3184

    
3185
	$ipsec_vti_cleanup_ifs = array();
3186
	$rgmap = array();
3187
	$filterdns_list = array();
3188
	$aggressive_mode_psk = false;
3189
	$mobile_ipsec_auth = "";
3190
	$ifacesuse = array();
3191
	$natfilterrules = false;
3192

    
3193
	/* Configure asynchronous crypto. See https://redmine.pfsense.org/issues/8772 */
3194
	set_sysctl(array('net.inet.ipsec.async_crypto' => (int) (isset($ipseccfg['async_crypto']) && ($ipseccfg['async_crypto'] == "enabled"))));
3195

    
3196
	/* Build a list of all IPsec interfaces configured on the firewall at the OS level */
3197
	$gateways_status = return_gateways_status(true);
3198
	foreach (get_interface_arr() as $thisif) {
3199
		if (substr($thisif, 0, 5) == "ipsec") {
3200
			$ipsec_vti_cleanup_ifs[] = $thisif;
3201
		}
3202
	}
3203
	/* Create directory structure for IPsec */
3204
	ipsec_create_dirs();
3205
	/* Setup gateways and interfaces */
3206
	ipsec_setup_gwifs($gateways_status);
3207
	/* Setup and write strongswan.conf */
3208
	ipsec_setup_strongswan();
3209
	/* Start Global Connection default values */
3210
	$conn_defaults = array();
3211
	/* Fragmentation is on for everyone */
3212
	$conn_defaults['fragmentation'] = "yes";
3213
	/* Default to 'replace' for unique IDs (was 'yes' in ipsec.conf previously) */
3214
	$conn_defaults['unique'] = 'replace';
3215
	/* If the configuration has a valid alternate value for unique ID handling,
3216
	 * use it instead. */
3217
	if (!empty($config['ipsec']['uniqueids']) &&
3218
	    array_key_exists($config['ipsec']['uniqueids'], $ipsec_idhandling)) {
3219
		$conn_defaults['unique'] = $config['ipsec']['uniqueids'];
3220
	}
3221
	/* Disable ipcomp for now. redmine #6167
3222
	if (isset($config['ipsec']['compression'])) {
3223
		$conn_defaults['compress'] = "yes";
3224
	}
3225
	set_single_sysctl('net.inet.ipcomp.ipcomp_enable', (isset($config['ipsec']['compression'])) ? 1 : 0);
3226
	*/
3227
	/* End Global Connection Defaults */
3228

    
3229
	/* Start swanctl configuration (scconf) */
3230
	$scconf = array();
3231
	$scconf[] = "# This file is automatically generated. Do not edit";
3232
	$scconf['connections'] = array();
3233
	/* Setup IPsec bypass */
3234
	ipsec_setup_bypass($gateways_status);
3235
	/* Setup connections */
3236
	ipsec_setup_tunnels($gateways_status);
3237
	$scconf['pools'] = array();
3238
	if ($mobile_configured) {
3239
		/* Setup mobile address pools */
3240
		ipsec_setup_pools();
3241
		/* Setup per-user pools */
3242
		ipsec_setup_userpools();
3243
	}
3244
	/* Setup secret data */
3245
	$scconf['secrets'] = array();
3246
	ipsec_setup_secrets($gateways_status);
3247

    
3248
	@file_put_contents("{$g['varetc_path']}/ipsec/swanctl.conf", ipsec_strongswan_confgen($scconf));
3249

    
3250
	/* Clean up unused VTI interfaces */
3251
	foreach ($ipsec_vti_cleanup_ifs as $cleanif) {
3252
		if (does_interface_exist($cleanif)) {
3253
			mwexec("/sbin/ifconfig " . escapeshellarg($cleanif) . " destroy", false);
3254
		}
3255
	}
3256

    
3257
	/* set default MTU to 1400 for GRE over IPsec, othewise to 1476 */
3258
	ipsec_gre_default_mtu(); 
3259

    
3260
	/* Manage process */
3261
	if ($restart === true) {
3262
		mwexec_bg("/usr/local/sbin/strongswanrc restart", false);
3263
	} else {
3264
		if (isvalidpid("{$g['varrun_path']}/charon.pid")) {
3265
			mwexec_bg("/usr/local/sbin/strongswanrc reload", false);
3266
		} else {
3267
			mwexec_bg("/usr/local/sbin/strongswanrc start", false);
3268
		}
3269
	}
3270

    
3271
	// Run ping_hosts.sh once if it's enabled to avoid wait for minicron
3272
	if ($ipsecpinghostsactive) {
3273
		mwexec_bg("/usr/local/bin/ping_hosts.sh");
3274
	}
3275

    
3276
	if ($natfilterrules == true) {
3277
		filter_configure();
3278
	}
3279
	/* start filterdns, if necessary */
3280
	if (count($filterdns_list) > 0) {
3281
		$interval = 60;
3282
		if (!empty($ipseccfg['dns-interval']) && is_numeric($ipseccfg['dns-interval'])) {
3283
			$interval = $ipseccfg['dns-interval'];
3284
		}
3285

    
3286
		$hostnames = "";
3287
		array_unique($filterdns_list);
3288
		foreach ($filterdns_list as $hostname) {
3289
			$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload ipsecdns\"'\n";
3290
		}
3291
		file_put_contents("{$g['varetc_path']}/ipsec/filterdns-ipsec.hosts", $hostnames);
3292
		unset($hostnames);
3293

    
3294
		if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid")) {
3295
			sigkillbypid("{$g['varrun_path']}/filterdns-ipsec.pid", "HUP");
3296
		} else {
3297
			mwexec_bg("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-ipsec.pid -i {$interval} -c {$g['varetc_path']}/ipsec/filterdns-ipsec.hosts -d 1");
3298
		}
3299
	} else {
3300
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3301
		@unlink("{$g['varrun_path']}/filterdns-ipsec.pid");
3302
	}
3303

    
3304
	if (platform_booting()) {
3305
		echo "done\n";
3306
	}
3307

    
3308
	unlock($ipsecstartlock);
3309
	return count($filterdns_list);
3310
}
3311

    
3312
function ipsec_gre_default_mtu() {
3313
	global $config;
3314

    
3315
	foreach ($config['interfaces'] as $if => $ifdetail) { 
3316
		if (interface_is_type($ifdetail['if'], 'gre') && !isset($ifdetail['mtu'])) {
3317
			if (is_greipsec($ifdetail['if'])) {
3318
				set_interface_mtu($ifdetail['if'], 1400);
3319
			} else {
3320
				set_interface_mtu($ifdetail['if'], 1476);
3321
			}
3322
		}
3323
	}
3324
}
3325

    
3326
/* Return the larger of derived SA rekey time and reauth time */
3327
function ipsec_get_renewmax($entry) {
3328
	if (empty($entry) || !is_array($entry)) {
3329
		return 0;
3330
	}
3331
	return max(ipsec_get_rekey_time($entry), ipsec_get_reauth_time($entry));
3332
}
3333

    
3334
/* Determine the life time of an SA entry (Hard upper total time limit for SA before it is removed) */
3335
function ipsec_get_life_time($entry) {
3336
	if (empty($entry) || !is_array($entry)) {
3337
		return 0;
3338
	}
3339
	/* Use a hardcoded value if present in the configuration */
3340
	if ($entry['lifetime'] > 0) {
3341
		return $entry['lifetime'];
3342
	}
3343
	/* If rekey or reauth are enabled, attempt to derive a lifetime from one of those */
3344
	$renewmax = ipsec_get_renewmax($entry);
3345
	if ($renewmax > 0) {
3346
		return intval($renewmax / 0.9);
3347
	}
3348
	/* To reach here, rekey_time and lifetime are both 0 which is invalid
3349
	 * Default to 16000 for p1 and 4000 for p2 */
3350
	if ($entry['iketype']) {
3351
		return 16000;
3352
	} else {
3353
		return 4000;
3354
	}
3355
}
3356

    
3357
/* Determine the rekey time of an SA entry (Time at which to rekey IKEv2 or Child SA entries) */
3358
function ipsec_get_rekey_time($entry) {
3359
	if (empty($entry) || !is_array($entry)) {
3360
		return 0;
3361
	}
3362
	/* Use a hardcoded value if present in the configuration */
3363
	if (strlen($entry['rekey_time'])) {
3364
		/* Check via strlen since 0 is a valid value */
3365
		return $entry['rekey_time'];
3366
	} elseif ($entry['lifetime'] > 0) {
3367
		/* If rekey_time is empty and lifetime is non-zero, use 90% lifetime */
3368
		return intval($entry['lifetime'] * 0.9);
3369
	}
3370
	/* To reach here, rekey_time and lifetime are empty
3371
	 * Default to 14400 for p1 and 3600 for p2 */
3372
	if ($entry['iketype']) {
3373
		return 14400;
3374
	} else {
3375
		return 3600;
3376
	}
3377
}
3378

    
3379
/* Determine the reauth time of an SA entry (IKE SA tear-down/reauthenticate) */
3380
function ipsec_get_reauth_time($entry) {
3381
	if (empty($entry) || !is_array($entry)) {
3382
		return 0;
3383
	}
3384
	/* Use a hardcoded value if present in the configuration */
3385
	if (strlen($entry['reauth_time'])) {
3386
		/* Check via strlen since 0 is a valid value */
3387
		return $entry['reauth_time'];
3388
	} elseif ($entry['lifetime'] > 0) {
3389
		/* If reauth_time is empty and lifetime is non-zero,
3390
		 * use 90% lifetime for IKEv1, disable for IKEv2/auto */
3391
		if ($entry['iketype'] == 'ikev1') {
3392
			return intval($entry['lifetime'] * 0.9);
3393
		} else {
3394
			return 0;
3395
		}
3396
	}
3397
	/* To reach here, rekey_time and lifetime are empty
3398
	 * Default to disabled (0) */
3399
	return 0;
3400
}
3401

    
3402
/* Determine the over time of an SA entry (Hard upper IKE SA time limit, relative to rekey/reauth time) */
3403
function ipsec_get_over_time($entry) {
3404
	if (empty($entry) || !is_array($entry)) {
3405
		return 0;
3406
	}
3407
	/* Automatically derive the value for rand_time */
3408
	$lifetime = ipsec_get_life_time($entry);
3409
	$renewmax = ipsec_get_renewmax($entry);
3410
	if (($lifetime > 0) && ($renewmax > 0)) {
3411
		/* If life time and rekey/reauth time both have values, subtract to get rand time */
3412
		return $lifetime - $renewmax;
3413
	} elseif ($lifetime > 0) {
3414
		/* If only life time has a value, use 10% of that */
3415
		return intval($lifetime * 0.1);
3416
	} elseif ($renewmax > 0) {
3417
		/* If only rekey/reauth time has a value, use 10% of that */
3418
		return intval($renewmax * 0.1);
3419
	}
3420
	/* No value can be determined, default to 0 */
3421
	return 0;
3422
}
3423

    
3424
/* Determine the rand time of an SA entry (random value subtracted from renewal time to prevent collisions) */
3425
function ipsec_get_rand_time($entry) {
3426
	if (empty($entry) || !is_array($entry)) {
3427
		return 0;
3428
	}
3429
	/* Use a hardcoded value if present in the configuration */
3430
	if (strlen($entry['rand_time'])) {
3431
		/* Check via strlen since 0 is a valid value */
3432
		return $entry['rand_time'];
3433
	}
3434
	/* Logic to automatically determine rand time is identical to calculating over time */
3435
	return ipsec_get_over_time($entry);
3436
}
3437

    
3438
?>
(26-26/61)