openvpn.inc 40.5 KB
Newer Older
Ad Schellevis's avatar
Ad Schellevis committed
1 2
<?php

3
/*
Ad Schellevis's avatar
Ad Schellevis committed
4
	Copyright (C) 2008 Scott Ullrich <sullrich@gmail.com>
5
	Copyright (C) 2006 Fernando Lemos
Ad Schellevis's avatar
Ad Schellevis committed
6
	Copyright (C) 2005 Peter Allgeyer <allgeyer_AT_web.de>
7
	Copyright (C) 2004 Peter Curran <peter@closeconsultants.com>
Ad Schellevis's avatar
Ad Schellevis committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	1. Redistributions of source code must retain the above copyright notices,
	   this list of conditions and the following disclaimer.

	2. Redistributions in binary form must reproduce the above copyright
	   notices, this list of conditions and the following disclaimer in the
	   documentation and/or other materials provided with the distribution.

	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	POSSIBILITY OF SUCH DAMAGE.
*/
31

Ad Schellevis's avatar
Ad Schellevis committed
32
require_once('config.inc');
33
require_once('certs.inc');
34
require_once('pfsense-utils.inc');
35
require_once('auth.inc');
36
require_once('util.inc');
Ad Schellevis's avatar
Ad Schellevis committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50

global $openvpn_prots;
$openvpn_prots = array("UDP", "UDP6", "TCP", "TCP6");

global $openvpn_dev_mode;
$openvpn_dev_mode = array("tun", "tap");

global $openvpn_verbosity_level;
$openvpn_verbosity_level = array(
	0 =>	"none",
	1 =>	"default",
	2 =>	"2",
	3 =>	"3 (recommended)",
	4 =>	"4",
51 52 53 54 55 56 57
	5 =>	"5",
	6 =>	"6",
	7 =>	"7",
	8 =>	"8",
	9 =>	"9",
	10 =>	"10",
	11 =>	"11"
Ad Schellevis's avatar
Ad Schellevis committed
58 59 60 61 62 63 64 65
);

/*
 * The User Auth mode below is disabled because
 * OpenVPN erroneously requires that we provide
 * a CA configuration parameter. In this mode,
 * clients don't send a certificate so there is
 * no need for a CA. If we require that admins
66
 * provide one in the OPNsense UI due to a bogus
Ad Schellevis's avatar
Ad Schellevis committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
 * requirement imposed by OpenVPN, it could be
 * considered very confusing ( I know I was ).
 *
 * -mgrooms
 */

global $openvpn_dh_lengths;
$openvpn_dh_lengths = array(
	1024, 2048, 4096 );

global $openvpn_cert_depths;
$openvpn_cert_depths = array(
	1 => "One (Client+Server)",
	2 => "Two (Client+Intermediate+Server)",
	3 => "Three (Client+2xIntermediate+Server)",
	4 => "Four (Client+3xIntermediate+Server)",
	5 => "Five (Client+4xIntermediate+Server)"
);

global $openvpn_server_modes;
$openvpn_server_modes = array(
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"),
	'server_tls' => gettext("Remote Access ( SSL/TLS )"),
	'server_user' => gettext("Remote Access ( User Auth )"),
	'server_tls_user' => gettext("Remote Access ( SSL/TLS + User Auth )"));

global $openvpn_client_modes;
$openvpn_client_modes = array(
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )") );

global $openvpn_compression_modes;
$openvpn_compression_modes = array(
	'' =>	gettext("No Preference"),
	'no' =>		gettext("Disabled - No Compression"),
	'adaptive' =>	gettext("Enabled with Adaptive Compression"),
	'yes' =>	gettext("Enabled without Adaptive Compression"));

function openvpn_create_key() {

	$fp = popen("/usr/local/sbin/openvpn --genkey --secret /dev/stdout 2>/dev/null", "r");
	if (!$fp)
		return false;

	$rslt = stream_get_contents($fp);
	pclose($fp);

	return $rslt;
}

function openvpn_vpnid_used($vpnid) {
	global $config;

	if (is_array($config['openvpn']['openvpn-server']))
		foreach ($config['openvpn']['openvpn-server'] as & $settings)
			if ($vpnid == $settings['vpnid'])
				return true;

	if (is_array($config['openvpn']['openvpn-client']))
		foreach ($config['openvpn']['openvpn-client'] as & $settings)
			if ($vpnid == $settings['vpnid'])
				return true;

	return false;
}

function openvpn_vpnid_next() {

	$vpnid = 1;
	while(openvpn_vpnid_used($vpnid))
		$vpnid++;

	return $vpnid;
}

function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
	global $config;

	if (is_array($config['openvpn']['openvpn-server'])) {
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
			if (isset($settings['disable']))
				continue;

			if ($curvpnid != 0 && $curvpnid == $settings['vpnid'])
				continue;

			if ($port == $settings['local_port'] && $prot == $settings['protocol'] &&
				($interface == $settings['interface'] || $interface == "any" || $settings['interface'] == "any"))
				return $settings['vpnid'];
		}
	}

	if (is_array($config['openvpn']['openvpn-client'])) {
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
			if (isset($settings['disable']))
				continue;

			if ($curvpnid != 0 && $curvpnid == $settings['vpnid'])
				continue;

			if ($port == $settings['local_port'] && $prot == $settings['protocol'] &&
				($interface == $settings['interface'] || $interface == "any" || $settings['interface'] == "any"))
				return $settings['vpnid'];
		}
	}

	return 0;
}

function openvpn_port_next($prot, $interface = "wan") {

	$port = 1194;
	while(openvpn_port_used($prot, $interface, $port))
		$port++;
	while(openvpn_port_used($prot, "any", $port))
		$port++;

	return $port;
}

function openvpn_get_cipherlist() {

	$ciphers = array();
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep "default key" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
	$cipher_lines = explode("\n", trim($cipher_out));
	sort($cipher_lines);
	foreach ($cipher_lines as $line) {
		$words = explode(' ', $line);
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
	}
	$ciphers["none"] = gettext("None (No Encryption)");
	return $ciphers;
}

function openvpn_get_digestlist() {

	$digests = array();
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
	$digest_lines = explode("\n", trim($digest_out));
	sort($digest_lines);
	foreach ($digest_lines as $line) {
		$words = explode(' ', $line);
		$digests[$words[0]] = "{$words[0]} {$words[1]}";
	}
	$digests["none"] = gettext("None (No Authentication)");
	return $digests;
}

216 217
function openvpn_get_engines()
{
Ad Schellevis's avatar
Ad Schellevis committed
218
	$openssl_engines = array('none' => 'No Hardware Crypto Acceleration');
219
	exec('/usr/local/bin/openssl engine -t -c', $openssl_engine_output);
Ad Schellevis's avatar
Ad Schellevis committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
	$openssl_engine_output = implode("\n", $openssl_engine_output);
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
	$openssl_engine_output = explode("\n", $openssl_engine_output);

	foreach ($openssl_engine_output as $oeo) {
		$keep = true;
		$details = explode("|", $oeo);
		$engine = array_shift($details);
		$linematch = array();
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
		foreach ($details as $dt) {
			if (strpos($dt, "unavailable") !== FALSE)
				$keep = false;
			if (strpos($dt, "available") !== FALSE)
				continue;
			if (strpos($dt, "[") !== FALSE)
				$ciphers = trim($dt, "[]");
		}
		if (!empty($ciphers))
			$ciphers = " - " . $ciphers;
		if (strlen($ciphers) > 60)
			$ciphers = substr($ciphers, 0, 60) . " ... ";
		if ($keep)
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
	}
	return $openssl_engines;
}

function openvpn_validate_engine($engine) {
	$engines = openvpn_get_engines();
	return array_key_exists($engine, $engines);
}

function openvpn_validate_host($value, $name) {
	$value = trim($value);
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value)))
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
	return false;
}

function openvpn_validate_port($value, $name) {
	$value = trim($value);
	if (empty($value) || !is_numeric($value) || $value < 0 || ($value > 65535))
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from 0 to 65535."), $name);
	return false;
}

function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4") {
	$value = trim($value);
	$error = false;
	if (empty($value))
		return false;
	$networks = explode(',', $value);

	if (!$multiple && (count($networks) > 1))
		return sprintf(gettext("The field '%s' must contain a single valid %s CIDR range."), $name, $ipproto);

	foreach ($networks as $network) {
		if ($ipproto == "ipv4")
			$error = !openvpn_validate_cidr_ipv4($network);
		else
			$error = !openvpn_validate_cidr_ipv6($network);
		if ($error)
			break;
	}

	if ($error)
		return sprintf(gettext("The field '%s' must contain only valid %s CIDR range(s) separated by commas."), $name, $ipproto);
	else
		return false;
}

function openvpn_validate_cidr_ipv4($value) {
	$value = trim($value);
	if (!empty($value)) {
		list($ip, $mask) = explode('/', $value);
		if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0))
			return false;
	}
	return true;
}

function openvpn_validate_cidr_ipv6($value) {
	$value = trim($value);
	if (!empty($value)) {
		list($ipv6, $prefix) = explode('/', $value);
		if (empty($prefix))
			$prefix = "128";
		if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0))
			return false;
	}
	return true;
}

function openvpn_add_dhcpopts(& $settings, & $conf) {

	if (!empty($settings['dns_domain']))
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";

	if (!empty($settings['dns_server1']))
		$conf .= "push \"dhcp-option DNS {$settings['dns_server1']}\"\n";
	if (!empty($settings['dns_server2']))
		$conf .= "push \"dhcp-option DNS {$settings['dns_server2']}\"\n";
	if (!empty($settings['dns_server3']))
		$conf .= "push \"dhcp-option DNS {$settings['dns_server3']}\"\n";
	if (!empty($settings['dns_server4']))
		$conf .= "push \"dhcp-option DNS {$settings['dns_server4']}\"\n";

	if (!empty($settings['push_register_dns']))
		$conf .= "push \"register-dns\"\n";

	if (!empty($settings['ntp_server1']))
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
	if (!empty($settings['ntp_server2']))
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";

	if ($settings['netbios_enable']) {

		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0))
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
		if (!empty($settings['dhcp_nbtscope']))
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";

		if (!empty($settings['wins_server1']))
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
		if (!empty($settings['wins_server2']))
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";

		if (!empty($settings['nbdd_server1']))
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
	}

	if ($settings['gwredir'])
		$conf .= "push \"redirect-gateway def1\"\n";
}

function openvpn_add_custom(& $settings, & $conf) {

	if ($settings['custom_options']) {

		$options = explode(';', $settings['custom_options']);

		if (is_array($options)) {
			foreach ($options as $option)
				$conf .= "$option\n";
		} else
			$conf .= "{$settings['custom_options']}\n";
	}
}

370 371 372
function openvpn_add_keyfile(&$data, &$conf, $mode_id, $directive, $opt = '')
{
	$fpath = "/var/etc/openvpn/{$mode_id}.{$directive}";
Ad Schellevis's avatar
Ad Schellevis committed
373 374 375 376 377 378 379 380 381
	openvpn_create_dirs();
	file_put_contents($fpath, base64_decode($data));
	//chown($fpath, 'nobody');
	//chgrp($fpath, 'nobody');
	@chmod($fpath, 0600);

	$conf .= "{$directive} {$fpath} {$opt}\n";
}

382 383
function openvpn_reconfigure($mode, $settings)
{
Ad Schellevis's avatar
Ad Schellevis committed
384 385
	global $g, $config;

386
	if (empty($settings) || isset($settings['disable'])) {
Ad Schellevis's avatar
Ad Schellevis committed
387
		return;
388 389
	}

Ad Schellevis's avatar
Ad Schellevis committed
390
	openvpn_create_dirs();
391

Ad Schellevis's avatar
Ad Schellevis committed
392 393 394 395 396 397 398 399 400
	/*
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
	 * we use a vpnid number which is allocated for a particular client
	 * or server configuration. ( see openvpn_vpnid_next() )
	 */

	$vpnid = $settings['vpnid'];
	$mode_id = $mode.$vpnid;

401
	if (isset($settings['dev_mode'])) {
Ad Schellevis's avatar
Ad Schellevis committed
402
		$tunname = "{$settings['dev_mode']}{$vpnid}";
403
	} else {	/* defaults to tun */
Ad Schellevis's avatar
Ad Schellevis committed
404 405 406 407
		$tunname = "tun{$vpnid}";
		$settings['dev_mode'] = "tun";
	}

408
	if ($mode == "server") {
Ad Schellevis's avatar
Ad Schellevis committed
409
		$devname = "ovpns{$vpnid}";
410
	} else {
Ad Schellevis's avatar
Ad Schellevis committed
411
		$devname = "ovpnc{$vpnid}";
412
	}
Ad Schellevis's avatar
Ad Schellevis committed
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472

	/* is our device already configured */
	if (!does_interface_exist($devname)) {

		/* create the tap device if required */
		if (!file_exists("/dev/{$tunname}"))
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");

		/* rename the device */
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));

		/* add the device to the openvpn group */
		mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " group openvpn");
	}

	$proto = strtolower($settings['protocol']);
	if (substr($settings['protocol'], 0, 3) == "TCP")
			$proto = "{$proto}-{$mode}";
	$dev_mode = $settings['dev_mode'];
	$cipher = $settings['crypto'];
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";

	$interface = get_failover_interface($settings['interface']);
	$ipaddr = $settings['ipaddr'];
	$ipaddrv6 = $settings['ipaddrv6'];

	// If a specific ip address (VIP) is requested, use it.
	// Otherwise, if a specific interface is requested, use it
	// If "any" interface was selected, local directive will be ommited.
	if (is_ipaddrv4($ipaddr)) {
		$iface_ip=$ipaddr;
	} else {
		if ((!empty($interface)) && (strcmp($interface, "any"))) {
			$iface_ip=get_interface_ip($interface);
		}
	}
	if (is_ipaddrv6($ipaddrv6)) {
		$iface_ipv6=$ipaddrv6;
	} else {
		if ((!empty($interface)) && (strcmp($interface, "any"))) {
			$iface_ipv6=get_interface_ipv6($interface);
		}
	}


	$conf = "dev {$devname}\n";
	if (isset($settings['verbosity_level'])) {
		$conf .= "verb {$settings['verbosity_level']}\n";
	}

	$conf .= "dev-type {$settings['dev_mode']}\n";
	switch($settings['dev_mode']) {
		case "tun":
			if (!$settings['no_tun_ipv6']) {
				$conf .= "tun-ipv6\n";
			}
			break;
	}
	$conf .= "dev-node /dev/{$tunname}\n";
473
	$conf .= "writepid /var/run/openvpn_{$mode_id}.pid\n";
Ad Schellevis's avatar
Ad Schellevis committed
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
	$conf .= "#user nobody\n";
	$conf .= "#group nobody\n";
	$conf .= "script-security 3\n";
	$conf .= "daemon\n";
	$conf .= "keepalive 10 60\n";
	$conf .= "ping-timer-rem\n";
	$conf .= "persist-tun\n";
	$conf .= "persist-key\n";
	$conf .= "proto {$proto}\n";
	$conf .= "cipher {$cipher}\n";
	$conf .= "auth {$digest}\n";
	$conf .= "up /usr/local/sbin/ovpn-linkup\n";
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
		switch($settings['mode']) {
			case 'server_user':
			case 'server_tls_user':
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
				break;
		}
	}

	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
	if (is_ipaddrv4($iface_ip) && (stristr($settings['protocol'], "6") === false)) {
		$conf .= "local {$iface_ip}\n";
	} elseif (is_ipaddrv6($iface_ipv6) && (stristr($settings['protocol'], "6") !== false)) {
		$conf .= "local {$iface_ipv6}\n";
	}

	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none"))
		$conf .= "engine {$settings['engine']}\n";

	// server specific settings
	if ($mode == 'server') {

		list($ip, $cidr) = explode('/', $settings['tunnel_network']);
		list($ipv6, $prefix) = explode('/', $settings['tunnel_networkv6']);
		$mask = gen_subnet_mask($cidr);

		// configure tls modes
		switch($settings['mode']) {
			case 'p2p_tls':
			case 'server_tls':
			case 'server_user':
			case 'server_tls_user':
				$conf .= "tls-server\n";
				break;
		}

		// configure p2p/server modes
		switch($settings['mode']) {
			case 'p2p_tls':
				// If the CIDR is less than a /30, OpenVPN will complain if you try to
				//  use the server directive. It works for a single client without it.
				//  See ticket #1417
				if (!empty($ip) && !empty($mask) && ($cidr < 30)) {
					$conf .= "server {$ip} {$mask}\n";
532
					$conf .= "client-config-dir /var/etc/openvpn-csc\n";
Ad Schellevis's avatar
Ad Schellevis committed
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
					if(is_ipaddr($ipv6))
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
				}
			case 'p2p_shared_key':
				if (!empty($ip) && !empty($mask)) {
					list($ip1, $ip2) = openvpn_get_interface_ip($ip, $mask);
					if ($settings['dev_mode'] == 'tun')
						$conf .= "ifconfig {$ip1} {$ip2}\n";
					else
						$conf .= "ifconfig {$ip1} {$mask}\n";
				}
				if (!empty($ipv6) && !empty($prefix)) {
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
					if ($settings['dev_mode'] == 'tun')
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$ipv6_2}\n";
					else
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$prefix}\n";
				}
				break;
			case 'server_tls':
			case 'server_user':
			case 'server_tls_user':
				if (!empty($ip) && !empty($mask)) {
					$conf .= "server {$ip} {$mask}\n";
					if(is_ipaddr($ipv6))
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
559
					$conf .= "client-config-dir /var/etc/openvpn-csc\n";
Ad Schellevis's avatar
Ad Schellevis committed
560 561 562 563 564 565 566
				} else {
					if ($settings['serverbridge_dhcp']) {
						if ((!empty($settings['serverbridge_interface'])) && (strcmp($settings['serverbridge_interface'], "none"))) {
							$biface_ip=get_interface_ip($settings['serverbridge_interface']);
							$biface_sm=gen_subnet_mask(get_interface_subnet($settings['serverbridge_interface']));
							if (is_ipaddrv4($biface_ip) && is_ipaddrv4($settings['serverbridge_dhcp_start']) && is_ipaddrv4($settings['serverbridge_dhcp_end'])) {
								$conf .= "server-bridge {$biface_ip} {$biface_sm} {$settings['serverbridge_dhcp_start']} {$settings['serverbridge_dhcp_end']}\n";
567
								$conf .= "client-config-dir /var/etc/openvpn-csc\n";
Ad Schellevis's avatar
Ad Schellevis committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
							} else {
								$conf .= "mode server\n";
							}
						} else {
							$conf .= "mode server\n";
						}
					}
				}
				break;
		}

		// configure user auth modes
		switch($settings['mode']) {
			case 'server_user':
				$conf .= "client-cert-not-required\n";
			case 'server_tls_user':
				/* username-as-common-name is not compatible with server-bridge */
				if (stristr($conf, "server-bridge") === false)
					$conf .= "username-as-common-name\n";
				if (!empty($settings['authmode'])) {
					$strictusercn = "false";
					if ($settings['strictusercn'])
						$strictusercn = "true";
					$conf .= "auth-user-pass-verify \"/usr/local/sbin/ovpn_auth_verify user '{$settings['authmode']}' {$strictusercn} {$mode_id}\" via-env\n";
				}
				break;
		}
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls')))
			$settings['cert_depth'] = 1;
		if (is_numeric($settings['cert_depth'])) {
			if (($mode == 'client') && empty($settings['certref']))
				$cert = "";
			else {
				$cert = lookup_cert($settings['certref']);
				/* XXX: Seems not used at all! */
				$servercn = urlencode(cert_get_cn($cert['crt']));
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
			}
		}

		// The local port to listen on
		$conf .= "lport {$settings['local_port']}\n";

		// The management port to listen on
		// Use unix socket to overcome the problem on any type of server
613
		$conf .= "management /var/etc/openvpn/{$mode_id}.sock unix\n";
Ad Schellevis's avatar
Ad Schellevis committed
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";

		if ($settings['maxclients'])
			$conf .= "max-clients {$settings['maxclients']}\n";

		// Can we push routes
		if ($settings['local_network']) {
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
		}
		if ($settings['local_networkv6']) {
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
		}

		switch($settings['mode']) {
			case 'server_tls':
			case 'server_user':
			case 'server_tls_user':
				// Configure client dhcp options
				openvpn_add_dhcpopts($settings, $conf);
				if ($settings['client2client'])
					$conf .= "client-to-client\n";
				break;
		}
		if (isset($settings['duplicate_cn']))
			$conf .= "duplicate-cn\n";
	}

	// client specific settings

	if ($mode == 'client') {

		// configure p2p mode
		switch($settings['mode']) {
			case 'p2p_tls':
				$conf .= "tls-client\n";
			case 'shared_key':
				$conf .= "client\n";
				break;
		}

		// If there is no bind option at all (ip and/or port), add "nobind" directive
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
		//  ensure a random source port.
		if ((empty($iface_ip)) && (!$settings['local_port']))
			$conf .= "nobind\n";
		elseif ($settings['local_port'])
			$conf .= "lport {$settings['local_port']}\n";
		else
			$conf .= "lport 0\n";

		// Use unix socket to overcome the problem on any type of server
665
		$conf .= "management /var/etc/openvpn/{$mode_id}.sock unix\n";
Ad Schellevis's avatar
Ad Schellevis committed
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692

		// The remote server
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";

		if (!empty($settings['use_shaper']))
			$conf .= "shaper {$settings['use_shaper']}\n";

		if (!empty($settings['tunnel_network'])) {
			list($ip, $mask) = explode('/', $settings['tunnel_network']);
			$mask = gen_subnet_mask($mask);
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $mask);
			if ($settings['dev_mode'] == 'tun')
				$conf .= "ifconfig {$ip2} {$ip1}\n";
			else
				$conf .= "ifconfig {$ip2} {$mask}\n";
		}

		if (!empty($settings['tunnel_networkv6'])) {
			list($ipv6, $prefix) = explode('/', $settings['tunnel_networkv6']);
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
			if ($settings['dev_mode'] == 'tun')
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
			else
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
		}

		if ($settings['auth_user'] && $settings['auth_pass']) {
693
			$up_file = "/var/etc/openvpn/{$mode_id}.up";
Ad Schellevis's avatar
Ad Schellevis committed
694 695 696 697 698 699 700 701 702
			$conf .= "auth-user-pass {$up_file}\n";
			$userpass = "{$settings['auth_user']}\n";
			$userpass .= "{$settings['auth_pass']}\n";
			file_put_contents($up_file, $userpass);
		}

		if ($settings['proxy_addr']) {
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
			if ($settings['proxy_authtype'] != "none") {
703
				$conf .= " /var/etc/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
Ad Schellevis's avatar
Ad Schellevis committed
704 705
				$proxypas = "{$settings['proxy_user']}\n";
				$proxypas .= "{$settings['proxy_passwd']}\n";
706
				file_put_contents("/var/etc/openvpn/{$mode_id}.pas", $proxypas);
Ad Schellevis's avatar
Ad Schellevis committed
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
			}
			$conf .= " \n";
		}
	}

	// Add a remote network route if set, and only for p2p modes.
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
	}
	// Add a remote network route if set, and only for p2p modes.
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
	}

	// Write the settings for the keys
	switch($settings['mode']) {
		case 'p2p_shared_key':
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
			break;
		case 'p2p_tls':
		case 'server_tls':
		case 'server_tls_user':
		case 'server_user':
			$ca = lookup_ca($settings['caref']);
			openvpn_add_keyfile($ca['crt'], $conf, $mode_id, "ca");

			if (!empty($settings['certref'])) {
				$cert = lookup_cert($settings['certref']);
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
			}
			if ($mode == 'server')
739
				$conf .= "dh /usr/local/etc/dh-parameters.{$settings['dh_length']}\n";
Ad Schellevis's avatar
Ad Schellevis committed
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
			if (!empty($settings['crlref'])) {
				$crl = lookup_crl($settings['crlref']);
				crl_update($crl);
				openvpn_add_keyfile($crl['text'], $conf, $mode_id, "crl-verify");
			}
			if ($settings['tls']) {
				if ($mode == "server")
					$tlsopt = 0;
				else
					$tlsopt = 1;
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, "tls-auth", $tlsopt);
			}
			break;
	}

	if (!empty($settings['compression']))
		$conf .= "comp-lzo {$settings['compression']}\n";

	if ($settings['passtos'])
		$conf .= "passtos\n";

	if ($settings['resolve_retry'])
		$conf .= "resolv-retry infinite\n";

	if ($settings['dynamic_ip']) {
		$conf .= "persist-remote-ip\n";
		$conf .= "float\n";
	}

	if ($settings['topology_subnet']) {
		$conf .= "topology subnet\n";
	}

	// New client features
	if ($mode == "client") {
		// Dont pull routes checkbox
		if ($settings['route_no_pull']) {
			$conf .= "route-nopull\n";
		}

		// Dont add/remove routes checkbox
		if ($settings['route_no_exec']) {
			$conf .= "route-noexec\n";
		}
	}

	openvpn_add_custom($settings, $conf);

	openvpn_create_dirs();
789
	$fpath = "/var/etc/openvpn/{$mode_id}.conf";
Ad Schellevis's avatar
Ad Schellevis committed
790 791
	file_put_contents($fpath, $conf);
	unset($conf);
792
	$fpath = "/var/etc/openvpn/{$mode_id}.interface";
Ad Schellevis's avatar
Ad Schellevis committed
793 794 795
	file_put_contents($fpath, $interface);
	//chown($fpath, 'nobody');
	//chgrp($fpath, 'nobody');
796 797 798 799 800
	@chmod("/var/etc/openvpn/{$mode_id}.conf", 0600);
	@chmod("/var/etc/openvpn/{$mode_id}.interface", 0600);
	@chmod("/var/etc/openvpn/{$mode_id}.key", 0600);
	@chmod("/var/etc/openvpn/{$mode_id}.tls-auth", 0600);
	@chmod("/var/etc/openvpn/{$mode_id}.conf", 0600);
Ad Schellevis's avatar
Ad Schellevis committed
801 802
}

803 804
function openvpn_restart($mode, $settings)
{
Ad Schellevis's avatar
Ad Schellevis committed
805 806 807 808 809 810
	global $g, $config;

	$vpnid = $settings['vpnid'];
	$mode_id = $mode.$vpnid;

	/* kill the process if running */
811 812 813 814
	$pfile = "/var/run/openvpn_{$mode_id}.pid";
	killbypid($pfile);
	while (isvalidpid($pfile)) {
		usleep(250000);
Ad Schellevis's avatar
Ad Schellevis committed
815 816
	}

817
	if (isset($settings['disable'])) {
Ad Schellevis's avatar
Ad Schellevis committed
818
		return;
819
	}
Ad Schellevis's avatar
Ad Schellevis committed
820 821

	/* Do not start a client if we are a CARP backup on this vip! */
822
	if (($mode == "client") && (strstr($settings['interface'], "_vip") && get_carp_interface_status($settings['interface']) == "BACKUP")) {
Ad Schellevis's avatar
Ad Schellevis committed
823
		return;
824
	}
Ad Schellevis's avatar
Ad Schellevis committed
825 826 827 828 829 830 831 832 833 834

	/* Check if client is bound to a gateway group */
	$a_groups = return_gateway_groups_array();
	if (is_array($a_groups[$settings['interface']])) {
	/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (get_carp_interface_status($a_groups[$settings['interface']][0]['vip']) == "BACKUP"))
			return;
	}

	/* start the new process */
835
	$fpath = "/var/etc/openvpn/{$mode_id}.conf";
Ad Schellevis's avatar
Ad Schellevis committed
836 837 838
	openvpn_clear_route($mode, $settings);
	mwexec_bg("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));

Ad Schellevis's avatar
Ad Schellevis committed
839
	if (!file_exists("/var/run/booting"))
840
		configd_run("filter reload");
Ad Schellevis's avatar
Ad Schellevis committed
841 842
}

843 844
function openvpn_delete($mode, & $settings)
{
Ad Schellevis's avatar
Ad Schellevis committed
845 846 847 848 849
	global $g, $config;

	$vpnid = $settings['vpnid'];
	$mode_id = $mode.$vpnid;

850
	if (isset($settings['dev_mode'])) {
Ad Schellevis's avatar
Ad Schellevis committed
851
		$tunname = "{$settings['dev_mode']}{$vpnid}";
852
	} else {  /* defaults to tun */
Ad Schellevis's avatar
Ad Schellevis committed
853 854 855
		$tunname = "tun{$vpnid}";
	}

856
	if ($mode == "server") {
Ad Schellevis's avatar
Ad Schellevis committed
857
		$devname = "ovpns{$vpnid}";
858
	} else {
Ad Schellevis's avatar
Ad Schellevis committed
859
		$devname = "ovpnc{$vpnid}";
860
	}
Ad Schellevis's avatar
Ad Schellevis committed
861 862

	/* kill the process if running */
863
	killbypid("/var/run/openvpn_{$mode_id}.pid");
Ad Schellevis's avatar
Ad Schellevis committed
864 865 866 867 868 869 870 871

	/* remove the device from the openvpn group */
	mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " -group openvpn");

	/* restore the original adapter name */
	mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " name " . escapeshellarg($tunname));

	/* remove the configuration files */
872
	@array_map('unlink', glob("/var/etc/openvpn/{$mode_id}.*"));
Ad Schellevis's avatar
Ad Schellevis committed
873 874
}

875 876 877
function openvpn_cleanup_csc($common_name)
{
	@unlink('/var/etc/openvpn-csc/' . basename($common_name));
Ad Schellevis's avatar
Ad Schellevis committed
878 879
}

880 881
function openvpn_resync_csc(&$settings)
{
Ad Schellevis's avatar
Ad Schellevis committed
882 883
	global $g, $config;

884
	$fpath = "/var/etc/openvpn-csc/{$settings['common_name']}";
Ad Schellevis's avatar
Ad Schellevis committed
885 886

	if (isset($settings['disable'])) {
887
		@unlink($fpath);
Ad Schellevis's avatar
Ad Schellevis committed
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
		return;
	}
	openvpn_create_dirs();

	$conf = '';
	if ($settings['block'])
		$conf .= "disable\n";

	if ($settings['push_reset'])
		$conf .= "push-reset\n";

	if (!empty($settings['tunnel_network'])) {
		list($ip, $mask) = explode('/', $settings['tunnel_network']);
		$baselong = ip2long32($ip) & gen_subnet_mask_long($mask);
		$serverip = long2ip32($baselong + 1);
		$clientip = long2ip32($baselong + 2);
		/* Because this is being pushed, the order from the client's point of view. */
		if ($settings['dev_mode'] != 'tap')
			$conf .= "ifconfig-push {$clientip} {$serverip}\n";
		else
			$conf .= "ifconfig-push {$clientip} {$mask}\n";
	}

	if ($settings['local_network']) {
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
	}
	if ($settings['local_networkv6']) {
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
	}

	// Add a remote network iroute if set
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
	}
	// Add a remote network iroute if set
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
	}

	openvpn_add_dhcpopts($settings, $conf);

	if ($settings['gwredir'])
		$conf .= "push \"redirect-gateway def1\"\n";

	openvpn_add_custom($settings, $conf);

	file_put_contents($fpath, $conf);
	chown($fpath, 'nobody');
	chgrp($fpath, 'nobody');
}

939 940 941
function openvpn_delete_csc(&$settings)
{
	@unlink("/var/etc/openvpn-csc/{$settings['common_name']}");
Ad Schellevis's avatar
Ad Schellevis committed
942 943
}

944 945
function openvpn_resync($mode, $settings)
{
Ad Schellevis's avatar
Ad Schellevis committed
946 947 948 949
	openvpn_reconfigure($mode, $settings);
	openvpn_restart($mode, $settings);
}

950 951
function openvpn_resync_all($interface = '')
{
Ad Schellevis's avatar
Ad Schellevis committed
952 953 954 955
	global $g, $config;

	openvpn_create_dirs();

956 957 958
	if (!isset($config['openvpn']) || !is_array($config['openvpn'])) {
		return;
	}
Ad Schellevis's avatar
Ad Schellevis committed
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019

	if ($interface <> "")
		log_error("Resyncing OpenVPN instances for interface " . convert_friendly_interface_to_friendly_descr($interface) . ".");
	else
		log_error("Resyncing OpenVPN instances.");

	if (is_array($config['openvpn']['openvpn-server'])) {
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
			if ($interface <> "" && $interface != $settings['interface'])
				continue;
			openvpn_resync('server', $settings);
		}
	}

	if (is_array($config['openvpn']['openvpn-client'])) {
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
			if ($interface <> "" && $interface != $settings['interface'])
				continue;
			openvpn_resync('client', $settings);
		}
	}

	if (is_array($config['openvpn']['openvpn-csc']))
		foreach ($config['openvpn']['openvpn-csc'] as & $settings)
			openvpn_resync_csc($settings);

}

// Resync and restart all VPNs using a gateway group.
function openvpn_resync_gwgroup($gwgroupname = "") {
	global $g, $config;

	if ($gwgroupname <> "") {
		if (is_array($config['openvpn']['openvpn-server'])) {
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
				if ($gwgroupname == $settings['interface']) {
					log_error("Resyncing OpenVPN for gateway group " . $gwgroupname . " server " . $settings["description"] . ".");
					openvpn_resync('server', $settings);
				}
			}
		}

		if (is_array($config['openvpn']['openvpn-client'])) {
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
				if ($gwgroupname == $settings['interface']) {
					log_error("Resyncing OpenVPN for gateway group " . $gwgroupname . " client " . $settings["description"] . ".");
					openvpn_resync('client', $settings);
				}
			}
		}

		// Note: no need to resysnc Client Specific (csc) here, as changes to the OpenVPN real interface do not effect these.

	} else
		log_error("openvpn_resync_gwgroup called with null gwgroup parameter.");
}

function openvpn_get_active_servers($type="multipoint") {
	global $config, $g;

	$servers = array();
1020
	if (isset($config['openvpn']['openvpn-server']) && is_array($config['openvpn']['openvpn-server'])) {
Ad Schellevis's avatar
Ad Schellevis committed
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
			if (empty($settings) || isset($settings['disable']))
				continue;

			$prot = $settings['protocol'];
			$port = $settings['local_port'];

			$server = array();
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
			$server['mode'] = $settings['mode'];
			if ($settings['description'])
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
			else
				$server['name'] = "Server {$prot}:{$port}";
			$server['conns'] = array();
			$server['vpnid'] = $settings['vpnid'];
			$server['mgmt'] = "server{$server['vpnid']}";
1038
			$socket = "unix:///var/etc/openvpn/{$server['mgmt']}.sock";
Ad Schellevis's avatar
Ad Schellevis committed
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
			list($tn, $sm) = explode('/', $settings['tunnel_network']);

			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30) ) && ($type == "p2p"))
				$servers[] = openvpn_get_client_status($server, $socket);
			elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30))
				$servers[] = openvpn_get_server_status($server, $socket);

		}
	}
	return $servers;
}

function openvpn_get_server_status($server, $socket) {
	$errval;
	$errstr;
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
	if ($fp) {
		stream_set_timeout($fp, 1);

		/* send our status request */
		fputs($fp, "status 2\n");

		/* recv all response lines */
		while (!feof($fp)) {

			/* read the next line */
			$line = fgets($fp, 1024);

			$info = stream_get_meta_data($fp);
			if ($info['timed_out'])
				break;

			/* parse header list line */
			if (strstr($line, "HEADER"))
				continue;

			/* parse end of output line */
			if (strstr($line, "END") || strstr($line, "ERROR"))
				break;

			/* parse client list line */
			if (strstr($line, "CLIENT_LIST")) {
				$list = explode(",", $line);
				$conn = array();
				$conn['common_name'] = $list[1];
				$conn['remote_host'] = $list[2];
				$conn['virtual_addr'] = $list[3];
				$conn['bytes_recv'] = $list[4];
				$conn['bytes_sent'] = $list[5];
				$conn['connect_time'] = $list[6];
				$server['conns'][] = $conn;
			}
			/* parse routing table lines */
			if (strstr($line, "ROUTING_TABLE")) {
				$list = explode(",", $line);
				$conn = array();
				$conn['virtual_addr'] = $list[1];
				$conn['common_name'] = $list[2];
				$conn['remote_host'] = $list[3];
				$conn['last_time'] = $list[4];
				$server['routes'][] = $conn;
			}
		}

		/* cleanup */
		fclose($fp);
	} else {
		$conn = array();
		$conn['common_name'] = "[error]";
		$conn['remote_host'] = "Unable to contact daemon";
		$conn['virtual_addr'] = "Service not running?";
		$conn['bytes_recv'] = 0;
		$conn['bytes_sent'] = 0;
		$conn['connect_time'] = 0;
		$server['conns'][] = $conn;
	}
	return $server;
}

function openvpn_get_active_clients() {
	global $config, $g;

	$clients = array();
1122
	if (isset($config['openvpn']['openvpn-client']) && is_array($config['openvpn']['openvpn-client'])) {
Ad Schellevis's avatar
Ad Schellevis committed
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {

			if (empty($settings) || isset($settings['disable']))
				continue;

			$prot = $settings['protocol'];
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";

			$client = array();
			$client['port'] = $settings['local_port'];
			if ($settings['description'])
				$client['name'] = "{$settings['description']} {$prot}{$port}";
			else
				$client['name'] = "Client {$prot}{$port}";

			$client['vpnid'] = $settings['vpnid'];
			$client['mgmt'] = "client{$client['vpnid']}";
1140
			$socket = "unix:///var/etc/openvpn/{$client['mgmt']}.sock";
Ad Schellevis's avatar
Ad Schellevis committed
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
			$client['status']="down";

			$clients[] = openvpn_get_client_status($client, $socket);
		}
	}
	return $clients;
}

function openvpn_get_client_status($client, $socket) {
	$errval;
	$errstr;
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
	if ($fp) {
		stream_set_timeout($fp, 1);
		/* send our status request */
		fputs($fp, "state 1\n");

		/* recv all response lines */
		while (!feof($fp)) {
			/* read the next line */
			$line = fgets($fp, 1024);

			$info = stream_get_meta_data($fp);
			if ($info['timed_out'])
				break;

			/* Get the client state */
			if (strstr($line,"CONNECTED")) {
				$client['status']="up";
				$list = explode(",", $line);

				$client['connect_time']  = date("D M j G:i:s Y", $list[0]);
				$client['virtual_addr']  = $list[3];
				$client['remote_host'] = $list[4];
			}
			if (strstr($line,"CONNECTING")) {
				$client['status']="connecting";
			}
			if (strstr($line,"ASSIGN_IP")) {
				$client['status']="waiting";
				$list = explode(",", $line);

				$client['connect_time']  = date("D M j G:i:s Y", $list[0]);
				$client['virtual_addr']  = $list[3];
			}
			if (strstr($line,"RECONNECTING")) {
				$client['status']="reconnecting";
				$list = explode(",", $line);

				$client['connect_time']  = date("D M j G:i:s Y", $list[0]);
				$client['status'] .= "; " . $list[2];
			}
			/* parse end of output line */
			if (strstr($line, "END") || strstr($line, "ERROR"))
				break;
		}

		/* If up, get read/write stats */
		if (strcmp($client['status'], "up") == 0) {
			fputs($fp, "status 2\n");
			/* recv all response lines */
			while (!feof($fp)) {
				/* read the next line */
				$line = fgets($fp, 1024);

				$info = stream_get_meta_data($fp);
				if ($info['timed_out'])
					break;

				if (strstr($line,"TCP/UDP read bytes")) {
					$list = explode(",", $line);
					$client['bytes_recv'] = $list[1];
				}

				if (strstr($line,"TCP/UDP write bytes")) {
					$list = explode(",", $line);
					$client['bytes_sent'] = $list[1];
				}

				/* parse end of output line */
				if (strstr($line, "END"))
					break;
			}
		}

		fclose($fp);

	} else {
		$DisplayNote=true;
		$client['remote_host'] = "Unable to contact daemon";
		$client['virtual_addr'] = "Service not running?";
		$client['bytes_recv'] = 0;
		$client['bytes_sent'] = 0;
		$client['connect_time'] = 0;
	}
	return $client;
}

function openvpn_refresh_crls() {
	global $g, $config;

	openvpn_create_dirs();

1244
	if (isset($config['openvpn']['openvpn-server']) && is_array($config['openvpn']['openvpn-server'])) {
Ad Schellevis's avatar
Ad Schellevis committed
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
			if (empty($settings))
				continue;
			if (isset($settings['disable']))
				continue;
			// Write the settings for the keys
			switch($settings['mode']) {
				case 'p2p_tls':
				case 'server_tls':
				case 'server_tls_user':
				case 'server_user':
					if (!empty($settings['crlref'])) {
						$crl = lookup_crl($settings['crlref']);
						crl_update($crl);
1259
						$fpath = "/var/etc/openvpn/server{$settings['vpnid']}.crl-verify";
Ad Schellevis's avatar
Ad Schellevis committed
1260 1261 1262 1263 1264 1265 1266 1267 1268
						file_put_contents($fpath, base64_decode($crl['text']));
						@chmod($fpath, 0644);
					}
					break;
			}
		}
	}
}

1269 1270 1271 1272
function openvpn_create_dirs()
{
	@mkdir('/var/etc/openvpn-csc', 0750);
	@mkdir('/var/etc/openvpn', 0750);
Ad Schellevis's avatar
Ad Schellevis committed
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
}

function openvpn_get_interface_ip($ip, $mask) {
	$baselong = ip2long32($ip) & ip2long($mask);
	$ip1 = long2ip32($baselong + 1);
	$ip2 = long2ip32($baselong + 2);
	return array($ip1, $ip2);
}

function openvpn_get_interface_ipv6($ipv6, $prefix) {
	$basev6 = gen_subnetv6($ipv6, $prefix);
	// Is there a better way to do this math?
	$ipv6_arr = explode(':', $basev6);
	$last = hexdec(array_pop($ipv6_arr));
	$ipv6_1 = Net_IPv6::compress(Net_IPv6::uncompress(implode(':', $ipv6_arr) . ':' . dechex($last + 1)));
	$ipv6_2 = Net_IPv6::compress(Net_IPv6::uncompress(implode(':', $ipv6_arr) . ':' . dechex($last + 2)));
	return array($ipv6_1, $ipv6_2);
}

function openvpn_clear_route($mode, $settings) {
	if (empty($settings['tunnel_network']))
		return;
	list($ip, $cidr) = explode('/', $settings['tunnel_network']);
	$mask = gen_subnet_mask($cidr);
	$clear_route = false;

	switch($settings['mode']) {
		case 'shared_key':
			$clear_route = true;
			break;
		case 'p2p_tls':
		case 'p2p_shared_key':
			if ($cidr == 30)
				$clear_route = true;
			break;
	}

	if ($clear_route && !empty($ip) && !empty($mask)) {
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $mask);
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
		/* XXX: Family for route? */
		mwexec("/sbin/route -q delete {$ip_to_clear}");
	}
}

function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
	$routes = "";
	if (empty($value))
		return "";
	$networks = explode(',', $value);

	foreach ($networks as $network) {
		if ($ipproto == "ipv4")
			$route = openvpn_gen_route_ipv4($network, $iroute);
		else
			$route = openvpn_gen_route_ipv6($network, $iroute);

		if ($push)
			$routes .= "push \"{$route}\"\n";
		else
			$routes .= "{$route}\n";
	}
	return $routes;
}

function openvpn_gen_route_ipv4($network, $iroute = false) {
	$i = ($iroute) ? "i" : "";
	list($ip, $mask) = explode('/', trim($network));
	$mask = gen_subnet_mask($mask);
	return "{$i}route $ip $mask";
}

function openvpn_gen_route_ipv6($network, $iroute = false) {
	$i = ($iroute) ? "i" : "";
	list($ipv6, $prefix) = explode('/', trim($network));
	if (empty($prefix))
		$prefix = "128";
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
}

function openvpn_get_settings($mode, $vpnid) {
	global $config;

	if (is_array($config['openvpn']['openvpn-server'])) {
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
			if (isset($settings['disable']))
				continue;

			if ($vpnid != 0 && $vpnid == $settings['vpnid'])
				return $settings;
		}
	}

	if (is_array($config['openvpn']['openvpn-client'])) {
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
			if (isset($settings['disable']))
				continue;

			if ($vpnid != 0 && $vpnid == $settings['vpnid'])
				return $settings;
		}
	}

	return array();
}

function openvpn_restart_by_vpnid($mode, $vpnid) {
	$settings = openvpn_get_settings($mode, $vpnid);
	openvpn_restart($mode, $settings);
}