Project

General

Profile

Download (70.3 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-2013 BSD Perimeter
8
 * Copyright (c) 2013-2016 Electric Sheep Fencing
9
 * Copyright (c) 2014-2022 Rubicon Communications, LLC (Netgate)
10
 * All rights reserved.
11
 *
12
 * This file was rewritten from scratch by Fernando Lemos but
13
 * *MIGHT* contain code previously written by:
14
 *
15
 * Copyright (c) 2005 Peter Allgeyer <allgeyer_AT_web.de>
16
 * Copyright (c) 2004 Peter Curran (peter@closeconsultants.com).
17
 * All rights reserved.
18
 *
19
 * Licensed under the Apache License, Version 2.0 (the "License");
20
 * you may not use this file except in compliance with the License.
21
 * You may obtain a copy of the License at
22
 *
23
 * http://www.apache.org/licenses/LICENSE-2.0
24
 *
25
 * Unless required by applicable law or agreed to in writing, software
26
 * distributed under the License is distributed on an "AS IS" BASIS,
27
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28
 * See the License for the specific language governing permissions and
29
 * limitations under the License.
30
 */
31

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

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

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

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

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

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

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

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

    
118
global $openvpn_tls_server_modes;
119
$openvpn_tls_server_modes = array('p2p_tls', 'server_tls', 'server_user', 'server_tls_user');
120

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

    
126
global $openvpn_allow_compression;
127
$openvpn_allow_compression = array(
128
	'asym' => gettext("Decompress incoming, do not compress outgoing (Asymmetric)"),
129
	'no'   => gettext("Refuse any non-stub compression (Most secure)"),
130
	'yes'  => gettext("Compress packets (WARNING: Potentially dangerous!)"),
131
);
132

    
133
global $openvpn_compression_modes;
134
$openvpn_compression_modes = array(
135
	'' => gettext("Disable Compression [Omit Preference]"),
136
	'none' => gettext("Disable Compression, retain compression packet framing [compress]"),
137
	'stub' => gettext("Enable Compression (stub) [compress stub]"),
138
	'stub-v2' => gettext("Enable Compression (stub v2) [compress stub-v2]"),
139
	'lz4' => gettext("LZ4 Compression [compress lz4]"),
140
	'lz4-v2' => gettext("LZ4 Compression v2 [compress lz4-v2]"),
141
	'lzo' => gettext("LZO Compression [compress lzo, equivalent to comp-lzo yes for compatibility]"),
142
	'noadapt' => gettext("Omit Preference, + Disable Adaptive LZO Compression [Legacy style, comp-noadapt]"),
143
	'adaptive' => gettext("Adaptive LZO Compression [Legacy style, comp-lzo adaptive]"),
144
	'yes' => gettext("LZO Compression [Legacy style, comp-lzo yes]"),
145
	'no' => gettext("No LZO Compression [Legacy style, comp-lzo no]"),
146
);
147

    
148
global $openvpn_topologies;
149
$openvpn_topologies = array(
150
	'subnet' => gettext("Subnet -- One IP address per client in a common subnet"),
151
	'net30' => gettext("net30 -- Isolated /30 network per client")
152
);
153

    
154
global $openvpn_tls_modes;
155
$openvpn_tls_modes = array(
156
	'auth' => gettext("TLS Authentication"),
157
	'crypt' => gettext("TLS Encryption and Authentication")
158
);
159

    
160
global $openvpn_ping_method;
161
$openvpn_ping_method = array(
162
	'keepalive' => gettext("keepalive -- Use keepalive helper to define ping configuration"),
163
	'ping' => gettext("ping -- Define ping/ping-exit/ping-restart manually")
164
);
165

    
166
global $openvpn_default_keepalive_interval;
167
$openvpn_default_keepalive_interval = 10;
168

    
169
global $openvpn_default_keepalive_timeout;
170
$openvpn_default_keepalive_timeout = 60;
171

    
172
global $openvpn_ping_action;
173
$openvpn_ping_action = array(
174
	'ping_restart' => gettext("ping-restart -- Restart OpenVPN after timeout"),
175
	'ping_exit' => gettext("ping-exit -- Exit OpenVPN after timeout")
176
);
177

    
178
global $openvpn_exit_notify_server;
179
$openvpn_exit_notify_server = array(
180
	'none' => gettext("Disabled"),
181
	'1' => gettext("Reconnect to this server / Retry once"),
182
	'2' => gettext("Reconnect to next server / Retry twice"),
183
);
184

    
185
global $openvpn_exit_notify_client;
186
$openvpn_exit_notify_client = array(
187
	'none' => gettext("Disabled"),
188
);
189
for ($i=1; $i<=5; $i++) {
190
	$openvpn_exit_notify_client[$i] = sprintf(gettext("Retry %dx"), $i);
191
}
192

    
193
function openvpn_build_mode_list() {
194
	global $openvpn_server_modes;
195

    
196
	$list = array();
197

    
198
	foreach ($openvpn_server_modes as $name => $desc) {
199
		$list[$name] = $desc;
200
	}
201

    
202
	return($list);
203
}
204

    
205
global $openvpn_interfacenames;
206
function convert_openvpn_interface_to_friendly_descr($if) {
207
	global $openvpn_interfacenames;
208
	if (!is_array($openvpn_interfacenames)) {
209
		$openvpn_interfacenames = openvpn_build_if_list();
210
	}
211
	foreach($openvpn_interfacenames as $key => $value) {
212
		list($item_if, $item_ip) = explode("|", $key);
213
		if ($if == $item_if) {
214
			echo "$value";
215
		}
216
	}
217
}
218

    
219
function openvpn_build_if_list() {
220
	$list = array();
221

    
222
	$interfaces = get_configured_interface_with_descr();
223
	$viplist = get_configured_vip_list();
224
	foreach ($viplist as $vip => $address) {
225
		$interfaces[$vip.'|'.$address] = $address;
226
		if (get_vip_descr($address)) {
227
			$interfaces[$vip.'|'.$address] .= " (";
228
			$interfaces[$vip.'|'.$address] .= get_vip_descr($address);
229
			$interfaces[$vip.'|'.$address] .= ")";
230
		}
231
	}
232

    
233
	$grouplist = return_gateway_groups_array();
234
	foreach ($grouplist as $name => $group) {
235
		if ($group[0]['vip'] != "") {
236
			$vipif = $group[0]['vip'];
237
		} else {
238
			$vipif = $group[0]['int'];
239
		}
240

    
241
		$interfaces[$name] = "GW Group {$name}";
242
	}
243

    
244
	$interfaces['lo0'] = "Localhost";
245
	$interfaces['any'] = "any";
246

    
247
	foreach ($interfaces as $iface => $ifacename) {
248
	   $list[$iface] = $ifacename;
249
	}
250

    
251
	return($list);
252
}
253

    
254
function openvpn_build_crl_list() {
255
	global $a_crl;
256

    
257
	$list = array('' => 'None');
258

    
259
	foreach ($a_crl as $crl) {
260
		$caname = "";
261
		$ca = lookup_ca($crl['caref']);
262

    
263
		if ($ca) {
264
			$caname = " (CA: {$ca['descr']})";
265
		}
266

    
267
		$list[$crl['refid']] = $crl['descr'] . $caname;
268
	}
269

    
270
	return($list);
271
}
272

    
273
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
274
	global $a_cert;
275
	$openvpn_compatible_certs = cert_build_list('cert', 'OpenVPN');
276

    
277
	if ($include_none) {
278
		$list = array('' => gettext('None (Username and/or Password required)'));
279
	} else {
280
		$list = array();
281
	}
282

    
283
	$non_server_list = array();
284

    
285
	if ($prioritize_server_certs) {
286
		$list[' '] = gettext("===== Server Certificates =====");
287
		$non_server_list['  '] = gettext("===== Non-Server Certificates =====");
288
	}
289

    
290
	foreach ($a_cert as $cert) {
291
		if (!array_key_exists($cert['refid'], $openvpn_compatible_certs)) {
292
			continue;
293
		}
294
		$properties = array();
295
		$propstr = "";
296
		$ca = lookup_ca($cert['caref']);
297
		$purpose = cert_get_purpose($cert['crt'], true);
298

    
299
		if ($purpose['server'] == "Yes") {
300
			$properties[] = gettext("Server: Yes");
301
		} elseif ($prioritize_server_certs) {
302
			$properties[] = gettext("Server: NO");
303
		}
304
		if ($ca) {
305
			$properties[] = sprintf(gettext("CA: %s"), $ca['descr']);
306
		}
307
		if (cert_in_use($cert['refid'])) {
308
			$properties[] = gettext("In Use");
309
		}
310
		if (is_cert_revoked($cert)) {
311
			$properties[] = gettext("Revoked");
312
		}
313

    
314
		if (!empty($properties)) {
315
			$propstr = " (" . implode(", ", $properties) . ")";
316
		}
317

    
318
		if ($prioritize_server_certs) {
319
			if ($purpose['server'] == "Yes") {
320
				$list[$cert['refid']] = $cert['descr'] . $propstr;
321
			} else {
322
				$non_server_list[$cert['refid']] = $cert['descr'] . $propstr;
323
			}
324
		} else {
325
			$list[$cert['refid']] = $cert['descr'] . $propstr;
326
		}
327
	}
328

    
329
	return(array('server' => $list, 'non-server' => $non_server_list));
330
}
331

    
332
function openvpn_build_bridge_list() {
333
	$list = array();
334

    
335
	$serverbridge_interface['none'] = "none";
336
	$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
337
	$viplist = get_configured_vip_list();
338

    
339
	foreach ($viplist as $vip => $address) {
340
		$serverbridge_interface[$vip.'|'.$address] = $address;
341
		if (get_vip_descr($address)) {
342
			$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
343
		}
344
	}
345

    
346
	foreach ($serverbridge_interface as $iface => $ifacename) {
347
		$list[$iface] = htmlspecialchars($ifacename);
348
	}
349

    
350
	return($list);
351
}
352

    
353
function openvpn_create_key() {
354

    
355
	$fp = popen("/usr/local/sbin/openvpn --genkey secret /dev/stdout 2>/dev/null", "r");
356
	if (!$fp) {
357
		return false;
358
	}
359

    
360
	$rslt = stream_get_contents($fp);
361
	pclose($fp);
362

    
363
	return $rslt;
364
}
365

    
366
function openvpn_create_dhparams($bits) {
367

    
368
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
369
	if (!$fp) {
370
		return false;
371
	}
372

    
373
	$rslt = stream_get_contents($fp);
374
	pclose($fp);
375

    
376
	return $rslt;
377
}
378

    
379
function openvpn_vpnid_used($vpnid) {
380
	global $config;
381

    
382
	if (is_array($config['openvpn']['openvpn-server'])) {
383
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
384
			if ($vpnid == $settings['vpnid']) {
385
				return true;
386
			}
387
		}
388
	}
389

    
390
	if (is_array($config['openvpn']['openvpn-client'])) {
391
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
392
			if ($vpnid == $settings['vpnid']) {
393
				return true;
394
			}
395
		}
396
	}
397

    
398
	return false;
399
}
400

    
401
function openvpn_vpnid_next() {
402

    
403
	$vpnid = 1;
404
	while (openvpn_vpnid_used($vpnid)) {
405
		$vpnid++;
406
	}
407

    
408
	return $vpnid;
409
}
410

    
411
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
412
	global $config;
413

    
414
	$ovpn_settings = array();
415
	if (is_array($config['openvpn']['openvpn-server'])) {
416
		$ovpn_settings = $config['openvpn']['openvpn-server'];
417
	}
418
	if (is_array($config['openvpn']['openvpn-client'])) {
419
		$ovpn_settings = array_merge($ovpn_settings,
420
		    $config['openvpn']['openvpn-client']);
421
	}
422

    
423
	foreach ($ovpn_settings as $settings) {
424
		if (isset($settings['disable'])) {
425
			continue;
426
		}
427

    
428
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
429
			continue;
430
		}
431

    
432
		/* (TCP|UDP)(4|6) does not conflict unless interface is any */
433
		if (($interface != "any" && $settings['interface'] != "any") &&
434
		    (strlen($prot) == 4) &&
435
		    (strlen($settings['protocol']) == 4) &&
436
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
437
		    substr($prot,3,1) != substr($settings['protocol'],3,1)) {
438
			continue;
439
		}
440

    
441
		if ($port == $settings['local_port'] &&
442
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
443
		    ($interface == $settings['interface'] ||
444
		    $interface == "any" || $settings['interface'] == "any")) {
445
			return $settings['vpnid'];
446
		}
447
	}
448

    
449
	return 0;
450
}
451

    
452
function openvpn_port_next($prot, $interface = "wan") {
453

    
454
	$port = 1194;
455
	while (openvpn_port_used($prot, $interface, $port)) {
456
		$port++;
457
	}
458
	while (openvpn_port_used($prot, "any", $port)) {
459
		$port++;
460
	}
461

    
462
	return $port;
463
}
464

    
465
function openvpn_get_cipherlist() {
466

    
467
	$ciphers = array();
468
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
469
	$cipher_lines = explode("\n", trim($cipher_out));
470
	sort($cipher_lines);
471
	foreach ($cipher_lines as $line) {
472
		$words = explode(' ', $line, 2);
473
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
474
	}
475
	$ciphers["none"] = gettext("None (No Encryption)");
476
	return $ciphers;
477
}
478

    
479
function openvpn_get_curvelist() {
480
	global $cert_curve_compatible;
481
	$curves = array();
482
	$curves["none"] = gettext("Use Default");
483
	foreach ($cert_curve_compatible['OpenVPN'] as $curve) {
484
		$curves[$curve] = $curve;
485
	}
486
	return $curves;
487
}
488

    
489
function openvpn_validate_curve($curve) {
490
	$curves = openvpn_get_curvelist();
491
	return array_key_exists($curve, $curves);
492
}
493

    
494
/* Obtain the list of digest algorithms supported by openssl and their alternate names */
495
function openvpn_get_openssldigestmappings() {
496
	$digests = array();
497
	$digest_out = shell_exec('/usr/bin/openssl list -digest-algorithms | /usr/bin/grep "=>"');
498
	$digest_lines = explode("\n", trim($digest_out));
499
	sort($digest_lines);
500
	foreach ($digest_lines as $line) {
501
		$words = explode(' => ', $line, 2);
502
		$digests[$words[0]] = $words[1];
503
	}
504
	return $digests;
505
}
506

    
507
/* Obtain the list of digest algorithms supported by openvpn */
508
function openvpn_get_digestlist() {
509
	/* Grab the list from OpenSSL to check for duplicates or aliases */
510
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
511
	$digests = array();
512
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
513
	$digest_lines = explode("\n", trim($digest_out));
514
	sort($digest_lines);
515
	foreach ($digest_lines as $line) {
516
		$words = explode(' ', $line);
517
		/* Only add the entry if it is NOT also listed as being an alias/mapping by OpenSSL */
518
		if (!array_key_exists($words[0], $openssl_digest_mappings)) {
519
			$digests[$words[0]] = "{$words[0]} {$words[1]}";
520
		}
521
	}
522
	$digests["none"] = gettext("None (No Authentication)");
523
	return $digests;
524
}
525

    
526
/* Check to see if a digest name is an alias and if so, find the actual digest
527
 * algorithm instead. Useful for upgrade code that has to translate aliased
528
 * algorithms to their actual names.
529
 */
530
function openvpn_remap_digest($digest) {
531
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
532
	if (array_key_exists($digest, $openssl_digest_mappings)) {
533
		/* Some mappings point to other mappings, keep going until we find the actual digest algorithm */
534
		if (array_key_exists($openssl_digest_mappings[$digest], $openssl_digest_mappings)) {
535
			return openvpn_remap_digest($openssl_digest_mappings[$digest]);
536
		} else {
537
			return $openssl_digest_mappings[$digest];
538
		}
539
	}
540
	return $digest;
541
}
542

    
543
function openvpn_get_keydirlist() {
544
	$keydirs = array(
545
		'default'  => gettext('Use default direction'),
546
		'0' => gettext('Direction 0'),
547
		'1' => gettext('Direction 1'),
548
		'2' => gettext('Both directions'),
549
	);
550
	return $keydirs;
551
}
552

    
553
function openvpn_get_engines() {
554
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
555
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
556
	$openssl_engine_output = implode("\n", $openssl_engine_output);
557
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
558
	$openssl_engine_output = explode("\n", $openssl_engine_output);
559

    
560
	foreach ($openssl_engine_output as $oeo) {
561
		$keep = true;
562
		$details = explode("|", $oeo);
563
		$engine = array_shift($details);
564
		$linematch = array();
565
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
566
		foreach ($details as $dt) {
567
			if (strpos($dt, "unavailable") !== FALSE) {
568
				$keep = false;
569
			}
570
			if (strpos($dt, "available") !== FALSE) {
571
				continue;
572
			}
573
			if (strpos($dt, "[") !== FALSE) {
574
				$ciphers = trim($dt, "[]");
575
			}
576
		}
577
		if (!empty($ciphers)) {
578
			$ciphers = " - " . $ciphers;
579
		}
580
		if (strlen($ciphers) > 60) {
581
			$ciphers = substr($ciphers, 0, 60) . " ... ";
582
		}
583
		if ($keep) {
584
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
585
		}
586
	}
587
	return $openssl_engines;
588
}
589

    
590
function openvpn_get_buffer_values() {
591
	$sendbuf_max = get_single_sysctl('net.inet.tcp.sendbuf_max');
592
	$recvbuf_max = get_single_sysctl('net.inet.tcp.recvbuf_max');
593
	/* Usually these two are equal, but if they are not, take whichever one is lower. */
594
	$buffer_max = ($sendbuf_max <= $recvbuf_max) ? $sendbuf_max : $recvbuf_max;
595
	$buffer_values = array('' => gettext('Default'));
596
	for ($bs = 32; $bs >= 1; $bs /= 2) {
597
		$buffer_values[$buffer_max/$bs] = format_bytes($buffer_max/$bs);
598
	}
599
	return $buffer_values;
600
}
601

    
602
function openvpn_validate_engine($engine) {
603
	$engines = openvpn_get_engines();
604
	return array_key_exists($engine, $engines);
605
}
606

    
607
function openvpn_validate_host($value, $name) {
608
	$value = trim($value);
609
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
610
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
611
	}
612
	return false;
613
}
614

    
615
function openvpn_validate_port($value, $name, $first_port = 0) {
616
	$value = trim($value);
617
	if (!is_numeric($first_port)) {
618
		$first_port = 0;
619
	}
620
	if (empty($value) || !is_numeric($value) || $value < $first_port || ($value > 65535)) {
621
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from %s to 65535."), $name, $first_port);
622
	}
623
	return false;
624
}
625

    
626
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4", $alias = false) {
627
	$value = trim($value);
628
	$error = false;
629
	if (empty($value)) {
630
		return false;
631
	}
632
	$networks = explode(',', $value);
633

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

    
638
	foreach ($networks as $network) {
639
		if ($ipproto == "ipv4") {
640
			$error = !openvpn_validate_cidr_ipv4($network, $alias);
641
		} else {
642
			$error = !openvpn_validate_cidr_ipv6($network, $alias);
643
		}
644
		if ($error) {
645
			break;
646
		}
647
	}
648

    
649
	if ($error) {
650
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) separated by commas."), $name, $ipproto);
651
	} else {
652
		return false;
653
	}
654
}
655

    
656
function openvpn_validate_cidr_ipv4($value, $alias = false) {
657
	$value = trim($value);
658
	if (!empty($value)) {
659
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
660
			foreach (alias_to_subnets_recursive($value) as $net) {
661
				if (!is_subnetv4($net)) {
662
					return false;
663
				}
664
			}
665
			return true;
666
		} else {
667
			if (!is_subnetv4($value)) {
668
				return false;
669
			}
670
		}
671
	}
672
	return true;
673
}
674

    
675
function openvpn_validate_cidr_ipv6($value, $alias = false) {
676
	$value = trim($value);
677
	if (!empty($value)) {
678
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
679
			foreach (alias_to_subnets_recursive($value) as $net) {
680
				if (!is_subnetv6($net)) {
681
					return false;
682
				}
683
			}
684
			return true;
685
		} else {
686
			list($ipv6, $prefix) = explode('/', $value);
687
			if (empty($prefix)) {
688
				$prefix = "128";
689
			}
690
			if (!is_subnetv6($ipv6 . '/' . $prefix)) {
691
				return false;
692
			}
693
		}
694
	}
695
	return true;
696
}
697

    
698
function openvpn_validate_tunnel_network($value, $ipproto) {
699
	$value = trim($value);
700
	if (!empty($value)) {
701
		if (is_alias($value) && (alias_get_type($value) == 'network')) {
702
			$net = alias_to_subnets_recursive($value);
703
			if ((!is_subnetv4($net[0]) && ($ipproto == 'ipv4')) ||
704
			    (!is_subnetv6($net[0]) && ($ipproto == 'ipv6')) ||
705
			    (count($net) > 1)) {
706
				return false;
707
			}
708
			return true;
709
		} else {
710
			if ((!is_subnetv4($value) && ($ipproto == 'ipv4')) ||
711
			    (!is_subnetv6($value) && ($ipproto == 'ipv6'))) { 
712
				return false;
713
			}
714
		}
715
	}
716
	return true;
717
}
718

    
719
function openvpn_gen_tunnel_network($tunnel_network) {
720
	if (is_alias($tunnel_network)) {
721
		$net = alias_to_subnets_recursive($tunnel_network);
722
		$pair = $net[0];
723
	} else {
724
		$pair = $tunnel_network;
725
	}
726
	return explode('/', trim($pair));
727
}
728

    
729
function openvpn_add_dhcpopts(& $settings, & $conf) {
730

    
731
	if (!empty($settings['dns_domain'])) {
732
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
733
	}
734

    
735
	if (!empty($settings['dns_server1'])) {
736
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
737
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
738
	}
739
	if (!empty($settings['dns_server2'])) {
740
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
741
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
742
	}
743
	if (!empty($settings['dns_server3'])) {
744
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
745
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
746
	}
747
	if (!empty($settings['dns_server4'])) {
748
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
749
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
750
	}
751

    
752
	if (!empty($settings['push_blockoutsidedns'])) {
753
		$conf .= "push \"block-outside-dns\"\n";
754
	}
755
	if (!empty($settings['push_register_dns'])) {
756
		$conf .= "push \"register-dns\"\n";
757
	}
758

    
759
	if (!empty($settings['ntp_server1'])) {
760
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
761
	}
762
	if (!empty($settings['ntp_server2'])) {
763
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
764
	}
765

    
766
	if ($settings['netbios_enable']) {
767

    
768
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
769
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
770
		}
771
		if (!empty($settings['dhcp_nbtscope'])) {
772
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
773
		}
774

    
775
		if (!empty($settings['wins_server1'])) {
776
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
777
		}
778
		if (!empty($settings['wins_server2'])) {
779
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
780
		}
781

    
782
		if (!empty($settings['nbdd_server1'])) {
783
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
784
		}
785
	}
786

    
787
	if ($settings['gwredir']) {
788
		$conf .= "push \"redirect-gateway def1\"\n";
789
	}
790
	if ($settings['gwredir6']) {
791
		$conf .= "push \"redirect-gateway ipv6\"\n";
792
	}
793
}
794

    
795
function openvpn_add_custom(& $settings, & $conf) {
796

    
797
	if ($settings['custom_options']) {
798

    
799
		$options = explode(';', $settings['custom_options']);
800

    
801
		if (is_array($options)) {
802
			foreach ($options as $option) {
803
				$conf .= "$option\n";
804
			}
805
		} else {
806
			$conf .= "{$settings['custom_options']}\n";
807
		}
808
	}
809
}
810

    
811
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
812
	global $g;
813

    
814
	$fpath = "{$g['openvpn_base']}/{$mode_id}/{$directive}";
815
	openvpn_create_dirs();
816
	file_put_contents($fpath, base64_decode($data));
817
	//chown($fpath, 'nobody');
818
	//chgrp($fpath, 'nobody');
819
	@chmod($fpath, 0600);
820

    
821
	$conf .= "{$directive} {$fpath} {$opt}\n";
822
}
823

    
824
function openvpn_reconfigure($mode, $settings) {
825
	global $g, $config, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
826

    
827
	if (empty($settings)) {
828
		return;
829
	}
830
	if (isset($settings['disable'])) {
831
		return;
832
	}
833
	openvpn_create_dirs();
834
	/*
835
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
836
	 * we use a vpnid number which is allocated for a particular client
837
	 * or server configuration. ( see openvpn_vpnid_next() )
838
	 */
839

    
840
	$vpnid = $settings['vpnid'];
841
	$mode_id = $mode.$vpnid;
842

    
843
	if (isset($settings['dev_mode'])) {
844
		$tunname = "{$settings['dev_mode']}{$vpnid}";
845
	} else {
846
		/* defaults to tun */
847
		$tunname = "tun{$vpnid}";
848
		$settings['dev_mode'] = "tun";
849
	}
850

    
851
	if ($mode == "server") {
852
		$devname = "ovpns{$vpnid}";
853
	} else {
854
		$devname = "ovpnc{$vpnid}";
855
	}
856

    
857
	/* is our device already configured */
858
	if (!does_interface_exist($devname)) {
859

    
860
		/* create the tap device if required */
861
		if (!file_exists("/dev/{$tunname}")) {
862
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
863
		}
864

    
865
		/* rename the device */
866
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
867

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

    
871
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
872
		$grouptmp = link_interface_to_group($ifname);
873
		if (!empty($grouptmp)) {
874
			array_walk($grouptmp, 'interface_group_add_member');
875
		}
876
		unset($grouptmp, $ifname);
877
	}
878

    
879
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
880
	$proto = strtolower($settings['protocol']);
881
	if (substr($settings['protocol'], 0, 3) == "TCP") {
882
			$proto = "{$proto}-{$mode}";
883
	}
884
	$dev_mode = $settings['dev_mode'];
885
	$fbcipher = $settings['data_ciphers_fallback'];
886
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
887
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
888

    
889
	$interface = get_failover_interface($settings['interface']);
890
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
891
	$ipaddr = $settings['ipaddr'];
892

    
893
	// If a specific ip address (VIP) is requested, use it.
894
	// Otherwise, if a specific interface is requested, use it
895
	// If "any" interface was selected, local directive will be omitted.
896
	if (is_ipaddrv4($ipaddr)) {
897
		$iface_ip = $ipaddr;
898
	} elseif (!empty($interface) && strcmp($interface, "any")) {
899
		$iface_ip=get_interface_ip($interface);
900
	}
901
	if (is_ipaddrv6($ipaddr)) {
902
		$iface_ipv6 = $ipaddr;
903
	} elseif (!empty($interface) && strcmp($interface, "any")) {
904
		/* get correct interface name for 6RD/6to4 interfaces
905
		 * see https://redmine.pfsense.org/issues/11674 */
906
		if (is_stf_interface($settings['interface'])) {
907
			$iface_ipv6=get_interface_ipv6($settings['interface']);
908
		} else {
909
			$iface_ipv6=get_interface_ipv6($interface);
910
		}
911
	}
912

    
913
	$conf = "dev {$devname}\n";
914
	if (isset($settings['verbosity_level'])) {
915
		$conf .= "verb {$settings['verbosity_level']}\n";
916
	}
917

    
918
	$conf .= "dev-type {$settings['dev_mode']}\n";
919
	$conf .= "dev-node /dev/{$tunname}\n";
920
	$conf .= "writepid {$pfile}\n";
921
	$conf .= "#user nobody\n";
922
	$conf .= "#group nobody\n";
923
	$conf .= "script-security 3\n";
924
	$conf .= "daemon\n";
925

    
926
	if (!empty($settings['ping_method']) &&
927
	    $settings['ping_method'] == 'ping') {
928
		$conf .= "ping {$settings['ping_seconds']}\n";
929

    
930
		if (!empty($settings['ping_push'])) {
931
			$conf .= "push \"ping {$settings['ping_seconds']}\"\n";
932
		}
933

    
934
		$action = str_replace("_", "-", $settings['ping_action']);
935
		$conf .= "{$action} {$settings['ping_action_seconds']}\n";
936

    
937
		if (!empty($settings['ping_action_push'])) {
938
			$conf .= "push \"{$action} " .
939
			    "{$settings['ping_action_seconds']}\"\n";
940
		}
941
	} else {
942
		$conf .= "keepalive " .
943
		    ($settings['keepalive_interval']
944
			?: $openvpn_default_keepalive_interval) . " " .
945
		    ($settings['keepalive_timeout']
946
			?: $openvpn_default_keepalive_timeout) . "\n";
947
	}
948

    
949
	$conf .= "ping-timer-rem\n";
950
	$conf .= "persist-tun\n";
951
	$conf .= "persist-key\n";
952
	$conf .= "proto {$proto}\n";
953
	$conf .= "auth {$digest}\n";
954
	if ($settings['dns_add']) {
955
		$conf .= "up /usr/local/sbin/ovpn-dnslinkup\n";
956
	} else {
957
		$conf .= "up /usr/local/sbin/ovpn-linkup\n";
958
	}
959
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
960
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
961
		switch ($settings['mode']) {
962
			case 'server_user':
963
			case 'server_tls_user':
964
			case 'server_tls':
965
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
966
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
967
				break;
968
		}
969
	}
970
	if ($settings['dev_mode'] === 'tun' && isset($config['unbound']['enable']) && isset($config['unbound']['regovpnclients'])) {
971
		if (($settings['mode'] == 'server_tls') || ($settings['mode'] == 'server_tls_user') ||
972
		    (($settings['mode'] == 'server_user') && ($settings['username_as_common_name'] == 'enabled'))) {
973
			$domain = !empty($settings['dns_domain']) ? $settings['dns_domain'] : $config['system']['domain'];
974
			if (is_domain($domain)) {
975
				$conf .= "learn-address \"/usr/local/sbin/openvpn.learn-address.sh $domain\"\n";
976
			}
977
		}
978
	}
979

    
980
	/*
981
	 * When binding specific address, wait cases where interface is in
982
	 * tentative state otherwise it will fail
983
	 */
984
	$wait_tentative = false;
985

    
986
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
987
	switch ($settings['protocol']) {
988
		case 'UDP':
989
		case 'TCP':
990
			$conf .= "multihome\n";
991
			break;
992
		case 'UDP4':
993
		case 'TCP4':
994
			if (is_ipaddrv4($iface_ip)) {
995
				$conf .= "local {$iface_ip}\n";
996
			}
997
			if ($settings['interface'] == "any") {
998
				$conf .= "multihome\n";
999
			}
1000
			break;
1001
		case 'UDP6':
1002
		case 'TCP6':
1003
			if (is_ipaddrv6($iface_ipv6)) {
1004
				$conf .= "local {$iface_ipv6}\n";
1005
				$wait_tentative = true;
1006
			}
1007
			if ($settings['interface'] == "any") {
1008
				$conf .= "multihome\n";
1009
			}
1010
			break;
1011
		default:
1012
	}
1013

    
1014
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
1015
		$conf .= "engine {$settings['engine']}\n";
1016
	}
1017

    
1018
	// server specific settings
1019
	if ($mode == 'server') {
1020

    
1021
		list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1022
		list($ipv6, $prefix) = openvpn_gen_tunnel_network($settings['tunnel_networkv6']);
1023
		$mask = gen_subnet_mask($cidr);
1024

    
1025
		// configure tls modes
1026
		switch ($settings['mode']) {
1027
			case 'p2p_tls':
1028
			case 'server_tls':
1029
			case 'server_user':
1030
			case 'server_tls_user':
1031
				$conf .= "tls-server\n";
1032
				break;
1033
		}
1034

    
1035
		// configure p2p/server modes
1036
		switch ($settings['mode']) {
1037
			case 'p2p_tls':
1038
				// If the CIDR is less than a /30, OpenVPN will complain if you try to
1039
				//  use the server directive. It works for a single client without it.
1040
				//  See ticket #1417
1041
				if ((!empty($ip) && !empty($mask)) ||
1042
				    (!empty($ipv6) && !empty($prefix))) {
1043
					$add_ccd = false;
1044
					if (is_ipaddr($ip) && ($cidr < 30)) {
1045
						$add_ccd = true;
1046
						$conf .= "server {$ip} {$mask}\n";
1047
					}
1048
					if (is_ipaddr($ipv6)) {
1049
						$add_ccd = true;
1050
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
1051
					}
1052
					if ($add_ccd) {
1053
						$conf .= "client-config-dir {$g['openvpn_base']}/server{$vpnid}/csc\n";
1054
					}
1055
				}
1056
			case 'p2p_shared_key':
1057
				if (!empty($ip) && !empty($mask)) {
1058
					list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1059
					if ($settings['dev_mode'] == 'tun') {
1060
						$conf .= "ifconfig {$ip1} {$ip2}\n";
1061
					} else {
1062
						$conf .= "ifconfig {$ip1} {$mask}\n";
1063
					}
1064
				}
1065
				if (!empty($ipv6) && !empty($prefix)) {
1066
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1067
					if ($settings['dev_mode'] == 'tun') {
1068
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$ipv6_2}\n";
1069
					} else {
1070
						$conf .= "ifconfig-ipv6 {$ipv6_1}/{$prefix} {$ipv6_2}\n";
1071
					}
1072
				}
1073
				break;
1074
			case 'server_tls':
1075
			case 'server_user':
1076
			case 'server_tls_user':
1077
				if ((!empty($ip) && !empty($mask)) ||
1078
				    (!empty($ipv6) && !empty($prefix))) {
1079
					if (is_ipaddr($ip)) {
1080
						$conf .= "server {$ip} {$mask}\n";
1081
					}
1082
					if (is_ipaddr($ipv6)) {
1083
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
1084
					}
1085
					$conf .= "client-config-dir {$g['openvpn_base']}/server{$vpnid}/csc\n";
1086
				} else {
1087
					if ($settings['serverbridge_dhcp']) {
1088
						if ((!empty($settings['serverbridge_interface'])) && (strcmp($settings['serverbridge_interface'], "none"))) {
1089
							$biface_ip=get_interface_ip($settings['serverbridge_interface']);
1090
							$biface_sm=gen_subnet_mask(get_interface_subnet($settings['serverbridge_interface']));
1091
							if (is_ipaddrv4($biface_ip) && is_ipaddrv4($settings['serverbridge_dhcp_start']) && is_ipaddrv4($settings['serverbridge_dhcp_end'])) {
1092
								$conf .= "server-bridge {$biface_ip} {$biface_sm} {$settings['serverbridge_dhcp_start']} {$settings['serverbridge_dhcp_end']}\n";
1093
								$conf .= "client-config-dir {$g['openvpn_base']}/server{$vpnid}/csc\n";
1094
							} else {
1095
								$conf .= "mode server\n";
1096
							}
1097
							if (!empty($settings['serverbridge_routegateway']) && is_ipaddrv4($biface_ip)) {
1098
								$conf .= "push \"route-gateway {$biface_ip}\"\n";
1099
							}
1100
							/* OpenVPN doesn't support this yet, clients do not recognize the option fully.
1101
							$biface_ip6=get_interface_ipv6($settings['serverbridge_interface']);
1102
							if (!empty($settings['serverbridge_routegateway']) && is_ipaddrv6($biface_ip6)) {
1103
								$conf .= "push \"route-ipv6-gateway {$biface_ip6}\"\n";
1104
							}
1105
							*/
1106
						} else {
1107
							$conf .= "mode server\n";
1108
						}
1109
					}
1110
				}
1111
				break;
1112
		}
1113

    
1114
		// configure user auth modes
1115
		switch ($settings['mode']) {
1116
			case 'server_user':
1117
				$conf .= "verify-client-cert none\n";
1118
			case 'server_tls_user':
1119
				/* username-as-common-name is not compatible with server-bridge */
1120
				if ((stristr($conf, "server-bridge") === false) &&
1121
				    ($settings['username_as_common_name'] != 'disabled')) {
1122
					$conf .= "username-as-common-name\n";
1123
				}
1124
				if (!empty($settings['authmode'])) {
1125
					$strictusercn = "false";
1126
					if ($settings['strictusercn']) {
1127
						$strictusercn = "true";
1128
					}
1129
					$conf .= openvpn_authscript_string($settings['authmode'], $strictusercn, $mode_id, $settings['local_port']);
1130
				}
1131
				break;
1132
		}
1133
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
1134
			$settings['cert_depth'] = 1;
1135
		}
1136
		if (is_numeric($settings['cert_depth'])) {
1137
			if (($mode == 'client') && empty($settings['certref'])) {
1138
				$cert = "";
1139
			} else {
1140
				$cert = lookup_cert($settings['certref']);
1141
				/* XXX: Seems not used at all! */
1142
				$servercn = urlencode(cert_get_cn($cert['crt']));
1143
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
1144
			}
1145
		}
1146

    
1147
		// The local port to listen on
1148
		$conf .= "lport {$settings['local_port']}\n";
1149

    
1150
		// The management port to listen on
1151
		// Use unix socket to overcome the problem on any type of server
1152
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1153
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
1154

    
1155
		if ($settings['maxclients']) {
1156
			$conf .= "max-clients {$settings['maxclients']}\n";
1157
		}
1158

    
1159
		// Can we push routes, and should we?
1160
		if ($settings['local_network'] && !$settings['gwredir']) {
1161
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1162
		}
1163
		if ($settings['local_networkv6'] && !$settings['gwredir6']) {
1164
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1165
		}
1166

    
1167
		switch ($settings['mode']) {
1168
			case 'server_tls':
1169
			case 'server_user':
1170
			case 'server_tls_user':
1171
				// Configure client dhcp options
1172
				openvpn_add_dhcpopts($settings, $conf);
1173
				if ($settings['client2client']) {
1174
					$conf .= "client-to-client\n";
1175
				}
1176
				break;
1177
		}
1178
		if ($settings['mode'] != 'p2p_shared_key' &&
1179
		    isset($settings['duplicate_cn'])) {
1180
			$conf .= "duplicate-cn\n";
1181
		}
1182
		if (($settings['mode'] != 'p2p_shared_key') &&
1183
		    isset($settings['remote_cert_tls'])) {
1184
			$conf .= "remote-cert-tls client\n";
1185
		}
1186
	}
1187

    
1188
	// client specific settings
1189

    
1190
	if ($mode == 'client') {
1191

    
1192
		// configure p2p mode
1193
		switch ($settings['mode']) {
1194
			case 'p2p_tls':
1195
				$conf .= "tls-client\n";
1196
			case 'shared_key':
1197
				$conf .= "client\n";
1198
				break;
1199
		}
1200

    
1201
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1202
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1203
		//  ensure a random source port.
1204
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1205
			$conf .= "nobind\n";
1206
		} elseif ($settings['local_port']) {
1207
			$conf .= "lport {$settings['local_port']}\n";
1208
		} else {
1209
			$conf .= "lport 0\n";
1210
		}
1211

    
1212
		// Use unix socket to overcome the problem on any type of server
1213
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1214

    
1215
		// The remote server
1216
		$remoteproto = strtolower($settings['protocol']);
1217
		if (substr($remoteproto, 0, 3) == "tcp") {
1218
			$remoteproto .= "-{$mode}";
1219
		}
1220
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']} {$remoteproto}\n";
1221

    
1222
		if (!empty($settings['use_shaper'])) {
1223
			$conf .= "shaper {$settings['use_shaper']}\n";
1224
		}
1225

    
1226
		if (!empty($settings['tunnel_network'])) {
1227
			list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1228
			$mask = gen_subnet_mask($cidr);
1229
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1230
			if ($settings['dev_mode'] == 'tun') {
1231
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1232
			} else {
1233
				$conf .= "ifconfig {$ip2} {$mask}\n";
1234
			}
1235
		}
1236

    
1237
		if (!empty($settings['tunnel_networkv6'])) {
1238
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1239
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1240
			if ($settings['dev_mode'] == 'tun') {
1241
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1242
			} else {
1243
				$conf .= "ifconfig-ipv6 {$ipv6_1}/{$prefix} {$ipv6_2}\n";
1244
			}
1245
		}
1246

    
1247
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
1248
			$up_file = "{$g['openvpn_base']}/{$mode_id}/up";
1249
			$conf .= "auth-user-pass {$up_file}\n";
1250
			if (!$settings['auth-retry-none']) {
1251
				$conf .= "auth-retry nointeract\n";
1252
			}
1253
			if ($settings['auth_user']) {
1254
				$userpass = "{$settings['auth_user']}\n";
1255
			} else {
1256
				$userpass = "";
1257
			}
1258
			if ($settings['auth_pass']) {
1259
				$userpass .= "{$settings['auth_pass']}\n";
1260
			}
1261
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
1262
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
1263
				$userpass .= "\n";
1264
			}
1265
			file_put_contents($up_file, $userpass);
1266
		}
1267

    
1268
		if ($settings['proxy_addr']) {
1269
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1270
			if ($settings['proxy_authtype'] != "none") {
1271
				$conf .= " {$g['openvpn_base']}/{$mode_id}/proxy_auth {$settings['proxy_authtype']}";
1272
				$proxypas = "{$settings['proxy_user']}\n";
1273
				$proxypas .= "{$settings['proxy_passwd']}\n";
1274
				file_put_contents("{$g['openvpn_base']}/{$mode_id}/proxy_auth", $proxypas);
1275
			}
1276
			$conf .= " \n";
1277
		}
1278

    
1279
		if (($settings['mode'] != 'shared_key') &&
1280
		    isset($settings['remote_cert_tls'])) {
1281
			$conf .= "remote-cert-tls server\n";
1282
		}
1283
	}
1284

    
1285
	// Add a remote network route if set, and only for p2p modes.
1286
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4", true) === FALSE)) {
1287
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1288
	}
1289
	// Add a remote network route if set, and only for p2p modes.
1290
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6", true) === FALSE)) {
1291
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1292
	}
1293

    
1294
	// Write the settings for the keys
1295
	switch ($settings['mode']) {
1296
		case 'p2p_shared_key':
1297
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
1298
			break;
1299
		case 'p2p_tls':
1300
		case 'server_tls':
1301
		case 'server_tls_user':
1302
		case 'server_user':
1303
			// ca_chain_array() expects parameter to be passed by reference.
1304
			// avoid passing the whole settings array, as param names or
1305
			// types might change in future releases.
1306
			$param = array('caref' => $settings['caref']);
1307
			$cas = ca_chain_array($param);
1308
			$capath = "{$g['openvpn_base']}/{$mode_id}/ca";
1309
			/* Cleanup old CA/CRL references */
1310
			@unlink_if_exists("{$capath}/*.0");
1311
			@unlink_if_exists("{$capath}/*.r*");
1312
			/* Find the CRL listed in the settings */
1313
			if (!empty($settings['crlref'])) {
1314
				$crl = lookup_crl($settings['crlref']);
1315
				crl_update($crl);
1316
			}
1317
			/* For each CA in the chain, setup the CApath */
1318
			foreach ($cas as $ca) {
1319
				ca_setup_capath($ca, $capath, $crl);
1320
			}
1321
			$conf .= "capath {$capath}\n";
1322
			unset($cas, $param);
1323

    
1324
			if (!empty($settings['certref'])) {
1325
				$cert = lookup_cert($settings['certref']);
1326
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
1327
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
1328
			}
1329
			if ($mode == 'server') {
1330
				if (is_numeric($settings['dh_length'])) {
1331
					if (!in_array($settings['dh_length'], array_keys($openvpn_dh_lengths))) {
1332
						/* The user selected a DH parameter length that does not have a corresponding file. */
1333
						log_error(gettext("Failed to construct OpenVPN server configuration. The selected DH Parameter length cannot be used."));
1334
						return;
1335
					}
1336
					$dh_file = "{$g['etc_path']}/dh-parameters.{$settings['dh_length']}";
1337
				} else {
1338
					$dh_file = $settings['dh_length'];
1339
				}
1340
				$conf .= "dh {$dh_file}\n";
1341
				if (!empty($settings['ecdh_curve']) && ($settings['ecdh_curve'] != "none") && openvpn_validate_curve($settings['ecdh_curve'])) {
1342
					$conf .= "ecdh-curve {$settings['ecdh_curve']}\n";
1343
				}
1344
			}
1345
			if ($settings['tls']) {
1346
				if ($settings['tls_type'] == "crypt") {
1347
					$tls_directive = "tls-crypt";
1348
					$tlsopt = "";
1349
				} else {
1350
					$tls_directive = "tls-auth";
1351
					if ($mode == "server") {
1352
						switch($settings['tlsauth_keydir']){
1353
							case '1':
1354
								$tlsopt = 1;
1355
								break;
1356
							case '2':
1357
								$tlsopt = '';
1358
								break;
1359
							default:
1360
								$tlsopt = 0;
1361
								break;
1362
						}
1363
					} else {
1364
						switch($settings['tlsauth_keydir']){
1365
							case '0':
1366
								$tlsopt = 0;
1367
								break;
1368
							case '2':
1369
								$tlsopt = '';
1370
								break;
1371
							default:
1372
								$tlsopt = 1;
1373
								break;
1374
						}
1375
					}
1376
				}
1377
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, $tls_directive, $tlsopt);
1378
			}
1379
			break;
1380
	}
1381

    
1382
	/* Data encryption cipher support.
1383
	 * If it is not set, assume enabled since that is OpenVPN's default.
1384
	 * Note that diabling this is now deprecated and will be removed in a future version of OpenVPN */
1385
	if (($settings['ncp_enable'] == "disabled") ||
1386
	    ($settings['mode'] == "p2p_shared_key")) {
1387
		if ($settings['mode'] != "p2p_shared_key") {
1388
			/* Do not include this option for shared key as it is redundant. */
1389
			$conf .= "ncp-disable\n";
1390
		}
1391
		$conf .= "cipher {$fbcipher}\n";
1392
	} else {
1393
		$conf .= "data-ciphers " . str_replace(',', ':', openvpn_build_data_cipher_list($settings['data_ciphers'], $fbcipher)) . "\n";
1394
		$conf .= "data-ciphers-fallback {$fbcipher}\n";
1395
	}
1396

    
1397
	if (!empty($settings['allow_compression'])) {
1398
		$conf .= "allow-compression {$settings['allow_compression']}\n";
1399
	}
1400

    
1401
	$compression = "";
1402
	switch ($settings['compression']) {
1403
		case 'none':
1404
			$settings['compression'] = '';
1405
		case 'lz4':
1406
		case 'lz4-v2':
1407
		case 'lzo':
1408
		case 'stub':
1409
		case 'stub-v2':
1410
			$compression .= "compress {$settings['compression']}";
1411
			break;
1412
		case 'noadapt':
1413
			$compression .= "comp-noadapt";
1414
			break;
1415
		case 'adaptive':
1416
		case 'yes':
1417
		case 'no':
1418
			$compression .= "comp-lzo {$settings['compression']}";
1419
			break;
1420
		default:
1421
			/* Add nothing to the configuration */
1422
			break;
1423
	}
1424

    
1425
	if (($settings['allow_compression'] != 'no') &&
1426
	    !empty($compression)) {
1427
		$conf .= "{$compression}\n";
1428
		if ($settings['compression_push']) {
1429
			$conf .= "push \"{$compression}\"\n";
1430
		}
1431
	}
1432

    
1433
	if ($settings['passtos']) {
1434
		$conf .= "passtos\n";
1435
	}
1436

    
1437
	if ($mode == 'client') {
1438
		$conf .= "resolv-retry infinite\n";
1439
	}
1440

    
1441
	if ($settings['dynamic_ip']) {
1442
		$conf .= "persist-remote-ip\n";
1443
		$conf .= "float\n";
1444
	}
1445

    
1446
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1447
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1448
		if (empty($settings['topology'])) {
1449
			$settings['topology'] = "subnet";
1450
		}
1451
		$conf .= "topology {$settings['topology']}\n";
1452
	}
1453

    
1454
	// New client features
1455
	if ($mode == "client") {
1456
		// Dont add/remove routes checkbox
1457
		if ($settings['route_no_exec']) {
1458
			$conf .= "route-noexec\n";
1459
		}
1460
	}
1461

    
1462
	/* UDP Fast I/O. Only compatible with UDP and also not compatible with OpenVPN's "shaper" directive. */
1463
	if ($settings['udp_fast_io']
1464
	    && (strtolower(substr($settings['protocol'], 0, 3)) == "udp")
1465
	    && (empty($settings['use_shaper']))) {
1466
		$conf .= "fast-io\n";
1467
	}
1468

    
1469
	/* Exit Notify.
1470
	 * Only compatible with UDP and specific combinations of
1471
	 * modes and settings, including:
1472
	 * if type is server AND
1473
	 *	mode is not shared key AND
1474
	 *		tunnel network CIDR mask < 30 AND
1475
	 *		tunnel network is not blank
1476
	 * if type is client AND
1477
	 *	mode is not shared key AND
1478
	 *		tunnel network is blank OR
1479
	 *		tunnel network CIDR mask < 30
1480
	 */
1481
	list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1482
	if ((!empty($settings['exit_notify']) &&
1483
	    is_numericint($settings['exit_notify']) &&
1484
	    (strtolower(substr($settings['protocol'], 0, 3)) == "udp")) &&
1485
	    ((($mode == "server") && (($settings['mode'] != 'p2p_shared_key') && (($cidr < 30) && !empty($ip)))) ||
1486
	    (($mode == "client") && (($settings['mode'] != 'p2p_shared_key') && (($cidr < 30) || empty($ip)))))) {
1487
		$conf .= "explicit-exit-notify {$settings['exit_notify']}\n";
1488
	}
1489

    
1490
	/* Inactive Seconds
1491
	 * Has similar restrictions to Exit Notify (above) but only for server mode.
1492
	 */
1493
	if (!empty($settings['inactive_seconds']) &&
1494
	    !(($mode == "server") && (($settings['mode'] == 'p2p_shared_key') || (($cidr >= 30) || empty($ip))))) {
1495
		$conf .= "inactive {$settings['inactive_seconds']}\n";
1496
	}
1497

    
1498
	/* Send and Receive Buffer Settings */
1499
	if (is_numericint($settings['sndrcvbuf'])
1500
	    && ($settings['sndrcvbuf'] > 0)
1501
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1502
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1503
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1504
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1505
	}
1506

    
1507
	openvpn_add_custom($settings, $conf);
1508

    
1509
	/* add nopull option after custom options, see https://redmine.pfsense.org/issues/11448 */
1510
	if (($mode == "client") && $settings['route_no_pull']) {
1511
		// Dont pull routes checkbox
1512
		$conf .= "route-nopull\n";
1513
	}
1514

    
1515
	openvpn_create_dirs();
1516
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1517
	file_put_contents($fpath, $conf);
1518
	unset($conf);
1519
	$fpath = "{$g['openvpn_base']}/{$mode_id}/interface";
1520
	file_put_contents($fpath, $interface);
1521
	//chown($fpath, 'nobody');
1522
	//chgrp($fpath, 'nobody');
1523
	@chmod("{$g['openvpn_base']}/{$mode_id}/config.ovpn", 0600);
1524
	@chmod("{$g['openvpn_base']}/{$mode_id}/interface", 0600);
1525
	@chmod("{$g['openvpn_base']}/{$mode_id}/key", 0600);
1526
	@chmod("{$g['openvpn_base']}/{$mode_id}/tls-auth", 0600);
1527
	@chmod("{$g['openvpn_base']}/{$mode_id}/conf", 0600);
1528

    
1529
	if ($wait_tentative) {
1530
		interface_wait_tentative($interface);
1531
	}
1532
}
1533

    
1534
function openvpn_restart($mode, $settings) {
1535
	global $g, $config;
1536

    
1537
	$vpnid = $settings['vpnid'];
1538
	$mode_id = $mode.$vpnid;
1539
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1540
	openvpn_clean_rules($mode, $vpnid);
1541
	openvpn_reconfigure($mode, $settings);
1542
	/* kill the process if running */
1543
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1544
	if (file_exists($pfile)) {
1545

    
1546
		/* read the pid file */
1547
		$pid = rtrim(file_get_contents($pfile));
1548
		unlink($pfile);
1549
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1550

    
1551
		/* send a term signal to the process */
1552
		posix_kill($pid, SIGTERM);
1553

    
1554
		/* wait until the process exits, or timeout and kill it */
1555
		$i = 0;
1556
		while (posix_kill($pid, 0)) {
1557
			usleep(250000);
1558
			if ($i > 10) {
1559
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1560
				posix_kill($pid, SIGKILL);
1561
				usleep(500000);
1562
			}
1563
			$i++;
1564
		}
1565
	}
1566

    
1567
	if (isset($settings['disable'])) {
1568
		openvpn_delete($mode, $settings);
1569
		unlock($lockhandle);
1570
		return;
1571
	}
1572

    
1573
	/* Do not start an instance if we are not CARP master on this vip! */
1574
	if (strstr($settings['interface'], "_vip")) {
1575
	       	$carpstatus = get_carp_bind_status($settings['interface']);
1576
		/* Do not start an instance if vip aliased to BACKUP CARP
1577
		 * see https://redmine.pfsense.org/issues/11793 */ 
1578
		if (in_array($carpstatus, array('BACKUP', 'INIT'))) {
1579
			unlock($lockhandle);
1580
			return;
1581
		} 
1582
	}
1583

    
1584
	/* Check if client is bound to a gateway group */
1585
	$a_groups = return_gateway_groups_array(true);
1586
	if (is_array($a_groups[$settings['interface']])) {
1587
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1588
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1589
			unlock($lockhandle);
1590
			return;
1591
		}
1592
	}
1593

    
1594
	/* start the new process */
1595
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1596
	openvpn_clear_route($mode, $settings);
1597
	$res = mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1598
	if ($res == 0) {
1599
		$i = 0;
1600
		$pid = "--";
1601
		while ($i < 3000) {
1602
			if (isvalidpid($pfile)) {
1603
				$pid = rtrim(file_get_contents($pfile));
1604
				break;
1605
			}
1606
			usleep(1000);
1607
			$i++;
1608
		}
1609
		syslog(LOG_INFO, "OpenVPN PID written: {$pid}");
1610
	} else {
1611
		syslog(LOG_ERR, "OpenVPN failed to start");
1612
	}
1613
	if (!platform_booting()) {
1614
		send_event("filter reload");
1615
	}
1616
	unlock($lockhandle);
1617
}
1618

    
1619
function openvpn_delete($mode, $settings) {
1620
	global $g, $config;
1621

    
1622
	$vpnid = $settings['vpnid'];
1623
	$mode_id = $mode.$vpnid;
1624

    
1625
	if ($mode == "server") {
1626
		$devname = "ovpns{$vpnid}";
1627
	} else {
1628
		$devname = "ovpnc{$vpnid}";
1629
	}
1630

    
1631
	/* kill the process if running */
1632
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1633
	if (file_exists($pfile)) {
1634

    
1635
		/* read the pid file */
1636
		$pid = trim(file_get_contents($pfile));
1637
		unlink($pfile);
1638

    
1639
		/* send a term signal to the process */
1640
		posix_kill($pid, SIGTERM);
1641
	}
1642

    
1643
	/* destroy the device */
1644
	pfSense_interface_destroy($devname);
1645

    
1646
	/* Invalidate cache */
1647
	get_interface_arr(true);
1648

    
1649
	/* remove the configuration files */
1650
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*/*");
1651
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*");
1652
	openvpn_clean_rules($mode, $vpnid);
1653
}
1654

    
1655
function openvpn_resync_csc(& $settings) {
1656
	global $g, $config, $openvpn_tls_server_modes;
1657
	if (isset($settings['disable'])) {
1658
		openvpn_delete_csc($settings);
1659
		return;
1660
	}
1661
	openvpn_create_dirs();
1662

    
1663
	if (empty($settings['server_list'])) {
1664
		$csc_server_list = array();
1665
	} else {
1666
		$csc_server_list = explode(",", $settings['server_list']);
1667
	}
1668

    
1669
	$conf = '';
1670
	if ($settings['block']) {
1671
		$conf .= "disable\n";
1672
	}
1673

    
1674
	if ($settings['push_reset']) {
1675
		$conf .= "push-reset\n";
1676
	}
1677

    
1678
	if ($settings['remove_route']) {
1679
		$conf .= "push-remove route\n";
1680
	}
1681

    
1682
	if ($settings['local_network']) {
1683
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1684
	}
1685
	if ($settings['local_networkv6']) {
1686
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1687
	}
1688

    
1689
	// Add a remote network iroute if set
1690
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4", true) === FALSE) {
1691
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1692
	}
1693
	// Add a remote network iroute if set
1694
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6", true) === FALSE) {
1695
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1696
	}
1697

    
1698
	openvpn_add_dhcpopts($settings, $conf);
1699

    
1700
	openvpn_add_custom($settings, $conf);
1701
	/* Loop through servers, find which ones can use this CSC */
1702
	if (is_array($config['openvpn']['openvpn-server'])) {
1703
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1704
			if (isset($serversettings['disable'])) {
1705
				continue;
1706
			}
1707
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1708
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1709
					$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1710
					$csc_conf = $conf;
1711

    
1712
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1713
						list($ip, $mask) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1714
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1715
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1716
						} else {
1717
							/* Because this is being pushed, the order from the client's point of view. */
1718
							$baselong = gen_subnetv4($ip, $mask);
1719
							$serverip = ip_after($baselong, 1);
1720
							$clientip = ip_after($baselong, 2);
1721
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1722
						}
1723
					}
1724

    
1725
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1726
						list($ipv6, $prefix) = openvpn_gen_tunnel_network($serversettings['tunnel_networkv6']);
1727
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1728
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1729
					}
1730

    
1731
					file_put_contents($csc_path, $csc_conf);
1732
					chown($csc_path, 'nobody');
1733
					chgrp($csc_path, 'nobody');
1734
				}
1735
			}
1736
		}
1737
	}
1738
}
1739

    
1740
function openvpn_resync_csc_all() {
1741
	global $config;
1742
	if (is_array($config['openvpn']['openvpn-csc'])) {
1743
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1744
			openvpn_resync_csc($settings);
1745
		}
1746
	}
1747
}
1748

    
1749
function openvpn_delete_csc(& $settings) {
1750
	global $g, $config, $openvpn_tls_server_modes;
1751
	if (empty($settings['server_list'])) {
1752
		$csc_server_list = array();
1753
	} else {
1754
		$csc_server_list = explode(",", $settings['server_list']);
1755
	}
1756

    
1757
	/* Loop through servers, find which ones used this CSC */
1758
	if (is_array($config['openvpn']['openvpn-server'])) {
1759
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1760
			if (isset($serversettings['disable'])) {
1761
				continue;
1762
			}
1763
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1764
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1765
					$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1766
					unlink_if_exists($csc_path);
1767
				}
1768
			}
1769
		}
1770
	}
1771
}
1772

    
1773
// Resync the configuration and restart the VPN
1774
function openvpn_resync($mode, $settings) {
1775
	openvpn_restart($mode, $settings);
1776
}
1777

    
1778
// Resync and restart all VPNs
1779
function openvpn_resync_all($interface = "") {
1780
	global $g, $config;
1781

    
1782
	openvpn_create_dirs();
1783

    
1784
	if (!is_array($config['openvpn'])) {
1785
		$config['openvpn'] = array();
1786
	}
1787

    
1788
	if ($interface <> "") {
1789
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1790
	} else {
1791
		log_error(gettext("Resyncing OpenVPN instances."));
1792
	}
1793

    
1794
	// Check if OpenVPN clients and servers require a resync.
1795
	foreach (array("server", "client") as $type) {
1796
		if (!is_array($config['openvpn']["openvpn-{$type}"])) {
1797
			continue;
1798
		}
1799
		foreach ($config['openvpn']["openvpn-{$type}"] as & $settings) {
1800
			$fpath = "{$g['openvpn_base']}/{$type}{$settings['vpnid']}/interface";
1801
			$gw_group_change = FALSE;
1802
			$ip_change = ($interface === "") ||
1803
			    ($interface === $settings['interface']);
1804

    
1805
			if (!$ip_change && file_exists($fpath)) {
1806
				$gw_group_change =
1807
				    (trim(file_get_contents($fpath), " \t\n") !=
1808
				    get_failover_interface(
1809
					$settings['interface']));
1810
			}
1811

    
1812
			if ($ip_change || $gw_group_change) {
1813
				openvpn_resync($type, $settings);
1814
			}
1815
		}
1816
	}
1817

    
1818
	openvpn_resync_csc_all();
1819

    
1820
	/* configure OpenVPN-parent QinQ interfaces after creating OpenVPN interfaces
1821
	 * see https://redmine.pfsense.org/issues/11662 */
1822
	if (platform_booting()) {
1823
		interfaces_qinq_configure(true);
1824
	}
1825
}
1826

    
1827
// Resync and restart all VPNs using a gateway group.
1828
function openvpn_resync_gwgroup($gwgroupname = "") {
1829
	global $g, $config;
1830

    
1831
	if ($gwgroupname <> "") {
1832
		if (is_array($config['openvpn']['openvpn-server'])) {
1833
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1834
				if ($gwgroupname == $settings['interface']) {
1835
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1836
					openvpn_resync('server', $settings);
1837
				}
1838
			}
1839
		}
1840

    
1841
		if (is_array($config['openvpn']['openvpn-client'])) {
1842
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1843
				if ($gwgroupname == $settings['interface']) {
1844
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1845
					openvpn_resync('client', $settings);
1846
				}
1847
			}
1848
		}
1849

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

    
1852
	} else {
1853
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1854
	}
1855
}
1856

    
1857
function openvpn_get_active_servers($type="multipoint") {
1858
	global $config, $g;
1859

    
1860
	$servers = array();
1861
	if (is_array($config['openvpn']['openvpn-server'])) {
1862
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1863
			if (empty($settings) || isset($settings['disable'])) {
1864
				continue;
1865
			}
1866

    
1867
			$prot = $settings['protocol'];
1868
			$port = $settings['local_port'];
1869

    
1870
			$server = array();
1871
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1872
			$server['mode'] = $settings['mode'];
1873
			if ($settings['description']) {
1874
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1875
			} else {
1876
				$server['name'] = "Server {$prot}:{$port}";
1877
			}
1878
			$server['conns'] = array();
1879
			$server['vpnid'] = $settings['vpnid'];
1880
			$server['mgmt'] = "server{$server['vpnid']}";
1881
			$socket = "unix://{$g['openvpn_base']}/{$server['mgmt']}/sock";
1882
			list($tn, $sm) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1883

    
1884
			if ((($server['mode'] == "p2p_shared_key") ||
1885
			    (($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network'])) ||
1886
			    ($sm >= 30)) &&
1887
			    ($type == "p2p")) {
1888
				$servers[] = openvpn_get_client_status($server, $socket);
1889
			} elseif (($server['mode'] != "p2p_shared_key") &&
1890
			    !(($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network'])) &&
1891
			    ($type == "multipoint") &&
1892
			    ($sm < 30)) {
1893
				$servers[] = openvpn_get_server_status($server, $socket);
1894
			}
1895
		}
1896
	}
1897
	return $servers;
1898
}
1899

    
1900
function openvpn_get_server_status($server, $socket) {
1901
	$errval = null;
1902
	$errstr = null;
1903
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1904
	if ($fp) {
1905
		stream_set_timeout($fp, 1);
1906

    
1907
		/* send our status request */
1908
		fputs($fp, "status 2\n");
1909

    
1910
		/* recv all response lines */
1911
		while (!feof($fp)) {
1912

    
1913
			/* read the next line */
1914
			$line = fgets($fp, 1024);
1915

    
1916
			$info = stream_get_meta_data($fp);
1917
			if ($info['timed_out']) {
1918
				break;
1919
			}
1920

    
1921
			/* parse header list line */
1922
			if (strstr($line, "HEADER")) {
1923
				continue;
1924
			}
1925

    
1926
			/* parse end of output line */
1927
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1928
				break;
1929
			}
1930

    
1931
			/* parse client list line */
1932
			if (strstr($line, "CLIENT_LIST")) {
1933
				$list = explode(",", $line);
1934
				$conn = array();
1935
				$conn['common_name'] = $list[1];
1936
				$conn['remote_host'] = $list[2];
1937
				$conn['virtual_addr'] = $list[3];
1938
				$conn['virtual_addr6'] = $list[4];
1939
				$conn['bytes_recv'] = $list[5];
1940
				$conn['bytes_sent'] = $list[6];
1941
				$conn['connect_time'] = $list[7];
1942
				$conn['connect_time_unix'] = $list[8];
1943
				$conn['user_name'] = $list[9];
1944
				$conn['client_id'] = $list[10];
1945
				$conn['peer_id'] = $list[11];
1946
				$conn['cipher'] = $list[12];
1947
				$server['conns'][] = $conn;
1948
			}
1949
			/* parse routing table lines */
1950
			if (strstr($line, "ROUTING_TABLE")) {
1951
				$list = explode(",", $line);
1952
				$conn = array();
1953
				$conn['virtual_addr'] = $list[1];
1954
				$conn['common_name'] = $list[2];
1955
				$conn['remote_host'] = $list[3];
1956
				$conn['last_time'] = $list[4];
1957
				$server['routes'][] = $conn;
1958
			}
1959
		}
1960

    
1961
		/* cleanup */
1962
		fclose($fp);
1963
	} else {
1964
		$conn = array();
1965
		$conn['common_name'] = "[error]";
1966
		$conn['remote_host'] = gettext("Unable to contact daemon");
1967
		$conn['virtual_addr'] = gettext("Service not running?");
1968
		$conn['bytes_recv'] = 0;
1969
		$conn['bytes_sent'] = 0;
1970
		$conn['connect_time'] = 0;
1971
		$server['conns'][] = $conn;
1972
	}
1973
	return $server;
1974
}
1975

    
1976
function openvpn_get_active_clients() {
1977
	global $config, $g;
1978

    
1979
	$clients = array();
1980
	if (is_array($config['openvpn']['openvpn-client'])) {
1981
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1982

    
1983
			if (empty($settings) || isset($settings['disable'])) {
1984
				continue;
1985
			}
1986

    
1987
			$prot = $settings['protocol'];
1988
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1989

    
1990
			$client = array();
1991
			$client['port'] = $settings['local_port'];
1992
			if ($settings['description']) {
1993
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1994
			} else {
1995
				$client['name'] = "Client {$prot}{$port}";
1996
			}
1997

    
1998
			$client['vpnid'] = $settings['vpnid'];
1999
			$client['mgmt'] = "client{$client['vpnid']}";
2000
			$socket = "unix://{$g['openvpn_base']}/{$client['mgmt']}/sock";
2001
			$client['status']="down";
2002

    
2003
			$clients[] = openvpn_get_client_status($client, $socket);
2004
		}
2005
	}
2006
	return $clients;
2007
}
2008

    
2009
function openvpn_get_client_status($client, $socket) {
2010
	$errval = null;
2011
	$errstr = null;
2012
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
2013
	if ($fp) {
2014
		stream_set_timeout($fp, 1);
2015
		/* send our status request */
2016
		fputs($fp, "state 1\n");
2017

    
2018
		/* recv all response lines */
2019
		while (!feof($fp)) {
2020
			/* read the next line */
2021
			$line = fgets($fp, 1024);
2022

    
2023
			$info = stream_get_meta_data($fp);
2024
			if ($info['timed_out']) {
2025
				break;
2026
			}
2027

    
2028
			/* Get the client state */
2029
			if (strstr($line, "CONNECTED")) {
2030
				$client['status'] = "up";
2031
				$list = explode(",", $line);
2032

    
2033
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
2034
				$client['virtual_addr'] = $list[3];
2035
				$client['remote_host'] = $list[4];
2036
				$client['remote_port'] = $list[5];
2037
				$client['local_host'] = $list[6];
2038
				$client['local_port'] = $list[7];
2039
				$client['virtual_addr6'] = $list[8];
2040
			}
2041
			if (strstr($line, "CONNECTING")) {
2042
				$client['status'] = "connecting";
2043
			}
2044
			if (strstr($line, "ASSIGN_IP")) {
2045
				$client['status'] = "waiting";
2046
				$list = explode(",", $line);
2047

    
2048
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
2049
				$client['virtual_addr'] = $list[3];
2050
			}
2051
			if (strstr($line, "RECONNECTING")) {
2052
				$client['status'] = "reconnecting";
2053
				$list = explode(",", $line);
2054

    
2055
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
2056
				$client['status'] .= "; " . $list[2];
2057
			}
2058
			/* parse end of output line */
2059
			if (strstr($line, "END") || strstr($line, "ERROR")) {
2060
				break;
2061
			}
2062
		}
2063

    
2064
		/* If up, get read/write stats */
2065
		if (strcmp($client['status'], "up") == 0) {
2066
			fputs($fp, "status 2\n");
2067
			/* recv all response lines */
2068
			while (!feof($fp)) {
2069
				/* read the next line */
2070
				$line = fgets($fp, 1024);
2071

    
2072
				$info = stream_get_meta_data($fp);
2073
				if ($info['timed_out']) {
2074
					break;
2075
				}
2076

    
2077
				if (strstr($line, "TCP/UDP read bytes")) {
2078
					$list = explode(",", $line);
2079
					$client['bytes_recv'] = $list[1];
2080
				}
2081

    
2082
				if (strstr($line, "TCP/UDP write bytes")) {
2083
					$list = explode(",", $line);
2084
					$client['bytes_sent'] = $list[1];
2085
				}
2086

    
2087
				/* parse end of output line */
2088
				if (strstr($line, "END")) {
2089
					break;
2090
				}
2091
			}
2092
		}
2093

    
2094
		fclose($fp);
2095

    
2096
	} else {
2097
		$client['remote_host'] = gettext("Unable to contact daemon");
2098
		$client['virtual_addr'] = gettext("Service not running?");
2099
		$client['bytes_recv'] = 0;
2100
		$client['bytes_sent'] = 0;
2101
		$client['connect_time'] = 0;
2102
	}
2103
	return $client;
2104
}
2105

    
2106
function openvpn_kill_client($port, $remipp, $client_id) {
2107
	global $g;
2108

    
2109
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
2110
	$tcpsrv = "unix://{$g['openvpn_base']}/{$port}/sock";
2111
	$errval = null;
2112
	$errstr = null;
2113

    
2114
	/* open a tcp connection to the management port of each server */
2115
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
2116
	$killed = -1;
2117
	if ($fp) {
2118
		stream_set_timeout($fp, 1);
2119
		if (is_numeric($client_id)) {
2120
			/* terminate remote client, see https://redmine.pfsense.org/issues/12416 */
2121
			fputs($fp, "client-kill {$client_id} HALT\n");
2122
		} else {
2123
			fputs($fp, "kill {$remipp}\n");
2124
		}
2125
		while (!feof($fp)) {
2126
			$line = fgets($fp, 1024);
2127

    
2128
			$info = stream_get_meta_data($fp);
2129
			if ($info['timed_out']) {
2130
				break;
2131
			}
2132

    
2133
			/* parse header list line */
2134
			if (strpos($line, "INFO:") !== false) {
2135
				continue;
2136
			}
2137
			if (strpos($line, "SUCCESS") !== false) {
2138
				$killed = 0;
2139
			}
2140
			break;
2141
		}
2142
		fclose($fp);
2143
	}
2144
	return $killed;
2145
}
2146

    
2147
function openvpn_refresh_crls() {
2148
	global $g, $config;
2149

    
2150
	openvpn_create_dirs();
2151

    
2152
	if (is_array($config['openvpn']['openvpn-server'])) {
2153
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2154
			if (empty($settings)) {
2155
				continue;
2156
			}
2157
			if (isset($settings['disable'])) {
2158
				continue;
2159
			}
2160
			// Write the settings for the keys
2161
			switch ($settings['mode']) {
2162
				case 'p2p_tls':
2163
				case 'server_tls':
2164
				case 'server_tls_user':
2165
				case 'server_user':
2166
					$param = array('caref' => $settings['caref']);
2167
					$cas = ca_chain_array($param);
2168
					$capath = "{$g['openvpn_base']}/server{$settings['vpnid']}/ca";
2169
					if (!empty($settings['crlref'])) {
2170
						$crl = lookup_crl($settings['crlref']);
2171
						crl_update($crl);
2172
					}
2173
					foreach ($cas as $ca) {
2174
						ca_setup_capath($ca, $capath, $crl, true);
2175
					}
2176
					unset($cas, $param, $capath, $crl);
2177
					break;
2178
			}
2179
		}
2180
	}
2181
}
2182

    
2183
function openvpn_create_dirs() {
2184
	global $g, $config, $openvpn_tls_server_modes;
2185
	if (!is_dir($g['openvpn_base'])) {
2186
		safe_mkdir($g['openvpn_base'], 0750);
2187
	}
2188

    
2189
	init_config_arr(array('openvpn', 'openvpn-server'));
2190
	init_config_arr(array('openvpn', 'openvpn-client'));
2191
	foreach(array('server', 'client') as $mode) {
2192
		foreach ($config['openvpn']["openvpn-{$mode}"] as $settings) {
2193
			$target = "{$g['openvpn_base']}/{$mode}{$settings['vpnid']}";
2194
			@unlink_if_exists($csctarget);
2195
			@safe_mkdir($target);
2196
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2197
				if ($settings['vpnid']) {
2198
					$csctarget = "{$target}/csc/";
2199
					@unlink_if_exists($csctarget);
2200
					@safe_mkdir($csctarget);
2201
				}
2202
			}
2203
		}
2204
	}
2205
}
2206

    
2207
function openvpn_get_interface_ip($ip, $cidr) {
2208
	$subnet = gen_subnetv4($ip, $cidr);
2209
	if ($cidr == 31) {
2210
		$ip1 = $subnet;
2211
	} else {
2212
		$ip1 = ip_after($subnet);
2213
	}
2214
	$ip2 = ip_after($ip1);
2215
	return array($ip1, $ip2);
2216
}
2217

    
2218
function openvpn_get_interface_ipv6($ipv6, $prefix) {
2219
	$basev6 = gen_subnetv6($ipv6, $prefix);
2220
	// Is there a better way to do this math?
2221
	$ipv6_arr = explode(':', $basev6);
2222
	$last = hexdec(array_pop($ipv6_arr));
2223
	if ($prefix == 127) {
2224
		$last--;
2225
	}
2226
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
2227
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
2228
	return array($ipv6_1, $ipv6_2);
2229
}
2230

    
2231
function openvpn_clear_route($mode, $settings) {
2232
	if (empty($settings['tunnel_network'])) {
2233
		return;
2234
	}
2235
	list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
2236
	$mask = gen_subnet_mask($cidr);
2237
	$clear_route = false;
2238

    
2239
	switch ($settings['mode']) {
2240
		case 'shared_key':
2241
			$clear_route = true;
2242
			break;
2243
		case 'p2p_tls':
2244
		case 'p2p_shared_key':
2245
			if ($cidr >= 30) {
2246
				$clear_route = true;
2247
			}
2248
			break;
2249
	}
2250

    
2251
	if ($clear_route && !empty($ip) && !empty($mask)) {
2252
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2253
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2254
		/* XXX: Family for route? */
2255
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2256
	}
2257
}
2258

    
2259
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2260
	$routes = "";
2261
	$networks = array();
2262
	if (empty($value)) {
2263
		return "";
2264
	}
2265
	$tmpnetworks = explode(',', $value);
2266
	foreach ($tmpnetworks as $network) {
2267
		if (is_alias($network)) {
2268
			foreach (alias_to_subnets_recursive($network) as $net) {
2269
				if ((($ipproto == "ipv4") && is_subnetv4($net)) ||
2270
				    (($ipproto == "ipv6") && is_subnetv6($net))) {
2271
					$networks[] = $net;
2272
				}
2273
			}
2274
		} else {
2275
			$networks[] = $network;
2276
		}
2277
	}
2278

    
2279
	foreach ($networks as $network) {
2280
		if ($ipproto == "ipv4") {
2281
			$route = openvpn_gen_route_ipv4($network, $iroute);
2282
		} else {
2283
			$route = openvpn_gen_route_ipv6($network, $iroute);
2284
		}
2285

    
2286
		if ($push) {
2287
			$routes .= "push \"{$route}\"\n";
2288
		} else {
2289
			$routes .= "{$route}\n";
2290
		}
2291
	}
2292
	return $routes;
2293
}
2294

    
2295
function openvpn_gen_route_ipv4($network, $iroute = false) {
2296
	$i = ($iroute) ? "i" : "";
2297
	list($ip, $mask) = explode('/', trim($network));
2298
	$mask = gen_subnet_mask($mask);
2299
	return "{$i}route $ip $mask";
2300
}
2301

    
2302
function openvpn_gen_route_ipv6($network, $iroute = false) {
2303
	$i = ($iroute) ? "i" : "";
2304
	list($ipv6, $prefix) = explode('/', trim($network));
2305
	if (empty($prefix) && !is_numeric($prefix)) {
2306
		$prefix = "128";
2307
	}
2308
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2309
}
2310

    
2311
function openvpn_get_settings($mode, $vpnid) {
2312
	global $config;
2313

    
2314
	if (is_array($config['openvpn']['openvpn-server'])) {
2315
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2316
			if (isset($settings['disable'])) {
2317
				continue;
2318
			}
2319

    
2320
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2321
				return $settings;
2322
			}
2323
		}
2324
	}
2325

    
2326
	if (is_array($config['openvpn']['openvpn-client'])) {
2327
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
2328
			if (isset($settings['disable'])) {
2329
				continue;
2330
			}
2331

    
2332
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2333
				return $settings;
2334
			}
2335
		}
2336
	}
2337

    
2338
	return array();
2339
}
2340

    
2341
function openvpn_restart_by_vpnid($mode, $vpnid) {
2342
	$settings = openvpn_get_settings($mode, $vpnid);
2343
	openvpn_restart($mode, $settings);
2344
}
2345

    
2346
/****f* certs/openvpn_is_tunnel_network_in_use
2347
 * NAME
2348
 *   openvpn_is_tunnel_network_in_use
2349
 *     Check if the supplied network is in use as an OpenVPN server or client
2350
 *     tunnel network
2351
 * INPUTS
2352
 *   $net : The IPv4 or IPv6 network to check
2353
 * RESULT
2354
 *   boolean value: true if the network is in use, false otherwise.
2355
 ******/
2356

    
2357
function openvpn_is_tunnel_network_in_use($net) {
2358
	global $config;
2359
	init_config_arr(array('openvpn', 'openvpn-server'));
2360
	init_config_arr(array('openvpn', 'openvpn-client'));
2361
	/* Determine whether to check IPv4 or IPv6 tunnel networks */
2362
	$tocheck = 'tunnel_network';
2363
	if (is_v6($net)) {
2364
		$tocheck .= "v6";
2365
	}
2366
	/* Check all OpenVPN clients and servers for this tunnel network */
2367
	foreach(array('server', 'client') as $mode) {
2368
		foreach ($config['openvpn']["openvpn-{$mode}"] as $ovpn) {
2369
			if (!empty($ovpn[$tocheck]) &&
2370
			    ($ovpn[$tocheck] == $net)) {
2371
				return true;
2372
			}
2373
		}
2374
	}
2375
	return false;
2376
}
2377

    
2378
function openvpn_build_data_cipher_list($data_ciphers = 'AES-256-GCM,AES-128-GCM,CHACHA20-POLY1305', $fallback_cipher = 'AES-256-GBC', $ncp_enabled = true) {
2379
	/* If the data_ciphers list is empty, populate it with the fallback cipher. */
2380
	if (empty($data_ciphers) || !$ncp_enabled) {
2381
		$data_ciphers = $fallback_cipher;
2382
	}
2383
	/* Add the fallback cipher to the data ciphers list if it isn't already present */
2384
	if (!in_array($fallback_cipher, explode(',', $data_ciphers))) {
2385
		$data_ciphers .= ',' . $fallback_cipher;
2386
	}
2387
	return $data_ciphers;
2388
}
2389

    
2390
function openvpn_authscript_string($authmode, $strictusercn, $mode_id, $local_port) {
2391
	return "plugin /usr/local/lib/openvpn/plugins/openvpn-plugin-auth-script.so /usr/local/sbin/ovpn_auth_verify_async user " . base64_encode($authmode) . " {$strictusercn} {$mode_id} {$local_port}\n";
2392
}
2393

    
2394
function openvpn_inuse($id, $mode) {
2395
	global $config;
2396

    
2397
	$type = ($mode == 'server') ? 's' : 'c';
2398

    
2399
	foreach (get_configured_interface_list(true) as $if) {
2400
		if ($config['interfaces'][$if]['if'] == "ovpn{$type}{$id}") {
2401
			return true;
2402
		}
2403
	}
2404

    
2405
	return false;
2406
}
2407

    
2408
function openvpn_clean_rules($mode, $id) {
2409
	global $g;
2410

    
2411
	if ($mode == "server") {
2412
		unlink_if_exists("{$g['tmp_path']}/ovpn_ovpns{$id}_*.rules");
2413
	}
2414
}
2415

    
2416
?>
(33-33/61)