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
	'chacha20poly1305' => array('name' => 'CHACHA20-POLY1305')
138
);
139

    
140
global $p2_ealgos;
141
$p2_ealgos = array(
142
	'aes' => array('name' => 'AES', 'keysel' => array('lo' => 128, 'hi' => 256, 'step' => 64)),
143
	'aes128gcm' => array('name' => 'AES128-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
144
	'aes192gcm' => array('name' => 'AES192-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
145
	'aes256gcm' => array('name' => 'AES256-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
146
	'chacha20poly1305' => array('name' => 'CHACHA20-POLY1305')
147
);
148

    
149
global $p1_halgos;
150
$p1_halgos = array(
151
	'sha1' => 'SHA1',
152
	'sha256' => 'SHA256',
153
	'sha384' => 'SHA384',
154
	'sha512' => 'SHA512',
155
	'aesxcbc' => 'AES-XCBC'
156
);
157

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

    
184
global $p2_halgos;
185
$p2_halgos = array(
186
	'hmac_sha1' => 'SHA1',
187
	'hmac_sha256' => 'SHA256',
188
	'hmac_sha384' => 'SHA384',
189
	'hmac_sha512' => 'SHA512',
190
	'aesxcbc' => 'AES-XCBC'
191
);
192

    
193
global $p1_authentication_methods;
194
$p1_authentication_methods = array(
195
	'hybrid_cert_server' => array('name' => gettext('Hybrid Certificate + Xauth'), 'mobile' => true),
196
	'xauth_cert_server' => array('name' => gettext('Mutual Certificate + Xauth'), 'mobile' => true),
197
	'xauth_psk_server' => array('name' => gettext('Mutual PSK + Xauth'), 'mobile' => true),
198
	'eap-tls' => array('name' => gettext('EAP-TLS'), 'mobile' => true),
199
	'eap-radius' => array('name' => gettext('EAP-RADIUS'), 'mobile' => true),
200
	'eap-mschapv2' => array('name' => gettext('EAP-MSChapv2'), 'mobile' => true),
201
	'cert' => array('name' => gettext('Mutual Certificate'), 'mobile' => false),
202
	'pkcs11' => array('name' => gettext('Mutual Certificate (PKCS#11)'), 'mobile' => false),
203
	'pre_shared_key' => array('name' => gettext('Mutual PSK'), 'mobile' => false)
204
);
205

    
206
global $ipsec_preshared_key_type;
207
$ipsec_preshared_key_type = array(
208
	'PSK' => 'PSK',
209
	'EAP' => 'EAP'
210
);
211

    
212
global $ipsec_startactions;
213
$ipsec_startactions = array(
214
	'' => gettext('Default'),
215
	'none' => gettext('None (Responder Only)'),
216
	'start' => gettext('Initiate at start (VTI or Tunnel Mode)'),
217
	'trap' => gettext('Initiate on demand (Tunnel mode only)'),
218
);
219

    
220
global $ipsec_closeactions;
221
$ipsec_closeactions = array(
222
	'' => gettext('Default'),
223
	'none' => gettext('Close connection and clear SA'),
224
	'start' => gettext('Restart/Reconnect'),
225
	'trap' => gettext('Close connection and reconnect on demand'),
226
);
227

    
228
global $p2_modes;
229
$p2_modes = array(
230
	'tunnel' => gettext('Tunnel IPv4'),
231
	'tunnel6' => gettext('Tunnel IPv6'),
232
	'transport' => gettext('Transport'),
233
	'vti' => gettext('Routed (VTI)')
234
);
235

    
236
global $p2_protos;
237
$p2_protos = array(
238
	'esp' => 'ESP',
239
	'ah' => 'AH'
240
);
241

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

    
269
function ipsec_enabled() {
270
	global $config;
271

    
272
	if (!isset($config['ipsec']) || !is_array($config['ipsec'])) {
273
		return false;
274
	}
275

    
276
	/* Check if we have at least one phase 1 entry. */
277
	if (!isset($config['ipsec']['phase1']) ||
278
	    !is_array($config['ipsec']['phase1']) ||
279
	    empty($config['ipsec']['phase1'])) {
280
		return false;
281
	}
282
	/* Check if at least one phase 1 entry is enabled. */
283
	foreach ($config['ipsec']['phase1'] as $phase1) {
284
		if (!isset($phase1['disabled'])) {
285
			return true;
286
		}
287
	}
288

    
289
	return false;
290
}
291

    
292
/*
293
 * ikeid management functions
294
 */
295

    
296
function ipsec_ikeid_used($ikeid) {
297
	global $config;
298
	init_config_arr(array('ipsec', 'phase1'));
299
	foreach ($config['ipsec']['phase1'] as $ph1ent) {
300
		if ($ikeid == $ph1ent['ikeid']) {
301
			return true;
302
		}
303
	}
304
	return false;
305
}
306

    
307
function ipsec_ikeid_next() {
308
	global $config;
309
	$ikeid = 1;
310
	init_config_arr(array('ipsec', 'phase1'));
311
	$ipsecikeid = lock('ipsecikeids', LOCK_EX);
312
	$ikeids = array();
313

    
314
	foreach ($config['ipsec']['phase1'] as $ph1) {
315
		$keyids[$ph1['ikeid']] = $ph1['ikeid'];
316
	}
317

    
318
	for ($i = 1; $i < 16000; $i++) {
319
		if (!isset($keyids[$i])) {
320
			$keyid = $i;
321
			break;
322
		}
323
	}
324

    
325
	unlock($ipsecreqid);
326
	return $keyid;
327
}
328

    
329
function ipsec_new_reqid() {
330
	global $config;
331
	init_config_arr(array('ipsec', 'phase2'));
332
	$ipsecreqid = lock('ipsecreqids', LOCK_EX);
333
	$keyids = array();
334
	$keyid = 1;
335

    
336
	foreach ($config['ipsec']['phase2'] as $ph2) {
337
		$keyids[$ph2['reqid']] = $ph2['reqid'];
338
	}
339

    
340
	for ($i = 1; $i < 16000; $i++) {
341
		if (!isset($keyids[$i])) {
342
			$keyid = $i;
343
			break;
344
		}
345
	}
346

    
347
	unlock($ipsecreqid);
348
	return $keyid;
349
}
350

    
351
function ipsec_get_phase1($ikeid) {
352
	global $config;
353
	init_config_arr(array('ipsec', 'phase1'));
354

    
355
	foreach ($config['ipsec']['phase1'] as $p1) {
356
		if ($p1['ikeid'] == $ikeid) {
357
			return $p1;
358
		}
359
	}
360
}
361

    
362
function ipsec_get_p1_descr($ikeid) {
363
	global $config;
364
	init_config_arr(array('ipsec', 'phase1'));
365
	$p1 = ipsec_get_phase1($ikeid);
366
	return (!empty($p1['descr'])) ? $p1['descr'] : '';
367
}
368

    
369
/*
370
 * Return phase1 by reference for a given phase2
371
 */
372
function ipsec_lookup_phase1($p2, &$p1ref) {
373
	global $config;
374
	init_config_arr(array('ipsec', 'phase1'));
375

    
376
	foreach ($config['ipsec']['phase1'] as & $p1) {
377
		if ($p1['ikeid'] == $p2['ikeid']) {
378
			$p1ref = $p1;
379
			return true;
380
		}
381
	}
382

    
383
	return false;
384
}
385

    
386
function ipsec_get_phase2($reqid) {
387
	global $config;
388
	init_config_arr(array('ipsec', 'phase2'));
389

    
390
	foreach ($config['ipsec']['phase2'] as $p2) {
391
		if ($p2['reqid'] == $reqid) {
392
			return $p2;
393
		}
394
	}
395
}
396

    
397
function ipsec_get_phase2_by_ikeid($ikeid) {
398
	global $config;
399
	init_config_arr(array('ipsec', 'phase2'));
400
	$results = array();
401
	foreach ($config['ipsec']['phase2'] as $p2) {
402
		if ($p2['ikeid'] == $ikeid) {
403
			$results[] = $p2;
404
		}
405
	}
406
	return $results;
407
}
408

    
409
function ipsec_get_number_of_phase2($ikeid) {
410
	global $config;
411
	return count(ipsec_get_phase2_by_ikeid($ikeid));
412
}
413

    
414
/* Return a nested hash with P1 indexed by ikeid and P2 indexed by reqid */
415
function ipsec_map_config_by_id() {
416
	global $config;
417
	init_config_arr(array('ipsec', 'phase1'));
418
	init_config_arr(array('ipsec', 'phase2'));
419
	$map = array();
420

    
421
	foreach ($config['ipsec']['phase1'] as $p1) {
422
		$map[$p1['ikeid']] = array();
423
		$map[$p1['ikeid']]['p1'] = $p1;
424
	}
425
	foreach ($config['ipsec']['phase2'] as $p2) {
426
		if (!is_array($map[$p2['ikeid']]['p2'])) {
427
			$map[$p2['ikeid']]['p2'] = array();
428
		}
429
		$map[$p2['ikeid']]['p2'][$p2['reqid']] = $p2;
430
	}
431

    
432
	return $map;
433
}
434

    
435
function ipsec_conid($p1 = null, $p2 = null) {
436
	global $ipsec_conid_prefix, $ipsec_conid_separator;
437

    
438
	$conid = NULL;
439
	$have_p1 = (!empty($p1) && is_array($p1));
440
	$have_p2 = (!empty($p2) && is_array($p2));
441

    
442
	if (!$have_p1 && $have_p2) {
443
		$p1 = ipsec_get_phase1($p2['ikeid']);
444
	}
445

    
446
	if (isset($p1['mobile'])) {
447
		return "{$ipsec_conid_prefix}-mobile";
448
	}
449

    
450
	$conid = "{$ipsec_conid_prefix}{$p1['ikeid']}";
451

    
452
	if ($have_p2) {
453
		/* IKEv1 or IKEv2+Split Connections use separate P2 entries
454
		 * so add reqid to ID */
455
		if (($p1['iketype'] != 'ikev2') || isset($p1['splitconn'])) {
456
			$conid .= "{$ipsec_conid_separator}{$p2['reqid']}";
457
		}
458
	}
459

    
460
	return $conid;
461
}
462

    
463
function ipsec_id_by_conid($conid) {
464
	global $config, $ipsec_conid_prefix, $ipsec_conid_separator;
465

    
466
	if ($conid == "{$ipsec_conid_prefix}-mobile") {
467
		init_config_arr(array('ipsec', 'phase1'));
468
		foreach ($config['ipsec']['phase1'] as $p1) {
469
			if (isset($p1['mobile'])) {
470
				$conid = "{$ipsec_conid_prefix}{$p1['ikeid']}";
471
			}
472
		}
473
	}
474

    
475
	if (substr($conid, 0, strlen($ipsec_conid_prefix)) == $ipsec_conid_prefix) {
476
		$conid = substr($conid, strlen($ipsec_conid_prefix));
477
	}
478
	$parts = explode($ipsec_conid_separator, $conid);
479
	if (count($parts) == 1) {
480
		$parts[1] = NULL;
481
	}
482
	return array($parts[0], $parts[1]);
483
}
484

    
485
/*
486
 * Return phase1 local address
487
 */
488
function ipsec_get_phase1_src(& $ph1ent, $gateways_status = false) {
489
	global $interface_ip_arr_cache;
490
	global $interface_sn_arr_cache;
491
	if ($ph1ent['interface']) {
492
		/* get_interface_ip() already calls get_failover_interface so no need for special handling */
493
		$if = $ph1ent['interface'];
494
	} else {
495
		$if = "wan";
496
	}
497

    
498
	/* Fetch gateway status if not passed */
499
	if (!is_array($gateways_status)) {
500
		$gateways_status = return_gateways_status(true);
501
	}
502

    
503
	$ifips = array();
504
	if (in_array($ph1ent['protocol'], array('inet', 'both'))) {
505
		$ip4 = get_interface_ip($if, $gateways_status);
506
		if (!empty($ip4)) {
507
			$ifips[] = $ip4;
508
		}
509
	}
510

    
511
	if (in_array($ph1ent['protocol'], array('inet6', 'both'))) {
512
		/* get correct interface name for 6RD/6to4 interfaces
513
		 * see https://redmine.pfsense.org/issues/11643 */
514
		if (is_stf_interface($ph1ent['interface'])) {
515
			$ip6 = get_interface_ipv6($ph1ent['interface'], false, false, $gateways_status);
516
		} else {
517
			$ip6 = get_interface_ipv6($if, false, false, $gateways_status);
518
		}
519
		if (!empty($ip6)) {
520
			$ifips[] = $ip6;
521
		}
522
	}
523

    
524
	return implode(',', $ifips);
525
}
526

    
527
/*
528
 * Return phase1 local address
529
 */
530
function ipsec_get_phase1_dst(& $ph1ent) {
531
	global $g;
532

    
533
	if (empty($ph1ent['remote-gateway'])) {
534
		return false;
535
	}
536
	$rg = $ph1ent['remote-gateway'];
537
	if (!is_ipaddr($rg)) {
538
		if (!platform_booting()) {
539
			$result = resolve_retry($rg, $ph1ent['protocol']);
540
			if (!empty($result)) {
541
				return $result;
542
			} else {
543
				return false;
544
			}
545
		}
546
	}
547
	if (!is_ipaddr($rg)) {
548
		return false;
549
	}
550

    
551
	return $rg;
552
}
553

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

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

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

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

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

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

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

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

    
683
function ipsec_status() {
684
	$cmap = ipsec_map_config_by_id();
685
	$status = ipsec_list_sa();
686

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

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

    
699
	if (!is_array($status)) {
700
		$status = array();
701
	}
702

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
982
	return $spd;
983
}
984

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

    
1035
	return $sad;
1036
}
1037

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

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

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

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

    
1056
	$response = array(
1057
		'pool' => array(),
1058
	);
1059

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

    
1085
	unset($_gb, $output, $rc, $pool_regex);
1086

    
1087
	return $response;
1088
}
1089

    
1090
function ipsec_mobilekey_sort() {
1091
	global $config;
1092

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

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

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

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

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

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

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

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

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

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

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

    
1197
	return $idstring;
1198
}
1199

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

    
1213
	return $result;
1214
}
1215

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

    
1220
	$levels = array();
1221

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

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

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

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

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

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

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

    
1322
	return $modpmap[$index];
1323
}
1324

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

    
1334
	if (!ipsec_enabled()) {
1335
		return;
1336
	}
1337

    
1338
	$ipseccfg = $config['ipsec'];
1339

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

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

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

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

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

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

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

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

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

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

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

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

    
1539
			$ikeid = $ph1ent['ikeid'];
1540

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

    
1550
			if (isset($ph1ent['mobile'])) {
1551
				$mobile_ipsec_auth = $ph1ent['authentication_method'];
1552
				continue;
1553
			}
1554

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

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

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

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

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

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

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

    
1700
	if ($aggressive_mode_psk) {
1701
		$stronconf = '';
1702
		if (file_exists("{$g['varetc_path']}/ipsec/strongswan.conf")) {
1703
			$stronconf = file_get_contents("{$g['varetc_path']}/ipsec/strongswan.conf");
1704
		}
1705
		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.");
1706
		$restart = (!empty($stronconf) && strpos($stronconf, 'i_dont_care_about_security_and_use_aggressive_mode_psk') === FALSE);
1707
		unset($stronconf);
1708
		$ssconf['charon']['i_dont_care_about_security_and_use_aggressive_mode_psk'] = "yes";
1709
	}
1710

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1833
		$ssconf['charon']['plugins']['attr'] = array();
1834

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

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

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

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

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

    
1892
		if (!empty($a_client['dns_split'])) {
1893
			$ssconf['charon']['plugins']['attr'][] = "# Split DNS (UNITY_SPLITDNS_NAME)";
1894
			$ssconf['charon']['plugins']['attr']['28675'] = $a_client['dns_split'];
1895
			$ssconf['charon']['plugins']['attr'][] = "# Split DNS (INTERNAL_DNS_DOMAIN, RFC 8598)";
1896
			$ssconf['charon']['plugins']['attr']['25'] = str_replace(' ', ',', $a_client['dns_split']);
1897
		}
1898

    
1899
		if (!empty($a_client['login_banner'])) {
1900
			$ssconf['charon']['plugins']['attr'][] = "# Login Banner";
1901
			$ssconf['charon']['plugins']['attr']['28672'] = $a_client['login_banner'];
1902
		}
1903

    
1904
		if (isset($a_client['save_passwd'])) {
1905
			$ssconf['charon']['plugins']['attr'][] = "# Save Xauth Password";
1906
			$ssconf['charon']['plugins']['attr']['28673'] = "1";
1907
		}
1908

    
1909
		if ($a_client['pfs_group']) {
1910
			$ssconf['charon']['plugins']['attr'][] = "# Phase2 PFS Group";
1911
			$ssconf['charon']['plugins']['attr']['28679'] = $a_client['pfs_group'];
1912
		}
1913
	}
1914

    
1915
	@file_put_contents("{$g['varetc_path']}/ipsec/strongswan.conf", ipsec_strongswan_confgen($ssconf));
1916
}
1917

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

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

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

    
1957
	return;
1958
}
1959

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

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

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

    
2005
		$scconf['connections'][$upconn] = array();
2006
		$scconf['pools'][$upname] = array();
2007

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

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

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

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

    
2039
	$scconf['connections']['bypass'] = array();
2040
	/* Prevents the connection from being considered for remote peers */
2041
	$scconf['connections']['bypass']['remote_addrs'] = "127.0.0.1";
2042
	$scconf['connections']['bypass']['children'] = array();
2043

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

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

    
2088
	return;
2089
}
2090

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

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

    
2173
	/* Fetch gateway status if not passed */
2174
	if (!is_array($gateways_status)) {
2175
		$gateways_status = return_gateways_status(true);
2176
	}
2177

    
2178
	list($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local', array(), $gateways_status);
2179
	$localid = ipsec_fixup_id($myid_type, $myid_data);
2180
	if (!empty($localid)) {
2181
		$local['id'] = $localid;
2182
	}
2183

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

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

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

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

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

    
2304
	/* Add the encryption algorithm (if present) */
2305
	if (!empty($ealg_id)) {
2306
		$palgo .= "{$ealg_id}";
2307
	}
2308

    
2309
	/* Add the key length (if present) */
2310
	if (!empty($keylen)) {
2311
		$palgo .= "{$keylen}";
2312
	}
2313

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

    
2325
	if (!empty($prfalgo)) {
2326
		$palgo .= "-prf{$prfalgo}";
2327
	}
2328

    
2329
	/* Convert the DH group to its keyword and add (if present) */
2330
	$modp = ipsec_convert_to_modp($modp);
2331
	if (!empty($modp)) {
2332
		$palgo .= "-{$modp}";
2333
	}
2334

    
2335
	return $palgo;
2336
}
2337

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

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

    
2365
	/* Add to master list */
2366
	$algo_arr = array_merge($algo_arr, $proposal);
2367
	return implode(',', $proposal);
2368
}
2369

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

    
2384
function ipsec_get_ifname_by_conf($p1 = array(), $p2 = array()) {
2385
	global $config;
2386
	$have_p1 = (!empty($p1) && is_array($p1));
2387
	$have_p2 = (!empty($p2) && is_array($p2));
2388
	$reqid = null;
2389

    
2390
	if (!$have_p1 && $have_p2) {
2391
		$p1 = ipsec_get_phase1($p2['ikeid']);
2392
	}
2393

    
2394
	if ($have_p2) {
2395
		$reqid = $p2['reqid'];
2396
	}
2397

    
2398
	return ipsec_get_ifname($p1, $reqid);
2399
}
2400

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

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

    
2449
	/* Fetch gateway status if not passed */
2450
	if (!is_array($gateways_status)) {
2451
		$gateways_status = return_gateways_status(true);
2452
	}
2453

    
2454
	$a_groups = return_gateway_groups_array(true);
2455

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

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

    
2489
		/* Common parameters for all children */
2490
		$child_params = array();
2491
		if (!empty($ph1ent['closeaction'])) {
2492
			$child_params['close_action'] = $ph1ent['closeaction'];
2493
		}
2494

    
2495
		$ikeid = $ph1ent['ikeid'];
2496

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

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

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

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

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

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

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

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

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

    
2603
		/* Reauth (Any) */
2604
		$conn['reauth_time'] = ipsec_get_reauth_time($ph1ent) . "s";
2605

    
2606
		/* Over Time */
2607
		$conn['over_time'] = ipsec_get_over_time($ph1ent) . "s";
2608

    
2609
		/* Rand Time */
2610
		$conn['rand_time'] = ipsec_get_rand_time($ph1ent) . "s";
2611

    
2612
		/* NAT Traversal */
2613
		$conn['encap'] = ($ph1ent['nat_traversal'] == 'force') ? "yes" : "no";
2614

    
2615
		/* MOBIKE support */
2616
		$conn['mobike'] = ($ph1ent['mobike'] == 'on') ? "yes" : "no";
2617

    
2618
		/* TFC Padding */
2619
		if (isset($ph1ent['tfc_enable'])) {
2620
			$conn['tfc_padding'] = (isset($ph1ent['tfc_bytes']) && is_numericint($ph1ent['tfc_bytes'])) ? $ph1ent['tfc_bytes'] : "mtu";
2621
		}
2622

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

    
2634
		/* Arrays for P2s/children */
2635
		$children = array();
2636
		$remote_ts_spec = array();
2637
		$local_ts_spec = array();
2638
		$reqids = array();
2639
		$has_vti = false;
2640
		$ealgoAHsp2arr = array();
2641
		$ealgoESPsp2arr = array();
2642

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

    
2657
				$localid_type = $ph2ent['localid']['type'];
2658
				$localsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
2659

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

    
2688
				$local_ts = $localsubnet_data;
2689

    
2690
				if (!isset($ph2ent['mobile'])) {
2691
					$remote_ts = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
2692
				} else if (!empty($a_client['pool_address'])) {
2693
					$remote_ts = "{$a_client['pool_address']}/{$a_client['pool_netbits']}";
2694
				}
2695

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

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

    
2725
				if (!isset($ph2ent['mobile'])) {
2726
					$remote_ts = $remote_spec;
2727
				}
2728
			}
2729

    
2730
			if (!empty($local_ts)) {
2731
				$local_ts_spec[] = $local_ts;
2732
			}
2733
			if (!empty($remote_ts)) {
2734
				$remote_ts_spec[] = $remote_ts;
2735
			}
2736

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

    
2743
			$reqids[] = $ph2ent['reqid'];
2744

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

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

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

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

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

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

    
2835
				$descr = "# P2 (reqid {$ph2ent['reqid']})";
2836
				if (!empty($ph2ent['descr'])) {
2837
					$descr .= ": {$ph2ent['descr']}";
2838
				}
2839
				array_unshift($children[$cname], $descr);
2840
			}
2841
		}
2842

    
2843
		$conn['local_addrs'] = $local_spec;
2844
		$conn['remote_addrs'] = $remote_spec;
2845

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

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

    
2899
		/* Setup connection authentication */
2900
		ipsec_setup_authentication($ph1ent, $conn, $gateways_status);
2901

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

    
2911
	return;
2912
}
2913

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

    
2926
	$suffix = 0;
2927

    
2928
	/* Fetch gateway status if not passed */
2929
	if (!is_array($gateways_status)) {
2930
		$gateways_status = return_gateways_status(true);
2931
	}
2932

    
2933
	$vpncas = array();
2934
	if (is_array($a_phase1) && count($a_phase1)) {
2935
		foreach ($a_phase1 as $ph1ent) {
2936
			if (isset($ph1ent['disabled'])) {
2937
				continue;
2938
			}
2939

    
2940
			if (isset($ph1ent['mobile'])) {
2941
				if ($ph1ent['authentication_method'] == 'pre_shared_key') {
2942
					$mobilepsk = true;
2943
				} elseif ($ph1ent['authentication_method'] == 'eap-mschapv2') {
2944
					$mobileeap = true;
2945
				}
2946
			}
2947

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

    
2953
				$ikeid = $ph1ent['ikeid'];
2954
				$cert = lookup_cert($ph1ent['certref']);
2955

    
2956
				if (!$cert) {
2957
					log_error(sprintf(gettext("Error: Invalid phase1 certificate reference for %s"), $ph1ent['name']));
2958
					continue;
2959
				}
2960

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

    
2971
				@chmod($ipsec_swanctl_dirs['certpath'], 0600);
2972

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

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

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

    
3008
				if (empty($peerid_data)) {
3009
					continue;
3010
				}
3011

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

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

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

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

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

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

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

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

    
3137
	/* service may have been enabled, disabled, or otherwise changed in a
3138
	 *way requiring rule updates */
3139
	filter_configure();
3140

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

    
3174
	if (platform_booting()) {
3175
		echo gettext("Configuring IPsec VPN... ");
3176
	}
3177

    
3178
	$ipsecstartlock = lock('ipsec', LOCK_EX);
3179

    
3180
	/* Prepare automatic ping_hosts.sh data */
3181
	unlink_if_exists("{$g['vardb_path']}/ipsecpinghosts");
3182
	touch("{$g['vardb_path']}/ipsecpinghosts");
3183
	$ipsecpinghostsactive = false;
3184

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

    
3195
	$mobile_configured = false;
3196

    
3197

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

    
3215
	$ipsec_vti_cleanup_ifs = array();
3216
	$rgmap = array();
3217
	$filterdns_list = array();
3218
	$aggressive_mode_psk = false;
3219
	$mobile_ipsec_auth = "";
3220
	$ifacesuse = array();
3221
	$natfilterrules = false;
3222

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

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

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

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

    
3280
	/* Clean up unused VTI interfaces */
3281
	foreach ($ipsec_vti_cleanup_ifs as $cleanif) {
3282
		if (does_interface_exist($cleanif)) {
3283
			mwexec("/sbin/ifconfig " . escapeshellarg($cleanif) . " destroy", false);
3284
		}
3285
	}
3286

    
3287
	/* set default MTU to 1400 for GRE over IPsec, otherwise to 1476 */
3288
	ipsec_gre_default_mtu(); 
3289

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

    
3301
	// Run ping_hosts.sh once if it's enabled to avoid wait for minicron
3302
	if ($ipsecpinghostsactive) {
3303
		mwexec_bg("/usr/local/bin/ping_hosts.sh");
3304
	}
3305

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

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

    
3324
		if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid")) {
3325
			if ($filterdns_restart) {
3326
				killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3327
				sleep(2);
3328
				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");
3329
			} else {
3330
				sigkillbypid("{$g['varrun_path']}/filterdns-ipsec.pid", "HUP");
3331
			}
3332
		} else {
3333
			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");
3334
		}
3335
	} else {
3336
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3337
		@unlink("{$g['varrun_path']}/filterdns-ipsec.pid");
3338
	}
3339

    
3340
	if (platform_booting()) {
3341
		echo "done\n";
3342
	}
3343

    
3344
	unlock($ipsecstartlock);
3345
	return count($filterdns_list);
3346
}
3347

    
3348
function ipsec_gre_default_mtu() {
3349
	global $config;
3350

    
3351
	foreach ($config['interfaces'] as $if => $ifdetail) { 
3352
		if (interface_is_type($ifdetail['if'], 'gre') && !isset($ifdetail['mtu'])) {
3353
			if (is_greipsec($ifdetail['if'])) {
3354
				set_interface_mtu($ifdetail['if'], 1400);
3355
			} else {
3356
				set_interface_mtu($ifdetail['if'], 1476);
3357
			}
3358
		}
3359
	}
3360
}
3361

    
3362
/* Return the larger of derived SA rekey time and reauth time */
3363
function ipsec_get_renewmax($entry) {
3364
	if (empty($entry) || !is_array($entry)) {
3365
		return 0;
3366
	}
3367
	return max(ipsec_get_rekey_time($entry), ipsec_get_reauth_time($entry));
3368
}
3369

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

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

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

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

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

    
3474
?>
(27-27/62)