Project

General

Profile

Download (70.1 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 8f585441 Luiz Souza
 * Copyright (c) 2014-2021 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 f2291484 jim-p
global $openvpn_prots;
38 ca366676 jim-p
$openvpn_prots = array(
39
	"UDP4" => "UDP on IPv4 only",
40
	"UDP6" => "UDP on IPv6 only",
41
	"TCP4" => "TCP on IPv4 only",
42
	"TCP6" => "TCP on IPv6 only",
43
	"UDP" => "UDP IPv4 and IPv6 on all interfaces (multihome)",
44
	"TCP" => "TCP IPv4 and IPv6 on all interfaces (multihome)"
45
);
46 702a4702 Scott Ullrich
47 f2291484 jim-p
global $openvpn_dev_mode;
48 b743ea87 jim-p
$openvpn_dev_mode = array(
49
	"tun" => "tun - Layer 3 Tunnel Mode",
50
	"tap" => "tap - Layer 2 Tap Mode"
51
);
52 691fbf14 Ermal Lu?i
53 b9e9903d Dmitriy K.
global $openvpn_verbosity_level;
54
$openvpn_verbosity_level = array(
55 e8c516a0 Phil Davis
	0 =>	gettext("none"),
56
	1 =>	gettext("default"),
57 42bb1bee Renato Botelho
	2 =>	"2",
58 e8c516a0 Phil Davis
	3 =>	gettext("3 (recommended)"),
59 b9e9903d Dmitriy K.
	4 =>	"4",
60
	5 => 	"5",
61
	6 => 	"6",
62
	7 => 	"7",
63
	8 => 	"8",
64
	9 => 	"9",
65
	10 => 	"10",
66
	11 => 	"11"
67 42bb1bee Renato Botelho
);
68 b9e9903d Dmitriy K.
69 42bb1bee Renato Botelho
/*
70 3c11bd3c Matthew Grooms
 * The User Auth mode below is disabled because
71
 * OpenVPN erroneously requires that we provide
72
 * a CA configuration parameter. In this mode,
73
 * clients don't send a certificate so there is
74
 * no need for a CA. If we require that admins
75
 * provide one in the pfSense UI due to a bogus
76
 * requirement imposed by OpenVPN, it could be
77
 * considered very confusing ( I know I was ).
78
 *
79
 * -mgrooms
80
 */
81
82 f2291484 jim-p
global $openvpn_dh_lengths;
83 fe787fc7 Matthew Grooms
$openvpn_dh_lengths = array(
84 f888c35a jim-p
	1024 => "1024 bit",
85 4b6bf6aa Justin Coffman
	2048 => "2048 bit",
86
	3072 => "3072 bit",
87
	4096 => "4096 bit",
88
	6144 => "6144 bit",
89 f888c35a jim-p
	7680 => "7680 bit",
90 4b6bf6aa Justin Coffman
	8192 => "8192 bit",
91 f888c35a jim-p
	15360 => "15360 bit",
92
	16384 => "16384 bit",
93
	"none" => "ECDH Only"
94 0693c967 stilez
);
95 f888c35a jim-p
foreach ($openvpn_dh_lengths as $idx => $dhlen) {
96
	if (is_numeric($idx) && !file_exists("/etc/dh-parameters.{$idx}")) {
97
		unset($openvpn_dh_lengths[$idx]);
98
	}
99
}
100 fe787fc7 Matthew Grooms
101 f2291484 jim-p
global $openvpn_cert_depths;
102 98963f27 jim-p
$openvpn_cert_depths = array(
103 e8c516a0 Phil Davis
	1 => gettext("One (Client+Server)"),
104
	2 => gettext("Two (Client+Intermediate+Server)"),
105
	3 => gettext("Three (Client+2xIntermediate+Server)"),
106
	4 => gettext("Four (Client+3xIntermediate+Server)"),
107
	5 => gettext("Five (Client+4xIntermediate+Server)")
108 98963f27 jim-p
);
109
110 f2291484 jim-p
global $openvpn_server_modes;
111 3c11bd3c Matthew Grooms
$openvpn_server_modes = array(
112 4aa02281 Carlos Eduardo Ramos
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
113
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"),
114
	'server_tls' => gettext("Remote Access ( SSL/TLS )"),
115
	'server_user' => gettext("Remote Access ( User Auth )"),
116
	'server_tls_user' => gettext("Remote Access ( SSL/TLS + User Auth )"));
117 3c11bd3c Matthew Grooms
118 154b0f80 jim-p
global $openvpn_tls_server_modes;
119
$openvpn_tls_server_modes = array('p2p_tls', 'server_tls', 'server_user', 'server_tls_user');
120
121 f2291484 jim-p
global $openvpn_client_modes;
122 3c11bd3c Matthew Grooms
$openvpn_client_modes = array(
123 4aa02281 Carlos Eduardo Ramos
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
124 ef00af3c Phil Davis
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"));
125 3c11bd3c Matthew Grooms
126 56e031a7 jim-p
global $openvpn_allow_compression;
127
$openvpn_allow_compression = array(
128
	'asym' => gettext("Decompress incoming, do not compress outgoing (Asymmetric)"),
129
	'no'   => gettext("Refuse any non-stub compression (Most secure)"),
130
	'yes'  => gettext("Compress packets (WARNING: Potentially dangerous!)"),
131
);
132
133 edba1982 jim-p
global $openvpn_compression_modes;
134
$openvpn_compression_modes = array(
135 56e031a7 jim-p
	'' => gettext("Disable Compression [Omit Preference]"),
136 38922574 jim-p
	'none' => gettext("Disable Compression, retain compression packet framing [compress]"),
137 56e031a7 jim-p
	'stub' => gettext("Enable Compression (stub) [compress stub]"),
138
	'stub-v2' => gettext("Enable Compression (stub v2) [compress stub-v2]"),
139 a4b36246 jim-p
	'lz4' => gettext("LZ4 Compression [compress lz4]"),
140 61a8cc10 jim-p
	'lz4-v2' => gettext("LZ4 Compression v2 [compress lz4-v2]"),
141 a4b36246 jim-p
	'lzo' => gettext("LZO Compression [compress lzo, equivalent to comp-lzo yes for compatibility]"),
142
	'noadapt' => gettext("Omit Preference, + Disable Adaptive LZO Compression [Legacy style, comp-noadapt]"),
143
	'adaptive' => gettext("Adaptive LZO Compression [Legacy style, comp-lzo adaptive]"),
144
	'yes' => gettext("LZO Compression [Legacy style, comp-lzo yes]"),
145
	'no' => gettext("No LZO Compression [Legacy style, comp-lzo no]"),
146
);
147 edba1982 jim-p
148 88cfb255 jim-p
global $openvpn_topologies;
149
$openvpn_topologies = array(
150
	'subnet' => gettext("Subnet -- One IP address per client in a common subnet"),
151
	'net30' => gettext("net30 -- Isolated /30 network per client")
152
);
153
154 c854afcc jim-p
global $openvpn_tls_modes;
155
$openvpn_tls_modes = array(
156
	'auth' => gettext("TLS Authentication"),
157 feec858c jim-p
	'crypt' => gettext("TLS Encryption and Authentication")
158 c854afcc jim-p
);
159
160 3bfecc81 Renato Botelho do Couto
global $openvpn_ping_method;
161
$openvpn_ping_method = array(
162
	'keepalive' => gettext("keepalive -- Use keepalive helper to define ping configuration"),
163
	'ping' => gettext("ping -- Define ping/ping-exit/ping-restart manually")
164
);
165
166
global $openvpn_default_keepalive_interval;
167
$openvpn_default_keepalive_interval = 10;
168
169
global $openvpn_default_keepalive_timeout;
170
$openvpn_default_keepalive_timeout = 60;
171
172
global $openvpn_ping_action;
173
$openvpn_ping_action = array(
174
	'ping_restart' => gettext("ping-restart -- Restart OpenVPN after timeout"),
175
	'ping_exit' => gettext("ping-exit -- Exit OpenVPN after timeout")
176
);
177
178 7591a72a jim-p
global $openvpn_exit_notify_server;
179
$openvpn_exit_notify_server = array(
180
	'none' => gettext("Disabled"),
181
	'1' => gettext("Reconnect to this server / Retry once"),
182
	'2' => gettext("Reconnect to next server / Retry twice"),
183
);
184
185
global $openvpn_exit_notify_client;
186
$openvpn_exit_notify_client = array(
187
	'none' => gettext("Disabled"),
188
);
189
for ($i=1; $i<=5; $i++) {
190
	$openvpn_exit_notify_client[$i] = sprintf(gettext("Retry %dx"), $i);
191
}
192
193 f4eec250 Phil Davis
function openvpn_build_mode_list() {
194
	global $openvpn_server_modes;
195
196
	$list = array();
197
198 4e322e2c Phil Davis
	foreach ($openvpn_server_modes as $name => $desc) {
199 f4eec250 Phil Davis
		$list[$name] = $desc;
200 4e322e2c Phil Davis
	}
201 f4eec250 Phil Davis
202
	return($list);
203
}
204
205 adf5849b PiBa-NL
global $openvpn_interfacenames;
206
function convert_openvpn_interface_to_friendly_descr($if) {
207
	global $openvpn_interfacenames;
208
	if (!is_array($openvpn_interfacenames)) {
209
		$openvpn_interfacenames = openvpn_build_if_list();
210
	}
211
	foreach($openvpn_interfacenames as $key => $value) {
212
		list($item_if, $item_ip) = explode("|", $key);
213
		if ($if == $item_if) {
214
			echo "$value";
215
		}
216
	}
217
}
218
219 f4eec250 Phil Davis
function openvpn_build_if_list() {
220
	$list = array();
221
222
	$interfaces = get_configured_interface_with_descr();
223 2a5960b0 Luiz Otavio O Souza
	$viplist = get_configured_vip_list();
224
	foreach ($viplist as $vip => $address) {
225
		$interfaces[$vip.'|'.$address] = $address;
226
		if (get_vip_descr($address)) {
227
			$interfaces[$vip.'|'.$address] .= " (";
228
			$interfaces[$vip.'|'.$address] .= get_vip_descr($address);
229
			$interfaces[$vip.'|'.$address] .= ")";
230
		}
231 4e322e2c Phil Davis
	}
232 f4eec250 Phil Davis
233
	$grouplist = return_gateway_groups_array();
234
	foreach ($grouplist as $name => $group) {
235 4e322e2c Phil Davis
		if ($group[0]['vip'] != "") {
236 f4eec250 Phil Davis
			$vipif = $group[0]['vip'];
237 4e322e2c Phil Davis
		} else {
238 f4eec250 Phil Davis
			$vipif = $group[0]['int'];
239 4e322e2c Phil Davis
		}
240 f4eec250 Phil Davis
241
		$interfaces[$name] = "GW Group {$name}";
242
	}
243
244
	$interfaces['lo0'] = "Localhost";
245
	$interfaces['any'] = "any";
246
247 4e322e2c Phil Davis
	foreach ($interfaces as $iface => $ifacename) {
248 f4eec250 Phil Davis
	   $list[$iface] = $ifacename;
249 4e322e2c Phil Davis
	}
250 f4eec250 Phil Davis
251
	return($list);
252
}
253
254
function openvpn_build_crl_list() {
255
	global $a_crl;
256
257
	$list = array('' => 'None');
258
259
	foreach ($a_crl as $crl) {
260
		$caname = "";
261
		$ca = lookup_ca($crl['caref']);
262
263 4e322e2c Phil Davis
		if ($ca) {
264 f4eec250 Phil Davis
			$caname = " (CA: {$ca['descr']})";
265 4e322e2c Phil Davis
		}
266 f4eec250 Phil Davis
267
		$list[$crl['refid']] = $crl['descr'] . $caname;
268
	}
269
270
	return($list);
271
}
272
273 0e9d4a6d jim-p
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
274 f4eec250 Phil Davis
	global $a_cert;
275 bc3e78ab jim-p
	$openvpn_compatible_certs = cert_build_list('cert', 'OpenVPN');
276 f4eec250 Phil Davis
277
	if ($include_none) {
278 e8c516a0 Phil Davis
		$list = array('' => gettext('None (Username and/or Password required)'));
279 f4eec250 Phil Davis
	} else {
280
		$list = array();
281
	}
282
283 a4ba0282 Stephen Beaver
	$non_server_list = array();
284
285 0e9d4a6d jim-p
	if ($prioritize_server_certs) {
286 e8c516a0 Phil Davis
		$list[' '] = gettext("===== Server Certificates =====");
287
		$non_server_list['  '] = gettext("===== Non-Server Certificates =====");
288 0e9d4a6d jim-p
	}
289
290 f4eec250 Phil Davis
	foreach ($a_cert as $cert) {
291 bc3e78ab jim-p
		if (!array_key_exists($cert['refid'], $openvpn_compatible_certs)) {
292
			continue;
293
		}
294 0e9d4a6d jim-p
		$properties = array();
295
		$propstr = "";
296 f4eec250 Phil Davis
		$ca = lookup_ca($cert['caref']);
297 0e9d4a6d jim-p
		$purpose = cert_get_purpose($cert['crt'], true);
298 f4eec250 Phil Davis
299 0e9d4a6d jim-p
		if ($purpose['server'] == "Yes") {
300 e8c516a0 Phil Davis
			$properties[] = gettext("Server: Yes");
301 0e9d4a6d jim-p
		} elseif ($prioritize_server_certs) {
302 e8c516a0 Phil Davis
			$properties[] = gettext("Server: NO");
303 0e9d4a6d jim-p
		}
304 de1a3167 jim-p
		if ($ca) {
305 e8c516a0 Phil Davis
			$properties[] = sprintf(gettext("CA: %s"), $ca['descr']);
306 de1a3167 jim-p
		}
307 0e9d4a6d jim-p
		if (cert_in_use($cert['refid'])) {
308 e8c516a0 Phil Davis
			$properties[] = gettext("In Use");
309 0e9d4a6d jim-p
		}
310
		if (is_cert_revoked($cert)) {
311 e8c516a0 Phil Davis
			$properties[] = gettext("Revoked");
312 de1a3167 jim-p
		}
313 f4eec250 Phil Davis
314 0e9d4a6d jim-p
		if (!empty($properties)) {
315
			$propstr = " (" . implode(", ", $properties) . ")";
316 de1a3167 jim-p
		}
317 f4eec250 Phil Davis
318 0e9d4a6d jim-p
		if ($prioritize_server_certs) {
319
			if ($purpose['server'] == "Yes") {
320
				$list[$cert['refid']] = $cert['descr'] . $propstr;
321
			} else {
322
				$non_server_list[$cert['refid']] = $cert['descr'] . $propstr;
323
			}
324
		} else {
325
			$list[$cert['refid']] = $cert['descr'] . $propstr;
326 de1a3167 jim-p
		}
327 0e9d4a6d jim-p
	}
328 f4eec250 Phil Davis
329 a4ba0282 Stephen Beaver
	return(array('server' => $list, 'non-server' => $non_server_list));
330 f4eec250 Phil Davis
}
331
332
function openvpn_build_bridge_list() {
333
	$list = array();
334
335
	$serverbridge_interface['none'] = "none";
336
	$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
337 2a5960b0 Luiz Otavio O Souza
	$viplist = get_configured_vip_list();
338 f4eec250 Phil Davis
339 2a5960b0 Luiz Otavio O Souza
	foreach ($viplist as $vip => $address) {
340
		$serverbridge_interface[$vip.'|'.$address] = $address;
341 d9901ff4 Chris Buechler
		if (get_vip_descr($address)) {
342 2a5960b0 Luiz Otavio O Souza
			$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
343 d9901ff4 Chris Buechler
		}
344 4e322e2c Phil Davis
	}
345 f4eec250 Phil Davis
346 4e322e2c Phil Davis
	foreach ($serverbridge_interface as $iface => $ifacename) {
347 f4eec250 Phil Davis
		$list[$iface] = htmlspecialchars($ifacename);
348 4e322e2c Phil Davis
	}
349 f4eec250 Phil Davis
350
	return($list);
351
}
352
353 3c11bd3c Matthew Grooms
function openvpn_create_key() {
354
355 a2ba5b6c Viktor G
	$fp = popen("/usr/local/sbin/openvpn --genkey secret /dev/stdout 2>/dev/null", "r");
356 ef00af3c Phil Davis
	if (!$fp) {
357 3c11bd3c Matthew Grooms
		return false;
358 ef00af3c Phil Davis
	}
359 3c11bd3c Matthew Grooms
360
	$rslt = stream_get_contents($fp);
361
	pclose($fp);
362
363
	return $rslt;
364
}
365 d799787e Matthew Grooms
366 8411b218 Matthew Grooms
function openvpn_create_dhparams($bits) {
367 34bc1324 Matthew Grooms
368 2ec95f1f Renato Botelho
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
369 ef00af3c Phil Davis
	if (!$fp) {
370 34bc1324 Matthew Grooms
		return false;
371 ef00af3c Phil Davis
	}
372 34bc1324 Matthew Grooms
373
	$rslt = stream_get_contents($fp);
374
	pclose($fp);
375
376
	return $rslt;
377
}
378
379 d799787e Matthew Grooms
function openvpn_vpnid_used($vpnid) {
380 8be2d6d3 Ermal Luçi
	global $config;
381
382 ef00af3c Phil Davis
	if (is_array($config['openvpn']['openvpn-server'])) {
383
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
384
			if ($vpnid == $settings['vpnid']) {
385 d799787e Matthew Grooms
				return true;
386 ef00af3c Phil Davis
			}
387
		}
388
	}
389 d799787e Matthew Grooms
390 ef00af3c Phil Davis
	if (is_array($config['openvpn']['openvpn-client'])) {
391
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
392
			if ($vpnid == $settings['vpnid']) {
393 d799787e Matthew Grooms
				return true;
394 ef00af3c Phil Davis
			}
395
		}
396
	}
397 04a6e900 Ermal Luçi
398 d799787e Matthew Grooms
	return false;
399
}
400
401
function openvpn_vpnid_next() {
402
403
	$vpnid = 1;
404 ef00af3c Phil Davis
	while (openvpn_vpnid_used($vpnid)) {
405 d799787e Matthew Grooms
		$vpnid++;
406 ef00af3c Phil Davis
	}
407 d799787e Matthew Grooms
408
	return $vpnid;
409
}
410
411 49b76122 Renato Botelho
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
412 f432e364 Matthew Grooms
	global $config;
413
414 65d0277d Renato Botelho
	$ovpn_settings = array();
415 49b76122 Renato Botelho
	if (is_array($config['openvpn']['openvpn-server'])) {
416 65d0277d Renato Botelho
		$ovpn_settings = $config['openvpn']['openvpn-server'];
417 49b76122 Renato Botelho
	}
418
	if (is_array($config['openvpn']['openvpn-client'])) {
419 65d0277d Renato Botelho
		$ovpn_settings = array_merge($ovpn_settings,
420
		    $config['openvpn']['openvpn-client']);
421
	}
422 49b76122 Renato Botelho
423 65d0277d Renato Botelho
	foreach ($ovpn_settings as $settings) {
424
		if (isset($settings['disable'])) {
425
			continue;
426
		}
427 49b76122 Renato Botelho
428 65d0277d Renato Botelho
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
429
			continue;
430
		}
431
432 f69e098f Renato Botelho
		/* (TCP|UDP)(4|6) does not conflict unless interface is any */
433
		if (($interface != "any" && $settings['interface'] != "any") &&
434
		    (strlen($prot) == 4) &&
435
		    (strlen($settings['protocol']) == 4) &&
436
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
437
		    substr($prot,3,1) != substr($settings['protocol'],3,1)) {
438
			continue;
439
		}
440
441 65d0277d Renato Botelho
		if ($port == $settings['local_port'] &&
442 f69e098f Renato Botelho
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
443 65d0277d Renato Botelho
		    ($interface == $settings['interface'] ||
444
		    $interface == "any" || $settings['interface'] == "any")) {
445
			return $settings['vpnid'];
446 49b76122 Renato Botelho
		}
447
	}
448 f432e364 Matthew Grooms
449
	return 0;
450
}
451
452 49b76122 Renato Botelho
function openvpn_port_next($prot, $interface = "wan") {
453 f432e364 Matthew Grooms
454
	$port = 1194;
455 ef00af3c Phil Davis
	while (openvpn_port_used($prot, $interface, $port)) {
456 49b76122 Renato Botelho
		$port++;
457 ef00af3c Phil Davis
	}
458
	while (openvpn_port_used($prot, "any", $port)) {
459 f432e364 Matthew Grooms
		$port++;
460 ef00af3c Phil Davis
	}
461 f432e364 Matthew Grooms
462
	return $port;
463
}
464
465 d799787e Matthew Grooms
function openvpn_get_cipherlist() {
466
467
	$ciphers = array();
468 4fd1130f jim-p
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
469 d799787e Matthew Grooms
	$cipher_lines = explode("\n", trim($cipher_out));
470
	sort($cipher_lines);
471
	foreach ($cipher_lines as $line) {
472 4fd1130f jim-p
		$words = explode(' ', $line, 2);
473 d799787e Matthew Grooms
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
474 8be2d6d3 Ermal Luçi
	}
475 4aa02281 Carlos Eduardo Ramos
	$ciphers["none"] = gettext("None (No Encryption)");
476 d799787e Matthew Grooms
	return $ciphers;
477
}
478
479 f888c35a jim-p
function openvpn_get_curvelist() {
480 bc3e78ab jim-p
	global $cert_curve_compatible;
481 f888c35a jim-p
	$curves = array();
482
	$curves["none"] = gettext("Use Default");
483 bc3e78ab jim-p
	foreach ($cert_curve_compatible['OpenVPN'] as $curve) {
484
		$curves[$curve] = $curve;
485 f888c35a jim-p
	}
486
	return $curves;
487
}
488
489
function openvpn_validate_curve($curve) {
490
	$curves = openvpn_get_curvelist();
491
	return array_key_exists($curve, $curves);
492
}
493
494 f49ef559 jim-p
/* Obtain the list of digest algorithms supported by openssl and their alternate names */
495
function openvpn_get_openssldigestmappings() {
496
	$digests = array();
497 bd5d33d8 mschiegl
	$digest_out = shell_exec('/usr/bin/openssl list -digest-algorithms | /usr/bin/grep "=>"');
498 f49ef559 jim-p
	$digest_lines = explode("\n", trim($digest_out));
499
	sort($digest_lines);
500
	foreach ($digest_lines as $line) {
501
		$words = explode(' => ', $line, 2);
502
		$digests[$words[0]] = $words[1];
503
	}
504
	return $digests;
505
}
506 97d5b59b jim-p
507 f49ef559 jim-p
/* Obtain the list of digest algorithms supported by openvpn */
508
function openvpn_get_digestlist() {
509
	/* Grab the list from OpenSSL to check for duplicates or aliases */
510
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
511 97d5b59b jim-p
	$digests = array();
512
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
513
	$digest_lines = explode("\n", trim($digest_out));
514
	sort($digest_lines);
515
	foreach ($digest_lines as $line) {
516
		$words = explode(' ', $line);
517 f49ef559 jim-p
		/* Only add the entry if it is NOT also listed as being an alias/mapping by OpenSSL */
518
		if (!array_key_exists($words[0], $openssl_digest_mappings)) {
519
			$digests[$words[0]] = "{$words[0]} {$words[1]}";
520
		}
521 97d5b59b jim-p
	}
522
	$digests["none"] = gettext("None (No Authentication)");
523
	return $digests;
524
}
525
526 f49ef559 jim-p
/* Check to see if a digest name is an alias and if so, find the actual digest
527
 * algorithm instead. Useful for upgrade code that has to translate aliased
528
 * algorithms to their actual names.
529
 */
530
function openvpn_remap_digest($digest) {
531
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
532
	if (array_key_exists($digest, $openssl_digest_mappings)) {
533
		/* Some mappings point to other mappings, keep going until we find the actual digest algorithm */
534
		if (array_key_exists($openssl_digest_mappings[$digest], $openssl_digest_mappings)) {
535
			return openvpn_remap_digest($openssl_digest_mappings[$digest]);
536
		} else {
537
			return $openssl_digest_mappings[$digest];
538
		}
539
	}
540
	return $digest;
541
}
542
543 8698f918 Vito Piserchia
function openvpn_get_keydirlist() {
544
	$keydirs = array(
545 d2011b0a jim-p
		'default'  => gettext('Use default direction'),
546 8698f918 Vito Piserchia
		'0' => gettext('Direction 0'),
547
		'1' => gettext('Direction 1'),
548 f08369ec Vito Piserchia
		'2' => gettext('Both directions'),
549 8698f918 Vito Piserchia
	);
550
	return $keydirs;
551
}
552
553 582c58ae jim-p
function openvpn_get_engines() {
554 e8c516a0 Phil Davis
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
555 2ec95f1f Renato Botelho
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
556 349bf358 jim-p
	$openssl_engine_output = implode("\n", $openssl_engine_output);
557
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
558
	$openssl_engine_output = explode("\n", $openssl_engine_output);
559
560 582c58ae jim-p
	foreach ($openssl_engine_output as $oeo) {
561 349bf358 jim-p
		$keep = true;
562
		$details = explode("|", $oeo);
563
		$engine = array_shift($details);
564 582c58ae jim-p
		$linematch = array();
565 349bf358 jim-p
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
566
		foreach ($details as $dt) {
567 ef00af3c Phil Davis
			if (strpos($dt, "unavailable") !== FALSE) {
568 349bf358 jim-p
				$keep = false;
569 ef00af3c Phil Davis
			}
570
			if (strpos($dt, "available") !== FALSE) {
571 349bf358 jim-p
				continue;
572 ef00af3c Phil Davis
			}
573
			if (strpos($dt, "[") !== FALSE) {
574 349bf358 jim-p
				$ciphers = trim($dt, "[]");
575 ef00af3c Phil Davis
			}
576 349bf358 jim-p
		}
577 ef00af3c Phil Davis
		if (!empty($ciphers)) {
578 349bf358 jim-p
			$ciphers = " - " . $ciphers;
579 ef00af3c Phil Davis
		}
580
		if (strlen($ciphers) > 60) {
581 349bf358 jim-p
			$ciphers = substr($ciphers, 0, 60) . " ... ";
582 ef00af3c Phil Davis
		}
583
		if ($keep) {
584 349bf358 jim-p
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
585 ef00af3c Phil Davis
		}
586 582c58ae jim-p
	}
587
	return $openssl_engines;
588
}
589
590 7618a842 jim-p
function openvpn_get_buffer_values() {
591
	$sendbuf_max = get_single_sysctl('net.inet.tcp.sendbuf_max');
592
	$recvbuf_max = get_single_sysctl('net.inet.tcp.recvbuf_max');
593
	/* Usually these two are equal, but if they are not, take whichever one is lower. */
594
	$buffer_max = ($sendbuf_max <= $recvbuf_max) ? $sendbuf_max : $recvbuf_max;
595
	$buffer_values = array('' => gettext('Default'));
596
	for ($bs = 32; $bs >= 1; $bs /= 2) {
597
		$buffer_values[$buffer_max/$bs] = format_bytes($buffer_max/$bs);
598
	}
599
	return $buffer_values;
600
}
601
602 582c58ae jim-p
function openvpn_validate_engine($engine) {
603
	$engines = openvpn_get_engines();
604
	return array_key_exists($engine, $engines);
605
}
606
607 d799787e Matthew Grooms
function openvpn_validate_host($value, $name) {
608
	$value = trim($value);
609 ef00af3c Phil Davis
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
610 4aa02281 Carlos Eduardo Ramos
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
611 ef00af3c Phil Davis
	}
612 d799787e Matthew Grooms
	return false;
613 8dc3ef67 Scott Ullrich
}
614
615 39fed386 jim-p
function openvpn_validate_port($value, $name, $first_port = 0) {
616 8dc3ef67 Scott Ullrich
	$value = trim($value);
617 39fed386 jim-p
	if (!is_numeric($first_port)) {
618
		$first_port = 0;
619
	}
620
	if (empty($value) || !is_numeric($value) || $value < $first_port || ($value > 65535)) {
621 9f2a58b5 Renato Botelho do Couto
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from %s to 65535."), $name, $first_port);
622 ef00af3c Phil Davis
	}
623 b398bbca Martin Fuchs
	return false;
624 8dc3ef67 Scott Ullrich
}
625
626 4b8d710c Viktor G
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4", $alias = false) {
627 a28d40cb jim-p
	$value = trim($value);
628
	$error = false;
629 ef00af3c Phil Davis
	if (empty($value)) {
630 a28d40cb jim-p
		return false;
631 ef00af3c Phil Davis
	}
632 a28d40cb jim-p
	$networks = explode(',', $value);
633
634 ef00af3c Phil Davis
	if (!$multiple && (count($networks) > 1)) {
635 e8c516a0 Phil Davis
		return sprintf(gettext("The field '%1\$s' must contain a single valid %2\$s CIDR range."), $name, $ipproto);
636 ef00af3c Phil Davis
	}
637 a28d40cb jim-p
638
	foreach ($networks as $network) {
639 ef00af3c Phil Davis
		if ($ipproto == "ipv4") {
640 4b8d710c Viktor G
			$error = !openvpn_validate_cidr_ipv4($network, $alias);
641 ef00af3c Phil Davis
		} else {
642 4b8d710c Viktor G
			$error = !openvpn_validate_cidr_ipv6($network, $alias);
643 ef00af3c Phil Davis
		}
644
		if ($error) {
645 a28d40cb jim-p
			break;
646 ef00af3c Phil Davis
		}
647 a28d40cb jim-p
	}
648
649 ef00af3c Phil Davis
	if ($error) {
650 e8c516a0 Phil Davis
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) separated by commas."), $name, $ipproto);
651 ef00af3c Phil Davis
	} else {
652 a28d40cb jim-p
		return false;
653 ef00af3c Phil Davis
	}
654 a28d40cb jim-p
}
655
656 4b8d710c Viktor G
function openvpn_validate_cidr_ipv4($value, $alias = false) {
657 8dc3ef67 Scott Ullrich
	$value = trim($value);
658
	if (!empty($value)) {
659 4b8d710c Viktor G
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
660
			foreach (alias_to_subnets_recursive($value) as $net) {
661
				if (!is_subnetv4($net)) {
662
					return false;
663
				}
664
			}
665
			return true;
666
		} else {
667
			if (!is_subnetv4($value)) {
668
				return false;
669
			}
670 ef00af3c Phil Davis
		}
671 8dc3ef67 Scott Ullrich
	}
672 a28d40cb jim-p
	return true;
673
}
674
675 4b8d710c Viktor G
function openvpn_validate_cidr_ipv6($value, $alias = false) {
676 a28d40cb jim-p
	$value = trim($value);
677
	if (!empty($value)) {
678 4b8d710c Viktor G
		if ($alias && is_alias($value) && in_array(alias_get_type($value), array('host', 'network'))) {
679
			foreach (alias_to_subnets_recursive($value) as $net) {
680
				if (!is_subnetv6($net)) {
681
					return false;
682
				}
683
			}
684
			return true;
685
		} else {
686
			list($ipv6, $prefix) = explode('/', $value);
687
			if (empty($prefix)) {
688
				$prefix = "128";
689
			}
690
			if (!is_subnetv6($ipv6 . '/' . $prefix)) {
691
				return false;
692
			}
693 ef00af3c Phil Davis
		}
694 4b8d710c Viktor G
	}
695
	return true;
696
}
697
698
function openvpn_validate_tunnel_network($value, $ipproto) {
699
	$value = trim($value);
700
	if (!empty($value)) {
701
		if (is_alias($value) && (alias_get_type($value) == 'network')) {
702
			$net = alias_to_subnets_recursive($value);
703
			if ((!is_subnetv4($net[0]) && ($ipproto == 'ipv4')) ||
704
			    (!is_subnetv6($net[0]) && ($ipproto == 'ipv6')) ||
705
			    (count($net) > 1)) {
706
				return false;
707
			}
708
			return true;
709
		} else {
710
			if ((!is_subnetv4($value) && ($ipproto == 'ipv4')) ||
711
			    (!is_subnetv6($value) && ($ipproto == 'ipv6'))) { 
712
				return false;
713
			}
714 ef00af3c Phil Davis
		}
715 a28d40cb jim-p
	}
716
	return true;
717 afb07cf1 Scott Ullrich
}
718
719 4b8d710c Viktor G
function openvpn_gen_tunnel_network($tunnel_network) {
720
	if (is_alias($tunnel_network)) {
721
		$net = alias_to_subnets_recursive($tunnel_network);
722
		$pair = $net[0];
723
	} else {
724
		$pair = $tunnel_network;
725
	}
726
	return explode('/', trim($pair));
727
}
728
729 d799787e Matthew Grooms
function openvpn_add_dhcpopts(& $settings, & $conf) {
730 afb07cf1 Scott Ullrich
731 ef00af3c Phil Davis
	if (!empty($settings['dns_domain'])) {
732 d799787e Matthew Grooms
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
733 ef00af3c Phil Davis
	}
734 add2e3f7 Scott Ullrich
735 ef00af3c Phil Davis
	if (!empty($settings['dns_server1'])) {
736 6a638752 jim-p
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
737
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
738 ef00af3c Phil Davis
	}
739
	if (!empty($settings['dns_server2'])) {
740 6a638752 jim-p
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
741
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
742 ef00af3c Phil Davis
	}
743
	if (!empty($settings['dns_server3'])) {
744 6a638752 jim-p
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
745
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
746 ef00af3c Phil Davis
	}
747
	if (!empty($settings['dns_server4'])) {
748 6a638752 jim-p
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
749
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
750 ef00af3c Phil Davis
	}
751 f9927473 Scott Ullrich
752 01c2735c jim-p
	if (!empty($settings['push_blockoutsidedns'])) {
753
		$conf .= "push \"block-outside-dns\"\n";
754
	}
755 ef00af3c Phil Davis
	if (!empty($settings['push_register_dns'])) {
756 c38764dc Dmitriy K.
		$conf .= "push \"register-dns\"\n";
757 ef00af3c Phil Davis
	}
758 c38764dc Dmitriy K.
759 ef00af3c Phil Davis
	if (!empty($settings['ntp_server1'])) {
760 c7f70dbc Chris Buechler
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
761 ef00af3c Phil Davis
	}
762
	if (!empty($settings['ntp_server2'])) {
763 c7f70dbc Chris Buechler
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
764 ef00af3c Phil Davis
	}
765 f9927473 Scott Ullrich
766 d799787e Matthew Grooms
	if ($settings['netbios_enable']) {
767 add2e3f7 Scott Ullrich
768 ef00af3c Phil Davis
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
769 095a95ae Matthew Grooms
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
770 ef00af3c Phil Davis
		}
771
		if (!empty($settings['dhcp_nbtscope'])) {
772 d799787e Matthew Grooms
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
773 ef00af3c Phil Davis
		}
774 8dc3ef67 Scott Ullrich
775 ef00af3c Phil Davis
		if (!empty($settings['wins_server1'])) {
776 d799787e Matthew Grooms
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
777 ef00af3c Phil Davis
		}
778
		if (!empty($settings['wins_server2'])) {
779 d799787e Matthew Grooms
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
780 ef00af3c Phil Davis
		}
781 add2e3f7 Scott Ullrich
782 ef00af3c Phil Davis
		if (!empty($settings['nbdd_server1'])) {
783 d799787e Matthew Grooms
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
784 ef00af3c Phil Davis
		}
785 d799787e Matthew Grooms
	}
786 8dc3ef67 Scott Ullrich
787 ef00af3c Phil Davis
	if ($settings['gwredir']) {
788 d799787e Matthew Grooms
		$conf .= "push \"redirect-gateway def1\"\n";
789 ef00af3c Phil Davis
	}
790 37f05e97 jim-p
	if ($settings['gwredir6']) {
791
		$conf .= "push \"redirect-gateway ipv6\"\n";
792
	}
793 d799787e Matthew Grooms
}
794 24012690 Scott Ullrich
795 d799787e Matthew Grooms
function openvpn_add_custom(& $settings, & $conf) {
796 add2e3f7 Scott Ullrich
797 d799787e Matthew Grooms
	if ($settings['custom_options']) {
798 8dc3ef67 Scott Ullrich
799 d799787e Matthew Grooms
		$options = explode(';', $settings['custom_options']);
800
801
		if (is_array($options)) {
802 ef00af3c Phil Davis
			foreach ($options as $option) {
803 d799787e Matthew Grooms
				$conf .= "$option\n";
804 ef00af3c Phil Davis
			}
805
		} else {
806 d799787e Matthew Grooms
			$conf .= "{$settings['custom_options']}\n";
807 ef00af3c Phil Davis
		}
808 add2e3f7 Scott Ullrich
	}
809
}
810
811 691fbf14 Ermal Lu?i
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
812 d799787e Matthew Grooms
	global $g;
813 add2e3f7 Scott Ullrich
814 348c2af1 jim-p
	$fpath = "{$g['openvpn_base']}/{$mode_id}/{$directive}";
815 a8f538a8 jim-p
	openvpn_create_dirs();
816 d799787e Matthew Grooms
	file_put_contents($fpath, base64_decode($data));
817 f9ac3784 Ermal Lu?i
	//chown($fpath, 'nobody');
818
	//chgrp($fpath, 'nobody');
819 6f27412f Ermal Lu?i
	@chmod($fpath, 0600);
820 d799787e Matthew Grooms
821 691fbf14 Ermal Lu?i
	$conf .= "{$directive} {$fpath} {$opt}\n";
822 4eefa6e8 Scott Ullrich
}
823
824 fc05822b jim-p
function openvpn_reconfigure($mode, $settings) {
825 99d7e8c1 jim-p
	global $g, $config, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
826 afb07cf1 Scott Ullrich
827 ef00af3c Phil Davis
	if (empty($settings)) {
828 93a0a028 Ermal Luçi
		return;
829 ef00af3c Phil Davis
	}
830
	if (isset($settings['disable'])) {
831 4eefa6e8 Scott Ullrich
		return;
832 ef00af3c Phil Davis
	}
833 a8f538a8 jim-p
	openvpn_create_dirs();
834 fdd725f0 Ermal Luçi
	/*
835 d799787e Matthew Grooms
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
836
	 * we use a vpnid number which is allocated for a particular client
837
	 * or server configuration. ( see openvpn_vpnid_next() )
838 fdd725f0 Ermal Luçi
	 */
839 8874c692 Ermal Luçi
840 d799787e Matthew Grooms
	$vpnid = $settings['vpnid'];
841
	$mode_id = $mode.$vpnid;
842 8874c692 Ermal Luçi
843 ef00af3c Phil Davis
	if (isset($settings['dev_mode'])) {
844 4936ff53 jim-p
		$tunname = "{$settings['dev_mode']}{$vpnid}";
845 ef00af3c Phil Davis
	} else {
846
		/* defaults to tun */
847 bd7ca506 jim-p
		$tunname = "tun{$vpnid}";
848 4936ff53 jim-p
		$settings['dev_mode'] = "tun";
849 691fbf14 Ermal Lu?i
	}
850
851 ef00af3c Phil Davis
	if ($mode == "server") {
852 bd7ca506 jim-p
		$devname = "ovpns{$vpnid}";
853 ef00af3c Phil Davis
	} else {
854 bd7ca506 jim-p
		$devname = "ovpnc{$vpnid}";
855 ef00af3c Phil Davis
	}
856 8874c692 Ermal Luçi
857 bd7ca506 jim-p
	/* is our device already configured */
858 4a97aa34 Ermal
	if (!does_interface_exist($devname)) {
859 dc408939 Matthew Grooms
860 bd7ca506 jim-p
		/* create the tap device if required */
861 ef00af3c Phil Davis
		if (!file_exists("/dev/{$tunname}")) {
862 873c1701 Renato Botelho
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
863 ef00af3c Phil Davis
		}
864 98872d89 Ermal Luçi
865 bd7ca506 jim-p
		/* rename the device */
866 873c1701 Renato Botelho
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
867 095a95ae Matthew Grooms
868 4ab1ffa0 Renato Botelho
		/* add the device to the openvpn group and make sure it's UP*/
869
		mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " group openvpn up");
870 da4f91a9 Renato Botelho
871 bd1a6267 Renato Botelho
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
872
		$grouptmp = link_interface_to_group($ifname);
873 ef00af3c Phil Davis
		if (!empty($grouptmp)) {
874 bd1a6267 Renato Botelho
			array_walk($grouptmp, 'interface_group_add_member');
875 ef00af3c Phil Davis
		}
876 bd1a6267 Renato Botelho
		unset($grouptmp, $ifname);
877 dc408939 Matthew Grooms
	}
878 d799787e Matthew Grooms
879 dc408939 Matthew Grooms
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
880 6714bbdc jim-p
	$proto = strtolower($settings['protocol']);
881 ef00af3c Phil Davis
	if (substr($settings['protocol'], 0, 3) == "TCP") {
882 6714bbdc jim-p
			$proto = "{$proto}-{$mode}";
883 ef00af3c Phil Davis
	}
884 4936ff53 jim-p
	$dev_mode = $settings['dev_mode'];
885 189edaf3 jim-p
	$fbcipher = $settings['data_ciphers_fallback'];
886 97d5b59b jim-p
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
887
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
888 d799787e Matthew Grooms
889 47c48e28 smos
	$interface = get_failover_interface($settings['interface']);
890 e27bc6cf Phil Davis
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
891 d7a0c22a bcyrill
	$ipaddr = $settings['ipaddr'];
892 d799787e Matthew Grooms
893 67b0902f pierrepomes
	// If a specific ip address (VIP) is requested, use it.
894
	// Otherwise, if a specific interface is requested, use it
895 ef00af3c Phil Davis
	// If "any" interface was selected, local directive will be omitted.
896 97ffc513 Seth Mos
	if (is_ipaddrv4($ipaddr)) {
897 4de8f7ba Phil Davis
		$iface_ip = $ipaddr;
898 af0257cf Renato Botelho
	} elseif (!empty($interface) && strcmp($interface, "any")) {
899 51e7132e Renato Botelho
		$iface_ip=get_interface_ip($interface);
900 47c48e28 smos
	}
901 e27bc6cf Phil Davis
	if (is_ipaddrv6($ipaddr)) {
902 6c07db48 Phil Davis
		$iface_ipv6 = $ipaddr;
903 af0257cf Renato Botelho
	} elseif (!empty($interface) && strcmp($interface, "any")) {
904 1b59af4f Viktor G
		/* get correct interface name for 6RD/6to4 interfaces
905
		 * see https://redmine.pfsense.org/issues/11674 */
906
		if (is_stf_interface($settings['interface'])) {
907
			$iface_ipv6=get_interface_ipv6($settings['interface']);
908
		} else {
909
			$iface_ipv6=get_interface_ipv6($interface);
910
		}
911 3d06e8f0 pierrepomes
	}
912 d799787e Matthew Grooms
913 b1e8e675 Dmitriy K.
	$conf = "dev {$devname}\n";
914 5b3c0116 Dmitriy K.
	if (isset($settings['verbosity_level'])) {
915 b1e8e675 Dmitriy K.
		$conf .= "verb {$settings['verbosity_level']}\n";
916 5b3c0116 Dmitriy K.
	}
917 42bb1bee Renato Botelho
918 4936ff53 jim-p
	$conf .= "dev-type {$settings['dev_mode']}\n";
919 bd7ca506 jim-p
	$conf .= "dev-node /dev/{$tunname}\n";
920 3c11bd3c Matthew Grooms
	$conf .= "writepid {$pfile}\n";
921
	$conf .= "#user nobody\n";
922
	$conf .= "#group nobody\n";
923 d1014c18 Chris Buechler
	$conf .= "script-security 3\n";
924 3c11bd3c Matthew Grooms
	$conf .= "daemon\n";
925 3bfecc81 Renato Botelho do Couto
926
	if (!empty($settings['ping_method']) &&
927
	    $settings['ping_method'] == 'ping') {
928
		$conf .= "ping {$settings['ping_seconds']}\n";
929
930
		if (!empty($settings['ping_push'])) {
931
			$conf .= "push \"ping {$settings['ping_seconds']}\"\n";
932
		}
933
934
		$action = str_replace("_", "-", $settings['ping_action']);
935
		$conf .= "{$action} {$settings['ping_action_seconds']}\n";
936
937
		if (!empty($settings['ping_action_push'])) {
938
			$conf .= "push \"{$action} " .
939
			    "{$settings['ping_action_seconds']}\"\n";
940
		}
941
	} else {
942
		$conf .= "keepalive " .
943
		    ($settings['keepalive_interval']
944
			?: $openvpn_default_keepalive_interval) . " " .
945
		    ($settings['keepalive_timeout']
946
			?: $openvpn_default_keepalive_timeout) . "\n";
947
	}
948
949 3c11bd3c Matthew Grooms
	$conf .= "ping-timer-rem\n";
950
	$conf .= "persist-tun\n";
951
	$conf .= "persist-key\n";
952
	$conf .= "proto {$proto}\n";
953 97d5b59b jim-p
	$conf .= "auth {$digest}\n";
954 ee712bbb Viktor G
	if ($settings['dns_add']) {
955
		$conf .= "up /usr/local/sbin/ovpn-dnslinkup\n";
956
	} else {
957
		$conf .= "up /usr/local/sbin/ovpn-linkup\n";
958
	}
959 8d964cea Ermal
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
960 1492e02c Ermal
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
961 ef00af3c Phil Davis
		switch ($settings['mode']) {
962 a1b9105b jim-p
			case 'server_user':
963
			case 'server_tls_user':
964 d1d8383c Viktor G
			case 'server_tls':
965 a1b9105b jim-p
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
966
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
967
				break;
968
		}
969 1492e02c Ermal
	}
970 4f4de341 Lorenz Schori
	if ($settings['dev_mode'] === 'tun' && isset($config['unbound']['enable']) && isset($config['unbound']['regovpnclients'])) {
971 3b88d971 Viktor G
		if (($settings['mode'] == 'server_tls') || ($settings['mode'] == 'server_tls_user') ||
972
		    (($settings['mode'] == 'server_user') && ($settings['username_as_common_name'] == 'enabled'))) {
973
			$domain = !empty($settings['dns_domain']) ? $settings['dns_domain'] : $config['system']['domain'];
974
			if (is_domain($domain)) {
975
				$conf .= "learn-address \"/usr/local/sbin/openvpn.learn-address.sh $domain\"\n";
976
			}
977 0cc17a06 Lorenz Schori
		}
978
	}
979 3c11bd3c Matthew Grooms
980 5280fd8d Renato Botelho
	/*
981
	 * When binding specific address, wait cases where interface is in
982
	 * tentative state otherwise it will fail
983
	 */
984
	$wait_tentative = false;
985
986 6714bbdc jim-p
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
987 ca366676 jim-p
	switch ($settings['protocol']) {
988
		case 'UDP':
989
		case 'TCP':
990
			$conf .= "multihome\n";
991
			break;
992
		case 'UDP4':
993
		case 'TCP4':
994
			if (is_ipaddrv4($iface_ip)) {
995
				$conf .= "local {$iface_ip}\n";
996
			}
997
			if ($settings['interface'] == "any") {
998
				$conf .= "multihome\n";
999
			}
1000
			break;
1001
		case 'UDP6':
1002
		case 'TCP6':
1003
			if (is_ipaddrv6($iface_ipv6)) {
1004
				$conf .= "local {$iface_ipv6}\n";
1005 5280fd8d Renato Botelho
				$wait_tentative = true;
1006 ca366676 jim-p
			}
1007
			if ($settings['interface'] == "any") {
1008
				$conf .= "multihome\n";
1009
			}
1010
			break;
1011
		default:
1012 97ffc513 Seth Mos
	}
1013 d799787e Matthew Grooms
1014 ef00af3c Phil Davis
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
1015 582c58ae jim-p
		$conf .= "engine {$settings['engine']}\n";
1016 ef00af3c Phil Davis
	}
1017 582c58ae jim-p
1018 67b0902f pierrepomes
	// server specific settings
1019 8dc3ef67 Scott Ullrich
	if ($mode == 'server') {
1020 d799787e Matthew Grooms
1021 4b8d710c Viktor G
		list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1022
		list($ipv6, $prefix) = openvpn_gen_tunnel_network($settings['tunnel_networkv6']);
1023 5dc6c910 jim-p
		$mask = gen_subnet_mask($cidr);
1024 8dc3ef67 Scott Ullrich
1025 3c11bd3c Matthew Grooms
		// configure tls modes
1026 ef00af3c Phil Davis
		switch ($settings['mode']) {
1027 3c11bd3c Matthew Grooms
			case 'p2p_tls':
1028
			case 'server_tls':
1029 e62e2f8b Ermal Lu?i
			case 'server_user':
1030 3c11bd3c Matthew Grooms
			case 'server_tls_user':
1031 d799787e Matthew Grooms
				$conf .= "tls-server\n";
1032 3c11bd3c Matthew Grooms
				break;
1033 8dc3ef67 Scott Ullrich
		}
1034 d799787e Matthew Grooms
1035 3c11bd3c Matthew Grooms
		// configure p2p/server modes
1036 ef00af3c Phil Davis
		switch ($settings['mode']) {
1037 6c9cf466 jim-p
			case 'p2p_tls':
1038 5dc6c910 jim-p
				// If the CIDR is less than a /30, OpenVPN will complain if you try to
1039
				//  use the server directive. It works for a single client without it.
1040
				//  See ticket #1417
1041 4af6affa jim-p
				if ((!empty($ip) && !empty($mask)) ||
1042
				    (!empty($ipv6) && !empty($prefix))) {
1043
					$add_ccd = false;
1044
					if (is_ipaddr($ip) && ($cidr < 30)) {
1045
						$add_ccd = true;
1046
						$conf .= "server {$ip} {$mask}\n";
1047
					}
1048 ef00af3c Phil Davis
					if (is_ipaddr($ipv6)) {
1049 4af6affa jim-p
						$add_ccd = true;
1050 a0e3ee98 jim-p
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
1051 ef00af3c Phil Davis
					}
1052 4af6affa jim-p
					if ($add_ccd) {
1053
						$conf .= "client-config-dir {$g['openvpn_base']}/server{$vpnid}/csc\n";
1054
					}
1055 5dc6c910 jim-p
				}
1056 3c11bd3c Matthew Grooms
			case 'p2p_shared_key':
1057 74a556a3 jim-p
				if (!empty($ip) && !empty($mask)) {
1058 30c8a290 Renato Botelho
					list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1059 ef00af3c Phil Davis
					if ($settings['dev_mode'] == 'tun') {
1060 459e9333 jim-p
						$conf .= "ifconfig {$ip1} {$ip2}\n";
1061 ef00af3c Phil Davis
					} else {
1062 459e9333 jim-p
						$conf .= "ifconfig {$ip1} {$mask}\n";
1063 ef00af3c Phil Davis
					}
1064 1ab6bdb5 jim-p
				}
1065 a0e3ee98 jim-p
				if (!empty($ipv6) && !empty($prefix)) {
1066 91c44185 jim-p
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1067 ef00af3c Phil Davis
					if ($settings['dev_mode'] == 'tun') {
1068 a0e3ee98 jim-p
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$ipv6_2}\n";
1069 ef00af3c Phil Davis
					} else {
1070 f0a0bae5 Viktor G
						$conf .= "ifconfig-ipv6 {$ipv6_1}/{$prefix} {$ipv6_2}\n";
1071 ef00af3c Phil Davis
					}
1072 a0e3ee98 jim-p
				}
1073 3c11bd3c Matthew Grooms
				break;
1074
			case 'server_tls':
1075
			case 'server_user':
1076
			case 'server_tls_user':
1077 4af6affa jim-p
				if ((!empty($ip) && !empty($mask)) ||
1078
				    (!empty($ipv6) && !empty($prefix))) {
1079
					if (is_ipaddr($ip)) {
1080
						$conf .= "server {$ip} {$mask}\n";
1081
					}
1082 ef00af3c Phil Davis
					if (is_ipaddr($ipv6)) {
1083 1ab6bdb5 jim-p
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
1084 ef00af3c Phil Davis
					}
1085 348c2af1 jim-p
					$conf .= "client-config-dir {$g['openvpn_base']}/server{$vpnid}/csc\n";
1086 1ab6bdb5 jim-p
				} else {
1087
					if ($settings['serverbridge_dhcp']) {
1088
						if ((!empty($settings['serverbridge_interface'])) && (strcmp($settings['serverbridge_interface'], "none"))) {
1089
							$biface_ip=get_interface_ip($settings['serverbridge_interface']);
1090
							$biface_sm=gen_subnet_mask(get_interface_subnet($settings['serverbridge_interface']));
1091
							if (is_ipaddrv4($biface_ip) && is_ipaddrv4($settings['serverbridge_dhcp_start']) && is_ipaddrv4($settings['serverbridge_dhcp_end'])) {
1092
								$conf .= "server-bridge {$biface_ip} {$biface_sm} {$settings['serverbridge_dhcp_start']} {$settings['serverbridge_dhcp_end']}\n";
1093 348c2af1 jim-p
								$conf .= "client-config-dir {$g['openvpn_base']}/server{$vpnid}/csc\n";
1094 1ab6bdb5 jim-p
							} else {
1095
								$conf .= "mode server\n";
1096
							}
1097 498f7e20 jim-p
							if (!empty($settings['serverbridge_routegateway']) && is_ipaddrv4($biface_ip)) {
1098
								$conf .= "push \"route-gateway {$biface_ip}\"\n";
1099
							}
1100
							/* OpenVPN doesn't support this yet, clients do not recognize the option fully.
1101
							$biface_ip6=get_interface_ipv6($settings['serverbridge_interface']);
1102
							if (!empty($settings['serverbridge_routegateway']) && is_ipaddrv6($biface_ip6)) {
1103
								$conf .= "push \"route-ipv6-gateway {$biface_ip6}\"\n";
1104
							}
1105
							*/
1106 1ab6bdb5 jim-p
						} else {
1107
							$conf .= "mode server\n";
1108
						}
1109
					}
1110
				}
1111 3c11bd3c Matthew Grooms
				break;
1112 8dc3ef67 Scott Ullrich
		}
1113
1114 3c11bd3c Matthew Grooms
		// configure user auth modes
1115 ef00af3c Phil Davis
		switch ($settings['mode']) {
1116 3c11bd3c Matthew Grooms
			case 'server_user':
1117 4cfd15a9 jim-p
				$conf .= "verify-client-cert none\n";
1118 3c11bd3c Matthew Grooms
			case 'server_tls_user':
1119 9eced774 jim-p
				/* username-as-common-name is not compatible with server-bridge */
1120 e5c4f2a7 jim-p
				if ((stristr($conf, "server-bridge") === false) &&
1121
				    ($settings['username_as_common_name'] != 'disabled')) {
1122 9eced774 jim-p
					$conf .= "username-as-common-name\n";
1123 ef00af3c Phil Davis
				}
1124 8a47c190 Ermal Lu?i
				if (!empty($settings['authmode'])) {
1125 5e28dad4 Ermal
					$strictusercn = "false";
1126 ef00af3c Phil Davis
					if ($settings['strictusercn']) {
1127 5e28dad4 Ermal
						$strictusercn = "true";
1128 ef00af3c Phil Davis
					}
1129 30064732 Viktor G
					$conf .= openvpn_authscript_string($settings['authmode'], $strictusercn, $mode_id, $settings['local_port']);
1130 e8a58de4 Ermal Lu?i
				}
1131 3c11bd3c Matthew Grooms
				break;
1132 8dc3ef67 Scott Ullrich
		}
1133 ef00af3c Phil Davis
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
1134 41936acc jim-p
			$settings['cert_depth'] = 1;
1135 ef00af3c Phil Davis
		}
1136 98963f27 jim-p
		if (is_numeric($settings['cert_depth'])) {
1137 ef00af3c Phil Davis
			if (($mode == 'client') && empty($settings['certref'])) {
1138 2da48592 jim-p
				$cert = "";
1139 ef00af3c Phil Davis
			} else {
1140 2da48592 jim-p
				$cert = lookup_cert($settings['certref']);
1141
				/* XXX: Seems not used at all! */
1142
				$servercn = urlencode(cert_get_cn($cert['crt']));
1143
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
1144
			}
1145 98963f27 jim-p
		}
1146 8dc3ef67 Scott Ullrich
1147 63084885 Matthew Grooms
		// The local port to listen on
1148 d799787e Matthew Grooms
		$conf .= "lport {$settings['local_port']}\n";
1149 c0cf27aa Scott Ullrich
1150 63084885 Matthew Grooms
		// The management port to listen on
1151 71ca2cb2 Ermal
		// Use unix socket to overcome the problem on any type of server
1152 348c2af1 jim-p
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1153 71ca2cb2 Ermal
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
1154 63084885 Matthew Grooms
1155 ef00af3c Phil Davis
		if ($settings['maxclients']) {
1156 d799787e Matthew Grooms
			$conf .= "max-clients {$settings['maxclients']}\n";
1157 ef00af3c Phil Davis
		}
1158 d799787e Matthew Grooms
1159 37f05e97 jim-p
		// Can we push routes, and should we?
1160
		if ($settings['local_network'] && !$settings['gwredir']) {
1161 a28d40cb jim-p
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1162 3c11bd3c Matthew Grooms
		}
1163 37f05e97 jim-p
		if ($settings['local_networkv6'] && !$settings['gwredir6']) {
1164 a28d40cb jim-p
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1165 787de45a Seth Mos
		}
1166 3c11bd3c Matthew Grooms
1167 ef00af3c Phil Davis
		switch ($settings['mode']) {
1168 3c11bd3c Matthew Grooms
			case 'server_tls':
1169
			case 'server_user':
1170
			case 'server_tls_user':
1171 5d8cd81a jim-p
				// Configure client dhcp options
1172 3c11bd3c Matthew Grooms
				openvpn_add_dhcpopts($settings, $conf);
1173 ef00af3c Phil Davis
				if ($settings['client2client']) {
1174 5d8cd81a jim-p
					$conf .= "client-to-client\n";
1175 ef00af3c Phil Davis
				}
1176 3c11bd3c Matthew Grooms
				break;
1177
		}
1178 4e42da90 Renato Botelho do Couto
		if ($settings['mode'] != 'p2p_shared_key' &&
1179
		    isset($settings['duplicate_cn'])) {
1180 bca35cff jim-p
			$conf .= "duplicate-cn\n";
1181 ef00af3c Phil Davis
		}
1182 810adc14 Viktor G
		if (($settings['mode'] != 'p2p_shared_key') &&
1183
		    isset($settings['remote_cert_tls'])) {
1184
			$conf .= "remote-cert-tls client\n";
1185
		}
1186 d799787e Matthew Grooms
	}
1187
1188 3c11bd3c Matthew Grooms
	// client specific settings
1189 d799787e Matthew Grooms
1190 3c11bd3c Matthew Grooms
	if ($mode == 'client') {
1191 d799787e Matthew Grooms
1192 3c11bd3c Matthew Grooms
		// configure p2p mode
1193 ef00af3c Phil Davis
		switch ($settings['mode']) {
1194 3c11bd3c Matthew Grooms
			case 'p2p_tls':
1195
				$conf .= "tls-client\n";
1196
			case 'shared_key':
1197
				$conf .= "client\n";
1198
				break;
1199
		}
1200 d799787e Matthew Grooms
1201 e3924384 jim-p
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1202 42bb1bee Renato Botelho
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1203 e3924384 jim-p
		//  ensure a random source port.
1204 b42ccf15 jim-p
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1205 e3924384 jim-p
			$conf .= "nobind\n";
1206 ef00af3c Phil Davis
		} elseif ($settings['local_port']) {
1207 e3924384 jim-p
			$conf .= "lport {$settings['local_port']}\n";
1208 ef00af3c Phil Davis
		} else {
1209 e3924384 jim-p
			$conf .= "lport 0\n";
1210 ef00af3c Phil Davis
		}
1211 5708241f jim-p
1212 4b887ef4 jim-p
		// Use unix socket to overcome the problem on any type of server
1213 348c2af1 jim-p
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1214 48a458d2 pierrepomes
1215 3c11bd3c Matthew Grooms
		// The remote server
1216 bd1291d0 Viktor Gurov
		$remoteproto = strtolower($settings['protocol']);
1217 6ac20ad3 Viktor G
		if (substr($remoteproto, 0, 3) == "tcp") {
1218
			$remoteproto .= "-{$mode}";
1219
		}
1220 bd1291d0 Viktor Gurov
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']} {$remoteproto}\n";
1221 3c11bd3c Matthew Grooms
1222 ef00af3c Phil Davis
		if (!empty($settings['use_shaper'])) {
1223 d799787e Matthew Grooms
			$conf .= "shaper {$settings['use_shaper']}\n";
1224 ef00af3c Phil Davis
		}
1225 ee506044 Scott Ullrich
1226 d799787e Matthew Grooms
		if (!empty($settings['tunnel_network'])) {
1227 4b8d710c Viktor G
			list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1228 30c8a290 Renato Botelho
			$mask = gen_subnet_mask($cidr);
1229 636918c9 Chris Buechler
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1230 ef00af3c Phil Davis
			if ($settings['dev_mode'] == 'tun') {
1231 459e9333 jim-p
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1232 ef00af3c Phil Davis
			} else {
1233 459e9333 jim-p
				$conf .= "ifconfig {$ip2} {$mask}\n";
1234 ef00af3c Phil Davis
			}
1235 8dc3ef67 Scott Ullrich
		}
1236 d799787e Matthew Grooms
1237 a0e3ee98 jim-p
		if (!empty($settings['tunnel_networkv6'])) {
1238 966cdb43 jim-p
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1239 91c44185 jim-p
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1240 ef00af3c Phil Davis
			if ($settings['dev_mode'] == 'tun') {
1241 a0e3ee98 jim-p
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1242 ef00af3c Phil Davis
			} else {
1243 f0a0bae5 Viktor G
				$conf .= "ifconfig-ipv6 {$ipv6_1}/{$prefix} {$ipv6_2}\n";
1244 ef00af3c Phil Davis
			}
1245 a0e3ee98 jim-p
		}
1246
1247 a6d55c23 Chris Buechler
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
1248 348c2af1 jim-p
			$up_file = "{$g['openvpn_base']}/{$mode_id}/up";
1249 5f242576 PiBa-NL
			$conf .= "auth-user-pass {$up_file}\n";
1250 a69a9182 jim-p
			if (!$settings['auth-retry-none']) {
1251
				$conf .= "auth-retry nointeract\n";
1252
			}
1253 7304c023 Phil Davis
			if ($settings['auth_user']) {
1254 4de8f7ba Phil Davis
				$userpass = "{$settings['auth_user']}\n";
1255 7304c023 Phil Davis
			} else {
1256
				$userpass = "";
1257
			}
1258
			if ($settings['auth_pass']) {
1259 4de8f7ba Phil Davis
				$userpass .= "{$settings['auth_pass']}\n";
1260 7304c023 Phil Davis
			}
1261
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
1262
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
1263
				$userpass .= "\n";
1264
			}
1265 5f242576 PiBa-NL
			file_put_contents($up_file, $userpass);
1266
		}
1267 42bb1bee Renato Botelho
1268 762a24a3 Ermal Lu?i
		if ($settings['proxy_addr']) {
1269
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1270
			if ($settings['proxy_authtype'] != "none") {
1271 348c2af1 jim-p
				$conf .= " {$g['openvpn_base']}/{$mode_id}/proxy_auth {$settings['proxy_authtype']}";
1272 762a24a3 Ermal Lu?i
				$proxypas = "{$settings['proxy_user']}\n";
1273
				$proxypas .= "{$settings['proxy_passwd']}\n";
1274 348c2af1 jim-p
				file_put_contents("{$g['openvpn_base']}/{$mode_id}/proxy_auth", $proxypas);
1275 762a24a3 Ermal Lu?i
			}
1276
			$conf .= " \n";
1277
		}
1278 810adc14 Viktor G
1279
		if (($settings['mode'] != 'shared_key') &&
1280
		    isset($settings['remote_cert_tls'])) {
1281
			$conf .= "remote-cert-tls server\n";
1282
		}
1283 8dc3ef67 Scott Ullrich
	}
1284
1285 17c98ba9 jim-p
	// Add a remote network route if set, and only for p2p modes.
1286 4b8d710c Viktor G
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4", true) === FALSE)) {
1287 a28d40cb jim-p
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1288 8dc3ef67 Scott Ullrich
	}
1289 4856df9b jim-p
	// Add a remote network route if set, and only for p2p modes.
1290 4b8d710c Viktor G
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6", true) === FALSE)) {
1291 a28d40cb jim-p
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1292 4856df9b jim-p
	}
1293 afb07cf1 Scott Ullrich
1294 d799787e Matthew Grooms
	// Write the settings for the keys
1295 ef00af3c Phil Davis
	switch ($settings['mode']) {
1296 3c11bd3c Matthew Grooms
		case 'p2p_shared_key':
1297
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
1298
			break;
1299
		case 'p2p_tls':
1300
		case 'server_tls':
1301
		case 'server_tls_user':
1302 e62e2f8b Ermal Lu?i
		case 'server_user':
1303 348c2af1 jim-p
			// ca_chain_array() expects parameter to be passed by reference.
1304 179377b0 robjarsen
			// avoid passing the whole settings array, as param names or
1305
			// types might change in future releases.
1306
			$param = array('caref' => $settings['caref']);
1307 348c2af1 jim-p
			$cas = ca_chain_array($param);
1308
			$capath = "{$g['openvpn_base']}/{$mode_id}/ca";
1309
			/* Cleanup old CA/CRL references */
1310 28cb1a27 jim-p
			@unlink_if_exists("{$capath}/*.0");
1311
			@unlink_if_exists("{$capath}/*.r*");
1312 348c2af1 jim-p
			/* Find the CRL listed in the settings */
1313
			if (!empty($settings['crlref'])) {
1314
				$crl = lookup_crl($settings['crlref']);
1315
				crl_update($crl);
1316
			}
1317
			/* For each CA in the chain, setup the CApath */
1318
			foreach ($cas as $ca) {
1319
				ca_setup_capath($ca, $capath, $crl);
1320
			}
1321
			$conf .= "capath {$capath}\n";
1322
			unset($cas, $param);
1323 2da48592 jim-p
1324
			if (!empty($settings['certref'])) {
1325
				$cert = lookup_cert($settings['certref']);
1326
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
1327
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
1328
			}
1329 ef00af3c Phil Davis
			if ($mode == 'server') {
1330 f888c35a jim-p
				if (is_numeric($settings['dh_length'])) {
1331 c6668aba Phil Davis
					if (!in_array($settings['dh_length'], array_keys($openvpn_dh_lengths))) {
1332 f888c35a jim-p
						/* The user selected a DH parameter length that does not have a corresponding file. */
1333
						log_error(gettext("Failed to construct OpenVPN server configuration. The selected DH Parameter length cannot be used."));
1334
						return;
1335
					}
1336
					$dh_file = "{$g['etc_path']}/dh-parameters.{$settings['dh_length']}";
1337
				} else {
1338
					$dh_file = $settings['dh_length'];
1339
				}
1340
				$conf .= "dh {$dh_file}\n";
1341
				if (!empty($settings['ecdh_curve']) && ($settings['ecdh_curve'] != "none") && openvpn_validate_curve($settings['ecdh_curve'])) {
1342
					$conf .= "ecdh-curve {$settings['ecdh_curve']}\n";
1343
				}
1344 ef00af3c Phil Davis
			}
1345 db746ce2 Ermal Lu?i
			if ($settings['tls']) {
1346 c854afcc jim-p
				if ($settings['tls_type'] == "crypt") {
1347
					$tls_directive = "tls-crypt";
1348
					$tlsopt = "";
1349 ef00af3c Phil Davis
				} else {
1350 c854afcc jim-p
					$tls_directive = "tls-auth";
1351
					if ($mode == "server") {
1352 8698f918 Vito Piserchia
						switch($settings['tlsauth_keydir']){
1353
							case '1':
1354
								$tlsopt = 1;
1355
								break;
1356
							case '2':
1357
								$tlsopt = '';
1358
								break;
1359
							default:
1360
								$tlsopt = 0;
1361
								break;
1362
						}
1363 c854afcc jim-p
					} else {
1364 8698f918 Vito Piserchia
						switch($settings['tlsauth_keydir']){
1365
							case '0':
1366
								$tlsopt = 0;
1367
								break;
1368
							case '2':
1369
								$tlsopt = '';
1370
								break;
1371
							default:
1372
								$tlsopt = 1;
1373
								break;
1374
						}
1375 c854afcc jim-p
					}
1376 ef00af3c Phil Davis
				}
1377 c854afcc jim-p
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, $tls_directive, $tlsopt);
1378 db746ce2 Ermal Lu?i
			}
1379 3c11bd3c Matthew Grooms
			break;
1380 8dc3ef67 Scott Ullrich
	}
1381
1382 924eeefb jim-p
	/* Data encryption cipher support.
1383
	 * If it is not set, assume enabled since that is OpenVPN's default.
1384
	 * Note that diabling this is now deprecated and will be removed in a future version of OpenVPN */
1385
	if ($settings['ncp_enable'] == "disabled") {
1386
		$conf .= "ncp-disable\n";
1387
		$conf .= "cipher {$fbcipher}\n";
1388
	} else {
1389
		$conf .= "data-ciphers " . str_replace(',', ':', openvpn_build_data_cipher_list($settings['data_ciphers'], $fbcipher)) . "\n";
1390
		$conf .= "data-ciphers-fallback {$fbcipher}\n";
1391
	}
1392
1393 56e031a7 jim-p
	if (!empty($settings['allow_compression'])) {
1394
		$conf .= "allow-compression {$settings['allow_compression']}\n";
1395
	}
1396
1397 a4b36246 jim-p
	$compression = "";
1398
	switch ($settings['compression']) {
1399 38922574 jim-p
		case 'none':
1400
			$settings['compression'] = '';
1401 a4b36246 jim-p
		case 'lz4':
1402
		case 'lz4-v2':
1403
		case 'lzo':
1404
		case 'stub':
1405 38922574 jim-p
		case 'stub-v2':
1406 a4b36246 jim-p
			$compression .= "compress {$settings['compression']}";
1407
			break;
1408
		case 'noadapt':
1409
			$compression .= "comp-noadapt";
1410
			break;
1411
		case 'adaptive':
1412
		case 'yes':
1413
		case 'no':
1414
			$compression .= "comp-lzo {$settings['compression']}";
1415
			break;
1416
		default:
1417
			/* Add nothing to the configuration */
1418
			break;
1419
	}
1420
1421 16fe7982 jim-p
	if (($settings['allow_compression'] != 'no') &&
1422
	    !empty($compression)) {
1423 a4b36246 jim-p
		$conf .= "{$compression}\n";
1424
		if ($settings['compression_push']) {
1425
			$conf .= "push \"{$compression}\"\n";
1426 9446ee68 jim-p
		}
1427 ef00af3c Phil Davis
	}
1428 d799787e Matthew Grooms
1429 ef00af3c Phil Davis
	if ($settings['passtos']) {
1430 d799787e Matthew Grooms
		$conf .= "passtos\n";
1431 ef00af3c Phil Davis
	}
1432 d799787e Matthew Grooms
1433 919a0f4a jim-p
	if ($mode == 'client') {
1434 30640018 Chris Buechler
		$conf .= "resolv-retry infinite\n";
1435 ef00af3c Phil Davis
	}
1436 d799787e Matthew Grooms
1437
	if ($settings['dynamic_ip']) {
1438
		$conf .= "persist-remote-ip\n";
1439
		$conf .= "float\n";
1440 8dc3ef67 Scott Ullrich
	}
1441 afb07cf1 Scott Ullrich
1442 ef378560 jim-p
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1443 4742e635 Chris Buechler
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1444 63646f4d jim-p
		if (empty($settings['topology'])) {
1445
			$settings['topology'] = "subnet";
1446
		}
1447
		$conf .= "topology {$settings['topology']}\n";
1448 ee55ce7d jim-p
	}
1449
1450 b9e9903d Dmitriy K.
	// New client features
1451
	if ($mode == "client") {
1452
		// Dont add/remove routes checkbox
1453
		if ($settings['route_no_exec']) {
1454
			$conf .= "route-noexec\n";
1455
		}
1456
	}
1457
1458 2df5d9ee jim-p
	/* UDP Fast I/O. Only compatible with UDP and also not compatible with OpenVPN's "shaper" directive. */
1459
	if ($settings['udp_fast_io']
1460
	    && (strtolower(substr($settings['protocol'], 0, 3)) == "udp")
1461
	    && (empty($settings['use_shaper']))) {
1462
		$conf .= "fast-io\n";
1463
	}
1464
1465 0a70f90a jim-p
	/* Exit Notify.
1466
	 * Only compatible with UDP and specific combinations of
1467
	 * modes and settings, including:
1468
	 * if type is server AND
1469
	 *	mode is not shared key AND
1470
	 *		tunnel network CIDR mask < 30 AND
1471
	 *		tunnel network is not blank
1472
	 * if type is client AND
1473
	 *	mode is not shared key AND
1474
	 *		tunnel network is blank OR
1475
	 *		tunnel network CIDR mask < 30
1476
	 */
1477
	list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1478
	if ((!empty($settings['exit_notify']) &&
1479 7591a72a jim-p
	    is_numericint($settings['exit_notify']) &&
1480 0a70f90a jim-p
	    (strtolower(substr($settings['protocol'], 0, 3)) == "udp")) &&
1481
	    ((($mode == "server") && (($settings['mode'] != 'p2p_shared_key') && (($cidr < 30) && !empty($ip)))) ||
1482
	    (($mode == "client") && (($settings['mode'] != 'p2p_shared_key') && (($cidr < 30) || empty($ip)))))) {
1483 7591a72a jim-p
		$conf .= "explicit-exit-notify {$settings['exit_notify']}\n";
1484
	}
1485
1486 0a70f90a jim-p
	/* Inactive Seconds
1487
	 * Has similar restrictions to Exit Notify (above) but only for server mode.
1488
	 */
1489
	if (!empty($settings['inactive_seconds']) &&
1490
	    !(($mode == "server") && (($settings['mode'] == 'p2p_shared_key') || (($cidr >= 30) || empty($ip))))) {
1491
		$conf .= "inactive {$settings['inactive_seconds']}\n";
1492
	}
1493
1494 7618a842 jim-p
	/* Send and Receive Buffer Settings */
1495
	if (is_numericint($settings['sndrcvbuf'])
1496
	    && ($settings['sndrcvbuf'] > 0)
1497
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1498
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1499
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1500
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1501
	}
1502
1503 d799787e Matthew Grooms
	openvpn_add_custom($settings, $conf);
1504
1505 969574b6 Viktor G
	/* add nopull option after custom options, see https://redmine.pfsense.org/issues/11448 */
1506
	if (($mode == "client") && $settings['route_no_pull']) {
1507
		// Dont pull routes checkbox
1508
		$conf .= "route-nopull\n";
1509
	}
1510
1511 a8f538a8 jim-p
	openvpn_create_dirs();
1512 348c2af1 jim-p
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1513 d799787e Matthew Grooms
	file_put_contents($fpath, $conf);
1514 938fc5b0 Ermal
	unset($conf);
1515 348c2af1 jim-p
	$fpath = "{$g['openvpn_base']}/{$mode_id}/interface";
1516 be00850b Phil Davis
	file_put_contents($fpath, $interface);
1517 f9ac3784 Ermal Lu?i
	//chown($fpath, 'nobody');
1518
	//chgrp($fpath, 'nobody');
1519 348c2af1 jim-p
	@chmod("{$g['openvpn_base']}/{$mode_id}/config.ovpn", 0600);
1520
	@chmod("{$g['openvpn_base']}/{$mode_id}/interface", 0600);
1521
	@chmod("{$g['openvpn_base']}/{$mode_id}/key", 0600);
1522
	@chmod("{$g['openvpn_base']}/{$mode_id}/tls-auth", 0600);
1523
	@chmod("{$g['openvpn_base']}/{$mode_id}/conf", 0600);
1524 5280fd8d Renato Botelho
1525
	if ($wait_tentative) {
1526
		interface_wait_tentative($interface);
1527
	}
1528 d799787e Matthew Grooms
}
1529
1530 fc05822b jim-p
function openvpn_restart($mode, $settings) {
1531 d799787e Matthew Grooms
	global $g, $config;
1532
1533
	$vpnid = $settings['vpnid'];
1534
	$mode_id = $mode.$vpnid;
1535 ce983754 PiBa-NL
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1536 a96a7151 Viktor G
	openvpn_clean_rules($mode, $vpnid);
1537 8845e137 PiBa-NL
	openvpn_reconfigure($mode, $settings);
1538 76369bfc Matthew Grooms
	/* kill the process if running */
1539 705c8ec9 Matthew Grooms
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1540 76369bfc Matthew Grooms
	if (file_exists($pfile)) {
1541 705c8ec9 Matthew Grooms
1542 76369bfc Matthew Grooms
		/* read the pid file */
1543
		$pid = rtrim(file_get_contents($pfile));
1544
		unlink($pfile);
1545 8845e137 PiBa-NL
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1546 705c8ec9 Matthew Grooms
1547 76369bfc Matthew Grooms
		/* send a term signal to the process */
1548
		posix_kill($pid, SIGTERM);
1549
1550 93ead355 Chris Buechler
		/* wait until the process exits, or timeout and kill it */
1551
		$i = 0;
1552 ef00af3c Phil Davis
		while (posix_kill($pid, 0)) {
1553 76369bfc Matthew Grooms
			usleep(250000);
1554 93ead355 Chris Buechler
			if ($i > 10) {
1555 e8c516a0 Phil Davis
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1556 93ead355 Chris Buechler
				posix_kill($pid, SIGKILL);
1557 02a2bffa Chris Buechler
				usleep(500000);
1558 93ead355 Chris Buechler
			}
1559
			$i++;
1560
		}
1561 76369bfc Matthew Grooms
	}
1562 d799787e Matthew Grooms
1563 ef00af3c Phil Davis
	if (isset($settings['disable'])) {
1564 1c334904 Viktor G
		openvpn_delete($mode, $settings);
1565 ce983754 PiBa-NL
		unlock($lockhandle);
1566 d799787e Matthew Grooms
		return;
1567 ef00af3c Phil Davis
	}
1568 d799787e Matthew Grooms
1569 f003f8db jim-p
	/* Do not start an instance if we are not CARP master on this vip! */
1570 70d79766 Viktor G
	if (strstr($settings['interface'], "_vip")) {
1571 6ae26227 Viktor G
	       	$carpstatus = get_carp_bind_status($settings['interface']);
1572
		/* Do not start an instance if vip aliased to BACKUP CARP
1573
		 * see https://redmine.pfsense.org/issues/11793 */ 
1574 866cc787 Steve Beaver
		if (in_array($carpstatus, array('BACKUP', 'INIT'))) {
1575 70d79766 Viktor G
			unlock($lockhandle);
1576
			return;
1577 6ae26227 Viktor G
		} 
1578 ef00af3c Phil Davis
	}
1579 42bb1bee Renato Botelho
1580
	/* Check if client is bound to a gateway group */
1581 43a9b03d PiBa-NL
	$a_groups = return_gateway_groups_array(true);
1582 330ecea1 Shahid Sheikh
	if (is_array($a_groups[$settings['interface']])) {
1583 ef00af3c Phil Davis
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1584 ddf99718 Phil Davis
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1585 ce983754 PiBa-NL
			unlock($lockhandle);
1586 330ecea1 Shahid Sheikh
			return;
1587 ef00af3c Phil Davis
		}
1588 330ecea1 Shahid Sheikh
	}
1589 9ea0cb90 jim-p
1590 705c8ec9 Matthew Grooms
	/* start the new process */
1591 348c2af1 jim-p
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1592 91c44185 jim-p
	openvpn_clear_route($mode, $settings);
1593 8845e137 PiBa-NL
	$res = mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1594
	if ($res == 0) {
1595
		$i = 0;
1596
		$pid = "--";
1597
		while ($i < 3000) {
1598 a1b39e94 PiBa-NL
			if (isvalidpid($pfile)) {
1599 8845e137 PiBa-NL
				$pid = rtrim(file_get_contents($pfile));
1600 a1b39e94 PiBa-NL
				break;
1601 8845e137 PiBa-NL
			}
1602
			usleep(1000);
1603
			$i++;
1604
		}
1605
		syslog(LOG_INFO, "OpenVPN PID written: {$pid}");
1606
	} else {
1607
		syslog(LOG_ERR, "OpenVPN failed to start");
1608
	}
1609 ef00af3c Phil Davis
	if (!platform_booting()) {
1610 847cd48d Ermal
		send_event("filter reload");
1611 ef00af3c Phil Davis
	}
1612 ce983754 PiBa-NL
	unlock($lockhandle);
1613 afb07cf1 Scott Ullrich
}
1614
1615 9272a448 Renato Botelho
function openvpn_delete($mode, $settings) {
1616 d799787e Matthew Grooms
	global $g, $config;
1617
1618
	$vpnid = $settings['vpnid'];
1619
	$mode_id = $mode.$vpnid;
1620
1621 ef00af3c Phil Davis
	if ($mode == "server") {
1622 095a95ae Matthew Grooms
		$devname = "ovpns{$vpnid}";
1623 ef00af3c Phil Davis
	} else {
1624 095a95ae Matthew Grooms
		$devname = "ovpnc{$vpnid}";
1625 ef00af3c Phil Davis
	}
1626 dc408939 Matthew Grooms
1627 76369bfc Matthew Grooms
	/* kill the process if running */
1628 dc408939 Matthew Grooms
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1629 76369bfc Matthew Grooms
	if (file_exists($pfile)) {
1630 dc408939 Matthew Grooms
1631 76369bfc Matthew Grooms
		/* read the pid file */
1632
		$pid = trim(file_get_contents($pfile));
1633
		unlink($pfile);
1634
1635
		/* send a term signal to the process */
1636
		posix_kill($pid, SIGTERM);
1637
	}
1638 705c8ec9 Matthew Grooms
1639 3b1642ff Renato Botelho
	/* destroy the device */
1640
	pfSense_interface_destroy($devname);
1641 dc408939 Matthew Grooms
1642 7d813139 batnas
	/* Invalidate cache */
1643
	get_interface_arr(true);
1644
1645 dc408939 Matthew Grooms
	/* remove the configuration files */
1646 93830bec Viktor G
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*/*");
1647
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*");
1648 a96a7151 Viktor G
	openvpn_clean_rules($mode, $vpnid);
1649 d799787e Matthew Grooms
}
1650 afb07cf1 Scott Ullrich
1651 dc408939 Matthew Grooms
function openvpn_resync_csc(& $settings) {
1652 154b0f80 jim-p
	global $g, $config, $openvpn_tls_server_modes;
1653 a1cab2c7 Ermal
	if (isset($settings['disable'])) {
1654 4e5e7540 jim-p
		openvpn_delete_csc($settings);
1655 c876662c Scott Ullrich
		return;
1656
	}
1657 a8f538a8 jim-p
	openvpn_create_dirs();
1658 d799787e Matthew Grooms
1659 154b0f80 jim-p
	if (empty($settings['server_list'])) {
1660
		$csc_server_list = array();
1661
	} else {
1662
		$csc_server_list = explode(",", $settings['server_list']);
1663
	}
1664
1665 8dc3ef67 Scott Ullrich
	$conf = '';
1666 ef00af3c Phil Davis
	if ($settings['block']) {
1667 d799787e Matthew Grooms
		$conf .= "disable\n";
1668 ef00af3c Phil Davis
	}
1669 d799787e Matthew Grooms
1670 ef00af3c Phil Davis
	if ($settings['push_reset']) {
1671 d799787e Matthew Grooms
		$conf .= "push-reset\n";
1672 ef00af3c Phil Davis
	}
1673 d799787e Matthew Grooms
1674 8d44d56a Viktor G
	if ($settings['remove_route']) {
1675
		$conf .= "push-remove route\n";
1676
	}
1677
1678 5c427ce7 jim-p
	if ($settings['local_network']) {
1679
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1680
	}
1681
	if ($settings['local_networkv6']) {
1682
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1683
	}
1684
1685
	// Add a remote network iroute if set
1686 4b8d710c Viktor G
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4", true) === FALSE) {
1687 5c427ce7 jim-p
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1688
	}
1689
	// Add a remote network iroute if set
1690 4b8d710c Viktor G
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6", true) === FALSE) {
1691 5c427ce7 jim-p
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1692
	}
1693
1694 d799787e Matthew Grooms
	openvpn_add_dhcpopts($settings, $conf);
1695 8dc3ef67 Scott Ullrich
1696 d799787e Matthew Grooms
	openvpn_add_custom($settings, $conf);
1697 154b0f80 jim-p
	/* Loop through servers, find which ones can use this CSC */
1698
	if (is_array($config['openvpn']['openvpn-server'])) {
1699
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1700
			if (isset($serversettings['disable'])) {
1701
				continue;
1702
			}
1703
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1704
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1705 348c2af1 jim-p
					$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1706 154b0f80 jim-p
					$csc_conf = $conf;
1707
1708 cd8f2f2b jim-p
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1709 4b8d710c Viktor G
						list($ip, $mask) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1710 154b0f80 jim-p
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1711
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1712
						} else {
1713
							/* Because this is being pushed, the order from the client's point of view. */
1714 493e6807 stilez
							$baselong = gen_subnetv4($ip, $mask);
1715
							$serverip = ip_after($baselong, 1);
1716
							$clientip = ip_after($baselong, 2);
1717 154b0f80 jim-p
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1718
						}
1719
					}
1720 b6dd335e jim-p
1721
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1722 4b8d710c Viktor G
						list($ipv6, $prefix) = openvpn_gen_tunnel_network($serversettings['tunnel_networkv6']);
1723 b6dd335e jim-p
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1724
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1725
					}
1726
1727 154b0f80 jim-p
					file_put_contents($csc_path, $csc_conf);
1728
					chown($csc_path, 'nobody');
1729
					chgrp($csc_path, 'nobody');
1730
				}
1731
			}
1732
		}
1733
	}
1734 d799787e Matthew Grooms
}
1735 8dc3ef67 Scott Ullrich
1736 1f954318 jim-p
function openvpn_resync_csc_all() {
1737
	global $config;
1738
	if (is_array($config['openvpn']['openvpn-csc'])) {
1739
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1740
			openvpn_resync_csc($settings);
1741
		}
1742
	}
1743
}
1744
1745 dc408939 Matthew Grooms
function openvpn_delete_csc(& $settings) {
1746 154b0f80 jim-p
	global $g, $config, $openvpn_tls_server_modes;
1747
	if (empty($settings['server_list'])) {
1748
		$csc_server_list = array();
1749
	} else {
1750
		$csc_server_list = explode(",", $settings['server_list']);
1751
	}
1752 3c2e5528 Scott Ullrich
1753 154b0f80 jim-p
	/* Loop through servers, find which ones used 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
					unlink_if_exists($csc_path);
1763
				}
1764
			}
1765
		}
1766
	}
1767 267ab13f Ermal Luçi
}
1768 afb07cf1 Scott Ullrich
1769 24012690 Scott Ullrich
// Resync the configuration and restart the VPN
1770 fc05822b jim-p
function openvpn_resync($mode, $settings) {
1771 dc408939 Matthew Grooms
	openvpn_restart($mode, $settings);
1772 afb07cf1 Scott Ullrich
}
1773
1774 add2e3f7 Scott Ullrich
// Resync and restart all VPNs
1775 c7f60193 Ermal
function openvpn_resync_all($interface = "") {
1776 d799787e Matthew Grooms
	global $g, $config;
1777 267ab13f Ermal Luçi
1778 a8f538a8 jim-p
	openvpn_create_dirs();
1779 3cb54b54 Matthew Grooms
1780 ef00af3c Phil Davis
	if (!is_array($config['openvpn'])) {
1781 34bc1324 Matthew Grooms
		$config['openvpn'] = array();
1782 ef00af3c Phil Davis
	}
1783 34bc1324 Matthew Grooms
1784 ef00af3c Phil Davis
	if ($interface <> "") {
1785 e8c516a0 Phil Davis
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1786 ef00af3c Phil Davis
	} else {
1787 e8c516a0 Phil Davis
		log_error(gettext("Resyncing OpenVPN instances."));
1788 ef00af3c Phil Davis
	}
1789 34bc1324 Matthew Grooms
1790 7071aab3 James Webb
	// Check if OpenVPN clients and servers require a resync.
1791 f7335af3 Renato Botelho do Couto
	foreach (array("server", "client") as $type) {
1792
		if (!is_array($config['openvpn']["openvpn-{$type}"])) {
1793
			continue;
1794 c7f60193 Ermal
		}
1795 f7335af3 Renato Botelho do Couto
		foreach ($config['openvpn']["openvpn-{$type}"] as & $settings) {
1796 348c2af1 jim-p
			$fpath = "{$g['openvpn_base']}/{$type}{$settings['vpnid']}/interface";
1797 7071aab3 James Webb
			$gw_group_change = FALSE;
1798 f7335af3 Renato Botelho do Couto
			$ip_change = ($interface === "") ||
1799
			    ($interface === $settings['interface']);
1800
1801 15f8062b James Webb
			if (!$ip_change && file_exists($fpath)) {
1802 f7335af3 Renato Botelho do Couto
				$gw_group_change =
1803
				    (trim(file_get_contents($fpath), " \t\n") !=
1804
				    get_failover_interface(
1805
					$settings['interface']));
1806 7071aab3 James Webb
			}
1807 f7335af3 Renato Botelho do Couto
1808 15f8062b James Webb
			if ($ip_change || $gw_group_change) {
1809 f7335af3 Renato Botelho do Couto
				openvpn_resync($type, $settings);
1810 ef00af3c Phil Davis
			}
1811 c7f60193 Ermal
		}
1812
	}
1813 afb07cf1 Scott Ullrich
1814 1f954318 jim-p
	openvpn_resync_csc_all();
1815 afb07cf1 Scott Ullrich
1816 3f0e9812 Viktor G
	/* configure OpenVPN-parent QinQ interfaces after creating OpenVPN interfaces
1817
	 * see https://redmine.pfsense.org/issues/11662 */
1818
	if (platform_booting()) {
1819
		interfaces_qinq_configure(true);
1820
	}
1821 5b237745 Scott Ullrich
}
1822 702a4702 Scott Ullrich
1823 99cc103b Phil Davis
// Resync and restart all VPNs using a gateway group.
1824
function openvpn_resync_gwgroup($gwgroupname = "") {
1825
	global $g, $config;
1826
1827
	if ($gwgroupname <> "") {
1828
		if (is_array($config['openvpn']['openvpn-server'])) {
1829
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1830
				if ($gwgroupname == $settings['interface']) {
1831 e8c516a0 Phil Davis
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1832 99cc103b Phil Davis
					openvpn_resync('server', $settings);
1833
				}
1834
			}
1835
		}
1836
1837
		if (is_array($config['openvpn']['openvpn-client'])) {
1838
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1839
				if ($gwgroupname == $settings['interface']) {
1840 e8c516a0 Phil Davis
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1841 99cc103b Phil Davis
					openvpn_resync('client', $settings);
1842
				}
1843
			}
1844
		}
1845
1846
		// Note: no need to resysnc Client Specific (csc) here, as changes to the OpenVPN real interface do not effect these.
1847
1848 ef00af3c Phil Davis
	} else {
1849 e8c516a0 Phil Davis
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1850 ef00af3c Phil Davis
	}
1851 99cc103b Phil Davis
}
1852
1853 453d9c96 jim-p
function openvpn_get_active_servers($type="multipoint") {
1854 71ca2cb2 Ermal
	global $config, $g;
1855
1856 53663f57 jim-p
	$servers = array();
1857
	if (is_array($config['openvpn']['openvpn-server'])) {
1858
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1859 ef00af3c Phil Davis
			if (empty($settings) || isset($settings['disable'])) {
1860 6b2dcac5 Ermal
				continue;
1861 ef00af3c Phil Davis
			}
1862 6b2dcac5 Ermal
1863 53663f57 jim-p
			$prot = $settings['protocol'];
1864
			$port = $settings['local_port'];
1865 42bb1bee Renato Botelho
1866 53663f57 jim-p
			$server = array();
1867 95305736 jim-p
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1868 41be629f jim-p
			$server['mode'] = $settings['mode'];
1869 ef00af3c Phil Davis
			if ($settings['description']) {
1870 53663f57 jim-p
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1871 ef00af3c Phil Davis
			} else {
1872 53663f57 jim-p
				$server['name'] = "Server {$prot}:{$port}";
1873 ef00af3c Phil Davis
			}
1874 53663f57 jim-p
			$server['conns'] = array();
1875 2eaa97b9 jim-p
			$server['vpnid'] = $settings['vpnid'];
1876
			$server['mgmt'] = "server{$server['vpnid']}";
1877 348c2af1 jim-p
			$socket = "unix://{$g['openvpn_base']}/{$server['mgmt']}/sock";
1878 4b8d710c Viktor G
			list($tn, $sm) = openvpn_gen_tunnel_network($settings['tunnel_network']);
1879 453d9c96 jim-p
1880 6c3bfb73 jim-p
			if ((($server['mode'] == "p2p_shared_key") ||
1881
			    (($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network'])) ||
1882
			    ($sm >= 30)) &&
1883
			    ($type == "p2p")) {
1884 95305736 jim-p
				$servers[] = openvpn_get_client_status($server, $socket);
1885 6c3bfb73 jim-p
			} elseif (($server['mode'] != "p2p_shared_key") &&
1886
			    !(($settings['dev_mode'] == 'tap') && empty($settings['tunnel_network'])) &&
1887
			    ($type == "multipoint") &&
1888
			    ($sm < 30)) {
1889 95305736 jim-p
				$servers[] = openvpn_get_server_status($server, $socket);
1890 ef00af3c Phil Davis
			}
1891 95305736 jim-p
		}
1892
	}
1893
	return $servers;
1894
}
1895 b0140675 Ermal
1896 95305736 jim-p
function openvpn_get_server_status($server, $socket) {
1897 247c417f Sjon Hortensius
	$errval = null;
1898
	$errstr = null;
1899 95305736 jim-p
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1900
	if ($fp) {
1901
		stream_set_timeout($fp, 1);
1902
1903
		/* send our status request */
1904
		fputs($fp, "status 2\n");
1905
1906
		/* recv all response lines */
1907
		while (!feof($fp)) {
1908
1909
			/* read the next line */
1910
			$line = fgets($fp, 1024);
1911
1912
			$info = stream_get_meta_data($fp);
1913 ef00af3c Phil Davis
			if ($info['timed_out']) {
1914 95305736 jim-p
				break;
1915 ef00af3c Phil Davis
			}
1916 95305736 jim-p
1917
			/* parse header list line */
1918 ef00af3c Phil Davis
			if (strstr($line, "HEADER")) {
1919 95305736 jim-p
				continue;
1920 ef00af3c Phil Davis
			}
1921 95305736 jim-p
1922
			/* parse end of output line */
1923 ef00af3c Phil Davis
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1924 95305736 jim-p
				break;
1925 ef00af3c Phil Davis
			}
1926 95305736 jim-p
1927
			/* parse client list line */
1928
			if (strstr($line, "CLIENT_LIST")) {
1929
				$list = explode(",", $line);
1930 53663f57 jim-p
				$conn = array();
1931 95305736 jim-p
				$conn['common_name'] = $list[1];
1932
				$conn['remote_host'] = $list[2];
1933
				$conn['virtual_addr'] = $list[3];
1934 6f17547a jim-p
				$conn['virtual_addr6'] = $list[4];
1935
				$conn['bytes_recv'] = $list[5];
1936
				$conn['bytes_sent'] = $list[6];
1937
				$conn['connect_time'] = $list[7];
1938
				$conn['connect_time_unix'] = $list[8];
1939
				$conn['user_name'] = $list[9];
1940
				$conn['client_id'] = $list[10];
1941
				$conn['peer_id'] = $list[11];
1942 f5736d98 Viktor G
				$conn['cipher'] = $list[12];
1943 53663f57 jim-p
				$server['conns'][] = $conn;
1944
			}
1945 ec970b50 jim-p
			/* parse routing table lines */
1946
			if (strstr($line, "ROUTING_TABLE")) {
1947
				$list = explode(",", $line);
1948
				$conn = array();
1949
				$conn['virtual_addr'] = $list[1];
1950
				$conn['common_name'] = $list[2];
1951
				$conn['remote_host'] = $list[3];
1952
				$conn['last_time'] = $list[4];
1953
				$server['routes'][] = $conn;
1954
			}
1955 53663f57 jim-p
		}
1956 95305736 jim-p
1957
		/* cleanup */
1958
		fclose($fp);
1959
	} else {
1960
		$conn = array();
1961
		$conn['common_name'] = "[error]";
1962 e8c516a0 Phil Davis
		$conn['remote_host'] = gettext("Unable to contact daemon");
1963
		$conn['virtual_addr'] = gettext("Service not running?");
1964 95305736 jim-p
		$conn['bytes_recv'] = 0;
1965
		$conn['bytes_sent'] = 0;
1966
		$conn['connect_time'] = 0;
1967
		$server['conns'][] = $conn;
1968 53663f57 jim-p
	}
1969 95305736 jim-p
	return $server;
1970 53663f57 jim-p
}
1971
1972
function openvpn_get_active_clients() {
1973 71ca2cb2 Ermal
	global $config, $g;
1974
1975 53663f57 jim-p
	$clients = array();
1976
	if (is_array($config['openvpn']['openvpn-client'])) {
1977
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1978 42bb1bee Renato Botelho
1979 ef00af3c Phil Davis
			if (empty($settings) || isset($settings['disable'])) {
1980 6b2dcac5 Ermal
				continue;
1981 ef00af3c Phil Davis
			}
1982 6b2dcac5 Ermal
1983 53663f57 jim-p
			$prot = $settings['protocol'];
1984 95305736 jim-p
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1985 42bb1bee Renato Botelho
1986 53663f57 jim-p
			$client = array();
1987
			$client['port'] = $settings['local_port'];
1988 ef00af3c Phil Davis
			if ($settings['description']) {
1989 95305736 jim-p
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1990 ef00af3c Phil Davis
			} else {
1991 95305736 jim-p
				$client['name'] = "Client {$prot}{$port}";
1992 ef00af3c Phil Davis
			}
1993 42bb1bee Renato Botelho
1994 2eaa97b9 jim-p
			$client['vpnid'] = $settings['vpnid'];
1995
			$client['mgmt'] = "client{$client['vpnid']}";
1996 348c2af1 jim-p
			$socket = "unix://{$g['openvpn_base']}/{$client['mgmt']}/sock";
1997 53663f57 jim-p
			$client['status']="down";
1998 95305736 jim-p
1999
			$clients[] = openvpn_get_client_status($client, $socket);
2000
		}
2001
	}
2002
	return $clients;
2003
}
2004
2005
function openvpn_get_client_status($client, $socket) {
2006 247c417f Sjon Hortensius
	$errval = null;
2007
	$errstr = null;
2008 95305736 jim-p
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
2009
	if ($fp) {
2010
		stream_set_timeout($fp, 1);
2011
		/* send our status request */
2012
		fputs($fp, "state 1\n");
2013
2014
		/* recv all response lines */
2015
		while (!feof($fp)) {
2016
			/* read the next line */
2017
			$line = fgets($fp, 1024);
2018
2019
			$info = stream_get_meta_data($fp);
2020 ef00af3c Phil Davis
			if ($info['timed_out']) {
2021 95305736 jim-p
				break;
2022 ef00af3c Phil Davis
			}
2023 95305736 jim-p
2024
			/* Get the client state */
2025 4de8f7ba Phil Davis
			if (strstr($line, "CONNECTED")) {
2026
				$client['status'] = "up";
2027 95305736 jim-p
				$list = explode(",", $line);
2028
2029 4de8f7ba Phil Davis
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
2030
				$client['virtual_addr'] = $list[3];
2031 95305736 jim-p
				$client['remote_host'] = $list[4];
2032 cbfd0754 jim-p
				$client['remote_port'] = $list[5];
2033
				$client['local_host'] = $list[6];
2034
				$client['local_port'] = $list[7];
2035
				$client['virtual_addr6'] = $list[8];
2036 95305736 jim-p
			}
2037 4de8f7ba Phil Davis
			if (strstr($line, "CONNECTING")) {
2038
				$client['status'] = "connecting";
2039 453d9c96 jim-p
			}
2040 4de8f7ba Phil Davis
			if (strstr($line, "ASSIGN_IP")) {
2041
				$client['status'] = "waiting";
2042 453d9c96 jim-p
				$list = explode(",", $line);
2043
2044 4de8f7ba Phil Davis
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
2045
				$client['virtual_addr'] = $list[3];
2046 453d9c96 jim-p
			}
2047 4de8f7ba Phil Davis
			if (strstr($line, "RECONNECTING")) {
2048
				$client['status'] = "reconnecting";
2049 453d9c96 jim-p
				$list = explode(",", $line);
2050
2051 4de8f7ba Phil Davis
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
2052 453d9c96 jim-p
				$client['status'] .= "; " . $list[2];
2053
			}
2054 95305736 jim-p
			/* parse end of output line */
2055 ef00af3c Phil Davis
			if (strstr($line, "END") || strstr($line, "ERROR")) {
2056 95305736 jim-p
				break;
2057 ef00af3c Phil Davis
			}
2058 95305736 jim-p
		}
2059
2060
		/* If up, get read/write stats */
2061
		if (strcmp($client['status'], "up") == 0) {
2062
			fputs($fp, "status 2\n");
2063
			/* recv all response lines */
2064
			while (!feof($fp)) {
2065
				/* read the next line */
2066
				$line = fgets($fp, 1024);
2067
2068
				$info = stream_get_meta_data($fp);
2069 ef00af3c Phil Davis
				if ($info['timed_out']) {
2070 95305736 jim-p
					break;
2071 ef00af3c Phil Davis
				}
2072 95305736 jim-p
2073 4de8f7ba Phil Davis
				if (strstr($line, "TCP/UDP read bytes")) {
2074 95305736 jim-p
					$list = explode(",", $line);
2075
					$client['bytes_recv'] = $list[1];
2076 53663f57 jim-p
				}
2077 95305736 jim-p
2078 4de8f7ba Phil Davis
				if (strstr($line, "TCP/UDP write bytes")) {
2079 95305736 jim-p
					$list = explode(",", $line);
2080
					$client['bytes_sent'] = $list[1];
2081 53663f57 jim-p
				}
2082 95305736 jim-p
2083
				/* parse end of output line */
2084 ef00af3c Phil Davis
				if (strstr($line, "END")) {
2085 95305736 jim-p
					break;
2086 ef00af3c Phil Davis
				}
2087 53663f57 jim-p
			}
2088
		}
2089 95305736 jim-p
2090
		fclose($fp);
2091
2092
	} else {
2093 e8c516a0 Phil Davis
		$client['remote_host'] = gettext("Unable to contact daemon");
2094
		$client['virtual_addr'] = gettext("Service not running?");
2095 95305736 jim-p
		$client['bytes_recv'] = 0;
2096
		$client['bytes_sent'] = 0;
2097
		$client['connect_time'] = 0;
2098 53663f57 jim-p
	}
2099 95305736 jim-p
	return $client;
2100 53663f57 jim-p
}
2101 8e022a76 jim-p
2102 08ef78ac Viktor G
function openvpn_kill_client($port, $remipp, $client_id) {
2103 61fce4a6 Phil Davis
	global $g;
2104
2105
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
2106 348c2af1 jim-p
	$tcpsrv = "unix://{$g['openvpn_base']}/{$port}/sock";
2107 61fce4a6 Phil Davis
	$errval = null;
2108
	$errstr = null;
2109
2110
	/* open a tcp connection to the management port of each server */
2111
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
2112
	$killed = -1;
2113
	if ($fp) {
2114
		stream_set_timeout($fp, 1);
2115 6e889d88 Viktor G
		if (is_numeric($client_id)) {
2116 08ef78ac Viktor G
			/* terminate remote client, see https://redmine.pfsense.org/issues/12416 */
2117
			fputs($fp, "client-kill {$client_id} HALT\n");
2118
		} else {
2119
			fputs($fp, "kill {$remipp}\n");
2120
		}
2121 61fce4a6 Phil Davis
		while (!feof($fp)) {
2122
			$line = fgets($fp, 1024);
2123
2124
			$info = stream_get_meta_data($fp);
2125
			if ($info['timed_out']) {
2126
				break;
2127
			}
2128
2129
			/* parse header list line */
2130
			if (strpos($line, "INFO:") !== false) {
2131
				continue;
2132
			}
2133
			if (strpos($line, "SUCCESS") !== false) {
2134
				$killed = 0;
2135
			}
2136
			break;
2137
		}
2138
		fclose($fp);
2139
	}
2140
	return $killed;
2141
}
2142
2143 8e022a76 jim-p
function openvpn_refresh_crls() {
2144
	global $g, $config;
2145
2146 a8f538a8 jim-p
	openvpn_create_dirs();
2147 8e022a76 jim-p
2148
	if (is_array($config['openvpn']['openvpn-server'])) {
2149
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2150 ef00af3c Phil Davis
			if (empty($settings)) {
2151 8e022a76 jim-p
				continue;
2152 ef00af3c Phil Davis
			}
2153
			if (isset($settings['disable'])) {
2154 8e022a76 jim-p
				continue;
2155 ef00af3c Phil Davis
			}
2156 8e022a76 jim-p
			// Write the settings for the keys
2157 ef00af3c Phil Davis
			switch ($settings['mode']) {
2158 8e022a76 jim-p
				case 'p2p_tls':
2159
				case 'server_tls':
2160
				case 'server_tls_user':
2161
				case 'server_user':
2162 348c2af1 jim-p
					$param = array('caref' => $settings['caref']);
2163
					$cas = ca_chain_array($param);
2164 475d712b jim-p
					$capath = "{$g['openvpn_base']}/server{$settings['vpnid']}/ca";
2165 8e022a76 jim-p
					if (!empty($settings['crlref'])) {
2166
						$crl = lookup_crl($settings['crlref']);
2167 728003c8 jim-p
						crl_update($crl);
2168 348c2af1 jim-p
					}
2169
					foreach ($cas as $ca) {
2170 475d712b jim-p
						ca_setup_capath($ca, $capath, $crl, true);
2171 8e022a76 jim-p
					}
2172 f61a794a jim-p
					unset($cas, $param, $capath, $crl);
2173 8e022a76 jim-p
					break;
2174
			}
2175
		}
2176
	}
2177
}
2178
2179 a8f538a8 jim-p
function openvpn_create_dirs() {
2180 154b0f80 jim-p
	global $g, $config, $openvpn_tls_server_modes;
2181 348c2af1 jim-p
	if (!is_dir($g['openvpn_base'])) {
2182
		safe_mkdir($g['openvpn_base'], 0750);
2183 ef00af3c Phil Davis
	}
2184 154b0f80 jim-p
2185 348c2af1 jim-p
	init_config_arr(array('openvpn', 'openvpn-server'));
2186
	init_config_arr(array('openvpn', 'openvpn-client'));
2187
	foreach(array('server', 'client') as $mode) {
2188
		foreach ($config['openvpn']["openvpn-{$mode}"] as $settings) {
2189
			$target = "{$g['openvpn_base']}/{$mode}{$settings['vpnid']}";
2190
			@unlink_if_exists($csctarget);
2191
			@safe_mkdir($target);
2192 154b0f80 jim-p
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2193
				if ($settings['vpnid']) {
2194 348c2af1 jim-p
					$csctarget = "{$target}/csc/";
2195
					@unlink_if_exists($csctarget);
2196
					@safe_mkdir($csctarget);
2197 154b0f80 jim-p
				}
2198
			}
2199
		}
2200
	}
2201 a8f538a8 jim-p
}
2202
2203 30c8a290 Renato Botelho
function openvpn_get_interface_ip($ip, $cidr) {
2204
	$subnet = gen_subnetv4($ip, $cidr);
2205 10a8b5ee PiBa-NL
	if ($cidr == 31) {
2206
		$ip1 = $subnet;
2207
	} else {
2208
		$ip1 = ip_after($subnet);
2209
	}
2210 30c8a290 Renato Botelho
	$ip2 = ip_after($ip1);
2211 91c44185 jim-p
	return array($ip1, $ip2);
2212
}
2213
2214
function openvpn_get_interface_ipv6($ipv6, $prefix) {
2215
	$basev6 = gen_subnetv6($ipv6, $prefix);
2216
	// Is there a better way to do this math?
2217
	$ipv6_arr = explode(':', $basev6);
2218
	$last = hexdec(array_pop($ipv6_arr));
2219 10a8b5ee PiBa-NL
	if ($prefix == 127) {
2220
		$last--;
2221
	}
2222 587995fb Phil Davis
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
2223
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
2224 91c44185 jim-p
	return array($ipv6_1, $ipv6_2);
2225
}
2226
2227
function openvpn_clear_route($mode, $settings) {
2228 ef00af3c Phil Davis
	if (empty($settings['tunnel_network'])) {
2229 91c44185 jim-p
		return;
2230 ef00af3c Phil Davis
	}
2231 4b8d710c Viktor G
	list($ip, $cidr) = openvpn_gen_tunnel_network($settings['tunnel_network']);
2232 91c44185 jim-p
	$mask = gen_subnet_mask($cidr);
2233 6ca938cf jim-p
	$clear_route = false;
2234
2235 ef00af3c Phil Davis
	switch ($settings['mode']) {
2236 6ca938cf jim-p
		case 'shared_key':
2237
			$clear_route = true;
2238
			break;
2239 91c44185 jim-p
		case 'p2p_tls':
2240
		case 'p2p_shared_key':
2241 a0f991ec PiBa-NL
			if ($cidr >= 30) {
2242 6ca938cf jim-p
				$clear_route = true;
2243 ef00af3c Phil Davis
			}
2244 91c44185 jim-p
			break;
2245
	}
2246 6ca938cf jim-p
2247 6d0b9fe9 jim-p
	if ($clear_route && !empty($ip) && !empty($mask)) {
2248 30c8a290 Renato Botelho
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2249 6ca938cf jim-p
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2250 615d7f0a Ermal
		/* XXX: Family for route? */
2251 6ca938cf jim-p
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2252
	}
2253 91c44185 jim-p
}
2254
2255 5c427ce7 jim-p
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2256 a28d40cb jim-p
	$routes = "";
2257 4b8d710c Viktor G
	$networks = array();
2258 ef00af3c Phil Davis
	if (empty($value)) {
2259 a28d40cb jim-p
		return "";
2260 ef00af3c Phil Davis
	}
2261 4b8d710c Viktor G
	$tmpnetworks = explode(',', $value);
2262
	foreach ($tmpnetworks as $network) {
2263
		if (is_alias($network)) {
2264
			foreach (alias_to_subnets_recursive($network) as $net) {
2265
				if ((($ipproto == "ipv4") && is_subnetv4($net)) ||
2266
				    (($ipproto == "ipv6") && is_subnetv6($net))) {
2267
					$networks[] = $net;
2268
				}
2269
			}
2270
		} else {
2271
			$networks[] = $network;
2272
		}
2273
	}
2274 a28d40cb jim-p
2275
	foreach ($networks as $network) {
2276 ef00af3c Phil Davis
		if ($ipproto == "ipv4") {
2277 5c427ce7 jim-p
			$route = openvpn_gen_route_ipv4($network, $iroute);
2278 ef00af3c Phil Davis
		} else {
2279 5c427ce7 jim-p
			$route = openvpn_gen_route_ipv6($network, $iroute);
2280 ef00af3c Phil Davis
		}
2281 a28d40cb jim-p
2282 ef00af3c Phil Davis
		if ($push) {
2283 a28d40cb jim-p
			$routes .= "push \"{$route}\"\n";
2284 ef00af3c Phil Davis
		} else {
2285 a28d40cb jim-p
			$routes .= "{$route}\n";
2286 ef00af3c Phil Davis
		}
2287 a28d40cb jim-p
	}
2288
	return $routes;
2289
}
2290
2291 5c427ce7 jim-p
function openvpn_gen_route_ipv4($network, $iroute = false) {
2292
	$i = ($iroute) ? "i" : "";
2293 a28d40cb jim-p
	list($ip, $mask) = explode('/', trim($network));
2294
	$mask = gen_subnet_mask($mask);
2295 5c427ce7 jim-p
	return "{$i}route $ip $mask";
2296 a28d40cb jim-p
}
2297
2298 5c427ce7 jim-p
function openvpn_gen_route_ipv6($network, $iroute = false) {
2299
	$i = ($iroute) ? "i" : "";
2300 a28d40cb jim-p
	list($ipv6, $prefix) = explode('/', trim($network));
2301 3000b44d Renato Botelho
	if (empty($prefix) && !is_numeric($prefix)) {
2302 a28d40cb jim-p
		$prefix = "128";
2303 ef00af3c Phil Davis
	}
2304 5c427ce7 jim-p
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2305 a28d40cb jim-p
}
2306
2307 699125b1 jim-p
function openvpn_get_settings($mode, $vpnid) {
2308
	global $config;
2309
2310
	if (is_array($config['openvpn']['openvpn-server'])) {
2311
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2312 ef00af3c Phil Davis
			if (isset($settings['disable'])) {
2313 699125b1 jim-p
				continue;
2314 ef00af3c Phil Davis
			}
2315 699125b1 jim-p
2316 ef00af3c Phil Davis
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2317 699125b1 jim-p
				return $settings;
2318 ef00af3c Phil Davis
			}
2319 699125b1 jim-p
		}
2320
	}
2321
2322
	if (is_array($config['openvpn']['openvpn-client'])) {
2323
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
2324 ef00af3c Phil Davis
			if (isset($settings['disable'])) {
2325 699125b1 jim-p
				continue;
2326 ef00af3c Phil Davis
			}
2327 699125b1 jim-p
2328 ef00af3c Phil Davis
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2329 699125b1 jim-p
				return $settings;
2330 ef00af3c Phil Davis
			}
2331 699125b1 jim-p
		}
2332
	}
2333
2334
	return array();
2335
}
2336
2337
function openvpn_restart_by_vpnid($mode, $vpnid) {
2338
	$settings = openvpn_get_settings($mode, $vpnid);
2339
	openvpn_restart($mode, $settings);
2340
}
2341
2342 19a0636d jim-p
/****f* certs/openvpn_is_tunnel_network_in_use
2343
 * NAME
2344
 *   openvpn_is_tunnel_network_in_use
2345
 *     Check if the supplied network is in use as an OpenVPN server or client
2346
 *     tunnel network
2347
 * INPUTS
2348
 *   $net : The IPv4 or IPv6 network to check
2349
 * RESULT
2350
 *   boolean value: true if the network is in use, false otherwise.
2351
 ******/
2352
2353
function openvpn_is_tunnel_network_in_use($net) {
2354
	global $config;
2355
	init_config_arr(array('openvpn', 'openvpn-server'));
2356
	init_config_arr(array('openvpn', 'openvpn-client'));
2357
	/* Determine whether to check IPv4 or IPv6 tunnel networks */
2358
	$tocheck = 'tunnel_network';
2359
	if (is_v6($net)) {
2360
		$tocheck .= "v6";
2361
	}
2362
	/* Check all OpenVPN clients and servers for this tunnel network */
2363
	foreach(array('server', 'client') as $mode) {
2364
		foreach ($config['openvpn']["openvpn-{$mode}"] as $ovpn) {
2365
			if (!empty($ovpn[$tocheck]) &&
2366
			    ($ovpn[$tocheck] == $net)) {
2367
				return true;
2368
			}
2369
		}
2370
	}
2371
	return false;
2372
}
2373 924eeefb jim-p
2374 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) {
2375 924eeefb jim-p
	/* If the data_ciphers list is empty, populate it with the fallback cipher. */
2376 3adc4134 jim-p
	if (empty($data_ciphers) || !$ncp_enabled) {
2377 924eeefb jim-p
		$data_ciphers = $fallback_cipher;
2378
	}
2379
	/* Add the fallback cipher to the data ciphers list if it isn't already present */
2380
	if (!in_array($fallback_cipher, explode(',', $data_ciphers))) {
2381
		$data_ciphers .= ',' . $fallback_cipher;
2382
	}
2383
	return $data_ciphers;
2384
}
2385
2386 30064732 Viktor G
function openvpn_authscript_string($authmode, $strictusercn, $mode_id, $local_port) {
2387
	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";
2388
}
2389
2390 2e6b2841 Viktor G
function openvpn_inuse($id, $mode) {
2391
	global $config;
2392
2393
	$type = ($mode == 'server') ? 's' : 'c';
2394
2395
	foreach (get_configured_interface_list(true) as $if) {
2396
		if ($config['interfaces'][$if]['if'] == "ovpn{$type}{$id}") {
2397
			return true;
2398
		}
2399
	}
2400
2401
	return false;
2402
}
2403
2404 a96a7151 Viktor G
function openvpn_clean_rules($mode, $id) {
2405
	global $g;
2406
2407
	if ($mode == "server") {
2408
		unlink_if_exists("{$g['tmp_path']}/ovpn_ovpns{$id}_*.rules");
2409
	}
2410
}
2411
2412 756720e2 Pierre POMES
?>