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-2024 Rubicon Communications, LLC (Netgate)
10
 * All rights reserved.
11
 *
12
 * Licensed under the Apache License, Version 2.0 (the "License");
13
 * you may not use this file except in compliance with the License.
14
 * You may obtain a copy of the License at
15
 *
16
 * http://www.apache.org/licenses/LICENSE-2.0
17
 *
18
 * Unless required by applicable law or agreed to in writing, software
19
 * distributed under the License is distributed on an "AS IS" BASIS,
20
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
 * See the License for the specific language governing permissions and
22
 * limitations under the License.
23
 */
24

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

    
30
/* IPsec defines */
31

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

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

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

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

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

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

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

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

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

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

    
132
global $p1_ealgos;
133
$p1_ealgos = array(
134
	'aes' => array('name' => 'AES', 'keysel' => array('lo' => 128, 'hi' => 256, 'step' => 64)),
135
	'aes128gcm' => array('name' => 'AES128-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
136
	'aes192gcm' => array('name' => 'AES192-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
137
	'aes256gcm' => array('name' => 'AES256-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
138
	'chacha20poly1305' => array('name' => 'CHACHA20-POLY1305')
139
);
140

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

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

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

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

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

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

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

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

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

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

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

    
270
function ipsec_enabled() {
271
	if (!is_array(config_get_path('ipsec'))) {
272
		return false;
273
	}
274

    
275
	/* Check if at least one phase 1 entry is enabled. */
276
	foreach (config_get_path('ipsec/phase1', []) as $phase1) {
277
		if (!isset($phase1['disabled'])) {
278
			return true;
279
		}
280
	}
281

    
282
	return false;
283
}
284

    
285
/*
286
 * ikeid management functions
287
 */
288

    
289
function ipsec_ikeid_used($ikeid) {
290
	foreach (config_get_path('ipsec/phase1', []) as $ph1ent) {
291
		if ($ikeid == $ph1ent['ikeid']) {
292
			return true;
293
		}
294
	}
295
	return false;
296
}
297

    
298
function ipsec_ikeid_next() {
299
	$ikeid = 1;
300
	$ipsecikeid = lock('ipsecikeids', LOCK_EX);
301
	$ikeids = array();
302

    
303
	foreach (config_get_path('ipsec/phase1', []) as $ph1) {
304
		$ikeids[$ph1['ikeid']] = $ph1['ikeid'];
305
	}
306

    
307
	for ($i = 1; $i < 16000; $i++) {
308
		if (!isset($ikeids[$i])) {
309
			$ikeid = $i;
310
			break;
311
		}
312
	}
313

    
314
	unlock($ipsecikeid);
315
	return $ikeid;
316
}
317

    
318
function ipsec_new_reqid() {
319
	$ipsecreqid = lock('ipsecreqids', LOCK_EX);
320
	$keyids = array();
321
	$keyid = 1;
322

    
323
	foreach (config_get_path('ipsec/phase2', []) as $ph2) {
324
		$keyids[$ph2['reqid']] = $ph2['reqid'];
325
	}
326

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

    
334
	unlock($ipsecreqid);
335
	return $keyid;
336
}
337

    
338
function ipsec_get_phase1($ikeid) {
339
	foreach (config_get_path('ipsec/phase1', []) as $p1) {
340
		if ($p1['ikeid'] == $ikeid) {
341
			return $p1;
342
		}
343
	}
344
}
345

    
346
function ipsec_get_p1_descr($ikeid) {
347
	$p1 = ipsec_get_phase1($ikeid);
348
	return (!empty($p1['descr'])) ? $p1['descr'] : '';
349
}
350

    
351
/*
352
 * Return copy of phase1 for a given phase2
353
 */
354
function ipsec_lookup_phase1($p2, &$p1_disabled) {
355
	foreach (config_get_path('ipsec/phase1', []) as $p1) {
356
		if ($p1['ikeid'] == $p2['ikeid']) {
357
			$p1_disabled = $p1['disabled'];
358
			return true;
359
		}
360
	}
361

    
362
	return false;
363
}
364

    
365
function ipsec_get_phase2($reqid) {
366
	foreach (config_get_path('ipsec/phase2', []) as $p2) {
367
		if ($p2['reqid'] == $reqid) {
368
			return $p2;
369
		}
370
	}
371
}
372

    
373
function ipsec_get_phase2_by_ikeid($ikeid) {
374
	$results = array();
375
	foreach (config_get_path('ipsec/phase2', []) as $p2) {
376
		if ($p2['ikeid'] == $ikeid) {
377
			$results[] = $p2;
378
		}
379
	}
380
	return $results;
381
}
382

    
383
function ipsec_get_number_of_phase2($ikeid) {
384
	return count(ipsec_get_phase2_by_ikeid($ikeid));
385
}
386

    
387
/* Return a nested hash with P1 indexed by ikeid and P2 indexed by reqid */
388
function ipsec_map_config_by_id() {
389
	$map = array();
390

    
391
	foreach (config_get_path('ipsec/phase1', []) as $p1) {
392
		$map[$p1['ikeid']] = array();
393
		$map[$p1['ikeid']]['p1'] = $p1;
394
	}
395
	foreach (config_get_path('ipsec/phase2', []) as $p2) {
396
		if (!is_array($map[$p2['ikeid']]['p2'])) {
397
			$map[$p2['ikeid']]['p2'] = array();
398
		}
399
		$map[$p2['ikeid']]['p2'][$p2['reqid']] = $p2;
400
	}
401

    
402
	return $map;
403
}
404

    
405
function ipsec_conid($p1 = null, $p2 = null) {
406
	global $ipsec_conid_prefix, $ipsec_conid_separator;
407

    
408
	$conid = NULL;
409
	$have_p1 = (!empty($p1) && is_array($p1));
410
	$have_p2 = (!empty($p2) && is_array($p2));
411

    
412
	if (!$have_p1 && $have_p2) {
413
		$p1 = ipsec_get_phase1($p2['ikeid']);
414
	}
415

    
416
	if (isset($p1['mobile'])) {
417
		return "{$ipsec_conid_prefix}-mobile";
418
	}
419

    
420
	$conid = "{$ipsec_conid_prefix}{$p1['ikeid']}";
421

    
422
	if ($have_p2) {
423
		/* IKEv1 or IKEv2+Split Connections use separate P2 entries
424
		 * so add reqid to ID */
425
		if (($p1['iketype'] != 'ikev2') || isset($p1['splitconn'])) {
426
			$conid .= "{$ipsec_conid_separator}{$p2['reqid']}";
427
		}
428
	}
429

    
430
	return $conid;
431
}
432

    
433
function ipsec_id_by_conid($conid) {
434
	global $ipsec_conid_prefix, $ipsec_conid_separator;
435

    
436
	if ($conid == "{$ipsec_conid_prefix}-mobile") {
437
		foreach (config_get_path('ipsec/phase1', []) as $p1) {
438
			if (isset($p1['mobile'])) {
439
				$conid = $ipsec_conid_prefix . $p1['ikeid'];
440
			}
441
		}
442
	}
443

    
444
	if (substr($conid, 0, strlen($ipsec_conid_prefix)) == $ipsec_conid_prefix) {
445
		$conid = substr($conid, strlen($ipsec_conid_prefix));
446
	}
447
	$parts = explode($ipsec_conid_separator, $conid);
448
	if (count($parts) == 1) {
449
		$parts[1] = NULL;
450
	}
451
	return array($parts[0], $parts[1]);
452
}
453

    
454
/*
455
 * Return phase1 local address
456
 */
457
function ipsec_get_phase1_src(& $ph1ent) {
458
	global $interface_ip_arr_cache;
459
	global $interface_sn_arr_cache;
460
	if ($ph1ent['interface']) {
461
		/* get_interface_ip() already calls get_failover_interface so no need for special handling */
462
		$if = $ph1ent['interface'];
463
	} else {
464
		$if = "wan";
465
	}
466

    
467
	$ifips = array();
468
	if (in_array($ph1ent['protocol'], array('inet', 'both'))) {
469
		$ip4 = get_interface_ip($if);
470
		if (!empty($ip4)) {
471
			$ifips[] = $ip4;
472
		}
473
	}
474

    
475
	if (in_array($ph1ent['protocol'], array('inet6', 'both'))) {
476
		/* get correct interface name for 6RD/6to4 interfaces
477
		 * see https://redmine.pfsense.org/issues/11643 */
478
		if (is_stf_interface($ph1ent['interface'])) {
479
			$ip6 = get_interface_ipv6($ph1ent['interface'], false, false);
480
		} else {
481
			$ip6 = get_interface_ipv6($if, false, false);
482
		}
483
		if (!empty($ip6)) {
484
			$ifips[] = $ip6;
485
		}
486
	}
487

    
488
	return implode(',', $ifips);
489
}
490

    
491
/*
492
 * Return phase1 local address
493
 */
494
function ipsec_get_phase1_dst(& $ph1ent) {
495
	global $g;
496

    
497
	if (empty($ph1ent['remote-gateway'])) {
498
		return false;
499
	}
500
	$rg = $ph1ent['remote-gateway'];
501
	if (!is_ipaddr($rg)) {
502
		if (!is_platform_booting()) {
503
			$result = resolve_retry($rg, $ph1ent['protocol']);
504
			if (!empty($result)) {
505
				return $result;
506
			} else {
507
				return false;
508
			}
509
		}
510
	}
511
	if (!is_ipaddr($rg)) {
512
		return false;
513
	}
514

    
515
	return $rg;
516
}
517

    
518
/*
519
 * Return phase2 idinfo in cidr format
520
 */
521
function ipsec_idinfo_to_cidr(& $idinfo, $addrbits = false, $mode = "") {
522
	switch ($idinfo['type']) {
523
		case "address":
524
			if ($addrbits) {
525
				if ($mode == "tunnel6") {
526
					return $idinfo['address']."/128";
527
				} elseif (($mode == "vti") && is_ipaddrv4($idinfo['address'])) {
528
					return $idinfo['address']."/30";
529
				} elseif (($mode == "vti") && is_ipaddrv6($idinfo['address'])) {
530
					return $idinfo['address']."/64";
531
				} else {
532
					return $idinfo['address']."/32";
533
				}
534
			} else {
535
				return $idinfo['address'];
536
			}
537
			break; /* NOTREACHED */
538
		case "network":
539
			return "{$idinfo['address']}/{$idinfo['netbits']}";
540
			break; /* NOTREACHED */
541
		case "none":
542
		case "mobile":
543
			return '0.0.0.0/0';
544
			break; /* NOTREACHED */
545
		default:
546
			if (empty($mode) && !empty($idinfo['mode'])) {
547
				$mode = $idinfo['mode'];
548
			}
549

    
550
			if ($mode == "tunnel6") {
551
				$address = get_interface_ipv6($idinfo['type']);
552
				$netbits = get_interface_subnetv6($idinfo['type']);
553
				$address = gen_subnetv6($address, $netbits);
554
				return "{$address}/{$netbits}";
555
			} else {
556
				$address = get_interface_ip($idinfo['type']);
557
				$netbits = get_interface_subnet($idinfo['type']);
558
				$address = gen_subnet($address, $netbits);
559
				return "{$address}/{$netbits}";
560
			}
561
			break; /* NOTREACHED */
562
	}
563
}
564

    
565
/*
566
 * Return phase2 idinfo in address/netmask format
567
 */
568
function ipsec_idinfo_to_subnet(& $idinfo, $addrbits = false) {
569
	switch ($idinfo['type']) {
570
		case "address":
571
			if ($addrbits) {
572
				if ($idinfo['mode'] == "tunnel6") {
573
					return $idinfo['address']."/128";
574
				} else {
575
					return $idinfo['address']."/255.255.255.255";
576
				}
577
			} else {
578
				return $idinfo['address'];
579
			}
580
			break; /* NOTREACHED */
581
		case "none":
582
		case "network":
583
			return $idinfo['address']."/".gen_subnet_mask($idinfo['netbits']);
584
			break; /* NOTREACHED */
585
		case "mobile":
586
			return "0.0.0.0/0";
587
			break; /* NOTREACHED */
588
		default:
589
			if ($idinfo['mode'] == "tunnel6") {
590
				$address = get_interface_ipv6($idinfo['type']);
591
				$netbits = get_interface_subnetv6($idinfo['type']);
592
				$address = gen_subnetv6($address, $netbits);
593
				return $address."/".$netbits;
594
			} else {
595
				$address = get_interface_ip($idinfo['type']);
596
				$netbits = get_interface_subnet($idinfo['type']);
597
				$address = gen_subnet($address, $netbits);
598
				return $address."/".$netbits;
599
			}
600
			break; /* NOTREACHED */
601
	}
602
}
603

    
604
/*
605
 *  Return phase2 idinfo in text format
606
 */
607
function ipsec_idinfo_to_text(& $idinfo) {
608
	switch ($idinfo['type']) {
609
		case "address":
610
			return $idinfo['address'];
611
			break; /* NOTREACHED */
612
		case "network":
613
			return $idinfo['address']."/".$idinfo['netbits'];
614
			break; /* NOTREACHED */
615
		case "mobile":
616
			return gettext("Mobile Client");
617
			break; /* NOTREACHED */
618
		case "none":
619
			return gettext("None");
620
			break; /* NOTREACHED */
621
		default:
622
			$specialnet = get_specialnet('', [SPECIALNET_IFSUB]);
623
			if (array_key_exists($idinfo['type'], $specialnet)) {
624
				return $specialnet[$idinfo['type']];
625
			} else {
626
				return strtoupper($idinfo['type']);
627
			}
628
			break; /* NOTREACHED */
629
	}
630
}
631

    
632
/*
633
 * Wrapper to call pfSense_ipsec_list_sa() when IPsec is enabled
634
 */
635
function ipsec_list_sa() {
636
	if (ipsec_enabled()) {
637
		return pfSense_ipsec_list_sa();
638
	}
639
	return array();
640
}
641

    
642
function ipsec_status() {
643
	$cmap = ipsec_map_config_by_id();
644
	$status = ipsec_list_sa();
645

    
646
	/*
647
	Start:
648
	$cmap[$ikeid]['p1'] => Phase 1 config
649
	$cmap[$ikeid]['p2'] => Array of P2 configs indexed by reqid
650

    
651
	End:
652
	$cmap[$ikeid]['p1']['status'] => Array of IKE SA entries and child SAs for this P1
653
	$cmap[$ikeid]['p1']['connected'] => true/false if the P1 is connected
654
	$cmap[$ikeid]['p2'][$reqid]['connected'] => true/false if the P2 is connected
655
		If non-split IKEv2 then mark all as 'true'
656
	*/
657

    
658
	if (!is_array($status)) {
659
		$status = array();
660
	}
661

    
662
	$cmap['connected'] = array(
663
		/* List of connected P1 conid entries (excluding mobile) */
664
		'p1' => array(),
665
		/* List of connected P2 conid entries (excluding mobile) */
666
		'p2' => array(),
667
	);
668
	$cmap['disconnected'] = array(
669
		/* List of disconnected P1 conid entries (excluding mobile) */
670
		'p1' => array(),
671
		/* List of disconnected P2 conid entries (excluding mobile) */
672
		'p2' => array(),
673
	);
674

    
675
	/* First level of array has IKE SA content */
676
	foreach ($status as $ikesa) {
677
		/* If the con-id isn't there it must not be a proper entry */
678
		if (!isset($ikesa['con-id'])) {
679
			continue;
680
		}
681

    
682
		/* Mark this IKE ID as connected and drop the status info underneath the P1 config */
683
		list($ikeid, $reqid) = ipsec_id_by_conid($ikesa['con-id']);
684
		if (!array_key_exists($ikeid, $cmap)) {
685
			// Doesn't match known tunnel
686
			$cmap['connected']['p1'][$ikesa['con-id']] = $ikesa['con-id'];
687
		} else {
688
			/* Track this IKE ID in the connection list */
689
			$cmap['connected']['p1'][$ikeid] = $ikesa['con-id'];
690
			/* Copy the status data. Use an array since it could be connected multiple times. */
691
			if (!is_array($cmap[$ikeid]['status'])) {
692
				$cmap[$ikeid]['status'] = array();
693
			}
694
			$cmap[$ikeid]['status'][] = $ikesa;
695
			$cmap[$ikeid]['p1']['connected'] = true;
696
		}
697

    
698
		/* If there are child SAs under this IKE entry, process them */
699
		if (array_key_exists('child-sas', $ikesa) &&
700
		    is_array($ikesa['child-sas'])) {
701
			foreach ($ikesa['child-sas'] as $childid => $childsa) {
702
				/* Mark this reqid as connected */
703
				list($childikeid, $childreqid) = ipsec_id_by_conid($childsa['name']);
704

    
705
				if ($childreqid != null) {
706
					if (!isset($cmap[$childikeid]['p2'][$childreqid]['mobile'])) {
707
						$cmap['connected']['p2'][$childreqid] = $childsa['name'];
708
						$cmap[$childikeid]['p2'][$childreqid]['connected'] = true;
709
					}
710
				} else {
711
					/* If this is IKEv2 w/o Split, mark all reqids for the P1 as connected */
712
					if ($cmap[$childikeid]['p1']['iketype'] == 'ikev2' &&
713
					    !isset($cmap[$childikeid]['p1']['splitconn'])) {
714
						foreach ($cmap[$ikeid]['p2'] as $p2) {
715
							if (isset($p2['mobile'])) {
716
								continue;
717
							}
718
							$cmap['connected']['p2'][$p2['reqid']] = $childsa['name'];
719
							$cmap[$childikeid]['p2'][$p2['reqid']]['connected'] = true;
720
						}
721
					}
722
				}
723
			}
724
		}
725
	}
726
	if (is_array($cmap)) {
727
		foreach ($cmap as $k => $tunnel) {
728
			if (in_array($k, array('connected', 'disconnected')) ||
729
			    (!array_key_exists('p1', $tunnel) ||
730
			    isset($tunnel['p1']['disabled'])) ||
731
			    isset($tunnel['p1']['mobile'])) {
732
				continue;
733
			}
734
			if (!array_key_exists($tunnel['p1']['ikeid'], $cmap['connected']['p1'])) {
735
				$cmap['disconnected']['p1'][$tunnel['p1']['ikeid']] = ipsec_conid($tunnel['p1']);
736
			}
737
			if (is_array($tunnel['p2'])) {
738
				foreach ($tunnel['p2'] as $p2) {
739
					if (isset($p2['mobile'])) {
740
						continue;
741
					}
742
					if (!array_key_exists($p2['reqid'], $cmap['connected']['p2'])) {
743
						/* This P2 is not connected */
744
						$cmap['disconnected']['p2'][$p2['reqid']] = ipsec_conid($tunnel['p1'], $p2);
745
					}
746
				}
747
			}
748
		}
749
	}
750
	return $cmap;
751
}
752

    
753
function ipsec_status_button($req, $act, $type, $conid, $uniqueid, $full) {
754
	$btn = '<a href="';
755
	if ($act == 'disconnect') {
756
		$buttonclass = ($type == 'ike') ? 'danger' : 'warning';
757
		$title = gettext("Disconnect");
758
		$icon = 'fa-solid fa-trash-can';
759
	} else {
760
		$buttonclass = 'success';
761
		$title = gettext("Connect");
762
		$icon = 'fa-solid fa-right-to-bracket';
763
	}
764
	if ($full) {
765
		$linkclass = 'btn btn-xs btn-' . htmlspecialchars($buttonclass);
766
	} else {
767
		$linkclass = '';
768
	}
769

    
770
	$title .= " ";
771
	switch ($type) {
772
		case 'all':
773
			$title .= gettext("P1 and P2s");
774
			break;
775
		case 'child':
776
			$title .= gettext("P2");
777
			break;
778
		case 'ike':
779
		default:
780
			$title .= gettext("P1");
781
			break;
782
	}
783

    
784
	if ($req == 'post') {
785
		$btn .= 'status_ipsec.php?act=' . htmlspecialchars($act) .
786
			'&amp;type=' . htmlspecialchars($type) .
787
			'&amp;conid=' . htmlspecialchars($conid);
788
		if (!empty($uniqueid)) {
789
			$btn .= '&amp;uniqueid=' . htmlspecialchars($uniqueid);
790
		}
791
	} else {
792
		$btn .= '#" id="' . 'ipsecstatus-' .
793
			htmlspecialchars($act) . '-' .
794
			htmlspecialchars($type) . '-' .
795
			htmlspecialchars($conid);
796
		if (!empty($uniqueid)) {
797
			$btn .= '-' . htmlspecialchars($uniqueid);
798
		}
799
	}
800

    
801
	$btn .= '"';
802
	if ($full) {
803
		$btn .= ' class="' . htmlspecialchars($linkclass) . '"';
804
	}
805
	$btn .= ' title="' . htmlspecialchars($title) . '"';
806

    
807
	if ($req == 'post') {
808
		$btn .= ' usepost';
809
	}
810
	$btn .= '>';
811
	$btn .= '<i class="' . htmlspecialchars($icon);
812
	if ($req == 'post') {
813
		$btn .= ' icon-embed-btn';
814
	}
815
	$btn .= '"></i>';
816

    
817
	if ($full) {
818
		$btn .= ' ' . htmlspecialchars($title);
819
	}
820
	$btn .= '</a>';
821
	return $btn;
822
}
823

    
824
function ipsec_initiate($type = 'ike', $p1 = null, $p2 = null) {
825
	return ipsec_initiate_by_conid($type, ipsec_conid($p1, $p2));
826
}
827

    
828
function ipsec_initiate_by_conid($type, $conid) {
829
	if (empty($conid)) {
830
		return false;
831
	}
832
	switch ($type) {
833
		case 'all':
834
			/* Find relevant P2s and initiate all of them */
835
			$cmap = ipsec_map_config_by_id();
836
			list($ikeid, $reqid) = ipsec_id_by_conid($conid);
837
			if (array_key_exists($ikeid, $cmap)) {
838
				if ($cmap[$ikeid]['p1']['iketype'] == 'ikev2' && !isset($cmap[$ikeid]['p1']['splitconn'])) {
839
					/* IKEv2 without split only has one P2, named the same as the P1 */
840
					ipsec_initiate_by_conid('child', ipsec_conid($cmap[$ikeid]['p1']));
841
				} else {
842
					foreach ($cmap[$ikeid]['p2'] as $p2) {
843
						ipsec_initiate_by_conid('child', ipsec_conid($cmap[$ikeid]['p1'], $p2));
844
					}
845
				}
846
			}
847
			break;
848
		case 'ike':
849
		case 'child':
850
			mwexec_bg("/usr/local/sbin/swanctl --initiate --timeout 5 " . escapeshellarg('--' . $type) . " " . escapeshellarg($conid));
851
			break;
852
		default:
853
			/* Do nothing. Invalid type. */
854
			break;
855
	}
856
	return true;
857
}
858

    
859
function ipsec_terminate($type = 'ike', $p1 = null, $p2 = null, $uniqueid = null) {
860
	return ipsec_terminate_by_conid($type, ipsec_conid($p1, $p2), $uniqueid);
861
}
862

    
863
function ipsec_terminate_by_conid($type = 'ike', $conid = null, $uniqueid = null) {
864
	/* Must have one or the other */
865
	if (($conid === null) && ($uniqueid === null)) {
866
		return false;
867
	}
868
	$selector = '--';
869
	$selector .= ($type == 'ike') ? 'ike' : 'child';
870

    
871
	if (ctype_digit(strval($uniqueid)) && ($uniqueid > 0)) {
872
		$selector .= '-id';
873
		$term = $uniqueid;
874
	} else {
875
		$term = $conid;
876
	}
877
	mwexec_bg("/usr/local/sbin/swanctl --terminate --force " . escapeshellarg($selector) . " " . escapeshellarg($term));
878
	return true;
879
}
880

    
881
/*
882
 * Return dump of SPD table
883
 */
884
function ipsec_dump_spd() {
885
	$fd = @popen("/sbin/setkey -DP", "r");
886
	$spd = array();
887
	if ($fd) {
888
		while (!feof($fd)) {
889
			$line = chop(fgets($fd));
890
			if (!$line) {
891
				continue;
892
			}
893
			if ($line == "No SPD entries.") {
894
				break;
895
			}
896
			if ($line[0] != "\t") {
897
				if (is_array($cursp)) {
898
					$spd[] = $cursp;
899
				}
900
				$cursp = array();
901
				$linea = explode(" ", $line);
902
				$cursp['srcid'] = substr($linea[0], 0, strpos($linea[0], "["));
903
				$cursp['dstid'] = substr($linea[1], 0, strpos($linea[1], "["));
904
				$i = 0;
905
			} else if (is_array($cursp)) {
906
				$line = trim($line, "\t\r\n ");
907
				$linea = explode(" ", $line);
908
				switch ($i) {
909
					case 1:
910
						if ($linea[1] == "none")	/* don't show default anti-lockout rule */ {
911
							unset($cursp);
912
						} else {
913
							$cursp['dir'] = $linea[0];
914
						}
915
						break;
916
					case 2:
917
						$upperspec = explode("/", $linea[0]);
918
						$cursp['proto'] = $upperspec[0];
919
						list($cursp['src'], $cursp['dst']) = explode("-", $upperspec[2]);
920
						$cursp['unique'] = substr($upperspec[3], strpos($upperspec[3], ":")+1);
921
						break;
922
					default:
923
						if (substr($linea[0], 0, 4) != 'spid') {
924
							break;
925
						}
926
						$cursp['scope'] = substr($linea[3], strpos($linea[3], "=")+1);
927
						if ($cursp['scope'] == 'ifnet') {
928
							$cursp['ifname'] = substr($linea[4], strpos($linea[4], "=")+1);
929
						}
930
						break;
931
				}
932
			}
933
			$i++;
934
		}
935
		if (is_array($cursp) && count($cursp)) {
936
			$spd[] = $cursp;
937
		}
938
		pclose($fd);
939
	}
940

    
941
	return $spd;
942
}
943

    
944
/*
945
 * Return dump of SAD table
946
 */
947
function ipsec_dump_sad() {
948
	$fd = @popen("/sbin/setkey -D", "r");
949
	$sad = array();
950
	if ($fd) {
951
		while (!feof($fd)) {
952
			$line = chop(fgets($fd));
953
			if (!$line || $line[0] == " ") {
954
				continue;
955
			}
956
			if ($line == "No SAD entries.") {
957
				break;
958
			}
959
			if ($line[0] != "\t") {
960
				if (is_array($cursa)) {
961
					$sad[] = $cursa;
962
				}
963
				$cursa = array();
964
				list($cursa['src'], $cursa['dst']) = explode(" ", $line);
965
			} else {
966
				$line = trim($line, "\t\n\r ");
967
				$linea = explode(" ", $line);
968
				foreach ($linea as $idx => $linee) {
969
					if ($linee == 'esp' || $linee == 'ah' || $linee[0] == '#') {
970
						$cursa['proto'] = $linee;
971
					} else if (substr($linee, 0, 3) == 'spi') {
972
						$cursa['spi'] = substr($linee, strpos($linee, 'x') + 1, -1);
973
					} else if (substr($linee, 0, 5) == 'reqid') {
974
						$cursa['reqid'] = substr($linee, strpos($linee, 'x') + 1, -1);
975
					} else if (substr($linee, 0, 2) == 'E:') {
976
						$cursa['ealgo'] = $linea[$idx + 1];
977
						break;
978
					} else if (substr($linee, 0, 2) == 'A:') {
979
						$cursa['aalgo'] = $linea[$idx + 1];
980
						break;
981
					} else if (substr($linee, 0, 8) == 'current:') {
982
						$cursa['data'] = substr($linea[$idx + 1], 0, strpos($linea[$idx + 1], 'bytes') - 1) . ' B';
983
						break;
984
					}
985
				}
986
			}
987
		}
988
		if (is_array($cursa) && count($cursa)) {
989
			$sad[] = $cursa;
990
		}
991
		pclose($fd);
992
	}
993

    
994
	return $sad;
995
}
996

    
997
/*
998
 * Return dump of mobile user list
999
 */
1000
function ipsec_dump_mobile() {
1001
	global $g;
1002

    
1003
	if(!config_path_enabled('ipsec/client')) {
1004
		return array();
1005
	}
1006

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

    
1010
	if ($rc != 0) {
1011
		log_error(gettext("Unable to find IPsec daemon leases file. Could not display mobile user stats!"));
1012
		return array();
1013
	}
1014

    
1015
	$response = array(
1016
		'pool' => array(),
1017
	);
1018

    
1019
	/* swanctl --list-pools --leases example output, field names can be confirmed by
1020
	 * looking at --raw or --pretty output. */
1021
	/* mobile-pool          10.7.200.0                          0 / 1 / 254 */
1022
	$pool_regex='/^(?P<name>\S+)\s+(?P<base>\S+)\s+(?P<online>\d+) \/ (?P<offline>\d+) \/ (?P<size>\d+)/';
1023
	/*   10.7.200.1                     online   'jimp' */
1024
	$lease_regex='/\s*(?P<host>[\d\.]+)\s+(?P<status>online|offline)\s+\'(?P<id>.*)\'/';
1025
	foreach ($output as $line) {
1026
		if (preg_match($pool_regex, $line, $matches)) {
1027
			$id++;
1028
			$response['pool'][$id] = array(
1029
			    'name'   => $matches['name'],
1030
			    'base'   => $matches['base'],
1031
			    'online' => $matches['online'],
1032
			    'offline'  => $matches['offline'],
1033
			    'size'   => $matches['size'],
1034
			);
1035
		} elseif (preg_match($lease_regex, $line, $matches)) {
1036
			$response['pool'][$id]['lease'][] = array(
1037
			    'host'   => $matches['host'],
1038
			    'status' => $matches['status'],
1039
			    'id'     => $matches['id']
1040
			);
1041
		}
1042
	}
1043

    
1044
	unset($_gb, $output, $rc, $pool_regex);
1045

    
1046
	return $response;
1047
}
1048

    
1049
function ipsec_mobilekey_sort() {
1050
	function mobilekeycmp($a, $b) {
1051
		return strcmp($a['ident'][0], $b['ident'][0]);
1052
	}
1053

    
1054
	$mobilekey_config = config_get_path('ipsec/mobilekey', []);
1055
	usort($mobilekey_config, "mobilekeycmp");
1056
	config_set_path('ipsec/mobilekey', $mobilekey_config);
1057
}
1058

    
1059
function ipsec_fixup_ip($ipaddr) {
1060
	if (is_ipaddrv6($ipaddr) || is_subnetv6($ipaddr)) {
1061
		return text_to_compressed_ip6($ipaddr);
1062
	} else {
1063
		return $ipaddr;
1064
	}
1065
}
1066

    
1067
function ipsec_find_id(& $ph1ent, $side = "local", $rgmap = array()) {
1068
	if ($side == "local") {
1069
		$id_type = $ph1ent['myid_type'];
1070
		$id_data = $ph1ent['myid_data'];
1071

    
1072
		$addr = ipsec_get_phase1_src($ph1ent);
1073
		if (!$addr) {
1074
			return array();
1075
		}
1076
		/* When automatically guessing, use the first address. */
1077
		$addr = explode(',', $addr);
1078
		$addr = $addr[0];
1079
	} elseif ($side == "peer") {
1080
		$id_type = $ph1ent['peerid_type'];
1081
		$id_data = $ph1ent['peerid_data'];
1082

    
1083
		if (isset($ph1ent['mobile'])) {
1084
			$addr = "%any";
1085
		} else {
1086
			$addr = $ph1ent['remote-gateway'];
1087
		}
1088
	} else {
1089
		return array();
1090
	}
1091

    
1092
	$thisid_type = $id_type;
1093
	switch ($thisid_type) {
1094
		case 'myaddress':
1095
			$thisid_type = 'address';
1096
			$thisid_data = $addr;
1097
			break;
1098
		case 'dyn_dns':
1099
			$thisid_type = 'dns';
1100
			$thisid_data = $id_data;
1101
			break;
1102
		case 'peeraddress':
1103
			$thisid_type = 'address';
1104
			$thisid_data = $rgmap[$ph1ent['remote-gateway']];
1105
			break;
1106
		case 'keyid tag':
1107
			$thisid_type = 'keyid';
1108
			$thisid_data = $id_data;
1109
			break;
1110
		case 'user_fqdn':
1111
			$thisid_type = 'userfqdn';
1112
			$thisid_data = $id_data;
1113
			break;
1114
		case 'any':
1115
			$thisid_data = '%any';
1116
			break;
1117
		case 'address':
1118
		case 'fqdn':
1119
		case 'asn1dn':
1120
		case 'auto':
1121
			$thisid_data = $id_data;
1122
			break;
1123
		default:
1124
			break;
1125
	}
1126
	return array($thisid_type, $thisid_data);
1127
}
1128

    
1129
/*
1130
 * Fixup ID type/data to include prefix when necessary, add quotes, etc.
1131
 */
1132
function ipsec_fixup_id($type, $data) {
1133
	/* List of types to pass through as-is without changes or adding prefix */
1134
	$auto_types = array('address', 'auto');
1135
	/* List of types which need the resulting string double quoted. */
1136
	$quote_types = array('keyid', 'asn1dn', 'auto');
1137

    
1138
	/* If the first character of asn1dn type data is not #, then rely on
1139
	 * automatic parsing https://redmine.pfsense.org/issues/4792 */
1140
	if (($type == 'asn1dn') && !empty($data) && ($data[0] != '#')) {
1141
		$auto_types[] = 'asn1dn';
1142
	}
1143

    
1144
	if ($type == 'any') {
1145
		$idstring = "%any";
1146
	} elseif (!in_array($type, $auto_types)) {
1147
		$idstring = "{$type}:{$data}";
1148
	} else {
1149
		$idstring = $data;
1150
	}
1151

    
1152
	if (in_array($type, $quote_types)) {
1153
		$idstring = "\"{$idstring}\"";
1154
	}
1155

    
1156
	return $idstring;
1157
}
1158

    
1159
function ipsec_fixup_network($network) {
1160
	if (substr($network, -3) == '|/0') {
1161
		$result = substr($network, 0, -3);
1162
	} else {
1163
		$tmp = explode('|', $network);
1164
		if (isset($tmp[1])) {
1165
			$result = $tmp[1];
1166
		} else {
1167
			$result = $tmp[0];
1168
		}
1169
		unset($tmp);
1170
	}
1171

    
1172
	return $result;
1173
}
1174

    
1175
function ipsec_get_loglevels() {
1176
	global $ipsec_log_cats;
1177
	$def_loglevel = '1';
1178

    
1179
	$levels = array();
1180

    
1181
	foreach (array_keys($ipsec_log_cats) as $cat) {
1182
		if (strlen(config_get_path('ipsec/logging/' . $cat, '')) > 0) {
1183
			$levels[$cat] = config_get_path('ipsec/logging/' . $cat);
1184
		} elseif (in_array($cat, array('ike', 'chd', 'cfg'))) {
1185
			$levels[$cat] = "2";
1186
		} else {
1187
			$levels[$cat] = $def_loglevel;
1188
		}
1189
	}
1190
	return $levels;
1191
}
1192

    
1193
function ipsec_vti($p1, $returnaddresses = false, $skipdisabled = true) {
1194
	$is_vti = false;
1195
	$vtisubnet_spec = array();
1196

    
1197
	foreach(ipsec_get_phase2_by_ikeid($p1['ikeid']) as $p2) {
1198
		if ($p2['mode'] == 'vti') {
1199
			if ($skipdisabled && isset($p2['disabled'])) {
1200
				continue;
1201
			} else {
1202
				$is_vti = true;
1203
			}
1204
			if ($returnaddresses) {
1205
				$vtisubnet_spec[] = array(
1206
					'left' => ipsec_idinfo_to_cidr($p2['localid'], true, $p2['mode']),
1207
					'right' => ipsec_idinfo_to_cidr($p2['remoteid'], false, $p2['mode']),
1208
					'descr' => $p2['descr'],
1209
					'reqid' => $p2['reqid'],
1210
				);
1211
			}
1212
		}
1213
	}
1214
	return ($returnaddresses) ? $vtisubnet_spec : $is_vti;
1215
}
1216

    
1217
/* Called when IPsec is reloaded through rc.newipsecdns and similar, gives
1218
 * packages an opportunity to execute custom code when IPsec reloads.
1219
 */
1220
function ipsec_reload_package_hook() {
1221
	global $g;
1222

    
1223
	foreach (config_get_path('installedpackages/package', []) as $package) {
1224
		if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
1225
			continue;
1226
		}
1227

    
1228
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], 'packagegui');
1229
		if (!empty($pkg_config['include_file']) &&
1230
		    file_exists($pkg_config['include_file'])) {
1231
			require_once($pkg_config['include_file']);
1232
		}
1233
		if (empty($pkg_config['ipsec_reload_function'])) {
1234
			continue;
1235
		}
1236
		$pkg_ipsec_reload = $pkg_config['ipsec_reload_function'];
1237
		if (!function_exists($pkg_ipsec_reload)) {
1238
			continue;
1239
		}
1240
		$pkg_ipsec_reload();
1241
	}
1242
}
1243

    
1244
/****f* certs/ipsec_convert_to_modp
1245
 * NAME
1246
 *   ipsec_convert_to_modp - Take a DH Group number value and return the
1247
 *                           associated name
1248
 * INPUTS
1249
 *   $index: DH group index number to look up
1250
 * RESULT
1251
 *   Returns the Diffie Hellman Group keyword associated with the group number.
1252
 ******/
1253
function ipsec_convert_to_modp($index) {
1254
	$modpmap = array(
1255
		'1' => 'modp768',
1256
		'2' => 'modp1024',
1257
		'5' => 'modp1536',
1258
		'14' => 'modp2048',
1259
		'15' => 'modp3072',
1260
		'16' => 'modp4096',
1261
		'17' => 'modp6144',
1262
		'18' => 'modp8192',
1263
		'19' => 'ecp256',
1264
		'20' => 'ecp384',
1265
		'21' => 'ecp521',
1266
		'22' => 'modp1024s160',
1267
		'23' => 'modp2048s224',
1268
		'24' => 'modp2048s256',
1269
		'25' => 'ecp192',
1270
		'26' => 'ecp224',
1271
		'27' => 'ecp224bp',
1272
		'28' => 'ecp256bp',
1273
		'29' => 'ecp384bp',
1274
		'30' => 'ecp512bp',
1275
		'31' => 'curve25519',
1276
		'32' => 'curve448',
1277
	);
1278

    
1279
	return $modpmap[$index];
1280
}
1281

    
1282
/*
1283
 * Forcefully restart IPsec
1284
 * This is required for when dynamic interfaces reload
1285
 * For all other occasions the normal ipsec_configure()
1286
 * will gracefully reload the settings without restarting
1287
 */
1288
function ipsec_force_reload($interface = "", $protocol = "") {
1289
	global $g;
1290

    
1291
	if (!ipsec_enabled()) {
1292
		return;
1293
	}
1294

    
1295
	$ipseccfg = config_get_path('ipsec');
1296

    
1297
	if (!empty($interface) && is_array($ipseccfg['phase1'])) {
1298
		$found = false;
1299
		$realif = array();
1300
		$ifcache = array();
1301
		foreach ($ipseccfg['phase1'] as $ipsec) {
1302
			if (isset($ipsec['disabled'])) {
1303
				continue;
1304
			}
1305
			if (!empty($protocol) &&
1306
			    ($ipsec['protocol'] != $protocol) &&
1307
			    ($ipsec['protocol'] != 'both')) {
1308
				continue;
1309
			}
1310
			if ($ipsec['interface'] == $interface) {
1311
				$found = true;
1312
				break;
1313
			} else {
1314
				$fam = (!empty($ipsec['protocol'])) ? $ipsec['protocol'] : 'inet';
1315

    
1316
				/* Find the real active passed interface for this address family, cache the result */
1317
				if (empty($realif) ||
1318
				    empty($realif[$fam])) {
1319
					$realif[$fam] = get_failover_interface($interface, $fam);
1320
				}
1321

    
1322
				/* Find the real active tunnel interface for this address family, cache the result */
1323
				if (empty($ifcache) ||
1324
				    empty($ifcache[$ipsec['interface']]) ||
1325
				    empty($ifcache[$ipsec['interface']][$fam])) {
1326
					if (!is_array($ifcache[$ipsec['interface']])) {
1327
						$ifcache[$ipsec['interface']] = array();
1328
					}
1329
					$ifcache[$ipsec['interface']][$fam] = get_failover_interface($ipsec['interface'], $fam);
1330
				}
1331

    
1332
				if ($realif[$fam] == $ifcache[$ipsec['interface']][$fam]) {
1333
					$found = true;
1334
					break;
1335
				}
1336
			}
1337
		}
1338
		if (!$found) {
1339
			log_error(sprintf(gettext("Ignoring IPsec reload since there are no tunnels on interface %s"), $interface));
1340
			return;
1341
		}
1342
	}
1343

    
1344
	/* If we get this far then we need to take action. */
1345
	log_error(gettext("Forcefully reloading IPsec"));
1346
	ipsec_configure();
1347
}
1348

    
1349
/****f* ipsec/ipsec_strongswan_confgen
1350
 * NAME
1351
 *   ipsec_strongswan_confgen - Generate strongswan.conf style formatted output
1352
 *                              From a multi-dimensional array.
1353
 * INPUTS
1354
 *   $confarr: An array of key=value pairs or key=array entries for subsections.
1355
 *   $indent : A string of tabs used when indenting lines.
1356
 * RESULT
1357
 *   Returns a string of key=value pairs with proper indenting, and with named
1358
 *   subsections enclosed in braces.
1359
 * NOTES
1360
 *   Values starting with a "#" (comments) or "include " will be printed
1361
 *   directly without their associated key name.
1362
 ******/
1363
function ipsec_strongswan_confgen($confarr, $indent = "") {
1364
	$confstr = "";
1365
	/* Only process the contents if it's an array. */
1366
	if (is_array($confarr)) {
1367
		foreach ($confarr as $key => $value) {
1368
			if (is_array($value)) {
1369
				/* If the array is empty, do not print anything */
1370
				if (empty($value)) {
1371
					continue;
1372
				}
1373
				/* If this is an array, setup the subsection name
1374
				 * and structure, then call this function
1375
				 * recursively to walk the lower array. */
1376
				$confstr .= "{$indent}{$key} {\n";
1377
				$confstr .= ipsec_strongswan_confgen($value, $indent . "\t");
1378
				$confstr .= "{$indent}}\n";
1379
			} else {
1380
				$confstr .= "{$indent}";
1381
				if ((substr($value, 0 , 1) != '#') &&
1382
				    (substr($value, 0 , 8) != 'include ')) {
1383
					/* Not a comment or include, print the key */
1384
					$confstr .= "{$key} = ";
1385
				}
1386
				$confstr .= "{$value}\n";
1387
			}
1388
		}
1389
	}
1390
	return $confstr;
1391
}
1392

    
1393
global $g, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs;
1394
$ipsec_swanctl_basedir = "{$g['varetc_path']}/ipsec";
1395
$ipsec_swanctl_dirs = array(
1396
	'conf'     => "{$ipsec_swanctl_basedir}/conf.d",
1397
	'certpath' => "{$ipsec_swanctl_basedir}/x509",
1398
	'capath'   => "{$ipsec_swanctl_basedir}/x509ca",
1399
	'aapath'   => "{$ipsec_swanctl_basedir}/x509aa",
1400
	'ocsppath' => "{$ipsec_swanctl_basedir}/x509ocsp",
1401
	'crlpath'  => "{$ipsec_swanctl_basedir}/x509crl",
1402
	'acpath'   => "{$ipsec_swanctl_basedir}/x509ac",
1403
	'rsakeys'  => "{$ipsec_swanctl_basedir}/rsa",
1404
	'eckeys'   => "{$ipsec_swanctl_basedir}/ecdsa",
1405
	'keypath'  => "{$ipsec_swanctl_basedir}/private",
1406
	'pubkpath' => "{$ipsec_swanctl_basedir}/pubkey",
1407
	'blisspath' => "{$ipsec_swanctl_basedir}/bliss",
1408
	'pkcs8path' => "{$ipsec_swanctl_basedir}/pkcs8",
1409
	'pkcs12path' => "{$ipsec_swanctl_basedir}/pkcs12",
1410
);
1411

    
1412
/****f* ipsec/ipsec_create_dirs
1413
 * NAME
1414
 *   ipsec_create_dirs - Create default set of strongSwan configuration directories.
1415
 * INPUTS
1416
 *   None
1417
 * RESULT
1418
 *   Cleans up and creates strongSwan configuration directories and links.
1419
 ******/
1420
function ipsec_create_dirs() {
1421
	global $g, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs;
1422

    
1423
	/* Cleanup base paths to ensure old files are not left behind (#5238) */
1424
	if (!empty($ipsec_swanctl_basedir)) {
1425
		@rmdir_recursive($ipsec_swanctl_basedir, false);
1426
	}
1427
	/* Create directory structure */
1428
	array_map('safe_mkdir', array_values($ipsec_swanctl_dirs));
1429

    
1430
	/* Create and link strongSwan config */
1431
	$ssdpath = "{$g['varetc_path']}/ipsec/strongswan.d";
1432
	if (!file_exists($ssdpath) || !is_link($ssdpath)) {
1433
		if (is_dir($ssdpath) && !is_link($ssdpath)) {
1434
			@rmdir_recursive($ssdpath, false);
1435
		} else {
1436
			@unlink($ssdpath);
1437
		}
1438
		@symlink("/usr/local/etc/strongswan.d",
1439
		    $ssdpath);
1440
	}
1441
	if (!file_exists("/usr/local/etc/strongswan.conf") ||
1442
	    !is_link("/usr/local/etc/strongswan.conf")) {
1443
		@unlink("/usr/local/etc/strongswan.conf");
1444
		@symlink("{$g['varetc_path']}/ipsec/strongswan.conf",
1445
		    "/usr/local/etc/strongswan.conf");
1446
	}
1447
}
1448

    
1449
/****f* ipsec/ipsec_setup_gwifs
1450
 * NAME
1451
 *   ipsec_setup_gwifs - Setup IPsec-related interfaces and gateways
1452
 * INPUTS
1453
 *   None
1454
 * RESULT
1455
 *   Sets up VTI interfaces and gateways, populates ipsecpinghosts
1456
 ******/
1457
function ipsec_setup_gwifs() {
1458
	global $g, $rgmap, $filterdns_list,
1459
		$aggressive_mode_psk, $mobile_ipsec_auth, $ifacesuse,
1460
		$ipsecpinghostsactive;
1461
	/* resolve all local, peer addresses and setup pings */
1462

    
1463
	unset($iflist);
1464
	$ipsecpinghosts = array();
1465
	/* step through each phase1 entry */
1466
	foreach (config_get_path('ipsec/phase1', []) as $ph1ent) {
1467
		if (isset($ph1ent['disabled'])) {
1468
			continue;
1469
		}
1470
		if (substr($ph1ent['interface'], 0, 4) == "_vip") {
1471
			$vpninterface = get_configured_vip_interface($ph1ent['interface']);
1472
			$ifacesuse[] = get_real_interface($vpninterface);
1473
		} else {
1474
			$vpninterface = get_failover_interface($ph1ent['interface'], 'all');
1475
			if (substr($vpninterface, 0, 4) == "_vip") {
1476
				$vpninterface = get_configured_vip_interface($vpninterface);
1477
				$ifacesuse[] = get_real_interface($vpninterface);
1478
			} elseif (!empty($vpninterface)) {
1479
				$ifacesuse[] = $vpninterface;
1480
			}
1481
		}
1482
		if ($ph1ent['mode'] == "aggressive" && ($ph1ent['authentication_method'] == "pre_shared_key" || $ph1ent['authentication_method'] == "xauth_psk_server")) {
1483
			$aggressive_mode_psk = true;
1484
		}
1485

    
1486
		$ikeid = $ph1ent['ikeid'];
1487

    
1488
		$local_spec = ipsec_get_phase1_src($ph1ent);
1489
		/* When automatically guessing, use the first address. */
1490
		$local_spec  = explode(',', $local_spec);
1491
		$local_spec  = $local_spec[0];
1492
		if (!is_ipaddr($local_spec)) {
1493
			log_error(sprintf(gettext("IPsec ERROR: Could not find phase 1 source for connection %s. Omitting from configuration file."), $ph1ent['descr']));
1494
			continue;
1495
		}
1496

    
1497
		if (isset($ph1ent['mobile'])) {
1498
			$mobile_ipsec_auth = $ph1ent['authentication_method'];
1499
			continue;
1500
		}
1501

    
1502
		/* see if this tunnel has a hostname for the remote-gateway. If so,
1503
		   try to resolve it now and add it to the list for filterdns */
1504
		$rg = $ph1ent['remote-gateway'];
1505
		if (!is_ipaddr($rg)) {
1506
			$filterdns_list[] = "{$rg}";
1507
			if (!is_platform_booting()) {
1508
				$rg = resolve_retry($rg, $ph1ent['protocol']);
1509
			}
1510
			if (!is_ipaddr($rg)) {
1511
				continue;
1512
			}
1513
		}
1514
		if (!isset($ph1ent['gw_duplicates']) && array_search($rg, $rgmap)) {
1515
			log_error(sprintf(gettext("The remote gateway %s already exists on another phase 1 entry"), $rg));
1516
			continue;
1517
		}
1518
		$rgmap[$ph1ent['remote-gateway']] = $rg;
1519

    
1520
		$is_vti = false;
1521
		/* step through each phase2 entry */
1522
		foreach (config_get_path('ipsec/phase2', []) as $ph2ent) {
1523
			if ($ph2ent['ikeid'] != $ph1ent['ikeid']) {
1524
				continue;
1525
			}
1526
			if ($ph2ent['mode'] == 'vti') {
1527
				$is_vti = true;
1528
			}
1529
			if (isset($ph2ent['disabled']) || ($ikeid != $ph2ent['ikeid'])) {
1530
				continue;
1531
			}
1532

    
1533
			/* add an ipsec pinghosts entry */
1534
			if ($ph2ent['pinghost']) {
1535
				if (!is_array($iflist)) {
1536
					$iflist = get_configured_interface_list();
1537
				}
1538
				$srcip = null;
1539
				$local_subnet = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
1540
				if (is_ipaddrv6($ph2ent['pinghost'])) {
1541
					foreach ($iflist as $ifent => $ifname) {
1542
						$interface_ip = get_interface_ipv6($ifent);
1543
						if (!is_ipaddrv6($interface_ip)) {
1544
							continue;
1545
						}
1546
						if (ip_in_subnet($interface_ip, $local_subnet)) {
1547
							$srcip = $interface_ip;
1548
							break;
1549
						}
1550
					}
1551
				} else {
1552
					foreach ($iflist as $ifent => $ifname) {
1553
						$interface_ip = get_interface_ip($ifent);
1554
						if (!is_ipaddrv4($interface_ip)) {
1555
							continue;
1556
						}
1557
						if ($local_subnet == "0.0.0.0/0" || ip_in_subnet($interface_ip, $local_subnet)) {
1558
							$srcip = $interface_ip;
1559
							break;
1560
						}
1561
					}
1562
				}
1563
				/* if no valid src IP was found in configured interfaces, try the vips */
1564
				if (is_null($srcip)) {
1565
					$viplist = get_configured_vip_list();
1566
					foreach ($viplist as $vip => $address) {
1567
						if (ip_in_subnet($address, $local_subnet)) {
1568
							$srcip = $address;
1569
							break;
1570
						}
1571
					}
1572
				}
1573
				$dstip = $ph2ent['pinghost'];
1574
				$family = "inet" . (is_ipaddrv6($dstip)) ? "6" : "";
1575
				if (is_ipaddr($srcip)) {
1576
					$ipsecpinghosts[] = "{$srcip}|{$dstip}|3|||||{$family}|\n";
1577
					$ipsecpinghostsactive = true;
1578
				}
1579
			}
1580
		}
1581
		if ($is_vti) {
1582
			interface_ipsec_vti_configure($ph1ent);
1583
		}
1584
	}
1585
	@file_put_contents("{$g['vardb_path']}/ipsecpinghosts", $ipsecpinghosts);
1586
	unset($ipsecpinghosts);
1587
	unset($iflist);
1588
}
1589

    
1590
/****f* ipsec/ipsec_logging_config
1591
 * NAME
1592
 *   ipsec_logging_config - Generate an array containing strongSwan logging
1593
 *                          values.
1594
 * INPUTS
1595
 *   None
1596
 * RESULT
1597
 *   Returns an array which can be merged into the strongswan daemon logging
1598
 *   values so that each logging category is represented, even those not listed
1599
 *   in config.xml.
1600
 ******/
1601
function ipsec_logging_config() {
1602
	global $ipsec_log_cats, $ipsec_log_sevs;
1603
	$logcfg = array();
1604
	$log_levels = ipsec_get_loglevels();
1605
	foreach (array_keys($ipsec_log_cats) as $cat) {
1606
		if (is_numeric($log_levels[$cat]) &&
1607
		    in_array(intval($log_levels[$cat]), array_keys($ipsec_log_sevs), true)) {
1608
			$logcfg[$cat] = $log_levels[$cat];
1609
		}
1610
	}
1611
	return $logcfg;
1612
}
1613

    
1614
/****f* ipsec/ipsec_setup_strongswan
1615
 * NAME
1616
 *   ipsec_setup_strongswan - Generate the strongswan.conf configuration file.
1617
 * INPUTS
1618
 *   None
1619
 * RESULT
1620
 *   Determines strongswan.conf values and crafts the configuration file in the
1621
 *   appropriate format.
1622
 * NOTES
1623
 *   Called from ipsec_configure()
1624
 ******/
1625
function ipsec_setup_strongswan() {
1626
	global $g, $mobile_ipsec_auth, $aggressive_mode_psk, $ifacesuse;
1627

    
1628
	/* strongswan.conf array */
1629
	$ssconf = array();
1630
	$ssconf[] = "# Automatically generated config file - DO NOT MODIFY. Changes will be overwritten.";
1631
	$ssconf['starter'] = array();
1632
	$ssconf['starter']['load_warning'] = "no";
1633

    
1634
	$ssconf['charon'] = array();
1635
	$ssconf['charon'][] = '# number of worker threads in charon';
1636
	$ssconf['charon']['threads'] = '16';
1637
	$ssconf['charon']['ikesa_table_size'] = '32';
1638
	$ssconf['charon']['ikesa_table_segments'] = '4';
1639
	$ssconf['charon']['init_limit_half_open'] = '1000';
1640
	$ssconf['charon']['install_routes'] = 'no';
1641
	$ssconf['charon']['load_modular'] = 'yes';
1642
	$ssconf['charon']['ignore_acquire_ts'] = 'yes';
1643

    
1644
	if ($aggressive_mode_psk) {
1645
		$stronconf = '';
1646
		if (file_exists("{$g['varetc_path']}/ipsec/strongswan.conf")) {
1647
			$stronconf = file_get_contents("{$g['varetc_path']}/ipsec/strongswan.conf");
1648
		}
1649
		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.");
1650
		$restart = (!empty($stronconf) && strpos($stronconf, 'i_dont_care_about_security_and_use_aggressive_mode_psk') === FALSE);
1651
		unset($stronconf);
1652
		$ssconf['charon']['i_dont_care_about_security_and_use_aggressive_mode_psk'] = "yes";
1653
	}
1654

    
1655
	if (config_path_enabled('ipsec', 'acceptunencryptedmainmode')) {
1656
		$ssconf['charon']['accept_unencrypted_mainmode_messages'] = "yes";
1657
	}
1658

    
1659
	if (!empty(config_get_path('ipsec/maxexchange'))) {
1660
		$ssconf['charon']['max_ikev1_exchanges'] = config_get_path('ipsec/maxexchange');
1661
	}
1662

    
1663
	$unity_enabled = config_path_enabled('ipsec', 'unityplugin') ? 'yes' : 'no';
1664
	$ssconf['charon']['cisco_unity'] = $unity_enabled;
1665

    
1666
	if (config_path_enabled('ipsec', 'enableinterfacesuse') && !empty($ifacesuse)) {
1667
		$ssconf['charon']['interfaces_use'] = implode(',', array_unique($ifacesuse));
1668
	}
1669

    
1670
	if (config_path_enabled('ipsec', 'makebeforebreak')) {
1671
		$ssconf['charon']['make_before_break'] = "yes";
1672
	}
1673

    
1674
	if (!empty(config_get_path('ipsec/port'))) {
1675
		$ssconf['charon']['port'] = config_get_path('ipsec/port');
1676
	}
1677

    
1678
	if (!empty(config_get_path('ipsec/port_nat_t'))) {
1679
		$ssconf['charon']['port_nat_t'] = config_get_path('ipsec/port_nat_t');
1680
	}
1681

    
1682
	/* IKEv2 retransmit options, see https://redmine.pfsense.org/issues/12184 */
1683
	if (!empty(config_get_path('ipsec/ikev2_retransmit_tries'))) {
1684
		$ssconf['charon']['retransmit_tries'] = config_get_path('ipsec/ikev2_retransmit_tries');
1685
	}
1686
	if (!empty(config_get_path('ipsec/ikev2_retransmit_timeout'))) {
1687
		$ssconf['charon']['retransmit_timeout'] = config_get_path('ipsec/ikev2_retransmit_timeout');
1688
	}
1689
	if (!empty(config_get_path('ipsec/ikev2_retransmit_base'))) {
1690
		$ssconf['charon']['retransmit_base'] = config_get_path('ipsec/ikev2_retransmit_base');
1691
	}
1692
	if (!empty(config_get_path('ipsec/ikev2_retransmit_jitter'))) {
1693
		$ssconf['charon']['retransmit_jitter'] = config_get_path('ipsec/ikev2_retransmit_jitter');
1694
	}
1695
	if (!empty(config_get_path('ipsec/ikev2_retransmit_limit'))) {
1696
		$ssconf['charon']['retransmit_limit'] = config_get_path('ipsec/ikev2_retransmit_limit');
1697
	}
1698

    
1699
	$ssconf['charon']['syslog'] = array();
1700
	$ssconf['charon']['syslog']['identifier'] = 'charon';
1701
	$ssconf['charon']['syslog'][] = "# log everything under daemon since it ends up in the same place regardless with our syslog.conf";
1702
	$ssconf['charon']['syslog']['daemon'] = array();
1703
	$ssconf['charon']['syslog']['daemon']['ike_name'] = 'yes';
1704
	$ssconf['charon']['syslog']['daemon'] = array_merge($ssconf['charon']['syslog']['daemon'], ipsec_logging_config());
1705
	$ssconf['charon']['syslog'][] = '# disable logging under auth so logs aren\'t duplicated';
1706
	$ssconf['charon']['syslog']['auth'] = array();
1707
	$ssconf['charon']['syslog']['auth']['default'] = -1;
1708

    
1709
	$ssconf['charon']['plugins'] = array();
1710
	$ssconf['charon']['plugins'][] = "# Load defaults";
1711
	$ssconf['charon']['plugins'][] = "include {$g['varetc_path']}/ipsec/strongswan.d/charon/*.conf";
1712
	$ssconf['charon']['plugins']['unity'] = array('load' => $unity_enabled);
1713
	$ssconf['charon']['plugins']['curve25519'] = array('load' => "yes");
1714

    
1715
	if (config_path_enabled('ipsec', 'pkcs11support')) {
1716
		$ssconf['charon']['plugins']['pkcs11'] = array();
1717
		$ssconf['charon']['plugins']['pkcs11']['load'] = "yes";
1718
		$ssconf['charon']['plugins']['pkcs11']['modules'] = array();
1719
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc'] = array();
1720
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc']['load_certs'] = "yes";
1721
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc']['path'] = "/usr/local/lib/opensc-pkcs11.so";
1722
	}
1723

    
1724
	/* Find RADIUS servers designated for Mobile IPsec user auth */
1725
	$radius_servers = array();
1726
	foreach (explode(',', config_get_path('ipsec/client/user_source', '')) as $user_source) {
1727
		$auth_server = auth_get_authserver($user_source);
1728
		$nice_user_source = strtolower(preg_replace('/[\s\.]+/', '_', $user_source));
1729
		if ($auth_server && ($auth_server['type'] === 'radius')) {
1730
			$radius_servers[$nice_user_source] = array();
1731
			$radius_servers[$nice_user_source]['address'] = $auth_server['host'];
1732
			$radius_servers[$nice_user_source]['secret'] = "\"{$auth_server['radius_secret']}\"";
1733
			$radius_servers[$nice_user_source]['auth_port'] = empty($auth_server['radius_auth_port']) ? 1812 : $auth_server['radius_auth_port'];;
1734
			$radius_servers[$nice_user_source]['acct_port'] = empty($auth_server['radius_acct_port']) ? 1813 : $auth_server['radius_acct_port'];
1735
		}
1736
	}
1737

    
1738
	/* Generate an eap-radius config section if appropriate */
1739
	if (count($radius_servers) && ($mobile_ipsec_auth === "eap-radius")) {
1740
		$ssconf['charon']['plugins']['eap-radius'] = array();
1741
		$ssconf['charon']['plugins']['eap-radius']['load'] = "2";
1742
		$ssconf['charon']['plugins']['eap-radius']['class_group'] = "yes";
1743
		$ssconf['charon']['plugins']['eap-radius']['eap_start'] = "no";
1744
		/* Activate RADIUS accounting only if it was selected on the IPsec Mobile Clients tab */
1745
		if ($auth_server && isset($auth_server['radius_acct_port']) &&
1746
		    (config_get_path('ipsec/client/radiusaccounting') == 'enabled')) {
1747
			$ssconf['charon']['plugins']['eap-radius']['accounting'] = "yes";
1748
			$ssconf['charon']['plugins']['eap-radius']['accounting_close_on_timeout'] = "no";
1749
			$ssconf['charon']['plugins']['eap-radius']['accounting_requires_vip'] = "yes";
1750
		}
1751
		/* advanced parameters, see https://redmine.pfsense.org/issues/11211 */
1752
		if (config_get_path('ipsec/client/radius_retransmit_base')) {
1753
			$ssconf['charon']['plugins']['eap-radius']['retransmit_base'] = config_get_path('ipsec/client/radius_retransmit_base');
1754
		}
1755
		if (config_get_path('ipsec/client/radius_retransmit_timeout')) {
1756
			$ssconf['charon']['plugins']['eap-radius']['retransmit_timeout'] = config_get_path('ipsec/client/radius_retransmit_timeout');
1757
		}
1758
		if (config_get_path('ipsec/client/radius_retransmit_tries')) {
1759
			$ssconf['charon']['plugins']['eap-radius']['retransmit_tries'] = config_get_path('ipsec/client/radius_retransmit_tries');
1760
		}
1761
		if (config_get_path('ipsec/client/radius_sockets')) {
1762
			$ssconf['charon']['plugins']['eap-radius']['sockets'] = config_get_path('ipsec/client/radius_sockets');
1763
		}
1764
		$ssconf['charon']['plugins']['eap-radius']['servers'] = $radius_servers;
1765
	}
1766

    
1767
	if (config_path_enabled('ipsec/client')) {
1768
		if (config_get_path('ipsec/client/user_source') != "none") {
1769
			$ssconf['charon']['plugins']['xauth-generic'] = array();
1770
			$ssconf['charon']['plugins']['xauth-generic']['script'] = "/etc/inc/ipsec.auth-user.php";
1771
			$authcfgs = array();
1772
			foreach (array_filter(explode(",", config_get_path('ipsec/client/user_source'))) as $authcfg) {
1773
				$authcfgs[] = ($authcfg == "system") ? "Local Database" : $authcfg;
1774
			}
1775
			$ssconf['charon']['plugins']['xauth-generic']['authcfg'] = implode(",", $authcfgs);
1776
		}
1777

    
1778
		$ssconf['charon']['plugins']['attr'] = array();
1779

    
1780
		$rightdnsservers = array();
1781
		if (!empty(config_get_path('ipsec/client/dns_server1'))) {
1782
			$rightdnsservers[] = config_get_path('ipsec/client/dns_server1');
1783
		}
1784
		if (!empty(config_get_path('ipsec/client/dns_server2'))) {
1785
			$rightdnsservers[] = config_get_path('ipsec/client/dns_server2');
1786
		}
1787
		if (!empty(config_get_path('ipsec/client/dns_server3'))) {
1788
			$rightdnsservers[] = config_get_path('ipsec/client/dns_server3');
1789
		}
1790
		if (!empty(config_get_path('ipsec/client/dns_server4'))) {
1791
			$rightdnsservers[] = config_get_path('ipsec/client/dns_server4');
1792
		}
1793
		if (count($rightdnsservers)) {
1794
			$ssconf['charon']['plugins']['attr']['dns'] = implode(',', $rightdnsservers);
1795
		}
1796

    
1797
		$cfgservers = array();
1798
		if (!empty(config_get_path('ipsec/client/wins_server1'))) {
1799
			$cfgservers[] = config_get_path('ipsec/client/wins_server1');
1800
		}
1801
		if (!empty(config_get_path('ipsec/client/wins_server2'))) {
1802
			$cfgservers[] = config_get_path('ipsec/client/wins_server2');
1803
		}
1804
		if (!empty($cfgservers)) {
1805
			$ssconf['charon']['plugins']['attr']['nbns'] = implode(',', $cfgservers);
1806
		}
1807
		unset($cfgservers);
1808

    
1809
		$net_list = array();
1810
		if (config_path_enabled('ipsec/client', 'net_list')) {
1811
			foreach (config_get_path('ipsec/phase2', []) as $ph2ent) {
1812
				if (isset($ph2ent['disabled']) ||
1813
				    !isset($ph2ent['mobile'])) {
1814
					continue;
1815
				}
1816
				$nlent = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
1817
				if (is_subnet($nlent)) {
1818
					$net_list[] = $nlent;
1819
				}
1820
				unset($nlent);
1821
			}
1822
		}
1823

    
1824
		if (!empty($net_list)) {
1825
			$ssconf['charon']['plugins']['attr']['subnet'] = implode(',', $net_list);
1826
			$ssconf['charon']['plugins']['attr']['split-include'] = implode(',', $net_list);
1827
		}
1828

    
1829
		if (!empty(config_get_path('ipsec/client/dns_domain'))) {
1830
			$ssconf['charon']['plugins']['attr'][] = "# Search domain and default domain";
1831
			$ssconf['charon']['plugins']['attr']['28674'] = config_get_path('ipsec/client/dns_domain');
1832
			if (!empty(config_get_path('ipsec/client/dns_split'))) {
1833
				$ssconf['charon']['plugins']['attr']['28675'] = config_get_path('ipsec/client/dns_domain');
1834
			}
1835
		}
1836

    
1837
		if (!empty(config_get_path('ipsec/client/dns_split'))) {
1838
			$ssconf['charon']['plugins']['attr'][] = "# Split DNS (UNITY_SPLITDNS_NAME)";
1839
			$ssconf['charon']['plugins']['attr']['28675'] = config_get_path('ipsec/client/dns_split');
1840
			$ssconf['charon']['plugins']['attr'][] = "# Split DNS (INTERNAL_DNS_DOMAIN, RFC 8598)";
1841
			$ssconf['charon']['plugins']['attr']['25'] = str_replace(' ', ',', config_get_path('ipsec/client/dns_split'));
1842
		}
1843

    
1844
		if (!empty(config_get_path('ipsec/client/login_banner'))) {
1845
			$ssconf['charon']['plugins']['attr'][] = "# Login Banner";
1846
			$ssconf['charon']['plugins']['attr']['28672'] = config_get_path('ipsec/client/login_banner');
1847
		}
1848

    
1849
		if (config_path_enabled('ipsec/client', 'save_passwd')) {
1850
			$ssconf['charon']['plugins']['attr'][] = "# Save Xauth Password";
1851
			$ssconf['charon']['plugins']['attr']['28673'] = "1";
1852
		}
1853

    
1854
		if (config_get_path('ipsec/client/pfs_group')) {
1855
			$ssconf['charon']['plugins']['attr'][] = "# Phase2 PFS Group";
1856
			$ssconf['charon']['plugins']['attr']['28679'] = config_get_path('ipsec/client/pfs_group');
1857
		}
1858
	}
1859

    
1860
	@file_put_contents("{$g['varetc_path']}/ipsec/strongswan.conf", ipsec_strongswan_confgen($ssconf));
1861
}
1862

    
1863
/****f* ipsec/ipsec_setup_pools
1864
 * NAME
1865
 *   ipsec_setup_pools - Generate primary mobile pool configuration for swanctl
1866
  * INPUTS
1867
 *   None
1868
 * RESULT
1869
 *   Adds configured mobile pool settings to $scconf
1870
 * NOTES
1871
 *   These values were formerly in strongswan.conf but may now be configured in
1872
 *   pools, making future expansion to support multiple pools possible.
1873
 ******/
1874
function ipsec_setup_pools() {
1875
	global $g, $mobile_ipsec_auth, $scconf;
1876
	if (!config_path_enabled('ipsec/client')) {
1877
		return;
1878
	}
1879
	if (($mobile_ipsec_auth == "eap-radius") && empty(config_get_path('ipsec/client/pool_address')) &&
1880
	    empty(config_get_path('ipsec/client/pool_address_v6'))) {
1881
		return;
1882
	}
1883

    
1884
	/* Keep the comment in the array to ensure the entry makes it into the
1885
	 * config in all cases.
1886
	 * See https://redmine.pfsense.org/issues/11891 */
1887
	$scconf['mobile-pool'] = array("# Mobile pool settings template");
1888
	$scconf['pools'] = array();
1889
	$pool_common =& $scconf['mobile-pool'];
1890

    
1891
	if (!empty(config_get_path('ipsec/client/pool_address'))) {
1892
		$scconf['pools']['mobile-pool-v4 : mobile-pool'] = array();
1893
		$v4pool =& $scconf['pools']['mobile-pool-v4 : mobile-pool'];
1894
		$v4pool['addrs'] = config_get_path('ipsec/client/pool_address') . '/' . config_get_path('ipsec/client/pool_netbits');
1895
	}
1896
	if (!empty(config_get_path('ipsec/client/pool_address_v6'))) {
1897
		$scconf['pools']['mobile-pool-v6 : mobile-pool'] = array();
1898
		$v6pool =& $scconf['pools']['mobile-pool-v6 : mobile-pool'];
1899
		$v6pool['addrs'] = config_get_path('ipsec/client/pool_address_v6') . '/' . config_get_path('ipsec/client/pool_netbits_v6');
1900
	}
1901

    
1902
	return;
1903
}
1904

    
1905
/****f* ipsec/ipsec_setup_userpools
1906
 * NAME
1907
 *   ipsec_setup_userpools - Generate per-user custom pool settings for swanctl
1908
  * INPUTS
1909
 *   None
1910
 * RESULT
1911
 *   Adds configured per-user pool settings to $scconf using the primary mobile
1912
 *   pool as a base configuration.
1913
 * NOTES
1914
 *   Given this new flexible format, it is now possible to override any valid
1915
 *   pool setting, so future expansion of per-user settings is possible.
1916
 ******/
1917
function ipsec_setup_userpools() {
1918
	global $scconf;
1919
	$a_mobilekey = config_get_path('ipsec/mobilekey');
1920

    
1921
	/* Do not waste time if we do not have all the necessary information. */
1922
	if (!is_array($a_mobilekey) ||
1923
	    empty($a_mobilekey) ||
1924
	    !is_array($scconf['connections']) ||
1925
	    !is_array($scconf['con-mobile-defaults']) ||
1926
	    !is_array($scconf['pools']) ||
1927
	    !is_array($scconf['mobile-pool'])) {
1928
		return;
1929
	}
1930

    
1931
	$suffix = 1;
1932
	foreach ($a_mobilekey as $mkent) {
1933
		if (($mkent['type'] != "EAP") ||
1934
		    !isset($mkent['ident_type']) ||
1935
		    !isset($mkent['pool_address']) ||
1936
		    !isset($mkent['pool_netbits']) ||
1937
		    (strlen($mkent['pool_address']) < 1) ||
1938
		    !is_ipaddr($mkent['pool_address'])) {
1939
			continue;
1940
		}
1941
		/* The name of just this pool */
1942
		$upbase = "mobile-userpool-{$suffix}";
1943
		/* The full connection name including a reference to the primary
1944
		 * mobile connection */
1945
		$upconn = "con-{$upbase} : con-mobile-defaults";
1946
		/* The full pool name including a reference to the primary
1947
		 * mobile pool */
1948
		$upname = "{$upbase} : mobile-pool";
1949

    
1950
		$scconf['connections'][$upconn] = array();
1951
		$scconf['pools'][$upname] = array();
1952

    
1953
		$clientid = (in_array($mkent['ident_type'], array('auto', 'none'))) ? "\"{$mkent['ident']}\"" : "{$mkent['ident_type']}:{$mkent['ident']}";
1954

    
1955
		/* Craft a cloned connection with the ID information to match */
1956
		$scconf['connections'][$upconn]['remote'] = array();
1957
		$scconf['connections'][$upconn]['remote']['id'] = $clientid;
1958
		$scconf['connections'][$upconn]['remote']['eap_id'] = '%any';
1959
		$scconf['connections'][$upconn]['pools'] = $upbase;
1960

    
1961
		/* Craft a cloned pool with pool settings to override for this user */
1962
		$scconf['pools'][$upname]['addrs'] = "{$mkent['pool_address']}/{$mkent['pool_netbits']}";
1963
		if (isset($mkent['dns_address']) && strlen($mkent['dns_address']) > 0 && is_ipaddr($mkent['dns_address'])) {
1964
			$scconf['pools'][$upname]['dns'] = $mkent['dns_address'];
1965
		}
1966
		$suffix++;
1967
	}
1968
	return;
1969
}
1970

    
1971
/****f* ipsec/ipsec_setup_bypass
1972
 * NAME
1973
 *   ipsec_setup_bypass - Generate a bypass connection for LAN-LAN and custom rules traffic
1974
 * INPUTS
1975
 *   None
1976
 * RESULT
1977
 *   Sets up a bypass connection to prevent local traffic from being caught by
1978
 *   IPsec policies.
1979
 ******/
1980
function ipsec_setup_bypass() {
1981
	global $scconf;
1982

    
1983
	$scconf['connections']['bypass'] = array();
1984
	/* Prevents the connection from being considered for remote peers */
1985
	$scconf['connections']['bypass']['remote_addrs'] = "127.0.0.1";
1986
	$scconf['connections']['bypass']['children'] = array();
1987

    
1988
	/* Locate the LAN IPv4 and IPv6 subnets */
1989
	$bypassnets = array();
1990
	if (!empty(config_get_path('interfaces/lan'))) {
1991
		$lanip = get_interface_ip("lan");
1992
		if (!empty($lanip) && is_ipaddrv4($lanip)) {
1993
			$lansn = get_interface_subnet("lan");
1994
			$lansa = gen_subnetv4($lanip, $lansn);
1995
			if (!empty($lansa) && !empty($lansn)) {
1996
				$bypassnets[] = "{$lansa}/{$lansn}";
1997
			}
1998
		}
1999
		$lanip6 = get_interface_ipv6("lan");
2000
		if (!empty($lanip6) && is_ipaddrv6($lanip6)) {
2001
			$lansn6 = get_interface_subnetv6("lan");
2002
			$lansa6 = gen_subnetv6($lanip6, $lansn6);
2003
			if (!empty($lansa6) && !empty($lansn6)) {
2004
				$bypassnets[] = "{$lansa6}/{$lansn6}";
2005
			}
2006
		}
2007
	}
2008
	/* If we have viable targets, setup a bypass LAN connection */
2009
	if (!empty($bypassnets) && !config_path_enabled('ipsec', 'noshuntlaninterfaces')) {
2010
		$bypass = implode(',', $bypassnets);
2011
		$scconf['connections']['bypass']['children']['bypasslan'] = array();
2012
		$scconf['connections']['bypass']['children']['bypasslan']['local_ts'] = $bypass;
2013
		$scconf['connections']['bypass']['children']['bypasslan']['remote_ts'] = $bypass;
2014
		$scconf['connections']['bypass']['children']['bypasslan']['mode'] = "pass";
2015
		$scconf['connections']['bypass']['children']['bypasslan']['start_action'] = "trap";
2016
	}
2017

    
2018
	/* Setup custom bypass rules */
2019
	if (config_path_enabled('ipsec', 'ipsecbypass')) {
2020
		foreach (config_get_path('ipsec/bypassrules/rule', []) as $id => $rule) {
2021
			$scconf['connections']['bypass']['children']["rule{$id}"] = array();
2022
			$scconf['connections']['bypass']['children']["rule{$id}"]["local_ts"] = $rule['source'] .
2023
			       	"/" . $rule['srcmask'];
2024
			$scconf['connections']['bypass']['children']["rule{$id}"]["remote_ts"] = $rule['destination'] .
2025
			       	"/" . $rule['dstmask'];
2026
			$scconf['connections']['bypass']['children']["rule{$id}"]["mode"] = "pass";
2027
			$scconf['connections']['bypass']['children']["rule{$id}"]["start_action"] = "trap";
2028
		}
2029
	}
2030

    
2031
	return;
2032
}
2033

    
2034
/****f* ipsec/ipsec_setup_routes
2035
 * NAME
2036
 *   ipsec_setup_routes - Setup OS routing table static routes for remote peers.
2037
 *                        This ensures that IPsec connections are routed out of
2038
 *                        the expected interface on egress.
2039
 * INPUTS
2040
 *   $interface : The interface upon which routes will be configured.
2041
 *   $family    : The address family ('inet' or 'inet6')
2042
 *   $sourcehost: The local source address used for initiating connections.
2043
 *   $duplicates: If the ipsec tunnel allows duplicates remote peers
2044
 * RESULT
2045
 *   Static routes in the OS routing table for IPsec peers
2046
 ******/
2047
function ipsec_setup_routes($interface, $family, $sourcehost, $duplicates) {
2048
	if (substr($interface, 0, 4) == "_vip") {
2049
		$vpninterface = get_configured_vip_interface($interface);
2050
		if (substr($vpninterface, 0, 4) == "_vip") {
2051
			// vips are nested if its a ipalias with a carp parent
2052
			$vpninterface = get_configured_vip_interface($vpninterface);
2053
		}
2054
		$ifacesuse = get_real_interface($vpninterface);
2055
	} else {
2056
		$ifacesuse = get_failover_interface($interface);
2057
		if (substr($ifacesuse, 0, 4) == "_vip") {
2058
			$vpninterface = get_configured_vip_interface($ifacesuse);
2059
			$ifacesuse = get_real_interface($vpninterface);
2060
		} else {
2061
			$vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse);
2062
		}
2063
	}
2064
	if ($family == 'inet' && !empty($ifacesuse) &&
2065
	    !empty($vpninterface) && interface_has_gateway($vpninterface)) {
2066
		$gatewayip = get_interface_gateway($vpninterface);
2067
		$interfaceip = get_interface_ip($vpninterface);
2068
		$subnet_bits = get_interface_subnet($vpninterface);
2069
		$subnet_ip = gen_subnetv4($interfaceip, $subnet_bits);
2070
		/*
2071
		 * if the remote gateway is in the local subnet, then don't add
2072
		 * a route
2073
		 */
2074
		if (is_ipaddrv4($sourcehost) &&
2075
		    !ip_in_subnet($sourcehost, "{$subnet_ip}/{$subnet_bits}") &&
2076
		    is_ipaddrv4($gatewayip) && !$duplicates) {
2077
			route_add_or_change($sourcehost, $gatewayip);
2078
		}
2079
	} else if ($family == 'inet6' && !empty($ifacesuse) &&
2080
	    !empty($vpninterface) && interface_has_gatewayv6($vpninterface)) {
2081
		$gatewayip = get_interface_gateway_v6($vpninterface);
2082
		$interfaceip = get_interface_ipv6($vpninterface);
2083
		$subnet_bits = get_interface_subnetv6($vpninterface);
2084
		$subnet_ip = gen_subnetv6($interfaceip, $subnet_bits);
2085
		/*
2086
		 * if the remote gateway is in the local subnet, then don't add
2087
		 * a route
2088
		 */
2089
		if (is_ipaddrv6($sourcehost) &&
2090
		    !ip_in_subnet($sourcehost, "{$subnet_ip}/{$subnet_bits}") &&
2091
		    is_ipaddrv6($gatewayip) && !$duplicates) {
2092
			route_add_or_change($sourcehost, $gatewayip);
2093
		}
2094
	}
2095
	return $ifacesuse;
2096
}
2097

    
2098
/****f* ipsec/ipsec_setup_authentication
2099
 * NAME
2100
 *   ipsec_setup_authentication - Generate an array with local/remote
2101
 *                                authentication information for a given IPsec
2102
 *                                Phase 1.
2103
 * INPUTS
2104
 *   $ph1ent: An IPsec Phase 1 configuration
2105
 *   $conn  : A swanctl connection array corresponding to the IPsec Phase 1.
2106
 * RESULT
2107
 *   Populates $conn with local and remote arrays containing authentication
2108
 *   details.
2109
 ******/
2110
function ipsec_setup_authentication(& $ph1ent, & $conn) {
2111
	global $rgmap, $ipsec_swanctl_dirs;
2112
	$local = array();
2113
	$remote = array();
2114
	$remote2 = array();
2115

    
2116
	list($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local', array());
2117
	$localid = ipsec_fixup_id($myid_type, $myid_data);
2118
	if (!empty($localid)) {
2119
		$local['id'] = $localid;
2120
	}
2121

    
2122
	// Only specify peer ID if we are not dealing with mobile PSK
2123
	if (!(isset($ph1ent['mobile']) &&
2124
	    in_array($ph1ent['authentication_method'], array("pre_shared_key", "xauth_psk_server")))) {
2125
		list ($remoteid_type, $remoteid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap);
2126
		$remoteid = ipsec_fixup_id($remoteid_type, $remoteid_data);
2127
	}
2128
	if (!empty($remoteid)) {
2129
		$remote['id'] = $remoteid;
2130
	}
2131

    
2132
	if (!empty($ph1ent['caref'])) {
2133
		$ca = lookup_ca($ph1ent['caref']);
2134
		$ca = $ca['item'];
2135
		if ($ca) {
2136
			/* Get hash value to use for filename */
2137
			$ca_details = openssl_x509_parse(base64_decode($ca['crt']));
2138
			$cafn = "{$ipsec_swanctl_dirs['capath']}/{$ca_details['hash']}.0";
2139
		}
2140
	}
2141

    
2142
	$authentication = "";
2143
	switch ($ph1ent['authentication_method']) {
2144
		case 'eap-mschapv2':
2145
			if (isset($ph1ent['mobile'])) {
2146
				$local['auth'] = "pubkey";
2147
				$remote['eap_id'] = "%any";
2148
				$remote['auth'] = "eap-mschapv2";
2149
			}
2150
			break;
2151
		case 'eap-tls':
2152
			if (isset($ph1ent['mobile'])) {
2153
				$local['auth'] = "pubkey";
2154
				$remote['eap_id'] = "%any";
2155
			} else {
2156
				$local['auth'] = "eap-tls";
2157
			}
2158
			$remote['auth'] = "eap-tls";
2159
			break;
2160
		case 'eap-radius':
2161
			if (isset($ph1ent['mobile'])) {
2162
				$local['auth'] = "pubkey";
2163
				$remote['eap_id'] = "%any";
2164
			} else {
2165
				$local['auth'] = "eap-radius";
2166
			}
2167
			if ((config_get_path('ipsec/client/group_source') == 'enabled') &&
2168
			    !empty(config_get_path('ipsec/client/auth_groups'))) {
2169
				$remote['groups'] = config_get_path('ipsec/client/auth_groups');
2170
			}
2171
			$remote['auth'] = "eap-radius";
2172
			break;
2173
		case 'xauth_cert_server':
2174
			$local['auth'] = "pubkey";
2175
			$remote['auth'] = "pubkey";
2176
			$remote2['auth'] = "xauth-generic";
2177
			break;
2178
		case 'xauth_psk_server':
2179
			$local['auth'] = "psk";
2180
			$remote['auth'] = "psk";
2181
			$remote2['auth'] = "xauth-generic";
2182
			break;
2183
		case 'pre_shared_key':
2184
			$local['auth'] = "psk";
2185
			$remote['auth'] = "psk";
2186
			break;
2187
		case 'cert':
2188
		case 'pkcs11':
2189
			$local['auth'] = "pubkey";
2190
			$remote['auth'] = "pubkey";
2191
			break;
2192
		case 'hybrid_cert_server':
2193
			$local['auth'] = "pubkey";
2194
			$remote['auth'] = "xauth-generic";
2195
			break;
2196
	}
2197
	if (in_array($ph1ent['authentication_method'], array('eap-mschapv2', 'eap-tls', 'eap-radius', 'xauth_cert_server', 'cert', 'hybrid_cert_server')) &&
2198
	    !empty($ph1ent['certref'])) {
2199
		$local['cert'] = array('file' => "{$ipsec_swanctl_dirs['certpath']}/cert-{$ph1ent['ikeid']}.crt");
2200
		$conn['send_cert'] = "always";
2201
	}
2202
	if ($ph1ent['authentication_method'] == 'pkcs11') {
2203
		$local['cert'] = array('handle' => "{$ph1ent['pkcs11certref']}");
2204
		$conn['send_cert'] = "always";
2205
	}
2206
	if (in_array($ph1ent['authentication_method'], array('eap-tls', 'xauth_cert_server', 'cert', 'pkcs11')) &&
2207
	    isset($cafn)) {
2208
		$remote['cacerts'] = $cafn;
2209
		if (config_path_enabled('ipsec', 'strictcrlpolicy')) {
2210
			$remote['revocation'] = "strict";
2211
		}
2212
	}
2213

    
2214
	$conn['local'] = $local;
2215
	/* If there is data for a second remote auth round, setup two remote
2216
	 * arrays with unique names, otherwise setup a single remote. */
2217
	if (empty($remote2)) {
2218
		$conn['remote'] = $remote;
2219
	} else {
2220
		$conn['remote-1'] = $remote;
2221
		$conn['remote-2'] = $remote2;
2222
	}
2223
}
2224

    
2225
/****f* ipsec/ipsec_setup_proposal_algo
2226
 * NAME
2227
 *   ipsec_setup_proposal_algo - Form a single proposal algorithm string
2228
 * INPUTS
2229
 *   $ealg_id: Encryption algorithm ID
2230
 *   $keylen : Key length for the encryption algorithm
2231
 *   $halgo  : Hash algorithm
2232
 *   $modp   : DH Group number
2233
 * RESULT
2234
 *   Returns a string using the available information to form a single proposal
2235
 *   algorithm definition.
2236
 * NOTES
2237
 *   Values left empty will not be added to the string. Some combinations may
2238
 *   require one or more parts to be omitted.
2239
 ******/
2240
function ipsec_setup_proposal_algo($ealg_id, $keylen, $halgo, $prfalgo, $modp) {
2241
	$palgo = "";
2242

    
2243
	/* Add the encryption algorithm (if present) */
2244
	if (!empty($ealg_id)) {
2245
		$palgo .= "{$ealg_id}";
2246
	}
2247

    
2248
	/* Add the key length (if present) */
2249
	if (!empty($keylen)) {
2250
		$palgo .= "{$keylen}";
2251
	}
2252

    
2253
	/* Add the hash algorithm (if present) */
2254
	if (!empty($halgo)) {
2255
		/* If there is some content in the proposal already, add a
2256
		 * separator */
2257
		if (!empty($palgo)) {
2258
			$palgo .= "-";
2259
		}
2260
		$halgo = str_replace('hmac_', '', $halgo);
2261
		$palgo .= "{$halgo}";
2262
	}
2263

    
2264
	if (!empty($prfalgo)) {
2265
		$palgo .= "-prf{$prfalgo}";
2266
	}
2267

    
2268
	/* Convert the DH group to its keyword and add (if present) */
2269
	$modp = ipsec_convert_to_modp($modp);
2270
	if (!empty($modp)) {
2271
		$palgo .= "-{$modp}";
2272
	}
2273

    
2274
	return $palgo;
2275
}
2276

    
2277
/****f* ipsec/ipsec_setup_proposal_entry
2278
 * NAME
2279
 *   ipsec_setup_proposal_entry - Generate a full proposal string for an IPsec
2280
 *                                Phase 2 configuration.
2281
 * INPUTS
2282
 *   $ph2ent  : An IPsec Phase 2 configuration
2283
 *   $algo_arr: An array in which all proposal algorithms are collected
2284
 *   $ealg_id : Encryption algorithm ID
2285
 *   $keylen  : Key length for the encryption algorithm
2286
 * RESULT
2287
 *   Returns a string containing all proposal elements, and merges the entries
2288
 *   to $algo_arr as well.
2289
 ******/
2290
function ipsec_setup_proposal_entry(& $ph2ent, & $algo_arr, $ealg_id, $keylen) {
2291
	global $p2_ealgos;
2292
	$proposal = array();
2293

    
2294
	/* If multiple hash algorithms are present, loop through and add them all. */
2295
	if (!empty($ph2ent['hash-algorithm-option']) && is_array($ph2ent['hash-algorithm-option']) 
2296
	    && !(strpos($ealg_id, "gcm") || $ealg_id == "chacha20poly1305")) {
2297
		foreach ($ph2ent['hash-algorithm-option'] as $halgo) {
2298
			$proposal[] = ipsec_setup_proposal_algo($ealg_id, $keylen, $halgo, false, $ph2ent['pfsgroup']);
2299
		}
2300
	} else {
2301
		$proposal[] = ipsec_setup_proposal_algo($ealg_id, $keylen, false, false, $ph2ent['pfsgroup']);
2302
	}
2303

    
2304
	/* Add to master list */
2305
	$algo_arr = array_merge($algo_arr, $proposal);
2306
	return implode(',', $proposal);
2307
}
2308

    
2309
function ipsec_get_ifname($p1, $reqid = 0) {
2310
	$ifname = "ipsec";
2311
	if ($reqid > 0) {
2312
		$ifname .= "{$reqid}";
2313
	} else {
2314
		$p2s = ipsec_get_phase2_by_ikeid($p1['ikeid']);
2315
		if (!empty($p2s)) {
2316
			$ifname .= $p2s[0]['reqid'];
2317
		}
2318
	}
2319
	return $ifname;
2320
}
2321

    
2322
function ipsec_get_ifname_by_conf($p1 = array(), $p2 = array()) {
2323
	$have_p1 = (!empty($p1) && is_array($p1));
2324
	$have_p2 = (!empty($p2) && is_array($p2));
2325
	$reqid = null;
2326

    
2327
	if (!$have_p1 && $have_p2) {
2328
		$p1 = ipsec_get_phase1($p2['ikeid']);
2329
	}
2330

    
2331
	if ($have_p2) {
2332
		$reqid = $p2['reqid'];
2333
	}
2334

    
2335
	return ipsec_get_ifname($p1, $reqid);
2336
}
2337

    
2338
/****f* ipsec/ipsec_setup_vtireq
2339
 * NAME
2340
 *   ipsec_setup_vtireq - Setup a VTI type IPsec request
2341
 * INPUTS
2342
 *   $child                : A swanctl child array
2343
 *   $ipsec_vti_cleanup_ifs: An array of VTI interface names for later cleanup
2344
 *   $p1                   : The IKE config under which this child exists
2345
 *   $reqid                : The reqid of the P2 if known, otherwise the first P2 reqid for this P1 is looked up.
2346
 * RESULT
2347
 *   Sets up VTI-specific values for a request.
2348
 ******/
2349
function ipsec_setup_vtireq(& $child, & $ipsec_vti_cleanup_ifs, $p1, $reqid = 0) {
2350
	global $ipsec_reqid_base;
2351
	if ($reqid > 0) {
2352
		$child['reqid'] = $ipsec_reqid_base + $reqid;
2353
	} else {
2354
		$p2s = ipsec_get_phase2_by_ikeid($p1['ikeid']);
2355
		if (!empty($p2s)) {
2356
			$reqid = $p2s[0]['reqid'];
2357
			$child['reqid'] = $ipsec_reqid_base + $reqid;
2358
		} else {
2359
			return false;
2360
		}
2361
	}
2362
	/* This interface will be a valid IPsec interface, so remove it from the cleanup list. */
2363
	$ipsec_vti_cleanup_ifs = array_diff($ipsec_vti_cleanup_ifs, array(ipsec_get_ifname($p1, $reqid)));
2364
	$child['local_ts'] .= ",0.0.0.0/0,::/0";
2365
	$child['remote_ts'] .= ",0.0.0.0/0,::/0";
2366
	return true;
2367
}
2368

    
2369
/****f* ipsec/ipsec_setup_tunnels
2370
 * NAME
2371
 *   ipsec_setup_tunnels - Configure all P1/P2 entries as swanctl connections
2372
 * INPUTS
2373
 *   None
2374
 * RESULT
2375
 *   Sets up a swanctl array for all connections in the configuration along with
2376
 *   their children, authentication, etc.
2377
 ******/
2378
function ipsec_setup_tunnels() {
2379
	global $aggressive_mode_psk,
2380
		$filterdns_list, $g, $ifacesuse, $ipsec_idhandling, $ipsec_log_cats,
2381
		$ipsec_log_sevs, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs,
2382
		$ipseccfg, $mobile_ipsec_auth, $natfilterrules, $p1_ealgos,
2383
		$p2_ealgos, $rgmap, $sa, $sn, $scconf, $conn, $tunnels,
2384
		$ipsec_vti_cleanup_ifs, $conn_defaults;
2385

    
2386
	$a_groups = return_gateway_groups_array(true);
2387

    
2388
	foreach ($tunnels as $ph1ent) {
2389
		/* Skip disabled entries */
2390
		if (isset($ph1ent['disabled'])) {
2391
			continue;
2392
		}
2393
		/* If the tunnel has no encryption algorithms, it isn't valid. */
2394
		if (count(array_get_path($ph1ent, 'encryption/item', [])) == 0) {
2395
			continue;
2396
		}
2397
		/* If the local source is invalid, skip this entry. */
2398
		$local_spec = ipsec_get_phase1_src($ph1ent);
2399
		if (!$local_spec) {
2400
			continue;
2401
		}
2402

    
2403
		/* Determine the name of this connection, either con-mobile for
2404
		 * mobile clients, or a name based on the IKE ID otherwise. */
2405
		if (isset($ph1ent['mobile'])) {
2406
			$cname = "con-mobile";
2407
			/* Start with common default values */
2408
			$scconf["{$cname}-defaults"] = $conn_defaults;
2409
			/* Array reference to make things easier */
2410
			$conn =& $scconf["{$cname}-defaults"];
2411
			$scconf['connections']["{$cname} : {$cname}-defaults"] = array("# Stub to load con-mobile-defaults");
2412
		} else {
2413
			$cname = ipsec_conid($ph1ent);
2414
			/* Start with common default values */
2415
			$scconf['connections'][$cname] = $conn_defaults;
2416
			$descr = "# P1 (ikeid {$ph1ent['ikeid']})";
2417
			if (!empty($ph1ent['descr'])) {
2418
				$descr .= ": {$ph1ent['descr']}";
2419
			}
2420
			array_unshift($scconf['connections'][$cname], $descr);
2421
			/* Array reference to make things easier */
2422
			$conn =& $scconf['connections'][$cname];
2423
		}
2424

    
2425
		/* Common parameters for all children */
2426
		$child_params = array();
2427
		if (!empty($ph1ent['closeaction'])) {
2428
			$child_params['close_action'] = $ph1ent['closeaction'];
2429
		}
2430

    
2431
		$ikeid = $ph1ent['ikeid'];
2432

    
2433
		$carpbackup = false;
2434
		if (((substr($ph1ent['interface'], 0, 4) == "_vip") &&
2435
		    in_array(get_carp_bind_status($ph1ent['interface']), array('BACKUP', 'INIT'))) ||
2436
		    (is_array($a_groups[$ph1ent['interface']]) &&
2437
		    !empty($a_groups[$ph1ent['interface']][0]['vip']) &&
2438
		    in_array(get_carp_bind_status($a_groups[$ph1ent['interface']][0]['vip']), array('BACKUP', 'INIT')))) {
2439
			$carpbackup = true;
2440
		}
2441

    
2442
		/* "trap" adds policies to start a tunnel when interesting
2443
		 * traffic is observed by the host. */
2444
		$start_action = "trap";
2445
		if ($carpbackup) {
2446
			$start_action = "none";
2447
		}
2448

    
2449
		/* Set the IKE version appropriately (empty = IKEv1) */
2450
		switch ($ph1ent['iketype']) {
2451
			case 'auto':
2452
				$ikeversion = 0;
2453
				break;
2454
			case 'ikev2':
2455
				$ikeversion = 2;
2456
				break;
2457
			case 'ikev1':
2458
			default:
2459
				$ikeversion = 1;
2460
				break;
2461
		}
2462
		$conn['version'] = $ikeversion;
2463

    
2464
		/* For IKEv1 or auto, setup aggressive mode if configured */
2465
		if ($ikeversion != 2){
2466
			$conn['aggressive'] = ($ph1ent['mode'] == "aggressive") ? "yes" : "no";
2467
		}
2468

    
2469
		if (isset($ph1ent['mobile'])) {
2470
			/* Mobile tunnels allow 'any' as a peer */
2471
			$remote_spec = "0.0.0.0/0,::/0";
2472
			/* Mobile tunnels cannot start automatically */
2473
			$start_action = 'none';
2474
		} else {
2475
			if (($ph1ent['protocol'] == 'both') &&
2476
			    (($ph1ent['remote-gateway'] == '0.0.0.0') ||
2477
			    ($ph1ent['remote-gateway'] == '::'))) {
2478
				$remote_spec = '%any';
2479
			} else {
2480
				$remote_spec = $ph1ent['remote-gateway'];
2481
			}
2482
			$sourcehost = (is_ipaddr($remote_spec)) ? $remote_spec : $rgmap[$remote_spec];
2483
			$ifacesuse = ipsec_setup_routes($ph1ent['interface'], $ph1ent['protocol'], $sourcehost, isset($ph1ent['gw_duplicates']));
2484
		}
2485

    
2486
		/* Setup IKE proposals */
2487
		$ciphers = array();
2488
		foreach(array_get_path($ph1ent, 'encryption/item', []) as $p1enc) {
2489
			if (empty($p1enc) ||
2490
			    empty(array_get_path($p1enc, 'encryption-algorithm/name', '')) ||
2491
			    empty(array_get_path($p1enc, 'hash-algorithm'))) {
2492
				continue;
2493
			}
2494
			if ($ph1ent['prfselect_enable'] != 'yes') {
2495
				$p1enc['prf-algorithm'] = false;
2496
			}
2497
			$ciphers[] = ipsec_setup_proposal_algo($p1enc['encryption-algorithm']['name'],
2498
								$p1enc['encryption-algorithm']['keylen'],
2499
								$p1enc['hash-algorithm'],
2500
								$p1enc['prf-algorithm'],
2501
								$p1enc['dhgroup']);
2502
		}
2503
		if (!empty($ciphers)) {
2504
			$conn['proposals'] = implode(",", $ciphers);
2505
		}
2506

    
2507
		/* Configure DPD values. The DPD action is a per-child parameter,
2508
		 * not per-connection like the delay and timeout. */
2509
		if ($ph1ent['dpd_delay'] && $ph1ent['dpd_maxfail']) {
2510
			if ($start_action == "trap") {
2511
				$child_params['dpd_action'] = "trap";
2512
			} else {
2513
				$child_params['dpd_action'] = "clear";
2514
			}
2515
			$conn['dpd_delay'] = "{$ph1ent['dpd_delay']}s";
2516
			if ($ph1ent['iketype'] == 'ikev1') {
2517
				/* in IKEv2 the default retransmission timeout applies,
2518
				 * see https://redmine.pfsense.org/issues/12184 */
2519
				$conn['dpd_timeout'] =  $ph1ent['dpd_delay'] * ($ph1ent['dpd_maxfail'] + 1) . "s";
2520
			}
2521

    
2522
			/* Adjust dpd_action if the close_action is explicitly set */
2523
			if (!empty($child_params['close_action'])) {
2524
				switch ($ph1ent['closeaction']) {
2525
					case 'trap':
2526
						$child_params['dpd_action'] = 'trap';
2527
						break;
2528
					case 'start':
2529
						$child_params['dpd_action'] = 'restart';
2530
						break;
2531
					case 'none':
2532
					default:
2533
						$child_params['dpd_action'] = 'clear';
2534
				}
2535
			}
2536
		} else {
2537
			$child_params['dpd_action'] = "clear";
2538
		}
2539

    
2540
		/* Rekey (IKEv2 or Auto only, not supported by IKEv1) */
2541
		if (($ikeversion == 0) || ($ikeversion == 2)) {
2542
			$conn['rekey_time'] = ipsec_get_rekey_time($ph1ent) . "s";
2543
		}
2544

    
2545
		/* Reauth (Any) */
2546
		$conn['reauth_time'] = ipsec_get_reauth_time($ph1ent) . "s";
2547

    
2548
		/* Over Time */
2549
		$conn['over_time'] = ipsec_get_over_time($ph1ent) . "s";
2550

    
2551
		/* Rand Time */
2552
		$conn['rand_time'] = ipsec_get_rand_time($ph1ent) . "s";
2553

    
2554
		/* NAT Traversal */
2555
		$conn['encap'] = ($ph1ent['nat_traversal'] == 'force') ? "yes" : "no";
2556

    
2557
		/* MOBIKE support */
2558
		$conn['mobike'] = ($ph1ent['mobike'] == 'on') ? "yes" : "no";
2559

    
2560
		/* TFC Padding */
2561
		if (isset($ph1ent['tfc_enable'])) {
2562
			$conn['tfc_padding'] = (isset($ph1ent['tfc_bytes']) && is_numericint($ph1ent['tfc_bytes'])) ? $ph1ent['tfc_bytes'] : "mtu";
2563
		}
2564

    
2565
		/* Custom Ports */
2566
		if (isset($ph1ent['ikeport'])) {
2567
			/* For a connection without encapsulation, do not set local_port */
2568
			$conn['remote_port'] = $ph1ent['ikeport'];
2569
		} elseif (isset($ph1ent['nattport'])) {
2570
			/* For an encapsulated connection,
2571
			 * set local_port to the server NAT-T port value or default (4500) */
2572
			$conn['local_port'] = config_get_path('ipsec/port_nat_t', 4500);
2573
			$conn['remote_port'] = $ph1ent['nattport'];
2574
		}
2575

    
2576
		/* Arrays for P2s/children */
2577
		$children = array();
2578
		$remote_ts_spec = array();
2579
		$local_ts_spec = array();
2580
		$reqids = array();
2581
		$has_vti = false;
2582
		$ealgoAHsp2arr = array();
2583
		$ealgoESPsp2arr = array();
2584

    
2585
		foreach ($ph1ent['p2'] as $ph2ent) {
2586
			/* If this entry is disabled, or cannot be configured, skip. */
2587
			if (isset($ph2ent['disabled']) ||
2588
			    (isset($ph2ent['mobile']) &&
2589
			    !config_path_enabled('ipsec/client'))) {
2590
				continue;
2591
			}
2592
			$child = array();
2593
			$local_ts = "";
2594
			$remote_ts = "";
2595
			if (($ph2ent['mode'] == 'tunnel') or ($ph2ent['mode'] == 'tunnel6')) {
2596
				/* Normal tunnel child config */
2597
				$child['mode'] = "tunnel";
2598
				$child['policies'] = "yes";
2599

    
2600
				$localid_type = $ph2ent['localid']['type'];
2601
				$localsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
2602

    
2603
				/* Do not print localid in some cases, such as a pure-psk or psk/xauth single phase2 mobile tunnel */
2604
				if (($localid_type == "none" || $localid_type == "mobile") &&
2605
				    isset($ph1ent['mobile']) && (ipsec_get_number_of_phase2($ikeid) == 1)) {
2606
					$local_spec = '0.0.0.0/0,::/0';
2607
				} else {
2608
					if ($localid_type != "address") {
2609
						$localid_type = "subnet";
2610
					}
2611
					// Don't let an empty subnet into config, it can cause parse errors. Ticket #2201.
2612
					if (!is_ipaddr($localsubnet_data) && !is_subnet($localsubnet_data) && ($localsubnet_data != "0.0.0.0/0")) {
2613
						log_error("Invalid IPsec Phase 2 \"{$ph2ent['descr']}\" - {$ph2ent['localid']['type']} has no subnet.");
2614
						continue;
2615
					}
2616
					if (!empty($ph2ent['natlocalid'])) {
2617
						$natlocalsubnet_data = ipsec_idinfo_to_cidr($ph2ent['natlocalid'], false, $ph2ent['mode']);
2618
						if ($ph2ent['natlocalid']['type'] != "address") {
2619
							if (is_subnet($natlocalsubnet_data)) {
2620
								$localsubnet_data = "{$natlocalsubnet_data}|{$localsubnet_data}";
2621
							}
2622
						} else {
2623
							if (is_ipaddr($natlocalsubnet_data)) {
2624
								$localsubnet_data = "{$natlocalsubnet_data}|{$localsubnet_data}";
2625
							}
2626
						}
2627
						$natfilterrules = true;
2628
					}
2629
				}
2630

    
2631
				$local_ts = $localsubnet_data;
2632

    
2633
				if (!isset($ph2ent['mobile'])) {
2634
					$remote_ts = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
2635
				} elseif (!empty(config_get_path('ipsec/client/pool_address'))) {
2636
					$remote_ts = config_get_path('ipsec/client/pool_address') . '/' . config_get_path('ipsec/client/pool_netbits');
2637
				}
2638

    
2639
			} elseif ($ph2ent['mode'] == 'vti') {
2640
				/* VTI-specific child config */
2641
				$child['policies'] = "no";
2642
				/* VTI cannot use trap policies, so start automatically instead */
2643
				$start_action = 'start';
2644
				if ($carpbackup) {
2645
					$start_action = "none";
2646
				}
2647
				if ($child_params['dpd_action'] == "trap") {
2648
					$child_params['dpd_action'] = "restart";
2649
				}
2650
				$localid_type = $ph2ent['localid']['type'];
2651
				$localsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
2652
				$local_ts = $localsubnet_data;
2653
				$remote_ts = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
2654
				$has_vti = true;
2655
			} else {
2656
				/* Transport mode child config */
2657
				$child['mode'] = "transport";
2658
				$child['policies'] = "yes";
2659

    
2660
				if ((($ph1ent['authentication_method'] == "xauth_psk_server") ||
2661
				    ($ph1ent['authentication_method'] == "pre_shared_key")) &&
2662
				    isset($ph1ent['mobile'])) {
2663
					$local_spec = "0.0.0.0/0,::/0";
2664
				} else {
2665
					$local_ts = ipsec_get_phase1_src($ph1ent);
2666
				}
2667

    
2668
				if (!isset($ph2ent['mobile'])) {
2669
					$remote_ts = $remote_spec;
2670
				}
2671
			}
2672

    
2673
			if (!empty($local_ts)) {
2674
				$local_ts_spec[] = $local_ts;
2675
			}
2676
			if (!empty($remote_ts)) {
2677
				$remote_ts_spec[] = $remote_ts;
2678
			}
2679

    
2680
			/* If a PFS group is configured on the Mobile Clients tab,
2681
			 * and this is a mobile P2, use it here. */
2682
			if (config_get_path('ipsec/client/pfs_group') &&
2683
			    isset($ph2ent['mobile'])) {
2684
				$ph2ent['pfsgroup'] = config_get_path('ipsec/client/pfs_group');
2685
			}
2686

    
2687
			$reqids[] = $ph2ent['reqid'];
2688

    
2689
			if (!empty($ph2ent['lifetime'])) {
2690
				$child['life_time'] = ipsec_get_life_time($ph2ent) . "s";
2691
				/* Rekey at 90% of lifetime */
2692
				$child['rekey_time'] = ipsec_get_rekey_time($ph2ent) . "s";
2693
				/* Random rekey fuzz time */
2694
				$child['rand_time'] = ipsec_get_rand_time($ph2ent) . "s";
2695
			}
2696

    
2697
			/* Set Child SA Start Action based on user preference, except
2698
			 * for invalid combinations such as 'trap' on VTI */
2699
			if (!isset($ph2ent['mobile']) && !$carpbackup &&
2700
			    !(($ph2ent['mode'] == 'vti') && ($ph1ent['startaction'] == 'trap'))) {
2701
				$start_action = !empty($ph1ent['startaction']) ? $ph1ent['startaction'] : $start_action;
2702
			}
2703
			$child['start_action'] = $start_action;
2704

    
2705
			/* Setup child SA proposals */
2706
			$proposal = array();
2707
			$ph2ent_ealgos = array();
2708
			$ph2ent_ealgos_aead = array();
2709
			if ($ph2ent['protocol'] == 'esp') {
2710
				if (is_array($ph2ent['encryption-algorithm-option'])) {
2711
					foreach ($ph2ent['encryption-algorithm-option'] as $ealg) {
2712
						if (strpos($ealg['name'], "gcm")) {
2713
							/* put AEAD ciphers on top, 
2714
							*  see https://redmine.pfsense.org/issues/11078 */
2715
							$ph2ent_ealgos_aead[] = $ealg;
2716
						} else {
2717
							$ph2ent_ealgos[] = $ealg;
2718
						}
2719
					}
2720
					$ph2ent_ealgos = array_merge(array_reverse($ph2ent_ealgos_aead), $ph2ent_ealgos);
2721
					foreach ($ph2ent_ealgos as $ealg) {
2722
						$ealg_id = $ealg['name'];
2723
						$ealg_kl = $ealg['keylen'];
2724

    
2725
						if (!empty($ealg_kl) && $ealg_kl == "auto") {
2726
							if (empty($p2_ealgos) || !is_array($p2_ealgos)) {
2727
								require_once("ipsec.inc");
2728
							}
2729
							$key_hi = $p2_ealgos[$ealg_id]['keysel']['hi'];
2730
							$key_lo = $p2_ealgos[$ealg_id]['keysel']['lo'];
2731
							$key_step = $p2_ealgos[$ealg_id]['keysel']['step'];
2732
							/* XXX: in some cases where include ordering is suspect these variables
2733
							 * are somehow 0 and we enter this loop forever and timeout after 900
2734
							 * seconds wrecking bootup */
2735
							if ($key_hi != 0 and $key_lo != 0 and $key_step != 0) {
2736
								for ($keylen = $key_hi; $keylen >= $key_lo; $keylen -= $key_step) {
2737
									$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoESPsp2arr, $ealg_id, $keylen);
2738
								}
2739
							}
2740
						} else {
2741
							$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoESPsp2arr, $ealg_id, $ealg_kl);
2742
						}
2743
					}
2744
				}
2745
			} else if ($ph2ent['protocol'] == 'ah') {
2746
				$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoAHsp2arr, '', '');
2747
			}
2748

    
2749
			/* Not mobile, and IKEv1 or Split Connections active */
2750
			if (!isset($ph1ent['mobile']) && (($ikeversion == 1) || isset($ph1ent['splitconn']))) {
2751
				if (!empty($remote_ts)) {
2752
					/* Setup child sub-connections using unique names */
2753
					$subconname = ipsec_conid($ph1ent, $ph2ent);
2754
					$children[$subconname] = $child;
2755

    
2756
					$descr = "# P2 (reqid {$ph2ent['reqid']})";
2757
					if (!empty($ph2ent['descr'])) {
2758
						$descr .= ": {$ph2ent['descr']}";
2759
					}
2760
					array_unshift($children[$subconname], $descr);
2761
					$children[$subconname]['local_ts'] = $local_ts;
2762
					$children[$subconname]['remote_ts'] = $remote_ts;
2763
					if ($has_vti) {
2764
						ipsec_setup_vtireq($children[$subconname], $ipsec_vti_cleanup_ifs, $ph1ent, $ph2ent['reqid']);
2765
					}
2766
					if (!empty($ph2ent['protocol']) && !empty($proposal)) {
2767
						$children[$subconname][$ph2ent['protocol'] . '_proposals'] = implode(',', $proposal);
2768
					}
2769
				} else {
2770
					log_error(sprintf(gettext("No phase2 specifications for tunnel with ikeid = %s"), $ikeid));
2771
				}
2772
			} else {
2773
				/* TODO: Fix this to nicely merge all P2 params for single child case */
2774
				if (!is_array($children[$cname])) {
2775
					$children[$cname] = array();
2776
				}
2777
				$children[$cname] = array_merge($children[$cname], $child);
2778

    
2779
				$descr = "# P2 (reqid {$ph2ent['reqid']})";
2780
				if (!empty($ph2ent['descr'])) {
2781
					$descr .= ": {$ph2ent['descr']}";
2782
				}
2783
				array_unshift($children[$cname], $descr);
2784
			}
2785
		}
2786

    
2787
		$conn['local_addrs'] = $local_spec;
2788
		$conn['remote_addrs'] = $remote_spec;
2789

    
2790
		$pools = array();
2791
		if (isset($ph1ent['mobile'])) {
2792
			if (($ph1ent['authentication_method'] == 'eap-radius') &&
2793
			    empty(config_get_path('ipsec/client/pool_address')) &&
2794
			    empty(config_get_path('ipsec/client/pool_address_v6'))) {
2795
				$pools[] = "radius";
2796
			} else {
2797
				if (!empty(config_get_path('ipsec/client/pool_address'))) {
2798
					$pools[] = "mobile-pool-v4";
2799
				}
2800
				if (!empty(config_get_path('ipsec/client/pool_address_v6'))) {
2801
					$pools[] = "mobile-pool-v6";
2802
				}
2803
				if (config_path_enabled('ipsec/client', 'radius_ip_priority_enable')) {
2804
					$pools[] = "radius";
2805
				}
2806
			}
2807
		}
2808
		if (!empty($pools)) {
2809
			$conn['pools'] = implode(', ', $pools);
2810
		}
2811

    
2812
		/* For IKEv2 without Split Connections, setup combined sets of
2813
		 * local/remote traffic selectors and proposals */
2814
		if (!(!isset($ph1ent['mobile']) && (($ikeversion == 1) || isset($ph1ent['splitconn'])))) {
2815
			if (!isset($ph1ent['mobile']) && !empty($remote_ts_spec)) {
2816
				$children[$cname]['remote_ts'] = implode(",", $remote_ts_spec);
2817
			}
2818
			if (!empty($local_ts_spec)) {
2819
				$children[$cname]['local_ts'] = implode(",", $local_ts_spec);
2820
			}
2821
			if ($has_vti) {
2822
				ipsec_setup_vtireq($children[$cname], $ipsec_vti_cleanup_ifs, $ph1ent);
2823
			}
2824
			if (!empty($ealgoAHsp2arr)) {
2825
				$halgos = array();
2826
				$halgos_sha = array();
2827
				foreach ($ealgoAHsp2arr as $halg) {
2828
					if (strstr($halg, "sha")) {
2829
						/* put SHA ciphers on top, 
2830
						*  see https://redmine.pfsense.org/issues/12323 */
2831
						$halgos_sha[] = $halg;
2832
					} else {
2833
						$halgos[] = $halg;
2834
					}
2835
				}
2836
				$ealgoAHsp2arr = array_merge(array_reverse($halgos_sha), $halgos);
2837
				$children[$cname]['ah_proposals'] = implode(',', array_unique($ealgoAHsp2arr));
2838
			}
2839
			if (!empty($ealgoESPsp2arr)) {
2840
				$children[$cname]['esp_proposals'] = implode(',', array_unique($ealgoESPsp2arr));
2841
			}
2842
		}
2843

    
2844
		/* Setup connection authentication */
2845
		ipsec_setup_authentication($ph1ent, $conn);
2846

    
2847
		/* Add children to this connection, including default child parameters */
2848
		if (count($children)) {
2849
			foreach($children as $name => $child) {
2850
				$conn['children'][$name] = array_merge($child, $child_params);
2851
			}
2852
		}
2853
		unset ($ph2ent);
2854
	}
2855

    
2856
	return;
2857
}
2858

    
2859
/****f* ipsec/ipsec_setup_secrets
2860
 * NAME
2861
 *   ipsec_setup_secrets - Setup swanctl authentication secrets
2862
 * INPUTS
2863
 *   None
2864
 * RESULT
2865
 *   Returns a swanctl array containing secrets (PSKs, certs, etc) and writes out
2866
 *   necessary CA, CRL, and certificate data.
2867
 ******/
2868
function ipsec_setup_secrets() {
2869
	global $ipsec_swanctl_dirs, $ipseccfg, $rgmap, $scconf;
2870

    
2871
	$suffix = 0;
2872

    
2873
	$vpncas = array();
2874
	foreach (config_get_path('ipsec/phase1', []) as $ph1ent) {
2875
		if (isset($ph1ent['disabled'])) {
2876
			continue;
2877
		}
2878

    
2879
		if (isset($ph1ent['mobile'])) {
2880
			if ($ph1ent['authentication_method'] == 'pre_shared_key') {
2881
				$mobilepsk = true;
2882
			} elseif ($ph1ent['authentication_method'] == 'eap-mschapv2') {
2883
				$mobileeap = true;
2884
			}
2885
		}
2886

    
2887
		if (strstr($ph1ent['authentication_method'], 'cert') ||
2888
		    in_array($ph1ent['authentication_method'], array('eap-mschapv2', 'eap-tls', 'eap-radius'))) {
2889
			/* Write certificate and private key, point to private key */
2890
			$certline = '';
2891

    
2892
			$ikeid = $ph1ent['ikeid'];
2893
			$cert = lookup_cert($ph1ent['certref']);
2894
			$cert = $cert['item'];
2895

    
2896
			if (!$cert) {
2897
				log_error(sprintf(gettext("Error: Invalid phase1 certificate reference for %s"), $ph1ent['name']));
2898
				continue;
2899
			}
2900

    
2901
			/* add signing CA cert chain of server cert
2902
			 * to the list of CAs to write
2903
			 */
2904
			$cachain = ca_chain_array($cert);
2905
			if ($cachain && is_array($cachain)) {
2906
				foreach ($cachain as $cacrt) {
2907
					$vpncas[$cacrt['refid']] = $cacrt;
2908
				}
2909
			}
2910

    
2911
			@chmod($ipsec_swanctl_dirs['certpath'], 0600);
2912

    
2913
			$ph1keyfile = "{$ipsec_swanctl_dirs['keypath']}/cert-{$ikeid}.key";
2914
			if (!file_put_contents($ph1keyfile, base64_decode($cert['prv']))) {
2915
				log_error(sprintf(gettext("Error: Cannot write phase1 key file for %s"), $ph1ent['name']));
2916
				continue;
2917
			}
2918
			@chmod($ph1keyfile, 0600);
2919

    
2920
			$ph1certfile = "{$ipsec_swanctl_dirs['certpath']}/cert-{$ikeid}.crt";
2921
			if (!file_put_contents($ph1certfile, base64_decode($cert['crt']))) {
2922
				log_error(sprintf(gettext("Error: Cannot write phase1 certificate file for %s"), $ph1ent['name']));
2923
				@unlink($ph1keyfile);
2924
				continue;
2925
			}
2926
			@chmod($ph1certfile, 0600);
2927

    
2928
			$scconf['secrets']['private-' . $suffix++] = array('file' => $ph1keyfile);
2929
		} else if (strstr($ph1ent['authentication_method'], 'pkcs11')) {
2930
			$p11_id = array();
2931
			$output = shell_exec('/usr/local/bin/pkcs15-tool -c');
2932
			preg_match_all('/ID\s+: (.*)/', $output, $p11_id);
2933
			if (!empty($ph1ent['pkcs11certref']) && in_array($ph1ent['pkcs11certref'], $p11_id[1])) {
2934
				$scconf['secrets']['token-' . $suffix++] = array(
2935
					'handle' => $ph1ent['pkcs11certref'],
2936
					'pin' => $ph1ent['pkcs11pin'],
2937
				);
2938
			} else {
2939
				log_error(sprintf(gettext("Error: Invalid phase1 PKCS#11 certificate reference or PKCS#11 is not present for %s"), $ph1ent['name']));
2940
				continue;
2941
			}
2942
		} else {
2943
			/* Setup pre-shared keys */
2944
			list($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local', array());
2945
			list($peerid_type, $peerid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap);
2946
			$myid = trim($myid_data);
2947

    
2948
			if (empty($peerid_data)) {
2949
				continue;
2950
			}
2951

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

    
2955
			if (!empty($ph1ent['pre-shared-key'])) {
2956
				$scconf['secrets']['ike-' . $suffix++] = array(
2957
					'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
2958
					'id-0' => $myid,
2959
					'id-1' => $peerid,
2960
				);
2961
				if (isset($ph1ent['mobile'])) {
2962
					$scconf['secrets']['ike-' . $suffix++] = array(
2963
						'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
2964
						'id-0' => $myid,
2965
						'id-1' => '%any',
2966
					);
2967
					$scconf['secrets']['ike-' . $suffix++] = array(
2968
						'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
2969
					);
2970
				}
2971
			}
2972
		}
2973

    
2974
		/* if the client authenticates with a cert add the
2975
		 * client cert CA chain to the list of CAs to write
2976
		 */
2977
		if (in_array($ph1ent['authentication_method'],
2978
		    array('cert', 'eap-tls', 'xauth_cert_server', 'pkcs11'))) {
2979
			if (!empty($ph1ent['caref']) && !array_key_exists($ph1ent['caref'], $vpncas)) {
2980
				$thisca = lookup_ca($ph1ent['caref']);
2981
				$thisca = $thisca['item'];
2982
				$vpncas[$ph1ent['caref']] = $thisca;
2983
				/* follow chain up to root */
2984
				$cachain = ca_chain_array($thisca);
2985
				if ($cachain and is_array($cachain)) {
2986
					foreach ($cachain as $cacrt) {
2987
						$vpncas[$cacrt['refid']] = $cacrt;
2988
					}
2989
				}
2990
			}
2991
		}
2992
	}
2993

    
2994
	/* Write the required CAs */
2995
	foreach ($vpncas as $carefid => $cadata) {
2996
		$cacrt = base64_decode($cadata['crt']);
2997
		$cacrtattrs = openssl_x509_parse($cacrt);
2998
		if (!is_array($cacrtattrs) || !isset($cacrtattrs['hash'])) {
2999
			log_error(sprintf(gettext("Error: Invalid certificate hash info for %s"), $cadata['descr']));
3000
			continue;
3001
		}
3002
		$cafilename = "{$ipsec_swanctl_dirs['capath']}/{$cacrtattrs['hash']}.0";
3003
		if (!@file_put_contents($cafilename, $cacrt)) {
3004
				log_error(sprintf(gettext("Error: Cannot write IPsec CA file for %s"), $cadata['descr']));
3005
				continue;
3006
		}
3007
	}
3008

    
3009
	/* write out CRL files */
3010
	if (!empty($vpncas)) {
3011
		foreach (config_get_path('crl', []) as $crl) {
3012
			if (!isset($crl['text'])) {
3013
				log_error(sprintf(gettext("Warning: Missing CRL data for %s"), $crl['descr']));
3014
				continue;
3015
			}
3016
			$fpath = "{$ipsec_swanctl_dirs['crlpath']}/{$crl['refid']}.crl";
3017
			if (!@file_put_contents($fpath, base64_decode($crl['text']))) {
3018
				log_error(sprintf(gettext("Error: Cannot write IPsec CRL file for %s"), $crl['descr']));
3019
				continue;
3020
			}
3021
		}
3022
	}
3023

    
3024
	/* Add user PSKs */
3025
	if ($mobilepsk) {
3026
		foreach (config_get_path('system/user', []) as $user) {
3027
			if (!empty($user['ipsecpsk'])) {
3028
				$scconf['secrets']['ike-' . $suffix++] = array(
3029
					'secret' => '0s' . base64_encode(trim($user['ipsecpsk'])),
3030
					'id-0' => $myid,
3031
					'id-1' => $user['name'],
3032
				);
3033
			}
3034
		}
3035
		unset($user);
3036
	}
3037

    
3038
	/* add PSKs/EAPs for mobile clients */
3039
	if (is_array($ipseccfg['mobilekey'])) {
3040
		foreach ($ipseccfg['mobilekey'] as $key) {
3041
			if (($mobileeap && ($key['type'] == 'EAP')) ||
3042
			    ($key['type'] == 'PSK')) {
3043
				if (($key['ident'] == 'allusers') ||
3044
				    ($key['ident'] == 'any')) {
3045
					$key['ident'] = '%any';
3046
				}
3047
				$userkeyprefix = (strtolower($key['type']) == 'eap') ? 'eap' : 'ike';
3048
				$scconf['secrets'][$userkeyprefix . '-' . $suffix++] = array(
3049
					'secret' => '0s' . base64_encode(trim($key['pre-shared-key'])),
3050
					'id-0' => $key['ident'],
3051
				);
3052
			}
3053
		}
3054
		unset($key);
3055
	}
3056
	return;
3057
}
3058

    
3059
/****f* ipsec/ipsec_configure
3060
 * NAME
3061
 *   ipsec_configure - Configure IPsec
3062
 * INPUTS
3063
 *   $restart: Boolean (default false), whether or not to restart the IPsec
3064
 *             daemons.
3065
 * RESULT
3066
 *   IPsec-related configuration files are written, daemon is started or stopped
3067
 *   appropriately.
3068
 ******/
3069
function ipsec_configure($restart = false, $filterdns_restart = false) {
3070
	global $aggressive_mode_psk,
3071
		$filterdns_list, $g, $ifacesuse, $ipsec_idhandling, $ipsec_log_cats,
3072
		$ipsec_log_sevs, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs,
3073
		$ipseccfg, $mobile_ipsec_auth, $natfilterrules, $p1_ealgos,
3074
		$p2_ealgos, $rgmap, $sa, $sn, $scconf, $tunnels, $mobile_configured,
3075
		$ipsec_vti_cleanup_ifs, $conn_defaults, $pool_addrs;
3076

    
3077
	/* service may have been enabled, disabled, or otherwise changed in a
3078
	 *way requiring rule updates */
3079
	filter_configure();
3080

    
3081
	if (!ipsec_enabled()) {
3082
		/* IPsec is disabled */
3083
		/* Stop charon */
3084
		mwexec("/usr/local/sbin/strongswanrc stop");
3085
		/* Stop dynamic monitoring */
3086
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3087
		/* Wait for process to die */
3088
		sleep(2);
3089
		/* Stop PC/SC Smart Card Services */
3090
		killbyname("pcscd");
3091
		/* Shutdown enc0 interface*/
3092
		mwexec("/sbin/ifconfig enc0 down");
3093
		ipsec_gre_default_mtu(); 
3094
		return 0;
3095
	} else {
3096
		/* Startup enc0 interface */
3097
		mwexec("/sbin/ifconfig enc0 up");
3098
		/* PC/SC daemon must be started before strongswan */
3099
		if (config_path_enabled('ipsec', 'pkcs11support') && !isvalidproc("pcscd")) {
3100
			if (is_platform_booting()) {
3101
				echo gettext("Starting PC/SC Smart Card Services...");
3102
			}
3103
			mwexec_bg("/usr/local/sbin/pcscd");
3104
			if (is_platform_booting()) {
3105
				echo gettext("done.\n");
3106
			}
3107
		} elseif (!config_path_enabled('ipsec', 'pkcs11support') && isvalidproc("pcscd")) {
3108
			/* strongswan must be stopped first, otherwise it will flood the logs */
3109
			mwexec("/usr/local/sbin/strongswanrc stop");
3110
			killbyname("pcscd");
3111
		}
3112
	}
3113

    
3114
	if (is_platform_booting()) {
3115
		echo gettext("Configuring IPsec VPN... ");
3116
	}
3117

    
3118
	$ipsecstartlock = lock('ipsec', LOCK_EX);
3119

    
3120
	/* Prepare automatic ping_hosts.sh data */
3121
	unlink_if_exists("{$g['vardb_path']}/ipsecpinghosts");
3122
	touch("{$g['vardb_path']}/ipsecpinghosts");
3123
	$ipsecpinghostsactive = false;
3124

    
3125
	/* Populate convenience variables */
3126
	$syscfg = config_get_path('system');
3127
	$ipseccfg = config_get_path('ipsec', []);
3128
	$a_phase1 = config_get_path('ipsec/phase1', []);
3129
	$a_phase2 = config_get_path('ipsec/phase2', []);
3130

    
3131
	$mobile_configured = false;
3132

    
3133

    
3134
	/* Setup a single structured array to process, to avoid repeatedly
3135
	 * looping through the arrays to locate entries later. */
3136
	$tunnels = array();
3137
	foreach ($a_phase1 as $p1) {
3138
		if (empty($p1)) {
3139
			continue;
3140
		}
3141
		if (isset($p1['mobile']) && !isset($p1['disabled'])) {
3142
			$mobile_configured = true;
3143
		}
3144
		$tunnels[$p1['ikeid']] = $p1;
3145
		$tunnels[$p1['ikeid']]['p2'] = array();
3146
	}
3147
	foreach ($a_phase2 as $p2) {
3148
		$tunnels[$p2['ikeid']]['p2'][] = $p2;
3149
	}
3150

    
3151
	$ipsec_vti_cleanup_ifs = array();
3152
	$rgmap = array();
3153
	$filterdns_list = array();
3154
	$aggressive_mode_psk = false;
3155
	$mobile_ipsec_auth = "";
3156
	$ifacesuse = array();
3157
	$natfilterrules = false;
3158

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

    
3162
	/* Build a list of all IPsec interfaces configured on the firewall at the OS level */
3163
	refresh_gateways(); // make sure automatic VTI gateways are created
3164
	foreach (get_interface_arr() as $thisif) {
3165
		if (substr($thisif, 0, 5) == "ipsec") {
3166
			$ipsec_vti_cleanup_ifs[] = $thisif;
3167
		}
3168
	}
3169
	/* Create directory structure for IPsec */
3170
	ipsec_create_dirs();
3171
	/* Setup gateways and interfaces */
3172
	ipsec_setup_gwifs();
3173
	/* Setup and write strongswan.conf */
3174
	ipsec_setup_strongswan();
3175
	/* Start Global Connection default values */
3176
	$conn_defaults = array();
3177
	/* Fragmentation is on for everyone */
3178
	$conn_defaults['fragmentation'] = "yes";
3179
	/* Default to 'replace' for unique IDs (was 'yes' in ipsec.conf previously) */
3180
	$conn_defaults['unique'] = 'replace';
3181
	/* If the configuration has a valid alternate value for unique ID handling,
3182
	 * use it instead. */
3183
	if (array_key_exists(config_get_path('ipsec/uniqueids', ""), $ipsec_idhandling)) {
3184
		$conn_defaults['unique'] = config_get_path('ipsec/uniqueids');
3185
	}
3186
	/* Disable ipcomp for now. redmine #6167
3187
	if (isset($config['ipsec']['compression'])) {
3188
		$conn_defaults['compress'] = "yes";
3189
	}
3190
	set_single_sysctl('net.inet.ipcomp.ipcomp_enable', (isset($config['ipsec']['compression'])) ? 1 : 0);
3191
	*/
3192
	/* End Global Connection Defaults */
3193

    
3194
	/* Start swanctl configuration (scconf) */
3195
	$scconf = array();
3196
	$scconf[] = "# This file is automatically generated. Do not edit";
3197
	$scconf['connections'] = array();
3198
	/* Setup IPsec bypass */
3199
	ipsec_setup_bypass();
3200
	/* Setup connections */
3201
	ipsec_setup_tunnels();
3202
	$scconf['pools'] = array();
3203
	if ($mobile_configured) {
3204
		/* Setup mobile address pools */
3205
		ipsec_setup_pools();
3206
		/* Setup per-user pools */
3207
		ipsec_setup_userpools();
3208
	}
3209
	/* Setup secret data */
3210
	$scconf['secrets'] = array();
3211
	ipsec_setup_secrets();
3212

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

    
3215
	/* Clean up unused VTI interfaces */
3216
	foreach ($ipsec_vti_cleanup_ifs as $cleanif) {
3217
		if (does_interface_exist($cleanif)) {
3218
			mwexec("/sbin/ifconfig " . escapeshellarg($cleanif) . " destroy", false);
3219
		}
3220
	}
3221

    
3222
	/* set default MTU to 1400 for GRE over IPsec, otherwise to 1476 */
3223
	ipsec_gre_default_mtu(); 
3224

    
3225
	/* Manage process */
3226
	if ($restart === true) {
3227
		mwexec_bg("/usr/local/sbin/strongswanrc restart", false);
3228
	} else {
3229
		if (isvalidpid("{$g['varrun_path']}/charon.pid")) {
3230
			mwexec_bg("/usr/local/sbin/strongswanrc reload", false);
3231
		} else {
3232
			mwexec_bg("/usr/local/sbin/strongswanrc start", false);
3233
		}
3234
	}
3235

    
3236
	// Run ping_hosts.sh once if it's enabled to avoid wait for minicron
3237
	if ($ipsecpinghostsactive) {
3238
		mwexec_bg("/usr/local/bin/ping_hosts.sh");
3239
	}
3240

    
3241
	if ($natfilterrules == true) {
3242
		filter_configure();
3243
	}
3244
	/* start filterdns, if necessary */
3245
	if (count($filterdns_list) > 0) {
3246
		$interval = 60;
3247
		if (!empty($ipseccfg['dns-interval']) && is_numeric($ipseccfg['dns-interval'])) {
3248
			$interval = $ipseccfg['dns-interval'];
3249
		}
3250

    
3251
		$hostnames = "";
3252
		array_unique($filterdns_list);
3253
		foreach ($filterdns_list as $hostname) {
3254
			$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload ipsecdns\"'\n";
3255
		}
3256
		file_put_contents("{$g['varetc_path']}/ipsec/filterdns-ipsec.hosts", $hostnames);
3257
		unset($hostnames);
3258

    
3259
		if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid")) {
3260
			if ($filterdns_restart) {
3261
				killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3262
				sleep(2);
3263
				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");
3264
			} else {
3265
				sigkillbypid("{$g['varrun_path']}/filterdns-ipsec.pid", "HUP");
3266
			}
3267
		} else {
3268
			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");
3269
		}
3270
	} else {
3271
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3272
		@unlink("{$g['varrun_path']}/filterdns-ipsec.pid");
3273
	}
3274

    
3275
	if (is_platform_booting()) {
3276
		echo "done\n";
3277
	}
3278

    
3279
	unlock($ipsecstartlock);
3280
	return count($filterdns_list);
3281
}
3282

    
3283
function ipsec_gre_default_mtu() {
3284
	foreach (config_get_path('interfaces', []) as $if => $ifdetail) { 
3285
		if (interface_is_type($ifdetail['if'], 'gre') && !isset($ifdetail['mtu'])) {
3286
			if (is_greipsec($ifdetail['if'])) {
3287
				set_interface_mtu($ifdetail['if'], 1400);
3288
			} else {
3289
				set_interface_mtu($ifdetail['if'], 1476);
3290
			}
3291
		}
3292
	}
3293
}
3294

    
3295
/* Return the larger of derived SA rekey time and reauth time */
3296
function ipsec_get_renewmax($entry) {
3297
	if (empty($entry) || !is_array($entry)) {
3298
		return 0;
3299
	}
3300
	return max(ipsec_get_rekey_time($entry), ipsec_get_reauth_time($entry));
3301
}
3302

    
3303
/* Determine the life time of an SA entry (Hard upper total time limit for SA before it is removed) */
3304
function ipsec_get_life_time($entry) {
3305
	if (empty($entry) || !is_array($entry)) {
3306
		return 0;
3307
	}
3308
	/* Use a hardcoded value if present in the configuration */
3309
	if ($entry['lifetime'] > 0) {
3310
		return $entry['lifetime'];
3311
	}
3312
	/* If rekey or reauth are enabled, attempt to derive a lifetime from one of those */
3313
	$renewmax = ipsec_get_renewmax($entry);
3314
	if ($renewmax > 0) {
3315
		return intval($renewmax / 0.9);
3316
	}
3317
	/* To reach here, rekey_time and lifetime are both 0 which is invalid
3318
	 * Default to 16000 for p1 and 4000 for p2 */
3319
	if ($entry['iketype']) {
3320
		return 16000;
3321
	} else {
3322
		return 4000;
3323
	}
3324
}
3325

    
3326
/* Determine the rekey time of an SA entry (Time at which to rekey IKEv2 or Child SA entries) */
3327
function ipsec_get_rekey_time($entry) {
3328
	if (empty($entry) || !is_array($entry)) {
3329
		return 0;
3330
	}
3331
	/* Use a hardcoded value if present in the configuration */
3332
	if (strlen($entry['rekey_time'])) {
3333
		/* Check via strlen since 0 is a valid value */
3334
		return $entry['rekey_time'];
3335
	} elseif ($entry['lifetime'] > 0) {
3336
		/* If rekey_time is empty and lifetime is non-zero, use 90% lifetime */
3337
		return intval($entry['lifetime'] * 0.9);
3338
	}
3339
	/* To reach here, rekey_time and lifetime are empty
3340
	 * Default to 14400 for p1 and 3600 for p2 */
3341
	if ($entry['iketype']) {
3342
		return 14400;
3343
	} else {
3344
		return 3600;
3345
	}
3346
}
3347

    
3348
/* Determine the reauth time of an SA entry (IKE SA tear-down/reauthenticate) */
3349
function ipsec_get_reauth_time($entry) {
3350
	if (empty($entry) || !is_array($entry)) {
3351
		return 0;
3352
	}
3353
	/* Use a hardcoded value if present in the configuration */
3354
	if (strlen($entry['reauth_time'])) {
3355
		/* Check via strlen since 0 is a valid value */
3356
		return $entry['reauth_time'];
3357
	} elseif ($entry['lifetime'] > 0) {
3358
		/* If reauth_time is empty and lifetime is non-zero,
3359
		 * use 90% lifetime for IKEv1, disable for IKEv2/auto */
3360
		if ($entry['iketype'] == 'ikev1') {
3361
			return intval($entry['lifetime'] * 0.9);
3362
		} else {
3363
			return 0;
3364
		}
3365
	}
3366
	/* To reach here, rekey_time and lifetime are empty
3367
	 * Default to disabled (0) */
3368
	return 0;
3369
}
3370

    
3371
/* Determine the over time of an SA entry (Hard upper IKE SA time limit, relative to rekey/reauth time) */
3372
function ipsec_get_over_time($entry) {
3373
	if (empty($entry) || !is_array($entry)) {
3374
		return 0;
3375
	}
3376
	/* Automatically derive the value for rand_time */
3377
	$lifetime = ipsec_get_life_time($entry);
3378
	$renewmax = ipsec_get_renewmax($entry);
3379
	if (($lifetime > 0) && ($renewmax > 0)) {
3380
		/* If life time and rekey/reauth time both have values, subtract to get rand time */
3381
		return $lifetime - $renewmax;
3382
	} elseif ($lifetime > 0) {
3383
		/* If only life time has a value, use 10% of that */
3384
		return intval($lifetime * 0.1);
3385
	} elseif ($renewmax > 0) {
3386
		/* If only rekey/reauth time has a value, use 10% of that */
3387
		return intval($renewmax * 0.1);
3388
	}
3389
	/* No value can be determined, default to 0 */
3390
	return 0;
3391
}
3392

    
3393
/* Determine the rand time of an SA entry (random value subtracted from renewal time to prevent collisions) */
3394
function ipsec_get_rand_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['rand_time'])) {
3400
		/* Check via strlen since 0 is a valid value */
3401
		return $entry['rand_time'];
3402
	}
3403
	/* Logic to automatically determine rand time is identical to calculating over time */
3404
	return ipsec_get_over_time($entry);
3405
}
3406

    
3407
/* Delete a list of IPsec P1 and related P2 entries
3408
 * Takes no action if any of the passed items are assigned VTI interfaces
3409
 * Caller must write the config after if the function succeeded.
3410
 */
3411
function delete_p1_and_children($p1list = []) {
3412
	global $input_errors;
3413

    
3414
	if (!is_array($p1list) || !count($p1list)) {
3415
		/* Nothing to do */
3416
		return 0;
3417
	}
3418
	$delp1ids = [];
3419
	$delp2ids = [];
3420

    
3421
	/* Check for relevant P1 and P2 entries to remove */
3422
	foreach ($p1list as $p1idx) {
3423
		$p1_has_vti = false;
3424
		$ikeid = config_get_path('ipsec/phase1/' . $p1idx . '/ikeid');
3425

    
3426
		/* Find relevant P2 entries */
3427
		foreach (config_get_path('ipsec/phase2', []) as $p2idx => $p2) {
3428
			/* Flag and remove invalid entries */
3429
			if (empty($p2) || !is_array($p2)) {
3430
				$delp2ids[] = $p2idx;
3431
				continue;
3432
			}
3433
			if ($p2['ikeid'] == $ikeid) {
3434
				if (is_interface_ipsec_vti_assigned($p2)) {
3435
					/* This entry is active VTI and cannot be deleted! */
3436
					$p1_has_vti = true;
3437
				} else {
3438
					$delp2ids[] = $p2idx;
3439
				}
3440
			}
3441
		}
3442

    
3443
		if ($p1_has_vti) {
3444
			$input_errors[] = gettext("Cannot delete a Phase 1 which contains an active VTI Phase 2 with an interface assigned. Remove the interface assignment before deleting this P1.");
3445
		} else {
3446
			$delp1ids[] = $p1idx;
3447
		}
3448
	}
3449

    
3450
	/* If there are errors, take no actions */
3451
	if (!empty($input_errors)) {
3452
		return 0;
3453
	}
3454

    
3455
	/* Remove P1 entries */
3456
	foreach ($delp1ids as $delp1) {
3457
		/* remove static route if interface is not WAN */
3458
		if (config_get_path('ipsec/phase1/' . $delp1 . '/interface') <> "wan") {
3459
			route_del(config_get_path('ipsec/phase1/' . $delp1 . '/remote-gateway'));
3460
		}
3461
		config_del_path('ipsec/phase1/' . $delp1);
3462
	}
3463
	/* Remove P2 entries */
3464
	foreach ($delp2ids as $dp2idx) {
3465
		config_del_path('ipsec/phase2/' . $dp2idx);
3466
	}
3467

    
3468
	/* Return the total number of entries removed. */
3469
	return count($delp1ids) + count($delp2ids);
3470

    
3471
}
3472

    
3473
?>
(26-26/61)