public function is_valid() { $objXMLSecDSig = new XMLSecurityDSig(); $objDSig = $objXMLSecDSig->locateSignature($this->document); if (!$objDSig) { throw new Exception("Cannot locate Signature Node"); } $objXMLSecDSig->canonicalizeSignedInfo(); $objXMLSecDSig->idKeys = array('ID'); $retVal = $objXMLSecDSig->validateReference(); if (!$retVal) { throw new Exception("Reference Validation Failed"); } $objKey = $objXMLSecDSig->locateKey(); if (!$objKey) { throw new Exception("We have no idea about the key"); } $key = null; $singleAssertion = $this->validateNumAssertions(); if (!$singleAssertion) { throw new Exception("Only one SAMLAssertion allowed"); } $validTimestamps = $this->validateTimestamps(); if (!$validTimestamps) { throw new Exception("SAMLAssertion conditions not met"); } $objKeyInfo = XMLSecEnc::staticLocateKeyInfo($objKey, $objDSig); $objKey->loadKey($this->settings->x509certificate, false, true); $result = $objXMLSecDSig->verify($objKey); return $result; }
/** * @return bool * @throws Exception */ public function isValid() { $singleAssertion = $this->validateNumAssertions(); if (!$singleAssertion) { throw new Exception('Multiple assertions are not supported'); } $validTimestamps = $this->validateTimestamps(); if (!$validTimestamps) { throw new Exception('Timing issues (please check your clock settings)'); } $objXMLSecDSig = new XMLSecurityDSig(); $objDSig = $objXMLSecDSig->locateSignature($this->_document); if (!$objDSig) { throw new Exception('Cannot locate Signature Node'); } $objXMLSecDSig->canonicalizeSignedInfo(); $objXMLSecDSig->idKeys = array('ID'); $objKey = $objXMLSecDSig->locateKey(); if (!$objKey) { throw new Exception('We have no idea about the key'); } try { $retVal = $objXMLSecDSig->validateReference(); } catch (Exception $e) { throw new Exception('Reference Validation Failed'); } XMLSecEnc::staticLocateKeyInfo($objKey, $objDSig); $objKey->loadKey($this->_settings->idpPublicCertificate, false, true); return $objXMLSecDSig->verify($objKey) === 1; }
public function testWithCommentIdUriObject() { $doc = new \DOMDocument(); $doc->load(dirname(__FILE__) . '/../withcomment-id-uri-object.xml'); $objXMLSecDSig = new XMLSecurityDSig(); $objXMLSecDSig->idKeys = array('xml:id'); $objDSig = $objXMLSecDSig->locateSignature($doc); $this->assertInstanceOf('\\DomElement', $objDSig, "Cannot locate Signature Node"); $retVal = $objXMLSecDSig->validateReference(); $this->assertTrue($retVal, "Reference Validation Failed"); }
function is_valid() { $objXMLSecDSig = new XMLSecurityDSig(); $objDSig = $objXMLSecDSig->locateSignature($this->doc); if (!$objDSig) { throw new Exception("Cannot locate Signature Node"); //, 'error', FALSE return false; } $objXMLSecDSig->canonicalizeSignedInfo(); $objXMLSecDSig->idKeys = array('ID'); $retVal = $objXMLSecDSig->validateReference(); if (!$retVal) { throw new Exception("SAML Assertion Error: Reference Validation Failed"); //, 'error', FALSE return false; // throw new Exception("Reference Validation Failed"); } $objKey = $objXMLSecDSig->locateKey(); if (!$objKey) { throw new Exception("SAML Assertion Error: We have no idea about the key"); //, 'error', FALSE return false; // throw new Exception("We have no idea about the key"); } $key = NULL; $singleAssertion = $this->validateNumAssertions(); if (!$singleAssertion) { throw new Exception("SAML Assertion Error: Only ONE SAML Assertion Allowed"); //, 'error', FALSE return false; // throw new Exception("Only ONE SamlAssertion allowed"); } $validTimestamps = $this->validateTimestamps(); if (!$validTimestamps) { throw new Exception("SAML Assertion Error: Check your timestamp conditions"); //, 'error', FALSE return false; // throw new Exception("Check your timestamp conditions"); } $objKeyInfo = XMLSecEnc::staticLocateKeyInfo($objKey, $objDSig); $objKey->loadKey($this->x509certificate, FALSE, true); $result = $objXMLSecDSig->verify($objKey); return $result; }
/** * This function initializes the validator. * * @param $xmlNode The XML node which contains the Signature element. * @param $idAttribute The ID attribute which is used in node references. If this attribute is * NULL (the default), then we will use whatever is the default ID. */ public function __construct($xmlNode, $idAttribute = NULL, $publickey = FALSE) { assert('$xmlNode instanceof DOMNode'); /* Create an XML security object. */ $objXMLSecDSig = new XMLSecurityDSig(); /* Add the id attribute if the user passed in an id attribute. */ if ($idAttribute !== NULL) { assert('is_string($idAttribute)'); $objXMLSecDSig->idKeys[] = $idAttribute; } /* Locate the XMLDSig Signature element to be used. */ $signatureElement = $objXMLSecDSig->locateSignature($xmlNode); if (!$signatureElement) { throw new Exception('Could not locate XML Signature element.'); } /* Canonicalize the XMLDSig SignedInfo element in the message. */ $objXMLSecDSig->canonicalizeSignedInfo(); /* Validate referenced xml nodes. */ if (!$objXMLSecDSig->validateReference()) { throw new Exception('XMLsec: digest validation failed'); } /* Find the key used to sign the document. */ $objKey = $objXMLSecDSig->locateKey(); if (empty($objKey)) { throw new Exception('Error loading key to handle XML signature'); } /* Load the key data. */ if ($publickey) { $objKey->loadKey($publickey); } else { if (!XMLSecEnc::staticLocateKeyInfo($objKey, $signatureElement)) { throw new Exception('Error finding key data for XML signature validation.'); } } /* Check the signature. */ if (!$objXMLSecDSig->verify($objKey)) { throw new Exception("Unable to validate Signature"); } /* Extract the certificate fingerprint. */ $this->x509Fingerprint = $objKey->getX509Fingerprint(); /* Find the list of validated nodes. */ $this->validNodes = $objXMLSecDSig->getValidatedNodes(); }
function is_valid() { $objXMLSecDSig = new XMLSecurityDSig(); $objDSig = $objXMLSecDSig->locateSignature($this->doc); if (!$objDSig) { throw new Exception("Cannot locate Signature Node"); } $objXMLSecDSig->canonicalizeSignedInfo(); $objXMLSecDSig->idKeys = array('ID'); $retVal = $objXMLSecDSig->validateReference(); if (!$retVal) { throw new Exception("Reference Validation Failed"); } $objKey = $objXMLSecDSig->locateKey(); if (!$objKey) { throw new Exception("We have no idea about the key"); } $key = NULL; $objKeyInfo = XMLSecEnc::staticLocateKeyInfo($objKey, $objDSig); $objKey->loadKey($this->x509certificate, FALSE, true); $result = $objXMLSecDSig->verify($objKey); return $result; }
public function attachTokentoSig($token) { if (!$token instanceof DOMElement) { throw new Exception('Invalid parameter: BinarySecurityToken element expected'); } $objXMLSecDSig = new XMLSecurityDSig(); if ($objDSig = $objXMLSecDSig->locateSignature($this->soapDoc)) { $tokenURI = '#' . $token->getAttributeNS(self::WSUNS, "Id"); $this->SOAPXPath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS); $query = "./secdsig:KeyInfo"; $nodeset = $this->SOAPXPath->query($query, $objDSig); $keyInfo = $nodeset->item(0); if (!$keyInfo) { $keyInfo = $objXMLSecDSig->createNewSignNode('KeyInfo'); $objDSig->appendChild($keyInfo); } $tokenRef = $this->soapDoc->createElementNS(self::WSSENS, self::WSSEPFX . ':SecurityTokenReference'); $keyInfo->appendChild($tokenRef); $reference = $this->soapDoc->createElementNS(self::WSSENS, self::WSSEPFX . ':Reference'); $reference->setAttribute('ValueType', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3'); $reference->setAttribute("URI", $tokenURI); $tokenRef->appendChild($reference); } else { throw new Exception('Unable to locate digital signature'); } }
/** * Validates a signature (Message or Assertion). * * @param string|DomDocument $xml The element we should validate * @param string|null $cert The pubic cert * @param string|null $fingerprint The fingerprint of the public cert */ public static function validateSign($xml, $cert = null, $fingerprint = null) { if ($xml instanceof DOMDocument) { $dom = clone $xml; } else { if ($xml instanceof DOMElement) { $dom = clone $xml->ownerDocument; } else { $dom = new DOMDocument(); $dom = self::loadXML($dom, $xml); } } $objXMLSecDSig = new XMLSecurityDSig(); $objXMLSecDSig->idKeys = array('ID'); $objDSig = $objXMLSecDSig->locateSignature($dom); if (!$objDSig) { throw new Exception('Cannot locate Signature Node'); } $objKey = $objXMLSecDSig->locateKey(); if (!$objKey) { throw new Exception('We have no idea about the key'); } $objXMLSecDSig->canonicalizeSignedInfo(); try { $retVal = $objXMLSecDSig->validateReference(); } catch (Exception $e) { throw $e; } XMLSecEnc::staticLocateKeyInfo($objKey, $objDSig); if (!empty($cert)) { $objKey->loadKey($cert, false, true); return $objXMLSecDSig->verify($objKey) === 1; } else { $domCert = $objKey->getX509Certificate(); $domCertFingerprint = OneLogin_Saml2_Utils::calculateX509Fingerprint($domCert); if (OneLogin_Saml2_Utils::formatFingerPrint($fingerprint) !== $domCertFingerprint) { return false; } else { $objKey->loadKey($domCert, false, true); return $objXMLSecDSig->verify($objKey) === 1; } } }
/** * This function initializes the validator. * * This function accepts an optional parameter $publickey, which is the public key * or certificate which should be used to validate the signature. This parameter can * take the following values: * - NULL/FALSE: No validation will be performed. This is the default. * - A string: Assumed to be a PEM-encoded certificate / public key. * - An array: Assumed to be an array returned by SimpleSAML_Utilities::loadPublicKey. * * @param DOMNode $xmlNode The XML node which contains the Signature element. * @param string|array $idAttribute The ID attribute which is used in node references. If * this attribute is NULL (the default), then we will use whatever is the default * ID. Can be eigther a string with one value, or an array with multiple ID * attrbute names. * @param array $publickey The public key / certificate which should be used to validate the XML node. */ public function __construct($xmlNode, $idAttribute = NULL, $publickey = FALSE) { assert('$xmlNode instanceof DOMNode'); if ($publickey === NULL) { $publickey = FALSE; } elseif (is_string($publickey)) { $publickey = array('PEM' => $publickey); } else { assert('$publickey === FALSE || is_array($publickey)'); } /* Create an XML security object. */ $objXMLSecDSig = new XMLSecurityDSig(); /* Add the id attribute if the user passed in an id attribute. */ if ($idAttribute !== NULL) { if (is_string($idAttribute)) { $objXMLSecDSig->idKeys[] = $idAttribute; } elseif (is_array($idAttribute)) { foreach ($idAttribute as $ida) { $objXMLSecDSig->idKeys[] = $ida; } } } /* Locate the XMLDSig Signature element to be used. */ $signatureElement = $objXMLSecDSig->locateSignature($xmlNode); if (!$signatureElement) { throw new Exception('Could not locate XML Signature element.'); } /* Canonicalize the XMLDSig SignedInfo element in the message. */ $objXMLSecDSig->canonicalizeSignedInfo(); /* Validate referenced xml nodes. */ if (!$objXMLSecDSig->validateReference()) { throw new Exception('XMLsec: digest validation failed'); } /* Find the key used to sign the document. */ $objKey = $objXMLSecDSig->locateKey(); if (empty($objKey)) { throw new Exception('Error loading key to handle XML signature'); } /* Load the key data. */ if ($publickey !== FALSE && array_key_exists('PEM', $publickey)) { /* We have PEM data for the public key / certificate. */ $objKey->loadKey($publickey['PEM']); } else { /* No PEM data. Search for key in signature. */ if (!XMLSecEnc::staticLocateKeyInfo($objKey, $signatureElement)) { throw new Exception('Error finding key data for XML signature validation.'); } if ($publickey !== FALSE) { /* $publickey is set, and should therefore contain one or more fingerprints. * Check that the response contains a certificate with a matching * fingerprint. */ assert('is_array($publickey["certFingerprint"])'); $certificate = $objKey->getX509Certificate(); if ($certificate === NULL) { /* Wasn't signed with an X509 certificate. */ throw new Exception('Message wasn\'t signed with an X509 certificate,' . ' and no public key was provided in the metadata.'); } self::validateCertificateFingerprint($certificate, $publickey['certFingerprint']); /* Key OK. */ } } /* Check the signature. */ if (!$objXMLSecDSig->verify($objKey)) { throw new Exception("Unable to validate Signature"); } /* Extract the certificate. */ $this->x509Certificate = $objKey->getX509Certificate(); /* Find the list of validated nodes. */ $this->validNodes = $objXMLSecDSig->getValidatedNodes(); }
public function addIssuerSerial($X509Cert) { $name = getIssuerName($X509Cert); $serialNumber = getSerialNumber($X509Cert); $objXMLSecDSig = new XMLSecurityDSig(); if ($objDSig = $objXMLSecDSig->locateSignature($this->soapDoc)) { $this->SOAPXPath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS); $query = "./secdsig:KeyInfo"; $nodeset = $this->SOAPXPath->query($query, $objDSig); $keyInfo = $nodeset->item(0); if (!$keyInfo) { $keyInfo = $objXMLSecDSig->createNewSignNode('KeyInfo'); $objDSig->appendChild($keyInfo); } $tokenRef = $this->soapDoc->createElementNS(WSSESoap::WSSENS, WSSESoap::WSSEPFX . ':SecurityTokenReference'); $keyInfo->appendChild($tokenRef); $x509Data = $objXMLSecDSig->createNewSignNode("X509Data"); $x509IssuerSerial = $objXMLSecDSig->createNewSignNode("X509IssuerSerial"); $x509Data->appendChild($x509IssuerSerial); $x509IssuerName = $objXMLSecDSig->createNewSignNode("X509IssuerName", $name); $x509SerialNumber = $objXMLSecDSig->createNewSignNode("X509SerialNumber", $serialNumber); $x509IssuerSerial->appendChild($x509IssuerName); $x509IssuerSerial->appendChild($x509SerialNumber); $tokenRef->appendChild($x509Data); } else { throw new Exception('Unable to locate digital signature'); } }
/** * Validates a signature (Message or Assertion). * * @param string|DomDocument $xml The element we should validate * @param string|null $cert The pubic cert * @param string|null $fingerprint The fingerprint of the public cert * @param string|null $fingerprintalg The algorithm used to get the fingerprint */ public static function validateSign($xml, $cert = null, $fingerprint = null, $fingerprintalg = 'sha1') { if ($xml instanceof DOMDocument) { $dom = clone $xml; } else { if ($xml instanceof DOMElement) { $dom = clone $xml->ownerDocument; } else { $dom = new DOMDocument(); $dom = self::loadXML($dom, $xml); } } # Check if Reference URI is empty try { $signatureElems = $dom->getElementsByTagName('Signature'); foreach ($signatureElems as $signatureElem) { $referenceElems = $dom->getElementsByTagName('Reference'); if (count($referenceElems) > 0) { $referenceElem = $referenceElems->item(0); if ($referenceElem->getAttribute('URI') == '') { $referenceElem->setAttribute('URI', '#' . $signatureElem->parentNode->getAttribute('ID')); } } } } catch (Exception $e) { continue; } $objXMLSecDSig = new XMLSecurityDSig(); $objXMLSecDSig->idKeys = array('ID'); $objDSig = $objXMLSecDSig->locateSignature($dom); if (!$objDSig) { throw new Exception('Cannot locate Signature Node'); } $objKey = $objXMLSecDSig->locateKey(); if (!$objKey) { throw new Exception('We have no idea about the key'); } $objXMLSecDSig->canonicalizeSignedInfo(); try { $retVal = $objXMLSecDSig->validateReference(); } catch (Exception $e) { throw $e; } XMLSecEnc::staticLocateKeyInfo($objKey, $objDSig); if (!empty($cert)) { $objKey->loadKey($cert, false, true); return $objXMLSecDSig->verify($objKey) === 1; } else { $domCert = $objKey->getX509Certificate(); $domCertFingerprint = OneLogin_Saml2_Utils::calculateX509Fingerprint($domCert, $fingerprintalg); if (OneLogin_Saml2_Utils::formatFingerPrint($fingerprint) !== $domCertFingerprint) { return false; } else { $objKey->loadKey($domCert, false, true); return $objXMLSecDSig->verify($objKey) === 1; } } }
public function mPayAttachCertificateInfo($cert, $isPEMFormat = TRUE) { $data = XMLSecurityDSig::get509XCert($cert, $isPEMFormat); $certData = openssl_x509_parse("-----BEGIN CERTIFICATE-----\n" . chunk_split($data, 64, "\n") . "-----END CERTIFICATE-----\n"); $objXMLSecDSig = new XMLSecurityDSig(); if ($objDSig = $objXMLSecDSig->locateSignature($this->soapDoc)) { $this->SOAPXPath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS); $query = "./secdsig:KeyInfo"; $nodeset = $this->SOAPXPath->query($query, $objDSig); $keyInfo = $nodeset->item(0); if (!$keyInfo) { $keyInfo = $objXMLSecDSig->createNewSignNode('KeyInfo'); $objDSig->appendChild($keyInfo); } $tokenRef = $this->soapDoc->createElementNS(WSSESoap::WSSENS, WSSESoap::WSSEPFX . ':SecurityTokenReference'); $keyInfo->appendChild($tokenRef); $xdata = $this->soapDoc->createElementNS(XMLSecurityDSig::XMLDSIGNS, 'ds:X509Data'); $tokenRef->appendChild($xdata); $serial = $this->soapDoc->createElementNS(XMLSecurityDSig::XMLDSIGNS, 'ds:X509IssuerSerial'); $xdata->appendChild($serial); if (!empty($certData['issuer']) && !empty($certData['serialNumber'])) { if (is_array($certData['issuer'])) { $parts = array(); foreach ($certData['issuer'] as $key => $value) { array_unshift($parts, "{$key}={$value}"); } $issuerName = implode(',', $parts); } else { $issuerName = $certData['issuer']; } $issuer_name_x = $this->soapDoc->createElementNS(XMLSecurityDSig::XMLDSIGNS, 'ds:X509IssuerName', $issuerName); $serial->appendChild($issuer_name_x); $serial_number = $this->soapDoc->createElementNS(XMLSecurityDSig::XMLDSIGNS, 'ds:X509SerialNumber', $certData['serialNumber']); $serial->appendChild($serial_number); } } else { throw new Exception('Unable to locate digital signature'); } }
function checkXMLSignature($token) { $objXMLSecDSig = new XMLSecurityDSig(); $objXMLSecDSig->idKeys[] = 'ID'; $objDSig = $objXMLSecDSig->locateSignature($token); /* Must check certificate fingerprint now - validateReference removes it */ if (!validateCertFingerprint($token)) { throw new Exception("Fingerprint Validation Failed"); } /* Canonicalize the signed info */ $objXMLSecDSig->canonicalizeSignedInfo(); $retVal = NULL; if ($objDSig) { $retVal = $objXMLSecDSig->validateReference(); } if (!$retVal) { throw new Exception("SAML Validation Failed"); } $key = NULL; $objKey = $objXMLSecDSig->locateKey(); if ($objKey) { if ($objKeyInfo = XMLSecEnc::staticLocateKeyInfo($objKey, $objDSig)) { /* Handle any additional key processing such as encrypted keys here */ } } if (empty($objKey)) { throw new Exception("Error loading key to handle Signature"); } return $objXMLSecDSig->verify($objKey) == 1; }
/** * @param $testName * @param $testFile * * @dataProvider verifyProvider */ public function testVerify($testName, $testFile) { $doc = new \DOMDocument(); $doc->load($testFile); $objXMLSecDSig = new XMLSecurityDSig(); $objDSig = $objXMLSecDSig->locateSignature($doc); $this->assertInstanceOf('\\DOMElement', $objDSig, "Cannot locate Signature Node"); $objXMLSecDSig->canonicalizeSignedInfo(); $objXMLSecDSig->idKeys = array('wsu:Id'); $objXMLSecDSig->idNS = array('wsu' => 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'); $retVal = $objXMLSecDSig->validateReference(); $this->assertTrue($retVal, "Reference Validation Failed"); $objKey = $objXMLSecDSig->locateKey(); $this->assertInstanceOf('\\XmlSecLibs\\XMLSecurityKey', $objKey, "We have no idea about the key"); $key = null; $objKeyInfo = XMLSecEnc::staticLocateKeyInfo($objKey, $objDSig); if (!$objKeyInfo->key && empty($key)) { $objKey->loadKey(dirname(__FILE__) . '/../mycert.pem', true); } $this->assertEquals(1, $objXMLSecDSig->verify($objKey), "{$testName}: Signature is invalid"); }
<?php define('DS', '\\'); $doc = new DOMDocument(); $doc->load('C:\\Users\\Miha Nahtigal\\Downloads\\Obcina_Trebnje_koledar_eslog (82).xml'); require dirname(dirname(__FILE__)) . DS . 'Plugin' . DS . 'LilInvoices' . DS . 'Lib' . DS . 'xmlseclibs_bes.php'; $objXMLSecDSig = new XMLSecurityDSig(); $objDSig = $objXMLSecDSig->locateSignature($doc); if (!$objDSig) { throw new Exception("Cannot locate Signature Node"); } $objXMLSecDSig->canonicalizeSignedInfo(); //$objXMLSecDSig->idKeys = array('xds:Id'); //$objXMLSecDSig->idNS = array('xds'=>'http://uri.etsi.org/01903/v1.1.1#'); $retVal = $objXMLSecDSig->validateReference(); if (!$retVal) { throw new Exception("Reference Validation Failed"); } $objKey = $objXMLSecDSig->locateKey(); if (!$objKey) { throw new Exception("We have no idea about the key"); } $key = NULL; $objKeyInfo = XMLSecEnc::staticLocateKeyInfo($objKey, $objDSig); if (!$objKeyInfo->key && empty($key)) { $objKey->loadKey(dirname(__FILE__) . '/mycert.pem', TRUE); } if ($objXMLSecDSig->verify($objKey)) { print "Signature validated!"; } else { print "Failure!!!!!!!!";
/** * Validate the SAML Response Signature */ private function _validateSignature() { $dom = $this->_responseXmlDom; $xmlSec = new XMLSecurityDSig(); $signature = $xmlSec->locateSignature($dom); if (!$signature) { throw Sperantus_SAML2_SP_Response_Exception::signatureNotFound(); } $xmlSec->canonicalizeSignedInfo(); $xmlSec->idKeys = array('ID'); if (!$xmlSec->validateReference()) { throw Sperantus_SAML2_SP_Response_Exception::invalidReference(); } $secKey = $xmlSec->locateKey(); if (!$secKey) { throw Sperantus_SAML2_SP_Response_Exception::invalidAlgorithm(); } $objKeyInfo = XMLSecEnc::staticLocateKeyInfo($secKey, $signature); $secKey->loadKey($this->_publicKey); if (!$xmlSec->verify($secKey)) { throw Sperantus_SAML2_SP_Response_Exception::invalidSignature(); } }