public static function handleLogin($authStateId, $xmlToken) { assert('is_string($authStateId)'); $config = SimpleSAML_Configuration::getInstance(); $autoconfig = $config->copyFromBase('logininfocard', 'config-login-infocard.php'); $idp_key = $autoconfig->getValue('idp_key'); $idp_pass = $autoconfig->getValue('idp_key_pass', NULL); $sts_crt = $autoconfig->getValue('sts_crt'); $Infocard = $autoconfig->getValue('InfoCard'); $infocard = new sspmod_InfoCard_RP_InfoCard(); $infocard->addIDPKey($idp_key, $idp_pass); $infocard->addSTSCertificate($sts_crt); if (!$xmlToken) { SimpleSAML_Logger::debug("XMLtoken: " . $xmlToken); } else { SimpleSAML_Logger::debug("NOXMLtoken: " . $xmlToken); } $claims = $infocard->process($xmlToken); if ($claims->isValid()) { $attributes = array(); foreach ($Infocard['requiredClaims'] as $claim => $data) { $attributes[$claim] = array($claims->{$claim}); } foreach ($Infocard['optionalClaims'] as $claim => $data) { $attributes[$claim] = array($claims->{$claim}); } // sanitize the input $sid = SimpleSAML_Utilities::parseStateID($authStateId); if (!is_null($sid['url'])) { SimpleSAML_Utilities::checkURLAllowed($sid['url']); } /* Retrieve the authentication state. */ $state = SimpleSAML_Auth_State::loadState($authStateId, self::STAGEID); /* Find authentication source. */ assert('array_key_exists(self::AUTHID, $state)'); $source = SimpleSAML_Auth_Source::getById($state[self::AUTHID]); if ($source === NULL) { throw new Exception('Could not find authentication source with id ' . $state[self::AUTHID]); } $state['Attributes'] = $attributes; unset($infocard); unset($claims); SimpleSAML_Auth_Source::completeAuth($state); } else { unset($infocard); unset($claims); return 'wrong_IC'; } }
/** * Check the credentials that the user got from the A-Select server. * This function is called after the user returns from the A-Select server. * * @author Wessel Dankers, Tilburg University */ function check_credentials() { if (!array_key_exists('ssp_state', $_REQUEST)) { SimpleSAML_Auth_State::throwException($state, new SimpleSAML_Error_Exception("Missing ssp_state parameter")); } $id = $_REQUEST['ssp_state']; // sanitize the input $sid = SimpleSAML_Utilities::parseStateID($id); if (!is_null($sid['url'])) { SimpleSAML_Utilities::checkURLAllowed($sid['url']); } $state = SimpleSAML_Auth_State::loadState($id, 'aselect:login'); if (!array_key_exists('a-select-server', $_REQUEST)) { SimpleSAML_Auth_State::throwException($state, new SimpleSAML_Error_Exception("Missing a-select-server parameter")); } $server_id = $_REQUEST['a-select-server']; if (!array_key_exists('aselect_credentials', $_REQUEST)) { SimpleSAML_Auth_State::throwException($state, new SimpleSAML_Error_Exception("Missing aselect_credentials parameter")); } $credentials = $_REQUEST['aselect_credentials']; if (!array_key_exists('rid', $_REQUEST)) { SimpleSAML_Auth_State::throwException($state, new SimpleSAML_Error_Exception("Missing rid parameter")); } $rid = $_REQUEST['rid']; try { if (!array_key_exists('aselect::authid', $state)) { throw new SimpleSAML_Error_Exception("ASelect authentication source missing in state"); } $authid = $state['aselect::authid']; $aselect = SimpleSAML_Auth_Source::getById($authid); if (is_null($aselect)) { throw new SimpleSAML_Error_Exception("Could not find authentication source with id {$authid}"); } $creds = $aselect->verify_credentials($server_id, $credentials, $rid); if (array_key_exists('attributes', $creds)) { $state['Attributes'] = $creds['attributes']; } else { $res = $creds['res']; $state['Attributes'] = array('uid' => array($res['uid']), 'organization' => array($res['organization'])); } } catch (Exception $e) { SimpleSAML_Auth_State::throwException($state, $e); } SimpleSAML_Auth_Source::completeAuth($state); SimpleSAML_Auth_State::throwException($state, new SimpleSAML_Error_Exception("Internal error in A-Select component")); }
/** * Called when we have completed the procssing chain. * * @param array $authProcState The processing chain state. */ public static function onProcessingCompleted(array $authProcState) { assert('array_key_exists("saml:sp:IdP", $authProcState)'); assert('array_key_exists("saml:sp:State", $authProcState)'); assert('array_key_exists("Attributes", $authProcState)'); $idp = $authProcState['saml:sp:IdP']; $state = $authProcState['saml:sp:State']; $sourceId = $state['saml:sp:AuthId']; $source = SimpleSAML_Auth_Source::getById($sourceId); if ($source === NULL) { throw new Exception('Could not find authentication source with id ' . $sourceId); } /* Register a callback that we can call if we receive a logout request from the IdP. */ $source->addLogoutCallback($idp, $state); $state['Attributes'] = $authProcState['Attributes']; if (isset($state['saml:sp:isUnsolicited']) && (bool) $state['saml:sp:isUnsolicited']) { if (!empty($state['saml:sp:RelayState'])) { $redirectTo = $state['saml:sp:RelayState']; } else { $redirectTo = $source->getMetadata()->getString('RelayState', '/'); } self::handleUnsolicitedAuth($sourceId, $state, $redirectTo); } SimpleSAML_Auth_Source::completeAuth($state); }
/** * Handle login request. * * This function is used by the login form (core/www/loginuserpass.php) when the user * enters a username and password. On success, it will not return. On wrong * username/password failure, and other errors, it will throw an exception. * * @param string $authStateId The identifier of the authentication state. * @param string $username The username the user wrote. * @param string $password The password the user wrote. */ public static function handleLogin($authStateId, $username, $password) { assert('is_string($authStateId)'); assert('is_string($username)'); assert('is_string($password)'); /* Here we retrieve the state array we saved in the authenticate-function. */ $state = SimpleSAML_Auth_State::loadState($authStateId, self::STAGEID); /* Retrieve the authentication source we are executing. */ assert('array_key_exists(self::AUTHID, $state)'); $source = SimpleSAML_Auth_Source::getById($state[self::AUTHID]); if ($source === NULL) { throw new Exception('Could not find authentication source with id ' . $state[self::AUTHID]); } /* * $source now contains the authentication source on which authenticate() * was called. We should call login() on the same authentication source. */ /* Attempt to log in. */ try { $attributes = $source->login($username, $password); } catch (Exception $e) { SimpleSAML_Logger::stats('Unsuccessful login attempt from ' . $_SERVER['REMOTE_ADDR'] . '.'); throw $e; } SimpleSAML_Logger::stats('User \'' . $username . '\' has been successfully authenticated.'); /* Save the attributes we received from the login-function in the $state-array. */ assert('is_array($attributes)'); $state['Attributes'] = $attributes; /* Return control to simpleSAMLphp after successful authentication. */ SimpleSAML_Auth_Source::completeAuth($state); }
public static function resume() { $request = Request::fromString($_SERVER['REQUEST_METHOD'] . ' ' . self::requesturi()); if (!($state_id = $request->getQuery('state'))) { throw new SimpleSAML_Error_BadRequest('Missing "state" parameter.'); } $state = SimpleSAML_Auth_State::loadState($state_id, 'dataportenoauth2:Connect'); /* * Now we have the $state-array, and can use it to locate the authentication * source. */ $source = SimpleSAML_Auth_Source::getById($state['dataportenoauth2:AuthID']); if ($source === NULL) { /* * The only way this should fail is if we remove or rename the authentication source * while the user is at the login page. */ throw new SimpleSAML_Error_Exception('Could not find authentication source.'); } if (!($code = $request->getQuery('code'))) { /** * Throwing error if no code is being sent. */ throw new SimpleSAML_Error_Exception('No code was sent from origin.'); } /* * Make sure that we haven't switched the source type while the * user was at the authentication page. This can only happen if we * change config/authsources.php while an user is logging in. */ if (!$source instanceof self) { throw new SimpleSAML_Error_Exception('Authentication source type changed.'); } $oauth_client = new OAuth2($source->getConfig()); $access_token = $oauth_client->get_access_token($state_id, $code); $identity = $oauth_client->get_identity($access_token, self::$user_endpoint); if (count($identity) < 1) { /** * The user isn't authenticated */ throw new SimpleSAML_Error_Exception('User not authenticated after login attempt.', $e->getCode(), $e); } $state['Attributes'] = self::getAttributes($identity); SimpleSAML_Auth_Source::completeAuth($state); /* * The completeAuth-function never returns, so we never get this far. */ assert('FALSE'); }
/** * Delegate authentication. * * This method is called once the user has choosen one authentication * source. It saves the selected authentication source in the session * to be able to logout properly. Then it calls the authenticate method * on such selected authentication source. * * @param string $authId Selected authentication source * @param array $state Information about the current authentication. */ public static function delegateAuthentication($authId, $state) { assert('is_string($authId)'); assert('is_array($state)'); $as = SimpleSAML_Auth_Source::getById($authId); if ($as === NULL) { throw new Exception('Invalid authentication source: ' . $authId); } /* Save the selected authentication source for the logout process. */ $session = SimpleSAML_Session::getSessionFromRequest(); $session->setData(self::SESSION_SOURCE, $state[self::AUTHID], $authId, SimpleSAML_Session::DATA_TIMEOUT_SESSION_END); try { $as->authenticate($state); } catch (SimpleSAML_Error_Exception $e) { SimpleSAML_Auth_State::throwException($state, $e); } catch (Exception $e) { $e = new SimpleSAML_Error_UnserializableException($e); SimpleSAML_Auth_State::throwException($state, $e); } SimpleSAML_Auth_Source::completeAuth($state); }
/** * Handle username-password login request. * * This function is used by the login form (www/loginuserpass.php) when the user * enters a username and password. On success, it will not return. If an error occurs, * it will return the error code. * * @param string $authStateId The identifier of the authentication state. * @param string $username The username the user wrote. * @param string $password The password the user wrote. * @return string Error code in the case of an error. */ public static function handleUserPassLogin($authStateId, $username, $password) { assert('is_string($authStateId)'); assert('is_string($username)'); assert('is_string($password)'); /* Here we retrieve the state array we saved in the authenticate-function. */ $state = SimpleSAML_Auth_State::loadState($authStateId, sspmod_authTiqr_Auth_Tiqr::STAGEID); /* Retrieve the authentication source we are executing. */ assert('array_key_exists(self::AUTHID, $state)'); $source = SimpleSAML_Auth_Source::getById($state[sspmod_authTiqr_Auth_Tiqr::USERPASSSOURCEID]); if ($source === NULL) { throw new Exception('Could not find authentication source with id ' . $state[sspmod_authTiqr_Auth_Tiqr::USERPASSSOURCEID]); } /* * $source now contains the authentication source on which authenticate() * was called. We should call login() on the same authentication source. */ try { /* Attempt to log in. */ $attributes = $source->login($username, $password); } catch (SimpleSAML_Error_Error $e) { /* * Login failed. Return the error code to the login form, so that it * can display an error message to the user. */ return $e->getErrorCode(); } /* Save the attributes we received from the login-function in the $state-array. */ assert('is_array($attributes)'); $state['Attributes'] = $attributes; /* Return control to simpleSAMLphp after successful authentication. */ SimpleSAML_Auth_Source::completeAuth($state); }
/** * Handle login request. * * This function is used by the login form (core/www/loginuserpass.php) when the user * enters a username and password. On success, it will not return. On wrong * username/password failure, it will return the error code. Other failures will throw an * exception. * * @param string $authStateId The identifier of the authentication state. * @param string $otp The one time password entered- * @return string Error code in the case of an error. */ public static function handleLogin($authStateId, $otp) { assert('is_string($authStateId)'); assert('is_string($otp)'); /* Retrieve the authentication state. */ $state = SimpleSAML_Auth_State::loadState($authStateId, self::STAGEID); /* Find authentication source. */ assert('array_key_exists(self::AUTHID, $state)'); $source = SimpleSAML_Auth_Source::getById($state[self::AUTHID]); if ($source === NULL) { throw new Exception('Could not find authentication source with id ' . $state[self::AUTHID]); } try { /* Attempt to log in. */ $attributes = $source->login($otp); } catch (SimpleSAML_Error_Error $e) { /* An error occurred during login. Check if it is because of the wrong * username/password - if it is, we pass that error up to the login form, * if not, we let the generic error handler deal with it. */ if ($e->getErrorCode() === 'WRONGUSERPASS') { return 'WRONGUSERPASS'; } /* Some other error occurred. Rethrow exception and let the generic error * handler deal with it. */ throw $e; } $state['Attributes'] = $attributes; SimpleSAML_Auth_Source::completeAuth($state); }
/** * Resume authentication process. * * This function resumes the authentication process after the user has * entered his or her credentials. * * @param array &$state The authentication state. */ public static function resume() { $request = Request::fromString($_SERVER['REQUEST_METHOD'] . ' ' . self::requesturi()); if (!($stateId = $request->getQuery('state'))) { throw new SimpleSAML_Error_BadRequest('Missing "state" parameter.'); } $state = SimpleSAML_Auth_State::loadState($stateId, 'openidconnect:Connect'); /* * Now we have the $state-array, and can use it to locate the authentication * source. */ $source = SimpleSAML_Auth_Source::getById($state['openidconnect:AuthID']); if ($source === NULL) { /* * The only way this should fail is if we remove or rename the authentication source * while the user is at the login page. */ throw new SimpleSAML_Error_Exception('Could not find authentication source.'); } /* * Make sure that we haven't switched the source type while the * user was at the authentication page. This can only happen if we * change config/authsources.php while an user is logging in. */ if (!$source instanceof self) { throw new SimpleSAML_Error_Exception('Authentication source type changed.'); } // The library has its own state manager but we're using SSP's. // We've already validated the state, so let's get the token. $tokenDispatcher = new Dispatcher(); $tokenRequest = new TokenRequest(); $clientInfo = new ClientInfo(); $clientInfo->fromArray(reset($source->getConfig())); $tokenRequest->setClientInfo($clientInfo); $tokenRequest->setCode($request->getQuery('code')); $tokenRequest->setGrantType('authorization_code'); $tokenDispatcher->setOptions(['http_options' => ['sslcapath' => $source->sslcapath]]); $tokenResponse = $tokenDispatcher->sendTokenRequest($tokenRequest); $userDispatcher = new InfoDispatcher(); $userDispatcher->setOptions(['http_options' => ['sslcapath' => $source->sslcapath]]); $infoRequest = new InfoRequest(); $infoRequest->setClientInfo($clientInfo); $infoRequest->setAccessToken($tokenResponse->getAccessToken()); try { $infoResponse = $userDispatcher->sendUserInfoRequest($infoRequest); $user = $infoResponse->getClaims(); } catch (Exception $e) { /* * The user isn't authenticated. * * Here we simply throw an exception, but we could also redirect the user back to the * login page. */ throw new SimpleSAML_Error_Exception('User not authenticated after login attempt.', $e->getCode(), $e); } /* * So, we have a valid user. Time to resume the authentication process where we * paused it in the authenticate()-function above. */ $state['Attributes'] = self::getAttributes($user); SimpleSAML_Auth_Source::completeAuth($state); /* * The completeAuth-function never returns, so we never get this far. */ assert('FALSE'); }
public static function resume() { if (!isset($_REQUEST['State'])) { throw new SimpleSAML_Error_BadRequest('Missing "State" parameter.'); } $state = SimpleSAML_Auth_State::loadState($_REQUEST['State'], 'negotiateserver:Negotiate'); $source = SimpleSAML_Auth_Source::getById($state['negotiateserver:AuthID']); if ($source === NULL) { throw new SimpleSAML_Error_Exception('Could not find authentication source with id ' . $state[self::authId]); } if (!$source instanceof self) { throw new SimpleSAML_Error_Exception('Authentication source type changed.'); } if (empty($state['UserIdentifier'])) { throw new SimpleSAML_Error_Exception('User identifier is empty or not set.'); } $attributes = $source->getUserAttributes($state['UserIdentifier']); if ($attributes === NULL) { throw new SimpleSAML_Error_Exception('User not authenticated after login page.'); } $state['Attributes'] = $attributes; SimpleSAML_Auth_Source::completeAuth($state); assert('FALSE'); }
/** * Called by linkback, to finish validate/ finish logging in. * @param state $state * @return list username, casattributes/ldap attributes */ public function finalStep(&$state) { global $mysqli; $ticket = $state['cas:ticket']; $stateID = SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); $service = SimpleSAML_Module::getModuleURL('cas/linkback.php', array('stateID' => $stateID)); list($username, $casattributes) = $this->casValidation($ticket, $service); //recherche du login gepi $path = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))))); require_once($path."/secure/connect.inc.php"); // Database connection require_once($path."/lib/mysql.inc"); if ($this->_champ_cas_uid_retour == 'username') { $uid = $username; } else { $uid = $casattributes['uid']; } $requete = 'SELECT '.$this->_search_table_gepi_login_column.' FROM '.$this->_search_table_name.' WHERE '.$this->_search_table_cas_uid_column.'=\''.$uid.'\''; $result = $mysqli->query($requete); $valeur = $result->fetch_array(MYSQLI_NUM); if (!$valeur) { //utilisateur non trouvé dans la base gepi, l'authentification a échoué SimpleSAML_Logger::error('gepicas:' . $this->authId . ': not authenticated. User is in the CAS but not in the gepi local database.'); throw new SimpleSAML_Error_UserNotFound('Utilisateur non trouve dans la base locale'); } $attributes['login'] = array($valeur[0]); $attributes['login_gepi'] = array($valeur[0]); # On interroge la base de données pour récupérer des attributs qu'on va retourner # Cela ne sert pas à gepi directement mais à des services qui peuvent s'appuyer sur gepi pour l'athentification $query = $mysqli->query("SELECT nom, prenom, email, statut FROM utilisateurs WHERE (login = '******'login_gepi'][0]."')"); $row = $query->fetch_object(); $attributes['nom'] = array($row->nom); $attributes['prenom'] = array($row->prenom); $attributes['statut'] = array($row->statut); $attributes['email'] = array($row->email); $state['Attributes'] = $attributes; SimpleSAML_Auth_Source::completeAuth($state); }
public static function completeLogin($authStateId) { $state = self::_validateAuthState($authStateId); $server = self::getServer(false); $session = SimpleSAML_Session::getSessionFromRequest(); $sessionId = $session->getSessionId(); $user = $server->getAuthenticatedUser($sessionId); if (empty($user)) { $url = SimpleSAML_Module::getModuleURL('authTiqr/login.php'); SimpleSAML_Utilities::redirect($url, array('AuthState' => $authStateId)); } else { if (!isset($state["tiqrUser"])) { // Single factor. We can now continue to login. $attributes = array('uid' => array($user), 'displayName' => array(self::getUserStorage()->getDisplayName($user))); $attributes = array_merge($attributes, self::getUserStorage()->getAdditionalAttributes($user)); $state['Attributes'] = $attributes; SimpleSAML_Auth_Source::completeAuth($state); } else { // Two factor, we can now complete the processing filter process. SimpleSAML_Auth_ProcessingChain::resumeProcessing($state); } } }
/** * Called when we have completed the procssing chain. * * @param array $authProcState The processing chain state. */ public static function onProcessingCompleted(array $authProcState) { assert('array_key_exists("saml2:sp:IdP", $authProcState)'); assert('array_key_exists("saml2:sp:State", $authProcState)'); assert('array_key_exists("Attributes", $authProcState)'); $idp = $authProcState['saml2:sp:IdP']; $state = $authProcState['saml2:sp:State']; $sourceId = $state[sspmod_saml2_Auth_Source_SP::AUTHID]; $source = SimpleSAML_Auth_Source::getById($sourceId); if ($source === NULL) { throw new Exception('Could not find authentication source with id ' . $sourceId); } /* Register a callback that we can call if we receive a logout request from the IdP. */ $source->addLogoutCallback($idp, $state); $state['Attributes'] = $authProcState['Attributes']; SimpleSAML_Auth_Source::completeAuth($state); }
public function finalStep(&$state) { $credentials = $state['aselect:credentials']; $rid = $state['aselect:rid']; assert('isset($credentials)'); assert('isset($rid)'); $params = array('request' => 'verify_credentials', 'rid' => $rid, 'a-select-server' => $this->asconfig['serverid'], 'aselect_credentials' => $credentials); if ($this->asconfig['type'] == 'cross') { $params['local_organization'] = $this->asconfig['local_organization']; } $url = SimpleSAML_Utilities::addURLparameter($this->asconfig['serverurl'], $params); $parms = $this->as_call($url); $attributes = array('uid' => array($parms['uid'])); if (array_key_exists('attributes', $parms)) { $decoded = base64_decode($parms['attributes']); foreach (explode('&', $decoded) as $parm) { $tuple = explode('=', $parm); $name = urldecode($tuple[0]); if (preg_match('/\\[\\]$/', $name)) { $name = substr($name, 0, -2); } if (!array_key_exists($name, $attributes)) { $attributes[$name] = array(); } $attributes[$name][] = urldecode($tuple[1]); } } $state['Attributes'] = $attributes; SimpleSAML_Auth_Source::completeAuth($state); }
<?php /** * Handle linkback() response from LinkedIn. */ if (array_key_exists('stateid', $_REQUEST)) { $stateId = $_REQUEST['stateid']; } else { throw new Exception('Lost OAuth Client State'); } $state = SimpleSAML_Auth_State::loadState($stateId, sspmod_authlinkedin_Auth_Source_LinkedIn::STAGE_INIT); // http://developer.linkedin.com/docs/DOC-1008#2_Redirect_the_User_to_our_Authorization_Server if (array_key_exists('oauth_verifier', $_REQUEST)) { $state['authlinkedin:oauth_verifier'] = $_REQUEST['oauth_verifier']; } else { throw new Exception('OAuth verifier not returned.'); } /* Find authentication source. */ assert('array_key_exists(sspmod_authlinkedin_Auth_Source_LinkedIn::AUTHID, $state)'); $sourceId = $state[sspmod_authlinkedin_Auth_Source_LinkedIn::AUTHID]; $source = SimpleSAML_Auth_Source::getById($sourceId); if ($source === NULL) { throw new Exception('Could not find authentication source with id ' . $sourceId); } $source->finalStep($state); SimpleSAML_Auth_Source::completeAuth($state);
/** * Handle login request. * * This function is used by the login form (core/www/loginuserpassorg.php) when the user * enters a username and password. On success, it will not return. On wrong * username/password failure, and other errors, it will throw an exception. * * @param string $authStateId The identifier of the authentication state. * @param string $username The username the user wrote. * @param string $password The password the user wrote. * @param string $organization The id of the organization the user chose. */ public static function handleLogin($authStateId, $username, $password, $organization) { assert('is_string($authStateId)'); assert('is_string($username)'); assert('is_string($password)'); assert('is_string($organization)'); /* Retrieve the authentication state. */ $state = SimpleSAML_Auth_State::loadState($authStateId, self::STAGEID); /* Find authentication source. */ assert('array_key_exists(self::AUTHID, $state)'); $source = SimpleSAML_Auth_Source::getById($state[self::AUTHID]); if ($source === NULL) { throw new Exception('Could not find authentication source with id ' . $state[self::AUTHID]); } $orgMethod = $source->getUsernameOrgMethod(); if ($orgMethod !== 'none') { $tmp = explode('@', $username, 2); if (count($tmp) === 2) { $username = $tmp[0]; $organization = $tmp[1]; } else { if ($orgMethod === 'force') { /* The organization should be a part of the username, but isn't. */ throw new SimpleSAML_Error_Error('WRONGUSERPASS'); } } } /* Attempt to log in. */ $attributes = $source->login($username, $password, $organization); // Add the selected Org to the state $state[self::ORGID] = $organization; $state['PersistentAuthData'][] = self::ORGID; $state['Attributes'] = $attributes; SimpleSAML_Auth_Source::completeAuth($state); }
/** * The inner workings of the module. * * Checks to see if client is in the defined subnets (if * defined in config). Sends the client a 401 Negotiate and * responds to the result. If the client fails to provide a * proper Kerberos ticket, the login process is handed over to * the 'fallback' module defined in the config. * * LDAP is used as a user metadata source. * * @param array &$state Information about the current authentication. */ public function authenticate(&$state) { assert('is_array($state)'); // Set the default backend to config $state['LogoutState'] = array('negotiate:backend' => $this->backend); $state['negotiate:authId'] = $this->authId; // Check for disabled SPs. The disable flag is store in the SP // metadata. if (array_key_exists('SPMetadata', $state) and $this->spDisabledInMetadata($state['SPMetadata'])) { $this->fallBack($state); } // Go straight to fallback if Negotiate is disabled or if you are // sent back to the IdP directly from the SP after having logged out $session = SimpleSAML_Session::getInstance(); $disabled = $session->getData('negotiate:disable', 'session'); if ($disabled or !empty($_COOKIE['NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT']) and $_COOKIE['NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT'] == 'True') { SimpleSAML_Logger::debug('Negotiate - session disabled. falling back'); $this->fallBack($state); // Never executed assert('FALSE'); } $mask = $this->checkMask(); if (!$mask) { $this->fallBack($state); // Never executed assert('FALSE'); } SimpleSAML_Logger::debug('Negotiate - authenticate(): looking for Negotate'); if (!empty($_SERVER['HTTP_AUTHORIZATION'])) { SimpleSAML_Logger::debug('Negotiate - authenticate(): Negotate found'); $this->ldap = new SimpleSAML_Auth_LDAP($this->hostname, $this->enableTLS, $this->debugLDAP, $this->timeout); list($mech, $data) = explode(' ', $_SERVER['HTTP_AUTHORIZATION'], 2); if (strtolower($mech) == 'basic') { SimpleSAML_Logger::debug('Negotiate - authenticate(): Basic found. Skipping.'); } else { if (strtolower($mech) != 'negotiate') { SimpleSAML_Logger::debug('Negotiate - authenticate(): No "Negotiate" found. Skipping.'); } } $auth = new KRB5NegotiateAuth($this->keytab); // Atempt Kerberos authentication try { $reply = $auth->doAuthentication(); } catch (Exception $e) { SimpleSAML_Logger::error('Negotiate - authenticate(): doAuthentication() exception: ' . $e->getMessage()); $reply = NULL; } if ($reply) { // Success. Krb TGS recieved. $user = $auth->getAuthenticatedUser(); SimpleSAML_Logger::info('Negotiate - authenticate(): ' . $user . ' authenticated.'); $lookup = $this->lookupUserData($user); if ($lookup) { $state['Attributes'] = $lookup; // Override the backend so logout will know what to look for. $state['LogoutState'] = array('negotiate:backend' => NULL); SimpleSAML_Logger::info('Negotiate - authenticate(): ' . $user . ' authorized.'); SimpleSAML_Auth_Source::completeAuth($state); // Never reached. assert('FALSE'); } } else { // Some error in the recieved ticket. Expired? SimpleSAML_Logger::info('Negotiate - authenticate(): Kerberos authN failed. Skipping.'); } } else { // No auth token. Send it. SimpleSAML_Logger::debug('Negotiate - authenticate(): Sending Negotiate.'); // Save the $state array, so that we can restore if after a redirect SimpleSAML_Logger::debug('Negotiate - fallback: ' . $state['LogoutState']['negotiate:backend']); $id = SimpleSAML_Auth_State::saveState($state, self::STAGEID); $params = array('AuthState' => $id); $this->sendNegotiate($params); exit; } SimpleSAML_Logger::info('Negotiate - authenticate(): Client failed Negotiate. Falling back'); $this->fallBack($state); /* The previous function never returns, so this code is never executed */ assert('FALSE'); }
/** * Process an authentication response. * * @param array &$state The state array. */ public function postAuth(array &$state) { $consumer = $this->getConsumer($state); $return_to = SimpleSAML_Utilities::selfURL(); // Complete the authentication process using the server's // response. $response = $consumer->complete($return_to); // Check the response status. if ($response->status == Auth_OpenID_CANCEL) { // This means the authentication was cancelled. throw new SimpleSAML_Error_UserAborted(); } else { if ($response->status == Auth_OpenID_FAILURE) { // Authentication failed; display the error message. throw new SimpleSAML_Error_AuthSource($this->authId, 'Authentication failed: ' . var_export($response->message, TRUE)); } else { if ($response->status != Auth_OpenID_SUCCESS) { throw new SimpleSAML_Error_AuthSource($this->authId, 'General error. Try again.'); } } } // This means the authentication succeeded; extract the // identity URL and Simple Registration data (if it was // returned). $openid = $response->identity_url; $attributes = array('openid' => array($openid)); $attributes['openid.server_url'] = array($response->endpoint->server_url); if ($response->endpoint->canonicalID) { $attributes['openid.canonicalID'] = array($response->endpoint->canonicalID); } if ($response->endpoint->local_id) { $attributes['openid.local_id'] = array($response->endpoint->local_id); } $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response, $this->validateSReg); $sregresponse = $sreg_resp->contents(); if (is_array($sregresponse) && count($sregresponse) > 0) { $attributes['openid.sregkeys'] = array_keys($sregresponse); foreach ($sregresponse as $sregkey => $sregvalue) { $attributes['openid.sreg.' . $sregkey] = array($sregvalue); } } // Get AX response information $ax = new Auth_OpenID_AX_FetchResponse(); $ax_resp = $ax->fromSuccessResponse($response); if ($ax_resp instanceof Auth_OpenID_AX_FetchResponse && !empty($ax_resp->data)) { $axresponse = $ax_resp->data; $attributes['openid.axkeys'] = array_keys($axresponse); foreach ($axresponse as $axkey => $axvalue) { if (preg_match("/^\\w+:/", $axkey)) { $attributes[$axkey] = is_array($axvalue) ? $axvalue : array($axvalue); } else { SimpleSAML_Logger::warning('Invalid attribute name in AX response: ' . var_export($axkey, TRUE)); } } } SimpleSAML_Logger::debug('OpenID Returned Attributes: ' . implode(", ", array_keys($attributes))); $state['Attributes'] = $attributes; SimpleSAML_Auth_Source::completeAuth($state); }
/** * Handle login request. * * This function is used by the login form (core/www/loginuserpass.php) when the user * enters a username and password. On success, it will not return. On wrong * username/password failure, and other errors, it will throw an exception. * * @param string $authStateId The identifier of the authentication state. * @param string $username The username the user wrote. * @param string $password The password the user wrote. * @param $transaction_id * @param $signaturedata * @param $clientdata * @throws Exception */ public static function handleLogin($authStateId, $username, $password, $transaction_id, $signaturedata, $clientdata) { assert('is_string($authStateId)'); assert('is_string($username)'); assert('is_string($password)'); assert('is_string($transaction_id)'); SimpleSAML_Logger::debug("calling privacyIDEA handleLogin with authState: " . $authStateId . " for user " . $username); if (array_key_exists("OTP", $_REQUEST)) { $otp = $_REQUEST["OTP"]; $password = $password . $otp; SimpleSAML_Logger::stats('Found OTP in Auth request. Concatenating passwords.'); } // sanitize the input $sid = SimpleSAML_Utilities::parseStateID($authStateId); if (!is_null($sid['url'])) { SimpleSAML_Utilities::checkURLAllowed($sid['url']); } /* Here we retrieve the state array we saved in the authenticate-function. */ $state = SimpleSAML_Auth_State::loadState($authStateId, self::STAGEID); /* Retrieve the authentication source we are executing. */ assert('array_key_exists(self::AUTHID, $state)'); $source = SimpleSAML_Auth_Source::getById($state[self::AUTHID]); if ($source === NULL) { throw new Exception('Could not find authentication source with id ' . $state[self::AUTHID]); } /* * $source now contains the authentication source on which authenticate() * was called. We should call login() on the same authentication source. */ /* Attempt to log in. */ try { $attributes = $source->login_chal_resp($username, $password, $transaction_id, $signaturedata, $clientdata); } catch (Exception $e) { SimpleSAML_Logger::stats('Unsuccessful login attempt from ' . $_SERVER['REMOTE_ADDR'] . '.'); throw $e; } SimpleSAML_Logger::stats('User \'' . $username . '\' has been successfully authenticated.'); /* Save the attributes we received from the login-function in the $state-array. */ assert('is_array($attributes)'); $state['Attributes'] = $attributes; /* Return control to simpleSAMLphp after successful authentication. */ SimpleSAML_Auth_Source::completeAuth($state); }
/** * Resume authentication process. * * This function resumes the authentication process after the user has * entered his or her credentials. * * @param array &$state The authentication state. */ public static function resume() { /* * First we need to restore the $state-array. We should have the identifier for * it in the 'State' request parameter. */ if (!isset($_REQUEST['State'])) { throw new SimpleSAML_Error_BadRequest('Missing "State" parameter.'); } $stateId = (string) $_REQUEST['State']; /* * Once again, note the second parameter to the loadState function. This must * match the string we used in the saveState-call above. */ $state = SimpleSAML_Auth_State::loadState($stateId, 'drupalauth:External'); /* * Now we have the $state-array, and can use it to locate the authentication * source. */ $source = SimpleSAML_Auth_Source::getById($state['drupalauth:AuthID']); if ($source === NULL) { /* * The only way this should fail is if we remove or rename the authentication source * while the user is at the login page. */ throw new SimpleSAML_Error_Exception('Could not find authentication source with id ' . $state[self::AUTHID]); } /* * Make sure that we haven't switched the source type while the * user was at the authentication page. This can only happen if we * change config/authsources.php while an user is logging in. */ if (!$source instanceof self) { throw new SimpleSAML_Error_Exception('Authentication source type changed.'); } /* * OK, now we know that our current state is sane. Time to actually log the user in. * * First we check that the user is acutally logged in, and didn't simply skip the login page. */ $attributes = $source->getUser(); if ($attributes === NULL) { /* * The user isn't authenticated. * * Here we simply throw an exception, but we could also redirect the user back to the * login page. */ throw new SimpleSAML_Error_Exception('User not authenticated after login page.'); } /* * So, we have a valid user. Time to resume the authentication process where we * paused it in the authenticate()-function above. */ $state['Attributes'] = $attributes; SimpleSAML_Auth_Source::completeAuth($state); /* * The completeAuth-function never returns, so we never get this far. */ assert('FALSE'); }
/** * Called by linkback, to finish validate/ finish logging in. * @param state $state * @return list username, casattributes/ldap attributes */ public function finalStep(&$state) { $ticket = $state['cas:ticket']; $stateID = SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); $service = SimpleSAML_Module::getModuleURL('cas/linkback.php', array('stateID' => $stateID)); list($username, $casattributes) = $this->casValidation($ticket, $service); $ldapattributes = array(); if ($this->_ldapConfig['servers']) { $ldap = new SimpleSAML_Auth_LDAP($this->_ldapConfig['servers'], $this->_ldapConfig['enable_tls']); $ldapattributes = $ldap->validate($this->_ldapConfig, $username); } $attributes = array_merge_recursive($casattributes, $ldapattributes); $state['Attributes'] = $attributes; SimpleSAML_Auth_Source::completeAuth($state); }
/** * Finish a succesfull authentication. * * This function can be overloaded by a child authentication * class that wish to perform some operations after login. * * @param array &$state Information about the current authentication. */ public function authSuccesful(&$state) { SimpleSAML_Auth_Source::completeAuth($state); assert('FALSE'); /* NOTREACHED */ return; }
function run_finish_auth() { $error = 'General error. Try again.'; try { $consumer = getConsumer(); $return_to = SimpleSAML_Utilities::selfURL(); // Complete the authentication process using the server's // response. $response = $consumer->complete($return_to); // Check the response status. if ($response->status == Auth_OpenID_CANCEL) { // This means the authentication was cancelled. throw new Exception('Verification cancelled.'); } else { if ($response->status == Auth_OpenID_FAILURE) { // Authentication failed; display the error message. throw new Exception("OpenID authentication failed: " . $response->message); } else { if ($response->status == Auth_OpenID_SUCCESS) { // This means the authentication succeeded; extract the // identity URL and Simple Registration data (if it was // returned). $openid = $response->identity_url; $attributes = array('openid' => array($openid)); if ($response->endpoint->canonicalID) { $attributes['openid.canonicalID'] = array($response->endpoint->canonicalID); } $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response); $sregresponse = $sreg_resp->contents(); if (is_array($sregresponse) && count($sregresponse) > 0) { $attributes['openid.sregkeys'] = array_keys($sregresponse); foreach ($sregresponse as $sregkey => $sregvalue) { $attributes['openid.sreg.' . $sregkey] = array($sregvalue); } } global $state; $state['Attributes'] = $attributes; SimpleSAML_Auth_Source::completeAuth($state); } } } } catch (Exception $e) { $error = $e->getMessage(); } $config = SimpleSAML_Configuration::getInstance(); $t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid'); $t->data['error'] = $error; global $authState; $t->data['AuthState'] = $authState; $t->show(); }