Project

General

Profile

Download (109 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
			$result = resolve_retry($rg, $ph1ent['protocol']);
547
			if (!empty($result)) {
548
				return $result;
549
			} else {
550
				return false;
551
			}
552
		}
553
	}
554
	if (!is_ipaddr($rg)) {
555
		return false;
556
	}
557

    
558
	return $rg;
559
}
560

    
561
/*
562
 * Return phase2 idinfo in cidr format
563
 */
564
function ipsec_idinfo_to_cidr(& $idinfo, $addrbits = false, $mode = "") {
565
	global $config;
566

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

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

    
610
/*
611
 * Return phase2 idinfo in address/netmask format
612
 */
613
function ipsec_idinfo_to_subnet(& $idinfo, $addrbits = false) {
614
	global $config;
615

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

    
651
/*
652
 *  Return phase2 idinfo in text format
653
 */
654
function ipsec_idinfo_to_text(& $idinfo) {
655
	global $config;
656

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

    
680
/*
681
 * Wrapper to call pfSense_ipsec_list_sa() when IPsec is enabled
682
 */
683
function ipsec_list_sa() {
684
	if (ipsec_enabled()) {
685
		return pfSense_ipsec_list_sa();
686
	}
687
	return array();
688
}
689

    
690
function ipsec_status() {
691
	$cmap = ipsec_map_config_by_id();
692
	$status = ipsec_list_sa();
693

    
694
	/*
695
	Start:
696
	$cmap[$ikeid]['p1'] => Phase 1 config
697
	$cmap[$ikeid]['p2'] => Array of P2 configs indexed by reqid
698

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

    
706
	if (!is_array($status)) {
707
		$status = array();
708
	}
709

    
710
	$cmap['connected'] = array(
711
		/* List of connected P1 conid entries (excluding mobile) */
712
		'p1' => array(),
713
		/* List of connected P2 conid entries (excluding mobile) */
714
		'p2' => array(),
715
	);
716
	$cmap['disconnected'] = array(
717
		/* List of disconnected P1 conid entries (excluding mobile) */
718
		'p1' => array(),
719
		/* List of disconnected P2 conid entries (excluding mobile) */
720
		'p2' => array(),
721
	);
722

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

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

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

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

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

    
818
	$title .= " ";
819
	switch ($type) {
820
		case 'all':
821
			$title .= gettext("P1 and P2s");
822
			break;
823
		case 'child':
824
			$title .= gettext("P2");
825
			break;
826
		case 'ike':
827
		default:
828
			$title .= gettext("P1");
829
			break;
830
	}
831

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

    
849
	$btn .= '"';
850
	if ($full) {
851
		$btn .= ' class="' . htmlspecialchars($linkclass) . '"';
852
	}
853
	$btn .= ' title="' . htmlspecialchars($title) . '"';
854

    
855
	if ($req == 'post') {
856
		$btn .= ' usepost';
857
	}
858
	$btn .= '>';
859
	$btn .= '<i class="fa fa-' . htmlspecialchars($icon);
860
	if ($req == 'post') {
861
		$btn .= ' icon-embed-btn';
862
	}
863
	$btn .= '"></i>';
864

    
865
	if ($full) {
866
		$btn .= ' ' . htmlspecialchars($title);
867
	}
868
	$btn .= '</a>';
869
	return $btn;
870
}
871

    
872
function ipsec_initiate($type = 'ike', $p1 = null, $p2 = null) {
873
	return ipsec_initiate_by_conid($type, ipsec_conid($p1, $p2));
874
}
875

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

    
907
function ipsec_terminate($type = 'ike', $p1 = null, $p2 = null, $uniqueid = null) {
908
	return ipsec_terminate_by_conid($type, ipsec_conid($p1, $p2), $uniqueid);
909
}
910

    
911
function ipsec_terminate_by_conid($type = 'ike', $conid = null, $uniqueid = null) {
912
	/* Must have one or the other */
913
	if (($conid === null) && ($uniqueid === null)) {
914
		return false;
915
	}
916
	$selector = '--';
917
	$selector .= ($type == 'ike') ? 'ike' : 'child';
918

    
919
	if (ctype_digit($uniqueid) && ($uniqueid > 0)) {
920
		$selector .= '-id';
921
		$term = $uniqueid;
922
	} else {
923
		$term = $conid;
924
	}
925
	mwexec_bg("/usr/local/sbin/swanctl --terminate --force " . escapeshellarg($selector) . " " . escapeshellarg($term));
926
	return true;
927
}
928

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

    
989
	return $spd;
990
}
991

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

    
1042
	return $sad;
1043
}
1044

    
1045
/*
1046
 * Return dump of mobile user list
1047
 */
1048
function ipsec_dump_mobile() {
1049
	global $g, $config;
1050

    
1051
	if(!isset($config['ipsec']['client']['enable'])) {
1052
		return array();
1053
	}
1054

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

    
1058
	if ($rc != 0) {
1059
		log_error(gettext("Unable to find IPsec daemon leases file. Could not display mobile user stats!"));
1060
		return array();
1061
	}
1062

    
1063
	$response = array(
1064
		'pool' => array(),
1065
	);
1066

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

    
1092
	unset($_gb, $output, $rc, $pool_regex);
1093

    
1094
	return $response;
1095
}
1096

    
1097
function ipsec_mobilekey_sort() {
1098
	global $config;
1099

    
1100
	function mobilekeycmp($a, $b) {
1101
		return strcmp($a['ident'][0], $b['ident'][0]);
1102
	}
1103

    
1104
	usort($config['ipsec']['mobilekey'], "mobilekeycmp");
1105
}
1106

    
1107
function ipsec_fixup_ip($ipaddr) {
1108
	if (is_ipaddrv6($ipaddr) || is_subnetv6($ipaddr)) {
1109
		return text_to_compressed_ip6($ipaddr);
1110
	} else {
1111
		return $ipaddr;
1112
	}
1113
}
1114

    
1115
function ipsec_find_id(& $ph1ent, $side = "local", $rgmap = array(), $gateways_status = false) {
1116
	if ($side == "local") {
1117
		$id_type = $ph1ent['myid_type'];
1118
		$id_data = $ph1ent['myid_data'];
1119

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

    
1131
		if (isset($ph1ent['mobile'])) {
1132
			$addr = "%any";
1133
		} else {
1134
			$addr = $ph1ent['remote-gateway'];
1135
		}
1136
	} else {
1137
		return array();
1138
	}
1139

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

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

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

    
1192
	if ($type == 'any') {
1193
		$idstring = "%any";
1194
	} elseif (!in_array($type, $auto_types)) {
1195
		$idstring = "{$type}:{$data}";
1196
	} else {
1197
		$idstring = $data;
1198
	}
1199

    
1200
	if (in_array($type, $quote_types)) {
1201
		$idstring = "\"{$idstring}\"";
1202
	}
1203

    
1204
	return $idstring;
1205
}
1206

    
1207
function ipsec_fixup_network($network) {
1208
	if (substr($network, -3) == '|/0') {
1209
		$result = substr($network, 0, -3);
1210
	} else {
1211
		$tmp = explode('|', $network);
1212
		if (isset($tmp[1])) {
1213
			$result = $tmp[1];
1214
		} else {
1215
			$result = $tmp[0];
1216
		}
1217
		unset($tmp);
1218
	}
1219

    
1220
	return $result;
1221
}
1222

    
1223
function ipsec_get_loglevels() {
1224
	global $config, $ipsec_log_cats;
1225
	$def_loglevel = '1';
1226

    
1227
	$levels = array();
1228

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

    
1241
function ipsec_vti($p1, $returnaddresses = false, $skipdisabled = true) {
1242
	global $config;
1243
	$is_vti = false;
1244
	$vtisubnet_spec = array();
1245

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

    
1266
/* Called when IPsec is reloaded through rc.newipsecdns and similar, gives
1267
 * packages an opportunity to execute custom code when IPsec reloads.
1268
 */
1269
function ipsec_reload_package_hook() {
1270
	global $g, $config;
1271

    
1272
	init_config_arr(array('installedpackages', 'package'));
1273
	foreach ($config['installedpackages']['package'] as $package) {
1274
		if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
1275
			continue;
1276
		}
1277

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

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

    
1329
	return $modpmap[$index];
1330
}
1331

    
1332
/*
1333
 * Forcefully restart IPsec
1334
 * This is required for when dynamic interfaces reload
1335
 * For all other occasions the normal ipsec_configure()
1336
 * will gracefully reload the settings without restarting
1337
 */
1338
function ipsec_force_reload($interface = "", $protocol = "") {
1339
	global $g, $config;
1340

    
1341
	if (!ipsec_enabled()) {
1342
		return;
1343
	}
1344

    
1345
	$ipseccfg = $config['ipsec'];
1346

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

    
1371
				/* Find the real active passed interface for this address family, cache the result */
1372
				if (empty($realif) ||
1373
				    empty($realif[$fam])) {
1374
					$realif[$fam] = get_failover_interface($interface, $fam, $gateways_status);
1375
				}
1376

    
1377
				/* Find the real active tunnel interface for this address family, cache the result */
1378
				if (empty($ifcache) ||
1379
				    empty($ifcache[$ipsec['interface']]) ||
1380
				    empty($ifcache[$ipsec['interface']][$fam])) {
1381
					if (!is_array($ifcache[$ipsec['interface']])) {
1382
						$ifcache[$ipsec['interface']] = array();
1383
					}
1384
					$ifcache[$ipsec['interface']][$fam] = get_failover_interface($ipsec['interface'], $fam, $gateways_status);
1385
				}
1386

    
1387
				if ($realif[$fam] == $ifcache[$ipsec['interface']][$fam]) {
1388
					$found = true;
1389
					break;
1390
				}
1391
			}
1392
		}
1393
		if (!$found) {
1394
			log_error(sprintf(gettext("Ignoring IPsec reload since there are no tunnels on interface %s"), $interface));
1395
			return;
1396
		}
1397
	}
1398

    
1399
	/* If we get this far then we need to take action. */
1400
	log_error(gettext("Forcefully reloading IPsec"));
1401
	ipsec_configure();
1402
}
1403

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

    
1448
global $g, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs;
1449
$ipsec_swanctl_basedir = "{$g['varetc_path']}/ipsec";
1450
$ipsec_swanctl_dirs = array(
1451
	'conf'     => "{$ipsec_swanctl_basedir}/conf.d",
1452
	'certpath' => "{$ipsec_swanctl_basedir}/x509",
1453
	'capath'   => "{$ipsec_swanctl_basedir}/x509ca",
1454
	'aapath'   => "{$ipsec_swanctl_basedir}/x509aa",
1455
	'ocsppath' => "{$ipsec_swanctl_basedir}/x509ocsp",
1456
	'crlpath'  => "{$ipsec_swanctl_basedir}/x509crl",
1457
	'acpath'   => "{$ipsec_swanctl_basedir}/x509ac",
1458
	'rsakeys'  => "{$ipsec_swanctl_basedir}/rsa",
1459
	'eckeys'   => "{$ipsec_swanctl_basedir}/ecdsa",
1460
	'keypath'  => "{$ipsec_swanctl_basedir}/private",
1461
	'pubkpath' => "{$ipsec_swanctl_basedir}/pubkey",
1462
	'blisspath' => "{$ipsec_swanctl_basedir}/bliss",
1463
	'pkcs8path' => "{$ipsec_swanctl_basedir}/pkcs8",
1464
	'pkcs12path' => "{$ipsec_swanctl_basedir}/pkcs12",
1465
);
1466

    
1467
/****f* ipsec/ipsec_create_dirs
1468
 * NAME
1469
 *   ipsec_create_dirs - Create default set of strongSwan configuration directories.
1470
 * INPUTS
1471
 *   None
1472
 * RESULT
1473
 *   Cleans up and creates strongSwan configuration directories and links.
1474
 ******/
1475
function ipsec_create_dirs() {
1476
	global $config, $g, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs;
1477

    
1478
	/* Cleanup base paths to ensure old files are not left behind (#5238) */
1479
	if (!empty($ipsec_swanctl_basedir)) {
1480
		@rmdir_recursive($ipsec_swanctl_basedir, false);
1481
	}
1482
	/* Create directory structure */
1483
	array_map('safe_mkdir', array_values($ipsec_swanctl_dirs));
1484

    
1485
	/* Create and link strongSwan config */
1486
	$ssdpath = "{$g['varetc_path']}/ipsec/strongswan.d";
1487
	if (!file_exists($ssdpath) || !is_link($ssdpath)) {
1488
		if (is_dir($ssdpath) && !is_link($ssdpath)) {
1489
			@rmdir_recursive($ssdpath, false);
1490
		} else {
1491
			@unlink($ssdpath);
1492
		}
1493
		@symlink("/usr/local/etc/strongswan.d",
1494
		    $ssdpath);
1495
	}
1496
	if (!file_exists("/usr/local/etc/strongswan.conf") ||
1497
	    !is_link("/usr/local/etc/strongswan.conf")) {
1498
		@unlink("/usr/local/etc/strongswan.conf");
1499
		@symlink("{$g['varetc_path']}/ipsec/strongswan.conf",
1500
		    "/usr/local/etc/strongswan.conf");
1501
	}
1502
}
1503

    
1504
/****f* ipsec/ipsec_setup_gwifs
1505
 * NAME
1506
 *   ipsec_setup_gwifs - Setup IPsec-related interfaces and gateways
1507
 * INPUTS
1508
 *   None
1509
 * RESULT
1510
 *   Sets up VTI interfaces and gateways, populates ipsecpinghosts
1511
 ******/
1512
function ipsec_setup_gwifs($gateways_status = false) {
1513
	global $g, $a_phase1, $a_phase2, $rgmap, $filterdns_list,
1514
		$aggressive_mode_psk, $mobile_ipsec_auth, $ifacesuse,
1515
		$ipsecpinghostsactive;
1516
	/* resolve all local, peer addresses and setup pings */
1517
	/* Fetch gateway status if not passed */
1518
	if (!is_array($gateways_status)) {
1519
		$gateways_status = return_gateways_status(true);
1520
	}
1521

    
1522
	unset($iflist);
1523
	if (is_array($a_phase1) && count($a_phase1)) {
1524
		$ipsecpinghosts = array();
1525
		/* step through each phase1 entry */
1526
		foreach ($a_phase1 as $ph1ent) {
1527
			if (isset($ph1ent['disabled'])) {
1528
				continue;
1529
			}
1530
			if (substr($ph1ent['interface'], 0, 4) == "_vip") {
1531
				$vpninterface = get_configured_vip_interface($ph1ent['interface']);
1532
				$ifacesuse[] = get_real_interface($vpninterface);
1533
			} else {
1534
				$vpninterface = get_failover_interface($ph1ent['interface'], 'all', $gateways_status);
1535
				if (substr($vpninterface, 0, 4) == "_vip") {
1536
					$vpninterface = get_configured_vip_interface($vpninterface);
1537
					$ifacesuse[] = get_real_interface($vpninterface);
1538
				} elseif (!empty($vpninterface)) {
1539
					$ifacesuse[] = $vpninterface;
1540
				}
1541
			}
1542
			if ($ph1ent['mode'] == "aggressive" && ($ph1ent['authentication_method'] == "pre_shared_key" || $ph1ent['authentication_method'] == "xauth_psk_server")) {
1543
				$aggressive_mode_psk = true;
1544
			}
1545

    
1546
			$ikeid = $ph1ent['ikeid'];
1547

    
1548
			$local_spec = ipsec_get_phase1_src($ph1ent, $gateways_status);
1549
			/* When automatically guessing, use the first address. */
1550
			$local_spec  = explode(',', $local_spec);
1551
			$local_spec  = $local_spec[0];
1552
			if (!is_ipaddr($local_spec)) {
1553
				log_error(sprintf(gettext("IPsec ERROR: Could not find phase 1 source for connection %s. Omitting from configuration file."), $ph1ent['descr']));
1554
				continue;
1555
			}
1556

    
1557
			if (isset($ph1ent['mobile'])) {
1558
				$mobile_ipsec_auth = $ph1ent['authentication_method'];
1559
				continue;
1560
			}
1561

    
1562
			/* see if this tunnel has a hostname for the remote-gateway. If so,
1563
			   try to resolve it now and add it to the list for filterdns */
1564
			$rg = $ph1ent['remote-gateway'];
1565
			if (!is_ipaddr($rg)) {
1566
				$filterdns_list[] = "{$rg}";
1567
				if (!platform_booting()) {
1568
					$rg = resolve_retry($rg, $ph1ent['protocol']);
1569
				}
1570
				if (!is_ipaddr($rg)) {
1571
					continue;
1572
				}
1573
			}
1574
			if (!isset($ph1ent['gw_duplicates']) && array_search($rg, $rgmap)) {
1575
				log_error(sprintf(gettext("The remote gateway %s already exists on another phase 1 entry"), $rg));
1576
				continue;
1577
			}
1578
			$rgmap[$ph1ent['remote-gateway']] = $rg;
1579

    
1580
			$is_vti = false;
1581
			if (is_array($a_phase2)) {
1582
				/* step through each phase2 entry */
1583
				foreach ($a_phase2 as $ph2ent) {
1584
					if ($ph2ent['ikeid'] != $ph1ent['ikeid']) {
1585
						continue;
1586
					}
1587
					if ($ph2ent['mode'] == 'vti') {
1588
						$is_vti = true;
1589
					}
1590
					if (isset($ph2ent['disabled']) || ($ikeid != $ph2ent['ikeid'])) {
1591
						continue;
1592
					}
1593

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

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

    
1677
/****f* ipsec/ipsec_setup_strongswan
1678
 * NAME
1679
 *   ipsec_setup_strongswan - Generate the strongswan.conf configuration file.
1680
 * INPUTS
1681
 *   None
1682
 * RESULT
1683
 *   Determines strongswan.conf values and crafts the configuration file in the
1684
 *   appropriate format.
1685
 * NOTES
1686
 *   Called from ipsec_configure()
1687
 ******/
1688
function ipsec_setup_strongswan() {
1689
	global $config, $g, $mobile_ipsec_auth, $a_client, $a_phase2, $aggressive_mode_psk, $ifacesuse;
1690

    
1691
	/* strongswan.conf array */
1692
	$ssconf = array();
1693
	$ssconf[] = "# Automatically generated config file - DO NOT MODIFY. Changes will be overwritten.";
1694
	$ssconf['starter'] = array();
1695
	$ssconf['starter']['load_warning'] = "no";
1696

    
1697
	$ssconf['charon'] = array();
1698
	$ssconf['charon'][] = '# number of worker threads in charon';
1699
	$ssconf['charon']['threads'] = '16';
1700
	$ssconf['charon']['ikesa_table_size'] = '32';
1701
	$ssconf['charon']['ikesa_table_segments'] = '4';
1702
	$ssconf['charon']['init_limit_half_open'] = '1000';
1703
	$ssconf['charon']['install_routes'] = 'no';
1704
	$ssconf['charon']['load_modular'] = 'yes';
1705
	$ssconf['charon']['ignore_acquire_ts'] = 'yes';
1706

    
1707
	if ($aggressive_mode_psk) {
1708
		$stronconf = '';
1709
		if (file_exists("{$g['varetc_path']}/ipsec/strongswan.conf")) {
1710
			$stronconf = file_get_contents("{$g['varetc_path']}/ipsec/strongswan.conf");
1711
		}
1712
		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.");
1713
		$restart = (!empty($stronconf) && strpos($stronconf, 'i_dont_care_about_security_and_use_aggressive_mode_psk') === FALSE);
1714
		unset($stronconf);
1715
		$ssconf['charon']['i_dont_care_about_security_and_use_aggressive_mode_psk'] = "yes";
1716
	}
1717

    
1718
	if (isset($config['ipsec']['acceptunencryptedmainmode'])) {
1719
		$ssconf['charon']['accept_unencrypted_mainmode_messages'] = "yes";
1720
	}
1721

    
1722
	if (isset($config['ipsec']['maxexchange'])) {
1723
		$ssconf['charon']['max_ikev1_exchanges'] = $config['ipsec']['maxexchange'];
1724
	}
1725

    
1726
	$unity_enabled = isset($config['ipsec']['unityplugin']) ? 'yes' : 'no';
1727
	$ssconf['charon']['cisco_unity'] = $unity_enabled;
1728

    
1729
	if (isset($config['ipsec']['enableinterfacesuse']) && !empty($ifacesuse)) {
1730
		$ssconf['charon']['interfaces_use'] = implode(',', array_unique($ifacesuse));
1731
	}
1732

    
1733
	if (isset($config['ipsec']['makebeforebreak'])) {
1734
		$ssconf['charon']['make_before_break'] = "yes";
1735
	}
1736

    
1737
	if (isset($config['ipsec']['port'])) {
1738
		$ssconf['charon']['port'] = $config['ipsec']['port'];
1739
	}
1740

    
1741
	if (isset($config['ipsec']['port_nat_t'])) {
1742
		$ssconf['charon']['port_nat_t'] = $config['ipsec']['port_nat_t'];
1743
	}
1744

    
1745
	/* IKEv2 retransmit options, see https://redmine.pfsense.org/issues/12184 */
1746
	if (isset($config['ipsec']['ikev2_retransmit_tries'])) {
1747
		$ssconf['charon']['retransmit_tries'] = $config['ipsec']['ikev2_retransmit_tries'];
1748
	}
1749
	if (isset($config['ipsec']['ikev2_retransmit_timeout'])) {
1750
		$ssconf['charon']['retransmit_timeout'] = $config['ipsec']['ikev2_retransmit_timeout'];
1751
	}
1752
	if (isset($config['ipsec']['ikev2_retransmit_base'])) {
1753
		$ssconf['charon']['retransmit_base'] = $config['ipsec']['ikev2_retransmit_base'];
1754
	}
1755
	if (isset($config['ipsec']['ikev2_retransmit_jitter'])) {
1756
		$ssconf['charon']['retransmit_jitter'] = $config['ipsec']['ikev2_retransmit_jitter'];
1757
	}
1758
	if (isset($config['ipsec']['ikev2_retransmit_limit'])) {
1759
		$ssconf['charon']['retransmit_limit'] = $config['ipsec']['ikev2_retransmit_limit'];
1760
	}
1761

    
1762
	$ssconf['charon']['syslog'] = array();
1763
	$ssconf['charon']['syslog']['identifier'] = 'charon';
1764
	$ssconf['charon']['syslog'][] = "# log everything under daemon since it ends up in the same place regardless with our syslog.conf";
1765
	$ssconf['charon']['syslog']['daemon'] = array();
1766
	$ssconf['charon']['syslog']['daemon']['ike_name'] = 'yes';
1767
	$ssconf['charon']['syslog']['daemon'] = array_merge($ssconf['charon']['syslog']['daemon'], ipsec_logging_config());
1768
	$ssconf['charon']['syslog'][] = '# disable logging under auth so logs aren\'t duplicated';
1769
	$ssconf['charon']['syslog']['auth'] = array();
1770
	$ssconf['charon']['syslog']['auth']['default'] = -1;
1771

    
1772
	$ssconf['charon']['plugins'] = array();
1773
	$ssconf['charon']['plugins'][] = "# Load defaults";
1774
	$ssconf['charon']['plugins'][] = "include {$g['varetc_path']}/ipsec/strongswan.d/charon/*.conf";
1775
	$ssconf['charon']['plugins']['unity'] = array('load' => $unity_enabled);
1776
	$ssconf['charon']['plugins']['curve25519'] = array('load' => "yes");
1777

    
1778
	if (isset($config['ipsec']['pkcs11support'])) {
1779
		$ssconf['charon']['plugins']['pkcs11'] = array();
1780
		$ssconf['charon']['plugins']['pkcs11']['load'] = "yes";
1781
		$ssconf['charon']['plugins']['pkcs11']['modules'] = array();
1782
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc'] = array();
1783
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc']['load_certs'] = "yes";
1784
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc']['path'] = "/usr/local/lib/opensc-pkcs11.so";
1785
	}
1786

    
1787
	/* Find RADIUS servers designated for Mobile IPsec user auth */
1788
	$radius_servers = array();
1789
	foreach (explode(',', $config['ipsec']['client']['user_source']) as $user_source) {
1790
		$auth_server = auth_get_authserver($user_source);
1791
		$nice_user_source = strtolower(preg_replace('/[\s\.]+/', '_', $user_source));
1792
		if ($auth_server && ($auth_server['type'] === 'radius')) {
1793
			$radius_servers[$nice_user_source] = array();
1794
			$radius_servers[$nice_user_source]['address'] = $auth_server['host'];
1795
			$radius_servers[$nice_user_source]['secret'] = "\"{$auth_server['radius_secret']}\"";
1796
			$radius_servers[$nice_user_source]['auth_port'] = empty($auth_server['radius_auth_port']) ? 1812 : $auth_server['radius_auth_port'];;
1797
			$radius_servers[$nice_user_source]['acct_port'] = empty($auth_server['radius_acct_port']) ? 1813 : $auth_server['radius_acct_port'];
1798
		}
1799
	}
1800

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

    
1829
	if (is_array($a_client) && isset($a_client['enable'])) {
1830
		if ($a_client['user_source'] != "none") {
1831
			$ssconf['charon']['plugins']['xauth-generic'] = array();
1832
			$ssconf['charon']['plugins']['xauth-generic']['script'] = "/etc/inc/ipsec.auth-user.php";
1833
			$authcfgs = array();
1834
			foreach (explode(",", $a_client['user_source']) as $authcfg) {
1835
				$authcfgs[] = ($authcfg == "system") ? "Local Database" : $authcfg;
1836
			}
1837
			$ssconf['charon']['plugins']['xauth-generic']['authcfg'] = implode(",", $authcfgs);
1838
		}
1839

    
1840
		$ssconf['charon']['plugins']['attr'] = array();
1841

    
1842
		$rightdnsservers = array();
1843
		if (!empty($a_client['dns_server1'])) {
1844
			$rightdnsservers[] = $a_client['dns_server1'];
1845
		}
1846
		if (!empty($a_client['dns_server2'])) {
1847
			$rightdnsservers[] = $a_client['dns_server2'];
1848
		}
1849
		if (!empty($a_client['dns_server3'])) {
1850
			$rightdnsservers[] = $a_client['dns_server3'];
1851
		}
1852
		if (!empty($a_client['dns_server4'])) {
1853
			$rightdnsservers[] = $a_client['dns_server4'];
1854
		}
1855
		if (count($rightdnsservers)) {
1856
			$ssconf['charon']['plugins']['attr']['dns'] = implode(',', $rightdnsservers);
1857
		}
1858

    
1859
		$cfgservers = array();
1860
		if (!empty($a_client['wins_server1'])) {
1861
			$cfgservers[] = $a_client['wins_server1'];
1862
		}
1863
		if (!empty($a_client['wins_server2'])) {
1864
			$cfgservers[] = $a_client['wins_server2'];
1865
		}
1866
		if (!empty($cfgservers)) {
1867
			$ssconf['charon']['plugins']['attr']['nbns'] = implode(',', $cfgservers);
1868
		}
1869
		unset($cfgservers);
1870

    
1871
		$net_list = array();
1872
		if (isset($a_client['net_list']) && is_array($a_phase2)) {
1873
			foreach ($a_phase2 as $ph2ent) {
1874
				if (isset($ph2ent['disabled']) ||
1875
				    !isset($ph2ent['mobile'])) {
1876
					continue;
1877
				}
1878
				$nlent = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
1879
				if (is_subnet($nlent)) {
1880
					$net_list[] = $nlent;
1881
				}
1882
				unset($nlent);
1883
			}
1884
		}
1885

    
1886
		if (!empty($net_list)) {
1887
			$ssconf['charon']['plugins']['attr']['subnet'] = implode(',', $net_list);
1888
			$ssconf['charon']['plugins']['attr']['split-include'] = implode(',', $net_list);
1889
		}
1890

    
1891
		if (!empty($a_client['dns_domain'])) {
1892
			$ssconf['charon']['plugins']['attr'][] = "# Search domain and default domain";
1893
			$ssconf['charon']['plugins']['attr']['27674'] = "\"{$a_client['dns_domain']}\"";
1894
			if (empty($a_client['dns_split'])) {
1895
				$ssconf['charon']['plugins']['attr']['27675'] = "\"{$a_client['dns_domain']}\"";
1896
			}
1897
		}
1898

    
1899
		if (!empty($a_client['dns_split'])) {
1900
			$ssconf['charon']['plugins']['attr'][] = "# Split DNS (UNITY_SPLITDNS_NAME)";
1901
			$ssconf['charon']['plugins']['attr']['28675'] = "\"{$a_client['dns_split']}\"";
1902
			$ssconf['charon']['plugins']['attr'][] = "# Split DNS (INTERNAL_DNS_DOMAIN, RFC 8598)";
1903
			$ssconf['charon']['plugins']['attr']['25'] = "\"{$a_client['dns_split']}\"";
1904
		}
1905

    
1906
		if (!empty($a_client['login_banner'])) {
1907
			$ssconf['charon']['plugins']['attr'][] = "# Login Banner";
1908
			$ssconf['charon']['plugins']['attr']['28672'] = "\"{$a_client['login_banner']}\"";
1909
		}
1910

    
1911
		if (isset($a_client['save_passwd'])) {
1912
			$ssconf['charon']['plugins']['attr'][] = "# Save Xauth Password";
1913
			$ssconf['charon']['plugins']['attr']['28673'] = "1";
1914
		}
1915

    
1916
		if ($a_client['pfs_group']) {
1917
			$ssconf['charon']['plugins']['attr'][] = "# Phase2 PFS Group";
1918
			$ssconf['charon']['plugins']['attr']['28679'] = "\"{$a_client['pfs_group']}\"";
1919
		}
1920
	}
1921

    
1922
	@file_put_contents("{$g['varetc_path']}/ipsec/strongswan.conf", ipsec_strongswan_confgen($ssconf));
1923
}
1924

    
1925
/****f* ipsec/ipsec_setup_pools
1926
 * NAME
1927
 *   ipsec_setup_pools - Generate primary mobile pool configuration for swanctl
1928
  * INPUTS
1929
 *   None
1930
 * RESULT
1931
 *   Adds configured mobile pool settings to $scconf
1932
 * NOTES
1933
 *   These values were formerly in strongswan.conf but may now be configured in
1934
 *   pools, making future expansion to support multiple pools possible.
1935
 ******/
1936
function ipsec_setup_pools() {
1937
	global $config, $g, $mobile_ipsec_auth, $a_client, $a_phase2, $scconf;
1938
	if (!is_array($a_client) || !isset($a_client['enable'])) {
1939
		return;
1940
	}
1941
	if (($mobile_ipsec_auth == "eap-radius") && empty($a_client['pool_address']) &&
1942
	    empty($a_client['pool_address_v6'])) {
1943
		return;
1944
	}
1945

    
1946
	/* Keep the comment in the array to ensure the entry makes it into the
1947
	 * config in all cases.
1948
	 * See https://redmine.pfsense.org/issues/11891 */
1949
	$scconf['mobile-pool'] = array("# Mobile pool settings template");
1950
	$scconf['pools'] = array();
1951
	$pool_common =& $scconf['mobile-pool'];
1952

    
1953
	if (!empty($a_client['pool_address'])) {
1954
		$scconf['pools']['mobile-pool-v4 : mobile-pool'] = array();
1955
		$v4pool =& $scconf['pools']['mobile-pool-v4 : mobile-pool'];
1956
		$v4pool['addrs'] = "{$a_client['pool_address']}/{$a_client['pool_netbits']}";
1957
	}
1958
	if (!empty($a_client['pool_address_v6'])) {
1959
		$scconf['pools']['mobile-pool-v6 : mobile-pool'] = array();
1960
		$v6pool =& $scconf['pools']['mobile-pool-v6 : mobile-pool'];
1961
		$v6pool['addrs'] = "{$a_client['pool_address_v6']}/{$a_client['pool_netbits_v6']}";
1962
	}
1963

    
1964
	return;
1965
}
1966

    
1967
/****f* ipsec/ipsec_setup_userpools
1968
 * NAME
1969
 *   ipsec_setup_userpools - Generate per-user custom pool settings for swanctl
1970
  * INPUTS
1971
 *   None
1972
 * RESULT
1973
 *   Adds configured per-user pool settings to $scconf using the primary mobile
1974
 *   pool as a base configuration.
1975
 * NOTES
1976
 *   Given this new flexible format, it is now possible to override any valid
1977
 *   pool setting, so future expansion of per-user settings is possible.
1978
 ******/
1979
function ipsec_setup_userpools() {
1980
	global $config, $scconf;
1981
	$a_mobilekey = $config['ipsec']['mobilekey'];
1982

    
1983
	/* Do not waste time if we do not have all the necessary information. */
1984
	if (!is_array($a_mobilekey) ||
1985
	    empty($a_mobilekey) ||
1986
	    !is_array($scconf['connections']) ||
1987
	    !is_array($scconf['con-mobile-defaults']) ||
1988
	    !is_array($scconf['pools']) ||
1989
	    !is_array($scconf['mobile-pool'])) {
1990
		return;
1991
	}
1992

    
1993
	$suffix = 1;
1994
	foreach ($a_mobilekey as $mkent) {
1995
		if (($mkent['type'] != "EAP") ||
1996
		    !isset($mkent['ident_type']) ||
1997
		    !isset($mkent['pool_address']) ||
1998
		    !isset($mkent['pool_netbits']) ||
1999
		    (strlen($mkent['pool_address']) < 1) ||
2000
		    !is_ipaddr($mkent['pool_address'])) {
2001
			continue;
2002
		}
2003
		/* The name of just this pool */
2004
		$upbase = "mobile-userpool-{$suffix}";
2005
		/* The full connection name including a reference to the primary
2006
		 * mobile connection */
2007
		$upconn = "con-{$upbase} : con-mobile-defaults";
2008
		/* The full pool name including a reference to the primary
2009
		 * mobile pool */
2010
		$upname = "{$upbase} : mobile-pool";
2011

    
2012
		$scconf['connections'][$upconn] = array();
2013
		$scconf['pools'][$upname] = array();
2014

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

    
2018
		/* Craft a cloned connection with the ID information to match */
2019
		$scconf['connections'][$upconn]['remote'] = array();
2020
		$scconf['connections'][$upconn]['remote']['id'] = $clientid;
2021
		$scconf['connections'][$upconn]['remote']['eap_id'] = $clienteapid;
2022
		$scconf['connections'][$upconn]['pools'] = $upbase;
2023

    
2024
		/* Craft a cloned pool with pool settings to override for this user */
2025
		$scconf['pools'][$upname]['addrs'] = "{$mkent['pool_address']}/{$mkent['pool_netbits']}";
2026
		if (isset($mkent['dns_address']) && strlen($mkent['dns_address']) > 0 && is_ipaddr($mkent['dns_address'])) {
2027
			$scconf['pools'][$upname]['dns'] = $mkent['dns_address'];
2028
		}
2029
		$suffix++;
2030
	}
2031
	return;
2032
}
2033

    
2034
/****f* ipsec/ipsec_setup_bypass
2035
 * NAME
2036
 *   ipsec_setup_bypass - Generate a bypass connection for LAN-LAN and custom rules traffic
2037
 * INPUTS
2038
 *   None
2039
 * RESULT
2040
 *   Sets up a bypass connection to prevent local traffic from being caught by
2041
 *   IPsec policies.
2042
 ******/
2043
function ipsec_setup_bypass($gateways_status) {
2044
	global $config, $scconf;
2045

    
2046
	$scconf['connections']['bypass'] = array();
2047
	/* Prevents the connection from being considered for remote peers */
2048
	$scconf['connections']['bypass']['remote_addrs'] = "127.0.0.1";
2049
	$scconf['connections']['bypass']['children'] = array();
2050

    
2051
	/* Locate the LAN IPv4 and IPv6 subnets */
2052
	$bypassnets = array();
2053
	if ($config['interfaces']['lan']) {
2054
		$lanip = get_interface_ip("lan", $gateways_status);
2055
		if (!empty($lanip) && is_ipaddrv4($lanip)) {
2056
			$lansn = get_interface_subnet("lan");
2057
			$lansa = gen_subnetv4($lanip, $lansn);
2058
			if (!empty($lansa) && !empty($lansn)) {
2059
				$bypassnets[] = "{$lansa}/{$lansn}";
2060
			}
2061
		}
2062
		$lanip6 = get_interface_ipv6("lan", $gateways_status);
2063
		if (!empty($lanip6) && is_ipaddrv6($lanip6)) {
2064
			$lansn6 = get_interface_subnetv6("lan");
2065
			$lansa6 = gen_subnetv6($lanip6, $lansn6);
2066
			if (!empty($lansa6) && !empty($lansn6)) {
2067
				$bypassnets[] = "{$lansa6}/{$lansn6}";
2068
			}
2069
		}
2070
	}
2071
	/* If we have viable targets, setup a bypass LAN connection */
2072
	if (!empty($bypassnets) && !isset($config['ipsec']['noshuntlaninterfaces'])) {
2073
		$bypass = implode(',', $bypassnets);
2074
		$scconf['connections']['bypass']['children']['bypasslan'] = array();
2075
		$scconf['connections']['bypass']['children']['bypasslan']['local_ts'] = $bypass;
2076
		$scconf['connections']['bypass']['children']['bypasslan']['remote_ts'] = $bypass;
2077
		$scconf['connections']['bypass']['children']['bypasslan']['mode'] = "pass";
2078
		$scconf['connections']['bypass']['children']['bypasslan']['start_action'] = "trap";
2079
	}
2080

    
2081
	/* Setup custom bypass rules */
2082
	if ((isset($config['ipsec']['ipsecbypass']) && $config['ipsec']['bypassrules']) &&
2083
	    is_array($config['ipsec']['bypassrules'])) {
2084
		foreach ($config['ipsec']['bypassrules']['rule'] as $id => $rule) {
2085
			$scconf['connections']['bypass']['children']["rule{$id}"] = array();
2086
			$scconf['connections']['bypass']['children']["rule{$id}"]["local_ts"] = $rule['source'] .
2087
			       	"/" . $rule['srcmask'];
2088
			$scconf['connections']['bypass']['children']["rule{$id}"]["remote_ts"] = $rule['destination'] .
2089
			       	"/" . $rule['dstmask'];
2090
			$scconf['connections']['bypass']['children']["rule{$id}"]["mode"] = "pass";
2091
			$scconf['connections']['bypass']['children']["rule{$id}"]["start_action"] = "trap";
2092
		}
2093
	}
2094

    
2095
	return;
2096
}
2097

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

    
2162
/****f* ipsec/ipsec_setup_authentication
2163
 * NAME
2164
 *   ipsec_setup_authentication - Generate an array with local/remote
2165
 *                                authentication information for a given IPsec
2166
 *                                Phase 1.
2167
 * INPUTS
2168
 *   $ph1ent: An IPsec Phase 1 configuration
2169
 *   $conn  : A swanctl connection array corresponding to the IPsec Phase 1.
2170
 * RESULT
2171
 *   Populates $conn with local and remote arrays containing authentication
2172
 *   details.
2173
 ******/
2174
function ipsec_setup_authentication(& $ph1ent, & $conn, $gateways_status = false) {
2175
	global $rgmap, $ipsec_swanctl_dirs, $config;
2176
	$local = array();
2177
	$remote = array();
2178
	$remote2 = array();
2179

    
2180
	/* Fetch gateway status if not passed */
2181
	if (!is_array($gateways_status)) {
2182
		$gateways_status = return_gateways_status(true);
2183
	}
2184

    
2185
	list($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local', array(), $gateways_status);
2186
	$localid = ipsec_fixup_id($myid_type, $myid_data);
2187
	if (!empty($localid)) {
2188
		$local['id'] = $localid;
2189
	}
2190

    
2191
	// Only specify peer ID if we are not dealing with mobile PSK
2192
	if (!(isset($ph1ent['mobile']) &&
2193
	    in_array($ph1ent['authentication_method'], array("pre_shared_key", "xauth_psk_server")))) {
2194
		list ($remoteid_type, $remoteid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap, $gateways_status);
2195
		$remoteid = ipsec_fixup_id($remoteid_type, $remoteid_data);
2196
	}
2197
	if (!empty($remoteid)) {
2198
		$remote['id'] = $remoteid;
2199
	}
2200

    
2201
	if (!empty($ph1ent['caref'])) {
2202
		$ca = lookup_ca($ph1ent['caref']);
2203
		if ($ca) {
2204
			/* Get hash value to use for filename */
2205
			$ca_details = openssl_x509_parse(base64_decode($ca['crt']));
2206
			$cafn = "{$ipsec_swanctl_dirs['capath']}/{$ca_details['hash']}.0";
2207
		}
2208
	}
2209

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

    
2282
	$conn['local'] = $local;
2283
	/* If there is data for a second remote auth round, setup two remote
2284
	 * arrays with unique names, otherwise setup a single remote. */
2285
	if (empty($remote2)) {
2286
		$conn['remote'] = $remote;
2287
	} else {
2288
		$conn['remote-1'] = $remote;
2289
		$conn['remote-2'] = $remote2;
2290
	}
2291
}
2292

    
2293
/****f* ipsec/ipsec_setup_proposal_algo
2294
 * NAME
2295
 *   ipsec_setup_proposal_algo - Form a single proposal algorithm string
2296
 * INPUTS
2297
 *   $ealg_id: Encryption algorithm ID
2298
 *   $keylen : Key length for the encryption algorithm
2299
 *   $halgo  : Hash algorithm
2300
 *   $modp   : DH Group number
2301
 * RESULT
2302
 *   Returns a string using the available information to form a single proposal
2303
 *   algorithm definition.
2304
 * NOTES
2305
 *   Values left empty will not be added to the string. Some combinations may
2306
 *   require one or more parts to be omitted.
2307
 ******/
2308
function ipsec_setup_proposal_algo($ealg_id, $keylen, $halgo, $prfalgo, $modp) {
2309
	$palgo = "";
2310

    
2311
	/* Add the encryption algorithm (if present) */
2312
	if (!empty($ealg_id)) {
2313
		$palgo .= "{$ealg_id}";
2314
	}
2315

    
2316
	/* Add the key length (if present) */
2317
	if (!empty($keylen)) {
2318
		$palgo .= "{$keylen}";
2319
	}
2320

    
2321
	/* Add the hash algorithm (if present) */
2322
	if (!empty($halgo)) {
2323
		/* If there is some content in the propsal already, add a
2324
		 * separator */
2325
		if (!empty($palgo)) {
2326
			$palgo .= "-";
2327
		}
2328
		$halgo = str_replace('hmac_', '', $halgo);
2329
		$palgo .= "{$halgo}";
2330
	}
2331

    
2332
	if (!empty($prfalgo)) {
2333
		$palgo .= "-prf{$prfalgo}";
2334
	}
2335

    
2336
	/* Convert the DH group to its keyword and add (if present) */
2337
	$modp = ipsec_convert_to_modp($modp);
2338
	if (!empty($modp)) {
2339
		$palgo .= "-{$modp}";
2340
	}
2341

    
2342
	return $palgo;
2343
}
2344

    
2345
/****f* ipsec/ipsec_setup_proposal_entry
2346
 * NAME
2347
 *   ipsec_setup_proposal_entry - Generate a full proposal string for an IPsec
2348
 *                                Phase 2 configuration.
2349
 * INPUTS
2350
 *   $ph2ent  : An IPsec Phase 2 configuration
2351
 *   $algo_arr: An array in which all proposal algorithms are collected
2352
 *   $ealg_id : Encryption algorithm ID
2353
 *   $keylen  : Key length for the encryption algorithm
2354
 * RESULT
2355
 *   Returns a string containing all proposal elements, and merges the entries
2356
 *   to $algo_arr as well.
2357
 ******/
2358
function ipsec_setup_proposal_entry(& $ph2ent, & $algo_arr, $ealg_id, $keylen) {
2359
	global $config, $p2_ealgos;
2360
	$proposal = array();
2361

    
2362
	/* If multiple hash algorithms are present, loop through and add them all. */
2363
	if (!empty($ph2ent['hash-algorithm-option']) && is_array($ph2ent['hash-algorithm-option']) 
2364
	    && !strpos($ealg_id, "gcm")) {
2365
		foreach ($ph2ent['hash-algorithm-option'] as $halgo) {
2366
			$proposal[] = ipsec_setup_proposal_algo($ealg_id, $keylen, $halgo, false, $ph2ent['pfsgroup']);
2367
		}
2368
	} else {
2369
		$proposal[] = ipsec_setup_proposal_algo($ealg_id, $keylen, false, false, $ph2ent['pfsgroup']);
2370
	}
2371

    
2372
	/* Add to master list */
2373
	$algo_arr = array_merge($algo_arr, $proposal);
2374
	return implode(',', $proposal);
2375
}
2376

    
2377
function ipsec_get_ifname($p1, $reqid = 0) {
2378
	global $config;
2379
	$ifname = "ipsec";
2380
	if ($reqid > 0) {
2381
		$ifname .= "{$reqid}";
2382
	} else {
2383
		$p2s = ipsec_get_phase2_by_ikeid($p1['ikeid']);
2384
		if (!empty($p2s)) {
2385
			$ifname .= $p2s[0]['reqid'];
2386
		}
2387
	}
2388
	return $ifname;
2389
}
2390

    
2391
function ipsec_get_ifname_by_conf($p1 = array(), $p2 = array()) {
2392
	global $config;
2393
	$have_p1 = (!empty($p1) && is_array($p1));
2394
	$have_p2 = (!empty($p2) && is_array($p2));
2395
	$reqid = null;
2396

    
2397
	if (!$have_p1 && $have_p2) {
2398
		$p1 = ipsec_get_phase1($p2['ikeid']);
2399
	}
2400

    
2401
	if ($have_p2) {
2402
		$reqid = $p2['reqid'];
2403
	}
2404

    
2405
	return ipsec_get_ifname($p1, $reqid);
2406
}
2407

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

    
2439
/****f* ipsec/ipsec_setup_tunnels
2440
 * NAME
2441
 *   ipsec_setup_tunnels - Configure all P1/P2 entries as swanctl connections
2442
 * INPUTS
2443
 *   None
2444
 * RESULT
2445
 *   Sets up a swanctl array for all connections in the configuration along with
2446
 *   their children, authentication, etc.
2447
 ******/
2448
function ipsec_setup_tunnels($gateways_status = false) {
2449
	global $aggressive_mode_psk, $a_client, $config,
2450
		$filterdns_list, $g, $ifacesuse, $ipsec_idhandling, $ipsec_log_cats,
2451
		$ipsec_log_sevs, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs,
2452
		$ipseccfg, $mobile_ipsec_auth, $natfilterrules, $p1_ealgos,
2453
		$p2_ealgos, $rgmap, $sa, $sn, $scconf, $conn, $tunnels,
2454
		$ipsec_vti_cleanup_ifs, $conn_defaults;
2455

    
2456
	/* Fetch gateway status if not passed */
2457
	if (!is_array($gateways_status)) {
2458
		$gateways_status = return_gateways_status(true);
2459
	}
2460

    
2461
	$a_groups = return_gateway_groups_array(true);
2462

    
2463
	foreach ($tunnels as $ph1ent) {
2464
		/* Skip disabled entries */
2465
		if (isset($ph1ent['disabled'])) {
2466
			continue;
2467
		}
2468
		/* If the local source is invalid, skip this entry. */
2469
		$local_spec = ipsec_get_phase1_src($ph1ent, $gateways_status);
2470
		if (!$local_spec) {
2471
			continue;
2472
		}
2473

    
2474
		/* Determine the name of this connection, either con-mobile for
2475
		 * mobile clients, or a name based on the IKE ID otherwise. */
2476
		if (isset($ph1ent['mobile'])) {
2477
			$cname = "con-mobile";
2478
			/* Start with common default values */
2479
			$scconf["{$cname}-defaults"] = $conn_defaults;
2480
			/* Array reference to make things easier */
2481
			$conn =& $scconf["{$cname}-defaults"];
2482
			$scconf['connections']["{$cname} : {$cname}-defaults"] = array("# Stub to load con-mobile-defaults");
2483
		} else {
2484
			$cname = ipsec_conid($ph1ent);
2485
			/* Start with common default values */
2486
			$scconf['connections'][$cname] = $conn_defaults;
2487
			$descr = "# P1 (ikeid {$ph1ent['ikeid']})";
2488
			if (!empty($ph1ent['descr'])) {
2489
				$descr .= ": {$ph1ent['descr']}";
2490
			}
2491
			array_unshift($scconf['connections'][$cname], $descr);
2492
			/* Array reference to make things easier */
2493
			$conn =& $scconf['connections'][$cname];
2494
		}
2495

    
2496
		/* Common parameters for all children */
2497
		$child_params = array();
2498
		if (!empty($ph1ent['closeaction'])) {
2499
			$child_params['close_action'] = $ph1ent['closeaction'];
2500
		}
2501

    
2502
		$ikeid = $ph1ent['ikeid'];
2503

    
2504
		$carpbackup = false;
2505
		if (((substr($ph1ent['interface'], 0, 4) == "_vip") &&
2506
		    in_array(get_carp_bind_status($ph1ent['interface']), array('BACKUP', 'INIT'))) ||
2507
		    (is_array($a_groups[$ph1ent['interface']]) &&
2508
		    !empty($a_groups[$ph1ent['interface']][0]['vip']) &&
2509
		    in_array(get_carp_bind_status($a_groups[$ph1ent['interface']][0]['vip']), array('BACKUP', 'INIT')))) {
2510
			$carpbackup = true;
2511
		}
2512

    
2513
		/* "trap" adds policies to start a tunnel when interesting
2514
		 * traffic is observed by the host. */
2515
		$start_action = "trap";
2516
		if ($carpbackup) {
2517
			$start_action = "none";
2518
		}
2519

    
2520
		/* Set the IKE version appropriately (empty = IKEv1) */
2521
		switch ($ph1ent['iketype']) {
2522
			case 'auto':
2523
				$ikeversion = 0;
2524
				break;
2525
			case 'ikev2':
2526
				$ikeversion = 2;
2527
				break;
2528
			case 'ikev1':
2529
			default:
2530
				$ikeversion = 1;
2531
				break;
2532
		}
2533
		$conn['version'] = $ikeversion;
2534

    
2535
		/* For IKEv1 or auto, setup aggressive mode if configured */
2536
		if ($ikeversion != 2){
2537
			$conn['aggressive'] = ($ph1ent['mode'] == "aggressive") ? "yes" : "no";
2538
		}
2539

    
2540
		if (isset($ph1ent['mobile'])) {
2541
			/* Mobile tunnels allow 'any' as a peer */
2542
			$remote_spec = "0.0.0.0/0,::/0";
2543
			/* Mobile tunnels cannot start automatically */
2544
			$start_action = 'none';
2545
		} else {
2546
			$remote_spec = $ph1ent['remote-gateway'];
2547
			$sourcehost = (is_ipaddr($remote_spec)) ? $remote_spec : $rgmap[$remote_spec];
2548
			$ifacesuse = ipsec_setup_routes($ph1ent['interface'], $ph1ent['protocol'], $sourcehost, isset($ph1ent['gw_duplicates']));
2549
		}
2550

    
2551
		/* Setup IKE proposals */
2552
		if (is_array($ph1ent['encryption']['item'])) {
2553
			$ciphers = array();
2554
			foreach($ph1ent['encryption']['item'] as $p1enc) {
2555
				if (!is_array($p1enc['encryption-algorithm']) ||
2556
						empty($p1enc['encryption-algorithm']['name']) ||
2557
						empty($p1enc['hash-algorithm'])) {
2558
					continue;
2559
				}
2560
				if ($ph1ent['prfselect_enable'] != 'yes') {
2561
					$p1enc['prf-algorithm'] = false;
2562
				}
2563
				$ciphers[] = ipsec_setup_proposal_algo($p1enc['encryption-algorithm']['name'],
2564
									$p1enc['encryption-algorithm']['keylen'],
2565
									$p1enc['hash-algorithm'],
2566
									$p1enc['prf-algorithm'],
2567
									$p1enc['dhgroup']);
2568
			}
2569
			$conn['proposals'] = implode(",", $ciphers);
2570
		}
2571

    
2572
		/* Configure DPD values. The DPD action is a per-child parameter,
2573
		 * not per-connection like the delay and timeout. */
2574
		if ($ph1ent['dpd_delay'] && $ph1ent['dpd_maxfail']) {
2575
			if ($start_action == "trap") {
2576
				$child_params['dpd_action'] = "trap";
2577
			} else {
2578
				$child_params['dpd_action'] = "clear";
2579
			}
2580
			$conn['dpd_delay'] = "{$ph1ent['dpd_delay']}s";
2581
			if ($ph1ent['iketype'] == 'ikev1') {
2582
				/* in IKEv2 the default retransmission timeout applies,
2583
				 * see https://redmine.pfsense.org/issues/12184 */
2584
				$conn['dpd_timeout'] =  $ph1ent['dpd_delay'] * ($ph1ent['dpd_maxfail'] + 1) . "s";
2585
			}
2586

    
2587
			/* Adjust dpd_action if the close_action is explicitly set */
2588
			if (!empty($child_params['close_action'])) {
2589
				switch ($ph1ent['closeaction']) {
2590
					case 'trap':
2591
						$child_params['dpd_action'] = 'trap';
2592
						break;
2593
					case 'start':
2594
						$child_params['dpd_action'] = 'restart';
2595
						break;
2596
					case 'none':
2597
					default:
2598
						$child_params['dpd_action'] = 'clear';
2599
				}
2600
			}
2601
		} else {
2602
			$child_params['dpd_action'] = "clear";
2603
		}
2604

    
2605
		/* Rekey (IKEv2 or Auto only, not supported by IKEv1) */
2606
		if (($ikeversion == 0) || ($ikeversion == 2)) {
2607
			$conn['rekey_time'] = ipsec_get_rekey_time($ph1ent) . "s";
2608
		}
2609

    
2610
		/* Reauth (Any) */
2611
		$conn['reauth_time'] = ipsec_get_reauth_time($ph1ent) . "s";
2612

    
2613
		/* Over Time */
2614
		$conn['over_time'] = ipsec_get_over_time($ph1ent) . "s";
2615

    
2616
		/* Rand Time */
2617
		$conn['rand_time'] = ipsec_get_rand_time($ph1ent) . "s";
2618

    
2619
		/* NAT Traversal */
2620
		$conn['encap'] = ($ph1ent['nat_traversal'] == 'force') ? "yes" : "no";
2621

    
2622
		/* MOBIKE support */
2623
		$conn['mobike'] = ($ph1ent['mobike'] == 'on') ? "yes" : "no";
2624

    
2625
		/* TFC Padding */
2626
		if (isset($ph1ent['tfc_enable'])) {
2627
			$conn['tfc_padding'] = (isset($ph1ent['tfc_bytes']) && is_numericint($ph1ent['tfc_bytes'])) ? $ph1ent['tfc_bytes'] : "mtu";
2628
		}
2629

    
2630
		/* Custom Ports */
2631
		if (isset($ph1ent['ikeport'])) {
2632
			/* For a connection without encapsulation, do not set local_port */
2633
			$conn['remote_port'] = $ph1ent['ikeport'];
2634
		} elseif (isset($ph1ent['nattport'])) {
2635
			/* For an encapsulated connection,
2636
			 * set local_port to the server NAT-T port value or default (4500) */
2637
			$conn['local_port'] = isset($config['ipsec']['port_nat_t']) ? $config['ipsec']['port_nat_t'] : 4500;
2638
			$conn['remote_port'] = $ph1ent['nattport'];
2639
		}
2640

    
2641
		/* Arrays for P2s/children */
2642
		$children = array();
2643
		$remote_ts_spec = array();
2644
		$local_ts_spec = array();
2645
		$reqids = array();
2646
		$has_vti = false;
2647
		$ealgoAHsp2arr = array();
2648
		$ealgoESPsp2arr = array();
2649

    
2650
		foreach ($ph1ent['p2'] as $ph2ent) {
2651
			/* If this entry is disabled, or cannot be configured, skip. */
2652
			if (isset($ph2ent['disabled']) ||
2653
			    (isset($ph2ent['mobile']) && !isset($a_client['enable']))) {
2654
				continue;
2655
			}
2656
			$child = array();
2657
			$local_ts = "";
2658
			$remote_ts = "";
2659
			if (($ph2ent['mode'] == 'tunnel') or ($ph2ent['mode'] == 'tunnel6')) {
2660
				/* Normal tunnel child config */
2661
				$child['mode'] = "tunnel";
2662
				$child['policies'] = "yes";
2663

    
2664
				$localid_type = $ph2ent['localid']['type'];
2665
				$localsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
2666

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

    
2695
				$local_ts = $localsubnet_data;
2696

    
2697
				if (!isset($ph2ent['mobile'])) {
2698
					$remote_ts = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
2699
				} else if (!empty($a_client['pool_address'])) {
2700
					$remote_ts = "{$a_client['pool_address']}/{$a_client['pool_netbits']}";
2701
				}
2702

    
2703
			} elseif ($ph2ent['mode'] == 'vti') {
2704
				/* VTI-specific child config */
2705
				$child['policies'] = "no";
2706
				/* VTI cannot use trap policies, so start automatically instead */
2707
				$start_action = 'start';
2708
				if ($carpbackup) {
2709
					$start_action = "none";
2710
				}
2711
				if ($child_params['dpd_action'] == "trap") {
2712
					$child_params['dpd_action'] = "restart";
2713
				}
2714
				$localid_type = $ph2ent['localid']['type'];
2715
				$localsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
2716
				$local_ts = $localsubnet_data;
2717
				$remote_ts = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
2718
				$has_vti = true;
2719
			} else {
2720
				/* Transport mode child config */
2721
				$child['mode'] = "transport";
2722
				$child['policies'] = "yes";
2723

    
2724
				if ((($ph1ent['authentication_method'] == "xauth_psk_server") ||
2725
				    ($ph1ent['authentication_method'] == "pre_shared_key")) &&
2726
				    isset($ph1ent['mobile'])) {
2727
					$local_spec = "0.0.0.0/0,::/0";
2728
				} else {
2729
					$local_ts = ipsec_get_phase1_src($ph1ent, $gateways_status);
2730
				}
2731

    
2732
				if (!isset($ph2ent['mobile'])) {
2733
					$remote_ts = $remote_spec;
2734
				}
2735
			}
2736

    
2737
			if (!empty($local_ts)) {
2738
				$local_ts_spec[] = $local_ts;
2739
			}
2740
			if (!empty($remote_ts)) {
2741
				$remote_ts_spec[] = $remote_ts;
2742
			}
2743

    
2744
			/* If a PFS group is configured on the Mobile Clients tab,
2745
			 * and this is a mobile P2, use it here. */
2746
			if (isset($a_client['pfs_group']) && isset($ph2ent['mobile'])) {
2747
				$ph2ent['pfsgroup'] = $a_client['pfs_group'];
2748
			}
2749

    
2750
			$reqids[] = $ph2ent['reqid'];
2751

    
2752
			if (!empty($ph2ent['lifetime'])) {
2753
				$child['life_time'] = ipsec_get_life_time($ph2ent) . "s";
2754
				/* Rekey at 90% of lifetime */
2755
				$child['rekey_time'] = ipsec_get_rekey_time($ph2ent) . "s";
2756
				/* Random rekey fuzz time */
2757
				$child['rand_time'] = ipsec_get_rand_time($ph2ent) . "s";
2758
			}
2759

    
2760
			/* Set Child SA Start Action based on user preference, except
2761
			 * for invalid combinations such as 'trap' on VTI */
2762
			if (!isset($ph2ent['mobile']) && !$carpbackup &&
2763
			    !(($ph2ent['mode'] == 'vti') && ($ph1ent['startaction'] == 'trap'))) {
2764
				$start_action = !empty($ph1ent['startaction']) ? $ph1ent['startaction'] : $start_action;
2765
			}
2766
			$child['start_action'] = $start_action;
2767

    
2768
			/* Setup child SA proposals */
2769
			$proposal = array();
2770
			$ph2ent_ealgos = array();
2771
			$ph2ent_ealgos_aead = array();
2772
			if ($ph2ent['protocol'] == 'esp') {
2773
				if (is_array($ph2ent['encryption-algorithm-option'])) {
2774
					foreach ($ph2ent['encryption-algorithm-option'] as $ealg) {
2775
						if (strpos($ealg['name'], "gcm")) {
2776
							/* put AEAD ciphers on top, 
2777
							*  see https://redmine.pfsense.org/issues/11078 */
2778
							$ph2ent_ealgos_aead[] = $ealg;
2779
						} else {
2780
							$ph2ent_ealgos[] = $ealg;
2781
						}
2782
					}
2783
					$ph2ent_ealgos = array_merge(array_reverse($ph2ent_ealgos_aead), $ph2ent_ealgos);
2784
					foreach ($ph2ent_ealgos as $ealg) {
2785
						$ealg_id = $ealg['name'];
2786
						$ealg_kl = $ealg['keylen'];
2787

    
2788
						if (!empty($ealg_kl) && $ealg_kl == "auto") {
2789
							if (empty($p2_ealgos) || !is_array($p2_ealgos)) {
2790
								require_once("ipsec.inc");
2791
							}
2792
							$key_hi = $p2_ealgos[$ealg_id]['keysel']['hi'];
2793
							$key_lo = $p2_ealgos[$ealg_id]['keysel']['lo'];
2794
							$key_step = $p2_ealgos[$ealg_id]['keysel']['step'];
2795
							/* XXX: in some cases where include ordering is suspect these variables
2796
							 * are somehow 0 and we enter this loop forever and timeout after 900
2797
							 * seconds wrecking bootup */
2798
							if ($key_hi != 0 and $key_lo != 0 and $key_step != 0) {
2799
								for ($keylen = $key_hi; $keylen >= $key_lo; $keylen -= $key_step) {
2800
									$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoESPsp2arr, $ealg_id, $keylen);
2801
								}
2802
							}
2803
						} else {
2804
							$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoESPsp2arr, $ealg_id, $ealg_kl);
2805
						}
2806
					}
2807
				}
2808
			} else if ($ph2ent['protocol'] == 'ah') {
2809
				$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoAHsp2arr, '', '');
2810
			}
2811

    
2812
			/* Not mobile, and IKEv1 or Split Connections active */
2813
			if (!isset($ph1ent['mobile']) && (($ikeversion == 1) || isset($ph1ent['splitconn']))) {
2814
				if (!empty($remote_ts)) {
2815
					/* Setup child sub-connections using unique names */
2816
					$subconname = ipsec_conid($ph1ent, $ph2ent);
2817
					$children[$subconname] = $child;
2818

    
2819
					$descr = "# P2 (reqid {$ph2ent['reqid']})";
2820
					if (!empty($ph2ent['descr'])) {
2821
						$descr .= ": {$ph2ent['descr']}";
2822
					}
2823
					array_unshift($children[$subconname], $descr);
2824
					$children[$subconname]['local_ts'] = $local_ts;
2825
					$children[$subconname]['remote_ts'] = $remote_ts;
2826
					if ($has_vti) {
2827
						ipsec_setup_vtireq($children[$subconname], $ipsec_vti_cleanup_ifs, $ph1ent, $ph2ent['reqid']);
2828
					}
2829
					if (!empty($ph2ent['protocol']) && !empty($proposal)) {
2830
						$children[$subconname][$ph2ent['protocol'] . '_proposals'] = implode(',', $proposal);
2831
					}
2832
				} else {
2833
					log_error(sprintf(gettext("No phase2 specifications for tunnel with ikeid = %s"), $ikeid));
2834
				}
2835
			} else {
2836
				/* TODO: Fix this to nicely merge all P2 params for single child case */
2837
				if (!is_array($children[$cname])) {
2838
					$children[$cname] = array();
2839
				}
2840
				$children[$cname] = array_merge($children[$cname], $child);
2841

    
2842
				$descr = "# P2 (reqid {$ph2ent['reqid']})";
2843
				if (!empty($ph2ent['descr'])) {
2844
					$descr .= ": {$ph2ent['descr']}";
2845
				}
2846
				array_unshift($children[$cname], $descr);
2847
			}
2848
		}
2849

    
2850
		$conn['local_addrs'] = $local_spec;
2851
		$conn['remote_addrs'] = $remote_spec;
2852

    
2853
		$pools = array();
2854
		if (isset($ph1ent['mobile'])) {
2855
			if (($ph1ent['authentication_method'] == 'eap-radius') && 
2856
			    empty($a_client['pool_address']) && empty($a_client['pool_address_v6'])) {
2857
				$pools[] = "radius";
2858
			} else {
2859
				if (!empty($a_client['pool_address'])) {
2860
					$pools[] = "mobile-pool-v4";
2861
				}
2862
				if (!empty($a_client['pool_address_v6'])) {
2863
					$pools[] = "mobile-pool-v6";
2864
				}
2865
				if (isset($a_client['radius_ip_priority_enable'])) {
2866
					$pools[] .= "radius";
2867
				}
2868
			}
2869
		}
2870
		if (!empty($pools)) {
2871
			$conn['pools'] = implode(', ', $pools);
2872
		}
2873

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

    
2906
		/* Setup connection authentication */
2907
		ipsec_setup_authentication($ph1ent, $conn, $gateways_status);
2908

    
2909
		/* Add children to this connection, including default child parameters */
2910
		if (count($children)) {
2911
			foreach($children as $name => $child) {
2912
				$conn['children'][$name] = array_merge($child, $child_params);
2913
			}
2914
		}
2915
		unset ($ph2ent);
2916
	}
2917

    
2918
	return;
2919
}
2920

    
2921
/****f* ipsec/ipsec_setup_secrets
2922
 * NAME
2923
 *   ipsec_setup_secrets - Setup swanctl authentication secrets
2924
 * INPUTS
2925
 *   None
2926
 * RESULT
2927
 *   Returns a swanctl array containing secrets (PSKs, certs, etc) and writes out
2928
 *   necessary CA, CRL, and certificate data.
2929
 ******/
2930
function ipsec_setup_secrets($gateways_status = false) {
2931
	global $config, $a_phase1, $ipsec_swanctl_dirs, $ipseccfg, $rgmap, $scconf;
2932

    
2933
	$suffix = 0;
2934

    
2935
	/* Fetch gateway status if not passed */
2936
	if (!is_array($gateways_status)) {
2937
		$gateways_status = return_gateways_status(true);
2938
	}
2939

    
2940
	$vpncas = array();
2941
	if (is_array($a_phase1) && count($a_phase1)) {
2942
		foreach ($a_phase1 as $ph1ent) {
2943
			if (isset($ph1ent['disabled'])) {
2944
				continue;
2945
			}
2946

    
2947
			if (isset($ph1ent['mobile'])) {
2948
				if ($ph1ent['authentication_method'] == 'pre_shared_key') {
2949
					$mobilepsk = true;
2950
				} elseif ($ph1ent['authentication_method'] == 'eap-mschapv2') {
2951
					$mobileeap = true;
2952
				}
2953
			}
2954

    
2955
			if (strstr($ph1ent['authentication_method'], 'cert') ||
2956
			    in_array($ph1ent['authentication_method'], array('eap-mschapv2', 'eap-tls', 'eap-radius'))) {
2957
				/* Write certificate and private key, point to private key */
2958
				$certline = '';
2959

    
2960
				$ikeid = $ph1ent['ikeid'];
2961
				$cert = lookup_cert($ph1ent['certref']);
2962

    
2963
				if (!$cert) {
2964
					log_error(sprintf(gettext("Error: Invalid phase1 certificate reference for %s"), $ph1ent['name']));
2965
					continue;
2966
				}
2967

    
2968
				/* add signing CA cert chain of server cert
2969
				 * to the list of CAs to write
2970
				 */
2971
				$cachain = ca_chain_array($cert);
2972
				if ($cachain && is_array($cachain)) {
2973
					foreach ($cachain as $cacrt) {
2974
						$vpncas[$cacrt['refid']] = $cacrt;
2975
					}
2976
				}
2977

    
2978
				@chmod($ipsec_swanctl_dirs['certpath'], 0600);
2979

    
2980
				$ph1keyfile = "{$ipsec_swanctl_dirs['keypath']}/cert-{$ikeid}.key";
2981
				if (!file_put_contents($ph1keyfile, base64_decode($cert['prv']))) {
2982
					log_error(sprintf(gettext("Error: Cannot write phase1 key file for %s"), $ph1ent['name']));
2983
					continue;
2984
				}
2985
				@chmod($ph1keyfile, 0600);
2986

    
2987
				$ph1certfile = "{$ipsec_swanctl_dirs['certpath']}/cert-{$ikeid}.crt";
2988
				if (!file_put_contents($ph1certfile, base64_decode($cert['crt']))) {
2989
					log_error(sprintf(gettext("Error: Cannot write phase1 certificate file for %s"), $ph1ent['name']));
2990
					@unlink($ph1keyfile);
2991
					continue;
2992
				}
2993
				@chmod($ph1certfile, 0600);
2994

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

    
3015
				if (empty($peerid_data)) {
3016
					continue;
3017
				}
3018

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

    
3022
				if (!empty($ph1ent['pre-shared-key'])) {
3023
					$scconf['secrets']['ike-' . $suffix++] = array(
3024
						'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
3025
						'id-0' => $myid,
3026
						'id-1' => $peerid,
3027
					);
3028
					if (isset($ph1ent['mobile'])) {
3029
						$scconf['secrets']['ike-' . $suffix++] = array(
3030
							'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
3031
							'id-0' => $myid,
3032
							'id-1' => '%any',
3033
						);
3034
						$scconf['secrets']['ike-' . $suffix++] = array(
3035
							'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
3036
						);
3037
					}
3038
				}
3039
			}
3040

    
3041
			/* if the client authenticates with a cert add the
3042
			 * client cert CA chain to the list of CAs to write
3043
			 */
3044
			if (in_array($ph1ent['authentication_method'],
3045
			    array('cert', 'eap-tls', 'xauth_cert_server', 'pkcs11'))) {
3046
				if (!empty($ph1ent['caref']) && !array_key_exists($ph1ent['caref'], $vpncas)) {
3047
					$thisca = lookup_ca($ph1ent['caref']);
3048
					$vpncas[$ph1ent['caref']] = $thisca;
3049
					/* follow chain up to root */
3050
					$cachain = ca_chain_array($thisca);
3051
					if ($cachain and is_array($cachain)) {
3052
						foreach ($cachain as $cacrt) {
3053
							$vpncas[$cacrt['refid']] = $cacrt;
3054
						}
3055
					}
3056
				}
3057
			}
3058
		}
3059
	}
3060

    
3061
	/* Write the required CAs */
3062
	foreach ($vpncas as $carefid => $cadata) {
3063
		$cacrt = base64_decode($cadata['crt']);
3064
		$cacrtattrs = openssl_x509_parse($cacrt);
3065
		if (!is_array($cacrtattrs) || !isset($cacrtattrs['hash'])) {
3066
			log_error(sprintf(gettext("Error: Invalid certificate hash info for %s"), $cadata['descr']));
3067
			continue;
3068
		}
3069
		$cafilename = "{$ipsec_swanctl_dirs['capath']}/{$cacrtattrs['hash']}.0";
3070
		if (!@file_put_contents($cafilename, $cacrt)) {
3071
				log_error(sprintf(gettext("Error: Cannot write IPsec CA file for %s"), $cadata['descr']));
3072
				continue;
3073
		}
3074
	}
3075

    
3076
	/* write out CRL files */
3077
	if (is_array($config['crl']) && count($config['crl']) && !empty($vpncas)) {
3078
		foreach ($config['crl'] as $crl) {
3079
			if (!isset($crl['text'])) {
3080
				log_error(sprintf(gettext("Warning: Missing CRL data for %s"), $crl['descr']));
3081
				continue;
3082
			}
3083
			$fpath = "{$ipsec_swanctl_dirs['crlpath']}/{$crl['refid']}.crl";
3084
			if (!@file_put_contents($fpath, base64_decode($crl['text']))) {
3085
				log_error(sprintf(gettext("Error: Cannot write IPsec CRL file for %s"), $crl['descr']));
3086
				continue;
3087
			}
3088
		}
3089
	}
3090

    
3091
	/* Add user PSKs */
3092
	if ($mobilepsk && is_array($config['system']) && is_array($config['system']['user'])) {
3093
		foreach ($config['system']['user'] as $user) {
3094
			if (!empty($user['ipsecpsk'])) {
3095
				$scconf['secrets']['ike-' . $suffix++] = array(
3096
					'secret' => '0s' . base64_encode(trim($user['ipsecpsk'])),
3097
					'id-0' => $myid,
3098
					'id-1' => $user['name'],
3099
				);
3100
			}
3101
		}
3102
		unset($user);
3103
	}
3104

    
3105
	/* add PSKs/EAPs for mobile clients */
3106
	if (is_array($ipseccfg['mobilekey'])) {
3107
		foreach ($ipseccfg['mobilekey'] as $key) {
3108
			if (($mobileeap && ($key['type'] == 'EAP')) ||
3109
			    ($key['type'] == 'PSK')) {
3110
				if (($key['ident'] == 'allusers') ||
3111
				    ($key['ident'] == 'any')) {
3112
					$key['ident'] = '%any';
3113
				}
3114
				$userkeyprefix = (strtolower($key['type']) == 'eap') ? 'eap' : 'ike';
3115
				$scconf['secrets'][$userkeyprefix . '-' . $suffix++] = array(
3116
					'secret' => '0s' . base64_encode(trim($key['pre-shared-key'])),
3117
					'id-0' => $key['ident'],
3118
				);
3119
			}
3120
		}
3121
		unset($key);
3122
	}
3123
	return;
3124
}
3125

    
3126
/****f* ipsec/ipsec_configure
3127
 * NAME
3128
 *   ipsec_configure - Configure IPsec
3129
 * INPUTS
3130
 *   $restart: Boolean (default false), whether or not to restart the IPsec
3131
 *             daemons.
3132
 * RESULT
3133
 *   IPsec-related configuration files are written, daemon is started or stopped
3134
 *   appropriately.
3135
 ******/
3136
function ipsec_configure($restart = false, $filterdns_restart = false) {
3137
	global $aggressive_mode_psk, $a_client, $a_phase1, $a_phase2, $config,
3138
		$filterdns_list, $g, $ifacesuse, $ipsec_idhandling, $ipsec_log_cats,
3139
		$ipsec_log_sevs, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs,
3140
		$ipseccfg, $mobile_ipsec_auth, $natfilterrules, $p1_ealgos,
3141
		$p2_ealgos, $rgmap, $sa, $sn, $scconf, $tunnels, $mobile_configured,
3142
		$ipsec_vti_cleanup_ifs, $conn_defaults, $pool_addrs;
3143

    
3144
	/* service may have been enabled, disabled, or otherwise changed in a
3145
	 *way requiring rule updates */
3146
	filter_configure();
3147

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

    
3181
	if (platform_booting()) {
3182
		echo gettext("Configuring IPsec VPN... ");
3183
	}
3184

    
3185
	$ipsecstartlock = lock('ipsec', LOCK_EX);
3186

    
3187
	/* Prepare automatic ping_hosts.sh data */
3188
	unlink_if_exists("{$g['vardb_path']}/ipsecpinghosts");
3189
	touch("{$g['vardb_path']}/ipsecpinghosts");
3190
	$ipsecpinghostsactive = false;
3191

    
3192
	/* Populate convenience variables */
3193
	$syscfg = $config['system'];
3194
	init_config_arr(array('ipsec', 'phase1'));
3195
	$ipseccfg = $config['ipsec'];
3196
	$a_phase1 = $config['ipsec']['phase1'];
3197
	init_config_arr(array('ipsec', 'phase2'));
3198
	$a_phase2 = $config['ipsec']['phase2'];
3199
	init_config_arr(array('ipsec', 'client'));
3200
	$a_client = $config['ipsec']['client'];
3201

    
3202
	$mobile_configured = false;
3203

    
3204

    
3205
	/* Setup a single structured array to process, to avoid repeatedly
3206
	 * looping through the arrays to locate entries later. */
3207
	$tunnels = array();
3208
	foreach ($a_phase1 as $p1) {
3209
		if (empty($p1)) {
3210
			continue;
3211
		}
3212
		if (isset($p1['mobile']) && !isset($p1['disabled'])) {
3213
			$mobile_configured = true;
3214
		}
3215
		$tunnels[$p1['ikeid']] = $p1;
3216
		$tunnels[$p1['ikeid']]['p2'] = array();
3217
	}
3218
	foreach ($a_phase2 as $p2) {
3219
		$tunnels[$p2['ikeid']]['p2'][] = $p2;
3220
	}
3221

    
3222
	$ipsec_vti_cleanup_ifs = array();
3223
	$rgmap = array();
3224
	$filterdns_list = array();
3225
	$aggressive_mode_psk = false;
3226
	$mobile_ipsec_auth = "";
3227
	$ifacesuse = array();
3228
	$natfilterrules = false;
3229

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

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

    
3266
	/* Start swanctl configuration (scconf) */
3267
	$scconf = array();
3268
	$scconf[] = "# This file is automatically generated. Do not edit";
3269
	$scconf['connections'] = array();
3270
	/* Setup IPsec bypass */
3271
	ipsec_setup_bypass($gateways_status);
3272
	/* Setup connections */
3273
	ipsec_setup_tunnels($gateways_status);
3274
	$scconf['pools'] = array();
3275
	if ($mobile_configured) {
3276
		/* Setup mobile address pools */
3277
		ipsec_setup_pools();
3278
		/* Setup per-user pools */
3279
		ipsec_setup_userpools();
3280
	}
3281
	/* Setup secret data */
3282
	$scconf['secrets'] = array();
3283
	ipsec_setup_secrets($gateways_status);
3284

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

    
3287
	/* Clean up unused VTI interfaces */
3288
	foreach ($ipsec_vti_cleanup_ifs as $cleanif) {
3289
		if (does_interface_exist($cleanif)) {
3290
			mwexec("/sbin/ifconfig " . escapeshellarg($cleanif) . " destroy", false);
3291
		}
3292
	}
3293

    
3294
	/* set default MTU to 1400 for GRE over IPsec, othewise to 1476 */
3295
	ipsec_gre_default_mtu(); 
3296

    
3297
	/* Manage process */
3298
	if ($restart === true) {
3299
		mwexec_bg("/usr/local/sbin/strongswanrc restart", false);
3300
	} else {
3301
		if (isvalidpid("{$g['varrun_path']}/charon.pid")) {
3302
			mwexec_bg("/usr/local/sbin/strongswanrc reload", false);
3303
		} else {
3304
			mwexec_bg("/usr/local/sbin/strongswanrc start", false);
3305
		}
3306
	}
3307

    
3308
	// Run ping_hosts.sh once if it's enabled to avoid wait for minicron
3309
	if ($ipsecpinghostsactive) {
3310
		mwexec_bg("/usr/local/bin/ping_hosts.sh");
3311
	}
3312

    
3313
	if ($natfilterrules == true) {
3314
		filter_configure();
3315
	}
3316
	/* start filterdns, if necessary */
3317
	if (count($filterdns_list) > 0) {
3318
		$interval = 60;
3319
		if (!empty($ipseccfg['dns-interval']) && is_numeric($ipseccfg['dns-interval'])) {
3320
			$interval = $ipseccfg['dns-interval'];
3321
		}
3322

    
3323
		$hostnames = "";
3324
		array_unique($filterdns_list);
3325
		foreach ($filterdns_list as $hostname) {
3326
			$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload ipsecdns\"'\n";
3327
		}
3328
		file_put_contents("{$g['varetc_path']}/ipsec/filterdns-ipsec.hosts", $hostnames);
3329
		unset($hostnames);
3330

    
3331
		if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid")) {
3332
			if ($filterdns_restart) {
3333
				killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3334
				sleep(2);
3335
				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");
3336
			} else {
3337
				sigkillbypid("{$g['varrun_path']}/filterdns-ipsec.pid", "HUP");
3338
			}
3339
		} else {
3340
			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");
3341
		}
3342
	} else {
3343
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3344
		@unlink("{$g['varrun_path']}/filterdns-ipsec.pid");
3345
	}
3346

    
3347
	if (platform_booting()) {
3348
		echo "done\n";
3349
	}
3350

    
3351
	unlock($ipsecstartlock);
3352
	return count($filterdns_list);
3353
}
3354

    
3355
function ipsec_gre_default_mtu() {
3356
	global $config;
3357

    
3358
	foreach ($config['interfaces'] as $if => $ifdetail) { 
3359
		if (interface_is_type($ifdetail['if'], 'gre') && !isset($ifdetail['mtu'])) {
3360
			if (is_greipsec($ifdetail['if'])) {
3361
				set_interface_mtu($ifdetail['if'], 1400);
3362
			} else {
3363
				set_interface_mtu($ifdetail['if'], 1476);
3364
			}
3365
		}
3366
	}
3367
}
3368

    
3369
/* Return the larger of derived SA rekey time and reauth time */
3370
function ipsec_get_renewmax($entry) {
3371
	if (empty($entry) || !is_array($entry)) {
3372
		return 0;
3373
	}
3374
	return max(ipsec_get_rekey_time($entry), ipsec_get_reauth_time($entry));
3375
}
3376

    
3377
/* Determine the life time of an SA entry (Hard upper total time limit for SA before it is removed) */
3378
function ipsec_get_life_time($entry) {
3379
	if (empty($entry) || !is_array($entry)) {
3380
		return 0;
3381
	}
3382
	/* Use a hardcoded value if present in the configuration */
3383
	if ($entry['lifetime'] > 0) {
3384
		return $entry['lifetime'];
3385
	}
3386
	/* If rekey or reauth are enabled, attempt to derive a lifetime from one of those */
3387
	$renewmax = ipsec_get_renewmax($entry);
3388
	if ($renewmax > 0) {
3389
		return intval($renewmax / 0.9);
3390
	}
3391
	/* To reach here, rekey_time and lifetime are both 0 which is invalid
3392
	 * Default to 16000 for p1 and 4000 for p2 */
3393
	if ($entry['iketype']) {
3394
		return 16000;
3395
	} else {
3396
		return 4000;
3397
	}
3398
}
3399

    
3400
/* Determine the rekey time of an SA entry (Time at which to rekey IKEv2 or Child SA entries) */
3401
function ipsec_get_rekey_time($entry) {
3402
	if (empty($entry) || !is_array($entry)) {
3403
		return 0;
3404
	}
3405
	/* Use a hardcoded value if present in the configuration */
3406
	if (strlen($entry['rekey_time'])) {
3407
		/* Check via strlen since 0 is a valid value */
3408
		return $entry['rekey_time'];
3409
	} elseif ($entry['lifetime'] > 0) {
3410
		/* If rekey_time is empty and lifetime is non-zero, use 90% lifetime */
3411
		return intval($entry['lifetime'] * 0.9);
3412
	}
3413
	/* To reach here, rekey_time and lifetime are empty
3414
	 * Default to 14400 for p1 and 3600 for p2 */
3415
	if ($entry['iketype']) {
3416
		return 14400;
3417
	} else {
3418
		return 3600;
3419
	}
3420
}
3421

    
3422
/* Determine the reauth time of an SA entry (IKE SA tear-down/reauthenticate) */
3423
function ipsec_get_reauth_time($entry) {
3424
	if (empty($entry) || !is_array($entry)) {
3425
		return 0;
3426
	}
3427
	/* Use a hardcoded value if present in the configuration */
3428
	if (strlen($entry['reauth_time'])) {
3429
		/* Check via strlen since 0 is a valid value */
3430
		return $entry['reauth_time'];
3431
	} elseif ($entry['lifetime'] > 0) {
3432
		/* If reauth_time is empty and lifetime is non-zero,
3433
		 * use 90% lifetime for IKEv1, disable for IKEv2/auto */
3434
		if ($entry['iketype'] == 'ikev1') {
3435
			return intval($entry['lifetime'] * 0.9);
3436
		} else {
3437
			return 0;
3438
		}
3439
	}
3440
	/* To reach here, rekey_time and lifetime are empty
3441
	 * Default to disabled (0) */
3442
	return 0;
3443
}
3444

    
3445
/* Determine the over time of an SA entry (Hard upper IKE SA time limit, relative to rekey/reauth time) */
3446
function ipsec_get_over_time($entry) {
3447
	if (empty($entry) || !is_array($entry)) {
3448
		return 0;
3449
	}
3450
	/* Automatically derive the value for rand_time */
3451
	$lifetime = ipsec_get_life_time($entry);
3452
	$renewmax = ipsec_get_renewmax($entry);
3453
	if (($lifetime > 0) && ($renewmax > 0)) {
3454
		/* If life time and rekey/reauth time both have values, subtract to get rand time */
3455
		return $lifetime - $renewmax;
3456
	} elseif ($lifetime > 0) {
3457
		/* If only life time has a value, use 10% of that */
3458
		return intval($lifetime * 0.1);
3459
	} elseif ($renewmax > 0) {
3460
		/* If only rekey/reauth time has a value, use 10% of that */
3461
		return intval($renewmax * 0.1);
3462
	}
3463
	/* No value can be determined, default to 0 */
3464
	return 0;
3465
}
3466

    
3467
/* Determine the rand time of an SA entry (random value subtracted from renewal time to prevent collisions) */
3468
function ipsec_get_rand_time($entry) {
3469
	if (empty($entry) || !is_array($entry)) {
3470
		return 0;
3471
	}
3472
	/* Use a hardcoded value if present in the configuration */
3473
	if (strlen($entry['rand_time'])) {
3474
		/* Check via strlen since 0 is a valid value */
3475
		return $entry['rand_time'];
3476
	}
3477
	/* Logic to automatically determine rand time is identical to calculating over time */
3478
	return ipsec_get_over_time($entry);
3479
}
3480

    
3481
?>
(27-27/62)