Project

General

Profile

Download (108 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-2022 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
	/* IKEv2 retransmit options, see https://redmine.pfsense.org/issues/12184 */
1737
	if (isset($config['ipsec']['ikev2_retransmit_tries'])) {
1738
		$ssconf['charon']['retransmit_tries'] = $config['ipsec']['ikev2_retransmit_tries'];
1739
	}
1740
	if (isset($config['ipsec']['ikev2_retransmit_timeout'])) {
1741
		$ssconf['charon']['retransmit_timeout'] = $config['ipsec']['ikev2_retransmit_timeout'];
1742
	}
1743
	if (isset($config['ipsec']['ikev2_retransmit_base'])) {
1744
		$ssconf['charon']['retransmit_base'] = $config['ipsec']['ikev2_retransmit_base'];
1745
	}
1746
	if (isset($config['ipsec']['ikev2_retransmit_jitter'])) {
1747
		$ssconf['charon']['retransmit_jitter'] = $config['ipsec']['ikev2_retransmit_jitter'];
1748
	}
1749
	if (isset($config['ipsec']['ikev2_retransmit_limit'])) {
1750
		$ssconf['charon']['retransmit_limit'] = $config['ipsec']['ikev2_retransmit_limit'];
1751
	}
1752

    
1753
	$ssconf['charon']['syslog'] = array();
1754
	$ssconf['charon']['syslog']['identifier'] = 'charon';
1755
	$ssconf['charon']['syslog'][] = "# log everything under daemon since it ends up in the same place regardless with our syslog.conf";
1756
	$ssconf['charon']['syslog']['daemon'] = array();
1757
	$ssconf['charon']['syslog']['daemon']['ike_name'] = 'yes';
1758
	$ssconf['charon']['syslog']['daemon'] = array_merge($ssconf['charon']['syslog']['daemon'], ipsec_logging_config());
1759
	$ssconf['charon']['syslog'][] = '# disable logging under auth so logs aren\'t duplicated';
1760
	$ssconf['charon']['syslog']['auth'] = array();
1761
	$ssconf['charon']['syslog']['auth']['default'] = -1;
1762

    
1763
	$ssconf['charon']['plugins'] = array();
1764
	$ssconf['charon']['plugins'][] = "# Load defaults";
1765
	$ssconf['charon']['plugins'][] = "include {$g['varetc_path']}/ipsec/strongswan.d/charon/*.conf";
1766
	$ssconf['charon']['plugins']['unity'] = array('load' => $unity_enabled);
1767
	$ssconf['charon']['plugins']['curve25519'] = array('load' => "yes");
1768

    
1769
	if (isset($config['ipsec']['pkcs11support'])) {
1770
		$ssconf['charon']['plugins']['pkcs11'] = array();
1771
		$ssconf['charon']['plugins']['pkcs11']['load'] = "yes";
1772
		$ssconf['charon']['plugins']['pkcs11']['modules'] = array();
1773
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc'] = array();
1774
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc']['load_certs'] = "yes";
1775
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc']['path'] = "/usr/local/lib/opensc-pkcs11.so";
1776
	}
1777

    
1778
	/* Find RADIUS servers designated for Mobile IPsec user auth */
1779
	$radius_servers = array();
1780
	foreach (explode(',', $config['ipsec']['client']['user_source']) as $user_source) {
1781
		$auth_server = auth_get_authserver($user_source);
1782
		$nice_user_source = strtolower(preg_replace('/[\s\.]+/', '_', $user_source));
1783
		if ($auth_server && ($auth_server['type'] === 'radius')) {
1784
			$radius_servers[$nice_user_source] = array();
1785
			$radius_servers[$nice_user_source]['address'] = $auth_server['host'];
1786
			$radius_servers[$nice_user_source]['secret'] = "\"{$auth_server['radius_secret']}\"";
1787
			$radius_servers[$nice_user_source]['auth_port'] = empty($auth_server['radius_auth_port']) ? 1812 : $auth_server['radius_auth_port'];;
1788
			$radius_servers[$nice_user_source]['acct_port'] = empty($auth_server['radius_acct_port']) ? 1813 : $auth_server['radius_acct_port'];
1789
		}
1790
	}
1791

    
1792
	/* Generate an eap-radius config section if appropriate */
1793
	if (count($radius_servers) && ($mobile_ipsec_auth === "eap-radius")) {
1794
		$ssconf['charon']['plugins']['eap-radius'] = array();
1795
		$ssconf['charon']['plugins']['eap-radius']['load'] = "2";
1796
		$ssconf['charon']['plugins']['eap-radius']['class_group'] = "yes";
1797
		$ssconf['charon']['plugins']['eap-radius']['eap_start'] = "no";
1798
		/* Activate RADIUS accounting only if it was selected on the IPsec Mobile Clients tab */
1799
		if ($auth_server && isset($auth_server['radius_acct_port']) &&
1800
		    (is_array($a_client) && ($a_client['radiusaccounting'] == "enabled"))) {
1801
			$ssconf['charon']['plugins']['eap-radius']['accounting'] = "yes";
1802
			$ssconf['charon']['plugins']['eap-radius']['accounting_close_on_timeout'] = "no";
1803
		}
1804
		/* advanced parameters, see https://redmine.pfsense.org/issues/11211 */
1805
		if (isset($a_client['radius_retransmit_base'])) {
1806
			$ssconf['charon']['plugins']['eap-radius']['retransmit_base'] = $a_client['radius_retransmit_base'];
1807
		}
1808
		if (isset($a_client['radius_retransmit_timeout'])) {
1809
			$ssconf['charon']['plugins']['eap-radius']['retransmit_timeout'] = $a_client['radius_retransmit_timeout'];
1810
		}
1811
		if (isset($a_client['radius_retransmit_tries'])) {
1812
			$ssconf['charon']['plugins']['eap-radius']['retransmit_tries'] = $a_client['radius_retransmit_tries'];
1813
		}
1814
		if (isset($a_client['radius_sockets'])) {
1815
			$ssconf['charon']['plugins']['eap-radius']['sockets'] = $a_client['radius_sockets'];
1816
		}
1817
		$ssconf['charon']['plugins']['eap-radius']['servers'] = $radius_servers;
1818
	}
1819

    
1820
	if (is_array($a_client) && isset($a_client['enable'])) {
1821
		if ($a_client['user_source'] != "none") {
1822
			$ssconf['charon']['plugins']['xauth-generic'] = array();
1823
			$ssconf['charon']['plugins']['xauth-generic']['script'] = "/etc/inc/ipsec.auth-user.php";
1824
			$authcfgs = array();
1825
			foreach (explode(",", $a_client['user_source']) as $authcfg) {
1826
				$authcfgs[] = ($authcfg == "system") ? "Local Database" : $authcfg;
1827
			}
1828
			$ssconf['charon']['plugins']['xauth-generic']['authcfg'] = implode(",", $authcfgs);
1829
		}
1830

    
1831
		$ssconf['charon']['plugins']['attr'] = array();
1832

    
1833
		$rightdnsservers = array();
1834
		if (!empty($a_client['dns_server1'])) {
1835
			$rightdnsservers[] = $a_client['dns_server1'];
1836
		}
1837
		if (!empty($a_client['dns_server2'])) {
1838
			$rightdnsservers[] = $a_client['dns_server2'];
1839
		}
1840
		if (!empty($a_client['dns_server3'])) {
1841
			$rightdnsservers[] = $a_client['dns_server3'];
1842
		}
1843
		if (!empty($a_client['dns_server4'])) {
1844
			$rightdnsservers[] = $a_client['dns_server4'];
1845
		}
1846
		if (count($rightdnsservers)) {
1847
			$ssconf['charon']['plugins']['attr']['dns'] = implode(',', $rightdnsservers);
1848
		}
1849

    
1850
		$cfgservers = array();
1851
		if (!empty($a_client['wins_server1'])) {
1852
			$cfgservers[] = $a_client['wins_server1'];
1853
		}
1854
		if (!empty($a_client['wins_server2'])) {
1855
			$cfgservers[] = $a_client['wins_server2'];
1856
		}
1857
		if (!empty($cfgservers)) {
1858
			$ssconf['charon']['plugins']['attr']['nbns'] = implode(',', $cfgservers);
1859
		}
1860
		unset($cfgservers);
1861

    
1862
		$net_list = array();
1863
		if (isset($a_client['net_list']) && is_array($a_phase2)) {
1864
			foreach ($a_phase2 as $ph2ent) {
1865
				if (isset($ph2ent['disabled']) ||
1866
				    !isset($ph2ent['mobile'])) {
1867
					continue;
1868
				}
1869
				$nlent = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
1870
				if (is_subnet($nlent)) {
1871
					$net_list[] = $nlent;
1872
				}
1873
				unset($nlent);
1874
			}
1875
		}
1876

    
1877
		if (!empty($net_list)) {
1878
			$ssconf['charon']['plugins']['attr']['subnet'] = implode(',', $net_list);
1879
			$ssconf['charon']['plugins']['attr']['split-include'] = implode(',', $net_list);
1880
		}
1881

    
1882
		if (!empty($a_client['dns_domain'])) {
1883
			$ssconf['charon']['plugins']['attr'][] = "# Search domain and default domain";
1884
			$ssconf['charon']['plugins']['attr']['27674'] = "\"{$a_client['dns_domain']}\"";
1885
			if (empty($a_client['dns_split'])) {
1886
				$ssconf['charon']['plugins']['attr']['27675'] = "\"{$a_client['dns_domain']}\"";
1887
			}
1888
		}
1889

    
1890
		if (!empty($a_client['dns_split'])) {
1891
			$ssconf['charon']['plugins']['attr'][] = "# Split DNS";
1892
			$ssconf['charon']['plugins']['attr']['28675'] = "\"{$a_client['dns_split']}\"";
1893
		}
1894

    
1895
		if (!empty($a_client['login_banner'])) {
1896
			$ssconf['charon']['plugins']['attr'][] = "# Login Banner";
1897
			$ssconf['charon']['plugins']['attr']['28672'] = "\"{$a_client['login_banner']}\"";
1898
		}
1899

    
1900
		if (isset($a_client['save_passwd'])) {
1901
			$ssconf['charon']['plugins']['attr'][] = "# Save Xauth Password";
1902
			$ssconf['charon']['plugins']['attr']['28673'] = "1";
1903
		}
1904

    
1905
		if ($a_client['pfs_group']) {
1906
			$ssconf['charon']['plugins']['attr'][] = "# Phase2 PFS Group";
1907
			$ssconf['charon']['plugins']['attr']['28679'] = "\"{$a_client['pfs_group']}\"";
1908
		}
1909
	}
1910

    
1911
	@file_put_contents("{$g['varetc_path']}/ipsec/strongswan.conf", ipsec_strongswan_confgen($ssconf));
1912
}
1913

    
1914
/****f* ipsec/ipsec_setup_pools
1915
 * NAME
1916
 *   ipsec_setup_pools - Generate primary mobile pool configuration for swanctl
1917
  * INPUTS
1918
 *   None
1919
 * RESULT
1920
 *   Adds configured mobile pool settings to $scconf
1921
 * NOTES
1922
 *   These values were formerly in strongswan.conf but may now be configured in
1923
 *   pools, making future expansion to support multiple pools possible.
1924
 ******/
1925
function ipsec_setup_pools() {
1926
	global $config, $g, $mobile_ipsec_auth, $a_client, $a_phase2, $scconf;
1927
	if (!is_array($a_client) || !isset($a_client['enable'])) {
1928
		return;
1929
	}
1930
	if (($mobile_ipsec_auth == "eap-radius") && empty($a_client['pool_address']) &&
1931
	    empty($a_client['pool_address_v6'])) {
1932
		return;
1933
	}
1934

    
1935
	/* Keep the comment in the array to ensure the entry makes it into the
1936
	 * config in all cases.
1937
	 * See https://redmine.pfsense.org/issues/11891 */
1938
	$scconf['mobile-pool'] = array("# Mobile pool settings template");
1939
	$scconf['pools'] = array();
1940
	$pool_common =& $scconf['mobile-pool'];
1941

    
1942
	if (!empty($a_client['pool_address'])) {
1943
		$scconf['pools']['mobile-pool-v4 : mobile-pool'] = array();
1944
		$v4pool =& $scconf['pools']['mobile-pool-v4 : mobile-pool'];
1945
		$v4pool['addrs'] = "{$a_client['pool_address']}/{$a_client['pool_netbits']}";
1946
	}
1947
	if (!empty($a_client['pool_address_v6'])) {
1948
		$scconf['pools']['mobile-pool-v6 : mobile-pool'] = array();
1949
		$v6pool =& $scconf['pools']['mobile-pool-v6 : mobile-pool'];
1950
		$v6pool['addrs'] = "{$a_client['pool_address_v6']}/{$a_client['pool_netbits_v6']}";
1951
	}
1952

    
1953
	return;
1954
}
1955

    
1956
/****f* ipsec/ipsec_setup_userpools
1957
 * NAME
1958
 *   ipsec_setup_userpools - Generate per-user custom pool settings for swanctl
1959
  * INPUTS
1960
 *   None
1961
 * RESULT
1962
 *   Adds configured per-user pool settings to $scconf using the primary mobile
1963
 *   pool as a base configuration.
1964
 * NOTES
1965
 *   Given this new flexible format, it is now possible to override any valid
1966
 *   pool setting, so future expansion of per-user settings is possible.
1967
 ******/
1968
function ipsec_setup_userpools() {
1969
	global $config, $scconf;
1970
	$a_mobilekey = $config['ipsec']['mobilekey'];
1971

    
1972
	/* Do not waste time if we do not have all the necessary information. */
1973
	if (!is_array($a_mobilekey) ||
1974
	    empty($a_mobilekey) ||
1975
	    !is_array($scconf['connections']) ||
1976
	    !is_array($scconf['con-mobile-defaults']) ||
1977
	    !is_array($scconf['pools']) ||
1978
	    !is_array($scconf['mobile-pool'])) {
1979
		return;
1980
	}
1981

    
1982
	$suffix = 1;
1983
	foreach ($a_mobilekey as $mkent) {
1984
		if (($mkent['type'] != "EAP") ||
1985
		    !isset($mkent['ident_type']) ||
1986
		    !isset($mkent['pool_address']) ||
1987
		    !isset($mkent['pool_netbits']) ||
1988
		    (strlen($mkent['pool_address']) < 1) ||
1989
		    !is_ipaddr($mkent['pool_address'])) {
1990
			continue;
1991
		}
1992
		/* The name of just this pool */
1993
		$upbase = "mobile-userpool-{$suffix}";
1994
		/* The full connection name including a reference to the primary
1995
		 * mobile connection */
1996
		$upconn = "con-{$upbase} : con-mobile-defaults";
1997
		/* The full pool name including a reference to the primary
1998
		 * mobile pool */
1999
		$upname = "{$upbase} : mobile-pool";
2000

    
2001
		$scconf['connections'][$upconn] = array();
2002
		$scconf['pools'][$upname] = array();
2003

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

    
2007
		/* Craft a cloned connection with the ID information to match */
2008
		$scconf['connections'][$upconn]['remote'] = array();
2009
		$scconf['connections'][$upconn]['remote']['id'] = $clientid;
2010
		$scconf['connections'][$upconn]['remote']['eap_id'] = $clienteapid;
2011
		$scconf['connections'][$upconn]['pools'] = $upbase;
2012

    
2013
		/* Craft a cloned pool with pool settings to override for this user */
2014
		$scconf['pools'][$upname]['addrs'] = "{$mkent['pool_address']}/{$mkent['pool_netbits']}";
2015
		if (isset($mkent['dns_address']) && strlen($mkent['dns_address']) > 0 && is_ipaddr($mkent['dns_address'])) {
2016
			$scconf['pools'][$upname]['dns'] = $mkent['dns_address'];
2017
		}
2018
		$suffix++;
2019
	}
2020
	return;
2021
}
2022

    
2023
/****f* ipsec/ipsec_setup_bypass
2024
 * NAME
2025
 *   ipsec_setup_bypass - Generate a bypass connection for LAN-LAN and custom rules traffic
2026
 * INPUTS
2027
 *   None
2028
 * RESULT
2029
 *   Sets up a bypass connection to prevent local traffic from being caught by
2030
 *   IPsec policies.
2031
 ******/
2032
function ipsec_setup_bypass($gateways_status) {
2033
	global $config, $scconf;
2034

    
2035
	$scconf['connections']['bypass'] = array();
2036
	/* Prevents the connection from being considered for remote peers */
2037
	$scconf['connections']['bypass']['remote_addrs'] = "127.0.0.1";
2038
	$scconf['connections']['bypass']['children'] = array();
2039

    
2040
	/* Locate the LAN IPv4 and IPv6 subnets */
2041
	$bypassnets = array();
2042
	if ($config['interfaces']['lan']) {
2043
		$lanip = get_interface_ip("lan", $gateways_status);
2044
		if (!empty($lanip) && is_ipaddrv4($lanip)) {
2045
			$lansn = get_interface_subnet("lan");
2046
			$lansa = gen_subnetv4($lanip, $lansn);
2047
			if (!empty($lansa) && !empty($lansn)) {
2048
				$bypassnets[] = "{$lansa}/{$lansn}";
2049
			}
2050
		}
2051
		$lanip6 = get_interface_ipv6("lan", $gateways_status);
2052
		if (!empty($lanip6) && is_ipaddrv6($lanip6)) {
2053
			$lansn6 = get_interface_subnetv6("lan");
2054
			$lansa6 = gen_subnetv6($lanip6, $lansn6);
2055
			if (!empty($lansa6) && !empty($lansn6)) {
2056
				$bypassnets[] = "{$lansa6}/{$lansn6}";
2057
			}
2058
		}
2059
	}
2060
	/* If we have viable targets, setup a bypass LAN connection */
2061
	if (!empty($bypassnets) && !isset($config['ipsec']['noshuntlaninterfaces'])) {
2062
		$bypass = implode(',', $bypassnets);
2063
		$scconf['connections']['bypass']['children']['bypasslan'] = array();
2064
		$scconf['connections']['bypass']['children']['bypasslan']['local_ts'] = $bypass;
2065
		$scconf['connections']['bypass']['children']['bypasslan']['remote_ts'] = $bypass;
2066
		$scconf['connections']['bypass']['children']['bypasslan']['mode'] = "pass";
2067
		$scconf['connections']['bypass']['children']['bypasslan']['start_action'] = "trap";
2068
	}
2069

    
2070
	/* Setup custom bypass rules */
2071
	if ((isset($config['ipsec']['ipsecbypass']) && $config['ipsec']['bypassrules']) &&
2072
	    is_array($config['ipsec']['bypassrules'])) {
2073
		foreach ($config['ipsec']['bypassrules']['rule'] as $id => $rule) {
2074
			$scconf['connections']['bypass']['children']["rule{$id}"] = array();
2075
			$scconf['connections']['bypass']['children']["rule{$id}"]["local_ts"] = $rule['source'] .
2076
			       	"/" . $rule['srcmask'];
2077
			$scconf['connections']['bypass']['children']["rule{$id}"]["remote_ts"] = $rule['destination'] .
2078
			       	"/" . $rule['dstmask'];
2079
			$scconf['connections']['bypass']['children']["rule{$id}"]["mode"] = "pass";
2080
			$scconf['connections']['bypass']['children']["rule{$id}"]["start_action"] = "trap";
2081
		}
2082
	}
2083

    
2084
	return;
2085
}
2086

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

    
2151
/****f* ipsec/ipsec_setup_authentication
2152
 * NAME
2153
 *   ipsec_setup_authentication - Generate an array with local/remote
2154
 *                                authentication information for a given IPsec
2155
 *                                Phase 1.
2156
 * INPUTS
2157
 *   $ph1ent: An IPsec Phase 1 configuration
2158
 *   $conn  : A swanctl connection array corresponding to the IPsec Phase 1.
2159
 * RESULT
2160
 *   Populates $conn with local and remote arrays containing authentication
2161
 *   details.
2162
 ******/
2163
function ipsec_setup_authentication(& $ph1ent, & $conn, $gateways_status = false) {
2164
	global $rgmap, $ipsec_swanctl_dirs, $config;
2165
	$local = array();
2166
	$remote = array();
2167
	$remote2 = array();
2168

    
2169
	/* Fetch gateway status if not passed */
2170
	if (!is_array($gateways_status)) {
2171
		$gateways_status = return_gateways_status(true);
2172
	}
2173

    
2174
	list($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local', array(), $gateways_status);
2175
	$localid = ipsec_fixup_id($myid_type, $myid_data);
2176
	if (!empty($localid)) {
2177
		$local['id'] = $localid;
2178
	}
2179

    
2180
	// Only specify peer ID if we are not dealing with mobile PSK
2181
	if (!(isset($ph1ent['mobile']) &&
2182
	    in_array($ph1ent['authentication_method'], array("pre_shared_key", "xauth_psk_server")))) {
2183
		list ($remoteid_type, $remoteid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap, $gateways_status);
2184
		$remoteid = ipsec_fixup_id($remoteid_type, $remoteid_data);
2185
	}
2186
	if (!empty($remoteid)) {
2187
		$remote['id'] = $remoteid;
2188
	}
2189

    
2190
	if (!empty($ph1ent['caref'])) {
2191
		$ca = lookup_ca($ph1ent['caref']);
2192
		if ($ca) {
2193
			/* Get hash value to use for filename */
2194
			$ca_details = openssl_x509_parse(base64_decode($ca['crt']));
2195
			$cafn = "{$ipsec_swanctl_dirs['capath']}/{$ca_details['hash']}.0";
2196
		}
2197
	}
2198

    
2199
	$authentication = "";
2200
	switch ($ph1ent['authentication_method']) {
2201
		case 'eap-mschapv2':
2202
			if (isset($ph1ent['mobile'])) {
2203
				$local['auth'] = "pubkey";
2204
				$remote['eap_id'] = "%any";
2205
				$remote['auth'] = "eap-mschapv2";
2206
			}
2207
			break;
2208
		case 'eap-tls':
2209
			if (isset($ph1ent['mobile'])) {
2210
				$local['auth'] = "pubkey";
2211
				$remote['eap_id'] = "%any";
2212
			} else {
2213
				$local['auth'] = "eap-tls";
2214
			}
2215
			$remote['auth'] = "eap-tls";
2216
			break;
2217
		case 'eap-radius':
2218
			if (isset($ph1ent['mobile'])) {
2219
				$local['auth'] = "pubkey";
2220
				$remote['eap_id'] = "%any";
2221
			} else {
2222
				$local['auth'] = "eap-radius";
2223
			}
2224
			if (($config['ipsec']['client']['group_source'] == 'enabled') &&
2225
			    !empty($config['ipsec']['client']['auth_groups'])) {
2226
				$remote['groups'] = $config['ipsec']['client']['auth_groups'];
2227
			}
2228
			$remote['auth'] = "eap-radius";
2229
			break;
2230
		case 'xauth_cert_server':
2231
			$local['auth'] = "pubkey";
2232
			$remote['auth'] = "pubkey";
2233
			$remote2['auth'] = "xauth-generic";
2234
			break;
2235
		case 'xauth_psk_server':
2236
			$local['auth'] = "psk";
2237
			$remote['auth'] = "psk";
2238
			$remote2['auth'] = "xauth-generic";
2239
			break;
2240
		case 'pre_shared_key':
2241
			$local['auth'] = "psk";
2242
			$remote['auth'] = "psk";
2243
			break;
2244
		case 'cert':
2245
		case 'pkcs11':
2246
			$local['auth'] = "pubkey";
2247
			$remote['auth'] = "pubkey";
2248
			break;
2249
		case 'hybrid_cert_server':
2250
			$local['auth'] = "pubkey";
2251
			$remote['auth'] = "xauth-generic";
2252
			break;
2253
	}
2254
	if (in_array($ph1ent['authentication_method'], array('eap-mschapv2', 'eap-tls', 'eap-radius', 'xauth_cert_server', 'cert', 'hybrid_cert_server')) &&
2255
	    !empty($ph1ent['certref'])) {
2256
		$local['cert'] = array('file' => "{$ipsec_swanctl_dirs['certpath']}/cert-{$ph1ent['ikeid']}.crt");
2257
		$conn['send_cert'] = "always";
2258
	}
2259
	if ($ph1ent['authentication_method'] == 'pkcs11') {
2260
		$local['cert'] = array('handle' => "{$ph1ent['pkcs11certref']}");
2261
		$conn['send_cert'] = "always";
2262
	}
2263
	if (in_array($ph1ent['authentication_method'], array('eap-tls', 'xauth_cert_server', 'cert', 'pkcs11')) &&
2264
	    isset($cafn)) {
2265
		$remote['cacerts'] = $cafn;
2266
		if (isset($config['ipsec']['strictcrlpolicy'])) {
2267
			$remote['revocation'] = "strict";
2268
		}
2269
	}
2270

    
2271
	$conn['local'] = $local;
2272
	/* If there is data for a second remote auth round, setup two remote
2273
	 * arrays with unique names, otherwise setup a single remote. */
2274
	if (empty($remote2)) {
2275
		$conn['remote'] = $remote;
2276
	} else {
2277
		$conn['remote-1'] = $remote;
2278
		$conn['remote-2'] = $remote2;
2279
	}
2280
}
2281

    
2282
/****f* ipsec/ipsec_setup_proposal_algo
2283
 * NAME
2284
 *   ipsec_setup_proposal_algo - Form a single proposal algorithm string
2285
 * INPUTS
2286
 *   $ealg_id: Encryption algorithm ID
2287
 *   $keylen : Key length for the encryption algorithm
2288
 *   $halgo  : Hash algorithm
2289
 *   $modp   : DH Group number
2290
 * RESULT
2291
 *   Returns a string using the available information to form a single proposal
2292
 *   algorithm definition.
2293
 * NOTES
2294
 *   Values left empty will not be added to the string. Some combinations may
2295
 *   require one or more parts to be omitted.
2296
 ******/
2297
function ipsec_setup_proposal_algo($ealg_id, $keylen, $halgo, $prfalgo, $modp) {
2298
	$palgo = "";
2299

    
2300
	/* Add the encryption algorithm (if present) */
2301
	if (!empty($ealg_id)) {
2302
		$palgo .= "{$ealg_id}";
2303
	}
2304

    
2305
	/* Add the key length (if present) */
2306
	if (!empty($keylen)) {
2307
		$palgo .= "{$keylen}";
2308
	}
2309

    
2310
	/* Add the hash algorithm (if present) */
2311
	if (!empty($halgo)) {
2312
		/* If there is some content in the propsal already, add a
2313
		 * separator */
2314
		if (!empty($palgo)) {
2315
			$palgo .= "-";
2316
		}
2317
		$halgo = str_replace('hmac_', '', $halgo);
2318
		$palgo .= "{$halgo}";
2319
	}
2320

    
2321
	if (!empty($prfalgo)) {
2322
		$palgo .= "-prf{$prfalgo}";
2323
	}
2324

    
2325
	/* Convert the DH group to its keyword and add (if present) */
2326
	$modp = ipsec_convert_to_modp($modp);
2327
	if (!empty($modp)) {
2328
		$palgo .= "-{$modp}";
2329
	}
2330

    
2331
	return $palgo;
2332
}
2333

    
2334
/****f* ipsec/ipsec_setup_proposal_entry
2335
 * NAME
2336
 *   ipsec_setup_proposal_entry - Generate a full proposal string for an IPsec
2337
 *                                Phase 2 configuration.
2338
 * INPUTS
2339
 *   $ph2ent  : An IPsec Phase 2 configuration
2340
 *   $algo_arr: An array in which all proposal algorithms are collected
2341
 *   $ealg_id : Encryption algorithm ID
2342
 *   $keylen  : Key length for the encryption algorithm
2343
 * RESULT
2344
 *   Returns a string containing all proposal elements, and merges the entries
2345
 *   to $algo_arr as well.
2346
 ******/
2347
function ipsec_setup_proposal_entry(& $ph2ent, & $algo_arr, $ealg_id, $keylen) {
2348
	global $config, $p2_ealgos;
2349
	$proposal = array();
2350

    
2351
	/* If multiple hash algorithms are present, loop through and add them all. */
2352
	if (!empty($ph2ent['hash-algorithm-option']) && is_array($ph2ent['hash-algorithm-option']) 
2353
	    && !strpos($ealg_id, "gcm")) {
2354
		foreach ($ph2ent['hash-algorithm-option'] as $halgo) {
2355
			$proposal[] = ipsec_setup_proposal_algo($ealg_id, $keylen, $halgo, false, $ph2ent['pfsgroup']);
2356
		}
2357
	} else {
2358
		$proposal[] = ipsec_setup_proposal_algo($ealg_id, $keylen, false, false, $ph2ent['pfsgroup']);
2359
	}
2360

    
2361
	/* Add to master list */
2362
	$algo_arr = array_merge($algo_arr, $proposal);
2363
	return implode(',', $proposal);
2364
}
2365

    
2366
function ipsec_get_ifname($p1, $reqid = 0) {
2367
	global $config;
2368
	$ifname = "ipsec";
2369
	if ($reqid > 0) {
2370
		$ifname .= "{$reqid}";
2371
	} else {
2372
		$p2s = ipsec_get_phase2_by_ikeid($p1['ikeid']);
2373
		if (!empty($p2s)) {
2374
			$ifname .= $p2s[0]['reqid'];
2375
		}
2376
	}
2377
	return $ifname;
2378
}
2379

    
2380
function ipsec_get_ifname_by_conf($p1 = array(), $p2 = array()) {
2381
	global $config;
2382
	$have_p1 = (!empty($p1) && is_array($p1));
2383
	$have_p2 = (!empty($p2) && is_array($p2));
2384
	$reqid = null;
2385

    
2386
	if (!$have_p1 && $have_p2) {
2387
		$p1 = ipsec_get_phase1($p2['ikeid']);
2388
	}
2389

    
2390
	if ($have_p2) {
2391
		$reqid = $p2['reqid'];
2392
	}
2393

    
2394
	return ipsec_get_ifname($p1, $reqid);
2395
}
2396

    
2397
/****f* ipsec/ipsec_setup_vtireq
2398
 * NAME
2399
 *   ipsec_setup_vtireq - Setup a VTI type IPsec request
2400
 * INPUTS
2401
 *   $child                : A swanctl child array
2402
 *   $ipsec_vti_cleanup_ifs: An array of VTI interface names for later cleanup
2403
 *   $p1                   : The IKE config under which this child exists
2404
 *   $reqid                : The reqid of the P2 if known, otherwise the first P2 reqid for this P1 is looked up.
2405
 * RESULT
2406
 *   Sets up VTI-specific values for a request.
2407
 ******/
2408
function ipsec_setup_vtireq(& $child, & $ipsec_vti_cleanup_ifs, $p1, $reqid = 0) {
2409
	global $ipsec_reqid_base;
2410
	if ($reqid > 0) {
2411
		$child['reqid'] = $ipsec_reqid_base + $reqid;
2412
	} else {
2413
		$p2s = ipsec_get_phase2_by_ikeid($p1['ikeid']);
2414
		if (!empty($p2s)) {
2415
			$reqid = $p2s[0]['reqid'];
2416
			$child['reqid'] = $ipsec_reqid_base + $reqid;
2417
		} else {
2418
			return false;
2419
		}
2420
	}
2421
	/* This interface will be a valid IPsec interface, so remove it from the cleanup list. */
2422
	$ipsec_vti_cleanup_ifs = array_diff($ipsec_vti_cleanup_ifs, array(ipsec_get_ifname($p1, $reqid)));
2423
	$child['local_ts'] .= ",0.0.0.0/0,::/0";
2424
	$child['remote_ts'] .= ",0.0.0.0/0,::/0";
2425
	return true;
2426
}
2427

    
2428
/****f* ipsec/ipsec_setup_tunnels
2429
 * NAME
2430
 *   ipsec_setup_tunnels - Configure all P1/P2 entries as swanctl connections
2431
 * INPUTS
2432
 *   None
2433
 * RESULT
2434
 *   Sets up a swanctl array for all connections in the configuration along with
2435
 *   their children, authentication, etc.
2436
 ******/
2437
function ipsec_setup_tunnels($gateways_status = false) {
2438
	global $aggressive_mode_psk, $a_client, $config,
2439
		$filterdns_list, $g, $ifacesuse, $ipsec_idhandling, $ipsec_log_cats,
2440
		$ipsec_log_sevs, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs,
2441
		$ipseccfg, $mobile_ipsec_auth, $natfilterrules, $p1_ealgos,
2442
		$p2_ealgos, $rgmap, $sa, $sn, $scconf, $conn, $tunnels,
2443
		$ipsec_vti_cleanup_ifs, $conn_defaults;
2444

    
2445
	/* Fetch gateway status if not passed */
2446
	if (!is_array($gateways_status)) {
2447
		$gateways_status = return_gateways_status(true);
2448
	}
2449

    
2450
	$a_groups = return_gateway_groups_array(true);
2451

    
2452
	foreach ($tunnels as $ph1ent) {
2453
		/* Skip disabled entries */
2454
		if (isset($ph1ent['disabled'])) {
2455
			continue;
2456
		}
2457
		/* If the local source is invalid, skip this entry. */
2458
		$local_spec = ipsec_get_phase1_src($ph1ent, $gateways_status);
2459
		if (!$local_spec) {
2460
			continue;
2461
		}
2462

    
2463
		/* Determine the name of this connection, either con-mobile for
2464
		 * mobile clients, or a name based on the IKE ID otherwise. */
2465
		if (isset($ph1ent['mobile'])) {
2466
			$cname = "con-mobile";
2467
			/* Start with common default values */
2468
			$scconf["{$cname}-defaults"] = $conn_defaults;
2469
			/* Array reference to make things easier */
2470
			$conn =& $scconf["{$cname}-defaults"];
2471
			$scconf['connections']["{$cname} : {$cname}-defaults"] = array("# Stub to load con-mobile-defaults");
2472
		} else {
2473
			$cname = ipsec_conid($ph1ent);
2474
			/* Start with common default values */
2475
			$scconf['connections'][$cname] = $conn_defaults;
2476
			$descr = "# P1 (ikeid {$ph1ent['ikeid']})";
2477
			if (!empty($ph1ent['descr'])) {
2478
				$descr .= ": {$ph1ent['descr']}";
2479
			}
2480
			array_unshift($scconf['connections'][$cname], $descr);
2481
			/* Array reference to make things easier */
2482
			$conn =& $scconf['connections'][$cname];
2483
		}
2484

    
2485
		/* Common parameters for all children */
2486
		$child_params = array();
2487
		if (!empty($ph1ent['closeaction'])) {
2488
			$child_params['close_action'] = $ph1ent['closeaction'];
2489
		}
2490

    
2491
		$ikeid = $ph1ent['ikeid'];
2492

    
2493
		$carpbackup = false;
2494
		if (((substr($ph1ent['interface'], 0, 4) == "_vip") &&
2495
		    in_array(get_carp_bind_status($ph1ent['interface']), array('BACKUP', 'INIT'))) ||
2496
		    (is_array($a_groups[$ph1ent['interface']]) &&
2497
		    !empty($a_groups[$ph1ent['interface']][0]['vip']) &&
2498
		    in_array(get_carp_bind_status($a_groups[$ph1ent['interface']][0]['vip']), array('BACKUP', 'INIT')))) {
2499
			$carpbackup = true;
2500
		}
2501

    
2502
		/* "trap" adds policies to start a tunnel when interesting
2503
		 * traffic is observed by the host. */
2504
		$start_action = "trap";
2505
		if ($carpbackup) {
2506
			$start_action = "none";
2507
		}
2508

    
2509
		/* Set the IKE version appropriately (empty = IKEv1) */
2510
		switch ($ph1ent['iketype']) {
2511
			case 'auto':
2512
				$ikeversion = 0;
2513
				break;
2514
			case 'ikev2':
2515
				$ikeversion = 2;
2516
				break;
2517
			case 'ikev1':
2518
			default:
2519
				$ikeversion = 1;
2520
				break;
2521
		}
2522
		$conn['version'] = $ikeversion;
2523

    
2524
		/* For IKEv1 or auto, setup aggressive mode if configured */
2525
		if ($ikeversion != 2){
2526
			$conn['aggressive'] = ($ph1ent['mode'] == "aggressive") ? "yes" : "no";
2527
		}
2528

    
2529
		if (isset($ph1ent['mobile'])) {
2530
			/* Mobile tunnels allow 'any' as a peer */
2531
			$remote_spec = "0.0.0.0/0,::/0";
2532
			/* Mobile tunnels cannot start automatically */
2533
			$start_action = 'none';
2534
		} else {
2535
			$remote_spec = $ph1ent['remote-gateway'];
2536
			$sourcehost = (is_ipaddr($remote_spec)) ? $remote_spec : $rgmap[$remote_spec];
2537
			$ifacesuse = ipsec_setup_routes($ph1ent['interface'], $ph1ent['protocol'], $sourcehost, isset($ph1ent['gw_duplicates']));
2538
		}
2539

    
2540
		/* Setup IKE proposals */
2541
		if (is_array($ph1ent['encryption']['item'])) {
2542
			$ciphers = array();
2543
			foreach($ph1ent['encryption']['item'] as $p1enc) {
2544
				if (!is_array($p1enc['encryption-algorithm']) ||
2545
						empty($p1enc['encryption-algorithm']['name']) ||
2546
						empty($p1enc['hash-algorithm'])) {
2547
					continue;
2548
				}
2549
				if ($ph1ent['prfselect_enable'] != 'yes') {
2550
					$p1enc['prf-algorithm'] = false;
2551
				}
2552
				$ciphers[] = ipsec_setup_proposal_algo($p1enc['encryption-algorithm']['name'],
2553
									$p1enc['encryption-algorithm']['keylen'],
2554
									$p1enc['hash-algorithm'],
2555
									$p1enc['prf-algorithm'],
2556
									$p1enc['dhgroup']);
2557
			}
2558
			$conn['proposals'] = implode(",", $ciphers);
2559
		}
2560

    
2561
		/* Configure DPD values. The DPD action is a per-child parameter,
2562
		 * not per-connection like the delay and timeout. */
2563
		if ($ph1ent['dpd_delay'] && $ph1ent['dpd_maxfail']) {
2564
			if ($start_action == "trap") {
2565
				$child_params['dpd_action'] = "trap";
2566
			} else {
2567
				$child_params['dpd_action'] = "clear";
2568
			}
2569
			$conn['dpd_delay'] = "{$ph1ent['dpd_delay']}s";
2570
			if ($ph1ent['iketype'] == 'ikev1') {
2571
				/* in IKEv2 the default retransmission timeout applies,
2572
				 * see https://redmine.pfsense.org/issues/12184 */
2573
				$conn['dpd_timeout'] =  $ph1ent['dpd_delay'] * ($ph1ent['dpd_maxfail'] + 1) . "s";
2574
			}
2575

    
2576
			/* Adjust dpd_action if the close_action is explicitly set */
2577
			if (!empty($child_params['close_action'])) {
2578
				switch ($ph1ent['closeaction']) {
2579
					case 'trap':
2580
						$child_params['dpd_action'] = 'trap';
2581
						break;
2582
					case 'start':
2583
						$child_params['dpd_action'] = 'restart';
2584
						break;
2585
					case 'none':
2586
					default:
2587
						$child_params['dpd_action'] = 'clear';
2588
				}
2589
			}
2590
		} else {
2591
			$child_params['dpd_action'] = "clear";
2592
		}
2593

    
2594
		/* Rekey (IKEv2 or Auto only, not supported by IKEv1) */
2595
		if (($ikeversion == 0) || ($ikeversion == 2)) {
2596
			$conn['rekey_time'] = ipsec_get_rekey_time($ph1ent) . "s";
2597
		}
2598

    
2599
		/* Reauth (Any) */
2600
		$conn['reauth_time'] = ipsec_get_reauth_time($ph1ent) . "s";
2601

    
2602
		/* Over Time */
2603
		$conn['over_time'] = ipsec_get_over_time($ph1ent) . "s";
2604

    
2605
		/* Rand Time */
2606
		$conn['rand_time'] = ipsec_get_rand_time($ph1ent) . "s";
2607

    
2608
		/* NAT Traversal */
2609
		$conn['encap'] = ($ph1ent['nat_traversal'] == 'force') ? "yes" : "no";
2610

    
2611
		/* MOBIKE support */
2612
		$conn['mobike'] = ($ph1ent['mobike'] == 'on') ? "yes" : "no";
2613

    
2614
		/* TFC Padding */
2615
		if (isset($ph1ent['tfc_enable'])) {
2616
			$conn['tfc_padding'] = (isset($ph1ent['tfc_bytes']) && is_numericint($ph1ent['tfc_bytes'])) ? $ph1ent['tfc_bytes'] : "mtu";
2617
		}
2618

    
2619
		/* Custom Ports */
2620
		if (isset($ph1ent['ikeport'])) {
2621
			/* For a connection without encapsulation, do not set local_port */
2622
			$conn['remote_port'] = $ph1ent['ikeport'];
2623
		} elseif (isset($ph1ent['nattport'])) {
2624
			/* For an encapsulated connection,
2625
			 * set local_port to the server NAT-T port value or default (4500) */
2626
			$conn['local_port'] = isset($config['ipsec']['port_nat_t']) ? $config['ipsec']['port_nat_t'] : 4500;
2627
			$conn['remote_port'] = $ph1ent['nattport'];
2628
		}
2629

    
2630
		/* Arrays for P2s/children */
2631
		$children = array();
2632
		$remote_ts_spec = array();
2633
		$local_ts_spec = array();
2634
		$reqids = array();
2635
		$has_vti = false;
2636
		$ealgoAHsp2arr = array();
2637
		$ealgoESPsp2arr = array();
2638

    
2639
		foreach ($ph1ent['p2'] as $ph2ent) {
2640
			/* If this entry is disabled, or cannot be configured, skip. */
2641
			if (isset($ph2ent['disabled']) ||
2642
			    (isset($ph2ent['mobile']) && !isset($a_client['enable']))) {
2643
				continue;
2644
			}
2645
			$child = array();
2646
			$local_ts = "";
2647
			$remote_ts = "";
2648
			if (($ph2ent['mode'] == 'tunnel') or ($ph2ent['mode'] == 'tunnel6')) {
2649
				/* Normal tunnel child config */
2650
				$child['mode'] = "tunnel";
2651
				$child['policies'] = "yes";
2652

    
2653
				$localid_type = $ph2ent['localid']['type'];
2654
				$localsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
2655

    
2656
				/* Do not print localid in some cases, such as a pure-psk or psk/xauth single phase2 mobile tunnel */
2657
				if (($localid_type == "none" || $localid_type == "mobile") &&
2658
				    isset($ph1ent['mobile']) && (ipsec_get_number_of_phase2($ikeid) == 1)) {
2659
					$local_spec = '0.0.0.0/0,::/0';
2660
				} else {
2661
					if ($localid_type != "address") {
2662
						$localid_type = "subnet";
2663
					}
2664
					// Don't let an empty subnet into config, it can cause parse errors. Ticket #2201.
2665
					if (!is_ipaddr($localsubnet_data) && !is_subnet($localsubnet_data) && ($localsubnet_data != "0.0.0.0/0")) {
2666
						log_error("Invalid IPsec Phase 2 \"{$ph2ent['descr']}\" - {$ph2ent['localid']['type']} has no subnet.");
2667
						continue;
2668
					}
2669
					if (!empty($ph2ent['natlocalid'])) {
2670
						$natlocalsubnet_data = ipsec_idinfo_to_cidr($ph2ent['natlocalid'], false, $ph2ent['mode']);
2671
						if ($ph2ent['natlocalid']['type'] != "address") {
2672
							if (is_subnet($natlocalsubnet_data)) {
2673
								$localsubnet_data = "{$natlocalsubnet_data}|{$localsubnet_data}";
2674
							}
2675
						} else {
2676
							if (is_ipaddr($natlocalsubnet_data)) {
2677
								$localsubnet_data = "{$natlocalsubnet_data}|{$localsubnet_data}";
2678
							}
2679
						}
2680
						$natfilterrules = true;
2681
					}
2682
				}
2683

    
2684
				$local_ts = $localsubnet_data;
2685

    
2686
				if (!isset($ph2ent['mobile'])) {
2687
					$remote_ts = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
2688
				} else if (!empty($a_client['pool_address'])) {
2689
					$remote_ts = "{$a_client['pool_address']}/{$a_client['pool_netbits']}";
2690
				}
2691

    
2692
			} elseif ($ph2ent['mode'] == 'vti') {
2693
				/* VTI-specific child config */
2694
				$child['policies'] = "no";
2695
				/* VTI cannot use trap policies, so start automatically instead */
2696
				$start_action = 'start';
2697
				if ($carpbackup) {
2698
					$start_action = "none";
2699
				}
2700
				if ($child_params['dpd_action'] == "trap") {
2701
					$child_params['dpd_action'] = "restart";
2702
				}
2703
				$localid_type = $ph2ent['localid']['type'];
2704
				$localsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
2705
				$local_ts = $localsubnet_data;
2706
				$remote_ts = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
2707
				$has_vti = true;
2708
			} else {
2709
				/* Transport mode child config */
2710
				$child['mode'] = "transport";
2711
				$child['policies'] = "yes";
2712

    
2713
				if ((($ph1ent['authentication_method'] == "xauth_psk_server") ||
2714
				    ($ph1ent['authentication_method'] == "pre_shared_key")) &&
2715
				    isset($ph1ent['mobile'])) {
2716
					$local_spec = "0.0.0.0/0,::/0";
2717
				} else {
2718
					$local_ts = ipsec_get_phase1_src($ph1ent, $gateways_status);
2719
				}
2720

    
2721
				if (!isset($ph2ent['mobile'])) {
2722
					$remote_ts = $remote_spec;
2723
				}
2724
			}
2725

    
2726
			if (!empty($local_ts)) {
2727
				$local_ts_spec[] = $local_ts;
2728
			}
2729
			if (!empty($remote_ts)) {
2730
				$remote_ts_spec[] = $remote_ts;
2731
			}
2732

    
2733
			/* If a PFS group is configured on the Mobile Clients tab,
2734
			 * and this is a mobile P2, use it here. */
2735
			if (isset($a_client['pfs_group']) && isset($ph2ent['mobile'])) {
2736
				$ph2ent['pfsgroup'] = $a_client['pfs_group'];
2737
			}
2738

    
2739
			$reqids[] = $ph2ent['reqid'];
2740

    
2741
			if (!empty($ph2ent['lifetime'])) {
2742
				$child['life_time'] = ipsec_get_life_time($ph2ent) . "s";
2743
				/* Rekey at 90% of lifetime */
2744
				$child['rekey_time'] = ipsec_get_rekey_time($ph2ent) . "s";
2745
				/* Random rekey fuzz time */
2746
				$child['rand_time'] = ipsec_get_rand_time($ph2ent) . "s";
2747
			}
2748

    
2749
			/* Set Child SA Start Action based on user preference, except
2750
			 * for invalid combinations such as 'trap' on VTI */
2751
			if (!isset($ph2ent['mobile']) && !$carpbackup &&
2752
			    !(($ph2ent['mode'] == 'vti') && ($ph1ent['startaction'] == 'trap'))) {
2753
				$start_action = !empty($ph1ent['startaction']) ? $ph1ent['startaction'] : $start_action;
2754
			}
2755
			$child['start_action'] = $start_action;
2756

    
2757
			/* Setup child SA proposals */
2758
			$proposal = array();
2759
			$ph2ent_ealgos = array();
2760
			$ph2ent_ealgos_aead = array();
2761
			if ($ph2ent['protocol'] == 'esp') {
2762
				if (is_array($ph2ent['encryption-algorithm-option'])) {
2763
					foreach ($ph2ent['encryption-algorithm-option'] as $ealg) {
2764
						if (strpos($ealg['name'], "gcm")) {
2765
							/* put AEAD ciphers on top, 
2766
							*  see https://redmine.pfsense.org/issues/11078 */
2767
							$ph2ent_ealgos_aead[] = $ealg;
2768
						} else {
2769
							$ph2ent_ealgos[] = $ealg;
2770
						}
2771
					}
2772
					$ph2ent_ealgos = array_merge(array_reverse($ph2ent_ealgos_aead), $ph2ent_ealgos);
2773
					foreach ($ph2ent_ealgos as $ealg) {
2774
						$ealg_id = $ealg['name'];
2775
						$ealg_kl = $ealg['keylen'];
2776

    
2777
						if (!empty($ealg_kl) && $ealg_kl == "auto") {
2778
							if (empty($p2_ealgos) || !is_array($p2_ealgos)) {
2779
								require_once("ipsec.inc");
2780
							}
2781
							$key_hi = $p2_ealgos[$ealg_id]['keysel']['hi'];
2782
							$key_lo = $p2_ealgos[$ealg_id]['keysel']['lo'];
2783
							$key_step = $p2_ealgos[$ealg_id]['keysel']['step'];
2784
							/* XXX: in some cases where include ordering is suspect these variables
2785
							 * are somehow 0 and we enter this loop forever and timeout after 900
2786
							 * seconds wrecking bootup */
2787
							if ($key_hi != 0 and $key_lo != 0 and $key_step != 0) {
2788
								for ($keylen = $key_hi; $keylen >= $key_lo; $keylen -= $key_step) {
2789
									$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoESPsp2arr, $ealg_id, $keylen);
2790
								}
2791
							}
2792
						} else {
2793
							$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoESPsp2arr, $ealg_id, $ealg_kl);
2794
						}
2795
					}
2796
				}
2797
			} else if ($ph2ent['protocol'] == 'ah') {
2798
				$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoAHsp2arr, '', '');
2799
			}
2800

    
2801
			/* Not mobile, and IKEv1 or Split Connections active */
2802
			if (!isset($ph1ent['mobile']) && (($ikeversion == 1) || isset($ph1ent['splitconn']))) {
2803
				if (!empty($remote_ts)) {
2804
					/* Setup child sub-connections using unique names */
2805
					$subconname = ipsec_conid($ph1ent, $ph2ent);
2806
					$children[$subconname] = $child;
2807

    
2808
					$descr = "# P2 (reqid {$ph2ent['reqid']})";
2809
					if (!empty($ph2ent['descr'])) {
2810
						$descr .= ": {$ph2ent['descr']}";
2811
					}
2812
					array_unshift($children[$subconname], $descr);
2813
					$children[$subconname]['local_ts'] = $local_ts;
2814
					$children[$subconname]['remote_ts'] = $remote_ts;
2815
					if ($has_vti) {
2816
						ipsec_setup_vtireq($children[$subconname], $ipsec_vti_cleanup_ifs, $ph1ent, $ph2ent['reqid']);
2817
					}
2818
					if (!empty($ph2ent['protocol']) && !empty($proposal)) {
2819
						$children[$subconname][$ph2ent['protocol'] . '_proposals'] = implode(',', $proposal);
2820
					}
2821
				} else {
2822
					log_error(sprintf(gettext("No phase2 specifications for tunnel with ikeid = %s"), $ikeid));
2823
				}
2824
			} else {
2825
				/* TODO: Fix this to nicely merge all P2 params for single child case */
2826
				if (!is_array($children[$cname])) {
2827
					$children[$cname] = array();
2828
				}
2829
				$children[$cname] = array_merge($children[$cname], $child);
2830

    
2831
				$descr = "# P2 (reqid {$ph2ent['reqid']})";
2832
				if (!empty($ph2ent['descr'])) {
2833
					$descr .= ": {$ph2ent['descr']}";
2834
				}
2835
				array_unshift($children[$cname], $descr);
2836
			}
2837
		}
2838

    
2839
		$conn['local_addrs'] = $local_spec;
2840
		$conn['remote_addrs'] = $remote_spec;
2841

    
2842
		$pools = array();
2843
		if (isset($ph1ent['mobile'])) {
2844
			if (($ph1ent['authentication_method'] == 'eap-radius') && 
2845
			    empty($a_client['pool_address']) && empty($a_client['pool_address_v6'])) {
2846
				$pools[] = "radius";
2847
			} else {
2848
				if (!empty($a_client['pool_address'])) {
2849
					$pools[] = "mobile-pool-v4";
2850
				}
2851
				if (!empty($a_client['pool_address_v6'])) {
2852
					$pools[] = "mobile-pool-v6";
2853
				}
2854
				if (isset($a_client['radius_ip_priority_enable'])) {
2855
					$pools[] .= "radius";
2856
				}
2857
			}
2858
		}
2859
		if (!empty($pools)) {
2860
			$conn['pools'] = implode(', ', $pools);
2861
		}
2862

    
2863
		/* For IKEv2 without Split Connections, setup combined sets of
2864
		 * local/remote traffic selectors and propsals */
2865
		if (!(!isset($ph1ent['mobile']) && (($ikeversion == 1) || isset($ph1ent['splitconn'])))) {
2866
			if (!isset($ph1ent['mobile']) && !empty($remote_ts_spec)) {
2867
				$children[$cname]['remote_ts'] = implode(",", $remote_ts_spec);
2868
			}
2869
			if (!empty($local_ts_spec)) {
2870
				$children[$cname]['local_ts'] = implode(",", $local_ts_spec);
2871
			}
2872
			if ($has_vti) {
2873
				ipsec_setup_vtireq($children[$cname], $ipsec_vti_cleanup_ifs, $ph1ent);
2874
			}
2875
			if (!empty($ealgoAHsp2arr)) {
2876
				$halgos = array();
2877
				$halgos_sha = array();
2878
				foreach ($ealgoAHsp2arr as $halg) {
2879
					if (strstr($halg, "sha")) {
2880
						/* put SHA ciphers on top, 
2881
						*  see https://redmine.pfsense.org/issues/12323 */
2882
						$halgos_sha[] = $halg;
2883
					} else {
2884
						$halgos[] = $halg;
2885
					}
2886
				}
2887
				$ealgoAHsp2arr = array_merge(array_reverse($halgos_sha), $halgos);
2888
				$children[$cname]['ah_proposals'] = implode(',', array_unique($ealgoAHsp2arr));
2889
			}
2890
			if (!empty($ealgoESPsp2arr)) {
2891
				$children[$cname]['esp_proposals'] = implode(',', array_unique($ealgoESPsp2arr));
2892
			}
2893
		}
2894

    
2895
		/* Setup connection authentication */
2896
		ipsec_setup_authentication($ph1ent, $conn, $gateways_status);
2897

    
2898
		/* Add children to this connection, including default child parameters */
2899
		if (count($children)) {
2900
			foreach($children as $name => $child) {
2901
				$conn['children'][$name] = array_merge($child, $child_params);
2902
			}
2903
		}
2904
		unset ($ph2ent);
2905
	}
2906

    
2907
	return;
2908
}
2909

    
2910
/****f* ipsec/ipsec_setup_secrets
2911
 * NAME
2912
 *   ipsec_setup_secrets - Setup swanctl authentication secrets
2913
 * INPUTS
2914
 *   None
2915
 * RESULT
2916
 *   Returns a swanctl array containing secrets (PSKs, certs, etc) and writes out
2917
 *   necessary CA, CRL, and certificate data.
2918
 ******/
2919
function ipsec_setup_secrets($gateways_status = false) {
2920
	global $config, $a_phase1, $ipsec_swanctl_dirs, $ipseccfg, $rgmap, $scconf;
2921

    
2922
	$suffix = 0;
2923

    
2924
	/* Fetch gateway status if not passed */
2925
	if (!is_array($gateways_status)) {
2926
		$gateways_status = return_gateways_status(true);
2927
	}
2928

    
2929
	$vpncas = array();
2930
	if (is_array($a_phase1) && count($a_phase1)) {
2931
		foreach ($a_phase1 as $ph1ent) {
2932
			if (isset($ph1ent['disabled'])) {
2933
				continue;
2934
			}
2935

    
2936
			if (isset($ph1ent['mobile'])) {
2937
				if ($ph1ent['authentication_method'] == 'pre_shared_key') {
2938
					$mobilepsk = true;
2939
				} elseif ($ph1ent['authentication_method'] == 'eap-mschapv2') {
2940
					$mobileeap = true;
2941
				}
2942
			}
2943

    
2944
			if (strstr($ph1ent['authentication_method'], 'cert') ||
2945
			    in_array($ph1ent['authentication_method'], array('eap-mschapv2', 'eap-tls', 'eap-radius'))) {
2946
				/* Write certificate and private key, point to private key */
2947
				$certline = '';
2948

    
2949
				$ikeid = $ph1ent['ikeid'];
2950
				$cert = lookup_cert($ph1ent['certref']);
2951

    
2952
				if (!$cert) {
2953
					log_error(sprintf(gettext("Error: Invalid phase1 certificate reference for %s"), $ph1ent['name']));
2954
					continue;
2955
				}
2956

    
2957
				/* add signing CA cert chain of server cert
2958
				 * to the list of CAs to write
2959
				 */
2960
				$cachain = ca_chain_array($cert);
2961
				if ($cachain && is_array($cachain)) {
2962
					foreach ($cachain as $cacrt) {
2963
						$vpncas[$cacrt['refid']] = $cacrt;
2964
					}
2965
				}
2966

    
2967
				@chmod($ipsec_swanctl_dirs['certpath'], 0600);
2968

    
2969
				$ph1keyfile = "{$ipsec_swanctl_dirs['keypath']}/cert-{$ikeid}.key";
2970
				if (!file_put_contents($ph1keyfile, base64_decode($cert['prv']))) {
2971
					log_error(sprintf(gettext("Error: Cannot write phase1 key file for %s"), $ph1ent['name']));
2972
					continue;
2973
				}
2974
				@chmod($ph1keyfile, 0600);
2975

    
2976
				$ph1certfile = "{$ipsec_swanctl_dirs['certpath']}/cert-{$ikeid}.crt";
2977
				if (!file_put_contents($ph1certfile, base64_decode($cert['crt']))) {
2978
					log_error(sprintf(gettext("Error: Cannot write phase1 certificate file for %s"), $ph1ent['name']));
2979
					@unlink($ph1keyfile);
2980
					continue;
2981
				}
2982
				@chmod($ph1certfile, 0600);
2983

    
2984
				$scconf['secrets']['private-' . $suffix++] = array('file' => $ph1keyfile);
2985
			} else if (strstr($ph1ent['authentication_method'], 'pkcs11')) {
2986
				$p11_id = array();
2987
				$output = shell_exec('/usr/local/bin/pkcs15-tool -c');
2988
				preg_match_all('/ID\s+: (.*)/', $output, $p11_id);
2989
				if (!empty($ph1ent['pkcs11certref']) && in_array($ph1ent['pkcs11certref'], $p11_id[1])) {
2990
					$scconf['secrets']['token-' . $suffix++] = array(
2991
						'handle' => $ph1ent['pkcs11certref'],
2992
						'pin' => $ph1ent['pkcs11pin'],
2993
					);
2994
				} else {
2995
					log_error(sprintf(gettext("Error: Invalid phase1 PKCS#11 certificate reference or PKCS#11 is not present for %s"), $ph1ent['name']));
2996
					continue;
2997
				}
2998
			} else {
2999
				/* Setup pre-shared keys */
3000
				list($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local', array(), $gateways_status);
3001
				list($peerid_type, $peerid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap, $gateways_status);
3002
				$myid = trim($myid_data);
3003

    
3004
				if (empty($peerid_data)) {
3005
					continue;
3006
				}
3007

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

    
3011
				if (!empty($ph1ent['pre-shared-key'])) {
3012
					$scconf['secrets']['ike-' . $suffix++] = array(
3013
						'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
3014
						'id-0' => $myid,
3015
						'id-1' => $peerid,
3016
					);
3017
					if (isset($ph1ent['mobile'])) {
3018
						$scconf['secrets']['ike-' . $suffix++] = array(
3019
							'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
3020
							'id-0' => $myid,
3021
							'id-1' => '%any',
3022
						);
3023
						$scconf['secrets']['ike-' . $suffix++] = array(
3024
							'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
3025
						);
3026
					}
3027
				}
3028
			}
3029

    
3030
			/* if the client authenticates with a cert add the
3031
			 * client cert CA chain to the list of CAs to write
3032
			 */
3033
			if (in_array($ph1ent['authentication_method'],
3034
			    array('cert', 'eap-tls', 'xauth_cert_server', 'pkcs11'))) {
3035
				if (!empty($ph1ent['caref']) && !array_key_exists($ph1ent['caref'], $vpncas)) {
3036
					$thisca = lookup_ca($ph1ent['caref']);
3037
					$vpncas[$ph1ent['caref']] = $thisca;
3038
					/* follow chain up to root */
3039
					$cachain = ca_chain_array($thisca);
3040
					if ($cachain and is_array($cachain)) {
3041
						foreach ($cachain as $cacrt) {
3042
							$vpncas[$cacrt['refid']] = $cacrt;
3043
						}
3044
					}
3045
				}
3046
			}
3047
		}
3048
	}
3049

    
3050
	/* Write the required CAs */
3051
	foreach ($vpncas as $carefid => $cadata) {
3052
		$cacrt = base64_decode($cadata['crt']);
3053
		$cacrtattrs = openssl_x509_parse($cacrt);
3054
		if (!is_array($cacrtattrs) || !isset($cacrtattrs['hash'])) {
3055
			log_error(sprintf(gettext("Error: Invalid certificate hash info for %s"), $cadata['descr']));
3056
			continue;
3057
		}
3058
		$cafilename = "{$ipsec_swanctl_dirs['capath']}/{$cacrtattrs['hash']}.0";
3059
		if (!@file_put_contents($cafilename, $cacrt)) {
3060
				log_error(sprintf(gettext("Error: Cannot write IPsec CA file for %s"), $cadata['descr']));
3061
				continue;
3062
		}
3063
	}
3064

    
3065
	/* write out CRL files */
3066
	if (is_array($config['crl']) && count($config['crl']) && !empty($vpncas)) {
3067
		foreach ($config['crl'] as $crl) {
3068
			if (!isset($crl['text'])) {
3069
				log_error(sprintf(gettext("Warning: Missing CRL data for %s"), $crl['descr']));
3070
				continue;
3071
			}
3072
			$fpath = "{$ipsec_swanctl_dirs['crlpath']}/{$crl['refid']}.crl";
3073
			if (!@file_put_contents($fpath, base64_decode($crl['text']))) {
3074
				log_error(sprintf(gettext("Error: Cannot write IPsec CRL file for %s"), $crl['descr']));
3075
				continue;
3076
			}
3077
		}
3078
	}
3079

    
3080
	/* Add user PSKs */
3081
	if ($mobilepsk && is_array($config['system']) && is_array($config['system']['user'])) {
3082
		foreach ($config['system']['user'] as $user) {
3083
			if (!empty($user['ipsecpsk'])) {
3084
				$scconf['secrets']['ike-' . $suffix++] = array(
3085
					'secret' => '0s' . base64_encode(trim($user['ipsecpsk'])),
3086
					'id-0' => $myid,
3087
					'id-1' => $user['name'],
3088
				);
3089
			}
3090
		}
3091
		unset($user);
3092
	}
3093

    
3094
	/* add PSKs/EAPs for mobile clients */
3095
	if (is_array($ipseccfg['mobilekey'])) {
3096
		foreach ($ipseccfg['mobilekey'] as $key) {
3097
			if (($mobileeap && ($key['type'] == 'EAP')) ||
3098
			    ($key['type'] == 'PSK')) {
3099
				if (($key['ident'] == 'allusers') ||
3100
				    ($key['ident'] == 'any')) {
3101
					$key['ident'] = '%any';
3102
				}
3103
				$userkeyprefix = (strtolower($key['type']) == 'eap') ? 'eap' : 'ike';
3104
				$scconf['secrets'][$userkeyprefix . '-' . $suffix++] = array(
3105
					'secret' => '0s' . base64_encode(trim($key['pre-shared-key'])),
3106
					'id-0' => $key['ident'],
3107
				);
3108
			}
3109
		}
3110
		unset($key);
3111
	}
3112
	return;
3113
}
3114

    
3115
/****f* ipsec/ipsec_configure
3116
 * NAME
3117
 *   ipsec_configure - Configure IPsec
3118
 * INPUTS
3119
 *   $restart: Boolean (default false), whether or not to restart the IPsec
3120
 *             daemons.
3121
 * RESULT
3122
 *   IPsec-related configuration files are written, daemon is started or stopped
3123
 *   appropriately.
3124
 ******/
3125
function ipsec_configure($restart = false) {
3126
	global $aggressive_mode_psk, $a_client, $a_phase1, $a_phase2, $config,
3127
		$filterdns_list, $g, $ifacesuse, $ipsec_idhandling, $ipsec_log_cats,
3128
		$ipsec_log_sevs, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs,
3129
		$ipseccfg, $mobile_ipsec_auth, $natfilterrules, $p1_ealgos,
3130
		$p2_ealgos, $rgmap, $sa, $sn, $scconf, $tunnels, $mobile_configured,
3131
		$ipsec_vti_cleanup_ifs, $conn_defaults, $pool_addrs;
3132

    
3133
	/* service may have been enabled, disabled, or otherwise changed in a
3134
	 *way requiring rule updates */
3135
	filter_configure();
3136

    
3137
	if (!ipsec_enabled()) {
3138
		/* IPsec is disabled */
3139
		/* Stop charon */
3140
		mwexec("/usr/local/sbin/strongswanrc stop");
3141
		/* Stop dynamic monitoring */
3142
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3143
		/* Wait for process to die */
3144
		sleep(2);
3145
		/* Stop PC/SC Smart Card Services */
3146
		killbyname("pcscd");
3147
		/* Shutdown enc0 interface*/
3148
		mwexec("/sbin/ifconfig enc0 down");
3149
		ipsec_gre_default_mtu(); 
3150
		return 0;
3151
	} else {
3152
		/* Startup enc0 interface */
3153
		mwexec("/sbin/ifconfig enc0 up");
3154
		/* PC/SC daemon must be started before strongswan */
3155
		if (isset($config['ipsec']['pkcs11support']) && !isvalidproc("pcscd")) {
3156
			if (platform_booting()) {
3157
				echo gettext("Starting PC/SC Smart Card Services...");
3158
			}
3159
			mwexec_bg("/usr/local/sbin/pcscd");
3160
			if (platform_booting()) {
3161
				echo gettext("done.\n");
3162
			}
3163
		} elseif (!isset($config['ipsec']['pkcs11support']) && isvalidproc("pcscd")) {
3164
			/* strongswan must be stopped first, otherwise it will flood the logs */
3165
			mwexec("/usr/local/sbin/strongswanrc stop");
3166
			killbyname("pcscd");
3167
		}
3168
	}
3169

    
3170
	if (platform_booting()) {
3171
		echo gettext("Configuring IPsec VPN... ");
3172
	}
3173

    
3174
	$ipsecstartlock = lock('ipsec', LOCK_EX);
3175

    
3176
	/* Prepare automatic ping_hosts.sh data */
3177
	unlink_if_exists("{$g['vardb_path']}/ipsecpinghosts");
3178
	touch("{$g['vardb_path']}/ipsecpinghosts");
3179
	$ipsecpinghostsactive = false;
3180

    
3181
	/* Populate convenience variables */
3182
	$syscfg = $config['system'];
3183
	init_config_arr(array('ipsec', 'phase1'));
3184
	$ipseccfg = $config['ipsec'];
3185
	$a_phase1 = $config['ipsec']['phase1'];
3186
	init_config_arr(array('ipsec', 'phase2'));
3187
	$a_phase2 = $config['ipsec']['phase2'];
3188
	init_config_arr(array('ipsec', 'client'));
3189
	$a_client = $config['ipsec']['client'];
3190

    
3191
	$mobile_configured = false;
3192

    
3193

    
3194
	/* Setup a single structured array to process, to avoid repeatedly
3195
	 * looping through the arrays to locate entries later. */
3196
	$tunnels = array();
3197
	foreach ($a_phase1 as $p1) {
3198
		if (empty($p1)) {
3199
			continue;
3200
		}
3201
		if (isset($p1['mobile']) && !isset($p1['disabled'])) {
3202
			$mobile_configured = true;
3203
		}
3204
		$tunnels[$p1['ikeid']] = $p1;
3205
		$tunnels[$p1['ikeid']]['p2'] = array();
3206
	}
3207
	foreach ($a_phase2 as $p2) {
3208
		$tunnels[$p2['ikeid']]['p2'][] = $p2;
3209
	}
3210

    
3211
	$ipsec_vti_cleanup_ifs = array();
3212
	$rgmap = array();
3213
	$filterdns_list = array();
3214
	$aggressive_mode_psk = false;
3215
	$mobile_ipsec_auth = "";
3216
	$ifacesuse = array();
3217
	$natfilterrules = false;
3218

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

    
3222
	/* Build a list of all IPsec interfaces configured on the firewall at the OS level */
3223
	$gateways_status = return_gateways_status(true);
3224
	foreach (get_interface_arr() as $thisif) {
3225
		if (substr($thisif, 0, 5) == "ipsec") {
3226
			$ipsec_vti_cleanup_ifs[] = $thisif;
3227
		}
3228
	}
3229
	/* Create directory structure for IPsec */
3230
	ipsec_create_dirs();
3231
	/* Setup gateways and interfaces */
3232
	ipsec_setup_gwifs($gateways_status);
3233
	/* Setup and write strongswan.conf */
3234
	ipsec_setup_strongswan();
3235
	/* Start Global Connection default values */
3236
	$conn_defaults = array();
3237
	/* Fragmentation is on for everyone */
3238
	$conn_defaults['fragmentation'] = "yes";
3239
	/* Default to 'replace' for unique IDs (was 'yes' in ipsec.conf previously) */
3240
	$conn_defaults['unique'] = 'replace';
3241
	/* If the configuration has a valid alternate value for unique ID handling,
3242
	 * use it instead. */
3243
	if (!empty($config['ipsec']['uniqueids']) &&
3244
	    array_key_exists($config['ipsec']['uniqueids'], $ipsec_idhandling)) {
3245
		$conn_defaults['unique'] = $config['ipsec']['uniqueids'];
3246
	}
3247
	/* Disable ipcomp for now. redmine #6167
3248
	if (isset($config['ipsec']['compression'])) {
3249
		$conn_defaults['compress'] = "yes";
3250
	}
3251
	set_single_sysctl('net.inet.ipcomp.ipcomp_enable', (isset($config['ipsec']['compression'])) ? 1 : 0);
3252
	*/
3253
	/* End Global Connection Defaults */
3254

    
3255
	/* Start swanctl configuration (scconf) */
3256
	$scconf = array();
3257
	$scconf[] = "# This file is automatically generated. Do not edit";
3258
	$scconf['connections'] = array();
3259
	/* Setup IPsec bypass */
3260
	ipsec_setup_bypass($gateways_status);
3261
	/* Setup connections */
3262
	ipsec_setup_tunnels($gateways_status);
3263
	$scconf['pools'] = array();
3264
	if ($mobile_configured) {
3265
		/* Setup mobile address pools */
3266
		ipsec_setup_pools();
3267
		/* Setup per-user pools */
3268
		ipsec_setup_userpools();
3269
	}
3270
	/* Setup secret data */
3271
	$scconf['secrets'] = array();
3272
	ipsec_setup_secrets($gateways_status);
3273

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

    
3276
	/* Clean up unused VTI interfaces */
3277
	foreach ($ipsec_vti_cleanup_ifs as $cleanif) {
3278
		if (does_interface_exist($cleanif)) {
3279
			mwexec("/sbin/ifconfig " . escapeshellarg($cleanif) . " destroy", false);
3280
		}
3281
	}
3282

    
3283
	/* set default MTU to 1400 for GRE over IPsec, othewise to 1476 */
3284
	ipsec_gre_default_mtu(); 
3285

    
3286
	/* Manage process */
3287
	if ($restart === true) {
3288
		mwexec_bg("/usr/local/sbin/strongswanrc restart", false);
3289
	} else {
3290
		if (isvalidpid("{$g['varrun_path']}/charon.pid")) {
3291
			mwexec_bg("/usr/local/sbin/strongswanrc reload", false);
3292
		} else {
3293
			mwexec_bg("/usr/local/sbin/strongswanrc start", false);
3294
		}
3295
	}
3296

    
3297
	// Run ping_hosts.sh once if it's enabled to avoid wait for minicron
3298
	if ($ipsecpinghostsactive) {
3299
		mwexec_bg("/usr/local/bin/ping_hosts.sh");
3300
	}
3301

    
3302
	if ($natfilterrules == true) {
3303
		filter_configure();
3304
	}
3305
	/* start filterdns, if necessary */
3306
	if (count($filterdns_list) > 0) {
3307
		$interval = 60;
3308
		if (!empty($ipseccfg['dns-interval']) && is_numeric($ipseccfg['dns-interval'])) {
3309
			$interval = $ipseccfg['dns-interval'];
3310
		}
3311

    
3312
		$hostnames = "";
3313
		array_unique($filterdns_list);
3314
		foreach ($filterdns_list as $hostname) {
3315
			$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload ipsecdns\"'\n";
3316
		}
3317
		file_put_contents("{$g['varetc_path']}/ipsec/filterdns-ipsec.hosts", $hostnames);
3318
		unset($hostnames);
3319

    
3320
		if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid")) {
3321
			sigkillbypid("{$g['varrun_path']}/filterdns-ipsec.pid", "HUP");
3322
		} else {
3323
			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");
3324
		}
3325
	} else {
3326
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3327
		@unlink("{$g['varrun_path']}/filterdns-ipsec.pid");
3328
	}
3329

    
3330
	if (platform_booting()) {
3331
		echo "done\n";
3332
	}
3333

    
3334
	unlock($ipsecstartlock);
3335
	return count($filterdns_list);
3336
}
3337

    
3338
function ipsec_gre_default_mtu() {
3339
	global $config;
3340

    
3341
	foreach ($config['interfaces'] as $if => $ifdetail) { 
3342
		if (interface_is_type($ifdetail['if'], 'gre') && !isset($ifdetail['mtu'])) {
3343
			if (is_greipsec($ifdetail['if'])) {
3344
				set_interface_mtu($ifdetail['if'], 1400);
3345
			} else {
3346
				set_interface_mtu($ifdetail['if'], 1476);
3347
			}
3348
		}
3349
	}
3350
}
3351

    
3352
/* Return the larger of derived SA rekey time and reauth time */
3353
function ipsec_get_renewmax($entry) {
3354
	if (empty($entry) || !is_array($entry)) {
3355
		return 0;
3356
	}
3357
	return max(ipsec_get_rekey_time($entry), ipsec_get_reauth_time($entry));
3358
}
3359

    
3360
/* Determine the life time of an SA entry (Hard upper total time limit for SA before it is removed) */
3361
function ipsec_get_life_time($entry) {
3362
	if (empty($entry) || !is_array($entry)) {
3363
		return 0;
3364
	}
3365
	/* Use a hardcoded value if present in the configuration */
3366
	if ($entry['lifetime'] > 0) {
3367
		return $entry['lifetime'];
3368
	}
3369
	/* If rekey or reauth are enabled, attempt to derive a lifetime from one of those */
3370
	$renewmax = ipsec_get_renewmax($entry);
3371
	if ($renewmax > 0) {
3372
		return intval($renewmax / 0.9);
3373
	}
3374
	/* To reach here, rekey_time and lifetime are both 0 which is invalid
3375
	 * Default to 16000 for p1 and 4000 for p2 */
3376
	if ($entry['iketype']) {
3377
		return 16000;
3378
	} else {
3379
		return 4000;
3380
	}
3381
}
3382

    
3383
/* Determine the rekey time of an SA entry (Time at which to rekey IKEv2 or Child SA entries) */
3384
function ipsec_get_rekey_time($entry) {
3385
	if (empty($entry) || !is_array($entry)) {
3386
		return 0;
3387
	}
3388
	/* Use a hardcoded value if present in the configuration */
3389
	if (strlen($entry['rekey_time'])) {
3390
		/* Check via strlen since 0 is a valid value */
3391
		return $entry['rekey_time'];
3392
	} elseif ($entry['lifetime'] > 0) {
3393
		/* If rekey_time is empty and lifetime is non-zero, use 90% lifetime */
3394
		return intval($entry['lifetime'] * 0.9);
3395
	}
3396
	/* To reach here, rekey_time and lifetime are empty
3397
	 * Default to 14400 for p1 and 3600 for p2 */
3398
	if ($entry['iketype']) {
3399
		return 14400;
3400
	} else {
3401
		return 3600;
3402
	}
3403
}
3404

    
3405
/* Determine the reauth time of an SA entry (IKE SA tear-down/reauthenticate) */
3406
function ipsec_get_reauth_time($entry) {
3407
	if (empty($entry) || !is_array($entry)) {
3408
		return 0;
3409
	}
3410
	/* Use a hardcoded value if present in the configuration */
3411
	if (strlen($entry['reauth_time'])) {
3412
		/* Check via strlen since 0 is a valid value */
3413
		return $entry['reauth_time'];
3414
	} elseif ($entry['lifetime'] > 0) {
3415
		/* If reauth_time is empty and lifetime is non-zero,
3416
		 * use 90% lifetime for IKEv1, disable for IKEv2/auto */
3417
		if ($entry['iketype'] == 'ikev1') {
3418
			return intval($entry['lifetime'] * 0.9);
3419
		} else {
3420
			return 0;
3421
		}
3422
	}
3423
	/* To reach here, rekey_time and lifetime are empty
3424
	 * Default to disabled (0) */
3425
	return 0;
3426
}
3427

    
3428
/* Determine the over time of an SA entry (Hard upper IKE SA time limit, relative to rekey/reauth time) */
3429
function ipsec_get_over_time($entry) {
3430
	if (empty($entry) || !is_array($entry)) {
3431
		return 0;
3432
	}
3433
	/* Automatically derive the value for rand_time */
3434
	$lifetime = ipsec_get_life_time($entry);
3435
	$renewmax = ipsec_get_renewmax($entry);
3436
	if (($lifetime > 0) && ($renewmax > 0)) {
3437
		/* If life time and rekey/reauth time both have values, subtract to get rand time */
3438
		return $lifetime - $renewmax;
3439
	} elseif ($lifetime > 0) {
3440
		/* If only life time has a value, use 10% of that */
3441
		return intval($lifetime * 0.1);
3442
	} elseif ($renewmax > 0) {
3443
		/* If only rekey/reauth time has a value, use 10% of that */
3444
		return intval($renewmax * 0.1);
3445
	}
3446
	/* No value can be determined, default to 0 */
3447
	return 0;
3448
}
3449

    
3450
/* Determine the rand time of an SA entry (random value subtracted from renewal time to prevent collisions) */
3451
function ipsec_get_rand_time($entry) {
3452
	if (empty($entry) || !is_array($entry)) {
3453
		return 0;
3454
	}
3455
	/* Use a hardcoded value if present in the configuration */
3456
	if (strlen($entry['rand_time'])) {
3457
		/* Check via strlen since 0 is a valid value */
3458
		return $entry['rand_time'];
3459
	}
3460
	/* Logic to automatically determine rand time is identical to calculating over time */
3461
	return ipsec_get_over_time($entry);
3462
}
3463

    
3464
?>
(26-26/61)