validateSign() public static method

Validates a signature (Message or Assertion).
public static validateSign ( string | DomNode $xml, string | null $cert = null, string | null $fingerprint = null, string | null $fingerprintalg = 'sha1', string | null $xpath = null ) : boolean
$xml string | DomNode The element we should validate
$cert string | null The pubic cert
$fingerprint string | null The fingerprint of the public cert
$fingerprintalg string | null The algorithm used to get the fingerprint
$xpath string | null The xpath of the signed element
return boolean
Example #1
0
 /**
  * Tests the validateSign method of the OneLogin_Saml2_Utils
  *
  * @covers OneLogin_Saml2_Utils::validateSign
  */
 public function testValidateSign()
 {
     $settingsDir = TEST_ROOT . '/settings/';
     include $settingsDir . 'settings1.php';
     $settings = new OneLogin_Saml2_Settings($settingsInfo);
     $idpData = $settings->getIdPData();
     $cert = $idpData['x509cert'];
     $fingerprint = OneLogin_Saml2_Utils::calculateX509Fingerprint($cert);
     $xmlMetadataSigned = file_get_contents(TEST_ROOT . '/data/metadata/signed_metadata_settings1.xml');
     $this->assertTrue(OneLogin_Saml2_Utils::validateSign($xmlMetadataSigned, $cert));
     $this->assertTrue(OneLogin_Saml2_Utils::validateSign($xmlMetadataSigned, null, $fingerprint));
     $xmlResponseMsgSigned = base64_decode(file_get_contents(TEST_ROOT . '/data/responses/signed_message_response.xml.base64'));
     $this->assertTrue(OneLogin_Saml2_Utils::validateSign($xmlResponseMsgSigned, $cert));
     $this->assertTrue(OneLogin_Saml2_Utils::validateSign($xmlResponseMsgSigned, null, $fingerprint));
     $xmlResponseAssertSigned = base64_decode(file_get_contents(TEST_ROOT . '/data/responses/signed_assertion_response.xml.base64'));
     $this->assertTrue(OneLogin_Saml2_Utils::validateSign($xmlResponseAssertSigned, $cert));
     $this->assertTrue(OneLogin_Saml2_Utils::validateSign($xmlResponseAssertSigned, null, $fingerprint));
     $xmlResponseDoubleSigned = base64_decode(file_get_contents(TEST_ROOT . '/data/responses/double_signed_response.xml.base64'));
     $this->assertTrue(OneLogin_Saml2_Utils::validateSign($xmlResponseDoubleSigned, $cert));
     $this->assertTrue(OneLogin_Saml2_Utils::validateSign($xmlResponseDoubleSigned, null, $fingerprint));
     $dom = new DOMDocument();
     $dom->loadXML($xmlResponseMsgSigned);
     $this->assertTrue(OneLogin_Saml2_Utils::validateSign($dom, $cert));
     $dom->firstChild->firstChild->nodeValue = 'https://example.com/other-idp';
     try {
         $this->assertFalse(OneLogin_Saml2_Utils::validateSign($dom, $cert));
         $this->assertTrue(false);
     } catch (Exception $e) {
         $this->assertContains('Reference validation failed', $e->getMessage());
     }
     $dom2 = new DOMDocument();
     $dom2->loadXML($xmlResponseMsgSigned);
     $assertElem = $dom2->firstChild->firstChild->nextSibling->nextSibling;
     $this->assertTrue(OneLogin_Saml2_Utils::validateSign($assertElem, $cert));
     $dom3 = new DOMDocument();
     $dom3->loadXML($xmlResponseMsgSigned);
     $dom3->firstChild->firstChild->nodeValue = 'https://example.com/other-idp';
     $assertElem2 = $dom3->firstChild->firstChild->nextSibling->nextSibling;
     try {
         $this->assertTrue(OneLogin_Saml2_Utils::validateSign($assertElem2, $cert));
         $this->assertTrue(false);
     } catch (Exception $e) {
         $this->assertContains('Reference validation failed', $e->getMessage());
     }
     $invalidFingerprint = 'afe71c34ef740bc87434be13a2263d31271da1f9';
     $this->assertFalse(OneLogin_Saml2_Utils::validateSign($xmlMetadataSigned, null, $invalidFingerprint));
     $noSigned = base64_decode(file_get_contents(TEST_ROOT . '/data/responses/invalids/no_signature.xml.base64'));
     try {
         $this->assertFalse(OneLogin_Saml2_Utils::validateSign($noSigned, $cert));
         $this->assertTrue(false);
     } catch (Exception $e) {
         $this->assertContains('Cannot locate Signature Node', $e->getMessage());
     }
     $noKey = base64_decode(file_get_contents(TEST_ROOT . '/data/responses/invalids/no_key.xml.base64'));
     try {
         $this->assertFalse(OneLogin_Saml2_Utils::validateSign($noKey, $cert));
         $this->assertTrue(false);
     } catch (Exception $e) {
         $this->assertContains('We have no idea about the key', $e->getMessage());
     }
 }
Example #2
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;
     }
 }