Project

General

Profile

Download (55.3 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2

    
3
/*
4
	vpn.inc
5
	Copyright (C) 2004 Scott Ullrich
6
	Copyright (C) 2008 Shrew Soft Inc
7
	Copyright (C) 2008 Ermal Lu�i
8
	All rights reserved.
9

    
10
	originally part of m0n0wall (http://m0n0.ch/wall)
11
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
12
	All rights reserved.
13

    
14
	Redistribution and use in source and binary forms, with or without
15
	modification, are permitted provided that the following conditions are met:
16

    
17
	1. Redistributions of source code must retain the above copyright notice,
18
	   this list of conditions and the following disclaimer.
19

    
20
	2. Redistributions in binary form must reproduce the above copyright
21
	   notice, this list of conditions and the following disclaimer in the
22
	   documentation and/or other materials provided with the distribution.
23

    
24
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
25
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
26
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
28
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33
	POSSIBILITY OF SUCH DAMAGE.
34
*/
35

    
36
/*
37
	pfSense_BUILDER_BINARIES:	/sbin/ifconfig
38
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/ipsec	/usr/local/libexec/ipsec/charon /usr/local/libexec/ipsec/starter
39
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/filterdns	/usr/local/sbin/mpd4
40
	pfSense_MODULE:	vpn
41
*/
42

    
43
require_once("ipsec.inc");
44

    
45
function vpn_ipsec_configure_loglevels($forconfig = false)
46
{
47
	global $config, $ipsec_loglevels;
48

    
49
	$cfgtext = array();
50
	foreach ($ipsec_loglevels as $lkey => $ldescr) {
51
		if (!isset($config['ipsec']["ipsec_{$lkey}"]) && !$forconfig) {
52
			mwexec("/usr/local/sbin/ipsec stroke loglevel {$lkey} -- -1", false);
53
		} else if (is_numeric($config['ipsec']["ipsec_{$lkey}"]) &&
54
		    intval($config['ipsec']["ipsec_{$lkey}"]) >= 0 && intval($config['ipsec']["ipsec_{$lkey}"]) <= 5) {
55
			$forconfig ? $cfgtext[] = "${lkey} " . (intval($config['ipsec']["ipsec_{$lkey}"]) - 1) :
56
				mwexec("/usr/local/sbin/ipsec stroke loglevel {$lkey} " . (intval($config['ipsec']["ipsec_{$lkey}"]) - 1) , false);
57
		}
58
	}
59
	if ($forconfig) {
60
		return implode(',', $cfgtext);
61
	}
62
}
63

    
64
/* include all configuration functions */
65
function vpn_ipsec_convert_to_modp($index)
66
{
67

    
68
	$convertion = "";
69
	switch ($index) {
70
		case '1':
71
			$convertion = "modp768";
72
			break;
73
		case '2':
74
			$convertion = "modp1024";
75
			break;
76
		case '5':
77
			$convertion = "modp1536";
78
			break;
79
		case '14':
80
			$convertion = "modp2048";
81
			break;
82
		case '15':
83
			$convertion = "modp3072";
84
			break;
85
		case '16':
86
			$convertion = "modp4096";
87
			break;
88
		case '17':
89
			$convertion = "modp6144";
90
			break;
91
		case '18':
92
			$convertion = "modp8192";
93
			break;
94
	}
95

    
96
	return $convertion;
97
}
98

    
99
function vpn_ipsec_configure($restart = false)
100
{
101
	global $config, $g, $sa, $sn, $p1_ealgos, $p2_ealgos, $ipsec_idhandling;
102

    
103
	if ($g['platform'] == 'jail') {
104
		return;
105
	}
106

    
107
	/* get the automatic ping_hosts.sh ready */
108
	unlink_if_exists("{$g['vardb_path']}/ipsecpinghosts");
109
	touch("{$g['vardb_path']}/ipsecpinghosts");
110

    
111
	$syscfg = $config['system'];
112
	$ipseccfg = $config['ipsec'];
113
	if (!isset($ipseccfg['enable'])) {
114
		/* try to stop charon */
115
		mwexec("/usr/local/sbin/ipsec stop");
116
		/* Stop dynamic monitoring */
117
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
118

    
119
		/* wait for process to die */
120
		sleep(2);
121

    
122
		/* disallow IPSEC, it is off */
123
		mwexec("/sbin/ifconfig enc0 down");
124
		set_single_sysctl("net.inet.ip.ipsec_in_use", "0");
125

    
126
		filter_configure();
127

    
128
		return 0;
129
	}
130

    
131
	$a_phase1 = $config['ipsec']['phase1'];
132
	$a_phase2 = $config['ipsec']['phase2'];
133
	$a_client = $config['ipsec']['client'];
134

    
135
	$certpath = "{$g['varetc_path']}/ipsec/ipsec.d/certs";
136
	$capath = "{$g['varetc_path']}/ipsec/ipsec.d/cacerts";
137
	$keypath = "{$g['varetc_path']}/ipsec/ipsec.d/private";
138

    
139
	mwexec("/sbin/ifconfig enc0 up");
140
	set_single_sysctl("net.inet.ip.ipsec_in_use", "1");
141
	/* needed for config files */
142
	if (!is_dir("{$g['varetc_path']}/ipsec")) {
143
		mkdir("{$g['varetc_path']}/ipsec");
144
	}
145
	if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d")) {
146
		mkdir("{$g['varetc_path']}/ipsec/ipsec.d");
147
	}
148
	if (!is_dir($capath)) {
149
		mkdir($capath);
150
	}
151
	if (!is_dir($keypath)) {
152
		mkdir($keypath);
153
	}
154
	if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/crls")) {
155
		mkdir("{$g['varetc_path']}/ipsec/ipsec.d/crls");
156
	}
157
	if (!is_dir($certpath)) {
158
		mkdir($certpath);
159
	}
160
	if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/aacerts")) {
161
		mkdir("{$g['varetc_path']}/ipsec/ipsec.d/aacerts");
162
	}
163
	if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/acerts")) {
164
		mkdir("{$g['varetc_path']}/ipsec/ipsec.d/acerts");
165
	}
166
	if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/ocspcerts")) {
167
		mkdir("{$g['varetc_path']}/ipsec/ipsec.d/ocspcerts");
168
	}
169
	if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/reqs")) {
170
		mkdir("{$g['varetc_path']}/ipsec/ipsec.d/reqs");
171
	}
172

    
173

    
174
	if (platform_booting()) {
175
		echo gettext("Configuring IPsec VPN... ");
176
	}
177

    
178
	/* fastforwarding is not compatible with ipsec tunnels */
179
	set_single_sysctl("net.inet.ip.fastforwarding", "0");
180

    
181
	/* resolve all local, peer addresses and setup pings */
182
	$ipmap = array();
183
	$rgmap = array();
184
	$filterdns_list = array();
185
	$listeniflist = array();
186
	$aggressive_mode_psk = false;
187
	unset($iflist);
188
	$ifacesuse = array();
189
	if (is_array($a_phase1) && count($a_phase1)) {
190

    
191
		$ipsecpinghosts = "";
192
		/* step through each phase1 entry */
193
		foreach ($a_phase1 as $ph1ent) {
194
			if (isset($ph1ent['disabled'])) {
195
				continue;
196
			}
197

    
198
			if (strpos($ph1ent['interface'], '_vip')) {
199
				$vpninterface = explode('_vip', $ph1ent['interface']);
200
				$ifacesuse[] = get_real_interface($vpninterface[0]);
201
			} else {
202
				$vpninterface = get_failover_interface($ph1ent['interface']);
203
				if (strpos($vpninterface, '_vip')) {
204
					$vpninterface = explode('_vip', $vpninterface);
205
					$ifacesuse[] = get_real_interface($vpninterface[0]);
206
				} elseif (!empty($vpninterface)) {
207
					$ifacesuse[] = $vpninterface;
208
				}
209
			}
210

    
211
			if ($ph1ent['mode'] == "aggressive" && ($ph1ent['authentication_method'] == "pre_shared_key" || $ph1ent['authentication_method'] == "xauth_psk_server")) {
212
				$aggressive_mode_psk = true;
213
			}
214

    
215
			$ikeid = $ph1ent['ikeid'];
216
			$listeniflist = get_real_interface($a_phase1['interface']);
217

    
218
			$ep = ipsec_get_phase1_src($ph1ent);
219
			if (!is_ipaddr($ep)) {
220
				log_error("IPsec ERROR: Could not find phase 1 source for connection {$ph1ent['descr']}. Omitting from configuration file.");
221
				continue;
222
			}
223

    
224
			if (!in_array($ep,$ipmap)) {
225
				$ipmap[] = $ep;
226
			}
227

    
228
			/* see if this tunnel has a hostname for the remote-gateway. If so,
229
			   try to resolve it now and add it to the list for filterdns */
230

    
231
			if (isset ($ph1ent['mobile'])) {
232
				continue;
233
			}
234

    
235
			$rg = $ph1ent['remote-gateway'];
236

    
237
			if (!is_ipaddr($rg)) {
238
				$filterdns_list[] = "{$rg}";
239
				add_hostname_to_watch($rg);
240
				if (!platform_booting()) {
241
					$rg = resolve_retry($rg);
242
				}
243
				if (!is_ipaddr($rg)) {
244
					continue;
245
				}
246
			}
247
			if (array_search($rg, $rgmap)) {
248
				log_error("The remote gateway {$rg} already exists on another phase 1 entry");
249
				continue;
250
			}
251
			$rgmap[$ph1ent['remote-gateway']] = $rg;
252

    
253
			if (is_array($a_phase2)) {
254
				/* step through each phase2 entry */
255
				foreach ($a_phase2 as $ph2ent) {
256
					if (isset($ph2ent['disabled'])) {
257
						continue;
258
					}
259

    
260
					if ($ikeid != $ph2ent['ikeid']) {
261
						continue;
262
					}
263

    
264
					/* add an ipsec pinghosts entry */
265
					if ($ph2ent['pinghost']) {
266
						if (!is_array($iflist)) {
267
							$iflist = get_configured_interface_list();
268
						}
269
						$srcip = null;
270
						$local_subnet = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
271
						if (is_ipaddrv6($ph2ent['pinghost'])) {
272
							foreach ($iflist as $ifent => $ifname) {
273
								$interface_ip = get_interface_ipv6($ifent);
274
								if (!is_ipaddrv6($interface_ip)) {
275
									continue;
276
								}
277
								if (ip_in_subnet($interface_ip, $local_subnet)) {
278
									$srcip = $interface_ip;
279
									break;
280
								}
281
							}
282
						} else {
283
							foreach ($iflist as $ifent => $ifname) {
284
								$interface_ip = get_interface_ip($ifent);
285
								if (!is_ipaddrv4($interface_ip)) {
286
									continue;
287
								}
288
								if ($local_subnet == "0.0.0.0/0" || ip_in_subnet($interface_ip, $local_subnet)) {
289
									$srcip = $interface_ip;
290
									break;
291
								}
292
							}
293
						}
294
						/* if no valid src IP was found in configured interfaces, try the vips */
295
						if (is_null($srcip)) {
296
							$viplist = get_configured_vips_list();
297
							foreach ($viplist as $vip) {
298
								if (ip_in_subnet($vip['ipaddr'], $local_subnet)) {
299
									$srcip = $vip['ipaddr'];
300
									break;
301
								}
302
							}
303
						}
304
						$dstip = $ph2ent['pinghost'];
305
						if (is_ipaddrv6($dstip)) {
306
							$family = "inet6";
307
						} else {
308
							$family = "inet";
309
						}
310
						if (is_ipaddr($srcip)) {
311
							$ipsecpinghosts[] = "{$srcip}|{$dstip}|3|||||{$family}|\n";
312
						}
313
					}
314
				}
315
			}
316
		}
317
		@file_put_contents("{$g['vardb_path']}/ipsecpinghosts", $ipsecpinghosts);
318
		unset($ipsecpinghosts);
319
	}
320
	unset($iflist);
321

    
322
	$accept_unencrypted = "";
323
	if (isset($config['ipsec']['acceptunencryptedmainmode'])) {
324
		$accept_unencrypted = "accept_unencrypted_mainmode_messages = yes";
325
	}
326

    
327
	$stronconf = '';
328
	if (file_exists("{$g['varetc_path']}/ipsec/strongswan.conf")) {
329
		$stronconf = file_get_contents("{$g['varetc_path']}/ipsec/strongswan.conf");
330
	}
331

    
332
	$i_dont_care_about_security_and_use_aggressive_mode_psk = "";
333
	if ($aggressive_mode_psk) {
334
		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.");
335
		if (!empty($stronconf) && strpos($stronconf, 'i_dont_care_about_security_and_use_aggressive_mode_psk') === FALSE) {
336
			$restart = true;
337
		}
338
		$i_dont_care_about_security_and_use_aggressive_mode_psk = "i_dont_care_about_security_and_use_aggressive_mode_psk=yes";
339
	}
340

    
341
	$unity_enabled = 'yes';
342
	if (isset($config['ipsec']['unityplugin'])) {
343
		$unity_enabled = 'no';
344
		if (file_exists("/usr/local/lib/ipsec/plugins/libstrongswan-unity.so")) {
345
			conf_mount_rw();
346
			mwexec("mv /usr/local/lib/ipsec/plugins/libstrongswan-unity.so /usr/local/lib/ipsec/plugins/libstrongswan-unity.MOVED");
347
			conf_mount_ro();
348
		}
349
	} else if (file_exists("/usr/local/lib/ipsec/plugins/libstrongswan-unity.MOVED")) {
350
		conf_mount_rw();
351
		mwexec("mv /usr/local/lib/ipsec/plugins/libstrongswan-unity.MOVED /usr/local/lib/ipsec/plugins/libstrongswan-unity.so");
352
		conf_mount_ro();
353
	}
354

    
355
	if (isset($config['ipsec']['enableinterfacesuse'])) {
356
		if (!empty($ifacesuse)) {
357
			$ifacesuse = 'interfaces_use = ' . implode(',', array_unique($ifacesuse));
358
		} else {
359
			$ifacesuse = '';
360
		}
361
	} else {
362
		$ifacesuse = '';
363
	}
364

    
365
	unset($stronconf);
366

    
367
	$strongswan = <<<EOD
368

    
369
# Automatically generated config file - DO NOT MODIFY. Changes will be overwritten.
370
starter {
371
load_warning = no
372
}
373

    
374
charon {
375
# number of worker threads in charon
376
threads = 16
377
ikesa_table_size = 32
378
ikesa_table_segments = 4
379
init_limit_half_open = 1000
380
install_routes = no
381
{$i_dont_care_about_security_and_use_aggressive_mode_psk}
382
{$accept_unencrypted}
383
cisco_unity = {$unity_enabled}
384
{$ifacesuse}
385

    
386
# And two loggers using syslog. The subsections define the facility to log
387
# to, currently one of: daemon, auth.
388
syslog {
389
	identifier = charon
390
	# default level to the LOG_DAEMON facility
391
	daemon {
392
		ike_name = yes
393
	}
394
	# very minimalistic IKE auditing logs to LOG_AUTHPRIV
395
	auth {
396
		default = -1
397
		ike = 1
398
		ike_name = yes
399
	}
400
}
401

    
402
EOD;
403

    
404
	$strongswan .= "\tplugins {\n";
405

    
406
	if (is_array($a_client) && isset($a_client['enable'])) {
407
		$strongswan .= "\t\tattr {\n";
408
		if ($a_client['pool_address'] && $a_client['pool_netbits']) {
409
			$strongswan .= "\t\t\tsubnet = {$a_client['pool_address']}/{$a_client['pool_netbits']}\n";
410
		}
411

    
412
		$cfgservers = array();
413
		if (!empty($a_client['dns_server1'])) {
414
			$cfgservers[] = $a_client['dns_server1'];
415
		}
416
		if (!empty($a_client['dns_server2'])) {
417
			$cfgservers[] = $a_client['dns_server2'];
418
		}
419
		if (!empty($a_client['dns_server3'])) {
420
			$cfgservers[] = $a_client['dns_server3'];
421
		}
422
		if (!empty($a_client['dns_server4'])) {
423
			$cfgservers[] = $a_client['dns_server4'];
424
		}
425

    
426
		if (!empty($cfgservers)) {
427
			$strongswan .= "\t\t\tdns = " . implode(",", $cfgservers) . "\n";
428
		}
429
		unset($cfgservers);
430
		$cfgservers = array();
431
		if (!empty($a_client['wins_server1'])) {
432
			$cfgservers[] = $a_client['wins_server1'];
433
		}
434
		if (!empty($a_client['wins_server2'])) {
435
			$cfgservers[] = $a_client['wins_server2'];
436
		}
437
		if (!empty($cfgservers)) {
438
			$strongswan .= "\t\t\tnbns = " . implode(",", $cfgservers) . "\n";
439
		}
440
		unset($cfgservers);
441

    
442
		if (isset($a_client['net_list']) && is_array($a_phase2)) {
443
			$net_list = '';
444
			foreach ($a_phase2 as $ph2ent) {
445
				if (isset($ph2ent['disabled'])) {
446
					continue;
447
				}
448

    
449
				if (!isset($ph2ent['mobile'])) {
450
					continue;
451
				}
452

    
453
				$localid = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
454

    
455
				if (!empty($net_list)) {
456
					$net_list .= ",";
457
				}
458
				$net_list .= $localid;
459
			}
460

    
461
			if (!empty($net_list)) {
462
				$strongswan .= "\t\t\tsplit-include = {$net_list}\n";
463
				unset($net_list);
464
			}
465
		}
466

    
467
		if (!empty($a_client['dns_domain'])) {
468
			$strongswan .= "\t\t\t# Search domain and default domain\n";
469
			$strongswan .= "\t\t\t28674 = \"{$a_client['dns_domain']}\"\n";
470
			if (empty($a_client['dns_split'])) {
471
				$strongswan .= "\t\t\t28675 = \"{$a_client['dns_domain']}\"";
472
			}
473
			$strongswan .= "\n";
474
		}
475

    
476
		if (!empty($a_client['dns_split'])) {
477
			$strongswan .= "\t\t\t28675 = {$a_client['dns_split']}\n";
478
		}
479

    
480
		if (!empty($a_client['login_banner'])) {
481
			$strongswan .= "\t\t\t28672 = \"{$a_client['login_banner']}\"\n";
482
		}
483

    
484
		if (isset($a_client['save_passwd'])) {
485
			$strongswan .= "\t\t\t28673 = 1\n";
486
		}
487

    
488
		if ($a_client['pfs_group']) {
489
			$strongswan .= "\t\t\t28679 = \"{$a_client['pfs_group']}\"\n";
490
		}
491
		$strongswan .= "\t\t}\n";
492

    
493
		if ($a_client['user_source'] != "none") {
494
			$strongswan .= "\t\txauth-generic {\n";
495
			$strongswan .= "\t\t\tscript = /etc/inc/ipsec.auth-user.php\n";
496
			$strongswan .= "\t\t\tauthcfg = ";
497
			$firstsed = 0;
498
			$authcfgs = explode(",", $a_client['user_source']);
499
			foreach ($authcfgs as $authcfg) {
500
				if ($firstsed > 0) {
501
					$strongswan .= ",";
502
				}
503
				if ($authcfg == "system") {
504
					$authcfg = "Local Database";
505
				}
506
				$strongswan .= $authcfg;
507
				$firstsed = 1;
508
			}
509
			$strongswan .= "\n";
510
			$strongswan .= "\t\t}\n";
511
		}
512
	}
513

    
514
	$strongswan .= "\t}\n}\n";
515
	@file_put_contents("{$g['varetc_path']}/ipsec/strongswan.conf", $strongswan);
516
	unset($strongswan);
517

    
518
	/* generate CA certificates files */
519
	if (is_array($config['ca']) && count($config['ca'])) {
520
		foreach ($config['ca'] as $ca) {
521
			if (!isset($ca['crt'])) {
522
				log_error(sprintf(gettext("Error: Invalid certificate info for %s"), $ca['descr']));
523
				continue;
524
			}
525
			$cert = base64_decode($ca['crt']);
526
			$x509cert = openssl_x509_parse(openssl_x509_read($cert));
527
			if (!is_array($x509cert) || !isset($x509cert['hash'])) {
528
				log_error(sprintf(gettext("Error: Invalid certificate hash info for %s"), $ca['descr']));
529
				continue;
530
			}
531
			$fname = "{$capath}/{$x509cert['hash']}.0.crt";
532
			if (!@file_put_contents($fname, $cert)) {
533
				log_error(sprintf(gettext("Error: Cannot write IPsec CA file for %s"), $ca['descr']));
534
				continue;
535
			}
536
			unset($cert);
537
		}
538
	}
539

    
540
	$pskconf = "";
541

    
542
	if (is_array($a_phase1) && count($a_phase1)) {
543
		foreach ($a_phase1 as $ph1ent) {
544

    
545
			if (isset($ph1ent['disabled'])) {
546
				continue;
547
			}
548

    
549
			if (strstr($ph1ent['authentication_method'], 'rsa') ||
550
			    in_array($ph1ent['authentication_method'], array('eap-mschapv2', 'eap-tls'))) {
551
				$certline = '';
552

    
553
				$ikeid = $ph1ent['ikeid'];
554
				$cert = lookup_cert($ph1ent['certref']);
555

    
556
				if (!$cert) {
557
					log_error(sprintf(gettext("Error: Invalid phase1 certificate reference for %s"), $ph1ent['name']));
558
					continue;
559
				}
560

    
561
				@chmod($certpath, 0600);
562

    
563
				$ph1keyfile = "{$keypath}/cert-{$ikeid}.key";
564
				if (!file_put_contents($ph1keyfile, base64_decode($cert['prv']))) {
565
					log_error(sprintf(gettext("Error: Cannot write phase1 key file for %s"), $ph1ent['name']));
566
					continue;
567
				}
568
				@chmod($ph1keyfile, 0600);
569

    
570
				$ph1certfile = "{$certpath}/cert-{$ikeid}.crt";
571
				if (!file_put_contents($ph1certfile, base64_decode($cert['crt']))) {
572
					log_error(sprintf(gettext("Error: Cannot write phase1 certificate file for %s"), $ph1ent['name']));
573
					@unlink($ph1keyfile);
574
					continue;
575
				}
576
				@chmod($ph1certfile, 0600);
577

    
578
				/* XXX" Traffic selectors? */
579
				$pskconf .= " : RSA {$ph1keyfile}\n";
580
			} else {
581
				list ($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local');
582
				list ($peerid_type, $peerid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap);
583

    
584
				if (empty($peerid_data)) {
585
					continue;
586
				}
587

    
588
				$myid = isset($ph1ent['mobile']) ? trim($myid_data) : "%any";
589
				$peerid = ($peerid_data != 'allusers') ? trim($peerid_data) : '';
590
				if (!empty($ph1ent['pre-shared-key'])) {
591
					if ($myid_type == 'fqdn' && !empty($myid_data)) {
592
						$pskconf .= "@{$myid} {$peerid} : PSK 0s" . base64_encode(trim($ph1ent['pre-shared-key'])) . "\n";
593
					} else {
594
						$pskconf .= "{$myid} {$peerid} : PSK 0s" . base64_encode(trim($ph1ent['pre-shared-key'])) . "\n";
595
					}
596
				}
597
			}
598
		}
599
	}
600

    
601
	/* Add user PSKs */
602
	if (is_array($config['system']) && is_array($config['system']['user'])) {
603
		foreach ($config['system']['user'] as $user) {
604
			if (!empty($user['ipsecpsk'])) {
605
				$pskconf .= "%any {$user['name']} : PSK 0s" . base64_encode($user['ipsecpsk']) . "\n";
606
			}
607
		}
608
		unset($user);
609
	}
610

    
611
	/* add PSKs for mobile clients */
612
	if (is_array($ipseccfg['mobilekey'])) {
613
		foreach ($ipseccfg['mobilekey'] as $key) {
614
			if ($key['ident'] == "allusers") {
615
				$key['ident'] = '%any';
616
			}
617
			if (empty($key['type'])) {
618
				$key['type'] = 'PSK';
619
			}
620
			$pskconf .= "%any {$key['ident']} : {$key['type']} 0s" . base64_encode($key['pre-shared-key']) . "\n";
621
		}
622
		unset($key);
623
	}
624

    
625
	@file_put_contents("{$g['varetc_path']}/ipsec/ipsec.secrets", $pskconf);
626
	chmod("{$g['varetc_path']}/ipsec/ipsec.secrets", 0600);
627
	unset($pskconf);
628

    
629
	$uniqueids = 'yes';
630
	if (!empty($config['ipsec']['uniqueids'])) {
631
		if (array_key_exists($config['ipsec']['uniqueids'], $ipsec_idhandling))
632
			$uniqueids = $config['ipsec']['uniqueids'];
633
	}
634
	$natfilterrules = false;
635
	/* begin ipsec.conf */
636
	$ipsecconf = "";
637
	$enablecompression = false;
638
	if (is_array($a_phase1) && count($a_phase1))  {
639

    
640
		$ipsecconf .= "# This file is automatically generated. Do not edit\n";
641
		$ipsecconf .= "config setup\n\tuniqueids = {$uniqueids}\n";
642
		$ipsecconf .= "\tcharondebug=\"" . vpn_ipsec_configure_loglevels(true) . "\"\n";
643

    
644
		if (!isset($config['ipsec']['noshuntlaninterfaces'])) {
645
			if ($config['interfaces']['lan']) {
646
				$lanip = get_interface_ip("lan");
647
				if (!empty($lanip) && is_ipaddrv4($lanip)) {
648
					$lansn = get_interface_subnet("lan");
649
					$lansa = gen_subnet($lanip, $lansn);
650
					$ipsecconf .= <<<EOD
651

    
652
conn bypasslan
653
	leftsubnet = {$lanip}/32
654
	rightsubnet = {$lansa}/{$lansn}
655
	authby = never
656
	type = passthrough
657
	auto = route
658

    
659
EOD;
660
				}
661
			}
662
		}
663

    
664
		foreach ($a_phase1 as $ph1ent) {
665
			if (isset($ph1ent['disabled'])) {
666
				continue;
667
			}
668

    
669
			if ($ph1ent['mode'] == "aggressive") {
670
				$aggressive = "yes";
671
			} else {
672
				$aggressive = "no";
673
			}
674

    
675
			$ep = ipsec_get_phase1_src($ph1ent);
676
			if (!$ep) {
677
				continue;
678
			}
679

    
680
			$ikeid = $ph1ent['ikeid'];
681
			$keyexchange = "ikev1";
682
			$passive = "route";
683
			if (!empty($ph1ent['iketype'])) {
684
				if ($ph1ent['iketype'] == "ikev2") {
685
					$keyexchange = "ikev2";
686
					//$passive = "start";
687
				} else if ($ph1ent['iketype'] == "auto") {
688
					$keyexchange = "ike";
689
				}
690
			}
691

    
692
			if (isset($ph1ent['mobile'])) {
693
				$right_spec = "%any";
694
				$passive = 'add';
695
			} else {
696
				if (isset($ph1ent['responderonly'])) {
697
					$passive = 'add';
698
				}
699

    
700
				$right_spec = $ph1ent['remote-gateway'];
701
				if (is_ipaddr($right_spec)) {
702
					$sourcehost = $right_spec;
703
				} else {
704
					$sourcehost = $rgmap['remote-gateway'];
705
				}
706

    
707
				if ($ph1ent['protocol'] == 'inet') {
708
					if (strpos($ph1ent['interface'], '_vip')) {
709
						$vpninterface = explode('_vip', $ph1ent['interface']);
710
						$ifacesuse = get_real_interface($vpninterface[0]);
711
						$vpninterface = $vpninterface[0];
712
					} else {
713
						$ifacesuse = get_failover_interface($ph1ent['interface']);
714
						if (strpos($ifacesuse, '_vip')) {
715
							$vpninterface = explode('_vip', $ifacesuse);
716
							$ifacesuse = get_real_interface($vpninterface[0]);
717
							$vpninterface = $vpninterface[0];
718
						} else {
719
							$vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse);
720
						}
721
					}
722

    
723
					if (!empty($ifacesuse) && interface_has_gateway($vpninterface)) {
724
						$gatewayip = get_interface_gateway($vpninterface);
725
						$interfaceip = get_interface_ip($vpninterface);
726
						$subnet_bits = get_interface_subnet($vpninterface);
727
						$subnet_ip = gen_subnetv4($interfaceip, $subnet_bits);
728
						/* if the remote gateway is in the local subnet, then don't add a route */
729
						if (!ip_in_subnet($sourcehost, "{$subnet_ip}/{$subnet_bits}")) {
730
							if (is_ipaddrv4($gatewayip)) {
731
								// log_error("IPSEC interface is not WAN but {$ifacesuse}, adding static route for VPN endpoint {$rgip} via {$gatewayip}");
732
								mwexec("/sbin/route change -host {$sourcehost} {$gatewayip}", true);
733
							}
734
						}
735
					}
736
				} else if ($ph1ent['protocol'] == 'inet6') {
737
					if (strpos($ph1ent['interface'], '_vip')) {
738
						$vpninterface = explode('_vip', $ph1ent['interface']);
739
						$ifacesuse = get_real_interface($vpninterface[0]);
740
						$vpninterface = $vpninterface[0];
741
					} else {
742
						$ifacesuse = get_failover_interface($ph1ent['interface']);
743
						if (strpos($ifacesuse, '_vip')) {
744
							$vpninterface = explode('_vip', $ifacesuse);
745
							$ifacesuse = get_real_interface($vpninterface[0]);
746
							$vpninterface = $vpninterface[0];
747
						} else {
748
							$vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse);
749
						}
750
					}
751

    
752
					if (!empty($ifacesuse) && interface_has_gateway($vpninterface)) {
753
						$gatewayip = get_interface_gateway_v6($vpninterface);
754
						$interfaceip = get_interface_ipv6($vpninterface);
755
						$subnet_bits = get_interface_subnetv6($vpninterface);
756
						$subnet_ip = gen_subnetv6($interfaceip, $subnet_bits);
757
						/* if the remote gateway is in the local subnet, then don't add a route */
758
						if (!ip_in_subnet($sourcehost, "{$subnet_ip}/{$subnet_bits}")) {
759
							if (is_ipaddrv6($gatewayip)) {
760
								// log_error("IPSEC interface is not WAN but {$ifacesuse}, adding static route for VPN endpoint {$rgip} via {$gatewayip}");
761
								mwexec("/sbin/route change -inet6 -host {$sourcehost} {$gatewayip}", true);
762
							}
763
						}
764
					}
765
				}
766
			}
767

    
768
			list ($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local');
769
			if ($myid_type != 'address') {
770
				$myid_data = "{$myid_type}:{$myid_data}";
771
			}
772

    
773
			/* Only specify peer ID if we are not dealing with a mobile PSK-only tunnel */
774
			$peerid_spec = '';
775
			if (!isset($ph1ent['mobile'])) {
776
				list ($peerid_type, $peerid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap);
777
				if ($peerid_type != 'address') {
778
					$peerid_spec = "{$peerid_type}:{$peerid_data}";
779
				} else {
780
					$peerid_spec = $peerid_data;
781
				}
782
			}
783

    
784
			if (is_array($ph1ent['encryption-algorithm']) && !empty($ph1ent['encryption-algorithm']['name']) && !empty($ph1ent['hash-algorithm'])) {
785
				$ealgosp1 = '';
786
				$ealg_id = $ph1ent['encryption-algorithm']['name'];
787
				$ealg_kl = $ph1ent['encryption-algorithm']['keylen'];
788
				if ($ealg_kl) {
789
					$ealgosp1 = "ike = {$ealg_id}{$ealg_kl}-{$ph1ent['hash-algorithm']}";
790
				} else {
791
					$ealgosp1 = "ike = {$ealg_id}-{$ph1ent['hash-algorithm']}";
792
				}
793

    
794
				$modp = vpn_ipsec_convert_to_modp($ph1ent['dhgroup']);
795
				if (!empty($modp)) {
796
					$ealgosp1 .= "-{$modp}";
797
				}
798

    
799
				$ealgosp1 .= "!";
800
			}
801

    
802
			if ($ph1ent['dpd_delay'] && $ph1ent['dpd_maxfail']) {
803
				if ($passive == "route") {
804
					$dpdline = "dpdaction = restart";
805
				} else {
806
					$dpdline = "dpdaction = clear";
807
				}
808
				$dpdline .= "\n\tdpddelay = {$ph1ent['dpd_delay']}s";
809
				$dpdtimeout = $ph1ent['dpd_delay'] * ($ph1ent['dpd_maxfail'] + 1);
810
				$dpdline .= "\n\tdpdtimeout = {$dpdtimeout}s";
811
			} else {
812
				$dpdline = "dpdaction = none";
813
			}
814

    
815
			$ikelifeline = '';
816
			if ($ph1ent['lifetime']) {
817
				$ikelifeline = "ikelifetime = {$ph1ent['lifetime']}s";
818
			}
819

    
820
			$rightsourceip = NULL;
821
			if (isset($ph1ent['mobile']) && !empty($a_client['pool_address'])) {
822
				$rightsourceip = "\trightsourceip = {$a_client['pool_address']}/{$a_client['pool_netbits']}\n";
823
			}
824

    
825
			$authentication = "";
826
			switch ($ph1ent['authentication_method']) {
827
				case 'eap-mschapv2':
828
					if (isset($ph1ent['mobile'])) {
829
						$authentication = "eap_identity=%any\n\t";
830
						$authentication .= "leftauth=pubkey\n\trightauth=eap-mschapv2";
831
						if (!empty($ph1ent['certref'])) {
832
							$authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt";
833
						}
834
					}
835
					break;
836
				case 'eap-tls':
837
					if (isset($ph1ent['mobile'])) {
838
						$authentication = "eap_identity=%identity\n\t";
839
						$authentication .= "leftauth=pubkey\n\trightauth=eap-tls";
840
						if (!empty($ph1ent['certref'])) {
841
							$authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt";
842
						}
843
					} else {
844
						$authentication = "leftauth=eap-tls\n\trightauth=eap-tls";
845
						if (!empty($ph1ent['certref'])) {
846
							$authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt";
847
						}
848
					}
849
					break;
850
				case 'xauth_rsa_server':
851
					$authentication = "leftauth = pubkey\n\trightauth = pubkey";
852
					$authentication .= "\n\trightauth2 = xauth-generic";
853
					if (!empty($ph1ent['certref'])) {
854
						$authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt";
855
					}
856
					break;
857
				case 'xauth_psk_server':
858
					$authentication = "leftauth = psk\n\trightauth = psk";
859
					$authentication .= "\n\trightauth2 = xauth-generic";
860
					break;
861
				case 'pre_shared_key':
862
					$authentication = "leftauth = psk\n\trightauth = psk";
863
					break;
864
				case 'rsasig':
865
					$authentication = "leftauth = pubkey\n\trightauth = pubkey";
866
					if (!empty($ph1ent['certref'])) {
867
						$authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt";
868
					}
869
					break;
870
				case 'hybrid_rsa_server':
871
					$authentication = "leftauth = xauth-generic\n\trightauth = pubkey";
872
					$authentication .= "\n\trightauth2 = xauth";
873
					if (!empty($ph1ent['certref'])) {
874
						$authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt";
875
					}
876
					break;
877
			}
878

    
879
			$left_spec = $ep;
880

    
881
			if (isset($ph1ent['reauth_enable'])) {
882
				$reauth = "reauth = no";
883
			} else {
884
				$reauth = "reauth = yes";
885
			}
886
			if (isset($ph1ent['rekey_enable'])) {
887
				$rekey = "rekey = no";
888
			} else {
889
				$rekey = "rekey = yes";
890
			}
891

    
892
			if ($ph1ent['nat_traversal'] == 'off') {
893
				$forceencaps = 'forceencaps = no';
894
			} else if ($ph1ent['nat_traversal'] == 'force') {
895
				$forceencaps = 'forceencaps = yes';
896
			} else {
897
				$forceencaps = 'forceencaps = no';
898
			}
899

    
900
			if ($ph1ent['mobike'] == 'on') {
901
				$mobike = 'mobike = yes';
902
			} else {
903
				$mobike = 'mobike = no';
904
			}
905

    
906
			$ipseclifetime = 0;
907
			$rightsubnet_spec = array();
908
			$leftsubnet_spec = array();
909
			$reqids = array();
910
			$ealgoAHsp2arr = array();
911
			$ealgoESPsp2arr = array();
912
		if (is_array($a_phase2) && count($a_phase2)) {
913
			foreach ($a_phase2 as $ph2ent) {
914
				if ($ikeid != $ph2ent['ikeid']) {
915
					continue;
916
				}
917

    
918
				if (isset($ph2ent['disabled'])) {
919
					continue;
920
				}
921

    
922
				if (isset($ph2ent['mobile']) && !isset($a_client['enable'])) {
923
					continue;
924
				}
925

    
926
				if (($ph2ent['mode'] == 'tunnel') or ($ph2ent['mode'] == 'tunnel6')) {
927
					$tunneltype = "type = tunnel";
928

    
929
					$localid_type = $ph2ent['localid']['type'];
930
					$leftsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
931

    
932
					/* Do not print localid in some cases, such as a pure-psk or psk/xauth single phase2 mobile tunnel */
933
					if (($localid_type == "none" || $localid_type == "mobile") &&
934
					    isset($ph1ent['mobile']) && (ipsec_get_number_of_phase2($ikeid)==1)) {
935
						$left_spec = '%any';
936
					} else {
937
						if ($localid_type != "address") {
938
							$localid_type = "subnet";
939
						}
940
						// Don't let an empty subnet into config, it can cause parse errors. Ticket #2201.
941
						if (!is_ipaddr($leftsubnet_data) && !is_subnet($leftsubnet_data) && ($leftsubnet_data != "0.0.0.0/0")) {
942
							log_error("Invalid IPsec Phase 2 \"{$ph2ent['descr']}\" - {$ph2ent['localid']['type']} has no subnet.");
943
							continue;
944
						}
945
						if (!empty($ph2ent['natlocalid'])) {
946
							$natleftsubnet_data =  ipsec_idinfo_to_cidr($ph2ent['natlocalid'], false, $ph2ent['mode']);
947
							if ($ph2ent['natlocalid']['type'] != "address") {
948
								if (is_subnet($natleftsubnet_data)) {
949
									$leftsubnet_data = "{$natleftsubnet_data}|{$leftsubnet_data}";
950
								}
951
							} else {
952
								if (is_ipaddr($natleftsubnet_data)) {
953
									$leftsubnet_data = "{$natleftsubnet_data}|{$leftsubnet_data}";
954
								}
955
							}
956
							$natfilterrules = true;
957
						}
958
					}
959

    
960
					$leftsubnet_spec[] = $leftsubnet_data;
961

    
962
					if (!isset($ph2ent['mobile'])) {
963
						$tmpsubnet = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
964
						$rightsubnet_spec[] = $tmpsubnet;
965
					} else if (!empty($a_client['pool_address'])) {
966
						$rightsubnet_spec[] = "{$a_client['pool_address']}/{$a_client['pool_netbits']}";
967
					}
968
				} else {
969
					$tunneltype = "type = transport";
970

    
971
					if ((($ph1ent['authentication_method'] == "xauth_psk_server") ||
972
					    ($ph1ent['authentication_method'] == "pre_shared_key")) && isset($ph1ent['mobile'])) {
973
						$left_spec = "%any";
974
					} else {
975
						$tmpsubnet = ipsec_get_phase1_src($ph1ent);
976
						$leftsubnet_spec[] = $tmpsubnet;
977
					}
978

    
979
					if (!isset($ph2ent['mobile'])) {
980
						$rightsubnet_spec[] = $right_spec;
981
					}
982
				}
983

    
984
				if (isset($a_client['pfs_group']) && isset($ph2ent['mobile'])) {
985
					$ph2ent['pfsgroup'] = $a_client['pfs_group'];
986
				}
987

    
988
				if ($ph2ent['protocol'] == 'esp') {
989
					if (is_array($ph2ent['encryption-algorithm-option'])) {
990
						foreach ($ph2ent['encryption-algorithm-option'] as $ealg) {
991
							$ealg_id = $ealg['name'];
992
							$ealg_kl = $ealg['keylen'];
993

    
994
							if (!empty($ealg_kl) && $ealg_kl == "auto") {
995
								if (empty($p2_ealgos) || !is_array($p2_ealgos)) {
996
									require("ipsec.inc");
997
								}
998
								$key_hi = $p2_ealgos[$ealg_id]['keysel']['hi'];
999
								$key_lo = $p2_ealgos[$ealg_id]['keysel']['lo'];
1000
								$key_step = $p2_ealgos[$ealg_id]['keysel']['step'];
1001
								/* XXX: in some cases where include ordering is suspect these variables
1002
								 * are somehow 0 and we enter this loop forever and timeout after 900
1003
								 * seconds wrecking bootup */
1004
								if ($key_hi != 0 and $key_lo !=0 and $key_step !=0) {
1005
									for ($keylen = $key_hi; $keylen >= $key_lo; $keylen -= $key_step) {
1006
										if (!empty($ph2ent['hash-algorithm-option']) && is_array($ph2ent['hash-algorithm-option'])) {
1007
											foreach ($ph2ent['hash-algorithm-option'] as $halgo) {
1008
												$halgo = str_replace('hmac_', '', $halgo);
1009
												$tmpealgo = "{$ealg_id}{$keylen}-{$halgo}";
1010
												$modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']);
1011
												if (!empty($modp)) {
1012
													$tmpealgo .= "-{$modp}";
1013
												}
1014
												$ealgoESPsp2arr[] = $tmpealgo;
1015
											}
1016
										} else {
1017
											$tmpealgo = "{$ealg_id}{$keylen}";
1018
											$modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']);
1019
											if (!empty($modp)) {
1020
												$tmpealgo .= "-{$modp}";
1021
											}
1022
											$ealgoESPsp2arr[] = $tmpealgo;
1023
										}
1024
									}
1025
								}
1026
							} else {
1027
								if (!empty($ph2ent['hash-algorithm-option']) && is_array($ph2ent['hash-algorithm-option'])) {
1028
									foreach ($ph2ent['hash-algorithm-option'] as $halgo) {
1029
										$halgo = str_replace('hmac_', '', $halgo);
1030
										$tmpealgo = "{$ealg_id}{$ealg_kl}-{$halgo}";
1031
										$modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']);
1032
										if (!empty($modp)) {
1033
											$tmpealgo .= "-{$modp}";
1034
										}
1035
										$ealgoESPsp2arr[] = $tmpealgo;
1036
									}
1037
								} else {
1038
									$tmpealgo = "{$ealg_id}{$ealg_kl}";
1039
									$modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']);
1040
									if (!empty($modp)) {
1041
										$tmpealgo .= "-{$modp}";
1042
									}
1043
									$ealgoESPsp2arr[] = $tmpealgo;
1044
								}
1045
							}
1046
						}
1047
					}
1048
				} else if ($ph2ent['protocol'] == 'ah') {
1049
					if (!empty($ph2ent['hash-algorithm-option']) && is_array($ph2ent['hash-algorithm-option'])) {
1050
						$modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']);
1051
						foreach ($ph2ent['hash-algorithm-option'] as $tmpAHalgo) {
1052
							$tmpAHalgo = str_replace('hmac_', '', $tmpAHalgo);
1053
							if (!empty($modp)) {
1054
								$tmpAHalgo = "-{$modp}";
1055
							}
1056
							$ealgoAHsp2arr[] = $tmpAHalgo;
1057
						}
1058
					}
1059
				}
1060

    
1061
				$reqids[] = $ph2ent['reqid'];
1062

    
1063
				if (!empty($ph2ent['lifetime'])) {
1064
					if ($ipseclifetime == 0 || intval($ipseclifetime) > intval($ph2ent['lifetime'])) {
1065
						$ipseclifetime = intval($ph2ent['lifetime']);
1066
					}
1067
				}
1068

    
1069
			}
1070
		}
1071

    
1072
			$ipsecconnect =<<<EOD
1073
	fragmentation = yes
1074
	keyexchange = {$keyexchange}
1075
	{$reauth}
1076
	{$forceencaps}
1077
	{$mobike}
1078
	{$rekey}
1079
	installpolicy = yes
1080
	{$tunneltype}
1081
	{$dpdline}
1082
	auto = {$passive}
1083
	left = {$left_spec}
1084
	right = {$right_spec}
1085
	leftid = {$myid_data}
1086

    
1087
EOD;
1088

    
1089
			if (isset($config['ipsec']['compression'])) {
1090
				$ipsecconnect .= "\tcompress = yes\n";
1091
				$enablecompression = true;
1092
			}
1093
			if (!empty($ikelifeline)) {
1094
				$ipsecconnect .= "\t{$ikelifeline}\n";
1095
			}
1096
			if ($ipseclifetime > 0) {
1097
				$ipsecconnect .= "\tlifetime = {$ipseclifetime}s\n";
1098
			}
1099
			if (!empty($rightsourceip)) {
1100
				$ipsecconnect .= "{$rightsourceip}";
1101
			}
1102
			if (!empty($ealgosp1)) {
1103
				$ipsecconnect .= "\t{$ealgosp1}\n";
1104
			}
1105
			if (!empty($ealgoAHsp2arr)) {
1106
				$ipsecconnect .= "\tah = " . join(',', $ealgoAHsp2arr) . "!\n";
1107
			}
1108
			if (!empty($ealgoESPsp2arr)) {
1109
				$ipsecconnect .= "\tesp = " . join(',', $ealgoESPsp2arr) . "!\n";
1110
			}
1111
			if (!empty($authentication)) {
1112
				$ipsecconnect .= "\t{$authentication}\n";
1113
			}
1114
			if (!empty($peerid_spec)) {
1115
				$ipsecconnect .= "\trightid = {$peerid_spec}\n";
1116
			}
1117
			if ($keyexchange == 'ikev1') {
1118
				$ipsecconnect .= "\taggressive = {$aggressive}\n";
1119
			}
1120

    
1121
			if (!isset($ph1ent['mobile']) && $keyexchange == 'ikev1') {
1122
				if (!empty($rightsubnet_spec)) {
1123
					$ipsecfin = '';
1124
					foreach ($rightsubnet_spec as $idx => $rsubnet) {
1125
						$ipsecfin .= "\nconn con{$ph1ent['ikeid']}00{$idx}\n";
1126
						if (!empty($reqids[$idx])) {
1127
							$ipsecfin .= "\treqid = " . $reqids[$idx] . "\n";
1128
						}
1129
						$ipsecfin .= $ipsecconnect;
1130
						$ipsecfin .= "\trightsubnet = {$rsubnet}\n";
1131
						$ipsecfin .= "\tleftsubnet = " . $leftsubnet_spec[$idx] . "\n";
1132
					}
1133
				} else {
1134
					log_error("No phase2 specifications for tunnel with REQID = {$ikeid}");
1135
				}
1136
			} else {
1137
				$ipsecfin = "\nconn con{$ph1ent['ikeid']}\n";
1138
				if (!empty($reqids[$idx])) {
1139
					$ipsecfin .= "\treqid = " . $reqids[0] . "\n";
1140
				}
1141
				$ipsecfin .= $ipsecconnect;
1142
				if (!isset($ph1ent['mobile']) && !empty($rightsubnet_spec)) {
1143
					$tempsubnets = array();
1144
					foreach ($rightsubnet_spec as $rightsubnet) {
1145
						$tempsubnets[$rightsubnet] = $rightsubnet;
1146
					}
1147
					$ipsecfin .= "\trightsubnet = " . join(",", $tempsubnets) . "\n";
1148
					unset($tempsubnets, $rightsubnet);
1149
				}
1150
				if (!empty($leftsubnet_spec)) {
1151
					$tempsubnets = array();
1152
					foreach ($leftsubnet_spec as $leftsubnet) {
1153
						$tempsubnets[$leftsubnet] = $leftsubnet;
1154
					}
1155
					$ipsecfin .= "\tleftsubnet = " . join(",", $leftsubnet_spec) . "\n";
1156
					unset($tempsubnets, $leftsubnet);
1157
				}
1158
			}
1159
			$ipsecconf .= $ipsecfin;
1160
			unset($ipsecfin);
1161
		}
1162
	}
1163

    
1164
	@file_put_contents("{$g['varetc_path']}/ipsec/ipsec.conf", $ipsecconf);
1165
	unset($ipsecconf);
1166
	/* end ipsec.conf */
1167

    
1168
	if ($enablecompression === true) {
1169
		set_single_sysctl('net.inet.ipcomp.ipcomp_enable', 1);
1170
	} else {
1171
		set_single_sysctl('net.inet.ipcomp.ipcomp_enable', 0);
1172
	}
1173

    
1174
	/* manage process */
1175
	if ($restart === true) {
1176
		mwexec("/usr/local/sbin/ipsec restart", false);
1177
	} else {
1178
		if (isvalidpid("{$g['varrun_path']}/charon.pid")) {
1179
			/* Read secrets */
1180
			mwexec("/usr/local/sbin/ipsec rereadall", false);
1181
			/* Update configuration changes */
1182
			mwexec("/usr/local/sbin/ipsec update", false);
1183
		} else {
1184
			mwexec("/usr/local/sbin/ipsec start", false);
1185
		}
1186
	}
1187

    
1188
	if ($natfilterrules == true) {
1189
		filter_configure();
1190
	}
1191
	/* start filterdns, if necessary */
1192
	if (count($filterdns_list) > 0) {
1193
		$interval = 60;
1194
		if (!empty($ipseccfg['dns-interval']) && is_numeric($ipseccfg['dns-interval'])) {
1195
			$interval = $ipseccfg['dns-interval'];
1196
		}
1197

    
1198
		$hostnames = "";
1199
		array_unique($filterdns_list);
1200
		foreach ($filterdns_list as $hostname) {
1201
			$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload ipsecdns\"'\n";
1202
		}
1203
		file_put_contents("{$g['varetc_path']}/ipsec/filterdns-ipsec.hosts", $hostnames);
1204
		unset($hostnames);
1205

    
1206
		if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid")) {
1207
			sigkillbypid("{$g['varrun_path']}/filterdns-ipsec.pid", "HUP");
1208
		} else {
1209
			mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-ipsec.pid -i {$interval} -c {$g['varetc_path']}/ipsec/filterdns-ipsec.hosts -d 1");
1210
		}
1211
	} else {
1212
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
1213
		@unlink("{$g['varrun_path']}/filterdns-ipsec.pid");
1214
	}
1215

    
1216
	if (platform_booting()) {
1217
		echo "done\n";
1218
	}
1219

    
1220
	return count($filterdns_list);
1221
}
1222

    
1223
/*
1224
 * Forcefully restart IPsec
1225
 * This is required for when dynamic interfaces reload
1226
 * For all other occasions the normal vpn_ipsec_configure()
1227
 * will gracefully reload the settings without restarting
1228
 */
1229
function vpn_ipsec_force_reload($interface = "") {
1230
	global $g, $config;
1231

    
1232
	$ipseccfg = $config['ipsec'];
1233

    
1234
	if (!empty($interface) && is_array($ipseccfg['phase1'])) {
1235
		$found = false;
1236
		foreach ($ipseccfg['phase1'] as $ipsec) {
1237
			if (!isset($ipsec['disabled']) && ($ipsec['interface'] == $interface)) {
1238
				$found = true;
1239
				break;
1240
			}
1241
		}
1242
		if (!$found) {
1243
			log_error(sprintf(gettext("Ignoring IPsec reload since there are no tunnels on interface %s"), $interface));
1244
			return;
1245
		}
1246
	}
1247

    
1248
	/* if ipsec is enabled, start up again */
1249
	if (isset($ipseccfg['enable'])) {
1250
		log_error(gettext("Forcefully reloading IPsec"));
1251
		vpn_ipsec_configure();
1252
	}
1253
}
1254

    
1255
/* master setup for vpn (mpd) */
1256
function vpn_setup() {
1257
	global $g;
1258

    
1259
	if ($g['platform'] == 'jail') {
1260
		return;
1261
	}
1262

    
1263
	/* start pptpd */
1264
	vpn_pptpd_configure();
1265

    
1266
	/* start pppoe server */
1267
	vpn_pppoes_configure();
1268

    
1269
	/* setup l2tp */
1270
	vpn_l2tp_configure();
1271
}
1272

    
1273
function vpn_netgraph_support() {
1274
	$iflist = get_configured_interface_list();
1275
	foreach ($iflist as $iface) {
1276
		$realif = get_real_interface($iface);
1277
		/* Get support for netgraph(4) from the nic */
1278
		$ifinfo = pfSense_get_interface_addresses($realif);
1279
		if (!empty($ifinfo) && in_array($ifinfo['iftype'], array("ether", "vlan", "bridge"))) {
1280
			pfSense_ngctl_attach(".", $realif);
1281
		}
1282
	}
1283
}
1284

    
1285
function vpn_pptpd_configure() {
1286
	global $config, $g;
1287

    
1288
	$syscfg = $config['system'];
1289
	$pptpdcfg = $config['pptpd'];
1290

    
1291
	if (platform_booting()) {
1292
		if (!$pptpdcfg['mode'] || ($pptpdcfg['mode'] == "off")) {
1293
			return 0;
1294
		}
1295

    
1296
		if (platform_booting(true)) {
1297
			echo gettext("Configuring PPTP VPN service... ");
1298
		}
1299
	} else {
1300
		/* kill mpd */
1301
		killbypid("{$g['varrun_path']}/pptp-vpn.pid");
1302

    
1303
		/* wait for process to die */
1304
		sleep(3);
1305

    
1306
		if (is_process_running("mpd -b")) {
1307
			killbypid("{$g['varrun_path']}/pptp-vpn.pid");
1308
			log_error(gettext("Could not kill mpd within 3 seconds.   Trying again."));
1309
		}
1310

    
1311
		/* remove mpd.conf, if it exists */
1312
		unlink_if_exists("{$g['varetc_path']}/pptp-vpn/mpd.conf");
1313
		unlink_if_exists("{$g['varetc_path']}/pptp-vpn/mpd.links");
1314
		unlink_if_exists("{$g['varetc_path']}/pptp-vpn/mpd.secret");
1315
	}
1316

    
1317
	if (empty($pptpdcfg['n_pptp_units'])) {
1318
		log_error("Something wrong in the PPTPd configuration. Preventing starting the daemon because issues would arise.");
1319
		return;
1320
	}
1321

    
1322
	/* make sure pptp-vpn directory exists */
1323
	if (!file_exists("{$g['varetc_path']}/pptp-vpn")) {
1324
		mkdir("{$g['varetc_path']}/pptp-vpn");
1325
	}
1326

    
1327
	switch ($pptpdcfg['mode']) {
1328
		case 'server':
1329
			/* write mpd.conf */
1330
			$fd = fopen("{$g['varetc_path']}/pptp-vpn/mpd.conf", "w");
1331
			if (!$fd) {
1332
				printf(gettext("Error: cannot open mpd.conf in vpn_pptpd_configure().") . "\n");
1333
				return 1;
1334
			}
1335

    
1336
			$mpdconf = <<<EOD
1337
pptps:
1338

    
1339
EOD;
1340

    
1341
			for ($i = 0; $i < $pptpdcfg['n_pptp_units']; $i++) {
1342
				$mpdconf .= "	load pt{$i}\n";
1343
			}
1344

    
1345
			for ($i = 0; $i < $pptpdcfg['n_pptp_units']; $i++) {
1346

    
1347
				$clientip = long2ip32(ip2long($pptpdcfg['remoteip']) + $i);
1348

    
1349
				$mpdconf .= <<<EOD
1350

    
1351
pt{$i}:
1352
	new -i pptpd{$i} pt{$i} pt{$i}
1353
	set ipcp ranges {$pptpdcfg['localip']}/32 {$clientip}/32
1354
	load pts
1355

    
1356
EOD;
1357
			}
1358

    
1359
			$mpdconf .=<<<EOD
1360

    
1361
pts:
1362
	set iface disable on-demand
1363
	set iface enable proxy-arp
1364
	set iface enable tcpmssfix
1365
	set iface idle 1800
1366
	set iface up-script /usr/local/sbin/vpn-linkup
1367
	set iface down-script /usr/local/sbin/vpn-linkdown
1368
	set bundle enable multilink
1369
	set bundle enable crypt-reqd
1370
	set link yes acfcomp protocomp
1371
	set link no pap chap
1372
	set link enable chap-msv2
1373
	set link mtu 1460
1374
	set link keep-alive 10 60
1375
	set ipcp yes vjcomp
1376
	set bundle enable compression
1377
	set ccp yes mppc
1378
	set ccp yes mpp-e128
1379
	set ccp yes mpp-stateless
1380

    
1381
EOD;
1382

    
1383
			if (!isset ($pptpdcfg['req128'])) {
1384
				$mpdconf .=<<<EOD
1385
	set ccp yes mpp-e40
1386
	set ccp yes mpp-e56
1387

    
1388
EOD;
1389
			}
1390

    
1391
			if  (isset($pptpdcfg["wins"]) && $pptpdcfg['wins'] != "") {
1392
				$mpdconf  .=  "	set ipcp nbns {$pptpdcfg['wins']}\n";
1393
			}
1394

    
1395
			if (!empty($pptpdcfg['dns1'])) {
1396
				$mpdconf .= "	set ipcp dns " . $pptpdcfg['dns1'];
1397
				if (!empty($pptpdcfg['dns2'])) {
1398
					$mpdconf .= " " . $pptpdcfg['dns2'];
1399
				}
1400
				$mpdconf .= "\n";
1401
			} elseif (isset ($config['dnsmasq']['enable'])) {
1402
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1403
				if ($syscfg['dnsserver'][0]) {
1404
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1405
				}
1406
				$mpdconf .= "\n";
1407
			} elseif (isset($config['unbound']['enable'])) {
1408
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1409
				if ($syscfg['dnsserver'][0]) {
1410
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1411
				}
1412
				$mpdconf .= "\n";
1413
			} elseif (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1414
					$mpdconf .= "	set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n";
1415
			}
1416

    
1417
			if (isset ($pptpdcfg['radius']['server']['enable'])) {
1418
				$authport = (isset($pptpdcfg['radius']['server']['port']) && strlen($pptpdcfg['radius']['server']['port']) > 1) ? $pptpdcfg['radius']['server']['port'] : 1812;
1419
				$acctport = $authport + 1;
1420
				$mpdconf .=<<<EOD
1421
	set radius server {$pptpdcfg['radius']['server']['ip']} "{$pptpdcfg['radius']['server']['secret']}" {$authport} {$acctport}
1422

    
1423
EOD;
1424
				if (isset ($pptpdcfg['radius']['server2']['enable'])) {
1425
					$authport = (isset($pptpdcfg['radius']['server2']['port']) && strlen($pptpdcfg['radius']['server2']['port']) > 1) ? $pptpdcfg['radius']['server2']['port'] : 1812;
1426
					$acctport = $authport + 1;
1427
					$mpdconf .=<<<EOD
1428
	set radius server {$pptpdcfg['radius']['server2']['ip']} "{$pptpdcfg['radius']['server2']['secret2']}" {$authport} {$acctport}
1429

    
1430
EOD;
1431
				}
1432
				$mpdconf .=<<<EOD
1433
	set radius retries 3
1434
	set radius timeout 10
1435
	set auth enable radius-auth
1436

    
1437
EOD;
1438

    
1439
				if (isset ($pptpdcfg['radius']['accounting'])) {
1440
					$mpdconf .=<<<EOD
1441
	set auth enable radius-acct
1442
	set radius acct-update 300
1443

    
1444
EOD;
1445
				}
1446
			}
1447

    
1448
			fwrite($fd, $mpdconf);
1449
			fclose($fd);
1450
			unset($mpdconf);
1451

    
1452
			/* write mpd.links */
1453
			$fd = fopen("{$g['varetc_path']}/pptp-vpn/mpd.links", "w");
1454
			if (!$fd) {
1455
				printf(gettext("Error: cannot open mpd.links in vpn_pptpd_configure().") . "\n");
1456
				return 1;
1457
			}
1458

    
1459
			$mpdlinks = "";
1460

    
1461
			for ($i = 0; $i < $pptpdcfg['n_pptp_units']; $i++) {
1462
				$mpdlinks .=<<<EOD
1463

    
1464
pt{$i}:
1465
	set link type pptp
1466
	set pptp enable incoming
1467
	set pptp disable originate
1468
	set pptp disable windowing
1469

    
1470
EOD;
1471
			}
1472

    
1473
			fwrite($fd, $mpdlinks);
1474
			fclose($fd);
1475
			unset($mpdlinks);
1476

    
1477
			/* write mpd.secret */
1478
			$fd = fopen("{$g['varetc_path']}/pptp-vpn/mpd.secret", "w");
1479
			if (!$fd) {
1480
				printf(gettext("Error: cannot open mpd.secret in vpn_pptpd_configure().") . "\n");
1481
				return 1;
1482
			}
1483

    
1484
			$mpdsecret = "";
1485

    
1486
			if (is_array($pptpdcfg['user'])) {
1487
				foreach ($pptpdcfg['user'] as $user) {
1488
					$pass = str_replace('\\', '\\\\', $user['password']);
1489
					$pass = str_replace('"', '\"', $pass);
1490
					$mpdsecret .= "{$user['name']} \"{$pass}\" {$user['ip']}\n";
1491
				}
1492
			}
1493

    
1494
			fwrite($fd, $mpdsecret);
1495
			fclose($fd);
1496
			unset($mpdsecret);
1497
			chmod("{$g['varetc_path']}/pptp-vpn/mpd.secret", 0600);
1498

    
1499
			vpn_netgraph_support();
1500

    
1501
			/* fire up mpd */
1502
			mwexec("/usr/local/sbin/mpd4 -b -d {$g['varetc_path']}/pptp-vpn -p {$g['varrun_path']}/pptp-vpn.pid -s pptps pptps");
1503

    
1504
			break;
1505

    
1506
		case 'redir':
1507
			break;
1508
	}
1509

    
1510
	if (platform_booting()) {
1511
		echo "done\n";
1512
	}
1513

    
1514
	return 0;
1515
}
1516

    
1517
function vpn_pppoes_configure() {
1518
	global $config;
1519

    
1520
	if (is_array($config['pppoes']['pppoe'])) {
1521
		foreach ($config['pppoes']['pppoe'] as $pppoe) {
1522
			vpn_pppoe_configure($pppoe);
1523
		}
1524
	}
1525
}
1526

    
1527
function vpn_pppoe_configure(&$pppoecfg) {
1528
	global $config, $g;
1529

    
1530
	$syscfg = $config['system'];
1531

    
1532
	/* create directory if it does not exist */
1533
	if (!is_dir("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn")) {
1534
		mkdir("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn");
1535
	}
1536

    
1537
	if (platform_booting()) {
1538
		if (!$pppoecfg['mode'] || ($pppoecfg['mode'] == "off")) {
1539
			return 0;
1540
		}
1541

    
1542
		echo gettext("Configuring PPPoE Server service... ");
1543
	} else {
1544
		/* kill mpd */
1545
		killbypid("{$g['varrun_path']}/pppoe{$pppoecfg['pppoeid']}-vpn.pid");
1546

    
1547
		/* wait for process to die */
1548
		sleep(2);
1549

    
1550
	}
1551

    
1552
	switch ($pppoecfg['mode']) {
1553

    
1554
		case 'server':
1555

    
1556
			$pppoe_interface = get_real_interface($pppoecfg['interface']);
1557

    
1558
			if ($pppoecfg['paporchap'] == "chap") {
1559
				$paporchap = "set link enable chap";
1560
			} else {
1561
				$paporchap = "set link enable pap";
1562
			}
1563

    
1564
			/* write mpd.conf */
1565
			$fd = fopen("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn/mpd.conf", "w");
1566
			if (!$fd) {
1567
				printf(gettext("Error: cannot open mpd.conf in vpn_pppoe_configure().") . "\n");
1568
				return 1;
1569
			}
1570
			$mpdconf = "\n\n";
1571
			$mpdconf .= "poes:\n";
1572

    
1573
			for ($i = 0; $i < $pppoecfg['n_pppoe_units']; $i++) {
1574
				$mpdconf .= "	load poes{$pppoecfg['pppoeid']}{$i}\n";
1575
			}
1576

    
1577
			for ($i = 0; $i < $pppoecfg['n_pppoe_units']; $i++) {
1578

    
1579
				$clientip = long2ip32(ip2long($pppoecfg['remoteip']) + $i);
1580

    
1581
				if (isset($pppoecfg['radius']['radiusissueips']) && isset($pppoecfg['radius']['server']['enable'])) {
1582
					$isssue_ip_type = "set ipcp ranges {$pppoecfg['localip']}/32 0.0.0.0/0";
1583
				} else {
1584
					$isssue_ip_type = "set ipcp ranges {$pppoecfg['localip']}/32 {$clientip}/32";
1585
				}
1586

    
1587
				$mpdconf .=<<<EOD
1588

    
1589
poes{$pppoecfg['pppoeid']}{$i}:
1590
	new -i poes{$pppoecfg['pppoeid']}{$i} poes{$pppoecfg['pppoeid']}{$i} poes{$pppoecfg['pppoeid']}{$i}
1591
	{$isssue_ip_type}
1592
	load pppoe_standard
1593

    
1594
EOD;
1595
			}
1596

    
1597
			$mpdconf .=<<<EOD
1598

    
1599
pppoe_standard:
1600
	set bundle no multilink
1601
	set bundle enable compression
1602
	set auth max-logins 1
1603
	set iface up-script /usr/local/sbin/vpn-linkup
1604
	set iface down-script /usr/local/sbin/vpn-linkdown
1605
	set iface idle 0
1606
	set iface disable on-demand
1607
	set iface disable proxy-arp
1608
	set iface enable tcpmssfix
1609
	set iface mtu 1500
1610
	set link no pap chap
1611
	{$paporchap}
1612
	set link keep-alive 60 180
1613
	set ipcp yes vjcomp
1614
	set ipcp no vjcomp
1615
	set link max-redial -1
1616
	set link mtu 1492
1617
	set link mru 1492
1618
	set ccp yes mpp-e40
1619
	set ccp yes mpp-e128
1620
	set ccp yes mpp-stateless
1621
	set link latency 1
1622
	#set ipcp dns 10.10.1.3
1623
	#set bundle accept encryption
1624

    
1625
EOD;
1626

    
1627
			if (!empty($pppoecfg['dns1'])) {
1628
				$mpdconf .= "	set ipcp dns " . $pppoecfg['dns1'];
1629
				if (!empty($pppoecfg['dns2'])) {
1630
					$mpdconf .= " " . $pppoecfg['dns2'];
1631
				}
1632
				$mpdconf .= "\n";
1633
			} elseif (isset ($config['dnsmasq']['enable'])) {
1634
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1635
				if ($syscfg['dnsserver'][0]) {
1636
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1637
				}
1638
				$mpdconf .= "\n";
1639
			} elseif (isset ($config['unbound']['enable'])) {
1640
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1641
				if ($syscfg['dnsserver'][0]) {
1642
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1643
				}
1644
				$mpdconf .= "\n";
1645
			} elseif (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1646
					$mpdconf .= "	set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n";
1647
			}
1648

    
1649
			if (isset ($pppoecfg['radius']['server']['enable'])) {
1650
				$radiusport = "";
1651
				$radiusacctport = "";
1652
				if (isset($pppoecfg['radius']['server']['port'])) {
1653
					$radiusport = $pppoecfg['radius']['server']['port'];
1654
				}
1655
				if (isset($pppoecfg['radius']['server']['acctport'])) {
1656
					$radiusacctport = $pppoecfg['radius']['server']['acctport'];
1657
				}
1658
				$mpdconf .=<<<EOD
1659
	set radius server {$pppoecfg['radius']['server']['ip']} "{$pppoecfg['radius']['server']['secret']}" {$radiusport} {$radiusacctport}
1660
	set radius retries 3
1661
	set radius timeout 10
1662
	set auth enable radius-auth
1663

    
1664
EOD;
1665

    
1666
				if (isset ($pppoecfg['radius']['accounting'])) {
1667
					$mpdconf .=<<<EOD
1668
	set auth enable radius-acct
1669

    
1670
EOD;
1671
				}
1672
			}
1673

    
1674
			fwrite($fd, $mpdconf);
1675
			fclose($fd);
1676
			unset($mpdconf);
1677

    
1678
			/* write mpd.links */
1679
			$fd = fopen("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn/mpd.links", "w");
1680
			if (!$fd) {
1681
				printf(gettext("Error: cannot open mpd.links in vpn_pppoe_configure().") . "\n");
1682
				return 1;
1683
			}
1684

    
1685
			$mpdlinks = "";
1686

    
1687
			for ($i = 0; $i < $pppoecfg['n_pppoe_units']; $i++) {
1688
				$mpdlinks .=<<<EOD
1689

    
1690
poes{$pppoecfg['pppoeid']}{$i}:
1691
	set phys type pppoe
1692
	set pppoe iface {$pppoe_interface}
1693
	set pppoe service "*"
1694
	set pppoe disable originate
1695
	set pppoe enable incoming
1696

    
1697
EOD;
1698
			}
1699

    
1700
			fwrite($fd, $mpdlinks);
1701
			fclose($fd);
1702
			unset($mpdlinks);
1703

    
1704
			if ($pppoecfg['username']) {
1705
				/* write mpd.secret */
1706
				$fd = fopen("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn/mpd.secret", "w");
1707
				if (!$fd) {
1708
					printf(gettext("Error: cannot open mpd.secret in vpn_pppoe_configure().") . "\n");
1709
					return 1;
1710
				}
1711

    
1712
				$mpdsecret = "\n\n";
1713

    
1714
				if (!empty($pppoecfg['username'])) {
1715
					$item = explode(" ", $pppoecfg['username']);
1716
					foreach ($item as $userdata) {
1717
						$data = explode(":", $userdata);
1718
						$mpdsecret .= "{$data[0]} \"" . base64_decode($data[1]) . "\" {$data[2]}\n";
1719
					}
1720
				}
1721

    
1722
				fwrite($fd, $mpdsecret);
1723
				fclose($fd);
1724
				unset($mpdsecret);
1725
				chmod("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn/mpd.secret", 0600);
1726
			}
1727

    
1728
			/* Check if previous instance is still up */
1729
			while (file_exists("{$g['varrun_path']}/pppoe{$pppoecfg['pppoeid']}-vpn.pid") && isvalidpid("{$g['varrun_path']}/pppoe{$pppoecfg['pppoeid']}-vpn.pid")) {
1730
				killbypid("{$g['varrun_path']}/pppoe{$pppoecfg['pppoeid']}-vpn.pid");
1731
			}
1732

    
1733
			/* Get support for netgraph(4) from the nic */
1734
			pfSense_ngctl_attach(".", $pppoe_interface);
1735
			/* fire up mpd */
1736
			mwexec("/usr/local/sbin/mpd4 -b -d {$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn -p {$g['varrun_path']}/pppoe{$pppoecfg['pppoeid']}-vpn.pid -s poes poes");
1737

    
1738
			break;
1739
	}
1740

    
1741
	if (platform_booting()) {
1742
		echo gettext("done") . "\n";
1743
	}
1744

    
1745
	return 0;
1746
}
1747

    
1748
function vpn_l2tp_configure() {
1749
	global $config, $g;
1750

    
1751
	$syscfg = $config['system'];
1752
	$l2tpcfg = $config['l2tp'];
1753

    
1754
	/* create directory if it does not exist */
1755
	if (!is_dir("{$g['varetc_path']}/l2tp-vpn")) {
1756
		mkdir("{$g['varetc_path']}/l2tp-vpn");
1757
	}
1758

    
1759
	if (platform_booting()) {
1760
		if (!$l2tpcfg['mode'] || ($l2tpcfg['mode'] == "off")) {
1761
			return 0;
1762
		}
1763

    
1764
		echo gettext("Configuring l2tp VPN service... ");
1765
	} else {
1766
		/* kill mpd */
1767
		killbypid("{$g['varrun_path']}/l2tp-vpn.pid");
1768

    
1769
		/* wait for process to die */
1770
		sleep(8);
1771

    
1772
	}
1773

    
1774
	/* make sure l2tp-vpn directory exists */
1775
	if (!file_exists("{$g['varetc_path']}/l2tp-vpn")) {
1776
		mkdir("{$g['varetc_path']}/l2tp-vpn");
1777
	}
1778

    
1779
	switch ($l2tpcfg['mode']) {
1780

    
1781
		case 'server':
1782
			if ($l2tpcfg['paporchap'] == "chap") {
1783
				$paporchap = "set link enable chap";
1784
			} else {
1785
				$paporchap = "set link enable pap";
1786
			}
1787

    
1788
			/* write mpd.conf */
1789
			$fd = fopen("{$g['varetc_path']}/l2tp-vpn/mpd.conf", "w");
1790
			if (!$fd) {
1791
				printf(gettext("Error: cannot open mpd.conf in vpn_l2tp_configure().") . "\n");
1792
				return 1;
1793
			}
1794
			$mpdconf = "\n\n";
1795
			$mpdconf .=<<<EOD
1796
l2tps:
1797

    
1798
EOD;
1799

    
1800
			for ($i = 0; $i < $l2tpcfg['n_l2tp_units']; $i++) {
1801
				$mpdconf .= "	load l2tp{$i}\n";
1802
			}
1803

    
1804
			for ($i = 0; $i < $l2tpcfg['n_l2tp_units']; $i++) {
1805

    
1806
				$clientip = long2ip32(ip2long($l2tpcfg['remoteip']) + $i);
1807

    
1808
				if (isset ($l2tpcfg['radius']['radiusissueips']) && isset ($l2tpcfg['radius']['enable'])) {
1809
					$isssue_ip_type = "set ipcp ranges {$l2tpcfg['localip']}/32 0.0.0.0/0";
1810
				} else {
1811
					$isssue_ip_type = "set ipcp ranges {$l2tpcfg['localip']}/32 {$clientip}/32";
1812
				}
1813

    
1814
				$mpdconf .=<<<EOD
1815

    
1816
l2tp{$i}:
1817
	new -i l2tp{$i} l2tp{$i} l2tp{$i}
1818
	{$isssue_ip_type}
1819
	load l2tp_standard
1820

    
1821
EOD;
1822
			}
1823

    
1824
			$mpdconf .=<<<EOD
1825

    
1826
l2tp_standard:
1827
	set bundle disable multilink
1828
	set bundle enable compression
1829
	set bundle yes crypt-reqd
1830
	set ipcp yes vjcomp
1831
	# set ipcp ranges 131.188.69.161/32 131.188.69.170/28
1832
	set ccp yes mppc
1833
	set iface disable on-demand
1834
	set iface enable proxy-arp
1835
	set iface up-script /usr/local/sbin/vpn-linkup
1836
	set iface down-script /usr/local/sbin/vpn-linkdown
1837
	set link yes acfcomp protocomp
1838
	set link no pap chap
1839
	{$paporchap}
1840
	set link keep-alive 10 180
1841

    
1842
EOD;
1843

    
1844
			if (is_ipaddr($l2tpcfg['wins'])) {
1845
				$mpdconf .= "	set ipcp nbns {$l2tpcfg['wins']}\n";
1846
			}
1847
			if (is_ipaddr($l2tpcfg['dns1'])) {
1848
				$mpdconf .= "	set ipcp dns " . $l2tpcfg['dns1'];
1849
				if (is_ipaddr($l2tpcfg['dns2'])) {
1850
					$mpdconf .= " " . $l2tpcfg['dns2'];
1851
				}
1852
				$mpdconf .= "\n";
1853
			} elseif (isset ($config['dnsmasq']['enable'])) {
1854
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1855
				if ($syscfg['dnsserver'][0]) {
1856
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1857
				}
1858
				$mpdconf .= "\n";
1859
			} elseif (isset ($config['unbound']['enable'])) {
1860
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1861
				if ($syscfg['dnsserver'][0]) {
1862
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1863
				}
1864
				$mpdconf .= "\n";
1865
			} elseif (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1866
				$mpdconf .= "	set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n";
1867
			}
1868

    
1869
			if (isset ($l2tpcfg['radius']['enable'])) {
1870
				$mpdconf .=<<<EOD
1871
	set radius server {$l2tpcfg['radius']['server']} "{$l2tpcfg['radius']['secret']}"
1872
	set radius retries 3
1873
	set radius timeout 10
1874
	set auth enable radius-auth
1875

    
1876
EOD;
1877

    
1878
				if (isset ($l2tpcfg['radius']['accounting'])) {
1879
					$mpdconf .=<<<EOD
1880
	set auth enable radius-acct
1881

    
1882
EOD;
1883
				}
1884
			}
1885

    
1886
			fwrite($fd, $mpdconf);
1887
			fclose($fd);
1888
			unset($mpdconf);
1889

    
1890
			/* write mpd.links */
1891
			$fd = fopen("{$g['varetc_path']}/l2tp-vpn/mpd.links", "w");
1892
			if (!$fd) {
1893
				printf(gettext("Error: cannot open mpd.links in vpn_l2tp_configure().") . "\n");
1894
				return 1;
1895
			}
1896

    
1897
			$mpdlinks = "";
1898

    
1899
			for ($i = 0; $i < $l2tpcfg['n_l2tp_units']; $i++) {
1900
				$mpdlinks .=<<<EOD
1901

    
1902
l2tp{$i}:
1903
	set link type l2tp
1904
	set l2tp enable incoming
1905
	set l2tp disable originate
1906

    
1907
EOD;
1908
				if (!empty($l2tpcfg['secret'])) {
1909
					$mpdlinks .= "set l2tp secret {$l2tpcfg['secret']}\n";
1910
				}
1911
			}
1912

    
1913
			fwrite($fd, $mpdlinks);
1914
			fclose($fd);
1915
			unset($mpdlinks);
1916

    
1917
			/* write mpd.secret */
1918
			$fd = fopen("{$g['varetc_path']}/l2tp-vpn/mpd.secret", "w");
1919
			if (!$fd) {
1920
				printf(gettext("Error: cannot open mpd.secret in vpn_l2tp_configure().") . "\n");
1921
				return 1;
1922
			}
1923

    
1924
			$mpdsecret = "\n\n";
1925

    
1926
			if (is_array($l2tpcfg['user'])) {
1927
				foreach ($l2tpcfg['user'] as $user) {
1928
					$mpdsecret .= "{$user['name']} \"{$user['password']}\" {$user['ip']}\n";
1929
				}
1930
			}
1931

    
1932
			fwrite($fd, $mpdsecret);
1933
			fclose($fd);
1934
			unset($mpdsecret);
1935
			chmod("{$g['varetc_path']}/l2tp-vpn/mpd.secret", 0600);
1936

    
1937
			vpn_netgraph_support();
1938

    
1939
			/* fire up mpd */
1940
			mwexec("/usr/local/sbin/mpd4 -b -d {$g['varetc_path']}/l2tp-vpn -p {$g['varrun_path']}/l2tp-vpn.pid -s l2tps l2tps");
1941

    
1942
			break;
1943

    
1944
		case 'redir':
1945
			break;
1946
	}
1947

    
1948
	if (platform_booting()) {
1949
		echo "done\n";
1950
	}
1951

    
1952
	return 0;
1953
}
1954

    
1955
?>
(58-58/67)