functions.php 18.4 KB
Newer Older
haemmer's avatar
haemmer committed
1 2 3 4 5 6 7 8 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 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
<?php
/******************************************************************************/
// Commonly used functions for the WAYF
/******************************************************************************/

/******************************************************************************/
// Generates an array of IDPs using the cookie value
function getIdPArrayFromValue($value){

	// Decodes and splits cookie value
	$CookieArray = preg_split('/ /', $value);
	$CookieArray = array_map('base64_decode', $CookieArray);
	
	return $CookieArray;
}

/******************************************************************************/
// Generate the value that is stored in the cookie using the list of IDPs
function getValueFromIdPArray($CookieArray){

	// Merges cookie content and encodes it
	$CookieArray = array_map('base64_encode', $CookieArray);
	$value = implode(' ', $CookieArray);
	return $value;
}

/******************************************************************************/
// Append a value to the array of IDPs
function appendValueToIdPArray($value, $CookieArray){
	
	// Remove value if it already existed in array
	foreach (array_keys($CookieArray) as $i){
		if ($CookieArray[$i] == $value){
			unset($CookieArray[$i]);
		}
	}
	
	// Add value to end of array
	$CookieArray[] = $value;
	
	return $CookieArray;
}

/******************************************************************************/
// Checks if the configuration file has changed. If it has, check the file
// and change its timestamp.
function checkConfig($IDPConfigFile, $backupIDPConfigFile){
	
	// Do files have the same modification time
	if (filemtime($IDPConfigFile) == filemtime($backupIDPConfigFile))
		return true;
	
	// Availability check
	if (!file_exists($IDPConfigFile))
		return false;
	
	// Readability check
	if (!is_readable($IDPConfigFile))
		return false;
	
	// Size check
	if (filesize($IDPConfigFile) < 200)
		return false;
	
	// Make modification time the same
	// If that doesnt work we won't notice it
	touch ($IDPConfigFile, filemtime($backupIDPConfigFile));
	
	return true;
}

/******************************************************************************/
// Checks if an IDP exists and prints an error if it doesnt
function checkIDP($IDP, $showError = true){
	
	global $IDProviders, $redirectCookieName;
	
	if (isset($IDProviders[$IDP])){
		return true;
	} elseif ($IDP == '-' || $IDP == ''){ 
		return false;
	} elseif(!$showError){
		return false;
	} else {
85
		$message = sprintf(getLocalString('invalid_user_idp'), htmlentities($IDP))."</p><p>\n<tt>";
haemmer's avatar
haemmer committed
86 87 88 89 90 91
					foreach ($IDProviders as $key => $value){
						if (isset($value['SSO'])){
							$message .= $key."<br>\n";
						}
					}
		$message .= "</tt>\n";
92
		
haemmer's avatar
haemmer committed
93 94 95 96 97
		printError($message);
		exit;
	}
}

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


/******************************************************************************/
// Validates the URL format and returns the URL without GET arguments and fragment
function verifyAndStripReturnURL($url){
	
	$components = parse_url($url);
	
	if (!$components){
		return false;
	}
	
	$recomposedURL = $components['scheme'].'://';
	
	if (isset($components['user'])){
		$recomposedURL .= $components['user'];
		
		if (isset($components['pass'])){
			$recomposedURL .= ':'.$components['pass'];
		}
		
		$recomposedURL .= '@';
	}
	
	if (isset($components['host'])){
		$recomposedURL .= $components['host'];
	}
	
	if (isset($components['port'])){
		$recomposedURL .= ':'.$components['port'];
	}
	
	if (isset($components['path'])){
		$recomposedURL .= $components['path'];
	}
	
	return $recomposedURL;
}

haemmer's avatar
haemmer committed
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 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 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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
/******************************************************************************/
// Parses the hostname out of a string and returns it
function getHostNameFromURI($string){
	
	// Check if string is URN
	if (preg_match('/^urn:mace:/i', $string)){
		// Return last component of URN
		return end(explode(':', $string));
	}
	
	// Apparently we are dealing with something like a URL
	if (preg_match('/([a-zA-Z0-9\-\.]+\.[a-zA-Z0-9\-\.]{2,6})/', $string, $matches)){
		return $matches[0];
	} else {
		return '';
	}
}

/******************************************************************************/
// Parses the domain out of a string and returns it
function getDomainNameFromURI($string){
	
	// Check if string is URN
	if (preg_match('/^urn:mace:/i', $string)){
		// Return last component of URN
		return getTopLevelDomain(end(explode(':', $string)));
	}
	
	// Apparently we are dealing with something like a URL
	if (preg_match('/[a-zA-Z0-9\-\.]+\.([a-zA-Z0-9\-\.]{2,6})/', $string, $matches)){
		return getTopLevelDomain($matches[0]);
	} else {
		return '';
	}
}

/******************************************************************************/
// Returns top level domain name from a DNS name
function getTopLevelDomain($string){
	$hostnameComponents = explode('.', $string);
	if (count($hostnameComponents) >= 2){
		return $hostnameComponents[count($hostnameComponents)-2].'.'.$hostnameComponents[count($hostnameComponents)-1];
	} else {
		return $string;
	}
}

/******************************************************************************/
// Parses the reverse dns lookup hostname out of a string and returns domain
function getDomainNameFromURIHint(){
	
	global $IDProviders;
	
	$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
	if ($hostname == $_SERVER['REMOTE_ADDR']){
		return '-';
	}
	
	// Do we still have something
	$domainname = getDomainNameFromURI($hostname);
	if ($domainname != ''){
		// Find a matching IdP SSO, must be matching the IdP urn 
		// or at least the last part of the urn
		foreach ($IDProviders as $key => $value){
			if (preg_match('/'.$domainname.'$/', $key)){
				return $key;
			}
		}
	} else {
		return '-';
	}
	
}

/******************************************************************************/
// Get the user's language using the accepted language http header
function determineLanguage(){
	
	global $langStrings, $defaultLanguage;
	
	// Check if language is enforced by PATH-INFO argument
	if (isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO'])){
		foreach ($langStrings as $lang => $values){
			if (preg_match('#/'.$lang.'($|/)#',$_SERVER['PATH_INFO'])){
				return $lang;
			}
		}
	}
	
	// Check if there is a language GET argument
	if (isset($_GET['lang'])){
		$localeComponents = decomposeLocale($_GET['lang']);
		if (
		    $localeComponents !== false 
		    && isset($langStrings[$localeComponents[0]])
		    ){
			
			// Return language
			return $localeComponents[0];
		}
	}
	
	// Return default language if no headers are present otherwise
	if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
		return $defaultLanguage;
	}
	
	// Inspect Accept-Language header which looks like:
	// Accept-Language: en,de-ch;q=0.8,fr;q=0.7,fr-ch;q=0.5,en-us;q=0.3,de;q=0.2
	$languages = explode( ',', trim($_SERVER['HTTP_ACCEPT_LANGUAGE']));
	foreach ($languages as $language){
		$languageParts = explode(';', $language);
		
		// Only treat art before the prioritization
		$localeComponents = decomposeLocale($languageParts[0]);
		if (
		    $localeComponents !== false 
		    && isset($langStrings[$localeComponents[0]])
		    ){
			
			// Return language
			return $localeComponents[0];
		}
	}
	
	return $defaultLanguage;
}

/******************************************************************************/

// Splits up a  string (relazed) according to
// http://www.debian.org/doc/manuals/intro-i18n/ch-locale.en.html#s-localename
// and returns an array with the four components
function decomposeLocale($locale){
	
	// Locale name syntax:  language[_territory][.codeset][@modifier]
	if (!preg_match('/^([a-zA-Z]{2})([-_][a-zA-Z]{2})?(\.[^@]+)?(@.+)?$/', $locale, $matches)){
		return false;
	} else {
		// Remove matched string in first position
		array_shift($matches);
		
		return $matches;
	}
}

/******************************************************************************/
// Gets a string in the user's language. If no localized version is available
// for the string, the English string is returned as default.
function getLocalString($string, $encoding = ''){
	
	global $defaultLanguage, $langStrings, $language;
	
	$textString = '';
	if (isset($langStrings[$language][$string])){
		$textString = $langStrings[$language][$string];
	} else {
		$textString = $langStrings[$defaultLanguage][$string];
	}
	
	// Change encoding if necessary
	if ($encoding == 'js'){
		$textString = convertToJSString($textString);
	}
	
	return $textString;
}

/******************************************************************************/
// Converts string to a JavaScript format that can be used in JS alert
function convertToJSString($string){
	return addslashes(utf8_encode(html_entity_decode($string)));
}

/******************************************************************************/
// Checks if entityID hostname of a valid IdP exists in path info
function getIdPPathInfoHint(){
	
	global $IDProviders;
	
	// Check if path info is available at all
	if (!isset($_SERVER['PATH_INFO']) || empty($_SERVER['PATH_INFO'])){
		return '-';
	}
	
	// Check for entityID hostnames of all available IdPs
	foreach ($IDProviders as $key => $value){
		// Only check actual IdPs
		if (
				isset($value['SSO']) 
				&& !empty($value['SSO'])
				&& $value['Type'] != 'wayf'
				&& checkPathInfo(getHostNameFromURI($key))
				){
			return $key;
		}
	}
	
	// Check for entityID domain names of all available IdPs
	foreach ($IDProviders as $key => $value){
		// Only check actual IdPs
		if (
				isset($value['SSO']) 
				&& !empty($value['SSO'])
				&& $value['Type'] != 'wayf'
				&& checkPathInfo(getDomainNameFromURI($key))
				){
			return $key;
		}
	}
	
	return '-';
}

/******************************************************************************/
// Parses the Kerbores realm out of the string and returns it
function getKerberosRealm($string){
	
	global $IDProviders;
	
	if ($string !='' ) {
		// Find a matching Kerberos realm
		foreach ($IDProviders as $key => $value){
			if ($value['Realm'] == $string) return $key;
		}
	}
	
	return '-';
}

/******************************************************************************/
// Tries to match an IP to a network mask
function getNetMatch($network, $ip) {
	$ip_arr = explode('/', $network);
	$network_long = ip2long($ip_arr[0]);
	
	$x = ip2long($ip_arr[1]);
	$mask = long2ip($x) == $ip_arr[1] ? $x : 0xffffffff << (32 - $ip_arr[1]);
	$ip_long = ip2long($ip);
	
	return ($ip_long & $mask) == ($network_long & $mask);
}

/******************************************************************************/
// Determines the IdP according to the IP address if possible
function getIPAdressHint() {
	global $IDProviders;
	
	foreach($IDProviders as $name => $idp) {
386
		if (is_array($idp) && array_key_exists("IP", $idp)) {
haemmer's avatar
haemmer committed
387 388 389 390 391 392 393 394 395 396 397
			$clientIP = $_SERVER["REMOTE_ADDR"];
			
			foreach( $idp["IP"] as $network ) {
				if (getNetMatch($network, $clientIP)) {
					return $name;
				}
			}
		}
	}
	return '-';
}
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
/******************************************************************************/
// Returns true if URL could be verified, false otherwise
function isVerifiedReturnURL($entityID, $returnURL) {
	global $SProviders, $enableDSReturnParamCheck, $useACURLsForReturnParamCheck;
	
	// Is check necessary
	if (!isset($enableDSReturnParamCheck) || !$enableDSReturnParamCheck){
		return true;
	}
	
	// SP unknown, therefore return false
	if (!isset($SProviders[$entityID])){
		return false;
	}
	
	// Check using DiscoveryResponse extension
414
	if (isset($SProviders[$entityID]['DSURL']) in_array($returnURL, $SProviders[$entityID]['DSURL'])){
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
		return true;
	}
	
	if ($useACURLsForReturnParamCheck){
		$returnURLHostName = getHostNameFromURI($returnURL);
		foreach($SProviders[$entityID]['DSURL'] as $ACURL){
			if (getHostNameFromURI($ACURL) == $returnURLHostName){
				return true;
			}
		}
	}
	
	// Default return value
	return false;
}

haemmer's avatar
haemmer committed
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 473 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 532 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 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
/******************************************************************************/
// Returns a reasonable value for returnIDParam
function getReturnIDParam() {
	
	if (isset($_GET['returnIDParam']) && !empty($_GET['returnIDParam'])){
		return $_GET['returnIDParam'];
	} else {
		return 'entityID';
	}
}

/******************************************************************************/
// Returns true if valid Shibboleth 1.x request or Directory Service request
function isValidShibRequest(){
	return (isValidShib1Request() || isValidDSRequest());
}

/******************************************************************************/
// Returns true if valid Shibboleth request
function isValidShib1Request(){
	if (isset($_GET['shire']) && isset($_GET['target'])){
		return true;
	} else {
		return false;
	}
}

/******************************************************************************/
// Returns true if valid Directory Service request
function isValidDSRequest(){
	if (isset($_GET['entityID']) && isset($_GET['return'])){
		return true;
	} else {
		return false;
	}
}

/******************************************************************************/
// Returns true if valid Directory Service request
function logAccessEntry($protocol, $type, $sp, $idp){
	global $WAYFLogFile, $useLogging;
	
	if (!$useLogging){
		return;
	}
	
	// Let's make sure the file exists and is writable first.
	if (is_writable($WAYFLogFile)) {
			// In our example we're opening $filename in append mode.
			// The file pointer is at the bottom of the file hence
			// that's where $somecontent will go when we fwrite() it.
			if (!$handle = fopen($WAYFLogFile, 'a')) {
					return;
			}
			
			// Create log entry
			$entry = date('Y-m-d H:i:s').' '.$_SERVER['REMOTE_ADDR'].' '.$protocol.' '.$type.' '.$idp.' '.$sp."\n";
			
			// Write $somecontent to our opened file.
			if (fwrite($handle, $entry) === FALSE) {
					return;
			}
			fclose($handle);
	}
}
/******************************************************************************/
// Returns true if PATH info indicates a request of type $type
function isRequestType($type){
	// Make sure the type is checked at end of path info
	return checkPathInfo($type.'$');
}

/******************************************************************************/
// Checks for substrings in Path Info and returns true if match was found
function checkPathInfo($needle){
	if (
		isset($_SERVER['PATH_INFO']) 
		&& !empty($_SERVER['PATH_INFO'])
		&& preg_match('|/'.$needle.'|', $_SERVER['PATH_INFO'])){
		
		return true;
	} else {
		return false;
	}
}

/******************************************************************************/
// Converts to the unified datastructure that the Shibboleth DS will be using
function convertToShibDSStructure($IDProviders){
	global $federationName;
	
	$ShibDSIDProviders['identityProviders'] = array();
	
	foreach ($IDProviders as $key => $value){
		
		// Skip unknown and category entries
		if(
			!isset($value['Type']) 
			|| $value['Type'] == 'category'
			|| $value['Type'] == 'wayf'
			){
			continue;
		}
		
		// Init and fill IdP data
		$identityProvider = array();
		$identityProvider['entityID'] = $key;
		$identityProvider['shibSSOEndpoint'] =  $value['SSO'];
		$identityProvider['displayNames'][] = array('lang' => 'en', 'name' => $value['Name']);
		$identityProvider['attributes'][] = array(
		'name' => 'type', 'value' => $value['Type']
		);
		
		// Add displayNames in other languages
		foreach($value as $lang => $name){
			if(
				   $lang == 'Name'
				|| $lang == 'SSO'
				|| $lang == 'Realm'
				|| $lang == 'Type'
				|| $lang == 'IP'
				
			){
				continue;
			}
			
			if (isset($name['Name'])){
				$identityProvider['displayNames'][] = array('lang' => $lang, 'name' => $name['Name']);
			}
		}
		
		
		// Add kerberos realm
		if(isset($value['Realm'])){
			$identityProvider['attributes'][] = array(
		'name' => 'kerberosRealm', 'value' => $value['Realm']
		);
		}
		
		
		// Add IP ranges
		if(isset($value['IP'])){
			$identityProvider['attributes'][] = array(
		'name' => 'IP', 'value' => $value['IP']
		);
		}
		
		// Add data to ShibDSIDProviders
		$ShibDSIDProviders['identityProviders'][] = $identityProvider;
	}
	
	return $ShibDSIDProviders;
	
}

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 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 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
/******************************************************************************/
// Sorts the IDProviders array
function sortIdentityProviders(&$IDProviders){
	$sortedIDProviders = Array();
	$sortedCategories = Array();
	
	foreach ($IDProviders as $entityId => $IDProvider){
		if (!is_array($IDProvider)){
			// Remove any entries that are not arrays
			unset($IDProviders[$entityId]);
		} elseif ($IDProvider['Type'] == 'category'){
			$sortedCategories[$entityId] = $IDProvider;
		} else {
			$sortedIDProviders[$entityId] = $IDProvider;
		}
	}
	
	// Sort categories and IdPs
	
	if (count($sortedCategories) > 1){
		// Sort using index
		uasort($sortedCategories, 'sortUsingTypeIndexAndName');
	} else {
		// Sort alphabetically using the key of a category
		ksort($sortedCategories);
	}
	
	// Add category 'unknown' if not present
	if (!isset($IDProviders['unknown'])){
		$sortedCategories['unknown'] = array (
		'Name' => 'Unknown',
		'Type' => 'category',
		);
	}
	
	// Sort Identity Providers
	uasort($sortedIDProviders, 'sortUsingTypeIndexAndName');
	$IDProviders = Array();
	
	// Compose array
	$showUnknownCategory = false;
	while(list($categoryKey, $categoryValue) = each($sortedCategories)){
		$IDProviders[$categoryKey] = $categoryValue;
		
		// Loop through all IdPs
		foreach ($sortedIDProviders as $IDProvidersPKey => $IDProvidersValue){
			// Add IdP if its type matches the current category
			if ($IDProvidersValue['Type'] == $categoryKey){
				$IDProviders[$IDProvidersPKey] = $IDProvidersValue;
				unset($sortedIDProviders[$IDProvidersPKey]);
			}
			
			// Add IdP if its type is 'unknown' or if there doesnt exist a category for its type
			if ($categoryKey == 'unknown' || !isset($sortedCategories[$IDProvidersValue['Type']])){
				$IDProviders[$IDProvidersPKey] = $IDProvidersValue;
				unset($sortedIDProviders[$IDProvidersPKey]);
				$showUnknownCategory = true;
			}
			
		}
	}
	
	// Check if unkown category is needed
	if (!$showUnknownCategory){
		unset($IDProviders['unknown']);
	}
	
}

/******************************************************************************/
// Sorts two entries according to their Type, Index and (local) Name
function sortUsingTypeIndexAndName($a, $b){
	global $language;
	
	if ($a['Type'] != $b['Type']){
		return strcmp($b['Type'], $a['Type']);
	} elseif (isset($a['Index']) && isset($b['Index']) && $a['Index'] != $b['Index']){
		return strcmp($a['Index'], $b['Index']);
	} else {
		// Sort using locale names
		$localNameB = (isset($a[$language]['Name'])) ? $a[$language]['Name'] : $a['Name'];
		$localNameA = (isset($b[$language]['Name'])) ? $b[$language]['Name'] : $b['Name'];
		return strcmp($localNameB, $localNameA);
	}
}

haemmer's avatar
haemmer committed
672
?>