Example #1
0
 /**
  * Require admin access to the current page.
  *
  * This is a helper function for limiting a page to those with administrative access. It will redirect the user to
  * a login page if the current user doesn't have admin access.
  *
  * @return void This function will only return if the user is admin.
  * @throws \SimpleSAML_Error_Exception If no "admin" authentication source was configured.
  *
  * @author Olav Morken, UNINETT AS <*****@*****.**>
  * @author Jaime Perez, UNINETT AS <*****@*****.**>
  */
 public static function requireAdmin()
 {
     if (self::isAdmin()) {
         return;
     }
     // not authenticated as admin user, start authentication
     if (\SimpleSAML_Auth_Source::getById('admin') !== null) {
         $as = new \SimpleSAML_Auth_Simple('admin');
         $as->login();
     } else {
         throw new \SimpleSAML_Error_Exception('Cannot find "admin" auth source, and admin privileges are required.');
     }
 }
 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';
     }
 }
Example #3
0
 /**
  * Start logout.
  *
  * This function starts a logout operation from the current authentication
  * source. This function will return if the logout operation does not
  * require a redirect.
  *
  * @param string $returnURL The URL we should redirect the user to after
  * logging out. No checking is performed on the URL, so make sure to verify
  * it on beforehand if the URL is obtained from user input. Refer to
  * \SimpleSAML\Utils\HTTP::checkURLAllowed() for more information.
  * @param string $authority The authentication source we are logging
  * out from.
  */
 public static function initLogoutReturn($returnURL, $authority)
 {
     assert('is_string($returnURL)');
     assert('is_string($authority)');
     $session = SimpleSAML_Session::getSessionFromRequest();
     $state = $session->getAuthData($authority, 'LogoutState');
     $session->doLogout($authority);
     $state['SimpleSAML_Auth_Default.ReturnURL'] = $returnURL;
     $state['LogoutCompletedHandler'] = array(get_class(), 'logoutCompleted');
     $as = SimpleSAML_Auth_Source::getById($authority);
     if ($as === NULL) {
         /* The authority wasn't an authentication source... */
         self::logoutCompleted($state);
     }
     $as->logout($state);
 }
Example #4
0
/**
 * 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"));
}
Example #5
0
 /**
  * Initialize an IdP.
  *
  * @param string $id  The identifier of this IdP.
  */
 private function __construct($id)
 {
     assert('is_string($id)');
     $this->id = $id;
     $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $globalConfig = SimpleSAML_Configuration::getInstance();
     if (substr($id, 0, 6) === 'saml2:') {
         if (!$globalConfig->getBoolean('enable.saml20-idp', FALSE)) {
             throw new SimpleSAML_Error_Exception('enable.saml20-idp disabled in config.php.');
         }
         $this->config = $metadata->getMetaDataConfig(substr($id, 6), 'saml20-idp-hosted');
     } elseif (substr($id, 0, 6) === 'saml1:') {
         if (!$globalConfig->getBoolean('enable.shib13-idp', FALSE)) {
             throw new SimpleSAML_Error_Exception('enable.shib13-idp disabled in config.php.');
         }
         $this->config = $metadata->getMetaDataConfig(substr($id, 6), 'shib13-idp-hosted');
     } elseif (substr($id, 0, 5) === 'adfs:') {
         if (!$globalConfig->getBoolean('enable.adfs-idp', FALSE)) {
             throw new SimpleSAML_Error_Exception('enable.adfs-idp disabled in config.php.');
         }
         $this->config = $metadata->getMetaDataConfig(substr($id, 5), 'adfs-idp-hosted');
         try {
             /* This makes the ADFS IdP use the same SP associations as the SAML 2.0 IdP. */
             $saml2EntityId = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
             $this->associationGroup = 'saml2:' . $saml2EntityId;
         } catch (Exception $e) {
             /* Probably no SAML 2 IdP configured for this host. Ignore the error. */
         }
     } else {
         assert(FALSE);
     }
     if ($this->associationGroup === NULL) {
         $this->associationGroup = $this->id;
     }
     $auth = $this->config->getString('auth');
     if (SimpleSAML_Auth_Source::getById($auth) !== NULL) {
         $this->authSource = new SimpleSAML_Auth_Simple($auth);
     } else {
         $this->authSource = new SimpleSAML_Auth_BWC($auth, $this->config->getString('authority', NULL));
     }
 }
 /**
  * Attempt to log in using the given username and password.
  *
  * On a successful login, this function should return the users attributes. On failure,
  * it should throw an exception. If the error was caused by the user entering the wrong
  * username or password, a SimpleSAML_Error_Error('WRONGUSERPASS') should be thrown.
  *
  * Note that both the username and the password are UTF-8 encoded.
  *
  * @param string $username  The username the user wrote.
  * @param string $password  The password the user wrote.
  * @return array  Associative array with the users attributes.
  */
 protected function login($username, $password)
 {
     assert('is_string($username)');
     assert('is_string($password)');
     $userpass = $username . ':' . $password;
     $qaLogin = SimpleSAML_Auth_Source::getById('auth2factor');
     $uid = $username;
     foreach (array_keys($this->users) as $user) {
         $u = explode(':', $user)[0];
         // lets see if we matched the username, and if we have a uid!
         if ($u == $username) {
             $uid = $this->users[$user]['uid'][0];
         }
     }
     if (!array_key_exists($userpass, $this->users)) {
         $qaLogin->failedLoginAttempt($uid, 'login_count', array('name' => $username, 'mail' => $this->users[$user]['mail'][0], 'uid' => $uid));
         $failedAttempts = $qaLogin->getFailedAttempts($uid);
         $loginCount = (int) (!empty($failedAttempts)) ? $failedAttempts[0]['login_count'] : 0;
         $answerCount = (int) (!empty($failedAttempts)) ? $failedAttempts[0]['answer_count'] : 0;
         $failCount = $loginCount + $answerCount;
         $firstFailCount = $qaLogin->getmaxFailLogin() - 2;
         $secondFailCount = $qaLogin->getmaxFailLogin() - 1;
         if ($failCount == $firstFailCount) {
             throw new SimpleSAML_Error_Error('2FAILEDATTEMPTWARNING');
         }
         if ($failCount == $secondFailCount) {
             throw new SimpleSAML_Error_Error('1FAILEDATTEMPTWARNING');
         }
         if ($qaLogin->isLocked($uid)) {
             throw new SimpleSAML_Error_Error('ACCOUNTLOCKED');
         }
         // both username and password are wrong
         throw new SimpleSAML_Error_Error('WRONGUSERPASS');
     }
     // make sure login counter is zero!
     $qaLogin->resetFailedLoginAttempts($uid);
     return $this->users[$userpass];
 }
Example #7
0
<?php

/**
 *
 *
 * @author Mathias Meisfjordskar, University of Oslo.
 *         <*****@*****.**>
 * @package simpleSAMLphp
 */
$state = SimpleSAML_Auth_State::loadState($_REQUEST['AuthState'], sspmod_negotiate_Auth_Source_Negotiate::STAGEID);
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$idpid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted', 'metaindex');
$idpmeta = $metadata->getMetaData($idpid, 'saml20-idp-hosted');
if (isset($idpmeta['auth'])) {
    $source = SimpleSAML_Auth_Source::getById($idpmeta['auth']);
    if ($source === NULL) {
        throw new SimpleSAML_Error_BadRequest('Invalid AuthId "' . $idpmeta['auth'] . '" - not found.');
    }
    $session = SimpleSAML_Session::getSessionFromRequest();
    $session->setData('negotiate:disable', 'session', FALSE, 24 * 60 * 60);
    SimpleSAML_Logger::debug('Negotiate(retry) - session enabled, retrying.');
    $source->authenticate($state);
    assert('FALSE');
} else {
    SimpleSAML_Logger::error('Negotiate - retry - no "auth" parameter found in IdP metadata.');
    assert('FALSE');
}
 /**
  * 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');
 }
<?php

/**
 * Handle linkback() response from CAS.
 */
if (!isset($_GET['stateID'])) {
    throw new SimpleSAML_Error_BadRequest('Missing stateID parameter.');
}
$stateId = (string) $_GET['stateID'];
if (!isset($_GET['ticket'])) {
    throw new SimpleSAML_Error_BadRequest('Missing ticket parameter.');
}
// sanitize the input
$sid = SimpleSAML_Utilities::parseStateID($stateId);
if (!is_null($sid['url'])) {
    SimpleSAML_Utilities::checkURLAllowed($sid['url']);
}
$state = SimpleSAML_Auth_State::loadState($stateId, sspmod_cas_Auth_Source_CAS::STAGE_INIT);
$state['cas:ticket'] = (string) $_GET['ticket'];
/* Find authentication source. */
assert('array_key_exists(sspmod_cas_Auth_Source_CAS::AUTHID, $state)');
$sourceId = $state[sspmod_cas_Auth_Source_CAS::AUTHID];
$source = SimpleSAML_Auth_Source::getById($sourceId);
if ($source === NULL) {
    throw new Exception('Could not find authentication source with id ' . $sourceId);
}
$source->finalStep($state);
Example #10
0
 /**
  * Log the user out.
  *
  * This function logs the user out. It will never return. By default,
  * it will cause a redirect to the current page after logging the user
  * out, but a different URL can be given with the $params parameter.
  *
  * Generic parameters are:
  *  - 'ReturnTo': The URL the user should be returned to after logout.
  *  - 'ReturnCallback': The function that should be called after logout.
  *  - 'ReturnStateParam': The parameter we should return the state in when redirecting.
  *  - 'ReturnStateStage': The stage the state array should be saved with.
  *
  * @param string|array|NULL $params  Either the URL the user should be redirected to after logging out,
  *                                   or an array with parameters for the logout. If this parameter is
  *                                   NULL, we will return to the current page.
  */
 public function logout($params = NULL)
 {
     assert('is_array($params) || is_string($params) || is_null($params)');
     if ($params === NULL) {
         $params = SimpleSAML_Utilities::selfURL();
     }
     if (is_string($params)) {
         $params = array('ReturnTo' => $params);
     }
     assert('is_array($params)');
     assert('isset($params["ReturnTo"]) || isset($params["ReturnCallback"])');
     if (isset($params['ReturnStateParam']) || isset($params['ReturnStateStage'])) {
         assert('isset($params["ReturnStateParam"]) && isset($params["ReturnStateStage"])');
     }
     $session = SimpleSAML_Session::getSessionFromRequest();
     if ($session->isValid($this->authSource)) {
         $state = $session->getAuthData($this->authSource, 'LogoutState');
         if ($state !== NULL) {
             $params = array_merge($state, $params);
         }
         $session->doLogout($this->authSource);
         $params['LogoutCompletedHandler'] = array(get_class(), 'logoutCompleted');
         $as = SimpleSAML_Auth_Source::getById($this->authSource);
         if ($as !== NULL) {
             $as->logout($params);
         }
     }
     self::logoutCompleted($params);
 }
/**
 * This page shows a username/password/organization login form, and passes information from
 * itto the sspmod_core_Auth_UserPassBase class, which is a generic class for
 * username/password/organization authentication.
 *
 * @author Olav Morken, UNINETT AS.
 * @package simpleSAMLphp
 * @version $Id$
 */
if (!array_key_exists('AuthState', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing AuthState parameter.');
}
$authStateId = $_REQUEST['AuthState'];
/* Retrieve the authentication state. */
$state = SimpleSAML_Auth_State::loadState($authStateId, sspmod_core_Auth_UserPassOrgBase::STAGEID);
$source = SimpleSAML_Auth_Source::getById($state[sspmod_core_Auth_UserPassOrgBase::AUTHID]);
if ($source === NULL) {
    throw new Exception('Could not find authentication source with id ' . $state[sspmod_core_Auth_UserPassOrgBase::AUTHID]);
}
$organizations = sspmod_core_Auth_UserPassOrgBase::listOrganizations($authStateId);
if (array_key_exists('username', $_REQUEST)) {
    $username = $_REQUEST['username'];
} elseif ($source->getRememberUsernameEnabled() && array_key_exists($source->getAuthId() . '-username', $_COOKIE)) {
    $username = $_COOKIE[$source->getAuthId() . '-username'];
} elseif (isset($state['core:username'])) {
    $username = (string) $state['core:username'];
} else {
    $username = '';
}
if (array_key_exists('password', $_REQUEST)) {
    $password = $_REQUEST['password'];
Example #12
0
<?php

/**
 * Assertion consumer service handler for SAML 2.0 SP authentication client.
 */
$sourceId = substr($_SERVER['PATH_INFO'], 1);
$source = SimpleSAML_Auth_Source::getById($sourceId, 'sspmod_saml_Auth_Source_SP');
$spMetadata = $source->getMetadata();
$b = SAML2_Binding::getCurrentBinding();
if ($b instanceof SAML2_HTTPArtifact) {
    $b->setSPMetadata($spMetadata);
}
$response = $b->receive();
if (!$response instanceof SAML2_Response) {
    throw new SimpleSAML_Error_BadRequest('Invalid message received to AssertionConsumerService endpoint.');
}
$idp = $response->getIssuer();
if ($idp === NULL) {
    /* No Issuer in the response. Look for an unencrypted assertion with an issuer. */
    foreach ($response->getAssertions() as $a) {
        if ($a instanceof SAML2_Assertion) {
            /* We found an unencrypted assertion - there should be an issuer here. */
            $idp = $a->getIssuer();
            break;
        }
    }
    if ($idp === NULL) {
        /* No issuer found in the assertions. */
        throw new Exception('Missing <saml:Issuer> in message delivered to AssertionConsumerService.');
    }
}
Example #13
0
 /**
  * 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);
 }
 /**
  * Attempt to log in using the given username and password.
  *
  * Will throw a SimpleSAML_Error_Error('WRONGUSERPASS') if the username or password is wrong.
  * If there is a configuration problem, an Exception will be thrown.
  *
  * @param string $username  The username the user wrote.
  * @param string $password  The password the user wrote.
  * @param arrray $sasl_args  Array of SASL options for LDAP bind.
  * @return array  Associative array with the users attributes.
  */
 public function login($username, $password, array $sasl_args = NULL)
 {
     assert('is_string($username)');
     assert('is_string($password)');
     if (empty($password)) {
         SimpleSAML_Logger::info($this->location . ': Login with empty password disallowed.');
         throw new SimpleSAML_Error_Error('WRONGUSERPASS');
     }
     $ldap = new SimpleSAML_Auth_LDAP($this->hostname, $this->enableTLS, $this->debug, $this->timeout, $this->port, $this->referrals);
     if (!$this->searchEnable) {
         $ldapusername = addcslashes($username, ',+"\\<>;*');
         $dn = str_replace('%username%', $ldapusername, $this->dnPattern);
     } else {
         if ($this->searchUsername !== NULL) {
             if (!$ldap->bind($this->searchUsername, $this->searchPassword)) {
                 throw new Exception('Error authenticating using search username & password.');
             }
         }
         $dn = $ldap->searchfordn($this->searchBase, $this->searchAttributes, $username, TRUE);
         if ($dn === NULL) {
             /* User not found with search. */
             SimpleSAML_Logger::info($this->location . ': Unable to find users DN. username=\'' . $username . '\'');
             throw new SimpleSAML_Error_Error('WRONGUSERPASS');
         }
     }
     $qaLogin = SimpleSAML_Auth_Source::getById('auth2factor');
     if (!$ldap->bind($dn, $password, $sasl_args)) {
         SimpleSAML_Logger::info($this->location . ': ' . $username . ' failed to authenticate. DN=' . $dn);
         /* Account lockout feature */
         // we need mail attributes so that we can notify user of locked account
         $attributes = $ldap->getAttributes($dn, $this->searchAttributes);
         // TODO what if these attributes are not available for search or not set in config?
         $qaLogin->failedLoginAttempt($username, 'login_count', array('name' => $attributes['givenName'][0], 'mail' => $attributes['mail'][0], 'uid' => $attributes['uid'][0]));
         $failedAttempts = $qaLogin->getFailedAttempts($username);
         $loginCount = (int) (!empty($failedAttempts)) ? $failedAttempts[0]['login_count'] : 0;
         $answerCount = (int) (!empty($failedAttempts)) ? $failedAttempts[0]['answer_count'] : 0;
         $failCount = $loginCount + $answerCount;
         // TODO this is bad! what if maxFailLogin is not set (i.e 0) or less than 3? instant lock?
         $firstFailCount = $qaLogin->getmaxFailLogin() - 2;
         $secondFailCount = $qaLogin->getmaxFailLogin() - 1;
         if ($failCount == $firstFailCount) {
             throw new SimpleSAML_Error_Error('2FAILEDATTEMPTWARNING');
         }
         if ($failCount == $secondFailCount) {
             throw new SimpleSAML_Error_Error('1FAILEDATTEMPTWARNING');
         }
         if ($qaLogin->isLocked($username)) {
             throw new SimpleSAML_Error_Error('ACCOUNTLOCKED');
         }
         throw new SimpleSAML_Error_Error('WRONGUSERPASS');
     }
     /* In case of SASL bind, authenticated and authorized DN may differ */
     if (isset($sasl_args)) {
         $dn = $ldap->whoami($this->searchBase, $this->searchAttributes);
     }
     /* Are privs needed to get the attributes? */
     if ($this->privRead) {
         /* Yes, rebind with privs */
         if (!$ldap->bind($this->privUsername, $this->privPassword)) {
             throw new Exception('Error authenticating using privileged DN & password.');
         }
     }
     // if we are here - we must have logged in successfully .. therefore reset login attempts
     $qaLogin->resetFailedLoginAttempts($username, 'login_count');
     return $ldap->getAttributes($dn, $this->attributes);
 }
<?php

/**
 * @author Shoaib Ali, Catalyst IT
 * @package simpleSAMLphp
 * @version $Id$
 */
$as = SimpleSAML_Configuration::getConfig('authsources.php')->getValue('auth2factor');
// Get session object
$session = \SimpleSAML_Session::getSessionFromRequest();
// Get the auth source so we can retrieve the URL we are ment to redirect to
$qaLogin = SimpleSAML_Auth_Source::getById('auth2factor');
// Trigger logout for the main auth source
if ($session->isValid($as['mainAuthSource'])) {
    SimpleSAML_Auth_Default::initLogout($qaLogin->getLogoutURL(), $as['mainAuthSource']);
}
 /**
  * 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);
 }
Example #17
0
 /**
  * Log out from this authentication source.
  *
  * This method either logs the user out from Negotiate or passes the
  * logout call to the fallback module.
  *
  * @param array &$state	 Information about the current logout operation.
  */
 public function logout(&$state)
 {
     assert('is_array($state)');
     /* Get the source that was used to authenticate */
     $authId = $state['negotiate:backend'];
     SimpleSAML_Logger::debug('Negotiate - logout has the following authId: "' . $authId . '"');
     if ($authId === NULL) {
         $session = SimpleSAML_Session::getInstance();
         $session->setData('negotiate:disable', 'session', TRUE, 24 * 60 * 60);
         parent::logout($state);
     } else {
         $source = SimpleSAML_Auth_Source::getById($authId);
         $source->logout($state);
     }
 }
Example #18
0
 /**
  * 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);
 }
Example #19
0
 * @version $Id$
 */
if (!array_key_exists('AuthState', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing AuthState parameter.');
}
$authStateId = $_REQUEST['AuthState'];
// 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, sspmod_multiauth_Auth_Source_MultiAuth::STAGEID);
if (array_key_exists("SimpleSAML_Auth_Default.id", $state)) {
    $authId = $state["SimpleSAML_Auth_Default.id"];
    $as = SimpleSAML_Auth_Source::getById($authId);
} else {
    $as = NULL;
}
$source = NULL;
if (array_key_exists('source', $_REQUEST)) {
    $source = $_REQUEST['source'];
} else {
    foreach ($_REQUEST as $k => $v) {
        $k = explode('-', $k, 2);
        if (count($k) === 2 && $k[0] === 'src') {
            $source = base64_decode($k[1]);
        }
    }
}
if ($source !== NULL) {
Example #20
0
*
*/
$username = !empty($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
$password = !empty($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;
if ($username === NULL || $password === NULL) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
}
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$idpEntityId = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
$idp = SimpleSAML_IdP::getById('saml2:' . $idpEntityId);
$auth = $idp->getConfig()->getString('auth');
$authSource = null;
if (SimpleSAML_Auth_Source::getById($auth) !== NULL) {
    $authSource = new SimpleSAML_Auth_Simple($auth);
}
if ($debug) {
    var_dump($authSource);
}
/* Attempt to log in. */
/*
 try {
 $attributes = $authSource->getAuthSource()->login($username, $password);
 } catch (Exception $e) {
 SimpleSAML_Logger::stats('Unsuccessful login attempt from '.$_SERVER['REMOTE_ADDR'].'.');
 throw $e;
 }
*
*/
Example #21
0
 /**
  * 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);
 }
<?php

/**
 * @author Tamas Frank, NIIFI
 *
 */
// Get session object
$session = SimpleSAML_Session::getSession();
// Get the authetication state
$authStateId = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authStateId, 'authtfaga.stage');
assert('array_key_exists("SimpleSAML_Auth_Source.id", $state)');
$authId = $state['SimpleSAML_Auth_Source.id'];
$as = SimpleSAML_Configuration::getConfig('authsources.php')->getValue($authId);
// Use 2 factor authentication class
$gaLogin = SimpleSAML_Auth_Source::getById($authId, 'sspmod_authtfaga_Auth_Source_authtfaga');
if ($gaLogin === null) {
    throw new Exception('Invalid authentication source: ' . $authId);
}
// Init template
$template = 'authtfaga:login.php';
$globalConfig = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($globalConfig, $template);
$errorCode = null;
//If user doesn't have session, force to use the main authentication method
if (!$session->isValid($as['mainAuthSource'])) {
    SimpleSAML_Auth_Default::initLogin($as['mainAuthSource'], SimpleSAML_Utilities::selfURL());
}
$attributes = $session->getAuthData($as['mainAuthSource'], 'Attributes');
$state['Attributes'] = $attributes;
$uid = $attributes[$as['uidField']][0];
Example #23
0
 /**
  * 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');
 }
Example #24
0
     */
} elseif (array_key_exists('spentityid', $_GET)) {
    /* Creating a request cache, even though there was no request, and adding the
     * information that is neccessary to be able to respond with an unsolited response
     */
    $requestcache = array('Issuer' => $_GET['spentityid']);
    if (isset($_GET['RelayState'])) {
        $requestcache['RelayState'] = $_GET['RelayState'];
    }
} else {
    SimpleSAML_Utilities::fatalError($session->getTrackID(), 'SSOSERVICEPARAMS');
}
/* Check whether we should authenticate with an AuthSource. Any time the auth-option matches a
 * valid AuthSource, we assume that this is the case.
 */
if (SimpleSAML_Auth_Source::getById($idpmetadata['auth']) !== NULL) {
    /* Authenticate with an AuthSource. */
    $authSource = TRUE;
    $authority = $idpmetadata['auth'];
} else {
    $authSource = FALSE;
    $authority = SimpleSAML_Utilities::getAuthority($idpmetadata);
}
/**
 * As we have passed the code above, we have an associated request that is already processed.
 *
 * Now we check whether we have a authenticated session. If we do not have an authenticated session,
 * we look up in the metadata of the IdP, to see what authenticaiton module to use, then we redirect
 * the user to the authentication module, to authenticate. Later the user is redirected back to this
 * endpoint - then the session is authenticated and set, and the user is redirected back with a RequestID
 * parameter so we can retrieve the cached information from the request.
Example #25
0
 /**
  * Log out from this authentication source.
  *
  * This method retrieves the authentication source used for this
  * session and then call the logout method on it.
  *
  * @param array &$state	 Information about the current logout operation.
  */
 public function logout(&$state)
 {
     assert('is_array($state)');
     /* Get the source that was used to authenticate */
     $session = SimpleSAML_Session::getSessionFromRequest();
     $authId = $session->getData(self::SESSION_SOURCE, $this->authId);
     $source = SimpleSAML_Auth_Source::getById($authId);
     if ($source === NULL) {
         throw new Exception('Invalid authentication source during logout: ' . $source);
     }
     /* Then, do the logout on it */
     $source->logout($state);
 }
Example #26
0
 /**
  * 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);
 }
Example #27
0
 /**
  * Require admin access for current page.
  *
  * This is a helper-function for limiting a page to admin access. It will redirect
  * the user to a login page if the current user doesn't have admin access.
  */
 public static function requireAdmin()
 {
     if (self::isAdmin()) {
         return;
     }
     $returnTo = self::selfURL();
     /* Not authenticated as admin user. Start authentication. */
     if (SimpleSAML_Auth_Source::getById('admin') !== NULL) {
         $as = new SimpleSAML_Auth_Simple('admin');
         $as->login();
     } else {
         /* For backwards-compatibility. */
         $config = SimpleSAML_Configuration::getInstance();
         self::redirectTrustedURL('/' . $config->getBaseURL() . 'auth/login-admin.php', array('RelayState' => $returnTo));
     }
 }
Example #28
0
    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 {
        $state['Attributes'] = array('uid' => array($creds['uid']), 'organization' => array($creds['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"));
 /**
  * Get available organizations.
  *
  * This function is used by the login form to get the available organizations.
  *
  * @param string $authStateId  The identifier of the authentication state.
  * @return array|NULL  Array of organizations. NULL if the user must enter the
  *         organization as part of the username.
  */
 public static function listOrganizations($authStateId)
 {
     assert('is_string($authStateId)');
     /* 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 === 'force') {
         return NULL;
     }
     return $source->getOrganizations();
 }
Example #30
0
 private function getAttributes()
 {
     $nameId = $this->query->getNameId();
     if (!$nameId) {
         throw new SimpleSAML_Error_BadRequest('[aa] Error getting NameID from AttributeQuery.');
     }
     if (array_key_exists('Format', $nameId)) {
         $nameIdFormat = $nameId['Format'];
     }
     SimpleSAML_Logger::info('[aa] Received attribute query for ' . $nameId['Value'] . ' (nameIdFormat: ' . $nameIdFormat . ')');
     /* Get the attributes from the AuthSource */
     $spMetadataArray = $this->spMetadata->toArray();
     $aaMetadataArray = $this->aaMetadata->toArray();
     $attributes = array();
     $state = array('Attributes' => $attributes, 'Destination' => $spMetadataArray, 'Source' => $aaMetadataArray, 'aa:nameId' => $nameId['Value'], 'aa:nameIdFormat' => $nameIdFormat);
     $as = SimpleSAML_Auth_Source::getById($this->config->getValue('authsource'));
     $as->authenticate($state);
     $attributes = $state['Attributes'];
     return $attributes;
 }