/** * Helper function for handling exception/errors. * * This function will send an error response to the SP which contacted this IdP. * * @param Exception $exception The exception. */ function handleError(Exception $exception) { global $requestcache, $config, $metadata, $idpentityid; assert('is_array($requestcache)'); assert('array_key_exists("Issuer", $requestcache)'); $issuer = $requestcache['Issuer']; if (array_key_exists('RequestID', $requestcache)) { $requestID = $requestcache['RequestID']; } else { $requestID = NULL; } if (array_key_exists('RelayState', $requestcache)) { $relayState = $requestcache['RelayState']; } else { $relayState = NULL; } $error = sspmod_saml2_Error::fromException($exception); SimpleSAML_Logger::warning('Returning error to sp: ' . var_export($issuer, TRUE)); $error->logWarning(); try { $idpMetadata = $metadata->getMetaDataConfig($idpentityid, 'saml20-idp-hosted'); $spMetadata = $metadata->getMetaDataConfig($issuer, 'saml20-sp-remote'); if (array_key_exists('ConsumerURL', $requestcache)) { $consumerURL = $requestcache['ConsumerURL']; } else { $urlArray = $spMetadata->getArrayizeString('AssertionConsumerService'); $consumerURL = $urlArray[0]; } $ar = sspmod_saml2_Message::buildResponse($idpMetadata, $spMetadata, $consumerURL); $ar->setInResponseTo($requestID); $ar->setRelayState($relayState); $ar->setStatus(array('Code' => $error->getStatus(), 'SubCode' => $error->getSubStatus(), 'Message' => $error->getStatusMessage())); $binding = new SAML2_HTTPPost(); $binding->setDestination(sspmod_SAML2_Message::getDebugDestination()); $binding->send($ar); } catch (Exception $e) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'GENERATEAUTHNRESPONSE', $e); } }
* Load the RelayState argument. The RelayState argument contains the address * we should redirect the user to after a successful authentication. */ if (!array_key_exists('RelayState', $_REQUEST)) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE'); } $relaystate = $_REQUEST['RelayState']; if ($username = $_POST['username']) { try { $ldap = new SimpleSAML_Auth_LDAP($ldapconfig['servers'], $ldapconfig['enable_tls']); $attributes = $ldap->validate($ldapconfig, $username, $_POST['password']); if ($attributes === FALSE) { $error = "LDAP_INVALID_CREDENTIALS"; } else { $session->doLogin('login-wayf-ldap'); $session->setAttributes($attributes); $session->setNameID(array('value' => SimpleSAML_Utilities::generateID(), 'Format' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient')); SimpleSAML_Utilities::redirect($relaystate); } } catch (Exception $e) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'LDAPERROR', $e); } } $t = new SimpleSAML_XHTML_Template($config, $ldapconfig['template']); $t->data['header'] = 'simpleSAMLphp: Enter username and password'; $t->data['relaystate'] = htmlspecialchars($relaystate); $t->data['error'] = $error; if (isset($error)) { $t->data['username'] = htmlspecialchars($username); } $t->show();
if (array_key_exists('url', $idpmeta)) { $metaArray['url'] = $idpmeta['url']; } if (array_key_exists('scope', $idpmeta)) { $metaArray['scope'] = $idpmeta['scope']; } $metaflat = '$metadata[' . var_export($idpentityid, TRUE) . '] = ' . var_export($metaArray, TRUE) . ';'; $metaArray['certData'] = $certInfo['certData']; $metaBuilder = new SimpleSAML_Metadata_SAMLBuilder($idpentityid); $metaBuilder->addMetadataIdP20($metaArray); $metaBuilder->addContact('technical', array('emailAddress' => $config->getString('technicalcontact_email', NULL), 'name' => $config->getString('technicalcontact_name', NULL))); $metaxml = $metaBuilder->getEntityDescriptorText(); /* Sign the metadata if enabled. */ $metaxml = SimpleSAML_Metadata_Signer::sign($metaxml, $idpmeta, 'SAML 2 IdP'); if (array_key_exists('output', $_GET) && $_GET['output'] == 'xhtml') { $defaultidp = $config->getString('default-saml20-idp', NULL); $t = new SimpleSAML_XHTML_Template($config, 'metadata.php', 'admin'); $t->data['header'] = 'saml20-idp'; $t->data['metaurl'] = SimpleSAML_Utilities::selfURLNoQuery(); $t->data['metadata'] = htmlentities($metaxml); $t->data['metadataflat'] = htmlentities($metaflat); $t->data['defaultidp'] = $defaultidp; $t->show(); } else { header('Content-Type: application/xml'); echo $metaxml; exit(0); } } catch (Exception $exception) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'METADATA', $exception); }
$casusername = $success->item(0)->textContent; return array($casusername, $attributes); } } else { throw new Exception("validate or serviceValidate not specified"); } /** * First request, will redirect the user to the CAS server for authentication. */ } else { SimpleSAML_Logger::info("AUTH - cas-ldap: redirecting to {$cas['login']}"); SimpleSAML_Utilities::redirect($cas['login'], array('service' => $service)); } } try { $relaystate = $_REQUEST['RelayState']; list($username, $casattributes) = casValidate($casconfig); SimpleSAML_Logger::info('AUTH - cas-ldap: ' . $username . ' authenticated by ' . $casconfig['validate']); $ldapattributes = array(); if ($ldapconfig['servers']) { $ldap = new SimpleSAML_Auth_LDAP($ldapconfig['servers'], $ldapconfig['enable_tls']); $ldapattributes = $ldap->validate($ldapconfig, $username); } $attributes = array_merge_recursive($casattributes, $ldapattributes); $session->doLogin('login-cas-ldap'); $session->setAttributes($attributes); $session->setNameID(array('value' => SimpleSAML_Utilities::generateID(), 'Format' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient')); SimpleSAML_Utilities::redirect($relaystate); } catch (Exception $exception) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'CASERROR', $exception); }
/** * Accept a SAML Request and form a Response * NOTE: that this function is Google Specific * */ function gsaml_send_auth_response($samldata) { global $CFG, $SESSION, $USER; SimpleSAML_Configuration::init($CFG->dirroot . '/auth/gsaml/config'); $config = SimpleSAML_Configuration::getInstance(); $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); $session = SimpleSAML_Session::getInstance(); try { $idpentityid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted'); $idmetaindex = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted', 'metaindex'); $idpmetadata = $metadata->getMetaDataCurrent('saml20-idp-hosted'); if (!array_key_exists('auth', $idpmetadata)) { throw new Exception('Missing mandatory parameter in SAML 2.0 IdP Hosted Metadata: [auth]'); } } catch (Exception $exception) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'METADATA', $exception); } /// SimpleSAML_Logger::info('SAML2.0 - IdP.SSOService: Accessing SAML 2.0 IdP endpoint SSOService'); if (!$config->getValue('enable.saml20-idp', false)) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS'); } $rawRequest = $samldata; if (!empty($SESSION->samlrelaystate)) { $relaystate = $SESSION->samlrelaystate; } else { $relaystate = NULL; } $decodedRequest = @base64_decode($rawRequest); if (!$decodedRequest) { throw new Exception('Could not base64 decode SAMLRequest GET parameter'); } $samlRequestXML = @gzinflate($decodedRequest); if (!$samlRequestXML) { $error = error_get_last(); throw new Exception('Could not gzinflate base64 decoded SAMLRequest: ' . $error['message']); } SimpleSAML_Utilities::validateXMLDocument($samlRequestXML, 'saml20'); $samlRequest = new SimpleSAML_XML_SAML20_AuthnRequest($config, $metadata); $samlRequest->setXML($samlRequestXML); if (!is_null($relaystate)) { $samlRequest->setRelayState($relaystate); } // $samlRequest presenting the request object $authnrequest = $samlRequest; if ($session == NULL) { debugging('No SAML Session gsaml_send_auth_response', DEBUG_DEVELOPER); return false; // if this func returns we Know it's an error } if (!empty($USER->id)) { // TODO: if moodle user is not the same as google user // use the mapping $username = $USER->username; } else { debugging('No User given to gsaml_send_auth_response', DEBUG_DEVELOPER); return false; } //TODO: better errors if (!($domain = get_config('auth/gsaml', 'domainname'))) { debugging('No domain set in gsaml_send_auth_response', DEBUG_DEVELOPER); return false; // if this func returns we Know it's an error } $attributes['useridemail'] = array($username . '@' . $domain); $session->doLogin('login'); // was login $session->setAttributes($attributes); $session->setNameID(array('value' => SimpleSAML_Utilities::generateID(), 'Format' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient')); $requestcache = array('RequestID' => $authnrequest->getRequestID(), 'Issuer' => $authnrequest->getIssuer(), 'ConsentCookie' => SimpleSAML_Utilities::generateID(), 'RelayState' => $authnrequest->getRelayState()); try { $spentityid = $requestcache['Issuer']; $spmetadata = $metadata->getMetaData($spentityid, 'saml20-sp-remote'); $sp_name = isset($spmetadata['name']) ? $spmetadata['name'] : $spentityid; // TODO: Are we really tracking SP's??? // // Adding this service provider to the list of sessions. // Right now the list is used for SAML 2.0 only. $session->add_sp_session($spentityid); /// SimpleSAML_Logger::info('SAML2.0 - IdP.SSOService: Sending back AuthnResponse to ' . $spentityid); // TODO: handle passive situtation // Rigth now I replaced $isPassive with isset($isPassive) to prevent notice on debug mode if (isset($isPassive)) { /* Generate an SAML 2.0 AuthNResponse message With statusCode: urn:oasis:names:tc:SAML:2.0:status:NoPassive */ $ar = new SimpleSAML_XML_SAML20_AuthnResponse($config, $metadata); $authnResponseXML = $ar->generate($idpentityid, $spentityid, $requestcache['RequestID'], null, array(), 'NoPassive'); // Sending the AuthNResponse using HTTP-Post SAML 2.0 binding $httppost = new SimpleSAML_Bindings_SAML20_HTTPPost($config, $metadata); $httppost->sendResponse($authnResponseXML, $idpentityid, $spentityid, $requestcache['RelayState']); exit; } /* * Attribute handling */ $attributes = $session->getAttributes(); $afilter = new SimpleSAML_XML_AttributeFilter($config, $attributes); $afilter->process($idpmetadata, $spmetadata); // KEEP this code for REFERENCE // /** // * Make a log entry in the statistics for this SSO login. // */ // $tempattr = $afilter->getAttributes(); // $realmattr = $config->getValue('statistics.realmattr', null); // $realmstr = 'NA'; // if (!empty($realmattr)) { // //error_log('SSO 420: if (!empty($realmattr)) {\n ',0); // if (array_key_exists($realmattr, $tempattr) && is_array($tempattr[$realmattr]) ) { // $realmstr = $tempattr[$realmattr][0]; // } else { // SimpleSAML_Logger::warning('Could not get realm attribute to log [' . $realmattr. ']'); // } // } // SimpleSAML_Logger::stats('saml20-idp-SSO ' . $spentityid . ' ' . $idpentityid . ' ' . $realmstr); // // $afilter->processFilter($idpmetadata, $spmetadata); $filteredattributes = $afilter->getAttributes(); // // KEEP THIS CODE FOR RERFERENCE // /* // * Dealing with attribute release consent. // */ // $requireconsent = false; // if (isset($idpmetadata['requireconsent'])) { // //error_log('SSO 453: if (isset($idpmetadata[\'requireconsent\']))\n ',0); // if (is_bool($idpmetadata['requireconsent'])) { // $requireconsent = $idpmetadata['requireconsent']; // } else { // throw new Exception('SAML 2.0 IdP hosted metadata parameter [requireconsent] is in illegal format, must be a PHP boolean type.'); // } // } // if ($requireconsent) { // // $consent = new SimpleSAML_Consent_Consent($config, $session, $spentityid, $idpentityid, $attributes, $filteredattributes, $requestcache['ConsentCookie']); // // if (!$consent->consent()) { // /* Save the request information. */ // $authId = SimpleSAML_Utilities::generateID(); // $session->setAuthnRequest('saml2', $authId, $requestcache); // // $t = new SimpleSAML_XHTML_Template($config, 'consent.php', 'attributes.php'); // $t->data['header'] = 'Consent'; // $t->data['sp_name'] = $sp_name; // $t->data['attributes'] = $filteredattributes; // $t->data['consenturl'] = SimpleSAML_Utilities::selfURLNoQuery();//$selfURLNoQuery; //SimpleSAML_Utilities::selfURLNoQuery(); DEBUG // $t->data['requestid'] = $authId; // $t->data['consent_cookie'] = $requestcache['ConsentCookie']; // $t->data['usestorage'] = $consent->useStorage(); // $t->data['noconsent'] = '/' . $config->getBaseURL() . 'noconsent.php'; // $t->show(); // exit; // } // // } // // END ATTRIBUTE CONSENT CODE // Generate the SAML 2.0 AuthNResponse message $ar = new SimpleSAML_XML_SAML20_AuthnResponse($config, $metadata); $authnResponseXML = $ar->generate($idpentityid, $spentityid, $requestcache['RequestID'], null, $filteredattributes); // TODO: clean the $SESSION->samlrelaystate so we don't accidently call it again // Sending the AuthNResponse using HTTP-Post SAML 2.0 binding $httppost = new SimpleSAML_Bindings_SAML20_HTTPPost($config, $metadata); $httppost->sendResponse($authnResponseXML, $idmetaindex, $spentityid, $requestcache['RelayState']); die; // VERY IMPORTANT BUG FIX to stop outputing the rest of the page. } catch (Exception $exception) { // TODO: better error reporting debugging('<pre>' . print_r($exception, true) . '</pre>', DEBUG_DEVELOPER); return false; } }
} /* Transpose from $entities[entityid][type] to $output[type][entityid]. */ $output = SimpleSAML_Utilities::transposeArray($entities); /* Merge all metadata of each type to a single string which should be * added to the corresponding file. */ foreach ($output as $type => &$entities) { $text = ''; foreach ($entities as $entityId => $entityMetadata) { if ($entityMetadata === NULL) { continue; } /* Remove the entityDescriptor element because it is unused, and only * makes the output harder to read. */ unset($entityMetadata['entityDescriptor']); $text .= '$metadata[' . var_export($entityId, TRUE) . '] = ' . var_export($entityMetadata, TRUE) . ";\n"; } $entities = $text; } } else { $xmldata = ''; $output = array(); } $template = new SimpleSAML_XHTML_Template($config, 'metadata-converter.php', 'admin'); $template->data['xmldata'] = $xmldata; $template->data['output'] = $output; $template->show(); } catch (Exception $exception) { SimpleSAML_Utilities::fatalError('', 'METADATA_PARSER', $exception); }
if (!SimpleSAML_Utilities::checkDateConditions($notBefore, $notOnOrAfter)) { throw new Exception('The response has expired.'); } } /* Extract the name identifier from the response. */ $nameid = $xpath->query('./saml:AuthenticationStatement/saml:Subject/saml:NameIdentifier', $assertion); if ($nameid->length === 0) { throw new Exception('Could not find the name identifier in the response from the WS-Fed IdP \'' . $idpEntityId . '\'.'); } $nameid = array('Format' => $nameid->item(0)->getAttribute('Format'), 'value' => $nameid->item(0)->textContent); /* Extract the attributes from the response. */ $attributes = array(); $attributeValues = $xpath->query('./saml:AttributeStatement/saml:Attribute/saml:AttributeValue', $assertion); foreach ($attributeValues as $attribute) { $name = $attribute->parentNode->getAttribute('AttributeName'); $value = $attribute->textContent; if (!array_key_exists($name, $attributes)) { $attributes[$name] = array(); } $attributes[$name][] = $value; } /* Mark the user as logged in. */ $session->doLogin('wsfed'); $session->setAttributes($attributes); $session->setNameID($nameid); $session->setIdP($idpEntityId); /* Redirect the user back to the page which requested the login. */ SimpleSAML_Utilities::redirect($wctx); } catch (Exception $exception) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'PROCESSASSERTION', $exception); }
if (!$config->getBoolean('enable.saml20-idp', false)) { SimpleSAML_Utilities::fatalError(isset($session) ? $session->getTrackID() : null, 'NOACCESS'); } try { $idpentityid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted'); } catch (Exception $exception) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'METADATA', $exception); } SimpleSAML_Logger::debug('SAML2.0 - IdP.SingleLogoutServiceiFrame: Got IdP entity id: ' . $idpentityid); $logouttype = 'traditional'; $idpmeta = $metadata->getMetaDataCurrent('saml20-idp-hosted'); if (array_key_exists('logouttype', $idpmeta)) { $logouttype = $idpmeta['logouttype']; } if ($logouttype !== 'iframe') { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS', new Exception('This IdP is configured to use logout type [' . $logouttype . '], but this endpoint is only available for IdP using logout type [iframe]')); } SimpleSAML_Logger::info('SAML2.0 - IdP.SingleLogoutServiceiFrameNoJavascript: Accessing SAML 2.0 IdP endpoint SingleLogoutService (iFrame version without javascript support) '); $config = SimpleSAML_Configuration::getInstance(); $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); $session = SimpleSAML_Session::getInstance(); $idpentityid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted'); $templistofsps = $session->get_sp_list(SimpleSAML_Session::STATE_ONLINE); $listofsps = array(); foreach ($templistofsps as $spentityid) { if (!empty($_COOKIE['spstate-' . sha1($spentityid)])) { $listofsps[] = $spentityid; } } if (count($templistofsps) === count($listofsps)) { $templistofsps = $session->get_sp_list(SimpleSAML_Session::STATE_ONLINE);
* AUTHOR: Samuel Muñoz Hidalgo * EMAIL: samuel.mh@gmail.com * LAST REVISION: 13-FEB-09 * DESCRIPTION: * Pretty form to get a managed InfoCard * User flow controller. * Displays the template and request a non null xmlToken */ /* Load the configuration. */ $config = SimpleSAML_Configuration::getInstance(); $autoconfig = $config->copyFromBase('logininfocard', 'config-login-infocard.php'); $Infocard = $autoconfig->getValue('InfoCard'); /* Load the session of the current user. */ $session = SimpleSAML_Session::getInstance(); if ($session == NULL) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOSESSION'); } if (!array_key_exists('AuthState', $_REQUEST)) { SimpleSAML_Logger::debug('NO AUTH STATE'); SimpleSAML_Logger::debug('ERROR: NO AUTH STATE'); throw new SimpleSAML_Error_BadRequest('Missing AuthState parameter.'); } else { $authStateId = $_REQUEST['AuthState']; SimpleSAML_Logger::debug('AUTH STATE: ' . $authStateId); } $username = null; $password = null; $state = "validate"; if (array_key_exists('form', $_POST) && $_POST['form'] != NULL) { if (array_key_exists('username', $_POST) && $_POST['username'] != NULL) { if (array_key_exists('password', $_POST) && $_POST['password'] != NULL) {
SimpleSAML_Logger::debug('SAML2.0 - IdP.SingleLogoutServiceiFrame: Got IdP entity id: ' . $idpEntityId); $logouttype = $idpMetadata->getString('logouttype', 'traditional'); if ($logouttype !== 'iframe') { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS', new Exception('This IdP is configured to use logout type [' . $logouttype . '], but this endpoint is only available for IdP using logout type [iframe]')); } if (!isset($_REQUEST['SAMLResponse'])) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'SLOSERVICEPARAMS', new Exception('No valid SAMLResponse found? Probably some error in remote partys metadata that sends something to this endpoint that is not SAML LogoutResponses')); } $binding = SAML2_Binding::getCurrentBinding(); $logoutResponse = $binding->receive(); if (!$logoutResponse instanceof SAML2_LogoutResponse) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'SLOSERVICEPARAMS', new Exception('Message received on response endpoint wasn\'t a response. Was: ' . get_class($logoutResponse))); } $spEntityId = $logoutResponse->getIssuer(); if ($spEntityId === NULL) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'SLOSERVICEPARAMS', new Exception('Missing issuer on logout response.')); } $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'saml20-sp-remote'); sspmod_saml2_Message::validateMessage($spMetadata, $idpMetadata, $logoutResponse); $sphash = sha1($spEntityId); setcookie('spstate-' . $sphash, '1'); // Duration: 2 hours SimpleSAML_Logger::info('SAML2.0 - IdP.SingleLogoutServiceiFrameResponse: Logging out completed'); echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Logout OK</title> </head> <body>OK</body>
$groupsAttr = $amc->getGroupsAttr(); if ($groupsAttr !== NULL) { if (!array_key_exists($groupsAttr, $attributes)) { throw new Exception('The user doesn\'t have an attribute named \'' . $groupsAttr . '\'. This attribute is expected to contain the groups the user is a member of.'); } $authData['Groups'] = $attributes[$groupsAttr]; } else { $authData['Groups'] = array(); } $authData['RemoteIP'] = $_SERVER['REMOTE_ADDR']; foreach ($attributes as $n => $v) { $authData['ATTR_' . $n] = $v; } /* Store the authentication data in the memcache server. */ $data = ''; foreach ($authData as $n => $v) { if (is_array($v)) { $v = implode(':', $v); } $data .= $n . '=' . $v . "\r\n"; } $memcache = $amc->getMemcache(); $expirationTime = $session->remainingTime(); $memcache->set($sessionID, $data, 0, $expirationTime); /* Register logout handler. */ $session->registerLogoutHandler('SimpleSAML_AuthMemCookie', 'logoutHandler'); /* Redirect the user back to this page to signal that the login is completed. */ SimpleSAML_Utilities::redirect(SimpleSAML_Utilities::selfURL()); } catch (Exception $e) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'CONFIG', $e); }
/** * This function processes a response message and adds information from it to the * current session if it is valid. It throws an exception if it is invalid. */ public function process() { $status = $this->findstatus(); if ($status == 'urn:oasis:names:tc:SAML:2.0:status:Success') { /* Find the issuer of this response. */ $this->issuer = $this->findIssuer(); $this->decryptAssertion(); /* Validate the signature element. */ $this->validateSignature(); /* Process all assertions. */ $assertions = $this->doXPathQuery('/samlp:Response/saml:Assertion'); foreach ($assertions as $assertion) { $this->processAssertion($assertion); } if ($this->nameid === NULL) { throw new Exception('No nameID found in AuthnResponse.'); } /* Update the session information */ $session = SimpleSAML_Session::getInstance(); $session->doLogin('saml2'); $session->setAttributes($this->attributes); $session->setNameID($this->nameid); $session->setSessionIndex($this->sessionIndex); $session->setIdP($this->issuer); } elseif ($status == 'urn:oasis:names:tc:SAML:2.0:status:NoPassive') { /* Do not process the authResponse when NoPassive is sent - we continue with an empty set of attributes. Some day we will be able to tell the application what happened */ $session = SimpleSAML_Session::getInstance(); $session->doLogin('saml2'); $session->setAttributes(array()); } else { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'RESPONSESTATUSNOSUCCESS', new Exception("Status = " . $status)); } }
// Extract some parameters from the logout request $requestid = $message->getId(); SimpleSAML_Logger::info('SAML2.0 - SP.SingleLogoutService: IdP (' . $idpEntityId . ') is sending logout request to me SP (' . $spEntityId . ') requestid ' . $requestid); SimpleSAML_Logger::stats('saml20-idp-SLO idpinit ' . $spEntityId . ' ' . $idpEntityId); /* Create response. */ $lr = sspmod_saml2_Message::buildLogoutResponse($spMetadata, $idpMetadata); $lr->setRelayState($message->getRelayState()); $lr->setInResponseTo($message->getId()); SimpleSAML_Logger::info('SAML2.0 - SP.SingleLogoutService: SP me (' . $spEntityId . ') is sending logout response to IdP (' . $idpEntityId . ')'); /* Send response. */ $binding = new SAML2_HTTPRedirect(); $binding->setDestination(sspmod_SAML2_Message::getDebugDestination()); $binding->send($lr); } catch (Exception $exception) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'LOGOUTREQUEST', $exception); } } elseif ($message instanceof SAML2_LogoutResponse) { SimpleSAML_Logger::stats('saml20-sp-SLO spinit ' . $spEntityId . ' ' . $idpEntityId); $id = $message->getRelayState(); if (empty($id)) { /* For backwardscompatibility. */ $id = $message->getInResponseTo(); } $returnTo = $session->getData('spLogoutReturnTo', $id); if (empty($returnTo)) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'LOGOUTINFOLOST'); } SimpleSAML_Utilities::redirect($returnTo); } else { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'SLOSERVICEPARAMS'); }
private static function getMetadata($eid, $revision, $type = null, array $option = null) { assert('ctype_digit($eid)'); assert('ctype_digit($revision)'); $janus_config = sspmod_janus_DiContainer::getInstance()->getConfig(); $entityController = sspmod_janus_DiContainer::getInstance()->getEntityController(); if (!($entity = $entityController->setEntity($eid, $revision))) { self::$_error = array('Entity could not be loaded - Eid: ' . $eid . ' Revisionid: ' . $revision); return false; } $metadata_raw = $entityController->getMetadata(); // Get metadata fields $nm_mb = new sspmod_janus_MetadataFieldBuilder($janus_config->getArray('metadatafields.' . $entity->getType())); $metadatafields_required = $nm_mb->getMetadataFields(); // Get required metadata fields $required = array(); foreach ($metadatafields_required as $mf) { if (isset($mf->required) && $mf->required === true) { $required[] = $mf->name; } } // Get metadata to me tested $metadata = array(); foreach ($metadata_raw as $k => $v) { // Metadata field not defined if (!isset($metadatafields_required[$v->getKey()])) { continue; } // Value not set for metadata if (is_string($v->getValue()) && $v->getValue() == '') { continue; } // Compute is the default values is allowed $default_allow = false; if (isset($metadatafields_required[$v->getKey()]->default_allow) && is_bool($metadatafields_required[$v->getKey()]->default_allow)) { $default_allow = $metadatafields_required[$v->getKey()]->default_allow; } /* * Do not include metadata if value is set to default and default * is not allowed. */ if (!$default_allow && (isset($metadatafields_required[$v->getKey()]->default) && $v->getValue() == $metadatafields_required[$v->getKey()]->default)) { continue; } $metadata[] = $v->getKey(); } // Compute missing metadata that is required $missing_required = array_diff($required, $metadata); $entityId = $entity->getEntityid(); if (!empty($missing_required)) { SimpleSAML_Logger::error('JANUS - Missing required metadata fields. Entity_id:' . $entityId); self::$_error = $missing_required; return false; } try { $metaArray = $entityController->getMetaArray(); $metaArray['eid'] = $eid; $blockedEntities = $entityController->getBlockedEntities(); $allowedEntities = $entityController->getAllowedEntities(); $disabledConsent = $entityController->getDisableConsent(); $metaFlat = '// Revision: ' . $entity->getRevisionid() . "\n"; $metaFlat .= var_export($entityId, TRUE) . ' => ' . var_export($metaArray, TRUE) . ','; // Add authproc filter to block blocked entities if (!empty($blockedEntities) || !empty($allowedEntities)) { $metaFlat = substr($metaFlat, 0, -2); if (!empty($allowedEntities)) { $metaFlat .= " 'allowed' => array(\n"; $metaArray['allowed'] = array(); foreach ($allowedEntities as $allowedEntity) { $metaFlat .= " '" . $allowedEntity['remoteentityid'] . "',\n"; $metaArray['allowed'][] = $allowedEntity['remoteentityid']; } $metaFlat .= " ),\n"; } if (!empty($blockedEntities)) { $metaFlat .= " 'blocked' => array(\n"; $metaArray['blocked'] = array(); foreach ($blockedEntities as $blockedEntity) { $metaFlat .= " '" . $blockedEntity['remoteentityid'] . "',\n"; $metaArray['blocked'][] = $blockedEntity['remoteentityid']; } $metaFlat .= " ),\n"; } $metaFlat .= '),'; } // Add disable consent if (!empty($disabledConsent)) { $metaFlat = substr($metaFlat, 0, -2); $metaFlat .= " 'consent.disable' => array(\n"; foreach ($disabledConsent as $key => $value) { $metaFlat .= " '" . $key . "',\n"; } $metaFlat .= " ),\n"; $metaFlat .= '),'; } $maxCache = isset($option['maxCache']) ? $option['maxCache'] : null; $maxDuration = isset($option['maxDuration']) ? $option['maxDuration'] : null; try { $metaBuilder = new SimpleSAML_Metadata_SAMLBuilder($entityId, $maxCache, $maxDuration); $metaBuilder->addMetadata($metaArray['metadata-set'], $metaArray); } catch (Exception $e) { SimpleSAML_Logger::error('JANUS - Entity_id:' . $entityId . ' - Error generating XML metadata - ' . var_export($e, true)); self::$_error = array('Error generating XML metadata - ' . $e->getMessage()); return false; } // Add organization info if (!empty($metaArray['OrganizationName']) && !empty($metaArray['OrganizationDisplayName']) && !empty($metaArray['OrganizationURL'])) { $metaBuilder->addOrganizationInfo(array('OrganizationName' => $metaArray['OrganizationName'], 'OrganizationDisplayName' => $metaArray['OrganizationDisplayName'], 'OrganizationURL' => $metaArray['OrganizationURL'])); } // Add contact info if (!empty($metaArray['contact'])) { $metaBuilder->addContact('technical', $metaArray['contact']); } switch ($type) { case self::XML: return $metaBuilder->getEntityDescriptor(); case self::XMLREADABLE: return $metaBuilder->getEntityDescriptorText(); case self::PHPARRAY: return $metaArray; case self::FLATFILE: default: return $metaFlat; } } catch (Exception $exception) { $session = SimpleSAML_Session::getInstance(); SimpleSAML_Utilities::fatalError($session->getTrackID(), 'JANUS - Metadatageneration', $exception); return false; } }
/** * Display this error. * * This method displays a standard simpleSAMLphp error page and exits. */ public function show() { $this->setHTTPCode(); $session = SimpleSAML_Session::getInstance(); if ($this->cause !== NULL) { $e = $this->cause; } else { $e = $this; } SimpleSAML_Utilities::fatalError($session->getTrackID(), $this->errorCode, $e); }
require_once '../../_include.php'; $config = SimpleSAML_Configuration::getInstance(); $session = SimpleSAML_Session::getInstance(); SimpleSAML_Logger::info('WS-Fed - SP.initSLO: Accessing WS-Fed SP initSLO script'); if (!$config->getBoolean('enable.wsfed-sp', false)) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS'); } if (isset($_REQUEST['RelayState'])) { $returnTo = $_REQUEST['RelayState']; } else { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE'); } if (isset($session)) { try { $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); $idpentityid = $session->getIdP(); $spentityid = isset($_GET['spentityid']) ? $_GET['spentityid'] : $metadata->getMetaDataCurrentEntityID(); /** * Create a logout request */ $session->doLogout(); SimpleSAML_Logger::info('WS-Fed - SP.initSLO: SP (' . $spentityid . ') is sending logout request to IdP (' . $idpentityid . ')'); $idpmeta = $metadata->getMetaData($idpentityid, 'wsfed-idp-remote'); SimpleSAML_Utilities::redirect($idpmeta['prp'], array('wa' => 'wsignout1.0', 'wct' => gmdate('Y-m-d\\TH:i:s\\Z', time()), 'wtrealm' => $spentityid, 'wctx' => $returnTo)); } catch (Exception $exception) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'CREATEREQUEST', $exception); } } else { SimpleSAML_Logger::info('WS-Fed - SP.initSLO: User is already logged out. Go back to relaystate'); SimpleSAML_Utilities::redirect($returnTo); }
* Clean up session object to save storage. */ if ($config->getBoolean('debug', false)) { SimpleSAML_Logger::info('SAML2.0 - IdP.SingleLogoutService: Session Size before cleaning: ' . $session->getSize()); } $session->clean(); if ($config->getBoolean('debug', false)) { SimpleSAML_Logger::info('SAML2.0 - IdP.SingleLogoutService: Session Size after cleaning: ' . $session->getSize()); } /* * Check if the Single Logout procedure is initated by an SP (alternatively IdP initiated SLO */ if (array_key_exists('Issuer', $logoutInfo)) { $spEntityId = $logoutInfo['Issuer']; $spMetadata = $metadata->getMetadataConfig($spEntityId, 'saml20-sp-remote'); $lr = sspmod_saml2_Message::buildLogoutResponse($idpMetadata, $spMetadata); $lr->setInResponseTo($logoutInfo['RequestID']); $lr->setRelayState($logoutInfo['RelayState']); $binding = new SAML2_HTTPRedirect(); $binding->setDestination(sspmod_SAML2_Message::getDebugDestination()); $binding->send($lr); } elseif (array_key_exists('RelayState', $logoutInfo)) { SimpleSAML_Utilities::redirect($logoutInfo['RelayState']); exit; } else { echo 'You are logged out'; exit; } } catch (Exception $exception) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'GENERATELOGOUTRESPONSE', $exception); }
<?php require_once '../_include.php'; try { $config = SimpleSAML_Configuration::getInstance(); $session = SimpleSAML_Session::getInstance(); /* Make sure that the user has admin access rights. */ SimpleSAML_Utilities::requireAdmin(); phpinfo(); } catch (Exception $e) { SimpleSAML_Utilities::fatalError('na', NULL, $e); }
<?php require_once '../_include.php'; /** * This page handles adding of metadata. */ $config = SimpleSAML_Configuration::getInstance(); $metaConfig = SimpleSAML_Configuration::getConfig('metashare.php'); if (!$metaConfig->getBoolean('metashare.enable', FALSE)) { header('HTTP/1.0 401 Forbidden'); $session = SimpleSAML_Session::getInstance(); SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS'); } $store = SimpleSAML_MetaShare_Store::getInstance(); $t = new SimpleSAML_XHTML_Template($config, 'metashare-add.php', 'metashare'); if (!array_key_exists('url', $_GET) || empty($_GET['url'])) { $t->data['url'] = NULL; $t->data['status'] = 'nourl'; $t->show(); exit; } $url = $_GET['url']; $t->data['url'] = $url; /* We accept http or https URLs */ if (substr($url, 0, 7) !== 'http://' && substr($url, 0, 8) !== 'https://') { $t->data['status'] = 'invalidurl'; $t->show(); exit; } /* Attempt to download the metadata. */ $metadata = file_get_contents($url);
warning('technicalcontact_email should be set to a email address users can contact for support.'); } } /* Load configuration and session information. */ $config = SimpleSAML_Configuration::getInstance(); $session = SimpleSAML_Session::getInstance(); /* Check if the user is logged in with admin access. */ SimpleSAML_Utilities::requireAdmin(); /* Find config directories. */ $configDir = $config->getBaseDir() . 'config/'; $configTemplateDir = $config->getBaseDir() . 'config-templates/'; /* Find all available configuration files. */ $configFiles = array(); $dirHandle = opendir($configTemplateDir); if ($dirHandle === FALSE) { SimpleSAML_Utilities::fatalError($session->getTrackId(), 'READCONFIGTEMPLATES'); } while (($configFile = readdir($dirHandle)) !== FALSE) { /* We are only interrested in .php-files in the directory. */ if (substr($configFile, -4) !== '.php') { continue; } $configFiles[] = $configFile; } closedir($dirHandle); if (array_key_exists('file', $_GET)) { /* The user has selected a file. */ $file = $_GET['file']; /* Can we check this file? */ if (canCheckFile($file) !== TRUE) { $file = NULL;
$config = SimpleSAML_Configuration::getInstance(); $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); $session = SimpleSAML_Session::getInstance(); $ldapconfigfile = $config->getBaseDir() . 'config/ldapmulti.php'; require_once $ldapconfigfile; SimpleSAML_Logger::info('AUTH - ldap-multi: Accessing auth endpoint login-ldapmulti'); if (empty($session)) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOSESSION'); } $error = null; $attributes = array(); /* Load the RelayState argument. The RelayState argument contains the address * we should redirect the user to after a successful authentication. */ if (!array_key_exists('RelayState', $_REQUEST)) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE'); } if (isset($_POST['username'])) { try { $ldapconfig = $ldapmulti[$_POST['org']]; if ($ldapconfig['search.enable'] === TRUE) { if (!$ldap->bind($ldapconfig['search.username'], $ldapconfig['search.password'])) { throw new Exception('Error authenticating using search username & password.'); } $dn = $ldap->searchfordn($ldapconfig['search.base'], $ldapconfig['search.attributes'], $_POST['username']); } else { $dn = str_replace('%username%', $_POST['username'], $ldapconfig['dnpattern']); } $pwd = $_POST['password']; $ldap = new SimpleSAML_Auth_LDAP($ldapconfig['hostname'], $ldapconfig['enable_tls']); if ($pwd == "" or !$ldap->bind($dn, $pwd)) {
$entitiesDescriptorName = $janus_config->getString('export.entitiesDescriptorName', 'Federation'); $entitiesDescriptor->setAttribute('Name', $entitiesDescriptorName); if ($maxCache !== NULL) { $entitiesDescriptor->setAttribute('cacheDuration', 'PT' . $maxCache . 'S'); } if ($maxDuration !== NULL) { $entitiesDescriptor->setAttribute('validUntil', SimpleSAML_Utilities::generateTimestamp(time() + $maxDuration)); } $xml->appendChild($entitiesDescriptor); foreach ($entities as $entity) { if ($entity['entityid'] == $exclude_entityid) { continue; } $entityDescriptor = sspmod_janus_MetaExport::getXMLMetadata($entity['eid'], $entity['revisionid'], array('maxCache' => $maxCache, 'maxDuration' => $maxDuration)); if (empty($entityDescriptor) || !$entityDescriptor) { continue; } $entitiesDescriptor->appendChild($xml->importNode($entityDescriptor, TRUE)); } /* Sign the metadata if enabled. */ if ($janus_config->getBoolean('sign.enable', FALSE)) { $signer = new SimpleSAML_XML_Signer(array('privatekey' => $janus_config->getString('sign.privatekey'), 'privatekey_pass' => $janus_config->getString('sign.privatekey_pass', NULL), 'certificate' => $janus_config->getString('sign.certificate'), 'id' => 'ID')); $signer->sign($entitiesDescriptor, $entitiesDescriptor, $entitiesDescriptor->firstChild); } header('Content-Type: application/xml'); header('Content-Disposition: attachment; filename="federation.xml"'); echo $xml->saveXML(); } catch (Exception $exception) { $session = SimpleSAML_Session::getInstance(); SimpleSAML_Utilities::fatalError($session->getTrackID(), 'AGGREGATOR', $exception); }