getSecurityData() public method

Gets security data.
public getSecurityData ( ) : array
return array SP info
示例#1
0
    /**
     * Constructs the AuthnRequest object.
     *
     * @param OneLogin_Saml2_Settings $settings Settings
     */
    public function __construct(OneLogin_Saml2_Settings $settings)
    {
        $this->_settings = $settings;
        $spData = $this->_settings->getSPData();
        $idpData = $this->_settings->getIdPData();
        $security = $this->_settings->getSecurityData();
        $id = OneLogin_Saml2_Utils::generateUniqueID();
        $issueInstant = OneLogin_Saml2_Utils::parseTime2SAML(time());
        $nameIDPolicyFormat = $spData['NameIDFormat'];
        if (isset($security['wantNameIdEncrypted']) && $security['wantNameIdEncrypted']) {
            $nameIDPolicyFormat = OneLogin_Saml2_Constants::NAMEID_ENCRYPTED;
        }
        $providerNameStr = '';
        $organizationData = $settings->getOrganization();
        if (!empty($organizationData)) {
            $langs = array_keys($organizationData);
            if (in_array('en-US', $langs)) {
                $lang = 'en-US';
            } else {
                $lang = $langs[0];
            }
            if (isset($organizationData[$lang]['displayname']) && !empty($organizationData[$lang]['displayname'])) {
                $providerNameStr = <<<PROVIDERNAME
    ProviderName="{$organizationData[$lang]['displayname']}" 
PROVIDERNAME;
            }
        }
        $request = <<<AUTHNREQUEST
<samlp:AuthnRequest
    xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
    ID="{$id}"
    Version="2.0"
{$providerNameStr}
    IssueInstant="{$issueInstant}"
    Destination="{$idpData['singleSignOnService']['url']}"
    ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
    AssertionConsumerServiceURL="{$spData['assertionConsumerService']['url']}">
    <saml:Issuer>{$spData['entityId']}</saml:Issuer>
    <samlp:NameIDPolicy
        Format="{$nameIDPolicyFormat}"
        AllowCreate="true" />
AUTHNREQUEST;
        if (!isset($security['allowedAuthContexts'])) {
            $security['allowedAuthContexts'] = array('urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport');
        }
        if ($security['allowedAuthContexts'] && is_array($security['allowedAuthContexts'])) {
            $request .= '<samlp:RequestedAuthnContext Comparison="exact">' . "\n";
            foreach ($security['allowedAuthContexts'] as $authCtx) {
                $request .= '<saml:AuthnContextClassRef>' . $authCtx . "</saml:AuthnContextClassRef>\n";
            }
            $request .= '</samlp:RequestedAuthnContext> ' . "\n";
        }
        $request .= '</samlp:AuthnRequest>';
        $this->_id = $id;
        $this->_authnRequest = $request;
    }
示例#2
0
文件: Auth.php 项目: DbyD/cruk
 /**
  * Initiates the SLO process.
  *
  * @param string $returnTo      The target URL the user should be returned to after logout.
  * @param array  $parameters    Extra parameters to be added to the GET
  * @param string $nameId        The NameID that will be set in the LogoutRequest.
  * @param string $sessionIndex  The SessionIndex (taken from the SAML Response in the SSO process).
  */
 public function logout($returnTo = null, $parameters = array(), $nameId = null, $sessionIndex = null)
 {
     assert('is_array($parameters)');
     $sloUrl = $this->getSLOurl();
     if (empty($sloUrl)) {
         throw new OneLogin_Saml2_Error('The IdP does not support Single Log Out', OneLogin_Saml2_Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED);
     }
     if (empty($nameId) && !empty($this->_nameid)) {
         $nameId = $this->_nameid;
     }
     $logoutRequest = new OneLogin_Saml2_LogoutRequest($this->_settings, null, $nameId, $sessionIndex);
     $samlRequest = $logoutRequest->getRequest();
     $parameters['SAMLRequest'] = $samlRequest;
     if (!empty($returnTo)) {
         $parameters['RelayState'] = $returnTo;
     } else {
         $parameters['RelayState'] = OneLogin_Saml2_Utils::getSelfRoutedURLNoQuery();
     }
     $security = $this->_settings->getSecurityData();
     if (isset($security['logoutRequestSigned']) && $security['logoutRequestSigned']) {
         $signature = $this->buildRequestSignature($samlRequest, $parameters['RelayState'], $security['signatureAlgorithm']);
         $parameters['SigAlg'] = $security['signatureAlgorithm'];
         $parameters['Signature'] = $signature;
     }
     return $this->redirectTo($sloUrl, $parameters);
 }
示例#3
0
 /**
  * Generates the Signature for a SAML Response
  *
  * @param string $samlResponse  The SAML Response
  * @param string $relayState    The RelayState
  * @param string $signAlgorithm Signature algorithm method
  *
  * @return string A base64 encoded signature
  *
  * @throws Exception
  * @throws OneLogin_Saml2_Error
  */
 public function buildResponseSignature($samlResponse, $relayState, $signAlgorithm = XMLSecurityKey::RSA_SHA1)
 {
     if (!$this->_settings->checkSPCerts()) {
         throw new OneLogin_Saml2_Error("Trying to sign the SAML Response but can't load the SP certs", OneLogin_Saml2_Error::SP_CERTS_NOT_FOUND);
     }
     $key = $this->_settings->getSPkey();
     $objKey = new XMLSecurityKey($signAlgorithm, array('type' => 'private'));
     $objKey->loadKey($key, false);
     $security = $this->_settings->getSecurityData();
     if ($security['lowercaseUrlencoding']) {
         $msg = 'SAMLResponse=' . rawurlencode($samlResponse);
         if (isset($relayState)) {
             $msg .= '&RelayState=' . rawurlencode($relayState);
         }
         $msg .= '&SigAlg=' . rawurlencode($signAlgorithm);
     } else {
         $msg = 'SAMLResponse=' . urlencode($samlResponse);
         if (isset($relayState)) {
             $msg .= '&RelayState=' . urlencode($relayState);
         }
         $msg .= '&SigAlg=' . urlencode($signAlgorithm);
     }
     $signature = $objKey->signData($msg);
     return base64_encode($signature);
 }
示例#4
0
 /**
  * Tests the signMetadata method of the OneLogin_Saml2_Metadata
  *
  * @covers OneLogin_Saml2_Metadata::signMetadata
  */
 public function testSignMetadata()
 {
     $settingsDir = TEST_ROOT . '/settings/';
     include $settingsDir . 'settings1.php';
     $settings = new OneLogin_Saml2_Settings($settingsInfo);
     $spData = $settings->getSPData();
     $security = $settings->getSecurityData();
     $metadata = OneLogin_Saml2_Metadata::builder($spData, $security['authnRequestsSigned'], $security['wantAssertionsSigned']);
     $this->assertNotEmpty($metadata);
     $certPath = $settings->getCertPath();
     $key = file_get_contents($certPath . 'sp.key');
     $cert = file_get_contents($certPath . 'sp.crt');
     $signedMetadata = OneLogin_Saml2_Metadata::signMetadata($metadata, $key, $cert);
     $this->assertContains('<md:SPSSODescriptor', $signedMetadata);
     $this->assertContains('entityID="http://stuff.com/endpoints/metadata.php"', $signedMetadata);
     $this->assertContains('AuthnRequestsSigned="false"', $signedMetadata);
     $this->assertContains('WantAssertionsSigned="false"', $signedMetadata);
     $this->assertContains('<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"', $signedMetadata);
     $this->assertContains('Location="http://stuff.com/endpoints/endpoints/acs.php"', $signedMetadata);
     $this->assertContains('<md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"', $signedMetadata);
     $this->assertContains(' Location="http://stuff.com/endpoints/endpoints/sls.php"/>', $signedMetadata);
     $this->assertContains('<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified</md:NameIDFormat>', $signedMetadata);
     $this->assertContains('<ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>', $signedMetadata);
     $this->assertContains('<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>', $signedMetadata);
     $this->assertContains('<ds:Reference', $signedMetadata);
     $this->assertContains('<ds:KeyInfo><ds:X509Data><ds:X509Certificate>', $signedMetadata);
     try {
         $signedMetadata2 = OneLogin_Saml2_Metadata::signMetadata('', $key, $cert);
         $this->assertFalse(true);
     } catch (Exception $e) {
         $this->assertContains('Empty string supplied as input', $e->getMessage());
     }
 }
 /**
  * Returns deflated, base64 encoded, unsigned AuthnRequest.
  *
  */
 public function getRequest()
 {
     $security = $this->_settings->getSecurityData();
     if (isset($security['authnRequestsSigned']) && $security['authnRequestsSigned']) {
         $base64Request = base64_encode($this->_authnRequest);
     } else {
         $deflatedRequest = gzdeflate($this->_authnRequest);
         $base64Request = base64_encode($deflatedRequest);
     }
     return $base64Request;
 }
示例#6
0
 /**
  * Gets the NameID Data provided by the SAML response from the IdP.
  *
  * @return array Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
  */
 public function getNameIdData()
 {
     $encryptedIdDataEntries = $this->_queryAssertion('/saml:Subject/saml:EncryptedID/xenc:EncryptedData');
     if ($encryptedIdDataEntries->length == 1) {
         $encryptedData = $encryptedIdDataEntries->item(0);
         $key = $this->_settings->getSPkey();
         $seckey = new XMLSecurityKey(XMLSecurityKey::RSA_1_5, array('type' => 'private'));
         $seckey->loadKey($key);
         $nameId = OneLogin_Saml2_Utils::decryptElement($encryptedData, $seckey);
     } else {
         $entries = $this->_queryAssertion('/saml:Subject/saml:NameID');
         if ($entries->length == 1) {
             $nameId = $entries->item(0);
         }
     }
     $nameIdData = array();
     if (!isset($nameId)) {
         $security = $this->_settings->getSecurityData();
         if ($security['wantNameId']) {
             throw new Exception("Not NameID found in the assertion of the Response");
         }
     } else {
         if ($this->_settings->isStrict() && empty($nameId->nodeValue)) {
             throw new Exception("An empty NameID value found");
         }
         $nameIdData['Value'] = $nameId->nodeValue;
         foreach (array('Format', 'SPNameQualifier', 'NameQualifier') as $attr) {
             if ($nameId->hasAttribute($attr)) {
                 if ($this->_settings->isStrict() && $attr == 'SPNameQualifier') {
                     $spData = $this->_settings->getSPData();
                     $spEntityId = $spData['entityId'];
                     if ($spEntityId != $nameId->getAttribute($attr)) {
                         throw new Exception("The SPNameQualifier value mistmatch the SP entityID value.");
                     }
                 }
                 $nameIdData[$attr] = $nameId->getAttribute($attr);
             }
         }
     }
     return $nameIdData;
 }
示例#7
0
 /**
  * Checks if the Logout Request recieved is valid.
  *
  * @return boolean If the Logout Request is or not valid
  */
 public function isValid($retrieveParametersFromServer = false)
 {
     $this->_error = null;
     try {
         $dom = new DOMDocument();
         $dom = OneLogin_Saml2_Utils::loadXML($dom, $this->_logoutRequest);
         $idpData = $this->_settings->getIdPData();
         $idPEntityId = $idpData['entityId'];
         if ($this->_settings->isStrict()) {
             $security = $this->_settings->getSecurityData();
             if ($security['wantXMLValidation']) {
                 $res = OneLogin_Saml2_Utils::validateXML($dom, 'saml-schema-protocol-2.0.xsd', $this->_settings->isDebugActive());
                 if (!$res instanceof DOMDocument) {
                     throw new Exception("Invalid SAML Logout Request. Not match the saml-schema-protocol-2.0.xsd");
                 }
             }
             $currentURL = OneLogin_Saml2_Utils::getSelfRoutedURLNoQuery();
             // Check NotOnOrAfter
             if ($dom->documentElement->hasAttribute('NotOnOrAfter')) {
                 $na = OneLogin_Saml2_Utils::parseSAML2Time($dom->documentElement->getAttribute('NotOnOrAfter'));
                 if ($na <= time()) {
                     throw new Exception('Timing issues (please check your clock settings)');
                 }
             }
             // Check destination
             if ($dom->documentElement->hasAttribute('Destination')) {
                 $destination = $dom->documentElement->getAttribute('Destination');
                 if (!empty($destination)) {
                     if (strpos($destination, $currentURL) === false) {
                         throw new Exception("The LogoutRequest was received at {$currentURL} instead of {$destination}");
                     }
                 }
             }
             $nameId = $this->getNameId($dom, $this->_settings->getSPkey());
             // Check issuer
             $issuer = $this->getIssuer($dom);
             if (!empty($issuer) && $issuer != $idPEntityId) {
                 throw new Exception("Invalid issuer in the Logout Request");
             }
             if ($security['wantMessagesSigned']) {
                 if (!isset($_GET['Signature'])) {
                     throw new Exception("The Message of the Logout Request is not signed and the SP require it");
                 }
             }
         }
         if (isset($_GET['Signature'])) {
             if (!isset($_GET['SigAlg'])) {
                 $signAlg = XMLSecurityKey::RSA_SHA1;
             } else {
                 $signAlg = $_GET['SigAlg'];
             }
             if ($retrieveParametersFromServer) {
                 $signedQuery = 'SAMLRequest=' . OneLogin_Saml2_Utils::extractOriginalQueryParam('SAMLRequest');
                 if (isset($_GET['RelayState'])) {
                     $signedQuery .= '&RelayState=' . OneLogin_Saml2_Utils::extractOriginalQueryParam('RelayState');
                 }
                 $signedQuery .= '&SigAlg=' . OneLogin_Saml2_Utils::extractOriginalQueryParam('SigAlg');
             } else {
                 $signedQuery = 'SAMLRequest=' . urlencode($_GET['SAMLRequest']);
                 if (isset($_GET['RelayState'])) {
                     $signedQuery .= '&RelayState=' . urlencode($_GET['RelayState']);
                 }
                 $signedQuery .= '&SigAlg=' . urlencode($signAlg);
             }
             if (!isset($idpData['x509cert']) || empty($idpData['x509cert'])) {
                 throw new Exception('In order to validate the sign on the Logout Request, the x509cert of the IdP is required');
             }
             $cert = $idpData['x509cert'];
             $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public'));
             $objKey->loadKey($cert, false, true);
             if ($signAlg != XMLSecurityKey::RSA_SHA1) {
                 try {
                     $objKey = OneLogin_Saml2_Utils::castKey($objKey, $signAlg, 'public');
                 } catch (Exception $e) {
                     throw new Exception('Invalid signAlg in the recieved Logout Request');
                 }
             }
             if (!$objKey->verifySignature($signedQuery, base64_decode($_GET['Signature']))) {
                 throw new Exception('Signature validation failed. Logout Request rejected');
             }
         }
         return true;
     } catch (Exception $e) {
         $this->_error = $e->getMessage();
         $debug = $this->_settings->isDebugActive();
         if ($debug) {
             echo $this->_error;
         }
         return false;
     }
 }
示例#8
0
 /**
  * Determines if the SAML LogoutResponse is valid
  *
  * @param string $requestId The ID of the LogoutRequest sent by this SP to the IdP
  *
  * @throws Exception
  * @return bool Returns if the SAML LogoutResponse is or not valid
  */
 public function isValid($requestId = null)
 {
     $this->_error = null;
     try {
         $idpData = $this->_settings->getIdPData();
         $idPEntityId = $idpData['entityId'];
         if ($this->_settings->isStrict()) {
             $res = OneLogin_Saml2_Utils::validateXML($this->document, 'saml-schema-protocol-2.0.xsd', $this->_settings->isDebugActive());
             if (!$res instanceof DOMDocument) {
                 throw new Exception("Invalid SAML Logout Response. Not match the saml-schema-protocol-2.0.xsd");
             }
             $security = $this->_settings->getSecurityData();
             // Check if the InResponseTo of the Logout Response matchs the ID of the Logout Request (requestId) if provided
             if (isset($requestId) && $this->document->documentElement->hasAttribute('InResponseTo')) {
                 $inResponseTo = $this->document->documentElement->getAttribute('InResponseTo');
                 if ($requestId != $inResponseTo) {
                     throw new Exception("The InResponseTo of the Logout Response: {$inResponseTo}, does not match the ID of the Logout request sent by the SP: {$requestId}");
                 }
             }
             // Check issuer
             $issuer = $this->getIssuer();
             if (empty($issuer) || $issuer != $idPEntityId) {
                 throw new Exception("Invalid issuer in the Logout Response");
             }
             $currentURL = OneLogin_Saml2_Utils::getSelfRoutedURLNoQuery();
             // Check destination
             if ($this->document->documentElement->hasAttribute('Destination')) {
                 $destination = $this->document->documentElement->getAttribute('Destination');
                 if (!empty($destination)) {
                     if (strpos($destination, $currentURL) === false) {
                         throw new Exception("The LogoutResponse was received at {$currentURL} instead of {$destination}");
                     }
                 }
             }
             if ($security['wantMessagesSigned']) {
                 if (!isset($_GET['Signature'])) {
                     throw new Exception("The Message of the Logout Response is not signed and the SP requires it");
                 }
             }
         }
         if (isset($_GET['Signature'])) {
             if (!isset($_GET['SigAlg'])) {
                 $signAlg = XMLSecurityKey::RSA_SHA1;
             } else {
                 $signAlg = $_GET['SigAlg'];
             }
             $signedQuery = 'SAMLResponse=' . urlencode($_GET['SAMLResponse']);
             if (isset($_GET['RelayState'])) {
                 $signedQuery .= '&RelayState=' . urlencode($_GET['RelayState']);
             }
             $signedQuery .= '&SigAlg=' . urlencode($signAlg);
             if (!isset($idpData['x509cert']) || empty($idpData['x509cert'])) {
                 throw new Exception('In order to validate the sign on the Logout Response, the x509cert of the IdP is required');
             }
             $cert = $idpData['x509cert'];
             $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public'));
             $objKey->loadKey($cert, false, true);
             if ($signAlg != XMLSecurityKey::RSA_SHA1) {
                 try {
                     $objKey = OneLogin_Saml2_Utils::castKey($objKey, $signAlg, 'public');
                 } catch (Exception $e) {
                     throw new Exception('Invalid signAlg in the recieved Logout Response');
                 }
             }
             if (!$objKey->verifySignature($signedQuery, base64_decode($_GET['Signature']))) {
                 throw new Exception('Signature validation failed. Logout Response rejected');
             }
         }
         return true;
     } catch (Exception $e) {
         $this->_error = $e->getMessage();
         $debug = $this->_settings->isDebugActive();
         if ($debug) {
             echo $this->_error;
         }
         return false;
     }
 }
示例#9
0
 /**
  * Tests default values of Security advanced sesettings
  *
  * @covers OneLogin_Saml2_Settings::getSecurityData
  */
 public function testGetDefaultSecurityValues()
 {
     $settingsDir = TEST_ROOT . '/settings/';
     include $settingsDir . 'settings1.php';
     unset($settingsInfo['security']);
     $settings = new OneLogin_Saml2_Settings($settingsInfo);
     $security = $settings->getSecurityData();
     $this->assertNotEmpty($security);
     $this->assertArrayHasKey('nameIdEncrypted', $security);
     $this->assertFalse($security['nameIdEncrypted']);
     $this->assertArrayHasKey('authnRequestsSigned', $security);
     $this->assertFalse($security['authnRequestsSigned']);
     $this->assertArrayHasKey('logoutRequestSigned', $security);
     $this->assertFalse($security['logoutRequestSigned']);
     $this->assertArrayHasKey('logoutResponseSigned', $security);
     $this->assertFalse($security['logoutResponseSigned']);
     $this->assertArrayHasKey('signMetadata', $security);
     $this->assertFalse($security['signMetadata']);
     $this->assertArrayHasKey('wantMessagesSigned', $security);
     $this->assertFalse($security['wantMessagesSigned']);
     $this->assertArrayHasKey('wantAssertionsSigned', $security);
     $this->assertFalse($security['wantAssertionsSigned']);
     $this->assertArrayHasKey('wantAssertionsEncrypted', $security);
     $this->assertFalse($security['wantAssertionsEncrypted']);
     $this->assertArrayHasKey('wantNameIdEncrypted', $security);
     $this->assertFalse($security['wantNameIdEncrypted']);
     $this->assertArrayHasKey('requestedAuthnContext', $security);
     $this->assertTrue($security['requestedAuthnContext']);
     $this->assertArrayHasKey('wantXMLValidation', $security);
     $this->assertTrue($security['wantXMLValidation']);
     $this->assertArrayHasKey('wantNameId', $security);
     $this->assertTrue($security['wantNameId']);
 }
示例#10
0
 /**
  * Determines if the SAML Response is valid using the certificate.
  *
  * @param string $requestId The ID of the AuthNRequest sent by this SP to the IdP
  *
  * @throws Exception
  * @return bool Validate the document
  */
 public function isValid($requestId = null)
 {
     $this->_error = null;
     try {
         // Check SAML version
         if ($this->document->documentElement->getAttribute('Version') != '2.0') {
             throw new Exception('Unsupported SAML version');
         }
         if (!$this->document->documentElement->hasAttribute('ID')) {
             throw new Exception('Missing ID attribute on SAML Response');
         }
         $status = $this->checkStatus();
         $singleAssertion = $this->validateNumAssertions();
         if (!$singleAssertion) {
             throw new Exception('SAML Response must contain 1 assertion');
         }
         $idpData = $this->_settings->getIdPData();
         $idPEntityId = $idpData['entityId'];
         $spData = $this->_settings->getSPData();
         $spEntityId = $spData['entityId'];
         $signedElements = array();
         if ($this->encrypted) {
             $signNodes = $this->decryptedDocument->getElementsByTagName('Signature');
         } else {
             $signNodes = $this->document->getElementsByTagName('Signature');
         }
         foreach ($signNodes as $signNode) {
             $signedElements[] = $signNode->parentNode->localName;
         }
         if (!empty($signedElements)) {
             // Check SignedElements
             if (!$this->validateSignedElements($signedElements)) {
                 throw new Exception('Found an unexpected Signature Element. SAML Response rejected');
             }
         }
         if ($this->_settings->isStrict()) {
             $security = $this->_settings->getSecurityData();
             if ($security['wantXMLValidation']) {
                 $res = OneLogin_Saml2_Utils::validateXML($this->document, 'saml-schema-protocol-2.0.xsd', $this->_settings->isDebugActive());
                 if (!$res instanceof DOMDocument) {
                     throw new Exception("Invalid SAML Response. Not match the saml-schema-protocol-2.0.xsd");
                 }
             }
             $currentURL = OneLogin_Saml2_Utils::getSelfRoutedURLNoQuery();
             if ($this->document->documentElement->hasAttribute('InResponseTo')) {
                 $responseInResponseTo = $this->document->documentElement->getAttribute('InResponseTo');
             }
             // Check if the InResponseTo of the Response matchs the ID of the AuthNRequest (requestId) if provided
             if (isset($requestId) && isset($responseInResponseTo)) {
                 if ($requestId != $responseInResponseTo) {
                     throw new Exception("The InResponseTo of the Response: {$responseInResponseTo}, does not match the ID of the AuthNRequest sent by the SP: {$requestId}");
                 }
             }
             if (!$this->encrypted && $security['wantAssertionsEncrypted']) {
                 throw new Exception("The assertion of the Response is not encrypted and the SP requires it");
             }
             if ($security['wantNameIdEncrypted']) {
                 $encryptedIdNodes = $this->_queryAssertion('/saml:Subject/saml:EncryptedID/xenc:EncryptedData');
                 if ($encryptedIdNodes->length == 0) {
                     throw new Exception("The NameID of the Response is not encrypted and the SP requires it");
                 }
             }
             // Validate Asserion timestamps
             $validTimestamps = $this->validateTimestamps();
             if (!$validTimestamps) {
                 throw new Exception('Timing issues (please check your clock settings)');
             }
             // EncryptedAttributes are not supported
             $encryptedAttributeNodes = $this->_queryAssertion('/saml:AttributeStatement/saml:EncryptedAttribute');
             if ($encryptedAttributeNodes->length > 0) {
                 throw new Exception("There is an EncryptedAttribute in the Response and this SP not support them");
             }
             // Check destination
             if ($this->document->documentElement->hasAttribute('Destination')) {
                 $destination = $this->document->documentElement->getAttribute('Destination');
                 if (!empty($destination)) {
                     if (strpos($destination, $currentURL) !== 0) {
                         $currentURLrouted = OneLogin_Saml2_Utils::getSelfRoutedURLNoQuery();
                         if (strpos($destination, $currentURLrouted) !== 0) {
                             throw new Exception("The response was received at {$currentURL} instead of {$destination}");
                         }
                     }
                 }
             }
             // Check audience
             $validAudiences = $this->getAudiences();
             if (!empty($validAudiences) && !in_array($spEntityId, $validAudiences)) {
                 throw new Exception("{$spEntityId} is not a valid audience for this Response");
             }
             // Check the issuers
             $issuers = $this->getIssuers();
             foreach ($issuers as $issuer) {
                 if (empty($issuer) || $issuer != $idPEntityId) {
                     throw new Exception("Invalid issuer in the Assertion/Response");
                 }
             }
             // Check the session Expiration
             $sessionExpiration = $this->getSessionNotOnOrAfter();
             if (!empty($sessionExpiration) && $sessionExpiration <= time()) {
                 throw new Exception("The attributes have expired, based on the SessionNotOnOrAfter of the AttributeStatement of this Response");
             }
             // Check the SubjectConfirmation, at least one SubjectConfirmation must be valid
             $anySubjectConfirmation = false;
             $subjectConfirmationNodes = $this->_queryAssertion('/saml:Subject/saml:SubjectConfirmation');
             foreach ($subjectConfirmationNodes as $scn) {
                 if ($scn->hasAttribute('Method') && $scn->getAttribute('Method') != OneLogin_Saml2_Constants::CM_BEARER) {
                     continue;
                 }
                 $subjectConfirmationDataNodes = $scn->getElementsByTagName('SubjectConfirmationData');
                 if ($subjectConfirmationDataNodes->length == 0) {
                     continue;
                 } else {
                     $scnData = $subjectConfirmationDataNodes->item(0);
                     if ($scnData->hasAttribute('InResponseTo')) {
                         $inResponseTo = $scnData->getAttribute('InResponseTo');
                         if ($responseInResponseTo != $inResponseTo) {
                             continue;
                         }
                     }
                     if ($scnData->hasAttribute('Recipient')) {
                         $recipient = $scnData->getAttribute('Recipient');
                         if (!empty($recipient) && strpos($recipient, $currentURL) === false) {
                             continue;
                         }
                     }
                     if ($scnData->hasAttribute('NotOnOrAfter')) {
                         $noa = OneLogin_Saml2_Utils::parseSAML2Time($scnData->getAttribute('NotOnOrAfter'));
                         if ($noa <= time()) {
                             continue;
                         }
                     }
                     if ($scnData->hasAttribute('NotBefore')) {
                         $nb = OneLogin_Saml2_Utils::parseSAML2Time($scnData->getAttribute('NotBefore'));
                         if ($nb > time()) {
                             continue;
                         }
                     }
                     $anySubjectConfirmation = true;
                     break;
                 }
             }
             if (!$anySubjectConfirmation) {
                 throw new Exception("A valid SubjectConfirmation was not found on this Response");
             }
             if ($security['wantAssertionsSigned'] && !in_array('Assertion', $signedElements)) {
                 throw new Exception("The Assertion of the Response is not signed and the SP requires it");
             }
             if ($security['wantMessagesSigned'] && !in_array('Response', $signedElements)) {
                 throw new Exception("The Message of the Response is not signed and the SP requires it");
             }
         }
         if (!empty($signedElements)) {
             $cert = $idpData['x509cert'];
             $fingerprint = $idpData['certFingerprint'];
             $fingerprintalg = $idpData['certFingerprintAlgorithm'];
             // Only validates the first signed element
             if (in_array('Response', $signedElements)) {
                 $documentToValidate = $this->document;
             } else {
                 $documentToValidate = $signNodes->item(0)->parentNode;
                 if ($this->encrypted) {
                     $encryptedIDNodes = OneLogin_Saml2_Utils::query($this->decryptedDocument, '/samlp:Response/saml:EncryptedAssertion/saml:Assertion/saml:Subject/saml:EncryptedID');
                     if ($encryptedIDNodes->length > 0) {
                         throw new Exception('Unsigned SAML Response that contains a signed and encrypted Assertion with encrypted nameId is not supported.');
                     }
                 }
             }
             if (!OneLogin_Saml2_Utils::validateSign($documentToValidate, $cert, $fingerprint, $fingerprintalg)) {
                 throw new Exception('Signature validation failed. SAML Response rejected');
             }
         } else {
             throw new Exception('No Signature found. SAML Response rejected');
         }
         return true;
     } catch (Exception $e) {
         $this->_error = $e->getMessage();
         $debug = $this->_settings->isDebugActive();
         if ($debug) {
             echo $this->_error;
         }
         return false;
     }
 }
示例#11
0
 /**
  * Tests the getSecurityData method of the OneLogin_Saml2_Settings
  *
  * @covers OneLogin_Saml2_Settings::getSecurityData
  */
 public function testGetSecurityData()
 {
     $settingsDir = TEST_ROOT . '/settings/';
     include $settingsDir . 'settings1.php';
     $settings = new OneLogin_Saml2_Settings($settingsInfo);
     $security = $settings->getSecurityData();
     $this->assertNotEmpty($security);
     $this->assertArrayHasKey('nameIdEncrypted', $security);
     $this->assertArrayHasKey('authnRequestsSigned', $security);
     $this->assertArrayHasKey('logoutRequestSigned', $security);
     $this->assertArrayHasKey('logoutResponseSigned', $security);
     $this->assertArrayHasKey('signMetadata', $security);
     $this->assertArrayHasKey('wantMessagesSigned', $security);
     $this->assertArrayHasKey('wantAssertionsSigned', $security);
     $this->assertArrayHasKey('wantNameIdEncrypted', $security);
 }
    /**
     * Constructs the AuthnRequest object.
     *
     * @param OneLogin_Saml2_Settings $settings Settings
     * @param bool   $forceAuthn When true the AuthNReuqest will set the ForceAuthn='true'
     * @param bool   $isPassive  When true the AuthNReuqest will set the Ispassive='true' 
     */
    public function __construct(OneLogin_Saml2_Settings $settings, $forceAuthn = false, $isPassive = false)
    {
        $this->_settings = $settings;
        $spData = $this->_settings->getSPData();
        $idpData = $this->_settings->getIdPData();
        $security = $this->_settings->getSecurityData();
        $id = OneLogin_Saml2_Utils::generateUniqueID();
        $issueInstant = OneLogin_Saml2_Utils::parseTime2SAML(time());
        $nameIDPolicyFormat = $spData['NameIDFormat'];
        echo "1@@@@@@@@@@@@<br /> nameIDPolicyFormat: ";
        print_r($nameIDPolicyFormat);
        echo "<br /> OneLogin_Saml2_Constants::NAMEID_ENCRYPTED: ";
        print_r(OneLogin_Saml2_Constants::NAMEID_ENCRYPTED);
        echo "2@@@@@@@@@@@@<br />";
        //$nameIDPolicyFormat = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified";
        if (isset($security['wantNameIdEncrypted']) && $security['wantNameIdEncrypted']) {
            $nameIDPolicyFormat = OneLogin_Saml2_Constants::NAMEID_ENCRYPTED;
        }
        $providerNameStr = '';
        $organizationData = $settings->getOrganization();
        if (!empty($organizationData)) {
            $langs = array_keys($organizationData);
            if (in_array('en-US', $langs)) {
                $lang = 'en-US';
            } else {
                $lang = $langs[0];
            }
            if (isset($organizationData[$lang]['displayname']) && !empty($organizationData[$lang]['displayname'])) {
                $providerNameStr = <<<PROVIDERNAME
    ProviderName="{$organizationData[$lang]['displayname']}" 
PROVIDERNAME;
            }
        }
        $forceAuthnStr = '';
        if ($forceAuthn) {
            $forceAuthnStr = <<<FORCEAUTHN

    ForceAuthn="true"
FORCEAUTHN;
        }
        $isPassiveStr = '';
        if ($isPassive) {
            $isPassiveStr = <<<ISPASSIVE

    IsPassive="true"
ISPASSIVE;
        }
        $requestedAuthnStr = '';
        if (isset($security['requestedAuthnContext']) && $security['requestedAuthnContext'] !== false) {
            if ($security['requestedAuthnContext'] === true) {
                $requestedAuthnStr = <<<REQUESTEDAUTHN
    <samlp:RequestedAuthnContext Comparison="exact">
        <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>
    </samlp:RequestedAuthnContext>
REQUESTEDAUTHN;
            } else {
                $requestedAuthnStr .= "    <samlp:RequestedAuthnContext Comparison=\"exact\">\n";
                foreach ($security['requestedAuthnContext'] as $contextValue) {
                    $requestedAuthnStr .= "        <saml:AuthnContextClassRef>" . $contextValue . "</saml:AuthnContextClassRef>\n";
                }
                $requestedAuthnStr .= '    </samlp:RequestedAuthnContext>';
            }
        }
        $request = <<<AUTHNREQUEST
<samlp:AuthnRequest
    xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
    ID="{$id}"
    Version="2.0"
{$providerNameStr}{$forceAuthnStr}{$isPassiveStr}
    IssueInstant="{$issueInstant}"
    Destination="{$idpData['singleSignOnService']['url']}"
    ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
    AssertionConsumerServiceURL="{$spData['assertionConsumerService']['url']}">
    <saml:Issuer>{$spData['entityId']}</saml:Issuer>
    <samlp:NameIDPolicy
        Format="{$nameIDPolicyFormat}"
        AllowCreate="true" />
{$requestedAuthnStr}
</samlp:AuthnRequest>
AUTHNREQUEST;
        $this->_id = $id;
        $this->_authnRequest = $request;
    }