public function testEncryption() { $key = Key::factory(Key::AES256_CBC); $cert = Key::factory(Key::RSA_OAEP_MGF1P, $this->fixturesDir . '/mycert.pem', true, Key::TYPE_PUBLIC); $tests = array(array('ref' => false, 'type' => Enc::ELEMENT, 'file' => 'encrypt_document_element.xml', 'desc' => 'Encrypt document with type ELEMENT'), array('ref' => false, 'type' => Enc::CONTENT, 'file' => 'encrypt_document_content.xml', 'desc' => 'Encrypt document with type CONTENT'), array('ref' => true, 'type' => Enc::ELEMENT, 'file' => 'encrypt_document_element_reference.xml', 'desc' => 'Encrypt document with type ELEMENT and key reference'), array('ref' => true, 'type' => Enc::CONTENT, 'file' => 'encrypt_document_content_reference.xml', 'desc' => 'Encrypt document with type CONTENT and key reference')); foreach ($tests as $test) { $doc = new DOMDocument(); $doc->load($this->fixturesDir . '/Enc/encrypt_document.xml'); if ($test['ref']) { $guid = 'EncKey-57cf0489-02e2-45c0-9fcc-fe1a51b53ab2'; // static - normally use DSig::generateUUID() $keyInfo = Enc::createEncryptedKeyReferenceKeyInfo($doc, $guid); $encryptedData = Enc::encryptNode($doc->documentElement, $test['type'], $key, null, $keyInfo); Enc::createEncryptedKey($guid, $key, $cert, $doc->documentElement); } else { $encryptedData = Enc::encryptNode($doc->documentElement, $test['type'], $key); Enc::createEncryptedKey(null, $key, $cert, $encryptedData); } $file = $this->fixturesDir . '/Enc/' . $test['file']; $expected = $this->removeCipherValues(file_get_contents($file)); $actual = $this->removeCipherValues($doc->saveXML()); $this->assertEquals($expected, $actual, $test['desc']); } }
/** * Modify the given request XML. * * @param \BeSimple\SoapCommon\SoapResponse $response SOAP response * * @return void */ public function filterResponse(CommonSoapResponse $response) { // get \DOMDocument from SOAP response $dom = $response->getContentDocument(); // create FilterHelper $filterHelper = new FilterHelper($dom); // add the neccessary namespaces $filterHelper->addNamespace(Helper::PFX_WSS, Helper::NS_WSS); $filterHelper->addNamespace(Helper::PFX_WSU, Helper::NS_WSU); $filterHelper->registerNamespace(XmlSecurityDSig::PFX_XMLDSIG, XmlSecurityDSig::NS_XMLDSIG); // init timestamp $dt = new \DateTime('now', new \DateTimeZone('UTC')); $createdTimestamp = $dt->format(static::DATETIME_FORMAT); // create security header $security = $filterHelper->createElement(Helper::NS_WSS, 'Security'); $filterHelper->addHeaderElement($security, true, $this->actor, $response->getVersion()); if (true === $this->addTimestamp || null !== $this->expires) { $timestamp = $filterHelper->createElement(Helper::NS_WSU, 'Timestamp'); $created = $filterHelper->createElement(Helper::NS_WSU, 'Created', $createdTimestamp); $timestamp->appendChild($created); if (null !== $this->expires) { $dt->modify('+' . $this->expires . ' seconds'); $expiresTimestamp = $dt->format(static::DATETIME_FORMAT); $expires = $filterHelper->createElement(Helper::NS_WSU, 'Expires', $expiresTimestamp); $timestamp->appendChild($expires); } $security->appendChild($timestamp); } if (null !== $this->userSecurityKey && $this->userSecurityKey->hasKeys()) { $guid = 'CertId-' . Helper::generateUUID(); // add token references $keyInfo = null; if (null !== $this->tokenReferenceSignature) { $keyInfo = $this->createKeyInfo($filterHelper, $this->tokenReferenceSignature, $guid, $this->userSecurityKey->getPublicKey()); } $nodes = $this->createNodeListForSigning($dom, $security); $signature = XmlSecurityDSig::createSignature($this->userSecurityKey->getPrivateKey(), XmlSecurityDSig::EXC_C14N, $security, null, $keyInfo); $options = array('id_ns_prefix' => Helper::PFX_WSU, 'id_prefix_ns' => Helper::NS_WSU); foreach ($nodes as $node) { XmlSecurityDSig::addNodeToSignature($signature, $node, XmlSecurityDSig::SHA1, XmlSecurityDSig::EXC_C14N, $options); } XmlSecurityDSig::signDocument($signature, $this->userSecurityKey->getPrivateKey(), XmlSecurityDSig::EXC_C14N); $publicCertificate = $this->userSecurityKey->getPublicKey()->getX509Certificate(true); $binarySecurityToken = $filterHelper->createElement(Helper::NS_WSS, 'BinarySecurityToken', $publicCertificate); $filterHelper->setAttribute($binarySecurityToken, null, 'EncodingType', Helper::NAME_WSS_SMS . '#Base64Binary'); $filterHelper->setAttribute($binarySecurityToken, null, 'ValueType', Helper::NAME_WSS_X509 . '#X509v3'); $filterHelper->setAttribute($binarySecurityToken, Helper::NS_WSU, 'Id', $guid); $security->insertBefore($binarySecurityToken, $signature); // encrypt soap document if (null !== $this->serviceSecurityKey && $this->serviceSecurityKey->hasKeys()) { $guid = 'EncKey-' . Helper::generateUUID(); // add token references $keyInfo = null; if (null !== $this->tokenReferenceEncryption) { $keyInfo = $this->createKeyInfo($filterHelper, $this->tokenReferenceEncryption, $guid, $this->serviceSecurityKey->getPublicKey()); } $encryptedKey = XmlSecurityEnc::createEncryptedKey($guid, $this->serviceSecurityKey->getPrivateKey(), $this->serviceSecurityKey->getPublicKey(), $security, $signature, $keyInfo); $referenceList = XmlSecurityEnc::createReferenceList($encryptedKey); // token reference to encrypted key $keyInfo = $this->createKeyInfo($filterHelper, self::TOKEN_REFERENCE_SECURITY_TOKEN, $guid); $nodes = $this->createNodeListForEncryption($dom); foreach ($nodes as $node) { $type = XmlSecurityEnc::ELEMENT; if ($node->localName == 'Body') { $type = XmlSecurityEnc::CONTENT; } XmlSecurityEnc::encryptNode($node, $type, $this->serviceSecurityKey->getPrivateKey(), $referenceList, $keyInfo); } } } }
/** * Tries to resolve a key from the given \DOMElement. * * @param \DOMElement $node Node where to resolve the key * @param string $algorithm XML security key algorithm * * @return \ass\XmlSecurity\Key|null */ public function keyInfoSecurityTokenReferenceResolver(\DOMElement $node, $algorithm) { foreach ($node->childNodes as $key) { if (Helper::NS_WSS === $key->namespaceURI) { switch ($key->localName) { case 'KeyIdentifier': return $this->serviceSecurityKey->getPublicKey(); case 'Reference': $uri = $key->getAttribute('URI'); $referencedNode = $this->getReferenceNodeForUri($node, $uri); if (XmlSecurityEnc::NS_XMLENC === $referencedNode->namespaceURI && 'EncryptedKey' == $referencedNode->localName) { $key = XmlSecurityEnc::decryptEncryptedKey($referencedNode, $this->userSecurityKey->getPrivateKey()); return XmlSecurityKey::factory($algorithm, $key, false, XmlSecurityKey::TYPE_PRIVATE); } elseif (Helper::NS_WSS === $referencedNode->namespaceURI && 'BinarySecurityToken' == $referencedNode->localName) { $key = XmlSecurityPem::formatKeyInPemFormat($referencedNode->textContent); return XmlSecurityKey::factory(XmlSecurityKey::RSA_SHA1, $key, false, XmlSecurityKey::TYPE_PUBLIC); } } } } return null; }
/** * Gets the security referenced in the given $encryptedData element. * * You can add your own key resolver by calling: * $ns = 'myns'; * $localname = 'MyKeyInfo'; * $keyResolver = array('MyClass' => 'function'); * \ass\XmlSecurity\DSig::addKeyInfoResolver($ns, $localName, $keyResolver); * * @param DOMElement $encryptedData Encrypted data element * @param Key $key Key to decrypt EncryptedKey * * @return Key|null */ public static function getSecurityKey(DOMElement $encryptedData, Key $key = null) { $encryptedMethod = $encryptedData->getElementsByTagNameNS(self::NS_XMLENC, 'EncryptionMethod')->item(0); if (!is_null($encryptedMethod)) { $algorithm = $encryptedMethod->getAttribute('Algorithm'); $keyInfo = $encryptedData->getElementsByTagNameNS(DSig::NS_XMLDSIG, 'KeyInfo')->item(0); if (!is_null($keyInfo)) { if (null !== $key) { $encryptedKey = self::locateEncryptedKey($keyInfo); if (null !== $encryptedKey) { $keyString = Enc::decryptEncryptedKey($encryptedKey, $key); return Key::factory($algorithm, $keyString, false, Key::TYPE_PRIVATE); } else { $class = __CLASS__; $keyResolver = function (DOMElement $node, $algorithm) use($class, $key) { if ($class::RETRIEVAL_METHOD_ENCRYPTED_KEY == $node->getAttribute('Type')) { $uri = $node->getAttribute('URI'); $referencedNode = $class::getReferenceNodeForUri($node, $uri); if (null !== $referencedNode && $class::NS_XMLENC == $referencedNode->namespaceURI && 'EncryptedKey' == $referencedNode->localName) { $keyString = $class::decryptEncryptedKey($referencedNode, $key); return Key::factory($algorithm, $keyString, false, Key::TYPE_PRIVATE); } } return null; }; DSig::addKeyInfoResolver(DSig::NS_XMLDSIG, 'RetrievalMethod', $keyResolver); } } return DSig::getSecurityKeyFromKeyInfo($keyInfo, $algorithm); } } return null; }
/** * Modify the given request XML. * * @param \BeSimple\SoapCommon\SoapResponse $response SOAP response * * @return void */ public function filterResponse(CommonSoapResponse $response) { // get \DOMDocument from SOAP response $dom = $response->getContentDocument(); // locate security header $security = $dom->getElementsByTagNameNS(Helper::NS_WSS, 'Security')->item(0); if (null !== $security) { // add SecurityTokenReference resolver for KeyInfo $keyResolver = array($this, 'keyInfoSecurityTokenReferenceResolver'); XmlSecurityDSig::addKeyInfoResolver(Helper::NS_WSS, 'SecurityTokenReference', $keyResolver); // do we have a reference list in header $referenceList = XmlSecurityEnc::locateReferenceList($security); // get a list of encrypted nodes $encryptedNodes = XmlSecurityEnc::locateEncryptedData($dom, $referenceList); // decrypt them if (null !== $encryptedNodes) { foreach ($encryptedNodes as $encryptedNode) { XmlSecurityEnc::decryptNode($encryptedNode); } } // locate signature node $signature = XmlSecurityDSig::locateSignature($security); if (null !== $signature) { // verify references $options = array('id_ns_prefix' => Helper::PFX_WSU, 'id_prefix_ns' => Helper::NS_WSU); if (XmlSecurityDSig::verifyReferences($signature, $options) !== true) { throw new \SoapFault('wsse:FailedCheck', 'The signature or decryption was invalid'); } // verify signature if (XmlSecurityDSig::verifyDocumentSignature($signature) !== true) { throw new \SoapFault('wsse:FailedCheck', 'The signature or decryption was invalid'); } } $security->parentNode->removeChild($security); } }