Project

General

Profile

Download (48.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
	if ($forconfig)
59
		return implode(',', $cfgtext);
60
}
61

    
62
/* include all configuration functions */
63
function vpn_ipsec_convert_to_modp($index)
64
{
65

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

    
94
	return $convertion;
95
}
96

    
97
function vpn_ipsec_configure($ipchg = false)
98
{
99
	global $config, $g, $sa, $sn, $p1_ealgos, $p2_ealgos;
100

    
101
	if ($g['platform'] == 'jail')
102
		return;
103

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

    
108
	vpn_ipsec_configure_preferoldsa();
109

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

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

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

    
125
		return 0;
126
	}
127

    
128
	$a_phase1 = $config['ipsec']['phase1'];
129
	$a_phase2 = $config['ipsec']['phase2'];
130
	$a_client = $config['ipsec']['client'];
131

    
132
	$certpath = "{$g['varetc_path']}/ipsec/ipsec.d/certs";
133
	$capath = "{$g['varetc_path']}/ipsec/ipsec.d/cacerts";
134
	$keypath = "{$g['varetc_path']}/ipsec/ipsec.d/private";
135

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

    
161
	if (platform_booting())
162
		echo gettext("Configuring IPsec VPN... ");
163

    
164
	/* fastforwarding is not compatible with ipsec tunnels */
165
	set_single_sysctl("net.inet.ip.fastforwarding", "0");
166

    
167
	/* resolve all local, peer addresses and setup pings */
168
	$ipmap = array();
169
	$rgmap = array();
170
	$filterdns_list = array();
171
	$listeniflist = array();
172
	$aggressive_mode_psk = false;
173
	unset($iflist);
174
	if (is_array($a_phase1) && count($a_phase1)) {
175

    
176
		$ipsecpinghosts = "";
177
		/* step through each phase1 entry */
178
		foreach ($a_phase1 as $ph1ent) {
179
			if (isset($ph1ent['disabled']))
180
				continue;
181

    
182
			if ($ph1ent['mode'] == "aggressive" && ($ph1ent['authentication_method'] == "pre_shared_key" || $ph1ent['authentication_method'] == "xauth_psk_server")) 
183
				$aggressive_mode_psk = true;
184

    
185
			$ikeid = $ph1ent['ikeid'];
186
			$listeniflist = get_real_interface($a_phase1['interface']);
187

    
188
			$ep = ipsec_get_phase1_src($ph1ent);
189
			if (!is_ipaddr($ep))
190
				continue;
191

    
192
			if(!in_array($ep,$ipmap))
193
				$ipmap[] = $ep;
194

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

    
198
			if (isset ($ph1ent['mobile']))
199
				continue;
200

    
201
			$rg = $ph1ent['remote-gateway'];
202

    
203
			if (!is_ipaddr($rg)) {
204
				$filterdns_list[] = "{$rg}";
205
				add_hostname_to_watch($rg);
206
				if (!platform_booting())
207
					$rg = resolve_retry($rg);
208
				if (!is_ipaddr($rg))
209
					continue;
210
			}
211
			if(array_search($rg, $rgmap)) {
212
				log_error("The remote gateway {$rg} already exists on another phase 1 entry");
213
				continue;
214
			}
215
			$rgmap[$ph1ent['remote-gateway']] = $rg;
216

    
217
			if (is_array($a_phase2)) {
218
				/* step through each phase2 entry */
219
				foreach ($a_phase2 as $ph2ent) {
220
					if (isset($ph2ent['disabled']))
221
						continue;
222

    
223
					if ($ikeid != $ph2ent['ikeid'])
224
						continue;
225

    
226
					/* add an ipsec pinghosts entry */
227
					if ($ph2ent['pinghost']) {
228
						if (!is_array($iflist))
229
							$iflist = get_configured_interface_list();
230
						$viplist = get_configured_vips_list();
231
						$srcip = null;
232
						$local_subnet = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
233
						if(is_ipaddrv6($ph2ent['pinghost'])) {
234
							foreach ($iflist as $ifent => $ifname) {
235
								$interface_ip = get_interface_ipv6($ifent);
236
								if(!is_ipaddrv6($interface_ip))
237
									continue;
238
								if (ip_in_subnet($interface_ip, $local_subnet)) {
239
									$srcip = $interface_ip;
240
									break;
241
								}
242
							}
243
						} else {
244
							foreach ($iflist as $ifent => $ifname) {
245
								$interface_ip = get_interface_ip($ifent);
246
								if(!is_ipaddrv4($interface_ip))
247
									continue;
248
								if ($local_subnet == "0.0.0.0/0" || ip_in_subnet($interface_ip, $local_subnet)) {
249
									$srcip = $interface_ip;
250
									break;
251
								}
252
							}
253
						}
254
						/* if no valid src IP was found in configured interfaces, try the vips */
255
						if (is_null($srcip)) {
256
							foreach ($viplist as $vip) {
257
								if (ip_in_subnet($vip['ipaddr'], $local_subnet)) {
258
									$srcip = $vip['ipaddr'];
259
									break;
260
								}
261
							}
262
						}
263
						$dstip = $ph2ent['pinghost'];
264
						if(is_ipaddrv6($dstip)) {
265
							$family = "inet6";
266
						} else {
267
							$family = "inet";
268
						}
269
						if (is_ipaddr($srcip))
270
							$ipsecpinghosts[] = "{$srcip}|{$dstip}|3|||||{$family}|\n";
271
					}
272
				}
273
			}
274
		}
275
		@file_put_contents("{$g['vardb_path']}/ipsecpinghosts", $ipsecpinghosts);
276
		unset($ipsecpinghosts);
277
	}
278
	unset($iflist);
279

    
280
	$accept_unencrypted = "";
281
	if (isset($config['ipsec']['acceptunencryptedmainmode']))
282
		$accept_unencrypted = "accept_unencrypted_mainmode_messages = yes";
283

    
284
	$i_dont_care_about_security_and_use_aggressive_mode_psk = "";
285
	if ($aggressive_mode_psk) {
286
		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.");
287
		$i_dont_care_about_security_and_use_aggressive_mode_psk = "i_dont_care_about_security_and_use_aggressive_mode_psk=yes";
288
	} 
289

    
290
	$unity_enabled = 'yes';
291
	if (isset($config['ipsec']['unityplugin']))
292
		$unity_enabled = 'no';
293

    
294
	$strongswan = <<<EOD
295

    
296
# Automatically generated config file - DO NOT MODIFY. Changes will be overwritten. 
297
starter {
298
load_warning = no
299
}
300

    
301
charon {
302
# number of worker threads in charon
303
threads = 16
304
ikesa_table_size = 32
305
ikesa_table_segments = 4
306
init_limit_half_open = 1000
307
install_routes = no
308
{$i_dont_care_about_security_and_use_aggressive_mode_psk}
309
{$accept_unencrypted}
310
cisco_unity = {$unity_enabled}
311

    
312
# And two loggers using syslog. The subsections define the facility to log
313
# to, currently one of: daemon, auth.
314
syslog {
315
	identifier = charon
316
	# default level to the LOG_DAEMON facility
317
	daemon {
318
	}
319
	# very minimalistic IKE auditing logs to LOG_AUTHPRIV
320
	auth {
321
		default = -1
322
		ike = 1
323
		ike_name = yes
324
	}
325
}
326

    
327
EOD;
328

    
329
	$strongswan .= "\tplugins {\n";
330

    
331
	if (is_array($a_client) && isset($a_client['enable'])) {
332
		$strongswan .= "\t\tattr {\n";
333
		if ($a_client['pool_address'] && $a_client['pool_netbits'])
334
			$strongswan .= "\t\t\tsubnet = {$a_client['pool_address']}/{$a_client['pool_netbits']}\n";
335

    
336
		$cfgservers = array();
337
		if (!empty($a_client['dns_server1']))
338
			$cfgservers[] = $a_client['dns_server1'];
339
		if (!empty($a_client['dns_server2']))
340
			$cfgservers[] = $a_client['dns_server2'];
341
		if (!empty($a_client['dns_server3']))
342
			$cfgservers[] = $a_client['dns_server3'];
343
		if (!empty($a_client['dns_server4']))
344
			$cfgservers[] = $a_client['dns_server4'];
345

    
346
		if (!empty($cfgservers))
347
			$strongswan .= "\t\t\tdns = " . implode(",", $cfgservers) . "\n";
348
		unset($cfgservers);
349
		$cfgservers = array();
350
		if (!empty($a_client['wins_server1']))
351
			$cfgservers[] = $a_client['wins_server1'];
352
		if (!empty($a_client['wins_server2']))
353
			$cfgservers[] = $a_client['wins_server2'];
354
		if (!empty($cfgservers))
355
			$strongswan .= "\t\t\tnbns = " . implode(",", $cfgservers) . "\n";
356
		unset($cfgservers);
357

    
358
		if (isset($a_client['net_list'])) {
359
			$net_list = '';
360
			foreach ($a_phase2 as $ph2ent) {
361
				if (isset($ph2ent['disabled']))
362
					continue;
363

    
364
				if (!isset($ph2ent['mobile']))
365
					continue;
366

    
367
				$localid = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']);
368

    
369
				if (!empty($net_list))
370
					$net_list .= ",";
371
				$net_list .= $localid;
372
			}
373

    
374
			if (!empty($net_list)) {
375
				$strongswan .= "\t\t\tsplit-include = {$net_list}\n";
376
				unset($net_list);
377
			}
378
		}
379

    
380
		if (!empty($a_client['dns_domain'])) {
381
			$strongswan .= "\t\t\t# Search domain and default domain\n";
382
			$strongswan .= "\t\t\t28674 = {$a_client['dns_domain']}\n";
383
			if (empty($a_client['dns_split']))
384
				$strongswan .= "\t\t\t28675 = {$a_client['dns_domain']}";
385
			$strongswan .= "\n";
386
		}
387

    
388
		if (!empty($a_client['dns_split'])) {
389
			$strongswan .= "\t\t\t28675 = {$a_client['dns_split']}\n";
390
		}
391

    
392
		if (!empty($a_client['login_banner']))
393
			$strongswan .= "\t\t\t28672 = {$a_client['login_banner']}\n";
394

    
395
		if (isset($a_client['save_passwd']))
396
			$strongswan .= "\t\t\t28673 = 1\n";
397

    
398
		if ($a_client['pfs_group'])
399
			$strongswan .= "\t\t\t28679 = {$a_client['pfs_group']}\n";
400
		$strongswan .= "\t\t}\n";
401

    
402
		if ($a_client['user_source'] != "none") {
403
			$strongswan .= "\t\txauth-generic {\n";
404
			$strongswan .= "\t\t\tscript = /etc/inc/ipsec.auth-user.php\n";
405
			$strongswan .= "\t\t\tauthcfg = ";
406
			$firstsed = 0;
407
			$authcfgs = explode(",", $a_client['user_source']);
408
			foreach ($authcfgs as $authcfg) {
409
				if ($firstsed > 0)
410
					$strongswan .= ",";
411
				if ($authcfg == "system")
412
					$authcfg = "Local Database";
413
				$strongswan .= $authcfg;
414
				$firstsed = 1;
415
			}
416
			$strongswan .= "\n";
417
			$strongswan .= "\t\t}\n";
418
		}
419
	}
420

    
421
	$strongswan .= "\t}\n}\n";
422
	@file_put_contents("{$g['varetc_path']}/ipsec/strongswan.conf", $strongswan);
423
	unset($strongswan);
424

    
425
	/* generate CA certificates files */
426
	if (is_array($config['ca']) && count($config['ca'])) {
427
		foreach ($config['ca'] as $ca) {
428
			if (!isset($ca['crt'])) {
429
				log_error(sprintf(gettext("Error: Invalid certificate info for %s"), $ca['descr']));
430
				continue;
431
			}
432
			$cert = base64_decode($ca['crt']);
433
			$x509cert = openssl_x509_parse(openssl_x509_read($cert));
434
			if (!is_array($x509cert) || !isset($x509cert['hash'])) {
435
				log_error(sprintf(gettext("Error: Invalid certificate hash info for %s"), $ca['descr']));
436
				continue;
437
			}
438
			$fname = "{$capath}/{$x509cert['hash']}.0.crt";
439
			if (!@file_put_contents($fname, $cert)) {
440
				log_error(sprintf(gettext("Error: Cannot write IPsec CA file for %s"), $ca['descr']));
441
				continue;
442
			}
443
			unset($cert);
444
		}
445
	}
446

    
447
	$pskconf = "";
448

    
449
	if (is_array($a_phase1) && count($a_phase1)) {
450
		foreach ($a_phase1 as $ph1ent) {
451

    
452
			if (isset($ph1ent['disabled']))
453
				continue;
454

    
455
			if (strstr($ph1ent['authentication_method'], 'rsa') || $ph1ent['authentication_method'] == 'eap-tls') {
456
				$certline = '';
457

    
458
				$ikeid = $ph1ent['ikeid'];
459
				$cert = lookup_cert($ph1ent['certref']);
460

    
461
				if (!$cert) {
462
					log_error(sprintf(gettext("Error: Invalid phase1 certificate reference for %s"), $ph1ent['name']));
463
					continue;
464
				}
465

    
466
				@chmod($certpath, 0600);
467

    
468
				$ph1keyfile = "{$keypath}/cert-{$ikeid}.key";
469
				if (!file_put_contents($ph1keyfile, base64_decode($cert['prv']))) {
470
					log_error(sprintf(gettext("Error: Cannot write phase1 key file for %s"), $ph1ent['name']));
471
					continue;
472
				}
473
				@chmod($ph1keyfile, 0600);
474

    
475
				$ph1certfile = "{$certpath}/cert-{$ikeid}.crt";
476
				if (!file_put_contents($ph1certfile, base64_decode($cert['crt']))) {
477
					log_error(sprintf(gettext("Error: Cannot write phase1 certificate file for %s"), $ph1ent['name']));
478
					@unlink($ph1keyfile);
479
					continue;
480
				}
481
				@chmod($ph1certfile, 0600);
482

    
483
				/* XXX" Traffic selectors? */
484
				$pskconf .= " : RSA {$ph1keyfile}\n";
485
			} else {
486
				list ($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local');
487
				list ($peerid_type, $peerid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap);
488

    
489
				if (empty($peerid_data))
490
					continue;
491

    
492
				$myid = isset($ph1ent['mobile']) ? trim($myid_data) : "%any";
493
				$peerid = ($peerid_data != 'allusers') ? trim($peerid_data) : '';
494
				if (!empty($ph1ent['pre-shared-key'])) {
495
					if ($myid_type == 'fqdn' && !empty($myid_data))
496
						$pskconf .= "@{$myid} {$peerid} : PSK 0s" . base64_encode(trim($ph1ent['pre-shared-key'])) . "\n";
497
					else
498
						$pskconf .= "{$myid} {$peerid} : PSK 0s" . base64_encode(trim($ph1ent['pre-shared-key'])) . "\n";
499
				}
500
			}
501
		}
502
	}
503

    
504
	/* Add user PSKs */
505
	if (is_array($config['system']) && is_array($config['system']['user'])) {
506
		foreach ($config['system']['user'] as $user) {
507
			if (!empty($user['ipsecpsk'])) {
508
				$pskconf .= "%any {$user['name']} : PSK 0s" . base64_encode($user['ipsecpsk']) . "\n";
509
			}
510
		}
511
		unset($user);
512
	}
513

    
514
	/* add PSKs for mobile clients */
515
	if (is_array($ipseccfg['mobilekey'])) {
516
		foreach ($ipseccfg['mobilekey'] as $key) {
517
			if ($key['ident'] == "allusers")
518
				$key['ident'] = '%any';
519
			$pskconf .= "%any {$key['ident']} : PSK 0s" . base64_encode($key['pre-shared-key']) . "\n";
520
		}
521
		unset($key);
522
	}
523

    
524
	@file_put_contents("{$g['varetc_path']}/ipsec/ipsec.secrets", $pskconf);
525
	chmod("{$g['varetc_path']}/ipsec/ipsec.secrets", 0600);
526
	unset($pskconf);
527

    
528
	$natfilterrules = false;
529
	/* begin ipsec.conf */
530
	$ipsecconf = "";
531
	$enablecompression = false;
532
	if (is_array($a_phase1) && count($a_phase1))  {
533

    
534
		$ipsecconf .= "# This file is automatically generated. Do not edit\n";
535
		$ipsecconf .= "config setup\n\tuniqueids = yes\n";
536
		$ipsecconf .= "\tcharondebug=\"" . vpn_ipsec_configure_loglevels(true) . "\"\n";
537

    
538
		foreach ($a_phase1 as $ph1ent) {
539
			if (isset($ph1ent['disabled']))
540
				continue;
541

    
542
			if ($ph1ent['mode'] == "aggressive")
543
				$aggressive = "yes";
544
			else
545
				$aggressive = "no";
546

    
547
			$ep = ipsec_get_phase1_src($ph1ent);
548
			if (!$ep)
549
				continue;
550

    
551
			$ikeid = $ph1ent['ikeid'];
552
			$keyexchange = "ikev1";
553
			$passive = "route";
554
			if (!empty($ph1ent['iketype'])) {
555
				if ($ph1ent['iketype'] == "ikev2") {
556
					$keyexchange = "ikev2";
557
					//$passive = "start";
558
				} else if ($ph1ent['iketype'] == "auto")
559
					$keyexchange = "ike";
560
			}
561

    
562
			if (isset($ph1ent['mobile'])) {
563
				$right_spec = "%any";
564
				$passive = 'add';
565
			} else
566
				$right_spec = $ph1ent['remote-gateway'];
567

    
568
			list ($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local');
569
			if ($myid_type != 'address')
570
				$myid_data = "{$myid_type}:{$myid_data}";
571

    
572
			/* Only specify peer ID if we are not dealing with a mobile PSK-only tunnel */
573
			$peerid_spec = '';
574
			if (!isset($ph1ent['mobile'])) {
575
				list ($peerid_type, $peerid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap);
576
				if ($peerid_type != 'address')
577
					$peerid_spec = "{$peerid_type}:{$peerid_data}";
578
				else
579
					$peerid_spec = $peerid_data;
580
			}
581

    
582
			if (is_array($ph1ent['encryption-algorithm']) && !empty($ph1ent['encryption-algorithm']['name']) && !empty($ph1ent['hash-algorithm'])) {
583
				$ealgosp1 = '';
584
				$ealg_id = $ph1ent['encryption-algorithm']['name'];
585
				$ealg_kl = $ph1ent['encryption-algorithm']['keylen'];
586
				if ($ealg_kl)
587
					$ealgosp1 = "ike = {$ealg_id}{$ealg_kl}-{$ph1ent['hash-algorithm']}";
588
				else
589
					$ealgosp1 = "ike = {$ealg_id}-{$ph1ent['hash-algorithm']}";
590

    
591
				$modp = vpn_ipsec_convert_to_modp($ph1ent['dhgroup']);
592
				if (!empty($modp))
593
					$ealgosp1 .= "-{$modp}";
594

    
595
				$ealgosp1 .= "!";
596
			}
597

    
598
			if ($ph1ent['dpd_delay'] && $ph1ent['dpd_maxfail']) {
599
				if ($passive == "route")
600
					$dpdline = "dpdaction = restart";
601
				else
602
					$dpdline = "dpdaction = clear";
603
				$dpdline .= "\n\tdpddelay = {$ph1ent['dpd_delay']}s";
604
				$dpdtimeout = $ph1ent['dpd_delay'] * ($ph1ent['dpd_maxfail'] + 1);
605
				$dpdline .= "\n\tdpdtimeout = {$dpdtimeout}s";
606
			} else
607
				$dpdline = "dpdaction = none";
608

    
609
			$ikelifeline = '';
610
			if ($ph1ent['lifetime'])
611
				$ikelifeline = "ikelifetime = {$ph1ent['lifetime']}s";
612

    
613
			$rightsourceip = NULL;
614
			if (isset($ph1ent['mobile']) && !empty($a_client['pool_address'])) 
615
				$rightsourceip = "\trightsourceip = {$a_client['pool_address']}/{$a_client['pool_netbits']}\n";
616

    
617
			$authentication = "";
618
			switch ($ph1ent['authentication_method']) {
619
			case 'eap-tls':
620
				$authentication = "leftauth=eap-tls\n\trightauth=eap-tls";
621
				if (!empty($ph1ent['certref']))
622
					$authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt";
623
				break;
624
			case 'xauth_rsa_server':
625
				$authentication = "leftauth = pubkey\n\trightauth = pubkey";
626
				$authentication .= "\n\trightauth2 = xauth-generic";
627
				if (!empty($ph1ent['certref']))
628
					$authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt";
629
				break;
630
			case 'xauth_psk_server':
631
				$authentication = "leftauth = psk\n\trightauth = psk";
632
				$authentication .= "\n\trightauth2 = xauth-generic";
633
				break;
634
			case 'pre_shared_key':
635
				$authentication = "leftauth = psk\n\trightauth = psk";
636
				break;
637
			case 'rsasig':
638
				$authentication = "leftauth = pubkey\n\trightauth = pubkey";
639
				if (!empty($ph1ent['certref']))
640
					$authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt";
641
				break;
642
			case 'hybrid_rsa_server':
643
				$authentication = "leftauth = xauth-generic\n\trightauth = pubkey";
644
				$authentication .= "\n\trightauth2 = xauth";
645
				if (!empty($ph1ent['certref']))
646
					$authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt";
647
				break;
648
			}
649

    
650
			$left_spec = $ep;
651

    
652
			if (isset($ph1ent['reauth_enable']))
653
				$reauth = "reauth = no";
654
			else
655
				$reauth = "reauth = yes";
656
			if (isset($ph1ent['rekey_enable']))
657
				$rekey = "rekey = no";
658
			else
659
				$rekey = "rekey = yes";
660

    
661
			if ($ph1ent['nat_traversal'] == 'off')
662
				$forceencaps = 'forceencaps = no';
663
			else if ($ph1ent['nat_traversal'] == 'force')
664
				$forceencaps = 'forceencaps = yes';
665
			else
666
				$forceencaps = 'forceencaps = no';
667

    
668
			$ipseclifetime = 0;
669
			$rightsubnet_spec = array();
670
			$leftsubnet_spec = array();
671
			$reqids = array();
672
			$ealgoAHsp2arr = array();
673
			$ealgoESPsp2arr = array();
674
		if (is_array($a_phase2) && count($a_phase2)) {
675
			foreach ($a_phase2 as $ph2ent) {
676
				if ($ikeid != $ph2ent['ikeid'])
677
					continue;
678

    
679
				if (isset($ph2ent['disabled']))
680
					continue;
681

    
682
				if (isset($ph2ent['mobile']) && !isset($a_client['enable']))
683
					continue;
684

    
685
				if (($ph2ent['mode'] == 'tunnel') or ($ph2ent['mode'] == 'tunnel6')) {
686
					$tunneltype = "type = tunnel";
687

    
688
					$localid_type = $ph2ent['localid']['type'];
689
					$leftsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']);
690

    
691
					/* Do not print localid in some cases, such as a pure-psk or psk/xauth single phase2 mobile tunnel */
692
					if (($localid_type == "none" || $localid_type == "mobile")
693
					    && isset($ph1ent['mobile']) && (ipsec_get_number_of_phase2($ikeid)==1)) {
694
						$left_spec = '%any';
695
					} else {
696
						if ($localid_type != "address") {
697
							$localid_type = "subnet";
698
						}
699
						// Don't let an empty subnet into config, it can cause parse errors. Ticket #2201.
700
						if (!is_ipaddr($leftsubnet_data) && !is_subnet($leftsubnet_data) && ($leftsubnet_data != "0.0.0.0/0")) {
701
							log_error("Invalid IPsec Phase 2 \"{$ph2ent['descr']}\" - {$ph2ent['localid']['type']} has no subnet.");
702
							continue;
703
						}
704
						if (!empty($ph2ent['natlocalid'])) {
705
							$natleftsubnet_data =  ipsec_idinfo_to_cidr($ph2ent['natlocalid'], false, $ph2ent['mode']);
706
							if ($ph2ent['natlocalid']['type'] != "address") {
707
								if (is_subnet($natleftsubnet_data))
708
									$leftsubnet_data = "{$natleftsubnet_data}|{$leftsubnet_data}";
709
							} else {
710
								if (is_ipaddr($natleftsubnet_data))
711
									$leftsubnet_data = "{$natleftsubnet_data}|{$leftsubnet_data}";
712
							}
713
							$natfilterrules = true;
714
						}
715
					}
716

    
717
					$leftsubnet_spec[] = $leftsubnet_data;
718

    
719
					if (!isset($ph2ent['mobile'])) {
720
						$tmpsubnet = ipsec_idinfo_to_cidr($ph2ent['remoteid'], false, $ph2ent['mode']);
721
						$rightsubnet_spec[] = $tmpsubnet;
722
					} else if (!empty($a_client['pool_address'])) {
723
						$rightsubnet_spec[] = "{$a_client['pool_address']}/{$a_client['pool_netbits']}";
724
					}
725
				} else {
726
					$tunneltype = "type = transport";
727

    
728
					if ((($ph1ent['authentication_method'] == "xauth_psk_server") ||
729
					    ($ph1ent['authentication_method'] == "pre_shared_key")) && isset($ph1ent['mobile'])) {
730
						$left_spec = "%any";
731
					} else {
732
						$tmpsubnet = ipsec_get_phase1_src($ph1ent);
733
						$leftsubnet_spec[] = $tmpsubnet;
734
					}
735

    
736
					if (!isset($ph2ent['mobile'])) {
737
						$rightsubnet_spec[] = $right_spec;
738
					}
739
				}
740

    
741
				if (isset($a_client['pfs_group']))
742
					$ph2ent['pfsgroup'] = $a_client['pfs_group'];
743

    
744
				if ($ph2ent['protocol'] == 'esp') {
745
					if (is_array($ph2ent['encryption-algorithm-option'])) {
746
						foreach ($ph2ent['encryption-algorithm-option'] as $ealg) {
747
							$ealg_id = $ealg['name'];
748
							$ealg_kl = $ealg['keylen'];
749

    
750
							if (!empty($ealg_kl) && $ealg_kl == "auto") {
751
								if (empty($p2_ealgos) || !is_array($p2_ealgos))
752
									require("ipsec.inc");
753
								$key_hi = $p2_ealgos[$ealg_id]['keysel']['hi'];
754
								$key_lo = $p2_ealgos[$ealg_id]['keysel']['lo'];
755
								$key_step = $p2_ealgos[$ealg_id]['keysel']['step'];
756
								/* XXX: in some cases where include ordering is suspect these variables
757
								 * are somehow 0 and we enter this loop forever and timeout after 900
758
								 * seconds wrecking bootup */
759
								if ($key_hi != 0 and $key_lo !=0 and $key_step !=0) {
760
									for ($keylen = $key_hi; $keylen >= $key_lo; $keylen -= $key_step) {
761
										if (!empty($ph2ent['hash-algorithm-option']) && is_array($ph2ent['hash-algorithm-option'])) {
762
											foreach ($ph2ent['hash-algorithm-option'] as $halgo) {
763
												$halgo = str_replace('hmac_', '', $halgo);
764
												$tmpealgo = "{$ealg_id}{$keylen}-{$halgo}";
765
												$modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']);
766
												if (!empty($modp))
767
													$tmpealgo .= "-{$modp}";
768
												$ealgoESPsp2arr[] = $tmpealgo;
769
											}
770
										} else {
771
											$tmpealgo = "{$ealg_id}{$keylen}";
772
											$modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']);
773
											if (!empty($modp))
774
												$tmpealgo .= "-{$modp}";
775
											$ealgoESPsp2arr[] = $tmpealgo;
776
										}
777
									}
778
								}
779
							} else {
780
								if (!empty($ph2ent['hash-algorithm-option']) && is_array($ph2ent['hash-algorithm-option'])) {
781
									foreach ($ph2ent['hash-algorithm-option'] as $halgo) {
782
										$halgo = str_replace('hmac_', '', $halgo);
783
										$tmpealgo = "{$ealg_id}{$ealg_kl}-{$halgo}";
784
										$modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']);
785
										if (!empty($modp))
786
											$tmpealgo .= "-{$modp}";
787
										$ealgoESPsp2arr[] = $tmpealgo;
788
									}
789
								} else {
790
									$tmpealgo = "{$ealg_id}{$ealg_kl}";
791
									$modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']);
792
									if (!empty($modp))
793
										$tmpealgo .= "-{$modp}";
794
									$ealgoESPsp2arr[] = $tmpealgo;
795
								}
796
							}
797
						}
798
					}
799
				} else if ($ph2ent['protocol'] == 'ah') {
800
					if (!empty($ph2ent['hash-algorithm-option']) && is_array($ph2ent['hash-algorithm-option'])) {
801
						$modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']);
802
						foreach ($ph2ent['hash-algorithm-option'] as $tmpAHalgo) {
803
							$tmpAHalgo = str_replace('hmac_', '', $tmpAHalgo);
804
							if (!empty($modp))
805
								$tmpAHalgo = "-{$modp}";
806
							$ealgoAHsp2arr[] = $tmpAHalgo;
807
						}
808
					}
809
				}
810

    
811
				$reqids[] = $ph2ent['reqid'];
812

    
813
				if (!empty($ph2ent['lifetime'])) {
814
					if ($ipseclifetime == 0 || intval($ipseclifetime) > intval($ph2ent['lifetime']))
815
						$ipseclifetime = intval($ph2ent['lifetime']);
816
				}
817

    
818
			}
819
		}
820

    
821
			$ipsecconnect =<<<EOD
822
	fragmentation = yes
823
	keyexchange = {$keyexchange}
824
	{$reauth}
825
	{$forceencaps}
826
	{$rekey}
827
	installpolicy = yes
828
	{$tunneltype}
829
	{$dpdline}
830
	auto = {$passive}
831
	left = {$left_spec}
832
	right = {$right_spec}
833
	leftid = {$myid_data}
834

    
835
EOD;
836

    
837
			if (isset($config['ipsec']['compression'])) {
838
				$ipsecconnect .= "\tcompress = yes\n";
839
				$enablecompression = true;
840
			}
841
			if (!empty($ikelifeline))
842
				$ipsecconnect .= "\t{$ikelifeline}\n";
843
			if ($ipseclifetime > 0)
844
				$ipsecconnect .= "\tlifetime = {$ipseclifetime}s\n";
845
			if (!empty($rightsourceip))
846
				$ipsecconnect .= "{$rightsourceip}";
847
			if (!empty($ealgosp1))
848
				$ipsecconnect .= "\t{$ealgosp1}\n";
849
			if (!empty($ealgoAHsp2arr))
850
				$ipsecconnect .= "\tah = " . join(',', $ealgoAHsp2arr) . "!\n";
851
			if (!empty($ealgoESPsp2arr))
852
				$ipsecconnect .= "\tesp = " . join(',', $ealgoESPsp2arr) . "!\n";
853
			if (!empty($authentication))
854
				$ipsecconnect .= "\t{$authentication}\n";
855
			if (!empty($peerid_spec))
856
				$ipsecconnect .= "\trightid = {$peerid_spec}\n";
857
			if ($keyexchange == 'ikev1')
858
				$ipsecconnect .= "\taggressive = {$aggressive}\n";
859

    
860
			if (!isset($ph1ent['mobile']) && $keyexchange == 'ikev1') {
861
				if (!empty($rightsubnet_spec)) {
862
					$ipsecfin = '';
863
					foreach ($rightsubnet_spec as $idx => $rsubnet) {
864
						$ipsecfin .= "\nconn con{$ph1ent['ikeid']}00{$idx}\n";
865
						if (!empty($reqids[$idx]))
866
							$ipsecfin .= "\treqid = " . $reqids[$idx] . "\n";
867
						$ipsecfin .= $ipsecconnect;
868
						$ipsecfin .= "\trightsubnet = {$rsubnet}\n";
869
						$ipsecfin .= "\tleftsubnet = " . $leftsubnet_spec[$idx] . "\n";
870
					}
871
				} else
872
					log_error("No phase2 specifications for tunnel with REQID = {$ikeid}");
873
			} else {
874
				$ipsecfin = "\nconn con{$ph1ent['ikeid']}\n";
875
				if (!empty($reqids[$idx]))
876
					$ipsecfin .= "\treqid = " . $reqids[0] . "\n";
877
				$ipsecfin .= $ipsecconnect;
878
				if (!empty($rightsubnet_spec)) {
879
					$tempsubnets = array();
880
					foreach ($rightsubnet_spec as $rightsubnet)
881
						$tempsubnets[$rightsubnet] = $rightsubnet;
882
					$ipsecfin .= "\trightsubnet = " . join(",", $tempsubnets) . "\n";
883
					unset($tempsubnets, $rightsubnet);
884
				}
885
				if (!empty($leftsubnet_spec)) {
886
					$tempsubnets = array();
887
					foreach ($leftsubnet_spec as $leftsubnet)
888
						$tempsubnets[$leftsubnet] = $leftsubnet;
889
					$ipsecfin .= "\tleftsubnet = " . join(",", $leftsubnet_spec) . "\n";
890
					unset($tempsubnets, $leftsubnet);
891
				}
892
			}
893
			$ipsecconf .= $ipsecfin;
894
			unset($ipsecfin);
895

    
896
		}
897
	}
898

    
899
	@file_put_contents("{$g['varetc_path']}/ipsec/ipsec.conf", $ipsecconf);
900
	unset($ipsecconf);
901
	/* end ipsec.conf */
902

    
903
	if ($enablecompression === true)
904
		set_single_sysctl('net.inet.ipcomp.ipcomp_enable', 1);
905
	else
906
		set_single_sysctl('net.inet.ipcomp.ipcomp_enable', 0);
907

    
908
	/* mange process */
909
	if (isvalidpid("{$g['varrun_path']}/charon.pid")) {
910
		/* Read secrets */
911
		mwexec("/usr/local/sbin/ipsec rereadall", false);
912
		/* Update configuration changes */
913
		mwexec("/usr/local/sbin/ipsec update", false);
914
		mwexec("/usr/local/sbin/ipsec reload", false);
915
	} else {
916
		mwexec("/usr/local/sbin/ipsec start", false); 
917
	}
918

    
919
	if ($natfilterrules == true)
920
		filter_configure();
921
	/* start filterdns, if necessary */
922
	if (count($filterdns_list) > 0) {
923
		$interval = 60;
924
		if (!empty($ipseccfg['dns-interval']) && is_numeric($ipseccfg['dns-interval']))
925
			$interval = $ipseccfg['dns-interval'];
926

    
927
		$hostnames = "";
928
		array_unique($filterdns_list);
929
		foreach ($filterdns_list as $hostname)
930
			$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload ipsecdns\"'\n";
931
		file_put_contents("{$g['varetc_path']}/ipsec/filterdns-ipsec.hosts", $hostnames);
932
		unset($hostnames);
933

    
934
		if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid"))
935
			sigkillbypid("{$g['varrun_path']}/filterdns-ipsec.pid", "HUP");
936
		else {
937
			mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-ipsec.pid -i {$interval} -c {$g['varetc_path']}/ipsec/filterdns-ipsec.hosts -d 1");
938
		}
939
	} else {
940
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
941
		@unlink("{$g['varrun_path']}/filterdns-ipsec.pid");
942
	}
943

    
944
	if (platform_booting())
945
		echo "done\n";
946

    
947
	return count($filterdns_list);
948
}
949

    
950
/*
951
 * Forcefully restart IPsec
952
 * This is required for when dynamic interfaces reload
953
 * For all other occasions the normal vpn_ipsec_configure()
954
 * will gracefully reload the settings without restarting
955
 */
956
function vpn_ipsec_force_reload($interface = "") {
957
	global $g, $config;
958

    
959
	$ipseccfg = $config['ipsec'];
960

    
961
	if (!empty($interface) && is_array($ipseccfg['phase1'])) {
962
		$found = false;
963
		foreach ($ipseccfg['phase1'] as $ipsec) {
964
			if (!isset($ipsec['disabled']) && ($ipsec['interface'] == $interface)) {
965
				$found = true;
966
				break;
967
			}
968
		}
969
		if (!$found) {
970
			log_error(sprintf(gettext("Ignoring IPsec reload since there are no tunnels on interface %s"), $interface));
971
			return;
972
		}
973
	}
974

    
975
	/* if ipsec is enabled, start up again */
976
	if (isset($ipseccfg['enable'])) {
977
		log_error(gettext("Forcefully reloading IPsec"));
978
		vpn_ipsec_configure();
979
	}
980
}
981

    
982
/* master setup for vpn (mpd) */
983
function vpn_setup() {
984
	global $g;
985

    
986
	if ($g['platform'] == 'jail')
987
		return;
988

    
989
	/* start pptpd */
990
	vpn_pptpd_configure();
991

    
992
	/* start pppoe server */
993
	vpn_pppoes_configure();
994

    
995
	/* setup l2tp */
996
	vpn_l2tp_configure();
997
}
998

    
999
function vpn_netgraph_support() {
1000
	$iflist = get_configured_interface_list();
1001
	foreach ($iflist as $iface) {
1002
		$realif = get_real_interface($iface);
1003
		/* Get support for netgraph(4) from the nic */
1004
		$ifinfo = pfSense_get_interface_addresses($realif);
1005
		if (!empty($ifinfo) && in_array($ifinfo['iftype'], array("ether", "vlan", "bridge")))
1006
			pfSense_ngctl_attach(".", $realif);
1007
	}
1008
}
1009

    
1010
function vpn_pptpd_configure() {
1011
	global $config, $g;
1012

    
1013
	$syscfg = $config['system'];
1014
	$pptpdcfg = $config['pptpd'];
1015

    
1016
	if (platform_booting()) {
1017
		if (!$pptpdcfg['mode'] || ($pptpdcfg['mode'] == "off"))
1018
			return 0;
1019

    
1020
		if (platform_booting(true))
1021
			echo gettext("Configuring PPTP VPN service... ");
1022
	} else {
1023
		/* kill mpd */
1024
		killbypid("{$g['varrun_path']}/pptp-vpn.pid");
1025

    
1026
		/* wait for process to die */
1027
		sleep(3);
1028

    
1029
		if (is_process_running("mpd -b")) {
1030
			killbypid("{$g['varrun_path']}/pptp-vpn.pid");
1031
			log_error(gettext("Could not kill mpd within 3 seconds.   Trying again."));
1032
		}
1033

    
1034
		/* remove mpd.conf, if it exists */
1035
		unlink_if_exists("{$g['varetc_path']}/pptp-vpn/mpd.conf");
1036
		unlink_if_exists("{$g['varetc_path']}/pptp-vpn/mpd.links");
1037
		unlink_if_exists("{$g['varetc_path']}/pptp-vpn/mpd.secret");
1038
	}
1039

    
1040
	if (empty($pptpdcfg['n_pptp_units'])) {
1041
		log_error("Something wrong in the PPTPd configuration. Preventing starting the daemon because issues would arise.");
1042
		return;
1043
	}
1044

    
1045
	/* make sure pptp-vpn directory exists */
1046
	if (!file_exists("{$g['varetc_path']}/pptp-vpn"))
1047
		mkdir("{$g['varetc_path']}/pptp-vpn");
1048

    
1049
	switch ($pptpdcfg['mode']) {
1050
		case 'server' :
1051
			/* write mpd.conf */
1052
			$fd = fopen("{$g['varetc_path']}/pptp-vpn/mpd.conf", "w");
1053
			if (!$fd) {
1054
				printf(gettext("Error: cannot open mpd.conf in vpn_pptpd_configure().") . "\n");
1055
				return 1;
1056
			}
1057

    
1058
			$mpdconf = <<<EOD
1059
pptps:
1060

    
1061
EOD;
1062

    
1063
			for ($i = 0; $i < $pptpdcfg['n_pptp_units']; $i++) {
1064
				$mpdconf .= "	load pt{$i}\n";
1065
			}
1066

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

    
1069
				$clientip = long2ip32(ip2long($pptpdcfg['remoteip']) + $i);
1070

    
1071
				$mpdconf .= <<<EOD
1072

    
1073
pt{$i}:
1074
	new -i pptpd{$i} pt{$i} pt{$i}
1075
	set ipcp ranges {$pptpdcfg['localip']}/32 {$clientip}/32
1076
	load pts
1077

    
1078
EOD;
1079
			}
1080

    
1081
			$mpdconf .=<<<EOD
1082

    
1083
pts:
1084
	set iface disable on-demand
1085
	set iface enable proxy-arp
1086
	set iface enable tcpmssfix
1087
	set iface idle 1800
1088
	set iface up-script /usr/local/sbin/vpn-linkup
1089
	set iface down-script /usr/local/sbin/vpn-linkdown
1090
	set bundle enable multilink
1091
	set bundle enable crypt-reqd
1092
	set link yes acfcomp protocomp
1093
	set link no pap chap
1094
	set link enable chap-msv2
1095
	set link mtu 1460
1096
	set link keep-alive 10 60
1097
	set ipcp yes vjcomp
1098
	set bundle enable compression
1099
	set ccp yes mppc
1100
	set ccp yes mpp-e128
1101
	set ccp yes mpp-stateless
1102

    
1103
EOD;
1104

    
1105
			if (!isset ($pptpdcfg['req128'])) {
1106
				$mpdconf .=<<<EOD
1107
	set ccp yes mpp-e40
1108
	set ccp yes mpp-e56
1109

    
1110
EOD;
1111
			}
1112

    
1113
			if  (isset($pptpdcfg["wins"]) && $pptpdcfg['wins'] != "")
1114
				$mpdconf  .=  "	set ipcp nbns {$pptpdcfg['wins']}\n";
1115

    
1116
			if (!empty($pptpdcfg['dns1'])) {
1117
				$mpdconf .= "	set ipcp dns " . $pptpdcfg['dns1'];
1118
				if (!empty($pptpdcfg['dns2']))
1119
					$mpdconf .= " " . $pptpdcfg['dns2'];
1120
				$mpdconf .= "\n";
1121
			} elseif (isset ($config['dnsmasq']['enable'])) {
1122
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1123
				if ($syscfg['dnsserver'][0])
1124
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1125
				$mpdconf .= "\n";
1126
			} elseif (isset($config['unbound']['enable'])) {
1127
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1128
				if ($syscfg['dnsserver'][0])
1129
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1130
				$mpdconf .= "\n";
1131
			} elseif (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1132
					$mpdconf .= "	set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n";
1133
			}
1134

    
1135
			if (isset ($pptpdcfg['radius']['server']['enable'])) {
1136
				$authport = (isset($pptpdcfg['radius']['server']['port']) && strlen($pptpdcfg['radius']['server']['port']) > 1) ? $pptpdcfg['radius']['server']['port'] : 1812;
1137
				$acctport = $authport + 1;
1138
				$mpdconf .=<<<EOD
1139
	set radius server {$pptpdcfg['radius']['server']['ip']} "{$pptpdcfg['radius']['server']['secret']}" {$authport} {$acctport}
1140

    
1141
EOD;
1142
			if (isset ($pptpdcfg['radius']['server2']['enable'])) {
1143
				$authport = (isset($pptpdcfg['radius']['server2']['port']) && strlen($pptpdcfg['radius']['server2']['port']) > 1) ? $pptpdcfg['radius']['server2']['port'] : 1812;
1144
				$acctport = $authport + 1;
1145
				$mpdconf .=<<<EOD
1146
	set radius server {$pptpdcfg['radius']['server2']['ip']} "{$pptpdcfg['radius']['server2']['secret2']}" {$authport} {$acctport}
1147

    
1148
EOD;
1149
			}
1150
			$mpdconf .=<<<EOD
1151
	set radius retries 3
1152
	set radius timeout 10
1153
	set auth enable radius-auth
1154

    
1155
EOD;
1156

    
1157
				if (isset ($pptpdcfg['radius']['accounting'])) {
1158
					$mpdconf .=<<<EOD
1159
	set auth enable radius-acct
1160
	set radius acct-update 300
1161

    
1162
EOD;
1163
				}
1164
			}
1165

    
1166
			fwrite($fd, $mpdconf);
1167
			fclose($fd);
1168
			unset($mpdconf);
1169

    
1170
			/* write mpd.links */
1171
			$fd = fopen("{$g['varetc_path']}/pptp-vpn/mpd.links", "w");
1172
			if (!$fd) {
1173
				printf(gettext("Error: cannot open mpd.links in vpn_pptpd_configure().") . "\n");
1174
				return 1;
1175
			}
1176

    
1177
			$mpdlinks = "";
1178

    
1179
			for ($i = 0; $i < $pptpdcfg['n_pptp_units']; $i++) {
1180
				$mpdlinks .=<<<EOD
1181

    
1182
pt{$i}:
1183
	set link type pptp
1184
	set pptp enable incoming
1185
	set pptp disable originate
1186
	set pptp disable windowing
1187

    
1188
EOD;
1189
			}
1190

    
1191
			fwrite($fd, $mpdlinks);
1192
			fclose($fd);
1193
			unset($mpdlinks);
1194

    
1195
			/* write mpd.secret */
1196
			$fd = fopen("{$g['varetc_path']}/pptp-vpn/mpd.secret", "w");
1197
			if (!$fd) {
1198
				printf(gettext("Error: cannot open mpd.secret in vpn_pptpd_configure().") . "\n");
1199
				return 1;
1200
			}
1201

    
1202
			$mpdsecret = "";
1203

    
1204
			if (is_array($pptpdcfg['user'])) {
1205
				foreach ($pptpdcfg['user'] as $user) {
1206
					$pass = str_replace('\\', '\\\\', $user['password']);
1207
					$pass = str_replace('"', '\"', $pass);
1208
					$mpdsecret .= "{$user['name']} \"{$pass}\" {$user['ip']}\n";
1209
				}
1210
			}
1211

    
1212
			fwrite($fd, $mpdsecret);
1213
			fclose($fd);
1214
			unset($mpdsecret);
1215
			chmod("{$g['varetc_path']}/pptp-vpn/mpd.secret", 0600);
1216

    
1217
			vpn_netgraph_support();
1218

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

    
1222
			break;
1223

    
1224
		case 'redir' :
1225
			break;
1226
	}
1227

    
1228
	if (platform_booting())
1229
		echo "done\n";
1230

    
1231
	return 0;
1232
}
1233

    
1234
function vpn_pppoes_configure() {
1235
	global $config;
1236

    
1237
	if (is_array($config['pppoes']['pppoe'])) {
1238
		foreach ($config['pppoes']['pppoe'] as $pppoe)
1239
			vpn_pppoe_configure($pppoe);
1240
	}
1241
}
1242

    
1243
function vpn_pppoe_configure(&$pppoecfg) {
1244
	global $config, $g;
1245

    
1246
	$syscfg = $config['system'];
1247

    
1248
	/* create directory if it does not exist */
1249
	if (!is_dir("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn"))
1250
		mkdir("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn");
1251

    
1252
	if (platform_booting()) {
1253
		if (!$pppoecfg['mode'] || ($pppoecfg['mode'] == "off"))
1254
			return 0;
1255

    
1256
		echo gettext("Configuring PPPoE Server service... ");
1257
	} else {
1258
		/* kill mpd */
1259
		killbypid("{$g['varrun_path']}/pppoe{$pppoecfg['pppoeid']}-vpn.pid");
1260

    
1261
		/* wait for process to die */
1262
		sleep(2);
1263

    
1264
	}
1265

    
1266
	switch ($pppoecfg['mode']) {
1267

    
1268
		case 'server' :
1269

    
1270
			$pppoe_interface = get_real_interface($pppoecfg['interface']);
1271

    
1272
			if ($pppoecfg['paporchap'] == "chap")
1273
				$paporchap = "set link enable chap";
1274
			else
1275
				$paporchap = "set link enable pap";
1276

    
1277
			/* write mpd.conf */
1278
			$fd = fopen("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn/mpd.conf", "w");
1279
			if (!$fd) {
1280
				printf(gettext("Error: cannot open mpd.conf in vpn_pppoe_configure().") . "\n");
1281
				return 1;
1282
			}
1283
			$mpdconf = "\n\n";
1284
			$mpdconf .= "poes:\n";
1285

    
1286
			for ($i = 0; $i < $pppoecfg['n_pppoe_units']; $i++) {
1287
				$mpdconf .= "	load poes{$pppoecfg['pppoeid']}{$i}\n";
1288
			}
1289

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

    
1292
				$clientip = long2ip32(ip2long($pppoecfg['remoteip']) + $i);
1293

    
1294
				if (isset($pppoecfg['radius']['radiusissueips']) && isset($pppoecfg['radius']['server']['enable'])) {
1295
					$isssue_ip_type = "set ipcp ranges {$pppoecfg['localip']}/32 0.0.0.0/0";
1296
				} else {
1297
					$isssue_ip_type = "set ipcp ranges {$pppoecfg['localip']}/32 {$clientip}/32";
1298
				}
1299

    
1300
				$mpdconf .=<<<EOD
1301

    
1302
poes{$pppoecfg['pppoeid']}{$i}:
1303
	new -i poes{$pppoecfg['pppoeid']}{$i} poes{$pppoecfg['pppoeid']}{$i} poes{$pppoecfg['pppoeid']}{$i}
1304
	{$isssue_ip_type}
1305
	load pppoe_standard
1306

    
1307
EOD;
1308
			}
1309

    
1310
			$mpdconf .=<<<EOD
1311

    
1312
pppoe_standard:
1313
	set bundle no multilink
1314
	set bundle enable compression
1315
	set auth max-logins 1
1316
	set iface up-script /usr/local/sbin/vpn-linkup
1317
	set iface down-script /usr/local/sbin/vpn-linkdown
1318
	set iface idle 0
1319
	set iface disable on-demand
1320
	set iface disable proxy-arp
1321
	set iface enable tcpmssfix
1322
	set iface mtu 1500
1323
	set link no pap chap
1324
	{$paporchap}
1325
	set link keep-alive 60 180
1326
	set ipcp yes vjcomp
1327
	set ipcp no vjcomp
1328
	set link max-redial -1
1329
	set link mtu 1492
1330
	set link mru 1492
1331
	set ccp yes mpp-e40
1332
	set ccp yes mpp-e128
1333
	set ccp yes mpp-stateless
1334
	set link latency 1
1335
	#set ipcp dns 10.10.1.3
1336
	#set bundle accept encryption
1337

    
1338
EOD;
1339

    
1340
			if (!empty($pppoecfg['dns1'])) {
1341
				$mpdconf .= "	set ipcp dns " . $pppoecfg['dns1'];
1342
				if (!empty($pppoecfg['dns2']))
1343
					$mpdconf .= " " . $pppoecfg['dns2'];
1344
				$mpdconf .= "\n";
1345
			} elseif (isset ($config['dnsmasq']['enable'])) {
1346
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1347
				if ($syscfg['dnsserver'][0])
1348
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1349
				$mpdconf .= "\n";
1350
			} elseif (isset ($config['unbound']['enable'])) {
1351
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1352
				if ($syscfg['dnsserver'][0])
1353
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1354
				$mpdconf .= "\n";
1355
			} elseif (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1356
					$mpdconf .= "	set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n";
1357
			}
1358

    
1359
			if (isset ($pppoecfg['radius']['server']['enable'])) {
1360
				$radiusport = "";
1361
				$radiusacctport = "";
1362
				if (isset($pppoecfg['radius']['server']['port']))
1363
					$radiusport = $pppoecfg['radius']['server']['port'];
1364
				if (isset($pppoecfg['radius']['server']['acctport']))
1365
					$radiusacctport = $pppoecfg['radius']['server']['acctport'];
1366
				$mpdconf .=<<<EOD
1367
	set radius server {$pppoecfg['radius']['server']['ip']} "{$pppoecfg['radius']['server']['secret']}" {$radiusport} {$radiusacctport}
1368
	set radius retries 3
1369
	set radius timeout 10
1370
	set auth enable radius-auth
1371

    
1372
EOD;
1373

    
1374
				if (isset ($pppoecfg['radius']['accounting'])) {
1375
					$mpdconf .=<<<EOD
1376
	set auth enable radius-acct
1377

    
1378
EOD;
1379
				}
1380
			}
1381

    
1382
			fwrite($fd, $mpdconf);
1383
			fclose($fd);
1384
			unset($mpdconf);
1385

    
1386
			/* write mpd.links */
1387
			$fd = fopen("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn/mpd.links", "w");
1388
			if (!$fd) {
1389
				printf(gettext("Error: cannot open mpd.links in vpn_pppoe_configure().") . "\n");
1390
				return 1;
1391
			}
1392

    
1393
			$mpdlinks = "";
1394

    
1395
			for ($i = 0; $i < $pppoecfg['n_pppoe_units']; $i++) {
1396
				$mpdlinks .=<<<EOD
1397

    
1398
poes{$pppoecfg['pppoeid']}{$i}:
1399
	set phys type pppoe
1400
	set pppoe iface {$pppoe_interface}
1401
	set pppoe service "*"
1402
	set pppoe disable originate
1403
	set pppoe enable incoming
1404

    
1405
EOD;
1406
			}
1407

    
1408
			fwrite($fd, $mpdlinks);
1409
			fclose($fd);
1410
			unset($mpdlinks);
1411

    
1412
			if ($pppoecfg['username']) {
1413
				/* write mpd.secret */
1414
				$fd = fopen("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn/mpd.secret", "w");
1415
				if (!$fd) {
1416
					printf(gettext("Error: cannot open mpd.secret in vpn_pppoe_configure().") . "\n");
1417
					return 1;
1418
				}
1419

    
1420
				$mpdsecret = "\n\n";
1421

    
1422
				if (!empty($pppoecfg['username'])) {
1423
					$item = explode(" ", $pppoecfg['username']);
1424
					foreach($item as $userdata) {
1425
						$data = explode(":", $userdata);
1426
						$mpdsecret .= "{$data[0]} \"" . base64_decode($data[1]) . "\" {$data[2]}\n";
1427
					}
1428
				}
1429

    
1430
				fwrite($fd, $mpdsecret);
1431
				fclose($fd);
1432
				unset($mpdsecret);
1433
				chmod("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn/mpd.secret", 0600);
1434
			}
1435

    
1436
			/* Check if previous instance is still up */
1437
			while (file_exists("{$g['varrun_path']}/pppoe{$pppoecfg['pppoeid']}-vpn.pid") && isvalidpid("{$g['varrun_path']}/pppoe{$pppoecfg['pppoeid']}-vpn.pid"))
1438
				killbypid("{$g['varrun_path']}/pppoe{$pppoecfg['pppoeid']}-vpn.pid");
1439

    
1440
			/* Get support for netgraph(4) from the nic */
1441
			pfSense_ngctl_attach(".", $pppoe_interface);
1442
			/* fire up mpd */
1443
			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");
1444

    
1445
			break;
1446
	}
1447

    
1448
	if (platform_booting())
1449
		echo gettext("done") . "\n";
1450

    
1451
	return 0;
1452
}
1453

    
1454
function vpn_l2tp_configure() {
1455
	global $config, $g;
1456

    
1457
	$syscfg = $config['system'];
1458
	$l2tpcfg = $config['l2tp'];
1459

    
1460
	/* create directory if it does not exist */
1461
	if (!is_dir("{$g['varetc_path']}/l2tp-vpn"))
1462
		mkdir("{$g['varetc_path']}/l2tp-vpn");
1463

    
1464
	if (platform_booting()) {
1465
		if (!$l2tpcfg['mode'] || ($l2tpcfg['mode'] == "off"))
1466
			return 0;
1467

    
1468
		echo gettext("Configuring l2tp VPN service... ");
1469
	} else {
1470
		/* kill mpd */
1471
		killbypid("{$g['varrun_path']}/l2tp-vpn.pid");
1472

    
1473
		/* wait for process to die */
1474
		sleep(8);
1475

    
1476
	}
1477

    
1478
	/* make sure l2tp-vpn directory exists */
1479
	if (!file_exists("{$g['varetc_path']}/l2tp-vpn"))
1480
		mkdir("{$g['varetc_path']}/l2tp-vpn");
1481

    
1482
	switch ($l2tpcfg['mode']) {
1483

    
1484
		case 'server' :
1485
			if ($l2tpcfg['paporchap'] == "chap")
1486
				$paporchap = "set link enable chap";
1487
			else
1488
				$paporchap = "set link enable pap";
1489

    
1490
			/* write mpd.conf */
1491
			$fd = fopen("{$g['varetc_path']}/l2tp-vpn/mpd.conf", "w");
1492
			if (!$fd) {
1493
				printf(gettext("Error: cannot open mpd.conf in vpn_l2tp_configure().") . "\n");
1494
				return 1;
1495
			}
1496
			$mpdconf = "\n\n";
1497
			$mpdconf .=<<<EOD
1498
l2tps:
1499

    
1500
EOD;
1501

    
1502
			for ($i = 0; $i < $l2tpcfg['n_l2tp_units']; $i++) {
1503
				$mpdconf .= "	load l2tp{$i}\n";
1504
			}
1505

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

    
1508
				$clientip = long2ip32(ip2long($l2tpcfg['remoteip']) + $i);
1509

    
1510
				if (isset ($l2tpcfg['radius']['radiusissueips']) && isset ($l2tpcfg['radius']['enable'])) {
1511
					$isssue_ip_type = "set ipcp ranges {$l2tpcfg['localip']}/32 0.0.0.0/0";
1512
				} else {
1513
					$isssue_ip_type = "set ipcp ranges {$l2tpcfg['localip']}/32 {$clientip}/32";
1514
				}
1515

    
1516
				$mpdconf .=<<<EOD
1517

    
1518
l2tp{$i}:
1519
	new -i l2tp{$i} l2tp{$i} l2tp{$i}
1520
	{$isssue_ip_type}
1521
	load l2tp_standard
1522

    
1523
EOD;
1524
			}
1525

    
1526
			$mpdconf .=<<<EOD
1527

    
1528
l2tp_standard:
1529
	set bundle disable multilink
1530
	set bundle enable compression
1531
	set bundle yes crypt-reqd
1532
	set ipcp yes vjcomp
1533
	# set ipcp ranges 131.188.69.161/32 131.188.69.170/28
1534
	set ccp yes mppc
1535
	set iface disable on-demand
1536
	set iface enable proxy-arp
1537
	set iface up-script /usr/local/sbin/vpn-linkup
1538
	set iface down-script /usr/local/sbin/vpn-linkdown
1539
	set link yes acfcomp protocomp
1540
	set link no pap chap
1541
	set link enable chap
1542
	set link keep-alive 10 180
1543

    
1544
EOD;
1545

    
1546
			if (is_ipaddr($l2tpcfg['wins'])) {
1547
				$mpdconf .= "	set ipcp nbns {$l2tpcfg['wins']}\n";
1548
			}
1549
			if (is_ipaddr($l2tpcfg['dns1'])) {
1550
				$mpdconf .= "	set ipcp dns " . $l2tpcfg['dns1'];
1551
				if (is_ipaddr($l2tpcfg['dns2']))
1552
					$mpdconf .= " " . $l2tpcfg['dns2'];
1553
				$mpdconf .= "\n";
1554
			} elseif (isset ($config['dnsmasq']['enable'])) {
1555
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1556
				if ($syscfg['dnsserver'][0])
1557
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1558
				$mpdconf .= "\n";
1559
			} elseif (isset ($config['unbound']['enable'])) {
1560
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1561
				if ($syscfg['dnsserver'][0])
1562
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1563
				$mpdconf .= "\n";
1564
			} elseif (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1565
					$mpdconf .= "	set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n";
1566
			}
1567

    
1568
			if (isset ($l2tpcfg['radius']['enable'])) {
1569
				$mpdconf .=<<<EOD
1570
	set radius server {$l2tpcfg['radius']['server']} "{$l2tpcfg['radius']['secret']}"
1571
	set radius retries 3
1572
	set radius timeout 10
1573
	set auth enable radius-auth
1574

    
1575
EOD;
1576

    
1577
				if (isset ($l2tpcfg['radius']['accounting'])) {
1578
					$mpdconf .=<<<EOD
1579
	set auth enable radius-acct
1580

    
1581
EOD;
1582
				}
1583
			}
1584

    
1585
			fwrite($fd, $mpdconf);
1586
			fclose($fd);
1587
			unset($mpdconf);
1588

    
1589
			/* write mpd.links */
1590
			$fd = fopen("{$g['varetc_path']}/l2tp-vpn/mpd.links", "w");
1591
			if (!$fd) {
1592
				printf(gettext("Error: cannot open mpd.links in vpn_l2tp_configure().") . "\n");
1593
				return 1;
1594
			}
1595

    
1596
			$mpdlinks = "";
1597

    
1598
			for ($i = 0; $i < $l2tpcfg['n_l2tp_units']; $i++) {
1599
				$mpdlinks .=<<<EOD
1600

    
1601
l2tp{$i}:
1602
	set link type l2tp
1603
	set l2tp enable incoming
1604
	set l2tp disable originate
1605

    
1606
EOD;
1607
			if (!empty($l2tpcfg['secret']))
1608
					$mpdlinks .= "set l2tp secret {$l2tpcfg['secret']}\n";
1609
			}
1610

    
1611
			fwrite($fd, $mpdlinks);
1612
			fclose($fd);
1613
			unset($mpdlinks);
1614

    
1615
			/* write mpd.secret */
1616
			$fd = fopen("{$g['varetc_path']}/l2tp-vpn/mpd.secret", "w");
1617
			if (!$fd) {
1618
				printf(gettext("Error: cannot open mpd.secret in vpn_l2tp_configure().") . "\n");
1619
				return 1;
1620
			}
1621

    
1622
			$mpdsecret = "\n\n";
1623

    
1624
			if (is_array($l2tpcfg['user'])) {
1625
				foreach ($l2tpcfg['user'] as $user)
1626
					$mpdsecret .= "{$user['name']} \"{$user['password']}\" {$user['ip']}\n";
1627
			}
1628

    
1629
			fwrite($fd, $mpdsecret);
1630
			fclose($fd);
1631
			unset($mpdsecret);
1632
			chmod("{$g['varetc_path']}/l2tp-vpn/mpd.secret", 0600);
1633

    
1634
			vpn_netgraph_support();
1635

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

    
1639
			break;
1640

    
1641
		case 'redir' :
1642
			break;
1643
	}
1644

    
1645
	if (platform_booting())
1646
		echo "done\n";
1647

    
1648
	return 0;
1649
}
1650

    
1651
function vpn_ipsec_configure_preferoldsa() {
1652
	global $config;
1653
	if(isset($config['ipsec']['preferoldsa']))
1654
		set_single_sysctl("net.key.preferred_oldsa", "-30");
1655
	else
1656
		set_single_sysctl("net.key.preferred_oldsa", "0");
1657
}
1658

    
1659
?>
(59-59/68)