Project

General

Profile

Download (73.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('config.lib.inc');
34
require_once("certs.inc");
35
require_once('pfsense-utils.inc');
36
require_once("auth.inc");
37

    
38
global $openvpn_sharedkey_warning;
39
$openvpn_sharedkey_warning = gettext(
40
	'OpenVPN has deprecated shared key mode as it does not meet current security standards. ' .
41
	'Shared key mode will be removed from future versions. ' .
42
	'Convert any existing shared key VPNs to TLS and do not configure any new shared key OpenVPN instances.'
43
);
44

    
45
global $openvpn_prots;
46
$openvpn_prots = array(
47
	"UDP4" => "UDP on IPv4 only",
48
	"UDP6" => "UDP on IPv6 only",
49
	"TCP4" => "TCP on IPv4 only",
50
	"TCP6" => "TCP on IPv6 only",
51
	"UDP" => "UDP IPv4 and IPv6 on all interfaces (multihome)",
52
	"TCP" => "TCP IPv4 and IPv6 on all interfaces (multihome)"
53
);
54

    
55
global $openvpn_dev_mode;
56
$openvpn_dev_mode = array(
57
	"tun" => "tun - Layer 3 Tunnel Mode",
58
	"tap" => "tap - Layer 2 Tap Mode"
59
);
60

    
61
global $openvpn_verbosity_level;
62
$openvpn_verbosity_level = array(
63
	0 =>	gettext("none"),
64
	1 =>	gettext("default"),
65
	2 =>	"2",
66
	3 =>	gettext("3 (recommended)"),
67
	4 =>	"4",
68
	5 => 	"5",
69
	6 => 	"6",
70
	7 => 	"7",
71
	8 => 	"8",
72
	9 => 	"9",
73
	10 => 	"10",
74
	11 => 	"11"
75
);
76

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

    
90
global $openvpn_dh_lengths;
91
$openvpn_dh_lengths = array(
92
	1024 => "1024 bit",
93
	2048 => "2048 bit",
94
	3072 => "3072 bit",
95
	4096 => "4096 bit",
96
	6144 => "6144 bit",
97
	7680 => "7680 bit",
98
	8192 => "8192 bit",
99
	15360 => "15360 bit",
100
	16384 => "16384 bit",
101
	"none" => "ECDH Only"
102
);
103
foreach ($openvpn_dh_lengths as $idx => $dhlen) {
104
	if (is_numeric($idx) && !file_exists("/etc/dh-parameters.{$idx}")) {
105
		unset($openvpn_dh_lengths[$idx]);
106
	}
107
}
108

    
109
global $openvpn_cert_depths;
110
$openvpn_cert_depths = array(
111
	1 => gettext("One (Client+Server)"),
112
	2 => gettext("Two (Client+Intermediate+Server)"),
113
	3 => gettext("Three (Client+2xIntermediate+Server)"),
114
	4 => gettext("Four (Client+3xIntermediate+Server)"),
115
	5 => gettext("Five (Client+4xIntermediate+Server)")
116
);
117

    
118
global $openvpn_server_modes;
119
$openvpn_server_modes = array(
120
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
121
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"),
122
	'server_tls' => gettext("Remote Access ( SSL/TLS )"),
123
	'server_user' => gettext("Remote Access ( User Auth )"),
124
	'server_tls_user' => gettext("Remote Access ( SSL/TLS + User Auth )"));
125

    
126
global $openvpn_tls_server_modes;
127
$openvpn_tls_server_modes = array('p2p_tls', 'server_tls', 'server_user', 'server_tls_user');
128

    
129
global $openvpn_client_modes;
130
$openvpn_client_modes = array(
131
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
132
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"));
133

    
134
global $openvpn_allow_compression;
135
$openvpn_allow_compression = array(
136
	'asym' => gettext("Decompress incoming, do not compress outgoing (Asymmetric)"),
137
	'no'   => gettext("Refuse any non-stub compression (Most secure)"),
138
	'yes'  => gettext("Compress packets (WARNING: Potentially dangerous!)"),
139
);
140

    
141
global $openvpn_compression_modes;
142
$openvpn_compression_modes = array(
143
	'' => gettext("Disable Compression [Omit Preference]"),
144
	'none' => gettext("Disable Compression, retain compression packet framing [compress]"),
145
	'stub' => gettext("Enable Compression (stub) [compress stub]"),
146
	'stub-v2' => gettext("Enable Compression (stub v2) [compress stub-v2]"),
147
	'lz4' => gettext("LZ4 Compression [compress lz4]"),
148
	'lz4-v2' => gettext("LZ4 Compression v2 [compress lz4-v2]"),
149
	'lzo' => gettext("LZO Compression [compress lzo, equivalent to comp-lzo yes for compatibility]"),
150
	'noadapt' => gettext("Omit Preference, + Disable Adaptive LZO Compression [Legacy style, comp-noadapt]"),
151
	'adaptive' => gettext("Adaptive LZO Compression [Legacy style, comp-lzo adaptive]"),
152
	'yes' => gettext("LZO Compression [Legacy style, comp-lzo yes]"),
153
	'no' => gettext("No LZO Compression [Legacy style, comp-lzo no]"),
154
);
155

    
156
global $openvpn_topologies;
157
$openvpn_topologies = array(
158
	'subnet' => gettext("Subnet -- One IP address per client in a common subnet"),
159
	'net30' => gettext("net30 -- Isolated /30 network per client")
160
);
161

    
162
global $openvpn_tls_modes;
163
$openvpn_tls_modes = array(
164
	'auth' => gettext("TLS Authentication"),
165
	'crypt' => gettext("TLS Encryption and Authentication")
166
);
167

    
168
global $openvpn_ping_method;
169
$openvpn_ping_method = array(
170
	'keepalive' => gettext("keepalive -- Use keepalive helper to define ping configuration"),
171
	'ping' => gettext("ping -- Define ping/ping-exit/ping-restart manually")
172
);
173

    
174
global $openvpn_default_keepalive_interval;
175
$openvpn_default_keepalive_interval = 10;
176

    
177
global $openvpn_default_keepalive_timeout;
178
$openvpn_default_keepalive_timeout = 60;
179

    
180
global $openvpn_ping_action;
181
$openvpn_ping_action = array(
182
	'ping_restart' => gettext("ping-restart -- Restart OpenVPN after timeout"),
183
	'ping_exit' => gettext("ping-exit -- Exit OpenVPN after timeout")
184
);
185

    
186
global $openvpn_exit_notify_server;
187
$openvpn_exit_notify_server = array(
188
	'none' => gettext("Disabled"),
189
	'1' => gettext("Reconnect to this server / Retry once"),
190
	'2' => gettext("Reconnect to next server / Retry twice"),
191
);
192

    
193
global $openvpn_exit_notify_client;
194
$openvpn_exit_notify_client = array(
195
	'none' => gettext("Disabled"),
196
);
197
for ($i=1; $i<=5; $i++) {
198
	$openvpn_exit_notify_client[$i] = sprintf(gettext("Retry %dx"), $i);
199
}
200

    
201
function openvpn_build_mode_list() {
202
	global $openvpn_server_modes;
203

    
204
	$list = array();
205

    
206
	foreach ($openvpn_server_modes as $name => $desc) {
207
		$list[$name] = $desc;
208
	}
209

    
210
	return($list);
211
}
212

    
213
global $openvpn_interfacenames;
214
function convert_openvpn_interface_to_friendly_descr($if) {
215
	global $openvpn_interfacenames;
216
	if (!is_array($openvpn_interfacenames)) {
217
		$openvpn_interfacenames = openvpn_build_if_list();
218
	}
219
	foreach($openvpn_interfacenames as $key => $value) {
220
		list($item_if, $item_ip) = explode("|", $key);
221
		if ($if == $item_if) {
222
			echo "$value";
223
		}
224
	}
225
}
226

    
227
function openvpn_build_if_list() {
228
	$list = array();
229

    
230
	$interfaces = get_configured_interface_with_descr();
231
	$viplist = get_configured_vip_list();
232
	foreach ($viplist as $vip => $address) {
233
		$interfaces[$vip.'|'.$address] = $address;
234
		if (get_vip_descr($address)) {
235
			$interfaces[$vip.'|'.$address] .= " (";
236
			$interfaces[$vip.'|'.$address] .= get_vip_descr($address);
237
			$interfaces[$vip.'|'.$address] .= ")";
238
		}
239
	}
240

    
241
	$grouplist = return_gateway_groups_array();
242
	foreach ($grouplist as $name => $group) {
243
		if ($group[0]['vip'] != "") {
244
			$vipif = $group[0]['vip'];
245
		} else {
246
			$vipif = $group[0]['int'];
247
		}
248

    
249
		$interfaces[$name] = "GW Group {$name}";
250
	}
251

    
252
	$interfaces['lo0'] = "Localhost";
253
	$interfaces['any'] = "any";
254

    
255
	foreach ($interfaces as $iface => $ifacename) {
256
	   $list[$iface] = $ifacename;
257
	}
258

    
259
	return($list);
260
}
261

    
262
function openvpn_build_crl_list() {
263
	global $a_crl;
264

    
265
	$list = array('' => 'None');
266

    
267
	foreach ($a_crl as $crl) {
268
		$caname = "";
269
		$ca = lookup_ca($crl['caref']);
270

    
271
		if ($ca) {
272
			$caname = " (CA: {$ca['descr']})";
273
		}
274

    
275
		$list[$crl['refid']] = $crl['descr'] . $caname;
276
	}
277

    
278
	return($list);
279
}
280

    
281
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
282
	global $a_cert;
283
	$openvpn_compatible_certs = cert_build_list('cert', 'OpenVPN');
284

    
285
	if ($include_none) {
286
		$list = array('' => gettext('None (Username and/or Password required)'));
287
	} else {
288
		$list = array();
289
	}
290

    
291
	$non_server_list = array();
292

    
293
	if ($prioritize_server_certs) {
294
		$list[' '] = gettext("===== Server Certificates =====");
295
		$non_server_list['  '] = gettext("===== Non-Server Certificates =====");
296
	}
297

    
298
	foreach ($a_cert as $cert) {
299
		if (!array_key_exists($cert['refid'], $openvpn_compatible_certs)) {
300
			continue;
301
		}
302
		$properties = array();
303
		$propstr = "";
304
		$ca = lookup_ca($cert['caref']);
305
		$purpose = cert_get_purpose($cert['crt'], true);
306

    
307
		if ($purpose['server'] == "Yes") {
308
			$properties[] = gettext("Server: Yes");
309
		} elseif ($prioritize_server_certs) {
310
			$properties[] = gettext("Server: NO");
311
		}
312
		if ($ca) {
313
			$properties[] = sprintf(gettext("CA: %s"), $ca['descr']);
314
		}
315
		if (cert_in_use($cert['refid'])) {
316
			$properties[] = gettext("In Use");
317
		}
318
		if (is_cert_revoked($cert)) {
319
			$properties[] = gettext("Revoked");
320
		}
321

    
322
		if (!empty($properties)) {
323
			$propstr = " (" . implode(", ", $properties) . ")";
324
		}
325

    
326
		if ($prioritize_server_certs) {
327
			if ($purpose['server'] == "Yes") {
328
				$list[$cert['refid']] = $cert['descr'] . $propstr;
329
			} else {
330
				$non_server_list[$cert['refid']] = $cert['descr'] . $propstr;
331
			}
332
		} else {
333
			$list[$cert['refid']] = $cert['descr'] . $propstr;
334
		}
335
	}
336

    
337
	return(array('server' => $list, 'non-server' => $non_server_list));
338
}
339

    
340
function openvpn_build_bridge_list() {
341
	$list = array();
342

    
343
	$serverbridge_interface['none'] = "none";
344
	$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
345
	$viplist = get_configured_vip_list();
346

    
347
	foreach ($viplist as $vip => $address) {
348
		$serverbridge_interface[$vip.'|'.$address] = $address;
349
		if (get_vip_descr($address)) {
350
			$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
351
		}
352
	}
353

    
354
	foreach ($serverbridge_interface as $iface => $ifacename) {
355
		$list[$iface] = htmlspecialchars($ifacename);
356
	}
357

    
358
	return($list);
359
}
360

    
361
function openvpn_create_key() {
362

    
363
	$fp = popen("/usr/local/sbin/openvpn --genkey secret /dev/stdout 2>/dev/null", "r");
364
	if (!$fp) {
365
		return false;
366
	}
367

    
368
	$rslt = stream_get_contents($fp);
369
	pclose($fp);
370

    
371
	return $rslt;
372
}
373

    
374
function openvpn_create_dhparams($bits) {
375

    
376
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
377
	if (!$fp) {
378
		return false;
379
	}
380

    
381
	$rslt = stream_get_contents($fp);
382
	pclose($fp);
383

    
384
	return $rslt;
385
}
386

    
387
function openvpn_vpnid_used($vpnid) {
388
	init_config_arr(array('openvpn', 'openvpn-server'));
389
	init_config_arr(array('openvpn', 'openvpn-client'));
390
	foreach (["server", "client"] as $mode) {
391
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
392
			if ($vpnid == $settings['vpnid']) {
393
				return true;
394
			}
395
		}
396
	}
397
	return false;
398
}
399

    
400
function openvpn_vpnid_next() {
401

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

    
407
	return $vpnid;
408
}
409

    
410
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
411

    
412
	$ovpn_settings = config_get_path('openvpn/openvpn-server', []);
413
	$ovpn_settings = array_merge($ovpn_settings, config_get_path('openvpn/openvpn-client', []));
414

    
415
	foreach ($ovpn_settings as $settings) {
416
		if (isset($settings['disable'])) {
417
			continue;
418
		}
419

    
420
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
421
			continue;
422
		}
423

    
424
		/* (TCP|UDP)(4|6) does not conflict unless interface is any */
425
		if (($interface != "any" && $settings['interface'] != "any") &&
426
		    (strlen($prot) == 4) &&
427
		    (strlen($settings['protocol']) == 4) &&
428
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
429
		    substr($prot,3,1) != substr($settings['protocol'],3,1)) {
430
			continue;
431
		}
432

    
433
		if ($port == $settings['local_port'] &&
434
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
435
		    ($interface == $settings['interface'] ||
436
		    $interface == "any" || $settings['interface'] == "any")) {
437
			return $settings['vpnid'];
438
		}
439
	}
440

    
441
	return 0;
442
}
443

    
444
function openvpn_port_next($prot, $interface = "wan") {
445

    
446
	$port = 1194;
447
	while (openvpn_port_used($prot, $interface, $port)) {
448
		$port++;
449
	}
450
	while (openvpn_port_used($prot, "any", $port)) {
451
		$port++;
452
	}
453

    
454
	return $port;
455
}
456

    
457
function openvpn_get_cipherlist() {
458

    
459
	$ciphers = array();
460
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
461
	$cipher_lines = explode("\n", trim($cipher_out));
462
	sort($cipher_lines);
463
	foreach ($cipher_lines as $line) {
464
		$words = explode(' ', $line, 2);
465
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
466
	}
467
	$ciphers["none"] = gettext("None (No Encryption)");
468
	return $ciphers;
469
}
470

    
471
function openvpn_get_curvelist() {
472
	global $cert_curve_compatible;
473
	$curves = array();
474
	$curves["none"] = gettext("Use Default");
475
	foreach ($cert_curve_compatible['OpenVPN'] as $curve) {
476
		$curves[$curve] = $curve;
477
	}
478
	return $curves;
479
}
480

    
481
function openvpn_validate_curve($curve) {
482
	$curves = openvpn_get_curvelist();
483
	return array_key_exists($curve, $curves);
484
}
485

    
486
/* Obtain the list of digest algorithms supported by openssl and their alternate names */
487
function openvpn_get_openssldigestmappings() {
488
	$digests = array();
489
	$digest_out = shell_exec('/usr/bin/openssl list -digest-algorithms | /usr/bin/grep "=>"');
490
	$digest_lines = explode("\n", trim($digest_out));
491
	sort($digest_lines);
492
	foreach ($digest_lines as $line) {
493
		$words = explode(' => ', $line, 2);
494
		$digests[$words[0]] = $words[1];
495
	}
496
	return $digests;
497
}
498

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

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

    
535
function openvpn_get_keydirlist() {
536
	$keydirs = array(
537
		'default'  => gettext('Use default direction'),
538
		'0' => gettext('Direction 0'),
539
		'1' => gettext('Direction 1'),
540
		'2' => gettext('Both directions'),
541
	);
542
	return $keydirs;
543
}
544

    
545
function openvpn_get_engines() {
546
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
547
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
548
	$openssl_engine_output = implode("\n", $openssl_engine_output);
549
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
550
	$openssl_engine_output = explode("\n", $openssl_engine_output);
551

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

    
582
function openvpn_get_buffer_values() {
583
	$sendbuf_max = get_single_sysctl('net.inet.tcp.sendbuf_max');
584
	$recvbuf_max = get_single_sysctl('net.inet.tcp.recvbuf_max');
585
	/* Usually these two are equal, but if they are not, take whichever one is lower. */
586
	$buffer_max = ($sendbuf_max <= $recvbuf_max) ? $sendbuf_max : $recvbuf_max;
587
	$buffer_values = array('' => gettext('Default'));
588
	for ($bs = 32; $bs >= 1; $bs /= 2) {
589
		$buffer_values[$buffer_max/$bs] = format_bytes($buffer_max/$bs);
590
	}
591
	return $buffer_values;
592
}
593

    
594
function openvpn_validate_engine($engine) {
595
	$engines = openvpn_get_engines();
596
	return array_key_exists($engine, $engines);
597
}
598

    
599
function openvpn_validate_host($value, $name) {
600
	$value = trim($value);
601
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
602
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
603
	}
604
	return false;
605
}
606

    
607
function openvpn_validate_port($value, $name, $first_port = 0) {
608
	$value = trim($value);
609
	if (!is_numeric($first_port)) {
610
		$first_port = 0;
611
	}
612
	if (empty($value) || !is_numeric($value) || $value < $first_port || ($value > 65535)) {
613
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from %s to 65535."), $name, $first_port);
614
	}
615
	return false;
616
}
617

    
618
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4", $alias = false) {
619
	$value = trim($value);
620
	$error = false;
621
	if (empty($value)) {
622
		return false;
623
	}
624
	$networks = explode(',', $value);
625

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

    
630
	foreach ($networks as $network) {
631
		if ($ipproto == "ipv4") {
632
			$error = !openvpn_validate_cidr_ipv4($network, $alias);
633
		} else {
634
			$error = !openvpn_validate_cidr_ipv6($network, $alias);
635
		}
636
		if ($error) {
637
			break;
638
		}
639
	}
640

    
641
	if ($error) {
642
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) or FQDN(s) separated by commas."), $name, $ipproto);
643
	} else {
644
		return false;
645
	}
646
}
647

    
648
function openvpn_validate_cidr_ipv4($value, $alias = false) {
649
	$value = trim($value);
650
	if (!empty($value)) {
651
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
652
			foreach (alias_to_subnets_recursive($value, true) as $net) {
653
				if (!is_subnetv4($net) && !is_fqdn($net)) {
654
					return false;
655
				}
656
			}
657
			return true;
658
		} else {
659
			if (!is_subnetv4($value)) {
660
				return false;
661
			}
662
		}
663
	}
664
	return true;
665
}
666

    
667
function openvpn_validate_cidr_ipv6($value, $alias = false) {
668
	$value = trim($value);
669
	if (!empty($value)) {
670
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
671
			foreach (alias_to_subnets_recursive($value, true) as $net) {
672
				if (!is_subnetv6($net) && !is_fqdn($net)) {
673
					return false;
674
				}
675
			}
676
			return true;
677
		} else {
678
			list($ipv6, $prefix) = explode('/', $value);
679
			if (empty($prefix)) {
680
				$prefix = "128";
681
			}
682
			if (!is_subnetv6($ipv6 . '/' . $prefix)) {
683
				return false;
684
			}
685
		}
686
	}
687
	return true;
688
}
689

    
690
function openvpn_validate_tunnel_network($value, $ipproto) {
691
	$value = trim($value);
692
	if (!empty($value)) {
693
		if (is_alias($value) && (alias_get_type($value) == 'network')) {
694
			$net = alias_to_subnets_recursive($value);
695
			if ((!is_subnetv4($net[0]) && ($ipproto == 'ipv4')) ||
696
			    (!is_subnetv6($net[0]) && ($ipproto == 'ipv6')) ||
697
			    (count($net) > 1)) {
698
				return false;
699
			}
700
			return true;
701
		} else {
702
			if ((!is_subnetv4($value) && ($ipproto == 'ipv4')) ||
703
			    (!is_subnetv6($value) && ($ipproto == 'ipv6'))) { 
704
				return false;
705
			}
706
		}
707
	}
708
	return true;
709
}
710

    
711
function openvpn_gen_tunnel_network($tunnel_network) {
712
	if (is_alias($tunnel_network)) {
713
		$net = alias_to_subnets_recursive($tunnel_network);
714
		$pair = openvpn_tunnel_network_fix($net[0]);
715
	} else {
716
		$pair = $tunnel_network;
717
	}
718
	return explode('/', $pair);
719
}
720

    
721
function openvpn_add_dhcpopts(& $settings, & $conf) {
722

    
723
	if (!empty($settings['dns_domain'])) {
724
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
725
	}
726

    
727
	if (!empty($settings['dns_server1'])) {
728
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
729
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
730
	}
731
	if (!empty($settings['dns_server2'])) {
732
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
733
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
734
	}
735
	if (!empty($settings['dns_server3'])) {
736
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
737
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
738
	}
739
	if (!empty($settings['dns_server4'])) {
740
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
741
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
742
	}
743

    
744
	if (!empty($settings['push_blockoutsidedns'])) {
745
		$conf .= "push \"block-outside-dns\"\n";
746
	}
747
	if (!empty($settings['push_register_dns'])) {
748
		$conf .= "push \"register-dns\"\n";
749
	}
750

    
751
	if (!empty($settings['ntp_server1'])) {
752
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
753
	}
754
	if (!empty($settings['ntp_server2'])) {
755
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
756
	}
757

    
758
	if ($settings['netbios_enable']) {
759

    
760
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
761
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
762
		}
763
		if (!empty($settings['dhcp_nbtscope'])) {
764
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
765
		}
766

    
767
		if (!empty($settings['wins_server1'])) {
768
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
769
		}
770
		if (!empty($settings['wins_server2'])) {
771
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
772
		}
773

    
774
		if (!empty($settings['nbdd_server1'])) {
775
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
776
		}
777
	}
778

    
779
	if ($settings['gwredir']) {
780
		$conf .= "push \"redirect-gateway def1\"\n";
781
	}
782
	if ($settings['gwredir6']) {
783
		$conf .= "push \"redirect-gateway ipv6\"\n";
784
	}
785
}
786

    
787
function openvpn_add_custom(& $settings, & $conf) {
788

    
789
	if ($settings['custom_options']) {
790

    
791
		$options = explode(';', $settings['custom_options']);
792

    
793
		if (is_array($options)) {
794
			foreach ($options as $option) {
795
				$conf .= "$option\n";
796
			}
797
		} else {
798
			$conf .= "{$settings['custom_options']}\n";
799
		}
800
	}
801
}
802

    
803
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
804
	global $g;
805

    
806
	$fpath = "{$g['openvpn_base']}/{$mode_id}/{$directive}";
807
	openvpn_create_dirs();
808
	file_put_contents($fpath, base64_decode($data));
809
	//chown($fpath, 'nobody');
810
	//chgrp($fpath, 'nobody');
811
	@chmod($fpath, 0600);
812

    
813
	$conf .= "{$directive} {$fpath} {$opt}\n";
814
}
815

    
816
function openvpn_delete_tmp($mode, $id) {
817
	global $g;
818

    
819
	/* delete temporary files created by connect script */
820
	if (($mode == "server") && (isset($id))) {
821
		unlink_if_exists("{$g['tmp_path']}/ovpn_ovpns{$id}_*.rules");
822
	}
823

    
824
	/* delete temporary files created by OpenVPN; only delete old files to
825
	 * avoid deleting files potentially still in use by another OpenVPN process
826
	*/
827
	$tmpfiles = array_filter(glob("{$g['tmp_path']}/openvpn_cc*.tmp"),'is_file');
828
	if (!empty($tmpfiles)) {
829
		foreach ($tmpfiles as $tmpfile) {
830
			if ((time() - filemtime($tmpfile)) > 60) {
831
				@unlink_if_exists($tmpfile);
832
			}
833
		}
834
	}
835
}
836

    
837
function openvpn_reconfigure($mode, $settings) {
838
	global $g, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
839

    
840
	if (empty($settings)) {
841
		return;
842
	}
843
	if (isset($settings['disable'])) {
844
		return;
845
	}
846
	openvpn_create_dirs();
847
	/*
848
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
849
	 * we use a vpnid number which is allocated for a particular client
850
	 * or server configuration. ( see openvpn_vpnid_next() )
851
	 */
852

    
853
	$vpnid = $settings['vpnid'];
854
	$mode_id = $mode.$vpnid;
855

    
856
	if (isset($settings['dev_mode'])) {
857
		$tunname = "{$settings['dev_mode']}{$vpnid}";
858
	} else {
859
		/* defaults to tun */
860
		$tunname = "tun{$vpnid}";
861
		$settings['dev_mode'] = "tun";
862
	}
863

    
864
	if ($mode == "server") {
865
		$devname = "ovpns{$vpnid}";
866
	} else {
867
		$devname = "ovpnc{$vpnid}";
868
	}
869

    
870
	/* is our device already configured */
871
	if (!does_interface_exist($devname)) {
872

    
873
		/* create the tap device if required */
874
		if (!file_exists("/dev/{$tunname}")) {
875
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
876
		}
877

    
878
		/* rename the device */
879
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
880

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

    
884
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
885
		$grouptmp = link_interface_to_group($ifname);
886
		if (!empty($grouptmp)) {
887
			array_walk($grouptmp, 'interface_group_add_member');
888
		}
889
		unset($grouptmp, $ifname);
890
	}
891

    
892
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
893
	$proto = strtolower($settings['protocol']);
894
	if (substr($settings['protocol'], 0, 3) == "TCP") {
895
			$proto = "{$proto}-{$mode}";
896
	}
897
	$dev_mode = $settings['dev_mode'];
898
	$fbcipher = $settings['data_ciphers_fallback'];
899
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
900
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
901

    
902
	$interface = get_failover_interface($settings['interface']);
903
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
904
	$ipaddr = $settings['ipaddr'];
905

    
906
	// If a specific ip address (VIP) is requested, use it.
907
	// Otherwise, if a specific interface is requested, use it
908
	// If "any" interface was selected, local directive will be omitted.
909
	if (is_ipaddrv4($ipaddr)) {
910
		$iface_ip = $ipaddr;
911
	} elseif (!empty($interface) && strcmp($interface, "any")) {
912
		$iface_ip=get_interface_ip($interface);
913
	}
914
	if (is_ipaddrv6($ipaddr)) {
915
		$iface_ipv6 = $ipaddr;
916
	} elseif (!empty($interface) && strcmp($interface, "any")) {
917
		/* get correct interface name for 6RD/6to4 interfaces
918
		 * see https://redmine.pfsense.org/issues/11674 */
919
		if (is_stf_interface($settings['interface'])) {
920
			$iface_ipv6=get_interface_ipv6($settings['interface']);
921
		} else {
922
			$iface_ipv6=get_interface_ipv6($interface);
923
		}
924
	}
925

    
926
	$conf = "dev {$devname}\n";
927
	if (isset($settings['verbosity_level'])) {
928
		$conf .= "verb {$settings['verbosity_level']}\n";
929
	}
930

    
931
	$conf .= "dev-type {$settings['dev_mode']}\n";
932
	$conf .= "dev-node /dev/{$tunname}\n";
933
	$conf .= "writepid {$pfile}\n";
934
	$conf .= "#user nobody\n";
935
	$conf .= "#group nobody\n";
936
	$conf .= "script-security 3\n";
937
	$conf .= "daemon\n";
938

    
939
	if (!empty($settings['ping_method']) &&
940
	    $settings['ping_method'] == 'ping') {
941
		$conf .= "ping {$settings['ping_seconds']}\n";
942

    
943
		if (!empty($settings['ping_push'])) {
944
			$conf .= "push \"ping {$settings['ping_seconds']}\"\n";
945
		}
946

    
947
		$action = str_replace("_", "-", $settings['ping_action']);
948
		$conf .= "{$action} {$settings['ping_action_seconds']}\n";
949

    
950
		if (!empty($settings['ping_action_push'])) {
951
			$conf .= "push \"{$action} " .
952
			    "{$settings['ping_action_seconds']}\"\n";
953
		}
954
	} else {
955
		$conf .= "keepalive " .
956
		    ($settings['keepalive_interval']
957
			?: $openvpn_default_keepalive_interval) . " " .
958
		    ($settings['keepalive_timeout']
959
			?: $openvpn_default_keepalive_timeout) . "\n";
960
	}
961

    
962
	$conf .= "ping-timer-rem\n";
963
	$conf .= "persist-tun\n";
964
	$conf .= "persist-key\n";
965
	$conf .= "proto {$proto}\n";
966
	$conf .= "auth {$digest}\n";
967
	if ($settings['dns_add']) {
968
		$conf .= "up /usr/local/sbin/ovpn-dnslinkup\n";
969
	} else {
970
		$conf .= "up /usr/local/sbin/ovpn-linkup\n";
971
	}
972
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
973
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
974
		switch ($settings['mode']) {
975
			case 'server_user':
976
			case 'server_tls_user':
977
			case 'server_tls':
978
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
979
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
980
				break;
981
		}
982
	}
983
	if ($settings['dev_mode'] === 'tun' && config_path_enabled('unbound') &&
984
		config_path_enabled('unbound','regovpnclients')) {
985
		if (($settings['mode'] == 'server_tls') || ($settings['mode'] == 'server_tls_user') ||
986
		    (($settings['mode'] == 'server_user') && ($settings['username_as_common_name'] == 'enabled'))) {
987
			$domain = !empty($settings['dns_domain']) ? $settings['dns_domain'] : config_get_path('system/domain');
988
			if (is_domain($domain)) {
989
				$conf .= "learn-address \"/usr/local/sbin/openvpn.learn-address.sh $domain\"\n";
990
			}
991
		}
992
	}
993

    
994
	/*
995
	 * When binding specific address, wait cases where interface is in
996
	 * tentative state otherwise it will fail
997
	 */
998
	$wait_tentative = false;
999

    
1000
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
1001
	switch ($settings['protocol']) {
1002
		case 'UDP':
1003
		case 'TCP':
1004
			$conf .= "multihome\n";
1005
			break;
1006
		case 'UDP4':
1007
		case 'TCP4':
1008
			if (is_ipaddrv4($iface_ip)) {
1009
				$conf .= "local {$iface_ip}\n";
1010
			}
1011
			if ($settings['interface'] == "any") {
1012
				$conf .= "multihome\n";
1013
			}
1014
			break;
1015
		case 'UDP6':
1016
		case 'TCP6':
1017
			if (is_ipaddrv6($iface_ipv6)) {
1018
				$conf .= "local {$iface_ipv6}\n";
1019
				$wait_tentative = true;
1020
			}
1021
			if ($settings['interface'] == "any") {
1022
				$conf .= "multihome\n";
1023
			}
1024
			break;
1025
		default:
1026
	}
1027

    
1028
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
1029
		$conf .= "engine {$settings['engine']}\n";
1030
	}
1031

    
1032
	// server specific settings
1033
	if ($mode == 'server') {
1034

    
1035
		list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1036
		list($ipv6, $prefix) = openvpn_gen_tunnel_network($settings['tunnel_networkv6']);
1037
		$mask = gen_subnet_mask($cidr);
1038

    
1039
		// configure tls modes
1040
		switch ($settings['mode']) {
1041
			case 'p2p_tls':
1042
			case 'server_tls':
1043
			case 'server_user':
1044
			case 'server_tls_user':
1045
				$conf .= "tls-server\n";
1046
				break;
1047
		}
1048

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

    
1128
		// configure user auth modes
1129
		switch ($settings['mode']) {
1130
			case 'server_user':
1131
				$conf .= "verify-client-cert none\n";
1132
			case 'server_tls_user':
1133
				/* username-as-common-name is not compatible with server-bridge */
1134
				if ((stristr($conf, "server-bridge") === false) &&
1135
				    ($settings['username_as_common_name'] != 'disabled')) {
1136
					$conf .= "username-as-common-name\n";
1137
				}
1138
				if (!empty($settings['authmode'])) {
1139
					$strictusercn = "false";
1140
					if ($settings['strictusercn']) {
1141
						$strictusercn = "true";
1142
					}
1143
					$conf .= openvpn_authscript_string($settings['authmode'], $strictusercn, $mode_id, $settings['local_port']);
1144
				}
1145
				break;
1146
		}
1147
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
1148
			$settings['cert_depth'] = 1;
1149
		}
1150
		if (is_numeric($settings['cert_depth'])) {
1151
			if (($mode == 'client') && empty($settings['certref'])) {
1152
				$cert = "";
1153
			} else {
1154
				$cert = lookup_cert($settings['certref']);
1155
				/* XXX: Seems not used at all! */
1156
				$servercn = urlencode(cert_get_cn($cert['crt']));
1157
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
1158
			}
1159
		}
1160

    
1161
		// The local port to listen on
1162
		$conf .= "lport {$settings['local_port']}\n";
1163

    
1164
		// The management port to listen on
1165
		// Use unix socket to overcome the problem on any type of server
1166
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1167
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
1168

    
1169
		if ($settings['maxclients']) {
1170
			$conf .= "max-clients {$settings['maxclients']}\n";
1171
		}
1172

    
1173
		// Can we push routes, and should we?
1174
		if ($settings['local_network'] && !$settings['gwredir']) {
1175
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1176
		}
1177
		if ($settings['local_networkv6'] && !$settings['gwredir6']) {
1178
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1179
		}
1180

    
1181
		switch ($settings['mode']) {
1182
			case 'server_tls':
1183
			case 'server_user':
1184
			case 'server_tls_user':
1185
				// Configure client dhcp options
1186
				openvpn_add_dhcpopts($settings, $conf);
1187
				if ($settings['client2client']) {
1188
					$conf .= "client-to-client\n";
1189
				}
1190
				break;
1191
		}
1192
		$connlimit = "0";
1193
		if ($settings['mode'] != 'p2p_shared_key' &&
1194
		    isset($settings['duplicate_cn'])) {
1195
			$conf .= "duplicate-cn\n";
1196
			if ($settings['connlimit']) {
1197
				$connlimit = "{$settings['connlimit']}";
1198
			}
1199
		}
1200
		if (($settings['mode'] != 'p2p_shared_key') &&
1201
		    isset($settings['remote_cert_tls'])) {
1202
			$conf .= "remote-cert-tls client\n";
1203
		}
1204
	}
1205

    
1206
	// client specific settings
1207

    
1208
	if ($mode == 'client') {
1209

    
1210
		$add_pull = false;
1211
		// configure p2p mode
1212
		if ($settings['mode'] == 'p2p_tls') {
1213
			$conf .= "tls-client\n";
1214
		}
1215

    
1216
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1217
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1218
		//  ensure a random source port.
1219
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1220
			$conf .= "nobind\n";
1221
		} elseif ($settings['local_port']) {
1222
			$conf .= "lport {$settings['local_port']}\n";
1223
		} else {
1224
			$conf .= "lport 0\n";
1225
		}
1226

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

    
1230
		// The remote server
1231
		$remoteproto = strtolower($settings['protocol']);
1232
		if (substr($remoteproto, 0, 3) == "tcp") {
1233
			$remoteproto .= "-{$mode}";
1234
		}
1235
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']} {$remoteproto}\n";
1236

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

    
1241
		if (!empty($settings['tunnel_network'])) {
1242
			list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1243
			$mask = gen_subnet_mask($cidr);
1244
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1245
			if ($settings['dev_mode'] == 'tun') {
1246
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1247
			} else {
1248
				$conf .= "ifconfig {$ip2} {$mask}\n";
1249
				if ($settings['mode'] == 'p2p_tls') {
1250
					$add_pull = true;
1251
				}
1252
			}
1253
		}
1254

    
1255
		if (!empty($settings['tunnel_networkv6'])) {
1256
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1257
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1258
			if ($settings['dev_mode'] == 'tun') {
1259
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1260
			} else {
1261
				$conf .= "ifconfig-ipv6 {$ipv6_1}/{$prefix} {$ipv6_2}\n";
1262
				if ($settings['mode'] == 'p2p_tls') {
1263
					$add_pull = true;
1264
				}
1265
			}
1266
		}
1267

    
1268
		/* If both tunnel networks are empty, then pull from server. */
1269
		if (empty($settings['tunnel_network']) &&
1270
		    empty($settings['tunnel_networkv6'])) {
1271
			$add_pull = true;
1272
		}
1273

    
1274
		/* Only add "pull" if the tunnel network is undefined or using tap mode.
1275
		   OpenVPN can't pull settings from a server in point-to-point mode. */
1276
		if (($settings['mode'] == 'p2p_tls') && $add_pull) {
1277
			$conf .= "pull\n";
1278
		}
1279

    
1280
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
1281
			$up_file = "{$g['openvpn_base']}/{$mode_id}/up";
1282
			$conf .= "auth-user-pass {$up_file}\n";
1283
			if (!$settings['auth-retry-none']) {
1284
				$conf .= "auth-retry nointeract\n";
1285
			}
1286
			if ($settings['auth_user']) {
1287
				$userpass = "{$settings['auth_user']}\n";
1288
			} else {
1289
				$userpass = "";
1290
			}
1291
			if ($settings['auth_pass']) {
1292
				$userpass .= "{$settings['auth_pass']}\n";
1293
			}
1294
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
1295
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
1296
				$userpass .= "\n";
1297
			}
1298
			file_put_contents($up_file, $userpass);
1299
		}
1300

    
1301
		if ($settings['proxy_addr']) {
1302
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1303
			if ($settings['proxy_authtype'] != "none") {
1304
				$conf .= " {$g['openvpn_base']}/{$mode_id}/proxy_auth {$settings['proxy_authtype']}";
1305
				$proxypas = "{$settings['proxy_user']}\n";
1306
				$proxypas .= "{$settings['proxy_passwd']}\n";
1307
				file_put_contents("{$g['openvpn_base']}/{$mode_id}/proxy_auth", $proxypas);
1308
			}
1309
			$conf .= " \n";
1310
		}
1311

    
1312
		if (($settings['mode'] != 'shared_key') &&
1313
		    isset($settings['remote_cert_tls'])) {
1314
			$conf .= "remote-cert-tls server\n";
1315
		}
1316
	}
1317

    
1318
	// Add a remote network route if set, and only for p2p modes.
1319
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4", true) === FALSE)) {
1320
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1321
	}
1322
	// Add a remote network route if set, and only for p2p modes.
1323
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6", true) === FALSE)) {
1324
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1325
	}
1326

    
1327
	// Write the settings for the keys
1328
	switch ($settings['mode']) {
1329
		case 'p2p_shared_key':
1330
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
1331
			break;
1332
		case 'p2p_tls':
1333
		case 'server_tls':
1334
		case 'server_tls_user':
1335
		case 'server_user':
1336
			// ca_chain_array() expects parameter to be passed by reference.
1337
			// avoid passing the whole settings array, as param names or
1338
			// types might change in future releases.
1339
			$param = array('caref' => $settings['caref']);
1340
			$cas = ca_chain_array($param);
1341
			$capath = "{$g['openvpn_base']}/{$mode_id}/ca";
1342
			/* Cleanup old CA/CRL references */
1343
			@unlink_if_exists("{$capath}/*.0");
1344
			@unlink_if_exists("{$capath}/*.r*");
1345
			/* Find the CRL listed in the settings */
1346
			if (!empty($settings['crlref'])) {
1347
				$crl = lookup_crl($settings['crlref']);
1348
				crl_update($crl);
1349
			}
1350
			/* For each CA in the chain, setup the CApath */
1351
			foreach ($cas as $ca) {
1352
				ca_setup_capath($ca, $capath, $crl);
1353
			}
1354
			$conf .= "capath {$capath}\n";
1355
			unset($cas, $param);
1356

    
1357
			if (!empty($settings['certref'])) {
1358
				$cert = lookup_cert($settings['certref']);
1359
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
1360
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
1361
			}
1362
			if ($mode == 'server') {
1363
				if (is_numeric($settings['dh_length'])) {
1364
					if (!in_array($settings['dh_length'], array_keys($openvpn_dh_lengths))) {
1365
						/* The user selected a DH parameter length that does not have a corresponding file. */
1366
						log_error(gettext("Failed to construct OpenVPN server configuration. The selected DH Parameter length cannot be used."));
1367
						return;
1368
					}
1369
					$dh_file = "{$g['etc_path']}/dh-parameters.{$settings['dh_length']}";
1370
				} else {
1371
					$dh_file = $settings['dh_length'];
1372
				}
1373
				$conf .= "dh {$dh_file}\n";
1374
				if (!empty($settings['ecdh_curve']) && ($settings['ecdh_curve'] != "none") && openvpn_validate_curve($settings['ecdh_curve'])) {
1375
					$conf .= "ecdh-curve {$settings['ecdh_curve']}\n";
1376
				}
1377
			}
1378
			if ($settings['tls']) {
1379
				if ($settings['tls_type'] == "crypt") {
1380
					$tls_directive = "tls-crypt";
1381
					$tlsopt = "";
1382
				} else {
1383
					$tls_directive = "tls-auth";
1384
					if ($mode == "server") {
1385
						switch($settings['tlsauth_keydir']){
1386
							case '1':
1387
								$tlsopt = 1;
1388
								break;
1389
							case '2':
1390
								$tlsopt = '';
1391
								break;
1392
							default:
1393
								$tlsopt = 0;
1394
								break;
1395
						}
1396
					} else {
1397
						switch($settings['tlsauth_keydir']){
1398
							case '0':
1399
								$tlsopt = 0;
1400
								break;
1401
							case '2':
1402
								$tlsopt = '';
1403
								break;
1404
							default:
1405
								$tlsopt = 1;
1406
								break;
1407
						}
1408
					}
1409
				}
1410
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, $tls_directive, $tlsopt);
1411
			}
1412
			break;
1413
	}
1414

    
1415
	/* Data encryption cipher support.
1416
	 * If it is not set, assume enabled since that is OpenVPN's default.
1417
	 * Note that diabling this is now deprecated and will be removed in a future version of OpenVPN */
1418
	if (($settings['ncp_enable'] == "disabled") ||
1419
	    ($settings['mode'] == "p2p_shared_key")) {
1420
		if ($settings['mode'] != "p2p_shared_key") {
1421
			/* Do not include this option for shared key as it is redundant. */
1422
			$conf .= "ncp-disable\n";
1423
		}
1424
		$conf .= "cipher {$fbcipher}\n";
1425
	} else {
1426
		$conf .= "data-ciphers " . str_replace(',', ':', openvpn_build_data_cipher_list($settings['data_ciphers'], $fbcipher)) . "\n";
1427
		$conf .= "data-ciphers-fallback {$fbcipher}\n";
1428
	}
1429

    
1430
	if (!empty($settings['allow_compression'])) {
1431
		$conf .= "allow-compression {$settings['allow_compression']}\n";
1432
	}
1433

    
1434
	$compression = "";
1435
	switch ($settings['compression']) {
1436
		case 'none':
1437
			$settings['compression'] = '';
1438
		case 'lz4':
1439
		case 'lz4-v2':
1440
		case 'lzo':
1441
		case 'stub':
1442
		case 'stub-v2':
1443
			$compression .= "compress {$settings['compression']}";
1444
			break;
1445
		case 'noadapt':
1446
			$compression .= "comp-noadapt";
1447
			break;
1448
		case 'adaptive':
1449
		case 'yes':
1450
		case 'no':
1451
			$compression .= "comp-lzo {$settings['compression']}";
1452
			break;
1453
		default:
1454
			/* Add nothing to the configuration */
1455
			break;
1456
	}
1457

    
1458
	if (($settings['allow_compression'] != 'no') &&
1459
	    !empty($compression)) {
1460
		$conf .= "{$compression}\n";
1461
		if ($settings['compression_push']) {
1462
			$conf .= "push \"{$compression}\"\n";
1463
		}
1464
	}
1465

    
1466
	if ($settings['passtos']) {
1467
		$conf .= "passtos\n";
1468
	}
1469

    
1470
	if ($mode == 'client') {
1471
		$conf .= "resolv-retry infinite\n";
1472
	}
1473

    
1474
	if ($settings['dynamic_ip']) {
1475
		$conf .= "persist-remote-ip\n";
1476
		$conf .= "float\n";
1477
	}
1478

    
1479
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1480
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1481
		if (empty($settings['topology'])) {
1482
			$settings['topology'] = "subnet";
1483
		}
1484
		$conf .= "topology {$settings['topology']}\n";
1485
	}
1486

    
1487
	// New client features
1488
	if ($mode == "client") {
1489
		// Dont add/remove routes checkbox
1490
		if ($settings['route_no_exec']) {
1491
			$conf .= "route-noexec\n";
1492
		}
1493
	}
1494

    
1495
	/* UDP Fast I/O. Only compatible with UDP and also not compatible with OpenVPN's "shaper" directive. */
1496
	if ($settings['udp_fast_io']
1497
	    && (strtolower(substr($settings['protocol'], 0, 3)) == "udp")
1498
	    && (empty($settings['use_shaper']))) {
1499
		$conf .= "fast-io\n";
1500
	}
1501

    
1502
	/* Exit Notify.
1503
	 * Only compatible with UDP and specific combinations of
1504
	 * modes and settings, including:
1505
	 * if type is server AND
1506
	 *	mode is not shared key AND
1507
	 *		tunnel network CIDR mask < 30 AND
1508
	 *		tunnel network is not blank
1509
	 * if type is client AND
1510
	 *	mode is not shared key AND
1511
	 *		tunnel network is blank OR
1512
	 *		tunnel network CIDR mask < 30
1513
	 */
1514
	list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1515
	if ((!empty($settings['exit_notify']) &&
1516
	    is_numericint($settings['exit_notify']) &&
1517
	    (strtolower(substr($settings['protocol'], 0, 3)) == "udp")) &&
1518
	    ((($mode == "server") && (($settings['mode'] != 'p2p_shared_key') && (($cidr < 30) && !empty($ip)))) ||
1519
	    (($mode == "client") && (($settings['mode'] != 'p2p_shared_key') && (($cidr < 30) || empty($ip)))))) {
1520
		$conf .= "explicit-exit-notify {$settings['exit_notify']}\n";
1521
	}
1522

    
1523
	/* Inactive Seconds
1524
	 * Has similar restrictions to Exit Notify (above) but only for server mode.
1525
	 */
1526
	if (!empty($settings['inactive_seconds']) &&
1527
	    !(($mode == "server") && (($settings['mode'] == 'p2p_shared_key') || (($cidr >= 30) || empty($ip))))) {
1528
		$conf .= "inactive {$settings['inactive_seconds']}\n";
1529
	}
1530

    
1531
	/* Send and Receive Buffer Settings */
1532
	if (is_numericint($settings['sndrcvbuf'])
1533
	    && ($settings['sndrcvbuf'] > 0)
1534
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1535
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1536
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1537
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1538
	}
1539

    
1540
	openvpn_add_custom($settings, $conf);
1541

    
1542
	/* add nopull option after custom options, see https://redmine.pfsense.org/issues/11448 */
1543
	if (($mode == "client") && $settings['route_no_pull']) {
1544
		// Dont pull routes checkbox
1545
		$conf .= "route-nopull\n";
1546
	}
1547

    
1548
	openvpn_create_dirs();
1549
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1550
	file_put_contents($fpath, $conf);
1551
	unset($conf);
1552
	$fpath = "{$g['openvpn_base']}/{$mode_id}/interface";
1553
	file_put_contents($fpath, $interface);
1554
	$fpath = "{$g['openvpn_base']}/{$mode_id}/connuserlimit";
1555
	file_put_contents($fpath, $connlimit);
1556
	//chown($fpath, 'nobody');
1557
	//chgrp($fpath, 'nobody');
1558
	@chmod("{$g['openvpn_base']}/{$mode_id}/config.ovpn", 0600);
1559
	@chmod("{$g['openvpn_base']}/{$mode_id}/interface", 0600);
1560
	@chmod("{$g['openvpn_base']}/{$mode_id}/key", 0600);
1561
	@chmod("{$g['openvpn_base']}/{$mode_id}/tls-auth", 0600);
1562
	@chmod("{$g['openvpn_base']}/{$mode_id}/conf", 0600);
1563
	@chmod("{$g['openvpn_base']}/{$mode_id}/connuserlimit", 0600);
1564

    
1565
	if ($wait_tentative) {
1566
		interface_wait_tentative($interface);
1567
	}
1568
}
1569

    
1570
function openvpn_restart($mode, $settings) {
1571
	global $g;
1572

    
1573
	$vpnid = $settings['vpnid'];
1574
	$mode_id = $mode.$vpnid;
1575
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1576
	openvpn_reconfigure($mode, $settings);
1577
	/* kill the process if running */
1578
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1579
	if (file_exists($pfile)) {
1580

    
1581
		/* read the pid file */
1582
		$pid = rtrim(file_get_contents($pfile));
1583
		unlink($pfile);
1584
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1585

    
1586
		/* send a term signal to the process */
1587
		posix_kill($pid, SIGTERM);
1588

    
1589
		/* wait until the process exits, or timeout and kill it */
1590
		$i = 0;
1591
		while (posix_kill($pid, 0)) {
1592
			usleep(250000);
1593
			if ($i > 10) {
1594
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1595
				posix_kill($pid, SIGKILL);
1596
				usleep(500000);
1597
			}
1598
			$i++;
1599
		}
1600
	}
1601

    
1602
	if (isset($settings['disable'])) {
1603
		openvpn_delete($mode, $settings);
1604
		unlock($lockhandle);
1605
		return;
1606
	}
1607

    
1608
	openvpn_delete_tmp($mode, $vpnid);
1609

    
1610
	/* Do not start an instance if we are not CARP master on this vip! */
1611
	if (strstr($settings['interface'], "_vip")) {
1612
	       	$carpstatus = get_carp_bind_status($settings['interface']);
1613
		/* Do not start an instance if vip aliased to BACKUP CARP
1614
		 * see https://redmine.pfsense.org/issues/11793 */ 
1615
		if (in_array($carpstatus, array('BACKUP', 'INIT'))) {
1616
			unlock($lockhandle);
1617
			return;
1618
		} 
1619
	}
1620

    
1621
	/* Check if client is bound to a gateway group */
1622
	$a_groups = return_gateway_groups_array(true);
1623
	if (is_array($a_groups[$settings['interface']])) {
1624
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1625
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1626
			unlock($lockhandle);
1627
			return;
1628
		}
1629
	}
1630

    
1631
	/* start the new process */
1632
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1633
	openvpn_clear_route($mode, $settings);
1634
	$res = mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1635
	if ($res == 0) {
1636
		$i = 0;
1637
		$pid = "--";
1638
		while ($i < 3000) {
1639
			if (isvalidpid($pfile)) {
1640
				$pid = rtrim(file_get_contents($pfile));
1641
				break;
1642
			}
1643
			usleep(1000);
1644
			$i++;
1645
		}
1646
		syslog(LOG_INFO, "OpenVPN PID written: {$pid}");
1647
	} else {
1648
		syslog(LOG_ERR, "OpenVPN failed to start");
1649
	}
1650
	if (!platform_booting()) {
1651
		send_event("filter reload");
1652
	}
1653
	unlock($lockhandle);
1654
}
1655

    
1656
function openvpn_delete($mode, $settings) {
1657
	global $g;
1658

    
1659
	$vpnid = $settings['vpnid'];
1660
	$mode_id = $mode.$vpnid;
1661

    
1662
	if ($mode == "server") {
1663
		$devname = "ovpns{$vpnid}";
1664
	} else {
1665
		$devname = "ovpnc{$vpnid}";
1666
	}
1667

    
1668
	/* kill the process if running */
1669
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1670
	if (file_exists($pfile)) {
1671

    
1672
		/* read the pid file */
1673
		$pid = trim(file_get_contents($pfile));
1674
		unlink($pfile);
1675

    
1676
		/* send a term signal to the process */
1677
		posix_kill($pid, SIGTERM);
1678
	}
1679

    
1680
	/* destroy the device */
1681
	pfSense_interface_destroy($devname);
1682

    
1683
	/* Invalidate cache */
1684
	get_interface_arr(true);
1685

    
1686
	/* remove the configuration files */
1687
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*/*");
1688
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*");
1689
	openvpn_delete_tmp($mode, $vpnid);
1690
	filter_configure();
1691
}
1692

    
1693
function openvpn_resync_csc($settings) {
1694
	global $g, $openvpn_tls_server_modes;
1695
	if (isset($settings['disable'])) {
1696
		openvpn_delete_csc($settings);
1697
		return;
1698
	}
1699
	openvpn_create_dirs();
1700

    
1701
	if (empty($settings['server_list'])) {
1702
		$csc_server_list = array();
1703
	} else {
1704
		$csc_server_list = explode(",", $settings['server_list']);
1705
	}
1706

    
1707
	$conf = '';
1708
	if ($settings['block']) {
1709
		$conf .= "disable\n";
1710
	}
1711

    
1712
	if ($settings['push_reset']) {
1713
		$conf .= "push-reset\n";
1714
	}
1715

    
1716
	if ($settings['remove_route']) {
1717
		$conf .= "push-remove route\n";
1718
	}
1719

    
1720
	if ($settings['local_network']) {
1721
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1722
	}
1723
	if ($settings['local_networkv6']) {
1724
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1725
	}
1726

    
1727
	// Add a remote network iroute if set
1728
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4", true) === FALSE) {
1729
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1730
	}
1731
	// Add a remote network iroute if set
1732
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6", true) === FALSE) {
1733
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1734
	}
1735

    
1736
	openvpn_add_dhcpopts($settings, $conf);
1737

    
1738
	openvpn_add_custom($settings, $conf);
1739
	/* Loop through servers, find which ones can use this CSC */
1740
	foreach (config_get_path('openvpn/openvpn-server', []) as $serversettings) {
1741
		if (isset($serversettings['disable'])) {
1742
			continue;
1743
		}
1744
		if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1745
			if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1746
				$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1747
				$csc_conf = $conf;
1748

    
1749
				if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1750
					list($ip, $mask) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1751
					if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1752
						$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1753
					} else {
1754
						/* Because this is being pushed, the order from the client's point of view. */
1755
						$baselong = gen_subnetv4($ip, $mask);
1756
						$serverip = ip_after($baselong, 1);
1757
						$clientip = ip_after($baselong, 2);
1758
						$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1759
					}
1760
				}
1761

    
1762
				if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1763
					list($ipv6, $prefix) = openvpn_gen_tunnel_network($serversettings['tunnel_networkv6']);
1764
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1765
					$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1766
				}
1767

    
1768
				file_put_contents($csc_path, $csc_conf);
1769
				chown($csc_path, 'nobody');
1770
				chgrp($csc_path, 'nobody');
1771
			}
1772
		}
1773
	}
1774
}
1775

    
1776
function openvpn_resync_csc_all() {
1777
	init_config_arr(array('openvpn', 'openvpn-csc'));
1778
	foreach (config_get_path('openvpn/openvpn-csc', []) as $settings) {
1779
		openvpn_resync_csc($settings);
1780
	}
1781
}
1782

    
1783
function openvpn_delete_csc($settings) {
1784
	global $g, $openvpn_tls_server_modes;
1785
	if (empty($settings['server_list'])) {
1786
		$csc_server_list = array();
1787
	} else {
1788
		$csc_server_list = explode(",", $settings['server_list']);
1789
	}
1790

    
1791
	/* Loop through servers, find which ones used this CSC */
1792
	foreach (config_get_path('openvpn/openvpn-server', []) as $serversettings) {
1793
		if (isset($serversettings['disable'])) {
1794
			continue;
1795
		}
1796
		if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1797
			if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1798
				$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1799
				unlink_if_exists($csc_path);
1800
			}
1801
		}
1802
	}
1803
}
1804

    
1805
// Resync the configuration and restart the VPN
1806
function openvpn_resync($mode, $settings) {
1807
	openvpn_restart($mode, $settings);
1808
}
1809

    
1810
// Resync and restart all VPNs
1811
function openvpn_resync_all($interface = "", $protocol = "") {
1812
	global $g;
1813

    
1814
	if ($interface <> "") {
1815
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1816
	} else {
1817
		log_error(gettext("Resyncing OpenVPN instances."));
1818
	}
1819

    
1820
	// Check if OpenVPN clients and servers require a resync.
1821
	init_config_arr(array('openvpn', 'openvpn-server'));
1822
	init_config_arr(array('openvpn', 'openvpn-client'));
1823
	foreach (array("server", "client") as $type) {
1824
		foreach (config_get_path("openvpn/openvpn-{$type}", []) as & $settings) {
1825
			if (isset($settings['disable'])) {
1826
				continue;
1827
			}
1828
			if (!empty($protocol) &&
1829
			    ((($protocol == 'inet') && strstr($settings['protocol'], "6")) ||
1830
			    (($protocol == 'inet6') && strstr($settings['protocol'], "4")))) {
1831
				continue;
1832
			}
1833
			$fpath = "{$g['openvpn_base']}/{$type}{$settings['vpnid']}/interface";
1834
			$gw_group_change = FALSE;
1835
			$ip_change = ($interface === "") ||
1836
			    ($interface === $settings['interface']);
1837

    
1838
			if (!$ip_change && file_exists($fpath)) {
1839
				$gw_group_change =
1840
				    (trim(file_get_contents($fpath), " \t\n") !=
1841
				    get_failover_interface(
1842
					$settings['interface']));
1843
			}
1844

    
1845
			if ($ip_change || $gw_group_change) {
1846
				if (!$dirs) {
1847
					openvpn_create_dirs();
1848
				}
1849
				openvpn_resync($type, $settings);
1850
				$restarted = true;
1851
				$dirs = true;
1852
			}
1853
		}
1854
	}
1855

    
1856
	if ($restarted) {
1857
		openvpn_resync_csc_all();
1858

    
1859
		/* configure OpenVPN-parent QinQ interfaces after creating OpenVPN interfaces
1860
		 * see https://redmine.pfsense.org/issues/11662 */
1861
		if (platform_booting()) {
1862
			interfaces_qinq_configure(true);
1863
		}
1864
	}
1865
}
1866

    
1867
// Resync and restart all VPNs using a gateway group.
1868
function openvpn_resync_gwgroup($gwgroupname = "") {
1869
	if ($gwgroupname <> "") {
1870
		foreach (["server", "client"] as $mode) {
1871
			foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
1872
				if ($gwgroupname == $settings['interface']) {
1873
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s %2$s %3$s.'), $gwgroupname, $mode, $settings["description"]));
1874
					openvpn_resync('server', $settings);
1875
				}
1876
			}
1877
		}
1878
		// Note: no need to resysnc Client Specific (csc) here, as changes to the OpenVPN real interface do not effect these.
1879
	} else {
1880
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1881
	}
1882
}
1883

    
1884
function openvpn_get_active_servers($type="multipoint") {
1885
	global $g;
1886

    
1887
	$servers = array();
1888
	foreach (config_get_path('openvpn/openvpn-server', []) as $settings) {
1889
		if (empty($settings) || isset($settings['disable'])) {
1890
			continue;
1891
		}
1892

    
1893
		$prot = $settings['protocol'];
1894
		$port = $settings['local_port'];
1895

    
1896
		$server = array();
1897
		$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1898
		$server['mode'] = $settings['mode'];
1899
		if ($settings['description']) {
1900
			$server['name'] = "{$settings['description']} {$prot}:{$port}";
1901
		} else {
1902
			$server['name'] = "Server {$prot}:{$port}";
1903
		}
1904
		$server['conns'] = array();
1905
		$server['vpnid'] = $settings['vpnid'];
1906
		$server['mgmt'] = "server{$server['vpnid']}";
1907
		$socket = "unix://{$g['openvpn_base']}/{$server['mgmt']}/sock";
1908
		list($tn, $sm) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1909

    
1910
		if ((($server['mode'] == "p2p_shared_key") ||
1911
			 (($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network']) && ($server['mode'] == 'p2p_tls')) ||
1912
			 ($sm >= 30)) &&
1913
			($type == "p2p")) {
1914
			$servers[] = openvpn_get_client_status($server, $socket);
1915
		} elseif (($server['mode'] != "p2p_shared_key") &&
1916
				  !(($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network']) && ($server['mode'] == 'p2p_tls')) &&
1917
				  ($type == "multipoint") &&
1918
				  ($sm < 30)) {
1919
			$servers[] = openvpn_get_server_status($server, $socket);
1920
		}
1921
	}
1922

    
1923
	return $servers;
1924
}
1925

    
1926
function openvpn_get_server_status($server, $socket) {
1927
	$errval = null;
1928
	$errstr = null;
1929
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1930
	if ($fp) {
1931
		stream_set_timeout($fp, 1);
1932

    
1933
		/* send our status request */
1934
		fputs($fp, "status 2\n");
1935

    
1936
		/* recv all response lines */
1937
		while (!feof($fp)) {
1938

    
1939
			/* read the next line */
1940
			$line = fgets($fp, 1024);
1941

    
1942
			$info = stream_get_meta_data($fp);
1943
			if ($info['timed_out']) {
1944
				break;
1945
			}
1946

    
1947
			/* parse header list line */
1948
			if (strstr($line, "HEADER")) {
1949
				continue;
1950
			}
1951

    
1952
			/* parse end of output line */
1953
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1954
				break;
1955
			}
1956

    
1957
			/* parse client list line */
1958
			if (strstr($line, "CLIENT_LIST")) {
1959
				$list = explode(",", $line);
1960
				$conn = array();
1961
				$conn['common_name'] = $list[1];
1962
				$conn['remote_host'] = $list[2];
1963
				$conn['virtual_addr'] = $list[3];
1964
				$conn['virtual_addr6'] = $list[4];
1965
				$conn['bytes_recv'] = $list[5];
1966
				$conn['bytes_sent'] = $list[6];
1967
				$conn['connect_time'] = $list[7];
1968
				$conn['connect_time_unix'] = $list[8];
1969
				$conn['user_name'] = $list[9];
1970
				$conn['client_id'] = $list[10];
1971
				$conn['peer_id'] = $list[11];
1972
				$conn['cipher'] = $list[12];
1973
				$server['conns'][] = $conn;
1974
			}
1975
			/* parse routing table lines */
1976
			if (strstr($line, "ROUTING_TABLE")) {
1977
				$list = explode(",", $line);
1978
				$conn = array();
1979
				$conn['virtual_addr'] = $list[1];
1980
				$conn['common_name'] = $list[2];
1981
				$conn['remote_host'] = $list[3];
1982
				$conn['last_time'] = $list[4];
1983
				$server['routes'][] = $conn;
1984
			}
1985
		}
1986

    
1987
		/* cleanup */
1988
		fclose($fp);
1989
	} else {
1990
		$conn = array();
1991
		$conn['common_name'] = "[error]";
1992
		$conn['remote_host'] = gettext("Unable to contact daemon");
1993
		$conn['virtual_addr'] = gettext("Service not running?");
1994
		$conn['bytes_recv'] = 0;
1995
		$conn['bytes_sent'] = 0;
1996
		$conn['connect_time'] = 0;
1997
		$server['conns'][] = $conn;
1998
	}
1999
	return $server;
2000
}
2001

    
2002
function openvpn_get_active_clients() {
2003
	global $g;
2004

    
2005
	$clients = array();
2006
		foreach (config_get_path('openvpn/openvpn-client', []) as $settings) {
2007
			if (empty($settings) || isset($settings['disable'])) {
2008
				continue;
2009
			}
2010

    
2011
			$prot = $settings['protocol'];
2012
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
2013

    
2014
			$client = array();
2015
			$client['port'] = $settings['local_port'];
2016
			if ($settings['description']) {
2017
				$client['name'] = "{$settings['description']} {$prot}{$port}";
2018
			} else {
2019
				$client['name'] = "Client {$prot}{$port}";
2020
			}
2021

    
2022
			$client['vpnid'] = $settings['vpnid'];
2023
			$client['mgmt'] = "client{$client['vpnid']}";
2024
			$socket = "unix://{$g['openvpn_base']}/{$client['mgmt']}/sock";
2025
			$client['status']="down";
2026

    
2027
			$clients[] = openvpn_get_client_status($client, $socket);
2028
	}
2029
	return $clients;
2030
}
2031

    
2032
function openvpn_get_client_status($client, $socket) {
2033
	$errval = null;
2034
	$errstr = null;
2035
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
2036
	if ($fp) {
2037
		stream_set_timeout($fp, 1);
2038
		/* send our status request */
2039
		fputs($fp, "state 1\n");
2040

    
2041
		/* recv all response lines */
2042
		while (!feof($fp)) {
2043
			/* read the next line */
2044
			$line = fgets($fp, 1024);
2045

    
2046
			$info = stream_get_meta_data($fp);
2047
			if ($info['timed_out']) {
2048
				break;
2049
			}
2050

    
2051
			/* Get the client state */
2052
			if (substr_count($line, ',') >= 7) {
2053
				$list = explode(",", trim($line));
2054
				$list = array_map('trim', $list);
2055

    
2056
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
2057
				$client['state'] = $list[1];
2058
				$client['state_detail'] = $list[2];
2059
				$client['virtual_addr'] = $list[3];
2060
				$client['remote_host'] = $list[4];
2061
				$client['remote_port'] = $list[5];
2062
				$client['local_host'] = $list[6];
2063
				$client['local_port'] = $list[7];
2064
				$client['virtual_addr6'] = $list[8];
2065

    
2066
				switch (trim($client['state'])) {
2067
					case 'CONNECTED':
2068
						$client['status'] = gettext("Connected");
2069
						break;
2070
					case 'CONNECTING':
2071
						$client['status'] = gettext("Connecting");
2072
						break;
2073
					case 'TCP_CONNECT':
2074
						$client['status'] = gettext("Connecting to TCP Server");
2075
						break;
2076
					case 'ASSIGN_IP':
2077
						$client['status'] = gettext("Configuring Interface/Waiting");
2078
						break;
2079
					case 'WAIT':
2080
						$client['status'] = gettext("Waiting for response from peer");
2081
						break;
2082
					case 'RECONNECTING':
2083
						switch ($client['state_detail']) {
2084
							case 'server_poll':
2085
								$client['status'] = gettext("Waiting for peer connection");
2086
								$client['state_detail'] = '';
2087
								break;
2088
							case 'tls-error':
2089
								$client['status'] = gettext("TLS Error, reconnecting");
2090
								$client['state_detail'] = '';
2091
								break;
2092
							default:
2093
								$client['status'] = gettext("Reconnecting");
2094
								break;
2095
						}
2096
						break;
2097
					case 'AUTH':
2098
						$client['status'] = gettext("Authenticating");
2099
						break;
2100
					case 'AUTH_PENDING':
2101
						$client['status'] = gettext("Authentication pending");
2102
						break;
2103
					case 'GET_CONFIG':
2104
						$client['status'] = gettext("Pulling configuration from server");
2105
						break;
2106
					case 'ADD_ROUTES':
2107
						$client['status'] = gettext("Adding routes to system");
2108
						break;
2109
					case 'RESOLVE':
2110
						$client['status'] = gettext("Resolving peer hostname via DNS");
2111
						break;
2112
					default:
2113
						$client['status'] = ucwords(strtolower(str_replace(array('_', '-'), ' ', $client['state'])));
2114
						break;
2115
				}
2116

    
2117
				if (!empty($client['state_detail'])) {
2118
					$client['status'] .= " (" . ucwords(strtolower(str_replace(array('_', '-'), ' ', $client['state_detail']))) . ")";
2119
				}
2120

    
2121
			}
2122
			/* parse end of output line */
2123
			if (strstr($line, "END") || strstr($line, "ERROR")) {
2124
				break;
2125
			}
2126
		}
2127

    
2128
		/* If up, get read/write stats */
2129
		if (strcmp($client['state'], "CONNECTED") == 0) {
2130
			fputs($fp, "status 2\n");
2131
			/* recv all response lines */
2132
			while (!feof($fp)) {
2133
				/* read the next line */
2134
				$line = fgets($fp, 1024);
2135

    
2136
				$info = stream_get_meta_data($fp);
2137
				if ($info['timed_out']) {
2138
					break;
2139
				}
2140

    
2141
				if (strstr($line, "TCP/UDP read bytes")) {
2142
					$list = explode(",", $line);
2143
					$client['bytes_recv'] = $list[1];
2144
				}
2145

    
2146
				if (strstr($line, "TCP/UDP write bytes")) {
2147
					$list = explode(",", $line);
2148
					$client['bytes_sent'] = $list[1];
2149
				}
2150

    
2151
				/* parse end of output line */
2152
				if (strstr($line, "END")) {
2153
					break;
2154
				}
2155
			}
2156
		}
2157

    
2158
		fclose($fp);
2159

    
2160
	} else {
2161
		$client['remote_host'] = gettext("Unable to contact daemon");
2162
		$client['virtual_addr'] = gettext("Service not running?");
2163
		$client['bytes_recv'] = 0;
2164
		$client['bytes_sent'] = 0;
2165
		$client['connect_time'] = 0;
2166
	}
2167
	return $client;
2168
}
2169

    
2170
function openvpn_kill_client($port, $remipp, $client_id) {
2171
	global $g;
2172

    
2173
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
2174
	$tcpsrv = "unix://{$g['openvpn_base']}/{$port}/sock";
2175
	$errval = null;
2176
	$errstr = null;
2177

    
2178
	/* open a tcp connection to the management port of each server */
2179
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
2180
	$killed = -1;
2181
	if ($fp) {
2182
		stream_set_timeout($fp, 1);
2183
		if (is_numeric($client_id)) {
2184
			/* terminate remote client, see https://redmine.pfsense.org/issues/12416 */
2185
			fputs($fp, "client-kill {$client_id} HALT\n");
2186
		} else {
2187
			fputs($fp, "kill {$remipp}\n");
2188
		}
2189
		while (!feof($fp)) {
2190
			$line = fgets($fp, 1024);
2191

    
2192
			$info = stream_get_meta_data($fp);
2193
			if ($info['timed_out']) {
2194
				break;
2195
			}
2196

    
2197
			/* parse header list line */
2198
			if (strpos($line, "INFO:") !== false) {
2199
				continue;
2200
			}
2201
			if (strpos($line, "SUCCESS") !== false) {
2202
				$killed = 0;
2203
			}
2204
			break;
2205
		}
2206
		fclose($fp);
2207
	}
2208
	return $killed;
2209
}
2210

    
2211
function openvpn_refresh_crls() {
2212
	global $g;
2213

    
2214
	openvpn_create_dirs();
2215

    
2216
	foreach (config_get_path('openvpn/openvpn-server', []) as $settings) {
2217
		if (empty($settings)) {
2218
			continue;
2219
		}
2220
		if (isset($settings['disable'])) {
2221
			continue;
2222
		}
2223
		// Write the settings for the keys
2224
		switch ($settings['mode']) {
2225
		case 'p2p_tls':
2226
		case 'server_tls':
2227
		case 'server_tls_user':
2228
		case 'server_user':
2229
			$param = array('caref' => $settings['caref']);
2230
			$cas = ca_chain_array($param);
2231
			$capath = "{$g['openvpn_base']}/server{$settings['vpnid']}/ca";
2232
			if (!empty($settings['crlref'])) {
2233
				$crl = lookup_crl($settings['crlref']);
2234
				crl_update($crl);
2235
			}
2236
			foreach ($cas as $ca) {
2237
				ca_setup_capath($ca, $capath, $crl, true);
2238
			}
2239
			unset($cas, $param, $capath, $crl);
2240
			break;
2241
		}
2242
	}
2243
}
2244

    
2245
function openvpn_create_dirs() {
2246
	global $g, $openvpn_tls_server_modes;
2247
	if (!is_dir($g['openvpn_base'])) {
2248
		safe_mkdir($g['openvpn_base'], 0750);
2249
	}
2250

    
2251
	init_config_arr(array('openvpn', 'openvpn-server'));
2252
	init_config_arr(array('openvpn', 'openvpn-client'));
2253
	foreach(array('server', 'client') as $mode) {
2254
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
2255
			if (isset($settings['disable'])) {
2256
				continue;
2257
			}
2258
			$target = "{$g['openvpn_base']}/{$mode}{$settings['vpnid']}";
2259
			$csctarget = "{$target}/csc/";
2260
			@unlink_if_exists($csctarget);
2261
			@safe_mkdir($target);
2262
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2263
				@safe_mkdir($csctarget);
2264
			}
2265
		}
2266
	}
2267
}
2268

    
2269
function openvpn_get_interface_ip($ip, $cidr) {
2270
	$subnet = gen_subnetv4($ip, $cidr);
2271
	if ($cidr == 31) {
2272
		$ip1 = $subnet;
2273
	} else {
2274
		$ip1 = ip_after($subnet);
2275
	}
2276
	$ip2 = ip_after($ip1);
2277
	return array($ip1, $ip2);
2278
}
2279

    
2280
function openvpn_get_interface_ipv6($ipv6, $prefix) {
2281
	$basev6 = gen_subnetv6($ipv6, $prefix);
2282
	// Is there a better way to do this math?
2283
	$ipv6_arr = explode(':', $basev6);
2284
	$last = hexdec(array_pop($ipv6_arr));
2285
	if ($prefix == 127) {
2286
		$last--;
2287
	}
2288
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
2289
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
2290
	return array($ipv6_1, $ipv6_2);
2291
}
2292

    
2293
function openvpn_clear_route($mode, $settings) {
2294
	if (empty($settings['tunnel_network'])) {
2295
		return;
2296
	}
2297
	list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
2298
	$mask = gen_subnet_mask($cidr);
2299
	$clear_route = false;
2300

    
2301
	switch ($settings['mode']) {
2302
		case 'shared_key':
2303
			$clear_route = true;
2304
			break;
2305
		case 'p2p_tls':
2306
		case 'p2p_shared_key':
2307
			if ($cidr >= 30) {
2308
				$clear_route = true;
2309
			}
2310
			break;
2311
	}
2312

    
2313
	if ($clear_route && !empty($ip) && !empty($mask)) {
2314
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2315
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2316
		/* XXX: Family for route? */
2317
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2318
	}
2319
}
2320

    
2321
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2322
	$routes = "";
2323
	$networks = array();
2324
	if (empty($value)) {
2325
		return "";
2326
	}
2327
	$tmpnetworks = explode(',', $value);
2328
	foreach ($tmpnetworks as $network) {
2329
		if (is_alias($network)) {
2330
			foreach (alias_to_subnets_recursive($network, true) as $net) {
2331
				if ((($ipproto == "ipv4") && is_subnetv4($net)) ||
2332
				    (($ipproto == "ipv6") && is_subnetv6($net))) {
2333
					$networks[] = $net;
2334
				} elseif (is_fqdn($net)) {
2335
					if ($ipproto == "ipv4" ) {
2336
						$recordtypes = array(DNS_A);
2337
						$mask = "/32";
2338
					} else {
2339
						$recordtypes = array(DNS_AAAA);
2340
						$mask = "/128";
2341
					}
2342
					$domips = resolve_host_addresses($net, $recordtypes, false);
2343
					if (!empty($domips)) {
2344
						foreach ($domips as $net) {
2345
							$networks[] = $net . $mask;
2346
						}
2347
					} else {
2348
						log_error(gettext("Failed to resolve {$net}. Skipping OpenVPN route entry."));
2349
					}
2350
				}
2351
			}
2352
		} else {
2353
			$networks[] = $network;
2354
		}
2355
	}
2356

    
2357
	foreach ($networks as $network) {
2358
		if ($ipproto == "ipv4") {
2359
			$route = openvpn_gen_route_ipv4($network, $iroute);
2360
		} else {
2361
			$route = openvpn_gen_route_ipv6($network, $iroute);
2362
		}
2363

    
2364
		if ($push) {
2365
			$routes .= "push \"{$route}\"\n";
2366
		} else {
2367
			$routes .= "{$route}\n";
2368
		}
2369
	}
2370
	return $routes;
2371
}
2372

    
2373
function openvpn_gen_route_ipv4($network, $iroute = false) {
2374
	$i = ($iroute) ? "i" : "";
2375
	list($ip, $mask) = explode('/', trim($network));
2376
	$mask = gen_subnet_mask($mask);
2377
	return "{$i}route $ip $mask";
2378
}
2379

    
2380
function openvpn_gen_route_ipv6($network, $iroute = false) {
2381
	$i = ($iroute) ? "i" : "";
2382
	list($ipv6, $prefix) = explode('/', trim($network));
2383
	if (empty($prefix) && !is_numeric($prefix)) {
2384
		$prefix = "128";
2385
	}
2386
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2387
}
2388

    
2389
function openvpn_get_settings($mode, $vpnid) {
2390
	init_config_arr(array('openvpn', 'openvpn-server'));
2391
	init_config_arr(array('openvpn', 'openvpn-client'));
2392
	foreach (["server", "client"] as $mode) {
2393
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
2394
			if (isset($settings['disable'])) {
2395
				continue;
2396
			}
2397

    
2398
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2399
				return $settings;
2400
			}
2401
		}
2402
	}
2403
	return array();
2404
}
2405

    
2406
function openvpn_restart_by_vpnid($mode, $vpnid) {
2407
	$settings = openvpn_get_settings($mode, $vpnid);
2408
	openvpn_restart($mode, $settings);
2409
}
2410

    
2411
/****f* certs/openvpn_is_tunnel_network_in_use
2412
 * NAME
2413
 *   openvpn_is_tunnel_network_in_use
2414
 *     Check if the supplied network is in use as an OpenVPN server or client
2415
 *     tunnel network
2416
 * INPUTS
2417
 *   $net : The IPv4 or IPv6 network to check
2418
 * RESULT
2419
 *   boolean value: true if the network is in use, false otherwise.
2420
 ******/
2421

    
2422
function openvpn_is_tunnel_network_in_use($net) {
2423
	init_config_arr(array('openvpn', 'openvpn-server'));
2424
	init_config_arr(array('openvpn', 'openvpn-client'));
2425
	/* Determine whether to check IPv4 or IPv6 tunnel networks */
2426
	$tocheck = 'tunnel_network';
2427
	if (is_v6($net)) {
2428
		$tocheck .= "v6";
2429
	}
2430
	/* Check all OpenVPN clients and servers for this tunnel network */
2431
	foreach(array('server', 'client') as $mode) {
2432
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $ovpn) {
2433
			if (!empty($ovpn[$tocheck]) &&
2434
			    ($ovpn[$tocheck] == $net)) {
2435
				return true;
2436
			}
2437
		}
2438
	}
2439
	return false;
2440
}
2441

    
2442
function openvpn_build_data_cipher_list($data_ciphers = 'AES-256-GCM,AES-128-GCM,CHACHA20-POLY1305', $fallback_cipher = 'AES-256-GBC', $ncp_enabled = true) {
2443
	/* If the data_ciphers list is empty, populate it with the fallback cipher. */
2444
	if (empty($data_ciphers) || !$ncp_enabled) {
2445
		$data_ciphers = $fallback_cipher;
2446
	}
2447
	/* Add the fallback cipher to the data ciphers list if it isn't already present */
2448
	if (!in_array($fallback_cipher, explode(',', $data_ciphers))) {
2449
		$data_ciphers .= ',' . $fallback_cipher;
2450
	}
2451
	return $data_ciphers;
2452
}
2453

    
2454
function openvpn_authscript_string($authmode, $strictusercn, $mode_id, $local_port) {
2455
	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";
2456
}
2457

    
2458
function openvpn_inuse($id, $mode) {
2459
	$type = ($mode == 'server') ? 's' : 'c';
2460

    
2461
	foreach (get_configured_interface_list(true) as $if) {
2462
		if (config_get_path("interfaces/{$if}/if") == "ovpn{$type}{$id}") {
2463
			return true;
2464
		}
2465
	}
2466

    
2467
	return false;
2468
}
2469

    
2470
function openvpn_tunnel_network_fix($tunnel_network) {
2471
	$tunnel_network = trim($tunnel_network);
2472
	if (is_subnet($tunnel_network)) {
2473
		/* convert to correct network address,
2474
		 * see https://redmine.pfsense.org/issues/11416 */
2475
		list($tunnel_ip, $tunnel_netmask) = explode('/', $tunnel_network);
2476
		$tunnel_network = gen_subnet($tunnel_ip, $tunnel_netmask) . '/' . $tunnel_netmask;
2477
	}
2478
	return $tunnel_network;
2479
}
2480

    
2481
?>
(34-34/62)