Project

General

Profile

Download (66 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 b656061a 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 a28d40cb jim-p
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4") {
627
	$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 a28d40cb jim-p
			$error = !openvpn_validate_cidr_ipv4($network);
641 ef00af3c Phil Davis
		} else {
642 a28d40cb jim-p
			$error = !openvpn_validate_cidr_ipv6($network);
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
function openvpn_validate_cidr_ipv4($value) {
657 8dc3ef67 Scott Ullrich
	$value = trim($value);
658
	if (!empty($value)) {
659
		list($ip, $mask) = explode('/', $value);
660 ef00af3c Phil Davis
		if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0)) {
661 a28d40cb jim-p
			return false;
662 ef00af3c Phil Davis
		}
663 8dc3ef67 Scott Ullrich
	}
664 a28d40cb jim-p
	return true;
665
}
666
667
function openvpn_validate_cidr_ipv6($value) {
668
	$value = trim($value);
669
	if (!empty($value)) {
670
		list($ipv6, $prefix) = explode('/', $value);
671 ef00af3c Phil Davis
		if (empty($prefix)) {
672 a28d40cb jim-p
			$prefix = "128";
673 ef00af3c Phil Davis
		}
674
		if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0)) {
675 a28d40cb jim-p
			return false;
676 ef00af3c Phil Davis
		}
677 a28d40cb jim-p
	}
678
	return true;
679 afb07cf1 Scott Ullrich
}
680
681 d799787e Matthew Grooms
function openvpn_add_dhcpopts(& $settings, & $conf) {
682 afb07cf1 Scott Ullrich
683 ef00af3c Phil Davis
	if (!empty($settings['dns_domain'])) {
684 d799787e Matthew Grooms
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
685 ef00af3c Phil Davis
	}
686 add2e3f7 Scott Ullrich
687 ef00af3c Phil Davis
	if (!empty($settings['dns_server1'])) {
688 6a638752 jim-p
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
689
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
690 ef00af3c Phil Davis
	}
691
	if (!empty($settings['dns_server2'])) {
692 6a638752 jim-p
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
693
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
694 ef00af3c Phil Davis
	}
695
	if (!empty($settings['dns_server3'])) {
696 6a638752 jim-p
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
697
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
698 ef00af3c Phil Davis
	}
699
	if (!empty($settings['dns_server4'])) {
700 6a638752 jim-p
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
701
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
702 ef00af3c Phil Davis
	}
703 f9927473 Scott Ullrich
704 01c2735c jim-p
	if (!empty($settings['push_blockoutsidedns'])) {
705
		$conf .= "push \"block-outside-dns\"\n";
706
	}
707 ef00af3c Phil Davis
	if (!empty($settings['push_register_dns'])) {
708 c38764dc Dmitriy K.
		$conf .= "push \"register-dns\"\n";
709 ef00af3c Phil Davis
	}
710 c38764dc Dmitriy K.
711 ef00af3c Phil Davis
	if (!empty($settings['ntp_server1'])) {
712 c7f70dbc Chris Buechler
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
713 ef00af3c Phil Davis
	}
714
	if (!empty($settings['ntp_server2'])) {
715 c7f70dbc Chris Buechler
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
716 ef00af3c Phil Davis
	}
717 f9927473 Scott Ullrich
718 d799787e Matthew Grooms
	if ($settings['netbios_enable']) {
719 add2e3f7 Scott Ullrich
720 ef00af3c Phil Davis
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
721 095a95ae Matthew Grooms
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
722 ef00af3c Phil Davis
		}
723
		if (!empty($settings['dhcp_nbtscope'])) {
724 d799787e Matthew Grooms
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
725 ef00af3c Phil Davis
		}
726 8dc3ef67 Scott Ullrich
727 ef00af3c Phil Davis
		if (!empty($settings['wins_server1'])) {
728 d799787e Matthew Grooms
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
729 ef00af3c Phil Davis
		}
730
		if (!empty($settings['wins_server2'])) {
731 d799787e Matthew Grooms
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
732 ef00af3c Phil Davis
		}
733 add2e3f7 Scott Ullrich
734 ef00af3c Phil Davis
		if (!empty($settings['nbdd_server1'])) {
735 d799787e Matthew Grooms
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
736 ef00af3c Phil Davis
		}
737 d799787e Matthew Grooms
	}
738 8dc3ef67 Scott Ullrich
739 ef00af3c Phil Davis
	if ($settings['gwredir']) {
740 d799787e Matthew Grooms
		$conf .= "push \"redirect-gateway def1\"\n";
741 ef00af3c Phil Davis
	}
742 37f05e97 jim-p
	if ($settings['gwredir6']) {
743
		$conf .= "push \"redirect-gateway ipv6\"\n";
744
	}
745 d799787e Matthew Grooms
}
746 24012690 Scott Ullrich
747 d799787e Matthew Grooms
function openvpn_add_custom(& $settings, & $conf) {
748 add2e3f7 Scott Ullrich
749 d799787e Matthew Grooms
	if ($settings['custom_options']) {
750 8dc3ef67 Scott Ullrich
751 d799787e Matthew Grooms
		$options = explode(';', $settings['custom_options']);
752
753
		if (is_array($options)) {
754 ef00af3c Phil Davis
			foreach ($options as $option) {
755 d799787e Matthew Grooms
				$conf .= "$option\n";
756 ef00af3c Phil Davis
			}
757
		} else {
758 d799787e Matthew Grooms
			$conf .= "{$settings['custom_options']}\n";
759 ef00af3c Phil Davis
		}
760 add2e3f7 Scott Ullrich
	}
761
}
762
763 691fbf14 Ermal Lu?i
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
764 d799787e Matthew Grooms
	global $g;
765 add2e3f7 Scott Ullrich
766 348c2af1 jim-p
	$fpath = "{$g['openvpn_base']}/{$mode_id}/{$directive}";
767 a8f538a8 jim-p
	openvpn_create_dirs();
768 d799787e Matthew Grooms
	file_put_contents($fpath, base64_decode($data));
769 f9ac3784 Ermal Lu?i
	//chown($fpath, 'nobody');
770
	//chgrp($fpath, 'nobody');
771 6f27412f Ermal Lu?i
	@chmod($fpath, 0600);
772 d799787e Matthew Grooms
773 691fbf14 Ermal Lu?i
	$conf .= "{$directive} {$fpath} {$opt}\n";
774 4eefa6e8 Scott Ullrich
}
775
776 fc05822b jim-p
function openvpn_reconfigure($mode, $settings) {
777 99d7e8c1 jim-p
	global $g, $config, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
778 afb07cf1 Scott Ullrich
779 ef00af3c Phil Davis
	if (empty($settings)) {
780 93a0a028 Ermal Luçi
		return;
781 ef00af3c Phil Davis
	}
782
	if (isset($settings['disable'])) {
783 4eefa6e8 Scott Ullrich
		return;
784 ef00af3c Phil Davis
	}
785 a8f538a8 jim-p
	openvpn_create_dirs();
786 fdd725f0 Ermal Luçi
	/*
787 d799787e Matthew Grooms
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
788
	 * we use a vpnid number which is allocated for a particular client
789
	 * or server configuration. ( see openvpn_vpnid_next() )
790 fdd725f0 Ermal Luçi
	 */
791 8874c692 Ermal Luçi
792 d799787e Matthew Grooms
	$vpnid = $settings['vpnid'];
793
	$mode_id = $mode.$vpnid;
794 8874c692 Ermal Luçi
795 ef00af3c Phil Davis
	if (isset($settings['dev_mode'])) {
796 4936ff53 jim-p
		$tunname = "{$settings['dev_mode']}{$vpnid}";
797 ef00af3c Phil Davis
	} else {
798
		/* defaults to tun */
799 bd7ca506 jim-p
		$tunname = "tun{$vpnid}";
800 4936ff53 jim-p
		$settings['dev_mode'] = "tun";
801 691fbf14 Ermal Lu?i
	}
802
803 ef00af3c Phil Davis
	if ($mode == "server") {
804 bd7ca506 jim-p
		$devname = "ovpns{$vpnid}";
805 ef00af3c Phil Davis
	} else {
806 bd7ca506 jim-p
		$devname = "ovpnc{$vpnid}";
807 ef00af3c Phil Davis
	}
808 8874c692 Ermal Luçi
809 bd7ca506 jim-p
	/* is our device already configured */
810 4a97aa34 Ermal
	if (!does_interface_exist($devname)) {
811 dc408939 Matthew Grooms
812 bd7ca506 jim-p
		/* create the tap device if required */
813 ef00af3c Phil Davis
		if (!file_exists("/dev/{$tunname}")) {
814 873c1701 Renato Botelho
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
815 ef00af3c Phil Davis
		}
816 98872d89 Ermal Luçi
817 bd7ca506 jim-p
		/* rename the device */
818 873c1701 Renato Botelho
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
819 095a95ae Matthew Grooms
820 4ab1ffa0 Renato Botelho
		/* add the device to the openvpn group and make sure it's UP*/
821
		mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " group openvpn up");
822 da4f91a9 Renato Botelho
823 bd1a6267 Renato Botelho
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
824
		$grouptmp = link_interface_to_group($ifname);
825 ef00af3c Phil Davis
		if (!empty($grouptmp)) {
826 bd1a6267 Renato Botelho
			array_walk($grouptmp, 'interface_group_add_member');
827 ef00af3c Phil Davis
		}
828 bd1a6267 Renato Botelho
		unset($grouptmp, $ifname);
829 dc408939 Matthew Grooms
	}
830 d799787e Matthew Grooms
831 dc408939 Matthew Grooms
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
832 6714bbdc jim-p
	$proto = strtolower($settings['protocol']);
833 ef00af3c Phil Davis
	if (substr($settings['protocol'], 0, 3) == "TCP") {
834 6714bbdc jim-p
			$proto = "{$proto}-{$mode}";
835 ef00af3c Phil Davis
	}
836 4936ff53 jim-p
	$dev_mode = $settings['dev_mode'];
837 189edaf3 jim-p
	$fbcipher = $settings['data_ciphers_fallback'];
838 97d5b59b jim-p
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
839
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
840 d799787e Matthew Grooms
841 47c48e28 smos
	$interface = get_failover_interface($settings['interface']);
842 e27bc6cf Phil Davis
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
843 d7a0c22a bcyrill
	$ipaddr = $settings['ipaddr'];
844 d799787e Matthew Grooms
845 67b0902f pierrepomes
	// If a specific ip address (VIP) is requested, use it.
846
	// Otherwise, if a specific interface is requested, use it
847 ef00af3c Phil Davis
	// If "any" interface was selected, local directive will be omitted.
848 97ffc513 Seth Mos
	if (is_ipaddrv4($ipaddr)) {
849 4de8f7ba Phil Davis
		$iface_ip = $ipaddr;
850 af0257cf Renato Botelho
	} elseif (!empty($interface) && strcmp($interface, "any")) {
851 51e7132e Renato Botelho
		$iface_ip=get_interface_ip($interface);
852 47c48e28 smos
	}
853 e27bc6cf Phil Davis
	if (is_ipaddrv6($ipaddr)) {
854 6c07db48 Phil Davis
		$iface_ipv6 = $ipaddr;
855 af0257cf Renato Botelho
	} elseif (!empty($interface) && strcmp($interface, "any")) {
856 c9f3f96a Viktor G
		/* get correct interface name for 6RD/6to4 interfaces
857
		 * see https://redmine.pfsense.org/issues/11674 */
858
		if (is_stf_interface($settings['interface'])) {
859
			$iface_ipv6=get_interface_ipv6($settings['interface']);
860
		} else {
861
			$iface_ipv6=get_interface_ipv6($interface);
862
		}
863 3d06e8f0 pierrepomes
	}
864 d799787e Matthew Grooms
865 b1e8e675 Dmitriy K.
	$conf = "dev {$devname}\n";
866 5b3c0116 Dmitriy K.
	if (isset($settings['verbosity_level'])) {
867 b1e8e675 Dmitriy K.
		$conf .= "verb {$settings['verbosity_level']}\n";
868 5b3c0116 Dmitriy K.
	}
869 42bb1bee Renato Botelho
870 4936ff53 jim-p
	$conf .= "dev-type {$settings['dev_mode']}\n";
871 bd7ca506 jim-p
	$conf .= "dev-node /dev/{$tunname}\n";
872 3c11bd3c Matthew Grooms
	$conf .= "writepid {$pfile}\n";
873
	$conf .= "#user nobody\n";
874
	$conf .= "#group nobody\n";
875 d1014c18 Chris Buechler
	$conf .= "script-security 3\n";
876 3c11bd3c Matthew Grooms
	$conf .= "daemon\n";
877 3bfecc81 Renato Botelho do Couto
878
	if (!empty($settings['inactive_seconds'])) {
879
		$conf .= "inactive {$settings['inactive_seconds']}\n";
880
	}
881
882
	if (!empty($settings['ping_method']) &&
883
	    $settings['ping_method'] == 'ping') {
884
		$conf .= "ping {$settings['ping_seconds']}\n";
885
886
		if (!empty($settings['ping_push'])) {
887
			$conf .= "push \"ping {$settings['ping_seconds']}\"\n";
888
		}
889
890
		$action = str_replace("_", "-", $settings['ping_action']);
891
		$conf .= "{$action} {$settings['ping_action_seconds']}\n";
892
893
		if (!empty($settings['ping_action_push'])) {
894
			$conf .= "push \"{$action} " .
895
			    "{$settings['ping_action_seconds']}\"\n";
896
		}
897
	} else {
898
		$conf .= "keepalive " .
899
		    ($settings['keepalive_interval']
900
			?: $openvpn_default_keepalive_interval) . " " .
901
		    ($settings['keepalive_timeout']
902
			?: $openvpn_default_keepalive_timeout) . "\n";
903
	}
904
905 3c11bd3c Matthew Grooms
	$conf .= "ping-timer-rem\n";
906
	$conf .= "persist-tun\n";
907
	$conf .= "persist-key\n";
908
	$conf .= "proto {$proto}\n";
909 97d5b59b jim-p
	$conf .= "auth {$digest}\n";
910 8d964cea Ermal
	$conf .= "up /usr/local/sbin/ovpn-linkup\n";
911
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
912 1492e02c Ermal
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
913 ef00af3c Phil Davis
		switch ($settings['mode']) {
914 a1b9105b jim-p
			case 'server_user':
915
			case 'server_tls_user':
916
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
917
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
918
				break;
919
		}
920 1492e02c Ermal
	}
921 4f4de341 Lorenz Schori
	if ($settings['dev_mode'] === 'tun' && isset($config['unbound']['enable']) && isset($config['unbound']['regovpnclients'])) {
922 3b88d971 Viktor G
		if (($settings['mode'] == 'server_tls') || ($settings['mode'] == 'server_tls_user') ||
923
		    (($settings['mode'] == 'server_user') && ($settings['username_as_common_name'] == 'enabled'))) {
924
			$domain = !empty($settings['dns_domain']) ? $settings['dns_domain'] : $config['system']['domain'];
925
			if (is_domain($domain)) {
926
				$conf .= "learn-address \"/usr/local/sbin/openvpn.learn-address.sh $domain\"\n";
927
			}
928 0cc17a06 Lorenz Schori
		}
929
	}
930 3c11bd3c Matthew Grooms
931 5280fd8d Renato Botelho
	/*
932
	 * When binding specific address, wait cases where interface is in
933
	 * tentative state otherwise it will fail
934
	 */
935
	$wait_tentative = false;
936
937 6714bbdc jim-p
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
938 ca366676 jim-p
	switch ($settings['protocol']) {
939
		case 'UDP':
940
		case 'TCP':
941
			$conf .= "multihome\n";
942
			break;
943
		case 'UDP4':
944
		case 'TCP4':
945
			if (is_ipaddrv4($iface_ip)) {
946
				$conf .= "local {$iface_ip}\n";
947
			}
948
			if ($settings['interface'] == "any") {
949
				$conf .= "multihome\n";
950
			}
951
			break;
952
		case 'UDP6':
953
		case 'TCP6':
954
			if (is_ipaddrv6($iface_ipv6)) {
955
				$conf .= "local {$iface_ipv6}\n";
956 5280fd8d Renato Botelho
				$wait_tentative = true;
957 ca366676 jim-p
			}
958
			if ($settings['interface'] == "any") {
959
				$conf .= "multihome\n";
960
			}
961
			break;
962
		default:
963 97ffc513 Seth Mos
	}
964 d799787e Matthew Grooms
965 ef00af3c Phil Davis
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
966 582c58ae jim-p
		$conf .= "engine {$settings['engine']}\n";
967 ef00af3c Phil Davis
	}
968 582c58ae jim-p
969 67b0902f pierrepomes
	// server specific settings
970 8dc3ef67 Scott Ullrich
	if ($mode == 'server') {
971 d799787e Matthew Grooms
972 966cdb43 jim-p
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
973
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
974 5dc6c910 jim-p
		$mask = gen_subnet_mask($cidr);
975 8dc3ef67 Scott Ullrich
976 3c11bd3c Matthew Grooms
		// configure tls modes
977 ef00af3c Phil Davis
		switch ($settings['mode']) {
978 3c11bd3c Matthew Grooms
			case 'p2p_tls':
979
			case 'server_tls':
980 e62e2f8b Ermal Lu?i
			case 'server_user':
981 3c11bd3c Matthew Grooms
			case 'server_tls_user':
982 d799787e Matthew Grooms
				$conf .= "tls-server\n";
983 3c11bd3c Matthew Grooms
				break;
984 8dc3ef67 Scott Ullrich
		}
985 d799787e Matthew Grooms
986 3c11bd3c Matthew Grooms
		// configure p2p/server modes
987 ef00af3c Phil Davis
		switch ($settings['mode']) {
988 6c9cf466 jim-p
			case 'p2p_tls':
989 5dc6c910 jim-p
				// If the CIDR is less than a /30, OpenVPN will complain if you try to
990
				//  use the server directive. It works for a single client without it.
991
				//  See ticket #1417
992 4af6affa jim-p
				if ((!empty($ip) && !empty($mask)) ||
993
				    (!empty($ipv6) && !empty($prefix))) {
994
					$add_ccd = false;
995
					if (is_ipaddr($ip) && ($cidr < 30)) {
996
						$add_ccd = true;
997
						$conf .= "server {$ip} {$mask}\n";
998
					}
999 ef00af3c Phil Davis
					if (is_ipaddr($ipv6)) {
1000 4af6affa jim-p
						$add_ccd = true;
1001 a0e3ee98 jim-p
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
1002 ef00af3c Phil Davis
					}
1003 4af6affa jim-p
					if ($add_ccd) {
1004
						$conf .= "client-config-dir {$g['openvpn_base']}/server{$vpnid}/csc\n";
1005
					}
1006 5dc6c910 jim-p
				}
1007 3c11bd3c Matthew Grooms
			case 'p2p_shared_key':
1008 74a556a3 jim-p
				if (!empty($ip) && !empty($mask)) {
1009 30c8a290 Renato Botelho
					list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1010 ef00af3c Phil Davis
					if ($settings['dev_mode'] == 'tun') {
1011 459e9333 jim-p
						$conf .= "ifconfig {$ip1} {$ip2}\n";
1012 ef00af3c Phil Davis
					} else {
1013 459e9333 jim-p
						$conf .= "ifconfig {$ip1} {$mask}\n";
1014 ef00af3c Phil Davis
					}
1015 1ab6bdb5 jim-p
				}
1016 a0e3ee98 jim-p
				if (!empty($ipv6) && !empty($prefix)) {
1017 91c44185 jim-p
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1018 ef00af3c Phil Davis
					if ($settings['dev_mode'] == 'tun') {
1019 a0e3ee98 jim-p
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$ipv6_2}\n";
1020 ef00af3c Phil Davis
					} else {
1021 60f501ec Phil Davis
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$prefix}\n";
1022 ef00af3c Phil Davis
					}
1023 a0e3ee98 jim-p
				}
1024 3c11bd3c Matthew Grooms
				break;
1025
			case 'server_tls':
1026
			case 'server_user':
1027
			case 'server_tls_user':
1028 4af6affa jim-p
				if ((!empty($ip) && !empty($mask)) ||
1029
				    (!empty($ipv6) && !empty($prefix))) {
1030
					if (is_ipaddr($ip)) {
1031
						$conf .= "server {$ip} {$mask}\n";
1032
					}
1033 ef00af3c Phil Davis
					if (is_ipaddr($ipv6)) {
1034 1ab6bdb5 jim-p
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
1035 ef00af3c Phil Davis
					}
1036 348c2af1 jim-p
					$conf .= "client-config-dir {$g['openvpn_base']}/server{$vpnid}/csc\n";
1037 1ab6bdb5 jim-p
				} else {
1038
					if ($settings['serverbridge_dhcp']) {
1039
						if ((!empty($settings['serverbridge_interface'])) && (strcmp($settings['serverbridge_interface'], "none"))) {
1040
							$biface_ip=get_interface_ip($settings['serverbridge_interface']);
1041
							$biface_sm=gen_subnet_mask(get_interface_subnet($settings['serverbridge_interface']));
1042
							if (is_ipaddrv4($biface_ip) && is_ipaddrv4($settings['serverbridge_dhcp_start']) && is_ipaddrv4($settings['serverbridge_dhcp_end'])) {
1043
								$conf .= "server-bridge {$biface_ip} {$biface_sm} {$settings['serverbridge_dhcp_start']} {$settings['serverbridge_dhcp_end']}\n";
1044 348c2af1 jim-p
								$conf .= "client-config-dir {$g['openvpn_base']}/server{$vpnid}/csc\n";
1045 1ab6bdb5 jim-p
							} else {
1046
								$conf .= "mode server\n";
1047
							}
1048 498f7e20 jim-p
							if (!empty($settings['serverbridge_routegateway']) && is_ipaddrv4($biface_ip)) {
1049
								$conf .= "push \"route-gateway {$biface_ip}\"\n";
1050
							}
1051
							/* OpenVPN doesn't support this yet, clients do not recognize the option fully.
1052
							$biface_ip6=get_interface_ipv6($settings['serverbridge_interface']);
1053
							if (!empty($settings['serverbridge_routegateway']) && is_ipaddrv6($biface_ip6)) {
1054
								$conf .= "push \"route-ipv6-gateway {$biface_ip6}\"\n";
1055
							}
1056
							*/
1057 1ab6bdb5 jim-p
						} else {
1058
							$conf .= "mode server\n";
1059
						}
1060
					}
1061
				}
1062 3c11bd3c Matthew Grooms
				break;
1063 8dc3ef67 Scott Ullrich
		}
1064
1065 3c11bd3c Matthew Grooms
		// configure user auth modes
1066 ef00af3c Phil Davis
		switch ($settings['mode']) {
1067 3c11bd3c Matthew Grooms
			case 'server_user':
1068 4cfd15a9 jim-p
				$conf .= "verify-client-cert none\n";
1069 3c11bd3c Matthew Grooms
			case 'server_tls_user':
1070 9eced774 jim-p
				/* username-as-common-name is not compatible with server-bridge */
1071 e5c4f2a7 jim-p
				if ((stristr($conf, "server-bridge") === false) &&
1072
				    ($settings['username_as_common_name'] != 'disabled')) {
1073 9eced774 jim-p
					$conf .= "username-as-common-name\n";
1074 ef00af3c Phil Davis
				}
1075 8a47c190 Ermal Lu?i
				if (!empty($settings['authmode'])) {
1076 5e28dad4 Ermal
					$strictusercn = "false";
1077 ef00af3c Phil Davis
					if ($settings['strictusercn']) {
1078 5e28dad4 Ermal
						$strictusercn = "true";
1079 ef00af3c Phil Davis
					}
1080 c67222fc Viktor G
					$conf .= openvpn_authscript_string($settings['authmode'], $strictusercn, $mode_id, $settings['local_port']);
1081 e8a58de4 Ermal Lu?i
				}
1082 3c11bd3c Matthew Grooms
				break;
1083 8dc3ef67 Scott Ullrich
		}
1084 ef00af3c Phil Davis
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
1085 41936acc jim-p
			$settings['cert_depth'] = 1;
1086 ef00af3c Phil Davis
		}
1087 98963f27 jim-p
		if (is_numeric($settings['cert_depth'])) {
1088 ef00af3c Phil Davis
			if (($mode == 'client') && empty($settings['certref'])) {
1089 2da48592 jim-p
				$cert = "";
1090 ef00af3c Phil Davis
			} else {
1091 2da48592 jim-p
				$cert = lookup_cert($settings['certref']);
1092
				/* XXX: Seems not used at all! */
1093
				$servercn = urlencode(cert_get_cn($cert['crt']));
1094
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
1095
			}
1096 98963f27 jim-p
		}
1097 8dc3ef67 Scott Ullrich
1098 63084885 Matthew Grooms
		// The local port to listen on
1099 d799787e Matthew Grooms
		$conf .= "lport {$settings['local_port']}\n";
1100 c0cf27aa Scott Ullrich
1101 63084885 Matthew Grooms
		// The management port to listen on
1102 71ca2cb2 Ermal
		// Use unix socket to overcome the problem on any type of server
1103 348c2af1 jim-p
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1104 71ca2cb2 Ermal
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
1105 63084885 Matthew Grooms
1106 ef00af3c Phil Davis
		if ($settings['maxclients']) {
1107 d799787e Matthew Grooms
			$conf .= "max-clients {$settings['maxclients']}\n";
1108 ef00af3c Phil Davis
		}
1109 d799787e Matthew Grooms
1110 37f05e97 jim-p
		// Can we push routes, and should we?
1111
		if ($settings['local_network'] && !$settings['gwredir']) {
1112 a28d40cb jim-p
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1113 3c11bd3c Matthew Grooms
		}
1114 37f05e97 jim-p
		if ($settings['local_networkv6'] && !$settings['gwredir6']) {
1115 a28d40cb jim-p
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1116 787de45a Seth Mos
		}
1117 3c11bd3c Matthew Grooms
1118 ef00af3c Phil Davis
		switch ($settings['mode']) {
1119 3c11bd3c Matthew Grooms
			case 'server_tls':
1120
			case 'server_user':
1121
			case 'server_tls_user':
1122 5d8cd81a jim-p
				// Configure client dhcp options
1123 3c11bd3c Matthew Grooms
				openvpn_add_dhcpopts($settings, $conf);
1124 ef00af3c Phil Davis
				if ($settings['client2client']) {
1125 5d8cd81a jim-p
					$conf .= "client-to-client\n";
1126 ef00af3c Phil Davis
				}
1127 3c11bd3c Matthew Grooms
				break;
1128
		}
1129 4e42da90 Renato Botelho do Couto
		if ($settings['mode'] != 'p2p_shared_key' &&
1130
		    isset($settings['duplicate_cn'])) {
1131 bca35cff jim-p
			$conf .= "duplicate-cn\n";
1132 ef00af3c Phil Davis
		}
1133 d799787e Matthew Grooms
	}
1134
1135 3c11bd3c Matthew Grooms
	// client specific settings
1136 d799787e Matthew Grooms
1137 3c11bd3c Matthew Grooms
	if ($mode == 'client') {
1138 d799787e Matthew Grooms
1139 3c11bd3c Matthew Grooms
		// configure p2p mode
1140 ef00af3c Phil Davis
		switch ($settings['mode']) {
1141 3c11bd3c Matthew Grooms
			case 'p2p_tls':
1142
				$conf .= "tls-client\n";
1143
			case 'shared_key':
1144
				$conf .= "client\n";
1145
				break;
1146
		}
1147 d799787e Matthew Grooms
1148 e3924384 jim-p
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1149 42bb1bee Renato Botelho
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1150 e3924384 jim-p
		//  ensure a random source port.
1151 b42ccf15 jim-p
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1152 e3924384 jim-p
			$conf .= "nobind\n";
1153 ef00af3c Phil Davis
		} elseif ($settings['local_port']) {
1154 e3924384 jim-p
			$conf .= "lport {$settings['local_port']}\n";
1155 ef00af3c Phil Davis
		} else {
1156 e3924384 jim-p
			$conf .= "lport 0\n";
1157 ef00af3c Phil Davis
		}
1158 5708241f jim-p
1159 4b887ef4 jim-p
		// Use unix socket to overcome the problem on any type of server
1160 348c2af1 jim-p
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1161 48a458d2 pierrepomes
1162 3c11bd3c Matthew Grooms
		// The remote server
1163 bd1291d0 Viktor Gurov
		$remoteproto = strtolower($settings['protocol']);
1164 6ac20ad3 Viktor G
		if (substr($remoteproto, 0, 3) == "tcp") {
1165
			$remoteproto .= "-{$mode}";
1166
		}
1167 bd1291d0 Viktor Gurov
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']} {$remoteproto}\n";
1168 3c11bd3c Matthew Grooms
1169 ef00af3c Phil Davis
		if (!empty($settings['use_shaper'])) {
1170 d799787e Matthew Grooms
			$conf .= "shaper {$settings['use_shaper']}\n";
1171 ef00af3c Phil Davis
		}
1172 ee506044 Scott Ullrich
1173 d799787e Matthew Grooms
		if (!empty($settings['tunnel_network'])) {
1174 966cdb43 jim-p
			list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1175 30c8a290 Renato Botelho
			$mask = gen_subnet_mask($cidr);
1176 636918c9 Chris Buechler
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1177 ef00af3c Phil Davis
			if ($settings['dev_mode'] == 'tun') {
1178 459e9333 jim-p
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1179 ef00af3c Phil Davis
			} else {
1180 459e9333 jim-p
				$conf .= "ifconfig {$ip2} {$mask}\n";
1181 ef00af3c Phil Davis
			}
1182 8dc3ef67 Scott Ullrich
		}
1183 d799787e Matthew Grooms
1184 a0e3ee98 jim-p
		if (!empty($settings['tunnel_networkv6'])) {
1185 966cdb43 jim-p
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1186 91c44185 jim-p
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1187 ef00af3c Phil Davis
			if ($settings['dev_mode'] == 'tun') {
1188 a0e3ee98 jim-p
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1189 ef00af3c Phil Davis
			} else {
1190 60f501ec Phil Davis
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
1191 ef00af3c Phil Davis
			}
1192 a0e3ee98 jim-p
		}
1193
1194 a6d55c23 Chris Buechler
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
1195 348c2af1 jim-p
			$up_file = "{$g['openvpn_base']}/{$mode_id}/up";
1196 5f242576 PiBa-NL
			$conf .= "auth-user-pass {$up_file}\n";
1197 a69a9182 jim-p
			if (!$settings['auth-retry-none']) {
1198
				$conf .= "auth-retry nointeract\n";
1199
			}
1200 7304c023 Phil Davis
			if ($settings['auth_user']) {
1201 4de8f7ba Phil Davis
				$userpass = "{$settings['auth_user']}\n";
1202 7304c023 Phil Davis
			} else {
1203
				$userpass = "";
1204
			}
1205
			if ($settings['auth_pass']) {
1206 4de8f7ba Phil Davis
				$userpass .= "{$settings['auth_pass']}\n";
1207 7304c023 Phil Davis
			}
1208
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
1209
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
1210
				$userpass .= "\n";
1211
			}
1212 5f242576 PiBa-NL
			file_put_contents($up_file, $userpass);
1213
		}
1214 42bb1bee Renato Botelho
1215 762a24a3 Ermal Lu?i
		if ($settings['proxy_addr']) {
1216
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1217
			if ($settings['proxy_authtype'] != "none") {
1218 348c2af1 jim-p
				$conf .= " {$g['openvpn_base']}/{$mode_id}/proxy_auth {$settings['proxy_authtype']}";
1219 762a24a3 Ermal Lu?i
				$proxypas = "{$settings['proxy_user']}\n";
1220
				$proxypas .= "{$settings['proxy_passwd']}\n";
1221 348c2af1 jim-p
				file_put_contents("{$g['openvpn_base']}/{$mode_id}/proxy_auth", $proxypas);
1222 762a24a3 Ermal Lu?i
			}
1223
			$conf .= " \n";
1224
		}
1225 8dc3ef67 Scott Ullrich
	}
1226
1227 17c98ba9 jim-p
	// Add a remote network route if set, and only for p2p modes.
1228 54285411 jim-p
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
1229 a28d40cb jim-p
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1230 8dc3ef67 Scott Ullrich
	}
1231 4856df9b jim-p
	// Add a remote network route if set, and only for p2p modes.
1232 54285411 jim-p
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
1233 a28d40cb jim-p
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1234 4856df9b jim-p
	}
1235 afb07cf1 Scott Ullrich
1236 d799787e Matthew Grooms
	// Write the settings for the keys
1237 ef00af3c Phil Davis
	switch ($settings['mode']) {
1238 3c11bd3c Matthew Grooms
		case 'p2p_shared_key':
1239
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
1240
			break;
1241
		case 'p2p_tls':
1242
		case 'server_tls':
1243
		case 'server_tls_user':
1244 e62e2f8b Ermal Lu?i
		case 'server_user':
1245 348c2af1 jim-p
			// ca_chain_array() expects parameter to be passed by reference.
1246 179377b0 robjarsen
			// avoid passing the whole settings array, as param names or
1247
			// types might change in future releases.
1248
			$param = array('caref' => $settings['caref']);
1249 348c2af1 jim-p
			$cas = ca_chain_array($param);
1250
			$capath = "{$g['openvpn_base']}/{$mode_id}/ca";
1251
			/* Cleanup old CA/CRL references */
1252
			@unlink_if_exists("{$capath}.*0");
1253
			/* Find the CRL listed in the settings */
1254
			if (!empty($settings['crlref'])) {
1255
				$crl = lookup_crl($settings['crlref']);
1256
				crl_update($crl);
1257
			}
1258
			/* For each CA in the chain, setup the CApath */
1259
			foreach ($cas as $ca) {
1260
				ca_setup_capath($ca, $capath, $crl);
1261
			}
1262
			$conf .= "capath {$capath}\n";
1263
			unset($cas, $param);
1264 2da48592 jim-p
1265
			if (!empty($settings['certref'])) {
1266
				$cert = lookup_cert($settings['certref']);
1267
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
1268
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
1269
			}
1270 ef00af3c Phil Davis
			if ($mode == 'server') {
1271 f888c35a jim-p
				if (is_numeric($settings['dh_length'])) {
1272 c6668aba Phil Davis
					if (!in_array($settings['dh_length'], array_keys($openvpn_dh_lengths))) {
1273 f888c35a jim-p
						/* The user selected a DH parameter length that does not have a corresponding file. */
1274
						log_error(gettext("Failed to construct OpenVPN server configuration. The selected DH Parameter length cannot be used."));
1275
						return;
1276
					}
1277
					$dh_file = "{$g['etc_path']}/dh-parameters.{$settings['dh_length']}";
1278
				} else {
1279
					$dh_file = $settings['dh_length'];
1280
				}
1281
				$conf .= "dh {$dh_file}\n";
1282
				if (!empty($settings['ecdh_curve']) && ($settings['ecdh_curve'] != "none") && openvpn_validate_curve($settings['ecdh_curve'])) {
1283
					$conf .= "ecdh-curve {$settings['ecdh_curve']}\n";
1284
				}
1285 ef00af3c Phil Davis
			}
1286 db746ce2 Ermal Lu?i
			if ($settings['tls']) {
1287 c854afcc jim-p
				if ($settings['tls_type'] == "crypt") {
1288
					$tls_directive = "tls-crypt";
1289
					$tlsopt = "";
1290 ef00af3c Phil Davis
				} else {
1291 c854afcc jim-p
					$tls_directive = "tls-auth";
1292
					if ($mode == "server") {
1293 8698f918 Vito Piserchia
						switch($settings['tlsauth_keydir']){
1294
							case '1':
1295
								$tlsopt = 1;
1296
								break;
1297
							case '2':
1298
								$tlsopt = '';
1299
								break;
1300
							default:
1301
								$tlsopt = 0;
1302
								break;
1303
						}
1304 c854afcc jim-p
					} else {
1305 8698f918 Vito Piserchia
						switch($settings['tlsauth_keydir']){
1306
							case '0':
1307
								$tlsopt = 0;
1308
								break;
1309
							case '2':
1310
								$tlsopt = '';
1311
								break;
1312
							default:
1313
								$tlsopt = 1;
1314
								break;
1315
						}
1316 c854afcc jim-p
					}
1317 ef00af3c Phil Davis
				}
1318 c854afcc jim-p
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, $tls_directive, $tlsopt);
1319 db746ce2 Ermal Lu?i
			}
1320 3c11bd3c Matthew Grooms
			break;
1321 8dc3ef67 Scott Ullrich
	}
1322
1323 924eeefb jim-p
	/* Data encryption cipher support.
1324
	 * If it is not set, assume enabled since that is OpenVPN's default.
1325
	 * Note that diabling this is now deprecated and will be removed in a future version of OpenVPN */
1326
	if ($settings['ncp_enable'] == "disabled") {
1327
		$conf .= "ncp-disable\n";
1328
		$conf .= "cipher {$fbcipher}\n";
1329
	} else {
1330
		$conf .= "data-ciphers " . str_replace(',', ':', openvpn_build_data_cipher_list($settings['data_ciphers'], $fbcipher)) . "\n";
1331
		$conf .= "data-ciphers-fallback {$fbcipher}\n";
1332
	}
1333
1334 56e031a7 jim-p
	if (!empty($settings['allow_compression'])) {
1335
		$conf .= "allow-compression {$settings['allow_compression']}\n";
1336
	}
1337
1338 a4b36246 jim-p
	$compression = "";
1339
	switch ($settings['compression']) {
1340 38922574 jim-p
		case 'none':
1341
			$settings['compression'] = '';
1342 a4b36246 jim-p
		case 'lz4':
1343
		case 'lz4-v2':
1344
		case 'lzo':
1345
		case 'stub':
1346 38922574 jim-p
		case 'stub-v2':
1347 a4b36246 jim-p
			$compression .= "compress {$settings['compression']}";
1348
			break;
1349
		case 'noadapt':
1350
			$compression .= "comp-noadapt";
1351
			break;
1352
		case 'adaptive':
1353
		case 'yes':
1354
		case 'no':
1355
			$compression .= "comp-lzo {$settings['compression']}";
1356
			break;
1357
		default:
1358
			/* Add nothing to the configuration */
1359
			break;
1360
	}
1361
1362 16fe7982 jim-p
	if (($settings['allow_compression'] != 'no') &&
1363
	    !empty($compression)) {
1364 a4b36246 jim-p
		$conf .= "{$compression}\n";
1365
		if ($settings['compression_push']) {
1366
			$conf .= "push \"{$compression}\"\n";
1367 9446ee68 jim-p
		}
1368 ef00af3c Phil Davis
	}
1369 d799787e Matthew Grooms
1370 ef00af3c Phil Davis
	if ($settings['passtos']) {
1371 d799787e Matthew Grooms
		$conf .= "passtos\n";
1372 ef00af3c Phil Davis
	}
1373 d799787e Matthew Grooms
1374 919a0f4a jim-p
	if ($mode == 'client') {
1375 30640018 Chris Buechler
		$conf .= "resolv-retry infinite\n";
1376 ef00af3c Phil Davis
	}
1377 d799787e Matthew Grooms
1378
	if ($settings['dynamic_ip']) {
1379
		$conf .= "persist-remote-ip\n";
1380
		$conf .= "float\n";
1381 8dc3ef67 Scott Ullrich
	}
1382 afb07cf1 Scott Ullrich
1383 ef378560 jim-p
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1384 4742e635 Chris Buechler
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1385 63646f4d jim-p
		if (empty($settings['topology'])) {
1386
			$settings['topology'] = "subnet";
1387
		}
1388
		$conf .= "topology {$settings['topology']}\n";
1389 ee55ce7d jim-p
	}
1390
1391 b9e9903d Dmitriy K.
	// New client features
1392
	if ($mode == "client") {
1393
		// Dont add/remove routes checkbox
1394
		if ($settings['route_no_exec']) {
1395
			$conf .= "route-noexec\n";
1396
		}
1397
	}
1398
1399 2df5d9ee jim-p
	/* UDP Fast I/O. Only compatible with UDP and also not compatible with OpenVPN's "shaper" directive. */
1400
	if ($settings['udp_fast_io']
1401
	    && (strtolower(substr($settings['protocol'], 0, 3)) == "udp")
1402
	    && (empty($settings['use_shaper']))) {
1403
		$conf .= "fast-io\n";
1404
	}
1405
1406 7591a72a jim-p
	/* Exit Notify. Only compatible with UDP. */
1407
	if (!empty($settings['exit_notify']) &&
1408
	    is_numericint($settings['exit_notify']) &&
1409
	    (strtolower(substr($settings['protocol'], 0, 3)) == "udp")) {
1410
		$conf .= "explicit-exit-notify {$settings['exit_notify']}\n";
1411
	}
1412
1413 7618a842 jim-p
	/* Send and Receive Buffer Settings */
1414
	if (is_numericint($settings['sndrcvbuf'])
1415
	    && ($settings['sndrcvbuf'] > 0)
1416
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1417
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1418
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1419
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1420
	}
1421
1422 d799787e Matthew Grooms
	openvpn_add_custom($settings, $conf);
1423
1424 97af9f20 Viktor G
	/* add nopull option after custom options, see https://redmine.pfsense.org/issues/11448 */
1425
	if (($mode == "client") && $settings['route_no_pull']) {
1426
		// Dont pull routes checkbox
1427
		$conf .= "route-nopull\n";
1428
	}
1429
1430 a8f538a8 jim-p
	openvpn_create_dirs();
1431 348c2af1 jim-p
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1432 d799787e Matthew Grooms
	file_put_contents($fpath, $conf);
1433 938fc5b0 Ermal
	unset($conf);
1434 348c2af1 jim-p
	$fpath = "{$g['openvpn_base']}/{$mode_id}/interface";
1435 be00850b Phil Davis
	file_put_contents($fpath, $interface);
1436 f9ac3784 Ermal Lu?i
	//chown($fpath, 'nobody');
1437
	//chgrp($fpath, 'nobody');
1438 348c2af1 jim-p
	@chmod("{$g['openvpn_base']}/{$mode_id}/config.ovpn", 0600);
1439
	@chmod("{$g['openvpn_base']}/{$mode_id}/interface", 0600);
1440
	@chmod("{$g['openvpn_base']}/{$mode_id}/key", 0600);
1441
	@chmod("{$g['openvpn_base']}/{$mode_id}/tls-auth", 0600);
1442
	@chmod("{$g['openvpn_base']}/{$mode_id}/conf", 0600);
1443 5280fd8d Renato Botelho
1444
	if ($wait_tentative) {
1445
		interface_wait_tentative($interface);
1446
	}
1447 d799787e Matthew Grooms
}
1448
1449 fc05822b jim-p
function openvpn_restart($mode, $settings) {
1450 d799787e Matthew Grooms
	global $g, $config;
1451
1452
	$vpnid = $settings['vpnid'];
1453
	$mode_id = $mode.$vpnid;
1454 ce983754 PiBa-NL
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1455 8845e137 PiBa-NL
	openvpn_reconfigure($mode, $settings);
1456 76369bfc Matthew Grooms
	/* kill the process if running */
1457 705c8ec9 Matthew Grooms
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1458 76369bfc Matthew Grooms
	if (file_exists($pfile)) {
1459 705c8ec9 Matthew Grooms
1460 76369bfc Matthew Grooms
		/* read the pid file */
1461
		$pid = rtrim(file_get_contents($pfile));
1462
		unlink($pfile);
1463 8845e137 PiBa-NL
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1464 705c8ec9 Matthew Grooms
1465 76369bfc Matthew Grooms
		/* send a term signal to the process */
1466
		posix_kill($pid, SIGTERM);
1467
1468 93ead355 Chris Buechler
		/* wait until the process exits, or timeout and kill it */
1469
		$i = 0;
1470 ef00af3c Phil Davis
		while (posix_kill($pid, 0)) {
1471 76369bfc Matthew Grooms
			usleep(250000);
1472 93ead355 Chris Buechler
			if ($i > 10) {
1473 e8c516a0 Phil Davis
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1474 93ead355 Chris Buechler
				posix_kill($pid, SIGKILL);
1475 02a2bffa Chris Buechler
				usleep(500000);
1476 93ead355 Chris Buechler
			}
1477
			$i++;
1478
		}
1479 76369bfc Matthew Grooms
	}
1480 d799787e Matthew Grooms
1481 ef00af3c Phil Davis
	if (isset($settings['disable'])) {
1482 ce983754 PiBa-NL
		unlock($lockhandle);
1483 d799787e Matthew Grooms
		return;
1484 ef00af3c Phil Davis
	}
1485 d799787e Matthew Grooms
1486 f003f8db jim-p
	/* Do not start an instance if we are not CARP master on this vip! */
1487 ddf99718 Phil Davis
	if (strstr($settings['interface'], "_vip") && !in_array(get_carp_interface_status($settings['interface']), array("MASTER", ""))) {
1488 ce983754 PiBa-NL
		unlock($lockhandle);
1489 9ea0cb90 jim-p
		return;
1490 ef00af3c Phil Davis
	}
1491 42bb1bee Renato Botelho
1492
	/* Check if client is bound to a gateway group */
1493 43a9b03d PiBa-NL
	$a_groups = return_gateway_groups_array(true);
1494 330ecea1 Shahid Sheikh
	if (is_array($a_groups[$settings['interface']])) {
1495 ef00af3c Phil Davis
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1496 ddf99718 Phil Davis
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1497 ce983754 PiBa-NL
			unlock($lockhandle);
1498 330ecea1 Shahid Sheikh
			return;
1499 ef00af3c Phil Davis
		}
1500 330ecea1 Shahid Sheikh
	}
1501 9ea0cb90 jim-p
1502 705c8ec9 Matthew Grooms
	/* start the new process */
1503 348c2af1 jim-p
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1504 91c44185 jim-p
	openvpn_clear_route($mode, $settings);
1505 8845e137 PiBa-NL
	$res = mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1506
	if ($res == 0) {
1507
		$i = 0;
1508
		$pid = "--";
1509
		while ($i < 3000) {
1510 a1b39e94 PiBa-NL
			if (isvalidpid($pfile)) {
1511 8845e137 PiBa-NL
				$pid = rtrim(file_get_contents($pfile));
1512 a1b39e94 PiBa-NL
				break;
1513 8845e137 PiBa-NL
			}
1514
			usleep(1000);
1515
			$i++;
1516
		}
1517
		syslog(LOG_INFO, "OpenVPN PID written: {$pid}");
1518
	} else {
1519
		syslog(LOG_ERR, "OpenVPN failed to start");
1520
	}
1521 ef00af3c Phil Davis
	if (!platform_booting()) {
1522 847cd48d Ermal
		send_event("filter reload");
1523 ef00af3c Phil Davis
	}
1524 ce983754 PiBa-NL
	unlock($lockhandle);
1525 afb07cf1 Scott Ullrich
}
1526
1527 9272a448 Renato Botelho
function openvpn_delete($mode, $settings) {
1528 d799787e Matthew Grooms
	global $g, $config;
1529
1530
	$vpnid = $settings['vpnid'];
1531
	$mode_id = $mode.$vpnid;
1532
1533 ef00af3c Phil Davis
	if ($mode == "server") {
1534 095a95ae Matthew Grooms
		$devname = "ovpns{$vpnid}";
1535 ef00af3c Phil Davis
	} else {
1536 095a95ae Matthew Grooms
		$devname = "ovpnc{$vpnid}";
1537 ef00af3c Phil Davis
	}
1538 dc408939 Matthew Grooms
1539 76369bfc Matthew Grooms
	/* kill the process if running */
1540 dc408939 Matthew Grooms
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1541 76369bfc Matthew Grooms
	if (file_exists($pfile)) {
1542 dc408939 Matthew Grooms
1543 76369bfc Matthew Grooms
		/* read the pid file */
1544
		$pid = trim(file_get_contents($pfile));
1545
		unlink($pfile);
1546
1547
		/* send a term signal to the process */
1548
		posix_kill($pid, SIGTERM);
1549
	}
1550 705c8ec9 Matthew Grooms
1551 3b1642ff Renato Botelho
	/* destroy the device */
1552
	pfSense_interface_destroy($devname);
1553 dc408939 Matthew Grooms
1554 7d813139 batnas
	/* Invalidate cache */
1555
	get_interface_arr(true);
1556
1557 dc408939 Matthew Grooms
	/* remove the configuration files */
1558 93830bec Viktor G
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*/*");
1559
	unlink_if_exists("{$g['openvpn_base']}/{$mode_id}/*");
1560 d799787e Matthew Grooms
}
1561 afb07cf1 Scott Ullrich
1562 dc408939 Matthew Grooms
function openvpn_resync_csc(& $settings) {
1563 154b0f80 jim-p
	global $g, $config, $openvpn_tls_server_modes;
1564 a1cab2c7 Ermal
	if (isset($settings['disable'])) {
1565 4e5e7540 jim-p
		openvpn_delete_csc($settings);
1566 c876662c Scott Ullrich
		return;
1567
	}
1568 a8f538a8 jim-p
	openvpn_create_dirs();
1569 d799787e Matthew Grooms
1570 154b0f80 jim-p
	if (empty($settings['server_list'])) {
1571
		$csc_server_list = array();
1572
	} else {
1573
		$csc_server_list = explode(",", $settings['server_list']);
1574
	}
1575
1576 8dc3ef67 Scott Ullrich
	$conf = '';
1577 ef00af3c Phil Davis
	if ($settings['block']) {
1578 d799787e Matthew Grooms
		$conf .= "disable\n";
1579 ef00af3c Phil Davis
	}
1580 d799787e Matthew Grooms
1581 ef00af3c Phil Davis
	if ($settings['push_reset']) {
1582 d799787e Matthew Grooms
		$conf .= "push-reset\n";
1583 ef00af3c Phil Davis
	}
1584 d799787e Matthew Grooms
1585 8d44d56a Viktor G
	if ($settings['remove_route']) {
1586
		$conf .= "push-remove route\n";
1587
	}
1588
1589 5c427ce7 jim-p
	if ($settings['local_network']) {
1590
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1591
	}
1592
	if ($settings['local_networkv6']) {
1593
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1594
	}
1595
1596
	// Add a remote network iroute if set
1597
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1598
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1599
	}
1600
	// Add a remote network iroute if set
1601
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1602
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1603
	}
1604
1605 d799787e Matthew Grooms
	openvpn_add_dhcpopts($settings, $conf);
1606 8dc3ef67 Scott Ullrich
1607 d799787e Matthew Grooms
	openvpn_add_custom($settings, $conf);
1608 154b0f80 jim-p
	/* Loop through servers, find which ones can use this CSC */
1609
	if (is_array($config['openvpn']['openvpn-server'])) {
1610
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1611
			if (isset($serversettings['disable'])) {
1612
				continue;
1613
			}
1614
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1615
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1616 348c2af1 jim-p
					$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1617 154b0f80 jim-p
					$csc_conf = $conf;
1618
1619 cd8f2f2b jim-p
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1620 966cdb43 jim-p
						list($ip, $mask) = explode('/', trim($settings['tunnel_network']));
1621 154b0f80 jim-p
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1622
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1623
						} else {
1624
							/* Because this is being pushed, the order from the client's point of view. */
1625 493e6807 stilez
							$baselong = gen_subnetv4($ip, $mask);
1626
							$serverip = ip_after($baselong, 1);
1627
							$clientip = ip_after($baselong, 2);
1628 154b0f80 jim-p
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1629
						}
1630
					}
1631 b6dd335e jim-p
1632
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1633
						list($ipv6, $prefix) = explode('/', trim($serversettings['tunnel_networkv6']));
1634
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1635
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1636
					}
1637
1638 154b0f80 jim-p
					file_put_contents($csc_path, $csc_conf);
1639
					chown($csc_path, 'nobody');
1640
					chgrp($csc_path, 'nobody');
1641
				}
1642
			}
1643
		}
1644
	}
1645 d799787e Matthew Grooms
}
1646 8dc3ef67 Scott Ullrich
1647 1f954318 jim-p
function openvpn_resync_csc_all() {
1648
	global $config;
1649
	if (is_array($config['openvpn']['openvpn-csc'])) {
1650
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1651
			openvpn_resync_csc($settings);
1652
		}
1653
	}
1654
}
1655
1656 dc408939 Matthew Grooms
function openvpn_delete_csc(& $settings) {
1657 154b0f80 jim-p
	global $g, $config, $openvpn_tls_server_modes;
1658
	if (empty($settings['server_list'])) {
1659
		$csc_server_list = array();
1660
	} else {
1661
		$csc_server_list = explode(",", $settings['server_list']);
1662
	}
1663 3c2e5528 Scott Ullrich
1664 154b0f80 jim-p
	/* Loop through servers, find which ones used this CSC */
1665
	if (is_array($config['openvpn']['openvpn-server'])) {
1666
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1667
			if (isset($serversettings['disable'])) {
1668
				continue;
1669
			}
1670
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1671
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1672 348c2af1 jim-p
					$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1673 154b0f80 jim-p
					unlink_if_exists($csc_path);
1674
				}
1675
			}
1676
		}
1677
	}
1678 267ab13f Ermal Luçi
}
1679 afb07cf1 Scott Ullrich
1680 24012690 Scott Ullrich
// Resync the configuration and restart the VPN
1681 fc05822b jim-p
function openvpn_resync($mode, $settings) {
1682 dc408939 Matthew Grooms
	openvpn_restart($mode, $settings);
1683 afb07cf1 Scott Ullrich
}
1684
1685 add2e3f7 Scott Ullrich
// Resync and restart all VPNs
1686 c7f60193 Ermal
function openvpn_resync_all($interface = "") {
1687 d799787e Matthew Grooms
	global $g, $config;
1688 267ab13f Ermal Luçi
1689 a8f538a8 jim-p
	openvpn_create_dirs();
1690 3cb54b54 Matthew Grooms
1691 ef00af3c Phil Davis
	if (!is_array($config['openvpn'])) {
1692 34bc1324 Matthew Grooms
		$config['openvpn'] = array();
1693 ef00af3c Phil Davis
	}
1694 34bc1324 Matthew Grooms
1695 ef00af3c Phil Davis
	if ($interface <> "") {
1696 e8c516a0 Phil Davis
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1697 ef00af3c Phil Davis
	} else {
1698 e8c516a0 Phil Davis
		log_error(gettext("Resyncing OpenVPN instances."));
1699 ef00af3c Phil Davis
	}
1700 34bc1324 Matthew Grooms
1701 7071aab3 James Webb
	// Check if OpenVPN clients and servers require a resync.
1702 f7335af3 Renato Botelho do Couto
	foreach (array("server", "client") as $type) {
1703
		if (!is_array($config['openvpn']["openvpn-{$type}"])) {
1704
			continue;
1705 c7f60193 Ermal
		}
1706 f7335af3 Renato Botelho do Couto
		foreach ($config['openvpn']["openvpn-{$type}"] as & $settings) {
1707 348c2af1 jim-p
			$fpath = "{$g['openvpn_base']}/{$type}{$settings['vpnid']}/interface";
1708 7071aab3 James Webb
			$gw_group_change = FALSE;
1709 f7335af3 Renato Botelho do Couto
			$ip_change = ($interface === "") ||
1710
			    ($interface === $settings['interface']);
1711
1712 15f8062b James Webb
			if (!$ip_change && file_exists($fpath)) {
1713 f7335af3 Renato Botelho do Couto
				$gw_group_change =
1714
				    (trim(file_get_contents($fpath), " \t\n") !=
1715
				    get_failover_interface(
1716
					$settings['interface']));
1717 7071aab3 James Webb
			}
1718 f7335af3 Renato Botelho do Couto
1719 15f8062b James Webb
			if ($ip_change || $gw_group_change) {
1720 f7335af3 Renato Botelho do Couto
				openvpn_resync($type, $settings);
1721 ef00af3c Phil Davis
			}
1722 c7f60193 Ermal
		}
1723
	}
1724 afb07cf1 Scott Ullrich
1725 1f954318 jim-p
	openvpn_resync_csc_all();
1726 afb07cf1 Scott Ullrich
1727 5b237745 Scott Ullrich
}
1728 702a4702 Scott Ullrich
1729 99cc103b Phil Davis
// Resync and restart all VPNs using a gateway group.
1730
function openvpn_resync_gwgroup($gwgroupname = "") {
1731
	global $g, $config;
1732
1733
	if ($gwgroupname <> "") {
1734
		if (is_array($config['openvpn']['openvpn-server'])) {
1735
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1736
				if ($gwgroupname == $settings['interface']) {
1737 e8c516a0 Phil Davis
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1738 99cc103b Phil Davis
					openvpn_resync('server', $settings);
1739
				}
1740
			}
1741
		}
1742
1743
		if (is_array($config['openvpn']['openvpn-client'])) {
1744
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1745
				if ($gwgroupname == $settings['interface']) {
1746 e8c516a0 Phil Davis
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1747 99cc103b Phil Davis
					openvpn_resync('client', $settings);
1748
				}
1749
			}
1750
		}
1751
1752
		// Note: no need to resysnc Client Specific (csc) here, as changes to the OpenVPN real interface do not effect these.
1753
1754 ef00af3c Phil Davis
	} else {
1755 e8c516a0 Phil Davis
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1756 ef00af3c Phil Davis
	}
1757 99cc103b Phil Davis
}
1758
1759 453d9c96 jim-p
function openvpn_get_active_servers($type="multipoint") {
1760 71ca2cb2 Ermal
	global $config, $g;
1761
1762 53663f57 jim-p
	$servers = array();
1763
	if (is_array($config['openvpn']['openvpn-server'])) {
1764
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1765 ef00af3c Phil Davis
			if (empty($settings) || isset($settings['disable'])) {
1766 6b2dcac5 Ermal
				continue;
1767 ef00af3c Phil Davis
			}
1768 6b2dcac5 Ermal
1769 53663f57 jim-p
			$prot = $settings['protocol'];
1770
			$port = $settings['local_port'];
1771 42bb1bee Renato Botelho
1772 53663f57 jim-p
			$server = array();
1773 95305736 jim-p
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1774 41be629f jim-p
			$server['mode'] = $settings['mode'];
1775 ef00af3c Phil Davis
			if ($settings['description']) {
1776 53663f57 jim-p
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1777 ef00af3c Phil Davis
			} else {
1778 53663f57 jim-p
				$server['name'] = "Server {$prot}:{$port}";
1779 ef00af3c Phil Davis
			}
1780 53663f57 jim-p
			$server['conns'] = array();
1781 2eaa97b9 jim-p
			$server['vpnid'] = $settings['vpnid'];
1782
			$server['mgmt'] = "server{$server['vpnid']}";
1783 348c2af1 jim-p
			$socket = "unix://{$g['openvpn_base']}/{$server['mgmt']}/sock";
1784 966cdb43 jim-p
			list($tn, $sm) = explode('/', trim($settings['tunnel_network']));
1785 453d9c96 jim-p
1786 ef00af3c Phil Davis
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1787 95305736 jim-p
				$servers[] = openvpn_get_client_status($server, $socket);
1788 ef00af3c Phil Davis
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1789 95305736 jim-p
				$servers[] = openvpn_get_server_status($server, $socket);
1790 ef00af3c Phil Davis
			}
1791 95305736 jim-p
		}
1792
	}
1793
	return $servers;
1794
}
1795 b0140675 Ermal
1796 95305736 jim-p
function openvpn_get_server_status($server, $socket) {
1797 247c417f Sjon Hortensius
	$errval = null;
1798
	$errstr = null;
1799 95305736 jim-p
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1800
	if ($fp) {
1801
		stream_set_timeout($fp, 1);
1802
1803
		/* send our status request */
1804
		fputs($fp, "status 2\n");
1805
1806
		/* recv all response lines */
1807
		while (!feof($fp)) {
1808
1809
			/* read the next line */
1810
			$line = fgets($fp, 1024);
1811
1812
			$info = stream_get_meta_data($fp);
1813 ef00af3c Phil Davis
			if ($info['timed_out']) {
1814 95305736 jim-p
				break;
1815 ef00af3c Phil Davis
			}
1816 95305736 jim-p
1817
			/* parse header list line */
1818 ef00af3c Phil Davis
			if (strstr($line, "HEADER")) {
1819 95305736 jim-p
				continue;
1820 ef00af3c Phil Davis
			}
1821 95305736 jim-p
1822
			/* parse end of output line */
1823 ef00af3c Phil Davis
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1824 95305736 jim-p
				break;
1825 ef00af3c Phil Davis
			}
1826 95305736 jim-p
1827
			/* parse client list line */
1828
			if (strstr($line, "CLIENT_LIST")) {
1829
				$list = explode(",", $line);
1830 53663f57 jim-p
				$conn = array();
1831 95305736 jim-p
				$conn['common_name'] = $list[1];
1832
				$conn['remote_host'] = $list[2];
1833
				$conn['virtual_addr'] = $list[3];
1834 6f17547a jim-p
				$conn['virtual_addr6'] = $list[4];
1835
				$conn['bytes_recv'] = $list[5];
1836
				$conn['bytes_sent'] = $list[6];
1837
				$conn['connect_time'] = $list[7];
1838
				$conn['connect_time_unix'] = $list[8];
1839
				$conn['user_name'] = $list[9];
1840
				$conn['client_id'] = $list[10];
1841
				$conn['peer_id'] = $list[11];
1842 d7247886 Viktor G
				$conn['cipher'] = $list[12];
1843 53663f57 jim-p
				$server['conns'][] = $conn;
1844
			}
1845 ec970b50 jim-p
			/* parse routing table lines */
1846
			if (strstr($line, "ROUTING_TABLE")) {
1847
				$list = explode(",", $line);
1848
				$conn = array();
1849
				$conn['virtual_addr'] = $list[1];
1850
				$conn['common_name'] = $list[2];
1851
				$conn['remote_host'] = $list[3];
1852
				$conn['last_time'] = $list[4];
1853
				$server['routes'][] = $conn;
1854
			}
1855 53663f57 jim-p
		}
1856 95305736 jim-p
1857
		/* cleanup */
1858
		fclose($fp);
1859
	} else {
1860
		$conn = array();
1861
		$conn['common_name'] = "[error]";
1862 e8c516a0 Phil Davis
		$conn['remote_host'] = gettext("Unable to contact daemon");
1863
		$conn['virtual_addr'] = gettext("Service not running?");
1864 95305736 jim-p
		$conn['bytes_recv'] = 0;
1865
		$conn['bytes_sent'] = 0;
1866
		$conn['connect_time'] = 0;
1867
		$server['conns'][] = $conn;
1868 53663f57 jim-p
	}
1869 95305736 jim-p
	return $server;
1870 53663f57 jim-p
}
1871
1872
function openvpn_get_active_clients() {
1873 71ca2cb2 Ermal
	global $config, $g;
1874
1875 53663f57 jim-p
	$clients = array();
1876
	if (is_array($config['openvpn']['openvpn-client'])) {
1877
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1878 42bb1bee Renato Botelho
1879 ef00af3c Phil Davis
			if (empty($settings) || isset($settings['disable'])) {
1880 6b2dcac5 Ermal
				continue;
1881 ef00af3c Phil Davis
			}
1882 6b2dcac5 Ermal
1883 53663f57 jim-p
			$prot = $settings['protocol'];
1884 95305736 jim-p
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1885 42bb1bee Renato Botelho
1886 53663f57 jim-p
			$client = array();
1887
			$client['port'] = $settings['local_port'];
1888 ef00af3c Phil Davis
			if ($settings['description']) {
1889 95305736 jim-p
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1890 ef00af3c Phil Davis
			} else {
1891 95305736 jim-p
				$client['name'] = "Client {$prot}{$port}";
1892 ef00af3c Phil Davis
			}
1893 42bb1bee Renato Botelho
1894 2eaa97b9 jim-p
			$client['vpnid'] = $settings['vpnid'];
1895
			$client['mgmt'] = "client{$client['vpnid']}";
1896 348c2af1 jim-p
			$socket = "unix://{$g['openvpn_base']}/{$client['mgmt']}/sock";
1897 53663f57 jim-p
			$client['status']="down";
1898 95305736 jim-p
1899
			$clients[] = openvpn_get_client_status($client, $socket);
1900
		}
1901
	}
1902
	return $clients;
1903
}
1904
1905
function openvpn_get_client_status($client, $socket) {
1906 247c417f Sjon Hortensius
	$errval = null;
1907
	$errstr = null;
1908 95305736 jim-p
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1909
	if ($fp) {
1910
		stream_set_timeout($fp, 1);
1911
		/* send our status request */
1912
		fputs($fp, "state 1\n");
1913
1914
		/* recv all response lines */
1915
		while (!feof($fp)) {
1916
			/* read the next line */
1917
			$line = fgets($fp, 1024);
1918
1919
			$info = stream_get_meta_data($fp);
1920 ef00af3c Phil Davis
			if ($info['timed_out']) {
1921 95305736 jim-p
				break;
1922 ef00af3c Phil Davis
			}
1923 95305736 jim-p
1924
			/* Get the client state */
1925 4de8f7ba Phil Davis
			if (strstr($line, "CONNECTED")) {
1926
				$client['status'] = "up";
1927 95305736 jim-p
				$list = explode(",", $line);
1928
1929 4de8f7ba Phil Davis
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1930
				$client['virtual_addr'] = $list[3];
1931 95305736 jim-p
				$client['remote_host'] = $list[4];
1932 cbfd0754 jim-p
				$client['remote_port'] = $list[5];
1933
				$client['local_host'] = $list[6];
1934
				$client['local_port'] = $list[7];
1935
				$client['virtual_addr6'] = $list[8];
1936 95305736 jim-p
			}
1937 4de8f7ba Phil Davis
			if (strstr($line, "CONNECTING")) {
1938
				$client['status'] = "connecting";
1939 453d9c96 jim-p
			}
1940 4de8f7ba Phil Davis
			if (strstr($line, "ASSIGN_IP")) {
1941
				$client['status'] = "waiting";
1942 453d9c96 jim-p
				$list = explode(",", $line);
1943
1944 4de8f7ba Phil Davis
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1945
				$client['virtual_addr'] = $list[3];
1946 453d9c96 jim-p
			}
1947 4de8f7ba Phil Davis
			if (strstr($line, "RECONNECTING")) {
1948
				$client['status'] = "reconnecting";
1949 453d9c96 jim-p
				$list = explode(",", $line);
1950
1951 4de8f7ba Phil Davis
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1952 453d9c96 jim-p
				$client['status'] .= "; " . $list[2];
1953
			}
1954 95305736 jim-p
			/* parse end of output line */
1955 ef00af3c Phil Davis
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1956 95305736 jim-p
				break;
1957 ef00af3c Phil Davis
			}
1958 95305736 jim-p
		}
1959
1960
		/* If up, get read/write stats */
1961
		if (strcmp($client['status'], "up") == 0) {
1962
			fputs($fp, "status 2\n");
1963
			/* recv all response lines */
1964
			while (!feof($fp)) {
1965
				/* read the next line */
1966
				$line = fgets($fp, 1024);
1967
1968
				$info = stream_get_meta_data($fp);
1969 ef00af3c Phil Davis
				if ($info['timed_out']) {
1970 95305736 jim-p
					break;
1971 ef00af3c Phil Davis
				}
1972 95305736 jim-p
1973 4de8f7ba Phil Davis
				if (strstr($line, "TCP/UDP read bytes")) {
1974 95305736 jim-p
					$list = explode(",", $line);
1975
					$client['bytes_recv'] = $list[1];
1976 53663f57 jim-p
				}
1977 95305736 jim-p
1978 4de8f7ba Phil Davis
				if (strstr($line, "TCP/UDP write bytes")) {
1979 95305736 jim-p
					$list = explode(",", $line);
1980
					$client['bytes_sent'] = $list[1];
1981 53663f57 jim-p
				}
1982 95305736 jim-p
1983
				/* parse end of output line */
1984 ef00af3c Phil Davis
				if (strstr($line, "END")) {
1985 95305736 jim-p
					break;
1986 ef00af3c Phil Davis
				}
1987 53663f57 jim-p
			}
1988
		}
1989 95305736 jim-p
1990
		fclose($fp);
1991
1992
	} else {
1993 e8c516a0 Phil Davis
		$client['remote_host'] = gettext("Unable to contact daemon");
1994
		$client['virtual_addr'] = gettext("Service not running?");
1995 95305736 jim-p
		$client['bytes_recv'] = 0;
1996
		$client['bytes_sent'] = 0;
1997
		$client['connect_time'] = 0;
1998 53663f57 jim-p
	}
1999 95305736 jim-p
	return $client;
2000 53663f57 jim-p
}
2001 8e022a76 jim-p
2002 61fce4a6 Phil Davis
function openvpn_kill_client($port, $remipp) {
2003
	global $g;
2004
2005
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
2006 348c2af1 jim-p
	$tcpsrv = "unix://{$g['openvpn_base']}/{$port}/sock";
2007 61fce4a6 Phil Davis
	$errval = null;
2008
	$errstr = null;
2009
2010
	/* open a tcp connection to the management port of each server */
2011
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
2012
	$killed = -1;
2013
	if ($fp) {
2014
		stream_set_timeout($fp, 1);
2015
		fputs($fp, "kill {$remipp}\n");
2016
		while (!feof($fp)) {
2017
			$line = fgets($fp, 1024);
2018
2019
			$info = stream_get_meta_data($fp);
2020
			if ($info['timed_out']) {
2021
				break;
2022
			}
2023
2024
			/* parse header list line */
2025
			if (strpos($line, "INFO:") !== false) {
2026
				continue;
2027
			}
2028
			if (strpos($line, "SUCCESS") !== false) {
2029
				$killed = 0;
2030
			}
2031
			break;
2032
		}
2033
		fclose($fp);
2034
	}
2035
	return $killed;
2036
}
2037
2038 8e022a76 jim-p
function openvpn_refresh_crls() {
2039
	global $g, $config;
2040
2041 a8f538a8 jim-p
	openvpn_create_dirs();
2042 8e022a76 jim-p
2043
	if (is_array($config['openvpn']['openvpn-server'])) {
2044
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2045 ef00af3c Phil Davis
			if (empty($settings)) {
2046 8e022a76 jim-p
				continue;
2047 ef00af3c Phil Davis
			}
2048
			if (isset($settings['disable'])) {
2049 8e022a76 jim-p
				continue;
2050 ef00af3c Phil Davis
			}
2051 8e022a76 jim-p
			// Write the settings for the keys
2052 ef00af3c Phil Davis
			switch ($settings['mode']) {
2053 8e022a76 jim-p
				case 'p2p_tls':
2054
				case 'server_tls':
2055
				case 'server_tls_user':
2056
				case 'server_user':
2057 348c2af1 jim-p
					$param = array('caref' => $settings['caref']);
2058
					$cas = ca_chain_array($param);
2059 475d712b jim-p
					$capath = "{$g['openvpn_base']}/server{$settings['vpnid']}/ca";
2060 8e022a76 jim-p
					if (!empty($settings['crlref'])) {
2061
						$crl = lookup_crl($settings['crlref']);
2062 728003c8 jim-p
						crl_update($crl);
2063 348c2af1 jim-p
					}
2064
					foreach ($cas as $ca) {
2065 475d712b jim-p
						ca_setup_capath($ca, $capath, $crl, true);
2066 8e022a76 jim-p
					}
2067 f61a794a jim-p
					unset($cas, $param, $capath, $crl);
2068 8e022a76 jim-p
					break;
2069
			}
2070
		}
2071
	}
2072
}
2073
2074 a8f538a8 jim-p
function openvpn_create_dirs() {
2075 154b0f80 jim-p
	global $g, $config, $openvpn_tls_server_modes;
2076 348c2af1 jim-p
	if (!is_dir($g['openvpn_base'])) {
2077
		safe_mkdir($g['openvpn_base'], 0750);
2078 ef00af3c Phil Davis
	}
2079 154b0f80 jim-p
2080 348c2af1 jim-p
	init_config_arr(array('openvpn', 'openvpn-server'));
2081
	init_config_arr(array('openvpn', 'openvpn-client'));
2082
	foreach(array('server', 'client') as $mode) {
2083
		foreach ($config['openvpn']["openvpn-{$mode}"] as $settings) {
2084
			$target = "{$g['openvpn_base']}/{$mode}{$settings['vpnid']}";
2085
			@unlink_if_exists($csctarget);
2086
			@safe_mkdir($target);
2087 154b0f80 jim-p
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2088
				if ($settings['vpnid']) {
2089 348c2af1 jim-p
					$csctarget = "{$target}/csc/";
2090
					@unlink_if_exists($csctarget);
2091
					@safe_mkdir($csctarget);
2092 154b0f80 jim-p
				}
2093
			}
2094
		}
2095
	}
2096 a8f538a8 jim-p
}
2097
2098 30c8a290 Renato Botelho
function openvpn_get_interface_ip($ip, $cidr) {
2099
	$subnet = gen_subnetv4($ip, $cidr);
2100 10a8b5ee PiBa-NL
	if ($cidr == 31) {
2101
		$ip1 = $subnet;
2102
	} else {
2103
		$ip1 = ip_after($subnet);
2104
	}
2105 30c8a290 Renato Botelho
	$ip2 = ip_after($ip1);
2106 91c44185 jim-p
	return array($ip1, $ip2);
2107
}
2108
2109
function openvpn_get_interface_ipv6($ipv6, $prefix) {
2110
	$basev6 = gen_subnetv6($ipv6, $prefix);
2111
	// Is there a better way to do this math?
2112
	$ipv6_arr = explode(':', $basev6);
2113
	$last = hexdec(array_pop($ipv6_arr));
2114 10a8b5ee PiBa-NL
	if ($prefix == 127) {
2115
		$last--;
2116
	}
2117 587995fb Phil Davis
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
2118
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
2119 91c44185 jim-p
	return array($ipv6_1, $ipv6_2);
2120
}
2121
2122
function openvpn_clear_route($mode, $settings) {
2123 ef00af3c Phil Davis
	if (empty($settings['tunnel_network'])) {
2124 91c44185 jim-p
		return;
2125 ef00af3c Phil Davis
	}
2126 966cdb43 jim-p
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
2127 91c44185 jim-p
	$mask = gen_subnet_mask($cidr);
2128 6ca938cf jim-p
	$clear_route = false;
2129
2130 ef00af3c Phil Davis
	switch ($settings['mode']) {
2131 6ca938cf jim-p
		case 'shared_key':
2132
			$clear_route = true;
2133
			break;
2134 91c44185 jim-p
		case 'p2p_tls':
2135
		case 'p2p_shared_key':
2136 a0f991ec PiBa-NL
			if ($cidr >= 30) {
2137 6ca938cf jim-p
				$clear_route = true;
2138 ef00af3c Phil Davis
			}
2139 91c44185 jim-p
			break;
2140
	}
2141 6ca938cf jim-p
2142 6d0b9fe9 jim-p
	if ($clear_route && !empty($ip) && !empty($mask)) {
2143 30c8a290 Renato Botelho
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2144 6ca938cf jim-p
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2145 615d7f0a Ermal
		/* XXX: Family for route? */
2146 6ca938cf jim-p
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2147
	}
2148 91c44185 jim-p
}
2149
2150 5c427ce7 jim-p
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2151 a28d40cb jim-p
	$routes = "";
2152 ef00af3c Phil Davis
	if (empty($value)) {
2153 a28d40cb jim-p
		return "";
2154 ef00af3c Phil Davis
	}
2155 a28d40cb jim-p
	$networks = explode(',', $value);
2156
2157
	foreach ($networks as $network) {
2158 ef00af3c Phil Davis
		if ($ipproto == "ipv4") {
2159 5c427ce7 jim-p
			$route = openvpn_gen_route_ipv4($network, $iroute);
2160 ef00af3c Phil Davis
		} else {
2161 5c427ce7 jim-p
			$route = openvpn_gen_route_ipv6($network, $iroute);
2162 ef00af3c Phil Davis
		}
2163 a28d40cb jim-p
2164 ef00af3c Phil Davis
		if ($push) {
2165 a28d40cb jim-p
			$routes .= "push \"{$route}\"\n";
2166 ef00af3c Phil Davis
		} else {
2167 a28d40cb jim-p
			$routes .= "{$route}\n";
2168 ef00af3c Phil Davis
		}
2169 a28d40cb jim-p
	}
2170
	return $routes;
2171
}
2172
2173 5c427ce7 jim-p
function openvpn_gen_route_ipv4($network, $iroute = false) {
2174
	$i = ($iroute) ? "i" : "";
2175 a28d40cb jim-p
	list($ip, $mask) = explode('/', trim($network));
2176
	$mask = gen_subnet_mask($mask);
2177 5c427ce7 jim-p
	return "{$i}route $ip $mask";
2178 a28d40cb jim-p
}
2179
2180 5c427ce7 jim-p
function openvpn_gen_route_ipv6($network, $iroute = false) {
2181
	$i = ($iroute) ? "i" : "";
2182 a28d40cb jim-p
	list($ipv6, $prefix) = explode('/', trim($network));
2183 3000b44d Renato Botelho
	if (empty($prefix) && !is_numeric($prefix)) {
2184 a28d40cb jim-p
		$prefix = "128";
2185 ef00af3c Phil Davis
	}
2186 5c427ce7 jim-p
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2187 a28d40cb jim-p
}
2188
2189 699125b1 jim-p
function openvpn_get_settings($mode, $vpnid) {
2190
	global $config;
2191
2192
	if (is_array($config['openvpn']['openvpn-server'])) {
2193
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2194 ef00af3c Phil Davis
			if (isset($settings['disable'])) {
2195 699125b1 jim-p
				continue;
2196 ef00af3c Phil Davis
			}
2197 699125b1 jim-p
2198 ef00af3c Phil Davis
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2199 699125b1 jim-p
				return $settings;
2200 ef00af3c Phil Davis
			}
2201 699125b1 jim-p
		}
2202
	}
2203
2204
	if (is_array($config['openvpn']['openvpn-client'])) {
2205
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
2206 ef00af3c Phil Davis
			if (isset($settings['disable'])) {
2207 699125b1 jim-p
				continue;
2208 ef00af3c Phil Davis
			}
2209 699125b1 jim-p
2210 ef00af3c Phil Davis
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2211 699125b1 jim-p
				return $settings;
2212 ef00af3c Phil Davis
			}
2213 699125b1 jim-p
		}
2214
	}
2215
2216
	return array();
2217
}
2218
2219
function openvpn_restart_by_vpnid($mode, $vpnid) {
2220
	$settings = openvpn_get_settings($mode, $vpnid);
2221
	openvpn_restart($mode, $settings);
2222
}
2223
2224 19a0636d jim-p
/****f* certs/openvpn_is_tunnel_network_in_use
2225
 * NAME
2226
 *   openvpn_is_tunnel_network_in_use
2227
 *     Check if the supplied network is in use as an OpenVPN server or client
2228
 *     tunnel network
2229
 * INPUTS
2230
 *   $net : The IPv4 or IPv6 network to check
2231
 * RESULT
2232
 *   boolean value: true if the network is in use, false otherwise.
2233
 ******/
2234
2235
function openvpn_is_tunnel_network_in_use($net) {
2236
	global $config;
2237
	init_config_arr(array('openvpn', 'openvpn-server'));
2238
	init_config_arr(array('openvpn', 'openvpn-client'));
2239
	/* Determine whether to check IPv4 or IPv6 tunnel networks */
2240
	$tocheck = 'tunnel_network';
2241
	if (is_v6($net)) {
2242
		$tocheck .= "v6";
2243
	}
2244
	/* Check all OpenVPN clients and servers for this tunnel network */
2245
	foreach(array('server', 'client') as $mode) {
2246
		foreach ($config['openvpn']["openvpn-{$mode}"] as $ovpn) {
2247
			if (!empty($ovpn[$tocheck]) &&
2248
			    ($ovpn[$tocheck] == $net)) {
2249
				return true;
2250
			}
2251
		}
2252
	}
2253
	return false;
2254
}
2255 924eeefb jim-p
2256 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) {
2257 924eeefb jim-p
	/* If the data_ciphers list is empty, populate it with the fallback cipher. */
2258 3adc4134 jim-p
	if (empty($data_ciphers) || !$ncp_enabled) {
2259 924eeefb jim-p
		$data_ciphers = $fallback_cipher;
2260
	}
2261
	/* Add the fallback cipher to the data ciphers list if it isn't already present */
2262
	if (!in_array($fallback_cipher, explode(',', $data_ciphers))) {
2263
		$data_ciphers .= ',' . $fallback_cipher;
2264
	}
2265
	return $data_ciphers;
2266
}
2267
2268 c67222fc Viktor G
function openvpn_authscript_string($authmode, $strictusercn, $mode_id, $local_port) {
2269
	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";
2270
}
2271
2272 756720e2 Pierre POMES
?>