Project

General

Profile

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

    
3
/* $Id$ */
4
/*
5
	$RCSfile$
6
	
7
	Copyright (C) 2008 Scott Ullrich <sullrich@gmail.com>
8
	All rights reserved.
9
	
10
	Copyright (C) 2006  Fernando Lemos
11
	All rights reserved.
12

    
13
	This file was rewritten from scratch by Fernando Lemos but
14
	*MIGHT* contain code previously written by:
15

    
16
	Copyright (C) 2005 Peter Allgeyer <allgeyer_AT_web.de>
17
	All rights reserved.
18

    
19
	Copyright (C) 2004 Peter Curran (peter@closeconsultants.com).
20
	All rights reserved.
21

    
22
	Redistribution and use in source and binary forms, with or without
23
	modification, are permitted provided that the following conditions are met:
24

    
25
	1. Redistributions of source code must retain the above copyright notices,
26
	   this list of conditions and the following disclaimer.
27

    
28
	2. Redistributions in binary form must reproduce the above copyright
29
	   notices, this list of conditions and the following disclaimer in the
30
	   documentation and/or other materials provided with the distribution.
31

    
32
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
33
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
34
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
35
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
36
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
37
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
39
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
41
	POSSIBILITY OF SUCH DAMAGE.
42
	
43
	DISABLE_PHP_LINT_CHECKING
44
	
45
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/openvpn	/usr/bin/openssl	/sbin/ifconfig
46
	pfSense_MODULE:	openvpn
47

    
48
*/
49
require_once('config.inc');
50
require_once("certs.inc");
51
require_once('pfsense-utils.inc');
52
require_once("auth.inc");
53

    
54
$openvpn_prots = array("UDP", "TCP");
55

    
56
$openvpn_dev_mode = array("tun", "tap");
57

    
58
/* 
59
 * The User Auth mode below is disabled because
60
 * OpenVPN erroneously requires that we provide
61
 * a CA configuration parameter. In this mode,
62
 * clients don't send a certificate so there is
63
 * no need for a CA. If we require that admins
64
 * provide one in the pfSense UI due to a bogus
65
 * requirement imposed by OpenVPN, it could be
66
 * considered very confusing ( I know I was ).
67
 *
68
 * -mgrooms
69
 */
70

    
71
$openvpn_dh_lengths = array(
72
	1024, 2048, 4096 );
73

    
74
$openvpn_server_modes = array(
75
	'p2p_tls' => "Peer to Peer ( SSL/TLS )",
76
	'p2p_shared_key' => "Peer to Peer ( Shared Key )",
77
	'server_tls' => "Remote Access ( SSL/TLS )",
78
	'server_user' => "Remote Access ( User Auth )",
79
	'server_tls_user' => "Remote Access ( SSL/TLS + User Auth )");
80

    
81
$openvpn_client_modes = array(
82
	'p2p_tls' => "Peer to Peer ( SSL/TLS )",
83
	'p2p_shared_key' => "Peer to Peer ( Shared Key )" );
84

    
85
function openvpn_create_key() {
86

    
87
	$fp = popen("/usr/local/sbin/openvpn --genkey --secret /dev/stdout 2>/dev/null", "r");
88
	if (!$fp)
89
		return false;
90

    
91
	$rslt = stream_get_contents($fp);
92
	pclose($fp);
93

    
94
	return $rslt;
95
}
96

    
97
function openvpn_create_dhparams($bits) {
98

    
99
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
100
	if (!$fp)
101
		return false;
102

    
103
	$rslt = stream_get_contents($fp);
104
	pclose($fp);
105

    
106
	return $rslt;
107
}
108

    
109
function openvpn_vpnid_used($vpnid) {
110
	global $config;
111

    
112
	if (is_array($config['openvpn']['openvpn-server']))
113
		foreach ($config['openvpn']['openvpn-server'] as & $settings)
114
			if ($vpnid == $settings['vpnid'])
115
				return true;
116

    
117
	if (is_array($config['openvpn']['openvpn-client']))
118
		foreach ($config['openvpn']['openvpn-client'] as & $settings)
119
			if ($vpnid == $settings['vpnid'])
120
				return true;
121

    
122
	return false;
123
}
124

    
125
function openvpn_vpnid_next() {
126

    
127
	$vpnid = 1;
128
	while(openvpn_vpnid_used($vpnid))
129
		$vpnid++;
130

    
131
	return $vpnid;
132
}
133

    
134
function openvpn_port_used($prot, $port) {
135
	global $config;
136

    
137
	if (is_array($config['openvpn']['openvpn-server']))
138
		foreach ($config['openvpn']['openvpn-server'] as & $settings)
139
			if ($port == $settings['local_port'] &&
140
				$prot == $settings['protocol'])
141
				return $settings['vpnid'];
142

    
143
	if (is_array($config['openvpn']['openvpn-client']))
144
		foreach ($config['openvpn']['openvpn-client'] as & $settings)
145
			if ($port == $settings['local_port'] &&
146
				$prot == $settings['protocol'])
147
				return $settings['vpnid'];
148

    
149
	return 0;
150
}
151

    
152
function openvpn_port_next($prot) {
153

    
154
	$port = 1194;
155
	while(openvpn_port_used($prot, $port))
156
		$port++;
157

    
158
	return $port;
159
}
160

    
161
function openvpn_get_cipherlist() {
162

    
163
	$ciphers = array();
164
	$cipher_out = shell_exec('openvpn --show-ciphers | grep "default key" | awk \'{print $1, "(" $2 "-" $3 ")";}\'');
165
	$cipher_lines = explode("\n", trim($cipher_out));
166
	sort($cipher_lines);
167
	foreach ($cipher_lines as $line) {
168
		$words = explode(' ', $line);
169
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
170
	}
171

    
172
	return $ciphers;
173
}
174

    
175
function openvpn_validate_host($value, $name) {
176
	$value = trim($value);
177
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value)))
178
		return "The field '$name' must contain a valid IP address or domain name.";
179
	return false;
180
}
181

    
182
function openvpn_validate_port($value, $name) {
183
	$value = trim($value);
184
	if (empty($value) || !is_numeric($value) || $value < 0 || ($value > 65535))
185
		return "The field '$name' must contain a valid port, ranging from 0 to 65535.";
186
	return false;
187
}
188

    
189
function openvpn_validate_cidr($value, $name) {
190
	$value = trim($value);
191
	if (!empty($value)) {
192
		list($ip, $mask) = explode('/', $value);
193
		if (!is_ipaddr($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0))
194
			return "The field '$name' must contain a valid CIDR range.";
195
	}
196
	return false;
197
}
198

    
199
function openvpn_add_dhcpopts(& $settings, & $conf) {
200

    
201
	if (!empty($settings['dns_domain'])) 
202
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
203

    
204
	if (!empty($settings['dns_server1']))
205
		$conf .= "push \"dhcp-option DNS {$settings['dns_server1']}\"\n";
206
	if (!empty($settings['dns_server2']))
207
		$conf .= "push \"dhcp-option DNS {$settings['dns_server2']}\"\n";
208
	if (!empty($settings['dns_server3']))
209
		$conf .= "push \"dhcp-option DNS {$settings['dns_server3']}\"\n";
210
	if (!empty($settings['dns_server4']))
211
		$conf .= "push \"dhcp-option DNS {$settings['dns_server4']}\"\n";
212

    
213
	if (!empty($settings['ntp_server1']))
214
		$conf .= "push \"dhcp-option NTP {$settings['dhcp_ntp']}\"\n";
215
	if (!empty($settings['ntp_server2']))
216
		$conf .= "push \"dhcp-option NTP {$settings['dhcp_ntp']}\"\n";
217

    
218
	if ($settings['netbios_enable']) {
219

    
220
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0))
221
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
222
		if (!empty($settings['dhcp_nbtscope'])) 
223
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
224

    
225
		if (!empty($settings['wins_server1']))
226
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
227
		if (!empty($settings['wins_server2']))
228
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
229

    
230
		if (!empty($settings['nbdd_server1']))
231
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
232
	}
233

    
234
	if ($settings['gwredir']) 
235
		$conf .= "push \"redirect-gateway def1\"\n";
236
}
237

    
238
function openvpn_add_custom(& $settings, & $conf) {
239

    
240
	if ($settings['custom_options']) {
241

    
242
		$options = explode(';', $settings['custom_options']);
243

    
244
		if (is_array($options)) {
245
			foreach ($options as $option)
246
				$conf .= "$option\n";
247
		} else
248
			$conf .= "{$settings['custom_options']}\n";
249
	}
250
}
251

    
252
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
253
	global $g;
254

    
255
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.{$directive}";
256
	file_put_contents($fpath, base64_decode($data));
257
	//chown($fpath, 'nobody');
258
	//chgrp($fpath, 'nobody');
259
	@chmod($fpath, 0600);
260

    
261
	$conf .= "{$directive} {$fpath} {$opt}\n";
262
}
263

    
264
function openvpn_reconfigure($mode,& $settings) {
265
	global $g, $config;
266

    
267
	if (empty($settings))
268
		return;
269
	if (isset($settings['disable'])) 
270
		return;
271

    
272
	/*
273
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
274
	 * we use a vpnid number which is allocated for a particular client
275
	 * or server configuration. ( see openvpn_vpnid_next() )
276
	 */
277

    
278
	$vpnid = $settings['vpnid'];
279
	$mode_id = $mode.$vpnid;
280

    
281
	if (isset($settings['dev_mode']))
282
		$tunname = "{$settings['dev_mode']}{$vpnid}";
283
	else {	/* defaults to tun */
284
		$tunname = "tun{$vpnid}";
285
		$settings['dev_mode'] = "tun";
286
	}
287

    
288
	if ($mode == "server")
289
		$devname = "ovpns{$vpnid}";
290
	else
291
		$devname = "ovpnc{$vpnid}";
292

    
293
	/* is our device already configured */
294
	if (mwexec("/sbin/ifconfig {$devname}")) {
295

    
296
		/* create the tap device if required */
297
		if (!file_exists("/dev/{$tunname}"))
298
			exec("/sbin/ifconfig {$tunname} create");
299

    
300
		/* rename the device */
301
		mwexec("/sbin/ifconfig {$tunname} name {$devname}");
302

    
303
		/* add the device to the openvpn group */
304
		mwexec("/sbin/ifconfig {$devname} group openvpn");
305
	}
306

    
307
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
308
	$proto = ($settings['protocol'] == 'UDP' ? 'udp' : "tcp-{$mode}");
309
	$cipher = $settings['crypto'];
310

    
311
	$interface = $settings['interface'];
312
	$ipaddr = $settings['ipaddr'];
313

    
314
	// If a specific ip address (VIP) is requested, use it.
315
	// Otherwise, if a specific interface is requested, use it
316
	// If "any" interface was selected, local directive will be ommited.
317
	if (!empty($ipaddr)) {
318
		$iface_ip=$ipaddr;
319
	} else {
320
		if ((!empty($interface)) && (strcmp($interface, "any"))) {
321
			$iface_ip=get_interface_ip($interface);
322
		}
323
	}
324

    
325
	$conf  = "dev {$devname}\n";
326
	$conf .= "dev-type {$settings['dev_mode']}\n";
327
	$conf .= "dev-node /dev/{$tunname}\n";
328
	$conf .= "writepid {$pfile}\n";
329
	$conf .= "#user nobody\n";
330
	$conf .= "#group nobody\n";
331
	$conf .= "script-security 3\n";
332
	$conf .= "daemon\n";
333
	$conf .= "keepalive 10 60\n";
334
	$conf .= "ping-timer-rem\n";
335
	$conf .= "persist-tun\n";
336
	$conf .= "persist-key\n";
337
	$conf .= "proto {$proto}\n";
338
	$conf .= "cipher {$cipher}\n";
339
	$conf .= "up /etc/rc.filter_configure\n";
340
	$conf .= "down /etc/rc.filter_configure\n";
341

    
342
	if (!empty($iface_ip)) {
343
		$conf .= "local {$iface_ip}\n";	
344
	}
345

    
346
	// server specific settings
347
	if ($mode == 'server') {
348

    
349
		list($ip, $mask) = explode('/', $settings['tunnel_network']);
350
		$mask = gen_subnet_mask($mask);
351

    
352
		// configure tls modes
353
		switch($settings['mode']) {
354
			case 'p2p_tls':
355
			case 'server_tls':
356
			case 'server_user':
357
			case 'server_tls_user':
358
				$conf .= "tls-server\n";
359
				break;
360
		}
361

    
362
		// configure p2p/server modes
363
		switch($settings['mode']) {
364
			case 'p2p_tls':
365
			case 'p2p_shared_key':
366
				$baselong = ip2long($ip) & ip2long($mask);
367
				$ip1 = long2ip($baselong + 1);
368
				$ip2 = long2ip($baselong + 2);
369
				$conf .= "ifconfig $ip1 $ip2\n";
370
				break;
371
			case 'server_tls':
372
			case 'server_user':
373
			case 'server_tls_user':
374
				$conf .= "server {$ip} {$mask}\n";
375
				$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc\n";
376
				break;
377
		}
378

    
379
		// configure user auth modes
380
		switch($settings['mode']) {
381
			case 'server_user':
382
				$conf .= "client-cert-not-required\n";
383
			case 'server_tls_user':
384
				$conf .= "username-as-common-name\n";
385
				if (!empty($settings['authmode'])) {
386
					$authcfgs = explode(",", $settings['authmode']);
387
					$sed = "\$authmodes=array(";
388
					$firstsed = 0;
389
					foreach ($authcfgs as $authcfg) {
390
						if ($firstsed > 0)
391
							$sed .= ",";
392
						$firstsed = 1;
393
						$sed .= "\"{$authcfg}\"";
394
					}
395
					$sed .= ");";
396
					mwexec("/bin/cat /etc/inc/openvpn.auth-user.php | /usr/bin/sed 's/\/\/<template>/{$sed}/g' >  {$g['varetc_path']}/openvpn/{$mode_id}.php");
397
					mwexec("/bin/chmod a+x {$g['varetc_path']}/openvpn/{$mode_id}.php");
398
					$conf .= "auth-user-pass-verify {$g['varetc_path']}/openvpn/{$mode_id}.php via-env\n";
399
				}
400
				break;
401
		}
402

    
403
		// The local port to listen on
404
		$conf .= "lport {$settings['local_port']}\n";
405

    
406
		// The management port to listen on
407
		$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
408

    
409
		if ($settings['maxclients'])
410
			$conf .= "max-clients {$settings['maxclients']}\n";
411

    
412
		// Can we push routes
413
		if ($settings['local_network']) {
414
			list($ip, $mask) = explode('/', $settings['local_network']);
415
			$mask = gen_subnet_mask($mask);
416
			$conf .= "push \"route $ip $mask\"\n";
417
		}
418

    
419
		// Configure client dhcp options
420
		switch($settings['mode']) {
421
			case 'server_tls':
422
			case 'server_user':
423
			case 'server_tls_user':
424
				openvpn_add_dhcpopts($settings, $conf);
425
				break;
426
		}
427
	}
428

    
429
	// client specific settings
430

    
431
	if ($mode == 'client') {
432

    
433
		// configure p2p mode
434
		switch($settings['mode']) {
435
			case 'p2p_tls':
436
				$conf .= "tls-client\n";
437
			case 'shared_key':
438
				$conf .= "client\n";
439
				break;
440
		}
441

    
442
		// The port we'll listen at
443
		// If local_port is used, bind the management port
444
		if ($settings['local_port']) {
445
			$conf .= "lport {$settings['local_port']}\n";
446
			$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
447
		}
448

    
449
		// If there is no bind option at all (ip and/or port), add "nobind" directive
450
		if ((empty($iface_ip)) && (!$settings['local_port'])) {
451
			$conf .= "nobind\n";
452
		}
453

    
454
		// The remote server
455
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
456

    
457
		if (!empty($settings['use_shaper']))
458
			$conf .= "shaper {$settings['use_shaper']}\n";
459

    
460
		if (!empty($settings['tunnel_network'])) {
461
			list($ip, $mask) = explode('/', $settings['tunnel_network']);
462
			$mask = gen_subnet_mask($mask);
463
			$baselong = ip2long($ip) & ip2long($mask);
464
			$ip1 = long2ip($baselong + 1);
465
			$ip2 = long2ip($baselong + 2);
466
			$conf .= "ifconfig $ip2 $ip1\n";
467
		}
468

    
469
		if ($settings['proxy_addr']) {
470
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
471
			if ($settings['proxy_authtype'] != "none") {
472
				$conf .= " {$g['varetc_path']}/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
473
				$proxypas = "{$settings['proxy_user']}\n";
474
				$proxypas .= "{$settings['proxy_passwd']}\n";
475
				file_put_contents("{$g['varetc_path']}/openvpn/{$mode_id}.pas", $proxypas);
476
			}
477
			$conf .= " \n";
478
		}
479
	}
480

    
481
	// Add a remote network route if set
482
	if ($settings['remote_network']) {
483
		list($ip, $mask) = explode('/', $settings['remote_network']);
484
		$mask = gen_subnet_mask($mask);
485
		$conf .= "route $ip $mask\n";
486
	}
487

    
488
	// Write the settings for the keys
489
	switch($settings['mode']) {
490
		case 'p2p_shared_key':
491
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
492
			break;
493
		case 'p2p_tls':
494
		case 'server_tls':
495
		case 'server_tls_user':
496
		case 'server_user':
497
			$ca = lookup_ca($settings['caref']);
498
			openvpn_add_keyfile($ca['crt'], $conf, $mode_id, "ca");
499
			$cert = lookup_cert($settings['certref']);
500
			openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
501
			openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
502
			if ($mode == 'server')
503
				$conf .= "dh {$g['etc_path']}/dh-parameters.{$settings['dh_length']}\n";
504
			if ($settings['crl'])
505
				openvpn_add_keyfile($settings['crl'], $conf, $mode_id, "crl-verify");
506
			if ($settings['tls']) {
507
				if (stristr($settings['mode'], "server"))
508
					$tlsopt = 0;
509
				else
510
					$tlsopt = 1;
511
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, "tls-auth", $tlsopt);
512
			}
513
			break;
514
	}
515

    
516
	if ($settings['compression'])
517
		$conf .= "comp-lzo\n";
518

    
519
	if ($settings['passtos'])
520
		$conf .= "passtos\n";
521

    
522
	if ($settings['resolve_retry'])
523
		$conf .= "resolv-retry infinite\n";
524

    
525
	if ($settings['dynamic_ip']) {
526
		$conf .= "persist-remote-ip\n";
527
		$conf .= "float\n";
528
	}
529

    
530
	openvpn_add_custom($settings, $conf);
531

    
532
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.conf";
533
	file_put_contents($fpath, $conf);
534
	//chown($fpath, 'nobody');
535
	//chgrp($fpath, 'nobody');
536
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
537
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
538
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
539
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
540
}
541

    
542
function openvpn_restart($mode, & $settings) {
543
	global $g, $config;
544

    
545
	$vpnid = $settings['vpnid'];
546
	$mode_id = $mode.$vpnid;
547

    
548
	/* kill the process if running */
549
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
550
	if (file_exists($pfile)) {
551

    
552
		/* read the pid file */
553
		$pid = rtrim(file_get_contents($pfile));
554
		unlink($pfile);
555

    
556
		/* send a term signal to the process */
557
		posix_kill($pid, SIGTERM);
558

    
559
		/* wait until the process exits */
560
		while(posix_kill($pid, 0))
561
			usleep(250000);
562
	}
563

    
564
	if (isset($settings['disable']))
565
		return;
566

    
567
	/* start the new process */
568
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.conf";
569
	mwexec_bg("nohup openvpn --config {$fpath}");
570
	touch("{$g['tmp_path']}/filter_dirty");
571
}
572

    
573
function openvpn_delete($mode, & $settings) {
574
	global $g, $config;
575

    
576
	$vpnid = $settings['vpnid'];
577
	$mode_id = $mode.$vpnid;
578

    
579
	$tunname = "tun{$vpnid}";
580
	if ($mode == "server")
581
		$devname = "ovpns{$vpnid}";
582
	else
583
		$devname = "ovpnc{$vpnid}";
584

    
585
	/* kill the process if running */
586
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
587
	if (file_exists($pfile)) {
588

    
589
		/* read the pid file */
590
		$pid = trim(file_get_contents($pfile));
591
		unlink($pfile);
592

    
593
		/* send a term signal to the process */
594
		posix_kill($pid, SIGTERM);
595
	}
596

    
597
	/* remove the device from the openvpn group */
598
	mwexec("/sbin/ifconfig {$devname} -group openvpn");
599

    
600
	/* restore the original adapter name */
601
	mwexec("/sbin/ifconfig {$devname} name {$tunname}");
602

    
603
	/* remove the configuration files */
604
	mwexec("/bin/rm {$g['varetc_path']}/openvpn/{$mode_id}.*");
605
}
606

    
607
function openvpn_resync_csc(& $settings) {
608
	global $g, $config;
609

    
610
	$fpath = $g['varetc_path']."/openvpn-csc/".$settings['common_name'];
611

    
612
	if (isset($settings['disable'])) {
613
		unlink_if_exists($fpath);
614
		return;
615
	}
616

    
617
	$conf = '';
618
	if ($settings['block'])
619
		$conf .= "disable\n";
620

    
621
	if ($settings['push_reset'])
622
		$conf .= "push-reset\n";
623

    
624
	if (!empty($settings['tunnel_network'])) {
625
		list($ip, $mask) = explode('/', $settings['tunnel_network']);
626
		$baselong = ip2long($ip) & gen_subnet_mask_long($mask);
627
		$ip1 = long2ip($baselong + 1);
628
		$ip2 = long2ip($baselong + 2);
629
		$conf .= "ifconfig-push {$ip1} {$ip2}\n";
630
	}
631

    
632
	openvpn_add_dhcpopts($settings, $conf);
633

    
634
	if ($settings['gwredir'])
635
		$conf .= "push \"redirect-gateway def1\"\n";
636

    
637
	openvpn_add_custom($settings, $conf);
638

    
639
	file_put_contents($fpath, $conf);
640
	chown($fpath, 'nobody');
641
	chgrp($fpath, 'nobody');
642
}
643

    
644
function openvpn_delete_csc(& $settings) {
645
	global $g, $config;
646

    
647
	$fpath = $g['varetc_path']."/openvpn-csc/".$settings['common_name'];
648
	unlink_if_exists($fpath);
649
}
650

    
651
// Resync the configuration and restart the VPN
652
function openvpn_resync($mode, & $settings) {
653
	openvpn_reconfigure($mode, $settings);
654
	openvpn_restart($mode, $settings);
655
}
656

    
657
// Resync and restart all VPNs
658
function openvpn_resync_all($interface = "") {
659
	global $g, $config;
660

    
661
	// delay our setup until the system
662
	// has a chance to init our paths
663
	if (!file_exists($g['varetc_path']."/openvpn") ||
664
		!file_exists($g['varetc_path']."/openvpn-csc"))
665
		return;
666

    
667
	if (!is_array($config['openvpn']))
668
		$config['openvpn'] = array();
669

    
670
/*
671
	if (!$config['openvpn']['dh-parameters']) {
672
		echo "Configuring OpenVPN Parameters ...\n";
673
		$dh_parameters = openvpn_create_dhparams(1024);
674
		$dh_parameters = base64_encode($dh_parameters);
675
		$config['openvpn']['dh-parameters'] = $dh_parameters;
676
		write_config("OpenVPN DH parameters");
677
	}
678

    
679
	$path_ovdh = $g['varetc_path']."/openvpn/dh-parameters";
680
	if (!file_exists($path_ovdh)) {
681
		$dh_parameters = $config['openvpn']['dh-parameters'];
682
		$dh_parameters = base64_decode($dh_parameters);
683
		file_put_contents($path_ovdh, $dh_parameters);
684
	}
685
*/
686

    
687
	if (is_array($config['openvpn']['openvpn-server'])) {
688
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
689
			if (!empty($interface) && $interface != $settings['interface'])
690
				continue;
691
			openvpn_resync('server', $settings);
692
		}
693
	}
694

    
695
	if (is_array($config['openvpn']['openvpn-client'])) {
696
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
697
			if (!empty($interface) && $interface != $settings['interface'])
698
				continue;
699
			openvpn_resync('client', $settings);
700
		}
701
	}
702

    
703
	if (is_array($config['openvpn']['openvpn-csc']))
704
		foreach ($config['openvpn']['openvpn-csc'] as & $settings)
705
			openvpn_resync_csc($settings);
706

    
707
}
708

    
709
function openvpn_get_active_servers() {
710
	$servers = array();
711
	global $config;
712
	if (is_array($config['openvpn']['openvpn-server'])) {
713
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
714
	
715
			$prot = $settings['protocol'];
716
			$port = $settings['local_port'];
717
	
718
			$server = array();
719
			$server['port'] = $settings['local_port'];
720
			if ($settings['description'])
721
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
722
			else
723
				$server['name'] = "Server {$prot}:{$port}";
724
			$server['conns'] = array();
725
	
726
			$tcpsrv = "tcp://127.0.0.1:{$port}";
727
			$errval;
728
			$errstr;
729
	
730
			/* open a tcp connection to the management port of each server */
731
			$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
732
			if ($fp) {
733
	
734
				/* send our status request */
735
				fputs($fp, "status 2\n");
736
	
737
				/* recv all response lines */
738
				while (!feof($fp)) {
739
	
740
					/* read the next line */
741
					$line = fgets($fp, 1024);
742
	
743
					/* parse header list line */
744
					if (strstr($line, "HEADER"))
745
						continue;
746
	
747
					/* parse end of output line */
748
					if (strstr($line, "END"))
749
						break;
750
	
751
					/* parse client list line */
752
					if (strstr($line, "CLIENT_LIST")) {
753
						$list = explode(",", $line);
754
						$conn = array();
755
						$conn['common_name'] = $list[1];
756
						$conn['remote_host'] = $list[2];
757
						$conn['virtual_addr'] = $list[3];
758
						$conn['bytes_recv'] = $list[4];
759
						$conn['bytes_sent'] = $list[5];
760
						$conn['connect_time'] = $list[6];
761
						$server['conns'][] = $conn;
762
					}
763
				}
764
	
765
				/* cleanup */
766
				fclose($fp);
767
			} else {
768
				$conn = array();
769
				$conn['common_name'] = "[error]";
770
				$conn['remote_host'] = "Management Daemon Unreachable";
771
				$conn['virtual_addr'] = "";
772
				$conn['bytes_recv'] = 0;
773
				$conn['bytes_sent'] = 0;
774
				$conn['connect_time'] = 0;
775
				$server['conns'][] = $conn;
776
			}
777
	
778
			$servers[] = $server;
779
		}
780
	}
781
	return $servers;
782
}
783

    
784
function openvpn_get_active_clients() {
785
	$clients = array();
786
	global $config;
787
	if (is_array($config['openvpn']['openvpn-client'])) {
788
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
789
	
790
			$prot = $settings['protocol'];
791
			$port = $settings['local_port'];
792
	
793
			$client = array();
794
			$client['port'] = $settings['local_port'];
795
			if ($settings['description'])
796
				$client['name'] = "{$settings['description']} {$prot}:{$port}";
797
			else
798
				$client['name'] = "Client {$prot}:{$port}";
799
	
800
			$tcpcli = "tcp://127.0.0.1:{$port}";
801
			$errval;
802
			$errstr;
803
	
804
			$client['status']="down";
805
	
806
			/* open a tcp connection to the management port of each cli */
807
			$fp = @stream_socket_client($tcpcli, $errval, $errstr, 1);
808
			if ($fp) {
809
	
810
				/* send our status request */
811
				fputs($fp, "state 1\n");
812
	
813
				/* recv all response lines */
814
				while (!feof($fp)) {
815
					/* read the next line */
816
					$line = fgets($fp, 1024);
817
	
818
					/* Get the client state */
819
					if (strstr($line,"CONNECTED")) {
820
						$client['status']="up";
821
						$list = explode(",", $line);
822
	
823
						$client['connect_time']  = date("D M j G:i:s Y", $list[0]);
824
						$client['virtual_addr']  = $list[3];
825
						$client['remote_host'] = $list[4];
826
					}
827
					/* parse end of output line */
828
					if (strstr($line, "END"))
829
						break;
830
				}
831
	
832
				/* If up, get read/write stats */
833
				if (strcmp($client['status'], "up") == 0) {
834
					fputs($fp, "status 2\n");
835
					/* recv all response lines */
836
					while (!feof($fp)) {
837
						/* read the next line */
838
						$line = fgets($fp, 1024);
839
	
840
						if (strstr($line,"TCP/UDP read bytes")) {
841
							$list = explode(",", $line);
842
							$client['bytes_recv'] = $list[1];
843
						}
844
	
845
						if (strstr($line,"TCP/UDP write bytes")) {
846
							$list = explode(",", $line);
847
							$client['bytes_sent'] = $list[1];
848
						}
849
	
850
						/* parse end of output line */
851
						if (strstr($line, "END"))
852
							break;
853
					}
854
				}
855
	
856
				fclose($fp);
857
	
858
			} else {
859
				$DisplayNote=true;
860
				$client['remote_host'] = "No Management Daemon";
861
				$client['virtual_addr'] = "See Note Below";
862
				$client['bytes_recv'] = 0;
863
				$client['bytes_sent'] = 0;
864
				$client['connect_time'] = 0;
865
			}
866
	
867
			$clients[] = $client;
868
		}
869
	}
870
	return $clients;
871
}
872
?>
(28-28/50)