Project

General

Profile

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

    
3
/*
4
	vpn.inc
5
	Copyright (C) 2004 Scott Ullrich
6
	All rights reserved.
7

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

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

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

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

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

    
34
/* include all configuration functions */
35
require_once ("functions.inc");
36

    
37
/* master setup for vpn (mpd) */
38
function vpn_setup() {
39
	/* start pptpd */
40
	vpn_pptpd_configure();
41

    
42
	/* start pppoe server */
43
	vpn_pppoe_configure();
44

    
45
	/* setup l2tp */
46
	vpn_l2tp_configure();
47
}
48

    
49
function vpn_ipsec_failover_configure() {
50
	global $config, $g;
51

    
52
	$sasyncd_text = "";
53

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

    
73
	$fd = fopen("{$g['varetc_path']}/sasyncd.conf", "w");
74
	fwrite($fd, $sasyncd_text);
75
	fclose($fd);
76
	chmod("{$g['varetc_path']}/sasyncd.conf", 0600);
77

    
78
	mwexec("killall sasyncd");
79

    
80
	/* launch sasyncd, oh wise one */
81
	mwexec_bg("/usr/local/sbin/sasyncd -d -v -v -v");
82
}
83

    
84
function find_last_gif_device() {
85
	$last_gif_found = -1;
86
	$regs = "";
87
	if (!($fp = popen("/sbin/ifconfig -l", "r")))
88
		return -1;
89
	$ifconfig_data = fread($fp, 4096);
90
	pclose($fp);
91
	$ifconfig_array = split(" ", $ifconfig_data);
92
	foreach ($ifconfig_array as $ifconfig) {
93
		ereg("gif(.)", $ifconfig, $regs);
94
		if ($regs[0] && $regs[0] > $last_gif_found) {
95
			$last_gif_found = $regs[1];
96
		}
97
	}
98
	return $last_gif_found;
99
}
100

    
101
function vpn_ipsec_configure($ipchg = false) {
102
	global $config, $g, $sa, $sn;
103

    
104
	mwexec("/sbin/ifconfig enc0 up");
105

    
106
	/* get the automatic /etc/ping_hosts.sh ready */
107
	unlink_if_exists("/var/db/ipsecpinghosts");
108
	touch("/var/db/ipsecpinghosts");
109

    
110
	if ($g['booting'] == true) {
111
		/* determine if we should load the via padlock module */
112
		$dmesg_boot = `/usr/bin/grep CPU {$g['varlog_path']}/dmesg.boot`;
113
		if (stristr($dmesg_boot, "ACE") == true) {
114
			//echo "Enabling [VIA Padlock] ...";
115
			//mwexec("/sbin/kldload padlock");
116
			//mwexec("/sbin/sysctl net.inet.ipsec.crypto_support=1");
117
			//mwexec("/sbin/setkey -F");
118
			//mwexec("/sbin/setkey -FP");
119
			//echo " done.\n";
120
		}
121
	}
122

    
123
	if(isset($config['ipsec']['preferredoldsa'])) {
124
		mwexec("/sbin/sysctl net.key.preferred_oldsa=0");
125
	} else {
126
		mwexec("/sbin/sysctl -w net.key.preferred_oldsa=-30");
127
	}
128

    
129
	$number_of_gifs = find_last_gif_device();
130
	for ($x = 0; $x < $number_of_gifs; $x++) {
131
		mwexec("/sbin/ifconfig gif" . $x . " delete");
132
	}
133

    
134
	$curwanip = get_current_wan_address();
135

    
136
	$syscfg = $config['system'];
137
	$ipseccfg = $config['ipsec'];
138
	$lancfg = $config['interfaces']['lan'];
139
	$lanip = $lancfg['ipaddr'];
140
	$lansa = gen_subnet($lancfg['ipaddr'], $lancfg['subnet']);
141
	$lansn = $lancfg['subnet'];
142

    
143

    
144
	if (!isset($ipseccfg['enable'])) {
145
		mwexec("/sbin/ifconfig enc0 down");
146
		mwexec("/sbin/ifconfig enc0 destroy");
147

    
148
		/* kill racoon */
149
		mwexec("/usr/bin/killall racoon");
150
		killbypid("{$g['varrun_path']}/dnswatch-ipsec.pid");
151
		
152
		/* wait for racoon process to die */
153
		sleep(2);
154

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

    
158
		/* flush SPD and SAD */
159
		mwexec("/sbin/setkey -FP");
160
		mwexec("/sbin/setkey -F");
161

    
162
		return true;
163
	}
164

    
165
	if ($g['booting']) {
166
		echo "Configuring IPsec VPN... ";
167
	}
168

    
169
	if (isset ($ipseccfg['enable'])) {
170
		/* fastforwarding is not compatible with ipsec tunnels */
171
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=0");
172

    
173
		if (!$curwanip) {
174
			/* IP address not configured yet, exit */
175
			if ($g['booting'])
176
				echo "done\n";
177
			return 0;
178
		}
179

    
180
		if ((is_array($ipseccfg['tunnel']) && count($ipseccfg['tunnel'])) ||
181
		  isset ($ipseccfg['mobileclients']['enable'])) {
182
		  
183
			$dnswatch_list = array();
184
			$rgmap = array();
185
		  
186
			if (is_array($ipseccfg['tunnel']) && count($ipseccfg['tunnel'])) {
187
				/* generate spd.conf */
188
				$fd = fopen("{$g['varetc_path']}/spd.conf", "w");
189
				if (!$fd) {
190
					printf("Error: cannot open spd.conf in vpn_ipsec_configure().\n");
191
					return 1;
192
				}
193

    
194
				$spdconf = "";
195

    
196
				$spdconf .= "spdadd {$lansa}/{$lansn} {$lanip}/32 any -P in none;\n";
197
				$spdconf .= "spdadd {$lanip}/32 {$lansa}/{$lansn} any -P out none;\n";
198

    
199
				foreach ($ipseccfg['tunnel'] as $tunnel) {
200
					if (isset ($tunnel['disabled']))
201
						continue;
202

    
203
				   /* see if this tunnel has a hostname for the remote-gateway, and if so,
204
				      try to resolve it now and add it to the list for dnswatch */
205
				   if (!is_ipaddr($tunnel['remote-gateway'])) {
206
				           $dnswatch_list[] = $tunnel['remote-gateway'];
207
				           $rgip = resolve_retry($tunnel['remote-gateway']);
208
				
209
				           if (!$rgip)
210
				                   continue;
211
				
212
				   } else {
213
				           $rgip = $tunnel['remote-gateway'];
214
				   }
215
				   $rgmap[$tunnel['remote-gateway']] = $rgip;
216

    
217
					$ep = vpn_endpoint_determine($tunnel, $curwanip);
218
					if (!$ep)
219
						continue;
220

    
221
					vpn_localnet_determine($tunnel['local-subnet'], $sa, $sn);
222

    
223
					if (is_domain($tunnel['remote-gateway'])) {
224
						$tmp = gethostbyname($tunnel['remote-gateway']);
225
						if ($tmp)
226
							$tunnel['remote-gateway'] = $tmp;
227
					}
228

    
229
					/* add entry to host pinger */
230
					if ($tunnel['pinghost']) {
231
						$pfd = fopen("/var/db/ipsecpinghosts", "a");
232
						$iflist = array("lan" => "lan", "wan" => "wan");
233
			          	for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++)
234
			          		$iflist['opt' . $i] = "opt{$i}";
235
			            foreach ($iflist as $ifent => $ifname) {
236
			            	$interface_ip = find_interface_ip($config['interfaces'][$ifname]['if']);
237
			            	if (ip_in_subnet($interface_ip, $sa . "/" . $sn))
238
			                	$srcip = find_interface_ip($config['interfaces'][$ifname]['if']);
239
			            }
240
						$dstip = $tunnel['pinghost'];
241
						fwrite($pfd, "$srcip|$dstip|3\n");
242
						fclose($pfd);
243
					}
244

    
245
					if (isset ($tunnel['creategif'])) {
246
						$number_of_gifs = find_last_gif_device();
247
						$number_of_gifs++;
248
						$curwanip = get_current_wan_address();
249
						if ($config['installedpackages']['sasyncd']['config'] <> "")
250
							foreach ($config['installedpackages']['sasyncd']['config'] as $sasyncd) {
251
								if ($sasyncd['ip'] <> "")
252
									$curwanip = $sasyncd['ip'];
253
							}
254
						mwexec("/sbin/ifconfig gif" . $number_of_gifs . " tunnel" . $curwanip . " " . $tunnel['remote-gateway']);
255
						mwexec("/sbin/ifconfig gif" . $number_of_gifs . " {$lansa}/{$lansn} {$lanip}/32");
256
					}
257

    
258
					$spdconf .= "spdadd {$sa}/{$sn} " .
259
					  "{$tunnel['remote-subnet']} any -P out ipsec " .
260
					  "{$tunnel['p2']['protocol']}/tunnel/{$ep}-" .
261
					  "{$rgip}/unique;\n";
262

    
263
					$spdconf .= "spdadd {$tunnel['remote-subnet']} " .
264
					  "{$sa}/{$sn} any -P in ipsec " .
265
					  "{$tunnel['p2']['protocol']}/tunnel/{$rgip}-" .
266
					  "{$ep}/unique;\n";
267
				}
268

    
269
				fwrite($fd, $spdconf);
270
				fclose($fd);
271
			}
272

    
273
			/* generate racoon.conf */
274
			$fd = fopen("{$g['varetc_path']}/racoon.conf", "w");
275
			if (!$fd) {
276
				printf("Error: cannot open racoon.conf in vpn_ipsec_configure().\n");
277
				return 1;
278
			}
279

    
280
			$racoonconf = "";
281

    
282
			$racoonconf .= "path pre_shared_key \"{$g['varetc_path']}/psk.txt\";\n\n";
283
			$racoonconf .= "path certificate  \"{$g['varetc_path']}\";\n\n";
284

    
285
			/* generate CA certificates files */
286
			$cacertnum = 0;
287
			if (is_array($ipseccfg['cacert']) && count($ipseccfg['cacert']))
288
				foreach ($ipseccfg['cacert'] as $cacert) {
289
					++ $cacertnum;
290
					if (isset ($cacert['cert'])) {
291
						$cert = base64_decode($cacert['cert']);
292
						$x509cert = openssl_x509_parse(openssl_x509_read($cert));
293
						if (is_array($x509cert) && isset ($x509cert['hash'])) {
294
							$fd1 = fopen("{$g['varetc_path']}/{$x509cert['hash']}.0", "w");
295
							if (!$fd1) {
296
								printf("Error: cannot open {$x509cert['hash']}.0 in vpn.\n");
297
								return 1;
298
							}
299
							chmod("{$g['varetc_path']}/{$x509cert['hash']}.0", 0600);
300
							fwrite($fd1, $cert);
301
							fclose($fd1);
302
						}
303
					}
304
				}
305

    
306
			$tunnelnumber = 0;
307
			if (is_array($ipseccfg['tunnel']) && count($ipseccfg['tunnel']))
308
				foreach ($ipseccfg['tunnel'] as $tunnel) {
309

    
310
					++ $tunnelnumber;
311

    
312
					if (isset ($tunnel['disabled']))
313
						continue;
314

    
315

    
316
					  $rgip = $rgmap[$tunnel['remote-gateway']];
317
					   if (!$rgip)
318
					           continue;
319

    
320
					$ep = vpn_endpoint_determine($tunnel, $curwanip);
321
					if (!$ep)
322
						continue;
323

    
324
					vpn_localnet_determine($tunnel['local-subnet'], $sa, $sn);
325

    
326
					if (isset ($tunnel['p1']['myident']['myaddress'])) {
327
						$myidentt = "address";
328
						$myident = $ep;
329
					} elseif (isset ($tunnel['p1']['myident']['address'])) {
330
						$myidentt = "address";
331
						$myident = $tunnel['p1']['myident']['address'];
332
					} elseif (isset ($tunnel['p1']['myident']['fqdn'])) {
333
						$myidentt = "fqdn";
334
						$myident = $tunnel['p1']['myident']['fqdn'];
335
					} elseif (isset ($tunnel['p1']['myident']['ufqdn'])) {
336
						$myidentt = "user_fqdn";
337
						$myident = $tunnel['p1']['myident']['ufqdn'];
338
					} else if (isset($tunnel['p1']['myident']['asn1dn'])) {
339
						$myidentt = "asn1dn";
340
						$myident = $tunnel['p1']['myident']['asn1dn'];					
341
					} else if (isset($tunnel['p1']['myident']['asn1dn'])) {
342
						$myidentt = "asn1dn";
343
						$myident = $tunnel['p1']['myident']['asn1dn'];						
344
					} elseif (isset ($tunnel['p1']['myident']['dyn_dns'])) {
345
						$myidentt = "dyn_dns";
346
						$myident = gethostbyname($tunnel['p1']['myident']['dyn_dns']);
347
					}
348

    
349
					$nattline = '';
350
					if (isset($tunnel['natt'])) {
351
						$nattline = "nat_traversal on;";
352
					}
353

    
354
					if (isset ($tunnel['p1']['authentication_method'])) {
355
						$authmethod = $tunnel['p1']['authentication_method'];
356
					} else {
357
						$authmethod = 'pre_shared_key';
358
					}
359

    
360
					$certline = '';
361

    
362
					if ($authmethod == 'rsasig') {
363
						if ($tunnel['p1']['cert'] && $tunnel['p1']['private-key']) {
364
							$cert = base64_decode($tunnel['p1']['cert']);
365
							$private_key = base64_decode($tunnel['p1']['private-key']);
366
						} else {
367
							/* null certificate/key */
368
							$cert = '';
369
							$private_key = '';
370
						}
371

    
372
						if ($tunnel['p1']['peercert'])
373
							$peercert = base64_decode($tunnel['p1']['peercert']);
374
						else
375
							$peercert = '';
376

    
377
						$fd1 = fopen("{$g['varetc_path']}/server{$tunnelnumber}-signed.pem", "w");
378
						if (!$fd1) {
379
							printf("Error: cannot open server{$tunnelnumber}-signed.pem in vpn.\n");
380
							return 1;
381
						}
382
						chmod("{$g['varetc_path']}/server{$tunnelnumber}-signed.pem", 0600);
383
						fwrite($fd1, $cert);
384
						fclose($fd1);
385

    
386
						$fd1 = fopen("{$g['varetc_path']}/server{$tunnelnumber}-key.pem", "w");
387
						if (!$fd1) {
388
							printf("Error: cannot open server{$tunnelnumber}-key.pem in vpn.\n");
389
							return 1;
390
						}
391
						chmod("{$g['varetc_path']}/server{$tunnelnumber}-key.pem", 0600);
392
						fwrite($fd1, $private_key);
393
						fclose($fd1);
394

    
395
						$certline = "certificate_type x509 \"server{$tunnelnumber}-signed.pem\" \"server{$tunnelnumber}-key.pem\";";
396

    
397
						if ($peercert != '') {
398
							$fd1 = fopen("{$g['varetc_path']}/peer{$tunnelnumber}-signed.pem", "w");
399
							if (!$fd1) {
400
								printf("Error: cannot open server{$tunnelnumber}-signed.pem in vpn.\n");
401
								return 1;
402
							}
403
							chmod("{$g['varetc_path']}/peer{$tunnelnumber}-signed.pem", 0600);
404
							fwrite($fd1, $peercert);
405
							fclose($fd1);
406
							$certline .=<<<EOD
407

    
408
	peers_certfile "peer{$tunnelnumber}-signed.pem";
409
EOD;
410
						}
411
					}
412
					$myidentifier = $myidentt;
413
					if (!empty($myident)) 
414
						$myidentifier .= ' "' . $myident . '"';					
415
					$racoonconf .=<<<EOD
416
remote {$tunnel['remote-gateway']} \{
417
	exchange_mode {$tunnel['p1']['mode']};
418
	my_identifier {$myidentifier};
419
	{$nattline}
420
	{$certline}
421
	peers_identifier address {$rgip};
422
	initial_contact on;
423
	support_proxy on;
424
	proposal_check obey;
425

    
426
	proposal \{
427
		encryption_algorithm {$tunnel['p1']['encryption-algorithm']};
428
		hash_algorithm {$tunnel['p1']['hash-algorithm']};
429
		authentication_method {$authmethod};
430
		dh_group {$tunnel['p1']['dhgroup']};
431

    
432
EOD;
433
					if ($tunnel['p1']['lifetime'])
434
						$racoonconf .= "		lifetime time {$tunnel['p1']['lifetime']} secs;\n";
435

    
436
					$racoonconf .= "	}\n";
437

    
438
					if ($tunnel['p1']['lifetime'])
439
						$racoonconf .= "	lifetime time {$tunnel['p1']['lifetime']} secs;\n";
440

    
441
					$racoonconf .= "}\n\n";
442

    
443
					$p2ealgos = join(",", $tunnel['p2']['encryption-algorithm-option']);
444
					$p2halgos = join(",", $tunnel['p2']['hash-algorithm-option']);
445

    
446
					$racoonconf .=<<<EOD
447
sainfo address {$sa}/{$sn} any address {$tunnel['remote-subnet']} any \{
448
	encryption_algorithm {$p2ealgos};
449
	authentication_algorithm {$p2halgos};
450
	compression_algorithm deflate;
451

    
452
EOD;
453

    
454
					if ($tunnel['p2']['pfsgroup'])
455
						$racoonconf .= "	pfs_group {$tunnel['p2']['pfsgroup']};\n";
456

    
457
					if ($tunnel['p2']['lifetime'])
458
						$racoonconf .= "	lifetime time {$tunnel['p2']['lifetime']} secs;\n";
459

    
460
					$racoonconf .= "}\n\n";
461
				}
462

    
463
			/* mobile clients? */
464
			if (isset ($ipseccfg['mobileclients']['enable'])) {
465

    
466
				$tunnel = $ipseccfg['mobileclients'];
467

    
468
				if (isset ($tunnel['p1']['myident']['myaddress'])) {
469
					$myidentt = "address";
470
					$myident = $curwanip;
471
				} else
472
					if (isset ($tunnel['p1']['myident']['address'])) {
473
						$myidentt = "address";
474
						$myident = $tunnel['p1']['myident']['address'];
475
					} else
476
						if (isset ($tunnel['p1']['myident']['fqdn'])) {
477
							$myidentt = "fqdn";
478
							$myident = $tunnel['p1']['myident']['fqdn'];
479
						} else
480
							if (isset ($tunnel['p1']['myident']['ufqdn'])) {
481
								$myidentt = "user_fqdn";
482
								$myident = $tunnel['p1']['myident']['ufqdn'];
483
							}
484

    
485
				if (isset ($tunnel['p1']['authentication_method'])) {
486
					$authmethod = $tunnel['p1']['authentication_method'];
487
				} else {
488
					$authmethod = 'pre_shared_key';
489
				}
490

    
491
				$certline = '';
492
				if ($authmethod == 'rsasig') {
493
					if ($tunnel['p1']['cert'] && $tunnel['p1']['private-key']) {
494
						$cert = base64_decode($tunnel['p1']['cert']);
495
						$private_key = base64_decode($tunnel['p1']['private-key']);
496
					} else {
497
						/* null certificate/key */
498
						$cert = '';
499
						$private_key = '';
500
					}
501

    
502
					if ($tunnel['p1']['peercert'])
503
						$peercert = base64_decode($tunnel['p1']['peercert']);
504
					else
505
						$peercert = '';
506

    
507
					$fd1 = fopen("{$g['varetc_path']}/server-mobile{$tunnelnumber}-signed.pem", "w");
508
					if (!$fd1) {
509
						printf("Error: cannot open server-mobile{$tunnelnumber}-signed.pem in vpn.\n");
510
						return 1;
511
					}
512
					chmod("{$g['varetc_path']}/server-mobile{$tunnelnumber}-signed.pem", 0600);
513
					fwrite($fd1, $cert);
514
					fclose($fd1);
515

    
516
					$fd1 = fopen("{$g['varetc_path']}/server-mobile{$tunnelnumber}-key.pem", "w");
517
					if (!$fd1) {
518
						printf("Error: cannot open server-mobile{$tunnelnumber}-key.pem in vpn.\n");
519
						return 1;
520
					}
521
					chmod("{$g['varetc_path']}/server-mobile{$tunnelnumber}-key.pem", 0600);
522
					fwrite($fd1, $private_key);
523
					fclose($fd1);
524

    
525
					$certline = "certificate_type x509 \"server-mobile{$tunnelnumber}-signed.pem\" \"server-mobile{$tunnelnumber}-key.pem\";";
526
				}
527
				$racoonconf .=<<<EOD
528
remote anonymous \{
529
	exchange_mode {$tunnel['p1']['mode']};
530
	my_identifier {$myidentt} "{$myident}";
531
	{$certline}
532
	initial_contact on;
533
	passive on;
534
	generate_policy on;
535
	support_proxy on;
536
	proposal_check obey;
537

    
538
	proposal \{
539
		encryption_algorithm {$tunnel['p1']['encryption-algorithm']};
540
		hash_algorithm {$tunnel['p1']['hash-algorithm']};
541
		authentication_method {$authmethod};
542
		dh_group {$tunnel['p1']['dhgroup']};
543

    
544
EOD;
545
				if ($tunnel['p1']['lifetime'])
546
					$racoonconf .= "		lifetime time {$tunnel['p1']['lifetime']} secs;\n";
547

    
548
				$racoonconf .= "	}\n";
549

    
550
				if ($tunnel['p1']['lifetime'])
551
					$racoonconf .= "	lifetime time {$tunnel['p1']['lifetime']} secs;\n";
552

    
553
				$racoonconf .= "}\n\n";
554

    
555
				$p2ealgos = join(",", $tunnel['p2']['encryption-algorithm-option']);
556
				$p2halgos = join(",", $tunnel['p2']['hash-algorithm-option']);
557

    
558
				$racoonconf .=<<<EOD
559
sainfo anonymous \{
560
	encryption_algorithm {$p2ealgos};
561
	authentication_algorithm {$p2halgos};
562
	compression_algorithm deflate;
563

    
564
EOD;
565

    
566
				if ($tunnel['p2']['pfsgroup'])
567
					$racoonconf .= "	pfs_group {$tunnel['p2']['pfsgroup']};\n";
568

    
569
				if ($tunnel['p2']['lifetime'])
570
					$racoonconf .= "	lifetime time {$tunnel['p2']['lifetime']} secs;\n";
571

    
572
				$racoonconf .= "}\n\n";
573
			}
574

    
575
			fwrite($fd, $racoonconf);
576
			fclose($fd);
577

    
578
			/* generate psk.txt */
579
			$fd = fopen("{$g['varetc_path']}/psk.txt", "w");
580
			if (!$fd) {
581
				printf("Error: cannot open psk.txt in vpn_ipsec_configure().\n");
582
				return 1;
583
			}
584

    
585
			$pskconf = "";
586

    
587
			if (is_array($ipseccfg['tunnel'])) {
588
				foreach ($ipseccfg['tunnel'] as $tunnel) {
589
					if (isset ($tunnel['disabled']))
590
						continue;
591
                   $rgip = $rgmap[$tunnel['remote-gateway']];
592
                   if (!$rgip)
593
                           continue;
594
                   $pskconf .= "{$rgip}     {$tunnel['p1']['pre-shared-key']}\n";
595
				}
596
			}
597

    
598
			/* add PSKs for mobile clients */
599
			if (is_array($ipseccfg['mobilekey'])) {
600
				foreach ($ipseccfg['mobilekey'] as $key) {
601
					$pskconf .= "{$key['ident']}	{$key['pre-shared-key']}\n";
602
				}
603
			}
604

    
605
			fwrite($fd, $pskconf);
606
			fclose($fd);
607
			chmod("{$g['varetc_path']}/psk.txt", 0600);
608

    
609

    
610
			if(is_process_running("racoon")) {
611
				/* We are already online, reload */
612
				mwexec("/usr/bin/killall -HUP racoon");
613
				/* flush SPD entries */
614
				mwexec("/sbin/setkey -FP");
615
				mwexec("/sbin/setkey -F");
616
				$i = 0;
617
				while($i < 4) {
618
					/* load SPD */
619
					mwexec("/bin/cat {$g['varetc_path']}/spd.conf | /usr/local/bin/slowdownpipe.sh | /sbin/setkey -c");
620
					sleep(2);
621
					$i++;
622
				}
623
			} else {
624
				/* start racoon */
625
				mwexec("/usr/local/sbin/racoon -f {$g['varetc_path']}/racoon.conf");
626
				/* flush SA + SPD  entries*/
627
				mwexec("/sbin/setkey -FP");
628
				mwexec("/sbin/setkey -F");
629
				$i = 0;
630
				while($i < 4) {
631
					/* load SPD */
632
					mwexec("/bin/cat {$g['varetc_path']}/spd.conf | /usr/local/bin/slowdownpipe.sh | /sbin/setkey -c");
633
					sleep(2);
634
					$i++;
635
				}
636

    
637
				/* start dnswatch, if necessary */
638
				if (count($dnswatch_list) > 0) {
639
					$interval = 60;
640
					if ($ipseccfg['dns-interval']) {
641
						$interval = $ipseccfg['dns-interval'];
642
					}
643
			
644
					$hostnames = "";
645
					foreach ($dnswatch_list as $dns) {
646
						$hostnames .= " " . escapeshellarg($dns);
647
					}
648
					mwexec("/usr/local/bin/dnswatch {$g['varrun_path']}/dnswatch-ipsec.pid $interval " .
649
					escapeshellarg("/etc/rc.newipsecdns") . $hostnames);
650
				}
651
			}
652

    
653
			if (is_array($ipseccfg['tunnel'])) {
654
				foreach ($ipseccfg['tunnel'] as $tunnel) {
655
					if (isset ($tunnel['auto'])) {
656
						$remotehost = substr($tunnel['remote-subnet'], 0, strpos($tunnel['remote-subnet'], "/"));
657
						$srchost = vpn_endpoint_determine($tunnel, $curwanip);
658
						if ($srchost)
659
							mwexec_bg("/sbin/ping -c 10 -S {$srchost} {$remotehost}");
660
					}
661
				}
662
			}
663
		}
664
	}
665

    
666
	vpn_ipsec_failover_configure();
667

    
668
	if (!$g['booting']) {
669
		/* reload the filter */
670
		touch("{$g["tmp_path"]}/filter_dirty");
671
	}
672

    
673
	if ($g['booting'])
674
		echo "done\n";
675

    
676
	return 0;
677
}
678

    
679
function vpn_pptpd_configure() {
680
	global $config, $g;
681

    
682
	$syscfg = $config['system'];
683
	$pptpdcfg = $config['pptpd'];
684

    
685
	$starting_ng = get_number_of_wan_netgraph_interfaces_needed();
686

    
687
	if ($g['booting']) {
688
		if (!$pptpdcfg['mode'] || ($pptpdcfg['mode'] == "off"))
689
			return 0;
690

    
691
		echo "Configuring PPTP VPN service... ";
692
	} else {
693
		/* kill mpd */
694
		killbypid("{$g['varrun_path']}/mpd-vpn.pid");
695

    
696
		/* wait for process to die */
697
		sleep(3);
698

    
699
		if (is_process_running("mpd -b")) {
700
			killbypid("{$g['varrun_path']}/mpd-vpn.pid");
701
			log_error("Could not kill mpd within 3 seconds.   Trying again.");
702
		}
703

    
704
		/* remove mpd.conf, if it exists */
705
		unlink_if_exists("{$g['varetc_path']}/mpd-vpn/mpd.conf");
706
		unlink_if_exists("{$g['varetc_path']}/mpd-vpn/mpd.links");
707
		unlink_if_exists("{$g['varetc_path']}/mpd-vpn/mpd.secret");
708
	}
709

    
710
	/* make sure mpd-vpn directory exists */
711
	if (!file_exists("{$g['varetc_path']}/mpd-vpn"))
712
		mkdir("{$g['varetc_path']}/mpd-vpn");
713

    
714
	switch ($pptpdcfg['mode']) {
715
		case 'server' :
716
			/* write mpd.conf */
717
			$fd = fopen("{$g['varetc_path']}/mpd-vpn/mpd.conf", "w");
718
			if (!$fd) {
719
				printf("Error: cannot open mpd.conf in vpn_pptpd_configure().\n");
720
				return 1;
721
			}
722

    
723
			$mpdconf =<<<EOD
724
pptpd:
725

    
726
EOD;
727

    
728
			for ($i = 0; $i < $g['n_pptp_units']; $i++) {
729
				$mpdconf .= "	load pt{$i}\n";
730
			}
731

    
732
			for ($i = 0; $i < $g['n_pptp_units']; $i++) {
733

    
734
				$clientip = long2ip(ip2long($pptpdcfg['remoteip']) + $i);
735
				$ngif = "ng" . ($i + $starting_ng);
736

    
737
				if(isset($pptpdcfg['radius']['radiusissueips']) && isset($pptpdcfg['radius']['enable'])) {
738
					$isssue_ip_type = "set ipcp ranges {$pptpdcfg['localip']}/32 0.0.0.0/0";
739
					$isssue_ip_type .="\n\tset ipcp yes radius-ip";
740
				} else {
741
					$isssue_ip_type = "set ipcp ranges {$pptpdcfg['localip']}/32 {$clientip}/32";
742
				}
743

    
744
				$mpdconf .=<<<EOD
745

    
746
pt{$i}:
747
	new -i {$ngif} pt{$i} pt{$i}
748
	{$isssue_ip_type}
749
	load pts
750

    
751
EOD;
752
			}
753

    
754
			$mpdconf .=<<<EOD
755

    
756
pts:
757
	set iface disable on-demand
758
	set iface enable proxy-arp
759
	set iface enable tcpmssfix
760
	set iface idle 1800
761
	set iface up-script /usr/local/sbin/vpn-linkup
762
	set iface down-script /usr/local/sbin/vpn-linkdown
763
	set bundle enable multilink
764
	set bundle enable crypt-reqd
765
	set link yes acfcomp protocomp
766
	set link no pap chap
767
	set link enable chap-msv2
768
	set link mtu 1460
769
	set link keep-alive 10 60
770
	set ipcp yes vjcomp
771
	set bundle enable compression
772
	set ccp yes mppc
773
	set ccp yes mpp-e128
774
	set ccp yes mpp-stateless
775

    
776
EOD;
777

    
778
			if (!isset ($pptpdcfg['req128'])) {
779
				$mpdconf .=<<<EOD
780
	set ccp yes mpp-e40
781
	set ccp yes mpp-e56
782

    
783
EOD;
784
			}
785

    
786
			if  (isset($pptpdcfg["wins"]))
787
				$mpdconf  .=  "	set ipcp nbns {$pptpdcfg['wins']}\n";
788
			if (is_array($pptpdcfg['dnsserver']) && ($pptpdcfg['dnsserver'][0])) {
789
				$mpdconf .= "	set ipcp dns " . join(" ", $pptpdcfg['dnsserver']) . "\n";
790
			} else
791
				if (isset ($config['dnsmasq']['enable'])) {
792
					$mpdconf .= "	set ipcp dns " . $config['interfaces']['lan']['ipaddr'];
793
					if ($syscfg['dnsserver'][0])
794
						$mpdconf .= " " . $syscfg['dnsserver'][0];
795
					$mpdconf .= "\n";
796
				} else
797
					if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
798
						$mpdconf .= "	set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n";
799
					}
800

    
801
			if (isset ($pptpdcfg['radius']['enable'])) {
802
				$authport = isset($pptpdcfg['radius']['port']) ? $pptpdcfg['radius']['port'] : 1812;
803
				$acctport = $authport + 1;
804
				$mpdconf .=<<<EOD
805
	set radius server {$pptpdcfg['radius']['server']} "{$pptpdcfg['radius']['secret']}" {$authport} {$acctport}
806
	set radius retries 3
807
	set radius timeout 10
808
	set bundle enable radius-auth
809
	set bundle disable radius-fallback
810

    
811
EOD;
812

    
813
				if (isset ($pptpdcfg['radius']['accounting'])) {
814
					$mpdconf .=<<<EOD
815
	set bundle enable radius-acct
816
	set radius acct-update 300
817

    
818
EOD;
819
				}
820
			}
821

    
822
			fwrite($fd, $mpdconf);
823
			fclose($fd);
824

    
825
			/* write mpd.links */
826
			$fd = fopen("{$g['varetc_path']}/mpd-vpn/mpd.links", "w");
827
			if (!$fd) {
828
				printf("Error: cannot open mpd.links in vpn_pptpd_configure().\n");
829
				return 1;
830
			}
831

    
832
			$mpdlinks = "";
833

    
834
			for ($i = 0; $i < $g['n_pptp_units']; $i++) {
835
				$mpdlinks .=<<<EOD
836

    
837
pt{$i}:
838
	set link type pptp
839
	set pptp enable incoming
840
	set pptp disable originate
841
	set pptp disable windowing
842
	set pptp self 127.0.0.1
843

    
844
EOD;
845
			}
846

    
847
			fwrite($fd, $mpdlinks);
848
			fclose($fd);
849

    
850
			/* write mpd.secret */
851
			$fd = fopen("{$g['varetc_path']}/mpd-vpn/mpd.secret", "w");
852
			if (!$fd) {
853
				printf("Error: cannot open mpd.secret in vpn_pptpd_configure().\n");
854
				return 1;
855
			}
856

    
857
			$mpdsecret = "";
858

    
859
			if (is_array($pptpdcfg['user'])) {
860
				foreach ($pptpdcfg['user'] as $user)
861
					$mpdsecret .= "{$user['name']} \"{$user['password']}\" {$user['ip']}\n";
862
			}
863

    
864
			fwrite($fd, $mpdsecret);
865
			fclose($fd);
866
			chmod("{$g['varetc_path']}/mpd-vpn/mpd.secret", 0600);
867

    
868
			/* fire up mpd */
869
			mwexec("/usr/local/sbin/mpd -b -d {$g['varetc_path']}/mpd-vpn -p {$g['varrun_path']}/mpd-vpn.pid pptpd");
870

    
871
			break;
872

    
873
		case 'redir' :
874
			break;
875
	}
876

    
877
	if (!$g['booting']) {
878
		/* reload the filter */
879
		filter_configure();
880
	}
881

    
882
	if ($g['booting'])
883
		echo "done\n";
884

    
885
	return 0;
886
}
887

    
888
function vpn_localnet_determine($adr, & $sa, & $sn) {
889
	global $config, $g;
890

    
891
	if (isset ($adr)) {
892
		if ($adr['network']) {
893
			switch ($adr['network']) {
894
				case 'lan' :
895
					$sn = $config['interfaces']['lan']['subnet'];
896
					$sa = gen_subnet($config['interfaces']['lan']['ipaddr'], $sn);
897
					break;
898
			}
899
		} else
900
			if ($adr['address']) {
901
				list ($sa, $sn) = explode("/", $adr['address']);
902
				if (is_null($sn))
903
					$sn = 32;
904
			}
905
	} else {
906
		$sn = $config['interfaces']['lan']['subnet'];
907
		$sa = gen_subnet($config['interfaces']['lan']['ipaddr'], $sn);
908
	}
909
}
910

    
911
function vpn_endpoint_determine($tunnel, $curwanip) {
912

    
913
	global $g, $config;
914

    
915
	if ((!$tunnel['interface']) || ($tunnel['interface'] == "wan")) {
916
		if ($curwanip)
917
			return $curwanip;
918
		else
919
			return null;
920
	} elseif ($tunnel['interface'] == "lan") {
921
		return $config['interfaces']['lan']['ipaddr'];
922
	} else {
923
		$oc = $config['interfaces'][$tunnel['interface']];
924
		/* carp ips, etc */
925
		$ip = find_interface_ip($tunnel['interface']);
926
		if($ip) 
927
			return $ip;
928
			
929
		if (isset ($oc['enable']) && $oc['if']) {
930
			return $oc['ipaddr'];
931
		}
932
	}
933

    
934
	return null;
935
}
936

    
937
function vpn_pppoe_configure() {
938
	global $config, $g;
939

    
940
	$syscfg = $config['system'];
941
	$pppoecfg = $config['pppoe'];
942

    
943
	$starting_ng = get_number_of_wan_netgraph_interfaces_needed();
944

    
945
	/* create directory if it does not exist */
946
	if (!is_dir("{$g['varetc_path']}/mpd-vpn"))
947
		mkdir("{$g['varetc_path']}/mpd-vpn");
948

    
949
	if ($g['booting']) {
950
		if (!$pppoecfg['mode'] || ($pppoecfg['mode'] == "off"))
951
			return 0;
952

    
953
		echo "Configuring PPPoE VPN service... ";
954
	} else {
955
		/* kill mpd */
956
		killbypid("{$g['varrun_path']}/mpd-vpn.pid");
957

    
958
		/* wait for process to die */
959
		sleep(2);
960

    
961
	}
962

    
963
	/* make sure mpd-vpn directory exists */
964
	if (!file_exists("{$g['varetc_path']}/mpd-vpn"))
965
		mkdir("{$g['varetc_path']}/mpd-vpn");
966

    
967
	switch ($pppoecfg['mode']) {
968

    
969
		case 'server' :
970

    
971
			$pppoe_interface = filter_translate_type_to_real_interface($pppoecfg['interface']);
972

    
973
			if ($pppoecfg['paporchap'] == "chap")
974
				$paporchap = "set link enable chap";
975
			else
976
				$paporchap = "set link enable pap";
977

    
978
			/* write mpd.conf */
979
			$fd = fopen("{$g['varetc_path']}/mpd-vpn/mpd.conf", "a");
980
			if (!$fd) {
981
				printf("Error: cannot open mpd.conf in vpn_pppoe_configure().\n");
982
				return 1;
983
			}
984
			$mpdconf = "\n\n";
985
			$mpdconf .=<<<EOD
986
pppoe:
987

    
988
EOD;
989

    
990
			for ($i = 0; $i < $pppoecfg['n_pppoe_units']; $i++) {
991
				$mpdconf .= "	load pppoe{$i}\n";
992
			}
993

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

    
996
				$clientip = long2ip(ip2long($pppoecfg['remoteip']) + $i);
997
				$ngif = "ng" . ($i + $starting_ng);
998

    
999
				if (isset ($pppoecfg['radius']['radiusissueips']) && isset ($pppoecfg['radius']['enable'])) {
1000
					$isssue_ip_type = "set ipcp ranges {$pppoecfg['localip']}/32 0.0.0.0/0";
1001
					$isssue_ip_type .= "\n\tset ipcp yes radius-ip";
1002
				} else {
1003
					$isssue_ip_type = "set ipcp ranges {$pppoecfg['localip']}/32 {$clientip}/32";
1004
				}
1005

    
1006
				$mpdconf .=<<<EOD
1007

    
1008
pppoe{$i}:
1009
	new -i {$ngif} pppoe{$i} pppoe{$i}
1010
	{$isssue_ip_type}
1011
	load pppoe_standart
1012

    
1013
EOD;
1014
			}
1015

    
1016
			$mpdconf .=<<<EOD
1017

    
1018
pppoe_standart:
1019
	set link type pppoe
1020
	set pppoe iface {$pppoe_interface}
1021
	set pppoe service "*"
1022
	set pppoe disable originate
1023
	set pppoe enable incoming
1024
	set bundle no multilink
1025
	set bundle enable compression
1026
	set bundle max-logins 1
1027
	set iface idle 0
1028
	set iface disable on-demand
1029
	set iface disable proxy-arp
1030
	set iface enable tcpmssfix
1031
	set iface mtu 1500
1032
	set link no pap chap
1033
	{$paporchap}
1034
	set link keep-alive 60 180
1035
	set ipcp yes vjcomp
1036
	set ipcp no vjcomp
1037
	set link max-redial -1
1038
	set link mtu 1492
1039
	set link mru 1492
1040
	set ccp yes mpp-e40
1041
	set ccp yes mpp-e128
1042
	set ccp yes mpp-stateless
1043
	set link latency 1
1044
	#set ipcp dns 10.10.1.3
1045
	#set bundle accept encryption
1046

    
1047
EOD;
1048

    
1049
			if (isset ($config['dnsmasq']['enable'])) {
1050
				$mpdconf .= "	set ipcp dns " . $config['interfaces']['lan']['ipaddr'];
1051
				if ($syscfg['dnsserver'][0])
1052
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1053
				$mpdconf .= "\n";
1054
			} else
1055
				if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1056
					$mpdconf .= "	set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n";
1057
				}
1058

    
1059
			if (isset ($pppoecfg['radius']['enable'])) {
1060
				$mpdconf .=<<<EOD
1061
	set radius server {$pppoecfg['radius']['server']} "{$pppoecfg['radius']['secret']}"
1062
	set ipcp radius-ip
1063
	set radius retries 3
1064
	set radius timeout 10
1065
	set bundle enable radius-auth
1066
	set bundle disable radius-fallback
1067

    
1068
EOD;
1069

    
1070
				if (isset ($pppoecfg['radius']['accounting'])) {
1071
					$mpdconf .=<<<EOD
1072
	set bundle enable radius-acct
1073

    
1074
EOD;
1075
				}
1076
			}
1077

    
1078
			fwrite($fd, $mpdconf);
1079
			fclose($fd);
1080

    
1081
			/* write mpd.links */
1082
			$fd = fopen("{$g['varetc_path']}/mpd-vpn/mpd.links", "a");
1083
			if (!$fd) {
1084
				printf("Error: cannot open mpd.links in vpn_pppoe_configure().\n");
1085
				return 1;
1086
			}
1087

    
1088
			$mpdlinks = "";
1089

    
1090
			for ($i = 0; $i < $pppoecfg['n_pppoe_units']; $i++) {
1091
				$mpdlinks .=<<<EOD
1092

    
1093
pppoe:
1094
	set link type pppoe
1095
	set pppoe iface {$pppoe_interface}
1096

    
1097
EOD;
1098
			}
1099

    
1100
			fwrite($fd, $mpdlinks);
1101
			fclose($fd);
1102

    
1103
			/* write mpd.secret */
1104
			$fd = fopen("{$g['varetc_path']}/mpd-vpn/mpd.secret", "a");
1105
			if (!$fd) {
1106
				printf("Error: cannot open mpd.secret in vpn_pppoe_configure().\n");
1107
				return 1;
1108
			}
1109

    
1110
			$mpdsecret = "\n\n";
1111

    
1112
			if (is_array($pppoecfg['user'])) {
1113
				foreach ($pppoecfg['user'] as $user)
1114
					$mpdsecret .= "{$user['name']} \"{$user['password']}\" {$user['ip']}\n";
1115
			}
1116

    
1117
			fwrite($fd, $mpdsecret);
1118
			fclose($fd);
1119
			chmod("{$g['varetc_path']}/mpd-vpn/mpd.secret", 0600);
1120

    
1121
			/* fire up mpd */
1122
			mwexec("/usr/local/sbin/mpd -b -d {$g['varetc_path']}/mpd-vpn -p {$g['varrun_path']}/mpd-vpn.pid pppoe");
1123

    
1124
			break;
1125

    
1126
		case 'redir' :
1127
			break;
1128
	}
1129

    
1130
	touch("{$g["tmp_path"]}/filter_dirty");
1131

    
1132
	if ($g['booting'])
1133
		echo "done\n";
1134

    
1135
	return 0;
1136
}
1137

    
1138
function vpn_l2tp_configure() {
1139
	global $config, $g;
1140

    
1141
	$syscfg = $config['system'];
1142
	$l2tpcfg = $config['l2tp'];
1143

    
1144
	mwexec("/sbin/kldload /boot/kernel/ng_l2tp.ko");
1145

    
1146
	$starting_ng = get_number_of_wan_netgraph_interfaces_needed();
1147

    
1148
	/* create directory if it does not exist */
1149
	if (!is_dir("{$g['varetc_path']}/mpd-vpn"))
1150
		mkdir("{$g['varetc_path']}/mpd-vpn");
1151

    
1152
	if ($g['booting']) {
1153
		if (!$l2tpcfg['mode'] || ($l2tpcfg['mode'] == "off"))
1154
			return 0;
1155

    
1156
		echo "Configuring l2tp VPN service... ";
1157
	} else {
1158
		/* kill mpd */
1159
		killbypid("{$g['varrun_path']}/mpd-vpn.pid");
1160

    
1161
		/* wait for process to die */
1162
		sleep(2);
1163

    
1164
	}
1165

    
1166
	/* make sure mpd-vpn directory exists */
1167
	if (!file_exists("{$g['varetc_path']}/mpd-vpn"))
1168
		mkdir("{$g['varetc_path']}/mpd-vpn");
1169

    
1170
	switch ($l2tpcfg['mode']) {
1171

    
1172
		case 'server' :
1173

    
1174
			$l2tp_interface = filter_translate_type_to_real_interface($l2tpcfg['interface']);
1175

    
1176
			if ($l2tpcfg['paporchap'] == "chap")
1177
				$paporchap = "set link enable chap";
1178
			else
1179
				$paporchap = "set link enable pap";
1180

    
1181
			/* write mpd.conf */
1182
			$fd = fopen("{$g['varetc_path']}/mpd-vpn/mpd.conf", "a");
1183
			if (!$fd) {
1184
				printf("Error: cannot open mpd.conf in vpn_l2tp_configure().\n");
1185
				return 1;
1186
			}
1187
			$mpdconf = "\n\n";
1188
			$mpdconf .=<<<EOD
1189
l2tp:
1190

    
1191
EOD;
1192

    
1193
			for ($i = 0; $i < $l2tpcfg['n_l2tp_units']; $i++) {
1194
				$mpdconf .= "	load l2tp{$i}\n";
1195
			}
1196

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

    
1199
				$clientip = long2ip(ip2long($l2tpcfg['remoteip']) + $i);
1200
				$ngif = "ng" . ($i + $starting_ng);
1201

    
1202
				if (isset ($l2tpcfg['radius']['radiusissueips']) && isset ($l2tpcfg['radius']['enable'])) {
1203
					$isssue_ip_type = "set ipcp ranges {$l2tpcfg['localip']}/32 0.0.0.0/0";
1204
					$isssue_ip_type .= "\n\tset ipcp yes radius-ip";
1205
				} else {
1206
					$isssue_ip_type = "set ipcp ranges {$l2tpcfg['localip']}/32 {$clientip}/32";
1207
				}
1208

    
1209
				$mpdconf .=<<<EOD
1210

    
1211
l2tp{$i}:
1212
	new -i {$ngif} l2tp{$i} l2tp{$i}
1213
	{$isssue_ip_type}
1214
	load l2tp_standard
1215

    
1216
EOD;
1217
			}
1218

    
1219
			$mpdconf .=<<<EOD
1220

    
1221
l2tp_standard:
1222
        set bundle disable multilink
1223
        set bundle enable compression
1224
        set bundle yes crypt-reqd
1225
        set ipcp yes vjcomp
1226
        # set ipcp ranges 131.188.69.161/32 131.188.69.170/28
1227
        set ccp yes mppc
1228
        set iface disable on-demand
1229
        set iface enable proxy-arp
1230
        set link yes acfcomp protocomp
1231
        set link no pap chap
1232
        set link enable chap
1233
        set link keep-alive 10 180
1234

    
1235
EOD;
1236

    
1237
			if (isset ($config['dnsmasq']['enable'])) {
1238
				$mpdconf .= "	set ipcp dns " . $config['interfaces']['lan']['ipaddr'];
1239
				if ($syscfg['dnsserver'][0])
1240
					$mpdconf .= " " . $syscfg['dnsserver'][0];
1241
				$mpdconf .= "\n";
1242
			} else
1243
				if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1244
					$mpdconf .= "	set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n";
1245
				}
1246

    
1247
			if (isset ($l2tpcfg['radius']['enable'])) {
1248
				$mpdconf .=<<<EOD
1249
	set radius server {$l2tpcfg['radius']['server']} "{$l2tpcfg['radius']['secret']}"
1250
	set ipcp radius-ip
1251
	set radius retries 3
1252
	set radius timeout 10
1253
	set bundle enable radius-auth
1254
	set bundle disable radius-fallback
1255

    
1256
EOD;
1257

    
1258
				if (isset ($l2tpcfg['radius']['accounting'])) {
1259
					$mpdconf .=<<<EOD
1260
	set bundle enable radius-acct
1261

    
1262
EOD;
1263
				}
1264
			}
1265

    
1266
			fwrite($fd, $mpdconf);
1267
			fclose($fd);
1268

    
1269
			/* write mpd.links */
1270
			$fd = fopen("{$g['varetc_path']}/mpd-vpn/mpd.links", "a");
1271
			if (!$fd) {
1272
				printf("Error: cannot open mpd.links in vpn_l2tp_configure().\n");
1273
				return 1;
1274
			}
1275

    
1276
			$mpdlinks = "";
1277

    
1278
			for ($i = 0; $i < $l2tpcfg['n_l2tp_units']; $i++) {
1279
				$mpdlinks .=<<<EOD
1280

    
1281
l2tp:
1282
	set link type l2tp
1283
	set l2tp iface {$l2tp_interface}
1284

    
1285
EOD;
1286
			}
1287

    
1288
			fwrite($fd, $mpdlinks);
1289
			fclose($fd);
1290

    
1291
			/* write mpd.secret */
1292
			$fd = fopen("{$g['varetc_path']}/mpd-vpn/mpd.secret", "a");
1293
			if (!$fd) {
1294
				printf("Error: cannot open mpd.secret in vpn_l2tp_configure().\n");
1295
				return 1;
1296
			}
1297

    
1298
			$mpdsecret = "\n\n";
1299

    
1300
			if (is_array($l2tpcfg['user'])) {
1301
				foreach ($l2tpcfg['user'] as $user)
1302
					$mpdsecret .= "{$user['name']} \"{$user['password']}\" {$user['ip']}\n";
1303
			}
1304

    
1305
			fwrite($fd, $mpdsecret);
1306
			fclose($fd);
1307
			chmod("{$g['varetc_path']}/mpd-vpn/mpd.secret", 0600);
1308

    
1309
			/* fire up mpd */
1310
			mwexec("/usr/local/sbin/mpd -b -d {$g['varetc_path']}/mpd-vpn -p {$g['varrun_path']}/mpd-vpn.pid l2tp");
1311

    
1312
			break;
1313

    
1314
		case 'redir' :
1315
			break;
1316
	}
1317

    
1318
	touch("{$g["tmp_path"]}/filter_dirty");
1319

    
1320
	if ($g['booting'])
1321
		echo "done\n";
1322

    
1323
	return 0;
1324
}
1325

    
1326
/* Forcefully restart IPsec
1327
 * This is required for when dynamic interfaces reload
1328
 * For all other occasions the normal vpn_ipsec_configure()
1329
 * will gracefully reload the settings without restarting
1330
 */
1331
function vpn_ipsec_force_reload() {
1332
	global $config;
1333
	global $g;
1334

    
1335
	$ipseccfg = $config['ipsec'];
1336

    
1337
	/* kill racoon */
1338
	mwexec("/usr/bin/killall racoon");
1339

    
1340
	/* wait for process to die */
1341
	sleep(4);
1342

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

    
1346
	/* wait for flushing to finish */
1347
	sleep(1);
1348

    
1349
	/* if ipsec is enabled, start up again */
1350
	if (isset($ipseccfg['enable'])) {
1351
		log_error("Forcefully reloading IPsec racoon daemon");
1352
		vpn_ipsec_configure();
1353
	}
1354

    
1355
}
1356

    
1357
?>
(24-24/29)