Project

General

Profile

Download (60 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
							if (!empty($settings['serverbridge_routegateway']) && is_ipaddrv4($biface_ip)) {
954
								$conf .= "push \"route-gateway {$biface_ip}\"\n";
955
							}
956
							/* OpenVPN doesn't support this yet, clients do not recognize the option fully.
957
							$biface_ip6=get_interface_ipv6($settings['serverbridge_interface']);
958
							if (!empty($settings['serverbridge_routegateway']) && is_ipaddrv6($biface_ip6)) {
959
								$conf .= "push \"route-ipv6-gateway {$biface_ip6}\"\n";
960
							}
961
							*/
962
						} else {
963
							$conf .= "mode server\n";
964
						}
965
					}
966
				}
967
				break;
968
		}
969

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

    
1002
		// The local port to listen on
1003
		$conf .= "lport {$settings['local_port']}\n";
1004

    
1005
		// The management port to listen on
1006
		// Use unix socket to overcome the problem on any type of server
1007
		$conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n";
1008
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
1009

    
1010
		if ($settings['maxclients']) {
1011
			$conf .= "max-clients {$settings['maxclients']}\n";
1012
		}
1013

    
1014
		// Can we push routes, and should we?
1015
		if ($settings['local_network'] && !$settings['gwredir']) {
1016
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1017
		}
1018
		if ($settings['local_networkv6'] && !$settings['gwredir6']) {
1019
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1020
		}
1021

    
1022
		switch ($settings['mode']) {
1023
			case 'server_tls':
1024
			case 'server_user':
1025
			case 'server_tls_user':
1026
				// Configure client dhcp options
1027
				openvpn_add_dhcpopts($settings, $conf);
1028
				if ($settings['client2client']) {
1029
					$conf .= "client-to-client\n";
1030
				}
1031
				break;
1032
		}
1033
		if (isset($settings['duplicate_cn'])) {
1034
			$conf .= "duplicate-cn\n";
1035
		}
1036
	}
1037

    
1038
	// client specific settings
1039

    
1040
	if ($mode == 'client') {
1041

    
1042
		// configure p2p mode
1043
		switch ($settings['mode']) {
1044
			case 'p2p_tls':
1045
				$conf .= "tls-client\n";
1046
			case 'shared_key':
1047
				$conf .= "client\n";
1048
				break;
1049
		}
1050

    
1051
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1052
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1053
		//  ensure a random source port.
1054
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1055
			$conf .= "nobind\n";
1056
		} elseif ($settings['local_port']) {
1057
			$conf .= "lport {$settings['local_port']}\n";
1058
		} else {
1059
			$conf .= "lport 0\n";
1060
		}
1061

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

    
1065
		// The remote server
1066
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
1067

    
1068
		if (!empty($settings['use_shaper'])) {
1069
			$conf .= "shaper {$settings['use_shaper']}\n";
1070
		}
1071

    
1072
		if (!empty($settings['tunnel_network'])) {
1073
			list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1074
			$mask = gen_subnet_mask($cidr);
1075
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1076
			if ($settings['dev_mode'] == 'tun') {
1077
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1078
			} else {
1079
				$conf .= "ifconfig {$ip2} {$mask}\n";
1080
			}
1081
		}
1082

    
1083
		if (!empty($settings['tunnel_networkv6'])) {
1084
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1085
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1086
			if ($settings['dev_mode'] == 'tun') {
1087
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1088
			} else {
1089
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
1090
			}
1091
		}
1092

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

    
1114
		if ($settings['proxy_addr']) {
1115
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1116
			if ($settings['proxy_authtype'] != "none") {
1117
				$conf .= " {$g['varetc_path']}/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
1118
				$proxypas = "{$settings['proxy_user']}\n";
1119
				$proxypas .= "{$settings['proxy_passwd']}\n";
1120
				file_put_contents("{$g['varetc_path']}/openvpn/{$mode_id}.pas", $proxypas);
1121
			}
1122
			$conf .= " \n";
1123
		}
1124
	}
1125

    
1126
	// Add a remote network route if set, and only for p2p modes.
1127
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
1128
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1129
	}
1130
	// Add a remote network route if set, and only for p2p modes.
1131
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
1132
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1133
	}
1134

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

    
1151
			openvpn_add_keyfile($ca, $conf, $mode_id, "ca");
1152

    
1153
			unset($ca, $param);
1154

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

    
1196
			/* NCP support. If it is not set, assume enabled since that is OpenVPN's default. */
1197
			if ($settings['ncp_enable'] == "disabled") {
1198
				$conf .= "ncp-disable\n";
1199
			} else {
1200
				/* If the ncp-ciphers list is empty, don't specify a list so OpenVPN's default will be used. */
1201
				if (!empty($settings['ncp-ciphers'])) {
1202
					$conf .= "ncp-ciphers " . str_replace(',', ':', $settings['ncp-ciphers']) . "\n";
1203
				}
1204
			}
1205

    
1206
			break;
1207
	}
1208

    
1209
	$compression = "";
1210
	switch ($settings['compression']) {
1211
		case 'lz4':
1212
		case 'lz4-v2':
1213
		case 'lzo':
1214
		case 'stub':
1215
			$compression .= "compress {$settings['compression']}";
1216
			break;
1217
		case 'noadapt':
1218
			$compression .= "comp-noadapt";
1219
			break;
1220
		case 'adaptive':
1221
		case 'yes':
1222
		case 'no':
1223
			$compression .= "comp-lzo {$settings['compression']}";
1224
			break;
1225
		default:
1226
			/* Add nothing to the configuration */
1227
			break;
1228
	}
1229

    
1230
	if (!empty($compression)) {
1231
		$conf .= "{$compression}\n";
1232
		if ($settings['compression_push']) {
1233
			$conf .= "push \"{$compression}\"\n";
1234
		}
1235
	}
1236

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

    
1241
	if ($mode == 'client') {
1242
		$conf .= "resolv-retry infinite\n";
1243
	}
1244

    
1245
	if ($settings['dynamic_ip']) {
1246
		$conf .= "persist-remote-ip\n";
1247
		$conf .= "float\n";
1248
	}
1249

    
1250
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1251
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1252
		if (empty($settings['topology'])) {
1253
			$settings['topology'] = "subnet";
1254
		}
1255
		$conf .= "topology {$settings['topology']}\n";
1256
	}
1257

    
1258
	// New client features
1259
	if ($mode == "client") {
1260
		// Dont pull routes checkbox
1261
		if ($settings['route_no_pull']) {
1262
			$conf .= "route-nopull\n";
1263
		}
1264

    
1265
		// Dont add/remove routes checkbox
1266
		if ($settings['route_no_exec']) {
1267
			$conf .= "route-noexec\n";
1268
		}
1269
	}
1270

    
1271
	/* UDP Fast I/O. Only compatible with UDP and also not compatible with OpenVPN's "shaper" directive. */
1272
	if ($settings['udp_fast_io']
1273
	    && (strtolower(substr($settings['protocol'], 0, 3)) == "udp")
1274
	    && (empty($settings['use_shaper']))) {
1275
		$conf .= "fast-io\n";
1276
	}
1277

    
1278
	/* Send and Receive Buffer Settings */
1279
	if (is_numericint($settings['sndrcvbuf'])
1280
	    && ($settings['sndrcvbuf'] > 0)
1281
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1282
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1283
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1284
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1285
	}
1286

    
1287
	openvpn_add_custom($settings, $conf);
1288

    
1289
	openvpn_create_dirs();
1290
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.conf";
1291
	file_put_contents($fpath, $conf);
1292
	unset($conf);
1293
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.interface";
1294
	file_put_contents($fpath, $interface);
1295
	//chown($fpath, 'nobody');
1296
	//chgrp($fpath, 'nobody');
1297
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1298
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.interface", 0600);
1299
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
1300
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
1301
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1302

    
1303
	if ($wait_tentative) {
1304
		interface_wait_tentative($interface);
1305
	}
1306
}
1307

    
1308
function openvpn_restart($mode, $settings) {
1309
	global $g, $config;
1310

    
1311
	$vpnid = $settings['vpnid'];
1312
	$mode_id = $mode.$vpnid;
1313
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1314
	openvpn_reconfigure($mode, $settings);
1315
	/* kill the process if running */
1316
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1317
	if (file_exists($pfile)) {
1318

    
1319
		/* read the pid file */
1320
		$pid = rtrim(file_get_contents($pfile));
1321
		unlink($pfile);
1322
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1323

    
1324
		/* send a term signal to the process */
1325
		posix_kill($pid, SIGTERM);
1326

    
1327
		/* wait until the process exits, or timeout and kill it */
1328
		$i = 0;
1329
		while (posix_kill($pid, 0)) {
1330
			usleep(250000);
1331
			if ($i > 10) {
1332
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1333
				posix_kill($pid, SIGKILL);
1334
				usleep(500000);
1335
			}
1336
			$i++;
1337
		}
1338
	}
1339

    
1340
	if (isset($settings['disable'])) {
1341
		unlock($lockhandle);
1342
		return;
1343
	}
1344

    
1345
	/* Do not start an instance if we are not CARP master on this vip! */
1346
	if (strstr($settings['interface'], "_vip") && !in_array(get_carp_interface_status($settings['interface']), array("MASTER", ""))) {
1347
		unlock($lockhandle);
1348
		return;
1349
	}
1350

    
1351
	/* Check if client is bound to a gateway group */
1352
	$a_groups = return_gateway_groups_array(true);
1353
	if (is_array($a_groups[$settings['interface']])) {
1354
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1355
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1356
			unlock($lockhandle);
1357
			return;
1358
		}
1359
	}
1360

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

    
1386
function openvpn_delete($mode, $settings) {
1387
	global $g, $config;
1388

    
1389
	$vpnid = $settings['vpnid'];
1390
	$mode_id = $mode.$vpnid;
1391

    
1392
	if ($mode == "server") {
1393
		$devname = "ovpns{$vpnid}";
1394
	} else {
1395
		$devname = "ovpnc{$vpnid}";
1396
	}
1397

    
1398
	/* kill the process if running */
1399
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1400
	if (file_exists($pfile)) {
1401

    
1402
		/* read the pid file */
1403
		$pid = trim(file_get_contents($pfile));
1404
		unlink($pfile);
1405

    
1406
		/* send a term signal to the process */
1407
		posix_kill($pid, SIGTERM);
1408
	}
1409

    
1410
	/* destroy the device */
1411
	pfSense_interface_destroy($devname);
1412

    
1413
	/* remove the configuration files */
1414
	@array_map('unlink', glob("{$g['varetc_path']}/openvpn/{$mode_id}.*"));
1415
}
1416

    
1417
function openvpn_resync_csc(& $settings) {
1418
	global $g, $config, $openvpn_tls_server_modes;
1419

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

    
1422
	if (isset($settings['disable'])) {
1423
		openvpn_delete_csc($settings);
1424
		return;
1425
	}
1426
	openvpn_create_dirs();
1427

    
1428
	if (empty($settings['server_list'])) {
1429
		$csc_server_list = array();
1430
	} else {
1431
		$csc_server_list = explode(",", $settings['server_list']);
1432
	}
1433

    
1434
	$conf = '';
1435
	if ($settings['block']) {
1436
		$conf .= "disable\n";
1437
	}
1438

    
1439
	if ($settings['push_reset']) {
1440
		$conf .= "push-reset\n";
1441
	}
1442

    
1443
	if ($settings['local_network']) {
1444
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1445
	}
1446
	if ($settings['local_networkv6']) {
1447
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1448
	}
1449

    
1450
	// Add a remote network iroute if set
1451
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1452
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1453
	}
1454
	// Add a remote network iroute if set
1455
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1456
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1457
	}
1458

    
1459
	openvpn_add_dhcpopts($settings, $conf);
1460

    
1461
	openvpn_add_custom($settings, $conf);
1462
	/* Loop through servers, find which ones can use this CSC */
1463
	if (is_array($config['openvpn']['openvpn-server'])) {
1464
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1465
			if (isset($serversettings['disable'])) {
1466
				continue;
1467
			}
1468
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1469
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1470
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1471
					$csc_conf = $conf;
1472

    
1473
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1474
						list($ip, $mask) = explode('/', trim($settings['tunnel_network']));
1475
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1476
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1477
						} else {
1478
							/* Because this is being pushed, the order from the client's point of view. */
1479
							$baselong = gen_subnetv4($ip, $mask);
1480
							$serverip = ip_after($baselong, 1);
1481
							$clientip = ip_after($baselong, 2);
1482
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1483
						}
1484
					}
1485

    
1486
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1487
						list($ipv6, $prefix) = explode('/', trim($serversettings['tunnel_networkv6']));
1488
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1489
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1490
					}
1491

    
1492
					file_put_contents($csc_path, $csc_conf);
1493
					chown($csc_path, 'nobody');
1494
					chgrp($csc_path, 'nobody');
1495
				}
1496
			}
1497
		}
1498
	}
1499
}
1500

    
1501
function openvpn_resync_csc_all() {
1502
	global $config;
1503
	if (is_array($config['openvpn']['openvpn-csc'])) {
1504
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1505
			openvpn_resync_csc($settings);
1506
		}
1507
	}
1508
}
1509

    
1510
function openvpn_delete_csc(& $settings) {
1511
	global $g, $config, $openvpn_tls_server_modes;
1512
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1513
	if (empty($settings['server_list'])) {
1514
		$csc_server_list = array();
1515
	} else {
1516
		$csc_server_list = explode(",", $settings['server_list']);
1517
	}
1518

    
1519
	/* Loop through servers, find which ones used this CSC */
1520
	if (is_array($config['openvpn']['openvpn-server'])) {
1521
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1522
			if (isset($serversettings['disable'])) {
1523
				continue;
1524
			}
1525
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1526
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1527
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1528
					unlink_if_exists($csc_path);
1529
				}
1530
			}
1531
		}
1532
	}
1533
}
1534

    
1535
// Resync the configuration and restart the VPN
1536
function openvpn_resync($mode, $settings) {
1537
	openvpn_restart($mode, $settings);
1538
}
1539

    
1540
// Resync and restart all VPNs
1541
function openvpn_resync_all($interface = "") {
1542
	global $g, $config;
1543

    
1544
	openvpn_create_dirs();
1545

    
1546
	if (!is_array($config['openvpn'])) {
1547
		$config['openvpn'] = array();
1548
	}
1549

    
1550
/*
1551
	if (!$config['openvpn']['dh-parameters']) {
1552
		echo "Configuring OpenVPN Parameters ...\n";
1553
		$dh_parameters = openvpn_create_dhparams(1024);
1554
		$dh_parameters = base64_encode($dh_parameters);
1555
		$config['openvpn']['dh-parameters'] = $dh_parameters;
1556
		write_config("OpenVPN DH parameters");
1557
	}
1558

    
1559
	$path_ovdh = $g['varetc_path']."/openvpn/dh-parameters";
1560
	if (!file_exists($path_ovdh)) {
1561
		$dh_parameters = $config['openvpn']['dh-parameters'];
1562
		$dh_parameters = base64_decode($dh_parameters);
1563
		file_put_contents($path_ovdh, $dh_parameters);
1564
	}
1565
*/
1566
	if ($interface <> "") {
1567
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1568
	} else {
1569
		log_error(gettext("Resyncing OpenVPN instances."));
1570
	}
1571

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

    
1581
	if (is_array($config['openvpn']['openvpn-client'])) {
1582
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1583
			if ($interface <> "" && $interface != $settings['interface']) {
1584
				continue;
1585
			}
1586
			openvpn_resync('client', $settings);
1587
		}
1588
	}
1589

    
1590
	openvpn_resync_csc_all();
1591

    
1592
}
1593

    
1594
// Resync and restart all VPNs using a gateway group.
1595
function openvpn_resync_gwgroup($gwgroupname = "") {
1596
	global $g, $config;
1597

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

    
1608
		if (is_array($config['openvpn']['openvpn-client'])) {
1609
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1610
				if ($gwgroupname == $settings['interface']) {
1611
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1612
					openvpn_resync('client', $settings);
1613
				}
1614
			}
1615
		}
1616

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

    
1619
	} else {
1620
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1621
	}
1622
}
1623

    
1624
function openvpn_get_active_servers($type="multipoint") {
1625
	global $config, $g;
1626

    
1627
	$servers = array();
1628
	if (is_array($config['openvpn']['openvpn-server'])) {
1629
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1630
			if (empty($settings) || isset($settings['disable'])) {
1631
				continue;
1632
			}
1633

    
1634
			$prot = $settings['protocol'];
1635
			$port = $settings['local_port'];
1636

    
1637
			$server = array();
1638
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1639
			$server['mode'] = $settings['mode'];
1640
			if ($settings['description']) {
1641
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1642
			} else {
1643
				$server['name'] = "Server {$prot}:{$port}";
1644
			}
1645
			$server['conns'] = array();
1646
			$server['vpnid'] = $settings['vpnid'];
1647
			$server['mgmt'] = "server{$server['vpnid']}";
1648
			$socket = "unix://{$g['varetc_path']}/openvpn/{$server['mgmt']}.sock";
1649
			list($tn, $sm) = explode('/', trim($settings['tunnel_network']));
1650

    
1651
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1652
				$servers[] = openvpn_get_client_status($server, $socket);
1653
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1654
				$servers[] = openvpn_get_server_status($server, $socket);
1655
			}
1656
		}
1657
	}
1658
	return $servers;
1659
}
1660

    
1661
function openvpn_get_server_status($server, $socket) {
1662
	$errval = null;
1663
	$errstr = null;
1664
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1665
	if ($fp) {
1666
		stream_set_timeout($fp, 1);
1667

    
1668
		/* send our status request */
1669
		fputs($fp, "status 2\n");
1670

    
1671
		/* recv all response lines */
1672
		while (!feof($fp)) {
1673

    
1674
			/* read the next line */
1675
			$line = fgets($fp, 1024);
1676

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

    
1682
			/* parse header list line */
1683
			if (strstr($line, "HEADER")) {
1684
				continue;
1685
			}
1686

    
1687
			/* parse end of output line */
1688
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1689
				break;
1690
			}
1691

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

    
1721
		/* cleanup */
1722
		fclose($fp);
1723
	} else {
1724
		$conn = array();
1725
		$conn['common_name'] = "[error]";
1726
		$conn['remote_host'] = gettext("Unable to contact daemon");
1727
		$conn['virtual_addr'] = gettext("Service not running?");
1728
		$conn['bytes_recv'] = 0;
1729
		$conn['bytes_sent'] = 0;
1730
		$conn['connect_time'] = 0;
1731
		$server['conns'][] = $conn;
1732
	}
1733
	return $server;
1734
}
1735

    
1736
function openvpn_get_active_clients() {
1737
	global $config, $g;
1738

    
1739
	$clients = array();
1740
	if (is_array($config['openvpn']['openvpn-client'])) {
1741
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1742

    
1743
			if (empty($settings) || isset($settings['disable'])) {
1744
				continue;
1745
			}
1746

    
1747
			$prot = $settings['protocol'];
1748
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1749

    
1750
			$client = array();
1751
			$client['port'] = $settings['local_port'];
1752
			if ($settings['description']) {
1753
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1754
			} else {
1755
				$client['name'] = "Client {$prot}{$port}";
1756
			}
1757

    
1758
			$client['vpnid'] = $settings['vpnid'];
1759
			$client['mgmt'] = "client{$client['vpnid']}";
1760
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1761
			$client['status']="down";
1762

    
1763
			$clients[] = openvpn_get_client_status($client, $socket);
1764
		}
1765
	}
1766
	return $clients;
1767
}
1768

    
1769
function openvpn_get_client_status($client, $socket) {
1770
	$errval = null;
1771
	$errstr = null;
1772
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1773
	if ($fp) {
1774
		stream_set_timeout($fp, 1);
1775
		/* send our status request */
1776
		fputs($fp, "state 1\n");
1777

    
1778
		/* recv all response lines */
1779
		while (!feof($fp)) {
1780
			/* read the next line */
1781
			$line = fgets($fp, 1024);
1782

    
1783
			$info = stream_get_meta_data($fp);
1784
			if ($info['timed_out']) {
1785
				break;
1786
			}
1787

    
1788
			/* Get the client state */
1789
			if (strstr($line, "CONNECTED")) {
1790
				$client['status'] = "up";
1791
				$list = explode(",", $line);
1792

    
1793
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1794
				$client['virtual_addr'] = $list[3];
1795
				$client['remote_host'] = $list[4];
1796
				$client['remote_port'] = $list[5];
1797
				$client['local_host'] = $list[6];
1798
				$client['local_port'] = $list[7];
1799
				$client['virtual_addr6'] = $list[8];
1800
			}
1801
			if (strstr($line, "CONNECTING")) {
1802
				$client['status'] = "connecting";
1803
			}
1804
			if (strstr($line, "ASSIGN_IP")) {
1805
				$client['status'] = "waiting";
1806
				$list = explode(",", $line);
1807

    
1808
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1809
				$client['virtual_addr'] = $list[3];
1810
			}
1811
			if (strstr($line, "RECONNECTING")) {
1812
				$client['status'] = "reconnecting";
1813
				$list = explode(",", $line);
1814

    
1815
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1816
				$client['status'] .= "; " . $list[2];
1817
			}
1818
			/* parse end of output line */
1819
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1820
				break;
1821
			}
1822
		}
1823

    
1824
		/* If up, get read/write stats */
1825
		if (strcmp($client['status'], "up") == 0) {
1826
			fputs($fp, "status 2\n");
1827
			/* recv all response lines */
1828
			while (!feof($fp)) {
1829
				/* read the next line */
1830
				$line = fgets($fp, 1024);
1831

    
1832
				$info = stream_get_meta_data($fp);
1833
				if ($info['timed_out']) {
1834
					break;
1835
				}
1836

    
1837
				if (strstr($line, "TCP/UDP read bytes")) {
1838
					$list = explode(",", $line);
1839
					$client['bytes_recv'] = $list[1];
1840
				}
1841

    
1842
				if (strstr($line, "TCP/UDP write bytes")) {
1843
					$list = explode(",", $line);
1844
					$client['bytes_sent'] = $list[1];
1845
				}
1846

    
1847
				/* parse end of output line */
1848
				if (strstr($line, "END")) {
1849
					break;
1850
				}
1851
			}
1852
		}
1853

    
1854
		fclose($fp);
1855

    
1856
	} else {
1857
		$client['remote_host'] = gettext("Unable to contact daemon");
1858
		$client['virtual_addr'] = gettext("Service not running?");
1859
		$client['bytes_recv'] = 0;
1860
		$client['bytes_sent'] = 0;
1861
		$client['connect_time'] = 0;
1862
	}
1863
	return $client;
1864
}
1865

    
1866
function openvpn_kill_client($port, $remipp) {
1867
	global $g;
1868

    
1869
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1870
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1871
	$errval = null;
1872
	$errstr = null;
1873

    
1874
	/* open a tcp connection to the management port of each server */
1875
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1876
	$killed = -1;
1877
	if ($fp) {
1878
		stream_set_timeout($fp, 1);
1879
		fputs($fp, "kill {$remipp}\n");
1880
		while (!feof($fp)) {
1881
			$line = fgets($fp, 1024);
1882

    
1883
			$info = stream_get_meta_data($fp);
1884
			if ($info['timed_out']) {
1885
				break;
1886
			}
1887

    
1888
			/* parse header list line */
1889
			if (strpos($line, "INFO:") !== false) {
1890
				continue;
1891
			}
1892
			if (strpos($line, "SUCCESS") !== false) {
1893
				$killed = 0;
1894
			}
1895
			break;
1896
		}
1897
		fclose($fp);
1898
	}
1899
	return $killed;
1900
}
1901

    
1902
function openvpn_refresh_crls() {
1903
	global $g, $config;
1904

    
1905
	openvpn_create_dirs();
1906

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

    
1934
function openvpn_create_dirs() {
1935
	global $g, $config, $openvpn_tls_server_modes;
1936
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
1937
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
1938
	}
1939
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
1940
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
1941
	}
1942

    
1943
	/* Check for enabled servers and create server-specific CSC dirs */
1944
	if (is_array($config['openvpn']['openvpn-server'])) {
1945
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1946
			if (isset($settings['disable'])) {
1947
				continue;
1948
			}
1949
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
1950
				if ($settings['vpnid']) {
1951
					safe_mkdir("{$g['varetc_path']}/openvpn-csc/server{$settings['vpnid']}");
1952
				}
1953
			}
1954
		}
1955
	}
1956
}
1957

    
1958
function openvpn_get_interface_ip($ip, $cidr) {
1959
	$subnet = gen_subnetv4($ip, $cidr);
1960
	if ($cidr == 31) {
1961
		$ip1 = $subnet;
1962
	} else {
1963
		$ip1 = ip_after($subnet);
1964
	}
1965
	$ip2 = ip_after($ip1);
1966
	return array($ip1, $ip2);
1967
}
1968

    
1969
function openvpn_get_interface_ipv6($ipv6, $prefix) {
1970
	$basev6 = gen_subnetv6($ipv6, $prefix);
1971
	// Is there a better way to do this math?
1972
	$ipv6_arr = explode(':', $basev6);
1973
	$last = hexdec(array_pop($ipv6_arr));
1974
	if ($prefix == 127) {
1975
		$last--;
1976
	}
1977
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
1978
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
1979
	return array($ipv6_1, $ipv6_2);
1980
}
1981

    
1982
function openvpn_clear_route($mode, $settings) {
1983
	if (empty($settings['tunnel_network'])) {
1984
		return;
1985
	}
1986
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1987
	$mask = gen_subnet_mask($cidr);
1988
	$clear_route = false;
1989

    
1990
	switch ($settings['mode']) {
1991
		case 'shared_key':
1992
			$clear_route = true;
1993
			break;
1994
		case 'p2p_tls':
1995
		case 'p2p_shared_key':
1996
			if ($cidr >= 30) {
1997
				$clear_route = true;
1998
			}
1999
			break;
2000
	}
2001

    
2002
	if ($clear_route && !empty($ip) && !empty($mask)) {
2003
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2004
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2005
		/* XXX: Family for route? */
2006
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2007
	}
2008
}
2009

    
2010
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2011
	$routes = "";
2012
	if (empty($value)) {
2013
		return "";
2014
	}
2015
	$networks = explode(',', $value);
2016

    
2017
	foreach ($networks as $network) {
2018
		if ($ipproto == "ipv4") {
2019
			$route = openvpn_gen_route_ipv4($network, $iroute);
2020
		} else {
2021
			$route = openvpn_gen_route_ipv6($network, $iroute);
2022
		}
2023

    
2024
		if ($push) {
2025
			$routes .= "push \"{$route}\"\n";
2026
		} else {
2027
			$routes .= "{$route}\n";
2028
		}
2029
	}
2030
	return $routes;
2031
}
2032

    
2033
function openvpn_gen_route_ipv4($network, $iroute = false) {
2034
	$i = ($iroute) ? "i" : "";
2035
	list($ip, $mask) = explode('/', trim($network));
2036
	$mask = gen_subnet_mask($mask);
2037
	return "{$i}route $ip $mask";
2038
}
2039

    
2040
function openvpn_gen_route_ipv6($network, $iroute = false) {
2041
	$i = ($iroute) ? "i" : "";
2042
	list($ipv6, $prefix) = explode('/', trim($network));
2043
	if (empty($prefix) && !is_numeric($prefix)) {
2044
		$prefix = "128";
2045
	}
2046
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2047
}
2048

    
2049
function openvpn_get_settings($mode, $vpnid) {
2050
	global $config;
2051

    
2052
	if (is_array($config['openvpn']['openvpn-server'])) {
2053
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2054
			if (isset($settings['disable'])) {
2055
				continue;
2056
			}
2057

    
2058
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2059
				return $settings;
2060
			}
2061
		}
2062
	}
2063

    
2064
	if (is_array($config['openvpn']['openvpn-client'])) {
2065
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
2066
			if (isset($settings['disable'])) {
2067
				continue;
2068
			}
2069

    
2070
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2071
				return $settings;
2072
			}
2073
		}
2074
	}
2075

    
2076
	return array();
2077
}
2078

    
2079
function openvpn_restart_by_vpnid($mode, $vpnid) {
2080
	$settings = openvpn_get_settings($mode, $vpnid);
2081
	openvpn_restart($mode, $settings);
2082
}
2083

    
2084
?>
(33-33/60)