public static loadPublicKey ( SimpleSAML_Configuration $metadata, $required = false, $prefix = '' ) | ||
$metadata | SimpleSAML_Configuration |
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); }
/** * Add signature key and sender certificate to an element (Message or Assertion). * * @param SimpleSAML_Configuration $srcMetadata The metadata of the sender. * @param SimpleSAML_Configuration $dstMetadata The metadata of the recipient. * @param SAML2_Message $element The element we should add the data to. */ public static function addSign(SimpleSAML_Configuration $srcMetadata, SimpleSAML_Configuration $dstMetadata, SAML2_SignedElement $element) { $keyArray = SimpleSAML_Utilities::loadPrivateKey($srcMetadata, TRUE); $certArray = SimpleSAML_Utilities::loadPublicKey($srcMetadata, FALSE); $algo = $dstMetadata->getString('signature.algorithm', NULL); if ($algo === NULL) { /* * In the NIST Special Publication 800-131A, SHA-1 became deprecated for generating * new digital signatures in 2011, and will be explicitly disallowed starting the 1st * of January, 2014. We'll keep this as a default for the next release and mark it * as deprecated, as part of the transition to SHA-256. * * See http://csrc.nist.gov/publications/nistpubs/800-131A/sp800-131A.pdf for more info. * * TODO: change default to XMLSecurityKey::RSA_SHA256. */ $algo = $srcMetadata->getString('signature.algorithm', XMLSecurityKey::RSA_SHA1); } $privateKey = new XMLSecurityKey($algo, array('type' => 'private')); if (array_key_exists('password', $keyArray)) { $privateKey->passphrase = $keyArray['password']; } $privateKey->loadKey($keyArray['PEM'], FALSE); $element->setSignatureKey($privateKey); if ($certArray === NULL) { /* We don't have a certificate to add. */ return; } if (!array_key_exists('PEM', $certArray)) { /* We have a public key with only a fingerprint. */ return; } $element->setCertificates(array($certArray['PEM'])); }
/** * Send an authenticationResponse using HTTP-POST. * * @param string $response The response which should be sent. * @param array $idpmd The metadata of the IdP which is sending the response. * @param array $spmd The metadata of the SP which is receiving the response. * @param string|NULL $relayState The relaystate for the SP. * @param string $shire The shire which should receive the response. */ public function sendResponse($response, $idpmd, $spmd, $relayState, $shire) { SimpleSAML_Utilities::validateXMLDocument($response, 'saml11'); $privatekey = SimpleSAML_Utilities::loadPrivateKey($idpmd, TRUE); $publickey = SimpleSAML_Utilities::loadPublicKey($idpmd, TRUE); $responsedom = new DOMDocument(); $responsedom->loadXML(str_replace("\r", "", $response)); $responseroot = $responsedom->getElementsByTagName('Response')->item(0); $firstassertionroot = $responsedom->getElementsByTagName('Assertion')->item(0); /* Determine what we should sign - either the Response element or the Assertion. The default * is to sign the Assertion, but that can be overridden by the 'signresponse' option in the * SP metadata or 'saml20.signresponse' in the global configuration. */ $signResponse = FALSE; if (array_key_exists('signresponse', $spmd) && $spmd['signresponse'] !== NULL) { $signResponse = $spmd['signresponse']; if (!is_bool($signResponse)) { throw new Exception('Expected the \'signresponse\' option in the metadata of the' . ' SP \'' . $spmd['entityid'] . '\' to be a boolean value.'); } } else { $signResponse = $this->configuration->getBoolean('shib13.signresponse', TRUE); } /* Check if we have an assertion to sign. Force to sign the response if not. */ if ($firstassertionroot === NULL) { $signResponse = TRUE; } $signer = new SimpleSAML_XML_Signer(array('privatekey_array' => $privatekey, 'publickey_array' => $publickey, 'id' => $signResponse ? 'ResponseID' : 'AssertionID')); if (array_key_exists('certificatechain', $idpmd)) { $signer->addCertificate($idpmd['certificatechain']); } if ($signResponse) { /* Sign the response - this must be done after encrypting the assertion. */ /* We insert the signature before the saml2p:Status element. */ $statusElements = SimpleSAML_Utilities::getDOMChildren($responseroot, 'Status', '@saml1p'); assert('count($statusElements) === 1'); $signer->sign($responseroot, $responseroot, $statusElements[0]); } else { /* Sign the assertion */ $signer->sign($firstassertionroot, $firstassertionroot); } $response = $responsedom->saveXML(); if ($this->configuration->getBoolean('debug', FALSE)) { $p = new SimpleSAML_XHTML_Template($this->configuration, 'post-debug.php'); $p->data['header'] = 'SAML (Shibboleth 1.3) Response Debug-mode'; $p->data['RelayStateName'] = 'TARGET'; $p->data['RelayState'] = $relayState; $p->data['destination'] = $shire; $p->data['response'] = str_replace("\n", "", base64_encode($response)); $p->data['responseHTML'] = htmlspecialchars(SimpleSAML_Utilities::formatXMLString($response)); $p->show(); } else { SimpleSAML_Utilities::postRedirect($shire, array('TARGET' => $relayState, 'SAMLResponse' => base64_encode($response))); } }
public function getMetadata() { $idpentityid = SimpleSAML_Utilities::getBaseURL() . 'module.php/fedlab/metadata.php'; $metaArray = array('metadata-set' => 'saml20-idp-remote', 'entityid' => $idpentityid, 'SingleSignOnService' => SimpleSAML_Utilities::getBaseURL() . 'module.php/fedlab/SingleSignOnService.php', 'SingleLogoutService' => SimpleSAML_Utilities::getBaseURL() . 'module.php/fedlab/SingleLogoutService.php', 'certificate' => 'server.crt'); $metaArrayConfig = SimpleSAML_Configuration::loadFromArray($metaArray); $certInfo = SimpleSAML_Utilities::loadPublicKey($metaArrayConfig, TRUE); $metaBuilder = new SimpleSAML_Metadata_SAMLBuilder($idpentityid); $metaBuilder->addMetadataIdP20($metaArray); $metaBuilder->addOrganizationInfo($metaArray); $metaBuilder->addContact('technical', array('emailAddress' => $this->config->getString('technicalcontact_email', NULL), 'name' => $this->config->getString('technicalcontact_name', NULL))); $metaxml = $metaBuilder->getEntityDescriptorText(); return $metaxml; }
/** * Add signature key and and senders certificate to an element (Message or Assertion). * * @param SimpleSAML_Configuration $srcMetadata The metadata of the sender. * @param SimpleSAML_Configuration $dstMetadata The metadata of the recipient. * @param SAML2_Message $element The element we should add the data to. */ public static function addSign(SimpleSAML_Configuration $srcMetadata, SimpleSAML_Configuration $dstMetadata, SAML2_SignedElement $element) { $keyArray = SimpleSAML_Utilities::loadPrivateKey($srcMetadata, TRUE); $certArray = SimpleSAML_Utilities::loadPublicKey($srcMetadata, FALSE); $privateKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'private')); if (array_key_exists('password', $keyArray)) { $privateKey->passphrase = $keyArray['password']; } $privateKey->loadKey($keyArray['PEM'], FALSE); $element->setSignatureKey($privateKey); if ($certArray === NULL) { /* We don't have a certificate to add. */ return; } if (!array_key_exists('PEM', $certArray)) { /* We have a public key with only a fingerprint. */ return; } $element->setCertificates(array($certArray['PEM'])); }
/** * Send an authenticationResponse using HTTP-POST. * * @param string $response The response which should be sent. * @param SimpleSAML_Configuration $idpmd The metadata of the IdP which is sending the response. * @param SimpleSAML_Configuration $spmd The metadata of the SP which is receiving the response. * @param string|NULL $relayState The relaystate for the SP. * @param string $shire The shire which should receive the response. */ public function sendResponse($response, SimpleSAML_Configuration $idpmd, SimpleSAML_Configuration $spmd, $relayState, $shire) { SimpleSAML_Utilities::validateXMLDocument($response, 'saml11'); $privatekey = SimpleSAML_Utilities::loadPrivateKey($idpmd, TRUE); $publickey = SimpleSAML_Utilities::loadPublicKey($idpmd, TRUE); $responsedom = new DOMDocument(); $responsedom->loadXML(str_replace("\r", "", $response)); $responseroot = $responsedom->getElementsByTagName('Response')->item(0); $firstassertionroot = $responsedom->getElementsByTagName('Assertion')->item(0); /* Determine what we should sign - either the Response element or the Assertion. The default * is to sign the Assertion, but that can be overridden by the 'signresponse' option in the * SP metadata or 'saml20.signresponse' in the global configuration. */ $signResponse = FALSE; if ($spmd->hasValue('signresponse')) { $signResponse = $spmd->getBoolean['signresponse']; } else { $signResponse = $this->configuration->getBoolean('shib13.signresponse', TRUE); } /* Check if we have an assertion to sign. Force to sign the response if not. */ if ($firstassertionroot === NULL) { $signResponse = TRUE; } $signer = new SimpleSAML_XML_Signer(array('privatekey_array' => $privatekey, 'publickey_array' => $publickey, 'id' => $signResponse ? 'ResponseID' : 'AssertionID')); if ($idpmd->hasValue('certificatechain')) { $signer->addCertificate($idpmd->getString('certificatechain')); } if ($signResponse) { /* Sign the response - this must be done after encrypting the assertion. */ /* We insert the signature before the saml2p:Status element. */ $statusElements = SimpleSAML_Utilities::getDOMChildren($responseroot, 'Status', '@saml1p'); assert('count($statusElements) === 1'); $signer->sign($responseroot, $responseroot, $statusElements[0]); } else { /* Sign the assertion */ $signer->sign($firstassertionroot, $firstassertionroot); } $response = $responsedom->saveXML(); SimpleSAML_Utilities::debugMessage($response, 'out'); SimpleSAML_Utilities::postRedirect($shire, array('TARGET' => $relayState, 'SAMLResponse' => base64_encode($response))); }
protected function createResponse($testrun, $request, $relayState = NULL) { $this->log($testrun, 'Creating response with relaystate [' . $relayState . ']'); $idpMetadata = SimpleSAML_Configuration::loadFromArray($this->idpmetadata); $spMetadata = SimpleSAML_Configuration::loadFromArray($this->metadata); $requestId = $request->getId(); $consumerURL = $request->getAssertionConsumerServiceURL(); $spentityid = $spMetadata->getString('entityid'); $idpentityid = $idpMetadata->getString('entityid'); $consumerURLf = $spMetadata->getDefaultEndpoint('AssertionConsumerService', array('urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST'), $consumerURL); $consumerURL = $consumerURLf['Location']; $protocolBinding = SAML2_Const::BINDING_HTTP_POST; $config = $this->getConfig($testrun); # print_r($requestId); // Build the response $signResponse = $config['signResponse']; $response = new sspmod_fedlab_xml_Response(); $response->setIssuer($this->getIssuerResponse($testrun, $idpentityid)); $response->setDestination($this->getDestinationResponse($testrun, $consumerURL)); if ($signResponse) { // self::addSign($srcMetadata, $dstMetadata, $r); $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'])); } $inresponseto = $this->getInResponseToResponse($testrun, $requestId); if (!empty($inresponseto)) { $response->setInResponseTo($inresponseto); } $response->setRelayState($this->getRelayState($testrun, $relayState)); $realAttr = array('urn:oid:1.3.6.1.4.1.5923.1.1.1.6' => array('*****@*****.**'), 'urn:mace:dir:attribute-def:eduPersonPrincipalName' => array('*****@*****.**')); $fakeAttr = array('urn:foo' => array('bar')); switch ($testrun) { /* getAssertion($testrun, $request, $attributes = NULL, $sign = FALSE, $includeAuthn = TRUE) { */ case 'multipleassertion1': $response->setAssertions(array($this->getAssertion($testrun, $request, $realAttr, $config['signAssertion'], TRUE), $this->getAssertion($testrun, $request, $fakeAttr, $config['signAssertion'], TRUE))); break; case 'multipleassertion2': $response->setAssertions(array($this->getAssertion($testrun, $request, $fakeAttr, $config['signAssertion'], TRUE), $this->getAssertion($testrun, $request, $realAttr, $config['signAssertion'], TRUE))); break; case 'multipleassertion3': $response->setAssertions(array($this->getAssertion($testrun, $request, $fakeAttr, TRUE, TRUE), $this->getAssertion($testrun, $request, $realAttr, FALSE, TRUE))); break; case 'multipleassertion3b': $response->setAssertions(array($this->getAssertion($testrun, $request, $realAttr, FALSE, TRUE), $this->getAssertion($testrun, $request, $fakeAttr, TRUE, TRUE))); break; case 'multipleassertion4': $response->setAssertions(array($this->getAssertion($testrun, $request, $realAttr, TRUE, FALSE), $this->getAssertion($testrun, $request, $fakeAttr, FALSE, TRUE))); break; case 'multipleassertion4b': $response->setAssertions(array($this->getAssertion($testrun, $request, $fakeAttr, FALSE, TRUE), $this->getAssertion($testrun, $request, $realAttr, TRUE, FALSE))); break; } $this->tweakResponse($testrun, $response); $msgStr = $response->toSignedXML(); $msgStr = $msgStr->ownerDocument->saveXML($msgStr); return array('url' => $consumerURL, 'Response' => $msgStr, 'RelayState' => $relayState); }
/** * 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 $srcMetadata The metadata of the sender (IdP). * @param SimpleSAML_Configuration $dstMetadata The metadata of the recipient (SP). * @param SAML2_Assertion $assertion The assertion we are encrypting. * @return SAML2_Assertion|SAML2_EncryptedAssertion The assertion. */ public static function encryptAssertion(SimpleSAML_Configuration $srcMetadata, SimpleSAML_Configuration $dstMetadata, SAML2_Assertion $assertion) { $encryptAssertion = $dstMetadata->getBoolean('assertion.encryption', NULL); if ($encryptAssertion === NULL) { $encryptAssertion = $srcMetadata->getBoolean('assertion.encryption', FALSE); } if (!$encryptAssertion) { /* We are _not_ encrypting this assertion, and are therefore done. */ return $assertion; } $sharedKey = $dstMetadata->getString('sharedkey', NULL); if ($sharedKey !== NULL) { $key = new XMLSecurityKey(XMLSecurityKey::AES128_CBC); $key->loadKey($sharedKey); } else { /* Find the certificate that we should use to encrypt messages to this SP. */ $certArray = SimpleSAML_Utilities::loadPublicKey($dstMetadata, TRUE); if (!array_key_exists('PEM', $certArray)) { throw new Exception('Unable to locate key we should use to encrypt the assertionst ' . 'to the SP: ' . var_export($dstMetadata->getString('entityid'), TRUE) . '.'); } $pemCert = $certArray['PEM']; /* Extract the public key from the certificate for encryption. */ $key = new XMLSecurityKey(XMLSecurityKey::RSA_1_5, array('type' => 'public')); $key->loadKey($pemCert); } $ea = new SAML2_EncryptedAssertion(); $ea->setAssertion($assertion, $key); return $ea; }
$idpmeta = $metadata->getMetaDataConfig($idpentityid, 'saml20-idp-hosted'); $availableCerts = array(); $keys = array(); $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, FALSE, 'new_'); if ($certInfo !== NULL) { $availableCerts['new_idp.crt'] = $certInfo; $keys[] = array('type' => 'X509Certificate', 'signing' => TRUE, 'encryption' => TRUE, 'X509Certificate' => $certInfo['certData']); $hasNewCert = TRUE; } else { $hasNewCert = FALSE; } $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, TRUE); $availableCerts['idp.crt'] = $certInfo; $keys[] = array('type' => 'X509Certificate', 'signing' => TRUE, 'encryption' => $hasNewCert ? FALSE : TRUE, 'X509Certificate' => $certInfo['certData']); if ($idpmeta->hasValue('https.certificate')) { $httpsCert = SimpleSAML_Utilities::loadPublicKey($idpmeta, TRUE, 'https.'); assert('isset($httpsCert["certData"])'); $availableCerts['https.crt'] = $httpsCert; $keys[] = array('type' => 'X509Certificate', 'signing' => TRUE, 'encryption' => FALSE, 'X509Certificate' => $httpsCert['certData']); } $metaArray = array('metadata-set' => 'saml20-idp-remote', 'entityid' => $idpentityid, 'SingleSignOnService' => array(0 => array('Binding' => SAML2_Const::BINDING_HTTP_REDIRECT, 'Location' => $metadata->getGenerated('SingleSignOnService', 'saml20-idp-hosted'))), 'SingleLogoutService' => $metadata->getGenerated('SingleLogoutService', 'saml20-idp-hosted')); if (count($keys) === 1) { $metaArray['certData'] = $keys[0]['X509Certificate']; } else { $metaArray['keys'] = $keys; } if ($idpmeta->getBoolean('saml20.sendartifact', FALSE)) { /* Artifact sending enabled. */ $metaArray['ArtifactResolutionService'][] = array('index' => 0, 'Location' => SimpleSAML_Utilities::getBaseURL() . 'saml2/idp/ArtifactResolutionService.php', 'Binding' => SAML2_Const::BINDING_SOAP); } if ($idpmeta->getBoolean('saml20.hok.assertion', FALSE)) {
private function authenticate() { $client_is_authenticated = false; /* Authenticate the requestor by verifying the TLS certificate used for the HTTP query */ if (array_key_exists('SSL_CLIENT_VERIFY', $_SERVER)) { SimpleSAML_Logger::debug('[aa] Request was made using the following certificate: ' . var_export($_SERVER['SSL_CLIENT_VERIFY'], 1)); } if (array_key_exists('SSL_CLIENT_VERIFY', $_SERVER) && $_SERVER['SSL_CLIENT_VERIFY'] && $_SERVER['SSL_CLIENT_VERIFY'] != 'NONE') { /* compare certificate fingerprints */ $clientCertData = trim(preg_replace('/--.* CERTIFICATE-+-/', '', $_SERVER['SSL_CLIENT_CERT'])); $clientCertFingerprint = strtolower(sha1(base64_decode($clientCertData))); if (!$clientCertFingerprint) { throw new SimpleSAML_Error_Exception('[aa] Can not calculate certificate fingerprint from the request.'); } $spCertArray = SimpleSAML_Utilities::loadPublicKey($this->spMetadata); if (!$spCertArray) { throw new SimpleSAML_Error_Exception('[aa] Can not find the public key of the requestor in the metadata!'); } foreach ($spCertArray['certFingerprint'] as $fingerprint) { if ($fingerprint && $clientCertFingerprint == $fingerprint) { $client_is_authenticated = true; SimpleSAML_Logger::debug('[aa] SSL certificate is checked and valid.'); break; } } /* Reject the request if the TLS certificate used for the request does not match metadata */ if (!$client_is_authenticated) { throw new SimpleSAML_Error_Exception('[aa] SSL certificate check failed.'); } } else { /* The request may be signed, so this is not fatal */ SimpleSAML_Logger::debug('[aa] SSL client certificate does not exist.'); } /* Authenticate the requestor by verifying the XML signature on the query */ $certs_of_query = $this->query->getCertificates(); if (count($certs_of_query) > 0) { if (sspmod_saml_Message::checkSign($this->spMetadata, $this->query)) { $client_is_authenticated = true; SimpleSAML_Logger::debug('[aa] AttributeQuery signature is checked and valid.'); } else { /* An invalid or unverifiable signature is fatal */ throw new SimpleSAML_Error_Exception('[aa] The signature of the AttributeQuery is wrong!'); } } else { /* The request may be protected by HTTP TLS (X.509) authentication, so this is not fatal */ SimpleSAML_Logger::debug('[aa] AttributeQuery has no signature.'); } if (!$client_is_authenticated) { SimpleSAML_Logger::info('[aa] Attribute query was not authenticated. Drop.'); header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: None', false); echo 'Not authenticated. Neither query signature nor SSL client certificate was available.'; exit; } else { SimpleSAML_Logger::debug('[aa] Attribute query was authenticated.'); } }
/** * This function sends the SOAP message to the service location and returns SOAP response * * @param SAML2_Message $m The request that should be sent. * @param SimpleSAML_Configuration $srcMetadata The metadata of the issuer of the message. * @param SimpleSAML_Configuration $dstMetadata The metadata of the destination of the message. * @return SAML2_Message The response we received. */ public function send(SAML2_Message $msg, SimpleSAML_Configuration $srcMetadata, SimpleSAML_Configuration $dstMetadata = NULL) { $issuer = $msg->getIssuer(); $ctxOpts = array('ssl' => array('capture_peer_cert' => TRUE)); // Determine if we are going to do a MutualSSL connection between the IdP and SP - Shoaib if ($srcMetadata->hasValue('saml.SOAPClient.certificate')) { $ctxOpts['ssl']['local_cert'] = SimpleSAML_Utilities::resolveCert($srcMetadata->getString('saml.SOAPClient.certificate')); if ($srcMetadata->hasValue('saml.SOAPClient.privatekey_pass')) { $ctxOpts['ssl']['passphrase'] = $srcMetadata->getString('saml.SOAPClient.privatekey_pass'); } } else { /* Use the SP certificate and privatekey if it is configured. */ $privateKey = SimpleSAML_Utilities::loadPrivateKey($srcMetadata); $publicKey = SimpleSAML_Utilities::loadPublicKey($srcMetadata); if ($privateKey !== NULL && $publicKey !== NULL && isset($publicKey['PEM'])) { $keyCertData = $privateKey['PEM'] . $publicKey['PEM']; $file = SimpleSAML_Utilities::getTempDir() . '/' . sha1($keyCertData) . '.pem'; if (!file_exists($file)) { SimpleSAML_Utilities::writeFile($file, $keyCertData); } $ctxOpts['ssl']['local_cert'] = $file; if (isset($privateKey['password'])) { $ctxOpts['ssl']['passphrase'] = $privateKey['password']; } } } // do peer certificate verification if ($dstMetadata !== NULL) { $peerPublicKeys = $dstMetadata->getPublicKeys('signing', TRUE); $certData = ''; foreach ($peerPublicKeys as $key) { if ($key['type'] !== 'X509Certificate') { continue; } $certData .= "-----BEGIN CERTIFICATE-----\n" . chunk_split($key['X509Certificate'], 64) . "-----END CERTIFICATE-----\n"; } $peerCertFile = SimpleSAML_Utilities::getTempDir() . '/' . sha1($certData) . '.pem'; if (!file_exists($peerCertFile)) { SimpleSAML_Utilities::writeFile($peerCertFile, $certData); } // create ssl context $ctxOpts['ssl']['verify_peer'] = TRUE; $ctxOpts['ssl']['verify_depth'] = 1; $ctxOpts['ssl']['cafile'] = $peerCertFile; } $context = stream_context_create($ctxOpts); if ($context === NULL) { throw new Exception('Unable to create SSL stream context'); } $options = array('uri' => $issuer, 'location' => $msg->getDestination(), 'stream_context' => $context); $x = new SoapClient(NULL, $options); // Add soap-envelopes $request = $msg->toSignedXML(); $request = self::START_SOAP_ENVELOPE . $request->ownerDocument->saveXML($request) . self::END_SOAP_ENVELOPE; SimpleSAML_Utilities::debugMessage($request, 'out'); $action = 'http://www.oasis-open.org/committees/security'; $version = '1.1'; $destination = $msg->getDestination(); /* Perform SOAP Request over HTTP */ $soapresponsexml = $x->__doRequest($request, $destination, $action, $version); if ($soapresponsexml === NULL || $soapresponsexml === "") { throw new Exception('Empty SOAP response, check peer certificate.'); } SimpleSAML_Utilities::debugMessage($soapresponsexml, 'in'); // Convert to SAML2_Message (DOMElement) $dom = new DOMDocument(); if (!$dom->loadXML($soapresponsexml)) { throw new Exception('Not a SOAP response.'); } $soapfault = $this->getSOAPFault($dom); if (isset($soapfault)) { throw new Exception($soapfault); } //Extract the message from the response $xml = $dom->firstChild; /* Soap Envelope */ $samlresponse = SAML2_Utils::xpQuery($dom->firstChild, '/soap-env:Envelope/soap-env:Body/*[1]'); $samlresponse = SAML2_Message::fromXML($samlresponse[0]); /* Add validator to message which uses the SSL context. */ self::addSSLValidator($samlresponse, $context); SimpleSAML_Logger::debug("Valid ArtifactResponse received from IdP"); return $samlresponse; }
$aameta = $metadata->getMetaDataConfig($aaentityid, 'attributeauthority-hosted'); $availableCerts = array(); $keys = array(); $certInfo = SimpleSAML_Utilities::loadPublicKey($aameta, false, 'new_'); if ($certInfo !== null) { $availableCerts['new_aa.crt'] = $certInfo; $keys[] = array('type' => 'X509Certificate', 'signing' => true, 'encryption' => true, 'X509Certificate' => $certInfo['certData']); $hasNewCert = true; } else { $hasNewCert = false; } $certInfo = SimpleSAML_Utilities::loadPublicKey($aameta, true); $availableCerts['aa.crt'] = $certInfo; $keys[] = array('type' => 'X509Certificate', 'signing' => true, 'encryption' => $hasNewCert ? false : true, 'X509Certificate' => $certInfo['certData']); if ($aameta->hasValue('https.certificate')) { $httpsCert = SimpleSAML_Utilities::loadPublicKey($aameta, true, 'https.'); assert('isset($httpsCert["certData"])'); $availableCerts['https.crt'] = $httpsCert; $keys[] = array('type' => 'X509Certificate', 'signing' => true, 'encryption' => false, 'X509Certificate' => $httpsCert['certData']); } $metaArray = array('metadata-set' => 'attributeauthority-hosted', 'entityid' => $aaentityid, 'protocols' => array(SAML2_Const::NS_SAMLP), 'AttributeService' => array(0 => array('Binding' => SAML2_Const::BINDING_SOAP, 'Location' => SimpleSAML_Utilities::getBaseURL() . 'module.php/aa/attributeserver.php'))); if (count($keys) === 1) { $metaArray['certData'] = $keys[0]['X509Certificate']; } else { $metaArray['keys'] = $keys; } $metaArray['NameIDFormat'] = array(SAML2_Const::NAMEID_PERSISTENT, SAML2_Const::NAMEID_TRANSIENT); if ($aameta->hasValue('OrganizationName')) { $metaArray['OrganizationName'] = $aameta->getLocalizedString('OrganizationName'); $metaArray['OrganizationDisplayName'] = $aameta->getLocalizedString('OrganizationDisplayName', $metaArray['OrganizationName']); if (!$aameta->hasValue('OrganizationURL')) {
if (!$config->getBoolean('enable.shib13-idp', false)) { throw new SimpleSAML_Error_Error('NOACCESS'); } /* Check if valid local session exists.. */ if ($config->getBoolean('admin.protectmetadata', false)) { SimpleSAML_Utilities::requireAdmin(); } try { $idpentityid = isset($_GET['idpentityid']) ? $_GET['idpentityid'] : $metadata->getMetaDataCurrentEntityID('shib13-idp-hosted'); $idpmeta = $metadata->getMetaDataConfig($idpentityid, 'shib13-idp-hosted'); $keys = array(); $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, FALSE, 'new_'); if ($certInfo !== NULL) { $keys[] = array('type' => 'X509Certificate', 'signing' => TRUE, 'encryption' => FALSE, 'X509Certificate' => $certInfo['certData']); } $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, TRUE); $keys[] = array('type' => 'X509Certificate', 'signing' => TRUE, 'encryption' => FALSE, 'X509Certificate' => $certInfo['certData']); $metaArray = array('metadata-set' => 'shib13-idp-remote', 'entityid' => $idpentityid, 'SingleSignOnService' => $metadata->getGenerated('SingleSignOnService', 'shib13-idp-hosted')); if (count($keys) === 1) { $metaArray['certData'] = $keys[0]['X509Certificate']; } else { $metaArray['keys'] = $keys; } $metaArray['NameIDFormat'] = $idpmeta->getString('NameIDFormat', 'urn:mace:shibboleth:1.0:nameIdentifier'); if ($idpmeta->hasValue('OrganizationName')) { $metaArray['OrganizationName'] = $idpmeta->getLocalizedString('OrganizationName'); $metaArray['OrganizationDisplayName'] = $idpmeta->getLocalizedString('OrganizationDisplayName', $metaArray['OrganizationName']); if (!$idpmeta->hasValue('OrganizationURL')) { throw new SimpleSAML_Error_Exception('If OrganizationName is set, OrganizationURL must also be set.'); } $metaArray['OrganizationURL'] = $idpmeta->getLocalizedString('OrganizationURL');
/** * This function receives a SAML 1.1 artifact. * * @param SimpleSAML_Configuration $spMetadata The metadata of the SP. * @param SimpleSAML_Configuration $idpMetadata The metadata of the IdP. * @return string The <saml1p:Response> element, as an XML string. */ public static function receive(SimpleSAML_Configuration $spMetadata, SimpleSAML_Configuration $idpMetadata) { $artifacts = self::getArtifacts(); $request = self::buildRequest($artifacts); $url = 'https://skjak.uninett.no:1245/test...'; $url = $idpMetadata->getString('ArtifactResolutionService'); $certData = SimpleSAML_Utilities::loadPublicKey($idpMetadata->toArray(), TRUE); if (!array_key_exists('PEM', $certData)) { throw new SimpleSAML_Error_Exception('Missing one of certData or certificate in metadata for ' . var_export($idpMetadata->getString('entityid'), TRUE)); } $certData = $certData['PEM']; $file = SimpleSAML_Utilities::getTempDir() . '/' . sha1($certData) . '.crt'; if (!file_exists($file)) { SimpleSAML_Utilities::writeFile($file, $certData); } $globalConfig = SimpleSAML_Configuration::getInstance(); $spKeyCertFile = $globalConfig->getPathValue('certdir', 'cert/') . $spMetadata->getString('privatekey'); $opts = array('ssl' => array('verify_peer' => TRUE, 'cafile' => $file, 'local_cert' => $spKeyCertFile, 'capture_peer_cert' => TRUE, 'capture_peer_chain' => TRUE), 'http' => array('method' => 'POST', 'content' => $request, 'header' => 'SOAPAction: http://www.oasis-open.org/committees/security' . "\r\n" . 'Content-Type: text/xml')); $context = stream_context_create($opts); /* Fetch the artifact. */ $response = file_get_contents($url, FALSE, $context); if ($response === FALSE) { throw new SimpleSAML_Error_Exception('Failed to retrieve assertion from IdP.'); } /* Find the response in the SOAP message. */ $response = self::extractResponse($response); return $response; }
break; } $eps[] = $acsArray; $index++; } $metaArray20['AssertionConsumerService'] = $eps; $keys = array(); $certInfo = SimpleSAML_Utilities::loadPublicKey($spconfig, FALSE, 'new_'); if ($certInfo !== NULL && array_key_exists('certData', $certInfo)) { $hasNewCert = TRUE; $certData = $certInfo['certData']; $keys[] = array('type' => 'X509Certificate', 'signing' => TRUE, 'encryption' => TRUE, 'X509Certificate' => $certInfo['certData']); } else { $hasNewCert = FALSE; } $certInfo = SimpleSAML_Utilities::loadPublicKey($spconfig); if ($certInfo !== NULL && array_key_exists('certData', $certInfo)) { $certData = $certInfo['certData']; $keys[] = array('type' => 'X509Certificate', 'signing' => TRUE, 'encryption' => $hasNewCert ? FALSE : TRUE, 'X509Certificate' => $certInfo['certData']); } else { $certData = NULL; } $name = $spconfig->getLocalizedString('name', NULL); $attributes = $spconfig->getArray('attributes', array()); if ($name !== NULL && !empty($attributes)) { $metaArray20['name'] = $name; $metaArray20['attributes'] = $attributes; $metaArray20['attributes.required'] = $spconfig->getArray('attributes.required', array()); $description = $spconfig->getArray('description', NULL); if ($description !== NULL) { $metaArray20['description'] = $description;
require_once '../../_include.php'; /* Load simpleSAMLphp, configuration and metadata */ $config = SimpleSAML_Configuration::getInstance(); $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); if (!$config->getBoolean('enable.shib13-sp', false)) { throw new SimpleSAML_Error_Error('NOACCESS'); } /* Check if valid local session exists.. */ if ($config->getBoolean('admin.protectmetadata', false)) { SimpleSAML_Utilities::requireAdmin(); } try { $spentityid = isset($_GET['spentityid']) ? $_GET['spentityid'] : $metadata->getMetaDataCurrentEntityID('shib13-sp-hosted'); $spmeta = $metadata->getMetaDataConfig($spentityid, 'shib13-sp-hosted'); $metaArray = array('metadata-set' => 'shib13-sp-remote', 'entityid' => $spentityid, 'AssertionConsumerService' => $metadata->getGenerated('AssertionConsumerService', 'shib13-sp-hosted')); $certInfo = SimpleSAML_Utilities::loadPublicKey($spmeta); if ($certInfo !== NULL && array_key_exists('certData', $certInfo)) { $metaArray['certData'] = $certInfo['certData']; } $metaArray['NameIDFormat'] = $spmeta->getString('NameIDFormat', 'urn:mace:shibboleth:1.0:nameIdentifier'); if ($spmeta->hasValue('OrganizationName')) { $metaArray['OrganizationName'] = $spmeta->getLocalizedString('OrganizationName'); $metaArray['OrganizationDisplayName'] = $spmeta->getLocalizedString('OrganizationDisplayName', $metaArray['OrganizationName']); if (!$spmeta->hasValue('OrganizationURL')) { throw new SimpleSAML_Error_Exception('If OrganizationName is set, OrganizationURL must also be set.'); } $metaArray['OrganizationURL'] = $spmeta->getLocalizedString('OrganizationURL'); } if ($spmeta->hasValue('attributes')) { $metaArray['attributes'] = $spmeta->getArray('attributes'); }
protected function createLogoutRequest($testrun, $samlResponse) { $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']; $lr = sspmod_fedlab_xml_Message::buildLogoutRequest($idpMetadata, $spMetadata); // $lr->setSessionIndex($association['saml:SessionIndex']); // $lr->setNameId($association['saml:NameID']); $lr->setSessionIndex($this->getSessionIndex($testrun, $samlResponse['SessionIndex'])); $lr->setNameId($this->getNameID($testrun, $samlResponse['NameID'])); if ($this->signRequest($testrun)) { $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); $lr->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]'); } $lr->setCertificates(array($certArray['PEM'])); } $this->tweakLogoutRequest($testrun, $lr); $msgStr = $lr->toSignedXML(); $this->tweakLogoutRequestDOM($testrun, $msgStr); $msgStr = $msgStr->ownerDocument->saveXML($msgStr); # echo '<pre>'; echo(htmlspecialchars($msgStr)); exit; # $msgStr = base64_encode($msgStr); # $msgStr = htmlspecialchars($msgStr); return array('url' => $consumerURL, 'Request' => $msgStr, 'RequestObj' => $lr); }
<?php $config = SimpleSAML_Configuration::getInstance(); #$statconfig = SimpleSAML_Configuration::getConfig('module_statistics.php'); $session = SimpleSAML_Session::getInstance(); $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); $idpentityid = SimpleSAML_Utilities::getBaseURL() . 'module.php/fedlab'; $metaArray = array('metadata-set' => 'saml20-idp-remote', 'entityid' => $idpentityid, 'SingleSignOnService' => SimpleSAML_Utilities::getBaseURL() . 'module.php/fedlab/SingleSignOnService.php', 'SingleLogoutService' => SimpleSAML_Utilities::getBaseURL() . 'module.php/fedlab/SingleLogoutService.php', 'certificate' => 'server.crt'); $metaArrayConfig = SimpleSAML_Configuration::loadFromArray($metaArray); $certInfo = SimpleSAML_Utilities::loadPublicKey($metaArrayConfig, TRUE); $metaBuilder = new SimpleSAML_Metadata_SAMLBuilder($idpentityid); $metaBuilder->addMetadataIdP20($metaArray); $metaBuilder->addOrganizationInfo($metaArray); $metaBuilder->addContact('technical', array('emailAddress' => $config->getString('technicalcontact_email', NULL), 'name' => $config->getString('technicalcontact_name', NULL))); $metaxml = $metaBuilder->getEntityDescriptorText(); if (isset($_REQUEST['xmlmetadata'])) { $session->setData('fedlab', 'xmlmetadata', $_REQUEST['xmlmetadata']); } if (isset($_REQUEST['initurl'])) { $session->setData('fedlab', 'initurl', $_REQUEST['initurl']); } if (isset($_REQUEST['initslo'])) { $session->setData('fedlab', 'initslo', $_REQUEST['initslo']); } $xmldata = $session->getData('fedlab', 'xmlmetadata'); $initurl = $session->getData('fedlab', 'initurl'); $initslo = $session->getData('fedlab', 'initslo'); if (isset($_REQUEST['output']) && $_REQUEST['output'] == 'xml') { header('Content-type: text/xml'); echo $metaxml; exit;
/** * This function sends the SOAP message to the service location and returns SOAP response * * @param SAML2_Message $msg The request that should be sent. * @param SimpleSAML_Configuration $srcMetadata The metadata of the issuer of the message. * @param SimpleSAML_Configuration $dstMetadata The metadata of the destination of the message. * @return SAML2_Message The response we received. * @throws Exception */ public function send(SAML2_Message $msg, SimpleSAML_Configuration $srcMetadata, SimpleSAML_Configuration $dstMetadata = NULL) { $issuer = $msg->getIssuer(); $ctxOpts = array('ssl' => array('capture_peer_cert' => TRUE)); /* Determine if we are going to do a MutualSSL connection between the IdP and SP - Shoaib */ if ($srcMetadata->hasValue('saml.SOAPClient.certificate')) { $cert = $srcMetadata->getValue('saml.SOAPClient.certificate'); if ($cert !== FALSE) { $ctxOpts['ssl']['local_cert'] = SimpleSAML_Utilities::resolveCert($srcMetadata->getString('saml.SOAPClient.certificate')); if ($srcMetadata->hasValue('saml.SOAPClient.privatekey_pass')) { $ctxOpts['ssl']['passphrase'] = $srcMetadata->getString('saml.SOAPClient.privatekey_pass'); } } } else { /* Use the SP certificate and privatekey if it is configured. */ $privateKey = SimpleSAML_Utilities::loadPrivateKey($srcMetadata); $publicKey = SimpleSAML_Utilities::loadPublicKey($srcMetadata); if ($privateKey !== NULL && $publicKey !== NULL && isset($publicKey['PEM'])) { $keyCertData = $privateKey['PEM'] . $publicKey['PEM']; $file = SimpleSAML_Utilities::getTempDir() . '/' . sha1($keyCertData) . '.pem'; if (!file_exists($file)) { SimpleSAML_Utilities::writeFile($file, $keyCertData); } $ctxOpts['ssl']['local_cert'] = $file; if (isset($privateKey['password'])) { $ctxOpts['ssl']['passphrase'] = $privateKey['password']; } } } /* Do peer certificate verification */ if ($dstMetadata !== NULL) { $peerPublicKeys = $dstMetadata->getPublicKeys('signing', TRUE); $certData = ''; foreach ($peerPublicKeys as $key) { if ($key['type'] !== 'X509Certificate') { continue; } $certData .= "-----BEGIN CERTIFICATE-----\n" . chunk_split($key['X509Certificate'], 64) . "-----END CERTIFICATE-----\n"; } $peerCertFile = SimpleSAML_Utilities::getTempDir() . '/' . sha1($certData) . '.pem'; if (!file_exists($peerCertFile)) { SimpleSAML_Utilities::writeFile($peerCertFile, $certData); } /* Create ssl context */ $ctxOpts['ssl']['verify_peer'] = TRUE; $ctxOpts['ssl']['verify_depth'] = 1; $ctxOpts['ssl']['cafile'] = $peerCertFile; } $ctxOpts['http']['header'] = 'SOAPAction: "http://www.oasis-open.org/committees/security"' . "\n"; if ($this->username !== NULL && $this->password !== NULL) { /* Add HTTP Basic authentication header. */ $authData = $this->username . ':' . $this->password; $authData = base64_encode($authData); $ctxOpts['http']['header'] .= 'Authorization: Basic ' . $authData . "\n"; } if ($srcMetadata->hasValue('saml.SOAPClient.proxyhost')) { $options['proxy_host'] = $srcMetadata->getValue('saml.SOAPClient.proxyhost'); } if ($srcMetadata->hasValue('saml.SOAPClient.proxyport')) { $options['proxy_port'] = $srcMetadata->getValue('saml.SOAPClient.proxyport'); } $x = new SoapClient(NULL, $options); /* Add soap-envelopes */ $request = $msg->toSignedXML(); $request = self::START_SOAP_ENVELOPE . $request->ownerDocument->saveXML($request) . self::END_SOAP_ENVELOPE; SAML2_Utils::getContainer()->debugMessage($request, 'out'); $ctxOpts['http']['content'] = $request; $ctxOpts['http']['header'] .= 'Content-Type: text/xml; charset=utf-8' . "\n"; $ctxOpts['http']['method'] = 'POST'; $destination = $msg->getDestination(); /* Perform SOAP Request over HTTP */ $context = stream_context_create($ctxOpts); if ($context === NULL) { throw new Exception('Unable to create stream context'); } $soapresponsexml = @file_get_contents($destination, FALSE, $context); if ($soapresponsexml === FALSE) { throw new Exception('Error processing SOAP call: ' . SimpleSAML_Utilities::getLastError()); } SAML2_Utils::getContainer()->debugMessage($soapresponsexml, 'in'); /* Convert to SAML2_Message (DOMElement) */ try { $dom = SAML2_DOMDocumentFactory::fromString($soapresponsexml); } catch (SAML2_Exception_RuntimeException $e) { throw new Exception('Not a SOAP response.', 0, $e); } $soapfault = $this->getSOAPFault($dom); if (isset($soapfault)) { throw new Exception($soapfault); } /* Extract the message from the response */ $samlresponse = SAML2_Utils::xpQuery($dom->firstChild, '/soap-env:Envelope/soap-env:Body/*[1]'); $samlresponse = SAML2_Message::fromXML($samlresponse[0]); /* Add validator to message which uses the SSL context. */ self::addSSLValidator($samlresponse, $context); SAML2_Utils::getContainer()->getLogger()->debug("Valid ArtifactResponse received from IdP"); return $samlresponse; }
protected function createResponse($testrun, $request, $relayState = NULL) { $this->log($testrun, 'Creating response with relaystate [' . $relayState . ']'); $idpMetadata = SimpleSAML_Configuration::loadFromArray($this->idpmetadata); $spMetadata = SimpleSAML_Configuration::loadFromArray($this->metadata); $requestId = $request->getId(); $consumerURL = $request->getAssertionConsumerServiceURL(); $spentityid = $spMetadata->getString('entityid'); $idpentityid = $idpMetadata->getString('entityid'); $consumerURLf = $spMetadata->getDefaultEndpoint('AssertionConsumerService', array('urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST'), $consumerURL); $consumerURL = $consumerURLf['Location']; # print_r($spMetadata); exit; # print_r($spMetadata->getString('AssertionConsumerServiceURL')) $protocolBinding = SAML2_Const::BINDING_HTTP_POST; $config = $this->getConfig($testrun); $authnInstant = time(); // Build assertion $a = new sspmod_fedlab_xml_Assertion(); if ($config['signAssertion']) { $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); $a->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]'); } $a->setCertificates(array($certArray['PEM'])); } $a->includeAuthn = $config['includeAuthn']; $a->addSubjectConfirmationData = $config['addSubjectConfirmationData']; $a->iterateSubjectConfirmationData = $config['iterateSubjectConfirmationData']; $a->subjectAddresses = $this->getAddresses($testrun, array(NULL)); if (isset($config['dateFormat'])) { $a->dateformat = $config['dateFormat']; } $a->setIssueInstant(time() + $config['issueInstantMod']); $a->extracondition = $config['extracondition']; $a->setIssuer($this->getIssuerAssertion($testrun, $idpentityid)); $a->setDestination($this->getDestinationAssertion($testrun, array($consumerURL))); $a->setValidAudiences($this->getValidAudience($testrun, array(array($spentityid)))); $a->setNotBefore(time() + $config['notBeforeSkew']); $assertionLifetime = $config['assertionLifetime']; $a->setNotOnOrAfter(time() + $assertionLifetime); $a->notOnOrAfterSubjectConfirmationData = time() + $config['SubjectConfirmationDataLifetime']; $a->setAuthnContext($this->getAuthnContext($testrun, SAML2_Const::AC_PASSWORD)); $a->setAuthnInstant($authnInstant); $sessionLifetime = $config['sessionLifetime']; $a->setSessionNotOnOrAfter(time() + $sessionLifetime); $sessionIndex = SimpleSAML_Utilities::generateID(); $a->setSessionIndex($sessionIndex); /* Add attributes. */ $attributeNameFormat = $config['attributeNameFormat']; $a->setAttributeNameFormat($attributeNameFormat); $attributes = array('urn:oid:1.3.6.1.4.1.5923.1.1.1.6' => array('*****@*****.**'), 'urn:mace:dir:attribute-def:eduPersonPrincipalName' => array('*****@*****.**')); $a->setAttributes($attributes); $nameId = array('Format' => $config['nameIdFormat'], 'SPNameQualifier' => $spentityid, 'Value' => SimpleSAML_Utilities::generateID()); $a->setNameId($nameId); // Assertion builded.... # print_r($requestId); $inresponseto = $this->getInResponseToAssertion($testrun, $requestId); if (!empty($inresponseto)) { $a->setInResponseTo($inresponseto); } // $assertion->setAuthenticatingAuthority($state['saml:AuthenticatingAuthority']); /* Maybe encrypt the assertion. */ // $a = sspmod_saml2_Message::encryptAssertion($idpMetadata, $spMetadata, $a); // Build the response $signResponse = $config['signResponse']; $response = new sspmod_fedlab_xml_Response(); $response->setIssuer($this->getIssuerResponse($testrun, $idpentityid)); $response->setDestination($this->getDestinationResponse($testrun, $consumerURL)); if ($signResponse) { // self::addSign($srcMetadata, $dstMetadata, $r); $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'])); } $inresponseto = $this->getInResponseToResponse($testrun, $requestId); if (!empty($inresponseto)) { $response->setInResponseTo($inresponseto); } $response->setRelayState($this->getRelayState($testrun, $relayState)); $response->setAssertions(array($a)); $this->tweakResponse($testrun, $response); $msgStr = $response->toSignedXML(); $this->tweakResponseDOM($testrun, $msgStr); $msgStr = $msgStr->ownerDocument->saveXML($msgStr); $this->tweakResponseText($testrun, $msgStr); # echo '<pre>'; echo(htmlspecialchars($msgStr)); exit; # $msgStr = base64_encode($msgStr); # $msgStr = htmlspecialchars($msgStr); return array('url' => $consumerURL, 'Response' => $msgStr, 'NameID' => $nameId, 'SessionIndex' => $sessionIndex, 'RelayState' => $relayState); }
throw new SimpleSAML_Error_NotFound('Could not find authentication source with id ' . $sourceId); } if (!$source instanceof sspmod_saml_Auth_Source_SP) { throw new SimpleSAML_Error_NotFound('Source isn\'t a SAML SP: ' . var_export($sourceId, TRUE)); } $entityId = $source->getEntityId(); $metaArray11 = array('AssertionConsumerService' => SimpleSAML_Module::getModuleURL('saml/sp/saml1-acs.php/' . $sourceId)); $spconfig = $source->getMetadata(); if ($spconfig->getBoolean('saml11.binding.artifact.enable', FALSE)) { $metaArray11['AssertionConsumerService.artifact'] = SimpleSAML_Module::getModuleURL('saml/sp/saml1-acs.php/' . $sourceId . '/artifact'); } $metaArray20 = array('AssertionConsumerService' => SimpleSAML_Module::getModuleURL('saml/sp/saml2-acs.php/' . $sourceId), 'SingleLogoutService' => SimpleSAML_Module::getModuleURL('saml/sp/saml2-logout.php/' . $sourceId)); if ($spconfig->getBoolean('saml20.binding.artifact.enable', FALSE)) { $metaArray20['AssertionConsumerService.artifact'] = SimpleSAML_Module::getModuleURL('saml/sp/saml2-acs.php/' . $sourceId); } $certInfo = SimpleSAML_Utilities::loadPublicKey($spconfig->toArray()); if ($certInfo !== NULL && array_key_exists('certData', $certInfo)) { $certData = $certInfo['certData']; $metaArray11['certData'] = $certData; $metaArray20['certData'] = $certData; } $metaBuilder = new SimpleSAML_Metadata_SAMLBuilder($entityId); $metaBuilder->addMetadataSP11($metaArray11); $metaBuilder->addMetadataSP20($metaArray20); $config = SimpleSAML_Configuration::getInstance(); $metaBuilder->addContact('technical', array('emailAddress' => $config->getString('technicalcontact_email', NULL), 'name' => $config->getString('technicalcontact_name', NULL))); $xml = $metaBuilder->getEntityDescriptorText(); if (array_key_exists('output', $_REQUEST) && $_REQUEST['output'] == 'xhtml') { $t = new SimpleSAML_XHTML_Template($config, 'metadata.php', 'admin'); $t->data['header'] = 'saml20-sp'; $t->data['metadata'] = htmlspecialchars($xml);
/** * Add certificate. * * Helper function for adding a certificate to the metadata. * * @param DOMElement $ssoDesc The IDPSSODescroptor or SPSSODecriptor the certificate * should be added to. * @param array $metadata The metadata for the entity. */ private function addCertificate(DOMElement $ssoDesc, $metadata) { assert('is_array($metadata)'); $certInfo = SimpleSAML_Utilities::loadPublicKey($metadata); if ($certInfo === NULL || !array_key_exists('certData', $certInfo)) { /* No certificate to add. */ return; } $certData = $certInfo['certData']; $this->addX509KeyDescriptor($ssoDesc, 'signing', $certData); $this->addX509KeyDescriptor($ssoDesc, 'encryption', $certData); }