Project

General

Profile

Download (77 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
			return $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
	$list = array('' => 'None');
284

    
285
	foreach (config_get_path('crl', []) as $crl) {
286
		$caname = "";
287
		$ca = lookup_ca($crl['caref']);
288
		$ca = $ca['item'];
289

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

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

    
297
	return($list);
298
}
299

    
300
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
301
	$openvpn_compatible_certs = cert_build_list('cert', 'OpenVPN');
302

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

    
309
	$non_server_list = array();
310

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

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

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

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

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

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

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

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

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

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

    
377
	return($list);
378
}
379

    
380
function openvpn_create_key() {
381

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

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

    
390
	return $rslt;
391
}
392

    
393
function openvpn_create_dhparams($bits) {
394

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

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

    
403
	return $rslt;
404
}
405

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

    
419
function openvpn_vpnid_next() {
420

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

    
426
	return $vpnid;
427
}
428

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

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

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

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

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

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

    
460
	return 0;
461
}
462

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

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

    
473
	return $port;
474
}
475

    
476
function openvpn_get_cipherlist() {
477

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

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

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

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

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

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

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

    
564
function openvpn_get_buffer_values() {
565
	$sendbuf_max = get_single_sysctl('net.inet.tcp.sendbuf_max');
566
	$recvbuf_max = get_single_sysctl('net.inet.tcp.recvbuf_max');
567
	/* Usually these two are equal, but if they are not, take whichever one is lower. */
568
	$buffer_max = ($sendbuf_max <= $recvbuf_max) ? $sendbuf_max : $recvbuf_max;
569
	$buffer_values = array('' => gettext('Default'));
570
	for ($bs = 32; $bs >= 1; $bs /= 2) {
571
		$buffer_values[$buffer_max/$bs] = format_bytes($buffer_max/$bs);
572
	}
573
	return $buffer_values;
574
}
575

    
576
function openvpn_validate_host($value, $name) {
577
	$value = trim($value);
578
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
579
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
580
	}
581
	return false;
582
}
583

    
584
function openvpn_validate_port($value, $name, $first_port = 0) {
585
	$value = trim($value);
586
	if (!is_numeric($first_port)) {
587
		$first_port = 0;
588
	}
589
	if (empty($value) || !is_numeric($value) || $value < $first_port || ($value > 65535)) {
590
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from %s to 65535."), $name, $first_port);
591
	}
592
	return false;
593
}
594

    
595
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4", $alias = false) {
596
	$value = trim($value);
597
	$error = false;
598
	if (empty($value)) {
599
		return false;
600
	}
601
	$networks = explode(',', $value);
602

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

    
607
	foreach ($networks as $network) {
608
		if ($ipproto == "ipv4") {
609
			$error = !openvpn_validate_cidr_ipv4($network, $alias);
610
		} else {
611
			$error = !openvpn_validate_cidr_ipv6($network, $alias);
612
		}
613
		if ($error) {
614
			break;
615
		}
616
	}
617

    
618
	if ($error) {
619
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) or FQDN(s) separated by commas."), $name, $ipproto);
620
	} else {
621
		return false;
622
	}
623
}
624

    
625
function openvpn_validate_cidr_ipv4($value, $alias = false) {
626
	$value = trim($value);
627
	if (!empty($value)) {
628
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
629
			foreach (alias_to_subnets_recursive($value, true) as $net) {
630
				if (!is_subnetv4($net) && !is_fqdn($net)) {
631
					return false;
632
				}
633
			}
634
			return true;
635
		} else {
636
			if (!is_subnetv4($value)) {
637
				return false;
638
			}
639
		}
640
	}
641
	return true;
642
}
643

    
644
function openvpn_validate_cidr_ipv6($value, $alias = false) {
645
	$value = trim($value);
646
	if (!empty($value)) {
647
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
648
			foreach (alias_to_subnets_recursive($value, true) as $net) {
649
				if (!is_subnetv6($net) && !is_fqdn($net)) {
650
					return false;
651
				}
652
			}
653
			return true;
654
		} else {
655
			list($ipv6, $prefix) = explode('/', $value);
656
			if (empty($prefix)) {
657
				$prefix = "128";
658
			}
659
			if (!is_subnetv6($ipv6 . '/' . $prefix)) {
660
				return false;
661
			}
662
		}
663
	}
664
	return true;
665
}
666

    
667
function openvpn_validate_tunnel_network($value, $ipproto) {
668
	$value = trim($value);
669
	if (!empty($value)) {
670
		if (is_alias($value) && (alias_get_type($value) == 'network')) {
671
			$net = alias_to_subnets_recursive($value);
672
			if ((!is_subnetv4($net[0]) && ($ipproto == 'ipv4')) ||
673
			    (!is_subnetv6($net[0]) && ($ipproto == 'ipv6')) ||
674
			    (count($net) > 1)) {
675
				return false;
676
			}
677
			return true;
678
		} else {
679
			if ((!is_subnetv4($value) && ($ipproto == 'ipv4')) ||
680
			    (!is_subnetv6($value) && ($ipproto == 'ipv6'))) { 
681
				return false;
682
			}
683
		}
684
	}
685
	return true;
686
}
687

    
688
function openvpn_gen_tunnel_network($tunnel_network) {
689
	if (is_alias($tunnel_network)) {
690
		$net = alias_to_subnets_recursive($tunnel_network);
691
		$pair = openvpn_tunnel_network_fix($net[0]);
692
	} else {
693
		$pair = $tunnel_network;
694
	}
695
	return explode('/', $pair);
696
}
697

    
698
function openvpn_add_dhcpopts(& $settings, & $conf) {
699

    
700
	if (!empty($settings['dns_domain'])) {
701
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
702
	}
703

    
704
	if (!empty($settings['dns_server1'])) {
705
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
706
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
707
	}
708
	if (!empty($settings['dns_server2'])) {
709
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
710
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
711
	}
712
	if (!empty($settings['dns_server3'])) {
713
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
714
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
715
	}
716
	if (!empty($settings['dns_server4'])) {
717
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
718
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
719
	}
720

    
721
	if (!empty($settings['push_blockoutsidedns'])) {
722
		$conf .= "push \"block-outside-dns\"\n";
723
	}
724
	if (!empty($settings['push_register_dns'])) {
725
		$conf .= "push \"register-dns\"\n";
726
	}
727

    
728
	if (!empty($settings['ntp_server1'])) {
729
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
730
	}
731
	if (!empty($settings['ntp_server2'])) {
732
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
733
	}
734

    
735
	if ($settings['netbios_enable']) {
736

    
737
		if (!empty($settings['netbios_ntype']) && ($settings['netbios_ntype'] != 0)) {
738
			$conf .= "push \"dhcp-option NBT {$settings['netbios_ntype']}\"\n";
739
		}
740
		if (!empty($settings['netbios_scope'])) {
741
			$conf .= "push \"dhcp-option NBS {$settings['netbios_scope']}\"\n";
742
		}
743

    
744
		if (!empty($settings['wins_server1'])) {
745
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
746
		}
747
		if (!empty($settings['wins_server2'])) {
748
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
749
		}
750

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

    
759
	if ($settings['gwredir']) {
760
		$conf .= "push \"redirect-gateway def1\"\n";
761
	}
762
	if ($settings['gwredir6']) {
763
		$conf .= "push \"redirect-gateway ipv6\"\n";
764
	}
765
}
766

    
767
function openvpn_add_custom(& $settings, & $conf) {
768

    
769
	if ($settings['custom_options']) {
770

    
771
		$options = explode(';', $settings['custom_options']);
772

    
773
		if (is_array($options)) {
774
			foreach ($options as $option) {
775
				$conf .= "$option\n";
776
			}
777
		} else {
778
			$conf .= "{$settings['custom_options']}\n";
779
		}
780
	}
781
}
782

    
783
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
784
	global $g;
785

    
786
	$fpath = "{$g['openvpn_base']}/{$mode_id}/{$directive}";
787
	openvpn_create_dirs();
788
	file_put_contents($fpath, base64_decode($data));
789
	//chown($fpath, 'nobody');
790
	//chgrp($fpath, 'nobody');
791
	@chmod($fpath, 0600);
792

    
793
	$conf .= "{$directive} {$fpath} {$opt}\n";
794
}
795

    
796
function openvpn_delete_tmp($mode, $id) {
797
	global $g;
798

    
799
	/* delete temporary files created by connect script */
800
	if (($mode == "server") && (isset($id))) {
801
		unlink_if_exists("{$g['tmp_path']}/ovpn_ovpns{$id}_*.rules");
802
	}
803

    
804
	/* delete temporary files created by OpenVPN; only delete old files to
805
	 * avoid deleting files potentially still in use by another OpenVPN process
806
	*/
807
	$tmpfiles = array_filter(glob("{$g['tmp_path']}/openvpn_cc*.tmp"),'is_file');
808
	if (!empty($tmpfiles)) {
809
		foreach ($tmpfiles as $tmpfile) {
810
			if ((time() - filemtime($tmpfile)) > 60) {
811
				@unlink_if_exists($tmpfile);
812
			}
813
		}
814
	}
815
}
816

    
817
function openvpn_reconfigure($mode, $settings) {
818
	global $g, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
819

    
820
	if (empty($settings)) {
821
		return;
822
	}
823
	if (isset($settings['disable'])) {
824
		return;
825
	}
826
	openvpn_create_dirs();
827
	/*
828
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
829
	 * we use a vpnid number which is allocated for a particular client
830
	 * or server configuration. ( see openvpn_vpnid_next() )
831
	 */
832

    
833
	$vpnid = $settings['vpnid'];
834
	$mode_id = openvpn_name($mode, $settings, 'generic');
835
	/* defaults to tun */
836
	if (!isset($settings['dev_mode'])) {
837
		$settings['dev_mode'] = "tun";
838
	}
839
	$tunname = openvpn_name($mode, $settings, 'dev');
840
	$devname = openvpn_name($mode, $settings);
841

    
842
	/* is our device already configured */
843
	if (!does_interface_exist($devname)) {
844

    
845
		/* create the tap device if required */
846
		if (!file_exists("/dev/{$tunname}")) {
847
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
848
		}
849

    
850
		/* rename the device */
851
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
852

    
853
		/* add the device to the openvpn group */
854
		mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " group openvpn");
855

    
856
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
857
		$grouptmp = link_interface_to_group($ifname);
858
		if (!empty($grouptmp)) {
859
			array_walk($grouptmp, 'interface_group_add_member');
860
		}
861
		unset($grouptmp, $ifname);
862
	}
863

    
864
	$pfile = g_get('varrun_path') . "/openvpn_{$mode_id}.pid";
865
	$proto = strtolower($settings['protocol']);
866
	if (substr($settings['protocol'], 0, 3) == "TCP") {
867
			$proto = "{$proto}-{$mode}";
868
	}
869
	$dev_mode = $settings['dev_mode'];
870
	$fbcipher = $settings['data_ciphers_fallback'];
871
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
872
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
873

    
874
	$interface = $settings['interface'];
875
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
876
	$ipaddr = $settings['ipaddr'];
877

    
878
	// If a specific ip address (VIP) is requested, use it.
879
	// Otherwise, if a specific interface is requested, use it
880
	// If "any" interface was selected, local directive will be omitted.
881
	if (is_ipaddrv4($ipaddr)) {
882
		$iface_ip = $ipaddr;
883
	} elseif (!empty($interface) && strcmp($interface, "any")) {
884
		$iface_ip=get_interface_ip($interface);
885
	}
886
	if (is_ipaddrv6($ipaddr)) {
887
		$iface_ipv6 = $ipaddr;
888
	} elseif (!empty($interface) && strcmp($interface, "any")) {
889
		/* get correct interface name for 6RD/6to4 interfaces
890
		 * see https://redmine.pfsense.org/issues/11674 */
891
		if (is_stf_interface($settings['interface'])) {
892
			$iface_ipv6=get_interface_ipv6($settings['interface']);
893
		} else {
894
			$iface_ipv6=get_interface_ipv6($interface);
895
		}
896
	}
897

    
898
	$conf = "dev {$devname}\n";
899
	if (isset($settings['verbosity_level'])) {
900
		$conf .= "verb {$settings['verbosity_level']}\n";
901
	}
902

    
903
	$conf .= "dev-type {$settings['dev_mode']}\n";
904
	$conf .= "dev-node /dev/{$tunname}\n";
905
	$conf .= "writepid {$pfile}\n";
906
	$conf .= "#user nobody\n";
907
	$conf .= "#group nobody\n";
908
	$conf .= "script-security 3\n";
909
	$conf .= "daemon\n";
910

    
911
	if (!empty($settings['ping_method']) &&
912
	    $settings['ping_method'] == 'ping') {
913
		$conf .= "ping {$settings['ping_seconds']}\n";
914

    
915
		if (!empty($settings['ping_push'])) {
916
			$conf .= "push \"ping {$settings['ping_seconds']}\"\n";
917
		}
918

    
919
		$action = str_replace("_", "-", $settings['ping_action']);
920
		$conf .= "{$action} {$settings['ping_action_seconds']}\n";
921

    
922
		if (!empty($settings['ping_action_push'])) {
923
			$conf .= "push \"{$action} " .
924
			    "{$settings['ping_action_seconds']}\"\n";
925
		}
926
	} else {
927
		$conf .= "keepalive " .
928
		    ($settings['keepalive_interval']
929
			?: $openvpn_default_keepalive_interval) . " " .
930
		    ($settings['keepalive_timeout']
931
			?: $openvpn_default_keepalive_timeout) . "\n";
932
	}
933

    
934
	$conf .= "ping-timer-rem\n";
935
	$conf .= "persist-tun\n";
936
	$conf .= "persist-key\n";
937
	$conf .= "proto {$proto}\n";
938
	$conf .= "auth {$digest}\n";
939
	if ($settings['dns_add']) {
940
		$conf .= "up /usr/local/sbin/ovpn-dnslinkup\n";
941
	} else {
942
		$conf .= "up /usr/local/sbin/ovpn-linkup\n";
943
	}
944
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
945
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
946
		switch ($settings['mode']) {
947
			case 'server_user':
948
			case 'server_tls_user':
949
			case 'server_tls':
950
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
951
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
952
				break;
953
		}
954
	}
955
	if ($settings['dev_mode'] === 'tun' && config_path_enabled('unbound') &&
956
		config_path_enabled('unbound','regovpnclients')) {
957
		if (($settings['mode'] == 'server_tls') || ($settings['mode'] == 'server_tls_user') ||
958
		    (($settings['mode'] == 'server_user') && ($settings['username_as_common_name'] == 'enabled'))) {
959
			$domain = !empty($settings['dns_domain']) ? $settings['dns_domain'] : config_get_path('system/domain');
960
			if (is_domain($domain)) {
961
				$conf .= "learn-address \"/usr/local/sbin/openvpn.learn-address.sh $domain\"\n";
962
			}
963
		}
964
	}
965

    
966
	/*
967
	 * When binding specific address, wait cases where interface is in
968
	 * tentative state otherwise it will fail
969
	 */
970
	$wait_tentative = false;
971

    
972
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
973
	switch ($settings['protocol']) {
974
		case 'UDP':
975
		case 'TCP':
976
			$conf .= "multihome\n";
977
			break;
978
		case 'UDP4':
979
		case 'TCP4':
980
			if (is_ipaddrv4($iface_ip)) {
981
				$conf .= "local {$iface_ip}\n";
982
			}
983
			if ($settings['interface'] == "any") {
984
				$conf .= "multihome\n";
985
			}
986
			break;
987
		case 'UDP6':
988
		case 'TCP6':
989
			if (is_ipaddrv6($iface_ipv6)) {
990
				$conf .= "local {$iface_ipv6}\n";
991
				$wait_tentative = true;
992
			}
993
			if ($settings['interface'] == "any") {
994
				$conf .= "multihome\n";
995
			}
996
			break;
997
		default:
998
	}
999

    
1000
	// server specific settings
1001
	if ($mode == 'server') {
1002

    
1003
		list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1004
		list($ipv6, $prefix) = openvpn_gen_tunnel_network($settings['tunnel_networkv6']);
1005
		$mask = gen_subnet_mask($cidr);
1006

    
1007
		// configure tls modes
1008
		switch ($settings['mode']) {
1009
			case 'p2p_tls':
1010
			case 'server_tls':
1011
			case 'server_user':
1012
			case 'server_tls_user':
1013
				$conf .= "tls-server\n";
1014
				break;
1015
		}
1016

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

    
1096
		// configure user auth modes
1097
		switch ($settings['mode']) {
1098
			case 'server_user':
1099
				$conf .= "verify-client-cert none\n";
1100
			case 'server_tls_user':
1101
				/* username-as-common-name is not compatible with server-bridge */
1102
				if ((stristr($conf, "server-bridge") === false) &&
1103
				    ($settings['username_as_common_name'] != 'disabled')) {
1104
					$conf .= "username-as-common-name\n";
1105
				}
1106
				if (!empty($settings['authmode'])) {
1107
					$strictusercn = "false";
1108
					if ($settings['strictusercn']) {
1109
						$strictusercn = "true";
1110
					}
1111
					$conf .= openvpn_authscript_string($settings['authmode'], $strictusercn, $mode_id, $settings['local_port']);
1112
				}
1113
				break;
1114
		}
1115
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
1116
			$settings['cert_depth'] = 1;
1117
		}
1118
		if (is_numeric($settings['cert_depth'])) {
1119
			if (($mode == 'client') && empty($settings['certref'])) {
1120
				$cert = "";
1121
			} else {
1122
				$cert = lookup_cert($settings['certref']);
1123
				$cert = $cert['item'];
1124
				// The script 'openvpn.tls-verify.php' (called by 'ovpn_auth_verify') does not verify the CN - the CN is effectively unused.
1125
				$servercn = urlencode(cert_get_cn($cert['crt']));
1126
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
1127
			}
1128
		}
1129

    
1130
		// The local port to listen on
1131
		$conf .= "lport {$settings['local_port']}\n";
1132

    
1133
		// The management port to listen on
1134
		// Use unix socket to overcome the problem on any type of server
1135
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1136
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
1137

    
1138
		if ($settings['maxclients']) {
1139
			$conf .= "max-clients {$settings['maxclients']}\n";
1140
		}
1141

    
1142
		// Can we push routes, and should we?
1143
		if ($settings['local_network'] && !$settings['gwredir']) {
1144
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1145
		}
1146
		if ($settings['local_networkv6'] && !$settings['gwredir6']) {
1147
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1148
		}
1149

    
1150
		switch ($settings['mode']) {
1151
			case 'server_tls':
1152
			case 'server_user':
1153
			case 'server_tls_user':
1154
				// Configure client dhcp options
1155
				openvpn_add_dhcpopts($settings, $conf);
1156
				if ($settings['client2client']) {
1157
					$conf .= "client-to-client\n";
1158
				}
1159
				break;
1160
		}
1161
		$connlimit = "0";
1162
		if ($settings['mode'] != 'p2p_shared_key' &&
1163
		    isset($settings['duplicate_cn'])) {
1164
			$conf .= "duplicate-cn\n";
1165
			if ($settings['connlimit']) {
1166
				$connlimit = "{$settings['connlimit']}";
1167
			}
1168
		}
1169
		if (($settings['mode'] != 'p2p_shared_key') &&
1170
		    isset($settings['remote_cert_tls'])) {
1171
			$conf .= "remote-cert-tls client\n";
1172
		}
1173
	}
1174

    
1175
	// client specific settings
1176

    
1177
	if ($mode == 'client') {
1178

    
1179
		$add_pull = false;
1180
		// configure p2p mode
1181
		if ($settings['mode'] == 'p2p_tls') {
1182
			$conf .= "tls-client\n";
1183
		}
1184

    
1185
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1186
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1187
		//  ensure a random source port.
1188
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1189
			$conf .= "nobind\n";
1190
		} elseif ($settings['local_port']) {
1191
			$conf .= "lport {$settings['local_port']}\n";
1192
		} else {
1193
			$conf .= "lport 0\n";
1194
		}
1195

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

    
1199
		// The remote server
1200
		$remoteproto = strtolower($settings['protocol']);
1201
		if (substr($remoteproto, 0, 3) == "tcp") {
1202
			$remoteproto .= "-{$mode}";
1203
		}
1204
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']} {$remoteproto}\n";
1205

    
1206
		if (!empty($settings['use_shaper'])) {
1207
			$conf .= "shaper {$settings['use_shaper']}\n";
1208
		}
1209

    
1210
		if (!empty($settings['tunnel_network'])) {
1211
			list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1212
			$mask = gen_subnet_mask($cidr);
1213
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1214
			if (($settings['dev_mode'] == 'tun') &&
1215
			    (($settings['topology'] == 'net30') ||
1216
			    ($cidr >= 30))) {
1217
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1218
			} else {
1219
				$conf .= "ifconfig {$ip2} {$mask}\n";
1220
				if ($settings['mode'] == 'p2p_tls') {
1221
					$add_pull = true;
1222
				}
1223
			}
1224
		}
1225

    
1226
		if (!empty($settings['tunnel_networkv6'])) {
1227
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1228
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1229
			if ($settings['dev_mode'] == 'tun') {
1230
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1231
			} else {
1232
				$conf .= "ifconfig-ipv6 {$ipv6_1}/{$prefix} {$ipv6_2}\n";
1233
				if ($settings['mode'] == 'p2p_tls') {
1234
					$add_pull = true;
1235
				}
1236
			}
1237
		}
1238

    
1239
		/* If both tunnel networks are empty, then pull from server. */
1240
		if (empty($settings['tunnel_network']) &&
1241
		    empty($settings['tunnel_networkv6'])) {
1242
			$add_pull = true;
1243
		}
1244

    
1245
		/* Only add "pull" if the tunnel network is undefined or using tap mode.
1246
		   OpenVPN can't pull settings from a server in point-to-point mode. */
1247
		if (($settings['mode'] == 'p2p_tls') && $add_pull) {
1248
			$conf .= "pull\n";
1249
		}
1250

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

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

    
1283
		if (($settings['mode'] != 'shared_key') &&
1284
		    isset($settings['remote_cert_tls'])) {
1285
			$conf .= "remote-cert-tls server\n";
1286
		}
1287
	}
1288

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

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

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

    
1388
	/* Data encryption cipher support.
1389
	 * If it is not set, assume enabled since that is OpenVPN's default.
1390
	 * Note that diabling this is now deprecated and will be removed in a future version of OpenVPN */
1391
	if ($settings['mode'] == "p2p_shared_key") {
1392
		$conf .= "cipher {$fbcipher}\n";
1393
	} else {
1394
		$conf .= "data-ciphers " . str_replace(',', ':', openvpn_build_data_cipher_list($settings['data_ciphers'], $fbcipher)) . "\n";
1395
		$conf .= "data-ciphers-fallback {$fbcipher}\n";
1396
	}
1397

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

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

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

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

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

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

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

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

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

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

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

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

    
1508
	openvpn_add_custom($settings, $conf);
1509

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

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

    
1533
	if ($wait_tentative) {
1534
		interface_wait_tentative($interface);
1535
	}
1536
}
1537

    
1538
function openvpn_restart($mode, $settings) {
1539
	global $g;
1540

    
1541
	$vpnid = $settings['vpnid'];
1542
	$mode_id = openvpn_name($mode, $settings, 'generic');
1543
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1544
	openvpn_reconfigure($mode, $settings);
1545
	/* kill the process if running */
1546
	$pfile = g_get('varrun_path')."/openvpn_{$mode_id}.pid";
1547
	if (file_exists($pfile)) {
1548

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

    
1554
		/* send a term signal to the process */
1555
		posix_kill($pid, SIGTERM);
1556

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

    
1570
	if (isset($settings['disable'])) {
1571
		openvpn_delete($mode, $settings);
1572
		unlock($lockhandle);
1573
		return;
1574
	}
1575

    
1576
	openvpn_delete_tmp($mode, $vpnid);
1577

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

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

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

    
1624
function openvpn_delete($mode, $settings) {
1625
	global $g;
1626

    
1627
	$vpnid = $settings['vpnid'];
1628
	$mode_id = openvpn_name($mode, $settings, 'generic');
1629

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

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

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

    
1642
	/* destroy the device */
1643
	pfSense_interface_destroy(openvpn_name($mode, $settings));
1644

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

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

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

    
1663
	/* Some options remove the gateway or topology which are required;
1664
	 * in such cases, these can be automatically determined. */
1665
	$auto_config_gateway4 = false;
1666
	$auto_config_gateway6 = false;
1667
	$auto_config_topology = false;
1668

    
1669
	if (empty($settings['server_list'])) {
1670
		$csc_server_list = array();
1671
	} else {
1672
		$csc_server_list = explode(",", $settings['server_list']);
1673
	}
1674

    
1675
	$conf = '';
1676
	if ($settings['block']) {
1677
		$conf .= "disable\n";
1678
	}
1679

    
1680
	// Reset options
1681
	if (isset($settings['push_reset'])) {
1682
		if (isset($settings['keep_minimal'])) {
1683
			$auto_config_gateway4 = true;
1684
			$auto_config_gateway6 = true;
1685
			$auto_config_topology = true;
1686
		}
1687
		$conf .= "push-reset\n";
1688
	} elseif (!empty($settings['remove_options'])) {
1689
		foreach (explode(',', $settings['remove_options']) as $option) {
1690
			if (isset($settings['keep_minimal']) && ($option == 'remove_route')) {
1691
				$auto_config_gateway4 = true;
1692
				$auto_config_gateway6 = true;
1693
			}
1694
			$options = match ($option) {
1695
				'remove_route' => 'route',
1696
				'remove_iroute' => 'iroute',
1697
				'remove_redirect_gateway' => 'redirect-gateway',
1698
				'remove_inactive' => 'inactive',
1699
				'remove_ping' => 'ping',
1700
				'remove_ping_action' => ['ping-restart', 'ping-exit'],
1701
				'remove_blockoutsidedns' => 'block-outside-dns',
1702
				'remove_dnsdomain' => '"dhcp-option DOMAIN"',
1703
				'remove_dnsservers' => '"dhcp-option DNS"',
1704
				'remove_ntpservers' => '"dhcp-option NTP"',
1705
				'remove_netbios_ntype' => '"dhcp-option NBT"',
1706
				'remove_netbios_scope' => '"dhcp-option NBS"',
1707
				'remove_wins' => '"dhcp-option WINS"'
1708
			};
1709
			if (is_array($options)) {
1710
				foreach ($options as $option_name) {
1711
					$conf .= "push-remove {$option_name}\n";
1712
				}
1713
			} else {
1714
				$conf .= "push-remove {$options}\n";
1715
			}
1716
		}
1717
	}
1718

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

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

    
1735
	// Gatewy override options
1736
	if (!empty($settings['gateway'])) {
1737
		$auto_config_gateway4 = false;
1738
		$conf .= "push \"route-gateway {$settings['gateway']}\"\n";
1739
	}
1740
	if (!empty($settings['gateway6'])) {
1741
		$auto_config_gateway6 = false;
1742
		$conf .= "push \"route-ipv6-gateway {$settings['gateway6']}\"\n";
1743
	}
1744

    
1745
	// Inactivity override options
1746
	if (isset($settings['inactive_seconds'])) {
1747
		$conf .= "push \"inactive {$settings['inactive_seconds']}\"\n";
1748
	}
1749

    
1750
	// Ping override options
1751
	if (isset($settings['ping_seconds'])) {
1752
		$conf .= "push \"ping {$settings['ping_seconds']}\"\n";
1753
	}
1754
	if (isset($settings['ping_action'])) {
1755
		$action = str_replace("_", "-", $settings['ping_action']);
1756
		$conf .= "push \"{$action} {$settings['ping_action_seconds']}\"\n";
1757
	}
1758

    
1759
	// DHCP and gateway redirect options
1760
	openvpn_add_dhcpopts($settings, $conf);
1761

    
1762
	// Custom options
1763
	openvpn_add_custom($settings, $conf);
1764

    
1765
	/* Loop through servers, find which ones can use this CSC */
1766
	foreach (config_get_path('openvpn/openvpn-server', []) as $serversettings) {
1767
		if (isset($serversettings['disable'])) {
1768
			continue;
1769
		}
1770
		if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1771
			if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1772
				$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1773
				$csc_conf = $conf;
1774

    
1775
				/* Topology is depends on the server configuration.
1776
				 * TAP mode always uses a subnet topology */
1777
				$topology = ($serversettings['dev_mode'] == 'tap') ? 'subnet' : $serversettings['topology'];
1778
				if ($auto_config_topology) {
1779
					$csc_conf .= "push \"topology {$topology}\"\n";
1780
				}
1781

    
1782
				/* The gateway is the first usable address in the tunnel network.
1783
				 * If the tunnel network is not set, the gateway must be manually
1784
				 * defined. This can happen when using a net30 topology and
1785
				 * resetting options. */
1786
				if ($auto_config_gateway6) {
1787
					// IPv6 always uses a subnet topology
1788
					$tunnel_network = null;
1789
					if (!empty($settings['tunnel_networkv6'])) {
1790
						$tunnel_network = $settings['tunnel_networkv6'];
1791
					} elseif (!empty($serversettings['tunnel_networkv6'])) {
1792
						$tunnel_network = $serversettings['tunnel_networkv6'];
1793
					}
1794
					if (!empty($tunnel_network)) {
1795
						$tunnel_network_parts = openvpn_gen_tunnel_network($tunnel_network);
1796
						$gateway = ip6_after(gen_subnetv6($tunnel_network_parts[0], $tunnel_network_parts[1]));
1797
						$csc_conf .= "push \"route-ipv6-gateway {$gateway}\"\n";
1798
					}
1799
				}
1800
				if ($auto_config_gateway4) {
1801
					$tunnel_network = null;
1802
					if ($topology == "subnet") {
1803
						// The client tunnel network is assumed to be the same as the server's
1804
						$tunnel_network = $serversettings['tunnel_network'];
1805
					} elseif (!empty($settings['tunnel_network'])) {
1806
						$tunnel_network = $settings['tunnel_network'];
1807
					}
1808
					if (!empty($tunnel_network)) {
1809
						$tunnel_network_parts = openvpn_gen_tunnel_network($tunnel_network);
1810
						$gateway = ip_after(gen_subnetv4($tunnel_network_parts[0], $tunnel_network_parts[1]), 1);
1811
						$csc_conf .= "push \"route-gateway {$gateway}\"\n";
1812
					}
1813
				}
1814

    
1815
				if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1816
					list($ip, $mask) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1817
					if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1818
						$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1819
					} else {
1820
						/* Because this is being pushed, the order from the client's point of view. */
1821
						$baselong = gen_subnetv4($ip, $mask);
1822
						$serverip = ip_after($baselong, 1);
1823
						$clientip = ip_after($baselong, 2);
1824
						$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1825
					}
1826
				}
1827

    
1828
				if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1829
					list($ipv6, $prefix) = openvpn_gen_tunnel_network($serversettings['tunnel_networkv6']);
1830
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1831
					$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1832
				}
1833

    
1834
				file_put_contents($csc_path, $csc_conf);
1835
				chown($csc_path, 'nobody');
1836
				chgrp($csc_path, 'nobody');
1837
			}
1838
		}
1839
	}
1840
}
1841

    
1842
function openvpn_resync_csc_all() {
1843
	config_init_path('openvpn/openvpn-csc');
1844
	foreach (config_get_path('openvpn/openvpn-csc', []) as $settings) {
1845
		openvpn_resync_csc($settings);
1846
	}
1847
}
1848

    
1849
function openvpn_delete_csc($settings) {
1850
	global $g, $openvpn_tls_server_modes;
1851
	if (empty($settings['server_list'])) {
1852
		$csc_server_list = array();
1853
	} else {
1854
		$csc_server_list = explode(",", $settings['server_list']);
1855
	}
1856

    
1857
	/* Loop through servers, find which ones used this CSC */
1858
	foreach (config_get_path('openvpn/openvpn-server', []) as $serversettings) {
1859
		if (isset($serversettings['disable'])) {
1860
			continue;
1861
		}
1862
		if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1863
			if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1864
				$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1865
				unlink_if_exists($csc_path);
1866
			}
1867
		}
1868
	}
1869
}
1870

    
1871
// Resync the configuration and restart the VPN
1872
function openvpn_resync($mode, $settings) {
1873
	openvpn_restart($mode, $settings);
1874
}
1875

    
1876
// Resync and restart all VPNs
1877
function openvpn_resync_all($interface = "", $protocol = "") {
1878
	global $g;
1879

    
1880
	if ($interface <> "") {
1881
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1882
	} else {
1883
		log_error(gettext("Resyncing OpenVPN instances."));
1884
	}
1885

    
1886
	// Check if OpenVPN clients and servers require a resync.
1887
	config_init_path('openvpn/openvpn-server');
1888
	config_init_path('openvpn/openvpn-client');
1889
	foreach (array("server", "client") as $type) {
1890
		foreach (config_get_path("openvpn/openvpn-{$type}", []) as & $settings) {
1891
			if (isset($settings['disable'])) {
1892
				continue;
1893
			}
1894
			if (!empty($protocol) &&
1895
			    ((($protocol == 'inet') && strstr($settings['protocol'], "6")) ||
1896
			    (($protocol == 'inet6') && strstr($settings['protocol'], "4")))) {
1897
				continue;
1898
			}
1899
			$fpath = "{$g['openvpn_base']}/{$type}{$settings['vpnid']}/interface";
1900
			$gw_group_change = FALSE;
1901
			$ip_change = ($interface === "") ||
1902
			    ($interface === $settings['interface']);
1903

    
1904
			if (!$ip_change && file_exists($fpath)) {
1905
				$gw_group_change =
1906
				    (trim(file_get_contents($fpath), " \t\n") !=
1907
				    get_failover_interface(
1908
					$settings['interface']));
1909
			}
1910

    
1911
			if ($ip_change || $gw_group_change) {
1912
				if (!$dirs) {
1913
					openvpn_create_dirs();
1914
				}
1915
				openvpn_resync($type, $settings);
1916
				$restarted = true;
1917
				$dirs = true;
1918
			}
1919
		}
1920
	}
1921

    
1922
	if ($restarted) {
1923
		openvpn_resync_csc_all();
1924

    
1925
		/* configure OpenVPN-parent QinQ interfaces after creating OpenVPN interfaces
1926
		 * see https://redmine.pfsense.org/issues/11662 */
1927
		if (is_platform_booting()) {
1928
			/* Refresh the cache; the parent interface may not yet exist in the cache. */
1929
			get_interface_arr(true);
1930
			interfaces_qinq_configure(true);
1931
			/* Configure all qinq interface addresses and add them to their
1932
			 * bridges. See https://redmine.pfsense.org/issues/13225,
1933
			 * https://redmine.pfsense.org/issues/13666 */
1934
			foreach (config_get_path('interfaces', []) as $ifname => $iface) {
1935
				$qinq = interface_is_qinq($iface['if']);
1936
				if ($qinq && strstr($qinq['if'], "ovpn")) {
1937
					interface_configure($ifname);
1938
				}
1939
			}
1940
		}
1941
	}
1942
}
1943

    
1944
// Resync and restart all VPNs using a gateway group.
1945
function openvpn_resync_gwgroup($gwgroupname = "") {
1946
	if ($gwgroupname <> "") {
1947
		foreach (["server", "client"] as $mode) {
1948
			foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
1949
				if ($gwgroupname == $settings['interface']) {
1950
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s %2$s %3$s.'), $gwgroupname, $mode, $settings["description"]));
1951
					openvpn_resync('server', $settings);
1952
				}
1953
			}
1954
		}
1955
		// Note: no need to resysnc Client Specific (csc) here, as changes to the OpenVPN real interface do not effect these.
1956
	} else {
1957
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1958
	}
1959
}
1960

    
1961
function openvpn_get_active_servers($type="multipoint") {
1962
	global $g;
1963

    
1964
	$servers = array();
1965
	foreach (config_get_path('openvpn/openvpn-server', []) as $settings) {
1966
		if (empty($settings) || isset($settings['disable'])) {
1967
			continue;
1968
		}
1969

    
1970
		$prot = $settings['protocol'];
1971
		$port = $settings['local_port'];
1972

    
1973
		$server = array();
1974
		$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1975
		$server['mode'] = $settings['mode'];
1976
		if ($settings['description']) {
1977
			$server['name'] = "{$settings['description']} {$prot}:{$port}";
1978
		} else {
1979
			$server['name'] = "Server {$prot}:{$port}";
1980
		}
1981
		$server['conns'] = array();
1982
		$server['vpnid'] = $settings['vpnid'];
1983
		$server['mgmt'] = "server{$server['vpnid']}";
1984
		$socket = "unix://{$g['openvpn_base']}/{$server['mgmt']}/sock";
1985
		list($tn, $sm) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1986

    
1987
		if ((($server['mode'] == "p2p_shared_key") ||
1988
			 (($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network']) && ($server['mode'] == 'p2p_tls')) ||
1989
			 ($sm >= 30)) &&
1990
			($type == "p2p")) {
1991
			$servers[] = openvpn_get_client_status($server, $socket);
1992
		} elseif (($server['mode'] != "p2p_shared_key") &&
1993
				  !(($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network']) && ($server['mode'] == 'p2p_tls')) &&
1994
				  ($type == "multipoint") &&
1995
				  ($sm < 30)) {
1996
			$servers[] = openvpn_get_server_status($server, $socket);
1997
		}
1998
	}
1999

    
2000
	return $servers;
2001
}
2002

    
2003
function openvpn_get_server_status($server, $socket) {
2004
	$errval = null;
2005
	$errstr = null;
2006
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
2007
	if ($fp) {
2008
		stream_set_timeout($fp, 1);
2009

    
2010
		/* send our status request */
2011
		fputs($fp, "status 2\n");
2012

    
2013
		/* recv all response lines */
2014
		while (!feof($fp)) {
2015

    
2016
			/* read the next line */
2017
			$line = fgets($fp, 1024);
2018

    
2019
			$info = stream_get_meta_data($fp);
2020
			if ($info['timed_out']) {
2021
				break;
2022
			}
2023

    
2024
			/* parse header list line */
2025
			if (strstr($line, "HEADER")) {
2026
				continue;
2027
			}
2028

    
2029
			/* parse end of output line */
2030
			if (strstr($line, "END") || strstr($line, "ERROR")) {
2031
				break;
2032
			}
2033

    
2034
			/* parse client list line */
2035
			if (strstr($line, "CLIENT_LIST")) {
2036
				$list = explode(",", $line);
2037
				$conn = array();
2038
				$conn['common_name'] = $list[1];
2039
				$conn['remote_host'] = $list[2];
2040
				$conn['virtual_addr'] = $list[3];
2041
				$conn['virtual_addr6'] = $list[4];
2042
				$conn['bytes_recv'] = $list[5];
2043
				$conn['bytes_sent'] = $list[6];
2044
				$conn['connect_time'] = $list[7];
2045
				$conn['connect_time_unix'] = $list[8];
2046
				$conn['user_name'] = $list[9];
2047
				$conn['client_id'] = $list[10];
2048
				$conn['peer_id'] = $list[11];
2049
				$conn['cipher'] = $list[12];
2050
				$server['conns'][] = $conn;
2051
			}
2052
			/* parse routing table lines */
2053
			if (strstr($line, "ROUTING_TABLE")) {
2054
				$list = explode(",", $line);
2055
				$conn = array();
2056
				$conn['virtual_addr'] = $list[1];
2057
				$conn['common_name'] = $list[2];
2058
				$conn['remote_host'] = $list[3];
2059
				$conn['last_time'] = $list[4];
2060
				$server['routes'][] = $conn;
2061
			}
2062
		}
2063

    
2064
		/* cleanup */
2065
		fclose($fp);
2066
	} else {
2067
		$conn = array();
2068
		$conn['common_name'] = "[error]";
2069
		$conn['remote_host'] = gettext("Unable to contact daemon");
2070
		$conn['virtual_addr'] = gettext("Service not running?");
2071
		$conn['bytes_recv'] = 0;
2072
		$conn['bytes_sent'] = 0;
2073
		$conn['connect_time'] = 0;
2074
		$server['conns'][] = $conn;
2075
	}
2076
	return $server;
2077
}
2078

    
2079
function openvpn_get_active_clients() {
2080
	global $g;
2081

    
2082
	$clients = array();
2083
		foreach (config_get_path('openvpn/openvpn-client', []) as $settings) {
2084
			if (empty($settings) || isset($settings['disable'])) {
2085
				continue;
2086
			}
2087

    
2088
			$prot = $settings['protocol'];
2089
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
2090

    
2091
			$client = array();
2092
			$client['port'] = $settings['local_port'];
2093
			if ($settings['description']) {
2094
				$client['name'] = "{$settings['description']} {$prot}{$port}";
2095
			} else {
2096
				$client['name'] = "Client {$prot}{$port}";
2097
			}
2098

    
2099
			$client['vpnid'] = $settings['vpnid'];
2100
			$client['mgmt'] = "client{$client['vpnid']}";
2101
			$socket = "unix://{$g['openvpn_base']}/{$client['mgmt']}/sock";
2102
			$client['status']="down";
2103

    
2104
			$clients[] = openvpn_get_client_status($client, $socket);
2105
	}
2106
	return $clients;
2107
}
2108

    
2109
function openvpn_get_client_status($client, $socket) {
2110
	$errval = null;
2111
	$errstr = null;
2112
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
2113
	if ($fp) {
2114
		stream_set_timeout($fp, 1);
2115
		/* send our status request */
2116
		fputs($fp, "state 1\n");
2117

    
2118
		/* recv all response lines */
2119
		while (!feof($fp)) {
2120
			/* read the next line */
2121
			$line = fgets($fp, 1024);
2122

    
2123
			$info = stream_get_meta_data($fp);
2124
			if ($info['timed_out']) {
2125
				break;
2126
			}
2127

    
2128
			/* Get the client state */
2129
			if (substr_count($line, ',') >= 7) {
2130
				$list = explode(",", trim($line));
2131
				$list = array_map('trim', $list);
2132

    
2133
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
2134
				$client['state'] = $list[1];
2135
				$client['state_detail'] = $list[2];
2136
				$client['virtual_addr'] = $list[3];
2137
				$client['remote_host'] = $list[4];
2138
				$client['remote_port'] = $list[5];
2139
				$client['local_host'] = $list[6];
2140
				$client['local_port'] = $list[7];
2141
				$client['virtual_addr6'] = $list[8];
2142

    
2143
				switch (trim($client['state'])) {
2144
					case 'CONNECTED':
2145
						$client['status'] = gettext("Connected");
2146
						break;
2147
					case 'CONNECTING':
2148
						$client['status'] = gettext("Connecting");
2149
						break;
2150
					case 'TCP_CONNECT':
2151
						$client['status'] = gettext("Connecting to TCP Server");
2152
						break;
2153
					case 'ASSIGN_IP':
2154
						$client['status'] = gettext("Configuring Interface/Waiting");
2155
						break;
2156
					case 'WAIT':
2157
						$client['status'] = gettext("Waiting for response from peer");
2158
						break;
2159
					case 'RECONNECTING':
2160
						switch ($client['state_detail']) {
2161
							case 'server_poll':
2162
								$client['status'] = gettext("Waiting for peer connection");
2163
								$client['state_detail'] = '';
2164
								break;
2165
							case 'tls-error':
2166
								$client['status'] = gettext("TLS Error, reconnecting");
2167
								$client['state_detail'] = '';
2168
								break;
2169
							default:
2170
								$client['status'] = gettext("Reconnecting");
2171
								break;
2172
						}
2173
						break;
2174
					case 'AUTH':
2175
						$client['status'] = gettext("Authenticating");
2176
						break;
2177
					case 'AUTH_PENDING':
2178
						$client['status'] = gettext("Authentication pending");
2179
						break;
2180
					case 'GET_CONFIG':
2181
						$client['status'] = gettext("Pulling configuration from server");
2182
						break;
2183
					case 'ADD_ROUTES':
2184
						$client['status'] = gettext("Adding routes to system");
2185
						break;
2186
					case 'RESOLVE':
2187
						$client['status'] = gettext("Resolving peer hostname via DNS");
2188
						break;
2189
					default:
2190
						$client['status'] = ucwords(strtolower(str_replace(array('_', '-'), ' ', $client['state'])));
2191
						break;
2192
				}
2193

    
2194
				if (!empty($client['state_detail'])) {
2195
					$client['status'] .= " (" . ucwords(strtolower(str_replace(array('_', '-'), ' ', $client['state_detail']))) . ")";
2196
				}
2197

    
2198
			}
2199
			/* parse end of output line */
2200
			if (strstr($line, "END") || strstr($line, "ERROR")) {
2201
				break;
2202
			}
2203
		}
2204

    
2205
		/* If up, get read/write stats */
2206
		if (strcmp($client['state'], "CONNECTED") == 0) {
2207
			fputs($fp, "status 2\n");
2208
			/* recv all response lines */
2209
			while (!feof($fp)) {
2210
				/* read the next line */
2211
				$line = fgets($fp, 1024);
2212

    
2213
				$info = stream_get_meta_data($fp);
2214
				if ($info['timed_out']) {
2215
					break;
2216
				}
2217

    
2218
				if (strstr($line, "TCP/UDP read bytes")) {
2219
					$list = explode(",", $line);
2220
					$client['bytes_recv'] = $list[1];
2221
				}
2222

    
2223
				if (strstr($line, "TCP/UDP write bytes")) {
2224
					$list = explode(",", $line);
2225
					$client['bytes_sent'] = $list[1];
2226
				}
2227

    
2228
				/* parse end of output line */
2229
				if (strstr($line, "END")) {
2230
					break;
2231
				}
2232
			}
2233
		}
2234

    
2235
		fclose($fp);
2236

    
2237
	} else {
2238
		$client['remote_host'] = gettext("Unable to contact daemon");
2239
		$client['virtual_addr'] = gettext("Service not running?");
2240
		$client['bytes_recv'] = 0;
2241
		$client['bytes_sent'] = 0;
2242
		$client['connect_time'] = 0;
2243
	}
2244
	return $client;
2245
}
2246

    
2247
function openvpn_kill_client($port, $remipp, $client_id) {
2248
	global $g;
2249

    
2250
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
2251
	$tcpsrv = "unix://{$g['openvpn_base']}/{$port}/sock";
2252
	$errval = null;
2253
	$errstr = null;
2254

    
2255
	/* open a tcp connection to the management port of each server */
2256
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
2257
	$killed = -1;
2258
	if ($fp) {
2259
		stream_set_timeout($fp, 1);
2260
		if (is_numeric($client_id)) {
2261
			/* terminate remote client, see https://redmine.pfsense.org/issues/12416 */
2262
			fputs($fp, "client-kill {$client_id} HALT\n");
2263
		} else {
2264
			fputs($fp, "kill {$remipp}\n");
2265
		}
2266
		while (!feof($fp)) {
2267
			$line = fgets($fp, 1024);
2268

    
2269
			$info = stream_get_meta_data($fp);
2270
			if ($info['timed_out']) {
2271
				break;
2272
			}
2273

    
2274
			/* parse header list line */
2275
			if (strpos($line, "INFO:") !== false) {
2276
				continue;
2277
			}
2278
			if (strpos($line, "SUCCESS") !== false) {
2279
				$killed = 0;
2280
			}
2281
			break;
2282
		}
2283
		fclose($fp);
2284
	}
2285
	return $killed;
2286
}
2287

    
2288
function openvpn_refresh_crls() {
2289
	global $g;
2290

    
2291
	openvpn_create_dirs();
2292

    
2293
	foreach (config_get_path('openvpn/openvpn-server', []) as $settings) {
2294
		if (empty($settings)) {
2295
			continue;
2296
		}
2297
		if (isset($settings['disable'])) {
2298
			continue;
2299
		}
2300
		// Write the settings for the keys
2301
		switch ($settings['mode']) {
2302
		case 'p2p_tls':
2303
		case 'server_tls':
2304
		case 'server_tls_user':
2305
		case 'server_user':
2306
			$param = array('caref' => $settings['caref']);
2307
			$cas = ca_chain_array($param);
2308
			$capath = "{$g['openvpn_base']}/server{$settings['vpnid']}/ca";
2309
			if (!empty($settings['crlref'])) {
2310
				$crl_item_config = lookup_crl($settings['crlref']);
2311
				$crl = &$crl_item_config['item'];
2312
				crl_update($crl_item_config);
2313
			}
2314
			foreach ($cas as $ca) {
2315
				ca_setup_capath($ca, $capath, $crl, true);
2316
			}
2317
			unset($cas, $param, $capath, $crl);
2318
			break;
2319
		}
2320
	}
2321
}
2322

    
2323
function openvpn_create_dirs() {
2324
	global $g, $openvpn_tls_server_modes;
2325
	if (!is_dir(g_get('openvpn_base'))) {
2326
		safe_mkdir(g_get('openvpn_base'), 0750);
2327
	}
2328

    
2329
	config_init_path('openvpn/openvpn-server');
2330
	config_init_path('openvpn/openvpn-client');
2331
	foreach(array('server', 'client') as $mode) {
2332
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
2333
			if (isset($settings['disable'])) {
2334
				continue;
2335
			}
2336
			$target = "{$g['openvpn_base']}/{$mode}{$settings['vpnid']}";
2337
			$csctarget = "{$target}/csc/";
2338
			@unlink_if_exists($csctarget);
2339
			@safe_mkdir($target);
2340
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2341
				@safe_mkdir($csctarget);
2342
			}
2343
		}
2344
	}
2345
}
2346

    
2347
function openvpn_get_interface_ip($ip, $cidr) {
2348
	$subnet = gen_subnetv4($ip, $cidr);
2349
	if ($cidr == 31) {
2350
		$ip1 = $subnet;
2351
	} else {
2352
		$ip1 = ip_after($subnet);
2353
	}
2354
	$ip2 = ip_after($ip1);
2355
	return array($ip1, $ip2);
2356
}
2357

    
2358
function openvpn_get_interface_ipv6($ipv6, $prefix) {
2359
	$basev6 = gen_subnetv6($ipv6, $prefix);
2360
	// Is there a better way to do this math?
2361
	$ipv6_arr = explode(':', $basev6);
2362
	$last = hexdec(array_pop($ipv6_arr));
2363
	if ($prefix == 127) {
2364
		$last--;
2365
	}
2366
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
2367
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
2368
	return array($ipv6_1, $ipv6_2);
2369
}
2370

    
2371
function openvpn_clear_route($mode, $settings) {
2372
	if (empty($settings['tunnel_network'])) {
2373
		return;
2374
	}
2375
	list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
2376
	$mask = gen_subnet_mask($cidr);
2377
	$clear_route = false;
2378

    
2379
	switch ($settings['mode']) {
2380
		case 'shared_key':
2381
			$clear_route = true;
2382
			break;
2383
		case 'p2p_tls':
2384
		case 'p2p_shared_key':
2385
			if ($cidr >= 30) {
2386
				$clear_route = true;
2387
			}
2388
			break;
2389
	}
2390

    
2391
	if ($clear_route && !empty($ip) && !empty($mask)) {
2392
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2393
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2394
		/* XXX: Family for route? */
2395
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2396
	}
2397
}
2398

    
2399
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2400
	$routes = "";
2401
	$networks = array();
2402
	if (empty($value)) {
2403
		return "";
2404
	}
2405
	$tmpnetworks = explode(',', $value);
2406

    
2407
	/* Remove empty entries from network array, which otherwise may lead to
2408
	 * invalid route statements.
2409
	 * https://redmine.pfsense.org/issues/14919
2410
	 */
2411
	$tmpnetworks = array_filter($tmpnetworks, function ($tnet) {
2412
		return !empty(trim($tnet));
2413
	});
2414

    
2415
	foreach ($tmpnetworks as $network) {
2416
		if (is_alias($network)) {
2417
			foreach (alias_to_subnets_recursive($network, true) as $net) {
2418
				if ((($ipproto == "ipv4") && is_subnetv4($net)) ||
2419
				    (($ipproto == "ipv6") && is_subnetv6($net))) {
2420
					$networks[] = $net;
2421
				} elseif (is_fqdn($net)) {
2422
					if ($ipproto == "ipv4" ) {
2423
						$recordtypes = array(DNS_A);
2424
						$mask = "/32";
2425
					} else {
2426
						$recordtypes = array(DNS_AAAA);
2427
						$mask = "/128";
2428
					}
2429
					$domips = resolve_host_addresses($net, $recordtypes, false);
2430
					if (!empty($domips)) {
2431
						foreach ($domips as $net) {
2432
							$networks[] = $net . $mask;
2433
						}
2434
					} else {
2435
						log_error(gettext("Failed to resolve {$net}. Skipping OpenVPN route entry."));
2436
					}
2437
				}
2438
			}
2439
		} else {
2440
			$networks[] = $network;
2441
		}
2442
	}
2443

    
2444
	foreach ($networks as $network) {
2445
		if ($ipproto == "ipv4") {
2446
			$route = openvpn_gen_route_ipv4($network, $iroute);
2447
		} else {
2448
			$route = openvpn_gen_route_ipv6($network, $iroute);
2449
		}
2450

    
2451
		if ($push) {
2452
			$routes .= "push \"{$route}\"\n";
2453
		} else {
2454
			$routes .= "{$route}\n";
2455
		}
2456
	}
2457
	return $routes;
2458
}
2459

    
2460
function openvpn_gen_route_ipv4($network, $iroute = false) {
2461
	$i = ($iroute) ? "i" : "";
2462
	list($ip, $mask) = explode('/', trim($network));
2463
	$mask = gen_subnet_mask($mask);
2464
	return "{$i}route $ip $mask";
2465
}
2466

    
2467
function openvpn_gen_route_ipv6($network, $iroute = false) {
2468
	$i = ($iroute) ? "i" : "";
2469
	list($ipv6, $prefix) = explode('/', trim($network));
2470
	if (empty($prefix) && !is_numeric($prefix)) {
2471
		$prefix = "128";
2472
	}
2473
	return "{$i}route-ipv6 {$ipv6}/{$prefix}";
2474
}
2475

    
2476
function openvpn_get_settings($mode, $vpnid) {
2477
	config_init_path('openvpn/openvpn-server');
2478
	config_init_path('openvpn/openvpn-client');
2479
	foreach (["server", "client"] as $mode) {
2480
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
2481
			if (isset($settings['disable'])) {
2482
				continue;
2483
			}
2484

    
2485
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2486
				return $settings;
2487
			}
2488
		}
2489
	}
2490
	return array();
2491
}
2492

    
2493
function openvpn_restart_by_vpnid($mode, $vpnid) {
2494
	$settings = openvpn_get_settings($mode, $vpnid);
2495
	openvpn_restart($mode, $settings);
2496
}
2497

    
2498
/****f* certs/openvpn_is_tunnel_network_in_use
2499
 * NAME
2500
 *   openvpn_is_tunnel_network_in_use
2501
 *     Check if the supplied network is in use as an OpenVPN server or client
2502
 *     tunnel network
2503
 * INPUTS
2504
 *   $net : The IPv4 or IPv6 network to check
2505
 * RESULT
2506
 *   boolean value: true if the network is in use, false otherwise.
2507
 ******/
2508

    
2509
function openvpn_is_tunnel_network_in_use($net) {
2510
	config_init_path('openvpn/openvpn-server');
2511
	config_init_path('openvpn/openvpn-client');
2512
	/* Determine whether to check IPv4 or IPv6 tunnel networks */
2513
	$tocheck = 'tunnel_network';
2514
	if (is_v6($net)) {
2515
		$tocheck .= "v6";
2516
	}
2517
	/* Check all OpenVPN clients and servers for this tunnel network */
2518
	foreach(array('server', 'client') as $mode) {
2519
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $ovpn) {
2520
			if (!empty($ovpn[$tocheck]) &&
2521
			    ($ovpn[$tocheck] == $net)) {
2522
				return true;
2523
			}
2524
		}
2525
	}
2526
	return false;
2527
}
2528

    
2529
function openvpn_build_data_cipher_list($data_ciphers = 'AES-256-GCM,AES-128-GCM,CHACHA20-POLY1305', $fallback_cipher = 'AES-256-GCM') {
2530
	/* If the data_ciphers list is empty, populate it with the fallback cipher. */
2531
	if (empty($data_ciphers)) {
2532
		$data_ciphers = $fallback_cipher;
2533
	}
2534
	/* Add the fallback cipher to the data ciphers list if it isn't already present */
2535
	if (!in_array($fallback_cipher, explode(',', $data_ciphers))) {
2536
		$data_ciphers .= ',' . $fallback_cipher;
2537
	}
2538
	return $data_ciphers;
2539
}
2540

    
2541
function openvpn_authscript_string($authmode, $strictusercn, $mode_id, $local_port) {
2542
	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";
2543
}
2544

    
2545
function openvpn_inuse($id, $mode) {
2546
	foreach (get_configured_interface_list(true) as $if) {
2547
		if (config_get_path("interfaces/{$if}/if") == openvpn_name($mode, ['vpnid' => $id])) {
2548
			return true;
2549
		}
2550
	}
2551

    
2552
	return false;
2553
}
2554

    
2555
function openvpn_tunnel_network_fix($tunnel_network) {
2556
	$tunnel_network = trim($tunnel_network);
2557
	if (is_subnet($tunnel_network)) {
2558
		/* convert to correct network address,
2559
		 * see https://redmine.pfsense.org/issues/11416 */
2560
		list($tunnel_ip, $tunnel_netmask) = explode('/', $tunnel_network);
2561
		$tunnel_network = gen_subnet($tunnel_ip, $tunnel_netmask) . '/' . $tunnel_netmask;
2562
	}
2563
	return $tunnel_network;
2564
}
2565

    
2566
?>
(34-34/61)