Project

General

Profile

Download (73.8 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-2023 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
function openvpn_name(string $mode, array $settings, string $type = 'if') : string {
214
	switch ($type) {
215
		case 'if':
216
			$prefix = ($mode == 'server') ? 'ovpns' : 'ovpnc';
217
			break;
218
		case 'dev':
219
			$prefix = array_get_path($settings, 'dev_mode', 'tun');
220
			break;
221
		case 'generic':
222
			$prefix = ($mode == 'server') ? 'server' : 'client';
223
			break;
224
		default:
225
			$prefix = '';
226
			break;
227
	}
228

    
229
	$id = array_get_path($settings, 'vpnid', '');
230
	return "{$prefix}{$id}";
231
}
232

    
233
global $openvpn_interfacenames;
234
function convert_openvpn_interface_to_friendly_descr($if) {
235
	global $openvpn_interfacenames;
236
	if (!is_array($openvpn_interfacenames)) {
237
		$openvpn_interfacenames = openvpn_build_if_list();
238
	}
239
	foreach($openvpn_interfacenames as $key => $value) {
240
		list($item_if, $item_ip) = explode("|", $key);
241
		if ($if == $item_if) {
242
			echo "$value";
243
		}
244
	}
245
}
246

    
247
function openvpn_build_if_list() {
248
	$list = array();
249

    
250
	$interfaces = get_configured_interface_with_descr();
251
	$viplist = get_configured_vip_list();
252
	foreach ($viplist as $vip => $address) {
253
		$interfaces[$vip.'|'.$address] = $address;
254
		if (get_vip_descr($address)) {
255
			$interfaces[$vip.'|'.$address] .= " (";
256
			$interfaces[$vip.'|'.$address] .= get_vip_descr($address);
257
			$interfaces[$vip.'|'.$address] .= ")";
258
		}
259
	}
260

    
261
	$grouplist = return_gateway_groups_array();
262
	foreach ($grouplist as $name => $group) {
263
		if ($group[0]['vip'] != "") {
264
			$vipif = $group[0]['vip'];
265
		} else {
266
			$vipif = $group[0]['int'];
267
		}
268

    
269
		$interfaces[$name] = "GW Group {$name}";
270
	}
271

    
272
	$interfaces['lo0'] = "Localhost";
273
	$interfaces['any'] = "any";
274

    
275
	foreach ($interfaces as $iface => $ifacename) {
276
	   $list[$iface] = $ifacename;
277
	}
278

    
279
	return($list);
280
}
281

    
282
function openvpn_build_crl_list() {
283
	global $a_crl;
284

    
285
	$list = array('' => 'None');
286

    
287
	foreach ($a_crl as $crl) {
288
		$caname = "";
289
		$ca = lookup_ca($crl['caref']);
290

    
291
		if ($ca) {
292
			$caname = " (CA: {$ca['descr']})";
293
		}
294

    
295
		$list[$crl['refid']] = $crl['descr'] . $caname;
296
	}
297

    
298
	return($list);
299
}
300

    
301
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
302
	global $a_cert;
303
	$openvpn_compatible_certs = cert_build_list('cert', 'OpenVPN');
304

    
305
	if ($include_none) {
306
		$list = array('' => gettext('None (Username and/or Password required)'));
307
	} else {
308
		$list = array();
309
	}
310

    
311
	$non_server_list = array();
312

    
313
	if ($prioritize_server_certs) {
314
		$list[' '] = gettext("===== Server Certificates =====");
315
		$non_server_list['  '] = gettext("===== Non-Server Certificates =====");
316
	}
317

    
318
	foreach ($a_cert as $cert) {
319
		if (!array_key_exists($cert['refid'], $openvpn_compatible_certs)) {
320
			continue;
321
		}
322
		$properties = array();
323
		$propstr = "";
324
		$ca = lookup_ca($cert['caref']);
325
		$purpose = cert_get_purpose($cert['crt'], true);
326

    
327
		if ($purpose['server'] == "Yes") {
328
			$properties[] = gettext("Server: Yes");
329
		} elseif ($prioritize_server_certs) {
330
			$properties[] = gettext("Server: NO");
331
		}
332
		if ($ca) {
333
			$properties[] = sprintf(gettext("CA: %s"), $ca['descr']);
334
		}
335
		if (cert_in_use($cert['refid'])) {
336
			$properties[] = gettext("In Use");
337
		}
338
		if (is_cert_revoked($cert)) {
339
			$properties[] = gettext("Revoked");
340
		}
341

    
342
		if (!empty($properties)) {
343
			$propstr = " (" . implode(", ", $properties) . ")";
344
		}
345

    
346
		if ($prioritize_server_certs) {
347
			if ($purpose['server'] == "Yes") {
348
				$list[$cert['refid']] = $cert['descr'] . $propstr;
349
			} else {
350
				$non_server_list[$cert['refid']] = $cert['descr'] . $propstr;
351
			}
352
		} else {
353
			$list[$cert['refid']] = $cert['descr'] . $propstr;
354
		}
355
	}
356

    
357
	return(array('server' => $list, 'non-server' => $non_server_list));
358
}
359

    
360
function openvpn_build_bridge_list() {
361
	$list = array();
362

    
363
	$serverbridge_interface['none'] = "none";
364
	$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
365
	$viplist = get_configured_vip_list();
366

    
367
	foreach ($viplist as $vip => $address) {
368
		$serverbridge_interface[$vip.'|'.$address] = $address;
369
		if (get_vip_descr($address)) {
370
			$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
371
		}
372
	}
373

    
374
	foreach ($serverbridge_interface as $iface => $ifacename) {
375
		$list[$iface] = htmlspecialchars($ifacename);
376
	}
377

    
378
	return($list);
379
}
380

    
381
function openvpn_create_key() {
382

    
383
	$fp = popen("/usr/local/sbin/openvpn --genkey secret /dev/stdout 2>/dev/null", "r");
384
	if (!$fp) {
385
		return false;
386
	}
387

    
388
	$rslt = stream_get_contents($fp);
389
	pclose($fp);
390

    
391
	return $rslt;
392
}
393

    
394
function openvpn_create_dhparams($bits) {
395

    
396
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
397
	if (!$fp) {
398
		return false;
399
	}
400

    
401
	$rslt = stream_get_contents($fp);
402
	pclose($fp);
403

    
404
	return $rslt;
405
}
406

    
407
function openvpn_vpnid_used($vpnid) {
408
	init_config_arr(array('openvpn', 'openvpn-server'));
409
	init_config_arr(array('openvpn', 'openvpn-client'));
410
	foreach (["server", "client"] as $mode) {
411
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
412
			if ($vpnid == $settings['vpnid']) {
413
				return true;
414
			}
415
		}
416
	}
417
	return false;
418
}
419

    
420
function openvpn_vpnid_next() {
421

    
422
	$vpnid = 1;
423
	while (openvpn_vpnid_used($vpnid)) {
424
		$vpnid++;
425
	}
426

    
427
	return $vpnid;
428
}
429

    
430
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
431

    
432
	$ovpn_settings = config_get_path('openvpn/openvpn-server', []);
433
	$ovpn_settings = array_merge($ovpn_settings, config_get_path('openvpn/openvpn-client', []));
434

    
435
	foreach ($ovpn_settings as $settings) {
436
		if (isset($settings['disable'])) {
437
			continue;
438
		}
439

    
440
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
441
			continue;
442
		}
443

    
444
		/* (TCP|UDP)(4|6) does not conflict unless interface is any */
445
		if (($interface != "any" && $settings['interface'] != "any") &&
446
		    (strlen($prot) == 4) &&
447
		    (strlen($settings['protocol']) == 4) &&
448
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
449
		    substr($prot,3,1) != substr($settings['protocol'],3,1)) {
450
			continue;
451
		}
452

    
453
		if ($port == $settings['local_port'] &&
454
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
455
		    ($interface == $settings['interface'] ||
456
		    $interface == "any" || $settings['interface'] == "any")) {
457
			return $settings['vpnid'];
458
		}
459
	}
460

    
461
	return 0;
462
}
463

    
464
function openvpn_port_next($prot, $interface = "wan") {
465

    
466
	$port = 1194;
467
	while (openvpn_port_used($prot, $interface, $port)) {
468
		$port++;
469
	}
470
	while (openvpn_port_used($prot, "any", $port)) {
471
		$port++;
472
	}
473

    
474
	return $port;
475
}
476

    
477
function openvpn_get_cipherlist() {
478

    
479
	$ciphers = array();
480
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
481
	$cipher_lines = explode("\n", trim($cipher_out));
482
	sort($cipher_lines);
483
	foreach ($cipher_lines as $line) {
484
		$words = explode(' ', $line, 2);
485
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
486
	}
487
	$ciphers["none"] = gettext("None (No Encryption)");
488
	return $ciphers;
489
}
490

    
491
function openvpn_get_curvelist() {
492
	global $cert_curve_compatible;
493
	$curves = array();
494
	$curves["none"] = gettext("Use Default");
495
	foreach ($cert_curve_compatible['OpenVPN'] as $curve) {
496
		$curves[$curve] = $curve;
497
	}
498
	return $curves;
499
}
500

    
501
function openvpn_validate_curve($curve) {
502
	$curves = openvpn_get_curvelist();
503
	return array_key_exists($curve, $curves);
504
}
505

    
506
/* Obtain the list of digest algorithms supported by openssl and their alternate names */
507
function openvpn_get_openssldigestmappings() {
508
	$digests = array();
509
	$digest_out = shell_exec('/usr/bin/openssl list -digest-algorithms | /usr/bin/grep "=>"');
510
	$digest_lines = explode("\n", trim($digest_out));
511
	sort($digest_lines);
512
	foreach ($digest_lines as $line) {
513
		$words = explode(' => ', $line, 2);
514
		$digests[$words[0]] = $words[1];
515
	}
516
	return $digests;
517
}
518

    
519
/* Obtain the list of digest algorithms supported by openvpn */
520
function openvpn_get_digestlist() {
521
	/* Grab the list from OpenSSL to check for duplicates or aliases */
522
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
523
	$digests = array();
524
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
525
	$digest_lines = explode("\n", trim($digest_out));
526
	sort($digest_lines);
527
	foreach ($digest_lines as $line) {
528
		$words = explode(' ', $line);
529
		/* Only add the entry if it is NOT also listed as being an alias/mapping by OpenSSL */
530
		if (!array_key_exists($words[0], $openssl_digest_mappings)) {
531
			$digests[$words[0]] = "{$words[0]} {$words[1]}";
532
		}
533
	}
534
	$digests["none"] = gettext("None (No Authentication)");
535
	return $digests;
536
}
537

    
538
/* Check to see if a digest name is an alias and if so, find the actual digest
539
 * algorithm instead. Useful for upgrade code that has to translate aliased
540
 * algorithms to their actual names.
541
 */
542
function openvpn_remap_digest($digest) {
543
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
544
	if (array_key_exists($digest, $openssl_digest_mappings)) {
545
		/* Some mappings point to other mappings, keep going until we find the actual digest algorithm */
546
		if (array_key_exists($openssl_digest_mappings[$digest], $openssl_digest_mappings)) {
547
			return openvpn_remap_digest($openssl_digest_mappings[$digest]);
548
		} else {
549
			return $openssl_digest_mappings[$digest];
550
		}
551
	}
552
	return $digest;
553
}
554

    
555
function openvpn_get_keydirlist() {
556
	$keydirs = array(
557
		'default'  => gettext('Use default direction'),
558
		'0' => gettext('Direction 0'),
559
		'1' => gettext('Direction 1'),
560
		'2' => gettext('Both directions'),
561
	);
562
	return $keydirs;
563
}
564

    
565
function openvpn_get_engines() {
566
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
567
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
568
	$openssl_engine_output = implode("\n", $openssl_engine_output);
569
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
570
	$openssl_engine_output = explode("\n", $openssl_engine_output);
571

    
572
	foreach ($openssl_engine_output as $oeo) {
573
		$keep = true;
574
		$details = explode("|", $oeo);
575
		$engine = array_shift($details);
576
		$linematch = array();
577
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
578
		foreach ($details as $dt) {
579
			if (strpos($dt, "unavailable") !== FALSE) {
580
				$keep = false;
581
			}
582
			if (strpos($dt, "available") !== FALSE) {
583
				continue;
584
			}
585
			if (strpos($dt, "[") !== FALSE) {
586
				$ciphers = trim($dt, "[]");
587
			}
588
		}
589
		if (!empty($ciphers)) {
590
			$ciphers = " - " . $ciphers;
591
		}
592
		if (strlen($ciphers) > 60) {
593
			$ciphers = substr($ciphers, 0, 60) . " ... ";
594
		}
595
		if ($keep) {
596
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
597
		}
598
	}
599
	return $openssl_engines;
600
}
601

    
602
function openvpn_get_buffer_values() {
603
	$sendbuf_max = get_single_sysctl('net.inet.tcp.sendbuf_max');
604
	$recvbuf_max = get_single_sysctl('net.inet.tcp.recvbuf_max');
605
	/* Usually these two are equal, but if they are not, take whichever one is lower. */
606
	$buffer_max = ($sendbuf_max <= $recvbuf_max) ? $sendbuf_max : $recvbuf_max;
607
	$buffer_values = array('' => gettext('Default'));
608
	for ($bs = 32; $bs >= 1; $bs /= 2) {
609
		$buffer_values[$buffer_max/$bs] = format_bytes($buffer_max/$bs);
610
	}
611
	return $buffer_values;
612
}
613

    
614
function openvpn_validate_engine($engine) {
615
	$engines = openvpn_get_engines();
616
	return array_key_exists($engine, $engines);
617
}
618

    
619
function openvpn_validate_host($value, $name) {
620
	$value = trim($value);
621
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
622
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
623
	}
624
	return false;
625
}
626

    
627
function openvpn_validate_port($value, $name, $first_port = 0) {
628
	$value = trim($value);
629
	if (!is_numeric($first_port)) {
630
		$first_port = 0;
631
	}
632
	if (empty($value) || !is_numeric($value) || $value < $first_port || ($value > 65535)) {
633
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from %s to 65535."), $name, $first_port);
634
	}
635
	return false;
636
}
637

    
638
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4", $alias = false) {
639
	$value = trim($value);
640
	$error = false;
641
	if (empty($value)) {
642
		return false;
643
	}
644
	$networks = explode(',', $value);
645

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

    
650
	foreach ($networks as $network) {
651
		if ($ipproto == "ipv4") {
652
			$error = !openvpn_validate_cidr_ipv4($network, $alias);
653
		} else {
654
			$error = !openvpn_validate_cidr_ipv6($network, $alias);
655
		}
656
		if ($error) {
657
			break;
658
		}
659
	}
660

    
661
	if ($error) {
662
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) or FQDN(s) separated by commas."), $name, $ipproto);
663
	} else {
664
		return false;
665
	}
666
}
667

    
668
function openvpn_validate_cidr_ipv4($value, $alias = false) {
669
	$value = trim($value);
670
	if (!empty($value)) {
671
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
672
			foreach (alias_to_subnets_recursive($value, true) as $net) {
673
				if (!is_subnetv4($net) && !is_fqdn($net)) {
674
					return false;
675
				}
676
			}
677
			return true;
678
		} else {
679
			if (!is_subnetv4($value)) {
680
				return false;
681
			}
682
		}
683
	}
684
	return true;
685
}
686

    
687
function openvpn_validate_cidr_ipv6($value, $alias = false) {
688
	$value = trim($value);
689
	if (!empty($value)) {
690
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
691
			foreach (alias_to_subnets_recursive($value, true) as $net) {
692
				if (!is_subnetv6($net) && !is_fqdn($net)) {
693
					return false;
694
				}
695
			}
696
			return true;
697
		} else {
698
			list($ipv6, $prefix) = explode('/', $value);
699
			if (empty($prefix)) {
700
				$prefix = "128";
701
			}
702
			if (!is_subnetv6($ipv6 . '/' . $prefix)) {
703
				return false;
704
			}
705
		}
706
	}
707
	return true;
708
}
709

    
710
function openvpn_validate_tunnel_network($value, $ipproto) {
711
	$value = trim($value);
712
	if (!empty($value)) {
713
		if (is_alias($value) && (alias_get_type($value) == 'network')) {
714
			$net = alias_to_subnets_recursive($value);
715
			if ((!is_subnetv4($net[0]) && ($ipproto == 'ipv4')) ||
716
			    (!is_subnetv6($net[0]) && ($ipproto == 'ipv6')) ||
717
			    (count($net) > 1)) {
718
				return false;
719
			}
720
			return true;
721
		} else {
722
			if ((!is_subnetv4($value) && ($ipproto == 'ipv4')) ||
723
			    (!is_subnetv6($value) && ($ipproto == 'ipv6'))) { 
724
				return false;
725
			}
726
		}
727
	}
728
	return true;
729
}
730

    
731
function openvpn_gen_tunnel_network($tunnel_network) {
732
	if (is_alias($tunnel_network)) {
733
		$net = alias_to_subnets_recursive($tunnel_network);
734
		$pair = openvpn_tunnel_network_fix($net[0]);
735
	} else {
736
		$pair = $tunnel_network;
737
	}
738
	return explode('/', $pair);
739
}
740

    
741
function openvpn_add_dhcpopts(& $settings, & $conf) {
742

    
743
	if (!empty($settings['dns_domain'])) {
744
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
745
	}
746

    
747
	if (!empty($settings['dns_server1'])) {
748
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
749
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
750
	}
751
	if (!empty($settings['dns_server2'])) {
752
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
753
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
754
	}
755
	if (!empty($settings['dns_server3'])) {
756
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
757
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
758
	}
759
	if (!empty($settings['dns_server4'])) {
760
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
761
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
762
	}
763

    
764
	if (!empty($settings['push_blockoutsidedns'])) {
765
		$conf .= "push \"block-outside-dns\"\n";
766
	}
767
	if (!empty($settings['push_register_dns'])) {
768
		$conf .= "push \"register-dns\"\n";
769
	}
770

    
771
	if (!empty($settings['ntp_server1'])) {
772
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
773
	}
774
	if (!empty($settings['ntp_server2'])) {
775
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
776
	}
777

    
778
	if ($settings['netbios_enable']) {
779

    
780
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
781
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
782
		}
783
		if (!empty($settings['dhcp_nbtscope'])) {
784
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
785
		}
786

    
787
		if (!empty($settings['wins_server1'])) {
788
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
789
		}
790
		if (!empty($settings['wins_server2'])) {
791
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
792
		}
793

    
794
		if (!empty($settings['nbdd_server1'])) {
795
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
796
		}
797
	}
798

    
799
	if ($settings['gwredir']) {
800
		$conf .= "push \"redirect-gateway def1\"\n";
801
	}
802
	if ($settings['gwredir6']) {
803
		$conf .= "push \"redirect-gateway ipv6\"\n";
804
	}
805
}
806

    
807
function openvpn_add_custom(& $settings, & $conf) {
808

    
809
	if ($settings['custom_options']) {
810

    
811
		$options = explode(';', $settings['custom_options']);
812

    
813
		if (is_array($options)) {
814
			foreach ($options as $option) {
815
				$conf .= "$option\n";
816
			}
817
		} else {
818
			$conf .= "{$settings['custom_options']}\n";
819
		}
820
	}
821
}
822

    
823
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
824
	global $g;
825

    
826
	$fpath = "{$g['openvpn_base']}/{$mode_id}/{$directive}";
827
	openvpn_create_dirs();
828
	file_put_contents($fpath, base64_decode($data));
829
	//chown($fpath, 'nobody');
830
	//chgrp($fpath, 'nobody');
831
	@chmod($fpath, 0600);
832

    
833
	$conf .= "{$directive} {$fpath} {$opt}\n";
834
}
835

    
836
function openvpn_delete_tmp($mode, $id) {
837
	global $g;
838

    
839
	/* delete temporary files created by connect script */
840
	if (($mode == "server") && (isset($id))) {
841
		unlink_if_exists("{$g['tmp_path']}/ovpn_ovpns{$id}_*.rules");
842
	}
843

    
844
	/* delete temporary files created by OpenVPN; only delete old files to
845
	 * avoid deleting files potentially still in use by another OpenVPN process
846
	*/
847
	$tmpfiles = array_filter(glob("{$g['tmp_path']}/openvpn_cc*.tmp"),'is_file');
848
	if (!empty($tmpfiles)) {
849
		foreach ($tmpfiles as $tmpfile) {
850
			if ((time() - filemtime($tmpfile)) > 60) {
851
				@unlink_if_exists($tmpfile);
852
			}
853
		}
854
	}
855
}
856

    
857
function openvpn_reconfigure($mode, $settings) {
858
	global $g, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
859

    
860
	if (empty($settings)) {
861
		return;
862
	}
863
	if (isset($settings['disable'])) {
864
		return;
865
	}
866
	openvpn_create_dirs();
867
	/*
868
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
869
	 * we use a vpnid number which is allocated for a particular client
870
	 * or server configuration. ( see openvpn_vpnid_next() )
871
	 */
872

    
873
	$vpnid = $settings['vpnid'];
874
	$mode_id = openvpn_name($mode, $settings, 'generic');
875
	/* defaults to tun */
876
	if (!isset($settings['dev_mode'])) {
877
		$settings['dev_mode'] = "tun";
878
	}
879
	$tunname = openvpn_name($mode, $settings, 'dev');
880
	$devname = openvpn_name($mode, $settings);
881

    
882
	/* is our device already configured */
883
	if (!does_interface_exist($devname)) {
884

    
885
		/* create the tap device if required */
886
		if (!file_exists("/dev/{$tunname}")) {
887
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
888
		}
889

    
890
		/* rename the device */
891
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
892

    
893
		/* add the device to the openvpn group */
894
		mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " group openvpn");
895

    
896
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
897
		$grouptmp = link_interface_to_group($ifname);
898
		if (!empty($grouptmp)) {
899
			array_walk($grouptmp, 'interface_group_add_member');
900
		}
901
		unset($grouptmp, $ifname);
902
	}
903

    
904
	$pfile = g_get('varrun_path') . "/openvpn_{$mode_id}.pid";
905
	$proto = strtolower($settings['protocol']);
906
	if (substr($settings['protocol'], 0, 3) == "TCP") {
907
			$proto = "{$proto}-{$mode}";
908
	}
909
	$dev_mode = $settings['dev_mode'];
910
	$fbcipher = $settings['data_ciphers_fallback'];
911
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
912
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
913

    
914
	$interface = $settings['interface'];
915
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
916
	$ipaddr = $settings['ipaddr'];
917

    
918
	// If a specific ip address (VIP) is requested, use it.
919
	// Otherwise, if a specific interface is requested, use it
920
	// If "any" interface was selected, local directive will be omitted.
921
	if (is_ipaddrv4($ipaddr)) {
922
		$iface_ip = $ipaddr;
923
	} elseif (!empty($interface) && strcmp($interface, "any")) {
924
		$iface_ip=get_interface_ip($interface);
925
	}
926
	if (is_ipaddrv6($ipaddr)) {
927
		$iface_ipv6 = $ipaddr;
928
	} elseif (!empty($interface) && strcmp($interface, "any")) {
929
		/* get correct interface name for 6RD/6to4 interfaces
930
		 * see https://redmine.pfsense.org/issues/11674 */
931
		if (is_stf_interface($settings['interface'])) {
932
			$iface_ipv6=get_interface_ipv6($settings['interface']);
933
		} else {
934
			$iface_ipv6=get_interface_ipv6($interface);
935
		}
936
	}
937

    
938
	$conf = "dev {$devname}\n";
939
	if (isset($settings['verbosity_level'])) {
940
		$conf .= "verb {$settings['verbosity_level']}\n";
941
	}
942

    
943
	$conf .= "dev-type {$settings['dev_mode']}\n";
944
	$conf .= "dev-node /dev/{$tunname}\n";
945
	$conf .= "writepid {$pfile}\n";
946
	$conf .= "#user nobody\n";
947
	$conf .= "#group nobody\n";
948
	$conf .= "script-security 3\n";
949
	$conf .= "daemon\n";
950

    
951
	if (!empty($settings['ping_method']) &&
952
	    $settings['ping_method'] == 'ping') {
953
		$conf .= "ping {$settings['ping_seconds']}\n";
954

    
955
		if (!empty($settings['ping_push'])) {
956
			$conf .= "push \"ping {$settings['ping_seconds']}\"\n";
957
		}
958

    
959
		$action = str_replace("_", "-", $settings['ping_action']);
960
		$conf .= "{$action} {$settings['ping_action_seconds']}\n";
961

    
962
		if (!empty($settings['ping_action_push'])) {
963
			$conf .= "push \"{$action} " .
964
			    "{$settings['ping_action_seconds']}\"\n";
965
		}
966
	} else {
967
		$conf .= "keepalive " .
968
		    ($settings['keepalive_interval']
969
			?: $openvpn_default_keepalive_interval) . " " .
970
		    ($settings['keepalive_timeout']
971
			?: $openvpn_default_keepalive_timeout) . "\n";
972
	}
973

    
974
	$conf .= "ping-timer-rem\n";
975
	$conf .= "persist-tun\n";
976
	$conf .= "persist-key\n";
977
	$conf .= "proto {$proto}\n";
978
	$conf .= "auth {$digest}\n";
979
	if ($settings['dns_add']) {
980
		$conf .= "up /usr/local/sbin/ovpn-dnslinkup\n";
981
	} else {
982
		$conf .= "up /usr/local/sbin/ovpn-linkup\n";
983
	}
984
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
985
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
986
		switch ($settings['mode']) {
987
			case 'server_user':
988
			case 'server_tls_user':
989
			case 'server_tls':
990
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
991
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
992
				break;
993
		}
994
	}
995
	if ($settings['dev_mode'] === 'tun' && config_path_enabled('unbound') &&
996
		config_path_enabled('unbound','regovpnclients')) {
997
		if (($settings['mode'] == 'server_tls') || ($settings['mode'] == 'server_tls_user') ||
998
		    (($settings['mode'] == 'server_user') && ($settings['username_as_common_name'] == 'enabled'))) {
999
			$domain = !empty($settings['dns_domain']) ? $settings['dns_domain'] : config_get_path('system/domain');
1000
			if (is_domain($domain)) {
1001
				$conf .= "learn-address \"/usr/local/sbin/openvpn.learn-address.sh $domain\"\n";
1002
			}
1003
		}
1004
	}
1005

    
1006
	/*
1007
	 * When binding specific address, wait cases where interface is in
1008
	 * tentative state otherwise it will fail
1009
	 */
1010
	$wait_tentative = false;
1011

    
1012
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
1013
	switch ($settings['protocol']) {
1014
		case 'UDP':
1015
		case 'TCP':
1016
			$conf .= "multihome\n";
1017
			break;
1018
		case 'UDP4':
1019
		case 'TCP4':
1020
			if (is_ipaddrv4($iface_ip)) {
1021
				$conf .= "local {$iface_ip}\n";
1022
			}
1023
			if ($settings['interface'] == "any") {
1024
				$conf .= "multihome\n";
1025
			}
1026
			break;
1027
		case 'UDP6':
1028
		case 'TCP6':
1029
			if (is_ipaddrv6($iface_ipv6)) {
1030
				$conf .= "local {$iface_ipv6}\n";
1031
				$wait_tentative = true;
1032
			}
1033
			if ($settings['interface'] == "any") {
1034
				$conf .= "multihome\n";
1035
			}
1036
			break;
1037
		default:
1038
	}
1039

    
1040
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
1041
		$conf .= "engine {$settings['engine']}\n";
1042
	}
1043

    
1044
	// server specific settings
1045
	if ($mode == 'server') {
1046

    
1047
		list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1048
		list($ipv6, $prefix) = openvpn_gen_tunnel_network($settings['tunnel_networkv6']);
1049
		$mask = gen_subnet_mask($cidr);
1050

    
1051
		// configure tls modes
1052
		switch ($settings['mode']) {
1053
			case 'p2p_tls':
1054
			case 'server_tls':
1055
			case 'server_user':
1056
			case 'server_tls_user':
1057
				$conf .= "tls-server\n";
1058
				break;
1059
		}
1060

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

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

    
1173
		// The local port to listen on
1174
		$conf .= "lport {$settings['local_port']}\n";
1175

    
1176
		// The management port to listen on
1177
		// Use unix socket to overcome the problem on any type of server
1178
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1179
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
1180

    
1181
		if ($settings['maxclients']) {
1182
			$conf .= "max-clients {$settings['maxclients']}\n";
1183
		}
1184

    
1185
		// Can we push routes, and should we?
1186
		if ($settings['local_network'] && !$settings['gwredir']) {
1187
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1188
		}
1189
		if ($settings['local_networkv6'] && !$settings['gwredir6']) {
1190
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1191
		}
1192

    
1193
		switch ($settings['mode']) {
1194
			case 'server_tls':
1195
			case 'server_user':
1196
			case 'server_tls_user':
1197
				// Configure client dhcp options
1198
				openvpn_add_dhcpopts($settings, $conf);
1199
				if ($settings['client2client']) {
1200
					$conf .= "client-to-client\n";
1201
				}
1202
				break;
1203
		}
1204
		$connlimit = "0";
1205
		if ($settings['mode'] != 'p2p_shared_key' &&
1206
		    isset($settings['duplicate_cn'])) {
1207
			$conf .= "duplicate-cn\n";
1208
			if ($settings['connlimit']) {
1209
				$connlimit = "{$settings['connlimit']}";
1210
			}
1211
		}
1212
		if (($settings['mode'] != 'p2p_shared_key') &&
1213
		    isset($settings['remote_cert_tls'])) {
1214
			$conf .= "remote-cert-tls client\n";
1215
		}
1216
	}
1217

    
1218
	// client specific settings
1219

    
1220
	if ($mode == 'client') {
1221

    
1222
		$add_pull = false;
1223
		// configure p2p mode
1224
		if ($settings['mode'] == 'p2p_tls') {
1225
			$conf .= "tls-client\n";
1226
		}
1227

    
1228
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1229
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1230
		//  ensure a random source port.
1231
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1232
			$conf .= "nobind\n";
1233
		} elseif ($settings['local_port']) {
1234
			$conf .= "lport {$settings['local_port']}\n";
1235
		} else {
1236
			$conf .= "lport 0\n";
1237
		}
1238

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

    
1242
		// The remote server
1243
		$remoteproto = strtolower($settings['protocol']);
1244
		if (substr($remoteproto, 0, 3) == "tcp") {
1245
			$remoteproto .= "-{$mode}";
1246
		}
1247
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']} {$remoteproto}\n";
1248

    
1249
		if (!empty($settings['use_shaper'])) {
1250
			$conf .= "shaper {$settings['use_shaper']}\n";
1251
		}
1252

    
1253
		if (!empty($settings['tunnel_network'])) {
1254
			list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1255
			$mask = gen_subnet_mask($cidr);
1256
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1257
			if (($settings['dev_mode'] == 'tun') &&
1258
			    (($settings['topology'] == 'net30') ||
1259
			    ($cidr >= 30))) {
1260
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1261
			} else {
1262
				$conf .= "ifconfig {$ip2} {$mask}\n";
1263
				if ($settings['mode'] == 'p2p_tls') {
1264
					$add_pull = true;
1265
				}
1266
			}
1267
		}
1268

    
1269
		if (!empty($settings['tunnel_networkv6'])) {
1270
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1271
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1272
			if ($settings['dev_mode'] == 'tun') {
1273
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1274
			} else {
1275
				$conf .= "ifconfig-ipv6 {$ipv6_1}/{$prefix} {$ipv6_2}\n";
1276
				if ($settings['mode'] == 'p2p_tls') {
1277
					$add_pull = true;
1278
				}
1279
			}
1280
		}
1281

    
1282
		/* If both tunnel networks are empty, then pull from server. */
1283
		if (empty($settings['tunnel_network']) &&
1284
		    empty($settings['tunnel_networkv6'])) {
1285
			$add_pull = true;
1286
		}
1287

    
1288
		/* Only add "pull" if the tunnel network is undefined or using tap mode.
1289
		   OpenVPN can't pull settings from a server in point-to-point mode. */
1290
		if (($settings['mode'] == 'p2p_tls') && $add_pull) {
1291
			$conf .= "pull\n";
1292
		}
1293

    
1294
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
1295
			$up_file = "{$g['openvpn_base']}/{$mode_id}/up";
1296
			$conf .= "auth-user-pass {$up_file}\n";
1297
			if (!$settings['auth-retry-none']) {
1298
				$conf .= "auth-retry nointeract\n";
1299
			}
1300
			if ($settings['auth_user']) {
1301
				$userpass = "{$settings['auth_user']}\n";
1302
			} else {
1303
				$userpass = "";
1304
			}
1305
			if ($settings['auth_pass']) {
1306
				$userpass .= "{$settings['auth_pass']}\n";
1307
			}
1308
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
1309
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
1310
				$userpass .= "\n";
1311
			}
1312
			file_put_contents($up_file, $userpass);
1313
		}
1314

    
1315
		if ($settings['proxy_addr']) {
1316
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1317
			if ($settings['proxy_authtype'] != "none") {
1318
				$conf .= " {$g['openvpn_base']}/{$mode_id}/proxy_auth {$settings['proxy_authtype']}";
1319
				$proxypas = "{$settings['proxy_user']}\n";
1320
				$proxypas .= "{$settings['proxy_passwd']}\n";
1321
				file_put_contents("{$g['openvpn_base']}/{$mode_id}/proxy_auth", $proxypas);
1322
			}
1323
			$conf .= " \n";
1324
		}
1325

    
1326
		if (($settings['mode'] != 'shared_key') &&
1327
		    isset($settings['remote_cert_tls'])) {
1328
			$conf .= "remote-cert-tls server\n";
1329
		}
1330
	}
1331

    
1332
	// Add a remote network route if set, and only for p2p modes.
1333
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4", true) === FALSE)) {
1334
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1335
	}
1336
	// Add a remote network route if set, and only for p2p modes.
1337
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6", true) === FALSE)) {
1338
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1339
	}
1340

    
1341
	// Write the settings for the keys
1342
	switch ($settings['mode']) {
1343
		case 'p2p_shared_key':
1344
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
1345
			break;
1346
		case 'p2p_tls':
1347
		case 'server_tls':
1348
		case 'server_tls_user':
1349
		case 'server_user':
1350
			// ca_chain_array() expects parameter to be passed by reference.
1351
			// avoid passing the whole settings array, as param names or
1352
			// types might change in future releases.
1353
			$param = array('caref' => $settings['caref']);
1354
			$cas = ca_chain_array($param);
1355
			$capath = "{$g['openvpn_base']}/{$mode_id}/ca";
1356
			/* Cleanup old CA/CRL references */
1357
			@unlink_if_exists("{$capath}/*.0");
1358
			@unlink_if_exists("{$capath}/*.r*");
1359
			/* Find the CRL listed in the settings */
1360
			if (!empty($settings['crlref'])) {
1361
				$crl = lookup_crl($settings['crlref']);
1362
				crl_update($crl);
1363
			}
1364
			/* For each CA in the chain, setup the CApath */
1365
			foreach ($cas as $ca) {
1366
				ca_setup_capath($ca, $capath, $crl);
1367
			}
1368
			$conf .= "capath {$capath}\n";
1369
			unset($cas, $param);
1370

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

    
1429
	/* Data encryption cipher support.
1430
	 * If it is not set, assume enabled since that is OpenVPN's default.
1431
	 * Note that diabling this is now deprecated and will be removed in a future version of OpenVPN */
1432
	if ($settings['mode'] == "p2p_shared_key") {
1433
		$conf .= "cipher {$fbcipher}\n";
1434
	} else {
1435
		$conf .= "data-ciphers " . str_replace(',', ':', openvpn_build_data_cipher_list($settings['data_ciphers'], $fbcipher)) . "\n";
1436
		$conf .= "data-ciphers-fallback {$fbcipher}\n";
1437
	}
1438

    
1439
	if (!empty($settings['allow_compression'])) {
1440
		$conf .= "allow-compression {$settings['allow_compression']}\n";
1441
	}
1442

    
1443
	$compression = "";
1444
	switch ($settings['compression']) {
1445
		case 'none':
1446
			$settings['compression'] = '';
1447
		case 'lz4':
1448
		case 'lz4-v2':
1449
		case 'lzo':
1450
		case 'stub':
1451
		case 'stub-v2':
1452
			$compression .= "compress {$settings['compression']}";
1453
			break;
1454
		case 'noadapt':
1455
			$compression .= "comp-noadapt";
1456
			break;
1457
		case 'adaptive':
1458
		case 'yes':
1459
		case 'no':
1460
			$compression .= "comp-lzo {$settings['compression']}";
1461
			break;
1462
		default:
1463
			/* Add nothing to the configuration */
1464
			break;
1465
	}
1466

    
1467
	if (($settings['allow_compression'] != 'no') &&
1468
	    !empty($compression)) {
1469
		$conf .= "{$compression}\n";
1470
		if ($settings['compression_push']) {
1471
			$conf .= "push \"{$compression}\"\n";
1472
		}
1473
	}
1474

    
1475
	if ($settings['passtos']) {
1476
		$conf .= "passtos\n";
1477
	}
1478

    
1479
	if ($mode == 'client') {
1480
		$conf .= "resolv-retry infinite\n";
1481
	}
1482

    
1483
	if ($settings['dynamic_ip']) {
1484
		$conf .= "persist-remote-ip\n";
1485
		$conf .= "float\n";
1486
	}
1487

    
1488
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1489
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1490
		if (empty($settings['topology'])) {
1491
			$settings['topology'] = "subnet";
1492
		}
1493
		$conf .= "topology {$settings['topology']}\n";
1494
	}
1495

    
1496
	// New client features
1497
	if ($mode == "client") {
1498
		// Dont add/remove routes checkbox
1499
		if ($settings['route_no_exec']) {
1500
			$conf .= "route-noexec\n";
1501
		}
1502
	}
1503

    
1504
	/* UDP Fast I/O. Only compatible with UDP and also not compatible with OpenVPN's "shaper" directive. */
1505
	if ($settings['udp_fast_io']
1506
	    && (strtolower(substr($settings['protocol'], 0, 3)) == "udp")
1507
	    && (empty($settings['use_shaper']))) {
1508
		$conf .= "fast-io\n";
1509
	}
1510

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

    
1532
	/* Inactive Seconds
1533
	 * Has similar restrictions to Exit Notify (above) but only for server mode.
1534
	 */
1535
	if (!empty($settings['inactive_seconds']) &&
1536
	    !(($mode == "server") && (($settings['mode'] == 'p2p_shared_key') || (($cidr >= 30) || empty($ip))))) {
1537
		$conf .= "inactive {$settings['inactive_seconds']}\n";
1538
	}
1539

    
1540
	/* Send and Receive Buffer Settings */
1541
	if (is_numericint($settings['sndrcvbuf'])
1542
	    && ($settings['sndrcvbuf'] > 0)
1543
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1544
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1545
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1546
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1547
	}
1548

    
1549
	openvpn_add_custom($settings, $conf);
1550

    
1551
	/* add nopull option after custom options, see https://redmine.pfsense.org/issues/11448 */
1552
	if (($mode == "client") && $settings['route_no_pull']) {
1553
		// Dont pull routes checkbox
1554
		$conf .= "route-nopull\n";
1555
	}
1556

    
1557
	openvpn_create_dirs();
1558
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1559
	file_put_contents($fpath, $conf);
1560
	unset($conf);
1561
	$fpath = "{$g['openvpn_base']}/{$mode_id}/interface";
1562
	file_put_contents($fpath, get_failover_interface($interface));
1563
	$fpath = "{$g['openvpn_base']}/{$mode_id}/connuserlimit";
1564
	file_put_contents($fpath, $connlimit);
1565
	//chown($fpath, 'nobody');
1566
	//chgrp($fpath, 'nobody');
1567
	@chmod("{$g['openvpn_base']}/{$mode_id}/config.ovpn", 0600);
1568
	@chmod("{$g['openvpn_base']}/{$mode_id}/interface", 0600);
1569
	@chmod("{$g['openvpn_base']}/{$mode_id}/key", 0600);
1570
	@chmod("{$g['openvpn_base']}/{$mode_id}/tls-auth", 0600);
1571
	@chmod("{$g['openvpn_base']}/{$mode_id}/conf", 0600);
1572
	@chmod("{$g['openvpn_base']}/{$mode_id}/connuserlimit", 0600);
1573

    
1574
	if ($wait_tentative) {
1575
		interface_wait_tentative($interface);
1576
	}
1577
}
1578

    
1579
function openvpn_restart($mode, $settings) {
1580
	global $g;
1581

    
1582
	$vpnid = $settings['vpnid'];
1583
	$mode_id = openvpn_name($mode, $settings, 'generic');
1584
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1585
	openvpn_reconfigure($mode, $settings);
1586
	/* kill the process if running */
1587
	$pfile = g_get('varrun_path')."/openvpn_{$mode_id}.pid";
1588
	if (file_exists($pfile)) {
1589

    
1590
		/* read the pid file */
1591
		$pid = rtrim(file_get_contents($pfile));
1592
		unlink($pfile);
1593
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1594

    
1595
		/* send a term signal to the process */
1596
		posix_kill($pid, SIGTERM);
1597

    
1598
		/* wait until the process exits, or timeout and kill it */
1599
		$i = 0;
1600
		while (posix_kill($pid, 0)) {
1601
			usleep(250000);
1602
			if ($i > 10) {
1603
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1604
				posix_kill($pid, SIGKILL);
1605
				usleep(500000);
1606
			}
1607
			$i++;
1608
		}
1609
	}
1610

    
1611
	if (isset($settings['disable'])) {
1612
		openvpn_delete($mode, $settings);
1613
		unlock($lockhandle);
1614
		return;
1615
	}
1616

    
1617
	openvpn_delete_tmp($mode, $vpnid);
1618

    
1619
	/* Do not start an instance if we are not CARP master on this vip! */
1620
	if (strstr($settings['interface'], "_vip")) {
1621
	       	$carpstatus = get_carp_bind_status($settings['interface']);
1622
		/* Do not start an instance if vip aliased to BACKUP CARP
1623
		 * see https://redmine.pfsense.org/issues/11793 */ 
1624
		if (in_array($carpstatus, array('BACKUP', 'INIT'))) {
1625
			unlock($lockhandle);
1626
			return;
1627
		} 
1628
	}
1629

    
1630
	/* Check if client is bound to a gateway group */
1631
	$a_groups = return_gateway_groups_array(true);
1632
	if (is_array($a_groups[$settings['interface']])) {
1633
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1634
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1635
			unlock($lockhandle);
1636
			return;
1637
		}
1638
	}
1639

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

    
1665
function openvpn_delete($mode, $settings) {
1666
	global $g;
1667

    
1668
	$vpnid = $settings['vpnid'];
1669
	$mode_id = openvpn_name($mode, $settings, 'generic');
1670

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

    
1675
		/* read the pid file */
1676
		$pid = trim(file_get_contents($pfile));
1677
		unlink($pfile);
1678

    
1679
		/* send a term signal to the process */
1680
		posix_kill($pid, SIGTERM);
1681
	}
1682

    
1683
	/* destroy the device */
1684
	pfSense_interface_destroy(openvpn_name($mode, $settings));
1685

    
1686
	/* Invalidate cache */
1687
	get_interface_arr(true);
1688

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

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

    
1704
	if (empty($settings['server_list'])) {
1705
		$csc_server_list = array();
1706
	} else {
1707
		$csc_server_list = explode(",", $settings['server_list']);
1708
	}
1709

    
1710
	$conf = '';
1711
	if ($settings['block']) {
1712
		$conf .= "disable\n";
1713
	}
1714

    
1715
	if ($settings['push_reset']) {
1716
		$conf .= "push-reset\n";
1717
	}
1718

    
1719
	if ($settings['remove_route']) {
1720
		$conf .= "push-remove route\n";
1721
	}
1722

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

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

    
1739
	openvpn_add_dhcpopts($settings, $conf);
1740

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

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

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

    
1771
				file_put_contents($csc_path, $csc_conf);
1772
				chown($csc_path, 'nobody');
1773
				chgrp($csc_path, 'nobody');
1774
			}
1775
		}
1776
	}
1777
}
1778

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

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

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

    
1808
// Resync the configuration and restart the VPN
1809
function openvpn_resync($mode, $settings) {
1810
	openvpn_restart($mode, $settings);
1811
}
1812

    
1813
// Resync and restart all VPNs
1814
function openvpn_resync_all($interface = "", $protocol = "") {
1815
	global $g;
1816

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

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

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

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

    
1859
	if ($restarted) {
1860
		openvpn_resync_csc_all();
1861

    
1862
		/* configure OpenVPN-parent QinQ interfaces after creating OpenVPN interfaces
1863
		 * see https://redmine.pfsense.org/issues/11662 */
1864
		if (platform_booting()) {
1865
			interfaces_qinq_configure(true);
1866
			/* Configure all qinq interface addresses and add them to their
1867
			 * bridges. See https://redmine.pfsense.org/issues/13225,
1868
			 * https://redmine.pfsense.org/issues/13666 */
1869
			foreach (config_get_path('interfaces', []) as $ifname => $iface) {
1870
				$qinq = interface_is_qinq($iface['if']);
1871
				if ($qinq && strstr($qinq['if'], "ovpn")) {
1872
					interface_configure($ifname);
1873
				}
1874
			}
1875
		}
1876
	}
1877
}
1878

    
1879
// Resync and restart all VPNs using a gateway group.
1880
function openvpn_resync_gwgroup($gwgroupname = "") {
1881
	if ($gwgroupname <> "") {
1882
		foreach (["server", "client"] as $mode) {
1883
			foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
1884
				if ($gwgroupname == $settings['interface']) {
1885
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s %2$s %3$s.'), $gwgroupname, $mode, $settings["description"]));
1886
					openvpn_resync('server', $settings);
1887
				}
1888
			}
1889
		}
1890
		// Note: no need to resysnc Client Specific (csc) here, as changes to the OpenVPN real interface do not effect these.
1891
	} else {
1892
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1893
	}
1894
}
1895

    
1896
function openvpn_get_active_servers($type="multipoint") {
1897
	global $g;
1898

    
1899
	$servers = array();
1900
	foreach (config_get_path('openvpn/openvpn-server', []) as $settings) {
1901
		if (empty($settings) || isset($settings['disable'])) {
1902
			continue;
1903
		}
1904

    
1905
		$prot = $settings['protocol'];
1906
		$port = $settings['local_port'];
1907

    
1908
		$server = array();
1909
		$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1910
		$server['mode'] = $settings['mode'];
1911
		if ($settings['description']) {
1912
			$server['name'] = "{$settings['description']} {$prot}:{$port}";
1913
		} else {
1914
			$server['name'] = "Server {$prot}:{$port}";
1915
		}
1916
		$server['conns'] = array();
1917
		$server['vpnid'] = $settings['vpnid'];
1918
		$server['mgmt'] = "server{$server['vpnid']}";
1919
		$socket = "unix://{$g['openvpn_base']}/{$server['mgmt']}/sock";
1920
		list($tn, $sm) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1921

    
1922
		if ((($server['mode'] == "p2p_shared_key") ||
1923
			 (($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network']) && ($server['mode'] == 'p2p_tls')) ||
1924
			 ($sm >= 30)) &&
1925
			($type == "p2p")) {
1926
			$servers[] = openvpn_get_client_status($server, $socket);
1927
		} elseif (($server['mode'] != "p2p_shared_key") &&
1928
				  !(($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network']) && ($server['mode'] == 'p2p_tls')) &&
1929
				  ($type == "multipoint") &&
1930
				  ($sm < 30)) {
1931
			$servers[] = openvpn_get_server_status($server, $socket);
1932
		}
1933
	}
1934

    
1935
	return $servers;
1936
}
1937

    
1938
function openvpn_get_server_status($server, $socket) {
1939
	$errval = null;
1940
	$errstr = null;
1941
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1942
	if ($fp) {
1943
		stream_set_timeout($fp, 1);
1944

    
1945
		/* send our status request */
1946
		fputs($fp, "status 2\n");
1947

    
1948
		/* recv all response lines */
1949
		while (!feof($fp)) {
1950

    
1951
			/* read the next line */
1952
			$line = fgets($fp, 1024);
1953

    
1954
			$info = stream_get_meta_data($fp);
1955
			if ($info['timed_out']) {
1956
				break;
1957
			}
1958

    
1959
			/* parse header list line */
1960
			if (strstr($line, "HEADER")) {
1961
				continue;
1962
			}
1963

    
1964
			/* parse end of output line */
1965
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1966
				break;
1967
			}
1968

    
1969
			/* parse client list line */
1970
			if (strstr($line, "CLIENT_LIST")) {
1971
				$list = explode(",", $line);
1972
				$conn = array();
1973
				$conn['common_name'] = $list[1];
1974
				$conn['remote_host'] = $list[2];
1975
				$conn['virtual_addr'] = $list[3];
1976
				$conn['virtual_addr6'] = $list[4];
1977
				$conn['bytes_recv'] = $list[5];
1978
				$conn['bytes_sent'] = $list[6];
1979
				$conn['connect_time'] = $list[7];
1980
				$conn['connect_time_unix'] = $list[8];
1981
				$conn['user_name'] = $list[9];
1982
				$conn['client_id'] = $list[10];
1983
				$conn['peer_id'] = $list[11];
1984
				$conn['cipher'] = $list[12];
1985
				$server['conns'][] = $conn;
1986
			}
1987
			/* parse routing table lines */
1988
			if (strstr($line, "ROUTING_TABLE")) {
1989
				$list = explode(",", $line);
1990
				$conn = array();
1991
				$conn['virtual_addr'] = $list[1];
1992
				$conn['common_name'] = $list[2];
1993
				$conn['remote_host'] = $list[3];
1994
				$conn['last_time'] = $list[4];
1995
				$server['routes'][] = $conn;
1996
			}
1997
		}
1998

    
1999
		/* cleanup */
2000
		fclose($fp);
2001
	} else {
2002
		$conn = array();
2003
		$conn['common_name'] = "[error]";
2004
		$conn['remote_host'] = gettext("Unable to contact daemon");
2005
		$conn['virtual_addr'] = gettext("Service not running?");
2006
		$conn['bytes_recv'] = 0;
2007
		$conn['bytes_sent'] = 0;
2008
		$conn['connect_time'] = 0;
2009
		$server['conns'][] = $conn;
2010
	}
2011
	return $server;
2012
}
2013

    
2014
function openvpn_get_active_clients() {
2015
	global $g;
2016

    
2017
	$clients = array();
2018
		foreach (config_get_path('openvpn/openvpn-client', []) as $settings) {
2019
			if (empty($settings) || isset($settings['disable'])) {
2020
				continue;
2021
			}
2022

    
2023
			$prot = $settings['protocol'];
2024
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
2025

    
2026
			$client = array();
2027
			$client['port'] = $settings['local_port'];
2028
			if ($settings['description']) {
2029
				$client['name'] = "{$settings['description']} {$prot}{$port}";
2030
			} else {
2031
				$client['name'] = "Client {$prot}{$port}";
2032
			}
2033

    
2034
			$client['vpnid'] = $settings['vpnid'];
2035
			$client['mgmt'] = "client{$client['vpnid']}";
2036
			$socket = "unix://{$g['openvpn_base']}/{$client['mgmt']}/sock";
2037
			$client['status']="down";
2038

    
2039
			$clients[] = openvpn_get_client_status($client, $socket);
2040
	}
2041
	return $clients;
2042
}
2043

    
2044
function openvpn_get_client_status($client, $socket) {
2045
	$errval = null;
2046
	$errstr = null;
2047
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
2048
	if ($fp) {
2049
		stream_set_timeout($fp, 1);
2050
		/* send our status request */
2051
		fputs($fp, "state 1\n");
2052

    
2053
		/* recv all response lines */
2054
		while (!feof($fp)) {
2055
			/* read the next line */
2056
			$line = fgets($fp, 1024);
2057

    
2058
			$info = stream_get_meta_data($fp);
2059
			if ($info['timed_out']) {
2060
				break;
2061
			}
2062

    
2063
			/* Get the client state */
2064
			if (substr_count($line, ',') >= 7) {
2065
				$list = explode(",", trim($line));
2066
				$list = array_map('trim', $list);
2067

    
2068
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
2069
				$client['state'] = $list[1];
2070
				$client['state_detail'] = $list[2];
2071
				$client['virtual_addr'] = $list[3];
2072
				$client['remote_host'] = $list[4];
2073
				$client['remote_port'] = $list[5];
2074
				$client['local_host'] = $list[6];
2075
				$client['local_port'] = $list[7];
2076
				$client['virtual_addr6'] = $list[8];
2077

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

    
2129
				if (!empty($client['state_detail'])) {
2130
					$client['status'] .= " (" . ucwords(strtolower(str_replace(array('_', '-'), ' ', $client['state_detail']))) . ")";
2131
				}
2132

    
2133
			}
2134
			/* parse end of output line */
2135
			if (strstr($line, "END") || strstr($line, "ERROR")) {
2136
				break;
2137
			}
2138
		}
2139

    
2140
		/* If up, get read/write stats */
2141
		if (strcmp($client['state'], "CONNECTED") == 0) {
2142
			fputs($fp, "status 2\n");
2143
			/* recv all response lines */
2144
			while (!feof($fp)) {
2145
				/* read the next line */
2146
				$line = fgets($fp, 1024);
2147

    
2148
				$info = stream_get_meta_data($fp);
2149
				if ($info['timed_out']) {
2150
					break;
2151
				}
2152

    
2153
				if (strstr($line, "TCP/UDP read bytes")) {
2154
					$list = explode(",", $line);
2155
					$client['bytes_recv'] = $list[1];
2156
				}
2157

    
2158
				if (strstr($line, "TCP/UDP write bytes")) {
2159
					$list = explode(",", $line);
2160
					$client['bytes_sent'] = $list[1];
2161
				}
2162

    
2163
				/* parse end of output line */
2164
				if (strstr($line, "END")) {
2165
					break;
2166
				}
2167
			}
2168
		}
2169

    
2170
		fclose($fp);
2171

    
2172
	} else {
2173
		$client['remote_host'] = gettext("Unable to contact daemon");
2174
		$client['virtual_addr'] = gettext("Service not running?");
2175
		$client['bytes_recv'] = 0;
2176
		$client['bytes_sent'] = 0;
2177
		$client['connect_time'] = 0;
2178
	}
2179
	return $client;
2180
}
2181

    
2182
function openvpn_kill_client($port, $remipp, $client_id) {
2183
	global $g;
2184

    
2185
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
2186
	$tcpsrv = "unix://{$g['openvpn_base']}/{$port}/sock";
2187
	$errval = null;
2188
	$errstr = null;
2189

    
2190
	/* open a tcp connection to the management port of each server */
2191
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
2192
	$killed = -1;
2193
	if ($fp) {
2194
		stream_set_timeout($fp, 1);
2195
		if (is_numeric($client_id)) {
2196
			/* terminate remote client, see https://redmine.pfsense.org/issues/12416 */
2197
			fputs($fp, "client-kill {$client_id} HALT\n");
2198
		} else {
2199
			fputs($fp, "kill {$remipp}\n");
2200
		}
2201
		while (!feof($fp)) {
2202
			$line = fgets($fp, 1024);
2203

    
2204
			$info = stream_get_meta_data($fp);
2205
			if ($info['timed_out']) {
2206
				break;
2207
			}
2208

    
2209
			/* parse header list line */
2210
			if (strpos($line, "INFO:") !== false) {
2211
				continue;
2212
			}
2213
			if (strpos($line, "SUCCESS") !== false) {
2214
				$killed = 0;
2215
			}
2216
			break;
2217
		}
2218
		fclose($fp);
2219
	}
2220
	return $killed;
2221
}
2222

    
2223
function openvpn_refresh_crls() {
2224
	global $g;
2225

    
2226
	openvpn_create_dirs();
2227

    
2228
	foreach (config_get_path('openvpn/openvpn-server', []) as $settings) {
2229
		if (empty($settings)) {
2230
			continue;
2231
		}
2232
		if (isset($settings['disable'])) {
2233
			continue;
2234
		}
2235
		// Write the settings for the keys
2236
		switch ($settings['mode']) {
2237
		case 'p2p_tls':
2238
		case 'server_tls':
2239
		case 'server_tls_user':
2240
		case 'server_user':
2241
			$param = array('caref' => $settings['caref']);
2242
			$cas = ca_chain_array($param);
2243
			$capath = "{$g['openvpn_base']}/server{$settings['vpnid']}/ca";
2244
			if (!empty($settings['crlref'])) {
2245
				$crl = lookup_crl($settings['crlref']);
2246
				crl_update($crl);
2247
			}
2248
			foreach ($cas as $ca) {
2249
				ca_setup_capath($ca, $capath, $crl, true);
2250
			}
2251
			unset($cas, $param, $capath, $crl);
2252
			break;
2253
		}
2254
	}
2255
}
2256

    
2257
function openvpn_create_dirs() {
2258
	global $g, $openvpn_tls_server_modes;
2259
	if (!is_dir(g_get('openvpn_base'))) {
2260
		safe_mkdir(g_get('openvpn_base'), 0750);
2261
	}
2262

    
2263
	init_config_arr(array('openvpn', 'openvpn-server'));
2264
	init_config_arr(array('openvpn', 'openvpn-client'));
2265
	foreach(array('server', 'client') as $mode) {
2266
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
2267
			if (isset($settings['disable'])) {
2268
				continue;
2269
			}
2270
			$target = "{$g['openvpn_base']}/{$mode}{$settings['vpnid']}";
2271
			$csctarget = "{$target}/csc/";
2272
			@unlink_if_exists($csctarget);
2273
			@safe_mkdir($target);
2274
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2275
				@safe_mkdir($csctarget);
2276
			}
2277
		}
2278
	}
2279
}
2280

    
2281
function openvpn_get_interface_ip($ip, $cidr) {
2282
	$subnet = gen_subnetv4($ip, $cidr);
2283
	if ($cidr == 31) {
2284
		$ip1 = $subnet;
2285
	} else {
2286
		$ip1 = ip_after($subnet);
2287
	}
2288
	$ip2 = ip_after($ip1);
2289
	return array($ip1, $ip2);
2290
}
2291

    
2292
function openvpn_get_interface_ipv6($ipv6, $prefix) {
2293
	$basev6 = gen_subnetv6($ipv6, $prefix);
2294
	// Is there a better way to do this math?
2295
	$ipv6_arr = explode(':', $basev6);
2296
	$last = hexdec(array_pop($ipv6_arr));
2297
	if ($prefix == 127) {
2298
		$last--;
2299
	}
2300
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
2301
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
2302
	return array($ipv6_1, $ipv6_2);
2303
}
2304

    
2305
function openvpn_clear_route($mode, $settings) {
2306
	if (empty($settings['tunnel_network'])) {
2307
		return;
2308
	}
2309
	list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
2310
	$mask = gen_subnet_mask($cidr);
2311
	$clear_route = false;
2312

    
2313
	switch ($settings['mode']) {
2314
		case 'shared_key':
2315
			$clear_route = true;
2316
			break;
2317
		case 'p2p_tls':
2318
		case 'p2p_shared_key':
2319
			if ($cidr >= 30) {
2320
				$clear_route = true;
2321
			}
2322
			break;
2323
	}
2324

    
2325
	if ($clear_route && !empty($ip) && !empty($mask)) {
2326
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2327
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2328
		/* XXX: Family for route? */
2329
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2330
	}
2331
}
2332

    
2333
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2334
	$routes = "";
2335
	$networks = array();
2336
	if (empty($value)) {
2337
		return "";
2338
	}
2339
	$tmpnetworks = explode(',', $value);
2340
	foreach ($tmpnetworks as $network) {
2341
		if (is_alias($network)) {
2342
			foreach (alias_to_subnets_recursive($network, true) as $net) {
2343
				if ((($ipproto == "ipv4") && is_subnetv4($net)) ||
2344
				    (($ipproto == "ipv6") && is_subnetv6($net))) {
2345
					$networks[] = $net;
2346
				} elseif (is_fqdn($net)) {
2347
					if ($ipproto == "ipv4" ) {
2348
						$recordtypes = array(DNS_A);
2349
						$mask = "/32";
2350
					} else {
2351
						$recordtypes = array(DNS_AAAA);
2352
						$mask = "/128";
2353
					}
2354
					$domips = resolve_host_addresses($net, $recordtypes, false);
2355
					if (!empty($domips)) {
2356
						foreach ($domips as $net) {
2357
							$networks[] = $net . $mask;
2358
						}
2359
					} else {
2360
						log_error(gettext("Failed to resolve {$net}. Skipping OpenVPN route entry."));
2361
					}
2362
				}
2363
			}
2364
		} else {
2365
			$networks[] = $network;
2366
		}
2367
	}
2368

    
2369
	foreach ($networks as $network) {
2370
		if ($ipproto == "ipv4") {
2371
			$route = openvpn_gen_route_ipv4($network, $iroute);
2372
		} else {
2373
			$route = openvpn_gen_route_ipv6($network, $iroute);
2374
		}
2375

    
2376
		if ($push) {
2377
			$routes .= "push \"{$route}\"\n";
2378
		} else {
2379
			$routes .= "{$route}\n";
2380
		}
2381
	}
2382
	return $routes;
2383
}
2384

    
2385
function openvpn_gen_route_ipv4($network, $iroute = false) {
2386
	$i = ($iroute) ? "i" : "";
2387
	list($ip, $mask) = explode('/', trim($network));
2388
	$mask = gen_subnet_mask($mask);
2389
	return "{$i}route $ip $mask";
2390
}
2391

    
2392
function openvpn_gen_route_ipv6($network, $iroute = false) {
2393
	$i = ($iroute) ? "i" : "";
2394
	list($ipv6, $prefix) = explode('/', trim($network));
2395
	if (empty($prefix) && !is_numeric($prefix)) {
2396
		$prefix = "128";
2397
	}
2398
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2399
}
2400

    
2401
function openvpn_get_settings($mode, $vpnid) {
2402
	init_config_arr(array('openvpn', 'openvpn-server'));
2403
	init_config_arr(array('openvpn', 'openvpn-client'));
2404
	foreach (["server", "client"] as $mode) {
2405
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
2406
			if (isset($settings['disable'])) {
2407
				continue;
2408
			}
2409

    
2410
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2411
				return $settings;
2412
			}
2413
		}
2414
	}
2415
	return array();
2416
}
2417

    
2418
function openvpn_restart_by_vpnid($mode, $vpnid) {
2419
	$settings = openvpn_get_settings($mode, $vpnid);
2420
	openvpn_restart($mode, $settings);
2421
}
2422

    
2423
/****f* certs/openvpn_is_tunnel_network_in_use
2424
 * NAME
2425
 *   openvpn_is_tunnel_network_in_use
2426
 *     Check if the supplied network is in use as an OpenVPN server or client
2427
 *     tunnel network
2428
 * INPUTS
2429
 *   $net : The IPv4 or IPv6 network to check
2430
 * RESULT
2431
 *   boolean value: true if the network is in use, false otherwise.
2432
 ******/
2433

    
2434
function openvpn_is_tunnel_network_in_use($net) {
2435
	init_config_arr(array('openvpn', 'openvpn-server'));
2436
	init_config_arr(array('openvpn', 'openvpn-client'));
2437
	/* Determine whether to check IPv4 or IPv6 tunnel networks */
2438
	$tocheck = 'tunnel_network';
2439
	if (is_v6($net)) {
2440
		$tocheck .= "v6";
2441
	}
2442
	/* Check all OpenVPN clients and servers for this tunnel network */
2443
	foreach(array('server', 'client') as $mode) {
2444
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $ovpn) {
2445
			if (!empty($ovpn[$tocheck]) &&
2446
			    ($ovpn[$tocheck] == $net)) {
2447
				return true;
2448
			}
2449
		}
2450
	}
2451
	return false;
2452
}
2453

    
2454
function openvpn_build_data_cipher_list($data_ciphers = 'AES-256-GCM,AES-128-GCM,CHACHA20-POLY1305', $fallback_cipher = 'AES-256-GCM') {
2455
	/* If the data_ciphers list is empty, populate it with the fallback cipher. */
2456
	if (empty($data_ciphers)) {
2457
		$data_ciphers = $fallback_cipher;
2458
	}
2459
	/* Add the fallback cipher to the data ciphers list if it isn't already present */
2460
	if (!in_array($fallback_cipher, explode(',', $data_ciphers))) {
2461
		$data_ciphers .= ',' . $fallback_cipher;
2462
	}
2463
	return $data_ciphers;
2464
}
2465

    
2466
function openvpn_authscript_string($authmode, $strictusercn, $mode_id, $local_port) {
2467
	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";
2468
}
2469

    
2470
function openvpn_inuse($id, $mode) {
2471
	foreach (get_configured_interface_list(true) as $if) {
2472
		if (config_get_path("interfaces/{$if}/if") == openvpn_name($mode, $id)) {
2473
			return true;
2474
		}
2475
	}
2476

    
2477
	return false;
2478
}
2479

    
2480
function openvpn_tunnel_network_fix($tunnel_network) {
2481
	$tunnel_network = trim($tunnel_network);
2482
	if (is_subnet($tunnel_network)) {
2483
		/* convert to correct network address,
2484
		 * see https://redmine.pfsense.org/issues/11416 */
2485
		list($tunnel_ip, $tunnel_netmask) = explode('/', $tunnel_network);
2486
		$tunnel_network = gen_subnet($tunnel_ip, $tunnel_netmask) . '/' . $tunnel_netmask;
2487
	}
2488
	return $tunnel_network;
2489
}
2490

    
2491
?>
(34-34/61)