Upgrade to new Gitlab Version 13.9 on Saturday 19th April 20:00. Expect an interruption of about 30 to 60 minutes

functions.php 35.7 KB
Newer Older
Lukas Haemmerle's avatar
Lukas Haemmerle committed
1
<?php // Copyright (c) 2019, SWITCH
2 3 4 5 6 7 8

/*
******************************************************************************
This file contains common functions of the SWITCHwayf
******************************************************************************
*/

9
// Initilizes default configuration options if they were not set already
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
function initConfigOptions()
{
    global $defaultLanguage;
    global $commonDomain;
    global $cookieNamePrefix;
    global $redirectCookieName;
    global $redirectStateCookieName;
    global $SAMLDomainCookieName;
    global $SPCookieName;
    global $cookieSecurity;
    global $cookieValidity;
    global $showPermanentSetting;
    global $useImprovedDropDownList;
    global $disableRemoteLogos;
    global $useSAML2Metadata;
    global $SAML2MetaOverLocalConf;
    global $includeLocalConfEntries;
    global $enableDSReturnParamCheck;
    global $useACURLsForReturnParamCheck;
    global $useKerberos;
    global $useReverseDNSLookup;
    global $useEmbeddedWAYF;
    global $useEmbeddedWAYFPrivacyProtection;
    global $useEmbeddedWAYFRefererForPrivacyProtection;
    global $useLogging;
    global $exportPreselectedIdP;
    global $federationName;
    global $supportContactEmail;
    global $federationURL;
    global $organizationURL;
    global $faqURL;
    global $helpURL;
    global $privacyURL;
    global $imageURL;
    global $javascriptURL;
    global $cssURL;
    global $logoURL;
    global $smallLogoURL;
    global $organizationLogoURL;
    global $customStrings;
    global $IDPConfigFile;
    global $backupIDPConfigFile;
    global $metadataFile;
    global $metadataIDPFile;
    global $metadataSPFile;
    global $metadataLockFile;
    global $WAYFLogFile;
    global $kerberosRedirectURL;
    global $instanceIdentifier;
    global $developmentMode;
    global $topLevelDir;
61 62 63
    global $useSelect2;
    global $select2PageSize;
    global $allowedCORSDomain;
64 65 66 67 68 69 70 71 72 73 74 75


    // Set independet default configuration options
    $defaults = array();
    $defaults['instanceIdentifier'] = 'SWITCHwayf';
    $defaults['defaultLanguage'] = 'en';
    $defaults['commonDomain'] = getTopLevelDomain($_SERVER['SERVER_NAME']);
    $defaults['cookieNamePrefix'] = '';
    $defaults['cookieSecurity'] = false;
    $defaults['cookieValidity'] = 100;
    $defaults['showPermanentSetting'] = false;
    $defaults['useImprovedDropDownList'] = true;
76
    $defaults['useSelect2'] = false;
77 78
    $defaults['select2PageSize'] = 100;
    $defaults['allowedCORSDomain'] = '*';
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
    $defaults['disableRemoteLogos'] = false;
    $defaults['useSAML2Metadata'] = false;
    $defaults['SAML2MetaOverLocalConf'] = false;
    $defaults['includeLocalConfEntries'] = true;
    $defaults['enableDSReturnParamCheck'] = true;
    $defaults['useACURLsForReturnParamCheck'] = false;
    $defaults['useKerberos'] = false;
    $defaults['useReverseDNSLookup'] = false;
    $defaults['useEmbeddedWAYF'] = false;
    $defaults['useEmbeddedWAYFPrivacyProtection'] = false;
    $defaults['useEmbeddedWAYFRefererForPrivacyProtection'] = false;
    $defaults['useLogging'] = true;
    $defaults['exportPreselectedIdP'] = false;
    $defaults['federationName'] = 'Identity Federation';
    $defaults['organizationURL'] = 'http://www.'.$defaults['commonDomain'];
    $defaults['federationURL'] = $defaults['organizationURL'].'/aai';
    $defaults['faqURL'] = $defaults['federationURL'].'/faq';
    $defaults['helpURL'] = $defaults['federationURL'].'/help';
    $defaults['privacyURL'] = $defaults['federationURL'].'/privacy';
    $defaults['supportContactEmail'] = 'support-contact@'.$defaults['commonDomain'];
    $defaults['imageURL'] = 'https://'.$_SERVER['SERVER_NAME'].dirname($_SERVER['SCRIPT_NAME']).'/images';
    $defaults['javascriptURL'] = 'https://'.$_SERVER['SERVER_NAME'].dirname($_SERVER['SCRIPT_NAME']).'/js';
    $defaults['cssURL'] = 'https://'.$_SERVER['SERVER_NAME'].dirname($_SERVER['SCRIPT_NAME']).'/css';
    $defaults['IDPConfigFile'] = 'IDProvider.conf.php';
    $defaults['backupIDPConfigFile'] = 'IDProvider.conf.php';
    $defaults['metadataFile'] = '/etc/shibboleth/metadata.switchaai.xml';
    $defaults['metadataIDPFile'] = 'IDProvider.metadata.php';
    $defaults['metadataSPFile'] = 'SProvider.metadata.php';
    $lockFileName = preg_replace('/[^-_\.a-zA-Z]/', '', $defaults['instanceIdentifier']);
    $defaults['metadataLockFile'] = (substr($_SERVER['PATH'], 0, 1) == '/') ? '/tmp/wayf_metadata-'.$lockFileName.'.lock' : 'C:\windows\TEMP\wayf_metadata-'.$lockFileName.'.lock';
    $defaults['WAYFLogFile'] = '/var/log/apache2/wayf.log';
    $defaults['kerberosRedirectURL'] = dirname($_SERVER['SCRIPT_NAME']).'kerberosRedirect.php';
    $defaults['developmentMode'] = false;
    $defaults['customStrings'] = array();

    // Initialize independent defaults
    foreach ($defaults as $key => $value) {
        if (!isset($$key)) {
            $$key = $value;
        }
    }

    // Set dependent default configuration options
    $defaults = array();
    $defaults['redirectCookieName'] = $cookieNamePrefix.'_redirect_user_idp';
    $defaults['redirectStateCookieName'] = $cookieNamePrefix.'_redirection_state';
    $defaults['SAMLDomainCookieName'] = $cookieNamePrefix.'_saml_idp';
    $defaults['SPCookieName'] = $cookieNamePrefix.'_saml_sp';
    $defaults['logoURL'] = $imageURL.'/federation-logo.png';
    $defaults['smallLogoURL'] = $imageURL.'/small-federation-logo.png';
    $defaults['organizationLogoURL'] = $imageURL.'/organization-logo.png';

    // Initialize dependent defaults
    foreach ($defaults as $key => $value) {
        if (!isset($$key)) {
            $$key = $value;
        }
    }

    // Turn relatives paths into absolute ones
    $files = array(
        'IDPConfigFile', 'backupIDPConfigFile', 'metadataFile',
        'metadataIDPFile', 'metadataSPFile', 'metadataLockFile'
    );
    foreach ($files as $file) {
        if (substr($$file, 0, 1) != '/') {
            $$file = $topLevelDir . '/etc/' . $$file;
        }
    }
148 149
}

haemmer's avatar
haemmer committed
150 151
/******************************************************************************/
// Generates an array of IDPs using the cookie value
152 153 154 155 156 157
function getIdPArrayFromValue($value)
{

    // Decodes and splits cookie value
    $CookieArray = preg_split('/ /', $value);
    $CookieArray = array_map('base64_decode', $CookieArray);
haemmer's avatar
haemmer committed
158

159
    return $CookieArray;
haemmer's avatar
haemmer committed
160 161 162 163
}

/******************************************************************************/
// Generate the value that is stored in the cookie using the list of IDPs
164 165
function getValueFromIdPArray($CookieArray)
{
haemmer's avatar
haemmer committed
166

167 168 169 170
    // Merges cookie content and encodes it
    $CookieArray = array_map('base64_encode', $CookieArray);
    $value = implode(' ', $CookieArray);
    return $value;
haemmer's avatar
haemmer committed
171 172 173
}

/******************************************************************************/
174
// Append a value to the array of IDPs, ensure no more than 5
175
// entries are in array
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
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;

    // Shorten array from beginning as latest entry should
    // be at end according to SAML spec
    while (count($CookieArray) > 5) {
        array_shift($CookieArray);
    }

    return $CookieArray;
haemmer's avatar
haemmer committed
196 197 198 199 200
}

/******************************************************************************/
// Checks if the configuration file has changed. If it has, check the file
// and change its timestamp.
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
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;
haemmer's avatar
haemmer committed
229 230 231
}

/******************************************************************************/
232
// Checks if an IDP exists and returns true if it does, false otherwise
233 234 235 236 237 238 239 240 241
function checkIDP($IDP)
{
    global $IDProviders;

    if (isset($IDProviders[$IDP])) {
        return true;
    } else {
        return false;
    }
242 243 244
}

/******************************************************************************/
245
// Checks if an IDP exists and returns true if it exists and prints an error
246
// if it doesnt
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
function checkIDPAndShowErrors($IDP)
{
    global $IDProviders;

    if (checkIDP($IDP)) {
        return true;
    }

    // Otherwise show an error
    $message = sprintf(getLocalString('invalid_user_idp'), htmlentities($IDP))."</p><p>\n<code>";
    foreach ($IDProviders as $key => $value) {
        if (isset($value['SSO'])) {
            $message .= $key."<br>\n";
        }
    }
    $message .= "</code>\n";

    printError($message);
    exit;
haemmer's avatar
haemmer committed
266 267
}

268 269

/******************************************************************************/
270 271 272 273 274 275 276 277 278 279
// Validates the URL and returns it if it is valid or false otherwise
function getSanitizedURL($url)
{
    $components = parse_url($url);

    if ($components) {
        return $url;
    } else {
        return false;
    }
280 281
}

haemmer's avatar
haemmer committed
282 283
/******************************************************************************/
// Parses the hostname out of a string and returns it
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
function getHostNameFromURI($string)
{

    // Check if string is URN
    if (preg_match('/^urn:mace:/i', $string)) {
        // Return last component of URN
        $components = explode(':', $string);
        return end($components);
    }

    // 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 '';
    }
haemmer's avatar
haemmer committed
300 301 302 303
}

/******************************************************************************/
// Parses the domain out of a string and returns it
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
function getDomainNameFromURI($string)
{

    // Check if string is URN
    if (preg_match('/^urn:mace:/i', $string)) {
        // Return last component of URN
        $components = explode(':', $string);
        return getTopLevelDomain(end($components));
    }

    // 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 '';
    }
haemmer's avatar
haemmer committed
320 321 322 323
}

/******************************************************************************/
// Returns top level domain name from a DNS name
324 325 326 327 328 329 330 331
function getTopLevelDomain($string)
{
    $hostnameComponents = explode('.', $string);
    if (count($hostnameComponents) >= 2) {
        return $hostnameComponents[count($hostnameComponents)-2].'.'.$hostnameComponents[count($hostnameComponents)-1];
    } else {
        return $string;
    }
haemmer's avatar
haemmer committed
332 333 334 335
}

/******************************************************************************/
// Parses the reverse dns lookup hostname out of a string and returns domain
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
function getDomainNameFromURIHint()
{
    global $IDProviders;

    $clientHostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
    if ($clientHostname == $_SERVER['REMOTE_ADDR']) {
        return '-';
    }

    // Get domain name from client host name
    $clientDomainName = getDomainNameFromURI($clientHostname);
    if ($clientDomainName == '') {
        return '-';
    }

    // Return first matching IdP entityID that contains the client domain name
    foreach ($IDProviders as $key => $value) {
        if (
               preg_match('/^http.+'.$clientDomainName.'/', $key)
            || preg_match('/^urn:.+'.$clientDomainName.'$/', $key)) {
            return $key;
        }
    }

    // No matching entityID was found
    return '-';
haemmer's avatar
haemmer committed
362 363 364 365
}

/******************************************************************************/
// Get the user's language using the accepted language http header
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
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;
haemmer's avatar
haemmer committed
416 417 418 419 420 421 422
}

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

// 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
423 424 425 426 427 428 429 430 431 432 433 434
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;
    }
haemmer's avatar
haemmer committed
435 436 437
}

/******************************************************************************/
438
// Gets a string in a specific language. Fallback to default language and
haemmer's avatar
haemmer committed
439
// to English.
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
function getLocalString($string, $encoding = '')
{
    global $defaultLanguage, $langStrings, $language;

    $textString = '';
    if (isset($langStrings[$language][$string])) {
        $textString = $langStrings[$language][$string];
    } elseif (isset($langStrings[$defaultLanguage][$string])) {
        $textString = $langStrings[$defaultLanguage][$string];
    } else {
        $textString = $langStrings['en'][$string];
    }

    // Change encoding if necessary
    if ($encoding == 'js') {
        $textString = convertToJSString($textString);
    }

    return $textString;
haemmer's avatar
haemmer committed
459 460 461 462
}

/******************************************************************************/
// Converts string to a JavaScript format that can be used in JS alert
463 464 465
function convertToJSString($string)
{
    return addslashes(html_entity_decode($string, ENT_COMPAT, 'UTF-8'));
haemmer's avatar
haemmer committed
466 467
}

haemmer's avatar
haemmer committed
468 469
/******************************************************************************/
// Replaces all newlines with spaces and then trims the string to get one line
470 471 472
function trimToSingleLine($string)
{
    return trim(preg_replace("|\n|", ' ', $string));
haemmer's avatar
haemmer committed
473 474
}

haemmer's avatar
haemmer committed
475 476
/******************************************************************************/
// Checks if entityID hostname of a valid IdP exists in path info
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
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'
                && isPartOfPathInfo(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'
                && isPartOfPathInfo(getDomainNameFromURI($key))
                ) {
            return $key;
        }
    }

    return '-';
haemmer's avatar
haemmer committed
513 514
}

515
/******************************************************************************/
516
// Joins localized names and keywords of an IdP to a single string
517 518 519 520 521 522 523 524 525 526 527 528 529 530
function composeOptionData($IdPValues)
{
    $data = '';
    foreach ($IdPValues as $key => $value) {
        if (is_array($value) && isset($value['Name'])) {
            $data .= ' '.$value['Name'];
        }

        if (is_array($value) && isset($value['Keywords'])) {
            $data .= ' '.$value['Keywords'];
        }
    }

    return $data;
531 532
}

haemmer's avatar
haemmer committed
533 534
/******************************************************************************/
// Parses the Kerbores realm out of the string and returns it
535 536 537 538 539 540 541 542 543 544 545 546 547 548
function getKerberosRealm($string)
{
    global $IDProviders;

    if ($string !='') {
        // Find a matching Kerberos realm
        foreach ($IDProviders as $key => $value) {
            if ($value['Realm'] == $string) {
                return $key;
            }
        }
    }

    return '-';
haemmer's avatar
haemmer committed
549 550 551 552 553
}


/******************************************************************************/
// Determines the IdP according to the IP address if possible
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
function getIPAdressHint()
{
    global $IDProviders;

    foreach ($IDProviders as $name => $idp) {
        if (is_array($idp) && array_key_exists("IP", $idp)) {
            $clientIP = $_SERVER["REMOTE_ADDR"];

            foreach ($idp["IP"] as $network) {
                if (isIPinCIDRBlock($network, $clientIP)) {
                    return $name;
                }
            }
        }
    }
    return '-';
haemmer's avatar
haemmer committed
570
}
571

572 573 574
/******************************************************************************/
// Returns true if IP is in IPv4/IPv6 CIDR range
// and returns false otherwise
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
function isIPinCIDRBlock($cidr, $ip)
{

    // Split CIDR notation
    list($net, $mask) = preg_split("|/|", $cidr);

    // Convert to binary string value of 1s and 0s
    $netAsBinary = convertIPtoBinaryForm($net);
    $ipAsBinary =  convertIPtoBinaryForm($ip);

    // Return false if netmask and ip are using different protocols
    if (strlen($netAsBinary) != strlen($ipAsBinary)) {
        return false;
    }

    // Compare the first $mask bits
    for ($i = 0; $i < $mask; $i++) {

        // Return false if bits don't match
        if ($netAsBinary[$i] != $ipAsBinary[$i]) {
            return false;
        }
    }

    // If we got here, ip matches net
    return true;
601 602 603 604
}

/******************************************************************************/
// Converts IP in human readable format to binary string
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
function convertIPtoBinaryForm($ip)
{

    //  Handle IPv4 IP
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
        return base_convert(ip2long($ip), 10, 2);
    }

    // Return false if IP is neither IPv4 nor a IPv6 IP
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
        return false;
    }

    // Convert IP to binary structure and return false if this fails
    if (($ipAsBinStructure = inet_pton($ip)) === false) {
        return false;
    }


    $numOfBytes = 16;
    $ipAsBinaryString = '';

    // Convert IP to binary string
    while ($numOfBytes > 0) {
        // Convert current byte to decimal number
        $currentByte = ord($ipAsBinStructure[$numOfBytes - 1]);

        // Convert currenty byte to string of 1 and 0
        $currentByteAsBinary = sprintf("%08b", $currentByte);

        // Prepend to rest of IP in binary string
        $ipAsBinaryString = $currentByteAsBinary.$ipAsBinaryString;

        // Decrease byte counter
        $numOfBytes--;
    }

    return $ipAsBinaryString;
643 644
}

haemmer's avatar
haemmer committed
645 646
/******************************************************************************/
// Returns URL without GET arguments
647 648 649
function getURLWithoutArguments($url)
{
    return preg_replace('/\?.*/', '', $url);
haemmer's avatar
haemmer committed
650 651
}

652
/******************************************************************************/
653
// Returns true if URL could be verified or if no check is necessary, false otherwise
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 686 687 688 689 690
function verifyReturnURL($entityID, $returnURL)
{
    global $SProviders, $useACURLsForReturnParamCheck;

    // If SP has a <idpdisc:DiscoveryResponse>, check return param
    if (isset($SProviders[$entityID]['DSURL'])) {
        $returnURLWithoutArguments = getURLWithoutArguments($returnURL);
        foreach ($SProviders[$entityID]['DSURL'] as $DSURL) {
            $DSURLWithoutArguments = getURLWithoutArguments($DSURL);
            if ($DSURLWithoutArguments == $returnURLWithoutArguments) {
                return true;
            }
        }

        // DS URLs did not match the return URL
        return false;
    }

    // Return true if SP has no <idpdisc:DiscoveryResponse>
    // and $useACURLsForReturnParamCheck is disabled (we don't check anything)
    if (!$useACURLsForReturnParamCheck) {
        return true;
    }

    // $useACURLsForReturnParamCheck is enabled, so
    // check return param against host name of assertion consumer URLs

    // Check hostnames
    $returnURLHostName = getHostNameFromURI($returnURL);
    foreach ($SProviders[$entityID]['ACURL'] as $ACURL) {
        if (getHostNameFromURI($ACURL) == $returnURLHostName) {
            return true;
        }
    }

    // We haven't found a matching assertion consumer URL, therefore we return false
    return false;
691 692
}

haemmer's avatar
haemmer committed
693 694
/******************************************************************************/
// Returns a reasonable value for returnIDParam
695 696 697 698 699 700 701
function getReturnIDParam()
{
    if (isset($_GET['returnIDParam']) && !empty($_GET['returnIDParam'])) {
        return $_GET['returnIDParam'];
    } else {
        return 'entityID';
    }
haemmer's avatar
haemmer committed
702 703 704 705
}

/******************************************************************************/
// Returns true if valid Shibboleth 1.x request or Directory Service request
706 707 708
function isValidShibRequest()
{
    return (isValidShib1Request() || isValidDSRequest());
haemmer's avatar
haemmer committed
709 710 711 712
}

/******************************************************************************/
// Returns true if valid Shibboleth request
713 714 715 716 717 718 719
function isValidShib1Request()
{
    if (isset($_GET['shire']) && isset($_GET['target'])) {
        return true;
    } else {
        return false;
    }
haemmer's avatar
haemmer committed
720 721 722
}

/******************************************************************************/
723
// Returns true if request is a valid Directory Service request
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
function isValidDSRequest()
{
    global $SProviders;

    // If entityID is not present, request is invalid
    if (!isset($_GET['entityID'])) {
        return false;
    }

    // If entityID and return parameters are present, request is valid
    if (isset($_GET['return'])) {
        return true;
    }

    // If no return parameter and no Discovery Service endpoint is available
    // for SP, request is invalid
    if (!isset($SProviders[$_GET['entityID']]['DSURL'])) {
        return false;
    }

    if (count($SProviders[$_GET['entityID']]['DSURL']) < 1) {
        return false;
    }

    // EntityID is available and there is at least one DiscoveryService
    // endpoint defined. Therefore, the request is valid
    return true;
haemmer's avatar
haemmer committed
751 752
}

753 754
/******************************************************************************/
// Sets the Location header to redirect the user's web browser
755 756 757
function redirectTo($url)
{
    header('Location: '.$url);
758 759 760 761
}

/******************************************************************************/
// Sets the Location that is used for redirect the web browser back to the SP
762 763 764 765 766 767 768
function redirectToSP($url, $IdP)
{
    if (preg_match('/\?/', $url) > 0) {
        redirectTo($url.'&'.getReturnIDParam().'='.urlencode($IdP));
    } else {
        redirectTo($url.'?'.getReturnIDParam().'='.urlencode($IdP));
    }
769
}
haemmer's avatar
haemmer committed
770
/******************************************************************************/
haemmer's avatar
haemmer committed
771 772 773
// Logs all events where users were redirected to their IdP or back to an SP
// The log then can be used to approximately detect how many users were served
// by the SWITCHwayf
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
function logAccessEntry($protocol, $type, $sp, $idp, $return)
{
    global $WAYFLogFile, $useLogging;

    // Return if logging deactivated
    if (!$useLogging) {
        return;
    }

    // Create log file if it does not exist yet
    if (!file_exists($WAYFLogFile) && !touch($WAYFLogFile)) {
        // File does not exist and cannot be written to
        logFatalErrorAndExit('WAYF log file '.$WAYFLogFile.' does not exist and could not be created.');
    }

    // Ensure that the file exists and is writable
    if (!is_writable($WAYFLogFile)) {
        logFatalErrorAndExit('Current file permission do not allow WAYF to write to its log file '.$WAYFLogFile.'.');
    }

    // Compose log entry
    $entry = date('Y-m-d H:i:s').' '.$_SERVER['REMOTE_ADDR'].' '.$protocol.' '.$type.' '.$idp.' '.$return.' '.$sp."\n";

    // Open file in append mode
    if (!$handle = fopen($WAYFLogFile, 'a')) {
        logFatalErrorAndExit('Could not open file '.$WAYFLogFile.' for appending log entries.');
    }

    // Try getting the lock
    while (!flock($handle, LOCK_EX)) {
        usleep(rand(10, 100));
    }

    // Write entry
    fwrite($handle, $entry);

    // Release the lock
    flock($handle, LOCK_UN);

    // Close file handle
    fclose($handle);
haemmer's avatar
haemmer committed
815 816
}

817 818
/******************************************************************************/
// Init connection to system logger
819 820 821 822 823
function initLogger()
{
    global $instanceIdentifier;

    openlog($instanceIdentifier, LOG_NDELAY, LOG_USER);
824 825
}

haemmer's avatar
haemmer committed
826
/******************************************************************************/
827 828 829 830 831 832
// Logs a debug message
function logDebug($infoMsg)
{
    wayfLog("DEBUG", $infoMsg);
}

haemmer's avatar
haemmer committed
833
// Logs an info message
834 835
function logInfo($infoMsg)
{
836
    wayfLog("INFO", $infoMsg);
haemmer's avatar
haemmer committed
837 838 839 840
}

/******************************************************************************/
// Logs an warnimg message
841 842
function logWarning($warnMsg)
{
843
    wayfLog("WARN", $warnMsg);
haemmer's avatar
haemmer committed
844 845 846 847
}

/******************************************************************************/
// Logs an error message
848 849
function logError($errorMsg)
{
850
    wayfLog("ERROR", $errorMsg);
haemmer's avatar
haemmer committed
851 852
}

haemmer's avatar
haemmer committed
853 854
/******************************************************************************/
// Logs an fatal error message
855 856 857 858
function logFatalErrorAndExit($errorMsg)
{
    logError($errorMsg);
    exit;
haemmer's avatar
haemmer committed
859
}
haemmer's avatar
haemmer committed
860

861 862 863 864 865 866
/******************************************************************************/
// Logs a message to errorLog
function wayfLog($level, $errorMsg)
{
    global $developmentMode;

867
    // If developmentMode => Log to errorLog
868 869
    if ($developmentMode) {
        error_log(sprintf("[%s] %s", $level, $errorMsg));
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
        // Legacy logging
        //echo $errorMsg;
    }

    $syslogPriority = LOG_INFO;
    if ($level == "ERROR") {
        $syslogPriority = LOG_ERR;
    }
    if ($level == "WARN") {
        $syslogPriority = LOG_WARNING;
    }

    if ($level != "DEBUG") {
        // Syslog Logging
        initLogger();

        syslog($syslogPriority, $errorMsg);
887 888 889
    }
}

haemmer's avatar
haemmer committed
890 891
/******************************************************************************/
// Returns true if PATH info indicates a request of type $type
892 893 894 895
function isRequestType($type)
{
    // Make sure the type is checked at end of path info
    return isPartOfPathInfo($type.'$');
haemmer's avatar
haemmer committed
896 897 898 899
}

/******************************************************************************/
// Checks for substrings in Path Info and returns true if match was found
900 901 902 903 904 905 906 907 908 909
function isPartOfPathInfo($needle)
{
    if (
        isset($_SERVER['PATH_INFO'])
        && !empty($_SERVER['PATH_INFO'])
        && preg_match('|/'.$needle.'|', $_SERVER['PATH_INFO'])) {
        return true;
    } else {
        return false;
    }
haemmer's avatar
haemmer committed
910 911 912 913
}

/******************************************************************************/
// Converts to the unified datastructure that the Shibboleth DS will be using
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 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
function convertToShibDSStructure($IDProviders)
{
    $ShibDSIDProviders = 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['DisplayNames'][] = array('lang' => 'en', 'value' => $value['Name']);

        // 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, 'value' => $name['Name']);
            }
        }

        // Add data to ShibDSIDProviders
        $ShibDSIDProviders[] = $identityProvider;
    }

    return $ShibDSIDProviders;
haemmer's avatar
haemmer committed
957 958
}

959 960
/******************************************************************************/
// Sorts the IDProviders array
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 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
function sortIdentityProviders(&$IDProviders)
{
    $orderedCategories = array();

    // Create array with categories and IdPs in categories
    $unknownCategory = array();
    foreach ($IDProviders as $entityId => $IDProvider) {
        // Add categories
        if ($IDProvider['Type'] == 'category') {
            $orderedCategories[$entityId]['data'] = $IDProvider;
        }
    }

    // Add category 'unknown' if not present
    if (!isset($orderedCategories['unknown'])) {
        $orderedCategories['unknown']['data'] = array(
            'Name' => 'Unknown',
            'Type' => 'category',
        );
    }

    foreach ($IDProviders as $entityId => $IDProvider) {

        // Skip categories
        if ($IDProvider['Type'] == 'category') {
            continue;
        }

        // Skip incomplete descriptions
        if (!is_array($IDProvider) || !isset($IDProvider['Name'])) {
            continue;
        }

        // Sanitize category
        if (!isset($IDProvider['Type'])) {
            $IDProvider['Type'] = 'unknown';
        }

        // Add IdP
        $orderedCategories[$IDProvider['Type']]['IdPs'][$entityId] = $IDProvider;
    }

    // Relocate all IdPs for which no category with a name was defined
    $toremoveCategories = array();
    foreach ($orderedCategories as $category => $object) {
        if (!isset($object['data'])) {
            foreach ($object['IdPs'] as $entityId => $IDProvider) {
                $unknownCategory[$entityId] = $IDProvider;
            }
            $toremoveCategories[] = $category;
        }
    }

    // Remove categories without descriptions
    foreach ($toremoveCategories as $category) {
        unset($orderedCategories[$category]);
    }

    // Recompose $IDProviders
    $IDProviders = array();
    foreach ($orderedCategories as $category => $object) {

        // Skip category if it contains no IdPs
        if (!isset($object['IdPs']) || count($object['IdPs']) < 1) {
            continue;
        }

        // Add category
        $IDProviders[$category] = $object['data'];

        // Sort IdPs in category
        uasort($object['IdPs'], 'sortUsingTypeIndexAndName');

        // Add IdPs
        foreach ($object['IdPs'] as $entityId => $IDProvider) {
            $IDProviders[$entityId] = $IDProvider;
        }
    }
1039 1040 1041 1042
}

/******************************************************************************/
// Sorts two entries according to their Type, Index and (local) Name
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
function sortUsingTypeIndexAndName($a, $b)
{
    global $language;

    if ($a['Type'] != $b['Type']) {
        return strcasecmp(removeAccents($a['Type']), removeAccents($b['Type']));
    } elseif (isset($a['Index']) && isset($b['Index']) && $a['Index'] != $b['Index']) {
        return strcasecmp(removeAccents($a['Index']), removeAccents($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 strcasecmp(removeAccents($localNameB), removeAccents($localNameA));
    }
}

/******************************************************************************/
// Return given Strring without accents
function removeAccents($string)
{
    $accents =    array("À","Á","Â","Ã","Ä","Å","à","á","â","ã","ä","å","Ò","Ó","Ô","Õ","Ö","Ø","ò","ó","ô","õ","ö","ø","È","É","Ê","Ë","è","é","ê","ë","Ç","ç","Ì","Í","Î","Ï","ì","í","î","ï","Ù","Ú","Û","Ü","ù","ú","û","ü","ÿ","Ñ","ñ");
    $nonAccents = array("a","a","a","a","a","a","a","a","a","a","a","a","o","o","o","o","o","o","o","o","o","o","o","o","e","e","e","e","e","e","e","e","c","c","i","i","i","i","i","i","i","i","u","u","u","u","u","u","u","u","y","n","n");
    return str_replace(
        $accents,
        $nonAccents,
        $string
        );
1070 1071
}

1072 1073 1074 1075

/******************************************************************************/
// Returns true if the referer of the current request is matching an assertion
// consumer or discovery service URL of a Service Provider
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
function isRequestRefererMatchingSPHost()
{
    global $SProviders;

    // If referer is not available return false
    if (!isset($_SERVER["HTTP_REFERER"]) || $_SERVER["HTTP_REFERER"] == '') {
        return false;
    }

    if (!isset($SProviders) || !is_array($SProviders)) {
        return false;
    }

    $refererHostname = getHostNameFromURI($_SERVER["HTTP_REFERER"]);
    foreach ($SProviders as $key => $SProvider) {
        // Check referer against entityID
        $spHostname = getHostNameFromURI($key);
        if ($refererHostname == $spHostname) {
            return true;
        }

        // Check referer against Discovery Response URL(DSURL)
        if (isset($SProvider['DSURL'])) {
            foreach ($SProvider['DSURL'] as $url) {
                $spHostname = getHostNameFromURI($url);
                if ($refererHostname == $spHostname) {
                    return true;
                }
            }
        }

        // Check referer against Assertion Consumer Service URL(ACURL)
        if (isset($SProvider['ACURL'])) {
            foreach ($SProvider['ACURL'] as $url) {
                $spHostname = getHostNameFromURI($url);
                if ($refererHostname == $spHostname) {
                    return true;
                }
            }
        }
    }

    return false;
1119
}
1120 1121 1122

/******************************************************************************/
// Is this script run in CLI mode
1123 1124 1125
function isRunViaCLI()
{
    return !isset($_SERVER['REMOTE_ADDR']);
1126 1127 1128 1129
}

/******************************************************************************/
// Is this script run in CLI mode
1130 1131 1132
function isRunViaInclude()
{
    return basename($_SERVER['SCRIPT_NAME']) != 'readMetadata.php';
1133
}
1134 1135 1136

function printSubmitAction()
{
1137
    if (isUseSelect2()) {
1138 1139 1140 1141 1142
        return "return select2CheckForm()";
    } else {
        return "return checkForm()";
    }
}
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

/******************************************************************************/
// Getter for useSelect2: we can't only rely on config.php::$useSelect2
// because of embeddedWAYF.
// If SP want's to use Select2, it has to add ?useSelect2=true
function isUseSelect2()
{
    global $useSelect2;

    if (!isset($_GET["useSelect2"])) {
        return $useSelect2;
    }

    return $_GET["useSelect2"];
}
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175

function getSelect2PageSize()
{
    global $select2PageSize;

    if (!isset($_GET["select2PageSize"])) {
        return $select2PageSize;
    }

    return $_GET["select2PageSize"];
}

function buildIdpData($IDProvider, $key)
{
    $data = getDomainNameFromURI($key);
    $data .= composeOptionData($IDProvider);
    return $data;
}