Project

General

Profile

Download (55.7 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
 * Licensed under the Apache License, Version 2.0 (the "License");
18
 * you may not use this file except in compliance with the License.
19
 * You may obtain a copy of the License at
20
 *
21
 * http://www.apache.org/licenses/LICENSE-2.0
22
 *
23
 * Unless required by applicable law or agreed to in writing, software
24
 * distributed under the License is distributed on an "AS IS" BASIS,
25
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
26
 * See the License for the specific language governing permissions and
27
 * limitations under the License.
28
 */
29

    
30
require_once('config.inc');
31
require_once("certs.inc");
32
require_once('pfsense-utils.inc');
33
require_once("auth.inc");
34

    
35
global $openvpn_prots;
36
$openvpn_prots = array(
37
	"UDP4" => "UDP on IPv4 only",
38
	"UDP6" => "UDP on IPv6 only",
39
	"TCP4" => "TCP on IPv4 only",
40
	"TCP6" => "TCP on IPv6 only",
41
	"UDP" => "UDP IPv4 and IPv6 on all interfaces (multihome)",
42
	"TCP" => "TCP IPv4 and IPv6 on all interfaces (multihome)"
43
);
44

    
45
global $openvpn_dev_mode;
46
$openvpn_dev_mode = array(
47
	"tun" => "tun - Layer 3 Tunnel Mode",
48
	"tap" => "tap - Layer 2 Tap Mode"
49
);
50

    
51
global $openvpn_verbosity_level;
52
$openvpn_verbosity_level = array(
53
	0 =>	gettext("none"),
54
	1 =>	gettext("default"),
55
	2 =>	"2",
56
	3 =>	gettext("3 (recommended)"),
57
	4 =>	"4",
58
	5 => 	"5",
59
	6 => 	"6",
60
	7 => 	"7",
61
	8 => 	"8",
62
	9 => 	"9",
63
	10 => 	"10",
64
	11 => 	"11"
65
);
66

    
67
/*
68
 * The User Auth mode below is disabled because
69
 * OpenVPN erroneously requires that we provide
70
 * a CA configuration parameter. In this mode,
71
 * clients don't send a certificate so there is
72
 * no need for a CA. If we require that admins
73
 * provide one in the pfSense UI due to a bogus
74
 * requirement imposed by OpenVPN, it could be
75
 * considered very confusing ( I know I was ).
76
 *
77
 * -mgrooms
78
 */
79

    
80
global $openvpn_dh_lengths;
81
$openvpn_dh_lengths = array(
82
	1024 => "1024 bit",
83
	2048 => "2048 bit",
84
	3072 => "3072 bit",
85
	4096 => "4096 bit",
86
	7680 => "7680 bit",
87
	8192 => "8192 bit",
88
	15360 => "15360 bit",
89
	16384 => "16384 bit",
90
	"none" => "ECDH Only"
91
);
92
foreach ($openvpn_dh_lengths as $idx => $dhlen) {
93
	if (is_numeric($idx) && !file_exists("/etc/dh-parameters.{$idx}")) {
94
		unset($openvpn_dh_lengths[$idx]);
95
	}
96
}
97

    
98
global $openvpn_cert_depths;
99
$openvpn_cert_depths = array(
100
	1 => gettext("One (Client+Server)"),
101
	2 => gettext("Two (Client+Intermediate+Server)"),
102
	3 => gettext("Three (Client+2xIntermediate+Server)"),
103
	4 => gettext("Four (Client+3xIntermediate+Server)"),
104
	5 => gettext("Five (Client+4xIntermediate+Server)")
105
);
106

    
107
global $openvpn_server_modes;
108
$openvpn_server_modes = array(
109
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
110
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"),
111
	'server_tls' => gettext("Remote Access ( SSL/TLS )"),
112
	'server_user' => gettext("Remote Access ( User Auth )"),
113
	'server_tls_user' => gettext("Remote Access ( SSL/TLS + User Auth )"));
114

    
115
global $openvpn_tls_server_modes;
116
$openvpn_tls_server_modes = array('p2p_tls', 'server_tls', 'server_user', 'server_tls_user');
117

    
118
global $openvpn_client_modes;
119
$openvpn_client_modes = array(
120
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
121
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"));
122

    
123
global $openvpn_compression_modes;
124
$openvpn_compression_modes = array(
125
	'' => gettext("Omit Preference (Use OpenVPN Default)"),
126
	'lz4' => gettext("LZ4 Compression [compress lz4]"),
127
	'lz4-v2' => gettext("LZ4 Comression v2 [compress lz4-v2]"),
128
	'lzo' => gettext("LZO Compression [compress lzo, equivalent to comp-lzo yes for compatibility]"),
129
	'stub' => gettext("Enable Compression (stub) [compress]"),
130
	'noadapt' => gettext("Omit Preference, + Disable Adaptive LZO Compression [Legacy style, comp-noadapt]"),
131
	'adaptive' => gettext("Adaptive LZO Compression [Legacy style, comp-lzo adaptive]"),
132
	'yes' => gettext("LZO Compression [Legacy style, comp-lzo yes]"),
133
	'no' => gettext("No LZO Compression [Legacy style, comp-lzo no]"),
134
);
135

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

    
143
global $openvpn_tls_modes;
144
$openvpn_tls_modes = array(
145
	'auth' => gettext("TLS Authentication"),
146
	'crypt' => gettext("TLS Encryption and Authentication")
147
);
148

    
149
function openvpn_build_mode_list() {
150
	global $openvpn_server_modes;
151

    
152
	$list = array();
153

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

    
158
	return($list);
159
}
160

    
161
function openvpn_build_if_list() {
162
	$list = array();
163

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

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

    
183
		$interfaces[$name] = "GW Group {$name}";
184
	}
185

    
186
	$interfaces['lo0'] = "Localhost";
187
	$interfaces['any'] = "any";
188

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

    
193
	return($list);
194
}
195

    
196
function openvpn_build_crl_list() {
197
	global $a_crl;
198

    
199
	$list = array('' => 'None');
200

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

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

    
209
		$list[$crl['refid']] = $crl['descr'] . $caname;
210
	}
211

    
212
	return($list);
213
}
214

    
215
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
216
	global $a_cert;
217

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

    
224
	$non_server_list = array();
225

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

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

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

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

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

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

    
270
function openvpn_build_bridge_list() {
271
	$list = array();
272

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

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

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

    
288
	return($list);
289
}
290

    
291
function openvpn_create_key() {
292

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

    
298
	$rslt = stream_get_contents($fp);
299
	pclose($fp);
300

    
301
	return $rslt;
302
}
303

    
304
function openvpn_create_dhparams($bits) {
305

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

    
311
	$rslt = stream_get_contents($fp);
312
	pclose($fp);
313

    
314
	return $rslt;
315
}
316

    
317
function openvpn_vpnid_used($vpnid) {
318
	global $config;
319

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

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

    
336
	return false;
337
}
338

    
339
function openvpn_vpnid_next() {
340

    
341
	$vpnid = 1;
342
	while (openvpn_vpnid_used($vpnid)) {
343
		$vpnid++;
344
	}
345

    
346
	return $vpnid;
347
}
348

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

    
352
	$ovpn_settings = array();
353
	if (is_array($config['openvpn']['openvpn-server'])) {
354
		$ovpn_settings = $config['openvpn']['openvpn-server'];
355
	}
356
	if (is_array($config['openvpn']['openvpn-client'])) {
357
		$ovpn_settings = array_merge($ovpn_settings,
358
		    $config['openvpn']['openvpn-client']);
359
	}
360

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

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

    
370
		/* (TCP|UDP)(4|6) does not conflict unless interface is any */
371
		if (($interface != "any" && $settings['interface'] != "any") &&
372
		    (strlen($prot) == 4) &&
373
		    (strlen($settings['protocol']) == 4) &&
374
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
375
		    substr($prot,3,1) != substr($settings['protocol'],3,1)) {
376
			continue;
377
		}
378

    
379
		if ($port == $settings['local_port'] &&
380
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
381
		    ($interface == $settings['interface'] ||
382
		    $interface == "any" || $settings['interface'] == "any")) {
383
			return $settings['vpnid'];
384
		}
385
	}
386

    
387
	return 0;
388
}
389

    
390
function openvpn_port_next($prot, $interface = "wan") {
391

    
392
	$port = 1194;
393
	while (openvpn_port_used($prot, $interface, $port)) {
394
		$port++;
395
	}
396
	while (openvpn_port_used($prot, "any", $port)) {
397
		$port++;
398
	}
399

    
400
	return $port;
401
}
402

    
403
function openvpn_get_cipherlist() {
404

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

    
417
function openvpn_get_curvelist() {
418

    
419
	$curves = array();
420
	$curves["none"] = gettext("Use Default");
421
	$curve_out = shell_exec('/usr/local/sbin/openvpn --show-curves | /usr/bin/grep -v \'Available Elliptic curves\'');
422
	$curve_lines = explode("\n", trim($curve_out));
423
	sort($curve_lines);
424
	foreach ($curve_lines as $line) {
425
		$line = trim($line);
426
		$curves[$line] = $line;
427
	}
428
	return $curves;
429
}
430

    
431
function openvpn_validate_curve($curve) {
432
	$curves = openvpn_get_curvelist();
433
	return array_key_exists($curve, $curves);
434
}
435

    
436
function openvpn_get_digestlist() {
437

    
438
	$digests = array();
439
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
440
	$digest_lines = explode("\n", trim($digest_out));
441
	sort($digest_lines);
442
	foreach ($digest_lines as $line) {
443
		$words = explode(' ', $line);
444
		$digests[$words[0]] = "{$words[0]} {$words[1]}";
445
	}
446
	$digests["none"] = gettext("None (No Authentication)");
447
	return $digests;
448
}
449

    
450
function openvpn_get_engines() {
451
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
452
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
453
	$openssl_engine_output = implode("\n", $openssl_engine_output);
454
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
455
	$openssl_engine_output = explode("\n", $openssl_engine_output);
456

    
457
	foreach ($openssl_engine_output as $oeo) {
458
		$keep = true;
459
		$details = explode("|", $oeo);
460
		$engine = array_shift($details);
461
		$linematch = array();
462
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
463
		foreach ($details as $dt) {
464
			if (strpos($dt, "unavailable") !== FALSE) {
465
				$keep = false;
466
			}
467
			if (strpos($dt, "available") !== FALSE) {
468
				continue;
469
			}
470
			if (strpos($dt, "[") !== FALSE) {
471
				$ciphers = trim($dt, "[]");
472
			}
473
		}
474
		if (!empty($ciphers)) {
475
			$ciphers = " - " . $ciphers;
476
		}
477
		if (strlen($ciphers) > 60) {
478
			$ciphers = substr($ciphers, 0, 60) . " ... ";
479
		}
480
		if ($keep) {
481
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
482
		}
483
	}
484
	return $openssl_engines;
485
}
486

    
487
function openvpn_validate_engine($engine) {
488
	$engines = openvpn_get_engines();
489
	return array_key_exists($engine, $engines);
490
}
491

    
492
function openvpn_validate_host($value, $name) {
493
	$value = trim($value);
494
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
495
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
496
	}
497
	return false;
498
}
499

    
500
function openvpn_validate_port($value, $name) {
501
	$value = trim($value);
502
	if (empty($value) || !is_numeric($value) || $value < 0 || ($value > 65535)) {
503
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from 0 to 65535."), $name);
504
	}
505
	return false;
506
}
507

    
508
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4") {
509
	$value = trim($value);
510
	$error = false;
511
	if (empty($value)) {
512
		return false;
513
	}
514
	$networks = explode(',', $value);
515

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

    
520
	foreach ($networks as $network) {
521
		if ($ipproto == "ipv4") {
522
			$error = !openvpn_validate_cidr_ipv4($network);
523
		} else {
524
			$error = !openvpn_validate_cidr_ipv6($network);
525
		}
526
		if ($error) {
527
			break;
528
		}
529
	}
530

    
531
	if ($error) {
532
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) separated by commas."), $name, $ipproto);
533
	} else {
534
		return false;
535
	}
536
}
537

    
538
function openvpn_validate_cidr_ipv4($value) {
539
	$value = trim($value);
540
	if (!empty($value)) {
541
		list($ip, $mask) = explode('/', $value);
542
		if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0)) {
543
			return false;
544
		}
545
	}
546
	return true;
547
}
548

    
549
function openvpn_validate_cidr_ipv6($value) {
550
	$value = trim($value);
551
	if (!empty($value)) {
552
		list($ipv6, $prefix) = explode('/', $value);
553
		if (empty($prefix)) {
554
			$prefix = "128";
555
		}
556
		if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0)) {
557
			return false;
558
		}
559
	}
560
	return true;
561
}
562

    
563
function openvpn_add_dhcpopts(& $settings, & $conf) {
564

    
565
	if (!empty($settings['dns_domain'])) {
566
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
567
	}
568

    
569
	if (!empty($settings['dns_server1'])) {
570
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
571
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
572
	}
573
	if (!empty($settings['dns_server2'])) {
574
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
575
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
576
	}
577
	if (!empty($settings['dns_server3'])) {
578
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
579
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
580
	}
581
	if (!empty($settings['dns_server4'])) {
582
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
583
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
584
	}
585

    
586
	if (!empty($settings['push_blockoutsidedns'])) {
587
		$conf .= "push \"block-outside-dns\"\n";
588
	}
589
	if (!empty($settings['push_register_dns'])) {
590
		$conf .= "push \"register-dns\"\n";
591
	}
592

    
593
	if (!empty($settings['ntp_server1'])) {
594
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
595
	}
596
	if (!empty($settings['ntp_server2'])) {
597
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
598
	}
599

    
600
	if ($settings['netbios_enable']) {
601

    
602
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
603
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
604
		}
605
		if (!empty($settings['dhcp_nbtscope'])) {
606
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
607
		}
608

    
609
		if (!empty($settings['wins_server1'])) {
610
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
611
		}
612
		if (!empty($settings['wins_server2'])) {
613
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
614
		}
615

    
616
		if (!empty($settings['nbdd_server1'])) {
617
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
618
		}
619
	}
620

    
621
	if ($settings['gwredir']) {
622
		$conf .= "push \"redirect-gateway def1\"\n";
623
	}
624
}
625

    
626
function openvpn_add_custom(& $settings, & $conf) {
627

    
628
	if ($settings['custom_options']) {
629

    
630
		$options = explode(';', $settings['custom_options']);
631

    
632
		if (is_array($options)) {
633
			foreach ($options as $option) {
634
				$conf .= "$option\n";
635
			}
636
		} else {
637
			$conf .= "{$settings['custom_options']}\n";
638
		}
639
	}
640
}
641

    
642
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
643
	global $g;
644

    
645
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.{$directive}";
646
	openvpn_create_dirs();
647
	file_put_contents($fpath, base64_decode($data));
648
	//chown($fpath, 'nobody');
649
	//chgrp($fpath, 'nobody');
650
	@chmod($fpath, 0600);
651

    
652
	$conf .= "{$directive} {$fpath} {$opt}\n";
653
}
654

    
655
function openvpn_reconfigure($mode, $settings) {
656
	global $g, $config, $openvpn_tls_server_modes, $openvpn_dh_lengths;
657

    
658
	if (empty($settings)) {
659
		return;
660
	}
661
	if (isset($settings['disable'])) {
662
		return;
663
	}
664
	openvpn_create_dirs();
665
	/*
666
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
667
	 * we use a vpnid number which is allocated for a particular client
668
	 * or server configuration. ( see openvpn_vpnid_next() )
669
	 */
670

    
671
	$vpnid = $settings['vpnid'];
672
	$mode_id = $mode.$vpnid;
673

    
674
	if (isset($settings['dev_mode'])) {
675
		$tunname = "{$settings['dev_mode']}{$vpnid}";
676
	} else {
677
		/* defaults to tun */
678
		$tunname = "tun{$vpnid}";
679
		$settings['dev_mode'] = "tun";
680
	}
681

    
682
	if ($mode == "server") {
683
		$devname = "ovpns{$vpnid}";
684
	} else {
685
		$devname = "ovpnc{$vpnid}";
686
	}
687

    
688
	/* is our device already configured */
689
	if (!does_interface_exist($devname)) {
690

    
691
		/* create the tap device if required */
692
		if (!file_exists("/dev/{$tunname}")) {
693
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
694
		}
695

    
696
		/* rename the device */
697
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
698

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

    
702
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
703
		$grouptmp = link_interface_to_group($ifname);
704
		if (!empty($grouptmp)) {
705
			array_walk($grouptmp, 'interface_group_add_member');
706
		}
707
		unset($grouptmp, $ifname);
708
	}
709

    
710
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
711
	$proto = strtolower($settings['protocol']);
712
	if (substr($settings['protocol'], 0, 3) == "TCP") {
713
			$proto = "{$proto}-{$mode}";
714
	}
715
	$dev_mode = $settings['dev_mode'];
716
	$cipher = $settings['crypto'];
717
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
718
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
719

    
720
	$interface = get_failover_interface($settings['interface']);
721
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
722
	$ipaddr = $settings['ipaddr'];
723

    
724
	// If a specific ip address (VIP) is requested, use it.
725
	// Otherwise, if a specific interface is requested, use it
726
	// If "any" interface was selected, local directive will be omitted.
727
	if (is_ipaddrv4($ipaddr)) {
728
		$iface_ip = $ipaddr;
729
	} elseif (!empty($interface) && strcmp($interface, "any")) {
730
		$iface_ip=get_interface_ip($interface);
731
	}
732
	if (is_ipaddrv6($ipaddr)) {
733
		$iface_ipv6 = $ipaddr;
734
	} elseif (!empty($interface) && strcmp($interface, "any")) {
735
		$iface_ipv6=get_interface_ipv6($interface);
736
	}
737

    
738
	$conf = "dev {$devname}\n";
739
	if (isset($settings['verbosity_level'])) {
740
		$conf .= "verb {$settings['verbosity_level']}\n";
741
	}
742

    
743
	$conf .= "dev-type {$settings['dev_mode']}\n";
744
	$conf .= "dev-node /dev/{$tunname}\n";
745
	$conf .= "writepid {$pfile}\n";
746
	$conf .= "#user nobody\n";
747
	$conf .= "#group nobody\n";
748
	$conf .= "script-security 3\n";
749
	$conf .= "daemon\n";
750
	$conf .= "keepalive 10 60\n";
751
	$conf .= "ping-timer-rem\n";
752
	$conf .= "persist-tun\n";
753
	$conf .= "persist-key\n";
754
	$conf .= "proto {$proto}\n";
755
	$conf .= "cipher {$cipher}\n";
756
	$conf .= "auth {$digest}\n";
757
	$conf .= "up /usr/local/sbin/ovpn-linkup\n";
758
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
759
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
760
		switch ($settings['mode']) {
761
			case 'server_user':
762
			case 'server_tls_user':
763
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
764
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
765
				break;
766
		}
767
	}
768

    
769
	/*
770
	 * When binding specific address, wait cases where interface is in
771
	 * tentative state otherwise it will fail
772
	 */
773
	$wait_tentative = false;
774

    
775
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
776
	switch ($settings['protocol']) {
777
		case 'UDP':
778
		case 'TCP':
779
			$conf .= "multihome\n";
780
			break;
781
		case 'UDP4':
782
		case 'TCP4':
783
			if (is_ipaddrv4($iface_ip)) {
784
				$conf .= "local {$iface_ip}\n";
785
			}
786
			if ($settings['interface'] == "any") {
787
				$conf .= "multihome\n";
788
			}
789
			break;
790
		case 'UDP6':
791
		case 'TCP6':
792
			if (is_ipaddrv6($iface_ipv6)) {
793
				$conf .= "local {$iface_ipv6}\n";
794
				$wait_tentative = true;
795
			}
796
			if ($settings['interface'] == "any") {
797
				$conf .= "multihome\n";
798
			}
799
			break;
800
		default:
801
	}
802

    
803
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
804
		$conf .= "engine {$settings['engine']}\n";
805
	}
806

    
807
	// server specific settings
808
	if ($mode == 'server') {
809

    
810
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
811
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
812
		$mask = gen_subnet_mask($cidr);
813

    
814
		// configure tls modes
815
		switch ($settings['mode']) {
816
			case 'p2p_tls':
817
			case 'server_tls':
818
			case 'server_user':
819
			case 'server_tls_user':
820
				$conf .= "tls-server\n";
821
				break;
822
		}
823

    
824
		// configure p2p/server modes
825
		switch ($settings['mode']) {
826
			case 'p2p_tls':
827
				// If the CIDR is less than a /30, OpenVPN will complain if you try to
828
				//  use the server directive. It works for a single client without it.
829
				//  See ticket #1417
830
				if (!empty($ip) && !empty($mask) && ($cidr < 30)) {
831
					$conf .= "server {$ip} {$mask}\n";
832
					$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
833
					if (is_ipaddr($ipv6)) {
834
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
835
					}
836
				}
837
			case 'p2p_shared_key':
838
				if (!empty($ip) && !empty($mask)) {
839
					list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
840
					if ($settings['dev_mode'] == 'tun') {
841
						$conf .= "ifconfig {$ip1} {$ip2}\n";
842
					} else {
843
						$conf .= "ifconfig {$ip1} {$mask}\n";
844
					}
845
				}
846
				if (!empty($ipv6) && !empty($prefix)) {
847
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
848
					if ($settings['dev_mode'] == 'tun') {
849
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$ipv6_2}\n";
850
					} else {
851
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$prefix}\n";
852
					}
853
				}
854
				break;
855
			case 'server_tls':
856
			case 'server_user':
857
			case 'server_tls_user':
858
				if (!empty($ip) && !empty($mask)) {
859
					$conf .= "server {$ip} {$mask}\n";
860
					if (is_ipaddr($ipv6)) {
861
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
862
					}
863
					$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
864
				} else {
865
					if ($settings['serverbridge_dhcp']) {
866
						if ((!empty($settings['serverbridge_interface'])) && (strcmp($settings['serverbridge_interface'], "none"))) {
867
							$biface_ip=get_interface_ip($settings['serverbridge_interface']);
868
							$biface_sm=gen_subnet_mask(get_interface_subnet($settings['serverbridge_interface']));
869
							if (is_ipaddrv4($biface_ip) && is_ipaddrv4($settings['serverbridge_dhcp_start']) && is_ipaddrv4($settings['serverbridge_dhcp_end'])) {
870
								$conf .= "server-bridge {$biface_ip} {$biface_sm} {$settings['serverbridge_dhcp_start']} {$settings['serverbridge_dhcp_end']}\n";
871
								$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
872
							} else {
873
								$conf .= "mode server\n";
874
							}
875
						} else {
876
							$conf .= "mode server\n";
877
						}
878
					}
879
				}
880
				break;
881
		}
882

    
883
		// configure user auth modes
884
		switch ($settings['mode']) {
885
			case 'server_user':
886
				$conf .= "verify-client-cert none\n";
887
			case 'server_tls_user':
888
				/* username-as-common-name is not compatible with server-bridge */
889
				if (stristr($conf, "server-bridge") === false) {
890
					$conf .= "username-as-common-name\n";
891
				}
892
				if (!empty($settings['authmode'])) {
893
					$strictusercn = "false";
894
					if ($settings['strictusercn']) {
895
						$strictusercn = "true";
896
					}
897
					$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";
898
				}
899
				break;
900
		}
901
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
902
			$settings['cert_depth'] = 1;
903
		}
904
		if (is_numeric($settings['cert_depth'])) {
905
			if (($mode == 'client') && empty($settings['certref'])) {
906
				$cert = "";
907
			} else {
908
				$cert = lookup_cert($settings['certref']);
909
				/* XXX: Seems not used at all! */
910
				$servercn = urlencode(cert_get_cn($cert['crt']));
911
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
912
			}
913
		}
914

    
915
		// The local port to listen on
916
		$conf .= "lport {$settings['local_port']}\n";
917

    
918
		// The management port to listen on
919
		// Use unix socket to overcome the problem on any type of server
920
		$conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n";
921
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
922

    
923
		if ($settings['maxclients']) {
924
			$conf .= "max-clients {$settings['maxclients']}\n";
925
		}
926

    
927
		// Can we push routes
928
		if ($settings['local_network']) {
929
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
930
		}
931
		if ($settings['local_networkv6']) {
932
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
933
		}
934

    
935
		switch ($settings['mode']) {
936
			case 'server_tls':
937
			case 'server_user':
938
			case 'server_tls_user':
939
				// Configure client dhcp options
940
				openvpn_add_dhcpopts($settings, $conf);
941
				if ($settings['client2client']) {
942
					$conf .= "client-to-client\n";
943
				}
944
				break;
945
		}
946
		if (isset($settings['duplicate_cn'])) {
947
			$conf .= "duplicate-cn\n";
948
		}
949
	}
950

    
951
	// client specific settings
952

    
953
	if ($mode == 'client') {
954

    
955
		// configure p2p mode
956
		switch ($settings['mode']) {
957
			case 'p2p_tls':
958
				$conf .= "tls-client\n";
959
			case 'shared_key':
960
				$conf .= "client\n";
961
				break;
962
		}
963

    
964
		// If there is no bind option at all (ip and/or port), add "nobind" directive
965
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
966
		//  ensure a random source port.
967
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
968
			$conf .= "nobind\n";
969
		} elseif ($settings['local_port']) {
970
			$conf .= "lport {$settings['local_port']}\n";
971
		} else {
972
			$conf .= "lport 0\n";
973
		}
974

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

    
978
		// The remote server
979
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
980

    
981
		if (!empty($settings['use_shaper'])) {
982
			$conf .= "shaper {$settings['use_shaper']}\n";
983
		}
984

    
985
		if (!empty($settings['tunnel_network'])) {
986
			list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
987
			$mask = gen_subnet_mask($cidr);
988
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
989
			if ($settings['dev_mode'] == 'tun') {
990
				$conf .= "ifconfig {$ip2} {$ip1}\n";
991
			} else {
992
				$conf .= "ifconfig {$ip2} {$mask}\n";
993
			}
994
		}
995

    
996
		if (!empty($settings['tunnel_networkv6'])) {
997
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
998
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
999
			if ($settings['dev_mode'] == 'tun') {
1000
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1001
			} else {
1002
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
1003
			}
1004
		}
1005

    
1006
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
1007
			$up_file = "{$g['varetc_path']}/openvpn/{$mode_id}.up";
1008
			$conf .= "auth-user-pass {$up_file}\n";
1009
			if ($settings['auth_user']) {
1010
				$userpass = "{$settings['auth_user']}\n";
1011
			} else {
1012
				$userpass = "";
1013
			}
1014
			if ($settings['auth_pass']) {
1015
				$userpass .= "{$settings['auth_pass']}\n";
1016
			}
1017
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
1018
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
1019
				$userpass .= "\n";
1020
			}
1021
			file_put_contents($up_file, $userpass);
1022
		}
1023

    
1024
		if ($settings['proxy_addr']) {
1025
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1026
			if ($settings['proxy_authtype'] != "none") {
1027
				$conf .= " {$g['varetc_path']}/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
1028
				$proxypas = "{$settings['proxy_user']}\n";
1029
				$proxypas .= "{$settings['proxy_passwd']}\n";
1030
				file_put_contents("{$g['varetc_path']}/openvpn/{$mode_id}.pas", $proxypas);
1031
			}
1032
			$conf .= " \n";
1033
		}
1034
	}
1035

    
1036
	// Add a remote network route if set, and only for p2p modes.
1037
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
1038
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1039
	}
1040
	// Add a remote network route if set, and only for p2p modes.
1041
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
1042
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1043
	}
1044

    
1045
	// Write the settings for the keys
1046
	switch ($settings['mode']) {
1047
		case 'p2p_shared_key':
1048
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
1049
			break;
1050
		case 'p2p_tls':
1051
		case 'server_tls':
1052
		case 'server_tls_user':
1053
		case 'server_user':
1054
			// ca_chain() expects parameter to be passed by reference. 
1055
			// avoid passing the whole settings array, as param names or 
1056
			// types might change in future releases. 
1057
			$param = array('caref' => $settings['caref']);	
1058
			$ca = ca_chain($param);
1059
			$ca = base64_encode($ca);
1060
			
1061
			openvpn_add_keyfile($ca, $conf, $mode_id, "ca");
1062
			
1063
			unset($ca, $param);
1064

    
1065
			if (!empty($settings['certref'])) {
1066
				$cert = lookup_cert($settings['certref']);
1067
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
1068
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
1069
			}
1070
			if ($mode == 'server') {
1071
				if (is_numeric($settings['dh_length'])) {
1072
					if (!in_array($settings['dh_length'], array_keys($openvpn_dh_lengths))) {
1073
						/* The user selected a DH parameter length that does not have a corresponding file. */
1074
						log_error(gettext("Failed to construct OpenVPN server configuration. The selected DH Parameter length cannot be used."));
1075
						return;
1076
					}
1077
					$dh_file = "{$g['etc_path']}/dh-parameters.{$settings['dh_length']}";
1078
				} else {
1079
					$dh_file = $settings['dh_length'];
1080
				}
1081
				$conf .= "dh {$dh_file}\n";
1082
				if (!empty($settings['ecdh_curve']) && ($settings['ecdh_curve'] != "none") && openvpn_validate_curve($settings['ecdh_curve'])) {
1083
					$conf .= "ecdh-curve {$settings['ecdh_curve']}\n";
1084
				}
1085
			}
1086
			if (!empty($settings['crlref'])) {
1087
				$crl = lookup_crl($settings['crlref']);
1088
				crl_update($crl);
1089
				openvpn_add_keyfile($crl['text'], $conf, $mode_id, "crl-verify");
1090
			}
1091
			if ($settings['tls']) {
1092
				if ($settings['tls_type'] == "crypt") {
1093
					$tls_directive = "tls-crypt";
1094
					$tlsopt = "";
1095
				} else {
1096
					$tls_directive = "tls-auth";
1097
					if ($mode == "server") {
1098
						$tlsopt = 0;
1099
					} else {
1100
						$tlsopt = 1;
1101
					}
1102
				}
1103
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, $tls_directive, $tlsopt);
1104
			}
1105

    
1106
			/* NCP support. If it is not set, assume enabled since that is OpenVPN's default. */
1107
			if ($settings['ncp_enable'] == "disabled") {
1108
				$conf .= "ncp-disable\n";
1109
			} else {
1110
				/* If the ncp-ciphers list is empty, don't specify a list so OpenVPN's default will be used. */
1111
				if (!empty($settings['ncp-ciphers'])) {
1112
					$conf .= "ncp-ciphers " . str_replace(',', ':', $settings['ncp-ciphers']) . "\n";
1113
				}
1114
			}
1115

    
1116
			break;
1117
	}
1118

    
1119
	$compression = "";
1120
	switch ($settings['compression']) {
1121
		case 'lz4':
1122
		case 'lz4-v2':
1123
		case 'lzo':
1124
		case 'stub':
1125
			$compression .= "compress {$settings['compression']}";
1126
			break;
1127
		case 'noadapt':
1128
			$compression .= "comp-noadapt";
1129
			break;
1130
		case 'adaptive':
1131
		case 'yes':
1132
		case 'no':
1133
			$compression .= "comp-lzo {$settings['compression']}";
1134
			break;
1135
		default:
1136
			/* Add nothing to the configuration */
1137
			break;
1138
	}
1139

    
1140
	if (!empty($compression)) {
1141
		$conf .= "{$compression}\n";
1142
		if ($settings['compression_push']) {
1143
			$conf .= "push \"{$compression}\"\n";
1144
		}
1145
	}
1146

    
1147
	if ($settings['passtos']) {
1148
		$conf .= "passtos\n";
1149
	}
1150

    
1151
	if ($settings['resolve_retry']) {
1152
		$conf .= "resolv-retry infinite\n";
1153
	} else if ($mode == 'client') {
1154
		$conf .= "resolv-retry infinite\n";
1155
	}
1156

    
1157
	if ($settings['dynamic_ip']) {
1158
		$conf .= "persist-remote-ip\n";
1159
		$conf .= "float\n";
1160
	}
1161

    
1162
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1163
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1164
		if (empty($settings['topology'])) {
1165
			$settings['topology'] = "subnet";
1166
		}
1167
		$conf .= "topology {$settings['topology']}\n";
1168
	}
1169

    
1170
	// New client features
1171
	if ($mode == "client") {
1172
		// Dont pull routes checkbox
1173
		if ($settings['route_no_pull']) {
1174
			$conf .= "route-nopull\n";
1175
		}
1176

    
1177
		// Dont add/remove routes checkbox
1178
		if ($settings['route_no_exec']) {
1179
			$conf .= "route-noexec\n";
1180
		}
1181
	}
1182

    
1183
	openvpn_add_custom($settings, $conf);
1184

    
1185
	openvpn_create_dirs();
1186
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.conf";
1187
	file_put_contents($fpath, $conf);
1188
	unset($conf);
1189
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.interface";
1190
	file_put_contents($fpath, $interface);
1191
	//chown($fpath, 'nobody');
1192
	//chgrp($fpath, 'nobody');
1193
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1194
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.interface", 0600);
1195
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
1196
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
1197
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1198

    
1199
	if ($wait_tentative) {
1200
		interface_wait_tentative($interface);
1201
	}
1202
}
1203

    
1204
function openvpn_restart($mode, $settings) {
1205
	global $g, $config;
1206

    
1207
	$vpnid = $settings['vpnid'];
1208
	$mode_id = $mode.$vpnid;
1209
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1210
	openvpn_reconfigure($mode, $settings);
1211
	/* kill the process if running */
1212
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1213
	if (file_exists($pfile)) {
1214

    
1215
		/* read the pid file */
1216
		$pid = rtrim(file_get_contents($pfile));
1217
		unlink($pfile);
1218
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1219

    
1220
		/* send a term signal to the process */
1221
		posix_kill($pid, SIGTERM);
1222

    
1223
		/* wait until the process exits, or timeout and kill it */
1224
		$i = 0;
1225
		while (posix_kill($pid, 0)) {
1226
			usleep(250000);
1227
			if ($i > 10) {
1228
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1229
				posix_kill($pid, SIGKILL);
1230
				usleep(500000);
1231
			}
1232
			$i++;
1233
		}
1234
	}
1235

    
1236
	if (isset($settings['disable'])) {
1237
		unlock($lockhandle);
1238
		return;
1239
	}
1240

    
1241
	/* Do not start an instance if we are not CARP master on this vip! */
1242
	if (strstr($settings['interface'], "_vip") && !in_array(get_carp_interface_status($settings['interface']), array("MASTER", ""))) {
1243
		unlock($lockhandle);
1244
		return;
1245
	}
1246

    
1247
	/* Check if client is bound to a gateway group */
1248
	$a_groups = return_gateway_groups_array();
1249
	if (is_array($a_groups[$settings['interface']])) {
1250
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1251
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1252
			unlock($lockhandle);
1253
			return;
1254
		}
1255
	}
1256

    
1257
	/* start the new process */
1258
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.conf";
1259
	openvpn_clear_route($mode, $settings);
1260
	$res = mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1261
	if ($res == 0) {
1262
		$i = 0;
1263
		$pid = "--";
1264
		while ($i < 3000) {
1265
			if (isvalidpid($pfile)) {
1266
				$pid = rtrim(file_get_contents($pfile));
1267
				break;
1268
			}
1269
			usleep(1000);
1270
			$i++;
1271
		}
1272
		syslog(LOG_INFO, "OpenVPN PID written: {$pid}");
1273
	} else {
1274
		syslog(LOG_ERR, "OpenVPN failed to start");
1275
	}
1276
	if (!platform_booting()) {
1277
		send_event("filter reload");
1278
	}
1279
	unlock($lockhandle);
1280
}
1281

    
1282
function openvpn_delete($mode, $settings) {
1283
	global $g, $config;
1284

    
1285
	$vpnid = $settings['vpnid'];
1286
	$mode_id = $mode.$vpnid;
1287

    
1288
	if ($mode == "server") {
1289
		$devname = "ovpns{$vpnid}";
1290
	} else {
1291
		$devname = "ovpnc{$vpnid}";
1292
	}
1293

    
1294
	/* kill the process if running */
1295
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1296
	if (file_exists($pfile)) {
1297

    
1298
		/* read the pid file */
1299
		$pid = trim(file_get_contents($pfile));
1300
		unlink($pfile);
1301

    
1302
		/* send a term signal to the process */
1303
		posix_kill($pid, SIGTERM);
1304
	}
1305

    
1306
	/* destroy the device */
1307
	pfSense_interface_destroy($devname);
1308

    
1309
	/* remove the configuration files */
1310
	@array_map('unlink', glob("{$g['varetc_path']}/openvpn/{$mode_id}.*"));
1311
}
1312

    
1313
function openvpn_resync_csc(& $settings) {
1314
	global $g, $config, $openvpn_tls_server_modes;
1315

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

    
1318
	if (isset($settings['disable'])) {
1319
		openvpn_delete_csc($settings);
1320
		return;
1321
	}
1322
	openvpn_create_dirs();
1323

    
1324
	if (empty($settings['server_list'])) {
1325
		$csc_server_list = array();
1326
	} else {
1327
		$csc_server_list = explode(",", $settings['server_list']);
1328
	}
1329

    
1330
	$conf = '';
1331
	if ($settings['block']) {
1332
		$conf .= "disable\n";
1333
	}
1334

    
1335
	if ($settings['push_reset']) {
1336
		$conf .= "push-reset\n";
1337
	}
1338

    
1339
	if ($settings['local_network']) {
1340
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1341
	}
1342
	if ($settings['local_networkv6']) {
1343
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1344
	}
1345

    
1346
	// Add a remote network iroute if set
1347
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1348
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1349
	}
1350
	// Add a remote network iroute if set
1351
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1352
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1353
	}
1354

    
1355
	openvpn_add_dhcpopts($settings, $conf);
1356

    
1357
	openvpn_add_custom($settings, $conf);
1358
	/* Loop through servers, find which ones can use this CSC */
1359
	if (is_array($config['openvpn']['openvpn-server'])) {
1360
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1361
			if (isset($serversettings['disable'])) {
1362
				continue;
1363
			}
1364
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1365
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1366
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1367
					$csc_conf = $conf;
1368

    
1369
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1370
						list($ip, $mask) = explode('/', trim($settings['tunnel_network']));
1371
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1372
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1373
						} else {
1374
							/* Because this is being pushed, the order from the client's point of view. */
1375
							$baselong = gen_subnetv4($ip, $mask);
1376
							$serverip = ip_after($baselong, 1);
1377
							$clientip = ip_after($baselong, 2);
1378
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1379
						}
1380
					}
1381

    
1382
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1383
						list($ipv6, $prefix) = explode('/', trim($serversettings['tunnel_networkv6']));
1384
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1385
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1386
					}
1387

    
1388
					file_put_contents($csc_path, $csc_conf);
1389
					chown($csc_path, 'nobody');
1390
					chgrp($csc_path, 'nobody');
1391
				}
1392
			}
1393
		}
1394
	}
1395
}
1396

    
1397
function openvpn_resync_csc_all() {
1398
	global $config;
1399
	if (is_array($config['openvpn']['openvpn-csc'])) {
1400
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1401
			openvpn_resync_csc($settings);
1402
		}
1403
	}
1404
}
1405

    
1406
function openvpn_delete_csc(& $settings) {
1407
	global $g, $config, $openvpn_tls_server_modes;
1408
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1409
	if (empty($settings['server_list'])) {
1410
		$csc_server_list = array();
1411
	} else {
1412
		$csc_server_list = explode(",", $settings['server_list']);
1413
	}
1414

    
1415
	/* Loop through servers, find which ones used this CSC */
1416
	if (is_array($config['openvpn']['openvpn-server'])) {
1417
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1418
			if (isset($serversettings['disable'])) {
1419
				continue;
1420
			}
1421
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1422
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1423
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1424
					unlink_if_exists($csc_path);
1425
				}
1426
			}
1427
		}
1428
	}
1429
}
1430

    
1431
// Resync the configuration and restart the VPN
1432
function openvpn_resync($mode, $settings) {
1433
	openvpn_restart($mode, $settings);
1434
}
1435

    
1436
// Resync and restart all VPNs
1437
function openvpn_resync_all($interface = "") {
1438
	global $g, $config;
1439

    
1440
	openvpn_create_dirs();
1441

    
1442
	if (!is_array($config['openvpn'])) {
1443
		$config['openvpn'] = array();
1444
	}
1445

    
1446
/*
1447
	if (!$config['openvpn']['dh-parameters']) {
1448
		echo "Configuring OpenVPN Parameters ...\n";
1449
		$dh_parameters = openvpn_create_dhparams(1024);
1450
		$dh_parameters = base64_encode($dh_parameters);
1451
		$config['openvpn']['dh-parameters'] = $dh_parameters;
1452
		write_config("OpenVPN DH parameters");
1453
	}
1454

    
1455
	$path_ovdh = $g['varetc_path']."/openvpn/dh-parameters";
1456
	if (!file_exists($path_ovdh)) {
1457
		$dh_parameters = $config['openvpn']['dh-parameters'];
1458
		$dh_parameters = base64_decode($dh_parameters);
1459
		file_put_contents($path_ovdh, $dh_parameters);
1460
	}
1461
*/
1462
	if ($interface <> "") {
1463
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1464
	} else {
1465
		log_error(gettext("Resyncing OpenVPN instances."));
1466
	}
1467

    
1468
	if (is_array($config['openvpn']['openvpn-server'])) {
1469
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1470
			if ($interface <> "" && $interface != $settings['interface']) {
1471
				continue;
1472
			}
1473
			openvpn_resync('server', $settings);
1474
		}
1475
	}
1476

    
1477
	if (is_array($config['openvpn']['openvpn-client'])) {
1478
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1479
			if ($interface <> "" && $interface != $settings['interface']) {
1480
				continue;
1481
			}
1482
			openvpn_resync('client', $settings);
1483
		}
1484
	}
1485

    
1486
	openvpn_resync_csc_all();
1487

    
1488
}
1489

    
1490
// Resync and restart all VPNs using a gateway group.
1491
function openvpn_resync_gwgroup($gwgroupname = "") {
1492
	global $g, $config;
1493

    
1494
	if ($gwgroupname <> "") {
1495
		if (is_array($config['openvpn']['openvpn-server'])) {
1496
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1497
				if ($gwgroupname == $settings['interface']) {
1498
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1499
					openvpn_resync('server', $settings);
1500
				}
1501
			}
1502
		}
1503

    
1504
		if (is_array($config['openvpn']['openvpn-client'])) {
1505
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1506
				if ($gwgroupname == $settings['interface']) {
1507
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1508
					openvpn_resync('client', $settings);
1509
				}
1510
			}
1511
		}
1512

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

    
1515
	} else {
1516
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1517
	}
1518
}
1519

    
1520
function openvpn_get_active_servers($type="multipoint") {
1521
	global $config, $g;
1522

    
1523
	$servers = array();
1524
	if (is_array($config['openvpn']['openvpn-server'])) {
1525
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1526
			if (empty($settings) || isset($settings['disable'])) {
1527
				continue;
1528
			}
1529

    
1530
			$prot = $settings['protocol'];
1531
			$port = $settings['local_port'];
1532

    
1533
			$server = array();
1534
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1535
			$server['mode'] = $settings['mode'];
1536
			if ($settings['description']) {
1537
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1538
			} else {
1539
				$server['name'] = "Server {$prot}:{$port}";
1540
			}
1541
			$server['conns'] = array();
1542
			$server['vpnid'] = $settings['vpnid'];
1543
			$server['mgmt'] = "server{$server['vpnid']}";
1544
			$socket = "unix://{$g['varetc_path']}/openvpn/{$server['mgmt']}.sock";
1545
			list($tn, $sm) = explode('/', trim($settings['tunnel_network']));
1546

    
1547
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1548
				$servers[] = openvpn_get_client_status($server, $socket);
1549
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1550
				$servers[] = openvpn_get_server_status($server, $socket);
1551
			}
1552
		}
1553
	}
1554
	return $servers;
1555
}
1556

    
1557
function openvpn_get_server_status($server, $socket) {
1558
	$errval = null;
1559
	$errstr = null;
1560
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1561
	if ($fp) {
1562
		stream_set_timeout($fp, 1);
1563

    
1564
		/* send our status request */
1565
		fputs($fp, "status 2\n");
1566

    
1567
		/* recv all response lines */
1568
		while (!feof($fp)) {
1569

    
1570
			/* read the next line */
1571
			$line = fgets($fp, 1024);
1572

    
1573
			$info = stream_get_meta_data($fp);
1574
			if ($info['timed_out']) {
1575
				break;
1576
			}
1577

    
1578
			/* parse header list line */
1579
			if (strstr($line, "HEADER")) {
1580
				continue;
1581
			}
1582

    
1583
			/* parse end of output line */
1584
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1585
				break;
1586
			}
1587

    
1588
			/* parse client list line */
1589
			if (strstr($line, "CLIENT_LIST")) {
1590
				$list = explode(",", $line);
1591
				$conn = array();
1592
				$conn['common_name'] = $list[1];
1593
				$conn['remote_host'] = $list[2];
1594
				$conn['virtual_addr'] = $list[3];
1595
				$conn['virtual_addr6'] = $list[4];
1596
				$conn['bytes_recv'] = $list[5];
1597
				$conn['bytes_sent'] = $list[6];
1598
				$conn['connect_time'] = $list[7];
1599
				$conn['connect_time_unix'] = $list[8];
1600
				$conn['user_name'] = $list[9];
1601
				$conn['client_id'] = $list[10];
1602
				$conn['peer_id'] = $list[11];
1603
				$server['conns'][] = $conn;
1604
			}
1605
			/* parse routing table lines */
1606
			if (strstr($line, "ROUTING_TABLE")) {
1607
				$list = explode(",", $line);
1608
				$conn = array();
1609
				$conn['virtual_addr'] = $list[1];
1610
				$conn['common_name'] = $list[2];
1611
				$conn['remote_host'] = $list[3];
1612
				$conn['last_time'] = $list[4];
1613
				$server['routes'][] = $conn;
1614
			}
1615
		}
1616

    
1617
		/* cleanup */
1618
		fclose($fp);
1619
	} else {
1620
		$conn = array();
1621
		$conn['common_name'] = "[error]";
1622
		$conn['remote_host'] = gettext("Unable to contact daemon");
1623
		$conn['virtual_addr'] = gettext("Service not running?");
1624
		$conn['bytes_recv'] = 0;
1625
		$conn['bytes_sent'] = 0;
1626
		$conn['connect_time'] = 0;
1627
		$server['conns'][] = $conn;
1628
	}
1629
	return $server;
1630
}
1631

    
1632
function openvpn_get_active_clients() {
1633
	global $config, $g;
1634

    
1635
	$clients = array();
1636
	if (is_array($config['openvpn']['openvpn-client'])) {
1637
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1638

    
1639
			if (empty($settings) || isset($settings['disable'])) {
1640
				continue;
1641
			}
1642

    
1643
			$prot = $settings['protocol'];
1644
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1645

    
1646
			$client = array();
1647
			$client['port'] = $settings['local_port'];
1648
			if ($settings['description']) {
1649
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1650
			} else {
1651
				$client['name'] = "Client {$prot}{$port}";
1652
			}
1653

    
1654
			$client['vpnid'] = $settings['vpnid'];
1655
			$client['mgmt'] = "client{$client['vpnid']}";
1656
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1657
			$client['status']="down";
1658

    
1659
			$clients[] = openvpn_get_client_status($client, $socket);
1660
		}
1661
	}
1662
	return $clients;
1663
}
1664

    
1665
function openvpn_get_client_status($client, $socket) {
1666
	$errval = null;
1667
	$errstr = null;
1668
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1669
	if ($fp) {
1670
		stream_set_timeout($fp, 1);
1671
		/* send our status request */
1672
		fputs($fp, "state 1\n");
1673

    
1674
		/* recv all response lines */
1675
		while (!feof($fp)) {
1676
			/* read the next line */
1677
			$line = fgets($fp, 1024);
1678

    
1679
			$info = stream_get_meta_data($fp);
1680
			if ($info['timed_out']) {
1681
				break;
1682
			}
1683

    
1684
			/* Get the client state */
1685
			if (strstr($line, "CONNECTED")) {
1686
				$client['status'] = "up";
1687
				$list = explode(",", $line);
1688

    
1689
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1690
				$client['virtual_addr'] = $list[3];
1691
				$client['remote_host'] = $list[4];
1692
				$client['remote_port'] = $list[5];
1693
				$client['local_host'] = $list[6];
1694
				$client['local_port'] = $list[7];
1695
				$client['virtual_addr6'] = $list[8];
1696
			}
1697
			if (strstr($line, "CONNECTING")) {
1698
				$client['status'] = "connecting";
1699
			}
1700
			if (strstr($line, "ASSIGN_IP")) {
1701
				$client['status'] = "waiting";
1702
				$list = explode(",", $line);
1703

    
1704
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1705
				$client['virtual_addr'] = $list[3];
1706
			}
1707
			if (strstr($line, "RECONNECTING")) {
1708
				$client['status'] = "reconnecting";
1709
				$list = explode(",", $line);
1710

    
1711
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1712
				$client['status'] .= "; " . $list[2];
1713
			}
1714
			/* parse end of output line */
1715
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1716
				break;
1717
			}
1718
		}
1719

    
1720
		/* If up, get read/write stats */
1721
		if (strcmp($client['status'], "up") == 0) {
1722
			fputs($fp, "status 2\n");
1723
			/* recv all response lines */
1724
			while (!feof($fp)) {
1725
				/* read the next line */
1726
				$line = fgets($fp, 1024);
1727

    
1728
				$info = stream_get_meta_data($fp);
1729
				if ($info['timed_out']) {
1730
					break;
1731
				}
1732

    
1733
				if (strstr($line, "TCP/UDP read bytes")) {
1734
					$list = explode(",", $line);
1735
					$client['bytes_recv'] = $list[1];
1736
				}
1737

    
1738
				if (strstr($line, "TCP/UDP write bytes")) {
1739
					$list = explode(",", $line);
1740
					$client['bytes_sent'] = $list[1];
1741
				}
1742

    
1743
				/* parse end of output line */
1744
				if (strstr($line, "END")) {
1745
					break;
1746
				}
1747
			}
1748
		}
1749

    
1750
		fclose($fp);
1751

    
1752
	} else {
1753
		$client['remote_host'] = gettext("Unable to contact daemon");
1754
		$client['virtual_addr'] = gettext("Service not running?");
1755
		$client['bytes_recv'] = 0;
1756
		$client['bytes_sent'] = 0;
1757
		$client['connect_time'] = 0;
1758
	}
1759
	return $client;
1760
}
1761

    
1762
function openvpn_kill_client($port, $remipp) {
1763
	global $g;
1764

    
1765
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1766
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1767
	$errval = null;
1768
	$errstr = null;
1769

    
1770
	/* open a tcp connection to the management port of each server */
1771
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1772
	$killed = -1;
1773
	if ($fp) {
1774
		stream_set_timeout($fp, 1);
1775
		fputs($fp, "kill {$remipp}\n");
1776
		while (!feof($fp)) {
1777
			$line = fgets($fp, 1024);
1778

    
1779
			$info = stream_get_meta_data($fp);
1780
			if ($info['timed_out']) {
1781
				break;
1782
			}
1783

    
1784
			/* parse header list line */
1785
			if (strpos($line, "INFO:") !== false) {
1786
				continue;
1787
			}
1788
			if (strpos($line, "SUCCESS") !== false) {
1789
				$killed = 0;
1790
			}
1791
			break;
1792
		}
1793
		fclose($fp);
1794
	}
1795
	return $killed;
1796
}
1797

    
1798
function openvpn_refresh_crls() {
1799
	global $g, $config;
1800

    
1801
	openvpn_create_dirs();
1802

    
1803
	if (is_array($config['openvpn']['openvpn-server'])) {
1804
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1805
			if (empty($settings)) {
1806
				continue;
1807
			}
1808
			if (isset($settings['disable'])) {
1809
				continue;
1810
			}
1811
			// Write the settings for the keys
1812
			switch ($settings['mode']) {
1813
				case 'p2p_tls':
1814
				case 'server_tls':
1815
				case 'server_tls_user':
1816
				case 'server_user':
1817
					if (!empty($settings['crlref'])) {
1818
						$crl = lookup_crl($settings['crlref']);
1819
						crl_update($crl);
1820
						$fpath = $g['varetc_path']."/openvpn/server{$settings['vpnid']}.crl-verify";
1821
						file_put_contents($fpath, base64_decode($crl['text']));
1822
						@chmod($fpath, 0644);
1823
					}
1824
					break;
1825
			}
1826
		}
1827
	}
1828
}
1829

    
1830
function openvpn_create_dirs() {
1831
	global $g, $config, $openvpn_tls_server_modes;
1832
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
1833
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
1834
	}
1835
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
1836
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
1837
	}
1838

    
1839
	/* Check for enabled servers and create server-specific CSC dirs */
1840
	if (is_array($config['openvpn']['openvpn-server'])) {
1841
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1842
			if (isset($settings['disable'])) {
1843
				continue;
1844
			}
1845
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
1846
				if ($settings['vpnid']) {
1847
					safe_mkdir("{$g['varetc_path']}/openvpn-csc/server{$settings['vpnid']}");
1848
				}
1849
			}
1850
		}
1851
	}
1852
}
1853

    
1854
function openvpn_get_interface_ip($ip, $cidr) {
1855
	$subnet = gen_subnetv4($ip, $cidr);
1856
	$ip1 = ip_after($subnet);
1857
	$ip2 = ip_after($ip1);
1858
	return array($ip1, $ip2);
1859
}
1860

    
1861
function openvpn_get_interface_ipv6($ipv6, $prefix) {
1862
	$basev6 = gen_subnetv6($ipv6, $prefix);
1863
	// Is there a better way to do this math?
1864
	$ipv6_arr = explode(':', $basev6);
1865
	$last = hexdec(array_pop($ipv6_arr));
1866
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
1867
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
1868
	return array($ipv6_1, $ipv6_2);
1869
}
1870

    
1871
function openvpn_clear_route($mode, $settings) {
1872
	if (empty($settings['tunnel_network'])) {
1873
		return;
1874
	}
1875
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1876
	$mask = gen_subnet_mask($cidr);
1877
	$clear_route = false;
1878

    
1879
	switch ($settings['mode']) {
1880
		case 'shared_key':
1881
			$clear_route = true;
1882
			break;
1883
		case 'p2p_tls':
1884
		case 'p2p_shared_key':
1885
			if ($cidr == 30) {
1886
				$clear_route = true;
1887
			}
1888
			break;
1889
	}
1890

    
1891
	if ($clear_route && !empty($ip) && !empty($mask)) {
1892
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1893
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
1894
		/* XXX: Family for route? */
1895
		mwexec("/sbin/route -q delete {$ip_to_clear}");
1896
	}
1897
}
1898

    
1899
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
1900
	$routes = "";
1901
	if (empty($value)) {
1902
		return "";
1903
	}
1904
	$networks = explode(',', $value);
1905

    
1906
	foreach ($networks as $network) {
1907
		if ($ipproto == "ipv4") {
1908
			$route = openvpn_gen_route_ipv4($network, $iroute);
1909
		} else {
1910
			$route = openvpn_gen_route_ipv6($network, $iroute);
1911
		}
1912

    
1913
		if ($push) {
1914
			$routes .= "push \"{$route}\"\n";
1915
		} else {
1916
			$routes .= "{$route}\n";
1917
		}
1918
	}
1919
	return $routes;
1920
}
1921

    
1922
function openvpn_gen_route_ipv4($network, $iroute = false) {
1923
	$i = ($iroute) ? "i" : "";
1924
	list($ip, $mask) = explode('/', trim($network));
1925
	$mask = gen_subnet_mask($mask);
1926
	return "{$i}route $ip $mask";
1927
}
1928

    
1929
function openvpn_gen_route_ipv6($network, $iroute = false) {
1930
	$i = ($iroute) ? "i" : "";
1931
	list($ipv6, $prefix) = explode('/', trim($network));
1932
	if (empty($prefix)) {
1933
		$prefix = "128";
1934
	}
1935
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
1936
}
1937

    
1938
function openvpn_get_settings($mode, $vpnid) {
1939
	global $config;
1940

    
1941
	if (is_array($config['openvpn']['openvpn-server'])) {
1942
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1943
			if (isset($settings['disable'])) {
1944
				continue;
1945
			}
1946

    
1947
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
1948
				return $settings;
1949
			}
1950
		}
1951
	}
1952

    
1953
	if (is_array($config['openvpn']['openvpn-client'])) {
1954
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
1955
			if (isset($settings['disable'])) {
1956
				continue;
1957
			}
1958

    
1959
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
1960
				return $settings;
1961
			}
1962
		}
1963
	}
1964

    
1965
	return array();
1966
}
1967

    
1968
function openvpn_restart_by_vpnid($mode, $vpnid) {
1969
	$settings = openvpn_get_settings($mode, $vpnid);
1970
	openvpn_restart($mode, $settings);
1971
}
1972

    
1973
?>
(28-28/51)