Project

General

Profile

Download (52.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * openvpn.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2006 Fernando Lemos
7
 * Copyright (c) 2006-2016 Rubicon Communications, LLC (Netgate)
8
 * All rights reserved.
9
 *
10
 * This file was rewritten from scratch by Fernando Lemos but
11
 * *MIGHT* contain code previously written by:
12
 *
13
 * Copyright (c) 2005 Peter Allgeyer <allgeyer_AT_web.de>
14
 * Copyright (c) 2004 Peter Curran (peter@closeconsultants.com).
15
 * All rights reserved.
16
 *
17
 * Redistribution and use in source and binary forms, with or without
18
 * modification, are permitted provided that the following conditions are met:
19
 *
20
 * 1. Redistributions of source code must retain the above copyright notice,
21
 *    this list of conditions and the following disclaimer.
22
 *
23
 * 2. Redistributions in binary form must reproduce the above copyright
24
 *    notice, this list of conditions and the following disclaimer in
25
 *    the documentation and/or other materials provided with the
26
 *    distribution.
27
 *
28
 * 3. All advertising materials mentioning features or use of this software
29
 *    must display the following acknowledgment:
30
 *    "This product includes software developed by the pfSense Project
31
 *    for use in the pfSense® software distribution. (http://www.pfsense.org/).
32
 *
33
 * 4. The names "pfSense" and "pfSense Project" must not be used to
34
 *    endorse or promote products derived from this software without
35
 *    prior written permission. For written permission, please contact
36
 *    coreteam@pfsense.org.
37
 *
38
 * 5. Products derived from this software may not be called "pfSense"
39
 *    nor may "pfSense" appear in their names without prior written
40
 *    permission of the Electric Sheep Fencing, LLC.
41
 *
42
 * 6. Redistributions of any form whatsoever must retain the following
43
 *    acknowledgment:
44
 *
45
 * "This product includes software developed by the pfSense Project
46
 * for use in the pfSense software distribution (http://www.pfsense.org/).
47
 *
48
 * THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
49
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
51
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
52
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
53
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
54
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
55
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
57
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
58
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
59
 * OF THE POSSIBILITY OF SUCH DAMAGE.
60
 */
61

    
62
require_once('config.inc');
63
require_once("certs.inc");
64
require_once('pfsense-utils.inc');
65
require_once("auth.inc");
66

    
67
global $openvpn_prots;
68
$openvpn_prots = array("UDP", "UDP6", "TCP", "TCP6");
69

    
70
global $openvpn_dev_mode;
71
$openvpn_dev_mode = array("tun", "tap");
72

    
73
global $openvpn_verbosity_level;
74
$openvpn_verbosity_level = array(
75
	0 =>	gettext("none"),
76
	1 =>	gettext("default"),
77
	2 =>	"2",
78
	3 =>	gettext("3 (recommended)"),
79
	4 =>	"4",
80
	5 => 	"5",
81
	6 => 	"6",
82
	7 => 	"7",
83
	8 => 	"8",
84
	9 => 	"9",
85
	10 => 	"10",
86
	11 => 	"11"
87
);
88

    
89
/*
90
 * The User Auth mode below is disabled because
91
 * OpenVPN erroneously requires that we provide
92
 * a CA configuration parameter. In this mode,
93
 * clients don't send a certificate so there is
94
 * no need for a CA. If we require that admins
95
 * provide one in the pfSense UI due to a bogus
96
 * requirement imposed by OpenVPN, it could be
97
 * considered very confusing ( I know I was ).
98
 *
99
 * -mgrooms
100
 */
101

    
102
global $openvpn_dh_lengths;
103
$openvpn_dh_lengths = array(
104
	1024, 2048, 3072, 4096, 7680, 8192, 15360, 16384
105
);
106

    
107
global $openvpn_cert_depths;
108
$openvpn_cert_depths = array(
109
	1 => gettext("One (Client+Server)"),
110
	2 => gettext("Two (Client+Intermediate+Server)"),
111
	3 => gettext("Three (Client+2xIntermediate+Server)"),
112
	4 => gettext("Four (Client+3xIntermediate+Server)"),
113
	5 => gettext("Five (Client+4xIntermediate+Server)")
114
);
115

    
116
global $openvpn_server_modes;
117
$openvpn_server_modes = array(
118
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
119
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"),
120
	'server_tls' => gettext("Remote Access ( SSL/TLS )"),
121
	'server_user' => gettext("Remote Access ( User Auth )"),
122
	'server_tls_user' => gettext("Remote Access ( SSL/TLS + User Auth )"));
123

    
124
global $openvpn_tls_server_modes;
125
$openvpn_tls_server_modes = array('p2p_tls', 'server_tls', 'server_user', 'server_tls_user');
126

    
127
global $openvpn_client_modes;
128
$openvpn_client_modes = array(
129
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
130
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"));
131

    
132
global $openvpn_compression_modes;
133
$openvpn_compression_modes = array(
134
	'' => gettext("No Preference"),
135
	'noadapt' => gettext("No Preference and Adaptive Compression Disabled"),
136
	'no' => gettext("Disabled - No Compression"),
137
	'adaptive' => gettext("Enabled with Adaptive Compression"),
138
	'yes' => gettext("Enabled without Adaptive Compression"));
139

    
140
global $openvpn_topologies;
141
$openvpn_topologies = array(
142
	'subnet' => gettext("Subnet -- One IP address per client in a common subnet"),
143
	'net30' => gettext("net30 -- Isolated /30 network per client")
144
//	'p2p => gettext("Peer to Peer -- One IP address per client peer-to-peer style. Does not work on Windows.")
145
);
146

    
147
function openvpn_build_mode_list() {
148
	global $openvpn_server_modes;
149

    
150
	$list = array();
151

    
152
	foreach ($openvpn_server_modes as $name => $desc) {
153
		$list[$name] = $desc;
154
	}
155

    
156
	return($list);
157
}
158

    
159
function openvpn_build_if_list() {
160
	$list = array();
161

    
162
	$interfaces = get_configured_interface_with_descr();
163
	$viplist = get_configured_vip_list();
164
	foreach ($viplist as $vip => $address) {
165
		$interfaces[$vip.'|'.$address] = $address;
166
		if (get_vip_descr($address)) {
167
			$interfaces[$vip.'|'.$address] .= " (";
168
			$interfaces[$vip.'|'.$address] .= get_vip_descr($address);
169
			$interfaces[$vip.'|'.$address] .= ")";
170
		}
171
	}
172

    
173
	$grouplist = return_gateway_groups_array();
174
	foreach ($grouplist as $name => $group) {
175
		if ($group[0]['vip'] != "") {
176
			$vipif = $group[0]['vip'];
177
		} else {
178
			$vipif = $group[0]['int'];
179
		}
180

    
181
		$interfaces[$name] = "GW Group {$name}";
182
	}
183

    
184
	$interfaces['lo0'] = "Localhost";
185
	$interfaces['any'] = "any";
186

    
187
	foreach ($interfaces as $iface => $ifacename) {
188
	   $list[$iface] = $ifacename;
189
	}
190

    
191
	return($list);
192
}
193

    
194
function openvpn_build_crl_list() {
195
	global $a_crl;
196

    
197
	$list = array('' => 'None');
198

    
199
	foreach ($a_crl as $crl) {
200
		$caname = "";
201
		$ca = lookup_ca($crl['caref']);
202

    
203
		if ($ca) {
204
			$caname = " (CA: {$ca['descr']})";
205
		}
206

    
207
		$list[$crl['refid']] = $crl['descr'] . $caname;
208
	}
209

    
210
	return($list);
211
}
212

    
213
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
214
	global $a_cert;
215

    
216
	if ($include_none) {
217
		$list = array('' => gettext('None (Username and/or Password required)'));
218
	} else {
219
		$list = array();
220
	}
221

    
222
	$non_server_list = array();
223

    
224
	if ($prioritize_server_certs) {
225
		$list[' '] = gettext("===== Server Certificates =====");
226
		$non_server_list['  '] = gettext("===== Non-Server Certificates =====");
227
	}
228

    
229
	foreach ($a_cert as $cert) {
230
		$properties = array();
231
		$propstr = "";
232
		$ca = lookup_ca($cert['caref']);
233
		$purpose = cert_get_purpose($cert['crt'], true);
234

    
235
		if ($purpose['server'] == "Yes") {
236
			$properties[] = gettext("Server: Yes");
237
		} elseif ($prioritize_server_certs) {
238
			$properties[] = gettext("Server: NO");
239
		}
240
		if ($ca) {
241
			$properties[] = sprintf(gettext("CA: %s"), $ca['descr']);
242
		}
243
		if (cert_in_use($cert['refid'])) {
244
			$properties[] = gettext("In Use");
245
		}
246
		if (is_cert_revoked($cert)) {
247
			$properties[] = gettext("Revoked");
248
		}
249

    
250
		if (!empty($properties)) {
251
			$propstr = " (" . implode(", ", $properties) . ")";
252
		}
253

    
254
		if ($prioritize_server_certs) {
255
			if ($purpose['server'] == "Yes") {
256
				$list[$cert['refid']] = $cert['descr'] . $propstr;
257
			} else {
258
				$non_server_list[$cert['refid']] = $cert['descr'] . $propstr;
259
			}
260
		} else {
261
			$list[$cert['refid']] = $cert['descr'] . $propstr;
262
		}
263
	}
264

    
265
	return(array('server' => $list, 'non-server' => $non_server_list));
266
}
267

    
268
function openvpn_build_bridge_list() {
269
	$list = array();
270

    
271
	$serverbridge_interface['none'] = "none";
272
	$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
273
	$viplist = get_configured_vip_list();
274

    
275
	foreach ($viplist as $vip => $address) {
276
		$serverbridge_interface[$vip.'|'.$address] = $address;
277
		if (get_vip_descr($address)) {
278
			$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
279
		}
280
	}
281

    
282
	foreach ($serverbridge_interface as $iface => $ifacename) {
283
		$list[$iface] = htmlspecialchars($ifacename);
284
	}
285

    
286
	return($list);
287
}
288

    
289
function openvpn_create_key() {
290

    
291
	$fp = popen("/usr/local/sbin/openvpn --genkey --secret /dev/stdout 2>/dev/null", "r");
292
	if (!$fp) {
293
		return false;
294
	}
295

    
296
	$rslt = stream_get_contents($fp);
297
	pclose($fp);
298

    
299
	return $rslt;
300
}
301

    
302
function openvpn_create_dhparams($bits) {
303

    
304
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
305
	if (!$fp) {
306
		return false;
307
	}
308

    
309
	$rslt = stream_get_contents($fp);
310
	pclose($fp);
311

    
312
	return $rslt;
313
}
314

    
315
function openvpn_vpnid_used($vpnid) {
316
	global $config;
317

    
318
	if (is_array($config['openvpn']['openvpn-server'])) {
319
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
320
			if ($vpnid == $settings['vpnid']) {
321
				return true;
322
			}
323
		}
324
	}
325

    
326
	if (is_array($config['openvpn']['openvpn-client'])) {
327
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
328
			if ($vpnid == $settings['vpnid']) {
329
				return true;
330
			}
331
		}
332
	}
333

    
334
	return false;
335
}
336

    
337
function openvpn_vpnid_next() {
338

    
339
	$vpnid = 1;
340
	while (openvpn_vpnid_used($vpnid)) {
341
		$vpnid++;
342
	}
343

    
344
	return $vpnid;
345
}
346

    
347
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
348
	global $config;
349

    
350
	if (is_array($config['openvpn']['openvpn-server'])) {
351
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
352
			if (isset($settings['disable'])) {
353
				continue;
354
			}
355

    
356
			if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
357
				continue;
358
			}
359

    
360
			if ($port == $settings['local_port'] && $prot == $settings['protocol'] &&
361
			    ($interface == $settings['interface'] || $interface == "any" || $settings['interface'] == "any")) {
362
				return $settings['vpnid'];
363
			}
364
		}
365
	}
366

    
367
	if (is_array($config['openvpn']['openvpn-client'])) {
368
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
369
			if (isset($settings['disable'])) {
370
				continue;
371
			}
372

    
373
			if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
374
				continue;
375
			}
376

    
377
			if ($port == $settings['local_port'] && $prot == $settings['protocol'] &&
378
			    ($interface == $settings['interface'] || $interface == "any" || $settings['interface'] == "any")) {
379
				return $settings['vpnid'];
380
			}
381
		}
382
	}
383

    
384
	return 0;
385
}
386

    
387
function openvpn_port_next($prot, $interface = "wan") {
388

    
389
	$port = 1194;
390
	while (openvpn_port_used($prot, $interface, $port)) {
391
		$port++;
392
	}
393
	while (openvpn_port_used($prot, "any", $port)) {
394
		$port++;
395
	}
396

    
397
	return $port;
398
}
399

    
400
function openvpn_get_cipherlist() {
401

    
402
	$ciphers = array();
403
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
404
	$cipher_lines = explode("\n", trim($cipher_out));
405
	sort($cipher_lines);
406
	foreach ($cipher_lines as $line) {
407
		$words = explode(' ', $line, 2);
408
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
409
	}
410
	$ciphers["none"] = gettext("None (No Encryption)");
411
	return $ciphers;
412
}
413

    
414
function openvpn_get_digestlist() {
415

    
416
	$digests = array();
417
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
418
	$digest_lines = explode("\n", trim($digest_out));
419
	sort($digest_lines);
420
	foreach ($digest_lines as $line) {
421
		$words = explode(' ', $line);
422
		$digests[$words[0]] = "{$words[0]} {$words[1]}";
423
	}
424
	$digests["none"] = gettext("None (No Authentication)");
425
	return $digests;
426
}
427

    
428
function openvpn_get_engines() {
429
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
430
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
431
	$openssl_engine_output = implode("\n", $openssl_engine_output);
432
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
433
	$openssl_engine_output = explode("\n", $openssl_engine_output);
434

    
435
	foreach ($openssl_engine_output as $oeo) {
436
		$keep = true;
437
		$details = explode("|", $oeo);
438
		$engine = array_shift($details);
439
		$linematch = array();
440
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
441
		foreach ($details as $dt) {
442
			if (strpos($dt, "unavailable") !== FALSE) {
443
				$keep = false;
444
			}
445
			if (strpos($dt, "available") !== FALSE) {
446
				continue;
447
			}
448
			if (strpos($dt, "[") !== FALSE) {
449
				$ciphers = trim($dt, "[]");
450
			}
451
		}
452
		if (!empty($ciphers)) {
453
			$ciphers = " - " . $ciphers;
454
		}
455
		if (strlen($ciphers) > 60) {
456
			$ciphers = substr($ciphers, 0, 60) . " ... ";
457
		}
458
		if ($keep) {
459
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
460
		}
461
	}
462
	return $openssl_engines;
463
}
464

    
465
function openvpn_validate_engine($engine) {
466
	$engines = openvpn_get_engines();
467
	return array_key_exists($engine, $engines);
468
}
469

    
470
function openvpn_validate_host($value, $name) {
471
	$value = trim($value);
472
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
473
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
474
	}
475
	return false;
476
}
477

    
478
function openvpn_validate_port($value, $name) {
479
	$value = trim($value);
480
	if (empty($value) || !is_numeric($value) || $value < 0 || ($value > 65535)) {
481
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from 0 to 65535."), $name);
482
	}
483
	return false;
484
}
485

    
486
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4") {
487
	$value = trim($value);
488
	$error = false;
489
	if (empty($value)) {
490
		return false;
491
	}
492
	$networks = explode(',', $value);
493

    
494
	if (!$multiple && (count($networks) > 1)) {
495
		return sprintf(gettext("The field '%1\$s' must contain a single valid %2\$s CIDR range."), $name, $ipproto);
496
	}
497

    
498
	foreach ($networks as $network) {
499
		if ($ipproto == "ipv4") {
500
			$error = !openvpn_validate_cidr_ipv4($network);
501
		} else {
502
			$error = !openvpn_validate_cidr_ipv6($network);
503
		}
504
		if ($error) {
505
			break;
506
		}
507
	}
508

    
509
	if ($error) {
510
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) separated by commas."), $name, $ipproto);
511
	} else {
512
		return false;
513
	}
514
}
515

    
516
function openvpn_validate_cidr_ipv4($value) {
517
	$value = trim($value);
518
	if (!empty($value)) {
519
		list($ip, $mask) = explode('/', $value);
520
		if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0)) {
521
			return false;
522
		}
523
	}
524
	return true;
525
}
526

    
527
function openvpn_validate_cidr_ipv6($value) {
528
	$value = trim($value);
529
	if (!empty($value)) {
530
		list($ipv6, $prefix) = explode('/', $value);
531
		if (empty($prefix)) {
532
			$prefix = "128";
533
		}
534
		if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0)) {
535
			return false;
536
		}
537
	}
538
	return true;
539
}
540

    
541
function openvpn_add_dhcpopts(& $settings, & $conf) {
542

    
543
	if (!empty($settings['dns_domain'])) {
544
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
545
	}
546

    
547
	if (!empty($settings['dns_server1'])) {
548
		$conf .= "push \"dhcp-option DNS {$settings['dns_server1']}\"\n";
549
	}
550
	if (!empty($settings['dns_server2'])) {
551
		$conf .= "push \"dhcp-option DNS {$settings['dns_server2']}\"\n";
552
	}
553
	if (!empty($settings['dns_server3'])) {
554
		$conf .= "push \"dhcp-option DNS {$settings['dns_server3']}\"\n";
555
	}
556
	if (!empty($settings['dns_server4'])) {
557
		$conf .= "push \"dhcp-option DNS {$settings['dns_server4']}\"\n";
558
	}
559

    
560
	if (!empty($settings['push_blockoutsidedns'])) {
561
		$conf .= "push \"block-outside-dns\"\n";
562
	}
563
	if (!empty($settings['push_register_dns'])) {
564
		$conf .= "push \"register-dns\"\n";
565
	}
566

    
567
	if (!empty($settings['ntp_server1'])) {
568
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
569
	}
570
	if (!empty($settings['ntp_server2'])) {
571
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
572
	}
573

    
574
	if ($settings['netbios_enable']) {
575

    
576
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
577
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
578
		}
579
		if (!empty($settings['dhcp_nbtscope'])) {
580
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
581
		}
582

    
583
		if (!empty($settings['wins_server1'])) {
584
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
585
		}
586
		if (!empty($settings['wins_server2'])) {
587
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
588
		}
589

    
590
		if (!empty($settings['nbdd_server1'])) {
591
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
592
		}
593
	}
594

    
595
	if ($settings['gwredir']) {
596
		$conf .= "push \"redirect-gateway def1\"\n";
597
	}
598
}
599

    
600
function openvpn_add_custom(& $settings, & $conf) {
601

    
602
	if ($settings['custom_options']) {
603

    
604
		$options = explode(';', $settings['custom_options']);
605

    
606
		if (is_array($options)) {
607
			foreach ($options as $option) {
608
				$conf .= "$option\n";
609
			}
610
		} else {
611
			$conf .= "{$settings['custom_options']}\n";
612
		}
613
	}
614
}
615

    
616
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
617
	global $g;
618

    
619
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.{$directive}";
620
	openvpn_create_dirs();
621
	file_put_contents($fpath, base64_decode($data));
622
	//chown($fpath, 'nobody');
623
	//chgrp($fpath, 'nobody');
624
	@chmod($fpath, 0600);
625

    
626
	$conf .= "{$directive} {$fpath} {$opt}\n";
627
}
628

    
629
function openvpn_reconfigure($mode, $settings) {
630
	global $g, $config, $openvpn_tls_server_modes;
631

    
632
	if (empty($settings)) {
633
		return;
634
	}
635
	if (isset($settings['disable'])) {
636
		return;
637
	}
638
	openvpn_create_dirs();
639
	/*
640
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
641
	 * we use a vpnid number which is allocated for a particular client
642
	 * or server configuration. ( see openvpn_vpnid_next() )
643
	 */
644

    
645
	$vpnid = $settings['vpnid'];
646
	$mode_id = $mode.$vpnid;
647

    
648
	if (isset($settings['dev_mode'])) {
649
		$tunname = "{$settings['dev_mode']}{$vpnid}";
650
	} else {
651
		/* defaults to tun */
652
		$tunname = "tun{$vpnid}";
653
		$settings['dev_mode'] = "tun";
654
	}
655

    
656
	if ($mode == "server") {
657
		$devname = "ovpns{$vpnid}";
658
	} else {
659
		$devname = "ovpnc{$vpnid}";
660
	}
661

    
662
	/* is our device already configured */
663
	if (!does_interface_exist($devname)) {
664

    
665
		/* create the tap device if required */
666
		if (!file_exists("/dev/{$tunname}")) {
667
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
668
		}
669

    
670
		/* rename the device */
671
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
672

    
673
		/* add the device to the openvpn group and make sure it's UP*/
674
		mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " group openvpn up");
675

    
676
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
677
		$grouptmp = link_interface_to_group($ifname);
678
		if (!empty($grouptmp)) {
679
			array_walk($grouptmp, 'interface_group_add_member');
680
		}
681
		unset($grouptmp, $ifname);
682
	}
683

    
684
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
685
	$proto = strtolower($settings['protocol']);
686
	if (substr($settings['protocol'], 0, 3) == "TCP") {
687
			$proto = "{$proto}-{$mode}";
688
	}
689
	$dev_mode = $settings['dev_mode'];
690
	$cipher = $settings['crypto'];
691
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
692
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
693

    
694
	$interface = get_failover_interface($settings['interface']);
695
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
696
	$ipaddr = $settings['ipaddr'];
697

    
698
	// If a specific ip address (VIP) is requested, use it.
699
	// Otherwise, if a specific interface is requested, use it
700
	// If "any" interface was selected, local directive will be omitted.
701
	if (is_ipaddrv4($ipaddr)) {
702
		$iface_ip = $ipaddr;
703
	} else {
704
		if ((!empty($interface)) && (strcmp($interface, "any"))) {
705
			$iface_ip=get_interface_ip($interface);
706
		}
707
	}
708
	if (is_ipaddrv6($ipaddr)) {
709
		$iface_ipv6 = $ipaddr;
710
	} else {
711
		if ((!empty($interface)) && (strcmp($interface, "any"))) {
712
			$iface_ipv6=get_interface_ipv6($interface);
713
		}
714
	}
715

    
716

    
717
	$conf = "dev {$devname}\n";
718
	if (isset($settings['verbosity_level'])) {
719
		$conf .= "verb {$settings['verbosity_level']}\n";
720
	}
721

    
722
	$conf .= "dev-type {$settings['dev_mode']}\n";
723
	switch ($settings['dev_mode']) {
724
		case "tun":
725
			if (!$settings['no_tun_ipv6']) {
726
				$conf .= "tun-ipv6\n";
727
			}
728
			break;
729
	}
730
	$conf .= "dev-node /dev/{$tunname}\n";
731
	$conf .= "writepid {$pfile}\n";
732
	$conf .= "#user nobody\n";
733
	$conf .= "#group nobody\n";
734
	$conf .= "script-security 3\n";
735
	$conf .= "daemon\n";
736
	$conf .= "keepalive 10 60\n";
737
	$conf .= "ping-timer-rem\n";
738
	$conf .= "persist-tun\n";
739
	$conf .= "persist-key\n";
740
	$conf .= "proto {$proto}\n";
741
	$conf .= "cipher {$cipher}\n";
742
	$conf .= "auth {$digest}\n";
743
	$conf .= "up /usr/local/sbin/ovpn-linkup\n";
744
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
745
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
746
		switch ($settings['mode']) {
747
			case 'server_user':
748
			case 'server_tls_user':
749
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
750
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
751
				break;
752
		}
753
	}
754

    
755
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
756
	if (is_ipaddrv4($iface_ip) && (stristr($settings['protocol'], "6") === false)) {
757
		$conf .= "local {$iface_ip}\n";
758
	} elseif (is_ipaddrv6($iface_ipv6) && (stristr($settings['protocol'], "6") !== false)) {
759
		$conf .= "local {$iface_ipv6}\n";
760
	}
761

    
762
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
763
		$conf .= "engine {$settings['engine']}\n";
764
	}
765

    
766
	// server specific settings
767
	if ($mode == 'server') {
768

    
769
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
770
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
771
		$mask = gen_subnet_mask($cidr);
772

    
773
		// configure tls modes
774
		switch ($settings['mode']) {
775
			case 'p2p_tls':
776
			case 'server_tls':
777
			case 'server_user':
778
			case 'server_tls_user':
779
				$conf .= "tls-server\n";
780
				break;
781
		}
782

    
783
		// configure p2p/server modes
784
		switch ($settings['mode']) {
785
			case 'p2p_tls':
786
				// If the CIDR is less than a /30, OpenVPN will complain if you try to
787
				//  use the server directive. It works for a single client without it.
788
				//  See ticket #1417
789
				if (!empty($ip) && !empty($mask) && ($cidr < 30)) {
790
					$conf .= "server {$ip} {$mask}\n";
791
					$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
792
					if (is_ipaddr($ipv6)) {
793
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
794
					}
795
				}
796
			case 'p2p_shared_key':
797
				if (!empty($ip) && !empty($mask)) {
798
					list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
799
					if ($settings['dev_mode'] == 'tun') {
800
						$conf .= "ifconfig {$ip1} {$ip2}\n";
801
					} else {
802
						$conf .= "ifconfig {$ip1} {$mask}\n";
803
					}
804
				}
805
				if (!empty($ipv6) && !empty($prefix)) {
806
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
807
					if ($settings['dev_mode'] == 'tun') {
808
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$ipv6_2}\n";
809
					} else {
810
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$prefix}\n";
811
					}
812
				}
813
				break;
814
			case 'server_tls':
815
			case 'server_user':
816
			case 'server_tls_user':
817
				if (!empty($ip) && !empty($mask)) {
818
					$conf .= "server {$ip} {$mask}\n";
819
					if (is_ipaddr($ipv6)) {
820
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
821
					}
822
					$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
823
				} else {
824
					if ($settings['serverbridge_dhcp']) {
825
						if ((!empty($settings['serverbridge_interface'])) && (strcmp($settings['serverbridge_interface'], "none"))) {
826
							$biface_ip=get_interface_ip($settings['serverbridge_interface']);
827
							$biface_sm=gen_subnet_mask(get_interface_subnet($settings['serverbridge_interface']));
828
							if (is_ipaddrv4($biface_ip) && is_ipaddrv4($settings['serverbridge_dhcp_start']) && is_ipaddrv4($settings['serverbridge_dhcp_end'])) {
829
								$conf .= "server-bridge {$biface_ip} {$biface_sm} {$settings['serverbridge_dhcp_start']} {$settings['serverbridge_dhcp_end']}\n";
830
								$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
831
							} else {
832
								$conf .= "mode server\n";
833
							}
834
						} else {
835
							$conf .= "mode server\n";
836
						}
837
					}
838
				}
839
				break;
840
		}
841

    
842
		// configure user auth modes
843
		switch ($settings['mode']) {
844
			case 'server_user':
845
				$conf .= "client-cert-not-required\n";
846
			case 'server_tls_user':
847
				/* username-as-common-name is not compatible with server-bridge */
848
				if (stristr($conf, "server-bridge") === false) {
849
					$conf .= "username-as-common-name\n";
850
				}
851
				if (!empty($settings['authmode'])) {
852
					$strictusercn = "false";
853
					if ($settings['strictusercn']) {
854
						$strictusercn = "true";
855
					}
856
					$conf .= "auth-user-pass-verify \"/usr/local/sbin/ovpn_auth_verify user '{$settings['authmode']}' {$strictusercn} {$mode_id} {$settings['local_port']}\" via-env\n";
857
				}
858
				break;
859
		}
860
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
861
			$settings['cert_depth'] = 1;
862
		}
863
		if (is_numeric($settings['cert_depth'])) {
864
			if (($mode == 'client') && empty($settings['certref'])) {
865
				$cert = "";
866
			} else {
867
				$cert = lookup_cert($settings['certref']);
868
				/* XXX: Seems not used at all! */
869
				$servercn = urlencode(cert_get_cn($cert['crt']));
870
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
871
			}
872
		}
873

    
874
		// The local port to listen on
875
		$conf .= "lport {$settings['local_port']}\n";
876

    
877
		// The management port to listen on
878
		// Use unix socket to overcome the problem on any type of server
879
		$conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n";
880
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
881

    
882
		if ($settings['maxclients']) {
883
			$conf .= "max-clients {$settings['maxclients']}\n";
884
		}
885

    
886
		// Can we push routes
887
		if ($settings['local_network']) {
888
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
889
		}
890
		if ($settings['local_networkv6']) {
891
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
892
		}
893

    
894
		switch ($settings['mode']) {
895
			case 'server_tls':
896
			case 'server_user':
897
			case 'server_tls_user':
898
				// Configure client dhcp options
899
				openvpn_add_dhcpopts($settings, $conf);
900
				if ($settings['client2client']) {
901
					$conf .= "client-to-client\n";
902
				}
903
				break;
904
		}
905
		if (isset($settings['duplicate_cn'])) {
906
			$conf .= "duplicate-cn\n";
907
		}
908
	}
909

    
910
	// client specific settings
911

    
912
	if ($mode == 'client') {
913

    
914
		// configure p2p mode
915
		switch ($settings['mode']) {
916
			case 'p2p_tls':
917
				$conf .= "tls-client\n";
918
			case 'shared_key':
919
				$conf .= "client\n";
920
				break;
921
		}
922

    
923
		// If there is no bind option at all (ip and/or port), add "nobind" directive
924
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
925
		//  ensure a random source port.
926
		if ((empty($iface_ip)) && (!$settings['local_port'])) {
927
			$conf .= "nobind\n";
928
		} elseif ($settings['local_port']) {
929
			$conf .= "lport {$settings['local_port']}\n";
930
		} else {
931
			$conf .= "lport 0\n";
932
		}
933

    
934
		// Use unix socket to overcome the problem on any type of server
935
		$conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n";
936

    
937
		// The remote server
938
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
939

    
940
		if (!empty($settings['use_shaper'])) {
941
			$conf .= "shaper {$settings['use_shaper']}\n";
942
		}
943

    
944
		if (!empty($settings['tunnel_network'])) {
945
			list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
946
			$mask = gen_subnet_mask($cidr);
947
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
948
			if ($settings['dev_mode'] == 'tun') {
949
				$conf .= "ifconfig {$ip2} {$ip1}\n";
950
			} else {
951
				$conf .= "ifconfig {$ip2} {$mask}\n";
952
			}
953
		}
954

    
955
		if (!empty($settings['tunnel_networkv6'])) {
956
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
957
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
958
			if ($settings['dev_mode'] == 'tun') {
959
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
960
			} else {
961
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
962
			}
963
		}
964

    
965
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
966
			$up_file = "{$g['varetc_path']}/openvpn/{$mode_id}.up";
967
			$conf .= "auth-user-pass {$up_file}\n";
968
			if ($settings['auth_user']) {
969
				$userpass = "{$settings['auth_user']}\n";
970
			} else {
971
				$userpass = "";
972
			}
973
			if ($settings['auth_pass']) {
974
				$userpass .= "{$settings['auth_pass']}\n";
975
			}
976
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
977
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
978
				$userpass .= "\n";
979
			}
980
			file_put_contents($up_file, $userpass);
981
		}
982

    
983
		if ($settings['proxy_addr']) {
984
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
985
			if ($settings['proxy_authtype'] != "none") {
986
				$conf .= " {$g['varetc_path']}/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
987
				$proxypas = "{$settings['proxy_user']}\n";
988
				$proxypas .= "{$settings['proxy_passwd']}\n";
989
				file_put_contents("{$g['varetc_path']}/openvpn/{$mode_id}.pas", $proxypas);
990
			}
991
			$conf .= " \n";
992
		}
993
	}
994

    
995
	// Add a remote network route if set, and only for p2p modes.
996
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
997
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
998
	}
999
	// Add a remote network route if set, and only for p2p modes.
1000
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
1001
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1002
	}
1003

    
1004
	// Write the settings for the keys
1005
	switch ($settings['mode']) {
1006
		case 'p2p_shared_key':
1007
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
1008
			break;
1009
		case 'p2p_tls':
1010
		case 'server_tls':
1011
		case 'server_tls_user':
1012
		case 'server_user':
1013
			// ca_chain() expects parameter to be passed by reference. 
1014
			// avoid passing the whole settings array, as param names or 
1015
			// types might change in future releases. 
1016
			$param = array('caref' => $settings['caref']);	
1017
			$ca = ca_chain($param);
1018
			$ca = base64_encode($ca);
1019
			
1020
			openvpn_add_keyfile($ca, $conf, $mode_id, "ca");
1021
			
1022
			unset($ca, $param);
1023

    
1024
			if (!empty($settings['certref'])) {
1025
				$cert = lookup_cert($settings['certref']);
1026
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
1027
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
1028
			}
1029
			if ($mode == 'server') {
1030
				$conf .= "dh {$g['etc_path']}/dh-parameters.{$settings['dh_length']}\n";
1031
			}
1032
			if (!empty($settings['crlref'])) {
1033
				$crl = lookup_crl($settings['crlref']);
1034
				crl_update($crl);
1035
				openvpn_add_keyfile($crl['text'], $conf, $mode_id, "crl-verify");
1036
			}
1037
			if ($settings['tls']) {
1038
				if ($mode == "server") {
1039
					$tlsopt = 0;
1040
				} else {
1041
					$tlsopt = 1;
1042
				}
1043
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, "tls-auth", $tlsopt);
1044
			}
1045
			break;
1046
	}
1047

    
1048
	if (!empty($settings['compression'])) {
1049
		if ($settings['compression'] == "noadapt") {
1050
			$conf .= "comp-noadapt\n";
1051
		} else {
1052
			$conf .= "comp-lzo {$settings['compression']}\n";
1053
		}
1054
	}
1055

    
1056
	if ($settings['passtos']) {
1057
		$conf .= "passtos\n";
1058
	}
1059

    
1060
	if ($settings['resolve_retry']) {
1061
		$conf .= "resolv-retry infinite\n";
1062
	} else if ($mode == 'client') {
1063
		$conf .= "resolv-retry infinite\n";
1064
	}
1065

    
1066
	if ($settings['dynamic_ip']) {
1067
		$conf .= "persist-remote-ip\n";
1068
		$conf .= "float\n";
1069
	}
1070

    
1071
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1072
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1073
		if (empty($settings['topology'])) {
1074
			$settings['topology'] = "subnet";
1075
		}
1076
		$conf .= "topology {$settings['topology']}\n";
1077
	}
1078

    
1079
	// New client features
1080
	if ($mode == "client") {
1081
		// Dont pull routes checkbox
1082
		if ($settings['route_no_pull']) {
1083
			$conf .= "route-nopull\n";
1084
		}
1085

    
1086
		// Dont add/remove routes checkbox
1087
		if ($settings['route_no_exec']) {
1088
			$conf .= "route-noexec\n";
1089
		}
1090
	}
1091

    
1092
	openvpn_add_custom($settings, $conf);
1093

    
1094
	openvpn_create_dirs();
1095
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.conf";
1096
	file_put_contents($fpath, $conf);
1097
	unset($conf);
1098
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.interface";
1099
	file_put_contents($fpath, $interface);
1100
	//chown($fpath, 'nobody');
1101
	//chgrp($fpath, 'nobody');
1102
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1103
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.interface", 0600);
1104
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
1105
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
1106
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1107
}
1108

    
1109
function openvpn_restart($mode, $settings) {
1110
	global $g, $config;
1111

    
1112
	$vpnid = $settings['vpnid'];
1113
	$mode_id = $mode.$vpnid;
1114

    
1115
	/* kill the process if running */
1116
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1117
	if (file_exists($pfile)) {
1118

    
1119
		/* read the pid file */
1120
		$pid = rtrim(file_get_contents($pfile));
1121
		unlink($pfile);
1122

    
1123
		/* send a term signal to the process */
1124
		posix_kill($pid, SIGTERM);
1125

    
1126
		/* wait until the process exits, or timeout and kill it */
1127
		$i = 0;
1128
		while (posix_kill($pid, 0)) {
1129
			usleep(250000);
1130
			if ($i > 10) {
1131
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1132
				posix_kill($pid, SIGKILL);
1133
				usleep(500000);
1134
			}
1135
			$i++;
1136
		}
1137
	}
1138

    
1139
	if (isset($settings['disable'])) {
1140
		return;
1141
	}
1142

    
1143
	/* Do not start an instance if we are not CARP master on this vip! */
1144
	if (strstr($settings['interface'], "_vip") && get_carp_interface_status($settings['interface']) != "MASTER") {
1145
		return;
1146
	}
1147

    
1148
	/* Check if client is bound to a gateway group */
1149
	$a_groups = return_gateway_groups_array();
1150
	if (is_array($a_groups[$settings['interface']])) {
1151
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1152
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (get_carp_interface_status($a_groups[$settings['interface']][0]['vip']) != "MASTER")) {
1153
			return;
1154
		}
1155
	}
1156

    
1157
	/* start the new process */
1158
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.conf";
1159
	openvpn_clear_route($mode, $settings);
1160
	mwexec_bg("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1161

    
1162
	if (!platform_booting()) {
1163
		send_event("filter reload");
1164
	}
1165
}
1166

    
1167
function openvpn_delete($mode, & $settings) {
1168
	global $g, $config;
1169

    
1170
	$vpnid = $settings['vpnid'];
1171
	$mode_id = $mode.$vpnid;
1172

    
1173
	if (isset($settings['dev_mode'])) {
1174
		$tunname = "{$settings['dev_mode']}{$vpnid}";
1175
	} else {
1176
		/* defaults to tun */
1177
		$tunname = "tun{$vpnid}";
1178
	}
1179

    
1180
	if ($mode == "server") {
1181
		$devname = "ovpns{$vpnid}";
1182
	} else {
1183
		$devname = "ovpnc{$vpnid}";
1184
	}
1185

    
1186
	/* kill the process if running */
1187
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1188
	if (file_exists($pfile)) {
1189

    
1190
		/* read the pid file */
1191
		$pid = trim(file_get_contents($pfile));
1192
		unlink($pfile);
1193

    
1194
		/* send a term signal to the process */
1195
		posix_kill($pid, SIGTERM);
1196
	}
1197

    
1198
	/* remove the device from the openvpn group */
1199
	mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " -group openvpn");
1200

    
1201
	/* restore the original adapter name */
1202
	mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " name " . escapeshellarg($tunname));
1203

    
1204
	/* remove the configuration files */
1205
	@array_map('unlink', glob("{$g['varetc_path']}/openvpn/{$mode_id}.*"));
1206
}
1207

    
1208
function openvpn_resync_csc(& $settings) {
1209
	global $g, $config, $openvpn_tls_server_modes;
1210

    
1211
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1212

    
1213
	if (isset($settings['disable'])) {
1214
		openvpn_delete_csc($settings);
1215
		return;
1216
	}
1217
	openvpn_create_dirs();
1218

    
1219
	if (empty($settings['server_list'])) {
1220
		$csc_server_list = array();
1221
	} else {
1222
		$csc_server_list = explode(",", $settings['server_list']);
1223
	}
1224

    
1225
	$conf = '';
1226
	if ($settings['block']) {
1227
		$conf .= "disable\n";
1228
	}
1229

    
1230
	if ($settings['push_reset']) {
1231
		$conf .= "push-reset\n";
1232
	}
1233

    
1234
	if ($settings['local_network']) {
1235
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1236
	}
1237
	if ($settings['local_networkv6']) {
1238
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1239
	}
1240

    
1241
	// Add a remote network iroute if set
1242
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1243
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1244
	}
1245
	// Add a remote network iroute if set
1246
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1247
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1248
	}
1249

    
1250
	openvpn_add_dhcpopts($settings, $conf);
1251

    
1252
	openvpn_add_custom($settings, $conf);
1253
	/* Loop through servers, find which ones can use this CSC */
1254
	if (is_array($config['openvpn']['openvpn-server'])) {
1255
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1256
			if (isset($serversettings['disable'])) {
1257
				continue;
1258
			}
1259
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1260
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1261
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1262
					$csc_conf = $conf;
1263

    
1264
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1265
						list($ip, $mask) = explode('/', trim($settings['tunnel_network']));
1266
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1267
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1268
						} else {
1269
							/* Because this is being pushed, the order from the client's point of view. */
1270
							$baselong = gen_subnetv4($ip, $mask);
1271
							$serverip = ip_after($baselong, 1);
1272
							$clientip = ip_after($baselong, 2);
1273
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1274
						}
1275
					}
1276
					file_put_contents($csc_path, $csc_conf);
1277
					chown($csc_path, 'nobody');
1278
					chgrp($csc_path, 'nobody');
1279
				}
1280
			}
1281
		}
1282
	}
1283
}
1284

    
1285
function openvpn_resync_csc_all() {
1286
	global $config;
1287
	if (is_array($config['openvpn']['openvpn-csc'])) {
1288
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1289
			openvpn_resync_csc($settings);
1290
		}
1291
	}
1292
}
1293

    
1294
function openvpn_delete_csc(& $settings) {
1295
	global $g, $config, $openvpn_tls_server_modes;
1296
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1297
	if (empty($settings['server_list'])) {
1298
		$csc_server_list = array();
1299
	} else {
1300
		$csc_server_list = explode(",", $settings['server_list']);
1301
	}
1302

    
1303
	/* Loop through servers, find which ones used this CSC */
1304
	if (is_array($config['openvpn']['openvpn-server'])) {
1305
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1306
			if (isset($serversettings['disable'])) {
1307
				continue;
1308
			}
1309
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1310
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1311
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1312
					unlink_if_exists($csc_path);
1313
				}
1314
			}
1315
		}
1316
	}
1317
}
1318

    
1319
// Resync the configuration and restart the VPN
1320
function openvpn_resync($mode, $settings) {
1321
	openvpn_reconfigure($mode, $settings);
1322
	openvpn_restart($mode, $settings);
1323
}
1324

    
1325
// Resync and restart all VPNs
1326
function openvpn_resync_all($interface = "") {
1327
	global $g, $config;
1328

    
1329
	openvpn_create_dirs();
1330

    
1331
	if (!is_array($config['openvpn'])) {
1332
		$config['openvpn'] = array();
1333
	}
1334

    
1335
/*
1336
	if (!$config['openvpn']['dh-parameters']) {
1337
		echo "Configuring OpenVPN Parameters ...\n";
1338
		$dh_parameters = openvpn_create_dhparams(1024);
1339
		$dh_parameters = base64_encode($dh_parameters);
1340
		$config['openvpn']['dh-parameters'] = $dh_parameters;
1341
		write_config("OpenVPN DH parameters");
1342
	}
1343

    
1344
	$path_ovdh = $g['varetc_path']."/openvpn/dh-parameters";
1345
	if (!file_exists($path_ovdh)) {
1346
		$dh_parameters = $config['openvpn']['dh-parameters'];
1347
		$dh_parameters = base64_decode($dh_parameters);
1348
		file_put_contents($path_ovdh, $dh_parameters);
1349
	}
1350
*/
1351
	if ($interface <> "") {
1352
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1353
	} else {
1354
		log_error(gettext("Resyncing OpenVPN instances."));
1355
	}
1356

    
1357
	if (is_array($config['openvpn']['openvpn-server'])) {
1358
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1359
			if ($interface <> "" && $interface != $settings['interface']) {
1360
				continue;
1361
			}
1362
			openvpn_resync('server', $settings);
1363
		}
1364
	}
1365

    
1366
	if (is_array($config['openvpn']['openvpn-client'])) {
1367
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1368
			if ($interface <> "" && $interface != $settings['interface']) {
1369
				continue;
1370
			}
1371
			openvpn_resync('client', $settings);
1372
		}
1373
	}
1374

    
1375
	openvpn_resync_csc_all();
1376

    
1377
}
1378

    
1379
// Resync and restart all VPNs using a gateway group.
1380
function openvpn_resync_gwgroup($gwgroupname = "") {
1381
	global $g, $config;
1382

    
1383
	if ($gwgroupname <> "") {
1384
		if (is_array($config['openvpn']['openvpn-server'])) {
1385
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1386
				if ($gwgroupname == $settings['interface']) {
1387
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1388
					openvpn_resync('server', $settings);
1389
				}
1390
			}
1391
		}
1392

    
1393
		if (is_array($config['openvpn']['openvpn-client'])) {
1394
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1395
				if ($gwgroupname == $settings['interface']) {
1396
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1397
					openvpn_resync('client', $settings);
1398
				}
1399
			}
1400
		}
1401

    
1402
		// Note: no need to resysnc Client Specific (csc) here, as changes to the OpenVPN real interface do not effect these.
1403

    
1404
	} else {
1405
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1406
	}
1407
}
1408

    
1409
function openvpn_get_active_servers($type="multipoint") {
1410
	global $config, $g;
1411

    
1412
	$servers = array();
1413
	if (is_array($config['openvpn']['openvpn-server'])) {
1414
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1415
			if (empty($settings) || isset($settings['disable'])) {
1416
				continue;
1417
			}
1418

    
1419
			$prot = $settings['protocol'];
1420
			$port = $settings['local_port'];
1421

    
1422
			$server = array();
1423
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1424
			$server['mode'] = $settings['mode'];
1425
			if ($settings['description']) {
1426
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1427
			} else {
1428
				$server['name'] = "Server {$prot}:{$port}";
1429
			}
1430
			$server['conns'] = array();
1431
			$server['vpnid'] = $settings['vpnid'];
1432
			$server['mgmt'] = "server{$server['vpnid']}";
1433
			$socket = "unix://{$g['varetc_path']}/openvpn/{$server['mgmt']}.sock";
1434
			list($tn, $sm) = explode('/', trim($settings['tunnel_network']));
1435

    
1436
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1437
				$servers[] = openvpn_get_client_status($server, $socket);
1438
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1439
				$servers[] = openvpn_get_server_status($server, $socket);
1440
			}
1441
		}
1442
	}
1443
	return $servers;
1444
}
1445

    
1446
function openvpn_get_server_status($server, $socket) {
1447
	$errval = null;
1448
	$errstr = null;
1449
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1450
	if ($fp) {
1451
		stream_set_timeout($fp, 1);
1452

    
1453
		/* send our status request */
1454
		fputs($fp, "status 2\n");
1455

    
1456
		/* recv all response lines */
1457
		while (!feof($fp)) {
1458

    
1459
			/* read the next line */
1460
			$line = fgets($fp, 1024);
1461

    
1462
			$info = stream_get_meta_data($fp);
1463
			if ($info['timed_out']) {
1464
				break;
1465
			}
1466

    
1467
			/* parse header list line */
1468
			if (strstr($line, "HEADER")) {
1469
				continue;
1470
			}
1471

    
1472
			/* parse end of output line */
1473
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1474
				break;
1475
			}
1476

    
1477
			/* parse client list line */
1478
			if (strstr($line, "CLIENT_LIST")) {
1479
				$list = explode(",", $line);
1480
				$conn = array();
1481
				$conn['common_name'] = $list[1];
1482
				$conn['remote_host'] = $list[2];
1483
				$conn['virtual_addr'] = $list[3];
1484
				$conn['bytes_recv'] = $list[4];
1485
				$conn['bytes_sent'] = $list[5];
1486
				$conn['connect_time'] = $list[6];
1487
				$server['conns'][] = $conn;
1488
			}
1489
			/* parse routing table lines */
1490
			if (strstr($line, "ROUTING_TABLE")) {
1491
				$list = explode(",", $line);
1492
				$conn = array();
1493
				$conn['virtual_addr'] = $list[1];
1494
				$conn['common_name'] = $list[2];
1495
				$conn['remote_host'] = $list[3];
1496
				$conn['last_time'] = $list[4];
1497
				$server['routes'][] = $conn;
1498
			}
1499
		}
1500

    
1501
		/* cleanup */
1502
		fclose($fp);
1503
	} else {
1504
		$conn = array();
1505
		$conn['common_name'] = "[error]";
1506
		$conn['remote_host'] = gettext("Unable to contact daemon");
1507
		$conn['virtual_addr'] = gettext("Service not running?");
1508
		$conn['bytes_recv'] = 0;
1509
		$conn['bytes_sent'] = 0;
1510
		$conn['connect_time'] = 0;
1511
		$server['conns'][] = $conn;
1512
	}
1513
	return $server;
1514
}
1515

    
1516
function openvpn_get_active_clients() {
1517
	global $config, $g;
1518

    
1519
	$clients = array();
1520
	if (is_array($config['openvpn']['openvpn-client'])) {
1521
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1522

    
1523
			if (empty($settings) || isset($settings['disable'])) {
1524
				continue;
1525
			}
1526

    
1527
			$prot = $settings['protocol'];
1528
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1529

    
1530
			$client = array();
1531
			$client['port'] = $settings['local_port'];
1532
			if ($settings['description']) {
1533
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1534
			} else {
1535
				$client['name'] = "Client {$prot}{$port}";
1536
			}
1537

    
1538
			$client['vpnid'] = $settings['vpnid'];
1539
			$client['mgmt'] = "client{$client['vpnid']}";
1540
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1541
			$client['status']="down";
1542

    
1543
			$clients[] = openvpn_get_client_status($client, $socket);
1544
		}
1545
	}
1546
	return $clients;
1547
}
1548

    
1549
function openvpn_get_client_status($client, $socket) {
1550
	$errval = null;
1551
	$errstr = null;
1552
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1553
	if ($fp) {
1554
		stream_set_timeout($fp, 1);
1555
		/* send our status request */
1556
		fputs($fp, "state 1\n");
1557

    
1558
		/* recv all response lines */
1559
		while (!feof($fp)) {
1560
			/* read the next line */
1561
			$line = fgets($fp, 1024);
1562

    
1563
			$info = stream_get_meta_data($fp);
1564
			if ($info['timed_out']) {
1565
				break;
1566
			}
1567

    
1568
			/* Get the client state */
1569
			if (strstr($line, "CONNECTED")) {
1570
				$client['status'] = "up";
1571
				$list = explode(",", $line);
1572

    
1573
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1574
				$client['virtual_addr'] = $list[3];
1575
				$client['remote_host'] = $list[4];
1576
			}
1577
			if (strstr($line, "CONNECTING")) {
1578
				$client['status'] = "connecting";
1579
			}
1580
			if (strstr($line, "ASSIGN_IP")) {
1581
				$client['status'] = "waiting";
1582
				$list = explode(",", $line);
1583

    
1584
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1585
				$client['virtual_addr'] = $list[3];
1586
			}
1587
			if (strstr($line, "RECONNECTING")) {
1588
				$client['status'] = "reconnecting";
1589
				$list = explode(",", $line);
1590

    
1591
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1592
				$client['status'] .= "; " . $list[2];
1593
			}
1594
			/* parse end of output line */
1595
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1596
				break;
1597
			}
1598
		}
1599

    
1600
		/* If up, get read/write stats */
1601
		if (strcmp($client['status'], "up") == 0) {
1602
			fputs($fp, "status 2\n");
1603
			/* recv all response lines */
1604
			while (!feof($fp)) {
1605
				/* read the next line */
1606
				$line = fgets($fp, 1024);
1607

    
1608
				$info = stream_get_meta_data($fp);
1609
				if ($info['timed_out']) {
1610
					break;
1611
				}
1612

    
1613
				if (strstr($line, "TCP/UDP read bytes")) {
1614
					$list = explode(",", $line);
1615
					$client['bytes_recv'] = $list[1];
1616
				}
1617

    
1618
				if (strstr($line, "TCP/UDP write bytes")) {
1619
					$list = explode(",", $line);
1620
					$client['bytes_sent'] = $list[1];
1621
				}
1622

    
1623
				/* parse end of output line */
1624
				if (strstr($line, "END")) {
1625
					break;
1626
				}
1627
			}
1628
		}
1629

    
1630
		fclose($fp);
1631

    
1632
	} else {
1633
		$client['remote_host'] = gettext("Unable to contact daemon");
1634
		$client['virtual_addr'] = gettext("Service not running?");
1635
		$client['bytes_recv'] = 0;
1636
		$client['bytes_sent'] = 0;
1637
		$client['connect_time'] = 0;
1638
	}
1639
	return $client;
1640
}
1641

    
1642
function openvpn_kill_client($port, $remipp) {
1643
	global $g;
1644

    
1645
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1646
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1647
	$errval = null;
1648
	$errstr = null;
1649

    
1650
	/* open a tcp connection to the management port of each server */
1651
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1652
	$killed = -1;
1653
	if ($fp) {
1654
		stream_set_timeout($fp, 1);
1655
		fputs($fp, "kill {$remipp}\n");
1656
		while (!feof($fp)) {
1657
			$line = fgets($fp, 1024);
1658

    
1659
			$info = stream_get_meta_data($fp);
1660
			if ($info['timed_out']) {
1661
				break;
1662
			}
1663

    
1664
			/* parse header list line */
1665
			if (strpos($line, "INFO:") !== false) {
1666
				continue;
1667
			}
1668
			if (strpos($line, "SUCCESS") !== false) {
1669
				$killed = 0;
1670
			}
1671
			break;
1672
		}
1673
		fclose($fp);
1674
	}
1675
	return $killed;
1676
}
1677

    
1678
function openvpn_refresh_crls() {
1679
	global $g, $config;
1680

    
1681
	openvpn_create_dirs();
1682

    
1683
	if (is_array($config['openvpn']['openvpn-server'])) {
1684
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1685
			if (empty($settings)) {
1686
				continue;
1687
			}
1688
			if (isset($settings['disable'])) {
1689
				continue;
1690
			}
1691
			// Write the settings for the keys
1692
			switch ($settings['mode']) {
1693
				case 'p2p_tls':
1694
				case 'server_tls':
1695
				case 'server_tls_user':
1696
				case 'server_user':
1697
					if (!empty($settings['crlref'])) {
1698
						$crl = lookup_crl($settings['crlref']);
1699
						crl_update($crl);
1700
						$fpath = $g['varetc_path']."/openvpn/server{$settings['vpnid']}.crl-verify";
1701
						file_put_contents($fpath, base64_decode($crl['text']));
1702
						@chmod($fpath, 0644);
1703
					}
1704
					break;
1705
			}
1706
		}
1707
	}
1708
}
1709

    
1710
function openvpn_create_dirs() {
1711
	global $g, $config, $openvpn_tls_server_modes;
1712
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
1713
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
1714
	}
1715
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
1716
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
1717
	}
1718

    
1719
	/* Check for enabled servers and create server-specific CSC dirs */
1720
	if (is_array($config['openvpn']['openvpn-server'])) {
1721
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1722
			if (isset($settings['disable'])) {
1723
				continue;
1724
			}
1725
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
1726
				if ($settings['vpnid']) {
1727
					safe_mkdir("{$g['varetc_path']}/openvpn-csc/server{$settings['vpnid']}");
1728
				}
1729
			}
1730
		}
1731
	}
1732
}
1733

    
1734
function openvpn_get_interface_ip($ip, $cidr) {
1735
	$subnet = gen_subnetv4($ip, $cidr);
1736
	$ip1 = ip_after($subnet);
1737
	$ip2 = ip_after($ip1);
1738
	return array($ip1, $ip2);
1739
}
1740

    
1741
function openvpn_get_interface_ipv6($ipv6, $prefix) {
1742
	$basev6 = gen_subnetv6($ipv6, $prefix);
1743
	// Is there a better way to do this math?
1744
	$ipv6_arr = explode(':', $basev6);
1745
	$last = hexdec(array_pop($ipv6_arr));
1746
	$ipv6_1 = Net_IPv6::compress(Net_IPv6::uncompress(implode(':', $ipv6_arr) . ':' . dechex($last + 1)));
1747
	$ipv6_2 = Net_IPv6::compress(Net_IPv6::uncompress(implode(':', $ipv6_arr) . ':' . dechex($last + 2)));
1748
	return array($ipv6_1, $ipv6_2);
1749
}
1750

    
1751
function openvpn_clear_route($mode, $settings) {
1752
	if (empty($settings['tunnel_network'])) {
1753
		return;
1754
	}
1755
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1756
	$mask = gen_subnet_mask($cidr);
1757
	$clear_route = false;
1758

    
1759
	switch ($settings['mode']) {
1760
		case 'shared_key':
1761
			$clear_route = true;
1762
			break;
1763
		case 'p2p_tls':
1764
		case 'p2p_shared_key':
1765
			if ($cidr == 30) {
1766
				$clear_route = true;
1767
			}
1768
			break;
1769
	}
1770

    
1771
	if ($clear_route && !empty($ip) && !empty($mask)) {
1772
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1773
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
1774
		/* XXX: Family for route? */
1775
		mwexec("/sbin/route -q delete {$ip_to_clear}");
1776
	}
1777
}
1778

    
1779
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
1780
	$routes = "";
1781
	if (empty($value)) {
1782
		return "";
1783
	}
1784
	$networks = explode(',', $value);
1785

    
1786
	foreach ($networks as $network) {
1787
		if ($ipproto == "ipv4") {
1788
			$route = openvpn_gen_route_ipv4($network, $iroute);
1789
		} else {
1790
			$route = openvpn_gen_route_ipv6($network, $iroute);
1791
		}
1792

    
1793
		if ($push) {
1794
			$routes .= "push \"{$route}\"\n";
1795
		} else {
1796
			$routes .= "{$route}\n";
1797
		}
1798
	}
1799
	return $routes;
1800
}
1801

    
1802
function openvpn_gen_route_ipv4($network, $iroute = false) {
1803
	$i = ($iroute) ? "i" : "";
1804
	list($ip, $mask) = explode('/', trim($network));
1805
	$mask = gen_subnet_mask($mask);
1806
	return "{$i}route $ip $mask";
1807
}
1808

    
1809
function openvpn_gen_route_ipv6($network, $iroute = false) {
1810
	$i = ($iroute) ? "i" : "";
1811
	list($ipv6, $prefix) = explode('/', trim($network));
1812
	if (empty($prefix)) {
1813
		$prefix = "128";
1814
	}
1815
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
1816
}
1817

    
1818
function openvpn_get_settings($mode, $vpnid) {
1819
	global $config;
1820

    
1821
	if (is_array($config['openvpn']['openvpn-server'])) {
1822
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1823
			if (isset($settings['disable'])) {
1824
				continue;
1825
			}
1826

    
1827
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
1828
				return $settings;
1829
			}
1830
		}
1831
	}
1832

    
1833
	if (is_array($config['openvpn']['openvpn-client'])) {
1834
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
1835
			if (isset($settings['disable'])) {
1836
				continue;
1837
			}
1838

    
1839
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
1840
				return $settings;
1841
			}
1842
		}
1843
	}
1844

    
1845
	return array();
1846
}
1847

    
1848
function openvpn_restart_by_vpnid($mode, $vpnid) {
1849
	$settings = openvpn_get_settings($mode, $vpnid);
1850
	openvpn_restart($mode, $settings);
1851
}
1852

    
1853
?>
(37-37/65)