function __doRequest($request, $location, $saction, $version) { $dom = new DOMDocument(); $dom->loadXML($request); $objWSSE = new WSSESoap($dom); /* Sign all headers to include signing the WS-Addressing headers */ $objWSSE->signAllHeaders = TRUE; $objWSSE->addTimestamp(); /* create new XMLSec Key using RSA SHA-1 and type is private key */ $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'private')); /* load the private key from file - last arg is bool if key in file (TRUE) or is string (FALSE) */ $objKey->loadKey(PRIVATE_KEY, TRUE); // Sign the message - also signs appropraite WS-Security items $objWSSE->signSoapDoc($objKey); /* Add certificate (BinarySecurityToken) to the message and attach pointer to Signature */ $token = $objWSSE->addBinaryToken(file_get_contents(CERT_FILE)); $objWSSE->attachTokentoSig($token); $request = $objWSSE->saveXML(); $dom = new DOMDocument(); $dom->loadXML($request); $objWSA = new WSASoap($dom); $objWSA->addAction($saction); $objWSA->addTo($location); $objWSA->addMessageID(); $objWSA->addReplyTo(); $request = $objWSA->getDoc()->saveXML(); return parent::__doRequest($request, $location, $saction, $version); }
public static function setUpBeforeClass() { $cert = "-----BEGIN CERTIFICATE-----\n" . "MIIDfjCCAmagAwIBAQICJxAwDQYJKoZIhvcNAQEFBQAwgYExCzAJBgNVBAYTAlVT\r\n" . "MRIwEAYDVQQIEwlMYXMgVmVnYXMxEjAQBgNVBAcTCUxhcyBWZWdhczEYMBYGA1UE\r\n" . "ChMPTGF1bmNoS2V5LCBJbmMuMRgwFgYDVQQLEw9MYXVuY2hLZXksIEluYy4xFjAU\r\n" . "BgNVBAMTDWxhdW5jaGtleS5jb20wHhcNMTUxMTAyMjMyNzQ5WhcNMTYxMTAxMjMy\r\n" . "NzQ5WjCBgTELMAkGA1UEBhMCVVMxEjAQBgNVBAgTCUxhcyBWZWdhczESMBAGA1UE\r\n" . "BxMJTGFzIFZlZ2FzMRgwFgYDVQQKEw9MYXVuY2hLZXksIEluYy4xGDAWBgNVBAsT\r\n" . "D0xhdW5jaEtleSwgSW5jLjEWMBQGA1UEAxMNbGF1bmNoa2V5LmNvbTCCASIwDQYJ\r\n" . "KoZIhvcNAQEBBQADggEPADCCAQoCggEBAN1Q3Og6izyf35UaeivS88Wlzjdz2yPm\r\n" . "juOge/awYJa8V2dED0oCjdAxex9Ak8lEE9naD6ZcuA0Kta5mHKk1ho5Z4aq1493w\r\n" . "HFbPbzVFldBAzFqig7m5/k1B/QY8w7CP1QG5aM9ebQeCJwdhz7UBmNQL2r2K02zn\r\n" . "2DFhEuus1YKM+pfSO2I+yTd/AyBtq4zu+LusibNoU9ADKQ3IoJtzyZ+CUuuOG3jz\r\n" . "Z+zwuzH/0hpuTs6TnBSAGYD1Xow2X7lULLzXwZ4R3SopTesncIbXLa2luTLQIody\r\n" . "uA/gSirbW7g02zQ8G3JcO+ce6UnusklzvdBPoJ2vttpDEsWlNqbSTWcCAwEAATAN\r\n" . "BgkqhkiG9w0BAQUFAAOCAQEARz9V7cBG2et/741mdtbspQTN4HF0hUp3NEJzBrP/\r\n" . "YtdMYIVAUh2sc3sf/oiakLgqYBA78rSk9CbNlv4EJ/FEC/5X3l1o9h5dFLXt40LL\r\n" . "4I+ijYY3BlsgRL9K2CNYRCq1bJX8xlcY0hVqqsZipzR4zeyqQVMLXH/zSScTrF5j\r\n" . "b5KQcYFiRP7AF30OtGoZxhnsDUcErhdWY5lGvaSex6LsOC2UGtmwK3FWu+NMDzL0\r\n" . "+ovdBGpsmDp3IN1AKwd9/6EQ3XbQPyXoXpW0TCBzs/OxGqnhiJD9rROCtVl1SJze\r\n" . "LWllWSmosQFhsXwSO5ZlnechO+SMaxN7OrV7POOv8aRcpQ==\r\n" . "-----END CERTIFICATE-----\n"; static::$key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public')); static::$key->loadKey($cert, false, true); static::$response_data = "PG5zMDpSZXNwb25zZSB4bWxuczpuczA9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpwcm90b2Nv" . "bCIgeG1sbnM6bnMxPSJ1cm46b2FzaX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ZW50aWNhdGluZ0F1dGhv" . "cml0eT5odHRwczovL3NhbWwubGF1bmNoa2V5LmNvbS9pZHAueG1sPC9uczE6QXV0aGVudGljYXRpbmd" . "BdXRob3JpdHk+PC9uczE6QXV0aG5Db250ZXh0PjwvbnMxOkF1dGhuU3RhdGVtZW50PjxuczE6QXR0cm" . "lidXRlU3RhdGVtZW50PjxuczE6QXR0cmlidXRlIE5hbWU9ImFrZXkiIE5hbWVGb3JtYXQ9InVybjpvY" . "XNpczpuYW1lczp0YzpTQU1MOjIuMDphdHRybmFtZS1mb3JtYXQ6dXJpIj48bnMxOkF0dHJpYnV0ZVZh" . "bHVlIHhzaTp0eXBlPSJ4czpzdHJpbmciPmF2YWx1ZTwvbnMxOkF0dHJpYnV0ZVZhbHVlPjwvbnMxOkF" . "0dHJpYnV0ZT48L25zMTpBdHRyaWJ1dGVTdGF0ZW1lbnQ+PC9uczE6QXNzZXJ0aW9uPjwvbnMwOlJlc3" . "BvbnNlPg=="; }
public static function setUpBeforeClass() { $cert = "-----BEGIN CERTIFICATE-----\n" . "MIIDfjCCAmagAwIBAQICJxAwDQYJKoZIhvcNAQEFBQAwgYExCzAJBgNVBAYTAlVT\r\n" . "MRIwEAYDVQQIEwlMYXMgVmVnYXMxEjAQBgNVBAcTCUxhcyBWZWdhczEYMBYGA1UE\r\n" . "ChMPTGF1bmNoS2V5LCBJbmMuMRgwFgYDVQQLEw9MYXVuY2hLZXksIEluYy4xFjAU\r\n" . "BgNVBAMTDWxhdW5jaGtleS5jb20wHhcNMTUxMTAyMjMyNzQ5WhcNMTYxMTAxMjMy\r\n" . "NzQ5WjCBgTELMAkGA1UEBhMCVVMxEjAQBgNVBAgTCUxhcyBWZWdhczESMBAGA1UE\r\n" . "BxMJTGFzIFZlZ2FzMRgwFgYDVQQKEw9MYXVuY2hLZXksIEluYy4xGDAWBgNVBAsT\r\n" . "D0xhdW5jaEtleSwgSW5jLjEWMBQGA1UEAxMNbGF1bmNoa2V5LmNvbTCCASIwDQYJ\r\n" . "KoZIhvcNAQEBBQADggEPADCCAQoCggEBAN1Q3Og6izyf35UaeivS88Wlzjdz2yPm\r\n" . "juOge/awYJa8V2dED0oCjdAxex9Ak8lEE9naD6ZcuA0Kta5mHKk1ho5Z4aq1493w\r\n" . "HFbPbzVFldBAzFqig7m5/k1B/QY8w7CP1QG5aM9ebQeCJwdhz7UBmNQL2r2K02zn\r\n" . "2DFhEuus1YKM+pfSO2I+yTd/AyBtq4zu+LusibNoU9ADKQ3IoJtzyZ+CUuuOG3jz\r\n" . "Z+zwuzH/0hpuTs6TnBSAGYD1Xow2X7lULLzXwZ4R3SopTesncIbXLa2luTLQIody\r\n" . "uA/gSirbW7g02zQ8G3JcO+ce6UnusklzvdBPoJ2vttpDEsWlNqbSTWcCAwEAATAN\r\n" . "BgkqhkiG9w0BAQUFAAOCAQEARz9V7cBG2et/741mdtbspQTN4HF0hUp3NEJzBrP/\r\n" . "YtdMYIVAUh2sc3sf/oiakLgqYBA78rSk9CbNlv4EJ/FEC/5X3l1o9h5dFLXt40LL\r\n" . "4I+ijYY3BlsgRL9K2CNYRCq1bJX8xlcY0hVqqsZipzR4zeyqQVMLXH/zSScTrF5j\r\n" . "b5KQcYFiRP7AF30OtGoZxhnsDUcErhdWY5lGvaSex6LsOC2UGtmwK3FWu+NMDzL0\r\n" . "+ovdBGpsmDp3IN1AKwd9/6EQ3XbQPyXoXpW0TCBzs/OxGqnhiJD9rROCtVl1SJze\r\n" . "LWllWSmosQFhsXwSO5ZlnechO+SMaxN7OrV7POOv8aRcpQ==\r\n" . "-----END CERTIFICATE-----\n"; static::$key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public')); static::$key->loadKey($cert, false, true); static::$request_data = "PG5zMDpMb2dvdXRSZXF1ZXN0IHhtbG5zOm5zMD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOnByb3R" . "vY29sIiB4bWxuczpuczE9InVybjpvYXNpczpuYW1lczp0YzpTQU1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zQxbWR0YnNwUVRONEhGMGhVcDNORUp6QnJQL1l0ZE1ZSVZBVWgyc2Mzc" . "2Yvb2lha0xncVlCQTc4clNrOUNiTmx2NEVKL0ZFQy81WDNsMW85aDVkRkxYdDQwTEw0SStpallZM0Jsc2dS" . "TDlLMkNOWVJDcTFiSlg4eGxjWTBoVnFxc1ppcHpSNHpleXFRVk1MWEgvelNTY1RyRjVqYjVLUWNZRmlSUDd" . "BRjMwT3RHb1p4aG5zRFVjRXJoZFdZNWxHdmFTZXg2THNPQzJVR3Rtd0szRld1K05NRHpMMCtvdmRCR3BzbU" . "RwM0lOMUFLd2Q5LzZFUTNYYlFQeVhvWHBXMFRDQnpzL094R3FuaGlKRDlyUk9DdFZsMVNKemVMV2xsV1Ntb" . "3NRRmhzWHdTTzVabG5lY2hPK1NNYXhON09yVjdQT092OGFSY3BRPT08L25zMjpYNTA5Q2VydGlmaWNhdGU+" . "PC9uczI6WDUwOURhdGE+PC9uczI6S2V5SW5mbz48L25zMjpTaWduYXR1cmU+PG5zMTpOYW1lSUQ+dGVzdGV" . "tYWlsQHRlc3RtZS5vcmc8L25zMTpOYW1lSUQ+PG5zMDpTZXNzaW9uSW5kZXg+aWQtMDcyNjAyMjVmZTdkMW" . "UyZWU4Zjg4Njg0NmNjNDBhZmE8L25zMDpTZXNzaW9uSW5kZXg+PC9uczA6TG9nb3V0UmVxdWVzdD4="; }
/** * BC compatible version of the signature check * * @param SAML2_SignedElement $element * @param SAML2_Certificate_X509[] $pemCandidates * * @throws Exception * * @return bool */ protected function validateElementWithKeys(SAML2_SignedElement $element, $pemCandidates) { $lastException = NULL; foreach ($pemCandidates as $index => $candidateKey) { $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public')); $key->loadKey($candidateKey->getCertificate()); try { /* * Make sure that we have a valid signature on either the response or the assertion. */ $result = $element->validate($key); if ($result) { $this->logger->debug(sprintf('Validation with key "#%d" succeeded', $index)); return TRUE; } $this->logger->debug(sprintf('Validation with key "#%d" failed without exception.', $index)); } catch (Exception $e) { $this->logger->debug(sprintf('Validation with key "#%d" failed with exception: %s', $index, $e->getMessage())); $lastException = $e; } } if ($lastException !== NULL) { throw $lastException; } else { return FALSE; } }
function processDocument() { global $src_file, $target_file, $user_pubkey_file_path, $user_cert_file_path; require dirname(__FILE__) . '/xmlseclibs.php'; if (file_exists($target_file)) { unlink($target_file); } $doc = new DOMDocument(); $doc->load($src_file); $objDSig = new XMLSecurityDSig(); $objDSig->setCanonicalMethod(XMLSecurityDSig::EXC_C14N); $objDSig->addReference($doc, XMLSecurityDSig::SHA1, array('http://www.w3.org/2000/09/xmldsig#enveloped-signature')); /* gako pribatu bat behar dugu prozesua burutzeko. orain edozein erabiliko dugu. gero txartelekoarekin ordezkatzeko */ $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'private')); /* if key has Passphrase, set it using $objKey->passphrase = <passphrase> " */ $objKey->loadKey(dirname(__FILE__) . '/privkey.pem', TRUE); $objDSig->sign($objKey); /* Add associated public key */ // $objDSig->add509Cert(file_get_contents(dirname(__FILE__) . '/mycert.pem')); // $objDSig->add509Cert(file_get_contents($user_cert_file_path)); if (!file_exists($user_cert_file_path)) { debug('File not found', $user_cert_file_path); } else { $objDSig->add509Cert($user_cert_file_path); } $objDSig->appendSignature($doc->documentElement); $doc->save($target_file); }
protected function createLogoutResponse($testrun, $logoutRequest, $logoutRelayState) { $this->log($testrun, 'Creating response with relaystate [' . $logoutRelayState . ']'); $idpMetadata = SimpleSAML_Configuration::loadFromArray($this->idpmetadata); $spMetadata = SimpleSAML_Configuration::loadFromArray($this->metadata); // Get SingleLogoutService URL $consumerURLf = $spMetadata->getDefaultEndpoint('SingleLogoutService', array('urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect')); $consumerURL = $consumerURLf['Location']; /* Create an send response. */ $response = sspmod_saml2_Message::buildLogoutResponse($idpMetadata, $spMetadata); $response->setRelayState($logoutRequest->getRelayState()); $response->setInResponseTo($logoutRequest->getId()); $keyArray = SimpleSAML_Utilities::loadPrivateKey($idpMetadata, TRUE); $certArray = SimpleSAML_Utilities::loadPublicKey($idpMetadata, FALSE); $privateKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'private')); $privateKey->loadKey($keyArray['PEM'], FALSE); $response->setSignatureKey($privateKey); if ($certArray === NULL) { throw new Exception('No certificates found. [1]'); } if (!array_key_exists('PEM', $certArray)) { throw new Exception('No certificates found. [2]'); } $response->setCertificates(array($certArray['PEM'])); #$this->tweakResponse($testrun, $response); $msgStr = $response->toUnsignedXML(); #$this->tweakResponseDOM($testrun, $msgStr); $msgStr = $msgStr->ownerDocument->saveXML($msgStr); # echo '<pre>'; echo(htmlspecialchars($msgStr)); exit; # $msgStr = base64_encode($msgStr); # $msgStr = htmlspecialchars($msgStr); return array('url' => $consumerURL, 'Response' => $msgStr, 'ResponseObj' => $response, 'RelayState' => $logoutRelayState); }
public function __doRequest($request, $location, $saction, $version) { $doc = new DOMDocument('1.0'); $doc->loadXML($request); $objWSSE = new WSSESoap($doc); /* add Timestamp with no expiration timestamp */ $objWSSE->addTimestamp(); /* create new XMLSec Key using AES256_CBC and type is private key */ $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'private')); /* load the private key from file - last arg is bool if key in file (true) or is string (false) */ $objKey->loadKey(PRIVATE_KEY, true); /* Sign the message - also signs appropiate WS-Security items */ $options = array("insertBefore" => false); $objWSSE->signSoapDoc($objKey, $options); /* Add certificate (BinarySecurityToken) to the message */ $token = $objWSSE->addBinaryToken(file_get_contents(CERT_FILE)); /* Attach pointer to Signature */ $objWSSE->attachTokentoSig($token); $objKey = new XMLSecurityKey(XMLSecurityKey::AES256_CBC); $objKey->generateSessionKey(); $siteKey = new XMLSecurityKey(XMLSecurityKey::RSA_OAEP_MGF1P, array('type' => 'public')); $siteKey->loadKey(SERVICE_CERT, true, true); $options = array("KeyInfo" => array("X509SubjectKeyIdentifier" => true)); $objWSSE->encryptSoapDoc($siteKey, $objKey, $options); $retVal = parent::__doRequest($objWSSE->saveXML(), $location, $saction, $version); $doc = new DOMDocument(); $doc->loadXML($retVal); $options = array("keys" => array("private" => array("key" => PRIVATE_KEY, "isFile" => true, "isCert" => false))); $objWSSE->decryptSoapDoc($doc, $options); return $doc->saveXML(); }
public function testThumbPrint() { $siteKey = new XMLSecurityKey(XMLSecurityKey::RSA_OAEP_MGF1P, array('type' => 'public')); $siteKey->loadKey(dirname(__FILE__) . '/../mycert.pem', true, true); $thumbprint = $siteKey->getX509Thumbprint(); $this->assertEquals('8b600d9155e8e8dfa3c10998f736be086e83ef3b', $thumbprint, "Thumbprint doesn't match"); $this->assertEquals('OGI2MDBkOTE1NWU4ZThkZmEzYzEwOTk4ZjczNmJlMDg2ZTgzZWYzYg==', base64_encode($thumbprint), "Base64 Thumbprint doesn't match"); }
/** * @param SAML2_Certificate_PrivateKey $privateKey * * @return XMLSecurityKey * @throws Exception */ private function convertPrivateKeyToRsaKey(SAML2_Certificate_PrivateKey $privateKey) { $key = new XMLSecurityKey(XMLSecurityKey::RSA_1_5, array('type' => 'private')); $passphrase = $privateKey->getPassphrase(); if ($passphrase) { $key->passphrase = $passphrase; } $key->loadKey($privateKey->getKeyAsString()); return $key; }
function __doRequest($request, $location, $saction, $version) { $doc = new DOMDocument('1.0'); $doc->loadXML($request); $objWSSE = new WSSESoap($doc); $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'private')); $objKey->loadKey(PRIVATE_KEY, TRUE); $options = array("insertBefore" => TRUE); $objWSSE->signSoapDoc($objKey, $options); $objWSSE->addIssuerSerial(CERT_FILE); $objKey = new XMLSecurityKey(XMLSecurityKey::AES256_CBC); $objKey->generateSessionKey(); #está wea está rara, no pasa el wsdl y cambía el puerto o.O $location = "https://201.238.207.130:7200/WSWebpayTransaction/cxf/WSWebpayService?wsdl"; #die($location); #die(CERT_FILE." ".PRIVATE_KEY); $retVal = parent::__doRequest($objWSSE->saveXML(), $location, $saction, $version); $doc = new DOMDocument(); $doc->loadXML($retVal); return $doc->saveXML(); /* if ($this->useSSL){ $locationparts = parse_url($location); $location = 'https://'; if(isset($locationparts['host'])) $location .= $locationparts['host']; if(isset($locationparts['port'])) $location .= ':'.$locationparts['port']; if(isset($locationparts['path'])) $location .= $locationparts['path']; if(isset($locationparts['query'])) $location .= '?'.$locationparts['query']; } $doc = new DOMDocument('1.0'); $doc->loadXML($request); $objWSSE = new WSSESoap($doc); $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1,array('type' => 'private')); $objKey->loadKey(PRIVATE_KEY, TRUE); $options = array("insertBefore" => TRUE); $objWSSE->signSoapDoc($objKey, $options); $objWSSE->addIssuerSerial(CERT_FILE); $objKey = new XMLSecurityKey(XMLSecurityKey::AES256_CBC); $objKey->generateSessionKey(); $retVal = parent::__doRequest($objWSSE->saveXML(), $location, $saction, $version); $doc = new DOMDocument(); $doc->loadXML($retVal); return $doc->saveXML(); */ }
/** * @return \AerialShip\LightSaml\Model\Protocol\AuthnRequest */ protected function getRequest() { $request = CommonHelper::buildAuthnRequestFromEntityDescriptors(__DIR__ . '/../../../../../resources/sample/EntityDescriptor/sp-ed2.xml', __DIR__ . '/../../../../../resources/sample/EntityDescriptor/idp2-ed.xml'); $certificate = new X509Certificate(); $certificate->loadFromFile(__DIR__ . '/../../../../../resources/sample/Certificate/saml.crt'); $key = new \XMLSecurityKey(\XMLSecurityKey::RSA_SHA1, array('type' => 'private')); $key->loadKey(__DIR__ . '/../../../../../resources/sample/Certificate/saml.pem', true, false); $signature = new SignatureCreator(); $signature->setCertificate($certificate); $signature->setXmlSecurityKey($key); $request->setSignature($signature); $request->setRelayState($this->relayState); return $request; }
function signXML($token, $privkey) { $sigdoc = new DOMDocument(); if (!$sigdoc->loadXML($token)) { throw new Exception("Invalid XML!"); } $sigNode = $sigdoc->firstChild; $enc = new XMLSecurityDSig(); $enc->idKeys[] = 'ID'; $enc->setCanonicalMethod(XMLSecurityDSig::EXC_C14N); $enc->addReference($sigNode, XMLSecurityDSig::SHA1, array('http://www.w3.org/2000/09/xmldsig#enveloped-signature', XMLSecurityDSig::EXC_C14N)); $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'private', 'library' => 'openssl')); $key->loadKey($privkey, false, false); $enc->sign($key); $enc->appendSignature($sigNode); return $sigdoc->saveXML(); }
/** * @dataProvider provider */ public function testAuthnRequestBuilder($name, array $idpData, array $spData, array $spMetaData, $expectedSendUrl, $expectedResponseType, $expectedReceiveUrl, $expectedReceiveBinding, $expectedException = null, $expectedExceptionMessage = '') { if ($expectedException) { $this->setExpectedException($expectedException, $expectedExceptionMessage); } $idp = new IdpSsoDescriptor(); foreach ($idpData as $data) { $idp->addService(new SingleSignOnService($data['binding'], $data['url'])); } $edIDP = new EntityDescriptor('idp'); $edIDP->addItem($idp); $sp = new SpSsoDescriptor(); foreach ($spData as $data) { $sp->addService(new AssertionConsumerService($data['binding'], $data['url'])); } $edSP = new EntityDescriptor('sp'); $edSP->addItem($sp); $spMeta = new SpMeta(); foreach ($spMetaData as $name => $value) { $spMeta->{$name}($value); } // without signing $builder = new AuthnRequestBuilder($edSP, $edIDP, $spMeta); $message = $builder->build(); $response = $builder->send($message); $this->assertStringStartsWith($expectedSendUrl, $response->getDestination(), $name); $this->assertInstanceOf($expectedResponseType, $response, $name); $this->assertEquals($expectedReceiveUrl, $message->getAssertionConsumerServiceURL(), $name); $this->assertEquals($expectedReceiveBinding, $message->getProtocolBinding(), $name); // with signing $signature = new SignatureCreator(); $certificate = new X509Certificate(); $certificate->loadFromFile(__DIR__ . '/../../../../../resources/sample/Certificate/saml.crt'); $key = new \XMLSecurityKey(\XMLSecurityKey::RSA_SHA1, array('type' => 'private')); $key->loadKey(__DIR__ . '/../../../../../resources/sample/Certificate/saml.pem', true); $signature->setCertificate($certificate); $signature->setXmlSecurityKey($key); $builder = new AuthnRequestBuilder($edSP, $edIDP, $spMeta, $signature); $message = $builder->build(); $response = $builder->send($message); $this->assertStringStartsWith($expectedSendUrl, $response->getDestination(), $name); $this->assertInstanceOf($expectedResponseType, $response, $name); $this->assertEquals($expectedReceiveUrl, $message->getAssertionConsumerServiceURL(), $name); $this->assertEquals($expectedReceiveBinding, $message->getProtocolBinding(), $name); }
public function __doRequest($request, $location, $saction, $version) { $doc = new DOMDocument('1.0'); $doc->loadXML($request); $objWSSE = new WSSESoap($doc); /* add Timestamp with no expiration timestamp */ $objWSSE->addTimestamp(); /* create new XMLSec Key using RSA SHA-1 and type is private key */ $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'private')); /* load the private key from file - last arg is bool if key in file (true) or is string (FALSE) */ $objKey->loadKey(PRIVATE_KEY, true); /* Sign the message - also signs appropraite WS-Security items */ $objWSSE->signSoapDoc($objKey); /* Add certificate (BinarySecurityToken) to the message and attach pointer to Signature */ $token = $objWSSE->addBinaryToken(file_get_contents(CERT_FILE)); $objWSSE->attachTokentoSig($token); return parent::__doRequest($objWSSE->saveXML(), $location, $saction, $version); }
/** * @param \XMLSecurityKey $key * @param string $algorithm * @throws \AerialShip\LightSaml\Error\SecurityException * @throws \InvalidArgumentException * @return \XMLSecurityKey */ static function castKey(\XMLSecurityKey $key, $algorithm) { if (!is_string($algorithm)) { throw new \InvalidArgumentException('Algorithm must be string'); } // do nothing if algorithm is already the type of the key if ($key->type === $algorithm) { return $key; } $keyInfo = openssl_pkey_get_details($key->key); if ($keyInfo === FALSE) { throw new SecurityException('Unable to get key details from XMLSecurityKey.'); } if (!isset($keyInfo['key'])) { throw new SecurityException('Missing key in public key details.'); } $newKey = new \XMLSecurityKey($algorithm, array('type' => 'public')); $newKey->loadKey($keyInfo['key']); return $newKey; }
function __doRequest($request, $location, $saction, $version) { $doc = new DOMDocument('1.0'); $doc->loadXML($request); $objWSSE = new WSSESoap($doc); #echo "<pre>"; var_dump($request); #die(); /* add Timestamp with no expiration timestamp */ $objWSSE->addTimestamp(); /* create new XMLSec Key using RSA SHA-1 and type is private key */ $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type'=>'private')); /* load the private key from file - last arg is bool if key in file (TRUE) or is string (FALSE) */ $objKey->loadKey($this->KeyPath, TRUE); try { /* Sign the message - also signs appropraite WS-Security items */ $objWSSE->signSoapDoc($objKey); } catch (Exception $e) { Core::RaiseError("[".__METHOD__."] ".$e->getMessage(), E_ERROR); } /* Add certificate (BinarySecurityToken) to the message and attach pointer to Signature */ $token = $objWSSE->addBinaryToken(file_get_contents($this->CertPath)); $objWSSE->attachTokentoSig($token); try { return parent::__doRequest($objWSSE->saveXML(), $location, $saction, $version); } catch (Exception $e) { Core::RaiseError("[".__METHOD__."] ".$e->__toString(), E_ERROR); } }
private function getSignedXml() { $doc = new \DOMDocument(); $doc->appendChild($doc->createElement('root')); /** @var $root \DOMElement */ $root = $doc->firstChild; $root->setAttribute('foo', 'bar'); $other = $doc->createElement('other'); $root->appendChild($other); $child = $doc->createElement('child', 'something'); $other->appendChild($child); $certificate = new X509Certificate(); $certificate->loadFromFile(__DIR__ . '/../../../../../../../resources/sample/Certificate/saml.crt'); $key = new \XMLSecurityKey(\XMLSecurityKey::RSA_SHA1, array('type' => 'private')); $key->loadKey(__DIR__ . '/../../../../../../../resources/sample/Certificate/saml.pem', true); $signatureCreator = new SignatureCreator(); $signatureCreator->setCertificate($certificate); $signatureCreator->setXmlSecurityKey($key); $context = new SerializationContext($doc); $signatureCreator->getXml($root, $context); $xml = $doc->saveXML(); return $xml; }
/** * 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; } }
/** * If this EntityDescriptor was signed this function use the public key to check the signature. * * @param array $certificates One ore more certificates with the public key. This makes it possible * to do a key rollover. * * @return boolean True if it is possible to check the signature with the certificate, false otherwise. * @throws Exception If the certificate file cannot be found. */ public function validateSignature($certificates) { foreach ($certificates as $cert) { assert('is_string($cert)'); $certFile = \SimpleSAML\Utils\Config::getCertPath($cert); if (!file_exists($certFile)) { throw new Exception('Could not find certificate file [' . $certFile . '], which is needed to validate signature'); } $certData = file_get_contents($certFile); foreach ($this->validators as $validator) { $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public')); $key->loadKey($certData); try { if ($validator->validate($key)) { return true; } } catch (Exception $e) { // this certificate did not sign this element, skip } } } SimpleSAML_Logger::debug('Could not validate signature'); return false; }
/** * Tests the decryptElement method of the OneLogin_Saml2_Utils * * @covers OneLogin_Saml2_Utils::decryptElement */ public function testDecryptElement() { $settingsDir = TEST_ROOT . '/settings/'; include $settingsDir . 'settings1.php'; $settings = new OneLogin_Saml2_Settings($settingsInfo); $key = $settings->getSPkey(); $seckey = new XMLSecurityKey(XMLSecurityKey::RSA_1_5, array('type' => 'private')); $seckey->loadKey($key); $xmlNameIdEnc = base64_decode(file_get_contents(TEST_ROOT . '/data/responses/response_encrypted_nameid.xml.base64')); $domNameIdEnc = new DOMDocument(); $domNameIdEnc->loadXML($xmlNameIdEnc); $encryptedNameIDNodes = $domNameIdEnc->getElementsByTagName('EncryptedID'); $encryptedData = $encryptedNameIDNodes->item(0)->firstChild; $decryptedNameId = OneLogin_Saml2_Utils::decryptElement($encryptedData, $seckey); $this->assertEquals('saml:NameID', $decryptedNameId->tagName); $this->assertEquals('2de11defd199f8d5bb63f9b7deb265ba5c675c10', $decryptedNameId->nodeValue); $xmlAsssertionEnc = base64_decode(file_get_contents(TEST_ROOT . '/data/responses/valid_encrypted_assertion.xml.base64')); $domAsssertionEnc = new DOMDocument(); $domAsssertionEnc->loadXML($xmlAsssertionEnc); $encryptedAssertionEncNodes = $domAsssertionEnc->getElementsByTagName('EncryptedAssertion'); $encryptedAssertionEncNode = $encryptedAssertionEncNodes->item(0); $encryptedDataAssertNodes = $encryptedAssertionEncNode->getElementsByTagName('EncryptedData'); $encryptedDataAssert = $encryptedDataAssertNodes->item(0); $decryptedAssertion = OneLogin_Saml2_Utils::decryptElement($encryptedDataAssert, $seckey); $this->assertEquals('saml:Assertion', $decryptedAssertion->tagName); try { $res = OneLogin_Saml2_Utils::decryptElement($encryptedNameIDNodes->item(0), $seckey); $this->assertTrue(false); } catch (Exception $e) { $this->assertContains('Algorithm mismatch between input key and key in message', $e->getMessage()); } $key2 = file_get_contents(TEST_ROOT . '/data/misc/sp2.key'); $seckey2 = new XMLSecurityKey(XMLSecurityKey::RSA_1_5, array('type' => 'private')); $seckey2->loadKey($key2); $decryptedNameId2 = OneLogin_Saml2_Utils::decryptElement($encryptedData, $seckey2); $this->assertEquals('saml:NameID', $decryptedNameId2->tagName); $this->assertEquals('2de11defd199f8d5bb63f9b7deb265ba5c675c10', $decryptedNameId2->nodeValue); $key3 = file_get_contents(TEST_ROOT . '/data/misc/sp2.key'); $seckey3 = new XMLSecurityKey(XMLSecurityKey::RSA_SHA512, array('type' => 'private')); $seckey3->loadKey($key3); try { $res = OneLogin_Saml2_Utils::decryptElement($encryptedData, $seckey3); $this->assertTrue(false); } catch (Exception $e) { $this->assertContains('Algorithm mismatch between input key and key used to encrypt the symmetric key for the message', $e->getMessage()); } $xmlNameIdEnc2 = base64_decode(file_get_contents(TEST_ROOT . '/data/responses/invalids/encrypted_nameID_without_EncMethod.xml.base64')); $domNameIdEnc2 = new DOMDocument(); $domNameIdEnc2->loadXML($xmlNameIdEnc2); $encryptedNameIDNodes2 = $domNameIdEnc2->getElementsByTagName('EncryptedID'); $encryptedData2 = $encryptedNameIDNodes2->item(0)->firstChild; try { $res = OneLogin_Saml2_Utils::decryptElement($encryptedData2, $seckey); $this->assertTrue(false); } catch (Exception $e) { $this->assertContains('Unable to locate algorithm for this Encrypted Key', $e->getMessage()); } $xmlNameIdEnc3 = base64_decode(file_get_contents(TEST_ROOT . '/data/responses/invalids/encrypted_nameID_without_keyinfo.xml.base64')); $domNameIdEnc3 = new DOMDocument(); $domNameIdEnc3->loadXML($xmlNameIdEnc3); $encryptedNameIDNodes3 = $domNameIdEnc3->getElementsByTagName('EncryptedID'); $encryptedData3 = $encryptedNameIDNodes3->item(0)->firstChild; try { $res = OneLogin_Saml2_Utils::decryptElement($encryptedData3, $seckey); $this->assertTrue(false); } catch (Exception $e) { $this->assertContains('Algorithm mismatch between input key and key in message', $e->getMessage()); } }
/** * Initialize LaunchKey WordPress Plugin * * This function will perform the entire initialization for the plugin. The initialization is encapsulated into * a funciton to protect against global variable collision. * * @since 1.0.0 * Enclose plug-in initialization to protect against global variable corruption */ function launchkey_plugin_init() { global $wpdb; /** * Register activation hooks for the plugin * @since 1.1.0 */ register_activation_hook(__FILE__, 'launchkey_create_tables'); /** * Remove the scheduled cron * @since 1.1.0 */ register_deactivation_hook(__FILE__, 'launchkey_cron_remove'); /** * @since 1.1.0 * Add the cron hook and schedule if not scheduled */ add_action('launchkey_cron_hook', 'launchkey_cron'); if (!wp_next_scheduled('launchkey_cron_hook')) { wp_schedule_event(time(), 'hourly', 'launchkey_cron_hook'); } /** * Language domain for the plugin */ $language_domain = 'launchkey'; /** * Register plugin text domain with language files * * @see load_plugin_textdomain * @link https://developer.wordpress.org/reference/hooks/plugins_loaded/ */ add_action('plugins_loaded', function () use($language_domain) { load_plugin_textdomain($language_domain, false, plugin_basename(__FILE__) . '/languages/'); }); /** * Create an AES encryption class for encryption/decryption of the secret options * @link https://docs.launchkey.com/glossary.html#term-aes */ $crypt_aes = new \phpseclib\Crypt\AES(); /** * Use an MD5 hash of the auth key as the crypto key. The crypto key is used as it would normally affect all auth * procedures as it is used as a salt for passwords. An md5 hash is used as it will be a constant value based on * the AUTH_KEY but guaranteed to be exactly thirty-two (32) characters as is needed by AES encryption. */ $crypt_aes->setKey(md5(AUTH_KEY)); // Create an options handler that will encrypt and decrypt the plugin options as necessary $options_handler = new LaunchKey_WP_Options($crypt_aes); /** * The pre_update_option_launchkey filter will process the "launchkey" option directly * before updating the data in the database. * * @since 1.0.0 * @link https://developer.wordpress.org/reference/hooks/pre_update_option_option/ * @see LaunchKey_WP_Options::pre_update_option_filter */ add_filter('pre_update_option_launchkey', array($options_handler, 'pre_update_option_filter')); add_filter('pre_update_site_option_launchkey', array($options_handler, 'pre_update_option_filter')); /** * The pre_update_option_filter filter will process the "launchkey" option directly * before adding the data in the database. * * @since 1.0.0 * @link https://developer.wordpress.org/reference/hooks/pre_update_option_option/ * @see LaunchKey_WP_Options::pre_update_option_filter */ add_filter('pre_add_option_launchkey', array($options_handler, 'pre_update_option_filter')); add_filter('pre_add_site_option_launchkey', array($options_handler, 'pre_update_option_filter')); /** * The option_launchkey filter will process the "launchkey" option directly * after retrieving the data from the database. * * @since 1.0.0 * @link https://developer.wordpress.org/reference/hooks/option_option/ * @see LaunchKey_WP_Options::post_get_option_filter */ add_filter('option_launchkey', array($options_handler, 'post_get_option_filter')); add_filter('site_option_launchkey', array($options_handler, 'post_get_option_filter')); $is_multi_site = is_multisite() && is_plugin_active_for_network(plugin_basename(__FILE__)); $options = $is_multi_site ? get_site_option(LaunchKey_WP_Admin::OPTION_KEY) : get_option(LaunchKey_WP_Admin::OPTION_KEY); /** * Handle upgrades if in the admin and not the latest version */ if (is_admin() && launchkey_is_activated() && $options && $options[LaunchKey_WP_Options::OPTION_VERSION] < 1.1) { launchkey_create_tables(); } /** * If the pre-1.0.0 option style was already used, create a 1.0.0 option and remove the old options. They are * removed as the secret_key was stored plain text in the database. * * @since 1.0.0 */ if (get_option('launchkey_app_key') || get_option('launchkey_secret_key')) { $launchkey_options[LaunchKey_WP_Options::OPTION_ROCKET_KEY] = get_option('launchkey_app_key'); $launchkey_options[LaunchKey_WP_Options::OPTION_SECRET_KEY] = get_option('launchkey_secret_key'); $launchkey_options[LaunchKey_WP_Options::OPTION_SSL_VERIFY] = defined('LAUNCHKEY_SSLVERIFY') && LAUNCHKEY_SSLVERIFY || true; $launchkey_options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE] = LaunchKey_WP_Implementation_Type::OAUTH; $launchkey_options[LaunchKey_WP_Options::OPTION_LEGACY_OAUTH] = true; $updated = $is_multi_site ? update_network_option(LaunchKey_WP_Admin::OPTION_KEY, $launchkey_options) : update_option(LaunchKey_WP_Admin::OPTION_KEY, $launchkey_options); if ($updated) { delete_option('launchkey_app_key'); delete_option('launchkey_secret_key'); } else { throw new RuntimeException('Unable to upgrade LaunchKey meta-data. Failed to save setting ' . LaunchKey_WP_Admin::OPTION_KEY); } } elseif (!$options) { $is_multi_site ? add_site_option(LaunchKey_WP_Admin::OPTION_KEY, array()) : add_option(LaunchKey_WP_Admin::OPTION_KEY, array()); $options = $is_multi_site ? get_site_option(LaunchKey_WP_Admin::OPTION_KEY) : get_option(LaunchKey_WP_Admin::OPTION_KEY); } /** * Get the WP global facade * @see LaunchKey_WP_Global_Facade */ $facade = new LaunchKey_WP_Global_Facade(); /** * Create a templating object and point it at the correct directory for template files. * * @see LaunchKey_WP_Template */ $template = new LaunchKey_WP_Template(__DIR__ . '/templates', $facade, $language_domain); // Prevent XXE Processing Vulnerability libxml_disable_entity_loader(true); // Get the plugin options to determine which authentication implementation should be utilized $logger = new LaunchKey_WP_Logger($facade); $launchkey_client = null; $client = null; // Only register the pieces that need to interact with LaunchKey if it's been configured if (LaunchKey_WP_Implementation_Type::SSO === $options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE] && !empty($options[LaunchKey_WP_Options::OPTION_SSO_ENTITY_ID])) { $container = new LaunchKey_WP_SAML2_Container($logger); SAML2_Compat_ContainerSingleton::setContainer($container); $securityKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public')); $securityKey->loadKey($options[LaunchKey_WP_Options::OPTION_SSO_CERTIFICATE], false, true); $saml_response_service = new LaunchKey_WP_SAML2_Response_Service($securityKey, $facade); $saml_request_service = new LaunchKey_WP_SAML2_Request_Service($securityKey); $client = new LaunchKey_WP_SSO_Client($facade, $template, $options[LaunchKey_WP_Options::OPTION_SSO_ENTITY_ID], $saml_response_service, $saml_request_service, $wpdb, $options[LaunchKey_WP_Options::OPTION_SSO_LOGIN_URL], $options[LaunchKey_WP_Options::OPTION_SSO_LOGOUT_URL], $options[LaunchKey_WP_Options::OPTION_SSO_ERROR_URL], $is_multi_site); } elseif (LaunchKey_WP_Implementation_Type::OAUTH === $options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE] && !empty($options[LaunchKey_WP_Options::OPTION_SECRET_KEY])) { /** * If the implementation type is OAuth, use the OAuth client * @see LaunchKey_WP_OAuth_Client */ $client = new LaunchKey_WP_OAuth_Client($facade, $template, $is_multi_site); } elseif (!empty($options[LaunchKey_WP_Options::OPTION_SECRET_KEY])) { $launchkey_client = \LaunchKey\SDK\Client::wpFactory($options[LaunchKey_WP_Options::OPTION_ROCKET_KEY], $options[LaunchKey_WP_Options::OPTION_SECRET_KEY], $options[LaunchKey_WP_Options::OPTION_PRIVATE_KEY], $options[LaunchKey_WP_Options::OPTION_SSL_VERIFY]); $client = new LaunchKey_WP_Native_Client($launchkey_client, $facade, $template, $language_domain, $is_multi_site); add_filter('init', function () use($facade) { wp_enqueue_script('launchkey-script', plugins_url('/public/launchkey-login.js', __FILE__), array('jquery'), '1.1.1', true); }); } if ($client) { /** * Register the non-admin actions for authentication client. These actions will handle all of the * authentication work for the plugin. * * @see LaunchKey_WP_Client::register_actions * @see LaunchKey_WP_OAuth_Client::register_actions * @see LaunchKey_WP_Native_Client::register_actions */ $client->register_actions(); /** * Create the a user profile object and register its actions. These actions will handle all functionality * related to a user customizing their authentication related options. * * @see LaunchKey_WP_User_Profile */ $profile = new LaunchKey_WP_User_Profile($facade, $template, $language_domain, $is_multi_site); $profile->register_actions(); /** * Hideous workaround for the wp-login.php page not printing styles in the header like it should. * * @since 1.0.0 */ if (!has_action('login_enqueue_scripts', 'wp_print_styles')) { add_action('login_enqueue_scripts', 'wp_print_styles', 11); } } if (is_admin() || $is_multi_site && is_network_admin()) { /** * If we are in the admin, create an admin object and register its actions. These actions * will manage setting of options and user management for the plugin. * * @see is_admin * @see LaunchKey_WP_Admin */ $launchkey_admin = new LaunchKey_WP_Admin($facade, $template, $language_domain, $is_multi_site); $launchkey_admin->register_actions(); $config_wizard = new LaunchKey_WP_Configuration_Wizard($facade, $launchkey_admin, $is_multi_site, $launchkey_client); $config_wizard->register_actions(); } /** * Add a filter to enqueue styles for the plugin * * @since 1.0.0 * * @see add_filter * @see wp_enqueue_style * @link https://developer.wordpress.org/reference/functions/add_filter/ * @link https://developer.wordpress.org/reference/functions/wp_enqueue_style/ */ add_filter('init', function () use($facade) { wp_enqueue_style('launchkey-style', plugins_url('/public/launchkey.css', __FILE__), array(), '1.0.1', false); }); /** * Handle activation when a "must use" plugin */ if (launchkey_is_mu_plugin()) { $mu_activated_option = "launchkey_activated"; if (!get_option($mu_activated_option)) { do_action("activate_" . plugin_basename(__FILE__)); add_option($mu_activated_option, true); } } }
/** * Sign the generated EntitiesDescriptor. */ protected function addSignature(SAML2_SignedElement $element) { if ($this->signKey === NULL) { return; } $privateKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'private')); if ($this->signKeyPass !== NULL) { $privateKey->passphrase = $this->signKeyPass; } $privateKey->loadKey($this->signKey, FALSE); $element->setSignatureKey($privateKey); if ($this->signCert !== NULL) { $element->setCertificates(array($this->signCert)); } }
/** * Encrypt an assertion. * * This function takes in a SAML2_Assertion and encrypts it if encryption of * assertions are enabled in the metadata. * * @param SimpleSAML_Configuration $idpMetadata The metadata of the IdP. * @param SimpleSAML_Configuration $spMetadata The metadata of the SP. * @param SAML2_Assertion $assertion The assertion we are encrypting. * @return SAML2_Assertion|SAML2_EncryptedAssertion The assertion. */ private static function encryptAssertion(SimpleSAML_Configuration $idpMetadata, SimpleSAML_Configuration $spMetadata, SAML2_Assertion $assertion) { $encryptAssertion = $spMetadata->getBoolean('assertion.encryption', NULL); if ($encryptAssertion === NULL) { $encryptAssertion = $idpMetadata->getBoolean('assertion.encryption', FALSE); } if (!$encryptAssertion) { /* We are _not_ encrypting this assertion, and are therefore done. */ return $assertion; } $sharedKey = $spMetadata->getString('sharedkey', NULL); if ($sharedKey !== NULL) { $key = new XMLSecurityKey(XMLSecurityKey::AES128_CBC); $key->loadKey($sharedKey); } else { $keys = $spMetadata->getPublicKeys('encryption', TRUE); $key = $keys[0]; switch ($key['type']) { case 'X509Certificate': $pemKey = "-----BEGIN CERTIFICATE-----\n" . chunk_split($key['X509Certificate'], 64) . "-----END CERTIFICATE-----\n"; break; default: throw new SimpleSAML_Error_Exception('Unsupported encryption key type: ' . $key['type']); } /* Extract the public key from the certificate for encryption. */ $key = new XMLSecurityKey(XMLSecurityKey::RSA_OAEP_MGF1P, array('type' => 'public')); $key->loadKey($pemKey); } $ea = new SAML2_EncryptedAssertion(); $ea->setAssertion($assertion, $key); return $ea; }
/** * Retrieve the encryption key for the given entity. * * @param SimpleSAML_Configuration $metadata The metadata of the entity. * @return XMLSecurityKey The encryption key. */ public static function getEncryptionKey(SimpleSAML_Configuration $metadata) { $sharedKey = $metadata->getString('sharedkey', NULL); if ($sharedKey !== NULL) { $key = new XMLSecurityKey(XMLSecurityKey::AES128_CBC); $key->loadKey($sharedKey); return $key; } $keys = $metadata->getPublicKeys('encryption', TRUE); foreach ($keys as $key) { switch ($key['type']) { case 'X509Certificate': $pemKey = "-----BEGIN CERTIFICATE-----\n" . chunk_split($key['X509Certificate'], 64) . "-----END CERTIFICATE-----\n"; $key = new XMLSecurityKey(XMLSecurityKey::RSA_OAEP_MGF1P, array('type' => 'public')); $key->loadKey($pemKey); return $key; } } throw new SimpleSAML_Error_Exception('No supported encryption key in ' . var_export($metadata->getString('entityid'), TRUE)); }
/** * Retrieve certificates that sign this element. * * @return array Array with certificates. */ public function getValidatingCertificates() { $ret = array(); foreach ($this->certificates as $cert) { /* We have found a matching fingerprint. */ $pemCert = "-----BEGIN CERTIFICATE-----\n" . chunk_split($cert, 64) . "-----END CERTIFICATE-----\n"; /* Extract the public key from the certificate for validation. */ $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public')); $key->loadKey($pemCert); try { /* Check the signature. */ if ($this->validate($key)) { $ret[] = $cert; } } catch (Exception $e) { /* This certificate does not sign this element. */ } } return $ret; }
/** * Retrieve and parse the metadata. * * @return SAML2_XML_md_EntitiesDescriptor|SAML2_XML_md_EntityDescriptor|NULL * The downloaded metadata or NULL if we were unable to download or parse it. */ private function downloadMetadata() { SimpleSAML\Logger::debug($this->logLoc . 'Downloading metadata from ' . var_export($this->url, TRUE)); $context = array('ssl' => array()); if ($this->sslCAFile !== NULL) { $context['ssl']['cafile'] = SimpleSAML_Utilities::resolveCert($this->sslCAFile); SimpleSAML\Logger::debug($this->logLoc . 'Validating https connection against CA certificate(s) found in ' . var_export($context['ssl']['cafile'], TRUE)); $context['ssl']['verify_peer'] = TRUE; $context['ssl']['CN_match'] = parse_url($this->url, PHP_URL_HOST); } $data = SimpleSAML_Utilities::fetch($this->url, $context); if ($data === FALSE || $data === NULL) { SimpleSAML\Logger::error($this->logLoc . 'Unable to load metadata from ' . var_export($this->url, TRUE)); return NULL; } $doc = new DOMDocument(); $res = $doc->loadXML($data); if (!$res) { SimpleSAML\Logger::error($this->logLoc . 'Error parsing XML from ' . var_export($this->url, TRUE)); return NULL; } $root = SAML2_Utils::xpQuery($doc->firstChild, '/saml_metadata:EntityDescriptor|/saml_metadata:EntitiesDescriptor'); if (count($root) === 0) { SimpleSAML\Logger::error($this->logLoc . 'No <EntityDescriptor> or <EntitiesDescriptor> in metadata from ' . var_export($this->url, TRUE)); return NULL; } if (count($root) > 1) { SimpleSAML\Logger::error($this->logLoc . 'More than one <EntityDescriptor> or <EntitiesDescriptor> in metadata from ' . var_export($this->url, TRUE)); return NULL; } $root = $root[0]; try { if ($root->localName === 'EntityDescriptor') { $md = new SAML2_XML_md_EntityDescriptor($root); } else { $md = new SAML2_XML_md_EntitiesDescriptor($root); } } catch (Exception $e) { SimpleSAML\Logger::error($this->logLoc . 'Unable to parse metadata from ' . var_export($this->url, TRUE) . ': ' . $e->getMessage()); return NULL; } if ($this->certificate !== NULL) { $file = SimpleSAML_Utilities::resolveCert($this->certificate); $certData = file_get_contents($file); if ($certData === FALSE) { throw new SimpleSAML_Error_Exception('Error loading certificate from ' . var_export($file, TRUE)); } // Extract the public key from the certificate for validation $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public')); $key->loadKey($file, TRUE); if (!$md->validate($key)) { SimpleSAML\Logger::error($this->logLoc . 'Error validating signature on metadata.'); return NULL; } SimpleSAML\Logger::debug($this->logLoc . 'Validated signature on metadata from ' . var_export($this->url, TRUE)); } return $md; }
/** * Adds signature key and senders certificate to an element (Message or Assertion). * * @param string|DomDocument $xml The element we should sign * @param string $key The private key * @param string $cert The public */ public static function addSign($xml, $key, $cert) { if ($xml instanceof DOMDocument) { $dom = $xml; } else { $dom = new DOMDocument(); $dom = self::loadXML($dom, $xml); if (!$dom) { throw new Exception('Error parsing xml string'); } } /* Load the private key. */ $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'private')); $objKey->loadKey($key, false); /* Get the EntityDescriptor node we should sign. */ $rootNode = $dom->firstChild; /* Sign the metadata with our private key. */ $objXMLSecDSig = new XMLSecurityDSig(); $objXMLSecDSig->setCanonicalMethod(XMLSecurityDSig::EXC_C14N); $objXMLSecDSig->addReferenceList(array($rootNode), XMLSecurityDSig::SHA1, array('http://www.w3.org/2000/09/xmldsig#enveloped-signature', XMLSecurityDSig::EXC_C14N), array('id_name' => 'ID')); $objXMLSecDSig->sign($objKey); /* Add the certificate to the signature. */ $objXMLSecDSig->add509Cert($cert, true); $insertBefore = $rootNode->firstChild; $messageTypes = array('samlp:AuthnRequest', 'samlp:Response', 'samlp:LogoutRequest', 'samlp:LogoutResponse'); if (in_array($rootNode->tagName, $messageTypes)) { $issuerNodes = self::query($dom, '/' . $rootNode->tagName . '/saml:Issuer'); if ($issuerNodes->length == 1) { $insertBefore = $issuerNodes->item(0)->nextSibling; } } /* Add the signature. */ $objXMLSecDSig->insertSignature($rootNode, $insertBefore); /* Return the DOM tree as a string. */ $signedxml = $dom->saveXML(); return $signedxml; }
/** * 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 */ 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); $msg = 'SAMLResponse=' . urlencode($samlResponse); $msg .= '&RelayState=' . urlencode($relayState); $msg .= '&SigAlg=' . urlencode($signAlgorithm); $signature = $objKey->signData($msg); return base64_encode($signature); }
public function decryptSoapDoc($doc, $options) { $privKey = null; $privKey_isFile = false; $privKey_isCert = false; if (is_array($options)) { $privKey = !empty($options["keys"]["private"]["key"]) ? $options["keys"]["private"]["key"] : null; $privKey_isFile = !empty($options["keys"]["private"]["isFile"]) ? true : false; $privKey_isCert = !empty($options["keys"]["private"]["isCert"]) ? true : false; } $objenc = new XMLSecEnc(); $xpath = new DOMXPath($doc); $envns = $doc->documentElement->namespaceURI; $xpath->registerNamespace("soapns", $envns); $xpath->registerNamespace("soapenc", "http://www.w3.org/2001/04/xmlenc#"); $nodes = $xpath->query('/soapns:Envelope/soapns:Header/*[local-name()="Security"]/soapenc:EncryptedKey'); $references = array(); if ($node = $nodes->item(0)) { $objenc = new XMLSecEnc(); $objenc->setNode($node); if (!($objKey = $objenc->locateKey())) { throw new Exception("Unable to locate algorithm for this Encrypted Key"); } $objKey->isEncrypted = true; $objKey->encryptedCtx = $objenc; XMLSecEnc::staticLocateKeyInfo($objKey, $node); if ($objKey && $objKey->isEncrypted) { $objencKey = $objKey->encryptedCtx; $objKey->loadKey($privKey, $privKey_isFile, $privKey_isCert); $key = $objencKey->decryptKey($objKey); $objKey->loadKey($key); } $refnodes = $xpath->query('./soapenc:ReferenceList/soapenc:DataReference/@URI', $node); foreach ($refnodes as $reference) { $references[] = $reference->nodeValue; } } foreach ($references as $reference) { $arUrl = parse_url($reference); $reference = $arUrl['fragment']; $query = '//*[@Id="' . $reference . '"]'; $nodes = $xpath->query($query); $encData = $nodes->item(0); if ($algo = $xpath->evaluate("string(./soapenc:EncryptionMethod/@Algorithm)", $encData)) { $objKey = new XMLSecurityKey($algo); $objKey->loadKey($key); } $objenc->setNode($encData); $objenc->type = $encData->getAttribute("Type"); $decrypt = $objenc->decryptNode($objKey, true); } return true; }
/** * Helper function to convert a XMLSecurityKey to the correct algorithm. * * @param XMLSecurityKey $key The key. * @param string $algorithm The desired algorithm. * @param string $type Public or private key, defaults to public. * @return XMLSecurityKey The new key. * @throws Exception */ public static function castKey(XMLSecurityKey $key, $algorithm, $type = 'public') { assert('is_string($algorithm)'); assert('$type === "public" || $type === "private"'); // do nothing if algorithm is already the type of the key if ($key->type === $algorithm) { return $key; } $keyInfo = openssl_pkey_get_details($key->key); if ($keyInfo === FALSE) { throw new Exception('Unable to get key details from XMLSecurityKey.'); } if (!isset($keyInfo['key'])) { throw new Exception('Missing key in public key details.'); } $newKey = new XMLSecurityKey($algorithm, array('type' => $type)); $newKey->loadKey($keyInfo['key']); return $newKey; }