Project

General

Profile

Download (74.6 KB) Statistics
| Branch: | Tag: | Revision:
1 5b237745 Scott Ullrich
<?php
2 b1ad443d Scott Ullrich
/*
3 ac24dc24 Renato Botelho
 * openvpn.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6 c5d81585 Renato Botelho
 * Copyright (c) 2006 Fernando Lemos
7 38809d47 Renato Botelho do Couto
 * Copyright (c) 2006-2013 BSD Perimeter
8
 * Copyright (c) 2013-2016 Electric Sheep Fencing
9 8f2f85c3 Luiz Otavio O Souza
 * Copyright (c) 2014-2022 Rubicon Communications, LLC (Netgate)
10 ac24dc24 Renato Botelho
 * All rights reserved.
11
 *
12
 * This file was rewritten from scratch by Fernando Lemos but
13
 * *MIGHT* contain code previously written by:
14
 *
15 c5d81585 Renato Botelho
 * Copyright (c) 2005 Peter Allgeyer <allgeyer_AT_web.de>
16
 * Copyright (c) 2004 Peter Curran (peter@closeconsultants.com).
17 ac24dc24 Renato Botelho
 * All rights reserved.
18
 *
19 b12ea3fb Renato Botelho
 * 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 ac24dc24 Renato Botelho
 *
23 b12ea3fb Renato Botelho
 * http://www.apache.org/licenses/LICENSE-2.0
24 ac24dc24 Renato Botelho
 *
25 b12ea3fb Renato Botelho
 * 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 ac24dc24 Renato Botelho
 */
31 6aa3723a Renato Botelho
32 8dc3ef67 Scott Ullrich
require_once('config.inc');
33 32a7a1f6 Ermal Lu?i
require_once("certs.inc");
34 36df0acc Scott Ullrich
require_once('pfsense-utils.inc');
35 c61e4626 Ermal Lu?i
require_once("auth.inc");
36 8dc3ef67 Scott Ullrich
37 209ad2e3 jim-p
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 f2291484 jim-p
global $openvpn_prots;
45 ca366676 jim-p
$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 702a4702 Scott Ullrich
54 f2291484 jim-p
global $openvpn_dev_mode;
55 b743ea87 jim-p
$openvpn_dev_mode = array(
56
	"tun" => "tun - Layer 3 Tunnel Mode",
57
	"tap" => "tap - Layer 2 Tap Mode"
58
);
59 691fbf14 Ermal Lu?i
60 b9e9903d Dmitriy K.
global $openvpn_verbosity_level;
61
$openvpn_verbosity_level = array(
62 e8c516a0 Phil Davis
	0 =>	gettext("none"),
63
	1 =>	gettext("default"),
64 42bb1bee Renato Botelho
	2 =>	"2",
65 e8c516a0 Phil Davis
	3 =>	gettext("3 (recommended)"),
66 b9e9903d Dmitriy K.
	4 =>	"4",
67
	5 => 	"5",
68
	6 => 	"6",
69
	7 => 	"7",
70
	8 => 	"8",
71
	9 => 	"9",
72
	10 => 	"10",
73
	11 => 	"11"
74 42bb1bee Renato Botelho
);
75 b9e9903d Dmitriy K.
76 42bb1bee Renato Botelho
/*
77 3c11bd3c Matthew Grooms
 * 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 f2291484 jim-p
global $openvpn_dh_lengths;
90 fe787fc7 Matthew Grooms
$openvpn_dh_lengths = array(
91 f888c35a jim-p
	1024 => "1024 bit",
92 4b6bf6aa Justin Coffman
	2048 => "2048 bit",
93
	3072 => "3072 bit",
94
	4096 => "4096 bit",
95
	6144 => "6144 bit",
96 f888c35a jim-p
	7680 => "7680 bit",
97 4b6bf6aa Justin Coffman
	8192 => "8192 bit",
98 f888c35a jim-p
	15360 => "15360 bit",
99
	16384 => "16384 bit",
100
	"none" => "ECDH Only"
101 0693c967 stilez
);
102 f888c35a jim-p
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 fe787fc7 Matthew Grooms
108 f2291484 jim-p
global $openvpn_cert_depths;
109 98963f27 jim-p
$openvpn_cert_depths = array(
110 e8c516a0 Phil Davis
	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 98963f27 jim-p
);
116
117 f2291484 jim-p
global $openvpn_server_modes;
118 3c11bd3c Matthew Grooms
$openvpn_server_modes = array(
119 4aa02281 Carlos Eduardo Ramos
	'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 3c11bd3c Matthew Grooms
125 154b0f80 jim-p
global $openvpn_tls_server_modes;
126
$openvpn_tls_server_modes = array('p2p_tls', 'server_tls', 'server_user', 'server_tls_user');
127
128 f2291484 jim-p
global $openvpn_client_modes;
129 3c11bd3c Matthew Grooms
$openvpn_client_modes = array(
130 4aa02281 Carlos Eduardo Ramos
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
131 ef00af3c Phil Davis
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"));
132 3c11bd3c Matthew Grooms
133 56e031a7 jim-p
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 edba1982 jim-p
global $openvpn_compression_modes;
141
$openvpn_compression_modes = array(
142 56e031a7 jim-p
	'' => gettext("Disable Compression [Omit Preference]"),
143 38922574 jim-p
	'none' => gettext("Disable Compression, retain compression packet framing [compress]"),
144 56e031a7 jim-p
	'stub' => gettext("Enable Compression (stub) [compress stub]"),
145
	'stub-v2' => gettext("Enable Compression (stub v2) [compress stub-v2]"),
146 a4b36246 jim-p
	'lz4' => gettext("LZ4 Compression [compress lz4]"),
147 61a8cc10 jim-p
	'lz4-v2' => gettext("LZ4 Compression v2 [compress lz4-v2]"),
148 a4b36246 jim-p
	'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 edba1982 jim-p
155 88cfb255 jim-p
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 c854afcc jim-p
global $openvpn_tls_modes;
162
$openvpn_tls_modes = array(
163
	'auth' => gettext("TLS Authentication"),
164 feec858c jim-p
	'crypt' => gettext("TLS Encryption and Authentication")
165 c854afcc jim-p
);
166
167 3bfecc81 Renato Botelho do Couto
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 7591a72a jim-p
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 f4eec250 Phil Davis
function openvpn_build_mode_list() {
201
	global $openvpn_server_modes;
202
203
	$list = array();
204
205 4e322e2c Phil Davis
	foreach ($openvpn_server_modes as $name => $desc) {
206 f4eec250 Phil Davis
		$list[$name] = $desc;
207 4e322e2c Phil Davis
	}
208 f4eec250 Phil Davis
209
	return($list);
210
}
211
212 adf5849b PiBa-NL
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 f4eec250 Phil Davis
function openvpn_build_if_list() {
227
	$list = array();
228
229
	$interfaces = get_configured_interface_with_descr();
230 2a5960b0 Luiz Otavio O Souza
	$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 4e322e2c Phil Davis
	}
239 f4eec250 Phil Davis
240
	$grouplist = return_gateway_groups_array();
241
	foreach ($grouplist as $name => $group) {
242 4e322e2c Phil Davis
		if ($group[0]['vip'] != "") {
243 f4eec250 Phil Davis
			$vipif = $group[0]['vip'];
244 4e322e2c Phil Davis
		} else {
245 f4eec250 Phil Davis
			$vipif = $group[0]['int'];
246 4e322e2c Phil Davis
		}
247 f4eec250 Phil Davis
248
		$interfaces[$name] = "GW Group {$name}";
249
	}
250
251
	$interfaces['lo0'] = "Localhost";
252
	$interfaces['any'] = "any";
253
254 4e322e2c Phil Davis
	foreach ($interfaces as $iface => $ifacename) {
255 f4eec250 Phil Davis
	   $list[$iface] = $ifacename;
256 4e322e2c Phil Davis
	}
257 f4eec250 Phil Davis
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 4e322e2c Phil Davis
		if ($ca) {
271 f4eec250 Phil Davis
			$caname = " (CA: {$ca['descr']})";
272 4e322e2c Phil Davis
		}
273 f4eec250 Phil Davis
274
		$list[$crl['refid']] = $crl['descr'] . $caname;
275
	}
276
277
	return($list);
278
}
279
280 0e9d4a6d jim-p
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
281 f4eec250 Phil Davis
	global $a_cert;
282 bc3e78ab jim-p
	$openvpn_compatible_certs = cert_build_list('cert', 'OpenVPN');
283 f4eec250 Phil Davis
284
	if ($include_none) {
285 e8c516a0 Phil Davis
		$list = array('' => gettext('None (Username and/or Password required)'));
286 f4eec250 Phil Davis
	} else {
287
		$list = array();
288
	}
289
290 a4ba0282 Stephen Beaver
	$non_server_list = array();
291
292 0e9d4a6d jim-p
	if ($prioritize_server_certs) {
293 e8c516a0 Phil Davis
		$list[' '] = gettext("===== Server Certificates =====");
294
		$non_server_list['  '] = gettext("===== Non-Server Certificates =====");
295 0e9d4a6d jim-p
	}
296
297 f4eec250 Phil Davis
	foreach ($a_cert as $cert) {
298 bc3e78ab jim-p
		if (!array_key_exists($cert['refid'], $openvpn_compatible_certs)) {
299
			continue;
300
		}
301 0e9d4a6d jim-p
		$properties = array();
302
		$propstr = "";
303 f4eec250 Phil Davis
		$ca = lookup_ca($cert['caref']);
304 0e9d4a6d jim-p
		$purpose = cert_get_purpose($cert['crt'], true);
305 f4eec250 Phil Davis
306 0e9d4a6d jim-p
		if ($purpose['server'] == "Yes") {
307 e8c516a0 Phil Davis
			$properties[] = gettext("Server: Yes");
308 0e9d4a6d jim-p
		} elseif ($prioritize_server_certs) {
309 e8c516a0 Phil Davis
			$properties[] = gettext("Server: NO");
310 0e9d4a6d jim-p
		}
311 de1a3167 jim-p
		if ($ca) {
312 e8c516a0 Phil Davis
			$properties[] = sprintf(gettext("CA: %s"), $ca['descr']);
313 de1a3167 jim-p
		}
314 0e9d4a6d jim-p
		if (cert_in_use($cert['refid'])) {
315 e8c516a0 Phil Davis
			$properties[] = gettext("In Use");
316 0e9d4a6d jim-p
		}
317
		if (is_cert_revoked($cert)) {
318 e8c516a0 Phil Davis
			$properties[] = gettext("Revoked");
319 de1a3167 jim-p
		}
320 f4eec250 Phil Davis
321 0e9d4a6d jim-p
		if (!empty($properties)) {
322
			$propstr = " (" . implode(", ", $properties) . ")";
323 de1a3167 jim-p
		}
324 f4eec250 Phil Davis
325 0e9d4a6d jim-p
		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 de1a3167 jim-p
		}
334 0e9d4a6d jim-p
	}
335 f4eec250 Phil Davis
336 a4ba0282 Stephen Beaver
	return(array('server' => $list, 'non-server' => $non_server_list));
337 f4eec250 Phil Davis
}
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 2a5960b0 Luiz Otavio O Souza
	$viplist = get_configured_vip_list();
345 f4eec250 Phil Davis
346 2a5960b0 Luiz Otavio O Souza
	foreach ($viplist as $vip => $address) {
347
		$serverbridge_interface[$vip.'|'.$address] = $address;
348 d9901ff4 Chris Buechler
		if (get_vip_descr($address)) {
349 2a5960b0 Luiz Otavio O Souza
			$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
350 d9901ff4 Chris Buechler
		}
351 4e322e2c Phil Davis
	}
352 f4eec250 Phil Davis
353 4e322e2c Phil Davis
	foreach ($serverbridge_interface as $iface => $ifacename) {
354 f4eec250 Phil Davis
		$list[$iface] = htmlspecialchars($ifacename);
355 4e322e2c Phil Davis
	}
356 f4eec250 Phil Davis
357
	return($list);
358
}
359
360 3c11bd3c Matthew Grooms
function openvpn_create_key() {
361
362 a2ba5b6c Viktor G
	$fp = popen("/usr/local/sbin/openvpn --genkey secret /dev/stdout 2>/dev/null", "r");
363 ef00af3c Phil Davis
	if (!$fp) {
364 3c11bd3c Matthew Grooms
		return false;
365 ef00af3c Phil Davis
	}
366 3c11bd3c Matthew Grooms
367
	$rslt = stream_get_contents($fp);
368
	pclose($fp);
369
370
	return $rslt;
371
}
372 d799787e Matthew Grooms
373 8411b218 Matthew Grooms
function openvpn_create_dhparams($bits) {
374 34bc1324 Matthew Grooms
375 2ec95f1f Renato Botelho
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
376 ef00af3c Phil Davis
	if (!$fp) {
377 34bc1324 Matthew Grooms
		return false;
378 ef00af3c Phil Davis
	}
379 34bc1324 Matthew Grooms
380
	$rslt = stream_get_contents($fp);
381
	pclose($fp);
382
383
	return $rslt;
384
}
385
386 d799787e Matthew Grooms
function openvpn_vpnid_used($vpnid) {
387 8be2d6d3 Ermal Luçi
	global $config;
388
389 ef00af3c Phil Davis
	if (is_array($config['openvpn']['openvpn-server'])) {
390
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
391
			if ($vpnid == $settings['vpnid']) {
392 d799787e Matthew Grooms
				return true;
393 ef00af3c Phil Davis
			}
394
		}
395
	}
396 d799787e Matthew Grooms
397 ef00af3c Phil Davis
	if (is_array($config['openvpn']['openvpn-client'])) {
398
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
399
			if ($vpnid == $settings['vpnid']) {
400 d799787e Matthew Grooms
				return true;
401 ef00af3c Phil Davis
			}
402
		}
403
	}
404 04a6e900 Ermal Luçi
405 d799787e Matthew Grooms
	return false;
406
}
407
408
function openvpn_vpnid_next() {
409
410
	$vpnid = 1;
411 ef00af3c Phil Davis
	while (openvpn_vpnid_used($vpnid)) {
412 d799787e Matthew Grooms
		$vpnid++;
413 ef00af3c Phil Davis
	}
414 d799787e Matthew Grooms
415
	return $vpnid;
416
}
417
418 49b76122 Renato Botelho
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
419 f432e364 Matthew Grooms
	global $config;
420
421 65d0277d Renato Botelho
	$ovpn_settings = array();
422 49b76122 Renato Botelho
	if (is_array($config['openvpn']['openvpn-server'])) {
423 65d0277d Renato Botelho
		$ovpn_settings = $config['openvpn']['openvpn-server'];
424 49b76122 Renato Botelho
	}
425
	if (is_array($config['openvpn']['openvpn-client'])) {
426 65d0277d Renato Botelho
		$ovpn_settings = array_merge($ovpn_settings,
427
		    $config['openvpn']['openvpn-client']);
428
	}
429 49b76122 Renato Botelho
430 65d0277d Renato Botelho
	foreach ($ovpn_settings as $settings) {
431
		if (isset($settings['disable'])) {
432
			continue;
433
		}
434 49b76122 Renato Botelho
435 65d0277d Renato Botelho
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
436
			continue;
437
		}
438
439 f69e098f Renato Botelho
		/* (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 65d0277d Renato Botelho
		if ($port == $settings['local_port'] &&
449 f69e098f Renato Botelho
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
450 65d0277d Renato Botelho
		    ($interface == $settings['interface'] ||
451
		    $interface == "any" || $settings['interface'] == "any")) {
452
			return $settings['vpnid'];
453 49b76122 Renato Botelho
		}
454
	}
455 f432e364 Matthew Grooms
456
	return 0;
457
}
458
459 49b76122 Renato Botelho
function openvpn_port_next($prot, $interface = "wan") {
460 f432e364 Matthew Grooms
461
	$port = 1194;
462 ef00af3c Phil Davis
	while (openvpn_port_used($prot, $interface, $port)) {
463 49b76122 Renato Botelho
		$port++;
464 ef00af3c Phil Davis
	}
465
	while (openvpn_port_used($prot, "any", $port)) {
466 f432e364 Matthew Grooms
		$port++;
467 ef00af3c Phil Davis
	}
468 f432e364 Matthew Grooms
469
	return $port;
470
}
471
472 d799787e Matthew Grooms
function openvpn_get_cipherlist() {
473
474
	$ciphers = array();
475 4fd1130f jim-p
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
476 d799787e Matthew Grooms
	$cipher_lines = explode("\n", trim($cipher_out));
477
	sort($cipher_lines);
478
	foreach ($cipher_lines as $line) {
479 4fd1130f jim-p
		$words = explode(' ', $line, 2);
480 d799787e Matthew Grooms
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
481 8be2d6d3 Ermal Luçi
	}
482 4aa02281 Carlos Eduardo Ramos
	$ciphers["none"] = gettext("None (No Encryption)");
483 d799787e Matthew Grooms
	return $ciphers;
484
}
485
486 f888c35a jim-p
function openvpn_get_curvelist() {
487 bc3e78ab jim-p
	global $cert_curve_compatible;
488 f888c35a jim-p
	$curves = array();
489
	$curves["none"] = gettext("Use Default");
490 bc3e78ab jim-p
	foreach ($cert_curve_compatible['OpenVPN'] as $curve) {
491
		$curves[$curve] = $curve;
492 f888c35a jim-p
	}
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 f49ef559 jim-p
/* Obtain the list of digest algorithms supported by openssl and their alternate names */
502
function openvpn_get_openssldigestmappings() {
503
	$digests = array();
504 bd5d33d8 mschiegl
	$digest_out = shell_exec('/usr/bin/openssl list -digest-algorithms | /usr/bin/grep "=>"');
505 f49ef559 jim-p
	$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 97d5b59b jim-p
514 f49ef559 jim-p
/* 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 97d5b59b jim-p
	$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 f49ef559 jim-p
		/* 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 97d5b59b jim-p
	}
529
	$digests["none"] = gettext("None (No Authentication)");
530
	return $digests;
531
}
532
533 f49ef559 jim-p
/* 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 8698f918 Vito Piserchia
function openvpn_get_keydirlist() {
551
	$keydirs = array(
552 d2011b0a jim-p
		'default'  => gettext('Use default direction'),
553 8698f918 Vito Piserchia
		'0' => gettext('Direction 0'),
554
		'1' => gettext('Direction 1'),
555 f08369ec Vito Piserchia
		'2' => gettext('Both directions'),
556 8698f918 Vito Piserchia
	);
557
	return $keydirs;
558
}
559
560 582c58ae jim-p
function openvpn_get_engines() {
561 e8c516a0 Phil Davis
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
562 2ec95f1f Renato Botelho
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
563 349bf358 jim-p
	$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 582c58ae jim-p
	foreach ($openssl_engine_output as $oeo) {
568 349bf358 jim-p
		$keep = true;
569
		$details = explode("|", $oeo);
570
		$engine = array_shift($details);
571 582c58ae jim-p
		$linematch = array();
572 349bf358 jim-p
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
573
		foreach ($details as $dt) {
574 ef00af3c Phil Davis
			if (strpos($dt, "unavailable") !== FALSE) {
575 349bf358 jim-p
				$keep = false;
576 ef00af3c Phil Davis
			}
577
			if (strpos($dt, "available") !== FALSE) {
578 349bf358 jim-p
				continue;
579 ef00af3c Phil Davis
			}
580
			if (strpos($dt, "[") !== FALSE) {
581 349bf358 jim-p
				$ciphers = trim($dt, "[]");
582 ef00af3c Phil Davis
			}
583 349bf358 jim-p
		}
584 ef00af3c Phil Davis
		if (!empty($ciphers)) {
585 349bf358 jim-p
			$ciphers = " - " . $ciphers;
586 ef00af3c Phil Davis
		}
587
		if (strlen($ciphers) > 60) {
588 349bf358 jim-p
			$ciphers = substr($ciphers, 0, 60) . " ... ";
589 ef00af3c Phil Davis
		}
590
		if ($keep) {
591 349bf358 jim-p
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
592 ef00af3c Phil Davis
		}
593 582c58ae jim-p
	}
594
	return $openssl_engines;
595
}
596
597 7618a842 jim-p
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 582c58ae jim-p
function openvpn_validate_engine($engine) {
610
	$engines = openvpn_get_engines();
611
	return array_key_exists($engine, $engines);
612
}
613
614 d799787e Matthew Grooms
function openvpn_validate_host($value, $name) {
615
	$value = trim($value);
616 ef00af3c Phil Davis
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
617 4aa02281 Carlos Eduardo Ramos
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
618 ef00af3c Phil Davis
	}
619 d799787e Matthew Grooms
	return false;
620 8dc3ef67 Scott Ullrich
}
621
622 39fed386 jim-p
function openvpn_validate_port($value, $name, $first_port = 0) {
623 8dc3ef67 Scott Ullrich
	$value = trim($value);
624 39fed386 jim-p
	if (!is_numeric($first_port)) {
625
		$first_port = 0;
626
	}
627
	if (empty($value) || !is_numeric($value) || $value < $first_port || ($value > 65535)) {
628 9f2a58b5 Renato Botelho do Couto
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from %s to 65535."), $name, $first_port);
629 ef00af3c Phil Davis
	}
630 b398bbca Martin Fuchs
	return false;
631 8dc3ef67 Scott Ullrich
}
632
633 4b8d710c Viktor G
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4", $alias = false) {
634 a28d40cb jim-p
	$value = trim($value);
635
	$error = false;
636 ef00af3c Phil Davis
	if (empty($value)) {
637 a28d40cb jim-p
		return false;
638 ef00af3c Phil Davis
	}
639 a28d40cb jim-p
	$networks = explode(',', $value);
640
641 ef00af3c Phil Davis
	if (!$multiple && (count($networks) > 1)) {
642 e8c516a0 Phil Davis
		return sprintf(gettext("The field '%1\$s' must contain a single valid %2\$s CIDR range."), $name, $ipproto);
643 ef00af3c Phil Davis
	}
644 a28d40cb jim-p
645
	foreach ($networks as $network) {
646 ef00af3c Phil Davis
		if ($ipproto == "ipv4") {
647 4b8d710c Viktor G
			$error = !openvpn_validate_cidr_ipv4($network, $alias);
648 ef00af3c Phil Davis
		} else {
649 4b8d710c Viktor G
			$error = !openvpn_validate_cidr_ipv6($network, $alias);
650 ef00af3c Phil Davis
		}
651
		if ($error) {
652 a28d40cb jim-p
			break;
653 ef00af3c Phil Davis
		}
654 a28d40cb jim-p
	}
655
656 ef00af3c Phil Davis
	if ($error) {
657 60c0b333 Viktor G
		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 ef00af3c Phil Davis
	} else {
659 a28d40cb jim-p
		return false;
660 ef00af3c Phil Davis
	}
661 a28d40cb jim-p
}
662
663 4b8d710c Viktor G
function openvpn_validate_cidr_ipv4($value, $alias = false) {
664 8dc3ef67 Scott Ullrich
	$value = trim($value);
665
	if (!empty($value)) {
666 4b8d710c Viktor G
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
667 60c0b333 Viktor G
			foreach (alias_to_subnets_recursive($value, true) as $net) {
668
				if (!is_subnetv4($net) && !is_fqdn($net)) {
669 4b8d710c Viktor G
					return false;
670
				}
671
			}
672
			return true;
673
		} else {
674
			if (!is_subnetv4($value)) {
675
				return false;
676
			}
677 ef00af3c Phil Davis
		}
678 8dc3ef67 Scott Ullrich
	}
679 a28d40cb jim-p
	return true;
680
}
681
682 4b8d710c Viktor G
function openvpn_validate_cidr_ipv6($value, $alias = false) {
683 a28d40cb jim-p
	$value = trim($value);
684
	if (!empty($value)) {
685 4b8d710c Viktor G
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
686 60c0b333 Viktor G
			foreach (alias_to_subnets_recursive($value, true) as $net) {
687
				if (!is_subnetv6($net) && !is_fqdn($net)) {
688 4b8d710c Viktor G
					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 ef00af3c Phil Davis
		}
701 4b8d710c Viktor G
	}
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 ef00af3c Phil Davis
		}
722 a28d40cb jim-p
	}
723
	return true;
724 afb07cf1 Scott Ullrich
}
725
726 4b8d710c Viktor G
function openvpn_gen_tunnel_network($tunnel_network) {
727
	if (is_alias($tunnel_network)) {
728
		$net = alias_to_subnets_recursive($tunnel_network);
729 0fe9c7bb Viktor G
		$pair = openvpn_tunnel_network_fix($net[0]);
730 4b8d710c Viktor G
	} else {
731
		$pair = $tunnel_network;
732
	}
733 0fe9c7bb Viktor G
	return explode('/', $pair);
734 4b8d710c Viktor G
}
735
736 d799787e Matthew Grooms
function openvpn_add_dhcpopts(& $settings, & $conf) {
737 afb07cf1 Scott Ullrich
738 ef00af3c Phil Davis
	if (!empty($settings['dns_domain'])) {
739 d799787e Matthew Grooms
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
740 ef00af3c Phil Davis
	}
741 add2e3f7 Scott Ullrich
742 ef00af3c Phil Davis
	if (!empty($settings['dns_server1'])) {
743 6a638752 jim-p
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
744
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
745 ef00af3c Phil Davis
	}
746
	if (!empty($settings['dns_server2'])) {
747 6a638752 jim-p
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
748
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
749 ef00af3c Phil Davis
	}
750
	if (!empty($settings['dns_server3'])) {
751 6a638752 jim-p
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
752
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
753 ef00af3c Phil Davis
	}
754
	if (!empty($settings['dns_server4'])) {
755 6a638752 jim-p
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
756
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
757 ef00af3c Phil Davis
	}
758 f9927473 Scott Ullrich
759 01c2735c jim-p
	if (!empty($settings['push_blockoutsidedns'])) {
760
		$conf .= "push \"block-outside-dns\"\n";
761
	}
762 ef00af3c Phil Davis
	if (!empty($settings['push_register_dns'])) {
763 c38764dc Dmitriy K.
		$conf .= "push \"register-dns\"\n";
764 ef00af3c Phil Davis
	}
765 c38764dc Dmitriy K.
766 ef00af3c Phil Davis
	if (!empty($settings['ntp_server1'])) {
767 c7f70dbc Chris Buechler
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
768 ef00af3c Phil Davis
	}
769
	if (!empty($settings['ntp_server2'])) {
770 c7f70dbc Chris Buechler
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
771 ef00af3c Phil Davis
	}
772 f9927473 Scott Ullrich
773 d799787e Matthew Grooms
	if ($settings['netbios_enable']) {
774 add2e3f7 Scott Ullrich
775 ef00af3c Phil Davis
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
776 095a95ae Matthew Grooms
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
777 ef00af3c Phil Davis
		}
778
		if (!empty($settings['dhcp_nbtscope'])) {
779 d799787e Matthew Grooms
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
780 ef00af3c Phil Davis
		}
781 8dc3ef67 Scott Ullrich
782 ef00af3c Phil Davis
		if (!empty($settings['wins_server1'])) {
783 d799787e Matthew Grooms
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
784 ef00af3c Phil Davis
		}
785
		if (!empty($settings['wins_server2'])) {
786 d799787e Matthew Grooms
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
787 ef00af3c Phil Davis
		}
788 add2e3f7 Scott Ullrich
789 ef00af3c Phil Davis
		if (!empty($settings['nbdd_server1'])) {
790 d799787e Matthew Grooms
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
791 ef00af3c Phil Davis
		}
792 d799787e Matthew Grooms
	}
793 8dc3ef67 Scott Ullrich
794 ef00af3c Phil Davis
	if ($settings['gwredir']) {
795 d799787e Matthew Grooms
		$conf .= "push \"redirect-gateway def1\"\n";
796 ef00af3c Phil Davis
	}
797 37f05e97 jim-p
	if ($settings['gwredir6']) {
798
		$conf .= "push \"redirect-gateway ipv6\"\n";
799
	}
800 d799787e Matthew Grooms
}
801 24012690 Scott Ullrich
802 d799787e Matthew Grooms
function openvpn_add_custom(& $settings, & $conf) {
803 add2e3f7 Scott Ullrich
804 d799787e Matthew Grooms
	if ($settings['custom_options']) {
805 8dc3ef67 Scott Ullrich
806 d799787e Matthew Grooms
		$options = explode(';', $settings['custom_options']);
807
808
		if (is_array($options)) {
809 ef00af3c Phil Davis
			foreach ($options as $option) {
810 d799787e Matthew Grooms
				$conf .= "$option\n";
811 ef00af3c Phil Davis
			}
812
		} else {
813 d799787e Matthew Grooms
			$conf .= "{$settings['custom_options']}\n";
814 ef00af3c Phil Davis
		}
815 add2e3f7 Scott Ullrich
	}
816
}
817
818 691fbf14 Ermal Lu?i
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
819 d799787e Matthew Grooms
	global $g;
820 add2e3f7 Scott Ullrich
821 348c2af1 jim-p
	$fpath = "{$g['openvpn_base']}/{$mode_id}/{$directive}";
822 a8f538a8 jim-p
	openvpn_create_dirs();
823 d799787e Matthew Grooms
	file_put_contents($fpath, base64_decode($data));
824 f9ac3784 Ermal Lu?i
	//chown($fpath, 'nobody');
825
	//chgrp($fpath, 'nobody');
826 6f27412f Ermal Lu?i
	@chmod($fpath, 0600);
827 d799787e Matthew Grooms
828 691fbf14 Ermal Lu?i
	$conf .= "{$directive} {$fpath} {$opt}\n";
829 4eefa6e8 Scott Ullrich
}
830
831 acb0c154 Marcos Mendoza
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 fc05822b jim-p
function openvpn_reconfigure($mode, $settings) {
853 99d7e8c1 jim-p
	global $g, $config, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
854 afb07cf1 Scott Ullrich
855 ef00af3c Phil Davis
	if (empty($settings)) {
856 93a0a028 Ermal Luçi
		return;
857 ef00af3c Phil Davis
	}
858
	if (isset($settings['disable'])) {
859 4eefa6e8 Scott Ullrich
		return;
860 ef00af3c Phil Davis
	}
861 a8f538a8 jim-p
	openvpn_create_dirs();
862 fdd725f0 Ermal Luçi
	/*
863 d799787e Matthew Grooms
	 * 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 fdd725f0 Ermal Luçi
	 */
867 8874c692 Ermal Luçi
868 d799787e Matthew Grooms
	$vpnid = $settings['vpnid'];
869
	$mode_id = $mode.$vpnid;
870 8874c692 Ermal Luçi
871 ef00af3c Phil Davis
	if (isset($settings['dev_mode'])) {
872 4936ff53 jim-p
		$tunname = "{$settings['dev_mode']}{$vpnid}";
873 ef00af3c Phil Davis
	} else {
874
		/* defaults to tun */
875 bd7ca506 jim-p
		$tunname = "tun{$vpnid}";
876 4936ff53 jim-p
		$settings['dev_mode'] = "tun";
877 691fbf14 Ermal Lu?i
	}
878
879 ef00af3c Phil Davis
	if ($mode == "server") {
880 bd7ca506 jim-p
		$devname = "ovpns{$vpnid}";
881 ef00af3c Phil Davis
	} else {
882 bd7ca506 jim-p
		$devname = "ovpnc{$vpnid}";
883 ef00af3c Phil Davis
	}
884 8874c692 Ermal Luçi
885 bd7ca506 jim-p
	/* is our device already configured */
886 4a97aa34 Ermal
	if (!does_interface_exist($devname)) {
887 dc408939 Matthew Grooms
888 bd7ca506 jim-p
		/* create the tap device if required */
889 ef00af3c Phil Davis
		if (!file_exists("/dev/{$tunname}")) {
890 873c1701 Renato Botelho
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
891 ef00af3c Phil Davis
		}
892 98872d89 Ermal Luçi
893 bd7ca506 jim-p
		/* rename the device */
894 873c1701 Renato Botelho
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
895 095a95ae Matthew Grooms
896 4ab1ffa0 Renato Botelho
		/* add the device to the openvpn group and make sure it's UP*/
897
		mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " group openvpn up");
898 da4f91a9 Renato Botelho
899 bd1a6267 Renato Botelho
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
900
		$grouptmp = link_interface_to_group($ifname);
901 ef00af3c Phil Davis
		if (!empty($grouptmp)) {
902 bd1a6267 Renato Botelho
			array_walk($grouptmp, 'interface_group_add_member');
903 ef00af3c Phil Davis
		}
904 bd1a6267 Renato Botelho
		unset($grouptmp, $ifname);
905 dc408939 Matthew Grooms
	}
906 d799787e Matthew Grooms
907 dc408939 Matthew Grooms
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
908 6714bbdc jim-p
	$proto = strtolower($settings['protocol']);
909 ef00af3c Phil Davis
	if (substr($settings['protocol'], 0, 3) == "TCP") {
910 6714bbdc jim-p
			$proto = "{$proto}-{$mode}";
911 ef00af3c Phil Davis
	}
912 4936ff53 jim-p
	$dev_mode = $settings['dev_mode'];
913 189edaf3 jim-p
	$fbcipher = $settings['data_ciphers_fallback'];
914 97d5b59b jim-p
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
915
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
916 d799787e Matthew Grooms
917 47c48e28 smos
	$interface = get_failover_interface($settings['interface']);
918 e27bc6cf Phil Davis
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
919 d7a0c22a bcyrill
	$ipaddr = $settings['ipaddr'];
920 d799787e Matthew Grooms
921 67b0902f pierrepomes
	// If a specific ip address (VIP) is requested, use it.
922
	// Otherwise, if a specific interface is requested, use it
923 ef00af3c Phil Davis
	// If "any" interface was selected, local directive will be omitted.
924 97ffc513 Seth Mos
	if (is_ipaddrv4($ipaddr)) {
925 4de8f7ba Phil Davis
		$iface_ip = $ipaddr;
926 af0257cf Renato Botelho
	} elseif (!empty($interface) && strcmp($interface, "any")) {
927 51e7132e Renato Botelho
		$iface_ip=get_interface_ip($interface);
928 47c48e28 smos
	}
929 e27bc6cf Phil Davis
	if (is_ipaddrv6($ipaddr)) {
930 6c07db48 Phil Davis
		$iface_ipv6 = $ipaddr;
931 af0257cf Renato Botelho
	} elseif (!empty($interface) && strcmp($interface, "any")) {
932 1b59af4f Viktor G
		/* 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 3d06e8f0 pierrepomes
	}
940 d799787e Matthew Grooms
941 b1e8e675 Dmitriy K.
	$conf = "dev {$devname}\n";
942 5b3c0116 Dmitriy K.
	if (isset($settings['verbosity_level'])) {
943 b1e8e675 Dmitriy K.
		$conf .= "verb {$settings['verbosity_level']}\n";
944 5b3c0116 Dmitriy K.
	}
945 42bb1bee Renato Botelho
946 4936ff53 jim-p
	$conf .= "dev-type {$settings['dev_mode']}\n";
947 bd7ca506 jim-p
	$conf .= "dev-node /dev/{$tunname}\n";
948 3c11bd3c Matthew Grooms
	$conf .= "writepid {$pfile}\n";
949
	$conf .= "#user nobody\n";
950
	$conf .= "#group nobody\n";
951 d1014c18 Chris Buechler
	$conf .= "script-security 3\n";
952 3c11bd3c Matthew Grooms
	$conf .= "daemon\n";
953 3bfecc81 Renato Botelho do Couto
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 3c11bd3c Matthew Grooms
	$conf .= "ping-timer-rem\n";
978
	$conf .= "persist-tun\n";
979
	$conf .= "persist-key\n";
980
	$conf .= "proto {$proto}\n";
981 97d5b59b jim-p
	$conf .= "auth {$digest}\n";
982 ee712bbb Viktor G
	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 8d964cea Ermal
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
988 1492e02c Ermal
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
989 ef00af3c Phil Davis
		switch ($settings['mode']) {
990 a1b9105b jim-p
			case 'server_user':
991
			case 'server_tls_user':
992 d1d8383c Viktor G
			case 'server_tls':
993 a1b9105b jim-p
				$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 1492e02c Ermal
	}
998 4f4de341 Lorenz Schori
	if ($settings['dev_mode'] === 'tun' && isset($config['unbound']['enable']) && isset($config['unbound']['regovpnclients'])) {
999 3b88d971 Viktor G
		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 0cc17a06 Lorenz Schori
		}
1006
	}
1007 3c11bd3c Matthew Grooms
1008 5280fd8d Renato Botelho
	/*
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 6714bbdc jim-p
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
1015 ca366676 jim-p
	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 5280fd8d Renato Botelho
				$wait_tentative = true;
1034 ca366676 jim-p
			}
1035
			if ($settings['interface'] == "any") {
1036
				$conf .= "multihome\n";
1037
			}
1038
			break;
1039
		default:
1040 97ffc513 Seth Mos
	}
1041 d799787e Matthew Grooms
1042 ef00af3c Phil Davis
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
1043 582c58ae jim-p
		$conf .= "engine {$settings['engine']}\n";
1044 ef00af3c Phil Davis
	}
1045 582c58ae jim-p
1046 67b0902f pierrepomes
	// server specific settings
1047 8dc3ef67 Scott Ullrich
	if ($mode == 'server') {
1048 d799787e Matthew Grooms
1049 4b8d710c Viktor G
		list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1050
		list($ipv6, $prefix) = openvpn_gen_tunnel_network($settings['tunnel_networkv6']);
1051 5dc6c910 jim-p
		$mask = gen_subnet_mask($cidr);
1052 8dc3ef67 Scott Ullrich
1053 3c11bd3c Matthew Grooms
		// configure tls modes
1054 ef00af3c Phil Davis
		switch ($settings['mode']) {
1055 3c11bd3c Matthew Grooms
			case 'p2p_tls':
1056
			case 'server_tls':
1057 e62e2f8b Ermal Lu?i
			case 'server_user':
1058 3c11bd3c Matthew Grooms
			case 'server_tls_user':
1059 d799787e Matthew Grooms
				$conf .= "tls-server\n";
1060 3c11bd3c Matthew Grooms
				break;
1061 8dc3ef67 Scott Ullrich
		}
1062 d799787e Matthew Grooms
1063 3c11bd3c Matthew Grooms
		// configure p2p/server modes
1064 ef00af3c Phil Davis
		switch ($settings['mode']) {
1065 6c9cf466 jim-p
			case 'p2p_tls':
1066 5dc6c910 jim-p
				// 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 4af6affa jim-p
				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 ef00af3c Phil Davis
					if (is_ipaddr($ipv6)) {
1077 4af6affa jim-p
						$add_ccd = true;
1078 a0e3ee98 jim-p
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
1079 ef00af3c Phil Davis
					}
1080 4af6affa jim-p
					if ($add_ccd) {
1081
						$conf .= "client-config-dir {$g['openvpn_base']}/server{$vpnid}/csc\n";
1082
					}
1083 5dc6c910 jim-p
				}
1084 3c11bd3c Matthew Grooms
			case 'p2p_shared_key':
1085 74a556a3 jim-p
				if (!empty($ip) && !empty($mask)) {
1086 30c8a290 Renato Botelho
					list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1087 ef00af3c Phil Davis
					if ($settings['dev_mode'] == 'tun') {
1088 459e9333 jim-p
						$conf .= "ifconfig {$ip1} {$ip2}\n";
1089 ef00af3c Phil Davis
					} else {
1090 459e9333 jim-p
						$conf .= "ifconfig {$ip1} {$mask}\n";
1091 ef00af3c Phil Davis
					}
1092 1ab6bdb5 jim-p
				}
1093 a0e3ee98 jim-p
				if (!empty($ipv6) && !empty($prefix)) {
1094 91c44185 jim-p
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1095 ef00af3c Phil Davis
					if ($settings['dev_mode'] == 'tun') {
1096 a0e3ee98 jim-p
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$ipv6_2}\n";
1097 ef00af3c Phil Davis
					} else {
1098 f0a0bae5 Viktor G
						$conf .= "ifconfig-ipv6 {$ipv6_1}/{$prefix} {$ipv6_2}\n";
1099 ef00af3c Phil Davis
					}
1100 a0e3ee98 jim-p
				}
1101 3c11bd3c Matthew Grooms
				break;
1102
			case 'server_tls':
1103
			case 'server_user':
1104
			case 'server_tls_user':
1105 4af6affa jim-p
				if ((!empty($ip) && !empty($mask)) ||
1106
				    (!empty($ipv6) && !empty($prefix))) {
1107
					if (is_ipaddr($ip)) {
1108
						$conf .= "server {$ip} {$mask}\n";
1109
					}
1110 ef00af3c Phil Davis
					if (is_ipaddr($ipv6)) {
1111 1ab6bdb5 jim-p
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
1112 ef00af3c Phil Davis
					}
1113 348c2af1 jim-p
					$conf .= "client-config-dir {$g['openvpn_base']}/server{$vpnid}/csc\n";
1114 1ab6bdb5 jim-p
				} 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 348c2af1 jim-p
								$conf .= "client-config-dir {$g['openvpn_base']}/server{$vpnid}/csc\n";
1122 1ab6bdb5 jim-p
							} else {
1123
								$conf .= "mode server\n";
1124
							}
1125 498f7e20 jim-p
							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 1ab6bdb5 jim-p
						} else {
1135
							$conf .= "mode server\n";
1136
						}
1137
					}
1138
				}
1139 3c11bd3c Matthew Grooms
				break;
1140 8dc3ef67 Scott Ullrich
		}
1141
1142 3c11bd3c Matthew Grooms
		// configure user auth modes
1143 ef00af3c Phil Davis
		switch ($settings['mode']) {
1144 3c11bd3c Matthew Grooms
			case 'server_user':
1145 4cfd15a9 jim-p
				$conf .= "verify-client-cert none\n";
1146 3c11bd3c Matthew Grooms
			case 'server_tls_user':
1147 9eced774 jim-p
				/* username-as-common-name is not compatible with server-bridge */
1148 e5c4f2a7 jim-p
				if ((stristr($conf, "server-bridge") === false) &&
1149
				    ($settings['username_as_common_name'] != 'disabled')) {
1150 9eced774 jim-p
					$conf .= "username-as-common-name\n";
1151 ef00af3c Phil Davis
				}
1152 8a47c190 Ermal Lu?i
				if (!empty($settings['authmode'])) {
1153 5e28dad4 Ermal
					$strictusercn = "false";
1154 ef00af3c Phil Davis
					if ($settings['strictusercn']) {
1155 5e28dad4 Ermal
						$strictusercn = "true";
1156 ef00af3c Phil Davis
					}
1157 30064732 Viktor G
					$conf .= openvpn_authscript_string($settings['authmode'], $strictusercn, $mode_id, $settings['local_port']);
1158 e8a58de4 Ermal Lu?i
				}
1159 3c11bd3c Matthew Grooms
				break;
1160 8dc3ef67 Scott Ullrich
		}
1161 ef00af3c Phil Davis
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
1162 41936acc jim-p
			$settings['cert_depth'] = 1;
1163 ef00af3c Phil Davis
		}
1164 98963f27 jim-p
		if (is_numeric($settings['cert_depth'])) {
1165 ef00af3c Phil Davis
			if (($mode == 'client') && empty($settings['certref'])) {
1166 2da48592 jim-p
				$cert = "";
1167 ef00af3c Phil Davis
			} else {
1168 2da48592 jim-p
				$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 98963f27 jim-p
		}
1174 8dc3ef67 Scott Ullrich
1175 63084885 Matthew Grooms
		// The local port to listen on
1176 d799787e Matthew Grooms
		$conf .= "lport {$settings['local_port']}\n";
1177 c0cf27aa Scott Ullrich
1178 63084885 Matthew Grooms
		// The management port to listen on
1179 71ca2cb2 Ermal
		// Use unix socket to overcome the problem on any type of server
1180 348c2af1 jim-p
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1181 71ca2cb2 Ermal
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
1182 63084885 Matthew Grooms
1183 ef00af3c Phil Davis
		if ($settings['maxclients']) {
1184 d799787e Matthew Grooms
			$conf .= "max-clients {$settings['maxclients']}\n";
1185 ef00af3c Phil Davis
		}
1186 d799787e Matthew Grooms
1187 37f05e97 jim-p
		// Can we push routes, and should we?
1188
		if ($settings['local_network'] && !$settings['gwredir']) {
1189 a28d40cb jim-p
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1190 3c11bd3c Matthew Grooms
		}
1191 37f05e97 jim-p
		if ($settings['local_networkv6'] && !$settings['gwredir6']) {
1192 a28d40cb jim-p
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1193 787de45a Seth Mos
		}
1194 3c11bd3c Matthew Grooms
1195 ef00af3c Phil Davis
		switch ($settings['mode']) {
1196 3c11bd3c Matthew Grooms
			case 'server_tls':
1197
			case 'server_user':
1198
			case 'server_tls_user':
1199 5d8cd81a jim-p
				// Configure client dhcp options
1200 3c11bd3c Matthew Grooms
				openvpn_add_dhcpopts($settings, $conf);
1201 ef00af3c Phil Davis
				if ($settings['client2client']) {
1202 5d8cd81a jim-p
					$conf .= "client-to-client\n";
1203 ef00af3c Phil Davis
				}
1204 3c11bd3c Matthew Grooms
				break;
1205
		}
1206 70e7b0c1 Marcos Mendoza
		$connlimit = "0";
1207 4e42da90 Renato Botelho do Couto
		if ($settings['mode'] != 'p2p_shared_key' &&
1208
		    isset($settings['duplicate_cn'])) {
1209 bca35cff jim-p
			$conf .= "duplicate-cn\n";
1210 70e7b0c1 Marcos Mendoza
			if ($settings['connlimit']) {
1211
				$connlimit = "{$settings['connlimit']}";
1212
			}
1213 ef00af3c Phil Davis
		}
1214 810adc14 Viktor G
		if (($settings['mode'] != 'p2p_shared_key') &&
1215
		    isset($settings['remote_cert_tls'])) {
1216
			$conf .= "remote-cert-tls client\n";
1217
		}
1218 d799787e Matthew Grooms
	}
1219
1220 3c11bd3c Matthew Grooms
	// client specific settings
1221 d799787e Matthew Grooms
1222 3c11bd3c Matthew Grooms
	if ($mode == 'client') {
1223 d799787e Matthew Grooms
1224 76569401 jim-p
		$add_pull = false;
1225 3c11bd3c Matthew Grooms
		// configure p2p mode
1226 76569401 jim-p
		if ($settings['mode'] == 'p2p_tls') {
1227
			$conf .= "tls-client\n";
1228 3c11bd3c Matthew Grooms
		}
1229 d799787e Matthew Grooms
1230 e3924384 jim-p
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1231 42bb1bee Renato Botelho
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1232 e3924384 jim-p
		//  ensure a random source port.
1233 b42ccf15 jim-p
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1234 e3924384 jim-p
			$conf .= "nobind\n";
1235 ef00af3c Phil Davis
		} elseif ($settings['local_port']) {
1236 e3924384 jim-p
			$conf .= "lport {$settings['local_port']}\n";
1237 ef00af3c Phil Davis
		} else {
1238 e3924384 jim-p
			$conf .= "lport 0\n";
1239 ef00af3c Phil Davis
		}
1240 5708241f jim-p
1241 4b887ef4 jim-p
		// Use unix socket to overcome the problem on any type of server
1242 348c2af1 jim-p
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1243 48a458d2 pierrepomes
1244 3c11bd3c Matthew Grooms
		// The remote server
1245 bd1291d0 Viktor Gurov
		$remoteproto = strtolower($settings['protocol']);
1246 6ac20ad3 Viktor G
		if (substr($remoteproto, 0, 3) == "tcp") {
1247
			$remoteproto .= "-{$mode}";
1248
		}
1249 bd1291d0 Viktor Gurov
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']} {$remoteproto}\n";
1250 3c11bd3c Matthew Grooms
1251 ef00af3c Phil Davis
		if (!empty($settings['use_shaper'])) {
1252 d799787e Matthew Grooms
			$conf .= "shaper {$settings['use_shaper']}\n";
1253 ef00af3c Phil Davis
		}
1254 ee506044 Scott Ullrich
1255 d799787e Matthew Grooms
		if (!empty($settings['tunnel_network'])) {
1256 4b8d710c Viktor G
			list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1257 30c8a290 Renato Botelho
			$mask = gen_subnet_mask($cidr);
1258 636918c9 Chris Buechler
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1259 ef00af3c Phil Davis
			if ($settings['dev_mode'] == 'tun') {
1260 459e9333 jim-p
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1261 ef00af3c Phil Davis
			} else {
1262 459e9333 jim-p
				$conf .= "ifconfig {$ip2} {$mask}\n";
1263 76569401 jim-p
				if ($settings['mode'] == 'p2p_tls') {
1264
					$add_pull = true;
1265
				}
1266 ef00af3c Phil Davis
			}
1267 8dc3ef67 Scott Ullrich
		}
1268 d799787e Matthew Grooms
1269 a0e3ee98 jim-p
		if (!empty($settings['tunnel_networkv6'])) {
1270 966cdb43 jim-p
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1271 91c44185 jim-p
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1272 ef00af3c Phil Davis
			if ($settings['dev_mode'] == 'tun') {
1273 a0e3ee98 jim-p
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1274 ef00af3c Phil Davis
			} else {
1275 f0a0bae5 Viktor G
				$conf .= "ifconfig-ipv6 {$ipv6_1}/{$prefix} {$ipv6_2}\n";
1276 76569401 jim-p
				if ($settings['mode'] == 'p2p_tls') {
1277
					$add_pull = true;
1278
				}
1279 ef00af3c Phil Davis
			}
1280 a0e3ee98 jim-p
		}
1281
1282 76569401 jim-p
		/* 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 a6d55c23 Chris Buechler
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
1295 348c2af1 jim-p
			$up_file = "{$g['openvpn_base']}/{$mode_id}/up";
1296 5f242576 PiBa-NL
			$conf .= "auth-user-pass {$up_file}\n";
1297 a69a9182 jim-p
			if (!$settings['auth-retry-none']) {
1298
				$conf .= "auth-retry nointeract\n";
1299
			}
1300 7304c023 Phil Davis
			if ($settings['auth_user']) {
1301 4de8f7ba Phil Davis
				$userpass = "{$settings['auth_user']}\n";
1302 7304c023 Phil Davis
			} else {
1303
				$userpass = "";
1304
			}
1305
			if ($settings['auth_pass']) {
1306 4de8f7ba Phil Davis
				$userpass .= "{$settings['auth_pass']}\n";
1307 7304c023 Phil Davis
			}
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 5f242576 PiBa-NL
			file_put_contents($up_file, $userpass);
1313
		}
1314 42bb1bee Renato Botelho
1315 762a24a3 Ermal Lu?i
		if ($settings['proxy_addr']) {
1316
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1317
			if ($settings['proxy_authtype'] != "none") {
1318 348c2af1 jim-p
				$conf .= " {$g['openvpn_base']}/{$mode_id}/proxy_auth {$settings['proxy_authtype']}";
1319 762a24a3 Ermal Lu?i
				$proxypas = "{$settings['proxy_user']}\n";
1320
				$proxypas .= "{$settings['proxy_passwd']}\n";
1321 348c2af1 jim-p
				file_put_contents("{$g['openvpn_base']}/{$mode_id}/proxy_auth", $proxypas);
1322 762a24a3 Ermal Lu?i
			}
1323
			$conf .= " \n";
1324
		}
1325 810adc14 Viktor G
1326
		if (($settings['mode'] != 'shared_key') &&
1327
		    isset($settings['remote_cert_tls'])) {
1328
			$conf .= "remote-cert-tls server\n";
1329
		}
1330 8dc3ef67 Scott Ullrich
	}
1331
1332 17c98ba9 jim-p
	// Add a remote network route if set, and only for p2p modes.
1333 4b8d710c Viktor G
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4", true) === FALSE)) {
1334 a28d40cb jim-p
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1335 8dc3ef67 Scott Ullrich
	}
1336 4856df9b jim-p
	// Add a remote network route if set, and only for p2p modes.
1337 4b8d710c Viktor G
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6", true) === FALSE)) {
1338 a28d40cb jim-p
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1339 4856df9b jim-p
	}
1340 afb07cf1 Scott Ullrich
1341 d799787e Matthew Grooms
	// Write the settings for the keys
1342 ef00af3c Phil Davis
	switch ($settings['mode']) {
1343 3c11bd3c Matthew Grooms
		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 e62e2f8b Ermal Lu?i
		case 'server_user':
1350 348c2af1 jim-p
			// ca_chain_array() expects parameter to be passed by reference.
1351 179377b0 robjarsen
			// avoid passing the whole settings array, as param names or
1352
			// types might change in future releases.
1353
			$param = array('caref' => $settings['caref']);
1354 348c2af1 jim-p
			$cas = ca_chain_array($param);
1355
			$capath = "{$g['openvpn_base']}/{$mode_id}/ca";
1356
			/* Cleanup old CA/CRL references */
1357 28cb1a27 jim-p
			@unlink_if_exists("{$capath}/*.0");
1358
			@unlink_if_exists("{$capath}/*.r*");
1359 348c2af1 jim-p
			/* 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 2da48592 jim-p
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 ef00af3c Phil Davis
			if ($mode == 'server') {
1377 f888c35a jim-p
				if (is_numeric($settings['dh_length'])) {
1378 c6668aba Phil Davis
					if (!in_array($settings['dh_length'], array_keys($openvpn_dh_lengths))) {
1379 f888c35a jim-p
						/* 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 ef00af3c Phil Davis
			}
1392 db746ce2 Ermal Lu?i
			if ($settings['tls']) {
1393 c854afcc jim-p
				if ($settings['tls_type'] == "crypt") {
1394
					$tls_directive = "tls-crypt";
1395
					$tlsopt = "";
1396 ef00af3c Phil Davis
				} else {
1397 c854afcc jim-p
					$tls_directive = "tls-auth";
1398
					if ($mode == "server") {
1399 8698f918 Vito Piserchia
						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 c854afcc jim-p
					} else {
1411 8698f918 Vito Piserchia
						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 c854afcc jim-p
					}
1423 ef00af3c Phil Davis
				}
1424 c854afcc jim-p
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, $tls_directive, $tlsopt);
1425 db746ce2 Ermal Lu?i
			}
1426 3c11bd3c Matthew Grooms
			break;
1427 8dc3ef67 Scott Ullrich
	}
1428
1429 924eeefb jim-p
	/* 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 78ce96a9 jim-p
	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 924eeefb jim-p
		$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 56e031a7 jim-p
	if (!empty($settings['allow_compression'])) {
1445
		$conf .= "allow-compression {$settings['allow_compression']}\n";
1446
	}
1447
1448 a4b36246 jim-p
	$compression = "";
1449
	switch ($settings['compression']) {
1450 38922574 jim-p
		case 'none':
1451
			$settings['compression'] = '';
1452 a4b36246 jim-p
		case 'lz4':
1453
		case 'lz4-v2':
1454
		case 'lzo':
1455
		case 'stub':
1456 38922574 jim-p
		case 'stub-v2':
1457 a4b36246 jim-p
			$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 16fe7982 jim-p
	if (($settings['allow_compression'] != 'no') &&
1473
	    !empty($compression)) {
1474 a4b36246 jim-p
		$conf .= "{$compression}\n";
1475
		if ($settings['compression_push']) {
1476
			$conf .= "push \"{$compression}\"\n";
1477 9446ee68 jim-p
		}
1478 ef00af3c Phil Davis
	}
1479 d799787e Matthew Grooms
1480 ef00af3c Phil Davis
	if ($settings['passtos']) {
1481 d799787e Matthew Grooms
		$conf .= "passtos\n";
1482 ef00af3c Phil Davis
	}
1483 d799787e Matthew Grooms
1484 919a0f4a jim-p
	if ($mode == 'client') {
1485 30640018 Chris Buechler
		$conf .= "resolv-retry infinite\n";
1486 ef00af3c Phil Davis
	}
1487 d799787e Matthew Grooms
1488
	if ($settings['dynamic_ip']) {
1489
		$conf .= "persist-remote-ip\n";
1490
		$conf .= "float\n";
1491 8dc3ef67 Scott Ullrich
	}
1492 afb07cf1 Scott Ullrich
1493 ef378560 jim-p
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1494 4742e635 Chris Buechler
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1495 63646f4d jim-p
		if (empty($settings['topology'])) {
1496
			$settings['topology'] = "subnet";
1497
		}
1498
		$conf .= "topology {$settings['topology']}\n";
1499 ee55ce7d jim-p
	}
1500
1501 b9e9903d Dmitriy K.
	// 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 2df5d9ee jim-p
	/* 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 0a70f90a jim-p
	/* 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 7591a72a jim-p
	    is_numericint($settings['exit_notify']) &&
1531 0a70f90a jim-p
	    (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 7591a72a jim-p
		$conf .= "explicit-exit-notify {$settings['exit_notify']}\n";
1535
	}
1536
1537 0a70f90a jim-p
	/* 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 7618a842 jim-p
	/* 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 d799787e Matthew Grooms
	openvpn_add_custom($settings, $conf);
1555
1556 969574b6 Viktor G
	/* 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 a8f538a8 jim-p
	openvpn_create_dirs();
1563 348c2af1 jim-p
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1564 d799787e Matthew Grooms
	file_put_contents($fpath, $conf);
1565 938fc5b0 Ermal
	unset($conf);
1566 348c2af1 jim-p
	$fpath = "{$g['openvpn_base']}/{$mode_id}/interface";
1567 be00850b Phil Davis
	file_put_contents($fpath, $interface);
1568 70e7b0c1 Marcos Mendoza
	$fpath = "{$g['openvpn_base']}/{$mode_id}/connuserlimit";
1569
	file_put_contents($fpath, $connlimit);
1570 f9ac3784 Ermal Lu?i
	//chown($fpath, 'nobody');
1571
	//chgrp($fpath, 'nobody');
1572 348c2af1 jim-p
	@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 70e7b0c1 Marcos Mendoza
	@chmod("{$g['openvpn_base']}/{$mode_id}/connuserlimit", 0600);
1578 5280fd8d Renato Botelho
1579
	if ($wait_tentative) {
1580
		interface_wait_tentative($interface);
1581
	}
1582 d799787e Matthew Grooms
}
1583
1584 fc05822b jim-p
function openvpn_restart($mode, $settings) {
1585 d799787e Matthew Grooms
	global $g, $config;
1586
1587
	$vpnid = $settings['vpnid'];
1588
	$mode_id = $mode.$vpnid;
1589 ce983754 PiBa-NL
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1590 8845e137 PiBa-NL
	openvpn_reconfigure($mode, $settings);
1591 76369bfc Matthew Grooms
	/* kill the process if running */
1592 705c8ec9 Matthew Grooms
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1593 76369bfc Matthew Grooms
	if (file_exists($pfile)) {
1594 705c8ec9 Matthew Grooms
1595 76369bfc Matthew Grooms
		/* read the pid file */
1596
		$pid = rtrim(file_get_contents($pfile));
1597
		unlink($pfile);
1598 8845e137 PiBa-NL
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1599 705c8ec9 Matthew Grooms
1600 76369bfc Matthew Grooms
		/* send a term signal to the process */
1601
		posix_kill($pid, SIGTERM);
1602
1603 93ead355 Chris Buechler
		/* wait until the process exits, or timeout and kill it */
1604
		$i = 0;
1605 ef00af3c Phil Davis
		while (posix_kill($pid, 0)) {
1606 76369bfc Matthew Grooms
			usleep(250000);
1607 93ead355 Chris Buechler
			if ($i > 10) {
1608 e8c516a0 Phil Davis
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1609 93ead355 Chris Buechler
				posix_kill($pid, SIGKILL);
1610 02a2bffa Chris Buechler
				usleep(500000);
1611 93ead355 Chris Buechler
			}
1612
			$i++;
1613
		}
1614 76369bfc Matthew Grooms
	}
1615 d799787e Matthew Grooms
1616 ef00af3c Phil Davis
	if (isset($settings['disable'])) {
1617 1c334904 Viktor G
		openvpn_delete($mode, $settings);
1618 ce983754 PiBa-NL
		unlock($lockhandle);
1619 d799787e Matthew Grooms
		return;
1620 ef00af3c Phil Davis
	}
1621 d799787e Matthew Grooms
1622 acb0c154 Marcos Mendoza
	openvpn_delete_tmp($mode, $vpnid);
1623
1624 f003f8db jim-p
	/* Do not start an instance if we are not CARP master on this vip! */
1625 70d79766 Viktor G
	if (strstr($settings['interface'], "_vip")) {
1626 6ae26227 Viktor G
	       	$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 866cc787 Steve Beaver
		if (in_array($carpstatus, array('BACKUP', 'INIT'))) {
1630 70d79766 Viktor G
			unlock($lockhandle);
1631
			return;
1632 6ae26227 Viktor G
		} 
1633 ef00af3c Phil Davis
	}
1634 42bb1bee Renato Botelho
1635
	/* Check if client is bound to a gateway group */
1636 43a9b03d PiBa-NL
	$a_groups = return_gateway_groups_array(true);
1637 330ecea1 Shahid Sheikh
	if (is_array($a_groups[$settings['interface']])) {
1638 ef00af3c Phil Davis
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1639 ddf99718 Phil Davis
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1640 ce983754 PiBa-NL
			unlock($lockhandle);
1641 330ecea1 Shahid Sheikh
			return;
1642 ef00af3c Phil Davis
		}
1643 330ecea1 Shahid Sheikh
	}
1644 9ea0cb90 jim-p
1645 705c8ec9 Matthew Grooms
	/* start the new process */
1646 348c2af1 jim-p
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1647 91c44185 jim-p
	openvpn_clear_route($mode, $settings);
1648 8845e137 PiBa-NL
	$res = mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1649
	if ($res == 0) {
1650
		$i = 0;
1651
		$pid = "--";
1652
		while ($i < 3000) {
1653 a1b39e94 PiBa-NL
			if (isvalidpid($pfile)) {
1654 8845e137 PiBa-NL
				$pid = rtrim(file_get_contents($pfile));
1655 a1b39e94 PiBa-NL
				break;
1656 8845e137 PiBa-NL
			}
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 0049d009 jim-p
	if (!platform_booting()) {
1665 847cd48d Ermal
		send_event("filter reload");
1666 ef00af3c Phil Davis
	}
1667 ce983754 PiBa-NL
	unlock($lockhandle);
1668 afb07cf1 Scott Ullrich
}
1669
1670 9272a448 Renato Botelho
function openvpn_delete($mode, $settings) {
1671 d799787e Matthew Grooms
	global $g, $config;
1672
1673
	$vpnid = $settings['vpnid'];
1674
	$mode_id = $mode.$vpnid;
1675
1676 ef00af3c Phil Davis
	if ($mode == "server") {
1677 095a95ae Matthew Grooms
		$devname = "ovpns{$vpnid}";
1678 ef00af3c Phil Davis
	} else {
1679 095a95ae Matthew Grooms
		$devname = "ovpnc{$vpnid}";
1680 ef00af3c Phil Davis
	}
1681 dc408939 Matthew Grooms
1682 76369bfc Matthew Grooms
	/* kill the process if running */
1683 dc408939 Matthew Grooms
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1684 76369bfc Matthew Grooms
	if (file_exists($pfile)) {
1685 dc408939 Matthew Grooms
1686 76369bfc Matthew Grooms
		/* 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 705c8ec9 Matthew Grooms
1694 3b1642ff Renato Botelho
	/* destroy the device */
1695
	pfSense_interface_destroy($devname);
1696 dc408939 Matthew Grooms
1697 7d813139 batnas
	/* Invalidate cache */
1698
	get_interface_arr(true);
1699
1700 dc408939 Matthew Grooms
	/* remove the configuration files */
1701 93830bec Viktor G
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*/*");
1702
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*");
1703 acb0c154 Marcos Mendoza
	openvpn_delete_tmp($mode, $vpnid);
1704 172452a4 Viktor G
	filter_configure();
1705 d799787e Matthew Grooms
}
1706 afb07cf1 Scott Ullrich
1707 dc408939 Matthew Grooms
function openvpn_resync_csc(& $settings) {
1708 154b0f80 jim-p
	global $g, $config, $openvpn_tls_server_modes;
1709 a1cab2c7 Ermal
	if (isset($settings['disable'])) {
1710 4e5e7540 jim-p
		openvpn_delete_csc($settings);
1711 c876662c Scott Ullrich
		return;
1712
	}
1713 a8f538a8 jim-p
	openvpn_create_dirs();
1714 d799787e Matthew Grooms
1715 154b0f80 jim-p
	if (empty($settings['server_list'])) {
1716
		$csc_server_list = array();
1717
	} else {
1718
		$csc_server_list = explode(",", $settings['server_list']);
1719
	}
1720
1721 8dc3ef67 Scott Ullrich
	$conf = '';
1722 ef00af3c Phil Davis
	if ($settings['block']) {
1723 d799787e Matthew Grooms
		$conf .= "disable\n";
1724 ef00af3c Phil Davis
	}
1725 d799787e Matthew Grooms
1726 ef00af3c Phil Davis
	if ($settings['push_reset']) {
1727 d799787e Matthew Grooms
		$conf .= "push-reset\n";
1728 ef00af3c Phil Davis
	}
1729 d799787e Matthew Grooms
1730 8d44d56a Viktor G
	if ($settings['remove_route']) {
1731
		$conf .= "push-remove route\n";
1732
	}
1733
1734 5c427ce7 jim-p
	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 4b8d710c Viktor G
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4", true) === FALSE) {
1743 5c427ce7 jim-p
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1744
	}
1745
	// Add a remote network iroute if set
1746 4b8d710c Viktor G
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6", true) === FALSE) {
1747 5c427ce7 jim-p
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1748
	}
1749
1750 d799787e Matthew Grooms
	openvpn_add_dhcpopts($settings, $conf);
1751 8dc3ef67 Scott Ullrich
1752 d799787e Matthew Grooms
	openvpn_add_custom($settings, $conf);
1753 154b0f80 jim-p
	/* 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 348c2af1 jim-p
					$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1762 154b0f80 jim-p
					$csc_conf = $conf;
1763
1764 cd8f2f2b jim-p
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1765 4b8d710c Viktor G
						list($ip, $mask) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1766 154b0f80 jim-p
						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 493e6807 stilez
							$baselong = gen_subnetv4($ip, $mask);
1771
							$serverip = ip_after($baselong, 1);
1772
							$clientip = ip_after($baselong, 2);
1773 154b0f80 jim-p
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1774
						}
1775
					}
1776 b6dd335e jim-p
1777
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1778 4b8d710c Viktor G
						list($ipv6, $prefix) = openvpn_gen_tunnel_network($serversettings['tunnel_networkv6']);
1779 b6dd335e jim-p
						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 154b0f80 jim-p
					file_put_contents($csc_path, $csc_conf);
1784
					chown($csc_path, 'nobody');
1785
					chgrp($csc_path, 'nobody');
1786
				}
1787
			}
1788
		}
1789
	}
1790 d799787e Matthew Grooms
}
1791 8dc3ef67 Scott Ullrich
1792 1f954318 jim-p
function openvpn_resync_csc_all() {
1793
	global $config;
1794 15713a56 Viktor G
	init_config_arr(array('openvpn', 'openvpn-csc'));
1795 1f954318 jim-p
	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 dc408939 Matthew Grooms
function openvpn_delete_csc(& $settings) {
1803 154b0f80 jim-p
	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 3c2e5528 Scott Ullrich
1810 154b0f80 jim-p
	/* 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 348c2af1 jim-p
					$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1819 154b0f80 jim-p
					unlink_if_exists($csc_path);
1820
				}
1821
			}
1822
		}
1823
	}
1824 267ab13f Ermal Luçi
}
1825 afb07cf1 Scott Ullrich
1826 24012690 Scott Ullrich
// Resync the configuration and restart the VPN
1827 fc05822b jim-p
function openvpn_resync($mode, $settings) {
1828 dc408939 Matthew Grooms
	openvpn_restart($mode, $settings);
1829 afb07cf1 Scott Ullrich
}
1830
1831 add2e3f7 Scott Ullrich
// Resync and restart all VPNs
1832 810f1026 Viktor G
function openvpn_resync_all($interface = "", $protocol = "") {
1833 d799787e Matthew Grooms
	global $g, $config;
1834 267ab13f Ermal Luçi
1835 ef00af3c Phil Davis
	if ($interface <> "") {
1836 e8c516a0 Phil Davis
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1837 ef00af3c Phil Davis
	} else {
1838 e8c516a0 Phil Davis
		log_error(gettext("Resyncing OpenVPN instances."));
1839 ef00af3c Phil Davis
	}
1840 34bc1324 Matthew Grooms
1841 7071aab3 James Webb
	// Check if OpenVPN clients and servers require a resync.
1842 15713a56 Viktor G
	init_config_arr(array('openvpn', 'openvpn-server'));
1843
	init_config_arr(array('openvpn', 'openvpn-client'));
1844 f7335af3 Renato Botelho do Couto
	foreach (array("server", "client") as $type) {
1845
		if (!is_array($config['openvpn']["openvpn-{$type}"])) {
1846
			continue;
1847 c7f60193 Ermal
		}
1848 f7335af3 Renato Botelho do Couto
		foreach ($config['openvpn']["openvpn-{$type}"] as & $settings) {
1849 15713a56 Viktor G
			if (isset($settings['disable'])) {
1850
				continue;
1851
			}
1852 810f1026 Viktor G
			if (!empty($protocol) &&
1853
			    ((($protocol == 'inet') && strstr($settings['protocol'], "6")) ||
1854
			    (($protocol == 'inet6') && strstr($settings['protocol'], "4")))) {
1855
				continue;
1856
			}
1857 348c2af1 jim-p
			$fpath = "{$g['openvpn_base']}/{$type}{$settings['vpnid']}/interface";
1858 7071aab3 James Webb
			$gw_group_change = FALSE;
1859 f7335af3 Renato Botelho do Couto
			$ip_change = ($interface === "") ||
1860
			    ($interface === $settings['interface']);
1861
1862 15f8062b James Webb
			if (!$ip_change && file_exists($fpath)) {
1863 f7335af3 Renato Botelho do Couto
				$gw_group_change =
1864
				    (trim(file_get_contents($fpath), " \t\n") !=
1865
				    get_failover_interface(
1866
					$settings['interface']));
1867 7071aab3 James Webb
			}
1868 f7335af3 Renato Botelho do Couto
1869 15f8062b James Webb
			if ($ip_change || $gw_group_change) {
1870 15713a56 Viktor G
				if (!$dirs) {
1871
					openvpn_create_dirs();
1872
				}
1873 f7335af3 Renato Botelho do Couto
				openvpn_resync($type, $settings);
1874 15713a56 Viktor G
				$restarted = true;
1875
				$dirs = true;
1876 ef00af3c Phil Davis
			}
1877 c7f60193 Ermal
		}
1878
	}
1879 afb07cf1 Scott Ullrich
1880 15713a56 Viktor G
	if ($restarted) {
1881
		openvpn_resync_csc_all();
1882 afb07cf1 Scott Ullrich
1883 15713a56 Viktor G
		/* 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 3f0e9812 Viktor G
	}
1889 5b237745 Scott Ullrich
}
1890 702a4702 Scott Ullrich
1891 99cc103b Phil Davis
// 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 e8c516a0 Phil Davis
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1900 99cc103b Phil Davis
					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 e8c516a0 Phil Davis
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1909 99cc103b Phil Davis
					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 ef00af3c Phil Davis
	} else {
1917 e8c516a0 Phil Davis
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1918 ef00af3c Phil Davis
	}
1919 99cc103b Phil Davis
}
1920
1921 453d9c96 jim-p
function openvpn_get_active_servers($type="multipoint") {
1922 71ca2cb2 Ermal
	global $config, $g;
1923
1924 53663f57 jim-p
	$servers = array();
1925
	if (is_array($config['openvpn']['openvpn-server'])) {
1926
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1927 ef00af3c Phil Davis
			if (empty($settings) || isset($settings['disable'])) {
1928 6b2dcac5 Ermal
				continue;
1929 ef00af3c Phil Davis
			}
1930 6b2dcac5 Ermal
1931 53663f57 jim-p
			$prot = $settings['protocol'];
1932
			$port = $settings['local_port'];
1933 42bb1bee Renato Botelho
1934 53663f57 jim-p
			$server = array();
1935 95305736 jim-p
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1936 41be629f jim-p
			$server['mode'] = $settings['mode'];
1937 ef00af3c Phil Davis
			if ($settings['description']) {
1938 53663f57 jim-p
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1939 ef00af3c Phil Davis
			} else {
1940 53663f57 jim-p
				$server['name'] = "Server {$prot}:{$port}";
1941 ef00af3c Phil Davis
			}
1942 53663f57 jim-p
			$server['conns'] = array();
1943 2eaa97b9 jim-p
			$server['vpnid'] = $settings['vpnid'];
1944
			$server['mgmt'] = "server{$server['vpnid']}";
1945 348c2af1 jim-p
			$socket = "unix://{$g['openvpn_base']}/{$server['mgmt']}/sock";
1946 4b8d710c Viktor G
			list($tn, $sm) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1947 453d9c96 jim-p
1948 6c3bfb73 jim-p
			if ((($server['mode'] == "p2p_shared_key") ||
1949 5f3aa946 Viktor G
			    (($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network']) && ($server['mode'] == 'p2p_tls')) ||
1950 6c3bfb73 jim-p
			    ($sm >= 30)) &&
1951
			    ($type == "p2p")) {
1952 95305736 jim-p
				$servers[] = openvpn_get_client_status($server, $socket);
1953 6c3bfb73 jim-p
			} elseif (($server['mode'] != "p2p_shared_key") &&
1954 9be20fdf Viktor G
			    !(($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network']) && ($server['mode'] == 'p2p_tls')) &&
1955 6c3bfb73 jim-p
			    ($type == "multipoint") &&
1956
			    ($sm < 30)) {
1957 95305736 jim-p
				$servers[] = openvpn_get_server_status($server, $socket);
1958 ef00af3c Phil Davis
			}
1959 95305736 jim-p
		}
1960
	}
1961
	return $servers;
1962
}
1963 b0140675 Ermal
1964 95305736 jim-p
function openvpn_get_server_status($server, $socket) {
1965 247c417f Sjon Hortensius
	$errval = null;
1966
	$errstr = null;
1967 95305736 jim-p
	$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 ef00af3c Phil Davis
			if ($info['timed_out']) {
1982 95305736 jim-p
				break;
1983 ef00af3c Phil Davis
			}
1984 95305736 jim-p
1985
			/* parse header list line */
1986 ef00af3c Phil Davis
			if (strstr($line, "HEADER")) {
1987 95305736 jim-p
				continue;
1988 ef00af3c Phil Davis
			}
1989 95305736 jim-p
1990
			/* parse end of output line */
1991 ef00af3c Phil Davis
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1992 95305736 jim-p
				break;
1993 ef00af3c Phil Davis
			}
1994 95305736 jim-p
1995
			/* parse client list line */
1996
			if (strstr($line, "CLIENT_LIST")) {
1997
				$list = explode(",", $line);
1998 53663f57 jim-p
				$conn = array();
1999 95305736 jim-p
				$conn['common_name'] = $list[1];
2000
				$conn['remote_host'] = $list[2];
2001
				$conn['virtual_addr'] = $list[3];
2002 6f17547a jim-p
				$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 f5736d98 Viktor G
				$conn['cipher'] = $list[12];
2011 53663f57 jim-p
				$server['conns'][] = $conn;
2012
			}
2013 ec970b50 jim-p
			/* 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 53663f57 jim-p
		}
2024 95305736 jim-p
2025
		/* cleanup */
2026
		fclose($fp);
2027
	} else {
2028
		$conn = array();
2029
		$conn['common_name'] = "[error]";
2030 e8c516a0 Phil Davis
		$conn['remote_host'] = gettext("Unable to contact daemon");
2031
		$conn['virtual_addr'] = gettext("Service not running?");
2032 95305736 jim-p
		$conn['bytes_recv'] = 0;
2033
		$conn['bytes_sent'] = 0;
2034
		$conn['connect_time'] = 0;
2035
		$server['conns'][] = $conn;
2036 53663f57 jim-p
	}
2037 95305736 jim-p
	return $server;
2038 53663f57 jim-p
}
2039
2040
function openvpn_get_active_clients() {
2041 71ca2cb2 Ermal
	global $config, $g;
2042
2043 53663f57 jim-p
	$clients = array();
2044
	if (is_array($config['openvpn']['openvpn-client'])) {
2045
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
2046 42bb1bee Renato Botelho
2047 ef00af3c Phil Davis
			if (empty($settings) || isset($settings['disable'])) {
2048 6b2dcac5 Ermal
				continue;
2049 ef00af3c Phil Davis
			}
2050 6b2dcac5 Ermal
2051 53663f57 jim-p
			$prot = $settings['protocol'];
2052 95305736 jim-p
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
2053 42bb1bee Renato Botelho
2054 53663f57 jim-p
			$client = array();
2055
			$client['port'] = $settings['local_port'];
2056 ef00af3c Phil Davis
			if ($settings['description']) {
2057 95305736 jim-p
				$client['name'] = "{$settings['description']} {$prot}{$port}";
2058 ef00af3c Phil Davis
			} else {
2059 95305736 jim-p
				$client['name'] = "Client {$prot}{$port}";
2060 ef00af3c Phil Davis
			}
2061 42bb1bee Renato Botelho
2062 2eaa97b9 jim-p
			$client['vpnid'] = $settings['vpnid'];
2063
			$client['mgmt'] = "client{$client['vpnid']}";
2064 348c2af1 jim-p
			$socket = "unix://{$g['openvpn_base']}/{$client['mgmt']}/sock";
2065 53663f57 jim-p
			$client['status']="down";
2066 95305736 jim-p
2067
			$clients[] = openvpn_get_client_status($client, $socket);
2068
		}
2069
	}
2070
	return $clients;
2071
}
2072
2073
function openvpn_get_client_status($client, $socket) {
2074 247c417f Sjon Hortensius
	$errval = null;
2075
	$errstr = null;
2076 95305736 jim-p
	$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 ef00af3c Phil Davis
			if ($info['timed_out']) {
2089 95305736 jim-p
				break;
2090 ef00af3c Phil Davis
			}
2091 95305736 jim-p
2092
			/* Get the client state */
2093 f2c2a2b4 jim-p
			if (substr_count($line, ',') >= 7) {
2094
				$list = explode(",", trim($line));
2095
				$list = array_map('trim', $list);
2096 95305736 jim-p
2097 4de8f7ba Phil Davis
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
2098 f2c2a2b4 jim-p
				$client['state'] = $list[1];
2099
				$client['state_detail'] = $list[2];
2100 4de8f7ba Phil Davis
				$client['virtual_addr'] = $list[3];
2101 95305736 jim-p
				$client['remote_host'] = $list[4];
2102 cbfd0754 jim-p
				$client['remote_port'] = $list[5];
2103
				$client['local_host'] = $list[6];
2104
				$client['local_port'] = $list[7];
2105
				$client['virtual_addr6'] = $list[8];
2106 453d9c96 jim-p
2107 f2c2a2b4 jim-p
				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 453d9c96 jim-p
2162
			}
2163 95305736 jim-p
			/* parse end of output line */
2164 ef00af3c Phil Davis
			if (strstr($line, "END") || strstr($line, "ERROR")) {
2165 95305736 jim-p
				break;
2166 ef00af3c Phil Davis
			}
2167 95305736 jim-p
		}
2168
2169
		/* If up, get read/write stats */
2170 f2c2a2b4 jim-p
		if (strcmp($client['state'], "CONNECTED") == 0) {
2171 95305736 jim-p
			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 ef00af3c Phil Davis
				if ($info['timed_out']) {
2179 95305736 jim-p
					break;
2180 ef00af3c Phil Davis
				}
2181 95305736 jim-p
2182 4de8f7ba Phil Davis
				if (strstr($line, "TCP/UDP read bytes")) {
2183 95305736 jim-p
					$list = explode(",", $line);
2184
					$client['bytes_recv'] = $list[1];
2185 53663f57 jim-p
				}
2186 95305736 jim-p
2187 4de8f7ba Phil Davis
				if (strstr($line, "TCP/UDP write bytes")) {
2188 95305736 jim-p
					$list = explode(",", $line);
2189
					$client['bytes_sent'] = $list[1];
2190 53663f57 jim-p
				}
2191 95305736 jim-p
2192
				/* parse end of output line */
2193 ef00af3c Phil Davis
				if (strstr($line, "END")) {
2194 95305736 jim-p
					break;
2195 ef00af3c Phil Davis
				}
2196 53663f57 jim-p
			}
2197
		}
2198 95305736 jim-p
2199
		fclose($fp);
2200
2201
	} else {
2202 e8c516a0 Phil Davis
		$client['remote_host'] = gettext("Unable to contact daemon");
2203
		$client['virtual_addr'] = gettext("Service not running?");
2204 95305736 jim-p
		$client['bytes_recv'] = 0;
2205
		$client['bytes_sent'] = 0;
2206
		$client['connect_time'] = 0;
2207 53663f57 jim-p
	}
2208 95305736 jim-p
	return $client;
2209 53663f57 jim-p
}
2210 8e022a76 jim-p
2211 08ef78ac Viktor G
function openvpn_kill_client($port, $remipp, $client_id) {
2212 61fce4a6 Phil Davis
	global $g;
2213
2214
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
2215 348c2af1 jim-p
	$tcpsrv = "unix://{$g['openvpn_base']}/{$port}/sock";
2216 61fce4a6 Phil Davis
	$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 6e889d88 Viktor G
		if (is_numeric($client_id)) {
2225 08ef78ac Viktor G
			/* 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 61fce4a6 Phil Davis
		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 8e022a76 jim-p
function openvpn_refresh_crls() {
2253
	global $g, $config;
2254
2255 a8f538a8 jim-p
	openvpn_create_dirs();
2256 8e022a76 jim-p
2257
	if (is_array($config['openvpn']['openvpn-server'])) {
2258
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2259 ef00af3c Phil Davis
			if (empty($settings)) {
2260 8e022a76 jim-p
				continue;
2261 ef00af3c Phil Davis
			}
2262
			if (isset($settings['disable'])) {
2263 8e022a76 jim-p
				continue;
2264 ef00af3c Phil Davis
			}
2265 8e022a76 jim-p
			// Write the settings for the keys
2266 ef00af3c Phil Davis
			switch ($settings['mode']) {
2267 8e022a76 jim-p
				case 'p2p_tls':
2268
				case 'server_tls':
2269
				case 'server_tls_user':
2270
				case 'server_user':
2271 348c2af1 jim-p
					$param = array('caref' => $settings['caref']);
2272
					$cas = ca_chain_array($param);
2273 475d712b jim-p
					$capath = "{$g['openvpn_base']}/server{$settings['vpnid']}/ca";
2274 8e022a76 jim-p
					if (!empty($settings['crlref'])) {
2275
						$crl = lookup_crl($settings['crlref']);
2276 728003c8 jim-p
						crl_update($crl);
2277 348c2af1 jim-p
					}
2278
					foreach ($cas as $ca) {
2279 475d712b jim-p
						ca_setup_capath($ca, $capath, $crl, true);
2280 8e022a76 jim-p
					}
2281 f61a794a jim-p
					unset($cas, $param, $capath, $crl);
2282 8e022a76 jim-p
					break;
2283
			}
2284
		}
2285
	}
2286
}
2287
2288 a8f538a8 jim-p
function openvpn_create_dirs() {
2289 154b0f80 jim-p
	global $g, $config, $openvpn_tls_server_modes;
2290 348c2af1 jim-p
	if (!is_dir($g['openvpn_base'])) {
2291
		safe_mkdir($g['openvpn_base'], 0750);
2292 ef00af3c Phil Davis
	}
2293 154b0f80 jim-p
2294 348c2af1 jim-p
	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 15713a56 Viktor G
			if (isset($settings['disable'])) {
2299
				continue;
2300
			}
2301 348c2af1 jim-p
			$target = "{$g['openvpn_base']}/{$mode}{$settings['vpnid']}";
2302 15713a56 Viktor G
			$csctarget = "{$target}/csc/";
2303 348c2af1 jim-p
			@unlink_if_exists($csctarget);
2304
			@safe_mkdir($target);
2305 154b0f80 jim-p
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2306 15713a56 Viktor G
				@safe_mkdir($csctarget);
2307 154b0f80 jim-p
			}
2308
		}
2309
	}
2310 a8f538a8 jim-p
}
2311
2312 30c8a290 Renato Botelho
function openvpn_get_interface_ip($ip, $cidr) {
2313
	$subnet = gen_subnetv4($ip, $cidr);
2314 10a8b5ee PiBa-NL
	if ($cidr == 31) {
2315
		$ip1 = $subnet;
2316
	} else {
2317
		$ip1 = ip_after($subnet);
2318
	}
2319 30c8a290 Renato Botelho
	$ip2 = ip_after($ip1);
2320 91c44185 jim-p
	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 10a8b5ee PiBa-NL
	if ($prefix == 127) {
2329
		$last--;
2330
	}
2331 587995fb Phil Davis
	$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 91c44185 jim-p
	return array($ipv6_1, $ipv6_2);
2334
}
2335
2336
function openvpn_clear_route($mode, $settings) {
2337 ef00af3c Phil Davis
	if (empty($settings['tunnel_network'])) {
2338 91c44185 jim-p
		return;
2339 ef00af3c Phil Davis
	}
2340 4b8d710c Viktor G
	list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
2341 91c44185 jim-p
	$mask = gen_subnet_mask($cidr);
2342 6ca938cf jim-p
	$clear_route = false;
2343
2344 ef00af3c Phil Davis
	switch ($settings['mode']) {
2345 6ca938cf jim-p
		case 'shared_key':
2346
			$clear_route = true;
2347
			break;
2348 91c44185 jim-p
		case 'p2p_tls':
2349
		case 'p2p_shared_key':
2350 a0f991ec PiBa-NL
			if ($cidr >= 30) {
2351 6ca938cf jim-p
				$clear_route = true;
2352 ef00af3c Phil Davis
			}
2353 91c44185 jim-p
			break;
2354
	}
2355 6ca938cf jim-p
2356 6d0b9fe9 jim-p
	if ($clear_route && !empty($ip) && !empty($mask)) {
2357 30c8a290 Renato Botelho
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2358 6ca938cf jim-p
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2359 615d7f0a Ermal
		/* XXX: Family for route? */
2360 6ca938cf jim-p
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2361
	}
2362 91c44185 jim-p
}
2363
2364 5c427ce7 jim-p
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2365 a28d40cb jim-p
	$routes = "";
2366 4b8d710c Viktor G
	$networks = array();
2367 ef00af3c Phil Davis
	if (empty($value)) {
2368 a28d40cb jim-p
		return "";
2369 ef00af3c Phil Davis
	}
2370 4b8d710c Viktor G
	$tmpnetworks = explode(',', $value);
2371
	foreach ($tmpnetworks as $network) {
2372
		if (is_alias($network)) {
2373 60c0b333 Viktor G
			foreach (alias_to_subnets_recursive($network, true) as $net) {
2374 4b8d710c Viktor G
				if ((($ipproto == "ipv4") && is_subnetv4($net)) ||
2375
				    (($ipproto == "ipv6") && is_subnetv6($net))) {
2376
					$networks[] = $net;
2377 60c0b333 Viktor G
				} elseif (is_fqdn($net)) {
2378
					if ($ipproto == "ipv4" ) {
2379
						$recordtypes = array(DNS_A);
2380 065e0508 Viktor G
						$mask = "/32";
2381 60c0b333 Viktor G
					} else {
2382
						$recordtypes = array(DNS_AAAA);
2383 065e0508 Viktor G
						$mask = "/128";
2384
					}
2385 4533e50b Viktor G
					$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 60c0b333 Viktor G
					}
2393 4b8d710c Viktor G
				}
2394
			}
2395
		} else {
2396
			$networks[] = $network;
2397
		}
2398
	}
2399 a28d40cb jim-p
2400
	foreach ($networks as $network) {
2401 ef00af3c Phil Davis
		if ($ipproto == "ipv4") {
2402 5c427ce7 jim-p
			$route = openvpn_gen_route_ipv4($network, $iroute);
2403 ef00af3c Phil Davis
		} else {
2404 5c427ce7 jim-p
			$route = openvpn_gen_route_ipv6($network, $iroute);
2405 ef00af3c Phil Davis
		}
2406 a28d40cb jim-p
2407 ef00af3c Phil Davis
		if ($push) {
2408 a28d40cb jim-p
			$routes .= "push \"{$route}\"\n";
2409 ef00af3c Phil Davis
		} else {
2410 a28d40cb jim-p
			$routes .= "{$route}\n";
2411 ef00af3c Phil Davis
		}
2412 a28d40cb jim-p
	}
2413
	return $routes;
2414
}
2415
2416 5c427ce7 jim-p
function openvpn_gen_route_ipv4($network, $iroute = false) {
2417
	$i = ($iroute) ? "i" : "";
2418 a28d40cb jim-p
	list($ip, $mask) = explode('/', trim($network));
2419
	$mask = gen_subnet_mask($mask);
2420 5c427ce7 jim-p
	return "{$i}route $ip $mask";
2421 a28d40cb jim-p
}
2422
2423 5c427ce7 jim-p
function openvpn_gen_route_ipv6($network, $iroute = false) {
2424
	$i = ($iroute) ? "i" : "";
2425 a28d40cb jim-p
	list($ipv6, $prefix) = explode('/', trim($network));
2426 3000b44d Renato Botelho
	if (empty($prefix) && !is_numeric($prefix)) {
2427 a28d40cb jim-p
		$prefix = "128";
2428 ef00af3c Phil Davis
	}
2429 5c427ce7 jim-p
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2430 a28d40cb jim-p
}
2431
2432 699125b1 jim-p
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 ef00af3c Phil Davis
			if (isset($settings['disable'])) {
2438 699125b1 jim-p
				continue;
2439 ef00af3c Phil Davis
			}
2440 699125b1 jim-p
2441 ef00af3c Phil Davis
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2442 699125b1 jim-p
				return $settings;
2443 ef00af3c Phil Davis
			}
2444 699125b1 jim-p
		}
2445
	}
2446
2447
	if (is_array($config['openvpn']['openvpn-client'])) {
2448
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
2449 ef00af3c Phil Davis
			if (isset($settings['disable'])) {
2450 699125b1 jim-p
				continue;
2451 ef00af3c Phil Davis
			}
2452 699125b1 jim-p
2453 ef00af3c Phil Davis
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2454 699125b1 jim-p
				return $settings;
2455 ef00af3c Phil Davis
			}
2456 699125b1 jim-p
		}
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 19a0636d jim-p
/****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 924eeefb jim-p
2499 3adc4134 jim-p
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 924eeefb jim-p
	/* If the data_ciphers list is empty, populate it with the fallback cipher. */
2501 3adc4134 jim-p
	if (empty($data_ciphers) || !$ncp_enabled) {
2502 924eeefb jim-p
		$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 30064732 Viktor G
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 2e6b2841 Viktor G
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 0fe9c7bb Viktor G
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 756720e2 Pierre POMES
?>