openvpn-client-export.inc 31.1 KB
Newer Older
1
<?php
2

3 4 5 6 7
/*
	Copyright (C) 2009 Scott Ullrich <sullrich@gmail.com>
	Copyright (C) 2008 Shrew Soft Inc
	Copyright (C) 2010 Ermal Luci
	Copyright (C) 2003-2004 Manuel Kasper
8
	All rights reserved.
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

	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 notice,
	   this list of conditions and the following disclaimer.

	2. Redistributions in binary form must reproduce the above copyright
	   notice, 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.
*/

global $current_openvpn_version, $current_openvpn_version_rev;
$current_openvpn_version     = "2.3.6";
$current_openvpn_version_rev = "01";

function openvpn_client_export_prefix($srvid, $usrid = null, $crtid = null) {
	global $config;

	// lookup server settings
	$settings = $config['openvpn']['openvpn-server'][$srvid];
	if (empty($settings))
		return false;
43
	if (!empty($settings['disable'])) {
44
		return false;
45
	}
46 47 48 49

	$host = empty($config['system']['hostname']) ? "openvpn" : $config['system']['hostname'];
	$prot = ($settings['protocol'] == 'UDP' ? 'udp' : $settings['protocol']);
	$port = $settings['local_port'];
50

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
	$filename_addition = "";
	if ($usrid && is_numeric($usrid))
		$filename_addition = "-".$config['system']['user'][$usrid]['name'];
	elseif ($crtid && is_numeric($crtid) && function_exists("cert_get_cn"))
		$filename_addition = "-" . str_replace(' ', '_', cert_get_cn($config['cert'][$crtid]['crt']));

	return "{$host}-{$prot}-{$port}{$filename_addition}";
}

function openvpn_client_pem_to_pk12($outpath, $outpass, $crtpath, $keypath, $capath = false) {
	$eoutpath = escapeshellarg($outpath);
	$eoutpass = escapeshellarg($outpass);
	$ecrtpath = escapeshellarg($crtpath);
	$ekeypath = escapeshellarg($keypath);
	if ($capath) {
		$ecapath = escapeshellarg($capath);
67
		exec("/usr/local/bin/openssl pkcs12 -export -in {$ecrtpath} -inkey {$ekeypath} -certfile {$ecapath} -out {$eoutpath} -passout pass:{$eoutpass}");
68
	} else
69
		exec("/usr/local/bin/openssl pkcs12 -export -in {$ecrtpath} -inkey {$ekeypath} -out {$eoutpath} -passout pass:{$eoutpass}");
70 71 72 73 74 75 76 77 78

	unlink($crtpath);
	unlink($keypath);
	if ($capath)
		unlink($capath);
}

function openvpn_client_export_validate_config($srvid, $usrid, $crtid) {
	global $config, $g, $input_errors;
79
	$nokeys = false;
80 81 82 83

	// lookup server settings
	$settings = $config['openvpn']['openvpn-server'][$srvid];
	if (empty($settings)) {
84
		$input_errors[] = gettext("Could not locate server configuration.");
85 86
		return false;
	}
87
	if (!empty($settings['disable'])) {
88
		$input_errors[] = gettext("You cannot export for disabled servers.");
89 90 91 92 93
		return false;
	}

	// lookup server certificate info
	$server_cert = lookup_cert($settings['certref']);
94
	if (!$server_cert)
95
	{
96
		$input_errors[] = gettext("Could not locate server certificate.");
97
	} else {
98
		$server_ca = isset($server_cert['caref']) ? lookup_ca($server_cert['caref']) : null;
99
		if (!$server_ca) {
100
			$input_errors[] = gettext("Could not locate the CA reference for the server certificate.");
101 102 103 104 105 106 107 108 109 110
		}
		if (function_exists("cert_get_cn")) {
			$servercn = cert_get_cn($server_cert['crt']);
		}
	}

	// lookup user info
	if (is_numeric($usrid)) {
		$user = $config['system']['user'][$usrid];
		if (!$user) {
111
			$input_errors[] = gettext("Could not find user settings.");
112 113 114 115 116 117 118 119 120 121
		}
	}

	// lookup user certificate info
	if ($settings['mode'] == "server_tls_user") {
		if ($settings['authmode'] == "Local Database") {
			$cert = $user['cert'][$crtid];
		} else {
			$cert = $config['cert'][$crtid];
		}
122 123
		if (!$cert) {
			$input_errors[] = gettext("Could not find client certificate.");
124 125 126 127 128 129 130 131
		} else {
			// If $cert is not an array, it's a certref not a cert.
			if (!is_array($cert))
				$cert = lookup_cert($cert);
		}
	} elseif (($settings['mode'] == "server_tls") || (($settings['mode'] == "server_tls_user") && ($settings['authmode'] != "Local Database"))) {
		$cert = $config['cert'][$crtid];
		if (!$cert)
132
			$input_errors[] = gettext("Could not find client certificate.");
133 134 135 136 137
	} else
		$nokeys = true;

	if ($input_errors)
		return false;
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
	return array($settings, $server_cert, $server_ca, $servercn, $user, $cert, $nokeys);
}

function openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $verifyservercn, $randomlocalport, $usetoken, $nokeys = false, $proxy, $expformat = "baseconf", $outpass = "", $skiptls=false, $doslines=false, $openvpnmanager, $advancedoptions = "") {
	global $config, $input_errors, $g;

	$nl = ($doslines) ? "\r\n" : "\n";
	$conf = "";

	$validconfig = openvpn_client_export_validate_config($srvid, $usrid, $crtid);
	if ($validconfig) {
		list($settings, $server_cert, $server_ca, $servercn, $user, $cert, $nokeys) = $validconfig;
	} else {
		return false;
	}

	// determine basic variables
	$remotes = openvpn_client_export_build_remote_lines($settings, $useaddr, $interface, $expformat, $nl);
	$server_port = $settings['local_port'];
	$cipher = $settings['crypto'];
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";

	// add basic settings
	$devmode = empty($settings['dev_mode']) ? "tun" : $settings['dev_mode'];
	if (($expformat != "inlinedroid") && ($expformat != "inlineios"))
		$conf .= "dev {$devmode}{$nl}";
	if(!empty($settings['tunnel_networkv6']) && ($expformat != "inlinedroid") && ($expformat != "inlineios")) {
		$conf .= "tun-ipv6{$nl}";
	}
	$conf .= "persist-tun{$nl}";
	$conf .= "persist-key{$nl}";

//	if ((($expformat != "inlinedroid") && ($expformat != "inlineios")) && ($proto == "tcp"))
//		$conf .= "proto tcp-client{$nl}";
	$conf .= "cipher {$cipher}{$nl}";
	$conf .= "auth {$digest}{$nl}";
	$conf .= "tls-client{$nl}";
	$conf .= "client{$nl}";
	if (($expformat != "inlinedroid") && ($expformat != "inlineios"))
		$conf .= "resolv-retry infinite{$nl}";
	$conf .= "$remotes{$nl}";

	/* Use a random local port, otherwise two clients will conflict if they run at the same time.
		May not be supported on older clients (Released before May 2010) */
	if (($randomlocalport != 0) && (substr($expformat, 0, 7) != "yealink") && ($expformat != "snom"))
		$conf .= "lport 0{$nl}";

	/* This line can cause problems with auth-only setups and also with Yealink/Snom phones
		since they are stuck on an older OpenVPN version that does not support this feature. */
	if (!empty($servercn) && !$nokeys) {
		switch ($verifyservercn) {
			case "none":
				break;
			case "tls-remote":
				$conf .= "tls-remote {$servercn}{$nl}";
				break;
			case "tls-remote-quote":
				$conf .= "tls-remote \"{$servercn}\"{$nl}";
				break;
			default:
				if ((substr($expformat, 0, 7) != "yealink") && ($expformat != "snom")) {
					$conf .= "verify-x509-name \"{$servercn}\" name{$nl}";
				}
		}
	}

	if (!empty($proxy)) {
		if ($proxy['proxy_type'] == "http") {

			if (strtoupper(substr($settings['protocol'], 0, 3)) == "UDP") {
209
				$input_errors[] = gettext("This server uses UDP protocol and cannot communicate with HTTP proxy.");
210 211 212 213
				return;
			}
			$conf .= "http-proxy {$proxy['ip']} {$proxy['port']} ";
		}
214
		if ($proxy['proxy_type'] == "socks")
215 216 217 218 219 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
			$conf .= "socks-proxy {$proxy['ip']} {$proxy['port']} ";
		if ($proxy['proxy_authtype'] != "none") {
			if (!isset($proxy['passwdfile']))
				$proxy['passwdfile'] = openvpn_client_export_prefix($srvid, $usrid, $crtid) . "-proxy";
			$conf .= " {$proxy['passwdfile']} {$proxy['proxy_authtype']}";
		}
		$conf .= "{$nl}";
	}

	// add user auth settings
	switch($settings['mode']) {
		case 'server_user':
		case 'server_tls_user':
			$conf .= "auth-user-pass{$nl}";
			break;
	}

	// add key settings
	$prefix = openvpn_client_export_prefix($srvid, $usrid, $crtid);
	$cafile = "{$prefix}-ca.crt";
	if($nokeys == false) {
		if ($expformat == "yealink_t28") {
			$conf .= "ca /yealink/config/openvpn/keys/ca.crt{$nl}";
			$conf .= "cert /yealink/config/openvpn/keys/client1.crt{$nl}";
			$conf .= "key /yealink/config/openvpn/keys/client1.key{$nl}";
		} elseif ($expformat == "yealink_t38g") {
			$conf .= "ca /phone/config/openvpn/keys/ca.crt{$nl}";
			$conf .= "cert /phone/config/openvpn/keys/client1.crt{$nl}";
			$conf .= "key /phone/config/openvpn/keys/client1.key{$nl}";
		} elseif ($expformat == "yealink_t38g2") {
			$conf .= "ca /config/openvpn/keys/ca.crt{$nl}";
			$conf .= "cert /config/openvpn/keys/client1.crt{$nl}";
			$conf .= "key /config/openvpn/keys/client1.key{$nl}";
		} elseif ($expformat == "snom") {
			$conf .= "ca /openvpn/ca.crt{$nl}";
			$conf .= "cert /openvpn/phone1.crt{$nl}";
			$conf .= "key /openvpn/phone1.key{$nl}";
		} elseif ($usetoken) {
			$conf .= "ca {$cafile}{$nl}";
			$conf .= "cryptoapicert \"SUBJ:{$user['name']}\"{$nl}";
		} elseif (substr($expformat, 0, 6) != "inline") {
			$conf .= "pkcs12 {$prefix}.p12{$nl}";
		}
	} else if ($settings['mode'] == "server_user") {
		if (substr($expformat, 0, 6) != "inline")
			$conf .= "ca {$cafile}{$nl}";
	}

	if ($settings['tls'] && !$skiptls) {
		if ($expformat == "yealink_t28")
			$conf .= "tls-auth /yealink/config/openvpn/keys/ta.key 1{$nl}";
		elseif ($expformat == "yealink_t38g")
			$conf .= "tls-auth /phone/config/openvpn/keys/ta.key 1{$nl}";
		elseif ($expformat == "yealink_t38g2")
			$conf .= "tls-auth /config/openvpn/keys/ta.key 1{$nl}";
		elseif ($expformat == "snom")
			$conf .= "tls-auth /openvpn/ta.key 1{$nl}";
		elseif (substr($expformat, 0, 6) != "inline")
			$conf .= "tls-auth {$prefix}-tls.key 1{$nl}";
	}

	// Prevent MITM attacks by verifying the server certificate.
	// - Disable for now, it requires the server cert to include special options
	//$conf .= "remote-cert-tls server{$nl}";

	// Extra protection for the server cert, if it's supported
	if (function_exists("cert_get_purpose")) {
		if (is_array($server_cert) && ($server_cert['crt'])) {
			$purpose = cert_get_purpose($server_cert['crt'], true);
			if ($purpose['server'] == 'Yes')
				$conf .= "ns-cert-type server{$nl}";
		}
	}

	// add optional settings
	if (!empty($settings['compression'])) {
291
		$conf .= "comp-lzo {$settings['compression']}{$nl}";
292 293
	}

294
	if ($settings['passtos']) {
295
		$conf .= "passtos{$nl}";
296
	}
297

298
	if ($openvpnmanager) {
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
		if (!empty($settings['client_mgmt_port'])) {
			$client_mgmt_port = $settings['client_mgmt_port'];
		} else {
			$client_mgmt_port = 166;
		}
		$conf .= $nl;
		$conf .= "# dont terminate service process on wrong password, ask again{$nl}";
		$conf .= "auth-retry interact{$nl}";
		$conf .= "# open management channel{$nl}";
		$conf .= "management 127.0.0.1 {$client_mgmt_port}{$nl}";
		$conf .= "# wait for management to explicitly start connection{$nl}";
		$conf .= "management-hold{$nl}";
		$conf .= "# query management channel for user/pass{$nl}";
		$conf .= "management-query-passwords{$nl}";
		$conf .= "# disconnect VPN when management program connection is closed{$nl}";
		$conf .= "management-signal{$nl}";
		$conf .= "# forget password when management disconnects{$nl}";
		$conf .= "management-forget-disconnect{$nl}";
		$conf .= $nl;
	};
319

320 321 322 323 324 325 326 327 328 329
	// add advanced options
	$advancedoptions = str_replace("\r\n", "\n", $advancedoptions);
	$advancedoptions = str_replace("\n", $nl, $advancedoptions);
	$advancedoptions = str_replace(";", $nl, $advancedoptions);
	$conf .= $advancedoptions;
	$conf .= $nl;

	switch ($expformat) {
		case "zip":
			// create template directory
330
			$tempdir = "/tmp/{$prefix}";
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
			@mkdir($tempdir, 0700, true);

			file_put_contents("{$tempdir}/{$prefix}.ovpn", $conf);

			$cafile = "{$tempdir}/{$cafile}";
			file_put_contents("{$cafile}", base64_decode($server_ca['crt']));
			if ($settings['tls']) {
				$tlsfile = "{$tempdir}/{$prefix}-tls.key";
				file_put_contents($tlsfile, base64_decode($settings['tls']));
			}

			// write key files
			if ($settings['mode'] != "server_user") {
				$crtfile = "{$tempdir}/{$prefix}-cert.crt";
				file_put_contents($crtfile, base64_decode($cert['crt']));
				$keyfile = "{$tempdir}/{$prefix}.key";
				file_put_contents($keyfile, base64_decode($cert['prv']));

				// convert to pkcs12 format
				$p12file = "{$tempdir}/{$prefix}.p12";
				if ($usetoken)
					openvpn_client_pem_to_pk12($p12file, $outpass, $crtfile, $keyfile);
				else
					openvpn_client_pem_to_pk12($p12file, $outpass, $crtfile, $keyfile, $cafile);
			}
			$command = "cd " . escapeshellarg("{$tempdir}/..")
					. " && /usr/local/bin/zip -r "
358
					. escapeshellarg("/tmp/{$prefix}-config.zip")
359 360 361 362
					. " " . escapeshellarg($prefix);
			exec($command);
			// Remove temporary directory
			exec("rm -rf " . escapeshellarg($tempdir));
363
			return "/tmp/{$prefix}-config.zip";
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
			break;
		case "inline":
		case "inlinedroid":
		case "inlineios":
			// Inline CA
			$conf .= "<ca>{$nl}" . trim(base64_decode($server_ca['crt'])) . "{$nl}</ca>{$nl}";
			if ($settings['mode'] != "server_user") {
				// Inline Cert
				$conf .= "<cert>{$nl}" . trim(base64_decode($cert['crt'])) . "{$nl}</cert>{$nl}";
				// Inline Key
				$conf .= "<key>{$nl}" . trim(base64_decode($cert['prv'])) . "{$nl}</key>{$nl}";
			} else {
				// Work around OpenVPN Connect assuming you have a client cert even when you don't need one
				$conf .= "setenv CLIENT_CERT 0{$nl}";
			}
			// Inline TLS
			if ($settings['tls']) {
				$conf .= "<tls-auth>{$nl}" . trim(base64_decode($settings['tls'])) . "{$nl}</tls-auth>{$nl} key-direction 1{$nl}";
			}
			return $conf;
			break;
		case "yealink_t28":
		case "yealink_t38g":
		case "yealink_t38g2":
			// create template directory
389
			$tempdir = "/tmp/{$prefix}";
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
			$keydir  = "{$tempdir}/keys";
			mkdir($tempdir, 0700, true);
			mkdir($keydir, 0700, true);

			file_put_contents("{$tempdir}/vpn.cnf", $conf);

			$cafile = "{$keydir}/ca.crt";
			file_put_contents("{$cafile}", base64_decode($server_ca['crt']));
			if ($settings['tls']) {
				$tlsfile = "{$keydir}/ta.key";
				file_put_contents($tlsfile, base64_decode($settings['tls']));
			}

			// write key files
			if ($settings['mode'] != "server_user") {
				$crtfile = "{$keydir}/client1.crt";
				file_put_contents($crtfile, base64_decode($cert['crt']));
				$keyfile = "{$keydir}/client1.key";
				file_put_contents($keyfile, base64_decode($cert['prv']));
			}
410
			exec("tar -C {$tempdir} -cf /tmp/client.tar ./keys ./vpn.cnf");
411 412
			// Remove temporary directory
			exec("rm -rf {$tempdir}");
413
			return '/tmp/client.tar';
414 415
		case "snom":
			// create template directory
416
			$tempdir = "/tmp/{$prefix}";
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
			mkdir($tempdir, 0700, true);

			file_put_contents("{$tempdir}/vpn.cnf", $conf);

			$cafile = "{$tempdir}/ca.crt";
			file_put_contents("{$cafile}", base64_decode($server_ca['crt']));
			if ($settings['tls']) {
				$tlsfile = "{$tempdir}/ta.key";
				file_put_contents($tlsfile, base64_decode($settings['tls']));
			}

			// write key files
			if ($settings['mode'] != "server_user") {
				$crtfile = "{$tempdir}/phone1.crt";
				file_put_contents($crtfile, base64_decode($cert['crt']));
				$keyfile = "{$tempdir}/phone1.key";
				file_put_contents($keyfile, base64_decode($cert['prv']));
			}
435
			exec("cd {$tempdir}/ && tar -cf /tmp/vpnclient.tar *");
436 437
			// Remove temporary directory
			exec("rm -rf {$tempdir}");
438
			return '/tmp/vpnclient.tar';
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 473 474 475
		default:
			return $conf;
	}
}

function openvpn_client_export_installer($srvid, $usrid, $crtid, $useaddr, $verifyservercn, $randomlocalport, $usetoken, $outpass, $proxy, $openvpnmanager, $advancedoptions, $openvpn_version = "x86-xp") {
	global $config, $g, $input_errors, $current_openvpn_version, $current_openvpn_version_rev;
	$uname_p = trim(exec("uname -p"));

	switch ($openvpn_version) {
		case "x86-xp":
			$client_install_exe = "openvpn-install-{$current_openvpn_version}-I0{$current_openvpn_version_rev}-i686.exe";
			break;
		case "x64-xp":
			$client_install_exe = "openvpn-install-{$current_openvpn_version}-I0{$current_openvpn_version_rev}-x86_64.exe";
			break;
		case "x86-win6":
			$client_install_exe = "openvpn-install-{$current_openvpn_version}-I6{$current_openvpn_version_rev}-i686.exe";
			break;
		case "x64-win6":
			$client_install_exe = "openvpn-install-{$current_openvpn_version}-I6{$current_openvpn_version_rev}-x86_64.exe";
			break;
		default:
			$client_install_exe = "openvpn-install-{$current_openvpn_version}-I0{$current_openvpn_version_rev}-i686.exe";
	}

	$ovpndir = "/usr/local/share/openvpn";
	$workdir = "{$ovpndir}/client-export";

	$validconfig = openvpn_client_export_validate_config($srvid, $usrid, $crtid);
	if ($validconfig) {
		list($settings, $server_cert, $server_ca, $servercn, $user, $cert, $nokeys) = $validconfig;
	} else {
		return false;
	}

	// create template directory
476
	$tempdir = "/tmp//openvpn-export-".uniqid();
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
	mkdir($tempdir, 0700, true);

	// create config directory
	$confdir = "{$tempdir}/config";
	if (!is_dir($conf_dir))
		mkdir($confdir, 0700, true);

	// copy the template directory
	exec("cp -r {$workdir}/template/* {$tempdir}");
	// and put the required installer exe in place
	exec("/bin/cp {$tempdir}/{$client_install_exe} {$tempdir}/openvpn-install.exe");
	if (stristr($openvpn_version, "x64"))
		rename("{$tempdir}/openvpn-postinstall64.exe", "{$tempdir}/openvpn-postinstall.exe");

	// write configuration file
	$prefix = openvpn_client_export_prefix($srvid, $usrid, $crtid);
	$cfgfile = "{$confdir}/{$prefix}-config.ovpn";
	if (!empty($proxy) && $proxy['proxy_authtype'] != "none") {
		$proxy['passwdfile'] = "{$prefix}-password";
		$pwdfle = "{$proxy['user']}\r\n";
		$pwdfle .= "{$proxy['password']}\r\n";
		file_put_contents("{$confdir}/{$proxy['passwdfile']}", $pwdfle);
	}
	$conf = openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $verifyservercn, $randomlocalport, $usetoken,  $nokeys, $proxy, "", "baseconf", false, true, $openvpnmanager, $advancedoptions);
	if (!$conf) {
502
		$input_errors[] = gettext("Could not create a config to export.");
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 532 533 534 535 536 537
		return false;
	}

	file_put_contents($cfgfile, $conf);

	$cafile = "{$tempdir}/config/{$prefix}-ca.crt";
	file_put_contents($cafile, base64_decode($server_ca['crt']));
	if ($settings['tls']) {
		$tlsfile = "{$tempdir}/config/{$prefix}-tls.key";
		file_put_contents($tlsfile, base64_decode($settings['tls']));
	}

	// write key files
	if ($settings['mode'] != "server_user") {
		$crtfile = "{$tempdir}/config/{$prefix}-{$user['name']}.crt";
		file_put_contents($crtfile, base64_decode($cert['crt']));
		$keyfile = "{$tempdir}/config/{$prefix}-{$user['name']}.key";
		file_put_contents($keyfile, base64_decode($cert['prv']));
		// convert to pkcs12 format
		$p12file = "{$tempdir}/config/{$prefix}.p12";
		if ($usetoken)
			openvpn_client_pem_to_pk12($p12file, $outpass, $crtfile, $keyfile);
		else
			openvpn_client_pem_to_pk12($p12file, $outpass, $crtfile, $keyfile, $cafile);
	}

	// 7zip the configuration data
	chdir($tempdir);
	$files  = "config ";
	if ($openvpnmanager)
		$files .= "openvpnmanager ";

	$files .= "openvpn-install.exe ";
	$files .= "openvpn-postinstall.exe ";
	if ($usetoken)
538
		$procchain =	';!@Install@!UTF-8!
539 540 541 542
RunProgram="openvpn-postinstall.exe /Import"
;!@InstallEnd@!'
;
	else
543
		$procchain =	';!@Install@!UTF-8!
544 545 546 547 548 549 550 551 552 553 554 555
RunProgram="openvpn-postinstall.exe"
;!@InstallEnd@!'
;
	file_put_contents("{$tempdir}/7zipConfig",$procchain);

	if(file_exists("/usr/pbi/p7zip-{$uname_p}/bin/7z"))
		exec("/usr/pbi/p7zip-{$uname_p}/bin/7z -y a archive.7z {$files}");
	else
		exec("/usr/local/libexec/p7zip/7z -y a archive.7z {$files}");

	// create the final installer
	$outfile = "{$tempdir}-install.exe";
556
	chdir('/tmp');
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
	exec("/bin/cat {$tempdir}/7zS.sfx {$tempdir}/7zipConfig {$tempdir}/archive.7z > {$outfile}");

	// cleanup
	exec("/bin/rm -r {$tempdir}");

	return $outfile;
}

function viscosity_openvpn_client_config_exporter($srvid, $usrid, $crtid, $useaddr, $verifyservercn, $randomlocalport, $usetoken, $outpass, $proxy, $openvpnmanager, $advancedoptions) {
	global $config, $g;
	$uname_p = trim(exec("uname -p"));

	$ovpndir = "/usr/local/share/openvpn/";

	$uniq = uniqid();
572 573
	$tempdir = "/tmp/openvpn-export-{$uniq}";
	$zipfile = "/tmp/{$uniq}-Viscosity.visc.zip";
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

	$validconfig = openvpn_client_export_validate_config($srvid, $usrid, $crtid);
	if ($validconfig) {
		list($settings, $server_cert, $server_ca, $servercn, $user, $cert, $nokeys) = $validconfig;
	} else {
		return false;
	}

	// create template directory
	mkdir($tempdir, 0700, true);
	mkdir($tempdir . "/Viscosity.visc", 0700, true);

	// Append new Viscosity.visc directory on top
	$tempdir = $tempdir . "/Viscosity.visc/";

	// write cofiguration file
	$prefix = openvpn_client_export_prefix($srvid, $usrid, $crtid);
	if (!empty($proxy) && $proxy['proxy_authtype'] != "none") {
		$proxy['passwdfile'] = "config-password";
		$pwdfle = "{$proxy['user']}\n";
		$pwdfle .= "{$proxy['password']}\n";
		file_put_contents("{$tempdir}/{$proxy['passwdfile']}", $pwdfle);
	}

	$conf = openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $verifyservercn, $randomlocalport, $usetoken, true, $proxy, "baseconf", $outpass, true, true, $openvpnmanager, $advancedoptions);
	if (!$conf)
		return false;

	// We need to nuke the ca line from the above config if it exists.
	$conf = explode("\n", $conf);
	for ($i=0; $i < count($conf); $i++) {
		if ((substr($conf[$i], 0, 3) == "ca ") || (substr($conf[$i], 0, 7) == "pkcs12 "))
			unset($conf[$i]);
	}
	$conf = implode("\n", $conf);

	$friendly_name = $settings['description'];
	$visc_settings = <<<EOF
612
#-- Config Auto Generated for Viscosity --#
613 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

#viscosity startonopen false
#viscosity dhcp true
#viscosity dnssupport true
#viscosity name {$friendly_name}

EOF;

	$configfile = "{$tempdir}/config.conf";
	$conf .= "ca ca.crt\n";
	$conf .= "tls-auth ta.key 1\n";
	if ($settings['mode'] != "server_user") {
		$conf .= <<<EOF
cert cert.crt
key key.key
EOF;
	}

	file_put_contents($configfile, $visc_settings . "\n" . $conf);

	//	ca.crt		cert.crt	config.conf	key.key		ta.key

	// write ca
	$cafile = "{$tempdir}/ca.crt";
	file_put_contents($cafile, base64_decode($server_ca['crt']));

	if ($settings['mode'] != "server_user") {

		// write user .crt
		$crtfile = "{$tempdir}/cert.crt";
		file_put_contents($crtfile, base64_decode($cert['crt']));

		// write user .key
		if (!empty($outpass)) {
			$keyfile = "{$tempdir}/key.key";
			$clearkeyfile = "{$tempdir}/key-clear.key";
			file_put_contents($clearkeyfile, base64_decode($cert['prv']));
			$eoutpass = escapeshellarg($outpass);
			$ekeyfile = escapeshellarg($keyfile);
			$eclearkeyfile = escapeshellarg($clearkeyfile);
653
			exec("/usr/local/bin/openssl rsa -in ${eclearkeyfile} -out ${ekeyfile} -des3 -passout pass:${eoutpass}");
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
			unlink($clearkeyfile);
		} else {
			$keyfile = "{$tempdir}/key.key";
			file_put_contents($keyfile, base64_decode($cert['prv']));
		}
	}

	// TLS support?
	if ($settings['tls']) {
		$tlsfile = "{$tempdir}/ta.key";
		file_put_contents($tlsfile, base64_decode($settings['tls']));
	}

	// Zip Viscosity file
	if(file_exists("/usr/pbi/zip-{$uname_p}/bin/zip"))
		exec("cd {$tempdir}/.. && /usr/pbi/zip-{$uname_p}/bin/zip -r {$zipfile} Viscosity.visc");
	else
		exec("cd {$tempdir}/.. && /usr/local/bin/zip -r {$zipfile} Viscosity.visc");

	// Remove temporary directory
	exec("rm -rf {$tempdir}");

	return $zipfile;

}

function openvpn_client_export_sharedkey_config($srvid, $useaddr, $proxy, $zipconf = false) {
	global $config, $input_errors, $g;

	// lookup server settings
	$settings = $config['openvpn']['openvpn-server'][$srvid];
	if (empty($settings)) {
686
		$input_errors[] = gettext("Could not locate server configuration.");
687 688 689
		return false;
	}
	if ($settings['disable']) {
690
		$input_errors[] = gettext("You cannot export for disabled servers.");
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 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 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
		return false;
	}

	// determine basic variables
	if ($useaddr == "serveraddr") {
		$interface = $settings['interface'];
		if (!empty($settings['ipaddr']) && is_ipaddr($settings['ipaddr'])) {
			$server_host = $settings['ipaddr'];
		} else {
			if (!$interface)
				$interface = "wan";
			if (in_array(strtolower($settings['protocol']), array("udp6", "tcp6")))
				$server_host = get_interface_ipv6($interface);
			else
				$server_host = get_interface_ip($interface);
		}
	} else if ($useaddr == "serverhostname" || empty($useaddr)) {
		$server_host = empty($config['system']['hostname']) ? "" : "{$config['system']['hostname']}.";
		$server_host .= "{$config['system']['domain']}";
	} else
		$server_host = $useaddr;

	$server_port = $settings['local_port'];

	$proto = strtolower($settings['protocol']);
	if (strtolower(substr($settings['protocol'], 0, 3)) == "tcp")
		$proto .= "-client";

	$cipher = $settings['crypto'];
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";

	// add basic settings
	$conf  = "dev tun\n";
	if(! empty($settings['tunnel_networkv6'])) {
		$conf .= "tun-ipv6\n";
	}
	$conf .= "persist-tun\n";
	$conf .= "persist-key\n";
	$conf .= "proto {$proto}\n";
	$conf .= "cipher {$cipher}\n";
	$conf .= "auth {$digest}\n";
	$conf .= "pull\n";
	$conf .= "resolv-retry infinite\n";
	$conf .= "remote {$server_host} {$server_port}\n";
	if ($settings['local_network']) {
		list($ip, $mask) = explode('/', $settings['local_network']);
		$mask = gen_subnet_mask($mask);
		$conf .= "route $ip $mask\n";
	}
	if (!empty($settings['tunnel_network'])) {
		list($ip, $mask) = explode('/', $settings['tunnel_network']);
		$mask = gen_subnet_mask($mask);
		$baselong = ip2long32($ip) & ip2long($mask);
		$ip1 = long2ip32($baselong + 1);
		$ip2 = long2ip32($baselong + 2);
		$conf .= "ifconfig $ip2 $ip1\n";
	}
	$conf .= "keepalive 10 60\n";
	$conf .= "ping-timer-rem\n";

	if (!empty($proxy)) {
		if ($proxy['proxy_type'] == "http") {
			if ($proto == "udp") {
754
				$input_errors[] = gettext("This server uses UDP protocol and cannot communicate with HTTP proxy.");
755 756 757 758
				return;
			}
			$conf .= "http-proxy {$proxy['ip']} {$proxy['port']} ";
		}
759
		if ($proxy['proxy_type'] == "socks")
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
			$conf .= "socks-proxy {$proxy['ip']} {$proxy['port']} ";
		if ($proxy['proxy_authtype'] != "none") {
			if (!isset($proxy['passwdfile']))
				$proxy['passwdfile'] = openvpn_client_export_prefix($srvid) . "-proxy";
			$conf .= " {$proxy['passwdfile']} {$proxy['proxy_authtype']}";
		}
		$conf .= "\n";
	}

	// add key settings
	$prefix = openvpn_client_export_prefix($srvid);
	$shkeyfile = "{$prefix}.secret";
	$conf .= "secret {$shkeyfile}\n";

	// add optional settings
	if ($settings['compression'])
		$conf .= "comp-lzo\n";
	if ($settings['passtos'])
		$conf .= "passtos\n";

	if ($zipconf == true) {
		// create template directory
782
		$tempdir = "/tmp/{$prefix}";
783 784 785 786 787 788 789 790
		mkdir($tempdir, 0700, true);

		file_put_contents("{$tempdir}/{$prefix}.ovpn", $conf);

		$shkeyfile = "{$tempdir}/{$shkeyfile}";
		file_put_contents("{$shkeyfile}", base64_decode($settings['shared_key']));

		if(file_exists("/usr/pbi/zip-{$uname_p}/bin/zip"))
791
			exec("cd {$tempdir}/.. && /usr/pbi/zip-{$uname_p}/bin/zip -r /tmp/{$prefix}-config.zip {$prefix}");
792
		else
793
			exec("cd {$tempdir}/.. && /usr/local/bin/zip -r /tmp/{$prefix}-config.zip {$prefix}");
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841

		// Remove temporary directory
		exec("rm -rf {$tempdir}");
		return "{$prefix}-config.zip";
	} else
		return $conf;
}

function openvpn_client_export_build_remote_lines($settings, $useaddr, $interface, $expformat, $nl) {
	global $config;
	$remotes = array();
	if (($useaddr == "serveraddr") || ($useaddr == "servermagic") || ($useaddr == "servermagichost")) {
		$interface = $settings['interface'];
		if (!empty($settings['ipaddr']) && is_ipaddr($settings['ipaddr'])) {
			$server_host = $settings['ipaddr'];
		} else {
			if (!$interface || ($interface == "any"))
				$interface = "wan";
			if (in_array(strtolower($settings['protocol']), array("udp6", "tcp6")))
				$server_host = get_interface_ipv6($interface);
			else
				$server_host = get_interface_ip($interface);
		}
	} else if ($useaddr == "serverhostname" || empty($useaddr)) {
		$server_host = empty($config['system']['hostname']) ? "" : "{$config['system']['hostname']}.";
		$server_host .= "{$config['system']['domain']}";
	} else
		$server_host = $useaddr;

	$proto = strtolower($settings['protocol']);
	if (strtolower(substr($settings['protocol'], 0, 3)) == "tcp")
		$proto .= "-client";

	if (($expformat == "inlineios") && ($proto == "tcp-client"))
		$proto = "tcp";

	if (($useaddr == "servermagic") || ($useaddr == "servermagichost")) {
		$destinations = openvpn_client_export_find_port_forwards($server_host, $settings['local_port'], $proto, true, ($useaddr == "servermagichost"));
		foreach ($destinations as $dest) {
			$remotes[] = "remote {$dest['host']} {$dest['port']} {$dest['proto']}";
		}
	} else {
		$remotes[] = "remote {$server_host} {$settings['local_port']} {$proto}";
	}

	return implode($nl, $remotes);
}

842 843
function openvpn_client_export_find_port_forwards($targetip, $targetport, $targetproto, $skipprivate, $findhostname = false)
{
844
	global $config;
845 846

	$FilterIflist = filter_generate_optcfg_array();
847 848
	$destinations = array();

849
	if (!isset($config['nat']['rule'])) {
850
		return $destinations;
851
	}
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867

	foreach ($config['nat']['rule'] as $natent) {
		$dest = array();
		if (!isset($natent['disabled'])
			&& ($natent['target'] == $targetip)
			&& ($natent['local-port'] == $targetport)
			&& ($natent['protocol'] == $targetproto)) {
			$dest['proto'] = $natent['protocol'];

			// Could be multiple ports... But we can only use one.
			$dports = is_port($natent['destination']['port']) ? array($natent['destination']['port']) : filter_expand_alias_array($natent['destination']['port']);
			$dest['port'] = $dports[0];

			// Could be network or address ...
			$natif = (!$natent['interface']) ? "wan" : $natent['interface'];

868
			if (!isset($FilterIflist[$natif])) {
869
				continue; // Skip if there is no interface
870
			}
871

872
			$dstaddr = trim(filter_generate_address($FilterIflist, $natent, 'destination', true));
873
			if (!$dstaddr) {
874
				$dstaddr = $FilterIflist[$natif]['ip'];
875
			}
876 877 878 879 880 881 882 883 884 885 886 887 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

			$dstaddr_port = explode(" ", $dstaddr);

			if(empty($dstaddr_port[0]) || strtolower(trim($dstaddr_port[0])) == "port")
				continue; // Skip port forward if no destination address found


			if (!is_ipaddr($dstaddr_port[0]))
				continue; // We can only work with single IPs, not subnets!


			if ($skipprivate && is_private_ip($dstaddr_port[0]))
				continue; // Skipping a private IP destination!

			$dest['host'] = $dstaddr_port[0];

			if ($findhostname) {
				$hostname = openvpn_client_export_find_hostname($natif);
				if (!empty($hostname))
					$dest['host'] = $hostname;
			}

			$destinations[] = $dest;
		}
	}

	return $destinations;
}

function openvpn_client_export_find_hostname($interface) {
	global $config;
	$hostname = "";
	if (is_array($config['dyndnses']['dyndns'])) {
		foreach ($config['dyndnses']['dyndns'] as $ddns) {
			if (($ddns['interface'] == $interface) && isset($ddns['enable']) && !empty($ddns['host']) && !is_numeric($ddns['host']) && is_hostname($ddns['host']))
				return $ddns['host'];
		}
	}
	if (is_array($config['dnsupdates']['dnsupdate'])) {
		foreach ($config['dnsupdates']['dnsupdate'] as $ddns) {
			if (($ddns['interface'] == $interface) && isset($ddns['enable']) && !empty($ddns['host']) && !is_numeric($ddns['host']) && is_hostname($ddns['host']))
				return $ddns['host'];
		}
	}

}
?>