Project

General

Profile

Download (60.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-2019 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
	6144 => "6144 bit",
87
	7680 => "7680 bit",
88
	8192 => "8192 bit",
89
	15360 => "15360 bit",
90
	16384 => "16384 bit",
91
	"none" => "ECDH Only"
92
);
93
foreach ($openvpn_dh_lengths as $idx => $dhlen) {
94
	if (is_numeric($idx) && !file_exists("/etc/dh-parameters.{$idx}")) {
95
		unset($openvpn_dh_lengths[$idx]);
96
	}
97
}
98

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

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

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

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

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

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

    
146
global $openvpn_tls_modes;
147
$openvpn_tls_modes = array(
148
	'auth' => gettext("TLS Authentication"),
149
	'crypt' => gettext("TLS Encryption and Authentication")
150
);
151

    
152
function openvpn_build_mode_list() {
153
	global $openvpn_server_modes;
154

    
155
	$list = array();
156

    
157
	foreach ($openvpn_server_modes as $name => $desc) {
158
		$list[$name] = $desc;
159
	}
160

    
161
	return($list);
162
}
163

    
164
global $openvpn_interfacenames;
165
function convert_openvpn_interface_to_friendly_descr($if) {
166
	global $openvpn_interfacenames;
167
	if (!is_array($openvpn_interfacenames)) {
168
		$openvpn_interfacenames = openvpn_build_if_list();
169
	}
170
	foreach($openvpn_interfacenames as $key => $value) {
171
		list($item_if, $item_ip) = explode("|", $key);
172
		if ($if == $item_if) {
173
			echo "$value";
174
		}
175
	}
176
}
177

    
178
function openvpn_build_if_list() {
179
	$list = array();
180

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

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

    
200
		$interfaces[$name] = "GW Group {$name}";
201
	}
202

    
203
	$interfaces['lo0'] = "Localhost";
204
	$interfaces['any'] = "any";
205

    
206
	foreach ($interfaces as $iface => $ifacename) {
207
	   $list[$iface] = $ifacename;
208
	}
209

    
210
	return($list);
211
}
212

    
213
function openvpn_build_crl_list() {
214
	global $a_crl;
215

    
216
	$list = array('' => 'None');
217

    
218
	foreach ($a_crl as $crl) {
219
		$caname = "";
220
		$ca = lookup_ca($crl['caref']);
221

    
222
		if ($ca) {
223
			$caname = " (CA: {$ca['descr']})";
224
		}
225

    
226
		$list[$crl['refid']] = $crl['descr'] . $caname;
227
	}
228

    
229
	return($list);
230
}
231

    
232
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
233
	global $a_cert;
234

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

    
241
	$non_server_list = array();
242

    
243
	if ($prioritize_server_certs) {
244
		$list[' '] = gettext("===== Server Certificates =====");
245
		$non_server_list['  '] = gettext("===== Non-Server Certificates =====");
246
	}
247

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

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

    
269
		if (!empty($properties)) {
270
			$propstr = " (" . implode(", ", $properties) . ")";
271
		}
272

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

    
284
	return(array('server' => $list, 'non-server' => $non_server_list));
285
}
286

    
287
function openvpn_build_bridge_list() {
288
	$list = array();
289

    
290
	$serverbridge_interface['none'] = "none";
291
	$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
292
	$viplist = get_configured_vip_list();
293

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

    
301
	foreach ($serverbridge_interface as $iface => $ifacename) {
302
		$list[$iface] = htmlspecialchars($ifacename);
303
	}
304

    
305
	return($list);
306
}
307

    
308
function openvpn_create_key() {
309

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

    
315
	$rslt = stream_get_contents($fp);
316
	pclose($fp);
317

    
318
	return $rslt;
319
}
320

    
321
function openvpn_create_dhparams($bits) {
322

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

    
328
	$rslt = stream_get_contents($fp);
329
	pclose($fp);
330

    
331
	return $rslt;
332
}
333

    
334
function openvpn_vpnid_used($vpnid) {
335
	global $config;
336

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

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

    
353
	return false;
354
}
355

    
356
function openvpn_vpnid_next() {
357

    
358
	$vpnid = 1;
359
	while (openvpn_vpnid_used($vpnid)) {
360
		$vpnid++;
361
	}
362

    
363
	return $vpnid;
364
}
365

    
366
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
367
	global $config;
368

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

    
378
	foreach ($ovpn_settings as $settings) {
379
		if (isset($settings['disable'])) {
380
			continue;
381
		}
382

    
383
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
384
			continue;
385
		}
386

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

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

    
404
	return 0;
405
}
406

    
407
function openvpn_port_next($prot, $interface = "wan") {
408

    
409
	$port = 1194;
410
	while (openvpn_port_used($prot, $interface, $port)) {
411
		$port++;
412
	}
413
	while (openvpn_port_used($prot, "any", $port)) {
414
		$port++;
415
	}
416

    
417
	return $port;
418
}
419

    
420
function openvpn_get_cipherlist() {
421

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

    
434
function openvpn_get_curvelist() {
435

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

    
448
function openvpn_validate_curve($curve) {
449
	$curves = openvpn_get_curvelist();
450
	return array_key_exists($curve, $curves);
451
}
452

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

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

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

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

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

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

    
551
function openvpn_validate_engine($engine) {
552
	$engines = openvpn_get_engines();
553
	return array_key_exists($engine, $engines);
554
}
555

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

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

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

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

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

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

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

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

    
630
function openvpn_add_dhcpopts(& $settings, & $conf) {
631

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

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

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

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

    
667
	if ($settings['netbios_enable']) {
668

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

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

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

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

    
696
function openvpn_add_custom(& $settings, & $conf) {
697

    
698
	if ($settings['custom_options']) {
699

    
700
		$options = explode(';', $settings['custom_options']);
701

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

    
712
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
713
	global $g;
714

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

    
722
	$conf .= "{$directive} {$fpath} {$opt}\n";
723
}
724

    
725
function openvpn_reconfigure($mode, $settings) {
726
	global $g, $config, $openvpn_tls_server_modes, $openvpn_dh_lengths;
727

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

    
741
	$vpnid = $settings['vpnid'];
742
	$mode_id = $mode.$vpnid;
743

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

    
752
	if ($mode == "server") {
753
		$devname = "ovpns{$vpnid}";
754
	} else {
755
		$devname = "ovpnc{$vpnid}";
756
	}
757

    
758
	/* is our device already configured */
759
	if (!does_interface_exist($devname)) {
760

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

    
766
		/* rename the device */
767
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
768

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

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

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

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

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

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

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

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

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

    
884
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
885
		$conf .= "engine {$settings['engine']}\n";
886
	}
887

    
888
	// server specific settings
889
	if ($mode == 'server') {
890

    
891
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
892
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
893
		$mask = gen_subnet_mask($cidr);
894

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

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

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

    
1005
		// The local port to listen on
1006
		$conf .= "lport {$settings['local_port']}\n";
1007

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

    
1013
		if ($settings['maxclients']) {
1014
			$conf .= "max-clients {$settings['maxclients']}\n";
1015
		}
1016

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

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

    
1041
	// client specific settings
1042

    
1043
	if ($mode == 'client') {
1044

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

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

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

    
1068
		// The remote server
1069
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
1070

    
1071
		if (!empty($settings['use_shaper'])) {
1072
			$conf .= "shaper {$settings['use_shaper']}\n";
1073
		}
1074

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

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

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

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

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

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

    
1154
			openvpn_add_keyfile($ca, $conf, $mode_id, "ca");
1155

    
1156
			unset($ca, $param);
1157

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

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

    
1209
			break;
1210
	}
1211

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

    
1236
	if (!empty($compression)) {
1237
		$conf .= "{$compression}\n";
1238
		if ($settings['compression_push']) {
1239
			$conf .= "push \"{$compression}\"\n";
1240
		}
1241
	}
1242

    
1243
	if ($settings['passtos']) {
1244
		$conf .= "passtos\n";
1245
	}
1246

    
1247
	if ($mode == 'client') {
1248
		$conf .= "resolv-retry infinite\n";
1249
	}
1250

    
1251
	if ($settings['dynamic_ip']) {
1252
		$conf .= "persist-remote-ip\n";
1253
		$conf .= "float\n";
1254
	}
1255

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

    
1264
	// New client features
1265
	if ($mode == "client") {
1266
		// Dont pull routes checkbox
1267
		if ($settings['route_no_pull']) {
1268
			$conf .= "route-nopull\n";
1269
		}
1270

    
1271
		// Dont add/remove routes checkbox
1272
		if ($settings['route_no_exec']) {
1273
			$conf .= "route-noexec\n";
1274
		}
1275
	}
1276

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

    
1284
	/* Send and Receive Buffer Settings */
1285
	if (is_numericint($settings['sndrcvbuf'])
1286
	    && ($settings['sndrcvbuf'] > 0)
1287
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1288
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1289
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1290
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1291
	}
1292

    
1293
	openvpn_add_custom($settings, $conf);
1294

    
1295
	openvpn_create_dirs();
1296
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.conf";
1297
	file_put_contents($fpath, $conf);
1298
	unset($conf);
1299
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.interface";
1300
	file_put_contents($fpath, $interface);
1301
	//chown($fpath, 'nobody');
1302
	//chgrp($fpath, 'nobody');
1303
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1304
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.interface", 0600);
1305
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
1306
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
1307
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1308

    
1309
	if ($wait_tentative) {
1310
		interface_wait_tentative($interface);
1311
	}
1312
}
1313

    
1314
function openvpn_restart($mode, $settings) {
1315
	global $g, $config;
1316

    
1317
	$vpnid = $settings['vpnid'];
1318
	$mode_id = $mode.$vpnid;
1319
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1320
	openvpn_reconfigure($mode, $settings);
1321
	/* kill the process if running */
1322
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1323
	if (file_exists($pfile)) {
1324

    
1325
		/* read the pid file */
1326
		$pid = rtrim(file_get_contents($pfile));
1327
		unlink($pfile);
1328
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1329

    
1330
		/* send a term signal to the process */
1331
		posix_kill($pid, SIGTERM);
1332

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

    
1346
	if (isset($settings['disable'])) {
1347
		unlock($lockhandle);
1348
		return;
1349
	}
1350

    
1351
	/* Do not start an instance if we are not CARP master on this vip! */
1352
	if (strstr($settings['interface'], "_vip") && !in_array(get_carp_interface_status($settings['interface']), array("MASTER", ""))) {
1353
		unlock($lockhandle);
1354
		return;
1355
	}
1356

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

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

    
1392
function openvpn_delete($mode, $settings) {
1393
	global $g, $config;
1394

    
1395
	$vpnid = $settings['vpnid'];
1396
	$mode_id = $mode.$vpnid;
1397

    
1398
	if ($mode == "server") {
1399
		$devname = "ovpns{$vpnid}";
1400
	} else {
1401
		$devname = "ovpnc{$vpnid}";
1402
	}
1403

    
1404
	/* kill the process if running */
1405
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1406
	if (file_exists($pfile)) {
1407

    
1408
		/* read the pid file */
1409
		$pid = trim(file_get_contents($pfile));
1410
		unlink($pfile);
1411

    
1412
		/* send a term signal to the process */
1413
		posix_kill($pid, SIGTERM);
1414
	}
1415

    
1416
	/* destroy the device */
1417
	pfSense_interface_destroy($devname);
1418

    
1419
	/* remove the configuration files */
1420
	@array_map('unlink', glob("{$g['varetc_path']}/openvpn/{$mode_id}.*"));
1421
}
1422

    
1423
function openvpn_resync_csc(& $settings) {
1424
	global $g, $config, $openvpn_tls_server_modes;
1425

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

    
1428
	if (isset($settings['disable'])) {
1429
		openvpn_delete_csc($settings);
1430
		return;
1431
	}
1432
	openvpn_create_dirs();
1433

    
1434
	if (empty($settings['server_list'])) {
1435
		$csc_server_list = array();
1436
	} else {
1437
		$csc_server_list = explode(",", $settings['server_list']);
1438
	}
1439

    
1440
	$conf = '';
1441
	if ($settings['block']) {
1442
		$conf .= "disable\n";
1443
	}
1444

    
1445
	if ($settings['push_reset']) {
1446
		$conf .= "push-reset\n";
1447
	}
1448

    
1449
	if ($settings['local_network']) {
1450
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1451
	}
1452
	if ($settings['local_networkv6']) {
1453
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1454
	}
1455

    
1456
	// Add a remote network iroute if set
1457
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1458
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1459
	}
1460
	// Add a remote network iroute if set
1461
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1462
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1463
	}
1464

    
1465
	openvpn_add_dhcpopts($settings, $conf);
1466

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

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

    
1492
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1493
						list($ipv6, $prefix) = explode('/', trim($serversettings['tunnel_networkv6']));
1494
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1495
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1496
					}
1497

    
1498
					file_put_contents($csc_path, $csc_conf);
1499
					chown($csc_path, 'nobody');
1500
					chgrp($csc_path, 'nobody');
1501
				}
1502
			}
1503
		}
1504
	}
1505
}
1506

    
1507
function openvpn_resync_csc_all() {
1508
	global $config;
1509
	if (is_array($config['openvpn']['openvpn-csc'])) {
1510
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1511
			openvpn_resync_csc($settings);
1512
		}
1513
	}
1514
}
1515

    
1516
function openvpn_delete_csc(& $settings) {
1517
	global $g, $config, $openvpn_tls_server_modes;
1518
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1519
	if (empty($settings['server_list'])) {
1520
		$csc_server_list = array();
1521
	} else {
1522
		$csc_server_list = explode(",", $settings['server_list']);
1523
	}
1524

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

    
1541
// Resync the configuration and restart the VPN
1542
function openvpn_resync($mode, $settings) {
1543
	openvpn_restart($mode, $settings);
1544
}
1545

    
1546
// Resync and restart all VPNs
1547
function openvpn_resync_all($interface = "") {
1548
	global $g, $config;
1549

    
1550
	openvpn_create_dirs();
1551

    
1552
	if (!is_array($config['openvpn'])) {
1553
		$config['openvpn'] = array();
1554
	}
1555

    
1556
/*
1557
	if (!$config['openvpn']['dh-parameters']) {
1558
		echo "Configuring OpenVPN Parameters ...\n";
1559
		$dh_parameters = openvpn_create_dhparams(1024);
1560
		$dh_parameters = base64_encode($dh_parameters);
1561
		$config['openvpn']['dh-parameters'] = $dh_parameters;
1562
		write_config("OpenVPN DH parameters");
1563
	}
1564

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

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

    
1587
	if (is_array($config['openvpn']['openvpn-client'])) {
1588
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1589
			if ($interface <> "" && $interface != $settings['interface']) {
1590
				continue;
1591
			}
1592
			openvpn_resync('client', $settings);
1593
		}
1594
	}
1595

    
1596
	openvpn_resync_csc_all();
1597

    
1598
}
1599

    
1600
// Resync and restart all VPNs using a gateway group.
1601
function openvpn_resync_gwgroup($gwgroupname = "") {
1602
	global $g, $config;
1603

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

    
1614
		if (is_array($config['openvpn']['openvpn-client'])) {
1615
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1616
				if ($gwgroupname == $settings['interface']) {
1617
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1618
					openvpn_resync('client', $settings);
1619
				}
1620
			}
1621
		}
1622

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

    
1625
	} else {
1626
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1627
	}
1628
}
1629

    
1630
function openvpn_get_active_servers($type="multipoint") {
1631
	global $config, $g;
1632

    
1633
	$servers = array();
1634
	if (is_array($config['openvpn']['openvpn-server'])) {
1635
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1636
			if (empty($settings) || isset($settings['disable'])) {
1637
				continue;
1638
			}
1639

    
1640
			$prot = $settings['protocol'];
1641
			$port = $settings['local_port'];
1642

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

    
1657
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1658
				$servers[] = openvpn_get_client_status($server, $socket);
1659
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1660
				$servers[] = openvpn_get_server_status($server, $socket);
1661
			}
1662
		}
1663
	}
1664
	return $servers;
1665
}
1666

    
1667
function openvpn_get_server_status($server, $socket) {
1668
	$errval = null;
1669
	$errstr = null;
1670
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1671
	if ($fp) {
1672
		stream_set_timeout($fp, 1);
1673

    
1674
		/* send our status request */
1675
		fputs($fp, "status 2\n");
1676

    
1677
		/* recv all response lines */
1678
		while (!feof($fp)) {
1679

    
1680
			/* read the next line */
1681
			$line = fgets($fp, 1024);
1682

    
1683
			$info = stream_get_meta_data($fp);
1684
			if ($info['timed_out']) {
1685
				break;
1686
			}
1687

    
1688
			/* parse header list line */
1689
			if (strstr($line, "HEADER")) {
1690
				continue;
1691
			}
1692

    
1693
			/* parse end of output line */
1694
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1695
				break;
1696
			}
1697

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

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

    
1742
function openvpn_get_active_clients() {
1743
	global $config, $g;
1744

    
1745
	$clients = array();
1746
	if (is_array($config['openvpn']['openvpn-client'])) {
1747
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1748

    
1749
			if (empty($settings) || isset($settings['disable'])) {
1750
				continue;
1751
			}
1752

    
1753
			$prot = $settings['protocol'];
1754
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1755

    
1756
			$client = array();
1757
			$client['port'] = $settings['local_port'];
1758
			if ($settings['description']) {
1759
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1760
			} else {
1761
				$client['name'] = "Client {$prot}{$port}";
1762
			}
1763

    
1764
			$client['vpnid'] = $settings['vpnid'];
1765
			$client['mgmt'] = "client{$client['vpnid']}";
1766
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1767
			$client['status']="down";
1768

    
1769
			$clients[] = openvpn_get_client_status($client, $socket);
1770
		}
1771
	}
1772
	return $clients;
1773
}
1774

    
1775
function openvpn_get_client_status($client, $socket) {
1776
	$errval = null;
1777
	$errstr = null;
1778
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1779
	if ($fp) {
1780
		stream_set_timeout($fp, 1);
1781
		/* send our status request */
1782
		fputs($fp, "state 1\n");
1783

    
1784
		/* recv all response lines */
1785
		while (!feof($fp)) {
1786
			/* read the next line */
1787
			$line = fgets($fp, 1024);
1788

    
1789
			$info = stream_get_meta_data($fp);
1790
			if ($info['timed_out']) {
1791
				break;
1792
			}
1793

    
1794
			/* Get the client state */
1795
			if (strstr($line, "CONNECTED")) {
1796
				$client['status'] = "up";
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
				$client['remote_host'] = $list[4];
1802
				$client['remote_port'] = $list[5];
1803
				$client['local_host'] = $list[6];
1804
				$client['local_port'] = $list[7];
1805
				$client['virtual_addr6'] = $list[8];
1806
			}
1807
			if (strstr($line, "CONNECTING")) {
1808
				$client['status'] = "connecting";
1809
			}
1810
			if (strstr($line, "ASSIGN_IP")) {
1811
				$client['status'] = "waiting";
1812
				$list = explode(",", $line);
1813

    
1814
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1815
				$client['virtual_addr'] = $list[3];
1816
			}
1817
			if (strstr($line, "RECONNECTING")) {
1818
				$client['status'] = "reconnecting";
1819
				$list = explode(",", $line);
1820

    
1821
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1822
				$client['status'] .= "; " . $list[2];
1823
			}
1824
			/* parse end of output line */
1825
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1826
				break;
1827
			}
1828
		}
1829

    
1830
		/* If up, get read/write stats */
1831
		if (strcmp($client['status'], "up") == 0) {
1832
			fputs($fp, "status 2\n");
1833
			/* recv all response lines */
1834
			while (!feof($fp)) {
1835
				/* read the next line */
1836
				$line = fgets($fp, 1024);
1837

    
1838
				$info = stream_get_meta_data($fp);
1839
				if ($info['timed_out']) {
1840
					break;
1841
				}
1842

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

    
1848
				if (strstr($line, "TCP/UDP write bytes")) {
1849
					$list = explode(",", $line);
1850
					$client['bytes_sent'] = $list[1];
1851
				}
1852

    
1853
				/* parse end of output line */
1854
				if (strstr($line, "END")) {
1855
					break;
1856
				}
1857
			}
1858
		}
1859

    
1860
		fclose($fp);
1861

    
1862
	} else {
1863
		$client['remote_host'] = gettext("Unable to contact daemon");
1864
		$client['virtual_addr'] = gettext("Service not running?");
1865
		$client['bytes_recv'] = 0;
1866
		$client['bytes_sent'] = 0;
1867
		$client['connect_time'] = 0;
1868
	}
1869
	return $client;
1870
}
1871

    
1872
function openvpn_kill_client($port, $remipp) {
1873
	global $g;
1874

    
1875
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1876
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1877
	$errval = null;
1878
	$errstr = null;
1879

    
1880
	/* open a tcp connection to the management port of each server */
1881
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1882
	$killed = -1;
1883
	if ($fp) {
1884
		stream_set_timeout($fp, 1);
1885
		fputs($fp, "kill {$remipp}\n");
1886
		while (!feof($fp)) {
1887
			$line = fgets($fp, 1024);
1888

    
1889
			$info = stream_get_meta_data($fp);
1890
			if ($info['timed_out']) {
1891
				break;
1892
			}
1893

    
1894
			/* parse header list line */
1895
			if (strpos($line, "INFO:") !== false) {
1896
				continue;
1897
			}
1898
			if (strpos($line, "SUCCESS") !== false) {
1899
				$killed = 0;
1900
			}
1901
			break;
1902
		}
1903
		fclose($fp);
1904
	}
1905
	return $killed;
1906
}
1907

    
1908
function openvpn_refresh_crls() {
1909
	global $g, $config;
1910

    
1911
	openvpn_create_dirs();
1912

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

    
1940
function openvpn_create_dirs() {
1941
	global $g, $config, $openvpn_tls_server_modes;
1942
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
1943
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
1944
	}
1945
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
1946
		/* If it's a file, remove it */
1947
		if (file_exists("{$g['varetc_path']}/openvpn-csc")) {
1948
			unlink_if_exists("{$g['varetc_path']}/openvpn-csc");
1949
		}
1950
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
1951
	}
1952

    
1953
	/* Check for enabled servers and create server-specific CSC dirs */
1954
	if (is_array($config['openvpn']['openvpn-server'])) {
1955
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1956
			if (isset($settings['disable'])) {
1957
				continue;
1958
			}
1959
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
1960
				if ($settings['vpnid']) {
1961
					safe_mkdir("{$g['varetc_path']}/openvpn-csc/server{$settings['vpnid']}");
1962
				}
1963
			}
1964
		}
1965
	}
1966
}
1967

    
1968
function openvpn_get_interface_ip($ip, $cidr) {
1969
	$subnet = gen_subnetv4($ip, $cidr);
1970
	if ($cidr == 31) {
1971
		$ip1 = $subnet;
1972
	} else {
1973
		$ip1 = ip_after($subnet);
1974
	}
1975
	$ip2 = ip_after($ip1);
1976
	return array($ip1, $ip2);
1977
}
1978

    
1979
function openvpn_get_interface_ipv6($ipv6, $prefix) {
1980
	$basev6 = gen_subnetv6($ipv6, $prefix);
1981
	// Is there a better way to do this math?
1982
	$ipv6_arr = explode(':', $basev6);
1983
	$last = hexdec(array_pop($ipv6_arr));
1984
	if ($prefix == 127) {
1985
		$last--;
1986
	}
1987
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
1988
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
1989
	return array($ipv6_1, $ipv6_2);
1990
}
1991

    
1992
function openvpn_clear_route($mode, $settings) {
1993
	if (empty($settings['tunnel_network'])) {
1994
		return;
1995
	}
1996
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1997
	$mask = gen_subnet_mask($cidr);
1998
	$clear_route = false;
1999

    
2000
	switch ($settings['mode']) {
2001
		case 'shared_key':
2002
			$clear_route = true;
2003
			break;
2004
		case 'p2p_tls':
2005
		case 'p2p_shared_key':
2006
			if ($cidr >= 30) {
2007
				$clear_route = true;
2008
			}
2009
			break;
2010
	}
2011

    
2012
	if ($clear_route && !empty($ip) && !empty($mask)) {
2013
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2014
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2015
		/* XXX: Family for route? */
2016
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2017
	}
2018
}
2019

    
2020
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2021
	$routes = "";
2022
	if (empty($value)) {
2023
		return "";
2024
	}
2025
	$networks = explode(',', $value);
2026

    
2027
	foreach ($networks as $network) {
2028
		if ($ipproto == "ipv4") {
2029
			$route = openvpn_gen_route_ipv4($network, $iroute);
2030
		} else {
2031
			$route = openvpn_gen_route_ipv6($network, $iroute);
2032
		}
2033

    
2034
		if ($push) {
2035
			$routes .= "push \"{$route}\"\n";
2036
		} else {
2037
			$routes .= "{$route}\n";
2038
		}
2039
	}
2040
	return $routes;
2041
}
2042

    
2043
function openvpn_gen_route_ipv4($network, $iroute = false) {
2044
	$i = ($iroute) ? "i" : "";
2045
	list($ip, $mask) = explode('/', trim($network));
2046
	$mask = gen_subnet_mask($mask);
2047
	return "{$i}route $ip $mask";
2048
}
2049

    
2050
function openvpn_gen_route_ipv6($network, $iroute = false) {
2051
	$i = ($iroute) ? "i" : "";
2052
	list($ipv6, $prefix) = explode('/', trim($network));
2053
	if (empty($prefix) && !is_numeric($prefix)) {
2054
		$prefix = "128";
2055
	}
2056
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2057
}
2058

    
2059
function openvpn_get_settings($mode, $vpnid) {
2060
	global $config;
2061

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

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

    
2074
	if (is_array($config['openvpn']['openvpn-client'])) {
2075
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
2076
			if (isset($settings['disable'])) {
2077
				continue;
2078
			}
2079

    
2080
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2081
				return $settings;
2082
			}
2083
		}
2084
	}
2085

    
2086
	return array();
2087
}
2088

    
2089
function openvpn_restart_by_vpnid($mode, $vpnid) {
2090
	$settings = openvpn_get_settings($mode, $vpnid);
2091
	openvpn_restart($mode, $settings);
2092
}
2093

    
2094
?>
(34-34/59)