Project

General

Profile

Download (55.5 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

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

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

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

    
797
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
798
		$conf .= "engine {$settings['engine']}\n";
799
	}
800

    
801
	// server specific settings
802
	if ($mode == 'server') {
803

    
804
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
805
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
806
		$mask = gen_subnet_mask($cidr);
807

    
808
		// configure tls modes
809
		switch ($settings['mode']) {
810
			case 'p2p_tls':
811
			case 'server_tls':
812
			case 'server_user':
813
			case 'server_tls_user':
814
				$conf .= "tls-server\n";
815
				break;
816
		}
817

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

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

    
909
		// The local port to listen on
910
		$conf .= "lport {$settings['local_port']}\n";
911

    
912
		// The management port to listen on
913
		// Use unix socket to overcome the problem on any type of server
914
		$conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n";
915
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
916

    
917
		if ($settings['maxclients']) {
918
			$conf .= "max-clients {$settings['maxclients']}\n";
919
		}
920

    
921
		// Can we push routes
922
		if ($settings['local_network']) {
923
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
924
		}
925
		if ($settings['local_networkv6']) {
926
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
927
		}
928

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

    
945
	// client specific settings
946

    
947
	if ($mode == 'client') {
948

    
949
		// configure p2p mode
950
		switch ($settings['mode']) {
951
			case 'p2p_tls':
952
				$conf .= "tls-client\n";
953
			case 'shared_key':
954
				$conf .= "client\n";
955
				break;
956
		}
957

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

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

    
972
		// The remote server
973
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
974

    
975
		if (!empty($settings['use_shaper'])) {
976
			$conf .= "shaper {$settings['use_shaper']}\n";
977
		}
978

    
979
		if (!empty($settings['tunnel_network'])) {
980
			list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
981
			$mask = gen_subnet_mask($cidr);
982
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
983
			if ($settings['dev_mode'] == 'tun') {
984
				$conf .= "ifconfig {$ip2} {$ip1}\n";
985
			} else {
986
				$conf .= "ifconfig {$ip2} {$mask}\n";
987
			}
988
		}
989

    
990
		if (!empty($settings['tunnel_networkv6'])) {
991
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
992
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
993
			if ($settings['dev_mode'] == 'tun') {
994
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
995
			} else {
996
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
997
			}
998
		}
999

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

    
1018
		if ($settings['proxy_addr']) {
1019
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1020
			if ($settings['proxy_authtype'] != "none") {
1021
				$conf .= " {$g['varetc_path']}/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
1022
				$proxypas = "{$settings['proxy_user']}\n";
1023
				$proxypas .= "{$settings['proxy_passwd']}\n";
1024
				file_put_contents("{$g['varetc_path']}/openvpn/{$mode_id}.pas", $proxypas);
1025
			}
1026
			$conf .= " \n";
1027
		}
1028
	}
1029

    
1030
	// Add a remote network route if set, and only for p2p modes.
1031
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
1032
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1033
	}
1034
	// Add a remote network route if set, and only for p2p modes.
1035
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
1036
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1037
	}
1038

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

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

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

    
1110
			break;
1111
	}
1112

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

    
1134
	if (!empty($compression)) {
1135
		$conf .= "{$compression}\n";
1136
		if ($settings['compression_push']) {
1137
			$conf .= "push \"{$compression}\"\n";
1138
		}
1139
	}
1140

    
1141
	if ($settings['passtos']) {
1142
		$conf .= "passtos\n";
1143
	}
1144

    
1145
	if ($settings['resolve_retry']) {
1146
		$conf .= "resolv-retry infinite\n";
1147
	} else if ($mode == 'client') {
1148
		$conf .= "resolv-retry infinite\n";
1149
	}
1150

    
1151
	if ($settings['dynamic_ip']) {
1152
		$conf .= "persist-remote-ip\n";
1153
		$conf .= "float\n";
1154
	}
1155

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

    
1164
	// New client features
1165
	if ($mode == "client") {
1166
		// Dont pull routes checkbox
1167
		if ($settings['route_no_pull']) {
1168
			$conf .= "route-nopull\n";
1169
		}
1170

    
1171
		// Dont add/remove routes checkbox
1172
		if ($settings['route_no_exec']) {
1173
			$conf .= "route-noexec\n";
1174
		}
1175
	}
1176

    
1177
	openvpn_add_custom($settings, $conf);
1178

    
1179
	openvpn_create_dirs();
1180
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.conf";
1181
	file_put_contents($fpath, $conf);
1182
	unset($conf);
1183
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.interface";
1184
	file_put_contents($fpath, $interface);
1185
	//chown($fpath, 'nobody');
1186
	//chgrp($fpath, 'nobody');
1187
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1188
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.interface", 0600);
1189
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
1190
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
1191
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1192
}
1193

    
1194
function openvpn_restart($mode, $settings) {
1195
	global $g, $config;
1196

    
1197
	$vpnid = $settings['vpnid'];
1198
	$mode_id = $mode.$vpnid;
1199
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1200
	openvpn_reconfigure($mode, $settings);
1201
	/* kill the process if running */
1202
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1203
	if (file_exists($pfile)) {
1204

    
1205
		/* read the pid file */
1206
		$pid = rtrim(file_get_contents($pfile));
1207
		unlink($pfile);
1208
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1209

    
1210
		/* send a term signal to the process */
1211
		posix_kill($pid, SIGTERM);
1212

    
1213
		/* wait until the process exits, or timeout and kill it */
1214
		$i = 0;
1215
		while (posix_kill($pid, 0)) {
1216
			usleep(250000);
1217
			if ($i > 10) {
1218
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1219
				posix_kill($pid, SIGKILL);
1220
				usleep(500000);
1221
			}
1222
			$i++;
1223
		}
1224
	}
1225

    
1226
	if (isset($settings['disable'])) {
1227
		unlock($lockhandle);
1228
		return;
1229
	}
1230

    
1231
	/* Do not start an instance if we are not CARP master on this vip! */
1232
	if (strstr($settings['interface'], "_vip") && get_carp_interface_status($settings['interface']) != "MASTER") {
1233
		unlock($lockhandle);
1234
		return;
1235
	}
1236

    
1237
	/* Check if client is bound to a gateway group */
1238
	$a_groups = return_gateway_groups_array();
1239
	if (is_array($a_groups[$settings['interface']])) {
1240
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1241
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (get_carp_interface_status($a_groups[$settings['interface']][0]['vip']) != "MASTER")) {
1242
			unlock($lockhandle);
1243
			return;
1244
		}
1245
	}
1246

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

    
1272
function openvpn_delete($mode, $settings) {
1273
	global $g, $config;
1274

    
1275
	$vpnid = $settings['vpnid'];
1276
	$mode_id = $mode.$vpnid;
1277

    
1278
	if ($mode == "server") {
1279
		$devname = "ovpns{$vpnid}";
1280
	} else {
1281
		$devname = "ovpnc{$vpnid}";
1282
	}
1283

    
1284
	/* kill the process if running */
1285
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1286
	if (file_exists($pfile)) {
1287

    
1288
		/* read the pid file */
1289
		$pid = trim(file_get_contents($pfile));
1290
		unlink($pfile);
1291

    
1292
		/* send a term signal to the process */
1293
		posix_kill($pid, SIGTERM);
1294
	}
1295

    
1296
	/* destroy the device */
1297
	pfSense_interface_destroy($devname);
1298

    
1299
	/* remove the configuration files */
1300
	@array_map('unlink', glob("{$g['varetc_path']}/openvpn/{$mode_id}.*"));
1301
}
1302

    
1303
function openvpn_resync_csc(& $settings) {
1304
	global $g, $config, $openvpn_tls_server_modes;
1305

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

    
1308
	if (isset($settings['disable'])) {
1309
		openvpn_delete_csc($settings);
1310
		return;
1311
	}
1312
	openvpn_create_dirs();
1313

    
1314
	if (empty($settings['server_list'])) {
1315
		$csc_server_list = array();
1316
	} else {
1317
		$csc_server_list = explode(",", $settings['server_list']);
1318
	}
1319

    
1320
	$conf = '';
1321
	if ($settings['block']) {
1322
		$conf .= "disable\n";
1323
	}
1324

    
1325
	if ($settings['push_reset']) {
1326
		$conf .= "push-reset\n";
1327
	}
1328

    
1329
	if ($settings['local_network']) {
1330
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1331
	}
1332
	if ($settings['local_networkv6']) {
1333
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1334
	}
1335

    
1336
	// Add a remote network iroute if set
1337
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1338
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1339
	}
1340
	// Add a remote network iroute if set
1341
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1342
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1343
	}
1344

    
1345
	openvpn_add_dhcpopts($settings, $conf);
1346

    
1347
	openvpn_add_custom($settings, $conf);
1348
	/* Loop through servers, find which ones can use this CSC */
1349
	if (is_array($config['openvpn']['openvpn-server'])) {
1350
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1351
			if (isset($serversettings['disable'])) {
1352
				continue;
1353
			}
1354
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1355
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1356
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1357
					$csc_conf = $conf;
1358

    
1359
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1360
						list($ip, $mask) = explode('/', trim($settings['tunnel_network']));
1361
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1362
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1363
						} else {
1364
							/* Because this is being pushed, the order from the client's point of view. */
1365
							$baselong = gen_subnetv4($ip, $mask);
1366
							$serverip = ip_after($baselong, 1);
1367
							$clientip = ip_after($baselong, 2);
1368
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1369
						}
1370
					}
1371

    
1372
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1373
						list($ipv6, $prefix) = explode('/', trim($serversettings['tunnel_networkv6']));
1374
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1375
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1376
					}
1377

    
1378
					file_put_contents($csc_path, $csc_conf);
1379
					chown($csc_path, 'nobody');
1380
					chgrp($csc_path, 'nobody');
1381
				}
1382
			}
1383
		}
1384
	}
1385
}
1386

    
1387
function openvpn_resync_csc_all() {
1388
	global $config;
1389
	if (is_array($config['openvpn']['openvpn-csc'])) {
1390
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1391
			openvpn_resync_csc($settings);
1392
		}
1393
	}
1394
}
1395

    
1396
function openvpn_delete_csc(& $settings) {
1397
	global $g, $config, $openvpn_tls_server_modes;
1398
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1399
	if (empty($settings['server_list'])) {
1400
		$csc_server_list = array();
1401
	} else {
1402
		$csc_server_list = explode(",", $settings['server_list']);
1403
	}
1404

    
1405
	/* Loop through servers, find which ones used this CSC */
1406
	if (is_array($config['openvpn']['openvpn-server'])) {
1407
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1408
			if (isset($serversettings['disable'])) {
1409
				continue;
1410
			}
1411
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1412
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1413
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1414
					unlink_if_exists($csc_path);
1415
				}
1416
			}
1417
		}
1418
	}
1419
}
1420

    
1421
// Resync the configuration and restart the VPN
1422
function openvpn_resync($mode, $settings) {
1423
	openvpn_restart($mode, $settings);
1424
}
1425

    
1426
// Resync and restart all VPNs
1427
function openvpn_resync_all($interface = "") {
1428
	global $g, $config;
1429

    
1430
	openvpn_create_dirs();
1431

    
1432
	if (!is_array($config['openvpn'])) {
1433
		$config['openvpn'] = array();
1434
	}
1435

    
1436
/*
1437
	if (!$config['openvpn']['dh-parameters']) {
1438
		echo "Configuring OpenVPN Parameters ...\n";
1439
		$dh_parameters = openvpn_create_dhparams(1024);
1440
		$dh_parameters = base64_encode($dh_parameters);
1441
		$config['openvpn']['dh-parameters'] = $dh_parameters;
1442
		write_config("OpenVPN DH parameters");
1443
	}
1444

    
1445
	$path_ovdh = $g['varetc_path']."/openvpn/dh-parameters";
1446
	if (!file_exists($path_ovdh)) {
1447
		$dh_parameters = $config['openvpn']['dh-parameters'];
1448
		$dh_parameters = base64_decode($dh_parameters);
1449
		file_put_contents($path_ovdh, $dh_parameters);
1450
	}
1451
*/
1452
	if ($interface <> "") {
1453
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1454
	} else {
1455
		log_error(gettext("Resyncing OpenVPN instances."));
1456
	}
1457

    
1458
	if (is_array($config['openvpn']['openvpn-server'])) {
1459
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1460
			if ($interface <> "" && $interface != $settings['interface']) {
1461
				continue;
1462
			}
1463
			openvpn_resync('server', $settings);
1464
		}
1465
	}
1466

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

    
1476
	openvpn_resync_csc_all();
1477

    
1478
}
1479

    
1480
// Resync and restart all VPNs using a gateway group.
1481
function openvpn_resync_gwgroup($gwgroupname = "") {
1482
	global $g, $config;
1483

    
1484
	if ($gwgroupname <> "") {
1485
		if (is_array($config['openvpn']['openvpn-server'])) {
1486
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1487
				if ($gwgroupname == $settings['interface']) {
1488
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1489
					openvpn_resync('server', $settings);
1490
				}
1491
			}
1492
		}
1493

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

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

    
1505
	} else {
1506
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1507
	}
1508
}
1509

    
1510
function openvpn_get_active_servers($type="multipoint") {
1511
	global $config, $g;
1512

    
1513
	$servers = array();
1514
	if (is_array($config['openvpn']['openvpn-server'])) {
1515
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1516
			if (empty($settings) || isset($settings['disable'])) {
1517
				continue;
1518
			}
1519

    
1520
			$prot = $settings['protocol'];
1521
			$port = $settings['local_port'];
1522

    
1523
			$server = array();
1524
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1525
			$server['mode'] = $settings['mode'];
1526
			if ($settings['description']) {
1527
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1528
			} else {
1529
				$server['name'] = "Server {$prot}:{$port}";
1530
			}
1531
			$server['conns'] = array();
1532
			$server['vpnid'] = $settings['vpnid'];
1533
			$server['mgmt'] = "server{$server['vpnid']}";
1534
			$socket = "unix://{$g['varetc_path']}/openvpn/{$server['mgmt']}.sock";
1535
			list($tn, $sm) = explode('/', trim($settings['tunnel_network']));
1536

    
1537
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1538
				$servers[] = openvpn_get_client_status($server, $socket);
1539
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1540
				$servers[] = openvpn_get_server_status($server, $socket);
1541
			}
1542
		}
1543
	}
1544
	return $servers;
1545
}
1546

    
1547
function openvpn_get_server_status($server, $socket) {
1548
	$errval = null;
1549
	$errstr = null;
1550
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1551
	if ($fp) {
1552
		stream_set_timeout($fp, 1);
1553

    
1554
		/* send our status request */
1555
		fputs($fp, "status 2\n");
1556

    
1557
		/* recv all response lines */
1558
		while (!feof($fp)) {
1559

    
1560
			/* read the next line */
1561
			$line = fgets($fp, 1024);
1562

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

    
1568
			/* parse header list line */
1569
			if (strstr($line, "HEADER")) {
1570
				continue;
1571
			}
1572

    
1573
			/* parse end of output line */
1574
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1575
				break;
1576
			}
1577

    
1578
			/* parse client list line */
1579
			if (strstr($line, "CLIENT_LIST")) {
1580
				$list = explode(",", $line);
1581
				$conn = array();
1582
				$conn['common_name'] = $list[1];
1583
				$conn['remote_host'] = $list[2];
1584
				$conn['virtual_addr'] = $list[3];
1585
				$conn['virtual_addr6'] = $list[4];
1586
				$conn['bytes_recv'] = $list[5];
1587
				$conn['bytes_sent'] = $list[6];
1588
				$conn['connect_time'] = $list[7];
1589
				$conn['connect_time_unix'] = $list[8];
1590
				$conn['user_name'] = $list[9];
1591
				$conn['client_id'] = $list[10];
1592
				$conn['peer_id'] = $list[11];
1593
				$server['conns'][] = $conn;
1594
			}
1595
			/* parse routing table lines */
1596
			if (strstr($line, "ROUTING_TABLE")) {
1597
				$list = explode(",", $line);
1598
				$conn = array();
1599
				$conn['virtual_addr'] = $list[1];
1600
				$conn['common_name'] = $list[2];
1601
				$conn['remote_host'] = $list[3];
1602
				$conn['last_time'] = $list[4];
1603
				$server['routes'][] = $conn;
1604
			}
1605
		}
1606

    
1607
		/* cleanup */
1608
		fclose($fp);
1609
	} else {
1610
		$conn = array();
1611
		$conn['common_name'] = "[error]";
1612
		$conn['remote_host'] = gettext("Unable to contact daemon");
1613
		$conn['virtual_addr'] = gettext("Service not running?");
1614
		$conn['bytes_recv'] = 0;
1615
		$conn['bytes_sent'] = 0;
1616
		$conn['connect_time'] = 0;
1617
		$server['conns'][] = $conn;
1618
	}
1619
	return $server;
1620
}
1621

    
1622
function openvpn_get_active_clients() {
1623
	global $config, $g;
1624

    
1625
	$clients = array();
1626
	if (is_array($config['openvpn']['openvpn-client'])) {
1627
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1628

    
1629
			if (empty($settings) || isset($settings['disable'])) {
1630
				continue;
1631
			}
1632

    
1633
			$prot = $settings['protocol'];
1634
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1635

    
1636
			$client = array();
1637
			$client['port'] = $settings['local_port'];
1638
			if ($settings['description']) {
1639
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1640
			} else {
1641
				$client['name'] = "Client {$prot}{$port}";
1642
			}
1643

    
1644
			$client['vpnid'] = $settings['vpnid'];
1645
			$client['mgmt'] = "client{$client['vpnid']}";
1646
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1647
			$client['status']="down";
1648

    
1649
			$clients[] = openvpn_get_client_status($client, $socket);
1650
		}
1651
	}
1652
	return $clients;
1653
}
1654

    
1655
function openvpn_get_client_status($client, $socket) {
1656
	$errval = null;
1657
	$errstr = null;
1658
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1659
	if ($fp) {
1660
		stream_set_timeout($fp, 1);
1661
		/* send our status request */
1662
		fputs($fp, "state 1\n");
1663

    
1664
		/* recv all response lines */
1665
		while (!feof($fp)) {
1666
			/* read the next line */
1667
			$line = fgets($fp, 1024);
1668

    
1669
			$info = stream_get_meta_data($fp);
1670
			if ($info['timed_out']) {
1671
				break;
1672
			}
1673

    
1674
			/* Get the client state */
1675
			if (strstr($line, "CONNECTED")) {
1676
				$client['status'] = "up";
1677
				$list = explode(",", $line);
1678

    
1679
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1680
				$client['virtual_addr'] = $list[3];
1681
				$client['remote_host'] = $list[4];
1682
				$client['remote_port'] = $list[5];
1683
				$client['local_host'] = $list[6];
1684
				$client['local_port'] = $list[7];
1685
				$client['virtual_addr6'] = $list[8];
1686
			}
1687
			if (strstr($line, "CONNECTING")) {
1688
				$client['status'] = "connecting";
1689
			}
1690
			if (strstr($line, "ASSIGN_IP")) {
1691
				$client['status'] = "waiting";
1692
				$list = explode(",", $line);
1693

    
1694
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1695
				$client['virtual_addr'] = $list[3];
1696
			}
1697
			if (strstr($line, "RECONNECTING")) {
1698
				$client['status'] = "reconnecting";
1699
				$list = explode(",", $line);
1700

    
1701
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1702
				$client['status'] .= "; " . $list[2];
1703
			}
1704
			/* parse end of output line */
1705
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1706
				break;
1707
			}
1708
		}
1709

    
1710
		/* If up, get read/write stats */
1711
		if (strcmp($client['status'], "up") == 0) {
1712
			fputs($fp, "status 2\n");
1713
			/* recv all response lines */
1714
			while (!feof($fp)) {
1715
				/* read the next line */
1716
				$line = fgets($fp, 1024);
1717

    
1718
				$info = stream_get_meta_data($fp);
1719
				if ($info['timed_out']) {
1720
					break;
1721
				}
1722

    
1723
				if (strstr($line, "TCP/UDP read bytes")) {
1724
					$list = explode(",", $line);
1725
					$client['bytes_recv'] = $list[1];
1726
				}
1727

    
1728
				if (strstr($line, "TCP/UDP write bytes")) {
1729
					$list = explode(",", $line);
1730
					$client['bytes_sent'] = $list[1];
1731
				}
1732

    
1733
				/* parse end of output line */
1734
				if (strstr($line, "END")) {
1735
					break;
1736
				}
1737
			}
1738
		}
1739

    
1740
		fclose($fp);
1741

    
1742
	} else {
1743
		$client['remote_host'] = gettext("Unable to contact daemon");
1744
		$client['virtual_addr'] = gettext("Service not running?");
1745
		$client['bytes_recv'] = 0;
1746
		$client['bytes_sent'] = 0;
1747
		$client['connect_time'] = 0;
1748
	}
1749
	return $client;
1750
}
1751

    
1752
function openvpn_kill_client($port, $remipp) {
1753
	global $g;
1754

    
1755
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1756
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1757
	$errval = null;
1758
	$errstr = null;
1759

    
1760
	/* open a tcp connection to the management port of each server */
1761
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1762
	$killed = -1;
1763
	if ($fp) {
1764
		stream_set_timeout($fp, 1);
1765
		fputs($fp, "kill {$remipp}\n");
1766
		while (!feof($fp)) {
1767
			$line = fgets($fp, 1024);
1768

    
1769
			$info = stream_get_meta_data($fp);
1770
			if ($info['timed_out']) {
1771
				break;
1772
			}
1773

    
1774
			/* parse header list line */
1775
			if (strpos($line, "INFO:") !== false) {
1776
				continue;
1777
			}
1778
			if (strpos($line, "SUCCESS") !== false) {
1779
				$killed = 0;
1780
			}
1781
			break;
1782
		}
1783
		fclose($fp);
1784
	}
1785
	return $killed;
1786
}
1787

    
1788
function openvpn_refresh_crls() {
1789
	global $g, $config;
1790

    
1791
	openvpn_create_dirs();
1792

    
1793
	if (is_array($config['openvpn']['openvpn-server'])) {
1794
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1795
			if (empty($settings)) {
1796
				continue;
1797
			}
1798
			if (isset($settings['disable'])) {
1799
				continue;
1800
			}
1801
			// Write the settings for the keys
1802
			switch ($settings['mode']) {
1803
				case 'p2p_tls':
1804
				case 'server_tls':
1805
				case 'server_tls_user':
1806
				case 'server_user':
1807
					if (!empty($settings['crlref'])) {
1808
						$crl = lookup_crl($settings['crlref']);
1809
						crl_update($crl);
1810
						$fpath = $g['varetc_path']."/openvpn/server{$settings['vpnid']}.crl-verify";
1811
						file_put_contents($fpath, base64_decode($crl['text']));
1812
						@chmod($fpath, 0644);
1813
					}
1814
					break;
1815
			}
1816
		}
1817
	}
1818
}
1819

    
1820
function openvpn_create_dirs() {
1821
	global $g, $config, $openvpn_tls_server_modes;
1822
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
1823
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
1824
	}
1825
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
1826
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
1827
	}
1828

    
1829
	/* Check for enabled servers and create server-specific CSC dirs */
1830
	if (is_array($config['openvpn']['openvpn-server'])) {
1831
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1832
			if (isset($settings['disable'])) {
1833
				continue;
1834
			}
1835
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
1836
				if ($settings['vpnid']) {
1837
					safe_mkdir("{$g['varetc_path']}/openvpn-csc/server{$settings['vpnid']}");
1838
				}
1839
			}
1840
		}
1841
	}
1842
}
1843

    
1844
function openvpn_get_interface_ip($ip, $cidr) {
1845
	$subnet = gen_subnetv4($ip, $cidr);
1846
	$ip1 = ip_after($subnet);
1847
	$ip2 = ip_after($ip1);
1848
	return array($ip1, $ip2);
1849
}
1850

    
1851
function openvpn_get_interface_ipv6($ipv6, $prefix) {
1852
	$basev6 = gen_subnetv6($ipv6, $prefix);
1853
	// Is there a better way to do this math?
1854
	$ipv6_arr = explode(':', $basev6);
1855
	$last = hexdec(array_pop($ipv6_arr));
1856
	$ipv6_1 = Net_IPv6::compress(Net_IPv6::uncompress(implode(':', $ipv6_arr) . ':' . dechex($last + 1)));
1857
	$ipv6_2 = Net_IPv6::compress(Net_IPv6::uncompress(implode(':', $ipv6_arr) . ':' . dechex($last + 2)));
1858
	return array($ipv6_1, $ipv6_2);
1859
}
1860

    
1861
function openvpn_clear_route($mode, $settings) {
1862
	if (empty($settings['tunnel_network'])) {
1863
		return;
1864
	}
1865
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1866
	$mask = gen_subnet_mask($cidr);
1867
	$clear_route = false;
1868

    
1869
	switch ($settings['mode']) {
1870
		case 'shared_key':
1871
			$clear_route = true;
1872
			break;
1873
		case 'p2p_tls':
1874
		case 'p2p_shared_key':
1875
			if ($cidr == 30) {
1876
				$clear_route = true;
1877
			}
1878
			break;
1879
	}
1880

    
1881
	if ($clear_route && !empty($ip) && !empty($mask)) {
1882
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1883
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
1884
		/* XXX: Family for route? */
1885
		mwexec("/sbin/route -q delete {$ip_to_clear}");
1886
	}
1887
}
1888

    
1889
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
1890
	$routes = "";
1891
	if (empty($value)) {
1892
		return "";
1893
	}
1894
	$networks = explode(',', $value);
1895

    
1896
	foreach ($networks as $network) {
1897
		if ($ipproto == "ipv4") {
1898
			$route = openvpn_gen_route_ipv4($network, $iroute);
1899
		} else {
1900
			$route = openvpn_gen_route_ipv6($network, $iroute);
1901
		}
1902

    
1903
		if ($push) {
1904
			$routes .= "push \"{$route}\"\n";
1905
		} else {
1906
			$routes .= "{$route}\n";
1907
		}
1908
	}
1909
	return $routes;
1910
}
1911

    
1912
function openvpn_gen_route_ipv4($network, $iroute = false) {
1913
	$i = ($iroute) ? "i" : "";
1914
	list($ip, $mask) = explode('/', trim($network));
1915
	$mask = gen_subnet_mask($mask);
1916
	return "{$i}route $ip $mask";
1917
}
1918

    
1919
function openvpn_gen_route_ipv6($network, $iroute = false) {
1920
	$i = ($iroute) ? "i" : "";
1921
	list($ipv6, $prefix) = explode('/', trim($network));
1922
	if (empty($prefix)) {
1923
		$prefix = "128";
1924
	}
1925
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
1926
}
1927

    
1928
function openvpn_get_settings($mode, $vpnid) {
1929
	global $config;
1930

    
1931
	if (is_array($config['openvpn']['openvpn-server'])) {
1932
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1933
			if (isset($settings['disable'])) {
1934
				continue;
1935
			}
1936

    
1937
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
1938
				return $settings;
1939
			}
1940
		}
1941
	}
1942

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

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

    
1955
	return array();
1956
}
1957

    
1958
function openvpn_restart_by_vpnid($mode, $vpnid) {
1959
	$settings = openvpn_get_settings($mode, $vpnid);
1960
	openvpn_restart($mode, $settings);
1961
}
1962

    
1963
?>
(28-28/51)