public function getAttributes($nameId, $attributes = array()) { // Set up config $config = $this->config; // Setup cURL $url = $this->as_config['api_url'] . '/' . $nameId; $ch = curl_init($url); curl_setopt_array($ch, array(CURLOPT_CUSTOMREQUEST => 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array('Content-Type: application/json'))); // Send the request $response = curl_exec($ch); $http_response = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Check for error; not even redirects are allowed here if ($http_response == 507) { throw new SimpleSAML_Error_Exception("Out of resources: " . $response); } elseif ($response === false || !($http_response >= 200 && $http_response < 300)) { SimpleSAML_Logger::error('[afra] API query failed: HTTP response code: ' . $http_response . ', curl error: "' . curl_error($ch)) . '"'; SimpleSAML_Logger::debug('[afra] API query failed: curl info: ' . var_export(curl_getinfo($ch), 1)); SimpleSAML_Logger::debug('[afra] API query failed: HTTP response: ' . var_export($response, 1)); throw new SimpleSAML_Error_Exception("Error at REST API response: " . $response . $http_response); } else { $data = json_decode($response, true); SimpleSAML_Logger::info('[afra] got reply from API'); SimpleSAML_Logger::debug('[afra] API query url: ' . var_export($url, true)); SimpleSAML_Logger::debug('[afra] API query result: ' . var_export($data, true)); } $attributes = $data['data']; return $attributes; }
/** * Hook to run a cron job. * * @param array &$croninfo Output */ function sanitycheck_hook_cron(&$croninfo) { assert('is_array($croninfo)'); assert('array_key_exists("summary", $croninfo)'); assert('array_key_exists("tag", $croninfo)'); SimpleSAML_Logger::info('cron [sanitycheck]: Running cron in cron tag [' . $croninfo['tag'] . '] '); try { $sconfig = SimpleSAML_Configuration::getOptionalConfig('config-sanitycheck.php'); $cronTag = $sconfig->getString('cron_tag', NULL); if ($cronTag === NULL || $cronTag !== $croninfo['tag']) { return; } $info = array(); $errors = array(); $hookinfo = array('info' => &$info, 'errors' => &$errors); SimpleSAML_Module::callHooks('sanitycheck', $hookinfo); if (count($errors) > 0) { foreach ($errors as $err) { $croninfo['summary'][] = 'Sanitycheck error: ' . $err; } } } catch (Exception $e) { $croninfo['summary'][] = 'Error executing sanity check: ' . $e->getMessage(); } }
public static function receiveAuthnRequest(SimpleSAML_IdP $idp) { try { // accomodate for disfunctional $_GET "windows" slash decoding in PHP $wctx = $_GET['wctx']; foreach (explode('&', $_SERVER['REQUEST_URI']) as $e) { $a = explode('=', $e); if ($a[0] == 'wctx') { $wctx = urldecode($a[1]); } } $requestid = $wctx; $issuer = $_GET['wtrealm']; $requestcache = array('RequestID' => $requestid, 'Issuer' => $issuer, 'RelayState' => $requestid); $spEntityId = $requestcache['Issuer']; $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'adfs-sp-remote'); SimpleSAML_Logger::info('ADFS - IdP.prp: Incoming Authentication request: ' . $issuer . ' id ' . $requestid); } catch (Exception $exception) { throw new SimpleSAML_Error_Error('PROCESSAUTHNREQUEST', $exception); } $sessionLostURL = NULL; // TODO? $forceAuthn = FALSE; $isPassive = FALSE; $state = array('Responder' => array('sspmod_adfs_IdP_ADFS', 'sendResponse'), 'SPMetadata' => $spMetadata->toArray(), 'ForceAuthn' => $forceAuthn, 'isPassive' => $isPassive, 'adfs:wctx' => $wctx); $idp->handleAuthenticationRequest($state); }
function driveProcessingChain($idp_metadata, $source, $sp_metadata, $sp_entityid, $attributes, $userid, $hashAttributes = FALSE) { /* * Create a new processing chain */ $pc = new SimpleSAML_Auth_ProcessingChain($idp_metadata, $sp_metadata, 'idp'); /* * Construct the state. * REMEMBER: Do not set Return URL if you are calling processStatePassive */ $authProcState = array('Attributes' => $attributes, 'Destination' => $sp_metadata, 'Source' => $idp_metadata, 'isPassive' => TRUE); /* * Call processStatePAssive. * We are not interested in any user interaction, only modifications to the attributes */ $pc->processStatePassive($authProcState); $attributes = $authProcState['Attributes']; /* * Generate identifiers and hashes */ $destination = $sp_metadata['metadata-set'] . '|' . $sp_entityid; $targeted_id = sspmod_consent_Auth_Process_Consent::getTargetedID($userid, $source, $destination); $attribute_hash = sspmod_consent_Auth_Process_Consent::getAttributeHash($attributes, $hashAttributes); SimpleSAML_Logger::info('consentAdmin: user: '******'consentAdmin: target: ' . $targeted_id); SimpleSAML_Logger::info('consentAdmin: attribute: ' . $attribute_hash); /* Return values */ return array($targeted_id, $attribute_hash, $attributes); }
public function getAttributes($nameId, $spid, $attributes = array()) { // Generate API key $time = new \DateTime(); date_timezone_set($time, new \DateTimeZone('UTC')); $stamp = $time->format('Y-m-d H:i'); $apiKey = hash('sha256', $this->as_config['hexaa_master_secret'] . $stamp); // Make the call // The data to send to the API $postData = array("apikey" => $apiKey, "fedid" => $nameId, "entityid" => $spid); // Setup cURL $ch = curl_init($this->as_config['hexaa_api_url'] . '/attributes.json'); curl_setopt_array($ch, array(CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_HTTPHEADER => array('Content-Type: application/json'), CURLOPT_POSTFIELDS => json_encode($postData), CURLOPT_FOLLOWLOCATION => TRUE, CURLOPT_POSTREDIR => 3)); // Send the request $response = curl_exec($ch); $http_response = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Check for error; not even redirects are allowed here if ($response === FALSE || !($http_response >= 200 && $http_response < 300)) { SimpleSAML_Logger::error('[aa] HEXAA API query failed: HTTP response code: ' . $http_response . ', curl error: "' . curl_error($ch)) . '"'; SimpleSAML_Logger::debug('[aa] HEXAA API query failed: curl info: ' . var_export(curl_getinfo($ch), 1)); SimpleSAML_Logger::debug('[aa] HEXAA API query failed: HTTP response: ' . var_export($response, 1)); $data = array(); } else { $data = json_decode($response, true); SimpleSAML_Logger::info('[aa] got reply from HEXAA API'); SimpleSAML_Logger::debug('[aa] HEXAA API query postData: ' . var_export($postData, TRUE)); SimpleSAML_Logger::debug('[aa] HEXAA API query result: ' . var_export($data, TRUE)); } return $data; }
function new_access_token($requestToken, $consumer) { SimpleSAML_Logger::info('OAuth new_access_token(' . $requestToken . ',' . $consumer . ')'); $token = new OAuthToken(SimpleSAML_Utilities::generateID(), SimpleSAML_Utilities::generateID()); // SimpleSAML_Logger::info('OAuth new_access_token(' . $requestToken . ',' . $consumer . ',' . $token . ')'); $this->store->set('access', $token->key, $consumer->key, $token, $this->config->getValue('accessTokenDuration', 60 * 60 * 24)); return $token; }
/** * Filter out YubiKey 'otp' attribute and replace it with * a 'yubiPrefix' attribute that leaves out the dynamic part. * * @param array &$state The state we should update. */ public function process(&$state) { assert('is_array($state)'); assert('array_key_exists("Attributes", $state)'); $attributes = $state['Attributes']; SimpleSAML_Logger::debug('OTP2YubiPrefix: enter with attributes: ' . implode(',', array_keys($attributes))); $otps = $attributes['otp']; $otp = $otps['0']; $token_size = 32; $identity = substr($otp, 0, strlen($otp) - $token_size); $attributes['yubiPrefix'] = array($identity); SimpleSAML_Logger::info('OTP2YubiPrefix: otp: ' . $otp . ' identity: ' . $identity . ' (otp keys: ' . implode(',', array_keys($otps)) . ')'); unset($attributes['otp']); SimpleSAML_Logger::debug('OTP2YubiPrefix: leaving with attributes: ' . implode(',', array_keys($attributes))); }
/** * Hook to run a cron job. * * @param array &$croninfo Output */ function metarefresh_hook_cron(&$croninfo) { assert('is_array($croninfo)'); assert('array_key_exists("summary", $croninfo)'); assert('array_key_exists("tag", $croninfo)'); SimpleSAML_Logger::info('cron [metarefresh]: Running cron in cron tag [' . $croninfo['tag'] . '] '); try { $config = SimpleSAML_Configuration::getInstance(); $mconfig = SimpleSAML_Configuration::getConfig('config-metarefresh.php'); $sets = $mconfig->getConfigList('sets'); foreach ($sets as $setkey => $set) { // Only process sets where cron matches the current cron tag. $cronTags = $set->getArray('cron'); if (!in_array($croninfo['tag'], $cronTags)) { continue; } SimpleSAML_Logger::info('cron [metarefresh]: Executing set [' . $setkey . ']'); $expireAfter = $set->getInteger('expireAfter', NULL); if ($expireAfter !== NULL) { $expire = time() + $expireAfter; } else { $expire = NULL; } $metaloader = new sspmod_metarefresh_MetaLoader($expire); foreach ($set->getArray('sources') as $source) { SimpleSAML_Logger::debug('cron [metarefresh]: In set [' . $setkey . '] loading source [' . $source['src'] . ']'); $metaloader->loadSource($source); } $outputDir = $set->getString('outputDir'); $outputDir = $config->resolvePath($outputDir); $outputFormat = $set->getValueValidate('outputFormat', array('flatfile', 'serialize'), 'flatfile'); switch ($outputFormat) { case 'flatfile': $metaloader->writeMetadataFiles($outputDir); break; case 'serialize': $metaloader->writeMetadataSerialize($outputDir); break; } if ($set->hasValue('arp')) { $arpconfig = SimpleSAML_Configuration::loadFromArray($set->getValue('arp')); $metaloader->writeARPfile($arpconfig); } } } catch (Exception $e) { $croninfo['summary'][] = 'Error during metarefresh: ' . $e->getMessage(); } }
protected function __construct(array $option) { // Is path parsed as a string if (!isset($option['path']) || !is_string($option['path'])) { throw new Exception('Invalid path given for FileSystem exporter.' . ' Should be a string:' . var_export($option['path'], true)); } // Do the file exists in advance if (file_exists($option['path'])) { SimpleSAML_Logger::info('File: ' . $option['path'] . ' exists and will be overwritten'); } // Is file writable if (!is_writable($option['path'])) { throw new Exception('Path not writable:' . var_export($option['path'], true)); } $this->_path = $option['path']; }
/** * Receive an authentication request. * * @param SimpleSAML_IdP $idp The IdP we are receiving it for. */ public static function receiveAuthnRequest(SimpleSAML_IdP $idp) { if (isset($_REQUEST['cookieTime'])) { $cookieTime = (int) $_REQUEST['cookieTime']; if ($cookieTime + 5 > time()) { /* * Less than five seconds has passed since we were * here the last time. Cookies are probably disabled. */ SimpleSAML_Utilities::checkCookie(SimpleSAML_Utilities::selfURL()); } } if (!isset($_REQUEST['providerId'])) { throw new SimpleSAML_Error_BadRequest('Missing providerId parameter.'); } $spEntityId = (string) $_REQUEST['providerId']; if (!isset($_REQUEST['shire'])) { throw new SimpleSAML_Error_BadRequest('Missing shire parameter.'); } $shire = (string) $_REQUEST['shire']; if (isset($_REQUEST['target'])) { $target = $_REQUEST['target']; } else { $target = NULL; } SimpleSAML_Logger::info('Shib1.3 - IdP.SSOService: Got incoming Shib authnRequest from ' . var_export($spEntityId, TRUE) . '.'); $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'shib13-sp-remote'); $found = FALSE; foreach ($spMetadata->getEndpoints('AssertionConsumerService') as $ep) { if ($ep['Binding'] !== 'urn:oasis:names:tc:SAML:1.0:profiles:browser-post') { continue; } if ($ep['Location'] !== $shire) { continue; } $found = TRUE; break; } if (!$found) { throw new Exception('Invalid AssertionConsumerService for SP ' . var_export($spEntityId, TRUE) . ': ' . var_export($shire, TRUE)); } SimpleSAML_Stats::log('saml:idp:AuthnRequest', array('spEntityID' => $spEntityId, 'protocol' => 'saml1')); $sessionLostURL = SimpleSAML_Utilities::addURLparameter(SimpleSAML_Utilities::selfURL(), array('cookieTime' => time())); $state = array('Responder' => array('sspmod_saml_IdP_SAML1', 'sendResponse'), 'SPMetadata' => $spMetadata->toArray(), 'saml:shire' => $shire, 'saml:target' => $target, 'saml:AuthnRequestReceivedAt' => microtime(TRUE)); $idp->handleAuthenticationRequest($state); }
/** * Hook to run a cron job. * * @param array &$croninfo Output */ function discojuice_hook_cron(&$croninfo) { assert('is_array($croninfo)'); assert('array_key_exists("summary", $croninfo)'); assert('array_key_exists("tag", $croninfo)'); if ($croninfo['tag'] !== 'hourly') return; SimpleSAML_Logger::info('cron [discojuice metadata caching]: Running cron in tag [' . $croninfo['tag'] . '] '); try { $feed = new sspmod_discojuice_Feed(); $feed->store(); } catch (Exception $e) { $croninfo['summary'][] = 'Error during discojuice metadata caching: ' . $e->getMessage(); } }
/** * Continue the logout operation. * * This function will never return. * * @param string $assocId The association that is terminated. * @param string|null $relayState The RelayState from the start of the logout. * @param SimpleSAML_Error_Exception|null $error The error that occurred during session termination (if any). * * @throws SimpleSAML_Error_Exception If the RelayState was lost during logout. */ public function onResponse($assocId, $relayState, SimpleSAML_Error_Exception $error = null) { assert('is_string($assocId)'); assert('is_string($relayState) || is_null($relayState)'); if ($relayState === null) { throw new SimpleSAML_Error_Exception('RelayState lost during logout.'); } $state = SimpleSAML_Auth_State::loadState($relayState, 'core:LogoutTraditional'); if ($error === null) { SimpleSAML_Logger::info('Logged out of ' . var_export($assocId, true) . '.'); $this->idp->terminateAssociation($assocId); } else { SimpleSAML_Logger::warning('Error received from ' . var_export($assocId, true) . ' during logout:'); $error->logWarning(); $state['core:Failed'] = true; } self::logoutNextSP($state); }
/** * Cron hook for JANUS * * This hook does the following: * * - Downloads the metadata of the entities registered in JANUS and * update the entities with the new metadata. * - Validates all entity certificates * - Validates all entity endpoints * * @param array &$cronInfo The array with the tags and output summary of the cron run * * @return void * * @since Function available since Release 1.4.0 */ function janus_hook_cron(&$cronInfo) { assert('is_array($cronInfo)'); assert('array_key_exists("summary", $cronInfo)'); assert('array_key_exists("tag", $cronInfo)'); SimpleSAML_Logger::info('cron [janus]: Running cron in cron tag [' . $cronInfo['tag'] . '] '); // Refresh metadata $refresher = new sspmod_janus_Cron_Job_MetadataRefresh(); $summaryLines = $refresher->runForCronTag($cronInfo['tag']); $cronInfo['summary'] = array_merge($cronInfo['summary'], $summaryLines); // Validate entity signing certificates $validator = new sspmod_janus_Cron_Job_ValidateEntityCertificate(); $summaryLines = $validator->runForCronTag($cronInfo['tag']); $cronInfo['summary'] = array_merge($cronInfo['summary'], $summaryLines); // Validate entity endpoints $validator = new sspmod_janus_Cron_Job_ValidateEntityEndpoints(); $summaryLines = $validator->runForCronTag($cronInfo['tag']); $cronInfo['summary'] = array_merge($cronInfo['summary'], $summaryLines); }
/** * Hook to run a cron job. * * @param array &$croninfo Output */ function riak_hook_cron(&$croninfo) { assert('is_array($croninfo)'); assert('array_key_exists("summary", $croninfo)'); assert('array_key_exists("tag", $croninfo)'); if ($croninfo['tag'] !== 'hourly') { return; } try { $store = new sspmod_riak_Store_Store(); $result = $store->bucket->indexSearch('expires', 'int', 1, time() - 30); foreach ($result as $link) { $link->getBinary()->delete(); } SimpleSAML_Logger::info(sprintf("deleted %s riak key%s", sizeof($result), sizeof($result) == 1 ? '' : 's')); } catch (Exception $e) { $message = 'riak threw exception: ' . $e->getMessage(); SimpleSAML_Logger::warning($message); $croninfo['summary'][] = $message; } }
/** * Continue the logout operation. * * This function will never return. * * @param string $assocId The association that is terminated. * @param string|NULL $relayState The RelayState from the start of the logout. * @param SimpleSAML_Error_Exception|NULL $error The error that occurred during session termination (if any). */ public function onResponse($assocId, $relayState, SimpleSAML_Error_Exception $error = NULL) { assert('is_string($assocId)'); assert('is_string($relayState) || is_null($relayState)'); if ($relayState === NULL) { throw new SimpleSAML_Error_Exception('RelayState lost during logout.'); } // sanitize the input $sid = SimpleSAML_Utilities::parseStateID($relayState); if (!is_null($sid['url'])) { SimpleSAML_Utilities::checkURLAllowed($sid['url']); } $state = SimpleSAML_Auth_State::loadState($relayState, 'core:LogoutTraditional'); if ($error === NULL) { SimpleSAML_Logger::info('Logged out of ' . var_export($assocId, TRUE) . '.'); $this->idp->terminateAssociation($assocId); } else { SimpleSAML_Logger::warning('Error received from ' . var_export($assocId, TRUE) . ' during logout:'); $error->logWarning(); $state['core:Failed'] = TRUE; } self::logoutNextSP($state); }
/** * Check for consent. * * This function checks whether a given user has authorized the release of * the attributes identified by $attributeSet from $source to $destination. * * @param string $userId The hash identifying the user at an IdP. * @param string $destinationId A string which identifies the destination. * @param string $attributeSet A hash which identifies the attributes. * * @return bool True if the user has given consent earlier, false if not * (or on error). */ public function hasConsent($userId, $destinationId, $attributeSet) { assert('is_string($userId)'); assert('is_string($destinationId)'); assert('is_string($attributeSet)'); $cookieName = self::_getCookieName($userId, $destinationId); $data = $userId . ':' . $attributeSet . ':' . $destinationId; SimpleSAML_Logger::debug('Consent cookie - Get [' . $data . ']'); if (!array_key_exists($cookieName, $_COOKIE)) { SimpleSAML_Logger::debug('Consent cookie - no cookie with name \'' . $cookieName . '\'.'); return false; } if (!is_string($_COOKIE[$cookieName])) { SimpleSAML_Logger::warning('Value of consent cookie wasn\'t a string. Was: ' . var_export($_COOKIE[$cookieName], true)); return false; } $data = self::_sign($data); if ($_COOKIE[$cookieName] !== $data) { SimpleSAML_Logger::info('Attribute set changed from the last time consent was given.'); return false; } SimpleSAML_Logger::debug('Consent cookie - found cookie with correct name and value.'); return true; }
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)) { SimpleSAML_Logger::info('AUTH - ldap-multi: ' . $_POST['username'] . ' failed to authenticate. DN=' . $dn); throw new Exception('Wrong username or password'); } $attributes = $ldap->getAttributes($dn, $ldapconfig['attributes']); SimpleSAML_Logger::info('AUTH - ldap-multi: ' . $_POST['username'] . ' successfully authenticated'); $session->doLogin('login-ldapmulti'); $session->setAttributes($attributes); $session->setNameID(array('value' => SimpleSAML_Utilities::generateID(), 'Format' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient')); /** * Create a statistics log entry for every successfull login attempt. * Also log a specific attribute as set in the config: statistics.authlogattr */ $authlogattr = $config->getValue('statistics.authlogattr', null); if ($authlogattr && array_key_exists($authlogattr, $attributes)) { SimpleSAML_Logger::stats('AUTH-login-ldapmulti OK ' . $attributes[$authlogattr][0]); } else { SimpleSAML_Logger::stats('AUTH-login-ldapmulti OK'); } $returnto = $_REQUEST['RelayState']; SimpleSAML_Utilities::redirect($returnto);
/** * Validate certificate and login * * This function try to validate the certificate. * On success, the user is logged in without going through * o login page. * On failure, The authX509:X509error.php template is * loaded. * * @param array &$state Information about the current authentication. */ public function authenticate(&$state) { assert('is_array($state)'); $ldapcf = $this->ldapcf; if (!isset($_SERVER['SSL_CLIENT_CERT']) || $_SERVER['SSL_CLIENT_CERT'] == '') { $state['authX509.error'] = "NOCERT"; $this->authFailed($state); assert('FALSE'); /* NOTREACHED */ return; } $client_cert = $_SERVER['SSL_CLIENT_CERT']; $client_cert_data = openssl_x509_parse($client_cert); if ($client_cert_data == FALSE) { SimpleSAML_Logger::error('authX509: invalid cert'); $state['authX509.error'] = "INVALIDCERT"; $this->authFailed($state); assert('FALSE'); /* NOTREACHED */ return; } $dn = NULL; foreach ($this->x509attributes as $x509_attr => $ldap_attr) { /* value is scalar */ if (array_key_exists($x509_attr, $client_cert_data['subject'])) { $value = $client_cert_data['subject'][$x509_attr]; SimpleSAML_Logger::info('authX509: cert ' . $x509_attr . ' = ' . $value); $dn = $ldapcf->searchfordn($ldap_attr, $value, TRUE); if ($dn !== NULL) { break; } } } if ($dn === NULL) { SimpleSAML_Logger::error('authX509: cert has ' . 'no matching user in LDAP'); $state['authX509.error'] = "UNKNOWNCERT"; $this->authFailed($state); assert('FALSE'); /* NOTREACHED */ return; } if ($this->ldapusercert === NULL) { // do not check for certificate match $attributes = $ldapcf->getAttributes($dn); assert('is_array($attributes)'); $state['Attributes'] = $attributes; $this->authSuccesful($state); assert('FALSE'); /* NOTREACHED */ return; } $ldap_certs = $ldapcf->getAttributes($dn, $this->ldapusercert); if ($ldap_certs === FALSE) { SimpleSAML_Logger::error('authX509: no certificate ' . 'found in LDAP for dn=' . $dn); $state['authX509.error'] = "UNKNOWNCERT"; $this->authFailed($state); assert('FALSE'); /* NOTREACHED */ return; } $merged_ldapcerts = array(); foreach ($this->ldapusercert as $attr) { $merged_ldapcerts = array_merge($merged_ldapcerts, $ldap_certs[$attr]); } $ldap_certs = $merged_ldapcerts; foreach ($ldap_certs as $ldap_cert) { $pem = $this->der2pem($ldap_cert); $ldap_cert_data = openssl_x509_parse($pem); if ($ldap_cert_data == FALSE) { SimpleSAML_Logger::error('authX509: cert in ' . 'LDAP in invalid for ' . 'dn = ' . $dn); continue; } if ($ldap_cert_data === $client_cert_data) { $attributes = $ldapcf->getAttributes($dn); assert('is_array($attributes)'); $state['Attributes'] = $attributes; $this->authSuccesful($state); assert('FALSE'); /* NOTREACHED */ return; } } SimpleSAML_Logger::error('authX509: no matching cert in ' . 'LDAP for dn = ' . $dn); $state['authX509.error'] = "UNKNOWNCERT"; $this->authFailed($state); assert('FALSE'); /* NOTREACHED */ return; }
<?php /** * about2expire.php * * @package simpleSAMLphp */ SimpleSAML_Logger::info('expirycheck - User has been warned that NetID is near to expirational date.'); if (!array_key_exists('StateId', $_REQUEST)) { throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.'); } $id = $_REQUEST['StateId']; // sanitize the input $sid = SimpleSAML_Utilities::parseStateID($id); if (!is_null($sid['url'])) { SimpleSAML_Utilities::checkURLAllowed($sid['url']); } $state = SimpleSAML_Auth_State::loadState($id, 'expirywarning:about2expire'); if (array_key_exists('yes', $_REQUEST)) { /* The user has pressed the yes-button. */ SimpleSAML_Auth_ProcessingChain::resumeProcessing($state); } $globalConfig = SimpleSAML_Configuration::getInstance(); $t = new SimpleSAML_XHTML_Template($globalConfig, 'expirycheck:about2expire.php'); $t->data['yesTarget'] = SimpleSAML_Module::getModuleURL('expirycheck/about2expire.php'); $t->data['yesData'] = array('StateId' => $id); $t->data['daysleft'] = $state['daysleft']; $t->data['expireOnDate'] = $state['expireOnDate']; $t->data['netId'] = $state['netId']; $t->show();
<?php /* * This endpoint is provided for backwards compatibility, * and should not be used. * * Use SingleLogoutService.php instead. */ require_once '../../_include.php'; SimpleSAML_Logger::info('SAML2.0 - IdP.SingleLogoutServiceiFrame: Accessing SAML 2.0 IdP endpoint SingleLogoutService (iFrame version)'); $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); $idpEntityId = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted'); $idp = SimpleSAML_IdP::getById('saml2:' . $idpEntityId); sspmod_saml_IdP_SAML2::receiveLogoutMessage($idp); assert('FALSE');
* WS-Federation/ADFS PRP protocol support for simpleSAMLphp. * * The AssertionConsumerService handler accepts responses from a WS-Federation * Account Partner using the Passive Requestor Profile (PRP) and handles it as * a Resource Partner. It receives a response, parses it and passes on the * authentication+attributes. * * @author Hans Zandbelt, SURFnet BV. <*****@*****.**> * @package simpleSAMLphp */ require_once '../../_include.php'; $config = SimpleSAML_Configuration::getInstance(); $session = SimpleSAML_Session::getSessionFromRequest(); $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); SimpleSAML_Logger::warning('The file wsfed/sp/prp.php is deprecated and will be removed in future versions.'); SimpleSAML_Logger::info('WS-Fed - SP.AssertionConsumerService: Accessing WS-Fed SP endpoint AssertionConsumerService'); if (!$config->getBoolean('enable.wsfed-sp', false)) { throw new SimpleSAML_Error_Error('NOACCESS'); } if (!empty($_GET['wa']) and $_GET['wa'] == 'wsignoutcleanup1.0') { if (isset($session) && $session->isValid('wsfed')) { $session->doLogout('wsfed'); } if (!empty($_GET['wreply'])) { SimpleSAML_Utilities::redirectUntrustedURL(urldecode($_GET['wreply'])); } exit; } /* Make sure that the correct query parameters are passed to this script. */ try { if (empty($_POST['wresult'])) {
foreach ($indexFiles as $if) { if (file_exists($path . $if)) { $path .= $if; break; } } } if (is_dir($path)) { /* Path is a directory - maybe no index file was found in the previous step, or maybe the path didn't end with * a slash. Either way, we don't do directory listings. */ throw new SimpleSAML_Error_NotFound('Directory listing not available.'); } if (!file_exists($path)) { // file not found SimpleSAML_Logger::info('Could not find file \'' . $path . '\'.'); throw new SimpleSAML_Error_NotFound('The URL wasn\'t found in the module.'); } if (preg_match('#\\.php$#D', $path)) { // PHP file - attempt to run it $_SERVER['SCRIPT_NAME'] .= '/' . $module . '/' . $url; require $path; exit; } // some other file type - attempt to serve it // find MIME type for file, based on extension $contentType = null; if (preg_match('#\\.([^/\\.]+)$#D', $path, $type)) { $type = strtolower($type[1]); if (array_key_exists($type, $mimeTypes)) { $contentType = $mimeTypes[$type];
/** * Add attributes from an LDAP server. * * @param array &$request The current request */ public function process(&$request) { assert('is_array($request)'); assert('array_key_exists("Attributes", $request)'); $attributes =& $request['Attributes']; // perform a merge on the ldap_search_filter // loop over the attributes and build the search and replace arrays foreach ($attributes as $attr => $val) { $arrSearch[] = '%' . $attr . '%'; if (strlen($val[0]) > 0) { $arrReplace[] = SimpleSAML_Auth_LDAP::escape_filter_value($val[0]); } else { $arrReplace[] = ''; } } // merge the attributes into the ldap_search_filter $filter = str_replace($arrSearch, $arrReplace, $this->search_filter); if (strpos($filter, '%') !== FALSE) { SimpleSAML_Logger::info('AttributeAddFromLDAP: There are non-existing attributes in the search filter. (' . $this->search_filter . ')'); return; } if (!in_array($this->attr_policy, array('merge', 'replace', 'add'))) { SimpleSAML_Logger::warning("AttributeAddFromLDAP: 'attribute.policy' must be one of 'merge'," . "'replace' or 'add'."); return; } // search for matching entries try { $entries = $this->getLdap()->searchformultiple($this->base_dn, $filter, array_values($this->search_attributes), TRUE, FALSE); } catch (Exception $e) { return; // silent fail, error is still logged by LDAP search } // handle [multiple] values foreach ($entries as $entry) { foreach ($this->search_attributes as $target => $name) { if (is_numeric($target)) { $target = $name; } if (isset($attributes[$target]) && $this->attr_policy === 'replace') { unset($attributes[$target]); } $name = strtolower($name); if (isset($entry[$name])) { unset($entry[$name]['count']); if (isset($attributes[$target])) { foreach (array_values($entry[$name]) as $value) { if ($this->attr_policy === 'merge') { if (!in_array($value, $attributes[$target])) { $attributes[$target][] = $value; } } else { $attributes[$target][] = $value; } } } else { $attributes[$target] = array_values($entry[$name]); } } } } }
/** * Retrieve a logout URL for a given logout association. * * @param SimpleSAML_IdP $idp The IdP we are sending a logout request from. * @param array $association The association that should be terminated. * @param string|NULL $relayState An id that should be carried across the logout. */ public static function getLogoutURL(SimpleSAML_IdP $idp, array $association, $relayState) { assert('is_string($relayState) || is_null($relayState)'); SimpleSAML_Logger::info('Sending SAML 2.0 LogoutRequest to: ' . var_export($association['saml:entityID'], TRUE)); $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); $idpMetadata = $idp->getConfig(); $spMetadata = $metadata->getMetaDataConfig($association['saml:entityID'], 'saml20-sp-remote'); $bindings = array(SAML2_Const::BINDING_HTTP_REDIRECT, SAML2_Const::BINDING_HTTP_POST); $dst = $spMetadata->getEndpointPrioritizedByBinding('SingleLogoutService', $bindings); if ($dst['Binding'] === SAML2_Const::BINDING_HTTP_POST) { $params = array('association' => $association['id'], 'idp' => $idp->getId()); if ($relayState !== NULL) { $params['RelayState'] = $relayState; } return SimpleSAML_Module::getModuleURL('core/idp/logout-iframe-post.php', $params); } $lr = self::buildLogoutRequest($idpMetadata, $spMetadata, $association, $relayState); $lr->setDestination($dst['Location']); $binding = new SAML2_HTTPRedirect(); return $binding->getRedirectURL($lr); }
if ($idp === NULL) { /* No issuer found in the assertions. */ throw new Exception('Missing <saml:Issuer> in message delivered to AssertionConsumerService.'); } } $session = SimpleSAML_Session::getInstance(); $prevAuth = $session->getAuthData($sourceId, 'saml:sp:prevAuth'); if ($prevAuth !== NULL && $prevAuth['id'] === $response->getId() && $prevAuth['issuer'] === $idp) { /* OK, it looks like this message has the same issuer * and ID as the SP session we already have active. We * therefore assume that the user has somehow triggered * a resend of the message. * In that case we may as well just redo the previous redirect * instead of displaying a confusing error message. */ SimpleSAML_Logger::info('Duplicate SAML 2 response detected - ignoring the response and redirecting the user to the correct page.'); SimpleSAML_Utilities::redirect($prevAuth['redirect']); } $stateId = $response->getInResponseTo(); if (!empty($stateId)) { /* This is a response to a request we sent earlier. */ $state = SimpleSAML_Auth_State::loadState($stateId, 'saml:sp:sso'); /* Check that the authentication source is correct. */ assert('array_key_exists("saml:sp:AuthId", $state)'); if ($state['saml:sp:AuthId'] !== $sourceId) { throw new SimpleSAML_Error_Exception('The authentication source id in the URL does not match the authentication source which sent the request.'); } /* Check that the issuer is the one we are expecting. */ assert('array_key_exists("ExpectedIssuer", $state)'); if ($state['ExpectedIssuer'] !== $idp) { throw new SimpleSAML_Error_Exception('The issuer of the response does not match to the identity provider we sent the request to.');
$session->doLogin('login-radius'); $session->setAttributes($attributes); $session->setNameID(array('value' => SimpleSAML_Utilities::generateID(), 'Format' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient')); /** * Create a statistics log entry for every successfull login attempt. * Also log a specific attribute as set in the config: statistics.authlogattr */ $authlogattr = $config->getValue('statistics.authlogattr', null); if ($authlogattr && array_key_exists($authlogattr, $attributes)) { SimpleSAML_Logger::stats('AUTH-login-radius OK ' . $attributes[$authlogattr][0]); } else { SimpleSAML_Logger::stats('AUTH-login-radius OK'); } SimpleSAML_Utilities::redirectTrustedURL($relaystate); case RADIUS_ACCESS_REJECT: SimpleSAML_Logger::info('AUTH - radius: ' . $_POST['username'] . ' failed to authenticate'); throw new Exception('Radius authentication error: Bad credentials '); break; case RADIUS_ACCESS_CHALLENGE: SimpleSAML_Logger::critical('AUTH - radius: Challenge requested: ' . radius_strerror($radius)); throw new Exception('Radius authentication error: Challenge requested'); break; default: SimpleSAML_Logger::critical('AUTH -radius: General radius error: ' . radius_strerror($radius)); throw new Exception('Error during radius authentication: ' . radius_strerror($radius)); } } catch (Exception $e) { $error = $e->getMessage(); } } $t = new SimpleSAML_XHTML_Template($config, 'login.php', 'login');
$userid = null; if (!array_key_exists('SSL_CLIENT_VERIFY', $_SERVER)) { throw new Exception('Apache header variable SSL_CLIENT_VERIFY was not available. Recheck your apache configuration.'); } if (strcmp($_SERVER['SSL_CLIENT_VERIFY'], "SUCCESS") != 0) { throw new SimpleSAML_Error_Error('NOTVALIDCERT', $e); } $userid = $_SERVER['SSL_CLIENT_S_DN']; $attributes['CertificateDN'] = array($userid); $attributes['CertificateDNCN'] = array($_SERVER['SSL_CLIENT_S_DN_CN']); $session->doLogin('tlsclient'); $session->setAttributes($attributes); #echo '<pre>'; #print_r($_SERVER); #echo '</pre>'; exit; SimpleSAML_Logger::info('AUTH - tlsclient: ' . $userid . ' successfully authenticated'); $session->setNameID(array('value' => SimpleSAML_Utilities::generateID(), 'Format' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient')); /** * Create a statistics log entry for every successfull login attempt. * Also log a specific attribute as set in the config: statistics.authlogattr */ $authlogattr = $config->getValue('statistics.authlogattr', null); if ($authlogattr && array_key_exists($authlogattr, $attributes)) { SimpleSAML_Logger::stats('AUTH-tlsclient OK ' . $attributes[$authlogattr][0]); } else { SimpleSAML_Logger::stats('AUTH-tlsclient OK'); } SimpleSAML_Utilities::redirectUntrustedURL($_REQUEST['RelayState']); } catch (Exception $e) { throw new SimpleSAML_Error_Error('CONFIG', $e); }
public function validate($config, $username, $password = null) { /* Escape any characters with a special meaning in LDAP. The following * characters have a special meaning (according to RFC 2253): * ',', '+', '"', '\', '<', '>', ';', '*' * These characters are escaped by prefixing them with '\'. */ $username = addcslashes($username, ',+"\\<>;*'); $password = addcslashes($password, ',+"\\<>;*'); if (isset($config['priv_user_dn'])) { $this->bind($config['priv_user_dn'], $config['priv_user_pw']); } if (isset($config['dnpattern'])) { $dn = str_replace('%username%', $username, $config['dnpattern']); } else { $dn = $this->searchfordn($config['searchbase'], $config['searchattributes'], $username); } if ($password != null) { /* checking users credentials ... assuming below that she may read her own attributes ... */ if (!$this->bind($dn, $password)) { SimpleSAML_Logger::info('Library - LDAP validate(): Failed to authenticate \'' . $username . '\' using DN \'' . $dn . '\''); return FALSE; } } /* * Retrieve attributes from LDAP */ $attributes = $this->getAttributes($dn, $config['attributes']); return $attributes; }
/** * Log a message. * * This is an helper function for logging messages. It will prefix the messages with our * discovery service type. * * @param $message The message which should be logged. */ protected function log($message) { SimpleSAML_Logger::info('PowerIdPDisco.' . $this->instance . ': ' . $message); }
<?php /** * * This script displays a page to the user, which requests that the user * * authorizes the release of attributes. * * * * @package simpleSAMLphp * * @version $Id$ * */ SimpleSAML_Logger::info('JANUS - Access blocked'); if (!array_key_exists('StateId', $_REQUEST)) { throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.'); } $id = $_REQUEST['StateId']; $state = SimpleSAML_Auth_State::loadState($id, 'janus:accessblock'); $globalConfig = SimpleSAML_Configuration::getInstance(); $t = new SimpleSAML_XHTML_Template($globalConfig, 'janus:accessblock.php', 'janus:accessblock'); $t->data['stateid'] = array('StateId' => $id); $t->show();