Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
204
	$list = array();
205

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

    
210
	return($list);
211
}
212

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

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

    
233
global $openvpn_interfacenames;
234
function convert_openvpn_interface_to_friendly_descr($if) {
235
	global $openvpn_interfacenames;
236
	if (!is_array($openvpn_interfacenames)) {
237
		$openvpn_interfacenames = openvpn_build_if_list();
238
	}
239
	foreach($openvpn_interfacenames as $key => $value) {
240
		list($item_if, $item_ip) = explode("|", $key);
241
		if ($if == $item_if) {
242
			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['override_options']) && ($settings['override_options'] == '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
	}
1689
	if (!empty($settings['remove_options'])) {
1690
		foreach (explode(',', $settings['remove_options']) as $option) {
1691
			if (isset($settings['keep_minimal']) && ($option == 'remove_route')) {
1692
				$auto_config_gateway4 = true;
1693
				$auto_config_gateway6 = true;
1694
			}
1695
			$options = match ($option) {
1696
				'remove_route' => 'route',
1697
				'remove_iroute' => 'iroute',
1698
				'remove_inactive' => 'inactive',
1699
				'remove_ping' => 'ping',
1700
				'remove_ping_action' => ['ping-restart', 'ping-exit'],
1701
				'remove_dnsdomain' => '"dhcp-option DOMAIN"',
1702
				'remove_dnsservers' => '"dhcp-option DNS"',
1703
				'remove_ntpservers' => '"dhcp-option NTP"',
1704
				'remove_netbios_ntype' => '"dhcp-option NBT"',
1705
				'remove_netbios_scope' => '"dhcp-option NBS"',
1706
				'remove_wins' => '"dhcp-option WINS"'
1707
			};
1708
			if (is_array($options)) {
1709
				foreach ($options as $option_name) {
1710
					$conf .= "push-remove {$option_name}\n";
1711
				}
1712
			} else {
1713
				$conf .= "push-remove {$options}\n";
1714
			}
1715
		}
1716
	}
1717

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1958
function openvpn_get_active_servers($type="multipoint") {
1959
	global $g;
1960

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

    
1967
		$prot = $settings['protocol'];
1968
		$port = $settings['local_port'];
1969

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

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

    
1997
	return $servers;
1998
}
1999

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

    
2007
		/* send our status request */
2008
		fputs($fp, "status 2\n");
2009

    
2010
		/* recv all response lines */
2011
		while (!feof($fp)) {
2012

    
2013
			/* read the next line */
2014
			$line = fgets($fp, 1024);
2015

    
2016
			$info = stream_get_meta_data($fp);
2017
			if ($info['timed_out']) {
2018
				break;
2019
			}
2020

    
2021
			/* parse header list line */
2022
			if (strstr($line, "HEADER")) {
2023
				continue;
2024
			}
2025

    
2026
			/* parse end of output line */
2027
			if (strstr($line, "END") || strstr($line, "ERROR")) {
2028
				break;
2029
			}
2030

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

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

    
2076
function openvpn_get_active_clients() {
2077
	global $g;
2078

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

    
2085
			$prot = $settings['protocol'];
2086
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
2087

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

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

    
2101
			$clients[] = openvpn_get_client_status($client, $socket);
2102
	}
2103
	return $clients;
2104
}
2105

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

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

    
2120
			$info = stream_get_meta_data($fp);
2121
			if ($info['timed_out']) {
2122
				break;
2123
			}
2124

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

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

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

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

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

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

    
2210
				$info = stream_get_meta_data($fp);
2211
				if ($info['timed_out']) {
2212
					break;
2213
				}
2214

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

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

    
2225
				/* parse end of output line */
2226
				if (strstr($line, "END")) {
2227
					break;
2228
				}
2229
			}
2230
		}
2231

    
2232
		fclose($fp);
2233

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

    
2244
function openvpn_kill_client($port, $remipp, $client_id) {
2245
	global $g;
2246

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

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

    
2266
			$info = stream_get_meta_data($fp);
2267
			if ($info['timed_out']) {
2268
				break;
2269
			}
2270

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

    
2285
function openvpn_refresh_crls() {
2286
	global $g;
2287

    
2288
	openvpn_create_dirs();
2289

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

    
2320
function openvpn_create_dirs() {
2321
	global $g, $openvpn_tls_server_modes;
2322
	if (!is_dir(g_get('openvpn_base'))) {
2323
		safe_mkdir(g_get('openvpn_base'), 0750);
2324
	}
2325

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

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

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

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

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

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

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

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

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

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

    
2448
		if ($push) {
2449
			$routes .= "push \"{$route}\"\n";
2450
		} else {
2451
			$routes .= "{$route}\n";
2452
		}
2453
	}
2454
	return $routes;
2455
}
2456

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

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

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

    
2482
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2483
				return $settings;
2484
			}
2485
		}
2486
	}
2487
	return array();
2488
}
2489

    
2490
function openvpn_restart_by_vpnid($mode, $vpnid) {
2491
	$settings = openvpn_get_settings($mode, $vpnid);
2492
	openvpn_restart($mode, $settings);
2493
}
2494

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

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

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

    
2538
function openvpn_authscript_string($authmode, $strictusercn, $mode_id, $local_port) {
2539
	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";
2540
}
2541

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

    
2549
	return false;
2550
}
2551

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

    
2563
?>
(34-34/61)