Project

General

Profile

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