getSPkey() public method

Returns the x509 private key of the SP.
public getSPkey ( ) : string
return string SP private key
Ejemplo n.º 1
0
 /**
  * Decrypts the Assertion (DOMDocument)
  *
  * @param string $dom DomDocument
  *
  * @throws Exception
  * @return DOMDocument Decrypted Assertion
  */
 private function _decryptAssertion($dom)
 {
     $pem = $this->_settings->getSPkey();
     if (empty($pem)) {
         throw new Exception("No private key available, check settings");
     }
     $objenc = new XMLSecEnc();
     $encData = $objenc->locateEncryptedData($dom);
     if (!$encData) {
         throw new Exception("Cannot locate encrypted assertion");
     }
     $objenc->setNode($encData);
     $objenc->type = $encData->getAttribute("Type");
     if (!($objKey = $objenc->locateKey())) {
         throw new Exception("Unknown algorithm");
     }
     $key = null;
     if ($objKeyInfo = $objenc->locateKeyInfo($objKey)) {
         if ($objKeyInfo->isEncrypted) {
             $objencKey = $objKeyInfo->encryptedCtx;
             $objKeyInfo->loadKey($pem, false, false);
             $key = $objencKey->decryptKey($objKeyInfo);
         }
     }
     if (empty($objKey->key)) {
         $objKey->loadKey($key);
     }
     $decrypt = $objenc->decryptNode($objKey, true);
     if ($decrypt instanceof DOMDocument) {
         return $decrypt;
     } else {
         return $decrypt->ownerDocument;
     }
 }
Ejemplo n.º 2
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);
 }
Ejemplo n.º 3
0
 /**
  * Decrypts the Assertion (DOMDocument)
  *
  * @param DomNode $dom DomDocument
  *
  * @return DOMDocument Decrypted Assertion
  *
  * @throws Exception
  */
 protected function _decryptAssertion($dom)
 {
     $pem = $this->_settings->getSPkey();
     if (empty($pem)) {
         throw new Exception("No private key available, check settings");
     }
     $objenc = new XMLSecEnc();
     $encData = $objenc->locateEncryptedData($dom);
     if (!$encData) {
         throw new Exception("Cannot locate encrypted assertion");
     }
     $objenc->setNode($encData);
     $objenc->type = $encData->getAttribute("Type");
     if (!($objKey = $objenc->locateKey())) {
         throw new Exception("Unknown algorithm");
     }
     $key = null;
     if ($objKeyInfo = $objenc->locateKeyInfo($objKey)) {
         if ($objKeyInfo->isEncrypted) {
             $objencKey = $objKeyInfo->encryptedCtx;
             $objKeyInfo->loadKey($pem, false, false);
             $key = $objencKey->decryptKey($objKeyInfo);
         } else {
             // symmetric encryption key support
             $objKeyInfo->loadKey($pem, false, false);
         }
     }
     if (empty($objKey->key)) {
         $objKey->loadKey($key);
     }
     $decrypted = $objenc->decryptNode($objKey, true);
     if ($decrypted instanceof DOMDocument) {
         return $decrypted;
     } else {
         $encryptedAssertion = $decrypted->parentNode;
         $container = $encryptedAssertion->parentNode;
         # Fix possible issue with saml namespace
         if (!$decrypted->hasAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:saml') && !$decrypted->hasAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:saml2') && !$decrypted->hasAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns') && !$container->hasAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:saml') && !$container->hasAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:saml2')) {
             if (strpos($encryptedAssertion->tagName, 'saml2:') !== false) {
                 $ns = 'xmlns:saml2';
             } else {
                 if (strpos($encryptedAssertion->tagName, 'saml:') != false) {
                     $ns = 'xmlns:saml';
                 } else {
                     $ns = 'xmlns';
                 }
             }
             $decrypted->setAttributeNS('http://www.w3.org/2000/xmlns/', $ns, OneLogin_Saml2_Constants::NS_SAML);
         }
         $container->replaceChild($decrypted, $encryptedAssertion);
         return $decrypted->ownerDocument;
     }
 }
Ejemplo n.º 4
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;
     }
 }
Ejemplo n.º 5
0
 /**
  * Tests the addSign method of the OneLogin_Saml2_Utils
  *
  * @covers OneLogin_Saml2_Utils::addSign
  */
 public function testAddSign()
 {
     $settingsDir = TEST_ROOT . '/settings/';
     include $settingsDir . 'settings1.php';
     $settings = new OneLogin_Saml2_Settings($settingsInfo);
     $key = $settings->getSPkey();
     $cert = $settings->getSPcert();
     $xmlAuthn = base64_decode(file_get_contents(TEST_ROOT . '/data/requests/authn_request.xml.base64'));
     $xmlAuthnSigned = OneLogin_Saml2_Utils::addSign($xmlAuthn, $key, $cert);
     $this->assertContains('<ds:SignatureValue>', $xmlAuthnSigned);
     $res = new DOMDocument();
     $res->loadXML($xmlAuthnSigned);
     $dsSignature = $res->firstChild->firstChild->nextSibling->nextSibling;
     $this->assertContains('ds:Signature', $dsSignature->tagName);
     $dom = new DOMDocument();
     $dom->loadXML($xmlAuthn);
     $xmlAuthnSigned2 = OneLogin_Saml2_Utils::addSign($dom, $key, $cert);
     $this->assertContains('<ds:SignatureValue>', $xmlAuthnSigned2);
     $res2 = new DOMDocument();
     $res2->loadXML($xmlAuthnSigned2);
     $dsSignature2 = $res2->firstChild->firstChild->nextSibling->nextSibling;
     $this->assertContains('ds:Signature', $dsSignature2->tagName);
     $xmlLogoutReq = base64_decode(file_get_contents(TEST_ROOT . '/data/logout_requests/logout_request.xml.base64'));
     $xmlLogoutReqSigned = OneLogin_Saml2_Utils::addSign($xmlLogoutReq, $key, $cert);
     $this->assertContains('<ds:SignatureValue>', $xmlLogoutReqSigned);
     $res3 = new DOMDocument();
     $res3->loadXML($xmlLogoutReqSigned);
     $dsSignature3 = $res3->firstChild->firstChild->nextSibling->nextSibling;
     $this->assertContains('ds:Signature', $dsSignature3->tagName);
     $xmlLogoutRes = base64_decode(file_get_contents(TEST_ROOT . '/data/logout_responses/logout_response.xml.base64'));
     $xmlLogoutResSigned = OneLogin_Saml2_Utils::addSign($xmlLogoutRes, $key, $cert);
     $this->assertContains('<ds:SignatureValue>', $xmlLogoutResSigned);
     $res4 = new DOMDocument();
     $res4->loadXML($xmlLogoutResSigned);
     $dsSignature4 = $res4->firstChild->firstChild->nextSibling->nextSibling;
     $this->assertContains('ds:Signature', $dsSignature4->tagName);
     $xmlMetadata = file_get_contents(TEST_ROOT . '/data/metadata/metadata_settings1.xml');
     $xmlMetadataSigned = OneLogin_Saml2_Utils::addSign($xmlMetadata, $key, $cert);
     $this->assertContains('<ds:SignatureValue>', $xmlMetadataSigned);
     $res5 = new DOMDocument();
     $res5->loadXML($xmlMetadataSigned);
     $dsSignature5 = $res5->firstChild->firstChild;
     $this->assertContains('ds:Signature', $dsSignature5->tagName);
 }
Ejemplo n.º 6
0
 /**
  * Tests the checkSPCerts method of the OneLogin_Saml2_Settings
  *
  * @covers OneLogin_Saml2_Settings::checkSPCerts
  * @covers OneLogin_Saml2_Settings::getSPcert
  * @covers OneLogin_Saml2_Settings::getSPkey
  */
 public function testCheckSPCerts()
 {
     $settings = new OneLogin_Saml2_Settings();
     $this->assertTrue($settings->checkSPCerts());
     $settingsDir = TEST_ROOT . '/settings/';
     include $settingsDir . 'settings2.php';
     $settings2 = new OneLogin_Saml2_Settings($settingsInfo);
     $this->assertTrue($settings2->checkSPCerts());
     $this->assertEquals($settings2->getSPkey(), $settings->getSPkey());
     $this->assertEquals($settings2->getSPcert(), $settings->getSPcert());
 }
Ejemplo n.º 7
0
    /**
     * 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'];
        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>';
            }
        }
        $signature = '';
        if (isset($security['authnRequestsSigned']) && $security['authnRequestsSigned']) {
            $key = $this->_settings->getSPkey();
            $objKey = new XMLSecurityKey($security['signatureAlgorithm'], array('type' => 'private'));
            $objKey->loadKey($key, false);
            $signatureValue = $objKey->signData(time());
            $signatureValue = base64_encode($signatureValue);
            $digestValue = base64_encode(sha1(time()));
            $x509Cert = $this->_settings->getSPcert();
            $x509Cert = OneLogin_Saml2_Utils::formatCert($x509Cert, false);
            $signature = <<<SIGNATURE
            <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <ds:SignedInfo>
        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
        <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
        <ds:Reference>
            <ds:Transforms>
                <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
            <ds:DigestValue>{$digestValue}</ds:DigestValue>
        </ds:Reference>
    </ds:SignedInfo>
    <ds:SignatureValue>asd{$signatureValue}</ds:SignatureValue>
    <ds:KeyInfo>
        <ds:X509Data>
            <ds:X509Certificate>{$x509Cert}</ds:X509Certificate>
        </ds:X509Data>
    </ds:KeyInfo>
</ds:Signature>
SIGNATURE;
        }
        $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>
    {$signature}
    <samlp:NameIDPolicy
        Format="{$nameIDPolicyFormat}"
        AllowCreate="true" />
{$requestedAuthnStr}
</samlp:AuthnRequest>
AUTHNREQUEST;
        $this->_id = $id;
        $this->_authnRequest = $request;
    }