Project

General

Profile

Download (49.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:	/usr/bin/killall	/usr/local/sbin/sasyncd	/sbin/ifconfig	/sbin/sysctl
38
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/setkey	/sbin/route	/bin/mkdir
39
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/racoonctl	/usr/local/sbin/racoon
40
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/filterdns	/usr/local/sbin/mpd4	
41
	pfSense_MODULE:	vpn
42
*/
43

    
44
/* include all configuration functions */
45

    
46
function vpn_ipsec_failover_configure() {
47
	global $config, $g;
48

    
49

    
50
	if (is_array($config['installedpackages']['sasyncd'])) {
51
		$sasyncd_text = "";
52
		foreach ($config['installedpackages']['sasyncd']['config'] as $sasyncd) {
53
			$enabled = isset ($sasyncd['enable']);
54
			if (!$enabled)
55
				return;
56
			if ($sasyncd['peerip'] <> "")
57
				$sasyncd_text .= "peer {$sasyncd['peerip']}\n";
58
			if ($sasyncd['interface'])
59
				$sasyncd_text .= "carp interface {$sasyncd['interface']}\n";
60
			if ($sasyncd['sharedkey'] <> "")
61
				$sasyncd_text .= "sharedkey {$sasyncd['sharedkey']}\n";
62
			if ($sasyncd['mode'] <> "")
63
				$sasyncd_text .= "mode {$sasyncd['mode']}\n";
64
			if ($sasyncd['listenon'] <> "")
65
				$sasyncd_text .= "listen on {$sasyncd['listenon']}\n";
66
			if ($sasyncd['flushmodesync'] <> "")
67
				$sasyncd_text .= "flushmode sync {$sasyncd['flushmodesync']}\n";
68
		}
69

    
70
		file_put_contents("{$g['varetc_path']}/sasyncd.conf", $sasyncd_text);
71
		chmod("{$g['varetc_path']}/sasyncd.conf", 0600);
72

    
73
		if(is_process_running("sasyncd"))
74
			mwexec("killall sasyncd", true);
75

    
76
		/* launch sasyncd, oh wise one */
77
		mwexec_bg("/usr/local/sbin/sasyncd -d -v -v -v");
78
	}
79
}
80

    
81
function vpn_ipsec_configure($ipchg = false)
82
{
83
	global $config, $g, $sa, $sn, $p1_ealgos, $p2_ealgos;
84

    
85
	/* get the automatic ping_hosts.sh ready */
86
	unlink_if_exists("{$g['vardb_path']}/ipsecpinghosts");
87
	touch("{$g['vardb_path']}/ipsecpinghosts");
88

    
89
	vpn_ipsec_configure_preferoldsa();
90

    
91
	$syscfg = $config['system'];
92
	$ipseccfg = $config['ipsec'];
93
	$a_phase1 = $config['ipsec']['phase1'];
94
	$a_phase2 = $config['ipsec']['phase2'];
95
	$a_client = $config['ipsec']['client'];
96

    
97
	if (!isset($ipseccfg['enable'])) {
98
		mwexec("/sbin/ifconfig enc0 down");
99

    
100
		/* send a SIGKILL to be sure */
101
		sigkillbypid("{$g['varrun_path']}/racoon.pid", "KILL");
102

    
103
		/* kill racoon */
104
		if(is_process_running("racoon"))
105
			mwexec("/usr/bin/killall racoon", true);
106
		killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
107

    
108
		/* wait for racoon process to die */
109
		sleep(2);
110

    
111
		/* flush SPD and SAD */
112
		mwexec("/usr/local/sbin/setkey -F");
113
		mwexec("/usr/local/sbin/setkey -FP");
114

    
115
		/* disallow IPSEC, it is off */
116
		exec("/sbin/sysctl net.inet.ip.ipsec_in_use=0");
117

    
118
		return true;
119
	} else {
120
		mwexec("/sbin/ifconfig enc0 up");
121
		mwexec("/sbin/sysctl net.inet.ip.ipsec_in_use=1");
122

    
123
		if ($g['booting'])
124
			echo "Configuring IPsec VPN... ";
125

    
126
		/* fastforwarding is not compatible with ipsec tunnels */
127
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=0");
128

    
129
		/* resolve all local, peer addresses and setup pings */
130
		$ipmap = array();
131
		$rgmap = array();
132
		$filterdns_list = array();
133
		if (is_array($a_phase1) && count($a_phase1)) {
134

    
135
			$ipsecpinghosts = "";
136
			/* step through each phase1 entry */
137
			foreach ($a_phase1 as $ph1ent) {
138
				if (isset($ph1ent['disabled']))
139
					continue;
140

    
141
				$ep = ipsec_get_phase1_src($ph1ent);
142
				if (!$ep)
143
					continue;
144

    
145
				if(!in_array($ep,$ipmap))
146
					$ipmap[] = $ep;
147

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

    
151
				if (isset ($ph1ent['mobile']))
152
					continue;
153

    
154
				$rg = $ph1ent['remote-gateway'];
155

    
156
				if (!is_ipaddr($rg)) {
157
					$filterdns_list[] = "{$rg}";
158
					add_hostname_to_watch($rg);
159
					if(! $g['booting'])
160
						$rg = resolve_retry($rg);
161
					if (!is_ipaddr($rg))
162
						continue;
163
				}
164
				if(array_search($rg, $rgmap)) {
165
					log_error("The remote gateway {$rg} already exists on another phase 1 entry");
166
					continue;
167
				}
168
				$rgmap[$ph1ent['remote-gateway']] = $rg;
169

    
170
				/* step through each phase2 entry */
171
				foreach ($a_phase2 as $ph2ent) {
172

    
173
					$ikeid = $ph2ent['ikeid'];
174

    
175
					if (isset($ph2ent['disabled']))
176
						continue;
177

    
178
					if ($ikeid != $ph1ent['ikeid'])
179
						continue;
180

    
181
					/* add an ipsec pinghosts entry */
182
					if ($ph2ent['pinghost']) {
183
						$iflist = get_configured_interface_list();
184
						foreach ($iflist as $ifent => $ifname) {
185
							$interface_ip = get_interface_ip($ifent);
186
							$local_subnet = ipsec_idinfo_to_cidr($ph2ent['localid'], true);
187
							if (ip_in_subnet($interface_ip, $local_subnet)) {
188
								$srcip = $interface_ip;
189
								break;
190
							}
191
						}
192
						$dstip = $ph2ent['pinghost'];
193
						if (is_ipaddr($srcip))
194
							$ipsecpinghosts .= "{$srcip}|{$dstip}|3\n";
195
					}
196
				}
197
				$pfd = fopen("{$g['vardb_path']}/ipsecpinghosts", "w");
198
				if ($pfd) {
199
					fwrite($pfd, $ipsecpinghosts);
200
					fclose($pfd);
201
				}
202
				
203
			}
204
		}
205

    
206
		/* generate CA certificates files */
207
		if (is_array($config['ca']) && count($config['ca'])) {
208
			foreach ($config['ca'] as $ca) {
209
				if (!isset($ca['crt'])) {
210
					log_error("Error: Invalid certificate info for {$ca['descr']}");
211
					continue;
212
				}
213
				$cert = base64_decode($ca['crt']);
214
				$x509cert = openssl_x509_parse(openssl_x509_read($cert));
215
				if (!is_array($x509cert) || !isset($x509cert['hash'])) {
216
					log_error("Error: Invalid certificate hash info for {$ca['descr']}");
217
					continue;
218
				}
219
				$fname = $g['varetc_path']."/".$x509cert['hash'].".0";
220
				if (!file_put_contents($fname, $cert)) {
221
					log_error("Error: Cannot write IPsec CA file for {$ca['descr']}");
222
					continue;
223
				}
224
			}
225
		}
226
		
227
		/* generate psk.txt */
228
		$fd = fopen("{$g['varetc_path']}/psk.txt", "w");
229
		if (!$fd) {
230
			printf("Error: cannot open psk.txt in vpn_ipsec_configure().\n");
231
			return 1;
232
		}
233

    
234
		$pskconf = "";
235

    
236
		if (is_array($a_phase1) && count($a_phase1)) {
237
			foreach ($a_phase1 as $ph1ent) {
238

    
239
				if (isset($ph1ent['disabled']))
240
					continue;
241

    
242
				if (strstr($ph1ent['authentication_method'],'rsa'))
243
					continue;
244

    
245
				$peerid_type = $ph1ent['peerid_type'];
246

    
247
				switch ($peerid_type) {
248
					case "peeraddress":
249
						$peerid_type = "address";
250
						$peerid_data = $rgmap[$ph1ent['remote-gateway']];
251
						break;
252

    
253
					case "address";
254
						$peerid_data = $ph1ent['peerid_data'];
255
						break;
256

    
257
					case "fqdn";
258
					case "keyid tag";
259
					case "user_fqdn";
260
						$peerid_data = $ph1ent['peerid_data'];
261
						break;
262
				}
263

    
264
				if (!empty($peerid_data) && !empty($ph1ent['pre-shared-key']))
265
					$pskconf .= trim($peerid_data) . "\t" . trim($ph1ent['pre-shared-key']) . "\n";
266
			}
267
		}
268

    
269
		/* Add user PSKs */
270
		foreach ($config['system']['user'] as $user) {
271
			if (!empty($user['ipsecpsk'])) {
272
				$pskconf .= "{$user['name']}\t{$user['ipsecpsk']}\n";
273
			}
274
		}
275

    
276
		/* add PSKs for mobile clients */
277
		if (is_array($ipseccfg['mobilekey'])) {
278
			foreach ($ipseccfg['mobilekey'] as $key) {
279
				$pskconf .= "{$key['ident']}\t{$key['pre-shared-key']}\n";
280
			}
281
		}
282

    
283
		fwrite($fd, $pskconf);
284
		fclose($fd);
285
		chmod("{$g['varetc_path']}/psk.txt", 0600);
286
			
287
		/* begin racoon.conf */
288
		if ((is_array($a_phase1) && count($a_phase1)) ||
289
			(is_array($a_phase2) && count($a_phase2))) {
290

    
291
			$fd = fopen("{$g['varetc_path']}/racoon.conf", "w");
292
			if (!$fd) {
293
				printf("Error: cannot open racoon.conf in vpn_ipsec_configure().\n");
294
				return 1;
295
			}
296

    
297
			$racoonconf = "# This file is automatically generated. Do not edit\n";			
298
			$racoonconf .= "path pre_shared_key \"{$g['varetc_path']}/psk.txt\";\n\n";
299
			$racoonconf .= "path certificate  \"{$g['varetc_path']}\";\n\n";
300

    
301
			/* begin listen section */
302
			if (count($ipmap)) {
303
				$racoonconf .= "\nlisten\n";
304
				$racoonconf .= "{\n";
305
				$racoonconf .= "	adminsock \"/var/db/racoon/racoon.sock\" \"root\" \"wheel\" 0660;\n";
306
				foreach ($ipmap as $addr) {
307
					$racoonconf .= "\tisakmp {$addr} [500];\n";
308
					$racoonconf .= "\tisakmp_natt {$addr} [4500];\n";
309
				}
310
				$racoonconf .= "}\n\n";
311
			}
312

    
313
			/* begin mode_cfg section */
314
			if (is_array($a_client) && isset($a_client['enable'])) {
315

    
316
				$racoonconf .= "\nmode_cfg\n";
317
				$racoonconf .= "{\n";
318

    
319
				if ($a_client['user_source'])
320
					$racoonconf .= "\tauth_source {$a_client['user_source']};\n";
321
				if ($a_client['group_source'])
322
					$racoonconf .= "\tgroup_source {$a_client['group_source']};\n";
323

    
324
				if ($a_client['pool_address'] && $a_client['pool_netbits']) {
325
					$pool_address = $a_client['pool_address'];
326
					$pool_netmask = gen_subnet_mask($a_client['pool_netbits']);
327

    
328
					$pool_address = long2ip32(ip2long($pool_address)+1);
329
					$pool_size = (~ip2long($pool_netmask) & 0xFFFFFFFF) - 2;
330

    
331
					$racoonconf .= "\tpool_size {$pool_size};\n";
332
					$racoonconf .= "\tnetwork4 {$pool_address};\n";
333
					$racoonconf .= "\tnetmask4 {$pool_netmask};\n";
334
				}
335

    
336
				if (isset($a_client['net_list'])) {
337

    
338
					$net_list = '';
339

    
340
					foreach ($a_phase2 as $ph2ent) {
341

    
342
						if (isset($ph2ent['disabled']))
343
							continue;
344

    
345
						if (!isset($ph2ent['mobile']))
346
							continue;
347

    
348
						$localid = ipsec_idinfo_to_cidr($ph2ent['localid'],true);
349

    
350
						if ($net_list)
351
							$net_list .= ", ";
352
						$net_list .= $localid;
353
					}
354

    
355
					if ($net_list)
356
						$racoonconf .= "\tsplit_network include {$net_list};\n";
357
				}
358

    
359
				if ($a_client['dns_server1'])
360
					$racoonconf .= "\tdns4 {$a_client['dns_server1']};\n";
361
				if ($a_client['dns_server2'])
362
					$racoonconf .= "\tdns4 {$a_client['dns_server2']};\n";
363
				if ($a_client['dns_server3'])
364
					$racoonconf .= "\tdns4 {$a_client['dns_server3']};\n";
365
				if ($a_client['dns_server4'])
366
					$racoonconf .= "\tdns4 {$a_client['dns_server4']};\n";
367

    
368
				if ($a_client['wins_server1'])
369
					$racoonconf .= "\twins4 {$a_client['wins_server1']};\n";
370
				if ($a_client['wins_server2'])
371
					$racoonconf .= "\twins4 {$a_client['wins_server2']};\n";
372

    
373
				if ($a_client['dns_domain']) {
374
					$racoonconf .= "\tdefault_domain \"{$a_client['dns_domain']}\";\n";
375
					$racoonconf .= "\tsplit_dns \"{$a_client['dns_domain']}\";\n";
376
				}
377

    
378
				if ($a_client['pfs_group'])
379
					$racoonconf .= "\tpfs_group {$a_client['pfs_group']};\n";
380

    
381
				if ($a_client['login_banner']) {
382
					$fn = "{$g['varetc_path']}/racoon.motd";
383
					$fd1 = fopen($fn, "w");
384
					if (!$fd1) {
385
						printf("Error: cannot open server{$fn} in vpn.\n");
386
						return 1;
387
					}
388

    
389
					fwrite($fd1, $a_client['login_banner']);
390
					fclose($fd1);
391

    
392
					$racoonconf .= "\tbanner \"{$fn}\";\n";
393
				}
394

    
395
				if (isset($a_client['save_passwd']))
396
					$racoonconf .= "\tsave_passwd on;\n";
397

    
398
				$racoonconf .= "}\n\n";
399
			}
400
			/* end mode_cfg section */
401

    
402
			/* begin remote sections */
403
			if (is_array($a_phase1) && count($a_phase1)) {
404
				/* begin remote */
405
				foreach ($a_phase1 as $ph1ent) {
406

    
407
					if (isset($ph1ent['disabled']))
408
						continue;
409

    
410
					if (isset($ph1ent['mobile']) && !isset($a_client['enable']))
411
						continue;
412

    
413
					$ikeid = $ph1ent['ikeid'];
414

    
415
					$ep = ipsec_get_phase1_src($ph1ent);
416
					if (!$ep)
417
						continue;
418

    
419
					if (!isset($ph1ent['mobile'])) {
420
						$rgip = $rgmap[$ph1ent['remote-gateway']];
421
						if (!$rgip)
422
							continue;
423
					}
424

    
425
					$myid_type = $ph1ent['myid_type'];
426

    
427
					switch ($myid_type) {
428

    
429
						case "myaddress":
430
							$myid_type = "address";
431
							$myid_data = $ep;
432
							break;
433

    
434
						case "dyn_dns":
435
							$myid_type = "address";
436
							$myid_data = gethostbyname($ph1ent['myid_data']);
437
							break;
438

    
439
						case "address";
440
							$myid_data = $ph1ent['myid_data'];
441
							break;
442

    
443
						case "fqdn";
444
						case "keyid tag";
445
						case "user_fqdn";
446
						case "asn1dn";
447
							$myid_data = $ph1ent['myid_data'];
448
							if( $myid_data )
449
								$myid_data = "\"".$myid_data."\"";
450
							break;
451
					}
452

    
453
					$peerid_type = $ph1ent['peerid_type'];
454

    
455
					switch ($peerid_type) {
456
						case "peeraddress":
457
							$peerid_type = "address";
458
							$peerid_data = $rgip;
459
							break;
460

    
461
						case "address";
462
							$peerid_data = $ph1ent['peerid_data'];
463
							break;
464

    
465
						case "fqdn";
466
						case "keyid tag";
467
						case "user_fqdn";
468
						case "asn1dn";
469
							$peerid_data = $ph1ent['peerid_data'];
470
							if( $peerid_data )
471
								$peerid_data = "\"".$peerid_data."\"";
472
							break;
473
					}
474

    
475
					$natt = "off";
476
					if (isset($ph1ent['nat_traversal']))
477
						$natt = $ph1ent['nat_traversal'];
478

    
479
					$init = "on";
480
					$genp = !empty($ph1ent['generate_policy']) ? $ph1ent['generate_policy'] : "off";
481
					$pcheck = !empty($ph1ent['proposal_check']) ? $ph1ent['proposal_check'] : $pcheck = "claim";
482
					$passive = "";
483
					if (isset($ph1ent['mobile'])) {
484
						$rgip = "anonymous";
485
						$passive = "passive on;";
486
						/* Mimic 1.2.3's behavior for pure-psk mobile tunnels */
487
						if ($ph1ent['authentication_method'] == "pre_shared_key") {
488
							$pcheck = !empty($ph1ent['proposal_check']) ? $ph1ent['proposal_check'] : $pcheck = "obey";
489
							$genp = !empty($ph1ent['generate_policy']) ? $ph1ent['generate_policy'] : "on";
490
						} else {
491
							$init = "off";
492
							$genp = !empty($ph1ent['generate_policy']) ? $ph1ent['generate_policy'] : "unique";
493
						}
494
					}
495

    
496
					$dpdline1 = '';
497
					$dpdline2 = '';
498
					if ($ph1ent['dpd_delay'] && $ph1ent['dpd_maxfail']) {
499
						$dpdline1 = "dpd_delay = {$ph1ent['dpd_delay']};";
500
						$dpdline2 = "dpd_maxfail = {$ph1ent['dpd_maxfail']};";
501
					}
502

    
503
					if (isset ($ph1ent['authentication_method']))
504
						$authmethod = $ph1ent['authentication_method'];
505
					else
506
						$authmethod = 'pre_shared_key';
507

    
508
					$certline = '';
509

    
510
					if (strstr($authmethod,'rsa')) {
511

    
512
						$cert = lookup_cert($ph1ent['certref']);
513

    
514
						if (!$cert)
515
						{
516
							log_error("Error: Invalid phase1 certificate reference for {$ph1ent['name']}");
517
							continue;
518
						}
519

    
520
						$certfile = "cert-".$ikeid.".crt";
521
						$certpath = $g['varetc_path']."/".$certfile;
522

    
523
						if (!file_put_contents($certpath, base64_decode($cert['crt'])))
524
						{
525
							log_error("Error: Cannot write phase1 certificate file for {$ph1ent['name']}");
526
							continue;
527
						}
528

    
529
						chmod($certpath, 0600);
530

    
531
						$keyfile = "cert-".$ikeid.".key";
532
						$keypath = $g['varetc_path']."/".$keyfile;
533

    
534
						if (!file_put_contents($keypath, base64_decode($cert['prv'])))
535
						{
536
							log_error("Error: Cannot write phase1 key file for {$ph1ent['name']}");
537
							continue;
538
						}
539

    
540
						chmod($keypath, 0600);
541

    
542
						$ca = lookup_ca($ph1ent['caref']);
543
						if ($ca) {
544
							$cafile = "ca-".$ikeid.".crt";
545
							$capath = $g['varetc_path']."/".$cafile;
546

    
547
							if (!file_put_contents($capath, base64_decode($ca['crt'])))
548
							{
549
								log_error("Error: Cannot write phase1 CA certificate file for {$ph1ent['name']}");
550
								continue;
551
							}
552

    
553
							chmod($capath, 0600);
554
							$caline = "ca_type x509 \"".basename($capath)."\";";
555
						}
556

    
557
						$certline = "certificate_type x509 \"".basename($certpath)."\" \"".basename($keypath)."\";";
558

    
559
					}
560

    
561
					$ealgos = '';
562
					$ealg_id = $ph1ent['encryption-algorithm']['name'];
563
					$ealg_kl = $ph1ent['encryption-algorithm']['keylen'];
564
					if ($ealg_kl)
565
						$ealgos = $ealgos.$ealg_id." ".$ealg_kl;
566
					else
567
						$ealgos = $ealgos.$ealg_id;
568

    
569
					$lifeline = '';
570
					if ($ph1ent['lifetime'])
571
						$lifeline = "lifetime time {$ph1ent['lifetime']} secs;";
572

    
573
					/* Only specify peer ID if we are not dealing with a mobile PSK-only tunnel */
574
					if (!(($ph1ent['authentication_method'] == "pre_shared_key") && isset($ph1ent['mobile']))) {
575
						$peerid_spec = "peers_identifier {$peerid_type} {$peerid_data};";
576
					}
577

    
578
					/* add remote section to configuration */
579

    
580
					$racoonconf .=<<<EOD
581

    
582
remote {$rgip}
583
{
584
	ph1id {$ikeid};
585
	exchange_mode {$ph1ent['mode']};
586
	my_identifier {$myid_type} {$myid_data};
587
	{$peerid_spec}
588
	ike_frag on;
589
	generate_policy = {$genp};
590
	initial_contact = {$init};
591
	nat_traversal = {$natt};
592
	{$certline}
593
	{$caline}
594
	{$dpdline1}
595
	{$dpdline2}
596
	support_proxy on;
597
	proposal_check {$pcheck};
598
	{$passive}
599

    
600
	proposal
601
	{
602
		authentication_method {$authmethod};
603
		encryption_algorithm ${ealgos};
604
		hash_algorithm {$ph1ent['hash-algorithm']};
605
		dh_group {$ph1ent['dhgroup']};
606
		${lifeline}
607
	}
608
}
609

    
610
EOD;
611
				}
612
				/* end remote */
613
			}
614
			/* end remote sections */
615
		
616
			/* begin sainfo sections */
617
			if (is_array($a_phase2) && count($a_phase2)) {
618

    
619
				/* begin sainfo */
620
				foreach ($a_phase2 as $ph2ent) {
621

    
622
					$ikeid = $ph2ent['ikeid'];
623

    
624
					if( !ipsec_lookup_phase1($ph2ent,$ph1ent))
625
						continue;
626

    
627
					if (isset($ph1ent['disabled']))
628
						continue;
629

    
630
					if (isset($ph2ent['disabled']))
631
						continue;
632

    
633
					if (isset($ph2ent['mobile']) && !isset($a_client['enable']))
634
						continue;
635

    
636
					if ($ph2ent['mode'] == 'tunnel') {
637

    
638
						$localid_type = $ph2ent['localid']['type'];
639
						$localid_data = ipsec_idinfo_to_cidr($ph2ent['localid']);
640
						/* Do not print localid in some cases, such as a pure-psk or psk/xauth single phase2 mobile tunnel */
641
						if (($localid_type == "none") ||
642
							(($ph1ent['authentication_method'] == "xauth_psk_server") ||
643
							($ph1ent['authentication_method'] == "pre_shared_key"))
644
							&& isset($ph1ent['mobile'])
645
							&& (ipsec_get_number_of_phase2($ikeid)==1))
646
							$localid_spec = " ";
647
						else {
648
							if ($localid_type != "address") {
649
								$localid_type = "subnet";
650
							}
651
							$localid_spec = $localid_type." ".$localid_data." any";
652
						}
653

    
654
						if (!isset($ph2ent['mobile'])) {
655
							$remoteid_type = $ph2ent['remoteid']['type'];
656
							if ($remoteid_type != "address")
657
								$remoteid_type = "subnet";
658

    
659
							$remoteid_data = ipsec_idinfo_to_cidr($ph2ent['remoteid']);
660
							$remoteid_spec = $remoteid_type." ".$remoteid_data." any";
661
						} else
662
							$remoteid_spec = "anonymous";
663

    
664
					} else {
665
						$rgip = $rgmap[$ph1ent['remote-gateway']];
666

    
667
						if ((($ph1ent['authentication_method'] == "xauth_psk_server") ||
668
							($ph1ent['authentication_method'] == "pre_shared_key"))
669
							&& isset($ph1ent['mobile']))
670
							$localid_spec = " ";
671
						else {
672
							$localid_data = ipsec_get_phase1_src($ph1ent);
673
							if($ph2ent['mode'] == 'transport') { $localid_data="$localid_data any"; }
674
							$localid_spec = "address {$localid_data}";
675
						}
676
						if (!isset($ph2ent['mobile'])) {
677
							$remoteid_data = $rgmap[$ph1ent['remote-gateway']];
678
							if($ph2ent['mode'] == 'transport') { $remoteid_data="$remoteid_data any"; }
679
							$remoteid_spec = "address {$remoteid_data}";
680
						} else
681
							$remoteid_spec = "anonymous";
682
					}
683

    
684
					if($ph2ent['protocol'] == 'esp') {
685

    
686
						$ealgos = '';
687

    
688
						foreach ($ph2ent['encryption-algorithm-option'] as $ealg) {
689

    
690
							$ealg_id = $ealg['name'];
691
							$ealg_kl = $ealg['keylen'];
692

    
693
							if ($ealg_kl) {
694
								if( $ealg_kl == "auto" ) {
695
									/*   This seems to be required on my system and was not reproducable
696
									 *   on other systems.   For some reason $p2_ealgos is not defined
697
									 *   and needs to be read back in!?  -sullrich Aug 26, 2009 
698
									 */
699
									if(!$p2_ealgos)
700
										require("ipsec.inc");
701
									$key_hi = $p2_ealgos[$ealg_id]['keysel']['hi'];
702
									$key_lo = $p2_ealgos[$ealg_id]['keysel']['lo'];
703
									$key_step = $p2_ealgos[$ealg_id]['keysel']['step'];
704
									/* in some cases where include ordering is suspect these variables
705
									   are somehow 0 and we enter this loop forever and timeout after 900
706
									   seconds wrecking bootup */
707
									if($key_hi != 0 and $key_lo !=0 and $key_step !=0) {
708
										for ($keylen = $key_hi; $keylen >= $key_lo; $keylen -= $key_step) {
709
//											Uncomment the next line if you want to test the comment 5 lines up.											
710
//											echo "$keylen = $key_hi; $keylen >= $key_lo; $keylen -= $key_step \n";
711
											if ($ealgos)
712
												$ealgos = $ealgos.", ";
713
											$ealgos = $ealgos.$ealg_id." ".$keylen;
714
										}
715
									}
716
								} else {
717
									if ($ealgos)
718
										$ealgos = $ealgos.", ";
719
									$ealgos = $ealgos.$ealg_id." ".$ealg_kl;
720
								}
721
							} else {
722
								if ($ealgos)
723
									$ealgos = $ealgos.", ";
724
								$ealgos = $ealgos.$ealg_id;
725
							}
726
						}
727

    
728
						$ealgosline = "encryption_algorithm {$ealgos};";
729

    
730
					} else {
731

    
732
						$ealgosline = "encryption_algorithm null_enc;";
733
					}
734

    
735
					$halgos = join(",", $ph2ent['hash-algorithm-option']);
736
					$halgosline = "authentication_algorithm {$halgos};";
737

    
738
					$pfsline = '';
739
					if ($ph2ent['pfsgroup'])
740
						$pfsline = "pfs_group {$ph2ent['pfsgroup']};";
741
					if (isset($a_client['pfs_group'])) {
742
						$pfsline = '';
743
						if ($a_client['pfs_group'])
744
							$pfsline = "pfs_group {$a_client['pfs_group']};";
745
					}
746

    
747
					$lifeline = '';
748
					if ($ph2ent['lifetime'])
749
						$lifeline = "lifetime time {$ph2ent['lifetime']} secs;";
750

    
751
					/* add sainfo section to configuration */
752
					
753
					$racoonconf .=<<<EOD
754
					
755
sainfo {$localid_spec} {$remoteid_spec}
756
{
757
	remoteid {$ikeid};
758
	{$ealgosline}
759
	{$halgosline}
760
	{$pfsline}
761
	{$lifeline}
762
	compression_algorithm deflate;
763
}
764

    
765
EOD;
766
				}
767
				/* end sainfo */
768
			}
769
			/* end sainfo sections */
770

    
771
			fwrite($fd, $racoonconf);
772
			fclose($fd);
773
		}
774
		/* end racoon.conf */
775

    
776
		/* generate IPsec policies */
777
		if (is_array($a_phase2) && count($a_phase2)) {
778
			/* generate spd.conf */
779
			$fd = fopen("{$g['varetc_path']}/spd.conf", "w");
780
			if (!$fd) {
781
				printf("Error: cannot open spd.conf in vpn_ipsec_configure().\n");
782
				return 1;
783
			}
784

    
785
			$spdconf = "";
786

    
787
			/* Try to prevent people from locking themselves out of webgui. Just in case. */
788
			if ($config['interfaces']['lan']) {
789
				$lanip = get_interface_ip("lan");
790
				if (!empty($lanip) && is_ipaddr($lanip)) {
791
					$lansn = get_interface_subnet("lan");
792
					$lansa = gen_subnet($lanip, $lansn);
793
					$spdconf .= "spdadd {$lanip}/32 {$lansa}/{$lansn} any -P out none;\n";
794
					$spdconf .= "spdadd {$lansa}/{$lansn} {$lanip}/32 any -P in none;\n";
795
				}
796
			}
797

    
798
			foreach ($a_phase2 as $ph2ent) {
799

    
800
				if( !ipsec_lookup_phase1($ph2ent,$ph1ent))
801
					continue;
802

    
803
				if (isset($ph1ent['mobile']))
804
					continue;
805

    
806
				if (isset($ph1ent['disabled']))
807
					continue;
808

    
809
				if (isset($ph2ent['disabled']))
810
					continue;
811

    
812
				$ep = ipsec_get_phase1_src($ph1ent);
813
				if (!$ep)
814
					continue;
815

    
816
				$rgip = $rgmap[$ph1ent['remote-gateway']];
817
				if(!is_ipaddr($rgip))
818
					continue;
819

    
820
				$localid = ipsec_idinfo_to_cidr($ph2ent['localid'],true);
821
				$remoteid = ipsec_idinfo_to_cidr($ph2ent['remoteid'],true);
822

    
823
				if($ph2ent['mode'] == "tunnel") {
824

    
825
					$spdconf .= "spdadd {$localid} {$remoteid} any -P out ipsec " .
826
						"{$ph2ent['protocol']}/tunnel/{$ep}-{$rgip}/unique;\n";
827

    
828
					$spdconf .= "spdadd {$remoteid} {$localid} any -P in ipsec " .
829
						"{$ph2ent['protocol']}/tunnel/{$rgip}-{$ep}/unique;\n";
830

    
831
				} else {
832

    
833
					$localid_data = ipsec_get_phase1_src($ph1ent);
834
					$remoteid_data = $rgmap[$ph1ent['remote-gateway']];
835

    
836
					$spdconf .= "spdadd {$localid_data} {$remoteid_data} any -P out ipsec " .
837
						"{$ph2ent['protocol']}/transport//require;\n";
838

    
839
					$spdconf .= "spdadd {$remoteid_data} {$localid_data} any -P in ipsec " .
840
						"{$ph2ent['protocol']}/transport//require;\n";
841

    
842
				}
843

    
844
				/* static route needed? */
845
				if (preg_match("/^carp|^vip/i", $ph1ent['interface']))
846
					$parentinterface = link_carp_interface_to_parent($ph1ent['interface']);
847
				else
848
					$parentinterface = $ph1ent['interface'];
849

    
850
				if (($parentinterface <> "wan") && (is_ipaddr($rgip))) {
851
					/* add endpoint routes to correct gateway on interface */
852
					if (interface_has_gateway($parentinterface)) {
853
						$gatewayip = get_interface_gateway("$parentinterface");
854
						$interfaceip = get_interface_ip($parentinterface);
855
						$subnet_bits = get_interface_subnet($parentinterface);
856
						$subnet_ip = gen_subnet("{$interfaceip}", "{$subnet_bits}");
857
						/* if the remote gateway is in the local subnet, then don't add a route */
858
						if (! ip_in_subnet($rgip, "{$subnet_ip}/{$subnet_bits}")) {
859
							if(is_ipaddr($gatewayip)) {
860
								/* FIXME: does adding route-to and reply-to on the in/outbound
861
								 * rules fix this? smos@ 13-01-2009 */
862
								// log_error("IPSEC interface is not WAN but {$parentinterface}, adding static route for VPN endpoint {$rgip} via {$gatewayip}");
863
								mwexec("/sbin/route change -host {$rgip} {$gatewayip}", true);
864
							}
865
						}
866
					}
867
				} else if(is_ipaddr($rgip))
868
					mwexec("/sbin/route delete -host {$rgip}", true);
869
			}
870

    
871
			fwrite($fd, $spdconf);
872
			fclose($fd);
873
		}
874

    
875
		/* needed for racoonctl admin socket */
876
		if (!is_dir("/var/db/racoon"))
877
			mkdir("/var/db/racoon/");
878
		
879
		/* mange racoon process */
880
		if (is_process_running("racoon")) {
881
			sleep("0.1");
882
			mwexec("/usr/local/sbin/racoonctl -s /var/db/racoon/racoon.sock reload-config", false);
883
			/* load SPD without flushing to be safe on config additions or changes. */
884
			mwexec("/usr/local/sbin/setkey -f {$g['varetc_path']}/spd.conf", false);
885
		} else {
886
			/* flush SA + SPD entries */
887
			mwexec("/usr/local/sbin/setkey -FP", false);
888
 			sleep("0.1");
889
			mwexec("/usr/local/sbin/setkey -F", false);
890
 			sleep("0.1");
891
 			/* start racoon */
892
			$ipsecdebug = isset($config['ipsec']['racoondebug']) ? "-d -v" : "";
893
			mwexec("/usr/local/sbin/racoon {$ipsecdebug} -f {$g['varetc_path']}/racoon.conf", false);
894
 			sleep("0.1");
895
 			/* load SPD */
896
			mwexec("/usr/local/sbin/setkey -f {$g['varetc_path']}/spd.conf", false);
897

    
898
		}
899
		/* start filterdns, if necessary */
900
		if (count($filterdns_list) > 0) {
901
			$interval = 60;
902
			if (!empty($ipseccfg['dns-interval']) && is_numeric($ipseccfg['dns-interval']))
903
				$interval = $ipseccfg['dns-interval'];
904

    
905
			$hostnames = "";
906
			array_unique($filterdns_list);
907
			foreach ($filterdns_list as $hostname)
908
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload ipsecdns\"'\n";
909
			file_put_contents("{$g['varetc_path']}/filterdns-ipsec.hosts", $hostnames);
910

    
911
			killbypid("{$g['varrun_path']}/filterdns-ipsec.pid");
912
			sleep(1);
913
			mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-ipsec.pid -i {$interval} -c {$g['varetc_path']}/filterdns-ipsec.hosts -d 1");
914
		}
915
	
916
		vpn_ipsec_failover_configure();
917

    
918
		if ($g['booting'])
919
			echo "done\n";
920
	}
921

    
922
	return 0;
923
}
924

    
925
/* Forcefully restart IPsec
926
 * This is required for when dynamic interfaces reload
927
 * For all other occasions the normal vpn_ipsec_configure()
928
 * will gracefully reload the settings without restarting
929
 */
930
function vpn_ipsec_force_reload() {
931
	global $config;
932
	global $g;
933

    
934
	$ipseccfg = $config['ipsec'];
935

    
936
	/* kill racoon */
937
	if(is_process_running("racoon"))
938
		mwexec("/usr/bin/killall racoon", true);
939

    
940
	/* wait for process to die */
941
	sleep(4);
942

    
943
	/* send a SIGKILL to be sure */
944
	sigkillbypid("{$g['varrun_path']}/racoon.pid", "KILL");
945

    
946
	/* wait for flushing to finish */
947
	sleep(1);
948

    
949
	/* if ipsec is enabled, start up again */
950
	if (isset($ipseccfg['enable'])) {
951
		log_error("Forcefully reloading IPsec racoon daemon");
952
		vpn_ipsec_configure();
953
	}
954

    
955
}
956

    
957
/* master setup for vpn (mpd) */
958
function vpn_setup() {
959
	/* start pptpd */
960
	vpn_pptpd_configure();
961

    
962
	/* start pppoe server */
963
	vpn_pppoes_configure();
964

    
965
	/* setup l2tp */
966
	vpn_l2tp_configure();
967
}
968

    
969
function vpn_netgraph_support() {
970
	$iflist = get_configured_interface_list();
971
	foreach ($iflist as $iface) {
972
		$realif = get_real_interface($iface);
973
		/* Get support for netgraph(4) from the nic */
974
		$ifinfo = pfSense_get_interface_addresses($realif);
975
		if (!empty($ifinfo) && in_array($ifinfo['iftype'], array("ether", "vlan", "bridge")))
976
                	pfSense_ngctl_attach(".", $realif);
977
	}
978
}
979

    
980
function vpn_pptpd_configure() {
981
	global $config, $g;
982

    
983
	$syscfg = $config['system'];
984
	$pptpdcfg = $config['pptpd'];
985

    
986
	if ($g['booting']) {
987
		if (!$pptpdcfg['mode'] || ($pptpdcfg['mode'] == "off"))
988
			return 0;
989

    
990
		echo "Configuring PPTP VPN service... ";
991
	} else {
992
		/* kill mpd */
993
		killbypid("{$g['varrun_path']}/pptp-vpn.pid");
994

    
995
		/* wait for process to die */
996
		sleep(3);
997

    
998
		if (is_process_running("mpd -b")) {
999
			killbypid("{$g['varrun_path']}/pptp-vpn.pid");
1000
			log_error("Could not kill mpd within 3 seconds.   Trying again.");
1001
		}
1002

    
1003
		/* remove mpd.conf, if it exists */
1004
		unlink_if_exists("{$g['varetc_path']}/pptp-vpn/mpd.conf");
1005
		unlink_if_exists("{$g['varetc_path']}/pptp-vpn/mpd.links");
1006
		unlink_if_exists("{$g['varetc_path']}/pptp-vpn/mpd.secret");
1007
	}
1008

    
1009
	if (empty($pptpdcfg['n_pptp_units'])) {
1010
		log_error("Something wrong in the PPTPd configuration. Preventing starting the daemon because issues would arise.");
1011
		return; 
1012
	}
1013

    
1014
	/* make sure pptp-vpn directory exists */
1015
	if (!file_exists("{$g['varetc_path']}/pptp-vpn"))
1016
		mkdir("{$g['varetc_path']}/pptp-vpn");
1017

    
1018
	switch ($pptpdcfg['mode']) {
1019
		case 'server' :
1020
			/* write mpd.conf */
1021
			$fd = fopen("{$g['varetc_path']}/pptp-vpn/mpd.conf", "w");
1022
			if (!$fd) {
1023
				printf("Error: cannot open mpd.conf in vpn_pptpd_configure().\n");
1024
				return 1;
1025
			}
1026

    
1027
			$mpdconf = <<<EOD
1028
pptps:
1029

    
1030
EOD;
1031

    
1032
			for ($i = 0; $i < $pptpdcfg['n_pptp_units']; $i++) {
1033
				$mpdconf .= "	load pt{$i}\n";
1034
			}
1035

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

    
1038
				$clientip = long2ip32(ip2long($pptpdcfg['remoteip']) + $i);
1039

    
1040
				$mpdconf .= <<<EOD
1041

    
1042
pt{$i}:
1043
	new -i pptpd{$i} pt{$i} pt{$i}
1044
	set ipcp ranges {$pptpdcfg['localip']}/32 {$clientip}/32
1045
	load pts
1046

    
1047
EOD;
1048
			}
1049

    
1050
			$mpdconf .=<<<EOD
1051

    
1052
pts:
1053
	set iface disable on-demand
1054
	set iface enable proxy-arp
1055
	set iface enable tcpmssfix
1056
	set iface idle 1800
1057
	set iface up-script /usr/local/sbin/vpn-linkup
1058
	set iface down-script /usr/local/sbin/vpn-linkdown
1059
	set bundle enable multilink
1060
	set bundle enable crypt-reqd
1061
	set link yes acfcomp protocomp
1062
	set link no pap chap
1063
	set link enable chap-msv2
1064
	set link mtu 1460
1065
	set link keep-alive 10 60
1066
	set ipcp yes vjcomp
1067
	set bundle enable compression
1068
	set ccp yes mppc
1069
	set ccp yes mpp-e128
1070
	set ccp yes mpp-stateless
1071

    
1072
EOD;
1073

    
1074
			if (!isset ($pptpdcfg['req128'])) {
1075
				$mpdconf .=<<<EOD
1076
	set ccp yes mpp-e40
1077
	set ccp yes mpp-e56
1078

    
1079
EOD;
1080
			}
1081

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

    
1085
			if (!empty($pptpdcfg['dns1'])) {
1086
				$mpdconf .= "	set ipcp dns " . $pptpdcfg['dns1'];
1087
				if (!empty($pptpdcfg['dns2']))
1088
					$mpdconf .= " " . $pptpdcfg['dns2'];
1089
				$mpdconf .= "\n";
1090
			} elseif (isset ($config['dnsmasq']['enable'])) {
1091
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1092
				if ($syscfg['dnsserver'][0])
1093
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1094
				$mpdconf .= "\n";
1095
			} elseif (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1096
					$mpdconf .= "	set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n";
1097
			}
1098

    
1099
			if (isset ($pptpdcfg['radius']['server']['enable'])) {
1100
				$authport = (isset($pptpdcfg['radius']['server']['port']) && strlen($pptpdcfg['radius']['server']['port']) > 1) ? $pptpdcfg['radius']['server']['port'] : 1812;
1101
				$acctport = $authport + 1;
1102
				$mpdconf .=<<<EOD
1103
	set radius server {$pptpdcfg['radius']['server']['ip']} "{$pptpdcfg['radius']['server']['secret']}" {$authport} {$acctport}
1104

    
1105
EOD;
1106
			if (isset ($pptpdcfg['radius']['server2']['enable'])) {
1107
				$authport = (isset($pptpdcfg['radius']['server2']['port']) && strlen($pptpdcfg['radius']['server2']['port']) > 1) ? $pptpdcfg['radius']['server2']['port'] : 1812;
1108
				$acctport = $authport + 1;
1109
				$mpdconf .=<<<EOD
1110
	set radius server {$pptpdcfg['radius']['server2']['ip']} "{$pptpdcfg['radius']['server2']['secret']}" {$authport} {$acctport}
1111

    
1112
EOD;
1113
			}
1114
			$mpdconf .=<<<EOD
1115
	set radius retries 3
1116
	set radius timeout 10
1117
	set auth enable radius-auth
1118

    
1119
EOD;
1120

    
1121
				if (isset ($pptpdcfg['radius']['accounting'])) {
1122
					$mpdconf .=<<<EOD
1123
	set auth enable radius-acct
1124
	set radius acct-update 300
1125

    
1126
EOD;
1127
				}
1128
			}
1129

    
1130
			fwrite($fd, $mpdconf);
1131
			fclose($fd);
1132

    
1133
			/* write mpd.links */
1134
			$fd = fopen("{$g['varetc_path']}/pptp-vpn/mpd.links", "w");
1135
			if (!$fd) {
1136
				printf("Error: cannot open mpd.links in vpn_pptpd_configure().\n");
1137
				return 1;
1138
			}
1139

    
1140
			$mpdlinks = "";
1141

    
1142
			for ($i = 0; $i < $pptpdcfg['n_pptp_units']; $i++) {
1143
				$mpdlinks .=<<<EOD
1144

    
1145
pt{$i}:
1146
	set link type pptp
1147
	set pptp enable incoming
1148
	set pptp disable originate
1149
	set pptp disable windowing
1150

    
1151
EOD;
1152
			}
1153

    
1154
			fwrite($fd, $mpdlinks);
1155
			fclose($fd);
1156

    
1157
			/* write mpd.secret */
1158
			$fd = fopen("{$g['varetc_path']}/pptp-vpn/mpd.secret", "w");
1159
			if (!$fd) {
1160
				printf("Error: cannot open mpd.secret in vpn_pptpd_configure().\n");
1161
				return 1;
1162
			}
1163

    
1164
			$mpdsecret = "";
1165

    
1166
			if (is_array($pptpdcfg['user'])) {
1167
				foreach ($pptpdcfg['user'] as $user) {
1168
					$pass = str_replace('\\', '\\\\', $user['password']);
1169
					$pass = str_replace('"', '\"', $pass);
1170
					$mpdsecret .= "{$user['name']} \"{$pass}\" {$user['ip']}\n";
1171
				}
1172
			}
1173

    
1174
			fwrite($fd, $mpdsecret);
1175
			fclose($fd);
1176
			chmod("{$g['varetc_path']}/pptp-vpn/mpd.secret", 0600);
1177

    
1178
			vpn_netgraph_support();
1179

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

    
1183
			break;
1184

    
1185
		case 'redir' :
1186
			break;
1187
	}
1188

    
1189
	if ($g['booting'])
1190
		echo "done\n";
1191

    
1192
	return 0;
1193
}
1194

    
1195
function vpn_pppoes_configure() {
1196
	global $config;
1197

    
1198
	if (is_array($config['pppoes']['pppoe'])) {
1199
		foreach ($config['pppoes']['pppoe'] as $pppoe)
1200
			vpn_pppoe_configure($pppoe);
1201
	}
1202
}
1203

    
1204
function vpn_pppoe_configure(&$pppoecfg) {
1205
	global $config, $g;
1206

    
1207
	$syscfg = $config['system'];
1208

    
1209
	/* create directory if it does not exist */
1210
	if (!is_dir("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn"))
1211
		mkdir("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn");
1212

    
1213
	if ($g['booting']) {
1214
		if (!$pppoecfg['mode'] || ($pppoecfg['mode'] == "off"))
1215
			return 0;
1216

    
1217
		echo "Configuring PPPoE VPN service... ";
1218
	} else {
1219
		/* kill mpd */
1220
		killbypid("{$g['varrun_path']}/pppoe{$pppoecfg['pppoeid']}-vpn.pid");
1221

    
1222
		/* wait for process to die */
1223
		sleep(2);
1224

    
1225
	}
1226

    
1227
	switch ($pppoecfg['mode']) {
1228

    
1229
		case 'server' :
1230

    
1231
			$pppoe_interface = get_real_interface($pppoecfg['interface']);
1232

    
1233
			if ($pppoecfg['paporchap'] == "chap")
1234
				$paporchap = "set link enable chap";
1235
			else
1236
				$paporchap = "set link enable pap";
1237

    
1238
			/* write mpd.conf */
1239
			$fd = fopen("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn/mpd.conf", "w");
1240
			if (!$fd) {
1241
				printf("Error: cannot open mpd.conf in vpn_pppoe_configure().\n");
1242
				return 1;
1243
			}
1244
			$mpdconf = "\n\n";
1245
			$mpdconf .= "poes:\n";
1246

    
1247
			for ($i = 0; $i < $pppoecfg['n_pppoe_units']; $i++) {
1248
				$mpdconf .= "	load poes{$pppoecfg['pppoeid']}{$i}\n";
1249
			}
1250

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

    
1253
				$clientip = long2ip32(ip2long($pppoecfg['remoteip']) + $i);
1254

    
1255
				if (isset($pppoecfg['radius']['radiusissueips']) && isset($pppoecfg['radius']['server']['enable'])) {
1256
					$isssue_ip_type = "set ipcp ranges {$pppoecfg['localip']}/32 0.0.0.0/0";
1257
				} else {
1258
					$isssue_ip_type = "set ipcp ranges {$pppoecfg['localip']}/32 {$clientip}/32";
1259
				}
1260

    
1261
				$mpdconf .=<<<EOD
1262

    
1263
poes{$pppoecfg['pppoeid']}{$i}:
1264
	new -i poes{$pppoecfg['pppoeid']}{$i} poes{$pppoecfg['pppoeid']}{$i} poes{$pppoecfg['pppoeid']}{$i}
1265
	{$isssue_ip_type}
1266
	load pppoe_standard
1267

    
1268
EOD;
1269
			}
1270

    
1271
			$mpdconf .=<<<EOD
1272

    
1273
pppoe_standard:
1274
	set bundle no multilink
1275
	set bundle enable compression
1276
	set auth max-logins 1
1277
	set iface up-script /usr/local/sbin/vpn-linkup
1278
	set iface down-script /usr/local/sbin/vpn-linkdown
1279
	set iface idle 0
1280
	set iface disable on-demand
1281
	set iface disable proxy-arp
1282
	set iface enable tcpmssfix
1283
	set iface mtu 1500
1284
	set link no pap chap
1285
	{$paporchap}
1286
	set link keep-alive 60 180
1287
	set ipcp yes vjcomp
1288
	set ipcp no vjcomp
1289
	set link max-redial -1
1290
	set link mtu 1492
1291
	set link mru 1492
1292
	set ccp yes mpp-e40
1293
	set ccp yes mpp-e128
1294
	set ccp yes mpp-stateless
1295
	set link latency 1
1296
	#set ipcp dns 10.10.1.3
1297
	#set bundle accept encryption
1298

    
1299
EOD;
1300

    
1301
			if (!empty($pppoecfg['dns1'])) {
1302
				$mpdconf .= "	set ipcp dns " . $pppoecfg['dns1'];
1303
				if (!empty($pppoecfg['dns2']))
1304
					$mpdconf .= " " . $pppoecfg['dns2'];
1305
				$mpdconf .= "\n";
1306
			} elseif (isset ($config['dnsmasq']['enable'])) {
1307
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1308
				if ($syscfg['dnsserver'][0])
1309
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1310
				$mpdconf .= "\n";
1311
			} elseif (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1312
					$mpdconf .= "	set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n";
1313
			}
1314

    
1315
			if (isset ($pppoecfg['radius']['server']['enable'])) {
1316
				$radiusport = "";
1317
				$radiusacctport = "";
1318
				if (isset($pppoecfg['radius']['server']['port']))
1319
					$radiusport = $pppoecfg['radius']['server']['port'];
1320
				if (isset($pppoecfg['radius']['server']['acctport']))
1321
					$radiusacctport = $pppoecfg['radius']['server']['acctport'];
1322
				$mpdconf .=<<<EOD
1323
	set radius server {$pppoecfg['radius']['server']['ip']} "{$pppoecfg['radius']['server']['secret']}" {$radiusport} {$radiusacctport}
1324
	set radius retries 3
1325
	set radius timeout 10
1326
	set auth enable radius-auth
1327

    
1328
EOD;
1329

    
1330
				if (isset ($pppoecfg['radius']['accounting'])) {
1331
					$mpdconf .=<<<EOD
1332
	set auth enable radius-acct
1333

    
1334
EOD;
1335
				}
1336
			}
1337

    
1338
			fwrite($fd, $mpdconf);
1339
			fclose($fd);
1340

    
1341
			/* write mpd.links */
1342
			$fd = fopen("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn/mpd.links", "w");
1343
			if (!$fd) {
1344
				printf("Error: cannot open mpd.links in vpn_pppoe_configure().\n");
1345
				return 1;
1346
			}
1347

    
1348
			$mpdlinks = "";
1349

    
1350
			for ($i = 0; $i < $pppoecfg['n_pppoe_units']; $i++) {
1351
				$mpdlinks .=<<<EOD
1352
			
1353
poes{$pppoecfg['pppoeid']}{$i}:
1354
	set phys type pppoe
1355
        set pppoe iface {$pppoe_interface}
1356
        set pppoe service "*"
1357
        set pppoe disable originate
1358
        set pppoe enable incoming
1359

    
1360
EOD;
1361
			}
1362

    
1363
			fwrite($fd, $mpdlinks);
1364
			fclose($fd);
1365

    
1366
			if ($pppoecfg['username']) {
1367
				/* write mpd.secret */
1368
				$fd = fopen("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn/mpd.secret", "w");
1369
				if (!$fd) {
1370
					printf("Error: cannot open mpd.secret in vpn_pppoe_configure().\n");
1371
					return 1;
1372
				}
1373

    
1374
				$mpdsecret = "\n\n";
1375

    
1376
				if (!empty($pppoecfg['username'])) {
1377
					$item = explode(" ", $pppoecfg['username']);
1378
					foreach($item as $userdata) {
1379
						$data = explode(":", $userdata);
1380
						$mpdsecret .= "{$data[0]} \"" . base64_decode($data[1]) . "\" {$data[2]}\n";
1381
					}
1382
				}
1383

    
1384
				fwrite($fd, $mpdsecret);
1385
				fclose($fd);
1386
				chmod("{$g['varetc_path']}/pppoe{$pppoecfg['pppoeid']}-vpn/mpd.secret", 0600);
1387
			}
1388

    
1389
			/* Get support for netgraph(4) from the nic */
1390
			pfSense_ngctl_attach(".", $pppoe_interface);
1391
			/* fire up mpd */
1392
			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");
1393

    
1394
			break;
1395
	}
1396

    
1397
	if ($g['booting'])
1398
		echo "done\n";
1399

    
1400
	return 0;
1401
}
1402

    
1403
function vpn_l2tp_configure() {
1404
	global $config, $g;
1405

    
1406
	$syscfg = $config['system'];
1407
	$l2tpcfg = $config['l2tp'];
1408

    
1409
	/* create directory if it does not exist */
1410
	if (!is_dir("{$g['varetc_path']}/l2tp-vpn"))
1411
		mkdir("{$g['varetc_path']}/l2tp-vpn");
1412

    
1413
	if ($g['booting']) {
1414
		if (!$l2tpcfg['mode'] || ($l2tpcfg['mode'] == "off"))
1415
			return 0;
1416

    
1417
		echo "Configuring l2tp VPN service... ";
1418
	} else {
1419
		/* kill mpd */
1420
		killbypid("{$g['varrun_path']}/l2tp-vpn.pid");
1421

    
1422
		/* wait for process to die */
1423
		sleep(8);
1424

    
1425
	}
1426

    
1427
	/* make sure l2tp-vpn directory exists */
1428
	if (!file_exists("{$g['varetc_path']}/l2tp-vpn"))
1429
		mkdir("{$g['varetc_path']}/l2tp-vpn");
1430

    
1431
	switch ($l2tpcfg['mode']) {
1432

    
1433
		case 'server' :
1434
			if ($l2tpcfg['paporchap'] == "chap")
1435
				$paporchap = "set link enable chap";
1436
			else
1437
				$paporchap = "set link enable pap";
1438

    
1439
			/* write mpd.conf */
1440
			$fd = fopen("{$g['varetc_path']}/l2tp-vpn/mpd.conf", "w");
1441
			if (!$fd) {
1442
				printf("Error: cannot open mpd.conf in vpn_l2tp_configure().\n");
1443
				return 1;
1444
			}
1445
			$mpdconf = "\n\n";
1446
			$mpdconf .=<<<EOD
1447
l2tps:
1448

    
1449
EOD;
1450

    
1451
			for ($i = 0; $i < $l2tpcfg['n_l2tp_units']; $i++) {
1452
				$mpdconf .= "	load l2tp{$i}\n";
1453
			}
1454

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

    
1457
				$clientip = long2ip32(ip2long($l2tpcfg['remoteip']) + $i);
1458

    
1459
				if (isset ($l2tpcfg['radius']['radiusissueips']) && isset ($l2tpcfg['radius']['enable'])) {
1460
					$isssue_ip_type = "set ipcp ranges {$l2tpcfg['localip']}/32 0.0.0.0/0";
1461
				} else {
1462
					$isssue_ip_type = "set ipcp ranges {$l2tpcfg['localip']}/32 {$clientip}/32";
1463
				}
1464

    
1465
				$mpdconf .=<<<EOD
1466

    
1467
l2tp{$i}:
1468
	new -i l2tp{$i} l2tp{$i} l2tp{$i}
1469
	{$isssue_ip_type}
1470
	load l2tp_standard
1471

    
1472
EOD;
1473
			}
1474

    
1475
			$mpdconf .=<<<EOD
1476

    
1477
l2tp_standard:
1478
        set bundle disable multilink
1479
        set bundle enable compression
1480
        set bundle yes crypt-reqd
1481
        set ipcp yes vjcomp
1482
        # set ipcp ranges 131.188.69.161/32 131.188.69.170/28
1483
        set ccp yes mppc
1484
        set iface disable on-demand
1485
        set iface enable proxy-arp
1486
	set iface up-script /usr/local/sbin/vpn-linkup
1487
	set iface down-script /usr/local/sbin/vpn-linkdown
1488
        set link yes acfcomp protocomp
1489
        set link no pap chap
1490
        set link enable chap
1491
        set link keep-alive 10 180
1492

    
1493
EOD;
1494

    
1495
			if (is_ipaddr($l2tpcfg['wins'])) {
1496
				$mpdconf .= "	set ipcp nbns {$l2tpcfg['wins']}\n";
1497
			}
1498
			if (is_ipaddr($l2tpcfg['dns1'])) {
1499
				$mpdconf .= "	set ipcp dns " . $l2tpcfg['dns1'];
1500
				if (is_ipaddr($l2tpcfg['dns2']))
1501
					$mpdconf .= " " . $l2tpcfg['dns2'];
1502
				$mpdconf .= "\n";
1503
			} elseif (isset ($config['dnsmasq']['enable'])) {
1504
				$mpdconf .= "	set ipcp dns " . get_interface_ip("lan");
1505
				if ($syscfg['dnsserver'][0])
1506
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1507
				$mpdconf .= "\n";
1508
			} elseif (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1509
					$mpdconf .= "	set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n";
1510
			}
1511

    
1512
			if (isset ($l2tpcfg['radius']['enable'])) {
1513
				$mpdconf .=<<<EOD
1514
	set radius server {$l2tpcfg['radius']['server']} "{$l2tpcfg['radius']['secret']}"
1515
	set radius retries 3
1516
	set radius timeout 10
1517
	set auth enable radius-auth
1518

    
1519
EOD;
1520

    
1521
				if (isset ($l2tpcfg['radius']['accounting'])) {
1522
					$mpdconf .=<<<EOD
1523
	set auth enable radius-acct
1524

    
1525
EOD;
1526
				}
1527
			}
1528

    
1529
			fwrite($fd, $mpdconf);
1530
			fclose($fd);
1531

    
1532
			/* write mpd.links */
1533
			$fd = fopen("{$g['varetc_path']}/l2tp-vpn/mpd.links", "w");
1534
			if (!$fd) {
1535
				printf("Error: cannot open mpd.links in vpn_l2tp_configure().\n");
1536
				return 1;
1537
			}
1538

    
1539
			$mpdlinks = "";
1540

    
1541
			for ($i = 0; $i < $l2tpcfg['n_l2tp_units']; $i++) {
1542
				$mpdlinks .=<<<EOD
1543

    
1544
l2tp{$i}:
1545
	set link type l2tp
1546
        set l2tp enable incoming
1547
        set l2tp disable originate
1548

    
1549
EOD;
1550
			if (!empty($l2tpcfg['secret']))
1551
					$mpdlinks .= "set l2tp secret {$l2tpcfg['secret']}\n";
1552
			}
1553

    
1554
			fwrite($fd, $mpdlinks);
1555
			fclose($fd);
1556

    
1557
			/* write mpd.secret */
1558
			$fd = fopen("{$g['varetc_path']}/l2tp-vpn/mpd.secret", "w");
1559
			if (!$fd) {
1560
				printf("Error: cannot open mpd.secret in vpn_l2tp_configure().\n");
1561
				return 1;
1562
			}
1563

    
1564
			$mpdsecret = "\n\n";
1565

    
1566
			if (is_array($l2tpcfg['user'])) {
1567
				foreach ($l2tpcfg['user'] as $user)
1568
					$mpdsecret .= "{$user['name']} \"{$user['password']}\" {$user['ip']}\n";
1569
			}
1570

    
1571
			fwrite($fd, $mpdsecret);
1572
			fclose($fd);
1573
			chmod("{$g['varetc_path']}/l2tp-vpn/mpd.secret", 0600);
1574

    
1575
			vpn_netgraph_support();
1576

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

    
1580
			break;
1581

    
1582
		case 'redir' :
1583
			break;
1584
	}
1585

    
1586
	if ($g['booting'])
1587
		echo "done\n";
1588

    
1589
	return 0;
1590
}
1591

    
1592
/* Walk the tunnels for hostname endpoints. If the hostnames 
1593
 * resolve to a different IP now compared to the DNS cache
1594
 * we reload the policies if the endpoint has changed */
1595
function vpn_ipsec_refresh_policies() {
1596
	global $config;
1597
	global $g;
1598

    
1599
	$ipseccfg = $config['ipsec'];
1600
	$a_phase1 = $config['ipsec']['phase1'];
1601
	$a_phase2 = $config['ipsec']['phase2'];
1602

    
1603
	if (isset($ipseccfg['disable'])) {
1604
		return true;
1605
	}
1606

    
1607
	/* Walk the Ipsec tunnel array */
1608
	if (!is_array($a_phase1) || (!count($a_phase1))) {
1609
		return;
1610
	}
1611

    
1612
	foreach ($a_phase1 as $phase1) {
1613
		if (isset($phase1['disabled'])) {
1614
			continue;
1615
		}
1616
		if (is_ipaddr($phase1['remote-gateway'])) {
1617
			continue;
1618
		}
1619
		if (!is_ipaddr($phase1['remote-gateway'])) {
1620
			$dnscache = compare_hostname_to_dnscache($phase1['remote-gateway']);
1621
			$dnscache = trim($dnscache);
1622
			/* we should have the old IP addresses in the dnscache now */
1623
			if($dnscache <> "") {
1624
				$oldphase1 = $phase1;
1625
				$oldphase1['remote-gateway'] = trim($dnscache);
1626
				/* now we need to find all tunnels for this host */
1627
				if (!is_array($a_phase2) || (!count($a_phase2))) {
1628
					continue;
1629
				}
1630
				foreach ($a_phase2 as $phase2) {
1631
					if($phase2['ikeid'] == $phase1['ikeid']) {
1632
						reload_tunnel_spd_policy ($phase1, $phase2, $oldphase1, $oldphase2);
1633
					}
1634
				}
1635
			}
1636
		}
1637
	}
1638

    
1639
	/* process all generated spd.conf files from tmp which are left behind
1640
	 * behind by either changes of dynamic tunnels or manual edits
1641
	 * scandir() is only available in PHP5 */
1642
	$tmpfiles = array();
1643
	$dh  = opendir($g['tmp_path']);
1644
	while (false !== ($filename = readdir($dh))) {
1645
		if(preg_match("/^spd.conf.reload./", $filename)) {
1646
			$tmpfiles[] = $filename;
1647
		}
1648
	}
1649
	sort($tmpfiles);
1650
	foreach($tmpfiles as $tmpfile) {
1651
		$ret = mwexec("/usr/local/sbin/setkey -f {$g['tmp_path']}/{$tmpfile} 2>&1", false);
1652
		if($ret == 0) {
1653
			unlink_if_exists("{$g['tmp_path']}/{$tmpfile}");
1654
		} else {
1655
			rename("{$g['tmp_path']}/{$tmpfile}", ("{$g['tmp_path']}/failed.{$tmpfile}"));
1656
		}
1657
	}
1658
}
1659

    
1660
/* reloads the tunnel configuration for a tunnel item
1661
 * Will remove and add SPD polices */
1662
function reload_tunnel_spd_policy($phase1, $phase2, $old_phase1, $old_phase2) {
1663
	global $config;
1664
	global $g;
1665

    
1666
	/* if we are not passed a old tunnel array we create one */
1667
	if(empty($old_phase1)) {
1668
		$old_phase1 = $phase1;
1669
	}
1670
	if(empty($old_phase2)) {
1671
		$old_phase2 = $phase2;
1672
	}
1673

    
1674
	$sad_arr = ipsec_dump_sad();
1675

    
1676
	$ep = ipsec_get_phase1_src($phase1);
1677
	$local_subnet = ipsec_idinfo_to_cidr($phase2['localid']);
1678
	$remote_subnet = ipsec_idinfo_to_cidr($phase2['remoteid']);
1679

    
1680
	/* make sure we pass the oldtunnel array with a IP for the remote gw */
1681
	$old_gw = trim($old_phase1['remote-gateway']);
1682

    
1683
	$old_ep = ipsec_get_phase1_src($old_phase1);
1684
	$old_local_subnet = ipsec_idinfo_to_cidr($old_phase2['localid']);
1685
	$old_remote_subnet = ipsec_idinfo_to_cidr($old_phase2['remoteid']);
1686

    
1687
	/* see if this tunnel has a hostname for the remote-gateway, and if so,
1688
	 * try to resolve it now and add it to the list for filterdns */
1689
	$rgip = "";
1690
	if (!is_ipaddr($phase1['remote-gateway'])) {
1691
		if(! $g['booting']) {
1692
			$rgip = resolve_retry($phase1['remote-gateway']);
1693
			add_hostname_to_watch($phase1['remote-gateway']);
1694
		} else {
1695
			add_hostname_to_watch($phase1['remote-gateway']);
1696
		}
1697
		if (!is_ipaddr($rgip)) {
1698
			log_error("Could not determine VPN endpoint for '{$phase1['descr']}'");
1699
			return false;
1700
		}
1701
	} else {
1702
		$rgip = $phase1['remote-gateway'];
1703
	}
1704
	if (!$ep) {
1705
		log_error("Could not determine VPN endpoint for '{$phase1['descr']}'");
1706
		return false;
1707
	}
1708

    
1709
	if((!is_ipaddr($old_ep)) || (! is_ipaddr($ep))) {
1710
		log_error("IPSEC: ERROR: One of the endpoints is not a IP address. Old EP '{$old_ep}' new EP '{$ep}'");
1711
	}
1712
	if((! is_ipaddr($rgip)) || (! is_ipaddr($old_gw))) {
1713
		log_error("IPSEC: ERROR: One of the remote endpoints is not a IP address. Old RG '{$old_gw}' new RG '{$rgip}'");
1714
	}
1715

    
1716
	$spdconf = "";
1717
	/* Delete old SPD policies if there are changes between the old and new */
1718
	if(($phase1 != $old_phase1) || ($phase2 != $old_phase2)) {
1719
		$spdconf .= "spddelete {$old_local_subnet} " .
1720
			"{$old_remote_subnet} any -P out ipsec " .
1721
			"{$old_phase2['protocol']}/tunnel/{$old_ep}-" .
1722
			"{$old_gw}/unique;\n";
1723
		$spdconf .= "spddelete {$old_remote_subnet} " .
1724
			"{$old_local_subnet} any -P in ipsec " .
1725
			"{$old_phase2['protocol']}/tunnel/{$old_gw}-" .
1726
			"{$old_ep}/unique;\n";
1727

    
1728
		/* zap any existing SA entries */
1729
		foreach($sad_arr as $sad) {
1730
			if(($sad['dst'] == $old_ep) && ($sad['src'] == $old_gw)) {
1731
				$spdconf .= "delete {$old_ep} {$old_gw} {$old_phase2['protocol']} 0x{$sad['spi']};\n";
1732
			}
1733
			if(($sad['src'] == $oldep) && ($sad['dst'] == $old_gw)) {
1734
				$spdconf .= "delete {$old_gw} {$old_ep} {$old_phase2['protocol']} 0x{$sad['spi']};\n";
1735
			}
1736
		}
1737
	}
1738

    
1739
	/* Create new SPD entries for the new configuration */
1740
	/* zap any existing SA entries beforehand */
1741
	foreach($sad_arr as $sad) {
1742
		if(($sad['dst'] == $ep) && ($sad['src'] == $rgip)) {
1743
			$spdconf .= "delete {$rgip} {$ep} {$phase2['protocol']} 0x{$sad['spi']};\n";
1744
		}
1745
		if(($sad['src'] == $ep) && ($sad['dst'] == $rgip)) {
1746
			$spdconf .= "delete {$ep} {$rgip} {$phase2['protocol']} 0x{$sad['spi']};\n";
1747
		}
1748
	}
1749
	/* add new SPD policies to replace them */
1750
	$spdconf .= "spdadd {$local_subnet} " .
1751
		"{$remote_subnet} any -P out ipsec " .
1752
		"{$phase2['protocol']}/tunnel/{$ep}-" .
1753
		"{$rgip}/unique;\n";
1754
	$spdconf .= "spdadd {$remote_subnet} " .
1755
		"{$local_subnet} any -P in ipsec " .
1756
		"{$phase2['protocol']}/tunnel/{$rgip}-" .
1757
		"{$ep}/unique;\n";
1758

    
1759
	log_error("Reloading IPsec tunnel '{$phase1['descr']}'. Previous IP '{$old_gw}', current IP '{$rgip}'. Reloading policy");
1760

    
1761
	$now = time();
1762
	$spdfile = tempnam("{$g['tmp_path']}", "spd.conf.reload.{$now}.");
1763
	/* generate temporary spd.conf */
1764
	file_put_contents($spdfile, $spdconf);
1765
	return true;
1766
}
1767

    
1768
function vpn_ipsec_configure_preferoldsa() {
1769
	global $config;
1770
	if(isset($config['ipsec']['preferoldsa']))
1771
		mwexec("/sbin/sysctl -w net.key.preferred_oldsa=-30");
1772
	else
1773
		mwexec("/sbin/sysctl net.key.preferred_oldsa=0");
1774
}
1775

    
1776
?>
(52-52/61)