Project

General

Profile

Download (82.9 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-2020 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

    
29
/* IPsec defines */
30
global $ipsec_loglevels;
31
$ipsec_loglevels = array(
32
	"dmn" => gettext("Daemon"),
33
	"mgr" => gettext("SA Manager"),
34
	"ike" => gettext("IKE SA"),
35
	"chd" => gettext("IKE Child SA"),
36
	"job" => gettext("Job Processing"),
37
	"cfg" => gettext("Configuration backend"),
38
	"knl" => gettext("Kernel Interface"),
39
	"net" => gettext("Networking"),
40
	"asn" => gettext("ASN encoding"),
41
	"enc" => gettext("Message encoding"),
42
	"imc" => gettext("Integrity checker"),
43
	"imv" => gettext("Integrity Verifier"),
44
	"pts" => gettext("Platform Trust Service"),
45
	"tls" => gettext("TLS handler"),
46
	"esp" => gettext("IPsec traffic"),
47
	"lib" => gettext("StrongSwan Lib")
48
);
49

    
50
global $ipsec_log_sevs;
51
$ipsec_log_sevs = array(
52
	'-1' => gettext('Silent'),
53
	'0' => gettext('Audit'),
54
	'1' => gettext('Control'),
55
	'2' => gettext('Diag'),
56
	'3' => gettext('Raw'),
57
	'4' => gettext('Highest')
58
);
59

    
60
global $ipsec_log_cats;
61
$ipsec_log_cats = array(
62
	"dmn" => gettext("Daemon"),
63
	"mgr" => gettext("SA Manager"),
64
	"ike" => gettext("IKE SA"),
65
	"chd" => gettext("IKE Child SA"),
66
	"job" => gettext("Job Processing"),
67
	"cfg" => gettext("Configuration backend"),
68
	"knl" => gettext("Kernel Interface"),
69
	"net" => gettext("Networking"),
70
	"asn" => gettext("ASN encoding"),
71
	"enc" => gettext("Message encoding"),
72
	"imc" => gettext("Integrity checker"),
73
	"imv" => gettext("Integrity Verifier"),
74
	"pts" => gettext("Platform Trust Service"),
75
	"tls" => gettext("TLS handler"),
76
	"esp" => gettext("IPsec traffic"),
77
	"lib" => gettext("StrongSwan Lib")
78
);
79

    
80
global $ipsec_identifier_list;
81
$ipsec_identifier_list = array(
82
	// 'ipv4' => array('desc' => gettext('IPv4 address'), 'mobile' => true),
83
	// 'ipv6' => array('desc' => gettext('IPv6 address'), 'mobile' => true),
84
	// 'rfc822' => array('desc' => gettext('RFC822'), 'mobile' => true),
85
	'none' => array('desc' => '', 'mobile' => true),
86
	'email' => array('desc' => gettext('E-mail address'), 'mobile' => true),
87
	'userfqdn' => array('desc' => gettext('User Fully Qualified Domain Name'), 'mobile' => true)
88
	// 'fqdn' => array('desc' => gettext('Fully Qualified Domain Name'), 'mobile' => true),
89
	// 'dns' => array('desc' => gettext('DNS'), 'mobile' => true),
90
	// 'asn1dn' => array('desc' => gettext('ASN.1 Distinguished Name'), 'mobile' => true),
91
	// 'asn1gn' => array('desc' => gettext('ASN.1 GN'), 'mobile' => true),
92
	// 'keyid' => array('desc' => gettext('KeyID'), 'mobile' => true)
93
);
94

    
95
global $my_identifier_list;
96
$my_identifier_list = array(
97
	'myaddress' => array('desc' => gettext('My IP address'), 'mobile' => true),
98
	'address' => array('desc' => gettext('IP address'), 'mobile' => true),
99
	'fqdn' => array('desc' => gettext('Distinguished name'), 'mobile' => true),
100
	'user_fqdn' => array('desc' => gettext('User distinguished name'), 'mobile' => true),
101
	'asn1dn' => array('desc' => gettext('ASN.1 distinguished Name'), 'mobile' => true),
102
	'keyid tag' => array('desc' => gettext('KeyID tag'), 'mobile' => true),
103
	'dyn_dns' => array('desc' => gettext('Dynamic DNS'), 'mobile' => true)
104
);
105

    
106
global $peer_identifier_list;
107
$peer_identifier_list = array(
108
	'any' => array('desc' => gettext('Any'), 'mobile' => true),
109
	'peeraddress' => array('desc' => gettext('Peer IP address'), 'mobile' => false),
110
	'address' => array('desc' => gettext('IP address'), 'mobile' => false),
111
	'fqdn' => array('desc' => gettext('Distinguished name'), 'mobile' => true),
112
	'user_fqdn' => array('desc' => gettext('User distinguished name'), 'mobile' => true),
113
	'asn1dn' => array('desc' => gettext('ASN.1 distinguished Name'), 'mobile' => true),
114
	'keyid tag' => array('desc' =>gettext('KeyID tag'), 'mobile' => true)
115
);
116

    
117
global $ipsec_idhandling;
118
$ipsec_idhandling = array(
119
	'replace' => 'Yes (Replace)', 'no' => 'No', 'never' => 'Never', 'keep' => 'Keep'
120
);
121

    
122
global $p1_ealgos;
123
$p1_ealgos = array(
124
	'aes' => array('name' => 'AES', 'keysel' => array('lo' => 128, 'hi' => 256, 'step' => 64)),
125
	'aes128gcm' => array('name' => 'AES128-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
126
	'aes192gcm' => array('name' => 'AES192-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
127
	'aes256gcm' => array('name' => 'AES256-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
128
	'blowfish' => array('name' => 'Blowfish', 'keysel' => array('lo' => 128, 'hi' => 256, 'step' => 64)),
129
	'3des' => array('name' => '3DES'),
130
	'cast128' => array('name' => 'CAST128')
131
);
132

    
133
global $p2_ealgos;
134
$p2_ealgos = array(
135
	'aes' => array('name' => 'AES', 'keysel' => array('lo' => 128, 'hi' => 256, 'step' => 64)),
136
	'aes128gcm' => array('name' => 'AES128-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
137
	'aes192gcm' => array('name' => 'AES192-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
138
	'aes256gcm' => array('name' => 'AES256-GCM', 'keysel' => array('lo' => 64, 'hi' => 128, 'step' => 32)),
139
	'blowfish' => array('name' => 'Blowfish', 'keysel' => array('lo' => 128, 'hi' => 256, 'step' => 64)),
140
	'3des' => array('name' => '3DES'),
141
	'cast128' => array('name' => 'CAST128')
142
);
143

    
144
global $p1_halgos;
145
$p1_halgos = array(
146
	'md5' => 'MD5',
147
	'sha1' => 'SHA1',
148
	'sha256' => 'SHA256',
149
	'sha384' => 'SHA384',
150
	'sha512' => 'SHA512',
151
	'aesxcbc' => 'AES-XCBC'
152
);
153

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

    
180
global $p2_halgos;
181
$p2_halgos = array(
182
	'hmac_md5' => 'MD5',
183
	'hmac_sha1' => 'SHA1',
184
	'hmac_sha256' => 'SHA256',
185
	'hmac_sha384' => 'SHA384',
186
	'hmac_sha512' => 'SHA512',
187
	'aesxcbc' => 'AES-XCBC'
188
);
189

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

    
203
global $ipsec_preshared_key_type;
204
$ipsec_preshared_key_type = array(
205
	'PSK' => 'PSK',
206
	'EAP' => 'EAP'
207
);
208

    
209
global $ipsec_closeactions;
210
$ipsec_closeactions = array(
211
	'' => gettext('Default'),
212
	'none' => gettext('No action'),
213
	'restart' => gettext('Restart/Reconnect'),
214
	'clear' => gettext('Close connection and clear SA'),
215
	'hold' => gettext('Close connection and reconnect on demand'),
216
);
217

    
218
global $p2_modes;
219
$p2_modes = array(
220
	'tunnel' => gettext('Tunnel IPv4'),
221
	'tunnel6' => gettext('Tunnel IPv6'),
222
	'transport' => gettext('Transport'),
223
	'vti' => gettext('Routed (VTI)')
224
);
225

    
226
global $p2_protos;
227
$p2_protos = array(
228
	'esp' => 'ESP',
229
	'ah' => 'AH'
230
);
231

    
232
global $p2_pfskeygroups;
233
$p2_pfskeygroups = array(
234
	0 => gettext('off'),
235
	1  => gettext('1 (768 bit)'),
236
	2  => gettext('2 (1024 bit)'),
237
	5  => gettext('5 (1536 bit)'),
238
	14 => gettext('14 (2048 bit)'),
239
	15 => gettext('15 (3072 bit)'),
240
	16 => gettext('16 (4096 bit)'),
241
	17 => gettext('17 (6144 bit)'),
242
	18 => gettext('18 (8192 bit)'),
243
	19 => gettext('19 (nist ecp256)'),
244
	20 => gettext('20 (nist ecp384)'),
245
	21 => gettext('21 (nist ecp521)'),
246
	22 => gettext('22 (1024(sub 160) bit)'),
247
	23 => gettext('23 (2048(sub 224) bit)'),
248
	24 => gettext('24 (2048(sub 256) bit)'),
249
	25 => gettext('25 (nist ecp192)'),
250
	26 => gettext('26 (nist ecp224)'),
251
	27 => gettext('27 (brainpool ecp224)'),
252
	28 => gettext('28 (brainpool ecp256)'),
253
	29 => gettext('29 (brainpool ecp384)'),
254
	30 => gettext('30 (brainpool ecp512)'),
255
	31 => gettext('31 (Elliptic Curve 25519, 256 bit)'),
256
	32 => gettext('32 (Elliptic Curve 25519, 448 bit)'),
257
);
258

    
259
function ipsec_enabled() {
260
	global $config;
261

    
262
	if (!isset($config['ipsec']) || !is_array($config['ipsec'])) {
263
		return false;
264
	}
265

    
266
	/* Check if we have at least one phase 1 entry. */
267
	if (!isset($config['ipsec']['phase1']) ||
268
	    !is_array($config['ipsec']['phase1']) ||
269
	    empty($config['ipsec']['phase1'])) {
270
		return false;
271
	}
272
	/* Check if at least one phase 1 entry is enabled. */
273
	foreach ($config['ipsec']['phase1'] as $phase1) {
274
		if (!isset($phase1['disabled'])) {
275
			return true;
276
		}
277
	}
278

    
279
	return false;
280
}
281

    
282
/*
283
 * ikeid management functions
284
 */
285

    
286
function ipsec_ikeid_used($ikeid) {
287
	global $config;
288

    
289
	foreach ($config['ipsec']['phase1'] as $ph1ent) {
290
		if ($ikeid == $ph1ent['ikeid']) {
291
			return true;
292
		}
293
	}
294

    
295
	return false;
296
}
297

    
298
function ipsec_ikeid_next() {
299

    
300
	$ikeid = 1;
301
	while (ipsec_ikeid_used($ikeid)) {
302
		$ikeid++;
303
	}
304

    
305
	return $ikeid;
306
}
307

    
308
/*
309
 * Return phase1 local address
310
 */
311
function ipsec_get_phase1_src(& $ph1ent) {
312

    
313
	if ($ph1ent['interface']) {
314
		if (substr($ph1ent['interface'], 0, 4) == "_vip") {
315
			$if = $ph1ent['interface'];
316
		} else {
317
			$if = get_failover_interface($ph1ent['interface']);
318
		}
319
	} else {
320
		$if = "wan";
321
	}
322
	$ip6 = get_interface_ipv6($if);
323
	$ip4 = get_interface_ip($if);
324
	if ($ph1ent['protocol'] == "inet6") {
325
		$interfaceip = $ip6;
326
	} elseif ($ph1ent['protocol'] == "inet") {
327
		$interfaceip = $ip4;
328
	} elseif ($ph1ent['protocol'] == "both") {
329
		$ifips = array();
330
		if (!empty($ip4)) {
331
			$ifips[] = $ip4;
332
		}
333
		if (!empty($ip6)) {
334
			$ifips[] = $ip6;
335
		}
336
		$interfaceip = implode(',', $ifips);
337
	}
338

    
339
	return $interfaceip;
340
}
341

    
342
/*
343
 * Return phase1 local address
344
 */
345
function ipsec_get_phase1_dst(& $ph1ent) {
346
	global $g;
347

    
348
	if (empty($ph1ent['remote-gateway'])) {
349
		return false;
350
	}
351
	$rg = $ph1ent['remote-gateway'];
352
	if (!is_ipaddr($rg)) {
353
		if (!platform_booting()) {
354
			return resolve_retry($rg);
355
		}
356
	}
357
	if (!is_ipaddr($rg)) {
358
		return false;
359
	}
360

    
361
	return $rg;
362
}
363

    
364
/*
365
 * Return phase2 idinfo in cidr format
366
 */
367
function ipsec_idinfo_to_cidr(& $idinfo, $addrbits = false, $mode = "") {
368
	global $config;
369

    
370
	switch ($idinfo['type']) {
371
		case "address":
372
			if ($addrbits) {
373
				if ($mode == "tunnel6") {
374
					return $idinfo['address']."/128";
375
				} else {
376
					return $idinfo['address']."/32";
377
				}
378
			} else {
379
				return $idinfo['address'];
380
			}
381
			break; /* NOTREACHED */
382
		case "network":
383
			return "{$idinfo['address']}/{$idinfo['netbits']}";
384
			break; /* NOTREACHED */
385
		case "none":
386
		case "mobile":
387
			return '0.0.0.0/0';
388
			break; /* NOTREACHED */
389
		default:
390
			if (empty($mode) && !empty($idinfo['mode'])) {
391
				$mode = $idinfo['mode'];
392
			}
393

    
394
			if ($mode == "tunnel6") {
395
				$address = get_interface_ipv6($idinfo['type']);
396
				$netbits = get_interface_subnetv6($idinfo['type']);
397
				$address = gen_subnetv6($address, $netbits);
398
				return "{$address}/{$netbits}";
399
			} else {
400
				$address = get_interface_ip($idinfo['type']);
401
				$netbits = get_interface_subnet($idinfo['type']);
402
				$address = gen_subnet($address, $netbits);
403
				return "{$address}/{$netbits}";
404
			}
405
			break; /* NOTREACHED */
406
	}
407
}
408

    
409
/*
410
 * Return phase2 idinfo in address/netmask format
411
 */
412
function ipsec_idinfo_to_subnet(& $idinfo, $addrbits = false) {
413
	global $config;
414

    
415
	switch ($idinfo['type']) {
416
		case "address":
417
			if ($addrbits) {
418
				if ($idinfo['mode'] == "tunnel6") {
419
					return $idinfo['address']."/128";
420
				} else {
421
					return $idinfo['address']."/255.255.255.255";
422
				}
423
			} else {
424
				return $idinfo['address'];
425
			}
426
			break; /* NOTREACHED */
427
		case "none":
428
		case "network":
429
			return $idinfo['address']."/".gen_subnet_mask($idinfo['netbits']);
430
			break; /* NOTREACHED */
431
		case "mobile":
432
			return "0.0.0.0/0";
433
			break; /* NOTREACHED */
434
		default:
435
			if ($idinfo['mode'] == "tunnel6") {
436
				$address = get_interface_ipv6($idinfo['type']);
437
				$netbits = get_interface_subnetv6($idinfo['type']);
438
				$address = gen_subnetv6($address, $netbits);
439
				return $address."/".$netbits;
440
			} else {
441
				$address = get_interface_ip($idinfo['type']);
442
				$netbits = get_interface_subnet($idinfo['type']);
443
				$address = gen_subnet($address, $netbits);
444
				return $address."/".$netbits;
445
			}
446
			break; /* NOTREACHED */
447
	}
448
}
449

    
450
/*
451
 *  Return phase2 idinfo in text format
452
 */
453
function ipsec_idinfo_to_text(& $idinfo) {
454
	global $config;
455

    
456
	switch ($idinfo['type']) {
457
		case "address":
458
			return $idinfo['address'];
459
			break; /* NOTREACHED */
460
		case "network":
461
			return $idinfo['address']."/".$idinfo['netbits'];
462
			break; /* NOTREACHED */
463
		case "mobile":
464
			return gettext("Mobile Client");
465
			break; /* NOTREACHED */
466
		case "none":
467
			return gettext("None");
468
			break; /* NOTREACHED */
469
		default:
470
			if (!empty($config['interfaces'][$idinfo['type']])) {
471
				return convert_friendly_interface_to_friendly_descr($idinfo['type']);
472
			} else {
473
				return strtoupper($idinfo['type']);
474
			}
475
			break; /* NOTREACHED */
476
	}
477
}
478

    
479
/*
480
 * Return phase1 association for phase2
481
 */
482
function ipsec_lookup_phase1(& $ph2ent, & $ph1ent) {
483
	global $config;
484

    
485
	if (!is_array($config['ipsec'])) {
486
		return false;
487
	}
488
	if (!is_array($config['ipsec']['phase1'])) {
489
		return false;
490
	}
491
	if (empty($config['ipsec']['phase1'])) {
492
		return false;
493
	}
494

    
495
	foreach ($config['ipsec']['phase1'] as $ph1tmp) {
496
		if ($ph1tmp['ikeid'] == $ph2ent['ikeid']) {
497
			$ph1ent = $ph1tmp;
498
			return $ph1ent;
499
		}
500
	}
501

    
502
	return false;
503
}
504

    
505
/*
506
 * Check phase1 communications status
507
 */
508
function ipsec_phase1_status(&$ipsec_status, $ikeid) {
509

    
510
	foreach ($ipsec_status as $ike) {
511
		if ($ike['id'] == $ikeid) {
512
			if ($ike['status'] == 'established') {
513
				return true;
514
			}
515
		}
516
	}
517

    
518
	return false;
519
}
520

    
521
/*
522
 * Check phase2 communications status
523
 */
524
function ipsec_phase2_status(&$ipsec_status, &$phase2) {
525

    
526
	if (ipsec_lookup_phase1($ph2ent, $ph1ent)) {
527
		return ipsec_phase1_status($ipsec_status, $ph1ent['ikeid']);
528
	}
529

    
530
	return false;
531
}
532

    
533
/*
534
 * Wrapper to call pfSense_ipsec_list_sa() when IPsec is enabled
535
 */
536
function ipsec_list_sa() {
537

    
538
	if (ipsec_enabled()) {
539
		return pfSense_ipsec_list_sa();
540
	}
541

    
542
	return array();
543
}
544

    
545
/*
546
 * Return dump of SPD table
547
 */
548
function ipsec_dump_spd() {
549
	$fd = @popen("/sbin/setkey -DP", "r");
550
	$spd = array();
551
	if ($fd) {
552
		while (!feof($fd)) {
553
			$line = chop(fgets($fd));
554
			if (!$line) {
555
				continue;
556
			}
557
			if ($line == "No SPD entries.") {
558
				break;
559
			}
560
			if ($line[0] != "\t") {
561
				if (is_array($cursp)) {
562
					$spd[] = $cursp;
563
				}
564
				$cursp = array();
565
				$linea = explode(" ", $line);
566
				$cursp['srcid'] = substr($linea[0], 0, strpos($linea[0], "["));
567
				$cursp['dstid'] = substr($linea[1], 0, strpos($linea[1], "["));
568
				$i = 0;
569
			} else if (is_array($cursp)) {
570
				$line = trim($line, "\t\r\n ");
571
				$linea = explode(" ", $line);
572
				switch ($i) {
573
					case 1:
574
						if ($linea[1] == "none")	/* don't show default anti-lockout rule */ {
575
							unset($cursp);
576
						} else {
577
							$cursp['dir'] = $linea[0];
578
						}
579
						break;
580
					case 2:
581
						$upperspec = explode("/", $linea[0]);
582
						$cursp['proto'] = $upperspec[0];
583
						list($cursp['src'], $cursp['dst']) = explode("-", $upperspec[2]);
584
						$cursp['reqid'] = substr($upperspec[3], strpos($upperspec[3], "#")+1);
585
						break;
586
				}
587
			}
588
			$i++;
589
		}
590
		if (is_array($cursp) && count($cursp)) {
591
			$spd[] = $cursp;
592
		}
593
		pclose($fd);
594
	}
595

    
596
	return $spd;
597
}
598

    
599
/*
600
 * Return dump of SAD table
601
 */
602
function ipsec_dump_sad() {
603
	$fd = @popen("/sbin/setkey -D", "r");
604
	$sad = array();
605
	if ($fd) {
606
		while (!feof($fd)) {
607
			$line = chop(fgets($fd));
608
			if (!$line || $line[0] == " ") {
609
				continue;
610
			}
611
			if ($line == "No SAD entries.") {
612
				break;
613
			}
614
			if ($line[0] != "\t") {
615
				if (is_array($cursa)) {
616
					$sad[] = $cursa;
617
				}
618
				$cursa = array();
619
				list($cursa['src'], $cursa['dst']) = explode(" ", $line);
620
			} else {
621
				$line = trim($line, "\t\n\r ");
622
				$linea = explode(" ", $line);
623
				foreach ($linea as $idx => $linee) {
624
					if ($linee == 'esp' || $linee == 'ah' || $linee[0] == '#') {
625
						$cursa['proto'] = $linee;
626
					} else if (substr($linee, 0, 3) == 'spi') {
627
						$cursa['spi'] = substr($linee, strpos($linee, 'x') + 1, -1);
628
					} else if (substr($linee, 0, 5) == 'reqid') {
629
						$cursa['reqid'] = substr($linee, strpos($linee, 'x') + 1, -1);
630
					} else if (substr($linee, 0, 2) == 'E:') {
631
						$cursa['ealgo'] = $linea[$idx + 1];
632
						break;
633
					} else if (substr($linee, 0, 2) == 'A:') {
634
						$cursa['aalgo'] = $linea[$idx + 1];
635
						break;
636
					} else if (substr($linee, 0, 8) == 'current:') {
637
						$cursa['data'] = substr($linea[$idx + 1], 0, strpos($linea[$idx + 1], 'bytes') - 1) . ' B';
638
						break;
639
					}
640
				}
641
			}
642
		}
643
		if (is_array($cursa) && count($cursa)) {
644
			$sad[] = $cursa;
645
		}
646
		pclose($fd);
647
	}
648

    
649
	return $sad;
650
}
651

    
652
/*
653
 * Return dump of mobile user list
654
 */
655
function ipsec_dump_mobile() {
656
	global $g, $config;
657

    
658
	if(!isset($config['ipsec']['client']['enable'])) {
659
		return array();
660
	}
661

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

    
665
	if ($rc != 0) {
666
		log_error(gettext("Unable to find IPsec daemon leases file. Could not display mobile user stats!"));
667
		return array();
668
	}
669

    
670
	$response = array(
671
		'pool' => array(),
672
	);
673

    
674
	/* swanctl --list-pools --leases example output, field names can be confirmed by
675
	 * looking at --raw or --pretty output. */
676
	/* mobile-pool          10.7.200.0                          0 / 1 / 254 */
677
	$pool_regex='/^(?P<name>\S+)\s+(?P<base>\S+)\s+(?P<online>\d+) \/ (?P<offline>\d+) \/ (?P<size>\d+)/';
678
	/*   10.7.200.1                     online   'jimp' */
679
	$lease_regex='/\s*(?P<host>[\d\.]+)\s+(?P<status>online|offline)\s+\'(?P<id>.*)\'/';
680
	foreach ($output as $line) {
681
		if (preg_match($pool_regex, $line, $matches)) {
682
			$id++;
683
			$response['pool'][$id] = array(
684
			    'name'   => $matches['name'],
685
			    'base'   => $matches['base'],
686
			    'online' => $matches['online'],
687
			    'offline'  => $matches['offline'],
688
			    'size'   => $matches['size'],
689
			);
690
		} elseif (preg_match($lease_regex, $line, $matches)) {
691
			$response['pool'][$id]['lease'][] = array(
692
			    'host'   => $matches['host'],
693
			    'status' => $matches['status'],
694
			    'id'     => $matches['id']
695
			);
696
		}
697
	}
698

    
699
	unset($_gb, $output, $rc, $pool_regex);
700

    
701
	return $response;
702
}
703

    
704
function ipsec_mobilekey_sort() {
705
	global $config;
706

    
707
	function mobilekeycmp($a, $b) {
708
		return strcmp($a['ident'][0], $b['ident'][0]);
709
	}
710

    
711
	usort($config['ipsec']['mobilekey'], "mobilekeycmp");
712
}
713

    
714
function ipsec_get_number_of_phase2($ikeid) {
715
	global $config;
716
	$a_phase2 = $config['ipsec']['phase2'];
717

    
718
	$nbph2 = 0;
719

    
720
	if (is_array($a_phase2) && count($a_phase2)) {
721
		foreach ($a_phase2 as $ph2tmp) {
722
			if ($ph2tmp['ikeid'] == $ikeid) {
723
				$nbph2++;
724
			}
725
		}
726
	}
727

    
728
	return $nbph2;
729
}
730

    
731
function ipsec_get_descr($ikeid) {
732
	global $config;
733

    
734
	if (!isset($config['ipsec']['phase1']) ||
735
	    !is_array($config['ipsec']['phase1'])) {
736
		return '';
737
	}
738

    
739
	foreach ($config['ipsec']['phase1'] as $p1) {
740
		if ($p1['ikeid'] == $ikeid) {
741
			return $p1['descr'];
742
		}
743
	}
744

    
745
	return '';
746
}
747

    
748
function ipsec_get_phase1($ikeid) {
749
		global $config;
750

    
751
		if (!isset($config['ipsec']['phase1']) ||
752
		    !is_array($config['ipsec']['phase1'])) {
753
			return '';
754
		}
755

    
756
		$a_phase1 = $config['ipsec']['phase1'];
757
		foreach ($a_phase1 as $p1) {
758
			if ($p1['ikeid'] == $ikeid) {
759
				return $p1;
760
			}
761
		}
762
		unset($a_phase1);
763
}
764

    
765
function ipsec_fixup_ip($ipaddr) {
766
	if (is_ipaddrv6($ipaddr) || is_subnetv6($ipaddr)) {
767
		return text_to_compressed_ip6($ipaddr);
768
	} else {
769
		return $ipaddr;
770
	}
771
}
772

    
773
function ipsec_find_id(& $ph1ent, $side = "local", $rgmap = array()) {
774
	if ($side == "local") {
775
		$id_type = $ph1ent['myid_type'];
776
		$id_data = $ph1ent['myid_data'];
777

    
778
		$addr = ipsec_get_phase1_src($ph1ent);
779
		if (!$addr) {
780
			return array();
781
		}
782
		/* When automatically guessing, use the first address. */
783
		$addr = explode(',', $addr);
784
		$addr = $addr[0];
785
	} elseif ($side == "peer") {
786
		$id_type = $ph1ent['peerid_type'];
787
		$id_data = $ph1ent['peerid_data'];
788

    
789
		if (isset($ph1ent['mobile'])) {
790
			$addr = "%any";
791
		} else {
792
			$addr = $ph1ent['remote-gateway'];
793
		}
794
	} else {
795
		return array();
796
	}
797

    
798

    
799
	$thisid_type = $id_type;
800
	switch ($thisid_type) {
801
		case 'myaddress':
802
			$thisid_type = 'address';
803
			$thisid_data = $addr;
804
			break;
805
		case 'dyn_dns':
806
			$thisid_type = 'dns';
807
			$thisid_data = $id_data;
808
			break;
809
		case 'peeraddress':
810
			$thisid_type = 'address';
811
			$thisid_data = $rgmap[$ph1ent['remote-gateway']];
812
			break;
813
		case 'address':
814
			$thisid_data = $id_data;
815
			break;
816
		case 'fqdn':
817
			$thisid_data = "{$id_data}";
818
			break;
819
		case 'keyid tag':
820
			$thisid_type = 'keyid';
821
			$thisid_data = "{$id_data}";
822
			break;
823
		case 'user_fqdn':
824
			$thisid_type = 'userfqdn';
825
			$thisid_data = "{$id_data}";
826
			break;
827
		case 'asn1dn':
828
			$thisid_data = $id_data;
829
			break;
830
	}
831
	return array($thisid_type, $thisid_data);
832
}
833

    
834
/*
835
 * Fixup ID type/data to include prefix when necessary, add quotes, etc.
836
 */
837
function ipsec_fixup_id($type, $data) {
838
	/* List of types to pass through as-is without changes or adding prefix */
839
	$auto_types = array('address');
840
	/* List of types which need the resulting string double quoted. */
841
	$quote_types = array('keyid', 'asn1dn');
842

    
843
	/* If the first character of asn1dn type data is not #, then rely on
844
	 * automatic parsing https://redmine.pfsense.org/issues/4792 */
845
	if (($type == 'asn1dn') && !empty($data) && ($data[0] != '#')) {
846
		$auto_types[] = 'asn1dn';
847
	}
848

    
849
	if ($type == 'any') {
850
		$idstring = "";
851
	} elseif (!in_array($type, $auto_types)) {
852
		$idstring = "{$type}:{$data}";
853
	} else {
854
		$idstring = $data;
855
	}
856

    
857
	if (in_array($type, $quote_types)) {
858
		$idstring = "\"{$idstring}\"";
859
	}
860

    
861
	return $idstring;
862
}
863

    
864
function ipsec_fixup_network($network) {
865
	if (substr($network, -3) == '|/0') {
866
		$result = substr($network, 0, -3);
867
	} else {
868
		$tmp = explode('|', $network);
869
		if (isset($tmp[1])) {
870
			$result = $tmp[1];
871
		} else {
872
			$result = $tmp[0];
873
		}
874
		unset($tmp);
875
	}
876

    
877
	return $result;
878
}
879

    
880
function ipsec_new_reqid() {
881
	global $config;
882

    
883
	if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) {
884
		return;
885
	}
886

    
887
	$ipsecreqid = lock('ipsecreqids', LOCK_EX);
888
	$keyids = array();
889
	$keyid = 1;
890
	foreach ($config['ipsec']['phase2'] as $ph2) {
891
		$keyids[$ph2['reqid']] = $ph2['reqid'];
892
	}
893

    
894
	for ($i = 1; $i < 16000; $i++) {
895
		if (!isset($keyids[$i])) {
896
			$keyid = $i;
897
			break;
898
		}
899
	}
900
	unlock($ipsecreqid);
901

    
902
	return $keyid;
903
}
904

    
905
function ipsec_get_loglevels() {
906
	global $config, $ipsec_log_cats;
907
	$def_loglevel = '1';
908

    
909
	$levels = array();
910

    
911
	foreach (array_keys($ipsec_log_cats) as $cat) {
912
		if (isset($config['ipsec']['logging'][$cat])) {
913
			$levels[$cat] = $config['ipsec']['logging'][$cat];
914
		} elseif (in_array($cat, array('ike', 'chd', 'cfg'))) {
915
			$levels[$cat] = "2";
916
		} else {
917
			$levels[$cat] = $def_loglevel;
918
		}
919
	}
920
	return $levels;
921
}
922

    
923
function ipsec_vti($ph1ent, $returnaddresses = false, $skipdisabled = true) {
924
	global $config;
925
	if (empty($ph1ent) || !is_array($ph1ent) || !is_array($config['ipsec']['phase2'])) {
926
		return false;
927
	}
928

    
929
	$is_vti = false;
930
	$vtisubnet_spec = array();
931

    
932
	foreach ($config['ipsec']['phase2'] as $ph2ent) {
933
		if ($ph1ent['ikeid'] != $ph2ent['ikeid']) {
934
			continue;
935
		}
936
		if ($ph2ent['mode'] == 'vti') {
937
			if ($returnaddresses) {
938
				$vtisubnet_spec[] = array(
939
					'left' => ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']),
940
					'right' => ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']),
941
					'descr' => $ph2ent['descr'],
942
				);
943
			}
944
			if (!$skipdisabled && isset($ph2ent['disabled'])) {
945
				continue;
946
			} else {
947
				$is_vti = true;
948
			}
949
		}
950
	}
951
	return ($returnaddresses) ? $vtisubnet_spec : $is_vti;
952
}
953

    
954
/* Called when IPsec is reloaded through rc.newipsecdns and similar, gives
955
 * packages an opportunity to execute custom code when IPsec reloads.
956
 */
957
function ipsec_reload_package_hook() {
958
	global $g, $config;
959

    
960
	init_config_arr(array('installedpackages', 'package'));
961
	foreach ($config['installedpackages']['package'] as $package) {
962
		if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
963
			continue;
964
		}
965

    
966
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], 'packagegui');
967
		if (!empty($pkg_config['include_file']) &&
968
		    file_exists($pkg_config['include_file'])) {
969
			require_once($pkg_config['include_file']);
970
		}
971
		if (empty($pkg_config['ipsec_reload_function'])) {
972
			continue;
973
		}
974
		$pkg_ipsec_reload = $pkg_config['ipsec_reload_function'];
975
		if (!function_exists($pkg_ipsec_reload)) {
976
			continue;
977
		}
978
		$pkg_ipsec_reload();
979
	}
980
}
981

    
982
/****f* certs/ipsec_convert_to_modp
983
 * NAME
984
 *   ipsec_convert_to_modp - Take a DH Group number value and return the
985
 *                           associated name
986
 * INPUTS
987
 *   $index: DH group index number to look up
988
 * RESULT
989
 *   Returns the Diffie Hellman Group keyword associated with the group number.
990
 ******/
991
function ipsec_convert_to_modp($index) {
992
	$modpmap = array(
993
		'1' => 'modp768',
994
		'2' => 'modp1024',
995
		'5' => 'modp1536',
996
		'14' => 'modp2048',
997
		'15' => 'modp3072',
998
		'16' => 'modp4096',
999
		'17' => 'modp6144',
1000
		'18' => 'modp8192',
1001
		'19' => 'ecp256',
1002
		'20' => 'ecp384',
1003
		'21' => 'ecp521',
1004
		'22' => 'modp1024s160',
1005
		'23' => 'modp2048s224',
1006
		'24' => 'modp2048s256',
1007
		'25' => 'ecp192',
1008
		'26' => 'ecp224',
1009
		'27' => 'ecp224bp',
1010
		'28' => 'ecp256bp',
1011
		'29' => 'ecp384bp',
1012
		'30' => 'ecp512bp',
1013
		'31' => 'curve25519',
1014
		'32' => 'curve448',
1015
	);
1016

    
1017
	return $modpmap[$index];
1018
}
1019

    
1020
/*
1021
 * Forcefully restart IPsec
1022
 * This is required for when dynamic interfaces reload
1023
 * For all other occasions the normal ipsec_configure()
1024
 * will gracefully reload the settings without restarting
1025
 */
1026
function ipsec_force_reload($interface = "") {
1027
	global $g, $config;
1028

    
1029
	if (!ipsec_enabled()) {
1030
		return;
1031
	}
1032

    
1033
	$ipseccfg = $config['ipsec'];
1034

    
1035
	if (!empty($interface) && is_array($ipseccfg['phase1'])) {
1036
		$found = false;
1037
		foreach ($ipseccfg['phase1'] as $ipsec) {
1038
			if (!isset($ipsec['disabled']) && ($ipsec['interface'] == $interface)) {
1039
				$found = true;
1040
				break;
1041
			}
1042
		}
1043
		if (!$found) {
1044
			log_error(sprintf(gettext("Ignoring IPsec reload since there are no tunnels on interface %s"), $interface));
1045
			return;
1046
		}
1047
	}
1048

    
1049
	/* If we get this far then we need to take action. */
1050
	log_error(gettext("Forcefully reloading IPsec"));
1051
	ipsec_configure();
1052
}
1053

    
1054
/****f* ipsec/ipsec_strongswan_confgen
1055
 * NAME
1056
 *   ipsec_strongswan_confgen - Generate strongswan.conf style formatted output
1057
 *                              From a multi-dimensional array.
1058
 * INPUTS
1059
 *   $confarr: An array of key=value pairs or key=array entries for subsections.
1060
 *   $indent : A string of tabs used when indenting lines.
1061
 * RESULT
1062
 *   Returns a string of key=value pairs with proper indenting, and with named
1063
 *   subsections enclosed in braces.
1064
 * NOTES
1065
 *   Values starting with a "#" (comments) or "include " will be printed
1066
 *   directly without their associated key name.
1067
 ******/
1068
function ipsec_strongswan_confgen($confarr, $indent = "") {
1069
	$confstr = "";
1070
	/* Only process the contents if it's an array. */
1071
	if (is_array($confarr)) {
1072
		foreach ($confarr as $key => $value) {
1073
			if (is_array($value)) {
1074
				/* If the array is empty, do not print anything */
1075
				if (empty($value)) {
1076
					continue;
1077
				}
1078
				/* If this is an array, setup the subsection name
1079
				 * and structure, then call this function
1080
				 * recursively to walk the lower array. */
1081
				$confstr .= "{$indent}{$key} {\n";
1082
				$confstr .= ipsec_strongswan_confgen($value, $indent . "\t");
1083
				$confstr .= "{$indent}}\n";
1084
			} else {
1085
				$confstr .= "{$indent}";
1086
				if ((substr($value, 0 , 1) != '#') &&
1087
				    (substr($value, 0 , 8) != 'include ')) {
1088
					/* Not a comment or include, print the key */
1089
					$confstr .= "{$key} = ";
1090
				}
1091
				$confstr .= "{$value}\n";
1092
			}
1093
		}
1094
	}
1095
	return $confstr;
1096
}
1097

    
1098
global $g, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs;
1099
$ipsec_swanctl_basedir = "{$g['varetc_path']}/ipsec";
1100
$ipsec_swanctl_dirs = array(
1101
	'conf'     => "{$ipsec_swanctl_basedir}/conf.d",
1102
	'certpath' => "{$ipsec_swanctl_basedir}/x509",
1103
	'capath'   => "{$ipsec_swanctl_basedir}/x509ca",
1104
	'aapath'   => "{$ipsec_swanctl_basedir}/x509aa",
1105
	'ocsppath' => "{$ipsec_swanctl_basedir}/x509ocsp",
1106
	'crlpath'  => "{$ipsec_swanctl_basedir}/x509crl",
1107
	'acpath'   => "{$ipsec_swanctl_basedir}/x509ac",
1108
	'rsakeys'  => "{$ipsec_swanctl_basedir}/rsa",
1109
	'eckeys'   => "{$ipsec_swanctl_basedir}/ecdsa",
1110
	'keypath'  => "{$ipsec_swanctl_basedir}/private",
1111
	'pubkpath' => "{$ipsec_swanctl_basedir}/pubkey",
1112
	'blisspath' => "{$ipsec_swanctl_basedir}/bliss",
1113
	'pkcs8path' => "{$ipsec_swanctl_basedir}/pkcs8",
1114
	'pkcs12path' => "{$ipsec_swanctl_basedir}/pkcs12",
1115
);
1116

    
1117
/****f* ipsec/ipsec_create_dirs
1118
 * NAME
1119
 *   ipsec_create_dirs - Create default set of strongSwan configuration directories.
1120
 * INPUTS
1121
 *   None
1122
 * RESULT
1123
 *   Cleans up and creates strongSwan configuration directories and links.
1124
 ******/
1125
function ipsec_create_dirs() {
1126
	global $config, $g, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs;
1127

    
1128
	/* Cleanup base paths to ensure old files are not left behind (#5238) */
1129
	if (!empty($ipsec_swanctl_basedir)) {
1130
		@rmdir_recursive($ipsec_swanctl_basedir, false);
1131
	}
1132
	/* Create directory structure */
1133
	array_map('safe_mkdir', array_values($ipsec_swanctl_dirs));
1134

    
1135
	/* Create and link strongSwan config */
1136
	$ssdpath = "{$g['varetc_path']}/ipsec/strongswan.d";
1137
	if (!file_exists($ssdpath) || !is_link($ssdpath)) {
1138
		if (is_dir($ssdpath) && !is_link($ssdpath)) {
1139
			@rmdir_recursive($ssdpath, false);
1140
		} else {
1141
			@unlink($ssdpath);
1142
		}
1143
		@symlink("/usr/local/etc/strongswan.d",
1144
		    $ssdpath);
1145
	}
1146
	if (!file_exists("/usr/local/etc/strongswan.conf") ||
1147
	    !is_link("/usr/local/etc/strongswan.conf")) {
1148
		@unlink("/usr/local/etc/strongswan.conf");
1149
		@symlink("{$g['varetc_path']}/ipsec/strongswan.conf",
1150
		    "/usr/local/etc/strongswan.conf");
1151
	}
1152
}
1153

    
1154
/****f* ipsec/ipsec_setup_gwifs
1155
 * NAME
1156
 *   ipsec_setup_gwifs - Setup IPsec-related interfaces and gateways
1157
 * INPUTS
1158
 *   None
1159
 * RESULT
1160
 *   Sets up VTI interfaces and gateways, populates ipsecpinghosts
1161
 ******/
1162
function ipsec_setup_gwifs() {
1163
	global $g, $a_phase1, $a_phase2, $rgmap, $filterdns_list,
1164
		$aggressive_mode_psk, $mobile_ipsec_auth, $ifacesuse,
1165
		$ipsecpinghostsactive;
1166
	/* resolve all local, peer addresses and setup pings */
1167
	unset($iflist);
1168
	if (is_array($a_phase1) && count($a_phase1)) {
1169
		$ipsecpinghosts = array();
1170
		/* step through each phase1 entry */
1171
		foreach ($a_phase1 as $ph1ent) {
1172
			if (isset($ph1ent['disabled'])) {
1173
				continue;
1174
			}
1175

    
1176
			if (substr($ph1ent['interface'], 0, 4) == "_vip") {
1177
				$vpninterface = get_configured_vip_interface($ph1ent['interface']);
1178
				$ifacesuse[] = get_real_interface($vpninterface);
1179
			} else {
1180
				$vpninterface = get_failover_interface($ph1ent['interface']);
1181
				if (substr($vpninterface, 0, 4) == "_vip") {
1182
					$vpninterface = get_configured_vip_interface($vpninterface);
1183
					$ifacesuse[] = get_real_interface($vpninterface);
1184
				} elseif (!empty($vpninterface)) {
1185
					$ifacesuse[] = $vpninterface;
1186
				}
1187
			}
1188

    
1189
			if ($ph1ent['mode'] == "aggressive" && ($ph1ent['authentication_method'] == "pre_shared_key" || $ph1ent['authentication_method'] == "xauth_psk_server")) {
1190
				$aggressive_mode_psk = true;
1191
			}
1192

    
1193
			$ikeid = $ph1ent['ikeid'];
1194

    
1195
			$local_spec = ipsec_get_phase1_src($ph1ent);
1196
			/* When automatically guessing, use the first address. */
1197
			$local_spec  = explode(',', $local_spec);
1198
			$local_spec  = $local_spec[0];
1199
			if (!is_ipaddr($local_spec)) {
1200
				log_error(sprintf(gettext("IPsec ERROR: Could not find phase 1 source for connection %s. Omitting from configuration file."), $ph1ent['descr']));
1201
				continue;
1202
			}
1203

    
1204
			if (isset($ph1ent['mobile'])) {
1205
				$mobile_ipsec_auth = $ph1ent['authentication_method'];
1206
				continue;
1207
			}
1208

    
1209
			/* see if this tunnel has a hostname for the remote-gateway. If so,
1210
			   try to resolve it now and add it to the list for filterdns */
1211
			$rg = $ph1ent['remote-gateway'];
1212
			if (!is_ipaddr($rg)) {
1213
				$filterdns_list[] = "{$rg}";
1214
				add_hostname_to_watch($rg);
1215
				if (!platform_booting()) {
1216
					$rg = resolve_retry($rg);
1217
				}
1218
				if (!is_ipaddr($rg)) {
1219
					continue;
1220
				}
1221
			}
1222
			if (!isset($ph1ent['gw_duplicates']) && array_search($rg, $rgmap)) {
1223
				log_error(sprintf(gettext("The remote gateway %s already exists on another phase 1 entry"), $rg));
1224
				continue;
1225
			}
1226
			$rgmap[$ph1ent['remote-gateway']] = $rg;
1227

    
1228
			$is_vti = false;
1229
			if (is_array($a_phase2)) {
1230
				/* step through each phase2 entry */
1231
				foreach ($a_phase2 as $ph2ent) {
1232
					if ($ph2ent['mode'] == 'vti') {
1233
						$is_vti = true;
1234
					}
1235
					if (isset($ph2ent['disabled']) || ($ikeid != $ph2ent['ikeid'])) {
1236
						continue;
1237
					}
1238

    
1239
					/* add an ipsec pinghosts entry */
1240
					if ($ph2ent['pinghost']) {
1241
						if (!is_array($iflist)) {
1242
							$iflist = get_configured_interface_list();
1243
						}
1244
						$srcip = null;
1245
						$local_subnet = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
1246
						if (is_ipaddrv6($ph2ent['pinghost'])) {
1247
							foreach ($iflist as $ifent => $ifname) {
1248
								$interface_ip = get_interface_ipv6($ifent);
1249
								if (!is_ipaddrv6($interface_ip)) {
1250
									continue;
1251
								}
1252
								if (ip_in_subnet($interface_ip, $local_subnet)) {
1253
									$srcip = $interface_ip;
1254
									break;
1255
								}
1256
							}
1257
						} else {
1258
							foreach ($iflist as $ifent => $ifname) {
1259
								$interface_ip = get_interface_ip($ifent);
1260
								if (!is_ipaddrv4($interface_ip)) {
1261
									continue;
1262
								}
1263
								if ($local_subnet == "0.0.0.0/0" || ip_in_subnet($interface_ip, $local_subnet)) {
1264
									$srcip = $interface_ip;
1265
									break;
1266
								}
1267
							}
1268
						}
1269
						/* if no valid src IP was found in configured interfaces, try the vips */
1270
						if (is_null($srcip)) {
1271
							$viplist = get_configured_vip_list();
1272
							foreach ($viplist as $vip => $address) {
1273
								if (ip_in_subnet($address, $local_subnet)) {
1274
									$srcip = $address;
1275
									break;
1276
								}
1277
							}
1278
						}
1279
						$dstip = $ph2ent['pinghost'];
1280
						$family = "inet" . (is_ipaddrv6($dstip)) ? "6" : "";
1281
						if (is_ipaddr($srcip)) {
1282
							$ipsecpinghosts[] = "{$srcip}|{$dstip}|3|||||{$family}|\n";
1283
							$ipsecpinghostsactive = true;
1284
						}
1285
					}
1286
				}
1287
			}
1288
			if ($is_vti) {
1289
				interface_ipsec_vti_configure($ph1ent);
1290
			}
1291
		}
1292
		@file_put_contents("{$g['vardb_path']}/ipsecpinghosts", $ipsecpinghosts);
1293
		unset($ipsecpinghosts);
1294
	}
1295
	unset($iflist);
1296
}
1297

    
1298
/****f* ipsec/ipsec_logging_config
1299
 * NAME
1300
 *   ipsec_logging_config - Generate an array containing strongSwan logging
1301
 *                          values.
1302
 * INPUTS
1303
 *   None
1304
 * RESULT
1305
 *   Returns an array which can be merged into the strongswan daemon logging
1306
 *   values so that each logging category is represented, even those not listed
1307
 *   in config.xml.
1308
 ******/
1309
function ipsec_logging_config() {
1310
	global $config, $ipsec_log_cats, $ipsec_log_sevs;
1311
	$logcfg = array();
1312
	$log_levels = ipsec_get_loglevels();
1313
	foreach (array_keys($ipsec_log_cats) as $cat) {
1314
		if (is_numeric($log_levels[$cat]) &&
1315
		    in_array(intval($log_levels[$cat]), array_keys($ipsec_log_sevs), true)) {
1316
			$logcfg[$cat] = $log_levels[$cat];
1317
		}
1318
	}
1319
	return $logcfg;
1320
}
1321

    
1322
/****f* ipsec/ipsec_setup_strongswan
1323
 * NAME
1324
 *   ipsec_setup_strongswan - Generate the strongswan.conf configuration file.
1325
 * INPUTS
1326
 *   None
1327
 * RESULT
1328
 *   Determines strongswan.conf values and crafts the configuration file in the
1329
 *   appropriate format.
1330
 * NOTES
1331
 *   Called from ipsec_configure()
1332
 ******/
1333
function ipsec_setup_strongswan() {
1334
	global $config, $g, $mobile_ipsec_auth, $a_client, $a_phase2, $aggressive_mode_psk, $ifacesuse;
1335

    
1336
	/* strongswan.conf array */
1337
	$ssconf = array();
1338
	$ssconf[] = "# Automatically generated config file - DO NOT MODIFY. Changes will be overwritten.";
1339
	$ssconf['starter'] = array();
1340
	$ssconf['starter']['load_warning'] = "no";
1341
	$ssconf['starter']['config_file'] = "{$g['varetc_path']}/ipsec/ipsec.conf";
1342

    
1343
	$ssconf['charon'] = array();
1344
	$ssconf['charon'][] = '# number of worker threads in charon';
1345
	$ssconf['charon']['threads'] = '16';
1346
	$ssconf['charon']['ikesa_table_size'] = '32';
1347
	$ssconf['charon']['ikesa_table_segments'] = '4';
1348
	$ssconf['charon']['init_limit_half_open'] = '1000';
1349
	$ssconf['charon']['install_routes'] = 'no';
1350
	$ssconf['charon']['load_modular'] = 'yes';
1351
	$ssconf['charon']['ignore_acquire_ts'] = 'yes';
1352

    
1353
	if ($aggressive_mode_psk) {
1354
		$stronconf = '';
1355
		if (file_exists("{$g['varetc_path']}/ipsec/strongswan.conf")) {
1356
			$stronconf = file_get_contents("{$g['varetc_path']}/ipsec/strongswan.conf");
1357
		}
1358
		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.");
1359
		$restart = (!empty($stronconf) && strpos($stronconf, 'i_dont_care_about_security_and_use_aggressive_mode_psk') === FALSE);
1360
		unset($stronconf);
1361
		$ssconf['charon']['i_dont_care_about_security_and_use_aggressive_mode_psk'] = "yes";
1362
	}
1363

    
1364
	if (isset($config['ipsec']['acceptunencryptedmainmode'])) {
1365
		$ssconf['charon']['accept_unencrypted_mainmode_messages'] = "yes";
1366
	}
1367

    
1368
	$unity_enabled = isset($config['ipsec']['unityplugin']) ? 'yes' : 'no';
1369
	$ssconf['charon']['cisco_unity'] = $unity_enabled;
1370

    
1371
	if (isset($config['ipsec']['enableinterfacesuse']) && !empty($ifacesuse)) {
1372
		$ssconf['charon']['interfaces_use'] = implode(',', array_unique($ifacesuse));
1373
	}
1374

    
1375
	if (isset($config['ipsec']['makebeforebreak'])) {
1376
		$ssconf['charon']['make_before_break'] = "yes";
1377
	}
1378

    
1379
	$ssconf['charon']['syslog'] = array();
1380
	$ssconf['charon']['syslog']['identifier'] = 'charon';
1381
	$ssconf['charon']['syslog'][] = "# log everything under daemon since it ends up in the same place regardless with our syslog.conf";
1382
	$ssconf['charon']['syslog']['daemon'] = array();
1383
	$ssconf['charon']['syslog']['daemon']['ike_name'] = 'yes';
1384
	$ssconf['charon']['syslog']['daemon'] = array_merge($ssconf['charon']['syslog']['daemon'], ipsec_logging_config());
1385
	$ssconf['charon']['syslog'][] = '# disable logging under auth so logs aren\'t duplicated';
1386
	$ssconf['charon']['syslog']['auth'] = array();
1387
	$ssconf['charon']['syslog']['auth']['default'] = -1;
1388

    
1389
	$ssconf['charon']['plugins'] = array();
1390
	$ssconf['charon']['plugins'][] = "# Load defaults";
1391
	$ssconf['charon']['plugins'][] = "include {$g['varetc_path']}/ipsec/strongswan.d/charon/*.conf";
1392
	$ssconf['charon']['plugins']['unity'] = array('load' => $unity_enabled);
1393
	$ssconf['charon']['plugins']['curve25519'] = array('load' => "yes");
1394

    
1395
	$ssconf['charon']['plugins']['pkcs11'] = array();
1396
	$ssconf['charon']['plugins']['pkcs11']['load'] = "yes";
1397
	$ssconf['charon']['plugins']['pkcs11']['modules'] = array();
1398
	$ssconf['charon']['plugins']['pkcs11']['modules']['opensc'] = array();
1399
	$ssconf['charon']['plugins']['pkcs11']['modules']['opensc']['load_certs'] = "yes";
1400
	$ssconf['charon']['plugins']['pkcs11']['modules']['opensc']['path'] = "/usr/local/lib/opensc-pkcs11.so";
1401

    
1402
	/* Find RADIUS servers designated for Mobile IPsec user auth */
1403
	$radius_servers = array();
1404
	foreach (explode(',', $config['ipsec']['client']['user_source']) as $user_source) {
1405
		$auth_server = auth_get_authserver($user_source);
1406
		$nice_user_source = strtolower(preg_replace('/[\s\.]+/', '_', $user_source));
1407
		if ($auth_server && ($auth_server['type'] === 'radius')) {
1408
			$radius_servers[$nice_user_source] = array();
1409
			$radius_servers[$nice_user_source]['address'] = $auth_server['host'];
1410
			$radius_servers[$nice_user_source]['secret'] = "\"{$auth_server['radius_secret']}\"";
1411
			$radius_servers[$nice_user_source]['auth_port'] = empty($auth_server['radius_auth_port']) ? 1812 : $auth_server['radius_auth_port'];;
1412
			$radius_servers[$nice_user_source]['acct_port'] = empty($auth_server['radius_acct_port']) ? 1813 : $auth_server['radius_acct_port'];
1413
		}
1414
	}
1415

    
1416
	/* Generate an eap-radius config section if appropriate */
1417
	if (count($radius_servers) && ($mobile_ipsec_auth === "eap-radius")) {
1418
		$ssconf['charon']['plugins']['eap-radius'] = array();
1419
		$ssconf['charon']['plugins']['eap-radius']['class_group'] = "yes";
1420
		$ssconf['charon']['plugins']['eap-radius']['eap_start'] = "no";
1421
		/* Activate RADIUS accounting only if it was selected on the IPsec Mobile Clients tab */
1422
		if ($auth_server && isset($auth_server['radius_acct_port']) &&
1423
		    (is_array($a_client) && ($a_client['radiusaccounting'] == "enabled"))){
1424
			$ssconf['charon']['plugins']['eap-radius']['accounting'] = "yes";
1425
			$ssconf['charon']['plugins']['eap-radius']['accounting_close_on_timeout'] = "no";
1426
		}
1427
		$ssconf['charon']['plugins']['eap-radius']['servers'] = $radius_servers;
1428
	}
1429

    
1430
	if (is_array($a_client) && isset($a_client['enable'])) {
1431
		if ($a_client['user_source'] != "none") {
1432
			$ssconf['charon']['plugins']['xauth-generic'] = array();
1433
			$ssconf['charon']['plugins']['xauth-generic']['script'] = "/etc/inc/ipsec.auth-user.php";
1434
			$authcfgs = array();
1435
			foreach (explode(",", $a_client['user_source']) as $authcfg) {
1436
				$authcfgs[] = ($authcfg == "system") ? "Local Database" : $authcfg;
1437
			}
1438
			$ssconf['charon']['plugins']['xauth-generic']['authcfg'] = implode(",", $authcfgs);
1439
		}
1440
	}
1441

    
1442
	@file_put_contents("{$g['varetc_path']}/ipsec/strongswan.conf", ipsec_strongswan_confgen($ssconf));
1443
}
1444

    
1445
/****f* ipsec/ipsec_setup_pools
1446
 * NAME
1447
 *   ipsec_setup_pools - Generate primary mobile pool configuration for swanctl
1448
  * INPUTS
1449
 *   None
1450
 * RESULT
1451
 *   Adds configured mobile pool settings to $scconf
1452
 * NOTES
1453
 *   These values were formerly in strongswan.conf but may now be configured in
1454
 *   pools, making future expansion to support multiple pools possible.
1455
 ******/
1456
function ipsec_setup_pools() {
1457
	global $config, $g, $mobile_ipsec_auth, $a_client, $a_phase2, $scconf;
1458
	if (!is_array($a_client) || !isset($a_client['enable'])) {
1459
		return;
1460
	}
1461
	$scconf['pools']['mobile-pool'] = array();
1462

    
1463
	$pool_addrs = array();
1464
	if (!empty($a_client['pool_address'])) {
1465
		$pool_addrs[] = "{$a_client['pool_address']}/{$a_client['pool_netbits']}";
1466
	}
1467
	if (!empty($a_client['pool_address_v6'])) {
1468
		$pool_addrs[] = "{$a_client['pool_address_v6']}/{$a_client['pool_netbits_v6']}";
1469
	}
1470
	if ($mobile_ipsec_auth == "eap-radius" && !count($pool_addrs)) {
1471
		$pool_addrs[] = "%radius";
1472
	}
1473
	if (count($pool_addrs)) {
1474
		$scconf['pools']['mobile-pool']['addrs'] = implode(',', $pool_addrs);
1475
	}
1476

    
1477
	$rightdnsservers = array();
1478
	if (!empty($a_client['dns_server1'])) {
1479
		$rightdnsservers[] = $a_client['dns_server1'];
1480
	}
1481
	if (!empty($a_client['dns_server2'])) {
1482
		$rightdnsservers[] = $a_client['dns_server2'];
1483
	}
1484
	if (!empty($a_client['dns_server3'])) {
1485
		$rightdnsservers[] = $a_client['dns_server3'];
1486
	}
1487
	if (!empty($a_client['dns_server4'])) {
1488
		$rightdnsservers[] = $a_client['dns_server4'];
1489
	}
1490
	if (count($rightdnsservers)) {
1491
		$scconf['pools']['mobile-pool']['dns'] = implode(',', $rightdnsservers);
1492
	}
1493

    
1494
	$cfgservers = array();
1495
	if (!empty($a_client['wins_server1'])) {
1496
		$cfgservers[] = $a_client['wins_server1'];
1497
	}
1498
	if (!empty($a_client['wins_server2'])) {
1499
		$cfgservers[] = $a_client['wins_server2'];
1500
	}
1501
	if (!empty($cfgservers)) {
1502
		$scconf['pools']['mobile-pool']['nbns'] = implode(",", $cfgservers);
1503
	}
1504
	unset($cfgservers);
1505

    
1506
	if (isset($a_client['net_list']) && is_array($a_phase2)) {
1507
		$net_list = array();
1508
		foreach ($a_phase2 as $ph2ent) {
1509
			if (isset($ph2ent['disabled']) ||
1510
			    !isset($ph2ent['mobile'])) {
1511
				continue;
1512
			}
1513
			$net_list[] = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
1514
		}
1515
		if (!empty($net_list)) {
1516
			$scconf['pools']['mobile-pool']['subnet'] = implode(",", $net_list);
1517
			$scconf['pools']['mobile-pool']['split_include'] = implode(",", $net_list);
1518
			unset($net_list);
1519
		}
1520
	}
1521
	if (!empty($a_client['dns_domain'])) {
1522
		$scconf['pools']['mobile-pool'][] = "# Search domain and default domain";
1523
		$scconf['pools']['mobile-pool']['28674'] = "\"{$a_client['dns_domain']}\"";
1524
		if (empty($a_client['dns_split'])) {
1525
			$scconf['pools']['mobile-pool']['28675'] = "\"{$a_client['dns_domain']}\"";
1526
		}
1527
	}
1528

    
1529
	if (!empty($a_client['dns_split'])) {
1530
		$scconf['pools']['mobile-pool']['28675'] = "\"{$a_client['dns_split']}\"";
1531
	}
1532

    
1533
	if (!empty($a_client['login_banner'])) {
1534
		$scconf['pools']['mobile-pool']['28672'] = "\"{$a_client['login_banner']}\"";
1535
	}
1536

    
1537
	if (isset($a_client['save_passwd'])) {
1538
		$scconf['pools']['mobile-pool']['28673'] = "1";
1539
	}
1540

    
1541
	if ($a_client['pfs_group']) {
1542
		$scconf['pools']['mobile-pool']['28679'] = "\"{$a_client['pfs_group']}\"";
1543
	}
1544

    
1545
	return;
1546
}
1547

    
1548
/****f* ipsec/ipsec_setup_userpools
1549
 * NAME
1550
 *   ipsec_setup_userpools - Generate per-user custom pool settings for swanctl
1551
  * INPUTS
1552
 *   None
1553
 * RESULT
1554
 *   Adds configured per-user pool settings to $scconf using the primary mobile
1555
 *   pool as a base configuration.
1556
 * NOTES
1557
 *   Given this new flexible format, it is now possible to override any valid
1558
 *   pool setting, so future expansion of per-user settings is possible.
1559
 ******/
1560
function ipsec_setup_userpools() {
1561
	global $config, $scconf;
1562
	$a_mobilekey = $config['ipsec']['mobilekey'];
1563

    
1564
	/* Do not waste time if we do not have all the necessary information. */
1565
	if (!is_array($a_mobilekey) ||
1566
	    empty($a_mobilekey) ||
1567
	    !is_array($scconf['connections']) ||
1568
	    !is_array($scconf['connections']['con-mobile']) ||
1569
	    !is_array($scconf['pools']) ||
1570
	    !is_array($scconf['pools']['mobile-pool'])) {
1571
		return;
1572
	}
1573

    
1574
	$suffix = 1;
1575
	foreach ($a_mobilekey as $mkent) {
1576
		if (($mkent['type'] != "EAP") ||
1577
		    !isset($mkent['ident_type']) ||
1578
		    !isset($mkent['pool_address']) ||
1579
		    !isset($mkent['pool_netbits']) ||
1580
		    (strlen($mkent['pool_address']) < 1) ||
1581
		    !is_ipaddr($mkent['pool_address'])) {
1582
			continue;
1583
		}
1584
		/* The name of just this pool */
1585
		$upbase = "mobile-userpool-{$suffix}";
1586
		/* The full connection name including a reference to the primary
1587
		 * mobile connection */
1588
		$upconn = "con-{$upbase} : con-mobile";
1589
		/* The full pool name including a reference to the primary
1590
		 * mobile pool */
1591
		$upname = "{$upbase} : mobile-pool";
1592

    
1593
		$scconf['connections'][$upconn] = array();
1594
		$scconf['pools'][$upname] = array();
1595

    
1596
		$clientid = ($mkent['ident_type'] == "none") ? "\"{$mkent['ident']}\"" : "{$mkent['ident_type']}:{$mkent['ident']}";
1597
		$clienteapid = ($ph1ent['authentication_method'] == "eap-mschapv2") ? $clientid : '%any';
1598

    
1599
		/* Craft a cloned connection with the ID information to match */
1600
		$scconf['connections'][$upconn]['remote'] = array();
1601
		$scconf['connections'][$upconn]['remote']['id'] = $clientid;
1602
		$scconf['connections'][$upconn]['remote']['eap_id'] = $clienteapid;
1603
		$scconf['connections'][$upconn]['pools'] = $upbase;
1604

    
1605
		/* Craft a cloned pool with pool settings to override for this user */
1606
		$scconf['pools'][$upname]['addrs'] = "{$mkent['pool_address']}/{$mkent['pool_netbits']}";
1607
		if (isset($mkent['dns_address']) && strlen($mkent['dns_address']) > 0 && is_ipaddr($mkent['dns_address'])) {
1608
			$scconf['pools'][$upname]['dns'] = $mkent['dns_address'];
1609
		}
1610
		$suffix++;
1611
	}
1612
	return;
1613
}
1614

    
1615
/****f* ipsec/ipsec_setup_bypasslan
1616
 * NAME
1617
 *   ipsec_setup_bypasslan - Generate a bypass connection for LAN-LAN traffic
1618
 * INPUTS
1619
 *   None
1620
 * RESULT
1621
 *   Sets up a bypass connection to prevent local traffic from being caught by
1622
 *   IPsec policies.
1623
 ******/
1624
function ipsec_setup_bypasslan() {
1625
	global $config, $scconf;
1626
	if (isset($config['ipsec']['noshuntlaninterfaces'])) {
1627
		return array();
1628
	}
1629
	$bypassnets = array();
1630
	/* Locate the LAN IPv4 and IPv6 subnets */
1631
	if ($config['interfaces']['lan']) {
1632
		$lanip = get_interface_ip("lan");
1633
		if (!empty($lanip) && is_ipaddrv4($lanip)) {
1634
			$lansn = get_interface_subnet("lan");
1635
			$lansa = gen_subnetv4($lanip, $lansn);
1636
			if (!empty($lansa) && !empty($lansn)) {
1637
				$bypassnets[] = "{$lansa}/{$lansn}";
1638
			}
1639
		}
1640
		$lanip6 = get_interface_ipv6("lan");
1641
		if (!empty($lanip6) && is_ipaddrv6($lanip6)) {
1642
			$lansn6 = get_interface_subnetv6("lan");
1643
			$lansa6 = gen_subnetv6($lanip6, $lansn6);
1644
			if (!empty($lansa6) && !empty($lansn6)) {
1645
				$bypassnets[] = "{$lansa6}/{$lansn6}";
1646
			}
1647
		}
1648
	}
1649
	/* If we have viable targets, setup a bypass connection */
1650
	if (!empty($bypassnets)) {
1651
		$bypass = implode(',', $bypassnets);
1652
		$scconf['connections']['bypass'] = array();
1653
		/* Prevents the connection from being considered for remote peers */
1654
		$scconf['connections']['bypass']['remote_addrs'] = "127.0.0.1";
1655
		$scconf['connections']['bypass']['children'] = array();
1656
		$scconf['connections']['bypass']['children']['bypass'] = array();
1657
		$scconf['connections']['bypass']['children']['bypass']['local_ts'] = $bypass;
1658
		$scconf['connections']['bypass']['children']['bypass']['remote_ts'] = $bypass;
1659
		$scconf['connections']['bypass']['children']['bypass']['mode'] = "pass";
1660
		$scconf['connections']['bypass']['children']['bypass']['start_action'] = "trap";
1661
	}
1662
	return;
1663
}
1664

    
1665
/****f* ipsec/ipsec_setup_routes
1666
 * NAME
1667
 *   ipsec_setup_routes - Setup OS routing table static routes for remote peers.
1668
 *                        This ensures that IPsec connections are routed out of
1669
 *                        the expected interface on egress.
1670
 * INPUTS
1671
 *   $interface : The interface upon which routes will be configured.
1672
 *   $family    : The address family ('inet' or 'inet6')
1673
 *   $sourcehost: The local source address used for initiating connections.
1674
 *   $duplicates: If the ipsec tunnel allows duplicates remote peers
1675
 * RESULT
1676
 *   Static routes in the OS routing table for IPsec peers
1677
 ******/
1678
function ipsec_setup_routes($interface, $family, $sourcehost) {
1679
	if (substr($interface, 0, 4) == "_vip") {
1680
		$vpninterface = get_configured_vip_interface($interface);
1681
		if (substr($vpninterface, 0, 4) == "_vip") {
1682
			// vips are nested if its a ipalias with a carp parent
1683
			$vpninterface = get_configured_vip_interface($vpninterface);
1684
		}
1685
		$ifacesuse = get_real_interface($vpninterface);
1686
	} else {
1687
		$ifacesuse = get_failover_interface($interface);
1688
		if (substr($ifacesuse, 0, 4) == "_vip") {
1689
			$vpninterface = get_configured_vip_interface($ifacesuse);
1690
			$ifacesuse = get_real_interface($vpninterface);
1691
		} else {
1692
			$vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse);
1693
		}
1694
	}
1695
	if ($family == 'inet') {
1696
		if (!empty($ifacesuse) && interface_has_gateway($vpninterface)) {
1697
			$gatewayip = get_interface_gateway($vpninterface);
1698
			$interfaceip = get_interface_ip($vpninterface);
1699
			$subnet_bits = get_interface_subnet($vpninterface);
1700
			$subnet_ip = gen_subnetv4($interfaceip, $subnet_bits);
1701
			/* if the remote gateway is in the local subnet, then don't add a route */
1702
			if (is_ipaddrv4($sourcehost) &&
1703
			    !ip_in_subnet($sourcehost, "{$subnet_ip}/{$subnet_bits}")) {
1704
				if (is_ipaddrv4($gatewayip) && !$duplicates) {
1705
					// log_error("IPSEC interface is not WAN but {$ifacesuse}, adding static route for VPN endpoint {$rgip} via {$gatewayip}");
1706
					route_add_or_change("-host {$sourcehost} {$gatewayip}");
1707
				}
1708
			}
1709
		}
1710
	} else if ($family == 'inet6') {
1711
		if (!empty($ifacesuse) && interface_has_gatewayv6($vpninterface)) {
1712
			$gatewayip = get_interface_gateway_v6($vpninterface);
1713
			$interfaceip = get_interface_ipv6($vpninterface);
1714
			$subnet_bits = get_interface_subnetv6($vpninterface);
1715
			$subnet_ip = gen_subnetv6($interfaceip, $subnet_bits);
1716
			/* if the remote gateway is in the local subnet, then don't add a route */
1717
			if (is_ipaddrv6($sourcehost) &&
1718
			    !ip_in_subnet($sourcehost, "{$subnet_ip}/{$subnet_bits}")) {
1719
				if (is_ipaddrv6($gatewayip) && !$duplicates) {
1720
					// log_error("IPSEC interface is not WAN but {$ifacesuse}, adding static route for VPN endpoint {$rgip} via {$gatewayip}");
1721
					route_add_or_change("-inet6 -host {$sourcehost} {$gatewayip}");
1722
				}
1723
			}
1724
		}
1725
	}
1726
	return $ifacesuse;
1727
}
1728

    
1729
/****f* ipsec/ipsec_setup_authentication
1730
 * NAME
1731
 *   ipsec_setup_authentication - Generate an array with local/remote
1732
 *                                authentication information for a given IPsec
1733
 *                                Phase 1.
1734
 * INPUTS
1735
 *   $ph1ent: An IPsec Phase 1 configuration
1736
 *   $conn  : A swanctl connection array corresponding to the IPsec Phase 1.
1737
 * RESULT
1738
 *   Populates $conn with local and remote arrays containing authentication
1739
 *   details.
1740
 ******/
1741
function ipsec_setup_authentication(& $ph1ent, & $conn) {
1742
	global $rgmap, $ipsec_swanctl_dirs;
1743
	$local = array();
1744
	$remote = array();
1745
	$remote2 = array();
1746

    
1747
	list($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local');
1748
	$localid = ipsec_fixup_id($myid_type, $myid_data);
1749
	if (!empty($localid)) {
1750
		$local['id'] = $localid;
1751
	}
1752

    
1753
	// Only specify peer ID if we are not dealing with mobile PSK
1754
	if (!(isset($ph1ent['mobile']) &&
1755
	    in_array($ph1ent['authentication_method'], array("pre_shared_key", "xauth_psk_server")))) {
1756
		list ($remoteid_type, $remoteid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap);
1757
		$remoteid = ipsec_fixup_id($remoteid_type, $remoteid_data);
1758
	}
1759
	if (!empty($remoteid)) {
1760
		$remote['id'] = $remoteid;
1761
	}
1762

    
1763
	if (!empty($ph1ent['caref'])) {
1764
		$ca = lookup_ca($ph1ent['caref']);
1765
		if ($ca) {
1766
			/* Get hash value to use for filename */
1767
			$ca_details = openssl_x509_parse(base64_decode($ca['crt']));
1768
			$cafn = "{$ipsec_swanctl_dirs['capath']}/{$ca_details['hash']}.0";
1769
		}
1770
	}
1771

    
1772
	$authentication = "";
1773
	switch ($ph1ent['authentication_method']) {
1774
		case 'eap-mschapv2':
1775
			if (isset($ph1ent['mobile'])) {
1776
				$local['auth'] = "pubkey";
1777
				$remote['eap_id'] = "%any";
1778
				$remote['auth'] = "eap-mschapv2";
1779
			}
1780
			break;
1781
		case 'eap-tls':
1782
			if (isset($ph1ent['mobile'])) {
1783
				$local['auth'] = "pubkey";
1784
				$remote['eap_id'] = "%any";
1785
			} else {
1786
				$local['auth'] = "eap-tls";
1787
			}
1788
			$remote['auth'] = "eap-tls";
1789
			break;
1790
		case 'eap-radius':
1791
			if (isset($ph1ent['mobile'])) {
1792
				$local['auth'] = "pubkey";
1793
				$remote['eap_id'] = "%any";
1794
			} else {
1795
				$local['auth'] = "eap-radius";
1796
			}
1797
			$remote['auth'] = "eap-radius";
1798
			break;
1799
		case 'xauth_cert_server':
1800
			$local['auth'] = "pubkey";
1801
			$remote['auth'] = "pubkey";
1802
			$remote2['auth'] = "xauth-generic";
1803
			break;
1804
		case 'xauth_psk_server':
1805
			$local['auth'] = "psk";
1806
			$remote['auth'] = "psk";
1807
			$remote2['auth'] = "xauth-generic";
1808
			break;
1809
		case 'pre_shared_key':
1810
			$local['auth'] = "psk";
1811
			$remote['auth'] = "psk";
1812
			break;
1813
		case 'cert':
1814
		case 'pkcs11':
1815
			$local['auth'] = "pubkey";
1816
			$remote['auth'] = "pubkey";
1817
			break;
1818
		case 'hybrid_cert_server':
1819
			$local['auth'] = "pubkey";
1820
			$remote['auth'] = "xauth-generic";
1821
			break;
1822
	}
1823
	if (in_array($ph1ent['authentication_method'], array('eap-mschapv2', 'eap-tls', 'eap-radius', 'xauth_cert_server', 'cert', 'hybrid_cert_server')) &&
1824
	    !empty($ph1ent['certref'])) {
1825
		$local['cert'] = array('file' => "{$ipsec_swanctl_dirs['certpath']}/cert-{$ph1ent['ikeid']}.crt");
1826
		$conn['send_cert'] = "always";
1827
	}
1828
	if ($ph1ent['authentication_method'] == 'pkcs11') {
1829
		$local['cert'] = array('handle' => "{$ph1ent['pkcs11certref']}");
1830
		$conn['send_cert'] = "always";
1831
	}
1832
	if (in_array($ph1ent['authentication_method'], array('eap-tls', 'xauth_cert_server', 'cert', 'pkcs11')) &&
1833
	    isset($cafn)) {
1834
		$remote['cacerts'] = $cafn;
1835
	}
1836

    
1837
	$conn['local'] = $local;
1838
	/* If there is data for a second remote auth round, setup two remote
1839
	 * arrays with unique names, otherwise setup a single remote. */
1840
	if (empty($remote2)) {
1841
		$conn['remote'] = $remote;
1842
	} else {
1843
		$conn['remote-1'] = $remote;
1844
		$conn['remote-2'] = $remote2;
1845
	}
1846
}
1847

    
1848
/****f* ipsec/ipsec_setup_proposal_algo
1849
 * NAME
1850
 *   ipsec_setup_proposal_algo - Form a single proposal algorithm string
1851
 * INPUTS
1852
 *   $ealg_id: Encryption algorithm ID
1853
 *   $keylen : Key length for the encryption algorithm
1854
 *   $halgo  : Hash algorithm
1855
 *   $modp   : DH Group number
1856
 * RESULT
1857
 *   Returns a string using the available information to form a single proposal
1858
 *   algorithm definition.
1859
 * NOTES
1860
 *   Values left empty will not be added to the string. Some combinations may
1861
 *   require one or more parts to be omitted.
1862
 ******/
1863
function ipsec_setup_proposal_algo($ealg_id, $keylen, $halgo, $modp) {
1864
	$palgo = "";
1865

    
1866
	/* Add the encryption algorithm (if present) */
1867
	if (!empty($ealg_id)) {
1868
		$palgo .= "{$ealg_id}";
1869
	}
1870

    
1871
	/* Add the key length (if present) */
1872
	if (!empty($keylen)) {
1873
		$palgo .= "{$keylen}";
1874
	}
1875

    
1876
	/* Add the hash algorithm (if present) */
1877
	if (!empty($halgo)) {
1878
		/* If there is some content in the propsal already, add a
1879
		 * separator */
1880
		if (!empty($palgo)) {
1881
			$palgo .= "-";
1882
		}
1883
		$halgo = str_replace('hmac_', '', $halgo);
1884
		$palgo .= "{$halgo}";
1885
	}
1886

    
1887
	/* Convert the DH group to its keyword and add (if present) */
1888
	$modp = ipsec_convert_to_modp($modp);
1889
	if (!empty($modp)) {
1890
		$palgo .= "-{$modp}";
1891
	}
1892

    
1893
	return $palgo;
1894
}
1895

    
1896
/****f* ipsec/ipsec_setup_proposal_entry
1897
 * NAME
1898
 *   ipsec_setup_proposal_entry - Generate a full proposal string for an IPsec
1899
 *                                Phase 2 configuration.
1900
 * INPUTS
1901
 *   $ph2ent  : An IPsec Phase 2 configuration
1902
 *   $algo_arr: An array in which all proposal algorithms are collected
1903
 *   $ealg_id : Encryption algorithm ID
1904
 *   $keylen  : Key length for the encryption algorithm
1905
 * RESULT
1906
 *   Returns a string containing all proposal elements, and merges the entries
1907
 *   to $algo_arr as well.
1908
 ******/
1909
function ipsec_setup_proposal_entry(& $ph2ent, & $algo_arr, $ealg_id, $keylen) {
1910
	global $config, $p2_ealgos;
1911
	$proposal = array();
1912

    
1913
	/* If multiple hash algorithms are present, loop through and add them all. */
1914
	if (!empty($ph2ent['hash-algorithm-option']) && is_array($ph2ent['hash-algorithm-option'])) {
1915
		foreach ($ph2ent['hash-algorithm-option'] as $halgo) {
1916
			$proposal[] = ipsec_setup_proposal_algo($ealg_id, $keylen, $halgo, $ph2ent['pfsgroup']);
1917
		}
1918
	} else {
1919
		$proposal[] = ipsec_setup_proposal_algo($ealg_id, $keylen, '', $ph2ent['pfsgroup']);
1920
	}
1921

    
1922
	/* Add to master list */
1923
	$algo_arr = array_merge($algo_arr, $proposal);
1924
	return implode(',', $proposal);
1925
}
1926

    
1927
/****f* ipsec/ipsec_setup_vtireq
1928
 * NAME
1929
 *   ipsec_setup_vtireq - Setup a VTI type IPsec request
1930
 * INPUTS
1931
 *   $child                : A swanctl child array
1932
 *   $ipsec_vti_cleanup_ifs: An array of VTI interface names for later cleanup
1933
 *   $ikeid                : The IKE ID of this child
1934
 *   $idx                  : The index of this child (for split connections/IKEv1)
1935
 * RESULT
1936
 *   Sets up VTI-specific values for a request.
1937
 ******/
1938
function ipsec_setup_vtireq(& $child, & $ipsec_vti_cleanup_ifs, $ikeid, $idx = 0) {
1939
	$child['reqid'] = "{$ikeid}00{$idx}";
1940
	/* This interface will be a valid IPsec interface, so remove it from the cleanup list. */
1941
	$ipsec_vti_cleanup_ifs = array_diff($ipsec_vti_cleanup_ifs, array("ipsec{$child['reqid']}"));
1942
	$child['local_ts'] .= ",0.0.0.0/0";
1943
	$child['remote_ts'] .= ",0.0.0.0/0";
1944
}
1945

    
1946
/****f* ipsec/ipsec_setup_tunnels
1947
 * NAME
1948
 *   ipsec_setup_tunnels - Configure all P1/P2 entries as swanctl connections
1949
 * INPUTS
1950
 *   None
1951
 * RESULT
1952
 *   Sets up a swanctl array for all connections in the configuration along with
1953
 *   their children, authentication, etc.
1954
 ******/
1955
function ipsec_setup_tunnels() {
1956
	global $aggressive_mode_psk, $a_client, $config,
1957
		$filterdns_list, $g, $ifacesuse, $ipsec_idhandling, $ipsec_log_cats,
1958
		$ipsec_log_sevs, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs,
1959
		$ipseccfg, $mobile_ipsec_auth, $natfilterrules, $p1_ealgos,
1960
		$p2_ealgos, $rgmap, $sa, $sn, $scconf, $conn, $tunnels,
1961
		$ipsec_vti_cleanup_ifs, $conn_defaults;
1962

    
1963
	foreach ($tunnels as $ph1ent) {
1964
		/* Skip disabled entries */
1965
		if (isset($ph1ent['disabled'])) {
1966
			continue;
1967
		}
1968
		/* If the local source is invalid, skip this entry. */
1969
		$local_spec = ipsec_get_phase1_src($ph1ent);
1970
		if (!$local_spec) {
1971
			continue;
1972
		}
1973

    
1974
		/* Determine the name of this connection, either con-mobile for
1975
		 * mobile clients, or a name based on the IKE ID otherwise. */
1976
		$cname = isset($ph1ent['mobile']) ? "con-mobile" : "con{$ph1ent['ikeid']}000";
1977
		/* Start with common default values */
1978
		$scconf['connections'][$cname] = $conn_defaults;
1979
		/* Array reference to make things easier */
1980
		$conn =& $scconf['connections'][$cname];
1981

    
1982
		/* Common parameters for all children */
1983
		$child_params = array();
1984
		if (!empty($ph1ent['closeaction'])) {
1985
			$child_params['close_action'] = $ph1ent['closeaction'];
1986
		}
1987

    
1988
		$ikeid = $ph1ent['ikeid'];
1989

    
1990
		/* "trap" adds policies to start a tunnel when interesting
1991
		 * traffic is observed by the host. */
1992
		$start_action = "trap";
1993

    
1994
		/* Set the IKE version appropriately (empty = IKEv1) */
1995
		switch ($ph1ent['iketype']) {
1996
			case 'auto':
1997
				$ikeversion = 0;
1998
				break;
1999
			case 'ikev2':
2000
				$ikeversion = 2;
2001
				break;
2002
			case 'ikev1':
2003
			default:
2004
				$ikeversion = 1;
2005
				break;
2006
		}
2007
		$conn['version'] = $ikeversion;
2008

    
2009
		/* For IKEv1 or auto, setup aggressive mode if configured */
2010
		if ($ikeversion != 2){
2011
			$conn['aggressive'] = ($ph1ent['mode'] == "aggressive") ? "yes" : "no";
2012
		}
2013

    
2014
		if (isset($ph1ent['mobile'])) {
2015
			/* Mobile tunnels allow 'any' as a peer */
2016
			$remote_spec = "0.0.0.0/0,::/0";
2017
			/* Mobile tunnels cannot start automatically */
2018
			$start_action = 'none';
2019
		} else {
2020
			$remote_spec = $ph1ent['remote-gateway'];
2021
			$sourcehost = (is_ipaddr($remote_spec)) ? $remote_spec : $rgmap[$remote_spec];
2022
			$ifacesuse = ipsec_setup_routes($ph1ent['interface'], $ph1ent['protocol'], $sourcehost, isset($ph1ent['gw_duplicates']));
2023
		}
2024

    
2025
		/* Setup IKE proposals */
2026
		if (is_array($ph1ent['encryption']['item'])) {
2027
			$ciphers = array();
2028
			foreach($ph1ent['encryption']['item'] as $p1enc) {
2029
				if (!is_array($p1enc['encryption-algorithm']) ||
2030
						empty($p1enc['encryption-algorithm']['name']) ||
2031
						empty($p1enc['hash-algorithm'])) {
2032
					continue;
2033
				}
2034
				$ciphers[] = ipsec_setup_proposal_algo($p1enc['encryption-algorithm']['name'],
2035
									$p1enc['encryption-algorithm']['keylen'],
2036
									$p1enc['hash-algorithm'],
2037
									$p1enc['dhgroup']);
2038
			}
2039
			$conn['proposals'] = implode(",", $ciphers);
2040
		}
2041

    
2042
		/* Configure DPD values. The DPD action is a per-child parameter,
2043
		 * not per-connection like the delay and timeout. */
2044
		if ($ph1ent['dpd_delay'] && $ph1ent['dpd_maxfail']) {
2045
			if ($start_action == "trap") {
2046
				$child_params['dpd_action'] = "restart";
2047
			} else {
2048
				$child_params['dpd_action'] = "clear";
2049
			}
2050
			$conn['dpd_delay'] = "{$ph1ent['dpd_delay']}s";
2051
			$conn['dpd_timeout'] =  $ph1ent['dpd_delay'] * ($ph1ent['dpd_maxfail'] + 1) . "s";
2052
		} else {
2053
			$child_params['dpd_action'] = "none";
2054
		}
2055

    
2056
		/* Reauth (Any) */
2057
		$conn['reauth_time'] = (empty($ph1ent['reauth_time']) ? "0" : $ph1ent['reauth_time']) . "s";
2058

    
2059
		/* Rekey (IKEv2 or Auto only, not supported by IKEv1) */
2060
		if (($ikeversion == 0) || ($ikeversion == 2)) {
2061
			$conn['rekey_time'] = (empty($ph1ent['rekey_time']) ? "0" : $ph1ent['rekey_time']) . "s";
2062
		}
2063

    
2064
		/* Over Time */
2065
		if (!empty($ph1ent['over_time'])) {
2066
			$conn['over_time'] = "{$ph1ent['over_time']}s";
2067
		}
2068

    
2069
		/* NAT Traversal */
2070
		$conn['encap'] = ($ph1ent['nat_traversal'] == 'force') ? "yes" : "no";
2071

    
2072
		/* MOBIKE support */
2073
		$conn['mobike'] = ($ph1ent['mobike'] == 'on') ? "yes" : "no";
2074

    
2075
		/* TFC Padding */
2076
		if (isset($ph1ent['tfc_enable'])) {
2077
			$conn['tfc_padding'] = (isset($ph1ent['tfc_bytes']) && is_numericint($ph1ent['tfc_bytes'])) ? $ph1ent['tfc_bytes'] : "mtu";
2078
		}
2079

    
2080
		/* Arrays for P2s/children */
2081
		$children = array();
2082
		$remote_ts_spec = array();
2083
		$local_ts_spec = array();
2084
		$reqids = array();
2085
		$has_vti = false;
2086
		$ealgoAHsp2arr = array();
2087
		$ealgoESPsp2arr = array();
2088
		$suffix = 0;
2089

    
2090
		foreach ($ph1ent['p2'] as $ph2ent) {
2091
			/* If this entry is disabled, or cannot be configured, skip. */
2092
			if (isset($ph2ent['disabled']) ||
2093
			    (isset($ph2ent['mobile']) && !isset($a_client['enable']))) {
2094
				continue;
2095
			}
2096
			$child = array();
2097
			$local_ts = "";
2098
			$remote_ts = "";
2099
			if (($ph2ent['mode'] == 'tunnel') or ($ph2ent['mode'] == 'tunnel6')) {
2100
				/* Normal tunnel child config */
2101
				$child['mode'] = "tunnel";
2102
				$child['policies'] = "yes";
2103

    
2104
				$localid_type = $ph2ent['localid']['type'];
2105
				$localsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
2106

    
2107
				/* Do not print localid in some cases, such as a pure-psk or psk/xauth single phase2 mobile tunnel */
2108
				if (($localid_type == "none" || $localid_type == "mobile") &&
2109
				    isset($ph1ent['mobile']) && (ipsec_get_number_of_phase2($ikeid) == 1)) {
2110
					$local_spec = '0.0.0.0/0,::/0';
2111
				} else {
2112
					if ($localid_type != "address") {
2113
						$localid_type = "subnet";
2114
					}
2115
					// Don't let an empty subnet into config, it can cause parse errors. Ticket #2201.
2116
					if (!is_ipaddr($localsubnet_data) && !is_subnet($localsubnet_data) && ($localsubnet_data != "0.0.0.0/0")) {
2117
						log_error("Invalid IPsec Phase 2 \"{$ph2ent['descr']}\" - {$ph2ent['localid']['type']} has no subnet.");
2118
						continue;
2119
					}
2120
					if (!empty($ph2ent['natlocalid'])) {
2121
						$natlocalsubnet_data = ipsec_idinfo_to_cidr($ph2ent['natlocalid'], false, $ph2ent['mode']);
2122
						if ($ph2ent['natlocalid']['type'] != "address") {
2123
							if (is_subnet($natlocalsubnet_data)) {
2124
								$localsubnet_data = "{$natlocalsubnet_data}|{$localsubnet_data}";
2125
							}
2126
						} else {
2127
							if (is_ipaddr($natlocalsubnet_data)) {
2128
								$localsubnet_data = "{$natlocalsubnet_data}|{$localsubnet_data}";
2129
							}
2130
						}
2131
						$natfilterrules = true;
2132
					}
2133
				}
2134

    
2135
				$local_ts = $localsubnet_data;
2136

    
2137
				if (!isset($ph2ent['mobile'])) {
2138
					$remote_ts = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
2139
				} else if (!empty($a_client['pool_address'])) {
2140
					$remote_ts = "{$a_client['pool_address']}/{$a_client['pool_netbits']}";
2141
				}
2142

    
2143
			} elseif ($ph2ent['mode'] == 'vti') {
2144
				/* VTI-specific child config */
2145
				$child['policies'] = "no";
2146
				/* VTI cannot use trap policies, so start automatically instead */
2147
				$start_action = 'start';
2148
				$localid_type = $ph2ent['localid']['type'];
2149
				$localsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
2150
				$local_ts = $localsubnet_data;
2151
				$remote_ts = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
2152
				$has_vti = true;
2153
			} else {
2154
				/* Transport mode child config */
2155
				$child['mode'] = "transport";
2156
				$child['policies'] = "yes";
2157

    
2158
				if ((($ph1ent['authentication_method'] == "xauth_psk_server") ||
2159
				    ($ph1ent['authentication_method'] == "pre_shared_key")) &&
2160
				    isset($ph1ent['mobile'])) {
2161
					$local_spec = "0.0.0.0/0,::/0";
2162
				} else {
2163
					$local_ts = ipsec_get_phase1_src($ph1ent);
2164
				}
2165

    
2166
				if (!isset($ph2ent['mobile'])) {
2167
					$remote_ts = $remote_spec;
2168
				}
2169
			}
2170

    
2171
			if (!empty($local_ts)) {
2172
				$local_ts_spec[] = $local_ts;
2173
			}
2174
			if (!empty($remote_ts)) {
2175
				$remote_ts_spec[] = $remote_ts;
2176
			}
2177

    
2178
			/* If a PFS group is configured on the Mobile Clients tab,
2179
			 * and this is a mobile P2, use it here. */
2180
			if (isset($a_client['pfs_group']) && isset($ph2ent['mobile'])) {
2181
				$ph2ent['pfsgroup'] = $a_client['pfs_group'];
2182
			}
2183

    
2184
			$reqids[] = $ph2ent['reqid'];
2185

    
2186
			if (!empty($ph2ent['lifetime'])) {
2187
				$child['life_time'] = intval($ph2ent['lifetime']);
2188
			}
2189

    
2190
			/* If we are to act only as a responder, disable the start action */
2191
			$child['start_action'] = isset($ph1ent['responderonly']) ? 'none' : $start_action;
2192

    
2193
			/* Setup child SA proposals */
2194
			$proposal = array();
2195
			if ($ph2ent['protocol'] == 'esp') {
2196
				if (is_array($ph2ent['encryption-algorithm-option'])) {
2197
					foreach ($ph2ent['encryption-algorithm-option'] as $ealg) {
2198
						$ealg_id = $ealg['name'];
2199
						$ealg_kl = $ealg['keylen'];
2200

    
2201
						if (!empty($ealg_kl) && $ealg_kl == "auto") {
2202
							if (empty($p2_ealgos) || !is_array($p2_ealgos)) {
2203
								require_once("ipsec.inc");
2204
							}
2205
							$key_hi = $p2_ealgos[$ealg_id]['keysel']['hi'];
2206
							$key_lo = $p2_ealgos[$ealg_id]['keysel']['lo'];
2207
							$key_step = $p2_ealgos[$ealg_id]['keysel']['step'];
2208
							/* XXX: in some cases where include ordering is suspect these variables
2209
							 * are somehow 0 and we enter this loop forever and timeout after 900
2210
							 * seconds wrecking bootup */
2211
							if ($key_hi != 0 and $key_lo != 0 and $key_step != 0) {
2212
								for ($keylen = $key_hi; $keylen >= $key_lo; $keylen -= $key_step) {
2213
									$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoESPsp2arr, $ealg_id, $keylen);
2214
								}
2215
							}
2216
						} else {
2217
							$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoESPsp2arr, $ealg_id, $ealg_kl);
2218
						}
2219
					}
2220
				}
2221
			} else if ($ph2ent['protocol'] == 'ah') {
2222
				$proposal[] = ipsec_setup_proposal_entry($ph2ent, $ealgoAHsp2arr, '', '');
2223
			}
2224

    
2225
			/* Not mobile, and IKEv1 or Split Connections active */
2226
			if (!isset($ph1ent['mobile']) && (($ikeversion == 1) || isset($ph1ent['splitconn']))) {
2227
				if (!empty($remote_ts)) {
2228
					/* Setup child sub-connections using unique names with a suffix */
2229
					$subconname = "con{$ph1ent['ikeid']}00{$suffix}";
2230
					$children[$subconname] = $child;
2231
					$children[$subconname]['local_ts'] = $local_ts;
2232
					$children[$subconname]['remote_ts'] = $remote_ts;
2233
					if ($has_vti) {
2234
						ipsec_setup_vtireq($children[$subconname], $ipsec_vti_cleanup_ifs, $ph1ent['ikeid'], $suffix);
2235
					}
2236
					if (!empty($ph2ent['protocol']) && !empty($proposal)) {
2237
						$children[$subconname][$ph2ent['protocol'] . '_proposals'] = implode(',', $proposal);
2238
					}
2239
				} else {
2240
					log_error(sprintf(gettext("No phase2 specifications for tunnel with REQID = %s"), $ikeid));
2241
				}
2242
			} else {
2243
				/* TODO: Fix this to nicely merge all P2 params for single child case */
2244
				if (!is_array($children[$cname])) {
2245
					$children[$cname] = array();
2246
				}
2247
				$children[$cname] = array_merge($children[$cname], $child);
2248
			}
2249
			$suffix++;
2250
		}
2251

    
2252
		$conn['local_addrs'] = $local_spec;
2253
		$conn['remote_addrs'] = $remote_spec;
2254

    
2255
		if (isset($ph1ent['mobile'])) {
2256
			$conn['pools'] = "mobile-pool";
2257
		}
2258

    
2259
		/* For IKEv2 without Split Connections, setup combined sets of
2260
		 * local/remote traffic selectors and propsals */
2261
		if (!(!isset($ph1ent['mobile']) && (($ikeversion == 1) || isset($ph1ent['splitconn'])))) {
2262
			if (!isset($ph1ent['mobile']) && !empty($remote_ts_spec)) {
2263
				$children[$cname]['remote_ts'] = implode(",", $remote_ts_spec);
2264
			}
2265
			if (!empty($local_ts_spec)) {
2266
				$children[$cname]['local_ts'] = implode(",", $local_ts_spec);
2267
			}
2268
			if ($has_vti) {
2269
				ipsec_setup_vtireq($children[$cname], $ipsec_vti_cleanup_ifs, $ph1ent['ikeid']);
2270
			}
2271
			if (!empty($ealgoAHsp2arr)) {
2272
				$children[$cname]['ah_proposals'] = implode(',', array_unique($ealgoAHsp2arr));
2273
			}
2274
			if (!empty($ealgoESPsp2arr)) {
2275
				$children[$cname]['esp_proposals'] = implode(',', array_unique($ealgoESPsp2arr));
2276
			}
2277
		}
2278

    
2279
		/* Setup connection authentication */
2280
		ipsec_setup_authentication($ph1ent, $conn);
2281

    
2282
		/* Add children to this connection, including default child parameters */
2283
		if (count($children)) {
2284
			foreach($children as $name => $child) {
2285
				$conn['children'][$name] = array_merge($child_params, $child);
2286
			}
2287
		}
2288

    
2289
	}
2290

    
2291
	return;
2292
}
2293

    
2294
/****f* ipsec/ipsec_setup_secrets
2295
 * NAME
2296
 *   ipsec_setup_secrets - Setup swanctl authentication secrets
2297
 * INPUTS
2298
 *   None
2299
 * RESULT
2300
 *   Returns a swanctl array containing secrets (PSKs, certs, etc) and writes out
2301
 *   necessary CA, CRL, and certificate data.
2302
 ******/
2303
function ipsec_setup_secrets() {
2304
	global $config, $a_phase1, $ipsec_swanctl_dirs, $ipseccfg, $rgmap, $scconf;
2305

    
2306
	$suffix = 0;
2307

    
2308
	/* write out CRL files */
2309
	if (is_array($config['crl']) && count($config['crl'])) {
2310
		foreach ($config['crl'] as $crl) {
2311
			if (!isset($crl['text'])) {
2312
				log_error(sprintf(gettext("Warning: Missing CRL data for %s"), $crl['descr']));
2313
				continue;
2314
			}
2315
			$fpath = "{$ipsec_swanctl_dirs['crlpath']}/{$crl['refid']}.crl";
2316
			if (!@file_put_contents($fpath, base64_decode($crl['text']))) {
2317
				log_error(sprintf(gettext("Error: Cannot write IPsec CRL file for %s"), $crl['descr']));
2318
				continue;
2319
			}
2320
		}
2321
	}
2322

    
2323
	$vpncas = array();
2324
	if (is_array($a_phase1) && count($a_phase1)) {
2325
		foreach ($a_phase1 as $ph1ent) {
2326
			if (isset($ph1ent['disabled'])) {
2327
				continue;
2328
			}
2329

    
2330
			if (strstr($ph1ent['authentication_method'], 'cert') ||
2331
			    in_array($ph1ent['authentication_method'], array('eap-mschapv2', 'eap-tls', 'eap-radius'))) {
2332
				/* Write certificate and private key, point to private key */
2333
				$certline = '';
2334

    
2335
				$ikeid = $ph1ent['ikeid'];
2336
				$cert = lookup_cert($ph1ent['certref']);
2337

    
2338
				if (!$cert) {
2339
					log_error(sprintf(gettext("Error: Invalid phase1 certificate reference for %s"), $ph1ent['name']));
2340
					continue;
2341
				}
2342

    
2343
				/* add signing CA cert chain of server cert
2344
				 * to the list of CAs to write
2345
				 */
2346
				$cachain = ca_chain_array($cert);
2347
				if ($cachain && is_array($cachain)) {
2348
					foreach ($cachain as $cacrt) {
2349
						$vpncas[$cacrt['refid']] = $cacrt;
2350
					}
2351
				}
2352

    
2353
				@chmod($ipsec_swanctl_dirs['certpath'], 0600);
2354

    
2355
				$ph1keyfile = "{$ipsec_swanctl_dirs['keypath']}/cert-{$ikeid}.key";
2356
				if (!file_put_contents($ph1keyfile, base64_decode($cert['prv']))) {
2357
					log_error(sprintf(gettext("Error: Cannot write phase1 key file for %s"), $ph1ent['name']));
2358
					continue;
2359
				}
2360
				@chmod($ph1keyfile, 0600);
2361

    
2362
				$ph1certfile = "{$ipsec_swanctl_dirs['certpath']}/cert-{$ikeid}.crt";
2363
				if (!file_put_contents($ph1certfile, base64_decode($cert['crt']))) {
2364
					log_error(sprintf(gettext("Error: Cannot write phase1 certificate file for %s"), $ph1ent['name']));
2365
					@unlink($ph1keyfile);
2366
					continue;
2367
				}
2368
				@chmod($ph1certfile, 0600);
2369

    
2370
				$scconf['secrets']['private-' . $suffix++] = array('file' => $ph1keyfile);
2371
			} else if (strstr($ph1ent['authentication_method'], 'pkcs11')) {
2372
				$p11_id = array();
2373
				$output = shell_exec('/usr/local/bin/pkcs15-tool -c');
2374
				preg_match_all('/ID\s+: (.*)/', $output, $p11_id);
2375
				if (!empty($ph1ent['pkcs11certref']) && in_array($ph1ent['pkcs11certref'], $p11_id[1])) {
2376
					$scconf['secrets']['token-' . $suffix++] = array(
2377
						'handle' => $ph1ent['pkcs11certref'],
2378
						'pin' => $ph1ent['pkcs11pin'],
2379
					);
2380
				} else {
2381
					log_error(sprintf(gettext("Error: Invalid phase1 PKCS#11 certificate reference or PKCS#11 is not present for %s"), $ph1ent['name']));
2382
					continue;
2383
				}
2384
			} else {
2385
				/* Setup pre-shared keys */
2386
				list($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local');
2387
				list($peerid_type, $peerid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap);
2388
				$myid = trim($myid_data);
2389

    
2390
				if (empty($peerid_data)) {
2391
					continue;
2392
				}
2393

    
2394
				if ($myid_type == 'fqdn' && !empty($myid)) {
2395
					$myid = "@{$myid}";
2396
				}
2397

    
2398
				$myid = isset($ph1ent['mobile']) ? trim($myid_data) : "%any";
2399
				$peerid = ($peerid_data != 'allusers') ? trim($peerid_data) : '';
2400

    
2401
				if ($peerid_type == 'fqdn' && !empty($peerid)) {
2402
					$peerid = "@{$peerid}";
2403
				}
2404

    
2405
				if (!empty($ph1ent['pre-shared-key'])) {
2406
					$scconf['secrets']['ike-' . $suffix++] = array(
2407
						'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
2408
						'id-0' => $myid,
2409
						'id-1' => $peerid,
2410
					);
2411
					if (isset($ph1ent['mobile'])) {
2412
						$scconf['secrets']['ike-' . $suffix++] = array(
2413
							'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
2414
							'id-0' => $myid,
2415
							'id-1' => '%any',
2416
						);
2417
						$scconf['secrets']['ike-' . $suffix++] = array(
2418
							'secret' => '0s' . base64_encode(trim($ph1ent['pre-shared-key'])),
2419
						);
2420
					}
2421
				}
2422
			}
2423

    
2424
			/* if the client authenticates with a cert add the
2425
			 * client cert CA chain to the list of CAs to write
2426
			 */
2427
			if (in_array($ph1ent['authentication_method'],
2428
			    array('cert', 'eap-tls', 'xauth_cert_server', 'pkcs11'))) {
2429
				if (!empty($ph1ent['caref']) && !array_key_exists($ph1ent['caref'], $vpncas)) {
2430
					$thisca = lookup_ca($ph1ent['caref']);
2431
					$vpncas[$ph1ent['caref']] = $thisca;
2432
					/* follow chain up to root */
2433
					$cachain = ca_chain_array($thisca);
2434
					if ($cachain and is_array($cachain)) {
2435
						foreach ($cachain as $cacrt) {
2436
							$vpncas[$cacrt['refid']] = $cacrt;
2437
						}
2438
					}
2439
				}
2440
			}
2441
		}
2442
	}
2443

    
2444
	/* Write the required CAs */
2445
	foreach ($vpncas as $carefid => $cadata) {
2446
		$cacrt = base64_decode($cadata['crt']);
2447
		$cacrtattrs = openssl_x509_parse($cacrt);
2448
		if (!is_array($cacrtattrs) || !isset($cacrtattrs['hash'])) {
2449
			log_error(sprintf(gettext("Error: Invalid certificate hash info for %s"), $cadata['descr']));
2450
			continue;
2451
		}
2452
		$cafilename = "{$ipsec_swanctl_dirs['capath']}/{$cacrtattrs['hash']}.0";
2453
		if (!@file_put_contents($cafilename, $cacrt)) {
2454
				log_error(sprintf(gettext("Error: Cannot write IPsec CA file for %s"), $cadata['descr']));
2455
				continue;
2456
		}
2457
	}
2458

    
2459
	/* Add user PSKs */
2460
	if (is_array($config['system']) && is_array($config['system']['user'])) {
2461
		foreach ($config['system']['user'] as $user) {
2462
			if (!empty($user['ipsecpsk'])) {
2463
				$scconf['secrets']['ike-' . $suffix++] = array(
2464
					'secret' => '0s' . base64_encode(trim($user['ipsecpsk'])),
2465
					'id-0' => $myid,
2466
					'id-1' => $user['name'],
2467
				);
2468
			}
2469
		}
2470
		unset($user);
2471
	}
2472

    
2473
	/* add PSKs for mobile clients */
2474
	if (is_array($ipseccfg['mobilekey'])) {
2475
		foreach ($ipseccfg['mobilekey'] as $key) {
2476
			if (($key['ident'] == 'allusers') ||
2477
			    ($key['ident'] == 'any')) {
2478
				$key['ident'] = '%any';
2479
			}
2480
			$scconf['secrets']['eap-' . $suffix++] = array(
2481
				'secret' => '0s' . base64_encode(trim($key['pre-shared-key'])),
2482
				'id-0' => $key['ident'],
2483
			);
2484
		}
2485
		unset($key);
2486
	}
2487
	return;
2488
}
2489

    
2490
/****f* ipsec/ipsec_configure
2491
 * NAME
2492
 *   ipsec_configure - Configure IPsec
2493
 * INPUTS
2494
 *   $restart: Boolean (default false), whether or not to restart the IPsec
2495
 *             daemons.
2496
 * RESULT
2497
 *   IPsec-related configuration files are written, daemon is started or stopped
2498
 *   appropriately.
2499
 ******/
2500
function ipsec_configure($restart = false) {
2501
	global $aggressive_mode_psk, $a_client, $a_phase1, $a_phase2, $config,
2502
		$filterdns_list, $g, $ifacesuse, $ipsec_idhandling, $ipsec_log_cats,
2503
		$ipsec_log_sevs, $ipsec_swanctl_basedir, $ipsec_swanctl_dirs,
2504
		$ipseccfg, $mobile_ipsec_auth, $natfilterrules, $p1_ealgos,
2505
		$p2_ealgos, $rgmap, $sa, $sn, $scconf, $tunnels, $mobile_configured,
2506
		$ipsec_vti_cleanup_ifs, $conn_defaults, $pool_addrs;
2507

    
2508
	/* service may have been enabled, disabled, or otherwise changed in a
2509
	 *way requiring rule updates */
2510
	filter_configure();
2511

    
2512
	if (!ipsec_enabled()) {
2513
		/* IPsec is disabled */
2514
		/* Stop charon */
2515
		mwexec("/usr/local/sbin/strongswanrc stop");
2516
		/* Stop dynamic monitoring */
2517
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
2518
		/* Wait for process to die */
2519
		sleep(2);
2520
		/* Shutdown enc0 interface*/
2521
		mwexec("/sbin/ifconfig enc0 down");
2522
		return 0;
2523
	} else {
2524
		/* Startup enc0 interface */
2525
		mwexec("/sbin/ifconfig enc0 up");
2526
	}
2527

    
2528
	if (platform_booting()) {
2529
		echo gettext("Configuring IPsec VPN... ");
2530
	}
2531

    
2532
	$ipsecstartlock = lock('ipsec', LOCK_EX);
2533

    
2534
	/* Prepare automatic ping_hosts.sh data */
2535
	unlink_if_exists("{$g['vardb_path']}/ipsecpinghosts");
2536
	touch("{$g['vardb_path']}/ipsecpinghosts");
2537
	$ipsecpinghostsactive = false;
2538

    
2539
	/* Populate convenience variables */
2540
	$syscfg = $config['system'];
2541
	init_config_arr(array('ipsec', 'phase1'));
2542
	$ipseccfg = $config['ipsec'];
2543
	$a_phase1 = $config['ipsec']['phase1'];
2544
	init_config_arr(array('ipsec', 'phase2'));
2545
	$a_phase2 = $config['ipsec']['phase2'];
2546
	init_config_arr(array('ipsec', 'client'));
2547
	$a_client = $config['ipsec']['client'];
2548

    
2549
	$mobile_configured = false;
2550

    
2551
	/* Setup a single structured array to process, to avoid repeatedly
2552
	 * looping through the arrays to locate entries later. */
2553
	$tunnels = array();
2554
	foreach ($a_phase1 as $p1) {
2555
		if (isset($p1['mobile']) && !isset($p1['disabled'])) {
2556
			$mobile_configured = true;
2557
		}
2558
		$tunnels[$p1['ikeid']] = $p1;
2559
		$tunnels[$p1['ikeid']]['p2'] = array();
2560
	}
2561
	foreach ($a_phase2 as $p2) {
2562
		$tunnels[$p2['ikeid']]['p2'][] = $p2;
2563
	}
2564

    
2565
	$ipsec_vti_cleanup_ifs = array();
2566
	$rgmap = array();
2567
	$filterdns_list = array();
2568
	$aggressive_mode_psk = false;
2569
	$mobile_ipsec_auth = "";
2570
	$ifacesuse = array();
2571
	$natfilterrules = false;
2572

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

    
2576
	/* Build a list of all IPsec interfaces configured on the firewall at the OS level */
2577
	foreach (get_interface_arr() as $thisif) {
2578
		if (substr($thisif, 0, 5) == "ipsec") {
2579
			$ipsec_vti_cleanup_ifs[] = $thisif;
2580
		}
2581
	}
2582

    
2583
	/* Create directory structure for IPsec */
2584
	ipsec_create_dirs();
2585

    
2586
	/* Setup gateways and interfaces */
2587
	ipsec_setup_gwifs();
2588

    
2589
	/* Setup and write strongswan.conf */
2590
	ipsec_setup_strongswan();
2591

    
2592
	/* Start Global Connection default values */
2593
	$conn_defaults = array();
2594
	/* Fragmentation is on for everyone */
2595
	$conn_defaults['fragmentation'] = "yes";
2596
	/* Default to 'replace' for unique IDs (was 'yes' in ipsec.conf previously) */
2597
	$conn_defaults['unique'] = 'replace';
2598
	/* If the configuration has a valid alternate value for unique ID handling,
2599
	 * use it instead. */
2600
	if (!empty($config['ipsec']['uniqueids']) &&
2601
	    array_key_exists($config['ipsec']['uniqueids'], $ipsec_idhandling)) {
2602
		$conn_defaults['unique'] = $config['ipsec']['uniqueids'];
2603
	}
2604
	if (isset($config['ipsec']['strictcrlpolicy'])) {
2605
		$conn_defaults['strictcrlpolicy'] = "yes";
2606
	}
2607
	/* Disable ipcomp for now. redmine #6167
2608
	if (isset($config['ipsec']['compression'])) {
2609
		$conn_defaults['compress'] = "yes";
2610
	}
2611
	set_single_sysctl('net.inet.ipcomp.ipcomp_enable', (isset($config['ipsec']['compression'])) ? 1 : 0);
2612
	*/
2613
	/* End Global Connection Defaults */
2614

    
2615
	/* Start swanctl configuration (scconf) */
2616
	$scconf = array();
2617
	$scconf[] = "# This file is automatically generated. Do not edit";
2618
	$scconf['connections'] = array();
2619
	/* Setup LAN bypass */
2620
	ipsec_setup_bypasslan();
2621
	/* Setup connections */
2622
	ipsec_setup_tunnels();
2623
	$scconf['pools'] = array();
2624
	if ($mobile_configured) {
2625
		/* Setup mobile address pools */
2626
		ipsec_setup_pools();
2627
		/* Setup per-user pools */
2628
		ipsec_setup_userpools();
2629
	}
2630
	/* Setup secret data */
2631
	$scconf['secrets'] = array();
2632
	ipsec_setup_secrets();
2633

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

    
2636
	/* Clean up unused VTI interfaces */
2637
	foreach ($ipsec_vti_cleanup_ifs as $cleanif) {
2638
		if (does_interface_exist($cleanif)) {
2639
			mwexec("/sbin/ifconfig " . escapeshellarg($cleanif) . " destroy", false);
2640
		}
2641
	}
2642

    
2643
	/* Manage process */
2644
	if ($restart === true) {
2645
		mwexec_bg("/usr/local/sbin/strongswanrc restart", false);
2646
	} else {
2647
		if (isvalidpid("{$g['varrun_path']}/charon.pid")) {
2648
			mwexec_bg("/usr/local/sbin/strongswanrc reload", false);
2649
		} else {
2650
			mwexec_bg("/usr/local/sbin/strongswanrc start", false);
2651
		}
2652
	}
2653

    
2654
	// Run ping_hosts.sh once if it's enabled to avoid wait for minicron
2655
	if ($ipsecpinghostsactive) {
2656
		mwexec_bg("/usr/local/bin/ping_hosts.sh");
2657
	}
2658

    
2659
	if ($natfilterrules == true) {
2660
		filter_configure();
2661
	}
2662
	/* start filterdns, if necessary */
2663
	if (count($filterdns_list) > 0) {
2664
		$interval = 60;
2665
		if (!empty($ipseccfg['dns-interval']) && is_numeric($ipseccfg['dns-interval'])) {
2666
			$interval = $ipseccfg['dns-interval'];
2667
		}
2668

    
2669
		$hostnames = "";
2670
		array_unique($filterdns_list);
2671
		foreach ($filterdns_list as $hostname) {
2672
			$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload ipsecdns\"'\n";
2673
		}
2674
		file_put_contents("{$g['varetc_path']}/ipsec/filterdns-ipsec.hosts", $hostnames);
2675
		unset($hostnames);
2676

    
2677
		if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid")) {
2678
			sigkillbypid("{$g['varrun_path']}/filterdns-ipsec.pid", "HUP");
2679
		} else {
2680
			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");
2681
		}
2682
	} else {
2683
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
2684
		@unlink("{$g['varrun_path']}/filterdns-ipsec.pid");
2685
	}
2686

    
2687
	if (platform_booting()) {
2688
		echo "done\n";
2689
	}
2690

    
2691
	unlock($ipsecstartlock);
2692
	return count($filterdns_list);
2693
}
2694
?>
(26-26/60)