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

Ad Schellevis's avatar
Ad Schellevis committed
3 4 5 6
/*
	Copyright (C) 2007 Scott Ullrich
	Copyright (C) 2008 Shrew Soft Inc
	Copyright (C) 2003-2004 Manuel Kasper
7
	All rights reserved.
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

	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.
*/
30
require_once("xmlparse.inc");
Ad Schellevis's avatar
Ad Schellevis committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 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

/* IPsec defines */
$ipsec_loglevels = array("dmn" => "Daemon", "mgr" => "SA Manager", "ike" => "IKE SA", "chd" => "IKE Child SA",
	"job" => "Job Processing", "cfg" => "Configuration backend", "knl" => "Kernel Interface",
	"net" => "Networking", "asn" => "ASN encoding", "enc" => "Message encoding",
	"imc" => "Integrity checker", "imv" => "Integrity Verifier", "pts" => "Platform Trust Service",
	"tls" => "TLS handler", "esp" => "IPsec traffic", "lib" => "StrongSWAN Lib");

$my_identifier_list = array(
	'myaddress' => array( 'desc' => gettext('My IP address'), 'mobile' => true ),
	'address' => array( 'desc' => gettext('IP address'), 'mobile' => true ),
	'fqdn' => array( 'desc' => gettext('Distinguished name'), 'mobile' => true ),
	'user_fqdn' => array( 'desc' => gettext('User distinguished name'), 'mobile' => true ),
	'asn1dn' => array( 'desc' => gettext('ASN.1 distinguished Name'), 'mobile' => true ),
	'keyid tag' => array( 'desc' => gettext('KeyID tag'), 'mobile' => true ),
	'dyn_dns' => array( 'desc' => gettext('Dynamic DNS'), 'mobile' => true ));

$peer_identifier_list = array(
	'peeraddress' => array( 'desc' => gettext('Peer IP address'), 'mobile' => false ),
	'address' => array( 'desc' => gettext('IP address'), 'mobile' => false ),
	'fqdn' => array( 'desc' => gettext('Distinguished name'), 'mobile' => true ),
	'user_fqdn' => array( 'desc' => gettext('User distinguished name'), 'mobile' => true ),
	'asn1dn' => array( 'desc' => gettext('ASN.1 distinguished Name'), 'mobile' => true ),
	'keyid tag' => array( 'desc' =>gettext('KeyID tag'), 'mobile' => true ));

$p1_ealgos = array(
	'aes' => array( 'name' => 'AES', 'keysel' => array( 'lo' => 128, 'hi' => 256, 'step' => 64 ) ),
	'aes128gcm' => array( 'name' => 'AES128-GCM', 'keysel' => array( 'lo' => 64, 'hi' => 128, 'step' => 32 ) ),
	'aes192gcm' => array( 'name' => 'AES192-GCM', 'keysel' => array( 'lo' => 64, 'hi' => 128, 'step' => 32 ) ),
	'aes256gcm' => array( 'name' => 'AES256-GCM', 'keysel' => array( 'lo' => 64, 'hi' => 128, 'step' => 32 ) ),
	'blowfish' => array( 'name' => 'Blowfish', 'keysel' => array( 'lo' => 128, 'hi' => 256, 'step' => 64 ) ),
	'3des' => array( 'name' => '3DES' ),
	'cast128' => array( 'name' => 'CAST128' ),
	'des' => array( 'name' => 'DES' ));

$p2_ealgos = array(
	'aes' => array( 'name' => 'AES', 'keysel' => array( 'lo' => 128, 'hi' => 256, 'step' => 64 ) ),
	'aes128gcm' => array( 'name' => 'AES128-GCM', 'keysel' => array( 'lo' => 64, 'hi' => 128, 'step' => 32 ) ),
	'aes192gcm' => array( 'name' => 'AES192-GCM', 'keysel' => array( 'lo' => 64, 'hi' => 128, 'step' => 32 ) ),
	'aes256gcm' => array( 'name' => 'AES256-GCM', 'keysel' => array( 'lo' => 64, 'hi' => 128, 'step' => 32 ) ),
	'blowfish' => array( 'name' => 'Blowfish', 'keysel' => array( 'lo' => 128, 'hi' => 256, 'step' => 64 ) ),
	'3des' => array( 'name' => '3DES' ),
	'cast128' => array( 'name' => 'CAST128' ),
	'des' => array( 'name' => 'DES' ));

$p1_halgos = array(
	'md5' => 'MD5',
	'sha1' => 'SHA1',
	'sha256' => 'SHA256',
	'sha384' => 'SHA384',
	'sha512' => 'SHA512',
	'aesxcbc' => 'AES-XCBC'
);

$p1_dhgroups = array(
	1  => '1 (768 bit)',
	2  => '2 (1024 bit)',
	5  => '5 (1536 bit)',
	14 => '14 (2048 bit)',
	15 => '15 (3072 bit)',
	16 => '16 (4096 bit)',
	17 => '17 (6144 bit)',
	18 => '18 (8192 bit)',
	22 => '22 (1024(sub 160) bit)',
	23 => '23 (2048(sub 224) bit)',
	24 => '24 (2048(sub 256) bit)'
);

$p2_halgos = array(
	'hmac_md5' => 'MD5',
	'hmac_sha1' => 'SHA1',
	'hmac_sha256' => 'SHA256',
	'hmac_sha384' => 'SHA384',
	'hmac_sha512' => 'SHA512',
	'aesxcbc' => 'AES-XCBC'
);

$p1_authentication_methods = array(
	'hybrid_rsa_server' => array( 'name' => 'Hybrid RSA + Xauth', 'mobile' => true ),
	'xauth_rsa_server' => array( 'name' => 'Mutual RSA + Xauth', 'mobile' => true ),
	'xauth_psk_server' => array( 'name' => 'Mutual PSK + Xauth', 'mobile' => true ),
	'eap-tls' => array( 'name' => 'EAP-TLS', 'mobile' => true),
	'rsasig' => array( 'name' => 'Mutual RSA', 'mobile' => false ),
	'pre_shared_key' => array( 'name' => 'Mutual PSK', 'mobile' => false ) );

$p2_modes = array(
	'tunnel' => 'Tunnel IPv4',
	'tunnel6' => 'Tunnel IPv6',
	'transport' => 'Transport');

$p2_protos = array(
	'esp' => 'ESP',
	'ah' => 'AH');

$p2_pfskeygroups = array(
	0 => 'off',
	1  => '1 (768 bit)',
	2  => '2 (1024 bit)',
	5  => '5 (1536 bit)',
	14 => '14 (2048 bit)',
	15 => '15 (3072 bit)',
	16 => '16 (4096 bit)',
	17 => '17 (6144 bit)',
	18 => '18 (8192 bit)'
);

/*
 * ikeid management functions
 */

function ipsec_ikeid_used($ikeid) {
	global $config;

	foreach ($config['ipsec']['phase1'] as $ph1ent)
		if( $ikeid == $ph1ent['ikeid'] )
			return true;

	return false;
}

function ipsec_ikeid_next() {

	$ikeid = 1;
	while(ipsec_ikeid_used($ikeid))
		$ikeid++;

	return $ikeid;
}

/*
 * Return phase1 local address
 */
function ipsec_get_phase1_src(& $ph1ent) {

	if ($ph1ent['interface']) {
		if (!is_ipaddr($ph1ent['interface'])) {
167
			if ($ph1ent['protocol'] == "inet6") {
Ad Schellevis's avatar
Ad Schellevis committed
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
				$if = get_failover_interface($ph1ent['interface'], "inet6");
				$interfaceip = get_interface_ipv6($if);
			} else {
				$if = get_failover_interface($ph1ent['interface']);
				$interfaceip = get_interface_ip($if);
			}
		} else {
			$interfaceip=$ph1ent['interface'];
		}
	} else {
		$if = "wan";
		if ($ph1ent['protocol'] == "inet6")
			$interfaceip = get_interface_ipv6($if);
		else
			$interfaceip = get_interface_ip($if);
	}

	return $interfaceip;
}

/*
 * Return phase1 local address
 */
function ipsec_get_phase1_dst(& $ph1ent) {
	global $g;

	if (empty($ph1ent['remote-gateway']))
		return false;
	$rg = $ph1ent['remote-gateway'];
	if (!is_ipaddr($rg)) {
Ad Schellevis's avatar
Ad Schellevis committed
198
		if(! file_exists("/var/run/booting"))
Ad Schellevis's avatar
Ad Schellevis committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 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 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
			return resolve_retry($rg);
	}
	if(!is_ipaddr($rg))
		return false;

	return $rg;
}

/*
 * Return phase2 idinfo in cidr format
 */
function ipsec_idinfo_to_cidr(& $idinfo, $addrbits = false, $mode = "") {
	global $config;

	switch ($idinfo['type']) {
		case "address":
			if ($addrbits) {
				if ($mode == "tunnel6")
					return $idinfo['address']."/128";
				else
					return $idinfo['address']."/32";
			} else
				return $idinfo['address'];
			break; /* NOTREACHED */
		case "network":
			return "{$idinfo['address']}/{$idinfo['netbits']}";
			break; /* NOTREACHED */
		case "none":
		case "mobile":
			return "0.0.0.0/0";
			break; /* NOTREACHED */
		default:
			if (empty($mode) && !empty($idinfo['mode']))
				$mode = $idinfo['mode'];

			if ($mode == "tunnel6") {
				$address = get_interface_ipv6($idinfo['type']);
				$netbits = get_interface_subnetv6($idinfo['type']);
				$address = gen_subnetv6($address,$netbits);
				return "{$address}/{$netbits}";
			} else {
				$address = get_interface_ip($idinfo['type']);
				$netbits = get_interface_subnet($idinfo['type']);
				$address = gen_subnet($address,$netbits);
				return "{$address}/{$netbits}";
			}
			break; /* NOTREACHED */
	}
}


/*
 *  Return phase2 idinfo in text format
 */
function ipsec_idinfo_to_text(& $idinfo) {
	global $config;

	switch ($idinfo['type']) {
        case "address":
		return $idinfo['address'];
		break; /* NOTREACHED */
        case "network":
		return $idinfo['address']."/".$idinfo['netbits'];
		break; /* NOTREACHED */
	case "mobile":
		return gettext("Mobile Client");
		break; /* NOTREACHED */
	case "none":
		return gettext("None");
		break; /* NOTREACHED */
        default:
		if (!empty($config['interfaces'][$idinfo['type']]))
			return convert_friendly_interface_to_friendly_descr($idinfo['type']);
		else
			return strtoupper($idinfo['type']);
		break; /* NOTREACHED */
	}
}

/*
 * Return phase1 association for phase2
 */
function ipsec_lookup_phase1(& $ph2ent,& $ph1ent) {
	global $config;

	if (!is_array($config['ipsec']))
		return false;
	if (!is_array($config['ipsec']['phase1']))
		return false;
	if (empty($config['ipsec']['phase1']))
		return false;

	foreach ($config['ipsec']['phase1'] as $ph1tmp) {
	    if ($ph1tmp['ikeid'] == $ph2ent['ikeid']) {
		$ph1ent = $ph1tmp;
		return $ph1ent;
	    }
	}

	return false;
}

/*
 * Check phase1 communications status
 */
function ipsec_phase1_status($ipsec_status, $ikeid) {

	foreach ($ipsec_status as $ike) {
		if ($ike['id'] != $ikeid)
			continue;
		if ($ike['status'] == 'established')
			return true;
		break;
	}

	return false;
}

function ipsec_smp_dump_status() {
	global $config, $g, $custom_listtags;

320
	if (!file_exists("/var/run/charon.xml")) {
Ad Schellevis's avatar
Ad Schellevis committed
321 322 323 324
		log_error("IPsec daemon seems to have issues or not running!");
		return;
	}

325
	$fd = @fsockopen("unix:///var/run/charon.xml");
Ad Schellevis's avatar
Ad Schellevis committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
	if (!$fd) {
		log_error("Could not read status from ipsec");
		return;
	}
	$query = '<?xml version="1.0"?><message xmlns="http://www.strongswan.org/smp/1.0" type="request" id="1">';
	$query .= '<query><ikesalist/></query></message>';

	@fwrite($fd, $query);
	$response = "";
	while (!strstr($sread, "</message>")) {
		$sread = fgets($fd);
		$response .= $sread;
	}
	fclose($fd);

341 342
	$smp_status_xml = '/tmp/smp_status.xml';
	@file_put_contents($smp_status_xml, $response);
Ad Schellevis's avatar
Ad Schellevis committed
343 344 345
	unset($response, $sread);

	$custom_listtags = array('ikesa', 'childsa', 'network', 'auth');
346 347
	$response = parse_xml_config($smp_status_xml, 'message');
	@unlink($smp_status_xml);
Ad Schellevis's avatar
Ad Schellevis committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 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 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 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
	unset($custom_listtags);

	return $response;
}

/*
 * Return dump of SPD table
 */
function ipsec_dump_spd()
{
	$fd = @popen("/sbin/setkey -DP", "r");
	$spd = array();
	if ($fd) {
		while (!feof($fd)) {
			$line = chop(fgets($fd));
			if (!$line)
				continue;
			if ($line == "No SPD entries.")
				break;
			if ($line[0] != "\t") {
				if (is_array($cursp))
					$spd[] = $cursp;
				$cursp = array();
				$linea = explode(" ", $line);
				$cursp['srcid'] = substr($linea[0], 0, strpos($linea[0], "["));
				$cursp['dstid'] = substr($linea[1], 0, strpos($linea[1], "["));
				$i = 0;
			} else if (is_array($cursp)) {
				$linea = explode(" ", trim($line));
				switch($i)
				{
					case 1:
						if ($linea[1] == "none")	/* don't show default anti-lockout rule */
							unset($cursp);
						else
							$cursp['dir'] = $linea[0];
						break;
					case 2:
						$upperspec = explode("/", $linea[0]);
						$cursp['proto'] = $upperspec[0];
						list($cursp['src'], $cursp['dst']) = explode("-", $upperspec[2]);
						$cursp['reqid'] =  substr($upperspec[3], strpos($upperspec[3], "#")+1);
						break;
				}
			}
			$i++;
		}
		if (is_array($cursp) && count($cursp))
			$spd[] = $cursp;
		pclose($fd);
	}

	return $spd;
}

/*
 * Return dump of SAD table
 */
function ipsec_dump_sad()
{
	$fd = @popen("/sbin/setkey -D", "r");
	$sad = array();
	if ($fd) {
		while (!feof($fd)) {
			$line = chop(fgets($fd));
			if (!$line || $line[0] == " ")
				continue;
			if ($line == "No SAD entries.")
				break;
			if ($line[0] != "\t")
			{
				if (is_array($cursa))
					$sad[] = $cursa;
				$cursa = array();
				list($cursa['src'],$cursa['dst']) = explode(" ", $line);
				$i = 0;
			}
			else
			{
				$linea = explode(" ", trim($line));
				switch ($i) {
					case 1:
						$cursa['proto'] = $linea[0];
						$cursa['spi'] = substr($linea[2], strpos($linea[2], "x")+1, -1);
						$reqid = substr($linea[3], strpos($linea[3], "=")+1);
						$cursa['reqid'] = substr($reqid, 0, strcspn($reqid,"("));
						break;
					case 2:
						$cursa['ealgo'] = $linea[1];
						break;
					case 3:
						$cursa['aalgo'] = $linea[1];
						break;
					case 8:
						$sadata = explode("(", $linea[1]);
						$cursa['data'] = $sadata[0] . " B";
						break;
				}
			}
			$i++;
		}
		if (is_array($cursa) && count($cursa))
			$sad[] = $cursa;
		pclose($fd);
	}

	return $sad;
}

/*
 * Return dump of mobile user list
 */
460 461
function ipsec_dump_mobile()
{
Ad Schellevis's avatar
Ad Schellevis committed
462 463
	global $g, $custom_listtags;

464 465 466
	$strongswan_leases_xml = '/tmp/strongswan_leases.xml';

	$_gb = exec(sprintf('/usr/local/sbin/ipsec stroke leases > %s', $strongswan_leases_xml));
Ad Schellevis's avatar
Ad Schellevis committed
467

468
	if (!file_exists($strongswan_leases_xml)) {
Ad Schellevis's avatar
Ad Schellevis committed
469 470 471 472 473
		log_error(gettext("IPsec daemon seems to have issues or not running! Could not display mobile user stats!"));
		return array();
	}

	$custom_listtags = array('lease', 'pool');
474 475
	$response = parse_xml_config($strongswan_leases_xml, 'leases');
	@unlink($strongswan_leases_xml);
Ad Schellevis's avatar
Ad Schellevis committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
	unset($custom_listtags, $_gb);

	return $response;
}

function ipsec_mobilekey_sort() {
	global $config;

	function mobilekeycmp($a, $b) {
		return strcmp($a['ident'][0], $b['ident'][0]);
	}

	usort($config['ipsec']['mobilekey'], "mobilekeycmp");
}

function ipsec_get_number_of_phase2($ikeid) {
	global $config;
493
	$a_phase2 = $config['ipsec']['phase2'];
Ad Schellevis's avatar
Ad Schellevis committed
494 495 496

	$nbph2=0;

497 498 499
	if (is_array($a_phase2) && count($a_phase2)) {
		foreach ($a_phase2 as $ph2tmp) {
			if ($ph2tmp['ikeid'] == $ikeid) {
Ad Schellevis's avatar
Ad Schellevis committed
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 532 533 534 535 536 537 538 539 540 541 542
				$nbph2++;
			}
		}
	}

	return $nbph2;
}

function ipsec_get_descr($ikeid) {
	global $config;

	if (!isset($config['ipsec']['phase1']) ||
	    !is_array($config['ipsec']['phase1']))
		return "";

	$descr = '';
	$a_phase1 = $config['ipsec']['phase1'];
	foreach ($a_phase1 as $p1) {
		if ($p1['ikeid'] == $ikeid) {
			$descr = $p1['descr'];
			break;
		}
	}
	unset($a_phase1);

	return $descr;
}

function ipsec_fixup_ip($ipaddr) {
	if (is_ipaddrv6($ipaddr) || is_subnetv6($ipaddr))
		return Net_IPv6::compress(Net_IPv6::uncompress($ipaddr));
	else
		return $ipaddr;
}

function ipsec_find_id(& $ph1ent, $side = "local", $rgmap = array()) {
	if ($side == "local") {
		$id_type = $ph1ent['myid_type'];
		$id_data = $ph1ent['myid_data'];

		$addr = ipsec_get_phase1_src($ph1ent);
		if (!$addr)
			return array();
543
	} elseif ($side == "peer") {
Ad Schellevis's avatar
Ad Schellevis committed
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 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
		$id_type = $ph1ent['peerid_type'];
		$id_data = $ph1ent['peerid_data'];

		if (isset($ph1ent['mobile']))
			$addr = "%any";
		else
			$addr = $ph1ent['remote-gateway'];
	} else {
		return array();
	}


	$thisid_type = $id_type;
	switch ($thisid_type) {
	case "myaddress":
		$thisid_type = "address";
		$thisid_data = $addr;
		break;

	case "dyn_dns":
		$thisid_type = "address";
		$thisid_data = resolve_retry($id_data);
		break;

	case "peeraddress":
		$thisid_type = "address";
		$thisid_data = $rgmap[$ph1ent['remote-gateway']];
		break;

	case "address";
		$thisid_data = $id_data;
		break;

	case "fqdn";
	case "keyid tag";
	case "user_fqdn";
	case "asn1dn";
		$thisid_data = $id_data;
		if( $thisid_data )
			$thisid_data = "{$thisid_data}";
		break;
	}
	return array($thisid_type, $thisid_data);
}

function ipsec_fixup_network($network) {
	if (substr($network, -3) == '|/0')
		$result = substr($network, 0, -3);
	else {
		$tmp = explode('|', $network);
		if (isset($tmp[1]))
			$result = $tmp[1];
		else
			$result = $tmp[0];
		unset($tmp);
	}

	return $result;
}

?>