Project

General

Profile

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