Project

General

Profile

Download (52.8 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
	$ovpn_settings = array();
351
	if (is_array($config['openvpn']['openvpn-server'])) {
352
		$ovpn_settings = $config['openvpn']['openvpn-server'];
353
	}
354
	if (is_array($config['openvpn']['openvpn-client'])) {
355
		$ovpn_settings = array_merge($ovpn_settings,
356
		    $config['openvpn']['openvpn-client']);
357
	}
358

    
359
	foreach ($ovpn_settings as $settings) {
360
		if (isset($settings['disable'])) {
361
			continue;
362
		}
363

    
364
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
365
			continue;
366
		}
367

    
368
		if ($port == $settings['local_port'] &&
369
		    $prot == $settings['protocol'] &&
370
		    ($interface == $settings['interface'] ||
371
		    $interface == "any" || $settings['interface'] == "any")) {
372
			return $settings['vpnid'];
373
		}
374
	}
375

    
376
	return 0;
377
}
378

    
379
function openvpn_port_next($prot, $interface = "wan") {
380

    
381
	$port = 1194;
382
	while (openvpn_port_used($prot, $interface, $port)) {
383
		$port++;
384
	}
385
	while (openvpn_port_used($prot, "any", $port)) {
386
		$port++;
387
	}
388

    
389
	return $port;
390
}
391

    
392
function openvpn_get_cipherlist() {
393

    
394
	$ciphers = array();
395
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
396
	$cipher_lines = explode("\n", trim($cipher_out));
397
	sort($cipher_lines);
398
	foreach ($cipher_lines as $line) {
399
		$words = explode(' ', $line, 2);
400
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
401
	}
402
	$ciphers["none"] = gettext("None (No Encryption)");
403
	return $ciphers;
404
}
405

    
406
function openvpn_get_digestlist() {
407

    
408
	$digests = array();
409
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
410
	$digest_lines = explode("\n", trim($digest_out));
411
	sort($digest_lines);
412
	foreach ($digest_lines as $line) {
413
		$words = explode(' ', $line);
414
		$digests[$words[0]] = "{$words[0]} {$words[1]}";
415
	}
416
	$digests["none"] = gettext("None (No Authentication)");
417
	return $digests;
418
}
419

    
420
function openvpn_get_engines() {
421
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
422
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
423
	$openssl_engine_output = implode("\n", $openssl_engine_output);
424
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
425
	$openssl_engine_output = explode("\n", $openssl_engine_output);
426

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

    
457
function openvpn_validate_engine($engine) {
458
	$engines = openvpn_get_engines();
459
	return array_key_exists($engine, $engines);
460
}
461

    
462
function openvpn_validate_host($value, $name) {
463
	$value = trim($value);
464
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
465
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
466
	}
467
	return false;
468
}
469

    
470
function openvpn_validate_port($value, $name) {
471
	$value = trim($value);
472
	if (empty($value) || !is_numeric($value) || $value < 0 || ($value > 65535)) {
473
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from 0 to 65535."), $name);
474
	}
475
	return false;
476
}
477

    
478
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4") {
479
	$value = trim($value);
480
	$error = false;
481
	if (empty($value)) {
482
		return false;
483
	}
484
	$networks = explode(',', $value);
485

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

    
490
	foreach ($networks as $network) {
491
		if ($ipproto == "ipv4") {
492
			$error = !openvpn_validate_cidr_ipv4($network);
493
		} else {
494
			$error = !openvpn_validate_cidr_ipv6($network);
495
		}
496
		if ($error) {
497
			break;
498
		}
499
	}
500

    
501
	if ($error) {
502
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) separated by commas."), $name, $ipproto);
503
	} else {
504
		return false;
505
	}
506
}
507

    
508
function openvpn_validate_cidr_ipv4($value) {
509
	$value = trim($value);
510
	if (!empty($value)) {
511
		list($ip, $mask) = explode('/', $value);
512
		if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0)) {
513
			return false;
514
		}
515
	}
516
	return true;
517
}
518

    
519
function openvpn_validate_cidr_ipv6($value) {
520
	$value = trim($value);
521
	if (!empty($value)) {
522
		list($ipv6, $prefix) = explode('/', $value);
523
		if (empty($prefix)) {
524
			$prefix = "128";
525
		}
526
		if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0)) {
527
			return false;
528
		}
529
	}
530
	return true;
531
}
532

    
533
function openvpn_add_dhcpopts(& $settings, & $conf) {
534

    
535
	if (!empty($settings['dns_domain'])) {
536
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
537
	}
538

    
539
	if (!empty($settings['dns_server1'])) {
540
		$conf .= "push \"dhcp-option DNS {$settings['dns_server1']}\"\n";
541
	}
542
	if (!empty($settings['dns_server2'])) {
543
		$conf .= "push \"dhcp-option DNS {$settings['dns_server2']}\"\n";
544
	}
545
	if (!empty($settings['dns_server3'])) {
546
		$conf .= "push \"dhcp-option DNS {$settings['dns_server3']}\"\n";
547
	}
548
	if (!empty($settings['dns_server4'])) {
549
		$conf .= "push \"dhcp-option DNS {$settings['dns_server4']}\"\n";
550
	}
551

    
552
	if (!empty($settings['push_blockoutsidedns'])) {
553
		$conf .= "push \"block-outside-dns\"\n";
554
	}
555
	if (!empty($settings['push_register_dns'])) {
556
		$conf .= "push \"register-dns\"\n";
557
	}
558

    
559
	if (!empty($settings['ntp_server1'])) {
560
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
561
	}
562
	if (!empty($settings['ntp_server2'])) {
563
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
564
	}
565

    
566
	if ($settings['netbios_enable']) {
567

    
568
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
569
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
570
		}
571
		if (!empty($settings['dhcp_nbtscope'])) {
572
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
573
		}
574

    
575
		if (!empty($settings['wins_server1'])) {
576
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
577
		}
578
		if (!empty($settings['wins_server2'])) {
579
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
580
		}
581

    
582
		if (!empty($settings['nbdd_server1'])) {
583
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
584
		}
585
	}
586

    
587
	if ($settings['gwredir']) {
588
		$conf .= "push \"redirect-gateway def1\"\n";
589
	}
590
}
591

    
592
function openvpn_add_custom(& $settings, & $conf) {
593

    
594
	if ($settings['custom_options']) {
595

    
596
		$options = explode(';', $settings['custom_options']);
597

    
598
		if (is_array($options)) {
599
			foreach ($options as $option) {
600
				$conf .= "$option\n";
601
			}
602
		} else {
603
			$conf .= "{$settings['custom_options']}\n";
604
		}
605
	}
606
}
607

    
608
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
609
	global $g;
610

    
611
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.{$directive}";
612
	openvpn_create_dirs();
613
	file_put_contents($fpath, base64_decode($data));
614
	//chown($fpath, 'nobody');
615
	//chgrp($fpath, 'nobody');
616
	@chmod($fpath, 0600);
617

    
618
	$conf .= "{$directive} {$fpath} {$opt}\n";
619
}
620

    
621
function openvpn_reconfigure($mode, $settings) {
622
	global $g, $config, $openvpn_tls_server_modes;
623

    
624
	if (empty($settings)) {
625
		return;
626
	}
627
	if (isset($settings['disable'])) {
628
		return;
629
	}
630
	openvpn_create_dirs();
631
	/*
632
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
633
	 * we use a vpnid number which is allocated for a particular client
634
	 * or server configuration. ( see openvpn_vpnid_next() )
635
	 */
636

    
637
	$vpnid = $settings['vpnid'];
638
	$mode_id = $mode.$vpnid;
639

    
640
	if (isset($settings['dev_mode'])) {
641
		$tunname = "{$settings['dev_mode']}{$vpnid}";
642
	} else {
643
		/* defaults to tun */
644
		$tunname = "tun{$vpnid}";
645
		$settings['dev_mode'] = "tun";
646
	}
647

    
648
	if ($mode == "server") {
649
		$devname = "ovpns{$vpnid}";
650
	} else {
651
		$devname = "ovpnc{$vpnid}";
652
	}
653

    
654
	/* is our device already configured */
655
	if (!does_interface_exist($devname)) {
656

    
657
		/* create the tap device if required */
658
		if (!file_exists("/dev/{$tunname}")) {
659
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
660
		}
661

    
662
		/* rename the device */
663
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
664

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

    
668
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
669
		$grouptmp = link_interface_to_group($ifname);
670
		if (!empty($grouptmp)) {
671
			array_walk($grouptmp, 'interface_group_add_member');
672
		}
673
		unset($grouptmp, $ifname);
674
	}
675

    
676
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
677
	$proto = strtolower($settings['protocol']);
678
	if (substr($settings['protocol'], 0, 3) == "TCP") {
679
			$proto = "{$proto}-{$mode}";
680
	}
681
	$dev_mode = $settings['dev_mode'];
682
	$cipher = $settings['crypto'];
683
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
684
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
685

    
686
	$interface = get_failover_interface($settings['interface']);
687
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
688
	$ipaddr = $settings['ipaddr'];
689

    
690
	// If a specific ip address (VIP) is requested, use it.
691
	// Otherwise, if a specific interface is requested, use it
692
	// If "any" interface was selected, local directive will be omitted.
693
	if (is_ipaddrv4($ipaddr)) {
694
		$iface_ip = $ipaddr;
695
	} elseif (!empty($interface) && strcmp($interface, "any")) {
696
		$iface_ip=get_interface_ip($interface);
697
	}
698
	if (is_ipaddrv6($ipaddr)) {
699
		$iface_ipv6 = $ipaddr;
700
	} elseif (!empty($interface) && strcmp($interface, "any")) {
701
		$iface_ipv6=get_interface_ipv6($interface);
702
	}
703

    
704
	$conf = "dev {$devname}\n";
705
	if (isset($settings['verbosity_level'])) {
706
		$conf .= "verb {$settings['verbosity_level']}\n";
707
	}
708

    
709
	$conf .= "dev-type {$settings['dev_mode']}\n";
710
	switch ($settings['dev_mode']) {
711
		case "tun":
712
			if (!$settings['no_tun_ipv6']) {
713
				$conf .= "tun-ipv6\n";
714
			}
715
			break;
716
	}
717
	$conf .= "dev-node /dev/{$tunname}\n";
718
	$conf .= "writepid {$pfile}\n";
719
	$conf .= "#user nobody\n";
720
	$conf .= "#group nobody\n";
721
	$conf .= "script-security 3\n";
722
	$conf .= "daemon\n";
723
	$conf .= "keepalive 10 60\n";
724
	$conf .= "ping-timer-rem\n";
725
	$conf .= "persist-tun\n";
726
	$conf .= "persist-key\n";
727
	$conf .= "proto {$proto}\n";
728
	$conf .= "cipher {$cipher}\n";
729
	$conf .= "auth {$digest}\n";
730
	$conf .= "up /usr/local/sbin/ovpn-linkup\n";
731
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
732
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
733
		switch ($settings['mode']) {
734
			case 'server_user':
735
			case 'server_tls_user':
736
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
737
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
738
				break;
739
		}
740
	}
741

    
742
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
743
	if (is_ipaddrv4($iface_ip) && (stristr($settings['protocol'], "6") === false)) {
744
		$conf .= "local {$iface_ip}\n";
745
	} elseif (is_ipaddrv6($iface_ipv6) && (stristr($settings['protocol'], "6") !== false)) {
746
		$conf .= "local {$iface_ipv6}\n";
747
	}
748

    
749
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
750
		$conf .= "engine {$settings['engine']}\n";
751
	}
752

    
753
	// server specific settings
754
	if ($mode == 'server') {
755

    
756
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
757
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
758
		$mask = gen_subnet_mask($cidr);
759

    
760
		// configure tls modes
761
		switch ($settings['mode']) {
762
			case 'p2p_tls':
763
			case 'server_tls':
764
			case 'server_user':
765
			case 'server_tls_user':
766
				$conf .= "tls-server\n";
767
				break;
768
		}
769

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

    
829
		// configure user auth modes
830
		switch ($settings['mode']) {
831
			case 'server_user':
832
				$conf .= "client-cert-not-required\n";
833
			case 'server_tls_user':
834
				/* username-as-common-name is not compatible with server-bridge */
835
				if (stristr($conf, "server-bridge") === false) {
836
					$conf .= "username-as-common-name\n";
837
				}
838
				if (!empty($settings['authmode'])) {
839
					$strictusercn = "false";
840
					if ($settings['strictusercn']) {
841
						$strictusercn = "true";
842
					}
843
					$conf .= "auth-user-pass-verify \"/usr/local/sbin/ovpn_auth_verify user " . base64_encode($settings['authmode']) . " {$strictusercn} {$mode_id} {$settings['local_port']}\" via-env\n";
844
				}
845
				break;
846
		}
847
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
848
			$settings['cert_depth'] = 1;
849
		}
850
		if (is_numeric($settings['cert_depth'])) {
851
			if (($mode == 'client') && empty($settings['certref'])) {
852
				$cert = "";
853
			} else {
854
				$cert = lookup_cert($settings['certref']);
855
				/* XXX: Seems not used at all! */
856
				$servercn = urlencode(cert_get_cn($cert['crt']));
857
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
858
			}
859
		}
860

    
861
		// The local port to listen on
862
		$conf .= "lport {$settings['local_port']}\n";
863

    
864
		// The management port to listen on
865
		// Use unix socket to overcome the problem on any type of server
866
		$conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n";
867
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
868

    
869
		if ($settings['maxclients']) {
870
			$conf .= "max-clients {$settings['maxclients']}\n";
871
		}
872

    
873
		// Can we push routes
874
		if ($settings['local_network']) {
875
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
876
		}
877
		if ($settings['local_networkv6']) {
878
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
879
		}
880

    
881
		switch ($settings['mode']) {
882
			case 'server_tls':
883
			case 'server_user':
884
			case 'server_tls_user':
885
				// Configure client dhcp options
886
				openvpn_add_dhcpopts($settings, $conf);
887
				if ($settings['client2client']) {
888
					$conf .= "client-to-client\n";
889
				}
890
				break;
891
		}
892
		if (isset($settings['duplicate_cn'])) {
893
			$conf .= "duplicate-cn\n";
894
		}
895
	}
896

    
897
	// client specific settings
898

    
899
	if ($mode == 'client') {
900

    
901
		// configure p2p mode
902
		switch ($settings['mode']) {
903
			case 'p2p_tls':
904
				$conf .= "tls-client\n";
905
			case 'shared_key':
906
				$conf .= "client\n";
907
				break;
908
		}
909

    
910
		// If there is no bind option at all (ip and/or port), add "nobind" directive
911
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
912
		//  ensure a random source port.
913
		if ((empty($iface_ip)) && (!$settings['local_port'])) {
914
			$conf .= "nobind\n";
915
		} elseif ($settings['local_port']) {
916
			$conf .= "lport {$settings['local_port']}\n";
917
		} else {
918
			$conf .= "lport 0\n";
919
		}
920

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

    
924
		// The remote server
925
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
926

    
927
		if (!empty($settings['use_shaper'])) {
928
			$conf .= "shaper {$settings['use_shaper']}\n";
929
		}
930

    
931
		if (!empty($settings['tunnel_network'])) {
932
			list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
933
			$mask = gen_subnet_mask($cidr);
934
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
935
			if ($settings['dev_mode'] == 'tun') {
936
				$conf .= "ifconfig {$ip2} {$ip1}\n";
937
			} else {
938
				$conf .= "ifconfig {$ip2} {$mask}\n";
939
			}
940
		}
941

    
942
		if (!empty($settings['tunnel_networkv6'])) {
943
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
944
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
945
			if ($settings['dev_mode'] == 'tun') {
946
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
947
			} else {
948
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
949
			}
950
		}
951

    
952
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
953
			$up_file = "{$g['varetc_path']}/openvpn/{$mode_id}.up";
954
			$conf .= "auth-user-pass {$up_file}\n";
955
			if ($settings['auth_user']) {
956
				$userpass = "{$settings['auth_user']}\n";
957
			} else {
958
				$userpass = "";
959
			}
960
			if ($settings['auth_pass']) {
961
				$userpass .= "{$settings['auth_pass']}\n";
962
			}
963
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
964
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
965
				$userpass .= "\n";
966
			}
967
			file_put_contents($up_file, $userpass);
968
		}
969

    
970
		if ($settings['proxy_addr']) {
971
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
972
			if ($settings['proxy_authtype'] != "none") {
973
				$conf .= " {$g['varetc_path']}/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
974
				$proxypas = "{$settings['proxy_user']}\n";
975
				$proxypas .= "{$settings['proxy_passwd']}\n";
976
				file_put_contents("{$g['varetc_path']}/openvpn/{$mode_id}.pas", $proxypas);
977
			}
978
			$conf .= " \n";
979
		}
980
	}
981

    
982
	// Add a remote network route if set, and only for p2p modes.
983
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
984
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
985
	}
986
	// Add a remote network route if set, and only for p2p modes.
987
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
988
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
989
	}
990

    
991
	// Write the settings for the keys
992
	switch ($settings['mode']) {
993
		case 'p2p_shared_key':
994
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
995
			break;
996
		case 'p2p_tls':
997
		case 'server_tls':
998
		case 'server_tls_user':
999
		case 'server_user':
1000
			// ca_chain() expects parameter to be passed by reference. 
1001
			// avoid passing the whole settings array, as param names or 
1002
			// types might change in future releases. 
1003
			$param = array('caref' => $settings['caref']);	
1004
			$ca = ca_chain($param);
1005
			$ca = base64_encode($ca);
1006
			
1007
			openvpn_add_keyfile($ca, $conf, $mode_id, "ca");
1008
			
1009
			unset($ca, $param);
1010

    
1011
			if (!empty($settings['certref'])) {
1012
				$cert = lookup_cert($settings['certref']);
1013
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
1014
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
1015
			}
1016
			if ($mode == 'server') {
1017
				$conf .= "dh {$g['etc_path']}/dh-parameters.{$settings['dh_length']}\n";
1018
			}
1019
			if (!empty($settings['crlref'])) {
1020
				$crl = lookup_crl($settings['crlref']);
1021
				crl_update($crl);
1022
				openvpn_add_keyfile($crl['text'], $conf, $mode_id, "crl-verify");
1023
			}
1024
			if ($settings['tls']) {
1025
				if ($mode == "server") {
1026
					$tlsopt = 0;
1027
				} else {
1028
					$tlsopt = 1;
1029
				}
1030
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, "tls-auth", $tlsopt);
1031
			}
1032
			break;
1033
	}
1034

    
1035
	if (!empty($settings['compression'])) {
1036
		if ($settings['compression'] == "noadapt") {
1037
			$conf .= "comp-noadapt\n";
1038
		} else {
1039
			$conf .= "comp-lzo {$settings['compression']}\n";
1040
		}
1041
	}
1042

    
1043
	if ($settings['passtos']) {
1044
		$conf .= "passtos\n";
1045
	}
1046

    
1047
	if ($settings['resolve_retry']) {
1048
		$conf .= "resolv-retry infinite\n";
1049
	} else if ($mode == 'client') {
1050
		$conf .= "resolv-retry infinite\n";
1051
	}
1052

    
1053
	if ($settings['dynamic_ip']) {
1054
		$conf .= "persist-remote-ip\n";
1055
		$conf .= "float\n";
1056
	}
1057

    
1058
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1059
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1060
		if (empty($settings['topology'])) {
1061
			$settings['topology'] = "subnet";
1062
		}
1063
		$conf .= "topology {$settings['topology']}\n";
1064
	}
1065

    
1066
	// New client features
1067
	if ($mode == "client") {
1068
		// Dont pull routes checkbox
1069
		if ($settings['route_no_pull']) {
1070
			$conf .= "route-nopull\n";
1071
		}
1072

    
1073
		// Dont add/remove routes checkbox
1074
		if ($settings['route_no_exec']) {
1075
			$conf .= "route-noexec\n";
1076
		}
1077
	}
1078

    
1079
	openvpn_add_custom($settings, $conf);
1080

    
1081
	openvpn_create_dirs();
1082
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.conf";
1083
	file_put_contents($fpath, $conf);
1084
	unset($conf);
1085
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.interface";
1086
	file_put_contents($fpath, $interface);
1087
	//chown($fpath, 'nobody');
1088
	//chgrp($fpath, 'nobody');
1089
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1090
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.interface", 0600);
1091
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
1092
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
1093
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1094
}
1095

    
1096
function openvpn_restart($mode, $settings) {
1097
	global $g, $config;
1098

    
1099
	$vpnid = $settings['vpnid'];
1100
	$mode_id = $mode.$vpnid;
1101
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1102
	openvpn_reconfigure($mode, $settings);
1103
	/* kill the process if running */
1104
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1105
	if (file_exists($pfile)) {
1106

    
1107
		/* read the pid file */
1108
		$pid = rtrim(file_get_contents($pfile));
1109
		unlink($pfile);
1110
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1111

    
1112
		/* send a term signal to the process */
1113
		posix_kill($pid, SIGTERM);
1114

    
1115
		/* wait until the process exits, or timeout and kill it */
1116
		$i = 0;
1117
		while (posix_kill($pid, 0)) {
1118
			usleep(250000);
1119
			if ($i > 10) {
1120
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1121
				posix_kill($pid, SIGKILL);
1122
				usleep(500000);
1123
			}
1124
			$i++;
1125
		}
1126
	}
1127

    
1128
	if (isset($settings['disable'])) {
1129
		unlock($lockhandle);
1130
		return;
1131
	}
1132

    
1133
	/* Do not start an instance if we are not CARP master on this vip! */
1134
	if (strstr($settings['interface'], "_vip") && !in_array(get_carp_interface_status($settings['interface']), array("MASTER", ""))) {
1135
		unlock($lockhandle);
1136
		return;
1137
	}
1138

    
1139
	/* Check if client is bound to a gateway group */
1140
	$a_groups = return_gateway_groups_array();
1141
	if (is_array($a_groups[$settings['interface']])) {
1142
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1143
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1144
			unlock($lockhandle);
1145
			return;
1146
		}
1147
	}
1148

    
1149
	/* start the new process */
1150
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.conf";
1151
	openvpn_clear_route($mode, $settings);
1152
	$res = mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1153
	if ($res == 0) {
1154
		$i = 0;
1155
		$pid = "--";
1156
		while ($i < 3000) {
1157
			if (isvalidpid($pfile)) {
1158
				$pid = rtrim(file_get_contents($pfile));
1159
				break;
1160
			}
1161
			usleep(1000);
1162
			$i++;
1163
		}
1164
		syslog(LOG_INFO, "OpenVPN PID written: {$pid}");
1165
	} else {
1166
		syslog(LOG_ERR, "OpenVPN failed to start");
1167
	}
1168
	if (!platform_booting()) {
1169
		send_event("filter reload");
1170
	}
1171
	unlock($lockhandle);
1172
}
1173

    
1174
function openvpn_delete($mode, $settings) {
1175
	global $g, $config;
1176

    
1177
	$vpnid = $settings['vpnid'];
1178
	$mode_id = $mode.$vpnid;
1179

    
1180
	if (isset($settings['dev_mode'])) {
1181
		$tunname = "{$settings['dev_mode']}{$vpnid}";
1182
	} else {
1183
		/* defaults to tun */
1184
		$tunname = "tun{$vpnid}";
1185
	}
1186

    
1187
	if ($mode == "server") {
1188
		$devname = "ovpns{$vpnid}";
1189
	} else {
1190
		$devname = "ovpnc{$vpnid}";
1191
	}
1192

    
1193
	/* kill the process if running */
1194
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1195
	if (file_exists($pfile)) {
1196

    
1197
		/* read the pid file */
1198
		$pid = trim(file_get_contents($pfile));
1199
		unlink($pfile);
1200

    
1201
		/* send a term signal to the process */
1202
		posix_kill($pid, SIGTERM);
1203
	}
1204

    
1205
	/* remove the device from the openvpn group */
1206
	mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " -group openvpn");
1207

    
1208
	/* restore the original adapter name */
1209
	mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " name " . escapeshellarg($tunname));
1210

    
1211
	/* remove the configuration files */
1212
	@array_map('unlink', glob("{$g['varetc_path']}/openvpn/{$mode_id}.*"));
1213
}
1214

    
1215
function openvpn_resync_csc(& $settings) {
1216
	global $g, $config, $openvpn_tls_server_modes;
1217

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

    
1220
	if (isset($settings['disable'])) {
1221
		openvpn_delete_csc($settings);
1222
		return;
1223
	}
1224
	openvpn_create_dirs();
1225

    
1226
	if (empty($settings['server_list'])) {
1227
		$csc_server_list = array();
1228
	} else {
1229
		$csc_server_list = explode(",", $settings['server_list']);
1230
	}
1231

    
1232
	$conf = '';
1233
	if ($settings['block']) {
1234
		$conf .= "disable\n";
1235
	}
1236

    
1237
	if ($settings['push_reset']) {
1238
		$conf .= "push-reset\n";
1239
	}
1240

    
1241
	if ($settings['local_network']) {
1242
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1243
	}
1244
	if ($settings['local_networkv6']) {
1245
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1246
	}
1247

    
1248
	// Add a remote network iroute if set
1249
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1250
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1251
	}
1252
	// Add a remote network iroute if set
1253
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1254
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1255
	}
1256

    
1257
	openvpn_add_dhcpopts($settings, $conf);
1258

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

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

    
1292
function openvpn_resync_csc_all() {
1293
	global $config;
1294
	if (is_array($config['openvpn']['openvpn-csc'])) {
1295
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1296
			openvpn_resync_csc($settings);
1297
		}
1298
	}
1299
}
1300

    
1301
function openvpn_delete_csc(& $settings) {
1302
	global $g, $config, $openvpn_tls_server_modes;
1303
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1304
	if (empty($settings['server_list'])) {
1305
		$csc_server_list = array();
1306
	} else {
1307
		$csc_server_list = explode(",", $settings['server_list']);
1308
	}
1309

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

    
1326
// Resync the configuration and restart the VPN
1327
function openvpn_resync($mode, $settings) {
1328
	openvpn_restart($mode, $settings);
1329
}
1330

    
1331
// Resync and restart all VPNs
1332
function openvpn_resync_all($interface = "") {
1333
	global $g, $config;
1334

    
1335
	openvpn_create_dirs();
1336

    
1337
	if (!is_array($config['openvpn'])) {
1338
		$config['openvpn'] = array();
1339
	}
1340

    
1341
/*
1342
	if (!$config['openvpn']['dh-parameters']) {
1343
		echo "Configuring OpenVPN Parameters ...\n";
1344
		$dh_parameters = openvpn_create_dhparams(1024);
1345
		$dh_parameters = base64_encode($dh_parameters);
1346
		$config['openvpn']['dh-parameters'] = $dh_parameters;
1347
		write_config("OpenVPN DH parameters");
1348
	}
1349

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

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

    
1372
	if (is_array($config['openvpn']['openvpn-client'])) {
1373
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1374
			if ($interface <> "" && $interface != $settings['interface']) {
1375
				continue;
1376
			}
1377
			openvpn_resync('client', $settings);
1378
		}
1379
	}
1380

    
1381
	openvpn_resync_csc_all();
1382

    
1383
}
1384

    
1385
// Resync and restart all VPNs using a gateway group.
1386
function openvpn_resync_gwgroup($gwgroupname = "") {
1387
	global $g, $config;
1388

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

    
1399
		if (is_array($config['openvpn']['openvpn-client'])) {
1400
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1401
				if ($gwgroupname == $settings['interface']) {
1402
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1403
					openvpn_resync('client', $settings);
1404
				}
1405
			}
1406
		}
1407

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

    
1410
	} else {
1411
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1412
	}
1413
}
1414

    
1415
function openvpn_get_active_servers($type="multipoint") {
1416
	global $config, $g;
1417

    
1418
	$servers = array();
1419
	if (is_array($config['openvpn']['openvpn-server'])) {
1420
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1421
			if (empty($settings) || isset($settings['disable'])) {
1422
				continue;
1423
			}
1424

    
1425
			$prot = $settings['protocol'];
1426
			$port = $settings['local_port'];
1427

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

    
1442
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1443
				$servers[] = openvpn_get_client_status($server, $socket);
1444
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1445
				$servers[] = openvpn_get_server_status($server, $socket);
1446
			}
1447
		}
1448
	}
1449
	return $servers;
1450
}
1451

    
1452
function openvpn_get_server_status($server, $socket) {
1453
	$errval = null;
1454
	$errstr = null;
1455
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1456
	if ($fp) {
1457
		stream_set_timeout($fp, 1);
1458

    
1459
		/* send our status request */
1460
		fputs($fp, "status 2\n");
1461

    
1462
		/* recv all response lines */
1463
		while (!feof($fp)) {
1464

    
1465
			/* read the next line */
1466
			$line = fgets($fp, 1024);
1467

    
1468
			$info = stream_get_meta_data($fp);
1469
			if ($info['timed_out']) {
1470
				break;
1471
			}
1472

    
1473
			/* parse header list line */
1474
			if (strstr($line, "HEADER")) {
1475
				continue;
1476
			}
1477

    
1478
			/* parse end of output line */
1479
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1480
				break;
1481
			}
1482

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

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

    
1522
function openvpn_get_active_clients() {
1523
	global $config, $g;
1524

    
1525
	$clients = array();
1526
	if (is_array($config['openvpn']['openvpn-client'])) {
1527
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1528

    
1529
			if (empty($settings) || isset($settings['disable'])) {
1530
				continue;
1531
			}
1532

    
1533
			$prot = $settings['protocol'];
1534
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1535

    
1536
			$client = array();
1537
			$client['port'] = $settings['local_port'];
1538
			if ($settings['description']) {
1539
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1540
			} else {
1541
				$client['name'] = "Client {$prot}{$port}";
1542
			}
1543

    
1544
			$client['vpnid'] = $settings['vpnid'];
1545
			$client['mgmt'] = "client{$client['vpnid']}";
1546
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1547
			$client['status']="down";
1548

    
1549
			$clients[] = openvpn_get_client_status($client, $socket);
1550
		}
1551
	}
1552
	return $clients;
1553
}
1554

    
1555
function openvpn_get_client_status($client, $socket) {
1556
	$errval = null;
1557
	$errstr = null;
1558
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1559
	if ($fp) {
1560
		stream_set_timeout($fp, 1);
1561
		/* send our status request */
1562
		fputs($fp, "state 1\n");
1563

    
1564
		/* recv all response lines */
1565
		while (!feof($fp)) {
1566
			/* read the next line */
1567
			$line = fgets($fp, 1024);
1568

    
1569
			$info = stream_get_meta_data($fp);
1570
			if ($info['timed_out']) {
1571
				break;
1572
			}
1573

    
1574
			/* Get the client state */
1575
			if (strstr($line, "CONNECTED")) {
1576
				$client['status'] = "up";
1577
				$list = explode(",", $line);
1578

    
1579
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1580
				$client['virtual_addr'] = $list[3];
1581
				$client['remote_host'] = $list[4];
1582
			}
1583
			if (strstr($line, "CONNECTING")) {
1584
				$client['status'] = "connecting";
1585
			}
1586
			if (strstr($line, "ASSIGN_IP")) {
1587
				$client['status'] = "waiting";
1588
				$list = explode(",", $line);
1589

    
1590
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1591
				$client['virtual_addr'] = $list[3];
1592
			}
1593
			if (strstr($line, "RECONNECTING")) {
1594
				$client['status'] = "reconnecting";
1595
				$list = explode(",", $line);
1596

    
1597
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1598
				$client['status'] .= "; " . $list[2];
1599
			}
1600
			/* parse end of output line */
1601
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1602
				break;
1603
			}
1604
		}
1605

    
1606
		/* If up, get read/write stats */
1607
		if (strcmp($client['status'], "up") == 0) {
1608
			fputs($fp, "status 2\n");
1609
			/* recv all response lines */
1610
			while (!feof($fp)) {
1611
				/* read the next line */
1612
				$line = fgets($fp, 1024);
1613

    
1614
				$info = stream_get_meta_data($fp);
1615
				if ($info['timed_out']) {
1616
					break;
1617
				}
1618

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

    
1624
				if (strstr($line, "TCP/UDP write bytes")) {
1625
					$list = explode(",", $line);
1626
					$client['bytes_sent'] = $list[1];
1627
				}
1628

    
1629
				/* parse end of output line */
1630
				if (strstr($line, "END")) {
1631
					break;
1632
				}
1633
			}
1634
		}
1635

    
1636
		fclose($fp);
1637

    
1638
	} else {
1639
		$client['remote_host'] = gettext("Unable to contact daemon");
1640
		$client['virtual_addr'] = gettext("Service not running?");
1641
		$client['bytes_recv'] = 0;
1642
		$client['bytes_sent'] = 0;
1643
		$client['connect_time'] = 0;
1644
	}
1645
	return $client;
1646
}
1647

    
1648
function openvpn_kill_client($port, $remipp) {
1649
	global $g;
1650

    
1651
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1652
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1653
	$errval = null;
1654
	$errstr = null;
1655

    
1656
	/* open a tcp connection to the management port of each server */
1657
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1658
	$killed = -1;
1659
	if ($fp) {
1660
		stream_set_timeout($fp, 1);
1661
		fputs($fp, "kill {$remipp}\n");
1662
		while (!feof($fp)) {
1663
			$line = fgets($fp, 1024);
1664

    
1665
			$info = stream_get_meta_data($fp);
1666
			if ($info['timed_out']) {
1667
				break;
1668
			}
1669

    
1670
			/* parse header list line */
1671
			if (strpos($line, "INFO:") !== false) {
1672
				continue;
1673
			}
1674
			if (strpos($line, "SUCCESS") !== false) {
1675
				$killed = 0;
1676
			}
1677
			break;
1678
		}
1679
		fclose($fp);
1680
	}
1681
	return $killed;
1682
}
1683

    
1684
function openvpn_refresh_crls() {
1685
	global $g, $config;
1686

    
1687
	openvpn_create_dirs();
1688

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

    
1716
function openvpn_create_dirs() {
1717
	global $g, $config, $openvpn_tls_server_modes;
1718
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
1719
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
1720
	}
1721
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
1722
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
1723
	}
1724

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

    
1740
function openvpn_get_interface_ip($ip, $cidr) {
1741
	$subnet = gen_subnetv4($ip, $cidr);
1742
	$ip1 = ip_after($subnet);
1743
	$ip2 = ip_after($ip1);
1744
	return array($ip1, $ip2);
1745
}
1746

    
1747
function openvpn_get_interface_ipv6($ipv6, $prefix) {
1748
	$basev6 = gen_subnetv6($ipv6, $prefix);
1749
	// Is there a better way to do this math?
1750
	$ipv6_arr = explode(':', $basev6);
1751
	$last = hexdec(array_pop($ipv6_arr));
1752
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
1753
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
1754
	return array($ipv6_1, $ipv6_2);
1755
}
1756

    
1757
function openvpn_clear_route($mode, $settings) {
1758
	if (empty($settings['tunnel_network'])) {
1759
		return;
1760
	}
1761
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1762
	$mask = gen_subnet_mask($cidr);
1763
	$clear_route = false;
1764

    
1765
	switch ($settings['mode']) {
1766
		case 'shared_key':
1767
			$clear_route = true;
1768
			break;
1769
		case 'p2p_tls':
1770
		case 'p2p_shared_key':
1771
			if ($cidr == 30) {
1772
				$clear_route = true;
1773
			}
1774
			break;
1775
	}
1776

    
1777
	if ($clear_route && !empty($ip) && !empty($mask)) {
1778
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1779
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
1780
		/* XXX: Family for route? */
1781
		mwexec("/sbin/route -q delete {$ip_to_clear}");
1782
	}
1783
}
1784

    
1785
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
1786
	$routes = "";
1787
	if (empty($value)) {
1788
		return "";
1789
	}
1790
	$networks = explode(',', $value);
1791

    
1792
	foreach ($networks as $network) {
1793
		if ($ipproto == "ipv4") {
1794
			$route = openvpn_gen_route_ipv4($network, $iroute);
1795
		} else {
1796
			$route = openvpn_gen_route_ipv6($network, $iroute);
1797
		}
1798

    
1799
		if ($push) {
1800
			$routes .= "push \"{$route}\"\n";
1801
		} else {
1802
			$routes .= "{$route}\n";
1803
		}
1804
	}
1805
	return $routes;
1806
}
1807

    
1808
function openvpn_gen_route_ipv4($network, $iroute = false) {
1809
	$i = ($iroute) ? "i" : "";
1810
	list($ip, $mask) = explode('/', trim($network));
1811
	$mask = gen_subnet_mask($mask);
1812
	return "{$i}route $ip $mask";
1813
}
1814

    
1815
function openvpn_gen_route_ipv6($network, $iroute = false) {
1816
	$i = ($iroute) ? "i" : "";
1817
	list($ipv6, $prefix) = explode('/', trim($network));
1818
	if (empty($prefix) && !is_numeric($prefix)) {
1819
		$prefix = "128";
1820
	}
1821
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
1822
}
1823

    
1824
function openvpn_get_settings($mode, $vpnid) {
1825
	global $config;
1826

    
1827
	if (is_array($config['openvpn']['openvpn-server'])) {
1828
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1829
			if (isset($settings['disable'])) {
1830
				continue;
1831
			}
1832

    
1833
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
1834
				return $settings;
1835
			}
1836
		}
1837
	}
1838

    
1839
	if (is_array($config['openvpn']['openvpn-client'])) {
1840
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
1841
			if (isset($settings['disable'])) {
1842
				continue;
1843
			}
1844

    
1845
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
1846
				return $settings;
1847
			}
1848
		}
1849
	}
1850

    
1851
	return array();
1852
}
1853

    
1854
function openvpn_restart_by_vpnid($mode, $vpnid) {
1855
	$settings = openvpn_get_settings($mode, $vpnid);
1856
	openvpn_restart($mode, $settings);
1857
}
1858

    
1859
?>
(39-39/67)