Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
204
	$list = array();
205

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

    
210
	return($list);
211
}
212

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

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

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

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

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

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

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

    
259
	return($list);
260
}
261

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

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

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

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

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

    
278
	return($list);
279
}
280

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

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

    
291
	$non_server_list = array();
292

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

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

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

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

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

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

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

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

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

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

    
358
	return($list);
359
}
360

    
361
function openvpn_create_key() {
362

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

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

    
371
	return $rslt;
372
}
373

    
374
function openvpn_create_dhparams($bits) {
375

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

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

    
384
	return $rslt;
385
}
386

    
387
function openvpn_vpnid_used($vpnid) {
388
	init_config_arr(array('openvpn', 'openvpn-server'));
389
	init_config_arr(array('openvpn', 'openvpn-client'));
390
	foreach (["server", "client"] as $mode) {
391
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
392
			if ($vpnid == $settings['vpnid']) {
393
				return true;
394
			}
395
		}
396
	}
397
	return false;
398
}
399

    
400
function openvpn_vpnid_next() {
401

    
402
	$vpnid = 1;
403
	while (openvpn_vpnid_used($vpnid)) {
404
		$vpnid++;
405
	}
406

    
407
	return $vpnid;
408
}
409

    
410
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
411

    
412
	$ovpn_settings = config_get_path('openvpn/openvpn-server', []);
413
	$ovpn_settings = array_merge($ovpn_settings, config_get_path('openvpn/openvpn-client', []));
414

    
415
	foreach ($ovpn_settings as $settings) {
416
		if (isset($settings['disable'])) {
417
			continue;
418
		}
419

    
420
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
421
			continue;
422
		}
423

    
424
		/* (TCP|UDP)(4|6) does not conflict unless interface is any */
425
		if (($interface != "any" && $settings['interface'] != "any") &&
426
		    (strlen($prot) == 4) &&
427
		    (strlen($settings['protocol']) == 4) &&
428
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
429
		    substr($prot,3,1) != substr($settings['protocol'],3,1)) {
430
			continue;
431
		}
432

    
433
		if ($port == $settings['local_port'] &&
434
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
435
		    ($interface == $settings['interface'] ||
436
		    $interface == "any" || $settings['interface'] == "any")) {
437
			return $settings['vpnid'];
438
		}
439
	}
440

    
441
	return 0;
442
}
443

    
444
function openvpn_port_next($prot, $interface = "wan") {
445

    
446
	$port = 1194;
447
	while (openvpn_port_used($prot, $interface, $port)) {
448
		$port++;
449
	}
450
	while (openvpn_port_used($prot, "any", $port)) {
451
		$port++;
452
	}
453

    
454
	return $port;
455
}
456

    
457
function openvpn_get_cipherlist() {
458

    
459
	$ciphers = array();
460
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
461
	$cipher_lines = explode("\n", trim($cipher_out));
462
	sort($cipher_lines);
463
	foreach ($cipher_lines as $line) {
464
		$words = explode(' ', $line, 2);
465
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
466
	}
467
	$ciphers["none"] = gettext("None (No Encryption)");
468
	return $ciphers;
469
}
470

    
471
function openvpn_get_curvelist() {
472
	global $cert_curve_compatible;
473
	$curves = array();
474
	$curves["none"] = gettext("Use Default");
475
	foreach ($cert_curve_compatible['OpenVPN'] as $curve) {
476
		$curves[$curve] = $curve;
477
	}
478
	return $curves;
479
}
480

    
481
function openvpn_validate_curve($curve) {
482
	$curves = openvpn_get_curvelist();
483
	return array_key_exists($curve, $curves);
484
}
485

    
486
/* Obtain the list of digest algorithms supported by openssl and their alternate names */
487
function openvpn_get_openssldigestmappings() {
488
	$digests = array();
489
	$digest_out = shell_exec('/usr/bin/openssl list -digest-algorithms | /usr/bin/grep "=>"');
490
	$digest_lines = explode("\n", trim($digest_out));
491
	sort($digest_lines);
492
	foreach ($digest_lines as $line) {
493
		$words = explode(' => ', $line, 2);
494
		$digests[$words[0]] = $words[1];
495
	}
496
	return $digests;
497
}
498

    
499
/* Obtain the list of digest algorithms supported by openvpn */
500
function openvpn_get_digestlist() {
501
	/* Grab the list from OpenSSL to check for duplicates or aliases */
502
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
503
	$digests = array();
504
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
505
	$digest_lines = explode("\n", trim($digest_out));
506
	sort($digest_lines);
507
	foreach ($digest_lines as $line) {
508
		$words = explode(' ', $line);
509
		/* Only add the entry if it is NOT also listed as being an alias/mapping by OpenSSL */
510
		if (!array_key_exists($words[0], $openssl_digest_mappings)) {
511
			$digests[$words[0]] = "{$words[0]} {$words[1]}";
512
		}
513
	}
514
	$digests["none"] = gettext("None (No Authentication)");
515
	return $digests;
516
}
517

    
518
/* Check to see if a digest name is an alias and if so, find the actual digest
519
 * algorithm instead. Useful for upgrade code that has to translate aliased
520
 * algorithms to their actual names.
521
 */
522
function openvpn_remap_digest($digest) {
523
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
524
	if (array_key_exists($digest, $openssl_digest_mappings)) {
525
		/* Some mappings point to other mappings, keep going until we find the actual digest algorithm */
526
		if (array_key_exists($openssl_digest_mappings[$digest], $openssl_digest_mappings)) {
527
			return openvpn_remap_digest($openssl_digest_mappings[$digest]);
528
		} else {
529
			return $openssl_digest_mappings[$digest];
530
		}
531
	}
532
	return $digest;
533
}
534

    
535
function openvpn_get_keydirlist() {
536
	$keydirs = array(
537
		'default'  => gettext('Use default direction'),
538
		'0' => gettext('Direction 0'),
539
		'1' => gettext('Direction 1'),
540
		'2' => gettext('Both directions'),
541
	);
542
	return $keydirs;
543
}
544

    
545
function openvpn_get_engines() {
546
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
547
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
548
	$openssl_engine_output = implode("\n", $openssl_engine_output);
549
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
550
	$openssl_engine_output = explode("\n", $openssl_engine_output);
551

    
552
	foreach ($openssl_engine_output as $oeo) {
553
		$keep = true;
554
		$details = explode("|", $oeo);
555
		$engine = array_shift($details);
556
		$linematch = array();
557
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
558
		foreach ($details as $dt) {
559
			if (strpos($dt, "unavailable") !== FALSE) {
560
				$keep = false;
561
			}
562
			if (strpos($dt, "available") !== FALSE) {
563
				continue;
564
			}
565
			if (strpos($dt, "[") !== FALSE) {
566
				$ciphers = trim($dt, "[]");
567
			}
568
		}
569
		if (!empty($ciphers)) {
570
			$ciphers = " - " . $ciphers;
571
		}
572
		if (strlen($ciphers) > 60) {
573
			$ciphers = substr($ciphers, 0, 60) . " ... ";
574
		}
575
		if ($keep) {
576
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
577
		}
578
	}
579
	return $openssl_engines;
580
}
581

    
582
function openvpn_get_buffer_values() {
583
	$sendbuf_max = get_single_sysctl('net.inet.tcp.sendbuf_max');
584
	$recvbuf_max = get_single_sysctl('net.inet.tcp.recvbuf_max');
585
	/* Usually these two are equal, but if they are not, take whichever one is lower. */
586
	$buffer_max = ($sendbuf_max <= $recvbuf_max) ? $sendbuf_max : $recvbuf_max;
587
	$buffer_values = array('' => gettext('Default'));
588
	for ($bs = 32; $bs >= 1; $bs /= 2) {
589
		$buffer_values[$buffer_max/$bs] = format_bytes($buffer_max/$bs);
590
	}
591
	return $buffer_values;
592
}
593

    
594
function openvpn_validate_engine($engine) {
595
	$engines = openvpn_get_engines();
596
	return array_key_exists($engine, $engines);
597
}
598

    
599
function openvpn_validate_host($value, $name) {
600
	$value = trim($value);
601
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
602
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
603
	}
604
	return false;
605
}
606

    
607
function openvpn_validate_port($value, $name, $first_port = 0) {
608
	$value = trim($value);
609
	if (!is_numeric($first_port)) {
610
		$first_port = 0;
611
	}
612
	if (empty($value) || !is_numeric($value) || $value < $first_port || ($value > 65535)) {
613
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from %s to 65535."), $name, $first_port);
614
	}
615
	return false;
616
}
617

    
618
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4", $alias = false) {
619
	$value = trim($value);
620
	$error = false;
621
	if (empty($value)) {
622
		return false;
623
	}
624
	$networks = explode(',', $value);
625

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

    
630
	foreach ($networks as $network) {
631
		if ($ipproto == "ipv4") {
632
			$error = !openvpn_validate_cidr_ipv4($network, $alias);
633
		} else {
634
			$error = !openvpn_validate_cidr_ipv6($network, $alias);
635
		}
636
		if ($error) {
637
			break;
638
		}
639
	}
640

    
641
	if ($error) {
642
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) or FQDN(s) separated by commas."), $name, $ipproto);
643
	} else {
644
		return false;
645
	}
646
}
647

    
648
function openvpn_validate_cidr_ipv4($value, $alias = false) {
649
	$value = trim($value);
650
	if (!empty($value)) {
651
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
652
			foreach (alias_to_subnets_recursive($value, true) as $net) {
653
				if (!is_subnetv4($net) && !is_fqdn($net)) {
654
					return false;
655
				}
656
			}
657
			return true;
658
		} else {
659
			if (!is_subnetv4($value)) {
660
				return false;
661
			}
662
		}
663
	}
664
	return true;
665
}
666

    
667
function openvpn_validate_cidr_ipv6($value, $alias = false) {
668
	$value = trim($value);
669
	if (!empty($value)) {
670
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
671
			foreach (alias_to_subnets_recursive($value, true) as $net) {
672
				if (!is_subnetv6($net) && !is_fqdn($net)) {
673
					return false;
674
				}
675
			}
676
			return true;
677
		} else {
678
			list($ipv6, $prefix) = explode('/', $value);
679
			if (empty($prefix)) {
680
				$prefix = "128";
681
			}
682
			if (!is_subnetv6($ipv6 . '/' . $prefix)) {
683
				return false;
684
			}
685
		}
686
	}
687
	return true;
688
}
689

    
690
function openvpn_validate_tunnel_network($value, $ipproto) {
691
	$value = trim($value);
692
	if (!empty($value)) {
693
		if (is_alias($value) && (alias_get_type($value) == 'network')) {
694
			$net = alias_to_subnets_recursive($value);
695
			if ((!is_subnetv4($net[0]) && ($ipproto == 'ipv4')) ||
696
			    (!is_subnetv6($net[0]) && ($ipproto == 'ipv6')) ||
697
			    (count($net) > 1)) {
698
				return false;
699
			}
700
			return true;
701
		} else {
702
			if ((!is_subnetv4($value) && ($ipproto == 'ipv4')) ||
703
			    (!is_subnetv6($value) && ($ipproto == 'ipv6'))) { 
704
				return false;
705
			}
706
		}
707
	}
708
	return true;
709
}
710

    
711
function openvpn_gen_tunnel_network($tunnel_network) {
712
	if (is_alias($tunnel_network)) {
713
		$net = alias_to_subnets_recursive($tunnel_network);
714
		$pair = openvpn_tunnel_network_fix($net[0]);
715
	} else {
716
		$pair = $tunnel_network;
717
	}
718
	return explode('/', $pair);
719
}
720

    
721
function openvpn_add_dhcpopts(& $settings, & $conf) {
722

    
723
	if (!empty($settings['dns_domain'])) {
724
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
725
	}
726

    
727
	if (!empty($settings['dns_server1'])) {
728
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
729
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
730
	}
731
	if (!empty($settings['dns_server2'])) {
732
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
733
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
734
	}
735
	if (!empty($settings['dns_server3'])) {
736
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
737
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
738
	}
739
	if (!empty($settings['dns_server4'])) {
740
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
741
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
742
	}
743

    
744
	if (!empty($settings['push_blockoutsidedns'])) {
745
		$conf .= "push \"block-outside-dns\"\n";
746
	}
747
	if (!empty($settings['push_register_dns'])) {
748
		$conf .= "push \"register-dns\"\n";
749
	}
750

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

    
758
	if ($settings['netbios_enable']) {
759

    
760
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
761
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
762
		}
763
		if (!empty($settings['dhcp_nbtscope'])) {
764
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
765
		}
766

    
767
		if (!empty($settings['wins_server1'])) {
768
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
769
		}
770
		if (!empty($settings['wins_server2'])) {
771
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
772
		}
773

    
774
		if (!empty($settings['nbdd_server1'])) {
775
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
776
		}
777
	}
778

    
779
	if ($settings['gwredir']) {
780
		$conf .= "push \"redirect-gateway def1\"\n";
781
	}
782
	if ($settings['gwredir6']) {
783
		$conf .= "push \"redirect-gateway ipv6\"\n";
784
	}
785
}
786

    
787
function openvpn_add_custom(& $settings, & $conf) {
788

    
789
	if ($settings['custom_options']) {
790

    
791
		$options = explode(';', $settings['custom_options']);
792

    
793
		if (is_array($options)) {
794
			foreach ($options as $option) {
795
				$conf .= "$option\n";
796
			}
797
		} else {
798
			$conf .= "{$settings['custom_options']}\n";
799
		}
800
	}
801
}
802

    
803
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
804
	global $g;
805

    
806
	$fpath = "{$g['openvpn_base']}/{$mode_id}/{$directive}";
807
	openvpn_create_dirs();
808
	file_put_contents($fpath, base64_decode($data));
809
	//chown($fpath, 'nobody');
810
	//chgrp($fpath, 'nobody');
811
	@chmod($fpath, 0600);
812

    
813
	$conf .= "{$directive} {$fpath} {$opt}\n";
814
}
815

    
816
function openvpn_delete_tmp($mode, $id) {
817
	global $g;
818

    
819
	/* delete temporary files created by connect script */
820
	if (($mode == "server") && (isset($id))) {
821
		unlink_if_exists("{$g['tmp_path']}/ovpn_ovpns{$id}_*.rules");
822
	}
823

    
824
	/* delete temporary files created by OpenVPN; only delete old files to
825
	 * avoid deleting files potentially still in use by another OpenVPN process
826
	*/
827
	$tmpfiles = array_filter(glob("{$g['tmp_path']}/openvpn_cc*.tmp"),'is_file');
828
	if (!empty($tmpfiles)) {
829
		foreach ($tmpfiles as $tmpfile) {
830
			if ((time() - filemtime($tmpfile)) > 60) {
831
				@unlink_if_exists($tmpfile);
832
			}
833
		}
834
	}
835
}
836

    
837
function openvpn_reconfigure($mode, $settings) {
838
	global $g, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
839

    
840
	if (empty($settings)) {
841
		return;
842
	}
843
	if (isset($settings['disable'])) {
844
		return;
845
	}
846
	openvpn_create_dirs();
847
	/*
848
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
849
	 * we use a vpnid number which is allocated for a particular client
850
	 * or server configuration. ( see openvpn_vpnid_next() )
851
	 */
852

    
853
	$vpnid = $settings['vpnid'];
854
	$mode_id = $mode.$vpnid;
855

    
856
	if (isset($settings['dev_mode'])) {
857
		$tunname = "{$settings['dev_mode']}{$vpnid}";
858
	} else {
859
		/* defaults to tun */
860
		$tunname = "tun{$vpnid}";
861
		$settings['dev_mode'] = "tun";
862
	}
863

    
864
	if ($mode == "server") {
865
		$devname = "ovpns{$vpnid}";
866
	} else {
867
		$devname = "ovpnc{$vpnid}";
868
	}
869

    
870
	/* is our device already configured */
871
	if (!does_interface_exist($devname)) {
872

    
873
		/* create the tap device if required */
874
		if (!file_exists("/dev/{$tunname}")) {
875
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
876
		}
877

    
878
		/* rename the device */
879
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
880

    
881
		/* add the device to the openvpn group */
882
		mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " group openvpn");
883

    
884
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
885
		$grouptmp = link_interface_to_group($ifname);
886
		if (!empty($grouptmp)) {
887
			array_walk($grouptmp, 'interface_group_add_member');
888
		}
889
		unset($grouptmp, $ifname);
890
	}
891

    
892
	$pfile = g_get('varrun_path') . "/openvpn_{$mode_id}.pid";
893
	$proto = strtolower($settings['protocol']);
894
	if (substr($settings['protocol'], 0, 3) == "TCP") {
895
			$proto = "{$proto}-{$mode}";
896
	}
897
	$dev_mode = $settings['dev_mode'];
898
	$fbcipher = $settings['data_ciphers_fallback'];
899
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
900
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
901

    
902
	$interface = get_failover_interface($settings['interface']);
903
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
904
	$ipaddr = $settings['ipaddr'];
905

    
906
	// If a specific ip address (VIP) is requested, use it.
907
	// Otherwise, if a specific interface is requested, use it
908
	// If "any" interface was selected, local directive will be omitted.
909
	if (is_ipaddrv4($ipaddr)) {
910
		$iface_ip = $ipaddr;
911
	} elseif (!empty($interface) && strcmp($interface, "any")) {
912
		$iface_ip=get_interface_ip($interface);
913
	}
914
	if (is_ipaddrv6($ipaddr)) {
915
		$iface_ipv6 = $ipaddr;
916
	} elseif (!empty($interface) && strcmp($interface, "any")) {
917
		/* get correct interface name for 6RD/6to4 interfaces
918
		 * see https://redmine.pfsense.org/issues/11674 */
919
		if (is_stf_interface($settings['interface'])) {
920
			$iface_ipv6=get_interface_ipv6($settings['interface']);
921
		} else {
922
			$iface_ipv6=get_interface_ipv6($interface);
923
		}
924
	}
925

    
926
	$conf = "dev {$devname}\n";
927
	if (isset($settings['verbosity_level'])) {
928
		$conf .= "verb {$settings['verbosity_level']}\n";
929
	}
930

    
931
	$conf .= "dev-type {$settings['dev_mode']}\n";
932
	$conf .= "dev-node /dev/{$tunname}\n";
933
	$conf .= "writepid {$pfile}\n";
934
	$conf .= "#user nobody\n";
935
	$conf .= "#group nobody\n";
936
	$conf .= "script-security 3\n";
937
	$conf .= "daemon\n";
938

    
939
	if (!empty($settings['ping_method']) &&
940
	    $settings['ping_method'] == 'ping') {
941
		$conf .= "ping {$settings['ping_seconds']}\n";
942

    
943
		if (!empty($settings['ping_push'])) {
944
			$conf .= "push \"ping {$settings['ping_seconds']}\"\n";
945
		}
946

    
947
		$action = str_replace("_", "-", $settings['ping_action']);
948
		$conf .= "{$action} {$settings['ping_action_seconds']}\n";
949

    
950
		if (!empty($settings['ping_action_push'])) {
951
			$conf .= "push \"{$action} " .
952
			    "{$settings['ping_action_seconds']}\"\n";
953
		}
954
	} else {
955
		$conf .= "keepalive " .
956
		    ($settings['keepalive_interval']
957
			?: $openvpn_default_keepalive_interval) . " " .
958
		    ($settings['keepalive_timeout']
959
			?: $openvpn_default_keepalive_timeout) . "\n";
960
	}
961

    
962
	$conf .= "ping-timer-rem\n";
963
	$conf .= "persist-tun\n";
964
	$conf .= "persist-key\n";
965
	$conf .= "proto {$proto}\n";
966
	$conf .= "auth {$digest}\n";
967
	if ($settings['dns_add']) {
968
		$conf .= "up /usr/local/sbin/ovpn-dnslinkup\n";
969
	} else {
970
		$conf .= "up /usr/local/sbin/ovpn-linkup\n";
971
	}
972
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
973
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
974
		switch ($settings['mode']) {
975
			case 'server_user':
976
			case 'server_tls_user':
977
			case 'server_tls':
978
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
979
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
980
				break;
981
		}
982
	}
983
	if ($settings['dev_mode'] === 'tun' && config_path_enabled('unbound') &&
984
		config_path_enabled('unbound','regovpnclients')) {
985
		if (($settings['mode'] == 'server_tls') || ($settings['mode'] == 'server_tls_user') ||
986
		    (($settings['mode'] == 'server_user') && ($settings['username_as_common_name'] == 'enabled'))) {
987
			$domain = !empty($settings['dns_domain']) ? $settings['dns_domain'] : config_get_path('system/domain');
988
			if (is_domain($domain)) {
989
				$conf .= "learn-address \"/usr/local/sbin/openvpn.learn-address.sh $domain\"\n";
990
			}
991
		}
992
	}
993

    
994
	/*
995
	 * When binding specific address, wait cases where interface is in
996
	 * tentative state otherwise it will fail
997
	 */
998
	$wait_tentative = false;
999

    
1000
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
1001
	switch ($settings['protocol']) {
1002
		case 'UDP':
1003
		case 'TCP':
1004
			$conf .= "multihome\n";
1005
			break;
1006
		case 'UDP4':
1007
		case 'TCP4':
1008
			if (is_ipaddrv4($iface_ip)) {
1009
				$conf .= "local {$iface_ip}\n";
1010
			}
1011
			if ($settings['interface'] == "any") {
1012
				$conf .= "multihome\n";
1013
			}
1014
			break;
1015
		case 'UDP6':
1016
		case 'TCP6':
1017
			if (is_ipaddrv6($iface_ipv6)) {
1018
				$conf .= "local {$iface_ipv6}\n";
1019
				$wait_tentative = true;
1020
			}
1021
			if ($settings['interface'] == "any") {
1022
				$conf .= "multihome\n";
1023
			}
1024
			break;
1025
		default:
1026
	}
1027

    
1028
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
1029
		$conf .= "engine {$settings['engine']}\n";
1030
	}
1031

    
1032
	// server specific settings
1033
	if ($mode == 'server') {
1034

    
1035
		list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1036
		list($ipv6, $prefix) = openvpn_gen_tunnel_network($settings['tunnel_networkv6']);
1037
		$mask = gen_subnet_mask($cidr);
1038

    
1039
		// configure tls modes
1040
		switch ($settings['mode']) {
1041
			case 'p2p_tls':
1042
			case 'server_tls':
1043
			case 'server_user':
1044
			case 'server_tls_user':
1045
				$conf .= "tls-server\n";
1046
				break;
1047
		}
1048

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

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

    
1161
		// The local port to listen on
1162
		$conf .= "lport {$settings['local_port']}\n";
1163

    
1164
		// The management port to listen on
1165
		// Use unix socket to overcome the problem on any type of server
1166
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1167
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
1168

    
1169
		if ($settings['maxclients']) {
1170
			$conf .= "max-clients {$settings['maxclients']}\n";
1171
		}
1172

    
1173
		// Can we push routes, and should we?
1174
		if ($settings['local_network'] && !$settings['gwredir']) {
1175
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1176
		}
1177
		if ($settings['local_networkv6'] && !$settings['gwredir6']) {
1178
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1179
		}
1180

    
1181
		switch ($settings['mode']) {
1182
			case 'server_tls':
1183
			case 'server_user':
1184
			case 'server_tls_user':
1185
				// Configure client dhcp options
1186
				openvpn_add_dhcpopts($settings, $conf);
1187
				if ($settings['client2client']) {
1188
					$conf .= "client-to-client\n";
1189
				}
1190
				break;
1191
		}
1192
		$connlimit = "0";
1193
		if ($settings['mode'] != 'p2p_shared_key' &&
1194
		    isset($settings['duplicate_cn'])) {
1195
			$conf .= "duplicate-cn\n";
1196
			if ($settings['connlimit']) {
1197
				$connlimit = "{$settings['connlimit']}";
1198
			}
1199
		}
1200
		if (($settings['mode'] != 'p2p_shared_key') &&
1201
		    isset($settings['remote_cert_tls'])) {
1202
			$conf .= "remote-cert-tls client\n";
1203
		}
1204
	}
1205

    
1206
	// client specific settings
1207

    
1208
	if ($mode == 'client') {
1209

    
1210
		$add_pull = false;
1211
		// configure p2p mode
1212
		if ($settings['mode'] == 'p2p_tls') {
1213
			$conf .= "tls-client\n";
1214
		}
1215

    
1216
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1217
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1218
		//  ensure a random source port.
1219
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1220
			$conf .= "nobind\n";
1221
		} elseif ($settings['local_port']) {
1222
			$conf .= "lport {$settings['local_port']}\n";
1223
		} else {
1224
			$conf .= "lport 0\n";
1225
		}
1226

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

    
1230
		// The remote server
1231
		$remoteproto = strtolower($settings['protocol']);
1232
		if (substr($remoteproto, 0, 3) == "tcp") {
1233
			$remoteproto .= "-{$mode}";
1234
		}
1235
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']} {$remoteproto}\n";
1236

    
1237
		if (!empty($settings['use_shaper'])) {
1238
			$conf .= "shaper {$settings['use_shaper']}\n";
1239
		}
1240

    
1241
		if (!empty($settings['tunnel_network'])) {
1242
			list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1243
			$mask = gen_subnet_mask($cidr);
1244
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1245
			if (($settings['dev_mode'] == 'tun') &&
1246
			    (($settings['topology'] == 'net30') ||
1247
			    ($cidr >= 30))) {
1248
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1249
			} else {
1250
				$conf .= "ifconfig {$ip2} {$mask}\n";
1251
				if ($settings['mode'] == 'p2p_tls') {
1252
					$add_pull = true;
1253
				}
1254
			}
1255
		}
1256

    
1257
		if (!empty($settings['tunnel_networkv6'])) {
1258
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1259
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1260
			if ($settings['dev_mode'] == 'tun') {
1261
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1262
			} else {
1263
				$conf .= "ifconfig-ipv6 {$ipv6_1}/{$prefix} {$ipv6_2}\n";
1264
				if ($settings['mode'] == 'p2p_tls') {
1265
					$add_pull = true;
1266
				}
1267
			}
1268
		}
1269

    
1270
		/* If both tunnel networks are empty, then pull from server. */
1271
		if (empty($settings['tunnel_network']) &&
1272
		    empty($settings['tunnel_networkv6'])) {
1273
			$add_pull = true;
1274
		}
1275

    
1276
		/* Only add "pull" if the tunnel network is undefined or using tap mode.
1277
		   OpenVPN can't pull settings from a server in point-to-point mode. */
1278
		if (($settings['mode'] == 'p2p_tls') && $add_pull) {
1279
			$conf .= "pull\n";
1280
		}
1281

    
1282
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
1283
			$up_file = "{$g['openvpn_base']}/{$mode_id}/up";
1284
			$conf .= "auth-user-pass {$up_file}\n";
1285
			if (!$settings['auth-retry-none']) {
1286
				$conf .= "auth-retry nointeract\n";
1287
			}
1288
			if ($settings['auth_user']) {
1289
				$userpass = "{$settings['auth_user']}\n";
1290
			} else {
1291
				$userpass = "";
1292
			}
1293
			if ($settings['auth_pass']) {
1294
				$userpass .= "{$settings['auth_pass']}\n";
1295
			}
1296
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
1297
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
1298
				$userpass .= "\n";
1299
			}
1300
			file_put_contents($up_file, $userpass);
1301
		}
1302

    
1303
		if ($settings['proxy_addr']) {
1304
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1305
			if ($settings['proxy_authtype'] != "none") {
1306
				$conf .= " {$g['openvpn_base']}/{$mode_id}/proxy_auth {$settings['proxy_authtype']}";
1307
				$proxypas = "{$settings['proxy_user']}\n";
1308
				$proxypas .= "{$settings['proxy_passwd']}\n";
1309
				file_put_contents("{$g['openvpn_base']}/{$mode_id}/proxy_auth", $proxypas);
1310
			}
1311
			$conf .= " \n";
1312
		}
1313

    
1314
		if (($settings['mode'] != 'shared_key') &&
1315
		    isset($settings['remote_cert_tls'])) {
1316
			$conf .= "remote-cert-tls server\n";
1317
		}
1318
	}
1319

    
1320
	// Add a remote network route if set, and only for p2p modes.
1321
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4", true) === FALSE)) {
1322
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1323
	}
1324
	// Add a remote network route if set, and only for p2p modes.
1325
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6", true) === FALSE)) {
1326
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1327
	}
1328

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

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

    
1417
	/* Data encryption cipher support.
1418
	 * If it is not set, assume enabled since that is OpenVPN's default.
1419
	 * Note that diabling this is now deprecated and will be removed in a future version of OpenVPN */
1420
	if ($settings['mode'] == "p2p_shared_key") {
1421
		$conf .= "cipher {$fbcipher}\n";
1422
	} else {
1423
		$conf .= "data-ciphers " . str_replace(',', ':', openvpn_build_data_cipher_list($settings['data_ciphers'], $fbcipher)) . "\n";
1424
		$conf .= "data-ciphers-fallback {$fbcipher}\n";
1425
	}
1426

    
1427
	if (!empty($settings['allow_compression'])) {
1428
		$conf .= "allow-compression {$settings['allow_compression']}\n";
1429
	}
1430

    
1431
	$compression = "";
1432
	switch ($settings['compression']) {
1433
		case 'none':
1434
			$settings['compression'] = '';
1435
		case 'lz4':
1436
		case 'lz4-v2':
1437
		case 'lzo':
1438
		case 'stub':
1439
		case 'stub-v2':
1440
			$compression .= "compress {$settings['compression']}";
1441
			break;
1442
		case 'noadapt':
1443
			$compression .= "comp-noadapt";
1444
			break;
1445
		case 'adaptive':
1446
		case 'yes':
1447
		case 'no':
1448
			$compression .= "comp-lzo {$settings['compression']}";
1449
			break;
1450
		default:
1451
			/* Add nothing to the configuration */
1452
			break;
1453
	}
1454

    
1455
	if (($settings['allow_compression'] != 'no') &&
1456
	    !empty($compression)) {
1457
		$conf .= "{$compression}\n";
1458
		if ($settings['compression_push']) {
1459
			$conf .= "push \"{$compression}\"\n";
1460
		}
1461
	}
1462

    
1463
	if ($settings['passtos']) {
1464
		$conf .= "passtos\n";
1465
	}
1466

    
1467
	if ($mode == 'client') {
1468
		$conf .= "resolv-retry infinite\n";
1469
	}
1470

    
1471
	if ($settings['dynamic_ip']) {
1472
		$conf .= "persist-remote-ip\n";
1473
		$conf .= "float\n";
1474
	}
1475

    
1476
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1477
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1478
		if (empty($settings['topology'])) {
1479
			$settings['topology'] = "subnet";
1480
		}
1481
		$conf .= "topology {$settings['topology']}\n";
1482
	}
1483

    
1484
	// New client features
1485
	if ($mode == "client") {
1486
		// Dont add/remove routes checkbox
1487
		if ($settings['route_no_exec']) {
1488
			$conf .= "route-noexec\n";
1489
		}
1490
	}
1491

    
1492
	/* UDP Fast I/O. Only compatible with UDP and also not compatible with OpenVPN's "shaper" directive. */
1493
	if ($settings['udp_fast_io']
1494
	    && (strtolower(substr($settings['protocol'], 0, 3)) == "udp")
1495
	    && (empty($settings['use_shaper']))) {
1496
		$conf .= "fast-io\n";
1497
	}
1498

    
1499
	/* Exit Notify.
1500
	 * Only compatible with UDP and specific combinations of
1501
	 * modes and settings, including:
1502
	 * if type is server AND
1503
	 *	mode is not shared key AND
1504
	 *		tunnel network CIDR mask < 30 AND
1505
	 *		tunnel network is not blank
1506
	 * if type is client AND
1507
	 *	mode is not shared key AND
1508
	 *		tunnel network is blank OR
1509
	 *		tunnel network CIDR mask < 30
1510
	 */
1511
	list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1512
	if ((!empty($settings['exit_notify']) &&
1513
	    is_numericint($settings['exit_notify']) &&
1514
	    (strtolower(substr($settings['protocol'], 0, 3)) == "udp")) &&
1515
	    ((($mode == "server") && (($settings['mode'] != 'p2p_shared_key') && (($cidr < 30) && !empty($ip)))) ||
1516
	    (($mode == "client") && (($settings['mode'] != 'p2p_shared_key') && (($cidr < 30) || empty($ip)))))) {
1517
		$conf .= "explicit-exit-notify {$settings['exit_notify']}\n";
1518
	}
1519

    
1520
	/* Inactive Seconds
1521
	 * Has similar restrictions to Exit Notify (above) but only for server mode.
1522
	 */
1523
	if (!empty($settings['inactive_seconds']) &&
1524
	    !(($mode == "server") && (($settings['mode'] == 'p2p_shared_key') || (($cidr >= 30) || empty($ip))))) {
1525
		$conf .= "inactive {$settings['inactive_seconds']}\n";
1526
	}
1527

    
1528
	/* Send and Receive Buffer Settings */
1529
	if (is_numericint($settings['sndrcvbuf'])
1530
	    && ($settings['sndrcvbuf'] > 0)
1531
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1532
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1533
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1534
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1535
	}
1536

    
1537
	openvpn_add_custom($settings, $conf);
1538

    
1539
	/* add nopull option after custom options, see https://redmine.pfsense.org/issues/11448 */
1540
	if (($mode == "client") && $settings['route_no_pull']) {
1541
		// Dont pull routes checkbox
1542
		$conf .= "route-nopull\n";
1543
	}
1544

    
1545
	openvpn_create_dirs();
1546
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1547
	file_put_contents($fpath, $conf);
1548
	unset($conf);
1549
	$fpath = "{$g['openvpn_base']}/{$mode_id}/interface";
1550
	file_put_contents($fpath, $interface);
1551
	$fpath = "{$g['openvpn_base']}/{$mode_id}/connuserlimit";
1552
	file_put_contents($fpath, $connlimit);
1553
	//chown($fpath, 'nobody');
1554
	//chgrp($fpath, 'nobody');
1555
	@chmod("{$g['openvpn_base']}/{$mode_id}/config.ovpn", 0600);
1556
	@chmod("{$g['openvpn_base']}/{$mode_id}/interface", 0600);
1557
	@chmod("{$g['openvpn_base']}/{$mode_id}/key", 0600);
1558
	@chmod("{$g['openvpn_base']}/{$mode_id}/tls-auth", 0600);
1559
	@chmod("{$g['openvpn_base']}/{$mode_id}/conf", 0600);
1560
	@chmod("{$g['openvpn_base']}/{$mode_id}/connuserlimit", 0600);
1561

    
1562
	if ($wait_tentative) {
1563
		interface_wait_tentative($interface);
1564
	}
1565
}
1566

    
1567
function openvpn_restart($mode, $settings) {
1568
	global $g;
1569

    
1570
	$vpnid = $settings['vpnid'];
1571
	$mode_id = $mode.$vpnid;
1572
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1573
	openvpn_reconfigure($mode, $settings);
1574
	/* kill the process if running */
1575
	$pfile = g_get('varrun_path')."/openvpn_{$mode_id}.pid";
1576
	if (file_exists($pfile)) {
1577

    
1578
		/* read the pid file */
1579
		$pid = rtrim(file_get_contents($pfile));
1580
		unlink($pfile);
1581
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1582

    
1583
		/* send a term signal to the process */
1584
		posix_kill($pid, SIGTERM);
1585

    
1586
		/* wait until the process exits, or timeout and kill it */
1587
		$i = 0;
1588
		while (posix_kill($pid, 0)) {
1589
			usleep(250000);
1590
			if ($i > 10) {
1591
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1592
				posix_kill($pid, SIGKILL);
1593
				usleep(500000);
1594
			}
1595
			$i++;
1596
		}
1597
	}
1598

    
1599
	if (isset($settings['disable'])) {
1600
		openvpn_delete($mode, $settings);
1601
		unlock($lockhandle);
1602
		return;
1603
	}
1604

    
1605
	openvpn_delete_tmp($mode, $vpnid);
1606

    
1607
	/* Do not start an instance if we are not CARP master on this vip! */
1608
	if (strstr($settings['interface'], "_vip")) {
1609
	       	$carpstatus = get_carp_bind_status($settings['interface']);
1610
		/* Do not start an instance if vip aliased to BACKUP CARP
1611
		 * see https://redmine.pfsense.org/issues/11793 */ 
1612
		if (in_array($carpstatus, array('BACKUP', 'INIT'))) {
1613
			unlock($lockhandle);
1614
			return;
1615
		} 
1616
	}
1617

    
1618
	/* Check if client is bound to a gateway group */
1619
	$a_groups = return_gateway_groups_array(true);
1620
	if (is_array($a_groups[$settings['interface']])) {
1621
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1622
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1623
			unlock($lockhandle);
1624
			return;
1625
		}
1626
	}
1627

    
1628
	/* start the new process */
1629
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1630
	openvpn_clear_route($mode, $settings);
1631
	$res = mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1632
	if ($res == 0) {
1633
		$i = 0;
1634
		$pid = "--";
1635
		while ($i < 3000) {
1636
			if (isvalidpid($pfile)) {
1637
				$pid = rtrim(file_get_contents($pfile));
1638
				break;
1639
			}
1640
			usleep(1000);
1641
			$i++;
1642
		}
1643
		syslog(LOG_INFO, "OpenVPN PID written: {$pid}");
1644
	} else {
1645
		syslog(LOG_ERR, "OpenVPN failed to start");
1646
	}
1647
	if (!platform_booting()) {
1648
		send_event("filter reload");
1649
	}
1650
	unlock($lockhandle);
1651
}
1652

    
1653
function openvpn_delete($mode, $settings) {
1654
	global $g;
1655

    
1656
	$vpnid = $settings['vpnid'];
1657
	$mode_id = $mode.$vpnid;
1658

    
1659
	if ($mode == "server") {
1660
		$devname = "ovpns{$vpnid}";
1661
	} else {
1662
		$devname = "ovpnc{$vpnid}";
1663
	}
1664

    
1665
	/* kill the process if running */
1666
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1667
	if (file_exists($pfile)) {
1668

    
1669
		/* read the pid file */
1670
		$pid = trim(file_get_contents($pfile));
1671
		unlink($pfile);
1672

    
1673
		/* send a term signal to the process */
1674
		posix_kill($pid, SIGTERM);
1675
	}
1676

    
1677
	/* destroy the device */
1678
	pfSense_interface_destroy($devname);
1679

    
1680
	/* Invalidate cache */
1681
	get_interface_arr(true);
1682

    
1683
	/* remove the configuration files */
1684
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*/*");
1685
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*");
1686
	openvpn_delete_tmp($mode, $vpnid);
1687
	filter_configure();
1688
}
1689

    
1690
function openvpn_resync_csc($settings) {
1691
	global $g, $openvpn_tls_server_modes;
1692
	if (isset($settings['disable'])) {
1693
		openvpn_delete_csc($settings);
1694
		return;
1695
	}
1696
	openvpn_create_dirs();
1697

    
1698
	if (empty($settings['server_list'])) {
1699
		$csc_server_list = array();
1700
	} else {
1701
		$csc_server_list = explode(",", $settings['server_list']);
1702
	}
1703

    
1704
	$conf = '';
1705
	if ($settings['block']) {
1706
		$conf .= "disable\n";
1707
	}
1708

    
1709
	if ($settings['push_reset']) {
1710
		$conf .= "push-reset\n";
1711
	}
1712

    
1713
	if ($settings['remove_route']) {
1714
		$conf .= "push-remove route\n";
1715
	}
1716

    
1717
	if ($settings['local_network']) {
1718
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1719
	}
1720
	if ($settings['local_networkv6']) {
1721
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1722
	}
1723

    
1724
	// Add a remote network iroute if set
1725
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4", true) === FALSE) {
1726
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1727
	}
1728
	// Add a remote network iroute if set
1729
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6", true) === FALSE) {
1730
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1731
	}
1732

    
1733
	openvpn_add_dhcpopts($settings, $conf);
1734

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

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

    
1759
				if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1760
					list($ipv6, $prefix) = openvpn_gen_tunnel_network($serversettings['tunnel_networkv6']);
1761
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1762
					$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1763
				}
1764

    
1765
				file_put_contents($csc_path, $csc_conf);
1766
				chown($csc_path, 'nobody');
1767
				chgrp($csc_path, 'nobody');
1768
			}
1769
		}
1770
	}
1771
}
1772

    
1773
function openvpn_resync_csc_all() {
1774
	init_config_arr(array('openvpn', 'openvpn-csc'));
1775
	foreach (config_get_path('openvpn/openvpn-csc', []) as $settings) {
1776
		openvpn_resync_csc($settings);
1777
	}
1778
}
1779

    
1780
function openvpn_delete_csc($settings) {
1781
	global $g, $openvpn_tls_server_modes;
1782
	if (empty($settings['server_list'])) {
1783
		$csc_server_list = array();
1784
	} else {
1785
		$csc_server_list = explode(",", $settings['server_list']);
1786
	}
1787

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

    
1802
// Resync the configuration and restart the VPN
1803
function openvpn_resync($mode, $settings) {
1804
	openvpn_restart($mode, $settings);
1805
}
1806

    
1807
// Resync and restart all VPNs
1808
function openvpn_resync_all($interface = "", $protocol = "") {
1809
	global $g;
1810

    
1811
	if ($interface <> "") {
1812
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1813
	} else {
1814
		log_error(gettext("Resyncing OpenVPN instances."));
1815
	}
1816

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

    
1835
			if (!$ip_change && file_exists($fpath)) {
1836
				$gw_group_change =
1837
				    (trim(file_get_contents($fpath), " \t\n") !=
1838
				    get_failover_interface(
1839
					$settings['interface']));
1840
			}
1841

    
1842
			if ($ip_change || $gw_group_change) {
1843
				if (!$dirs) {
1844
					openvpn_create_dirs();
1845
				}
1846
				openvpn_resync($type, $settings);
1847
				$restarted = true;
1848
				$dirs = true;
1849
			}
1850
		}
1851
	}
1852

    
1853
	if ($restarted) {
1854
		openvpn_resync_csc_all();
1855

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

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

    
1890
function openvpn_get_active_servers($type="multipoint") {
1891
	global $g;
1892

    
1893
	$servers = array();
1894
	foreach (config_get_path('openvpn/openvpn-server', []) as $settings) {
1895
		if (empty($settings) || isset($settings['disable'])) {
1896
			continue;
1897
		}
1898

    
1899
		$prot = $settings['protocol'];
1900
		$port = $settings['local_port'];
1901

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

    
1916
		if ((($server['mode'] == "p2p_shared_key") ||
1917
			 (($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network']) && ($server['mode'] == 'p2p_tls')) ||
1918
			 ($sm >= 30)) &&
1919
			($type == "p2p")) {
1920
			$servers[] = openvpn_get_client_status($server, $socket);
1921
		} elseif (($server['mode'] != "p2p_shared_key") &&
1922
				  !(($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network']) && ($server['mode'] == 'p2p_tls')) &&
1923
				  ($type == "multipoint") &&
1924
				  ($sm < 30)) {
1925
			$servers[] = openvpn_get_server_status($server, $socket);
1926
		}
1927
	}
1928

    
1929
	return $servers;
1930
}
1931

    
1932
function openvpn_get_server_status($server, $socket) {
1933
	$errval = null;
1934
	$errstr = null;
1935
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1936
	if ($fp) {
1937
		stream_set_timeout($fp, 1);
1938

    
1939
		/* send our status request */
1940
		fputs($fp, "status 2\n");
1941

    
1942
		/* recv all response lines */
1943
		while (!feof($fp)) {
1944

    
1945
			/* read the next line */
1946
			$line = fgets($fp, 1024);
1947

    
1948
			$info = stream_get_meta_data($fp);
1949
			if ($info['timed_out']) {
1950
				break;
1951
			}
1952

    
1953
			/* parse header list line */
1954
			if (strstr($line, "HEADER")) {
1955
				continue;
1956
			}
1957

    
1958
			/* parse end of output line */
1959
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1960
				break;
1961
			}
1962

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

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

    
2008
function openvpn_get_active_clients() {
2009
	global $g;
2010

    
2011
	$clients = array();
2012
		foreach (config_get_path('openvpn/openvpn-client', []) as $settings) {
2013
			if (empty($settings) || isset($settings['disable'])) {
2014
				continue;
2015
			}
2016

    
2017
			$prot = $settings['protocol'];
2018
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
2019

    
2020
			$client = array();
2021
			$client['port'] = $settings['local_port'];
2022
			if ($settings['description']) {
2023
				$client['name'] = "{$settings['description']} {$prot}{$port}";
2024
			} else {
2025
				$client['name'] = "Client {$prot}{$port}";
2026
			}
2027

    
2028
			$client['vpnid'] = $settings['vpnid'];
2029
			$client['mgmt'] = "client{$client['vpnid']}";
2030
			$socket = "unix://{$g['openvpn_base']}/{$client['mgmt']}/sock";
2031
			$client['status']="down";
2032

    
2033
			$clients[] = openvpn_get_client_status($client, $socket);
2034
	}
2035
	return $clients;
2036
}
2037

    
2038
function openvpn_get_client_status($client, $socket) {
2039
	$errval = null;
2040
	$errstr = null;
2041
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
2042
	if ($fp) {
2043
		stream_set_timeout($fp, 1);
2044
		/* send our status request */
2045
		fputs($fp, "state 1\n");
2046

    
2047
		/* recv all response lines */
2048
		while (!feof($fp)) {
2049
			/* read the next line */
2050
			$line = fgets($fp, 1024);
2051

    
2052
			$info = stream_get_meta_data($fp);
2053
			if ($info['timed_out']) {
2054
				break;
2055
			}
2056

    
2057
			/* Get the client state */
2058
			if (substr_count($line, ',') >= 7) {
2059
				$list = explode(",", trim($line));
2060
				$list = array_map('trim', $list);
2061

    
2062
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
2063
				$client['state'] = $list[1];
2064
				$client['state_detail'] = $list[2];
2065
				$client['virtual_addr'] = $list[3];
2066
				$client['remote_host'] = $list[4];
2067
				$client['remote_port'] = $list[5];
2068
				$client['local_host'] = $list[6];
2069
				$client['local_port'] = $list[7];
2070
				$client['virtual_addr6'] = $list[8];
2071

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

    
2123
				if (!empty($client['state_detail'])) {
2124
					$client['status'] .= " (" . ucwords(strtolower(str_replace(array('_', '-'), ' ', $client['state_detail']))) . ")";
2125
				}
2126

    
2127
			}
2128
			/* parse end of output line */
2129
			if (strstr($line, "END") || strstr($line, "ERROR")) {
2130
				break;
2131
			}
2132
		}
2133

    
2134
		/* If up, get read/write stats */
2135
		if (strcmp($client['state'], "CONNECTED") == 0) {
2136
			fputs($fp, "status 2\n");
2137
			/* recv all response lines */
2138
			while (!feof($fp)) {
2139
				/* read the next line */
2140
				$line = fgets($fp, 1024);
2141

    
2142
				$info = stream_get_meta_data($fp);
2143
				if ($info['timed_out']) {
2144
					break;
2145
				}
2146

    
2147
				if (strstr($line, "TCP/UDP read bytes")) {
2148
					$list = explode(",", $line);
2149
					$client['bytes_recv'] = $list[1];
2150
				}
2151

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

    
2157
				/* parse end of output line */
2158
				if (strstr($line, "END")) {
2159
					break;
2160
				}
2161
			}
2162
		}
2163

    
2164
		fclose($fp);
2165

    
2166
	} else {
2167
		$client['remote_host'] = gettext("Unable to contact daemon");
2168
		$client['virtual_addr'] = gettext("Service not running?");
2169
		$client['bytes_recv'] = 0;
2170
		$client['bytes_sent'] = 0;
2171
		$client['connect_time'] = 0;
2172
	}
2173
	return $client;
2174
}
2175

    
2176
function openvpn_kill_client($port, $remipp, $client_id) {
2177
	global $g;
2178

    
2179
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
2180
	$tcpsrv = "unix://{$g['openvpn_base']}/{$port}/sock";
2181
	$errval = null;
2182
	$errstr = null;
2183

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

    
2198
			$info = stream_get_meta_data($fp);
2199
			if ($info['timed_out']) {
2200
				break;
2201
			}
2202

    
2203
			/* parse header list line */
2204
			if (strpos($line, "INFO:") !== false) {
2205
				continue;
2206
			}
2207
			if (strpos($line, "SUCCESS") !== false) {
2208
				$killed = 0;
2209
			}
2210
			break;
2211
		}
2212
		fclose($fp);
2213
	}
2214
	return $killed;
2215
}
2216

    
2217
function openvpn_refresh_crls() {
2218
	global $g;
2219

    
2220
	openvpn_create_dirs();
2221

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

    
2251
function openvpn_create_dirs() {
2252
	global $g, $openvpn_tls_server_modes;
2253
	if (!is_dir(g_get('openvpn_base'))) {
2254
		safe_mkdir(g_get('openvpn_base'), 0750);
2255
	}
2256

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

    
2275
function openvpn_get_interface_ip($ip, $cidr) {
2276
	$subnet = gen_subnetv4($ip, $cidr);
2277
	if ($cidr == 31) {
2278
		$ip1 = $subnet;
2279
	} else {
2280
		$ip1 = ip_after($subnet);
2281
	}
2282
	$ip2 = ip_after($ip1);
2283
	return array($ip1, $ip2);
2284
}
2285

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

    
2299
function openvpn_clear_route($mode, $settings) {
2300
	if (empty($settings['tunnel_network'])) {
2301
		return;
2302
	}
2303
	list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
2304
	$mask = gen_subnet_mask($cidr);
2305
	$clear_route = false;
2306

    
2307
	switch ($settings['mode']) {
2308
		case 'shared_key':
2309
			$clear_route = true;
2310
			break;
2311
		case 'p2p_tls':
2312
		case 'p2p_shared_key':
2313
			if ($cidr >= 30) {
2314
				$clear_route = true;
2315
			}
2316
			break;
2317
	}
2318

    
2319
	if ($clear_route && !empty($ip) && !empty($mask)) {
2320
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2321
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2322
		/* XXX: Family for route? */
2323
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2324
	}
2325
}
2326

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

    
2363
	foreach ($networks as $network) {
2364
		if ($ipproto == "ipv4") {
2365
			$route = openvpn_gen_route_ipv4($network, $iroute);
2366
		} else {
2367
			$route = openvpn_gen_route_ipv6($network, $iroute);
2368
		}
2369

    
2370
		if ($push) {
2371
			$routes .= "push \"{$route}\"\n";
2372
		} else {
2373
			$routes .= "{$route}\n";
2374
		}
2375
	}
2376
	return $routes;
2377
}
2378

    
2379
function openvpn_gen_route_ipv4($network, $iroute = false) {
2380
	$i = ($iroute) ? "i" : "";
2381
	list($ip, $mask) = explode('/', trim($network));
2382
	$mask = gen_subnet_mask($mask);
2383
	return "{$i}route $ip $mask";
2384
}
2385

    
2386
function openvpn_gen_route_ipv6($network, $iroute = false) {
2387
	$i = ($iroute) ? "i" : "";
2388
	list($ipv6, $prefix) = explode('/', trim($network));
2389
	if (empty($prefix) && !is_numeric($prefix)) {
2390
		$prefix = "128";
2391
	}
2392
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2393
}
2394

    
2395
function openvpn_get_settings($mode, $vpnid) {
2396
	init_config_arr(array('openvpn', 'openvpn-server'));
2397
	init_config_arr(array('openvpn', 'openvpn-client'));
2398
	foreach (["server", "client"] as $mode) {
2399
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $settings) {
2400
			if (isset($settings['disable'])) {
2401
				continue;
2402
			}
2403

    
2404
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2405
				return $settings;
2406
			}
2407
		}
2408
	}
2409
	return array();
2410
}
2411

    
2412
function openvpn_restart_by_vpnid($mode, $vpnid) {
2413
	$settings = openvpn_get_settings($mode, $vpnid);
2414
	openvpn_restart($mode, $settings);
2415
}
2416

    
2417
/****f* certs/openvpn_is_tunnel_network_in_use
2418
 * NAME
2419
 *   openvpn_is_tunnel_network_in_use
2420
 *     Check if the supplied network is in use as an OpenVPN server or client
2421
 *     tunnel network
2422
 * INPUTS
2423
 *   $net : The IPv4 or IPv6 network to check
2424
 * RESULT
2425
 *   boolean value: true if the network is in use, false otherwise.
2426
 ******/
2427

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

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

    
2460
function openvpn_authscript_string($authmode, $strictusercn, $mode_id, $local_port) {
2461
	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";
2462
}
2463

    
2464
function openvpn_inuse($id, $mode) {
2465
	$type = ($mode == 'server') ? 's' : 'c';
2466

    
2467
	foreach (get_configured_interface_list(true) as $if) {
2468
		if (config_get_path("interfaces/{$if}/if") == "ovpn{$type}{$id}") {
2469
			return true;
2470
		}
2471
	}
2472

    
2473
	return false;
2474
}
2475

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

    
2487
?>
(35-35/62)