Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
203
	$list = array();
204

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

    
209
	return($list);
210
}
211

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

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

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

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

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

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

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

    
258
	return($list);
259
}
260

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

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

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

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

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

    
277
	return($list);
278
}
279

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

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

    
290
	$non_server_list = array();
291

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

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

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

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

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

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

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

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

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

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

    
357
	return($list);
358
}
359

    
360
function openvpn_create_key() {
361

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

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

    
370
	return $rslt;
371
}
372

    
373
function openvpn_create_dhparams($bits) {
374

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

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

    
383
	return $rslt;
384
}
385

    
386
function openvpn_vpnid_used($vpnid) {
387
	global $config;
388

    
389
	if (is_array($config['openvpn']['openvpn-server'])) {
390
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
391
			if ($vpnid == $settings['vpnid']) {
392
				return true;
393
			}
394
		}
395
	}
396

    
397
	if (is_array($config['openvpn']['openvpn-client'])) {
398
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
399
			if ($vpnid == $settings['vpnid']) {
400
				return true;
401
			}
402
		}
403
	}
404

    
405
	return false;
406
}
407

    
408
function openvpn_vpnid_next() {
409

    
410
	$vpnid = 1;
411
	while (openvpn_vpnid_used($vpnid)) {
412
		$vpnid++;
413
	}
414

    
415
	return $vpnid;
416
}
417

    
418
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
419
	global $config;
420

    
421
	$ovpn_settings = array();
422
	if (is_array($config['openvpn']['openvpn-server'])) {
423
		$ovpn_settings = $config['openvpn']['openvpn-server'];
424
	}
425
	if (is_array($config['openvpn']['openvpn-client'])) {
426
		$ovpn_settings = array_merge($ovpn_settings,
427
		    $config['openvpn']['openvpn-client']);
428
	}
429

    
430
	foreach ($ovpn_settings as $settings) {
431
		if (isset($settings['disable'])) {
432
			continue;
433
		}
434

    
435
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
436
			continue;
437
		}
438

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

    
448
		if ($port == $settings['local_port'] &&
449
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
450
		    ($interface == $settings['interface'] ||
451
		    $interface == "any" || $settings['interface'] == "any")) {
452
			return $settings['vpnid'];
453
		}
454
	}
455

    
456
	return 0;
457
}
458

    
459
function openvpn_port_next($prot, $interface = "wan") {
460

    
461
	$port = 1194;
462
	while (openvpn_port_used($prot, $interface, $port)) {
463
		$port++;
464
	}
465
	while (openvpn_port_used($prot, "any", $port)) {
466
		$port++;
467
	}
468

    
469
	return $port;
470
}
471

    
472
function openvpn_get_cipherlist() {
473

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

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

    
496
function openvpn_validate_curve($curve) {
497
	$curves = openvpn_get_curvelist();
498
	return array_key_exists($curve, $curves);
499
}
500

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

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

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

    
550
function openvpn_get_keydirlist() {
551
	$keydirs = array(
552
		'default'  => gettext('Use default direction'),
553
		'0' => gettext('Direction 0'),
554
		'1' => gettext('Direction 1'),
555
		'2' => gettext('Both directions'),
556
	);
557
	return $keydirs;
558
}
559

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

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

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

    
609
function openvpn_validate_engine($engine) {
610
	$engines = openvpn_get_engines();
611
	return array_key_exists($engine, $engines);
612
}
613

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

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

    
633
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4", $alias = false) {
634
	$value = trim($value);
635
	$error = false;
636
	if (empty($value)) {
637
		return false;
638
	}
639
	$networks = explode(',', $value);
640

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

    
645
	foreach ($networks as $network) {
646
		if ($ipproto == "ipv4") {
647
			$error = !openvpn_validate_cidr_ipv4($network, $alias);
648
		} else {
649
			$error = !openvpn_validate_cidr_ipv6($network, $alias);
650
		}
651
		if ($error) {
652
			break;
653
		}
654
	}
655

    
656
	if ($error) {
657
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) or FQDN(s) separated by commas."), $name, $ipproto);
658
	} else {
659
		return false;
660
	}
661
}
662

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

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

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

    
726
function openvpn_gen_tunnel_network($tunnel_network) {
727
	if (is_alias($tunnel_network)) {
728
		$net = alias_to_subnets_recursive($tunnel_network);
729
		$pair = openvpn_tunnel_network_fix($net[0]);
730
	} else {
731
		$pair = $tunnel_network;
732
	}
733
	return explode('/', $pair);
734
}
735

    
736
function openvpn_add_dhcpopts(& $settings, & $conf) {
737

    
738
	if (!empty($settings['dns_domain'])) {
739
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
740
	}
741

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

    
759
	if (!empty($settings['push_blockoutsidedns'])) {
760
		$conf .= "push \"block-outside-dns\"\n";
761
	}
762
	if (!empty($settings['push_register_dns'])) {
763
		$conf .= "push \"register-dns\"\n";
764
	}
765

    
766
	if (!empty($settings['ntp_server1'])) {
767
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
768
	}
769
	if (!empty($settings['ntp_server2'])) {
770
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
771
	}
772

    
773
	if ($settings['netbios_enable']) {
774

    
775
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
776
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
777
		}
778
		if (!empty($settings['dhcp_nbtscope'])) {
779
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
780
		}
781

    
782
		if (!empty($settings['wins_server1'])) {
783
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
784
		}
785
		if (!empty($settings['wins_server2'])) {
786
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
787
		}
788

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

    
794
	if ($settings['gwredir']) {
795
		$conf .= "push \"redirect-gateway def1\"\n";
796
	}
797
	if ($settings['gwredir6']) {
798
		$conf .= "push \"redirect-gateway ipv6\"\n";
799
	}
800
}
801

    
802
function openvpn_add_custom(& $settings, & $conf) {
803

    
804
	if ($settings['custom_options']) {
805

    
806
		$options = explode(';', $settings['custom_options']);
807

    
808
		if (is_array($options)) {
809
			foreach ($options as $option) {
810
				$conf .= "$option\n";
811
			}
812
		} else {
813
			$conf .= "{$settings['custom_options']}\n";
814
		}
815
	}
816
}
817

    
818
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
819
	global $g;
820

    
821
	$fpath = "{$g['openvpn_base']}/{$mode_id}/{$directive}";
822
	openvpn_create_dirs();
823
	file_put_contents($fpath, base64_decode($data));
824
	//chown($fpath, 'nobody');
825
	//chgrp($fpath, 'nobody');
826
	@chmod($fpath, 0600);
827

    
828
	$conf .= "{$directive} {$fpath} {$opt}\n";
829
}
830

    
831
function openvpn_delete_tmp($mode, $id) {
832
	global $g;
833

    
834
	/* delete temporary files created by connect script */
835
	if (($mode == "server") && (isset($id))) {
836
		unlink_if_exists("{$g['tmp_path']}/ovpn_ovpns{$id}_*.rules");
837
	}
838

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

    
852
function openvpn_reconfigure($mode, $settings) {
853
	global $g, $config, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
854

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

    
868
	$vpnid = $settings['vpnid'];
869
	$mode_id = $mode.$vpnid;
870

    
871
	if (isset($settings['dev_mode'])) {
872
		$tunname = "{$settings['dev_mode']}{$vpnid}";
873
	} else {
874
		/* defaults to tun */
875
		$tunname = "tun{$vpnid}";
876
		$settings['dev_mode'] = "tun";
877
	}
878

    
879
	if ($mode == "server") {
880
		$devname = "ovpns{$vpnid}";
881
	} else {
882
		$devname = "ovpnc{$vpnid}";
883
	}
884

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1220
	// client specific settings
1221

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1429
	/* Data encryption cipher support.
1430
	 * If it is not set, assume enabled since that is OpenVPN's default.
1431
	 * Note that diabling this is now deprecated and will be removed in a future version of OpenVPN */
1432
	if (($settings['ncp_enable'] == "disabled") ||
1433
	    ($settings['mode'] == "p2p_shared_key")) {
1434
		if ($settings['mode'] != "p2p_shared_key") {
1435
			/* Do not include this option for shared key as it is redundant. */
1436
			$conf .= "ncp-disable\n";
1437
		}
1438
		$conf .= "cipher {$fbcipher}\n";
1439
	} else {
1440
		$conf .= "data-ciphers " . str_replace(',', ':', openvpn_build_data_cipher_list($settings['data_ciphers'], $fbcipher)) . "\n";
1441
		$conf .= "data-ciphers-fallback {$fbcipher}\n";
1442
	}
1443

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

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

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

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

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

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

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

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

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

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

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

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

    
1554
	openvpn_add_custom($settings, $conf);
1555

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

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

    
1579
	if ($wait_tentative) {
1580
		interface_wait_tentative($interface);
1581
	}
1582
}
1583

    
1584
function openvpn_restart($mode, $settings) {
1585
	global $g, $config;
1586

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

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

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

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

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

    
1622
	openvpn_delete_tmp($mode, $vpnid);
1623

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

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

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

    
1670
function openvpn_delete($mode, $settings) {
1671
	global $g, $config;
1672

    
1673
	$vpnid = $settings['vpnid'];
1674
	$mode_id = $mode.$vpnid;
1675

    
1676
	if ($mode == "server") {
1677
		$devname = "ovpns{$vpnid}";
1678
	} else {
1679
		$devname = "ovpnc{$vpnid}";
1680
	}
1681

    
1682
	/* kill the process if running */
1683
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1684
	if (file_exists($pfile)) {
1685

    
1686
		/* read the pid file */
1687
		$pid = trim(file_get_contents($pfile));
1688
		unlink($pfile);
1689

    
1690
		/* send a term signal to the process */
1691
		posix_kill($pid, SIGTERM);
1692
	}
1693

    
1694
	/* destroy the device */
1695
	pfSense_interface_destroy($devname);
1696

    
1697
	/* Invalidate cache */
1698
	get_interface_arr(true);
1699

    
1700
	/* remove the configuration files */
1701
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*/*");
1702
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*");
1703
	openvpn_delete_tmp($mode, $vpnid);
1704
	filter_configure();
1705
}
1706

    
1707
function openvpn_resync_csc(& $settings) {
1708
	global $g, $config, $openvpn_tls_server_modes;
1709
	if (isset($settings['disable'])) {
1710
		openvpn_delete_csc($settings);
1711
		return;
1712
	}
1713
	openvpn_create_dirs();
1714

    
1715
	if (empty($settings['server_list'])) {
1716
		$csc_server_list = array();
1717
	} else {
1718
		$csc_server_list = explode(",", $settings['server_list']);
1719
	}
1720

    
1721
	$conf = '';
1722
	if ($settings['block']) {
1723
		$conf .= "disable\n";
1724
	}
1725

    
1726
	if ($settings['push_reset']) {
1727
		$conf .= "push-reset\n";
1728
	}
1729

    
1730
	if ($settings['remove_route']) {
1731
		$conf .= "push-remove route\n";
1732
	}
1733

    
1734
	if ($settings['local_network']) {
1735
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1736
	}
1737
	if ($settings['local_networkv6']) {
1738
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1739
	}
1740

    
1741
	// Add a remote network iroute if set
1742
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4", true) === FALSE) {
1743
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1744
	}
1745
	// Add a remote network iroute if set
1746
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6", true) === FALSE) {
1747
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1748
	}
1749

    
1750
	openvpn_add_dhcpopts($settings, $conf);
1751

    
1752
	openvpn_add_custom($settings, $conf);
1753
	/* Loop through servers, find which ones can use this CSC */
1754
	if (is_array($config['openvpn']['openvpn-server'])) {
1755
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1756
			if (isset($serversettings['disable'])) {
1757
				continue;
1758
			}
1759
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1760
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1761
					$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1762
					$csc_conf = $conf;
1763

    
1764
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1765
						list($ip, $mask) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1766
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1767
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1768
						} else {
1769
							/* Because this is being pushed, the order from the client's point of view. */
1770
							$baselong = gen_subnetv4($ip, $mask);
1771
							$serverip = ip_after($baselong, 1);
1772
							$clientip = ip_after($baselong, 2);
1773
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1774
						}
1775
					}
1776

    
1777
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1778
						list($ipv6, $prefix) = openvpn_gen_tunnel_network($serversettings['tunnel_networkv6']);
1779
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1780
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1781
					}
1782

    
1783
					file_put_contents($csc_path, $csc_conf);
1784
					chown($csc_path, 'nobody');
1785
					chgrp($csc_path, 'nobody');
1786
				}
1787
			}
1788
		}
1789
	}
1790
}
1791

    
1792
function openvpn_resync_csc_all() {
1793
	global $config;
1794
	init_config_arr(array('openvpn', 'openvpn-csc'));
1795
	if (is_array($config['openvpn']['openvpn-csc'])) {
1796
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1797
			openvpn_resync_csc($settings);
1798
		}
1799
	}
1800
}
1801

    
1802
function openvpn_delete_csc(& $settings) {
1803
	global $g, $config, $openvpn_tls_server_modes;
1804
	if (empty($settings['server_list'])) {
1805
		$csc_server_list = array();
1806
	} else {
1807
		$csc_server_list = explode(",", $settings['server_list']);
1808
	}
1809

    
1810
	/* Loop through servers, find which ones used this CSC */
1811
	if (is_array($config['openvpn']['openvpn-server'])) {
1812
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1813
			if (isset($serversettings['disable'])) {
1814
				continue;
1815
			}
1816
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1817
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1818
					$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1819
					unlink_if_exists($csc_path);
1820
				}
1821
			}
1822
		}
1823
	}
1824
}
1825

    
1826
// Resync the configuration and restart the VPN
1827
function openvpn_resync($mode, $settings) {
1828
	openvpn_restart($mode, $settings);
1829
}
1830

    
1831
// Resync and restart all VPNs
1832
function openvpn_resync_all($interface = "", $protocol = "") {
1833
	global $g, $config;
1834

    
1835
	if ($interface <> "") {
1836
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1837
	} else {
1838
		log_error(gettext("Resyncing OpenVPN instances."));
1839
	}
1840

    
1841
	// Check if OpenVPN clients and servers require a resync.
1842
	init_config_arr(array('openvpn', 'openvpn-server'));
1843
	init_config_arr(array('openvpn', 'openvpn-client'));
1844
	foreach (array("server", "client") as $type) {
1845
		if (!is_array($config['openvpn']["openvpn-{$type}"])) {
1846
			continue;
1847
		}
1848
		foreach ($config['openvpn']["openvpn-{$type}"] as & $settings) {
1849
			if (isset($settings['disable'])) {
1850
				continue;
1851
			}
1852
			if (!empty($protocol) &&
1853
			    ((($protocol == 'inet') && strstr($settings['protocol'], "6")) ||
1854
			    (($protocol == 'inet6') && strstr($settings['protocol'], "4")))) {
1855
				continue;
1856
			}
1857
			$fpath = "{$g['openvpn_base']}/{$type}{$settings['vpnid']}/interface";
1858
			$gw_group_change = FALSE;
1859
			$ip_change = ($interface === "") ||
1860
			    ($interface === $settings['interface']);
1861

    
1862
			if (!$ip_change && file_exists($fpath)) {
1863
				$gw_group_change =
1864
				    (trim(file_get_contents($fpath), " \t\n") !=
1865
				    get_failover_interface(
1866
					$settings['interface']));
1867
			}
1868

    
1869
			if ($ip_change || $gw_group_change) {
1870
				if (!$dirs) {
1871
					openvpn_create_dirs();
1872
				}
1873
				openvpn_resync($type, $settings);
1874
				$restarted = true;
1875
				$dirs = true;
1876
			}
1877
		}
1878
	}
1879

    
1880
	if ($restarted) {
1881
		openvpn_resync_csc_all();
1882

    
1883
		/* configure OpenVPN-parent QinQ interfaces after creating OpenVPN interfaces
1884
		 * see https://redmine.pfsense.org/issues/11662 */
1885
		if (platform_booting()) {
1886
			interfaces_qinq_configure(true);
1887
		}
1888
	}
1889
}
1890

    
1891
// Resync and restart all VPNs using a gateway group.
1892
function openvpn_resync_gwgroup($gwgroupname = "") {
1893
	global $g, $config;
1894

    
1895
	if ($gwgroupname <> "") {
1896
		if (is_array($config['openvpn']['openvpn-server'])) {
1897
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1898
				if ($gwgroupname == $settings['interface']) {
1899
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1900
					openvpn_resync('server', $settings);
1901
				}
1902
			}
1903
		}
1904

    
1905
		if (is_array($config['openvpn']['openvpn-client'])) {
1906
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1907
				if ($gwgroupname == $settings['interface']) {
1908
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1909
					openvpn_resync('client', $settings);
1910
				}
1911
			}
1912
		}
1913

    
1914
		// Note: no need to resysnc Client Specific (csc) here, as changes to the OpenVPN real interface do not effect these.
1915

    
1916
	} else {
1917
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1918
	}
1919
}
1920

    
1921
function openvpn_get_active_servers($type="multipoint") {
1922
	global $config, $g;
1923

    
1924
	$servers = array();
1925
	if (is_array($config['openvpn']['openvpn-server'])) {
1926
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1927
			if (empty($settings) || isset($settings['disable'])) {
1928
				continue;
1929
			}
1930

    
1931
			$prot = $settings['protocol'];
1932
			$port = $settings['local_port'];
1933

    
1934
			$server = array();
1935
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1936
			$server['mode'] = $settings['mode'];
1937
			if ($settings['description']) {
1938
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1939
			} else {
1940
				$server['name'] = "Server {$prot}:{$port}";
1941
			}
1942
			$server['conns'] = array();
1943
			$server['vpnid'] = $settings['vpnid'];
1944
			$server['mgmt'] = "server{$server['vpnid']}";
1945
			$socket = "unix://{$g['openvpn_base']}/{$server['mgmt']}/sock";
1946
			list($tn, $sm) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1947

    
1948
			if ((($server['mode'] == "p2p_shared_key") ||
1949
			    (($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network']) && ($server['mode'] == 'p2p_tls')) ||
1950
			    ($sm >= 30)) &&
1951
			    ($type == "p2p")) {
1952
				$servers[] = openvpn_get_client_status($server, $socket);
1953
			} elseif (($server['mode'] != "p2p_shared_key") &&
1954
			    !(($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network']) && ($server['mode'] == 'p2p_tls')) &&
1955
			    ($type == "multipoint") &&
1956
			    ($sm < 30)) {
1957
				$servers[] = openvpn_get_server_status($server, $socket);
1958
			}
1959
		}
1960
	}
1961
	return $servers;
1962
}
1963

    
1964
function openvpn_get_server_status($server, $socket) {
1965
	$errval = null;
1966
	$errstr = null;
1967
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1968
	if ($fp) {
1969
		stream_set_timeout($fp, 1);
1970

    
1971
		/* send our status request */
1972
		fputs($fp, "status 2\n");
1973

    
1974
		/* recv all response lines */
1975
		while (!feof($fp)) {
1976

    
1977
			/* read the next line */
1978
			$line = fgets($fp, 1024);
1979

    
1980
			$info = stream_get_meta_data($fp);
1981
			if ($info['timed_out']) {
1982
				break;
1983
			}
1984

    
1985
			/* parse header list line */
1986
			if (strstr($line, "HEADER")) {
1987
				continue;
1988
			}
1989

    
1990
			/* parse end of output line */
1991
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1992
				break;
1993
			}
1994

    
1995
			/* parse client list line */
1996
			if (strstr($line, "CLIENT_LIST")) {
1997
				$list = explode(",", $line);
1998
				$conn = array();
1999
				$conn['common_name'] = $list[1];
2000
				$conn['remote_host'] = $list[2];
2001
				$conn['virtual_addr'] = $list[3];
2002
				$conn['virtual_addr6'] = $list[4];
2003
				$conn['bytes_recv'] = $list[5];
2004
				$conn['bytes_sent'] = $list[6];
2005
				$conn['connect_time'] = $list[7];
2006
				$conn['connect_time_unix'] = $list[8];
2007
				$conn['user_name'] = $list[9];
2008
				$conn['client_id'] = $list[10];
2009
				$conn['peer_id'] = $list[11];
2010
				$conn['cipher'] = $list[12];
2011
				$server['conns'][] = $conn;
2012
			}
2013
			/* parse routing table lines */
2014
			if (strstr($line, "ROUTING_TABLE")) {
2015
				$list = explode(",", $line);
2016
				$conn = array();
2017
				$conn['virtual_addr'] = $list[1];
2018
				$conn['common_name'] = $list[2];
2019
				$conn['remote_host'] = $list[3];
2020
				$conn['last_time'] = $list[4];
2021
				$server['routes'][] = $conn;
2022
			}
2023
		}
2024

    
2025
		/* cleanup */
2026
		fclose($fp);
2027
	} else {
2028
		$conn = array();
2029
		$conn['common_name'] = "[error]";
2030
		$conn['remote_host'] = gettext("Unable to contact daemon");
2031
		$conn['virtual_addr'] = gettext("Service not running?");
2032
		$conn['bytes_recv'] = 0;
2033
		$conn['bytes_sent'] = 0;
2034
		$conn['connect_time'] = 0;
2035
		$server['conns'][] = $conn;
2036
	}
2037
	return $server;
2038
}
2039

    
2040
function openvpn_get_active_clients() {
2041
	global $config, $g;
2042

    
2043
	$clients = array();
2044
	if (is_array($config['openvpn']['openvpn-client'])) {
2045
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
2046

    
2047
			if (empty($settings) || isset($settings['disable'])) {
2048
				continue;
2049
			}
2050

    
2051
			$prot = $settings['protocol'];
2052
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
2053

    
2054
			$client = array();
2055
			$client['port'] = $settings['local_port'];
2056
			if ($settings['description']) {
2057
				$client['name'] = "{$settings['description']} {$prot}{$port}";
2058
			} else {
2059
				$client['name'] = "Client {$prot}{$port}";
2060
			}
2061

    
2062
			$client['vpnid'] = $settings['vpnid'];
2063
			$client['mgmt'] = "client{$client['vpnid']}";
2064
			$socket = "unix://{$g['openvpn_base']}/{$client['mgmt']}/sock";
2065
			$client['status']="down";
2066

    
2067
			$clients[] = openvpn_get_client_status($client, $socket);
2068
		}
2069
	}
2070
	return $clients;
2071
}
2072

    
2073
function openvpn_get_client_status($client, $socket) {
2074
	$errval = null;
2075
	$errstr = null;
2076
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
2077
	if ($fp) {
2078
		stream_set_timeout($fp, 1);
2079
		/* send our status request */
2080
		fputs($fp, "state 1\n");
2081

    
2082
		/* recv all response lines */
2083
		while (!feof($fp)) {
2084
			/* read the next line */
2085
			$line = fgets($fp, 1024);
2086

    
2087
			$info = stream_get_meta_data($fp);
2088
			if ($info['timed_out']) {
2089
				break;
2090
			}
2091

    
2092
			/* Get the client state */
2093
			if (substr_count($line, ',') >= 7) {
2094
				$list = explode(",", trim($line));
2095
				$list = array_map('trim', $list);
2096

    
2097
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
2098
				$client['state'] = $list[1];
2099
				$client['state_detail'] = $list[2];
2100
				$client['virtual_addr'] = $list[3];
2101
				$client['remote_host'] = $list[4];
2102
				$client['remote_port'] = $list[5];
2103
				$client['local_host'] = $list[6];
2104
				$client['local_port'] = $list[7];
2105
				$client['virtual_addr6'] = $list[8];
2106

    
2107
				switch (trim($client['state'])) {
2108
					case 'CONNECTED':
2109
						$client['status'] = gettext("Connected");
2110
						break;
2111
					case 'CONNECTING':
2112
						$client['status'] = gettext("Connecting");
2113
						break;
2114
					case 'TCP_CONNECT':
2115
						$client['status'] = gettext("Connecting to TCP Server");
2116
						break;
2117
					case 'ASSIGN_IP':
2118
						$client['status'] = gettext("Configuring Interface/Waiting");
2119
						break;
2120
					case 'WAIT':
2121
						$client['status'] = gettext("Waiting for response from peer");
2122
						break;
2123
					case 'RECONNECTING':
2124
						switch ($client['state_detail']) {
2125
							case 'server_poll':
2126
								$client['status'] = gettext("Waiting for peer connection");
2127
								$client['state_detail'] = '';
2128
								break;
2129
							case 'tls-error':
2130
								$client['status'] = gettext("TLS Error, reconnecting");
2131
								$client['state_detail'] = '';
2132
								break;
2133
							default:
2134
								$client['status'] = gettext("Reconnecting");
2135
								break;
2136
						}
2137
						break;
2138
					case 'AUTH':
2139
						$client['status'] = gettext("Authenticating");
2140
						break;
2141
					case 'AUTH_PENDING':
2142
						$client['status'] = gettext("Authentication pending");
2143
						break;
2144
					case 'GET_CONFIG':
2145
						$client['status'] = gettext("Pulling configuration from server");
2146
						break;
2147
					case 'ADD_ROUTES':
2148
						$client['status'] = gettext("Adding routes to system");
2149
						break;
2150
					case 'RESOLVE':
2151
						$client['status'] = gettext("Resolving peer hostname via DNS");
2152
						break;
2153
					default:
2154
						$client['status'] = ucwords(strtolower(str_replace(array('_', '-'), ' ', $client['state'])));
2155
						break;
2156
				}
2157

    
2158
				if (!empty($client['state_detail'])) {
2159
					$client['status'] .= " (" . ucwords(strtolower(str_replace(array('_', '-'), ' ', $client['state_detail']))) . ")";
2160
				}
2161

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

    
2169
		/* If up, get read/write stats */
2170
		if (strcmp($client['state'], "CONNECTED") == 0) {
2171
			fputs($fp, "status 2\n");
2172
			/* recv all response lines */
2173
			while (!feof($fp)) {
2174
				/* read the next line */
2175
				$line = fgets($fp, 1024);
2176

    
2177
				$info = stream_get_meta_data($fp);
2178
				if ($info['timed_out']) {
2179
					break;
2180
				}
2181

    
2182
				if (strstr($line, "TCP/UDP read bytes")) {
2183
					$list = explode(",", $line);
2184
					$client['bytes_recv'] = $list[1];
2185
				}
2186

    
2187
				if (strstr($line, "TCP/UDP write bytes")) {
2188
					$list = explode(",", $line);
2189
					$client['bytes_sent'] = $list[1];
2190
				}
2191

    
2192
				/* parse end of output line */
2193
				if (strstr($line, "END")) {
2194
					break;
2195
				}
2196
			}
2197
		}
2198

    
2199
		fclose($fp);
2200

    
2201
	} else {
2202
		$client['remote_host'] = gettext("Unable to contact daemon");
2203
		$client['virtual_addr'] = gettext("Service not running?");
2204
		$client['bytes_recv'] = 0;
2205
		$client['bytes_sent'] = 0;
2206
		$client['connect_time'] = 0;
2207
	}
2208
	return $client;
2209
}
2210

    
2211
function openvpn_kill_client($port, $remipp, $client_id) {
2212
	global $g;
2213

    
2214
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
2215
	$tcpsrv = "unix://{$g['openvpn_base']}/{$port}/sock";
2216
	$errval = null;
2217
	$errstr = null;
2218

    
2219
	/* open a tcp connection to the management port of each server */
2220
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
2221
	$killed = -1;
2222
	if ($fp) {
2223
		stream_set_timeout($fp, 1);
2224
		if (is_numeric($client_id)) {
2225
			/* terminate remote client, see https://redmine.pfsense.org/issues/12416 */
2226
			fputs($fp, "client-kill {$client_id} HALT\n");
2227
		} else {
2228
			fputs($fp, "kill {$remipp}\n");
2229
		}
2230
		while (!feof($fp)) {
2231
			$line = fgets($fp, 1024);
2232

    
2233
			$info = stream_get_meta_data($fp);
2234
			if ($info['timed_out']) {
2235
				break;
2236
			}
2237

    
2238
			/* parse header list line */
2239
			if (strpos($line, "INFO:") !== false) {
2240
				continue;
2241
			}
2242
			if (strpos($line, "SUCCESS") !== false) {
2243
				$killed = 0;
2244
			}
2245
			break;
2246
		}
2247
		fclose($fp);
2248
	}
2249
	return $killed;
2250
}
2251

    
2252
function openvpn_refresh_crls() {
2253
	global $g, $config;
2254

    
2255
	openvpn_create_dirs();
2256

    
2257
	if (is_array($config['openvpn']['openvpn-server'])) {
2258
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2259
			if (empty($settings)) {
2260
				continue;
2261
			}
2262
			if (isset($settings['disable'])) {
2263
				continue;
2264
			}
2265
			// Write the settings for the keys
2266
			switch ($settings['mode']) {
2267
				case 'p2p_tls':
2268
				case 'server_tls':
2269
				case 'server_tls_user':
2270
				case 'server_user':
2271
					$param = array('caref' => $settings['caref']);
2272
					$cas = ca_chain_array($param);
2273
					$capath = "{$g['openvpn_base']}/server{$settings['vpnid']}/ca";
2274
					if (!empty($settings['crlref'])) {
2275
						$crl = lookup_crl($settings['crlref']);
2276
						crl_update($crl);
2277
					}
2278
					foreach ($cas as $ca) {
2279
						ca_setup_capath($ca, $capath, $crl, true);
2280
					}
2281
					unset($cas, $param, $capath, $crl);
2282
					break;
2283
			}
2284
		}
2285
	}
2286
}
2287

    
2288
function openvpn_create_dirs() {
2289
	global $g, $config, $openvpn_tls_server_modes;
2290
	if (!is_dir($g['openvpn_base'])) {
2291
		safe_mkdir($g['openvpn_base'], 0750);
2292
	}
2293

    
2294
	init_config_arr(array('openvpn', 'openvpn-server'));
2295
	init_config_arr(array('openvpn', 'openvpn-client'));
2296
	foreach(array('server', 'client') as $mode) {
2297
		foreach ($config['openvpn']["openvpn-{$mode}"] as $settings) {
2298
			if (isset($settings['disable'])) {
2299
				continue;
2300
			}
2301
			$target = "{$g['openvpn_base']}/{$mode}{$settings['vpnid']}";
2302
			$csctarget = "{$target}/csc/";
2303
			@unlink_if_exists($csctarget);
2304
			@safe_mkdir($target);
2305
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2306
				@safe_mkdir($csctarget);
2307
			}
2308
		}
2309
	}
2310
}
2311

    
2312
function openvpn_get_interface_ip($ip, $cidr) {
2313
	$subnet = gen_subnetv4($ip, $cidr);
2314
	if ($cidr == 31) {
2315
		$ip1 = $subnet;
2316
	} else {
2317
		$ip1 = ip_after($subnet);
2318
	}
2319
	$ip2 = ip_after($ip1);
2320
	return array($ip1, $ip2);
2321
}
2322

    
2323
function openvpn_get_interface_ipv6($ipv6, $prefix) {
2324
	$basev6 = gen_subnetv6($ipv6, $prefix);
2325
	// Is there a better way to do this math?
2326
	$ipv6_arr = explode(':', $basev6);
2327
	$last = hexdec(array_pop($ipv6_arr));
2328
	if ($prefix == 127) {
2329
		$last--;
2330
	}
2331
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
2332
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
2333
	return array($ipv6_1, $ipv6_2);
2334
}
2335

    
2336
function openvpn_clear_route($mode, $settings) {
2337
	if (empty($settings['tunnel_network'])) {
2338
		return;
2339
	}
2340
	list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
2341
	$mask = gen_subnet_mask($cidr);
2342
	$clear_route = false;
2343

    
2344
	switch ($settings['mode']) {
2345
		case 'shared_key':
2346
			$clear_route = true;
2347
			break;
2348
		case 'p2p_tls':
2349
		case 'p2p_shared_key':
2350
			if ($cidr >= 30) {
2351
				$clear_route = true;
2352
			}
2353
			break;
2354
	}
2355

    
2356
	if ($clear_route && !empty($ip) && !empty($mask)) {
2357
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2358
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2359
		/* XXX: Family for route? */
2360
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2361
	}
2362
}
2363

    
2364
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2365
	$routes = "";
2366
	$networks = array();
2367
	if (empty($value)) {
2368
		return "";
2369
	}
2370
	$tmpnetworks = explode(',', $value);
2371
	foreach ($tmpnetworks as $network) {
2372
		if (is_alias($network)) {
2373
			foreach (alias_to_subnets_recursive($network, true) as $net) {
2374
				if ((($ipproto == "ipv4") && is_subnetv4($net)) ||
2375
				    (($ipproto == "ipv6") && is_subnetv6($net))) {
2376
					$networks[] = $net;
2377
				} elseif (is_fqdn($net)) {
2378
					if ($ipproto == "ipv4" ) {
2379
						$recordtypes = array(DNS_A);
2380
						$mask = "/32";
2381
					} else {
2382
						$recordtypes = array(DNS_AAAA);
2383
						$mask = "/128";
2384
					}
2385
					$domips = resolve_host_addresses($net, $recordtypes, false);
2386
					if (!empty($domips)) {
2387
						foreach ($domips as $net) {
2388
							$networks[] = $net . $mask;
2389
						}
2390
					} else {
2391
						log_error(gettext("Failed to resolve {$net}. Skipping OpenVPN route entry."));
2392
					}
2393
				}
2394
			}
2395
		} else {
2396
			$networks[] = $network;
2397
		}
2398
	}
2399

    
2400
	foreach ($networks as $network) {
2401
		if ($ipproto == "ipv4") {
2402
			$route = openvpn_gen_route_ipv4($network, $iroute);
2403
		} else {
2404
			$route = openvpn_gen_route_ipv6($network, $iroute);
2405
		}
2406

    
2407
		if ($push) {
2408
			$routes .= "push \"{$route}\"\n";
2409
		} else {
2410
			$routes .= "{$route}\n";
2411
		}
2412
	}
2413
	return $routes;
2414
}
2415

    
2416
function openvpn_gen_route_ipv4($network, $iroute = false) {
2417
	$i = ($iroute) ? "i" : "";
2418
	list($ip, $mask) = explode('/', trim($network));
2419
	$mask = gen_subnet_mask($mask);
2420
	return "{$i}route $ip $mask";
2421
}
2422

    
2423
function openvpn_gen_route_ipv6($network, $iroute = false) {
2424
	$i = ($iroute) ? "i" : "";
2425
	list($ipv6, $prefix) = explode('/', trim($network));
2426
	if (empty($prefix) && !is_numeric($prefix)) {
2427
		$prefix = "128";
2428
	}
2429
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2430
}
2431

    
2432
function openvpn_get_settings($mode, $vpnid) {
2433
	global $config;
2434

    
2435
	if (is_array($config['openvpn']['openvpn-server'])) {
2436
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2437
			if (isset($settings['disable'])) {
2438
				continue;
2439
			}
2440

    
2441
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2442
				return $settings;
2443
			}
2444
		}
2445
	}
2446

    
2447
	if (is_array($config['openvpn']['openvpn-client'])) {
2448
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
2449
			if (isset($settings['disable'])) {
2450
				continue;
2451
			}
2452

    
2453
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2454
				return $settings;
2455
			}
2456
		}
2457
	}
2458

    
2459
	return array();
2460
}
2461

    
2462
function openvpn_restart_by_vpnid($mode, $vpnid) {
2463
	$settings = openvpn_get_settings($mode, $vpnid);
2464
	openvpn_restart($mode, $settings);
2465
}
2466

    
2467
/****f* certs/openvpn_is_tunnel_network_in_use
2468
 * NAME
2469
 *   openvpn_is_tunnel_network_in_use
2470
 *     Check if the supplied network is in use as an OpenVPN server or client
2471
 *     tunnel network
2472
 * INPUTS
2473
 *   $net : The IPv4 or IPv6 network to check
2474
 * RESULT
2475
 *   boolean value: true if the network is in use, false otherwise.
2476
 ******/
2477

    
2478
function openvpn_is_tunnel_network_in_use($net) {
2479
	global $config;
2480
	init_config_arr(array('openvpn', 'openvpn-server'));
2481
	init_config_arr(array('openvpn', 'openvpn-client'));
2482
	/* Determine whether to check IPv4 or IPv6 tunnel networks */
2483
	$tocheck = 'tunnel_network';
2484
	if (is_v6($net)) {
2485
		$tocheck .= "v6";
2486
	}
2487
	/* Check all OpenVPN clients and servers for this tunnel network */
2488
	foreach(array('server', 'client') as $mode) {
2489
		foreach ($config['openvpn']["openvpn-{$mode}"] as $ovpn) {
2490
			if (!empty($ovpn[$tocheck]) &&
2491
			    ($ovpn[$tocheck] == $net)) {
2492
				return true;
2493
			}
2494
		}
2495
	}
2496
	return false;
2497
}
2498

    
2499
function openvpn_build_data_cipher_list($data_ciphers = 'AES-256-GCM,AES-128-GCM,CHACHA20-POLY1305', $fallback_cipher = 'AES-256-GBC', $ncp_enabled = true) {
2500
	/* If the data_ciphers list is empty, populate it with the fallback cipher. */
2501
	if (empty($data_ciphers) || !$ncp_enabled) {
2502
		$data_ciphers = $fallback_cipher;
2503
	}
2504
	/* Add the fallback cipher to the data ciphers list if it isn't already present */
2505
	if (!in_array($fallback_cipher, explode(',', $data_ciphers))) {
2506
		$data_ciphers .= ',' . $fallback_cipher;
2507
	}
2508
	return $data_ciphers;
2509
}
2510

    
2511
function openvpn_authscript_string($authmode, $strictusercn, $mode_id, $local_port) {
2512
	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";
2513
}
2514

    
2515
function openvpn_inuse($id, $mode) {
2516
	global $config;
2517

    
2518
	$type = ($mode == 'server') ? 's' : 'c';
2519

    
2520
	foreach (get_configured_interface_list(true) as $if) {
2521
		if ($config['interfaces'][$if]['if'] == "ovpn{$type}{$id}") {
2522
			return true;
2523
		}
2524
	}
2525

    
2526
	return false;
2527
}
2528

    
2529
function openvpn_tunnel_network_fix($tunnel_network) {
2530
	$tunnel_network = trim($tunnel_network);
2531
	if (is_subnet($tunnel_network)) {
2532
		/* convert to correct network address,
2533
		 * see https://redmine.pfsense.org/issues/11416 */
2534
		list($tunnel_ip, $tunnel_netmask) = explode('/', $tunnel_network);
2535
		$tunnel_network = gen_subnet($tunnel_ip, $tunnel_netmask) . '/' . $tunnel_netmask;
2536
	}
2537
	return $tunnel_network;
2538
}
2539

    
2540
?>
(33-33/61)