Project

General

Profile

Download (59.4 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-2018 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 Compression 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
global $openvpn_interfacenames;
162
function convert_openvpn_interface_to_friendly_descr($if) {
163
	global $openvpn_interfacenames;
164
	if (!is_array($openvpn_interfacenames)) {
165
		$openvpn_interfacenames = openvpn_build_if_list();
166
	}
167
	foreach($openvpn_interfacenames as $key => $value) {
168
		list($item_if, $item_ip) = explode("|", $key);
169
		if ($if == $item_if) {
170
			echo "$value";
171
		}
172
	}
173
}
174

    
175
function openvpn_build_if_list() {
176
	$list = array();
177

    
178
	$interfaces = get_configured_interface_with_descr();
179
	$viplist = get_configured_vip_list();
180
	foreach ($viplist as $vip => $address) {
181
		$interfaces[$vip.'|'.$address] = $address;
182
		if (get_vip_descr($address)) {
183
			$interfaces[$vip.'|'.$address] .= " (";
184
			$interfaces[$vip.'|'.$address] .= get_vip_descr($address);
185
			$interfaces[$vip.'|'.$address] .= ")";
186
		}
187
	}
188

    
189
	$grouplist = return_gateway_groups_array();
190
	foreach ($grouplist as $name => $group) {
191
		if ($group[0]['vip'] != "") {
192
			$vipif = $group[0]['vip'];
193
		} else {
194
			$vipif = $group[0]['int'];
195
		}
196

    
197
		$interfaces[$name] = "GW Group {$name}";
198
	}
199

    
200
	$interfaces['lo0'] = "Localhost";
201
	$interfaces['any'] = "any";
202

    
203
	foreach ($interfaces as $iface => $ifacename) {
204
	   $list[$iface] = $ifacename;
205
	}
206

    
207
	return($list);
208
}
209

    
210
function openvpn_build_crl_list() {
211
	global $a_crl;
212

    
213
	$list = array('' => 'None');
214

    
215
	foreach ($a_crl as $crl) {
216
		$caname = "";
217
		$ca = lookup_ca($crl['caref']);
218

    
219
		if ($ca) {
220
			$caname = " (CA: {$ca['descr']})";
221
		}
222

    
223
		$list[$crl['refid']] = $crl['descr'] . $caname;
224
	}
225

    
226
	return($list);
227
}
228

    
229
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
230
	global $a_cert;
231

    
232
	if ($include_none) {
233
		$list = array('' => gettext('None (Username and/or Password required)'));
234
	} else {
235
		$list = array();
236
	}
237

    
238
	$non_server_list = array();
239

    
240
	if ($prioritize_server_certs) {
241
		$list[' '] = gettext("===== Server Certificates =====");
242
		$non_server_list['  '] = gettext("===== Non-Server Certificates =====");
243
	}
244

    
245
	foreach ($a_cert as $cert) {
246
		$properties = array();
247
		$propstr = "";
248
		$ca = lookup_ca($cert['caref']);
249
		$purpose = cert_get_purpose($cert['crt'], true);
250

    
251
		if ($purpose['server'] == "Yes") {
252
			$properties[] = gettext("Server: Yes");
253
		} elseif ($prioritize_server_certs) {
254
			$properties[] = gettext("Server: NO");
255
		}
256
		if ($ca) {
257
			$properties[] = sprintf(gettext("CA: %s"), $ca['descr']);
258
		}
259
		if (cert_in_use($cert['refid'])) {
260
			$properties[] = gettext("In Use");
261
		}
262
		if (is_cert_revoked($cert)) {
263
			$properties[] = gettext("Revoked");
264
		}
265

    
266
		if (!empty($properties)) {
267
			$propstr = " (" . implode(", ", $properties) . ")";
268
		}
269

    
270
		if ($prioritize_server_certs) {
271
			if ($purpose['server'] == "Yes") {
272
				$list[$cert['refid']] = $cert['descr'] . $propstr;
273
			} else {
274
				$non_server_list[$cert['refid']] = $cert['descr'] . $propstr;
275
			}
276
		} else {
277
			$list[$cert['refid']] = $cert['descr'] . $propstr;
278
		}
279
	}
280

    
281
	return(array('server' => $list, 'non-server' => $non_server_list));
282
}
283

    
284
function openvpn_build_bridge_list() {
285
	$list = array();
286

    
287
	$serverbridge_interface['none'] = "none";
288
	$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
289
	$viplist = get_configured_vip_list();
290

    
291
	foreach ($viplist as $vip => $address) {
292
		$serverbridge_interface[$vip.'|'.$address] = $address;
293
		if (get_vip_descr($address)) {
294
			$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
295
		}
296
	}
297

    
298
	foreach ($serverbridge_interface as $iface => $ifacename) {
299
		$list[$iface] = htmlspecialchars($ifacename);
300
	}
301

    
302
	return($list);
303
}
304

    
305
function openvpn_create_key() {
306

    
307
	$fp = popen("/usr/local/sbin/openvpn --genkey --secret /dev/stdout 2>/dev/null", "r");
308
	if (!$fp) {
309
		return false;
310
	}
311

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

    
315
	return $rslt;
316
}
317

    
318
function openvpn_create_dhparams($bits) {
319

    
320
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
321
	if (!$fp) {
322
		return false;
323
	}
324

    
325
	$rslt = stream_get_contents($fp);
326
	pclose($fp);
327

    
328
	return $rslt;
329
}
330

    
331
function openvpn_vpnid_used($vpnid) {
332
	global $config;
333

    
334
	if (is_array($config['openvpn']['openvpn-server'])) {
335
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
336
			if ($vpnid == $settings['vpnid']) {
337
				return true;
338
			}
339
		}
340
	}
341

    
342
	if (is_array($config['openvpn']['openvpn-client'])) {
343
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
344
			if ($vpnid == $settings['vpnid']) {
345
				return true;
346
			}
347
		}
348
	}
349

    
350
	return false;
351
}
352

    
353
function openvpn_vpnid_next() {
354

    
355
	$vpnid = 1;
356
	while (openvpn_vpnid_used($vpnid)) {
357
		$vpnid++;
358
	}
359

    
360
	return $vpnid;
361
}
362

    
363
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
364
	global $config;
365

    
366
	$ovpn_settings = array();
367
	if (is_array($config['openvpn']['openvpn-server'])) {
368
		$ovpn_settings = $config['openvpn']['openvpn-server'];
369
	}
370
	if (is_array($config['openvpn']['openvpn-client'])) {
371
		$ovpn_settings = array_merge($ovpn_settings,
372
		    $config['openvpn']['openvpn-client']);
373
	}
374

    
375
	foreach ($ovpn_settings as $settings) {
376
		if (isset($settings['disable'])) {
377
			continue;
378
		}
379

    
380
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
381
			continue;
382
		}
383

    
384
		/* (TCP|UDP)(4|6) does not conflict unless interface is any */
385
		if (($interface != "any" && $settings['interface'] != "any") &&
386
		    (strlen($prot) == 4) &&
387
		    (strlen($settings['protocol']) == 4) &&
388
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
389
		    substr($prot,3,1) != substr($settings['protocol'],3,1)) {
390
			continue;
391
		}
392

    
393
		if ($port == $settings['local_port'] &&
394
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
395
		    ($interface == $settings['interface'] ||
396
		    $interface == "any" || $settings['interface'] == "any")) {
397
			return $settings['vpnid'];
398
		}
399
	}
400

    
401
	return 0;
402
}
403

    
404
function openvpn_port_next($prot, $interface = "wan") {
405

    
406
	$port = 1194;
407
	while (openvpn_port_used($prot, $interface, $port)) {
408
		$port++;
409
	}
410
	while (openvpn_port_used($prot, "any", $port)) {
411
		$port++;
412
	}
413

    
414
	return $port;
415
}
416

    
417
function openvpn_get_cipherlist() {
418

    
419
	$ciphers = array();
420
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
421
	$cipher_lines = explode("\n", trim($cipher_out));
422
	sort($cipher_lines);
423
	foreach ($cipher_lines as $line) {
424
		$words = explode(' ', $line, 2);
425
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
426
	}
427
	$ciphers["none"] = gettext("None (No Encryption)");
428
	return $ciphers;
429
}
430

    
431
function openvpn_get_curvelist() {
432

    
433
	$curves = array();
434
	$curves["none"] = gettext("Use Default");
435
	$curve_out = shell_exec('/usr/local/sbin/openvpn --show-curves | /usr/bin/grep -v \'Available Elliptic curves\'');
436
	$curve_lines = explode("\n", trim($curve_out));
437
	sort($curve_lines);
438
	foreach ($curve_lines as $line) {
439
		$line = trim($line);
440
		$curves[$line] = $line;
441
	}
442
	return $curves;
443
}
444

    
445
function openvpn_validate_curve($curve) {
446
	$curves = openvpn_get_curvelist();
447
	return array_key_exists($curve, $curves);
448
}
449

    
450
/* Obtain the list of digest algorithms supported by openssl and their alternate names */
451
function openvpn_get_openssldigestmappings() {
452
	$digests = array();
453
	$digest_out = shell_exec('/usr/bin/openssl list-message-digest-algorithms | /usr/bin/grep "=>"');
454
	$digest_lines = explode("\n", trim($digest_out));
455
	sort($digest_lines);
456
	foreach ($digest_lines as $line) {
457
		$words = explode(' => ', $line, 2);
458
		$digests[$words[0]] = $words[1];
459
	}
460
	return $digests;
461
}
462

    
463
/* Obtain the list of digest algorithms supported by openvpn */
464
function openvpn_get_digestlist() {
465
	/* Grab the list from OpenSSL to check for duplicates or aliases */
466
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
467
	$digests = array();
468
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
469
	$digest_lines = explode("\n", trim($digest_out));
470
	sort($digest_lines);
471
	foreach ($digest_lines as $line) {
472
		$words = explode(' ', $line);
473
		/* Only add the entry if it is NOT also listed as being an alias/mapping by OpenSSL */
474
		if (!array_key_exists($words[0], $openssl_digest_mappings)) {
475
			$digests[$words[0]] = "{$words[0]} {$words[1]}";
476
		}
477
	}
478
	$digests["none"] = gettext("None (No Authentication)");
479
	return $digests;
480
}
481

    
482
/* Check to see if a digest name is an alias and if so, find the actual digest
483
 * algorithm instead. Useful for upgrade code that has to translate aliased
484
 * algorithms to their actual names.
485
 */
486
function openvpn_remap_digest($digest) {
487
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
488
	if (array_key_exists($digest, $openssl_digest_mappings)) {
489
		/* Some mappings point to other mappings, keep going until we find the actual digest algorithm */
490
		if (array_key_exists($openssl_digest_mappings[$digest], $openssl_digest_mappings)) {
491
			return openvpn_remap_digest($openssl_digest_mappings[$digest]);
492
		} else {
493
			return $openssl_digest_mappings[$digest];
494
		}
495
	}
496
	return $digest;
497
}
498

    
499
function openvpn_get_engines() {
500
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
501
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
502
	$openssl_engine_output = implode("\n", $openssl_engine_output);
503
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
504
	$openssl_engine_output = explode("\n", $openssl_engine_output);
505

    
506
	foreach ($openssl_engine_output as $oeo) {
507
		$keep = true;
508
		$details = explode("|", $oeo);
509
		$engine = array_shift($details);
510
		$linematch = array();
511
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
512
		foreach ($details as $dt) {
513
			if (strpos($dt, "unavailable") !== FALSE) {
514
				$keep = false;
515
			}
516
			if (strpos($dt, "available") !== FALSE) {
517
				continue;
518
			}
519
			if (strpos($dt, "[") !== FALSE) {
520
				$ciphers = trim($dt, "[]");
521
			}
522
		}
523
		if (!empty($ciphers)) {
524
			$ciphers = " - " . $ciphers;
525
		}
526
		if (strlen($ciphers) > 60) {
527
			$ciphers = substr($ciphers, 0, 60) . " ... ";
528
		}
529
		if ($keep) {
530
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
531
		}
532
	}
533
	return $openssl_engines;
534
}
535

    
536
function openvpn_get_buffer_values() {
537
	$sendbuf_max = get_single_sysctl('net.inet.tcp.sendbuf_max');
538
	$recvbuf_max = get_single_sysctl('net.inet.tcp.recvbuf_max');
539
	/* Usually these two are equal, but if they are not, take whichever one is lower. */
540
	$buffer_max = ($sendbuf_max <= $recvbuf_max) ? $sendbuf_max : $recvbuf_max;
541
	$buffer_values = array('' => gettext('Default'));
542
	for ($bs = 32; $bs >= 1; $bs /= 2) {
543
		$buffer_values[$buffer_max/$bs] = format_bytes($buffer_max/$bs);
544
	}
545
	return $buffer_values;
546
}
547

    
548
function openvpn_validate_engine($engine) {
549
	$engines = openvpn_get_engines();
550
	return array_key_exists($engine, $engines);
551
}
552

    
553
function openvpn_validate_host($value, $name) {
554
	$value = trim($value);
555
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
556
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
557
	}
558
	return false;
559
}
560

    
561
function openvpn_validate_port($value, $name, $first_port = 0) {
562
	$value = trim($value);
563
	if (!is_numeric($first_port)) {
564
		$first_port = 0;
565
	}
566
	if (empty($value) || !is_numeric($value) || $value < $first_port || ($value > 65535)) {
567
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from {$first_port} to 65535."), $name);
568
	}
569
	return false;
570
}
571

    
572
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4") {
573
	$value = trim($value);
574
	$error = false;
575
	if (empty($value)) {
576
		return false;
577
	}
578
	$networks = explode(',', $value);
579

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

    
584
	foreach ($networks as $network) {
585
		if ($ipproto == "ipv4") {
586
			$error = !openvpn_validate_cidr_ipv4($network);
587
		} else {
588
			$error = !openvpn_validate_cidr_ipv6($network);
589
		}
590
		if ($error) {
591
			break;
592
		}
593
	}
594

    
595
	if ($error) {
596
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) separated by commas."), $name, $ipproto);
597
	} else {
598
		return false;
599
	}
600
}
601

    
602
function openvpn_validate_cidr_ipv4($value) {
603
	$value = trim($value);
604
	if (!empty($value)) {
605
		list($ip, $mask) = explode('/', $value);
606
		if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0)) {
607
			return false;
608
		}
609
	}
610
	return true;
611
}
612

    
613
function openvpn_validate_cidr_ipv6($value) {
614
	$value = trim($value);
615
	if (!empty($value)) {
616
		list($ipv6, $prefix) = explode('/', $value);
617
		if (empty($prefix)) {
618
			$prefix = "128";
619
		}
620
		if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0)) {
621
			return false;
622
		}
623
	}
624
	return true;
625
}
626

    
627
function openvpn_add_dhcpopts(& $settings, & $conf) {
628

    
629
	if (!empty($settings['dns_domain'])) {
630
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
631
	}
632

    
633
	if (!empty($settings['dns_server1'])) {
634
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
635
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
636
	}
637
	if (!empty($settings['dns_server2'])) {
638
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
639
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
640
	}
641
	if (!empty($settings['dns_server3'])) {
642
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
643
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
644
	}
645
	if (!empty($settings['dns_server4'])) {
646
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
647
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
648
	}
649

    
650
	if (!empty($settings['push_blockoutsidedns'])) {
651
		$conf .= "push \"block-outside-dns\"\n";
652
	}
653
	if (!empty($settings['push_register_dns'])) {
654
		$conf .= "push \"register-dns\"\n";
655
	}
656

    
657
	if (!empty($settings['ntp_server1'])) {
658
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
659
	}
660
	if (!empty($settings['ntp_server2'])) {
661
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
662
	}
663

    
664
	if ($settings['netbios_enable']) {
665

    
666
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
667
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
668
		}
669
		if (!empty($settings['dhcp_nbtscope'])) {
670
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
671
		}
672

    
673
		if (!empty($settings['wins_server1'])) {
674
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
675
		}
676
		if (!empty($settings['wins_server2'])) {
677
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
678
		}
679

    
680
		if (!empty($settings['nbdd_server1'])) {
681
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
682
		}
683
	}
684

    
685
	if ($settings['gwredir']) {
686
		$conf .= "push \"redirect-gateway def1\"\n";
687
	}
688
	if ($settings['gwredir6']) {
689
		$conf .= "push \"redirect-gateway ipv6\"\n";
690
	}
691
}
692

    
693
function openvpn_add_custom(& $settings, & $conf) {
694

    
695
	if ($settings['custom_options']) {
696

    
697
		$options = explode(';', $settings['custom_options']);
698

    
699
		if (is_array($options)) {
700
			foreach ($options as $option) {
701
				$conf .= "$option\n";
702
			}
703
		} else {
704
			$conf .= "{$settings['custom_options']}\n";
705
		}
706
	}
707
}
708

    
709
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
710
	global $g;
711

    
712
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.{$directive}";
713
	openvpn_create_dirs();
714
	file_put_contents($fpath, base64_decode($data));
715
	//chown($fpath, 'nobody');
716
	//chgrp($fpath, 'nobody');
717
	@chmod($fpath, 0600);
718

    
719
	$conf .= "{$directive} {$fpath} {$opt}\n";
720
}
721

    
722
function openvpn_reconfigure($mode, $settings) {
723
	global $g, $config, $openvpn_tls_server_modes, $openvpn_dh_lengths;
724

    
725
	if (empty($settings)) {
726
		return;
727
	}
728
	if (isset($settings['disable'])) {
729
		return;
730
	}
731
	openvpn_create_dirs();
732
	/*
733
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
734
	 * we use a vpnid number which is allocated for a particular client
735
	 * or server configuration. ( see openvpn_vpnid_next() )
736
	 */
737

    
738
	$vpnid = $settings['vpnid'];
739
	$mode_id = $mode.$vpnid;
740

    
741
	if (isset($settings['dev_mode'])) {
742
		$tunname = "{$settings['dev_mode']}{$vpnid}";
743
	} else {
744
		/* defaults to tun */
745
		$tunname = "tun{$vpnid}";
746
		$settings['dev_mode'] = "tun";
747
	}
748

    
749
	if ($mode == "server") {
750
		$devname = "ovpns{$vpnid}";
751
	} else {
752
		$devname = "ovpnc{$vpnid}";
753
	}
754

    
755
	/* is our device already configured */
756
	if (!does_interface_exist($devname)) {
757

    
758
		/* create the tap device if required */
759
		if (!file_exists("/dev/{$tunname}")) {
760
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
761
		}
762

    
763
		/* rename the device */
764
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
765

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

    
769
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
770
		$grouptmp = link_interface_to_group($ifname);
771
		if (!empty($grouptmp)) {
772
			array_walk($grouptmp, 'interface_group_add_member');
773
		}
774
		unset($grouptmp, $ifname);
775
	}
776

    
777
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
778
	$proto = strtolower($settings['protocol']);
779
	if (substr($settings['protocol'], 0, 3) == "TCP") {
780
			$proto = "{$proto}-{$mode}";
781
	}
782
	$dev_mode = $settings['dev_mode'];
783
	$cipher = $settings['crypto'];
784
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
785
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
786

    
787
	$interface = get_failover_interface($settings['interface']);
788
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
789
	$ipaddr = $settings['ipaddr'];
790

    
791
	// If a specific ip address (VIP) is requested, use it.
792
	// Otherwise, if a specific interface is requested, use it
793
	// If "any" interface was selected, local directive will be omitted.
794
	if (is_ipaddrv4($ipaddr)) {
795
		$iface_ip = $ipaddr;
796
	} elseif (!empty($interface) && strcmp($interface, "any")) {
797
		$iface_ip=get_interface_ip($interface);
798
	}
799
	if (is_ipaddrv6($ipaddr)) {
800
		$iface_ipv6 = $ipaddr;
801
	} elseif (!empty($interface) && strcmp($interface, "any")) {
802
		$iface_ipv6=get_interface_ipv6($interface);
803
	}
804

    
805
	$conf = "dev {$devname}\n";
806
	if (isset($settings['verbosity_level'])) {
807
		$conf .= "verb {$settings['verbosity_level']}\n";
808
	}
809

    
810
	$conf .= "dev-type {$settings['dev_mode']}\n";
811
	$conf .= "dev-node /dev/{$tunname}\n";
812
	$conf .= "writepid {$pfile}\n";
813
	$conf .= "#user nobody\n";
814
	$conf .= "#group nobody\n";
815
	$conf .= "script-security 3\n";
816
	$conf .= "daemon\n";
817
	$conf .= "keepalive 10 60\n";
818
	$conf .= "ping-timer-rem\n";
819
	$conf .= "persist-tun\n";
820
	$conf .= "persist-key\n";
821
	$conf .= "proto {$proto}\n";
822
	$conf .= "cipher {$cipher}\n";
823
	$conf .= "auth {$digest}\n";
824
	$conf .= "up /usr/local/sbin/ovpn-linkup\n";
825
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
826
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
827
		switch ($settings['mode']) {
828
			case 'server_user':
829
			case 'server_tls_user':
830
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
831
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
832
				break;
833
		}
834
	}
835
	if ($settings['dev_mode'] === 'tun' && isset($config['unbound']['enable']) && isset($config['unbound']['regovpnclients'])) {
836
		switch($settings['mode']) {
837
			case 'server_tls':
838
			case 'server_tls_user':
839
				$domain = !empty($settings['dns_domain']) ? $settings['dns_domain'] : $config['system']['domain'];
840
				if (is_domain($domain)) {
841
					$conf .= "learn-address \"/usr/local/sbin/openvpn.learn-address.sh $domain\"\n";
842
				}
843
				break;
844
		}
845
	}
846

    
847
	/*
848
	 * When binding specific address, wait cases where interface is in
849
	 * tentative state otherwise it will fail
850
	 */
851
	$wait_tentative = false;
852

    
853
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
854
	switch ($settings['protocol']) {
855
		case 'UDP':
856
		case 'TCP':
857
			$conf .= "multihome\n";
858
			break;
859
		case 'UDP4':
860
		case 'TCP4':
861
			if (is_ipaddrv4($iface_ip)) {
862
				$conf .= "local {$iface_ip}\n";
863
			}
864
			if ($settings['interface'] == "any") {
865
				$conf .= "multihome\n";
866
			}
867
			break;
868
		case 'UDP6':
869
		case 'TCP6':
870
			if (is_ipaddrv6($iface_ipv6)) {
871
				$conf .= "local {$iface_ipv6}\n";
872
				$wait_tentative = true;
873
			}
874
			if ($settings['interface'] == "any") {
875
				$conf .= "multihome\n";
876
			}
877
			break;
878
		default:
879
	}
880

    
881
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
882
		$conf .= "engine {$settings['engine']}\n";
883
	}
884

    
885
	// server specific settings
886
	if ($mode == 'server') {
887

    
888
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
889
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
890
		$mask = gen_subnet_mask($cidr);
891

    
892
		// configure tls modes
893
		switch ($settings['mode']) {
894
			case 'p2p_tls':
895
			case 'server_tls':
896
			case 'server_user':
897
			case 'server_tls_user':
898
				$conf .= "tls-server\n";
899
				break;
900
		}
901

    
902
		// configure p2p/server modes
903
		switch ($settings['mode']) {
904
			case 'p2p_tls':
905
				// If the CIDR is less than a /30, OpenVPN will complain if you try to
906
				//  use the server directive. It works for a single client without it.
907
				//  See ticket #1417
908
				if (!empty($ip) && !empty($mask) && ($cidr < 30)) {
909
					$conf .= "server {$ip} {$mask}\n";
910
					$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
911
					if (is_ipaddr($ipv6)) {
912
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
913
					}
914
				}
915
			case 'p2p_shared_key':
916
				if (!empty($ip) && !empty($mask)) {
917
					list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
918
					if ($settings['dev_mode'] == 'tun') {
919
						$conf .= "ifconfig {$ip1} {$ip2}\n";
920
					} else {
921
						$conf .= "ifconfig {$ip1} {$mask}\n";
922
					}
923
				}
924
				if (!empty($ipv6) && !empty($prefix)) {
925
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
926
					if ($settings['dev_mode'] == 'tun') {
927
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$ipv6_2}\n";
928
					} else {
929
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$prefix}\n";
930
					}
931
				}
932
				break;
933
			case 'server_tls':
934
			case 'server_user':
935
			case 'server_tls_user':
936
				if (!empty($ip) && !empty($mask)) {
937
					$conf .= "server {$ip} {$mask}\n";
938
					if (is_ipaddr($ipv6)) {
939
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
940
					}
941
					$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
942
				} else {
943
					if ($settings['serverbridge_dhcp']) {
944
						if ((!empty($settings['serverbridge_interface'])) && (strcmp($settings['serverbridge_interface'], "none"))) {
945
							$biface_ip=get_interface_ip($settings['serverbridge_interface']);
946
							$biface_sm=gen_subnet_mask(get_interface_subnet($settings['serverbridge_interface']));
947
							if (is_ipaddrv4($biface_ip) && is_ipaddrv4($settings['serverbridge_dhcp_start']) && is_ipaddrv4($settings['serverbridge_dhcp_end'])) {
948
								$conf .= "server-bridge {$biface_ip} {$biface_sm} {$settings['serverbridge_dhcp_start']} {$settings['serverbridge_dhcp_end']}\n";
949
								$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
950
							} else {
951
								$conf .= "mode server\n";
952
							}
953
						} else {
954
							$conf .= "mode server\n";
955
						}
956
					}
957
				}
958
				break;
959
		}
960

    
961
		// configure user auth modes
962
		switch ($settings['mode']) {
963
			case 'server_user':
964
				$conf .= "verify-client-cert none\n";
965
			case 'server_tls_user':
966
				/* username-as-common-name is not compatible with server-bridge */
967
				if (stristr($conf, "server-bridge") === false) {
968
					$conf .= "username-as-common-name\n";
969
				}
970
				if (!empty($settings['authmode'])) {
971
					$strictusercn = "false";
972
					if ($settings['strictusercn']) {
973
						$strictusercn = "true";
974
					}
975
					$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";
976
				}
977
				break;
978
		}
979
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
980
			$settings['cert_depth'] = 1;
981
		}
982
		if (is_numeric($settings['cert_depth'])) {
983
			if (($mode == 'client') && empty($settings['certref'])) {
984
				$cert = "";
985
			} else {
986
				$cert = lookup_cert($settings['certref']);
987
				/* XXX: Seems not used at all! */
988
				$servercn = urlencode(cert_get_cn($cert['crt']));
989
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
990
			}
991
		}
992

    
993
		// The local port to listen on
994
		$conf .= "lport {$settings['local_port']}\n";
995

    
996
		// The management port to listen on
997
		// Use unix socket to overcome the problem on any type of server
998
		$conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n";
999
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
1000

    
1001
		if ($settings['maxclients']) {
1002
			$conf .= "max-clients {$settings['maxclients']}\n";
1003
		}
1004

    
1005
		// Can we push routes, and should we?
1006
		if ($settings['local_network'] && !$settings['gwredir']) {
1007
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1008
		}
1009
		if ($settings['local_networkv6'] && !$settings['gwredir6']) {
1010
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1011
		}
1012

    
1013
		switch ($settings['mode']) {
1014
			case 'server_tls':
1015
			case 'server_user':
1016
			case 'server_tls_user':
1017
				// Configure client dhcp options
1018
				openvpn_add_dhcpopts($settings, $conf);
1019
				if ($settings['client2client']) {
1020
					$conf .= "client-to-client\n";
1021
				}
1022
				break;
1023
		}
1024
		if (isset($settings['duplicate_cn'])) {
1025
			$conf .= "duplicate-cn\n";
1026
		}
1027
	}
1028

    
1029
	// client specific settings
1030

    
1031
	if ($mode == 'client') {
1032

    
1033
		// configure p2p mode
1034
		switch ($settings['mode']) {
1035
			case 'p2p_tls':
1036
				$conf .= "tls-client\n";
1037
			case 'shared_key':
1038
				$conf .= "client\n";
1039
				break;
1040
		}
1041

    
1042
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1043
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1044
		//  ensure a random source port.
1045
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1046
			$conf .= "nobind\n";
1047
		} elseif ($settings['local_port']) {
1048
			$conf .= "lport {$settings['local_port']}\n";
1049
		} else {
1050
			$conf .= "lport 0\n";
1051
		}
1052

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

    
1056
		// The remote server
1057
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
1058

    
1059
		if (!empty($settings['use_shaper'])) {
1060
			$conf .= "shaper {$settings['use_shaper']}\n";
1061
		}
1062

    
1063
		if (!empty($settings['tunnel_network'])) {
1064
			list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1065
			$mask = gen_subnet_mask($cidr);
1066
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1067
			if ($settings['dev_mode'] == 'tun') {
1068
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1069
			} else {
1070
				$conf .= "ifconfig {$ip2} {$mask}\n";
1071
			}
1072
		}
1073

    
1074
		if (!empty($settings['tunnel_networkv6'])) {
1075
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1076
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1077
			if ($settings['dev_mode'] == 'tun') {
1078
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1079
			} else {
1080
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
1081
			}
1082
		}
1083

    
1084
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
1085
			$up_file = "{$g['varetc_path']}/openvpn/{$mode_id}.up";
1086
			$conf .= "auth-user-pass {$up_file}\n";
1087
			if (!$settings['auth-retry-none']) {
1088
				$conf .= "auth-retry nointeract\n";
1089
			}
1090
			if ($settings['auth_user']) {
1091
				$userpass = "{$settings['auth_user']}\n";
1092
			} else {
1093
				$userpass = "";
1094
			}
1095
			if ($settings['auth_pass']) {
1096
				$userpass .= "{$settings['auth_pass']}\n";
1097
			}
1098
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
1099
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
1100
				$userpass .= "\n";
1101
			}
1102
			file_put_contents($up_file, $userpass);
1103
		}
1104

    
1105
		if ($settings['proxy_addr']) {
1106
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1107
			if ($settings['proxy_authtype'] != "none") {
1108
				$conf .= " {$g['varetc_path']}/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
1109
				$proxypas = "{$settings['proxy_user']}\n";
1110
				$proxypas .= "{$settings['proxy_passwd']}\n";
1111
				file_put_contents("{$g['varetc_path']}/openvpn/{$mode_id}.pas", $proxypas);
1112
			}
1113
			$conf .= " \n";
1114
		}
1115
	}
1116

    
1117
	// Add a remote network route if set, and only for p2p modes.
1118
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
1119
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1120
	}
1121
	// Add a remote network route if set, and only for p2p modes.
1122
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
1123
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1124
	}
1125

    
1126
	// Write the settings for the keys
1127
	switch ($settings['mode']) {
1128
		case 'p2p_shared_key':
1129
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
1130
			break;
1131
		case 'p2p_tls':
1132
		case 'server_tls':
1133
		case 'server_tls_user':
1134
		case 'server_user':
1135
			// ca_chain() expects parameter to be passed by reference. 
1136
			// avoid passing the whole settings array, as param names or 
1137
			// types might change in future releases. 
1138
			$param = array('caref' => $settings['caref']);	
1139
			$ca = ca_chain($param);
1140
			$ca = base64_encode($ca);
1141
			
1142
			openvpn_add_keyfile($ca, $conf, $mode_id, "ca");
1143
			
1144
			unset($ca, $param);
1145

    
1146
			if (!empty($settings['certref'])) {
1147
				$cert = lookup_cert($settings['certref']);
1148
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
1149
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
1150
			}
1151
			if ($mode == 'server') {
1152
				if (is_numeric($settings['dh_length'])) {
1153
					if (!in_array($settings['dh_length'], array_keys($openvpn_dh_lengths))) {
1154
						/* The user selected a DH parameter length that does not have a corresponding file. */
1155
						log_error(gettext("Failed to construct OpenVPN server configuration. The selected DH Parameter length cannot be used."));
1156
						return;
1157
					}
1158
					$dh_file = "{$g['etc_path']}/dh-parameters.{$settings['dh_length']}";
1159
				} else {
1160
					$dh_file = $settings['dh_length'];
1161
				}
1162
				$conf .= "dh {$dh_file}\n";
1163
				if (!empty($settings['ecdh_curve']) && ($settings['ecdh_curve'] != "none") && openvpn_validate_curve($settings['ecdh_curve'])) {
1164
					$conf .= "ecdh-curve {$settings['ecdh_curve']}\n";
1165
				}
1166
			}
1167
			if (!empty($settings['crlref'])) {
1168
				$crl = lookup_crl($settings['crlref']);
1169
				crl_update($crl);
1170
				openvpn_add_keyfile($crl['text'], $conf, $mode_id, "crl-verify");
1171
			}
1172
			if ($settings['tls']) {
1173
				if ($settings['tls_type'] == "crypt") {
1174
					$tls_directive = "tls-crypt";
1175
					$tlsopt = "";
1176
				} else {
1177
					$tls_directive = "tls-auth";
1178
					if ($mode == "server") {
1179
						$tlsopt = 0;
1180
					} else {
1181
						$tlsopt = 1;
1182
					}
1183
				}
1184
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, $tls_directive, $tlsopt);
1185
			}
1186

    
1187
			/* NCP support. If it is not set, assume enabled since that is OpenVPN's default. */
1188
			if ($settings['ncp_enable'] == "disabled") {
1189
				$conf .= "ncp-disable\n";
1190
			} else {
1191
				/* If the ncp-ciphers list is empty, don't specify a list so OpenVPN's default will be used. */
1192
				if (!empty($settings['ncp-ciphers'])) {
1193
					$conf .= "ncp-ciphers " . str_replace(',', ':', $settings['ncp-ciphers']) . "\n";
1194
				}
1195
			}
1196

    
1197
			break;
1198
	}
1199

    
1200
	$compression = "";
1201
	switch ($settings['compression']) {
1202
		case 'lz4':
1203
		case 'lz4-v2':
1204
		case 'lzo':
1205
		case 'stub':
1206
			$compression .= "compress {$settings['compression']}";
1207
			break;
1208
		case 'noadapt':
1209
			$compression .= "comp-noadapt";
1210
			break;
1211
		case 'adaptive':
1212
		case 'yes':
1213
		case 'no':
1214
			$compression .= "comp-lzo {$settings['compression']}";
1215
			break;
1216
		default:
1217
			/* Add nothing to the configuration */
1218
			break;
1219
	}
1220

    
1221
	if (!empty($compression)) {
1222
		$conf .= "{$compression}\n";
1223
		if ($settings['compression_push']) {
1224
			$conf .= "push \"{$compression}\"\n";
1225
		}
1226
	}
1227

    
1228
	if ($settings['passtos']) {
1229
		$conf .= "passtos\n";
1230
	}
1231

    
1232
	if ($mode == 'client') {
1233
		$conf .= "resolv-retry infinite\n";
1234
	}
1235

    
1236
	if ($settings['dynamic_ip']) {
1237
		$conf .= "persist-remote-ip\n";
1238
		$conf .= "float\n";
1239
	}
1240

    
1241
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1242
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1243
		if (empty($settings['topology'])) {
1244
			$settings['topology'] = "subnet";
1245
		}
1246
		$conf .= "topology {$settings['topology']}\n";
1247
	}
1248

    
1249
	// New client features
1250
	if ($mode == "client") {
1251
		// Dont pull routes checkbox
1252
		if ($settings['route_no_pull']) {
1253
			$conf .= "route-nopull\n";
1254
		}
1255

    
1256
		// Dont add/remove routes checkbox
1257
		if ($settings['route_no_exec']) {
1258
			$conf .= "route-noexec\n";
1259
		}
1260
	}
1261

    
1262
	/* UDP Fast I/O. Only compatible with UDP and also not compatible with OpenVPN's "shaper" directive. */
1263
	if ($settings['udp_fast_io']
1264
	    && (strtolower(substr($settings['protocol'], 0, 3)) == "udp")
1265
	    && (empty($settings['use_shaper']))) {
1266
		$conf .= "fast-io\n";
1267
	}
1268

    
1269
	/* Send and Receive Buffer Settings */
1270
	if (is_numericint($settings['sndrcvbuf'])
1271
	    && ($settings['sndrcvbuf'] > 0)
1272
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1273
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1274
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1275
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1276
	}
1277

    
1278
	openvpn_add_custom($settings, $conf);
1279

    
1280
	openvpn_create_dirs();
1281
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.conf";
1282
	file_put_contents($fpath, $conf);
1283
	unset($conf);
1284
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.interface";
1285
	file_put_contents($fpath, $interface);
1286
	//chown($fpath, 'nobody');
1287
	//chgrp($fpath, 'nobody');
1288
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1289
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.interface", 0600);
1290
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
1291
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
1292
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1293

    
1294
	if ($wait_tentative) {
1295
		interface_wait_tentative($interface);
1296
	}
1297
}
1298

    
1299
function openvpn_restart($mode, $settings) {
1300
	global $g, $config;
1301

    
1302
	$vpnid = $settings['vpnid'];
1303
	$mode_id = $mode.$vpnid;
1304
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1305
	openvpn_reconfigure($mode, $settings);
1306
	/* kill the process if running */
1307
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1308
	if (file_exists($pfile)) {
1309

    
1310
		/* read the pid file */
1311
		$pid = rtrim(file_get_contents($pfile));
1312
		unlink($pfile);
1313
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1314

    
1315
		/* send a term signal to the process */
1316
		posix_kill($pid, SIGTERM);
1317

    
1318
		/* wait until the process exits, or timeout and kill it */
1319
		$i = 0;
1320
		while (posix_kill($pid, 0)) {
1321
			usleep(250000);
1322
			if ($i > 10) {
1323
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1324
				posix_kill($pid, SIGKILL);
1325
				usleep(500000);
1326
			}
1327
			$i++;
1328
		}
1329
	}
1330

    
1331
	if (isset($settings['disable'])) {
1332
		unlock($lockhandle);
1333
		return;
1334
	}
1335

    
1336
	/* Do not start an instance if we are not CARP master on this vip! */
1337
	if (strstr($settings['interface'], "_vip") && !in_array(get_carp_interface_status($settings['interface']), array("MASTER", ""))) {
1338
		unlock($lockhandle);
1339
		return;
1340
	}
1341

    
1342
	/* Check if client is bound to a gateway group */
1343
	$a_groups = return_gateway_groups_array();
1344
	if (is_array($a_groups[$settings['interface']])) {
1345
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1346
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1347
			unlock($lockhandle);
1348
			return;
1349
		}
1350
	}
1351

    
1352
	/* start the new process */
1353
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.conf";
1354
	openvpn_clear_route($mode, $settings);
1355
	$res = mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1356
	if ($res == 0) {
1357
		$i = 0;
1358
		$pid = "--";
1359
		while ($i < 3000) {
1360
			if (isvalidpid($pfile)) {
1361
				$pid = rtrim(file_get_contents($pfile));
1362
				break;
1363
			}
1364
			usleep(1000);
1365
			$i++;
1366
		}
1367
		syslog(LOG_INFO, "OpenVPN PID written: {$pid}");
1368
	} else {
1369
		syslog(LOG_ERR, "OpenVPN failed to start");
1370
	}
1371
	if (!platform_booting()) {
1372
		send_event("filter reload");
1373
	}
1374
	unlock($lockhandle);
1375
}
1376

    
1377
function openvpn_delete($mode, $settings) {
1378
	global $g, $config;
1379

    
1380
	$vpnid = $settings['vpnid'];
1381
	$mode_id = $mode.$vpnid;
1382

    
1383
	if ($mode == "server") {
1384
		$devname = "ovpns{$vpnid}";
1385
	} else {
1386
		$devname = "ovpnc{$vpnid}";
1387
	}
1388

    
1389
	/* kill the process if running */
1390
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1391
	if (file_exists($pfile)) {
1392

    
1393
		/* read the pid file */
1394
		$pid = trim(file_get_contents($pfile));
1395
		unlink($pfile);
1396

    
1397
		/* send a term signal to the process */
1398
		posix_kill($pid, SIGTERM);
1399
	}
1400

    
1401
	/* destroy the device */
1402
	pfSense_interface_destroy($devname);
1403

    
1404
	/* remove the configuration files */
1405
	@array_map('unlink', glob("{$g['varetc_path']}/openvpn/{$mode_id}.*"));
1406
}
1407

    
1408
function openvpn_resync_csc(& $settings) {
1409
	global $g, $config, $openvpn_tls_server_modes;
1410

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

    
1413
	if (isset($settings['disable'])) {
1414
		openvpn_delete_csc($settings);
1415
		return;
1416
	}
1417
	openvpn_create_dirs();
1418

    
1419
	if (empty($settings['server_list'])) {
1420
		$csc_server_list = array();
1421
	} else {
1422
		$csc_server_list = explode(",", $settings['server_list']);
1423
	}
1424

    
1425
	$conf = '';
1426
	if ($settings['block']) {
1427
		$conf .= "disable\n";
1428
	}
1429

    
1430
	if ($settings['push_reset']) {
1431
		$conf .= "push-reset\n";
1432
	}
1433

    
1434
	if ($settings['local_network']) {
1435
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1436
	}
1437
	if ($settings['local_networkv6']) {
1438
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1439
	}
1440

    
1441
	// Add a remote network iroute if set
1442
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1443
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1444
	}
1445
	// Add a remote network iroute if set
1446
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1447
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1448
	}
1449

    
1450
	openvpn_add_dhcpopts($settings, $conf);
1451

    
1452
	openvpn_add_custom($settings, $conf);
1453
	/* Loop through servers, find which ones can use this CSC */
1454
	if (is_array($config['openvpn']['openvpn-server'])) {
1455
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1456
			if (isset($serversettings['disable'])) {
1457
				continue;
1458
			}
1459
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1460
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1461
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1462
					$csc_conf = $conf;
1463

    
1464
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1465
						list($ip, $mask) = explode('/', trim($settings['tunnel_network']));
1466
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1467
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1468
						} else {
1469
							/* Because this is being pushed, the order from the client's point of view. */
1470
							$baselong = gen_subnetv4($ip, $mask);
1471
							$serverip = ip_after($baselong, 1);
1472
							$clientip = ip_after($baselong, 2);
1473
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1474
						}
1475
					}
1476

    
1477
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1478
						list($ipv6, $prefix) = explode('/', trim($serversettings['tunnel_networkv6']));
1479
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1480
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1481
					}
1482

    
1483
					file_put_contents($csc_path, $csc_conf);
1484
					chown($csc_path, 'nobody');
1485
					chgrp($csc_path, 'nobody');
1486
				}
1487
			}
1488
		}
1489
	}
1490
}
1491

    
1492
function openvpn_resync_csc_all() {
1493
	global $config;
1494
	if (is_array($config['openvpn']['openvpn-csc'])) {
1495
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1496
			openvpn_resync_csc($settings);
1497
		}
1498
	}
1499
}
1500

    
1501
function openvpn_delete_csc(& $settings) {
1502
	global $g, $config, $openvpn_tls_server_modes;
1503
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1504
	if (empty($settings['server_list'])) {
1505
		$csc_server_list = array();
1506
	} else {
1507
		$csc_server_list = explode(",", $settings['server_list']);
1508
	}
1509

    
1510
	/* Loop through servers, find which ones used this CSC */
1511
	if (is_array($config['openvpn']['openvpn-server'])) {
1512
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1513
			if (isset($serversettings['disable'])) {
1514
				continue;
1515
			}
1516
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1517
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1518
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1519
					unlink_if_exists($csc_path);
1520
				}
1521
			}
1522
		}
1523
	}
1524
}
1525

    
1526
// Resync the configuration and restart the VPN
1527
function openvpn_resync($mode, $settings) {
1528
	openvpn_restart($mode, $settings);
1529
}
1530

    
1531
// Resync and restart all VPNs
1532
function openvpn_resync_all($interface = "") {
1533
	global $g, $config;
1534

    
1535
	openvpn_create_dirs();
1536

    
1537
	if (!is_array($config['openvpn'])) {
1538
		$config['openvpn'] = array();
1539
	}
1540

    
1541
/*
1542
	if (!$config['openvpn']['dh-parameters']) {
1543
		echo "Configuring OpenVPN Parameters ...\n";
1544
		$dh_parameters = openvpn_create_dhparams(1024);
1545
		$dh_parameters = base64_encode($dh_parameters);
1546
		$config['openvpn']['dh-parameters'] = $dh_parameters;
1547
		write_config("OpenVPN DH parameters");
1548
	}
1549

    
1550
	$path_ovdh = $g['varetc_path']."/openvpn/dh-parameters";
1551
	if (!file_exists($path_ovdh)) {
1552
		$dh_parameters = $config['openvpn']['dh-parameters'];
1553
		$dh_parameters = base64_decode($dh_parameters);
1554
		file_put_contents($path_ovdh, $dh_parameters);
1555
	}
1556
*/
1557
	if ($interface <> "") {
1558
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1559
	} else {
1560
		log_error(gettext("Resyncing OpenVPN instances."));
1561
	}
1562

    
1563
	if (is_array($config['openvpn']['openvpn-server'])) {
1564
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1565
			if ($interface <> "" && $interface != $settings['interface']) {
1566
				continue;
1567
			}
1568
			openvpn_resync('server', $settings);
1569
		}
1570
	}
1571

    
1572
	if (is_array($config['openvpn']['openvpn-client'])) {
1573
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1574
			if ($interface <> "" && $interface != $settings['interface']) {
1575
				continue;
1576
			}
1577
			openvpn_resync('client', $settings);
1578
		}
1579
	}
1580

    
1581
	openvpn_resync_csc_all();
1582

    
1583
}
1584

    
1585
// Resync and restart all VPNs using a gateway group.
1586
function openvpn_resync_gwgroup($gwgroupname = "") {
1587
	global $g, $config;
1588

    
1589
	if ($gwgroupname <> "") {
1590
		if (is_array($config['openvpn']['openvpn-server'])) {
1591
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1592
				if ($gwgroupname == $settings['interface']) {
1593
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1594
					openvpn_resync('server', $settings);
1595
				}
1596
			}
1597
		}
1598

    
1599
		if (is_array($config['openvpn']['openvpn-client'])) {
1600
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1601
				if ($gwgroupname == $settings['interface']) {
1602
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1603
					openvpn_resync('client', $settings);
1604
				}
1605
			}
1606
		}
1607

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

    
1610
	} else {
1611
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1612
	}
1613
}
1614

    
1615
function openvpn_get_active_servers($type="multipoint") {
1616
	global $config, $g;
1617

    
1618
	$servers = array();
1619
	if (is_array($config['openvpn']['openvpn-server'])) {
1620
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1621
			if (empty($settings) || isset($settings['disable'])) {
1622
				continue;
1623
			}
1624

    
1625
			$prot = $settings['protocol'];
1626
			$port = $settings['local_port'];
1627

    
1628
			$server = array();
1629
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1630
			$server['mode'] = $settings['mode'];
1631
			if ($settings['description']) {
1632
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1633
			} else {
1634
				$server['name'] = "Server {$prot}:{$port}";
1635
			}
1636
			$server['conns'] = array();
1637
			$server['vpnid'] = $settings['vpnid'];
1638
			$server['mgmt'] = "server{$server['vpnid']}";
1639
			$socket = "unix://{$g['varetc_path']}/openvpn/{$server['mgmt']}.sock";
1640
			list($tn, $sm) = explode('/', trim($settings['tunnel_network']));
1641

    
1642
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1643
				$servers[] = openvpn_get_client_status($server, $socket);
1644
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1645
				$servers[] = openvpn_get_server_status($server, $socket);
1646
			}
1647
		}
1648
	}
1649
	return $servers;
1650
}
1651

    
1652
function openvpn_get_server_status($server, $socket) {
1653
	$errval = null;
1654
	$errstr = null;
1655
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1656
	if ($fp) {
1657
		stream_set_timeout($fp, 1);
1658

    
1659
		/* send our status request */
1660
		fputs($fp, "status 2\n");
1661

    
1662
		/* recv all response lines */
1663
		while (!feof($fp)) {
1664

    
1665
			/* read the next line */
1666
			$line = fgets($fp, 1024);
1667

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

    
1673
			/* parse header list line */
1674
			if (strstr($line, "HEADER")) {
1675
				continue;
1676
			}
1677

    
1678
			/* parse end of output line */
1679
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1680
				break;
1681
			}
1682

    
1683
			/* parse client list line */
1684
			if (strstr($line, "CLIENT_LIST")) {
1685
				$list = explode(",", $line);
1686
				$conn = array();
1687
				$conn['common_name'] = $list[1];
1688
				$conn['remote_host'] = $list[2];
1689
				$conn['virtual_addr'] = $list[3];
1690
				$conn['virtual_addr6'] = $list[4];
1691
				$conn['bytes_recv'] = $list[5];
1692
				$conn['bytes_sent'] = $list[6];
1693
				$conn['connect_time'] = $list[7];
1694
				$conn['connect_time_unix'] = $list[8];
1695
				$conn['user_name'] = $list[9];
1696
				$conn['client_id'] = $list[10];
1697
				$conn['peer_id'] = $list[11];
1698
				$server['conns'][] = $conn;
1699
			}
1700
			/* parse routing table lines */
1701
			if (strstr($line, "ROUTING_TABLE")) {
1702
				$list = explode(",", $line);
1703
				$conn = array();
1704
				$conn['virtual_addr'] = $list[1];
1705
				$conn['common_name'] = $list[2];
1706
				$conn['remote_host'] = $list[3];
1707
				$conn['last_time'] = $list[4];
1708
				$server['routes'][] = $conn;
1709
			}
1710
		}
1711

    
1712
		/* cleanup */
1713
		fclose($fp);
1714
	} else {
1715
		$conn = array();
1716
		$conn['common_name'] = "[error]";
1717
		$conn['remote_host'] = gettext("Unable to contact daemon");
1718
		$conn['virtual_addr'] = gettext("Service not running?");
1719
		$conn['bytes_recv'] = 0;
1720
		$conn['bytes_sent'] = 0;
1721
		$conn['connect_time'] = 0;
1722
		$server['conns'][] = $conn;
1723
	}
1724
	return $server;
1725
}
1726

    
1727
function openvpn_get_active_clients() {
1728
	global $config, $g;
1729

    
1730
	$clients = array();
1731
	if (is_array($config['openvpn']['openvpn-client'])) {
1732
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1733

    
1734
			if (empty($settings) || isset($settings['disable'])) {
1735
				continue;
1736
			}
1737

    
1738
			$prot = $settings['protocol'];
1739
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1740

    
1741
			$client = array();
1742
			$client['port'] = $settings['local_port'];
1743
			if ($settings['description']) {
1744
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1745
			} else {
1746
				$client['name'] = "Client {$prot}{$port}";
1747
			}
1748

    
1749
			$client['vpnid'] = $settings['vpnid'];
1750
			$client['mgmt'] = "client{$client['vpnid']}";
1751
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1752
			$client['status']="down";
1753

    
1754
			$clients[] = openvpn_get_client_status($client, $socket);
1755
		}
1756
	}
1757
	return $clients;
1758
}
1759

    
1760
function openvpn_get_client_status($client, $socket) {
1761
	$errval = null;
1762
	$errstr = null;
1763
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1764
	if ($fp) {
1765
		stream_set_timeout($fp, 1);
1766
		/* send our status request */
1767
		fputs($fp, "state 1\n");
1768

    
1769
		/* recv all response lines */
1770
		while (!feof($fp)) {
1771
			/* read the next line */
1772
			$line = fgets($fp, 1024);
1773

    
1774
			$info = stream_get_meta_data($fp);
1775
			if ($info['timed_out']) {
1776
				break;
1777
			}
1778

    
1779
			/* Get the client state */
1780
			if (strstr($line, "CONNECTED")) {
1781
				$client['status'] = "up";
1782
				$list = explode(",", $line);
1783

    
1784
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1785
				$client['virtual_addr'] = $list[3];
1786
				$client['remote_host'] = $list[4];
1787
				$client['remote_port'] = $list[5];
1788
				$client['local_host'] = $list[6];
1789
				$client['local_port'] = $list[7];
1790
				$client['virtual_addr6'] = $list[8];
1791
			}
1792
			if (strstr($line, "CONNECTING")) {
1793
				$client['status'] = "connecting";
1794
			}
1795
			if (strstr($line, "ASSIGN_IP")) {
1796
				$client['status'] = "waiting";
1797
				$list = explode(",", $line);
1798

    
1799
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1800
				$client['virtual_addr'] = $list[3];
1801
			}
1802
			if (strstr($line, "RECONNECTING")) {
1803
				$client['status'] = "reconnecting";
1804
				$list = explode(",", $line);
1805

    
1806
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1807
				$client['status'] .= "; " . $list[2];
1808
			}
1809
			/* parse end of output line */
1810
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1811
				break;
1812
			}
1813
		}
1814

    
1815
		/* If up, get read/write stats */
1816
		if (strcmp($client['status'], "up") == 0) {
1817
			fputs($fp, "status 2\n");
1818
			/* recv all response lines */
1819
			while (!feof($fp)) {
1820
				/* read the next line */
1821
				$line = fgets($fp, 1024);
1822

    
1823
				$info = stream_get_meta_data($fp);
1824
				if ($info['timed_out']) {
1825
					break;
1826
				}
1827

    
1828
				if (strstr($line, "TCP/UDP read bytes")) {
1829
					$list = explode(",", $line);
1830
					$client['bytes_recv'] = $list[1];
1831
				}
1832

    
1833
				if (strstr($line, "TCP/UDP write bytes")) {
1834
					$list = explode(",", $line);
1835
					$client['bytes_sent'] = $list[1];
1836
				}
1837

    
1838
				/* parse end of output line */
1839
				if (strstr($line, "END")) {
1840
					break;
1841
				}
1842
			}
1843
		}
1844

    
1845
		fclose($fp);
1846

    
1847
	} else {
1848
		$client['remote_host'] = gettext("Unable to contact daemon");
1849
		$client['virtual_addr'] = gettext("Service not running?");
1850
		$client['bytes_recv'] = 0;
1851
		$client['bytes_sent'] = 0;
1852
		$client['connect_time'] = 0;
1853
	}
1854
	return $client;
1855
}
1856

    
1857
function openvpn_kill_client($port, $remipp) {
1858
	global $g;
1859

    
1860
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1861
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1862
	$errval = null;
1863
	$errstr = null;
1864

    
1865
	/* open a tcp connection to the management port of each server */
1866
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1867
	$killed = -1;
1868
	if ($fp) {
1869
		stream_set_timeout($fp, 1);
1870
		fputs($fp, "kill {$remipp}\n");
1871
		while (!feof($fp)) {
1872
			$line = fgets($fp, 1024);
1873

    
1874
			$info = stream_get_meta_data($fp);
1875
			if ($info['timed_out']) {
1876
				break;
1877
			}
1878

    
1879
			/* parse header list line */
1880
			if (strpos($line, "INFO:") !== false) {
1881
				continue;
1882
			}
1883
			if (strpos($line, "SUCCESS") !== false) {
1884
				$killed = 0;
1885
			}
1886
			break;
1887
		}
1888
		fclose($fp);
1889
	}
1890
	return $killed;
1891
}
1892

    
1893
function openvpn_refresh_crls() {
1894
	global $g, $config;
1895

    
1896
	openvpn_create_dirs();
1897

    
1898
	if (is_array($config['openvpn']['openvpn-server'])) {
1899
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1900
			if (empty($settings)) {
1901
				continue;
1902
			}
1903
			if (isset($settings['disable'])) {
1904
				continue;
1905
			}
1906
			// Write the settings for the keys
1907
			switch ($settings['mode']) {
1908
				case 'p2p_tls':
1909
				case 'server_tls':
1910
				case 'server_tls_user':
1911
				case 'server_user':
1912
					if (!empty($settings['crlref'])) {
1913
						$crl = lookup_crl($settings['crlref']);
1914
						crl_update($crl);
1915
						$fpath = $g['varetc_path']."/openvpn/server{$settings['vpnid']}.crl-verify";
1916
						file_put_contents($fpath, base64_decode($crl['text']));
1917
						@chmod($fpath, 0644);
1918
					}
1919
					break;
1920
			}
1921
		}
1922
	}
1923
}
1924

    
1925
function openvpn_create_dirs() {
1926
	global $g, $config, $openvpn_tls_server_modes;
1927
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
1928
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
1929
	}
1930
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
1931
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
1932
	}
1933

    
1934
	/* Check for enabled servers and create server-specific CSC dirs */
1935
	if (is_array($config['openvpn']['openvpn-server'])) {
1936
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1937
			if (isset($settings['disable'])) {
1938
				continue;
1939
			}
1940
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
1941
				if ($settings['vpnid']) {
1942
					safe_mkdir("{$g['varetc_path']}/openvpn-csc/server{$settings['vpnid']}");
1943
				}
1944
			}
1945
		}
1946
	}
1947
}
1948

    
1949
function openvpn_get_interface_ip($ip, $cidr) {
1950
	$subnet = gen_subnetv4($ip, $cidr);
1951
	$ip1 = ip_after($subnet);
1952
	$ip2 = ip_after($ip1);
1953
	return array($ip1, $ip2);
1954
}
1955

    
1956
function openvpn_get_interface_ipv6($ipv6, $prefix) {
1957
	$basev6 = gen_subnetv6($ipv6, $prefix);
1958
	// Is there a better way to do this math?
1959
	$ipv6_arr = explode(':', $basev6);
1960
	$last = hexdec(array_pop($ipv6_arr));
1961
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
1962
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
1963
	return array($ipv6_1, $ipv6_2);
1964
}
1965

    
1966
function openvpn_clear_route($mode, $settings) {
1967
	if (empty($settings['tunnel_network'])) {
1968
		return;
1969
	}
1970
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1971
	$mask = gen_subnet_mask($cidr);
1972
	$clear_route = false;
1973

    
1974
	switch ($settings['mode']) {
1975
		case 'shared_key':
1976
			$clear_route = true;
1977
			break;
1978
		case 'p2p_tls':
1979
		case 'p2p_shared_key':
1980
			if ($cidr == 30) {
1981
				$clear_route = true;
1982
			}
1983
			break;
1984
	}
1985

    
1986
	if ($clear_route && !empty($ip) && !empty($mask)) {
1987
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1988
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
1989
		/* XXX: Family for route? */
1990
		mwexec("/sbin/route -q delete {$ip_to_clear}");
1991
	}
1992
}
1993

    
1994
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
1995
	$routes = "";
1996
	if (empty($value)) {
1997
		return "";
1998
	}
1999
	$networks = explode(',', $value);
2000

    
2001
	foreach ($networks as $network) {
2002
		if ($ipproto == "ipv4") {
2003
			$route = openvpn_gen_route_ipv4($network, $iroute);
2004
		} else {
2005
			$route = openvpn_gen_route_ipv6($network, $iroute);
2006
		}
2007

    
2008
		if ($push) {
2009
			$routes .= "push \"{$route}\"\n";
2010
		} else {
2011
			$routes .= "{$route}\n";
2012
		}
2013
	}
2014
	return $routes;
2015
}
2016

    
2017
function openvpn_gen_route_ipv4($network, $iroute = false) {
2018
	$i = ($iroute) ? "i" : "";
2019
	list($ip, $mask) = explode('/', trim($network));
2020
	$mask = gen_subnet_mask($mask);
2021
	return "{$i}route $ip $mask";
2022
}
2023

    
2024
function openvpn_gen_route_ipv6($network, $iroute = false) {
2025
	$i = ($iroute) ? "i" : "";
2026
	list($ipv6, $prefix) = explode('/', trim($network));
2027
	if (empty($prefix) && !is_numeric($prefix)) {
2028
		$prefix = "128";
2029
	}
2030
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2031
}
2032

    
2033
function openvpn_get_settings($mode, $vpnid) {
2034
	global $config;
2035

    
2036
	if (is_array($config['openvpn']['openvpn-server'])) {
2037
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2038
			if (isset($settings['disable'])) {
2039
				continue;
2040
			}
2041

    
2042
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2043
				return $settings;
2044
			}
2045
		}
2046
	}
2047

    
2048
	if (is_array($config['openvpn']['openvpn-client'])) {
2049
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
2050
			if (isset($settings['disable'])) {
2051
				continue;
2052
			}
2053

    
2054
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2055
				return $settings;
2056
			}
2057
		}
2058
	}
2059

    
2060
	return array();
2061
}
2062

    
2063
function openvpn_restart_by_vpnid($mode, $vpnid) {
2064
	$settings = openvpn_get_settings($mode, $vpnid);
2065
	openvpn_restart($mode, $settings);
2066
}
2067

    
2068
?>
(31-31/55)