Project

General

Profile

Download (73.9 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-2024 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['netbios_ntype']) && ($settings['netbios_ntype'] != 0)) {
781
			$conf .= "push \"dhcp-option NBT {$settings['netbios_ntype']}\"\n";
782
		}
783
		if (!empty($settings['netbios_scope'])) {
784
			$conf .= "push \"dhcp-option NBS {$settings['netbios_scope']}\"\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
		if (!empty($settings['nbdd_server2'])) {
798
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server2']}\"\n";
799
		}
800
	}
801

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

    
810
function openvpn_add_custom(& $settings, & $conf) {
811

    
812
	if ($settings['custom_options']) {
813

    
814
		$options = explode(';', $settings['custom_options']);
815

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

    
826
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
827
	global $g;
828

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

    
836
	$conf .= "{$directive} {$fpath} {$opt}\n";
837
}
838

    
839
function openvpn_delete_tmp($mode, $id) {
840
	global $g;
841

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

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

    
860
function openvpn_reconfigure($mode, $settings) {
861
	global $g, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
862

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

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

    
885
	/* is our device already configured */
886
	if (!does_interface_exist($devname)) {
887

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

    
893
		/* rename the device */
894
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
895

    
896
		/* add the device to the openvpn group */
897
		mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " group openvpn");
898

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

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

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

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

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

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

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

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

    
962
		$action = str_replace("_", "-", $settings['ping_action']);
963
		$conf .= "{$action} {$settings['ping_action_seconds']}\n";
964

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

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

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

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

    
1043
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
1044
		$conf .= "engine {$settings['engine']}\n";
1045
	}
1046

    
1047
	// server specific settings
1048
	if ($mode == 'server') {
1049

    
1050
		list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1051
		list($ipv6, $prefix) = openvpn_gen_tunnel_network($settings['tunnel_networkv6']);
1052
		$mask = gen_subnet_mask($cidr);
1053

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

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

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

    
1176
		// The local port to listen on
1177
		$conf .= "lport {$settings['local_port']}\n";
1178

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

    
1184
		if ($settings['maxclients']) {
1185
			$conf .= "max-clients {$settings['maxclients']}\n";
1186
		}
1187

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

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

    
1221
	// client specific settings
1222

    
1223
	if ($mode == 'client') {
1224

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

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

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

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

    
1252
		if (!empty($settings['use_shaper'])) {
1253
			$conf .= "shaper {$settings['use_shaper']}\n";
1254
		}
1255

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1478
	if ($settings['passtos']) {
1479
		$conf .= "passtos\n";
1480
	}
1481

    
1482
	if ($mode == 'client') {
1483
		$conf .= "resolv-retry infinite\n";
1484
	}
1485

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

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

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

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

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

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

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

    
1552
	openvpn_add_custom($settings, $conf);
1553

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

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

    
1577
	if ($wait_tentative) {
1578
		interface_wait_tentative($interface);
1579
	}
1580
}
1581

    
1582
function openvpn_restart($mode, $settings) {
1583
	global $g;
1584

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

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

    
1598
		/* send a term signal to the process */
1599
		posix_kill($pid, SIGTERM);
1600

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

    
1614
	if (isset($settings['disable'])) {
1615
		openvpn_delete($mode, $settings);
1616
		unlock($lockhandle);
1617
		return;
1618
	}
1619

    
1620
	openvpn_delete_tmp($mode, $vpnid);
1621

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

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

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

    
1668
function openvpn_delete($mode, $settings) {
1669
	global $g;
1670

    
1671
	$vpnid = $settings['vpnid'];
1672
	$mode_id = openvpn_name($mode, $settings, 'generic');
1673

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

    
1678
		/* read the pid file */
1679
		$pid = trim(file_get_contents($pfile));
1680
		unlink($pfile);
1681

    
1682
		/* send a term signal to the process */
1683
		posix_kill($pid, SIGTERM);
1684
	}
1685

    
1686
	/* destroy the device */
1687
	pfSense_interface_destroy(openvpn_name($mode, $settings));
1688

    
1689
	/* Invalidate cache */
1690
	get_interface_arr(true);
1691

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

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

    
1707
	if (empty($settings['server_list'])) {
1708
		$csc_server_list = array();
1709
	} else {
1710
		$csc_server_list = explode(",", $settings['server_list']);
1711
	}
1712

    
1713
	$conf = '';
1714
	if ($settings['block']) {
1715
		$conf .= "disable\n";
1716
	}
1717

    
1718
	if ($settings['push_reset']) {
1719
		$conf .= "push-reset\n";
1720
	}
1721

    
1722
	if ($settings['remove_route']) {
1723
		$conf .= "push-remove route\n";
1724
	}
1725

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

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

    
1742
	openvpn_add_dhcpopts($settings, $conf);
1743

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

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

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

    
1774
				file_put_contents($csc_path, $csc_conf);
1775
				chown($csc_path, 'nobody');
1776
				chgrp($csc_path, 'nobody');
1777
			}
1778
		}
1779
	}
1780
}
1781

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

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

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

    
1811
// Resync the configuration and restart the VPN
1812
function openvpn_resync($mode, $settings) {
1813
	openvpn_restart($mode, $settings);
1814
}
1815

    
1816
// Resync and restart all VPNs
1817
function openvpn_resync_all($interface = "", $protocol = "") {
1818
	global $g;
1819

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

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

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

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

    
1862
	if ($restarted) {
1863
		openvpn_resync_csc_all();
1864

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

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

    
1899
function openvpn_get_active_servers($type="multipoint") {
1900
	global $g;
1901

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

    
1908
		$prot = $settings['protocol'];
1909
		$port = $settings['local_port'];
1910

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

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

    
1938
	return $servers;
1939
}
1940

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

    
1948
		/* send our status request */
1949
		fputs($fp, "status 2\n");
1950

    
1951
		/* recv all response lines */
1952
		while (!feof($fp)) {
1953

    
1954
			/* read the next line */
1955
			$line = fgets($fp, 1024);
1956

    
1957
			$info = stream_get_meta_data($fp);
1958
			if ($info['timed_out']) {
1959
				break;
1960
			}
1961

    
1962
			/* parse header list line */
1963
			if (strstr($line, "HEADER")) {
1964
				continue;
1965
			}
1966

    
1967
			/* parse end of output line */
1968
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1969
				break;
1970
			}
1971

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

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

    
2017
function openvpn_get_active_clients() {
2018
	global $g;
2019

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

    
2026
			$prot = $settings['protocol'];
2027
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
2028

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

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

    
2042
			$clients[] = openvpn_get_client_status($client, $socket);
2043
	}
2044
	return $clients;
2045
}
2046

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

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

    
2061
			$info = stream_get_meta_data($fp);
2062
			if ($info['timed_out']) {
2063
				break;
2064
			}
2065

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

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

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

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

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

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

    
2151
				$info = stream_get_meta_data($fp);
2152
				if ($info['timed_out']) {
2153
					break;
2154
				}
2155

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

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

    
2166
				/* parse end of output line */
2167
				if (strstr($line, "END")) {
2168
					break;
2169
				}
2170
			}
2171
		}
2172

    
2173
		fclose($fp);
2174

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

    
2185
function openvpn_kill_client($port, $remipp, $client_id) {
2186
	global $g;
2187

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

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

    
2207
			$info = stream_get_meta_data($fp);
2208
			if ($info['timed_out']) {
2209
				break;
2210
			}
2211

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

    
2226
function openvpn_refresh_crls() {
2227
	global $g;
2228

    
2229
	openvpn_create_dirs();
2230

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

    
2260
function openvpn_create_dirs() {
2261
	global $g, $openvpn_tls_server_modes;
2262
	if (!is_dir(g_get('openvpn_base'))) {
2263
		safe_mkdir(g_get('openvpn_base'), 0750);
2264
	}
2265

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

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

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

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

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

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

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

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

    
2379
		if ($push) {
2380
			$routes .= "push \"{$route}\"\n";
2381
		} else {
2382
			$routes .= "{$route}\n";
2383
		}
2384
	}
2385
	return $routes;
2386
}
2387

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

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

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

    
2413
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2414
				return $settings;
2415
			}
2416
		}
2417
	}
2418
	return array();
2419
}
2420

    
2421
function openvpn_restart_by_vpnid($mode, $vpnid) {
2422
	$settings = openvpn_get_settings($mode, $vpnid);
2423
	openvpn_restart($mode, $settings);
2424
}
2425

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

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

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

    
2469
function openvpn_authscript_string($authmode, $strictusercn, $mode_id, $local_port) {
2470
	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";
2471
}
2472

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

    
2480
	return false;
2481
}
2482

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

    
2494
?>
(34-34/61)