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-2023 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
	init_config_arr(array('ipsec', 'phase1'));
291
	foreach (config_get_path('ipsec/phase1', []) as $ph1ent) {
292
		if ($ikeid == $ph1ent['ikeid']) {
293
			return true;
294
		}
295
	}
296
	return false;
297
}
298

    
299
function ipsec_ikeid_next() {
300
	$ikeid = 1;
301
	init_config_arr(array('ipsec', 'phase1'));
302
	$ipsecikeid = lock('ipsecikeids', LOCK_EX);
303
	$ikeids = array();
304

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

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

    
316
	unlock($ipsecikeid);
317
	return $ikeid;
318
}
319

    
320
function ipsec_new_reqid() {
321
	init_config_arr(array('ipsec', 'phase2'));
322
	$ipsecreqid = lock('ipsecreqids', LOCK_EX);
323
	$keyids = array();
324
	$keyid = 1;
325

    
326
	foreach (config_get_path('ipsec/phase2', []) as $ph2) {
327
		$keyids[$ph2['reqid']] = $ph2['reqid'];
328
	}
329

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

    
337
	unlock($ipsecreqid);
338
	return $keyid;
339
}
340

    
341
function ipsec_get_phase1($ikeid) {
342
	init_config_arr(array('ipsec', 'phase1'));
343

    
344
	foreach (config_get_path('ipsec/phase1', []) as $p1) {
345
		if ($p1['ikeid'] == $ikeid) {
346
			return $p1;
347
		}
348
	}
349
}
350

    
351
function ipsec_get_p1_descr($ikeid) {
352
	init_config_arr(array('ipsec', 'phase1'));
353
	$p1 = ipsec_get_phase1($ikeid);
354
	return (!empty($p1['descr'])) ? $p1['descr'] : '';
355
}
356

    
357
/*
358
 * Return copy of phase1 for a given phase2
359
 */
360
function ipsec_lookup_phase1($p2, &$p1_disabled) {
361
	init_config_arr(array('ipsec', 'phase1'));
362

    
363
	foreach (config_get_path('ipsec/phase1', []) as $p1) {
364
		if ($p1['ikeid'] == $p2['ikeid']) {
365
			$p1_disabled = $p1['disabled'];
366
			return true;
367
		}
368
	}
369

    
370
	return false;
371
}
372

    
373
function ipsec_get_phase2($reqid) {
374
	init_config_arr(array('ipsec', 'phase2'));
375

    
376
	foreach (config_get_path('ipsec/phase2', []) as $p2) {
377
		if ($p2['reqid'] == $reqid) {
378
			return $p2;
379
		}
380
	}
381
}
382

    
383
function ipsec_get_phase2_by_ikeid($ikeid) {
384
	init_config_arr(array('ipsec', 'phase2'));
385
	$results = array();
386
	foreach (config_get_path('ipsec/phase2', []) as $p2) {
387
		if ($p2['ikeid'] == $ikeid) {
388
			$results[] = $p2;
389
		}
390
	}
391
	return $results;
392
}
393

    
394
function ipsec_get_number_of_phase2($ikeid) {
395
	return count(ipsec_get_phase2_by_ikeid($ikeid));
396
}
397

    
398
/* Return a nested hash with P1 indexed by ikeid and P2 indexed by reqid */
399
function ipsec_map_config_by_id() {
400
	init_config_arr(array('ipsec', 'phase1'));
401
	init_config_arr(array('ipsec', 'phase2'));
402
	$map = array();
403

    
404
	foreach (config_get_path('ipsec/phase1', []) as $p1) {
405
		$map[$p1['ikeid']] = array();
406
		$map[$p1['ikeid']]['p1'] = $p1;
407
	}
408
	foreach (config_get_path('ipsec/phase2', []) as $p2) {
409
		if (!is_array($map[$p2['ikeid']]['p2'])) {
410
			$map[$p2['ikeid']]['p2'] = array();
411
		}
412
		$map[$p2['ikeid']]['p2'][$p2['reqid']] = $p2;
413
	}
414

    
415
	return $map;
416
}
417

    
418
function ipsec_conid($p1 = null, $p2 = null) {
419
	global $ipsec_conid_prefix, $ipsec_conid_separator;
420

    
421
	$conid = NULL;
422
	$have_p1 = (!empty($p1) && is_array($p1));
423
	$have_p2 = (!empty($p2) && is_array($p2));
424

    
425
	if (!$have_p1 && $have_p2) {
426
		$p1 = ipsec_get_phase1($p2['ikeid']);
427
	}
428

    
429
	if (isset($p1['mobile'])) {
430
		return "{$ipsec_conid_prefix}-mobile";
431
	}
432

    
433
	$conid = "{$ipsec_conid_prefix}{$p1['ikeid']}";
434

    
435
	if ($have_p2) {
436
		/* IKEv1 or IKEv2+Split Connections use separate P2 entries
437
		 * so add reqid to ID */
438
		if (($p1['iketype'] != 'ikev2') || isset($p1['splitconn'])) {
439
			$conid .= "{$ipsec_conid_separator}{$p2['reqid']}";
440
		}
441
	}
442

    
443
	return $conid;
444
}
445

    
446
function ipsec_id_by_conid($conid) {
447
	global $ipsec_conid_prefix, $ipsec_conid_separator;
448

    
449
	if ($conid == "{$ipsec_conid_prefix}-mobile") {
450
		init_config_arr(array('ipsec', 'phase1'));
451
		foreach (config_get_path('ipsec/phase1', []) as $p1) {
452
			if (isset($p1['mobile'])) {
453
				$conid = $ipsec_conid_prefix . $p1['ikeid'];
454
			}
455
		}
456
	}
457

    
458
	if (substr($conid, 0, strlen($ipsec_conid_prefix)) == $ipsec_conid_prefix) {
459
		$conid = substr($conid, strlen($ipsec_conid_prefix));
460
	}
461
	$parts = explode($ipsec_conid_separator, $conid);
462
	if (count($parts) == 1) {
463
		$parts[1] = NULL;
464
	}
465
	return array($parts[0], $parts[1]);
466
}
467

    
468
/*
469
 * Return phase1 local address
470
 */
471
function ipsec_get_phase1_src(& $ph1ent, $gateways_status = false) {
472
	global $interface_ip_arr_cache;
473
	global $interface_sn_arr_cache;
474
	if ($ph1ent['interface']) {
475
		/* get_interface_ip() already calls get_failover_interface so no need for special handling */
476
		$if = $ph1ent['interface'];
477
	} else {
478
		$if = "wan";
479
	}
480

    
481
	/* Fetch gateway status if not passed */
482
	if (!is_array($gateways_status)) {
483
		$gateways_status = return_gateways_status(true);
484
	}
485

    
486
	$ifips = array();
487
	if (in_array($ph1ent['protocol'], array('inet', 'both'))) {
488
		$ip4 = get_interface_ip($if, $gateways_status);
489
		if (!empty($ip4)) {
490
			$ifips[] = $ip4;
491
		}
492
	}
493

    
494
	if (in_array($ph1ent['protocol'], array('inet6', 'both'))) {
495
		/* get correct interface name for 6RD/6to4 interfaces
496
		 * see https://redmine.pfsense.org/issues/11643 */
497
		if (is_stf_interface($ph1ent['interface'])) {
498
			$ip6 = get_interface_ipv6($ph1ent['interface'], false, false, $gateways_status);
499
		} else {
500
			$ip6 = get_interface_ipv6($if, false, false, $gateways_status);
501
		}
502
		if (!empty($ip6)) {
503
			$ifips[] = $ip6;
504
		}
505
	}
506

    
507
	return implode(',', $ifips);
508
}
509

    
510
/*
511
 * Return phase1 local address
512
 */
513
function ipsec_get_phase1_dst(& $ph1ent) {
514
	global $g;
515

    
516
	if (empty($ph1ent['remote-gateway'])) {
517
		return false;
518
	}
519
	$rg = $ph1ent['remote-gateway'];
520
	if (!is_ipaddr($rg)) {
521
		if (!platform_booting()) {
522
			$result = resolve_retry($rg, $ph1ent['protocol']);
523
			if (!empty($result)) {
524
				return $result;
525
			} else {
526
				return false;
527
			}
528
		}
529
	}
530
	if (!is_ipaddr($rg)) {
531
		return false;
532
	}
533

    
534
	return $rg;
535
}
536

    
537
/*
538
 * Return phase2 idinfo in cidr format
539
 */
540
function ipsec_idinfo_to_cidr(& $idinfo, $addrbits = false, $mode = "") {
541
	switch ($idinfo['type']) {
542
		case "address":
543
			if ($addrbits) {
544
				if ($mode == "tunnel6") {
545
					return $idinfo['address']."/128";
546
				} elseif (($mode == "vti") && is_ipaddrv4($idinfo['address'])) {
547
					return $idinfo['address']."/30";
548
				} elseif (($mode == "vti") && is_ipaddrv6($idinfo['address'])) {
549
					return $idinfo['address']."/64";
550
				} else {
551
					return $idinfo['address']."/32";
552
				}
553
			} else {
554
				return $idinfo['address'];
555
			}
556
			break; /* NOTREACHED */
557
		case "network":
558
			return "{$idinfo['address']}/{$idinfo['netbits']}";
559
			break; /* NOTREACHED */
560
		case "none":
561
		case "mobile":
562
			return '0.0.0.0/0';
563
			break; /* NOTREACHED */
564
		default:
565
			if (empty($mode) && !empty($idinfo['mode'])) {
566
				$mode = $idinfo['mode'];
567
			}
568

    
569
			if ($mode == "tunnel6") {
570
				$address = get_interface_ipv6($idinfo['type']);
571
				$netbits = get_interface_subnetv6($idinfo['type']);
572
				$address = gen_subnetv6($address, $netbits);
573
				return "{$address}/{$netbits}";
574
			} else {
575
				$address = get_interface_ip($idinfo['type']);
576
				$netbits = get_interface_subnet($idinfo['type']);
577
				$address = gen_subnet($address, $netbits);
578
				return "{$address}/{$netbits}";
579
			}
580
			break; /* NOTREACHED */
581
	}
582
}
583

    
584
/*
585
 * Return phase2 idinfo in address/netmask format
586
 */
587
function ipsec_idinfo_to_subnet(& $idinfo, $addrbits = false) {
588
	switch ($idinfo['type']) {
589
		case "address":
590
			if ($addrbits) {
591
				if ($idinfo['mode'] == "tunnel6") {
592
					return $idinfo['address']."/128";
593
				} else {
594
					return $idinfo['address']."/255.255.255.255";
595
				}
596
			} else {
597
				return $idinfo['address'];
598
			}
599
			break; /* NOTREACHED */
600
		case "none":
601
		case "network":
602
			return $idinfo['address']."/".gen_subnet_mask($idinfo['netbits']);
603
			break; /* NOTREACHED */
604
		case "mobile":
605
			return "0.0.0.0/0";
606
			break; /* NOTREACHED */
607
		default:
608
			if ($idinfo['mode'] == "tunnel6") {
609
				$address = get_interface_ipv6($idinfo['type']);
610
				$netbits = get_interface_subnetv6($idinfo['type']);
611
				$address = gen_subnetv6($address, $netbits);
612
				return $address."/".$netbits;
613
			} else {
614
				$address = get_interface_ip($idinfo['type']);
615
				$netbits = get_interface_subnet($idinfo['type']);
616
				$address = gen_subnet($address, $netbits);
617
				return $address."/".$netbits;
618
			}
619
			break; /* NOTREACHED */
620
	}
621
}
622

    
623
/*
624
 *  Return phase2 idinfo in text format
625
 */
626
function ipsec_idinfo_to_text(& $idinfo) {
627
	switch ($idinfo['type']) {
628
		case "address":
629
			return $idinfo['address'];
630
			break; /* NOTREACHED */
631
		case "network":
632
			return $idinfo['address']."/".$idinfo['netbits'];
633
			break; /* NOTREACHED */
634
		case "mobile":
635
			return gettext("Mobile Client");
636
			break; /* NOTREACHED */
637
		case "none":
638
			return gettext("None");
639
			break; /* NOTREACHED */
640
		default:
641
			if (!(empty(config_get_path('interfaces/' . $idinfo['type'])))) {
642
				return convert_friendly_interface_to_friendly_descr($idinfo['type']);
643
			} else {
644
				return strtoupper($idinfo['type']);
645
			}
646
			break; /* NOTREACHED */
647
	}
648
}
649

    
650
/*
651
 * Wrapper to call pfSense_ipsec_list_sa() when IPsec is enabled
652
 */
653
function ipsec_list_sa() {
654
	if (ipsec_enabled()) {
655
		return pfSense_ipsec_list_sa();
656
	}
657
	return array();
658
}
659

    
660
function ipsec_status() {
661
	$cmap = ipsec_map_config_by_id();
662
	$status = ipsec_list_sa();
663

    
664
	/*
665
	Start:
666
	$cmap[$ikeid]['p1'] => Phase 1 config
667
	$cmap[$ikeid]['p2'] => Array of P2 configs indexed by reqid
668

    
669
	End:
670
	$cmap[$ikeid]['p1']['status'] => Array of IKE SA entries and child SAs for this P1
671
	$cmap[$ikeid]['p1']['connected'] => true/false if the P1 is connected
672
	$cmap[$ikeid]['p2'][$reqid]['connected'] => true/false if the P2 is connected
673
		If non-split IKEv2 then mark all as 'true'
674
	*/
675

    
676
	if (!is_array($status)) {
677
		$status = array();
678
	}
679

    
680
	$cmap['connected'] = array(
681
		/* List of connected P1 conid entries (excluding mobile) */
682
		'p1' => array(),
683
		/* List of connected P2 conid entries (excluding mobile) */
684
		'p2' => array(),
685
	);
686
	$cmap['disconnected'] = array(
687
		/* List of disconnected P1 conid entries (excluding mobile) */
688
		'p1' => array(),
689
		/* List of disconnected P2 conid entries (excluding mobile) */
690
		'p2' => array(),
691
	);
692

    
693
	/* First level of array has IKE SA content */
694
	foreach ($status as $ikesa) {
695
		/* If the con-id isn't there it must not be a proper entry */
696
		if (!isset($ikesa['con-id'])) {
697
			continue;
698
		}
699

    
700
		/* Mark this IKE ID as connected and drop the status info underneath the P1 config */
701
		list($ikeid, $reqid) = ipsec_id_by_conid($ikesa['con-id']);
702
		if (!array_key_exists($ikeid, $cmap)) {
703
			// Doesn't match known tunnel
704
			$cmap['connected']['p1'][$ikesa['con-id']] = $ikesa['con-id'];
705
		} else {
706
			/* Track this IKE ID in the connection list */
707
			$cmap['connected']['p1'][$ikeid] = $ikesa['con-id'];
708
			/* Copy the status data. Use an array since it could be connected multiple times. */
709
			if (!is_array($cmap[$ikeid]['status'])) {
710
				$cmap[$ikeid]['status'] = array();
711
			}
712
			$cmap[$ikeid]['status'][] = $ikesa;
713
			$cmap[$ikeid]['p1']['connected'] = true;
714
		}
715

    
716
		/* If there are child SAs under this IKE entry, process them */
717
		if (array_key_exists('child-sas', $ikesa) &&
718
		    is_array($ikesa['child-sas'])) {
719
			foreach ($ikesa['child-sas'] as $childid => $childsa) {
720
				/* Mark this reqid as connected */
721
				list($childikeid, $childreqid) = ipsec_id_by_conid($childsa['name']);
722

    
723
				if ($childreqid != null) {
724
					if (!isset($cmap[$childikeid]['p2'][$childreqid]['mobile'])) {
725
						$cmap['connected']['p2'][$childreqid] = $childsa['name'];
726
						$cmap[$childikeid]['p2'][$childreqid]['connected'] = true;
727
					}
728
				} else {
729
					/* If this is IKEv2 w/o Split, mark all reqids for the P1 as connected */
730
					if ($cmap[$childikeid]['p1']['iketype'] == 'ikev2' &&
731
					    !isset($cmap[$childikeid]['p1']['splitconn'])) {
732
						foreach ($cmap[$ikeid]['p2'] as $p2) {
733
							if (isset($p2['mobile'])) {
734
								continue;
735
							}
736
							$cmap['connected']['p2'][$p2['reqid']] = $childsa['name'];
737
							$cmap[$childikeid]['p2'][$p2['reqid']]['connected'] = true;
738
						}
739
					}
740
				}
741
			}
742
		}
743
	}
744
	if (is_array($cmap)) {
745
		foreach ($cmap as $k => $tunnel) {
746
			if (in_array($k, array('connected', 'disconnected')) ||
747
			    (!array_key_exists('p1', $tunnel) ||
748
			    isset($tunnel['p1']['disabled'])) ||
749
			    isset($tunnel['p1']['mobile'])) {
750
				continue;
751
			}
752
			if (!array_key_exists($tunnel['p1']['ikeid'], $cmap['connected']['p1'])) {
753
				$cmap['disconnected']['p1'][$tunnel['p1']['ikeid']] = ipsec_conid($tunnel['p1']);
754
			}
755
			if (is_array($tunnel['p2'])) {
756
				foreach ($tunnel['p2'] as $p2) {
757
					if (isset($p2['mobile'])) {
758
						continue;
759
					}
760
					if (!array_key_exists($p2['reqid'], $cmap['connected']['p2'])) {
761
						/* This P2 is not connected */
762
						$cmap['disconnected']['p2'][$p2['reqid']] = ipsec_conid($p1['p1'], $p2);
763
					}
764
				}
765
			}
766
		}
767
	}
768
	return $cmap;
769
}
770

    
771
function ipsec_status_button($req, $act, $type, $conid, $uniqueid, $full) {
772
	$btn = '<a href="';
773
	if ($act == 'disconnect') {
774
		$buttonclass = ($type == 'ike') ? 'danger' : 'warning';
775
		$title = gettext("Disconnect");
776
		$icon = 'trash';
777
	} else {
778
		$buttonclass = 'success';
779
		$title = gettext("Connect");
780
		$icon = 'sign-in';
781
	}
782
	if ($full) {
783
		$linkclass = 'btn btn-xs btn-' . htmlspecialchars($buttonclass);
784
	} else {
785
		$linkclass = '';
786
	}
787

    
788
	$title .= " ";
789
	switch ($type) {
790
		case 'all':
791
			$title .= gettext("P1 and P2s");
792
			break;
793
		case 'child':
794
			$title .= gettext("P2");
795
			break;
796
		case 'ike':
797
		default:
798
			$title .= gettext("P1");
799
			break;
800
	}
801

    
802
	if ($req == 'post') {
803
		$btn .= 'status_ipsec.php?act=' . htmlspecialchars($act) .
804
			'&amp;type=' . htmlspecialchars($type) .
805
			'&amp;conid=' . htmlspecialchars($conid);
806
		if (!empty($uniqueid)) {
807
			$btn .= '&amp;uniqueid=' . htmlspecialchars($uniqueid);
808
		}
809
	} else {
810
		$btn .= '#" id="' . 'ipsecstatus-' .
811
			htmlspecialchars($act) . '-' .
812
			htmlspecialchars($type) . '-' .
813
			htmlspecialchars($conid);
814
		if (!empty($uniqueid)) {
815
			$btn .= '-' . htmlspecialchars($uniqueid);
816
		}
817
	}
818

    
819
	$btn .= '"';
820
	if ($full) {
821
		$btn .= ' class="' . htmlspecialchars($linkclass) . '"';
822
	}
823
	$btn .= ' title="' . htmlspecialchars($title) . '"';
824

    
825
	if ($req == 'post') {
826
		$btn .= ' usepost';
827
	}
828
	$btn .= '>';
829
	$btn .= '<i class="fa fa-' . htmlspecialchars($icon);
830
	if ($req == 'post') {
831
		$btn .= ' icon-embed-btn';
832
	}
833
	$btn .= '"></i>';
834

    
835
	if ($full) {
836
		$btn .= ' ' . htmlspecialchars($title);
837
	}
838
	$btn .= '</a>';
839
	return $btn;
840
}
841

    
842
function ipsec_initiate($type = 'ike', $p1 = null, $p2 = null) {
843
	return ipsec_initiate_by_conid($type, ipsec_conid($p1, $p2));
844
}
845

    
846
function ipsec_initiate_by_conid($type, $conid) {
847
	if (empty($conid)) {
848
		return false;
849
	}
850
	switch ($type) {
851
		case 'all':
852
			/* Find relevant P2s and initiate all of them */
853
			$cmap = ipsec_map_config_by_id();
854
			list($ikeid, $reqid) = ipsec_id_by_conid($conid);
855
			if (array_key_exists($ikeid, $cmap)) {
856
				if ($cmap[$ikeid]['p1']['iketype'] == 'ikev2' && !isset($cmap[$ikeid]['p1']['splitconn'])) {
857
					/* IKEv2 without split only has one P2, named the same as the P1 */
858
					ipsec_initiate_by_conid('child', ipsec_conid($cmap[$ikeid]['p1']));
859
				} else {
860
					foreach ($cmap[$ikeid]['p2'] as $p2) {
861
						ipsec_initiate_by_conid('child', ipsec_conid($cmap[$ikeid]['p1'], $p2));
862
					}
863
				}
864
			}
865
			break;
866
		case 'ike':
867
		case 'child':
868
			mwexec_bg("/usr/local/sbin/swanctl --initiate --timeout 5 " . escapeshellarg('--' . $type) . " " . escapeshellarg($conid));
869
			break;
870
		default:
871
			/* Do nothing. Invalid type. */
872
			break;
873
	}
874
	return true;
875
}
876

    
877
function ipsec_terminate($type = 'ike', $p1 = null, $p2 = null, $uniqueid = null) {
878
	return ipsec_terminate_by_conid($type, ipsec_conid($p1, $p2), $uniqueid);
879
}
880

    
881
function ipsec_terminate_by_conid($type = 'ike', $conid = null, $uniqueid = null) {
882
	/* Must have one or the other */
883
	if (($conid === null) && ($uniqueid === null)) {
884
		return false;
885
	}
886
	$selector = '--';
887
	$selector .= ($type == 'ike') ? 'ike' : 'child';
888

    
889
	if (ctype_digit(strval($uniqueid)) && ($uniqueid > 0)) {
890
		$selector .= '-id';
891
		$term = $uniqueid;
892
	} else {
893
		$term = $conid;
894
	}
895
	mwexec_bg("/usr/local/sbin/swanctl --terminate --force " . escapeshellarg($selector) . " " . escapeshellarg($term));
896
	return true;
897
}
898

    
899
/*
900
 * Return dump of SPD table
901
 */
902
function ipsec_dump_spd() {
903
	$fd = @popen("/sbin/setkey -DP", "r");
904
	$spd = array();
905
	if ($fd) {
906
		while (!feof($fd)) {
907
			$line = chop(fgets($fd));
908
			if (!$line) {
909
				continue;
910
			}
911
			if ($line == "No SPD entries.") {
912
				break;
913
			}
914
			if ($line[0] != "\t") {
915
				if (is_array($cursp)) {
916
					$spd[] = $cursp;
917
				}
918
				$cursp = array();
919
				$linea = explode(" ", $line);
920
				$cursp['srcid'] = substr($linea[0], 0, strpos($linea[0], "["));
921
				$cursp['dstid'] = substr($linea[1], 0, strpos($linea[1], "["));
922
				$i = 0;
923
			} else if (is_array($cursp)) {
924
				$line = trim($line, "\t\r\n ");
925
				$linea = explode(" ", $line);
926
				switch ($i) {
927
					case 1:
928
						if ($linea[1] == "none")	/* don't show default anti-lockout rule */ {
929
							unset($cursp);
930
						} else {
931
							$cursp['dir'] = $linea[0];
932
						}
933
						break;
934
					case 2:
935
						$upperspec = explode("/", $linea[0]);
936
						$cursp['proto'] = $upperspec[0];
937
						list($cursp['src'], $cursp['dst']) = explode("-", $upperspec[2]);
938
						$cursp['unique'] = substr($upperspec[3], strpos($upperspec[3], ":")+1);
939
						break;
940
					default:
941
						if (substr($linea[0], 0, 4) != 'spid') {
942
							break;
943
						}
944
						$cursp['scope'] = substr($linea[3], strpos($linea[3], "=")+1);
945
						if ($cursp['scope'] == 'ifnet') {
946
							$cursp['ifname'] = substr($linea[4], strpos($linea[4], "=")+1);
947
						}
948
						break;
949
				}
950
			}
951
			$i++;
952
		}
953
		if (is_array($cursp) && count($cursp)) {
954
			$spd[] = $cursp;
955
		}
956
		pclose($fd);
957
	}
958

    
959
	return $spd;
960
}
961

    
962
/*
963
 * Return dump of SAD table
964
 */
965
function ipsec_dump_sad() {
966
	$fd = @popen("/sbin/setkey -D", "r");
967
	$sad = array();
968
	if ($fd) {
969
		while (!feof($fd)) {
970
			$line = chop(fgets($fd));
971
			if (!$line || $line[0] == " ") {
972
				continue;
973
			}
974
			if ($line == "No SAD entries.") {
975
				break;
976
			}
977
			if ($line[0] != "\t") {
978
				if (is_array($cursa)) {
979
					$sad[] = $cursa;
980
				}
981
				$cursa = array();
982
				list($cursa['src'], $cursa['dst']) = explode(" ", $line);
983
			} else {
984
				$line = trim($line, "\t\n\r ");
985
				$linea = explode(" ", $line);
986
				foreach ($linea as $idx => $linee) {
987
					if ($linee == 'esp' || $linee == 'ah' || $linee[0] == '#') {
988
						$cursa['proto'] = $linee;
989
					} else if (substr($linee, 0, 3) == 'spi') {
990
						$cursa['spi'] = substr($linee, strpos($linee, 'x') + 1, -1);
991
					} else if (substr($linee, 0, 5) == 'reqid') {
992
						$cursa['reqid'] = substr($linee, strpos($linee, 'x') + 1, -1);
993
					} else if (substr($linee, 0, 2) == 'E:') {
994
						$cursa['ealgo'] = $linea[$idx + 1];
995
						break;
996
					} else if (substr($linee, 0, 2) == 'A:') {
997
						$cursa['aalgo'] = $linea[$idx + 1];
998
						break;
999
					} else if (substr($linee, 0, 8) == 'current:') {
1000
						$cursa['data'] = substr($linea[$idx + 1], 0, strpos($linea[$idx + 1], 'bytes') - 1) . ' B';
1001
						break;
1002
					}
1003
				}
1004
			}
1005
		}
1006
		if (is_array($cursa) && count($cursa)) {
1007
			$sad[] = $cursa;
1008
		}
1009
		pclose($fd);
1010
	}
1011

    
1012
	return $sad;
1013
}
1014

    
1015
/*
1016
 * Return dump of mobile user list
1017
 */
1018
function ipsec_dump_mobile() {
1019
	global $g;
1020

    
1021
	if(!config_path_enabled('ipsec/client')) {
1022
		return array();
1023
	}
1024

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

    
1028
	if ($rc != 0) {
1029
		log_error(gettext("Unable to find IPsec daemon leases file. Could not display mobile user stats!"));
1030
		return array();
1031
	}
1032

    
1033
	$response = array(
1034
		'pool' => array(),
1035
	);
1036

    
1037
	/* swanctl --list-pools --leases example output, field names can be confirmed by
1038
	 * looking at --raw or --pretty output. */
1039
	/* mobile-pool          10.7.200.0                          0 / 1 / 254 */
1040
	$pool_regex='/^(?P<name>\S+)\s+(?P<base>\S+)\s+(?P<online>\d+) \/ (?P<offline>\d+) \/ (?P<size>\d+)/';
1041
	/*   10.7.200.1                     online   'jimp' */
1042
	$lease_regex='/\s*(?P<host>[\d\.]+)\s+(?P<status>online|offline)\s+\'(?P<id>.*)\'/';
1043
	foreach ($output as $line) {
1044
		if (preg_match($pool_regex, $line, $matches)) {
1045
			$id++;
1046
			$response['pool'][$id] = array(
1047
			    'name'   => $matches['name'],
1048
			    'base'   => $matches['base'],
1049
			    'online' => $matches['online'],
1050
			    'offline'  => $matches['offline'],
1051
			    'size'   => $matches['size'],
1052
			);
1053
		} elseif (preg_match($lease_regex, $line, $matches)) {
1054
			$response['pool'][$id]['lease'][] = array(
1055
			    'host'   => $matches['host'],
1056
			    'status' => $matches['status'],
1057
			    'id'     => $matches['id']
1058
			);
1059
		}
1060
	}
1061

    
1062
	unset($_gb, $output, $rc, $pool_regex);
1063

    
1064
	return $response;
1065
}
1066

    
1067
function ipsec_mobilekey_sort() {
1068
	function mobilekeycmp($a, $b) {
1069
		return strcmp($a['ident'][0], $b['ident'][0]);
1070
	}
1071

    
1072
	usort($config['ipsec']['mobilekey'], "mobilekeycmp");
1073
}
1074

    
1075
function ipsec_fixup_ip($ipaddr) {
1076
	if (is_ipaddrv6($ipaddr) || is_subnetv6($ipaddr)) {
1077
		return text_to_compressed_ip6($ipaddr);
1078
	} else {
1079
		return $ipaddr;
1080
	}
1081
}
1082

    
1083
function ipsec_find_id(& $ph1ent, $side = "local", $rgmap = array(), $gateways_status = false) {
1084
	if ($side == "local") {
1085
		$id_type = $ph1ent['myid_type'];
1086
		$id_data = $ph1ent['myid_data'];
1087

    
1088
		$addr = ipsec_get_phase1_src($ph1ent, $gateways_status);
1089
		if (!$addr) {
1090
			return array();
1091
		}
1092
		/* When automatically guessing, use the first address. */
1093
		$addr = explode(',', $addr);
1094
		$addr = $addr[0];
1095
	} elseif ($side == "peer") {
1096
		$id_type = $ph1ent['peerid_type'];
1097
		$id_data = $ph1ent['peerid_data'];
1098

    
1099
		if (isset($ph1ent['mobile'])) {
1100
			$addr = "%any";
1101
		} else {
1102
			$addr = $ph1ent['remote-gateway'];
1103
		}
1104
	} else {
1105
		return array();
1106
	}
1107

    
1108
	$thisid_type = $id_type;
1109
	switch ($thisid_type) {
1110
		case 'myaddress':
1111
			$thisid_type = 'address';
1112
			$thisid_data = $addr;
1113
			break;
1114
		case 'dyn_dns':
1115
			$thisid_type = 'dns';
1116
			$thisid_data = $id_data;
1117
			break;
1118
		case 'peeraddress':
1119
			$thisid_type = 'address';
1120
			$thisid_data = $rgmap[$ph1ent['remote-gateway']];
1121
			break;
1122
		case 'keyid tag':
1123
			$thisid_type = 'keyid';
1124
			$thisid_data = $id_data;
1125
			break;
1126
		case 'user_fqdn':
1127
			$thisid_type = 'userfqdn';
1128
			$thisid_data = $id_data;
1129
			break;
1130
		case 'any':
1131
			$thisid_data = '%any';
1132
			break;
1133
		case 'address':
1134
		case 'fqdn':
1135
		case 'asn1dn':
1136
		case 'auto':
1137
			$thisid_data = $id_data;
1138
			break;
1139
		default:
1140
			break;
1141
	}
1142
	return array($thisid_type, $thisid_data);
1143
}
1144

    
1145
/*
1146
 * Fixup ID type/data to include prefix when necessary, add quotes, etc.
1147
 */
1148
function ipsec_fixup_id($type, $data) {
1149
	/* List of types to pass through as-is without changes or adding prefix */
1150
	$auto_types = array('address', 'auto');
1151
	/* List of types which need the resulting string double quoted. */
1152
	$quote_types = array('keyid', 'asn1dn', 'auto');
1153

    
1154
	/* If the first character of asn1dn type data is not #, then rely on
1155
	 * automatic parsing https://redmine.pfsense.org/issues/4792 */
1156
	if (($type == 'asn1dn') && !empty($data) && ($data[0] != '#')) {
1157
		$auto_types[] = 'asn1dn';
1158
	}
1159

    
1160
	if ($type == 'any') {
1161
		$idstring = "%any";
1162
	} elseif (!in_array($type, $auto_types)) {
1163
		$idstring = "{$type}:{$data}";
1164
	} else {
1165
		$idstring = $data;
1166
	}
1167

    
1168
	if (in_array($type, $quote_types)) {
1169
		$idstring = "\"{$idstring}\"";
1170
	}
1171

    
1172
	return $idstring;
1173
}
1174

    
1175
function ipsec_fixup_network($network) {
1176
	if (substr($network, -3) == '|/0') {
1177
		$result = substr($network, 0, -3);
1178
	} else {
1179
		$tmp = explode('|', $network);
1180
		if (isset($tmp[1])) {
1181
			$result = $tmp[1];
1182
		} else {
1183
			$result = $tmp[0];
1184
		}
1185
		unset($tmp);
1186
	}
1187

    
1188
	return $result;
1189
}
1190

    
1191
function ipsec_get_loglevels() {
1192
	global $ipsec_log_cats;
1193
	$def_loglevel = '1';
1194

    
1195
	$levels = array();
1196

    
1197
	foreach (array_keys($ipsec_log_cats) as $cat) {
1198
		if (!empty(config_get_path('ipsec/logging/' . $cat))) {
1199
			$levels[$cat] = config_get_path('ipsec/logging/' . $cat);
1200
		} elseif (in_array($cat, array('ike', 'chd', 'cfg'))) {
1201
			$levels[$cat] = "2";
1202
		} else {
1203
			$levels[$cat] = $def_loglevel;
1204
		}
1205
	}
1206
	return $levels;
1207
}
1208

    
1209
function ipsec_vti($p1, $returnaddresses = false, $skipdisabled = true) {
1210
	$is_vti = false;
1211
	$vtisubnet_spec = array();
1212

    
1213
	foreach(ipsec_get_phase2_by_ikeid($p1['ikeid']) as $p2) {
1214
		if ($p2['mode'] == 'vti') {
1215
			if ($skipdisabled && isset($p2['disabled'])) {
1216
				continue;
1217
			} else {
1218
				$is_vti = true;
1219
			}
1220
			if ($returnaddresses) {
1221
				$vtisubnet_spec[] = array(
1222
					'left' => ipsec_idinfo_to_cidr($p2['localid'], true, $p2['mode']),
1223
					'right' => ipsec_idinfo_to_cidr($p2['remoteid'], false, $p2['mode']),
1224
					'descr' => $p2['descr'],
1225
					'reqid' => $p2['reqid'],
1226
				);
1227
			}
1228
		}
1229
	}
1230
	return ($returnaddresses) ? $vtisubnet_spec : $is_vti;
1231
}
1232

    
1233
/* Called when IPsec is reloaded through rc.newipsecdns and similar, gives
1234
 * packages an opportunity to execute custom code when IPsec reloads.
1235
 */
1236
function ipsec_reload_package_hook() {
1237
	global $g;
1238

    
1239
	init_config_arr(array('installedpackages', 'package'));
1240
	foreach (config_get_path('installedpackages/package', []) as $package) {
1241
		if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
1242
			continue;
1243
		}
1244

    
1245
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], 'packagegui');
1246
		if (!empty($pkg_config['include_file']) &&
1247
		    file_exists($pkg_config['include_file'])) {
1248
			require_once($pkg_config['include_file']);
1249
		}
1250
		if (empty($pkg_config['ipsec_reload_function'])) {
1251
			continue;
1252
		}
1253
		$pkg_ipsec_reload = $pkg_config['ipsec_reload_function'];
1254
		if (!function_exists($pkg_ipsec_reload)) {
1255
			continue;
1256
		}
1257
		$pkg_ipsec_reload();
1258
	}
1259
}
1260

    
1261
/****f* certs/ipsec_convert_to_modp
1262
 * NAME
1263
 *   ipsec_convert_to_modp - Take a DH Group number value and return the
1264
 *                           associated name
1265
 * INPUTS
1266
 *   $index: DH group index number to look up
1267
 * RESULT
1268
 *   Returns the Diffie Hellman Group keyword associated with the group number.
1269
 ******/
1270
function ipsec_convert_to_modp($index) {
1271
	$modpmap = array(
1272
		'1' => 'modp768',
1273
		'2' => 'modp1024',
1274
		'5' => 'modp1536',
1275
		'14' => 'modp2048',
1276
		'15' => 'modp3072',
1277
		'16' => 'modp4096',
1278
		'17' => 'modp6144',
1279
		'18' => 'modp8192',
1280
		'19' => 'ecp256',
1281
		'20' => 'ecp384',
1282
		'21' => 'ecp521',
1283
		'22' => 'modp1024s160',
1284
		'23' => 'modp2048s224',
1285
		'24' => 'modp2048s256',
1286
		'25' => 'ecp192',
1287
		'26' => 'ecp224',
1288
		'27' => 'ecp224bp',
1289
		'28' => 'ecp256bp',
1290
		'29' => 'ecp384bp',
1291
		'30' => 'ecp512bp',
1292
		'31' => 'curve25519',
1293
		'32' => 'curve448',
1294
	);
1295

    
1296
	return $modpmap[$index];
1297
}
1298

    
1299
/*
1300
 * Forcefully restart IPsec
1301
 * This is required for when dynamic interfaces reload
1302
 * For all other occasions the normal ipsec_configure()
1303
 * will gracefully reload the settings without restarting
1304
 */
1305
function ipsec_force_reload($interface = "", $protocol = "") {
1306
	global $g;
1307

    
1308
	if (!ipsec_enabled()) {
1309
		return;
1310
	}
1311

    
1312
	$ipseccfg = config_get_path('ipsec');
1313

    
1314
	if (!empty($interface) && is_array($ipseccfg['phase1'])) {
1315
		$found = false;
1316
		$gateways_status = null;
1317
		$realif = array();
1318
		$ifcache = array();
1319
		foreach ($ipseccfg['phase1'] as $ipsec) {
1320
			if (isset($ipsec['disabled'])) {
1321
				continue;
1322
			}
1323
			if (!empty($protocol) &&
1324
			    ($ipsec['protocol'] != $protocol) &&
1325
			    ($ipsec['protocol'] != 'both')) {
1326
				continue;
1327
			}
1328
			if ($ipsec['interface'] == $interface) {
1329
				$found = true;
1330
				break;
1331
			} else {
1332
				/* Fetch gateway status just once, and only if needed */
1333
				if (!is_array($gateways_status)) {
1334
					$gateways_status = return_gateways_status(true);
1335
				}
1336
				$fam = (!empty($ipsec['protocol'])) ? $ipsec['protocol'] : 'inet';
1337

    
1338
				/* Find the real active passed interface for this address family, cache the result */
1339
				if (empty($realif) ||
1340
				    empty($realif[$fam])) {
1341
					$realif[$fam] = get_failover_interface($interface, $fam, $gateways_status);
1342
				}
1343

    
1344
				/* Find the real active tunnel interface for this address family, cache the result */
1345
				if (empty($ifcache) ||
1346
				    empty($ifcache[$ipsec['interface']]) ||
1347
				    empty($ifcache[$ipsec['interface']][$fam])) {
1348
					if (!is_array($ifcache[$ipsec['interface']])) {
1349
						$ifcache[$ipsec['interface']] = array();
1350
					}
1351
					$ifcache[$ipsec['interface']][$fam] = get_failover_interface($ipsec['interface'], $fam, $gateways_status);
1352
				}
1353

    
1354
				if ($realif[$fam] == $ifcache[$ipsec['interface']][$fam]) {
1355
					$found = true;
1356
					break;
1357
				}
1358
			}
1359
		}
1360
		if (!$found) {
1361
			log_error(sprintf(gettext("Ignoring IPsec reload since there are no tunnels on interface %s"), $interface));
1362
			return;
1363
		}
1364
	}
1365

    
1366
	/* If we get this far then we need to take action. */
1367
	log_error(gettext("Forcefully reloading IPsec"));
1368
	ipsec_configure();
1369
}
1370

    
1371
/****f* ipsec/ipsec_strongswan_confgen
1372
 * NAME
1373
 *   ipsec_strongswan_confgen - Generate strongswan.conf style formatted output
1374
 *                              From a multi-dimensional array.
1375
 * INPUTS
1376
 *   $confarr: An array of key=value pairs or key=array entries for subsections.
1377
 *   $indent : A string of tabs used when indenting lines.
1378
 * RESULT
1379
 *   Returns a string of key=value pairs with proper indenting, and with named
1380
 *   subsections enclosed in braces.
1381
 * NOTES
1382
 *   Values starting with a "#" (comments) or "include " will be printed
1383
 *   directly without their associated key name.
1384
 ******/
1385
function ipsec_strongswan_confgen($confarr, $indent = "") {
1386
	$confstr = "";
1387
	/* Only process the contents if it's an array. */
1388
	if (is_array($confarr)) {
1389
		foreach ($confarr as $key => $value) {
1390
			if (is_array($value)) {
1391
				/* If the array is empty, do not print anything */
1392
				if (empty($value)) {
1393
					continue;
1394
				}
1395
				/* If this is an array, setup the subsection name
1396
				 * and structure, then call this function
1397
				 * recursively to walk the lower array. */
1398
				$confstr .= "{$indent}{$key} {\n";
1399
				$confstr .= ipsec_strongswan_confgen($value, $indent . "\t");
1400
				$confstr .= "{$indent}}\n";
1401
			} else {
1402
				$confstr .= "{$indent}";
1403
				if ((substr($value, 0 , 1) != '#') &&
1404
				    (substr($value, 0 , 8) != 'include ')) {
1405
					/* Not a comment or include, print the key */
1406
					$confstr .= "{$key} = ";
1407
				}
1408
				$confstr .= "{$value}\n";
1409
			}
1410
		}
1411
	}
1412
	return $confstr;
1413
}
1414

    
1415
global $g, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs;
1416
$ipsec_swanctl_basedir = "{$g['varetc_path']}/ipsec";
1417
$ipsec_swanctl_dirs = array(
1418
	'conf'     => "{$ipsec_swanctl_basedir}/conf.d",
1419
	'certpath' => "{$ipsec_swanctl_basedir}/x509",
1420
	'capath'   => "{$ipsec_swanctl_basedir}/x509ca",
1421
	'aapath'   => "{$ipsec_swanctl_basedir}/x509aa",
1422
	'ocsppath' => "{$ipsec_swanctl_basedir}/x509ocsp",
1423
	'crlpath'  => "{$ipsec_swanctl_basedir}/x509crl",
1424
	'acpath'   => "{$ipsec_swanctl_basedir}/x509ac",
1425
	'rsakeys'  => "{$ipsec_swanctl_basedir}/rsa",
1426
	'eckeys'   => "{$ipsec_swanctl_basedir}/ecdsa",
1427
	'keypath'  => "{$ipsec_swanctl_basedir}/private",
1428
	'pubkpath' => "{$ipsec_swanctl_basedir}/pubkey",
1429
	'blisspath' => "{$ipsec_swanctl_basedir}/bliss",
1430
	'pkcs8path' => "{$ipsec_swanctl_basedir}/pkcs8",
1431
	'pkcs12path' => "{$ipsec_swanctl_basedir}/pkcs12",
1432
);
1433

    
1434
/****f* ipsec/ipsec_create_dirs
1435
 * NAME
1436
 *   ipsec_create_dirs - Create default set of strongSwan configuration directories.
1437
 * INPUTS
1438
 *   None
1439
 * RESULT
1440
 *   Cleans up and creates strongSwan configuration directories and links.
1441
 ******/
1442
function ipsec_create_dirs() {
1443
	global $g, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs;
1444

    
1445
	/* Cleanup base paths to ensure old files are not left behind (#5238) */
1446
	if (!empty($ipsec_swanctl_basedir)) {
1447
		@rmdir_recursive($ipsec_swanctl_basedir, false);
1448
	}
1449
	/* Create directory structure */
1450
	array_map('safe_mkdir', array_values($ipsec_swanctl_dirs));
1451

    
1452
	/* Create and link strongSwan config */
1453
	$ssdpath = "{$g['varetc_path']}/ipsec/strongswan.d";
1454
	if (!file_exists($ssdpath) || !is_link($ssdpath)) {
1455
		if (is_dir($ssdpath) && !is_link($ssdpath)) {
1456
			@rmdir_recursive($ssdpath, false);
1457
		} else {
1458
			@unlink($ssdpath);
1459
		}
1460
		@symlink("/usr/local/etc/strongswan.d",
1461
		    $ssdpath);
1462
	}
1463
	if (!file_exists("/usr/local/etc/strongswan.conf") ||
1464
	    !is_link("/usr/local/etc/strongswan.conf")) {
1465
		@unlink("/usr/local/etc/strongswan.conf");
1466
		@symlink("{$g['varetc_path']}/ipsec/strongswan.conf",
1467
		    "/usr/local/etc/strongswan.conf");
1468
	}
1469
}
1470

    
1471
/****f* ipsec/ipsec_setup_gwifs
1472
 * NAME
1473
 *   ipsec_setup_gwifs - Setup IPsec-related interfaces and gateways
1474
 * INPUTS
1475
 *   None
1476
 * RESULT
1477
 *   Sets up VTI interfaces and gateways, populates ipsecpinghosts
1478
 ******/
1479
function ipsec_setup_gwifs($gateways_status = false) {
1480
	global $g, $rgmap, $filterdns_list,
1481
		$aggressive_mode_psk, $mobile_ipsec_auth, $ifacesuse,
1482
		$ipsecpinghostsactive;
1483
	/* resolve all local, peer addresses and setup pings */
1484
	/* Fetch gateway status if not passed */
1485
	if (!is_array($gateways_status)) {
1486
		$gateways_status = return_gateways_status(true);
1487
	}
1488

    
1489
	unset($iflist);
1490
	$ipsecpinghosts = array();
1491
	/* step through each phase1 entry */
1492
	foreach (config_get_path('ipsec/phase1', []) as $ph1ent) {
1493
		if (isset($ph1ent['disabled'])) {
1494
			continue;
1495
		}
1496
		if (substr($ph1ent['interface'], 0, 4) == "_vip") {
1497
			$vpninterface = get_configured_vip_interface($ph1ent['interface']);
1498
			$ifacesuse[] = get_real_interface($vpninterface);
1499
		} else {
1500
			$vpninterface = get_failover_interface($ph1ent['interface'], 'all', $gateways_status);
1501
			if (substr($vpninterface, 0, 4) == "_vip") {
1502
				$vpninterface = get_configured_vip_interface($vpninterface);
1503
				$ifacesuse[] = get_real_interface($vpninterface);
1504
			} elseif (!empty($vpninterface)) {
1505
				$ifacesuse[] = $vpninterface;
1506
			}
1507
		}
1508
		if ($ph1ent['mode'] == "aggressive" && ($ph1ent['authentication_method'] == "pre_shared_key" || $ph1ent['authentication_method'] == "xauth_psk_server")) {
1509
			$aggressive_mode_psk = true;
1510
		}
1511

    
1512
		$ikeid = $ph1ent['ikeid'];
1513

    
1514
		$local_spec = ipsec_get_phase1_src($ph1ent, $gateways_status);
1515
		/* When automatically guessing, use the first address. */
1516
		$local_spec  = explode(',', $local_spec);
1517
		$local_spec  = $local_spec[0];
1518
		if (!is_ipaddr($local_spec)) {
1519
			log_error(sprintf(gettext("IPsec ERROR: Could not find phase 1 source for connection %s. Omitting from configuration file."), $ph1ent['descr']));
1520
			continue;
1521
		}
1522

    
1523
		if (isset($ph1ent['mobile'])) {
1524
			$mobile_ipsec_auth = $ph1ent['authentication_method'];
1525
			continue;
1526
		}
1527

    
1528
		/* see if this tunnel has a hostname for the remote-gateway. If so,
1529
		   try to resolve it now and add it to the list for filterdns */
1530
		$rg = $ph1ent['remote-gateway'];
1531
		if (!is_ipaddr($rg)) {
1532
			$filterdns_list[] = "{$rg}";
1533
			if (!platform_booting()) {
1534
				$rg = resolve_retry($rg, $ph1ent['protocol']);
1535
			}
1536
			if (!is_ipaddr($rg)) {
1537
				continue;
1538
			}
1539
		}
1540
		if (!isset($ph1ent['gw_duplicates']) && array_search($rg, $rgmap)) {
1541
			log_error(sprintf(gettext("The remote gateway %s already exists on another phase 1 entry"), $rg));
1542
			continue;
1543
		}
1544
		$rgmap[$ph1ent['remote-gateway']] = $rg;
1545

    
1546
		$is_vti = false;
1547
		/* step through each phase2 entry */
1548
		foreach (config_get_path('ipsec/phase2', []) as $ph2ent) {
1549
			if ($ph2ent['ikeid'] != $ph1ent['ikeid']) {
1550
				continue;
1551
			}
1552
			if ($ph2ent['mode'] == 'vti') {
1553
				$is_vti = true;
1554
			}
1555
			if (isset($ph2ent['disabled']) || ($ikeid != $ph2ent['ikeid'])) {
1556
				continue;
1557
			}
1558

    
1559
			/* add an ipsec pinghosts entry */
1560
			if ($ph2ent['pinghost']) {
1561
				if (!is_array($iflist)) {
1562
					$iflist = get_configured_interface_list();
1563
				}
1564
				$srcip = null;
1565
				$local_subnet = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
1566
				if (is_ipaddrv6($ph2ent['pinghost'])) {
1567
					foreach ($iflist as $ifent => $ifname) {
1568
						$interface_ip = get_interface_ipv6($ifent);
1569
						if (!is_ipaddrv6($interface_ip)) {
1570
							continue;
1571
						}
1572
						if (ip_in_subnet($interface_ip, $local_subnet)) {
1573
							$srcip = $interface_ip;
1574
							break;
1575
						}
1576
					}
1577
				} else {
1578
					foreach ($iflist as $ifent => $ifname) {
1579
						$interface_ip = get_interface_ip($ifent, $gateways_status);
1580
						if (!is_ipaddrv4($interface_ip)) {
1581
							continue;
1582
						}
1583
						if ($local_subnet == "0.0.0.0/0" || ip_in_subnet($interface_ip, $local_subnet)) {
1584
							$srcip = $interface_ip;
1585
							break;
1586
						}
1587
					}
1588
				}
1589
				/* if no valid src IP was found in configured interfaces, try the vips */
1590
				if (is_null($srcip)) {
1591
					$viplist = get_configured_vip_list();
1592
					foreach ($viplist as $vip => $address) {
1593
						if (ip_in_subnet($address, $local_subnet)) {
1594
							$srcip = $address;
1595
							break;
1596
						}
1597
					}
1598
				}
1599
				$dstip = $ph2ent['pinghost'];
1600
				$family = "inet" . (is_ipaddrv6($dstip)) ? "6" : "";
1601
				if (is_ipaddr($srcip)) {
1602
					$ipsecpinghosts[] = "{$srcip}|{$dstip}|3|||||{$family}|\n";
1603
					$ipsecpinghostsactive = true;
1604
				}
1605
			}
1606
		}
1607
		if ($is_vti) {
1608
			interface_ipsec_vti_configure($ph1ent, $gateways_status);
1609
		}
1610
	}
1611
	@file_put_contents("{$g['vardb_path']}/ipsecpinghosts", $ipsecpinghosts);
1612
	unset($ipsecpinghosts);
1613
	unset($iflist);
1614
}
1615

    
1616
/****f* ipsec/ipsec_logging_config
1617
 * NAME
1618
 *   ipsec_logging_config - Generate an array containing strongSwan logging
1619
 *                          values.
1620
 * INPUTS
1621
 *   None
1622
 * RESULT
1623
 *   Returns an array which can be merged into the strongswan daemon logging
1624
 *   values so that each logging category is represented, even those not listed
1625
 *   in config.xml.
1626
 ******/
1627
function ipsec_logging_config() {
1628
	global $ipsec_log_cats, $ipsec_log_sevs;
1629
	$logcfg = array();
1630
	$log_levels = ipsec_get_loglevels();
1631
	foreach (array_keys($ipsec_log_cats) as $cat) {
1632
		if (is_numeric($log_levels[$cat]) &&
1633
		    in_array(intval($log_levels[$cat]), array_keys($ipsec_log_sevs), true)) {
1634
			$logcfg[$cat] = $log_levels[$cat];
1635
		}
1636
	}
1637
	return $logcfg;
1638
}
1639

    
1640
/****f* ipsec/ipsec_setup_strongswan
1641
 * NAME
1642
 *   ipsec_setup_strongswan - Generate the strongswan.conf configuration file.
1643
 * INPUTS
1644
 *   None
1645
 * RESULT
1646
 *   Determines strongswan.conf values and crafts the configuration file in the
1647
 *   appropriate format.
1648
 * NOTES
1649
 *   Called from ipsec_configure()
1650
 ******/
1651
function ipsec_setup_strongswan() {
1652
	global $g, $mobile_ipsec_auth, $a_client, $aggressive_mode_psk, $ifacesuse;
1653

    
1654
	/* strongswan.conf array */
1655
	$ssconf = array();
1656
	$ssconf[] = "# Automatically generated config file - DO NOT MODIFY. Changes will be overwritten.";
1657
	$ssconf['starter'] = array();
1658
	$ssconf['starter']['load_warning'] = "no";
1659

    
1660
	$ssconf['charon'] = array();
1661
	$ssconf['charon'][] = '# number of worker threads in charon';
1662
	$ssconf['charon']['threads'] = '16';
1663
	$ssconf['charon']['ikesa_table_size'] = '32';
1664
	$ssconf['charon']['ikesa_table_segments'] = '4';
1665
	$ssconf['charon']['init_limit_half_open'] = '1000';
1666
	$ssconf['charon']['install_routes'] = 'no';
1667
	$ssconf['charon']['load_modular'] = 'yes';
1668
	$ssconf['charon']['ignore_acquire_ts'] = 'yes';
1669

    
1670
	if ($aggressive_mode_psk) {
1671
		$stronconf = '';
1672
		if (file_exists("{$g['varetc_path']}/ipsec/strongswan.conf")) {
1673
			$stronconf = file_get_contents("{$g['varetc_path']}/ipsec/strongswan.conf");
1674
		}
1675
		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.");
1676
		$restart = (!empty($stronconf) && strpos($stronconf, 'i_dont_care_about_security_and_use_aggressive_mode_psk') === FALSE);
1677
		unset($stronconf);
1678
		$ssconf['charon']['i_dont_care_about_security_and_use_aggressive_mode_psk'] = "yes";
1679
	}
1680

    
1681
	if (config_path_enabled('ipsec', 'acceptunencryptedmainmode')) {
1682
		$ssconf['charon']['accept_unencrypted_mainmode_messages'] = "yes";
1683
	}
1684

    
1685
	if (!empty(config_get_path('ipsec/maxexchange'))) {
1686
		$ssconf['charon']['max_ikev1_exchanges'] = config_get_path('ipsec/maxexchange');
1687
	}
1688

    
1689
	$unity_enabled = config_path_enabled('ipsec', 'unityplugin') ? 'yes' : 'no';
1690
	$ssconf['charon']['cisco_unity'] = $unity_enabled;
1691

    
1692
	if (config_path_enabled('ipsec', 'enableinterfacesuse') && !empty($ifacesuse)) {
1693
		$ssconf['charon']['interfaces_use'] = implode(',', array_unique($ifacesuse));
1694
	}
1695

    
1696
	if (config_path_enabled('ipsec', 'makebeforebreak')) {
1697
		$ssconf['charon']['make_before_break'] = "yes";
1698
	}
1699

    
1700
	if (!empty(config_get_path('ipsec/port'))) {
1701
		$ssconf['charon']['port'] = config_get_path('ipsec/port');
1702
	}
1703

    
1704
	if (!empty(config_get_path('ipsec/port_nat_t'))) {
1705
		$ssconf['charon']['port_nat_t'] = config_get_path('ipsec/port_nat_t');
1706
	}
1707

    
1708
	/* IKEv2 retransmit options, see https://redmine.pfsense.org/issues/12184 */
1709
	if (!empty(config_get_path('ipsec/ikev2_retransmit_tries'))) {
1710
		$ssconf['charon']['retransmit_tries'] = config_get_path('ipsec/ikev2_retransmit_tries');
1711
	}
1712
	if (!empty(config_get_path('ipsec/ikev2_retransmit_timeout'))) {
1713
		$ssconf['charon']['retransmit_timeout'] = config_get_path('ipsec/ikev2_retransmit_timeout');
1714
	}
1715
	if (!empty(config_get_path('ipsec/ikev2_retransmit_base'))) {
1716
		$ssconf['charon']['retransmit_base'] = config_get_path('ipsec/ikev2_retransmit_base');
1717
	}
1718
	if (!empty(config_get_path('ipsec/ikev2_retransmit_jitter'))) {
1719
		$ssconf['charon']['retransmit_jitter'] = config_get_path('ipsec/ikev2_retransmit_jitter');
1720
	}
1721
	if (!empty(config_get_path('ipsec/ikev2_retransmit_limit'))) {
1722
		$ssconf['charon']['retransmit_limit'] = config_get_path('ipsec/ikev2_retransmit_limit');
1723
	}
1724

    
1725
	$ssconf['charon']['syslog'] = array();
1726
	$ssconf['charon']['syslog']['identifier'] = 'charon';
1727
	$ssconf['charon']['syslog'][] = "# log everything under daemon since it ends up in the same place regardless with our syslog.conf";
1728
	$ssconf['charon']['syslog']['daemon'] = array();
1729
	$ssconf['charon']['syslog']['daemon']['ike_name'] = 'yes';
1730
	$ssconf['charon']['syslog']['daemon'] = array_merge($ssconf['charon']['syslog']['daemon'], ipsec_logging_config());
1731
	$ssconf['charon']['syslog'][] = '# disable logging under auth so logs aren\'t duplicated';
1732
	$ssconf['charon']['syslog']['auth'] = array();
1733
	$ssconf['charon']['syslog']['auth']['default'] = -1;
1734

    
1735
	$ssconf['charon']['plugins'] = array();
1736
	$ssconf['charon']['plugins'][] = "# Load defaults";
1737
	$ssconf['charon']['plugins'][] = "include {$g['varetc_path']}/ipsec/strongswan.d/charon/*.conf";
1738
	$ssconf['charon']['plugins']['unity'] = array('load' => $unity_enabled);
1739
	$ssconf['charon']['plugins']['curve25519'] = array('load' => "yes");
1740

    
1741
	if (config_path_enabled('ipsec', 'pkcs11support')) {
1742
		$ssconf['charon']['plugins']['pkcs11'] = array();
1743
		$ssconf['charon']['plugins']['pkcs11']['load'] = "yes";
1744
		$ssconf['charon']['plugins']['pkcs11']['modules'] = array();
1745
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc'] = array();
1746
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc']['load_certs'] = "yes";
1747
		$ssconf['charon']['plugins']['pkcs11']['modules']['opensc']['path'] = "/usr/local/lib/opensc-pkcs11.so";
1748
	}
1749

    
1750
	/* Find RADIUS servers designated for Mobile IPsec user auth */
1751
	$radius_servers = array();
1752
	foreach (explode(',', config_get_path('ipsec/client/user_source', '')) as $user_source) {
1753
		$auth_server = auth_get_authserver($user_source);
1754
		$nice_user_source = strtolower(preg_replace('/[\s\.]+/', '_', $user_source));
1755
		if ($auth_server && ($auth_server['type'] === 'radius')) {
1756
			$radius_servers[$nice_user_source] = array();
1757
			$radius_servers[$nice_user_source]['address'] = $auth_server['host'];
1758
			$radius_servers[$nice_user_source]['secret'] = "\"{$auth_server['radius_secret']}\"";
1759
			$radius_servers[$nice_user_source]['auth_port'] = empty($auth_server['radius_auth_port']) ? 1812 : $auth_server['radius_auth_port'];;
1760
			$radius_servers[$nice_user_source]['acct_port'] = empty($auth_server['radius_acct_port']) ? 1813 : $auth_server['radius_acct_port'];
1761
		}
1762
	}
1763

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

    
1792
	if (config_path_enabled('ipsec/client')) {
1793
		if (config_get_path('ipsec/client/user_source') != "none") {
1794
			$ssconf['charon']['plugins']['xauth-generic'] = array();
1795
			$ssconf['charon']['plugins']['xauth-generic']['script'] = "/etc/inc/ipsec.auth-user.php";
1796
			$authcfgs = array();
1797
			foreach (explode(",", $a_client['user_source']) as $authcfg) {
1798
				$authcfgs[] = ($authcfg == "system") ? "Local Database" : $authcfg;
1799
			}
1800
			$ssconf['charon']['plugins']['xauth-generic']['authcfg'] = implode(",", $authcfgs);
1801
		}
1802

    
1803
		$ssconf['charon']['plugins']['attr'] = array();
1804

    
1805
		$rightdnsservers = array();
1806
		if (!empty(config_get_path('ipsec/client/dns_server1'))) {
1807
			$rightdnsservers[] = config_get_path('ipsec/client/dns_server1');
1808
		}
1809
		if (!empty(config_get_path('ipsec/client/dns_server2'))) {
1810
			$rightdnsservers[] = config_get_path('ipsec/client/dns_server2');
1811
		}
1812
		if (!empty(config_get_path('ipsec/client/dns_server3'))) {
1813
			$rightdnsservers[] = config_get_path('ipsec/client/dns_server3');
1814
		}
1815
		if (!empty(config_get_path('ipsec/client/dns_server4'))) {
1816
			$rightdnsservers[] = config_get_path('ipsec/client/dns_server4');
1817
		}
1818
		if (count($rightdnsservers)) {
1819
			$ssconf['charon']['plugins']['attr']['dns'] = implode(',', $rightdnsservers);
1820
		}
1821

    
1822
		$cfgservers = array();
1823
		if (!empty(config_get_path('ipsec/client/wins_server1'))) {
1824
			$cfgservers[] = config_get_path('ipsec/client/wins_server1');
1825
		}
1826
		if (!empty(config_get_path('ipsec/client/wins_server2'))) {
1827
			$cfgservers[] = config_get_path('ipsec/client/wins_server2');
1828
		}
1829
		if (!empty($cfgservers)) {
1830
			$ssconf['charon']['plugins']['attr']['nbns'] = implode(',', $cfgservers);
1831
		}
1832
		unset($cfgservers);
1833

    
1834
		$net_list = array();
1835
		if (config_path_enabled('ipsec/client', 'net_list')) {
1836
			foreach (config_get_path('ipsec/phase2', []) as $ph2ent) {
1837
				if (isset($ph2ent['disabled']) ||
1838
				    !isset($ph2ent['mobile'])) {
1839
					continue;
1840
				}
1841
				$nlent = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
1842
				if (is_subnet($nlent)) {
1843
					$net_list[] = $nlent;
1844
				}
1845
				unset($nlent);
1846
			}
1847
		}
1848

    
1849
		if (!empty($net_list)) {
1850
			$ssconf['charon']['plugins']['attr']['subnet'] = implode(',', $net_list);
1851
			$ssconf['charon']['plugins']['attr']['split-include'] = implode(',', $net_list);
1852
		}
1853

    
1854
		if (!empty(config_get_path('ipsec/client/dns_domain'))) {
1855
			$ssconf['charon']['plugins']['attr'][] = "# Search domain and default domain";
1856
			$ssconf['charon']['plugins']['attr']['27674'] = config_get_path('ipsec/client/dns_domain');
1857
			if (!empty(config_get_path('ipsec/client/dns_split'))) {
1858
				$ssconf['charon']['plugins']['attr']['27675'] = config_get_path('ipsec/client/dns_domain');
1859
			}
1860
		}
1861

    
1862
		if (!empty($a_client['dns_split'])) {
1863
			$ssconf['charon']['plugins']['attr'][] = "# Split DNS (UNITY_SPLITDNS_NAME)";
1864
			$ssconf['charon']['plugins']['attr']['28675'] = config_get_path('ipsec/client/dns_split');
1865
			$ssconf['charon']['plugins']['attr'][] = "# Split DNS (INTERNAL_DNS_DOMAIN, RFC 8598)";
1866
			$ssconf['charon']['plugins']['attr']['25'] = str_replace(' ', ',', config_get_path('ipsec/client/dns_split'));
1867
		}
1868

    
1869
		if (!empty($a_client['login_banner'])) {
1870
			$ssconf['charon']['plugins']['attr'][] = "# Login Banner";
1871
			$ssconf['charon']['plugins']['attr']['28672'] = config_get_path('ipsec/client/login_banner');
1872
		}
1873

    
1874
		if (isset($a_client['save_passwd'])) {
1875
			$ssconf['charon']['plugins']['attr'][] = "# Save Xauth Password";
1876
			$ssconf['charon']['plugins']['attr']['28673'] = "1";
1877
		}
1878

    
1879
		if ($a_client['pfs_group']) {
1880
			$ssconf['charon']['plugins']['attr'][] = "# Phase2 PFS Group";
1881
			$ssconf['charon']['plugins']['attr']['28679'] = config_get_path('ipsec/client/pfs_group');
1882
		}
1883
	}
1884

    
1885
	@file_put_contents("{$g['varetc_path']}/ipsec/strongswan.conf", ipsec_strongswan_confgen($ssconf));
1886
}
1887

    
1888
/****f* ipsec/ipsec_setup_pools
1889
 * NAME
1890
 *   ipsec_setup_pools - Generate primary mobile pool configuration for swanctl
1891
  * INPUTS
1892
 *   None
1893
 * RESULT
1894
 *   Adds configured mobile pool settings to $scconf
1895
 * NOTES
1896
 *   These values were formerly in strongswan.conf but may now be configured in
1897
 *   pools, making future expansion to support multiple pools possible.
1898
 ******/
1899
function ipsec_setup_pools() {
1900
	global $g, $mobile_ipsec_auth, $scconf;
1901
	if (!config_path_enabled('ipsec/client')) {
1902
		return;
1903
	}
1904
	if (($mobile_ipsec_auth == "eap-radius") && empty(config_get_path('ipsec/client/pool_address')) &&
1905
	    empty(config_get_path('ipsec/client/pool_address_v6'))) {
1906
		return;
1907
	}
1908

    
1909
	/* Keep the comment in the array to ensure the entry makes it into the
1910
	 * config in all cases.
1911
	 * See https://redmine.pfsense.org/issues/11891 */
1912
	$scconf['mobile-pool'] = array("# Mobile pool settings template");
1913
	$scconf['pools'] = array();
1914
	$pool_common =& $scconf['mobile-pool'];
1915

    
1916
	if (!empty(config_get_path('ipsec/client/pool_address'))) {
1917
		$scconf['pools']['mobile-pool-v4 : mobile-pool'] = array();
1918
		$v4pool =& $scconf['pools']['mobile-pool-v4 : mobile-pool'];
1919
		$v4pool['addrs'] = config_get_path('ipsec/client/pool_address') . '/' . config_get_path('ipsec/client/pool_netbits');
1920
	}
1921
	if (!empty(config_get_path('ipsec/client/pool_address_v6'))) {
1922
		$scconf['pools']['mobile-pool-v6 : mobile-pool'] = array();
1923
		$v6pool =& $scconf['pools']['mobile-pool-v6 : mobile-pool'];
1924
		$v6pool['addrs'] = config_get_path('ipsec/client/pool_address_v6') . '/' . config_get_path('ipsec/client/pool_netbits_v6');
1925
	}
1926

    
1927
	return;
1928
}
1929

    
1930
/****f* ipsec/ipsec_setup_userpools
1931
 * NAME
1932
 *   ipsec_setup_userpools - Generate per-user custom pool settings for swanctl
1933
  * INPUTS
1934
 *   None
1935
 * RESULT
1936
 *   Adds configured per-user pool settings to $scconf using the primary mobile
1937
 *   pool as a base configuration.
1938
 * NOTES
1939
 *   Given this new flexible format, it is now possible to override any valid
1940
 *   pool setting, so future expansion of per-user settings is possible.
1941
 ******/
1942
function ipsec_setup_userpools() {
1943
	global $scconf;
1944
	$a_mobilekey = config_get_path('ipsec/mobilekey');
1945

    
1946
	/* Do not waste time if we do not have all the necessary information. */
1947
	if (!is_array($a_mobilekey) ||
1948
	    empty($a_mobilekey) ||
1949
	    !is_array($scconf['connections']) ||
1950
	    !is_array($scconf['con-mobile-defaults']) ||
1951
	    !is_array($scconf['pools']) ||
1952
	    !is_array($scconf['mobile-pool'])) {
1953
		return;
1954
	}
1955

    
1956
	$suffix = 1;
1957
	foreach ($a_mobilekey as $mkent) {
1958
		if (($mkent['type'] != "EAP") ||
1959
		    !isset($mkent['ident_type']) ||
1960
		    !isset($mkent['pool_address']) ||
1961
		    !isset($mkent['pool_netbits']) ||
1962
		    (strlen($mkent['pool_address']) < 1) ||
1963
		    !is_ipaddr($mkent['pool_address'])) {
1964
			continue;
1965
		}
1966
		/* The name of just this pool */
1967
		$upbase = "mobile-userpool-{$suffix}";
1968
		/* The full connection name including a reference to the primary
1969
		 * mobile connection */
1970
		$upconn = "con-{$upbase} : con-mobile-defaults";
1971
		/* The full pool name including a reference to the primary
1972
		 * mobile pool */
1973
		$upname = "{$upbase} : mobile-pool";
1974

    
1975
		$scconf['connections'][$upconn] = array();
1976
		$scconf['pools'][$upname] = array();
1977

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

    
1981
		/* Craft a cloned connection with the ID information to match */
1982
		$scconf['connections'][$upconn]['remote'] = array();
1983
		$scconf['connections'][$upconn]['remote']['id'] = $clientid;
1984
		$scconf['connections'][$upconn]['remote']['eap_id'] = $clienteapid;
1985
		$scconf['connections'][$upconn]['pools'] = $upbase;
1986

    
1987
		/* Craft a cloned pool with pool settings to override for this user */
1988
		$scconf['pools'][$upname]['addrs'] = "{$mkent['pool_address']}/{$mkent['pool_netbits']}";
1989
		if (isset($mkent['dns_address']) && strlen($mkent['dns_address']) > 0 && is_ipaddr($mkent['dns_address'])) {
1990
			$scconf['pools'][$upname]['dns'] = $mkent['dns_address'];
1991
		}
1992
		$suffix++;
1993
	}
1994
	return;
1995
}
1996

    
1997
/****f* ipsec/ipsec_setup_bypass
1998
 * NAME
1999
 *   ipsec_setup_bypass - Generate a bypass connection for LAN-LAN and custom rules traffic
2000
 * INPUTS
2001
 *   None
2002
 * RESULT
2003
 *   Sets up a bypass connection to prevent local traffic from being caught by
2004
 *   IPsec policies.
2005
 ******/
2006
function ipsec_setup_bypass($gateways_status) {
2007
	global $scconf;
2008

    
2009
	$scconf['connections']['bypass'] = array();
2010
	/* Prevents the connection from being considered for remote peers */
2011
	$scconf['connections']['bypass']['remote_addrs'] = "127.0.0.1";
2012
	$scconf['connections']['bypass']['children'] = array();
2013

    
2014
	/* Locate the LAN IPv4 and IPv6 subnets */
2015
	$bypassnets = array();
2016
	if (!empty(config_get_path('interfaces/lan'))) {
2017
		$lanip = get_interface_ip("lan", $gateways_status);
2018
		if (!empty($lanip) && is_ipaddrv4($lanip)) {
2019
			$lansn = get_interface_subnet("lan");
2020
			$lansa = gen_subnetv4($lanip, $lansn);
2021
			if (!empty($lansa) && !empty($lansn)) {
2022
				$bypassnets[] = "{$lansa}/{$lansn}";
2023
			}
2024
		}
2025
		$lanip6 = get_interface_ipv6("lan", $gateways_status);
2026
		if (!empty($lanip6) && is_ipaddrv6($lanip6)) {
2027
			$lansn6 = get_interface_subnetv6("lan");
2028
			$lansa6 = gen_subnetv6($lanip6, $lansn6);
2029
			if (!empty($lansa6) && !empty($lansn6)) {
2030
				$bypassnets[] = "{$lansa6}/{$lansn6}";
2031
			}
2032
		}
2033
	}
2034
	/* If we have viable targets, setup a bypass LAN connection */
2035
	if (!empty($bypassnets) && !config_path_enabled('ipsec', 'noshuntlaninterfaces')) {
2036
		$bypass = implode(',', $bypassnets);
2037
		$scconf['connections']['bypass']['children']['bypasslan'] = array();
2038
		$scconf['connections']['bypass']['children']['bypasslan']['local_ts'] = $bypass;
2039
		$scconf['connections']['bypass']['children']['bypasslan']['remote_ts'] = $bypass;
2040
		$scconf['connections']['bypass']['children']['bypasslan']['mode'] = "pass";
2041
		$scconf['connections']['bypass']['children']['bypasslan']['start_action'] = "trap";
2042
	}
2043

    
2044
	/* Setup custom bypass rules */
2045
	if (config_path_enabled('ipsec', 'ipsecbypass')) {
2046
		foreach (config_get_path('ipsec/bypassrules/rule', []) as $id => $rule) {
2047
			$scconf['connections']['bypass']['children']["rule{$id}"] = array();
2048
			$scconf['connections']['bypass']['children']["rule{$id}"]["local_ts"] = $rule['source'] .
2049
			       	"/" . $rule['srcmask'];
2050
			$scconf['connections']['bypass']['children']["rule{$id}"]["remote_ts"] = $rule['destination'] .
2051
			       	"/" . $rule['dstmask'];
2052
			$scconf['connections']['bypass']['children']["rule{$id}"]["mode"] = "pass";
2053
			$scconf['connections']['bypass']['children']["rule{$id}"]["start_action"] = "trap";
2054
		}
2055
	}
2056

    
2057
	return;
2058
}
2059

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

    
2124
/****f* ipsec/ipsec_setup_authentication
2125
 * NAME
2126
 *   ipsec_setup_authentication - Generate an array with local/remote
2127
 *                                authentication information for a given IPsec
2128
 *                                Phase 1.
2129
 * INPUTS
2130
 *   $ph1ent: An IPsec Phase 1 configuration
2131
 *   $conn  : A swanctl connection array corresponding to the IPsec Phase 1.
2132
 * RESULT
2133
 *   Populates $conn with local and remote arrays containing authentication
2134
 *   details.
2135
 ******/
2136
function ipsec_setup_authentication(& $ph1ent, & $conn, $gateways_status = false) {
2137
	global $rgmap, $ipsec_swanctl_dirs;
2138
	$local = array();
2139
	$remote = array();
2140
	$remote2 = array();
2141

    
2142
	/* Fetch gateway status if not passed */
2143
	if (!is_array($gateways_status)) {
2144
		$gateways_status = return_gateways_status(true);
2145
	}
2146

    
2147
	list($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local', array(), $gateways_status);
2148
	$localid = ipsec_fixup_id($myid_type, $myid_data);
2149
	if (!empty($localid)) {
2150
		$local['id'] = $localid;
2151
	}
2152

    
2153
	// Only specify peer ID if we are not dealing with mobile PSK
2154
	if (!(isset($ph1ent['mobile']) &&
2155
	    in_array($ph1ent['authentication_method'], array("pre_shared_key", "xauth_psk_server")))) {
2156
		list ($remoteid_type, $remoteid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap, $gateways_status);
2157
		$remoteid = ipsec_fixup_id($remoteid_type, $remoteid_data);
2158
	}
2159
	if (!empty($remoteid)) {
2160
		$remote['id'] = $remoteid;
2161
	}
2162

    
2163
	if (!empty($ph1ent['caref'])) {
2164
		$ca = lookup_ca($ph1ent['caref']);
2165
		if ($ca) {
2166
			/* Get hash value to use for filename */
2167
			$ca_details = openssl_x509_parse(base64_decode($ca['crt']));
2168
			$cafn = "{$ipsec_swanctl_dirs['capath']}/{$ca_details['hash']}.0";
2169
		}
2170
	}
2171

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

    
2244
	$conn['local'] = $local;
2245
	/* If there is data for a second remote auth round, setup two remote
2246
	 * arrays with unique names, otherwise setup a single remote. */
2247
	if (empty($remote2)) {
2248
		$conn['remote'] = $remote;
2249
	} else {
2250
		$conn['remote-1'] = $remote;
2251
		$conn['remote-2'] = $remote2;
2252
	}
2253
}
2254

    
2255
/****f* ipsec/ipsec_setup_proposal_algo
2256
 * NAME
2257
 *   ipsec_setup_proposal_algo - Form a single proposal algorithm string
2258
 * INPUTS
2259
 *   $ealg_id: Encryption algorithm ID
2260
 *   $keylen : Key length for the encryption algorithm
2261
 *   $halgo  : Hash algorithm
2262
 *   $modp   : DH Group number
2263
 * RESULT
2264
 *   Returns a string using the available information to form a single proposal
2265
 *   algorithm definition.
2266
 * NOTES
2267
 *   Values left empty will not be added to the string. Some combinations may
2268
 *   require one or more parts to be omitted.
2269
 ******/
2270
function ipsec_setup_proposal_algo($ealg_id, $keylen, $halgo, $prfalgo, $modp) {
2271
	$palgo = "";
2272

    
2273
	/* Add the encryption algorithm (if present) */
2274
	if (!empty($ealg_id)) {
2275
		$palgo .= "{$ealg_id}";
2276
	}
2277

    
2278
	/* Add the key length (if present) */
2279
	if (!empty($keylen)) {
2280
		$palgo .= "{$keylen}";
2281
	}
2282

    
2283
	/* Add the hash algorithm (if present) */
2284
	if (!empty($halgo)) {
2285
		/* If there is some content in the proposal already, add a
2286
		 * separator */
2287
		if (!empty($palgo)) {
2288
			$palgo .= "-";
2289
		}
2290
		$halgo = str_replace('hmac_', '', $halgo);
2291
		$palgo .= "{$halgo}";
2292
	}
2293

    
2294
	if (!empty($prfalgo)) {
2295
		$palgo .= "-prf{$prfalgo}";
2296
	}
2297

    
2298
	/* Convert the DH group to its keyword and add (if present) */
2299
	$modp = ipsec_convert_to_modp($modp);
2300
	if (!empty($modp)) {
2301
		$palgo .= "-{$modp}";
2302
	}
2303

    
2304
	return $palgo;
2305
}
2306

    
2307
/****f* ipsec/ipsec_setup_proposal_entry
2308
 * NAME
2309
 *   ipsec_setup_proposal_entry - Generate a full proposal string for an IPsec
2310
 *                                Phase 2 configuration.
2311
 * INPUTS
2312
 *   $ph2ent  : An IPsec Phase 2 configuration
2313
 *   $algo_arr: An array in which all proposal algorithms are collected
2314
 *   $ealg_id : Encryption algorithm ID
2315
 *   $keylen  : Key length for the encryption algorithm
2316
 * RESULT
2317
 *   Returns a string containing all proposal elements, and merges the entries
2318
 *   to $algo_arr as well.
2319
 ******/
2320
function ipsec_setup_proposal_entry(& $ph2ent, & $algo_arr, $ealg_id, $keylen) {
2321
	global $p2_ealgos;
2322
	$proposal = array();
2323

    
2324
	/* If multiple hash algorithms are present, loop through and add them all. */
2325
	if (!empty($ph2ent['hash-algorithm-option']) && is_array($ph2ent['hash-algorithm-option']) 
2326
	    && !(strpos($ealg_id, "gcm") || $ealg_id == "chacha20poly1305")) {
2327
		foreach ($ph2ent['hash-algorithm-option'] as $halgo) {
2328
			$proposal[] = ipsec_setup_proposal_algo($ealg_id, $keylen, $halgo, false, $ph2ent['pfsgroup']);
2329
		}
2330
	} else {
2331
		$proposal[] = ipsec_setup_proposal_algo($ealg_id, $keylen, false, false, $ph2ent['pfsgroup']);
2332
	}
2333

    
2334
	/* Add to master list */
2335
	$algo_arr = array_merge($algo_arr, $proposal);
2336
	return implode(',', $proposal);
2337
}
2338

    
2339
function ipsec_get_ifname($p1, $reqid = 0) {
2340
	$ifname = "ipsec";
2341
	if ($reqid > 0) {
2342
		$ifname .= "{$reqid}";
2343
	} else {
2344
		$p2s = ipsec_get_phase2_by_ikeid($p1['ikeid']);
2345
		if (!empty($p2s)) {
2346
			$ifname .= $p2s[0]['reqid'];
2347
		}
2348
	}
2349
	return $ifname;
2350
}
2351

    
2352
function ipsec_get_ifname_by_conf($p1 = array(), $p2 = array()) {
2353
	$have_p1 = (!empty($p1) && is_array($p1));
2354
	$have_p2 = (!empty($p2) && is_array($p2));
2355
	$reqid = null;
2356

    
2357
	if (!$have_p1 && $have_p2) {
2358
		$p1 = ipsec_get_phase1($p2['ikeid']);
2359
	}
2360

    
2361
	if ($have_p2) {
2362
		$reqid = $p2['reqid'];
2363
	}
2364

    
2365
	return ipsec_get_ifname($p1, $reqid);
2366
}
2367

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

    
2399
/****f* ipsec/ipsec_setup_tunnels
2400
 * NAME
2401
 *   ipsec_setup_tunnels - Configure all P1/P2 entries as swanctl connections
2402
 * INPUTS
2403
 *   None
2404
 * RESULT
2405
 *   Sets up a swanctl array for all connections in the configuration along with
2406
 *   their children, authentication, etc.
2407
 ******/
2408
function ipsec_setup_tunnels($gateways_status = false) {
2409
	global $aggressive_mode_psk,
2410
		$filterdns_list, $g, $ifacesuse, $ipsec_idhandling, $ipsec_log_cats,
2411
		$ipsec_log_sevs, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs,
2412
		$ipseccfg, $mobile_ipsec_auth, $natfilterrules, $p1_ealgos,
2413
		$p2_ealgos, $rgmap, $sa, $sn, $scconf, $conn, $tunnels,
2414
		$ipsec_vti_cleanup_ifs, $conn_defaults;
2415

    
2416
	/* Fetch gateway status if not passed */
2417
	if (!is_array($gateways_status)) {
2418
		$gateways_status = return_gateways_status(true);
2419
	}
2420

    
2421
	$a_groups = return_gateway_groups_array(true);
2422

    
2423
	foreach ($tunnels as $ph1ent) {
2424
		/* Skip disabled entries */
2425
		if (isset($ph1ent['disabled'])) {
2426
			continue;
2427
		}
2428
		/* If the tunnel has no encryption algorithms, it isn't valid. */
2429
		if (count(array_get_path($ph1ent, 'encryption/item', [])) == 0) {
2430
			continue;
2431
		}
2432
		/* If the local source is invalid, skip this entry. */
2433
		$local_spec = ipsec_get_phase1_src($ph1ent, $gateways_status);
2434
		if (!$local_spec) {
2435
			continue;
2436
		}
2437

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

    
2460
		/* Common parameters for all children */
2461
		$child_params = array();
2462
		if (!empty($ph1ent['closeaction'])) {
2463
			$child_params['close_action'] = $ph1ent['closeaction'];
2464
		}
2465

    
2466
		$ikeid = $ph1ent['ikeid'];
2467

    
2468
		$carpbackup = false;
2469
		if (((substr($ph1ent['interface'], 0, 4) == "_vip") &&
2470
		    in_array(get_carp_bind_status($ph1ent['interface']), array('BACKUP', 'INIT'))) ||
2471
		    (is_array($a_groups[$ph1ent['interface']]) &&
2472
		    !empty($a_groups[$ph1ent['interface']][0]['vip']) &&
2473
		    in_array(get_carp_bind_status($a_groups[$ph1ent['interface']][0]['vip']), array('BACKUP', 'INIT')))) {
2474
			$carpbackup = true;
2475
		}
2476

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

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

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

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

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

    
2536
		/* Configure DPD values. The DPD action is a per-child parameter,
2537
		 * not per-connection like the delay and timeout. */
2538
		if ($ph1ent['dpd_delay'] && $ph1ent['dpd_maxfail']) {
2539
			if ($start_action == "trap") {
2540
				$child_params['dpd_action'] = "trap";
2541
			} else {
2542
				$child_params['dpd_action'] = "clear";
2543
			}
2544
			$conn['dpd_delay'] = "{$ph1ent['dpd_delay']}s";
2545
			if ($ph1ent['iketype'] == 'ikev1') {
2546
				/* in IKEv2 the default retransmission timeout applies,
2547
				 * see https://redmine.pfsense.org/issues/12184 */
2548
				$conn['dpd_timeout'] =  $ph1ent['dpd_delay'] * ($ph1ent['dpd_maxfail'] + 1) . "s";
2549
			}
2550

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2659
				$local_ts = $localsubnet_data;
2660

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2882
	return;
2883
}
2884

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

    
2897
	$suffix = 0;
2898

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

    
2904
	$vpncas = array();
2905
	foreach (config_get_path('ipsec/phase1', []) as $ph1ent) {
2906
		if (isset($ph1ent['disabled'])) {
2907
			continue;
2908
		}
2909

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3164
	$mobile_configured = false;
3165

    
3166

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

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

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

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

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

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

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

    
3255
	/* set default MTU to 1400 for GRE over IPsec, otherwise to 1476 */
3256
	ipsec_gre_default_mtu(); 
3257

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

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

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

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

    
3292
		if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid")) {
3293
			if ($filterdns_restart) {
3294
				killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3295
				sleep(2);
3296
				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");
3297
			} else {
3298
				sigkillbypid("{$g['varrun_path']}/filterdns-ipsec.pid", "HUP");
3299
			}
3300
		} else {
3301
			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");
3302
		}
3303
	} else {
3304
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
3305
		@unlink("{$g['varrun_path']}/filterdns-ipsec.pid");
3306
	}
3307

    
3308
	if (platform_booting()) {
3309
		echo "done\n";
3310
	}
3311

    
3312
	unlock($ipsecstartlock);
3313
	return count($filterdns_list);
3314
}
3315

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

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

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

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

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

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

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

    
3440
?>
(26-26/61)