Project

General

Profile

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