/**
* This function retrieves the current instance of the metadata handler.
* The metadata handler will be instantiated if this is the first call
* to this function.
*
* @return SimpleSAML_Metadata_MetaDataStorageHandler The current metadata handler instance.
*/
public static function getMetadataHandler()
{
if (self::$metadataHandler === null) {
self::$metadataHandler = new SimpleSAML_Metadata_MetaDataStorageHandler();
}
return self::$metadataHandler;
}
public function actionSso()
{
//logout previous sso session
\utilities\Registry::clearRegistry();
$isRequestPost = $this->_request->isPost();
if ($isRequestPost) {
// check if every required parameter is set or not
$username = $this->_request->getParam('username', null);
$password = $this->_request->getParam('password', null);
$referrer = $this->_request->getParam('spentityid', null);
if (!$username) {
$this->_response->renderJson(array('message' => 'Username is not set'));
}
if (!$password) {
$this->_response->renderJson(array('message' => 'Password is not set'));
}
if (!$referrer) {
$this->_response->renderJson(array('message' => 'Referrer not set'));
}
$objDbUserauth = new \models\Users();
// check if user is authenticated or not
$userAuthenticationStatus = $objDbUserauth->authenticate($username, $password);
// user locked due to 5 invalid attempts
if (\models\Users::ERROR_USER_LOCKED === $userAuthenticationStatus) {
$this->_response->renderJson(array('message' => 'Your account is locked due to 5 invalid attempts', 'authstatus' => $userAuthenticationStatus));
}
//user password is expired
if (\models\Users::ERROR_USER_PWD_EXPIRED === $userAuthenticationStatus) {
$this->_response->renderJson(array('message' => 'Your password is expired', 'authstatus' => $userAuthenticationStatus));
}
//user authentication is successfull
if ($userAuthenticationStatus === true) {
$metadata = \SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$idpEntityId = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
$idp = \SimpleSAML_IdP::getById('saml2:' . $idpEntityId);
\sspmod_saml_IdP_SAML2::receiveAuthnRequest($idp);
assert('FALSE');
} else {
//handle invalid attempts
$objInvalidAttempts = new \models\UserLoginAttempts();
$loginAttemptsLeft = $objInvalidAttempts->handleInvalidLoginAttempts($username);
$invalidAttempt = false;
// if attempt is invalid username is wrong
$message = "Invalid credentials";
if ($loginAttemptsLeft !== false) {
// if last attempt was hit then show that account is locked
if ($loginAttemptsLeft === 0) {
$this->_response->renderJson(array('message' => 'Your account is locked due to 5 invalid attempts', 'authstatus' => \models\Users::ERROR_USER_LOCKED));
}
$invalidAttempt = true;
$message = "Incorrect Password.You have {$loginAttemptsLeft} attempts left";
}
$this->_response->renderJson(array('message' => $message, 'invalidAttempt' => $invalidAttempt));
exit;
}
}
$this->_response->renderJson(array('message' => 'Only post request are accepted'));
}
public function createRedirect($destination, $shire = NULL)
{
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$idpmetadata = $metadata->getMetaData($destination, 'shib13-idp-remote');
if ($shire === NULL) {
$shire = $metadata->getGenerated('AssertionConsumerService', 'shib13-sp-hosted');
}
if (!isset($idpmetadata['SingleSignOnService'])) {
throw new Exception('Could not find the SingleSignOnService parameter in the Shib 1.3 IdP Remote metadata. This parameter has changed name from an earlier version of simpleSAMLphp, when it was called SingleSignOnUrl. Please check your shib13-sp-remote.php configuration the IdP with entity id ' . $destination . ' and make sure the SingleSignOnService parameter is set.');
}
$desturl = $idpmetadata['SingleSignOnService'];
$target = $this->getRelayState();
$url = $desturl . '?' . 'providerId=' . urlencode($this->getIssuer()) . '&shire=' . urlencode($shire) . (isset($target) ? '&target=' . urlencode($target) : '');
return $url;
}
/**
* Initializes this discovery service.
*
* The constructor does the parsing of the request. If this is an invalid request, it will
* throw an exception.
*
* @param array $metadataSets Array with metadata sets we find remote entities in.
* @param string $instance The name of this instance of the discovery service.
*/
public function __construct(array $metadataSets, $instance)
{
assert('is_string($instance)');
/* Initialize standard classes. */
$this->config = SimpleSAML_Configuration::getInstance();
$this->metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$this->session = SimpleSAML_Session::getSessionFromRequest();
$this->instance = $instance;
$this->metadataSets = $metadataSets;
$this->log('Accessing discovery service.');
/* Standard discovery service parameters. */
if (!array_key_exists('entityID', $_GET)) {
throw new Exception('Missing parameter: entityID');
} else {
$this->spEntityId = $_GET['entityID'];
}
if (!array_key_exists('returnIDParam', $_GET)) {
$this->returnIdParam = 'entityID';
} else {
$this->returnIdParam = $_GET['returnIDParam'];
}
$this->log('returnIdParam initially set to [' . $this->returnIdParam . ']');
if (!array_key_exists('return', $_GET)) {
throw new Exception('Missing parameter: return');
} else {
$this->returnURL = SimpleSAML_Utilities::checkURLAllowed($_GET['return']);
}
$this->isPassive = FALSE;
if (array_key_exists('isPassive', $_GET)) {
if ($_GET['isPassive'] === 'true') {
$this->isPassive = TRUE;
}
}
$this->log('isPassive initially set to [' . ($this->isPassive ? 'TRUE' : 'FALSE') . ']');
if (array_key_exists('IdPentityID', $_GET)) {
$this->setIdPentityID = $_GET['IdPentityID'];
} else {
$this->setIdPentityID = NULL;
}
if (array_key_exists('IDPList', $_REQUEST)) {
$this->scopedIDPList = $_REQUEST['IDPList'];
}
}
/**
* Process a authentication response
*
* This function saves the state, and redirects the user to the page where
* the user can log in with their second factor.
*
* @param array &$state The state of the response.
*
* @return void
*/
public function process(&$state)
{
assert('is_array($state)');
assert('array_key_exists("Destination", $state)');
assert('array_key_exists("entityid", $state["Destination"])');
assert('array_key_exists("metadata-set", $state["Destination"])');
assert('array_key_exists("Source", $state)');
assert('array_key_exists("entityid", $state["Source"])');
assert('array_key_exists("metadata-set", $state["Source"])');
$spEntityId = $state['Destination']['entityid'];
$idpEntityId = $state['Source']['entityid'];
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
/**
* If the Duo Security module is active on a bridge $state['saml:sp:IdP']
* will contain an entry id for the remote IdP. If not, then
* it is active on a local IdP and nothing needs to be
* done.
*/
if (isset($state['saml:sp:IdP'])) {
$idpEntityId = $state['saml:sp:IdP'];
$idpmeta = $metadata->getMetaData($idpEntityId, 'saml20-idp-remote');
$state['Source'] = $idpmeta;
}
if (isset($state['duo_complete'])) {
return;
}
// Set Keys for Duo SDK
$state['duosecurity:akey'] = $this->_akey;
$state['duosecurity:ikey'] = $this->_ikey;
$state['duosecurity:skey'] = $this->_skey;
$state['duosecurity:host'] = $this->_host;
$state['duosecurity:authSources'] = $this->_authSources;
$state['duosecurity:usernameAttribute'] = $this->_usernameAttribute;
// User interaction nessesary. Throw exception on isPassive request
if (isset($state['isPassive']) && $state['isPassive'] == true) {
throw new SimpleSAML_Error_NoPassive('Unable to login with passive request.');
}
// Save state and redirect
$id = SimpleSAML_Auth_State::saveState($state, 'duosecurity:request');
$url = SimpleSAML_Module::getModuleURL('duosecurity/getduo.php');
SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id));
}
/**
* Get a list of associated SAML 2 SPs.
*
* This function is just for backwards-compatibility. New code should
* use the SimpleSAML_IdP::getAssociations()-function.
*
* @return array Array of SAML 2 entityIDs.
* @deprecated Will be removed in the future.
*/
public function get_sp_list()
{
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
try {
$idpEntityId = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
$idp = SimpleSAML_IdP::getById('saml2:' . $idpEntityId);
} catch (Exception $e) {
/* No SAML 2 IdP configured? */
return array();
}
$ret = array();
foreach ($idp->getAssociations() as $assoc) {
if (isset($assoc['saml:entityID'])) {
$ret[] = $assoc['saml:entityID'];
}
}
return $ret;
}
/**
* Process a authentication response
*
* This function saves the state, and redirects the user to the page where
* the user can authorize the release of the attributes.
* If storage is used and the consent has already been given the user is
* passed on.
*
* @param array &$state The state of the response.
*
* @return void
*/
public function process(&$state)
{
assert('is_array($state)');
assert('array_key_exists("UserID", $state)');
assert('array_key_exists("Destination", $state)');
assert('array_key_exists("entityid", $state["Destination"])');
assert('array_key_exists("metadata-set", $state["Destination"])');
assert('array_key_exists("entityid", $state["Source"])');
assert('array_key_exists("metadata-set", $state["Source"])');
$spEntityId = $state['Destination']['entityid'];
$idpEntityId = $state['Source']['entityid'];
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
/**
* If the consent module is active on a bridge $state['saml:sp:IdP']
* will contain an entry id for the remote IdP. If not, then the
* consent module is active on a local IdP and nothing needs to be
* done.
*/
if (isset($state['saml:sp:IdP'])) {
$idpEntityId = $state['saml:sp:IdP'];
$idpmeta = $metadata->getMetaData($idpEntityId, 'saml20-idp-remote');
$state['Source'] = $idpmeta;
}
$statsData = array('spEntityID' => $spEntityId);
// Do not use consent if disabled
if (isset($state['Source']['consent.disable']) && self::checkDisable($state['Source']['consent.disable'], $spEntityId)) {
SimpleSAML_Logger::debug('Consent: Consent disabled for entity ' . $spEntityId . ' with IdP ' . $idpEntityId);
SimpleSAML_Stats::log('consent:disabled', $statsData);
return;
}
if (isset($state['Destination']['consent.disable']) && self::checkDisable($state['Destination']['consent.disable'], $idpEntityId)) {
SimpleSAML_Logger::debug('Consent: Consent disabled for entity ' . $spEntityId . ' with IdP ' . $idpEntityId);
SimpleSAML_Stats::log('consent:disabled', $statsData);
return;
}
if ($this->_store !== null) {
$source = $state['Source']['metadata-set'] . '|' . $idpEntityId;
$destination = $state['Destination']['metadata-set'] . '|' . $spEntityId;
$attributes = $state['Attributes'];
// Remove attributes that do not require consent
foreach ($attributes as $attrkey => $attrval) {
if (in_array($attrkey, $this->_noconsentattributes)) {
unset($attributes[$attrkey]);
}
}
SimpleSAML_Logger::debug('Consent: userid: ' . $state['UserID']);
SimpleSAML_Logger::debug('Consent: source: ' . $source);
SimpleSAML_Logger::debug('Consent: destination: ' . $destination);
$userId = self::getHashedUserID($state['UserID'], $source);
$targetedId = self::getTargetedID($state['UserID'], $source, $destination);
$attributeSet = self::getAttributeHash($attributes, $this->_includeValues);
SimpleSAML_Logger::debug('Consent: hasConsent() [' . $userId . '|' . $targetedId . '|' . $attributeSet . ']');
try {
if ($this->_store->hasConsent($userId, $targetedId, $attributeSet)) {
// Consent already given
SimpleSAML_Logger::stats('Consent: Consent found');
SimpleSAML_Stats::log('consent:found', $statsData);
return;
}
SimpleSAML_Logger::stats('Consent: Consent notfound');
SimpleSAML_Stats::log('consent:notfound', $statsData);
$state['consent:store'] = $this->_store;
$state['consent:store.userId'] = $userId;
$state['consent:store.destination'] = $targetedId;
$state['consent:store.attributeSet'] = $attributeSet;
} catch (Exception $e) {
SimpleSAML_Logger::error('Consent: Error reading from storage: ' . $e->getMessage());
SimpleSAML_Logger::stats('Consent: Failed');
SimpleSAML_Stats::log('consent:failed', $statsData);
}
} else {
SimpleSAML_Logger::stats('Consent: No storage');
SimpleSAML_Stats::log('consent:nostorage', $statsData);
}
$state['consent:focus'] = $this->_focus;
$state['consent:checked'] = $this->_checked;
$state['consent:hiddenAttributes'] = $this->_hiddenAttributes;
$state['consent:noconsentattributes'] = $this->_noconsentattributes;
$state['consent:showNoConsentAboutService'] = $this->_showNoConsentAboutService;
// User interaction nessesary. Throw exception on isPassive request
if (isset($state['isPassive']) && $state['isPassive'] == true) {
SimpleSAML_Stats::log('consent:nopassive', $statsData);
throw new SimpleSAML_Error_NoPassive('Unable to give consent on passive request.');
}
// Save state and redirect
$id = SimpleSAML_Auth_State::saveState($state, 'consent:request');
$url = SimpleSAML_Module::getModuleURL('consent/getconsent.php');
SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id));
//.........这里部分代码省略.........
/**
* Process a authentication response.
*
* This function saves the state, and redirects the user to the page where the user
* can authorize the release of the attributes.
*
* @param array $state The state of the response.
*/
public function process(&$state)
{
assert('is_array($state)');
assert('array_key_exists("UserID", $state)');
assert('array_key_exists("Destination", $state)');
assert('array_key_exists("entityid", $state["Destination"])');
assert('array_key_exists("metadata-set", $state["Destination"])');
assert('array_key_exists("entityid", $state["Source"])');
assert('array_key_exists("metadata-set", $state["Source"])');
$session = SimpleSAML_Session::getInstance();
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
/* If the consent module is active on a bridge $state['saml:sp:IdP'] will contain
* an entry id for the remote IdP. If not, then the
* consent module is active on a local IdP and nothing needs to be done.
*/
if (isset($state['saml:sp:IdP'])) {
$idpmeta = $metadata->getMetaData($state['saml:sp:IdP'], 'saml20-idp-remote');
$state['Source'] = $idpmeta;
} elseif ($session->getIdP() !== NULL) {
/* For backwards compatibility. TODO: Remove in version 1.8. */
$idpmeta = $metadata->getMetaData($session->getIdP(), 'saml20-idp-remote');
$state['Source'] = $idpmeta;
}
if ($this->store !== NULL) {
// Do not use consent if disabled on source entity
if (isset($state['Source']['consent.disable']) && in_array($state['Destination']['entityid'], $state['Source']['consent.disable'])) {
SimpleSAML_Logger::debug('Consent - Consent disabled for entity ' . $state['Destination']['entityid']);
return;
}
$source = $state['Source']['metadata-set'] . '|' . $state['Source']['entityid'];
$destination = $state['Destination']['metadata-set'] . '|' . $state['Destination']['entityid'];
SimpleSAML_Logger::debug('Consent - userid : ' . $state['UserID']);
SimpleSAML_Logger::debug('Consent - source : ' . $source);
SimpleSAML_Logger::debug('Consent - destination : ' . $destination);
$userId = self::getHashedUserID($state['UserID'], $source);
$targetedId = self::getTargetedID($state['UserID'], $source, $destination);
$attributeSet = self::getAttributeHash($state['Attributes'], $this->includeValues);
SimpleSAML_Logger::debug('Consent - hasConsent() : [' . $userId . '|' . $targetedId . '|' . $attributeSet . ']');
if ($this->store->hasConsent($userId, $targetedId, $attributeSet)) {
SimpleSAML_Logger::stats('consent found');
/* Consent already given. */
return;
}
SimpleSAML_Logger::stats('consent notfound');
$state['consent:store'] = $this->store;
$state['consent:store.userId'] = $userId;
$state['consent:store.destination'] = $targetedId;
$state['consent:store.attributeSet'] = $attributeSet;
} else {
SimpleSAML_Logger::stats('consent nostorage');
}
$state['consent:focus'] = $this->focus;
$state['consent:checked'] = $this->checked;
$state['consent:hiddenAttributes'] = $this->hiddenAttributes;
/* User interaction nessesary. Throw exception on isPassive request */
if (isset($state['isPassive']) && $state['isPassive'] == TRUE) {
throw new SimpleSAML_Error_NoPassive('Unable to give consent on passive request.');
}
/* Save state and redirect. */
$id = SimpleSAML_Auth_State::saveState($state, 'consent:request');
$url = SimpleSAML_Module::getModuleURL('consent/getconsent.php');
SimpleSAML_Utilities::redirect($url, array('StateId' => $id));
}
/**
* Re-authenticate an user.
*
* This function is called by the IdP to give the authentication source a chance to
* interact with the user even in the case when the user is already authenticated.
*
* @param array &$state Information about the current authentication.
*/
public function reauthenticate(array &$state)
{
assert('is_array($state)');
$session = SimpleSAML_Session::getSessionFromRequest();
$data = $session->getAuthState($this->authId);
foreach ($data as $k => $v) {
$state[$k] = $v;
}
// check if we have an IDPList specified in the request
if (isset($state['saml:IDPList']) && sizeof($state['saml:IDPList']) > 0 && !in_array($state['saml:sp:IdP'], $state['saml:IDPList'], true)) {
/*
* The user has an existing, valid session. However, the SP provided a list of IdPs it accepts for
* authentication, and the IdP the existing session is related to is not in that list.
*
* First, check if we recognize any of the IdPs requested.
*/
$mdh = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$known_idps = $mdh->getList();
$intersection = array_intersect($state['saml:IDPList'], array_keys($known_idps));
if (empty($intersection)) {
// all requested IdPs are unknown
throw new SimpleSAML\Module\saml\Error\NoSupportedIDP(\SAML2\Constants::STATUS_REQUESTER, 'None of the IdPs requested are supported by this proxy.');
}
/*
* We have at least one IdP in the IDPList that we recognize, and it's not the one currently in use. Let's
* see if this proxy enforces the use of one single IdP.
*/
if (!is_null($this->idp) && !in_array($this->idp, $intersection)) {
// an IdP is enforced but not requested
throw new SimpleSAML\Module\saml\Error\NoAvailableIDP(\SAML2\Constants::STATUS_REQUESTER, 'None of the IdPs requested are available to this proxy.');
}
/*
* We need to inform the user, and ask whether we should logout before starting the authentication process
* again with a different IdP, or cancel the current SSO attempt.
*/
SimpleSAML\Logger::warning("Reauthentication after logout is needed. The IdP '{$state['saml:sp:IdP']}' is not in the IDPList " . "provided by the Service Provider '{$state['core:SP']}'.");
$state['saml:sp:IdPMetadata'] = $this->getIdPMetadata($state['saml:sp:IdP']);
$state['saml:sp:AuthId'] = $this->authId;
self::askForIdPChange($state);
}
}
/**
* Accept a SAML Request and form a Response
* NOTE: that this function is Google Specific
*
*/
function gsaml_send_auth_response($samldata)
{
global $CFG, $SESSION, $USER;
SimpleSAML_Configuration::init($CFG->dirroot . '/auth/gsaml/config');
$config = SimpleSAML_Configuration::getInstance();
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$session = SimpleSAML_Session::getInstance();
try {
$idpentityid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
$idmetaindex = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted', 'metaindex');
$idpmetadata = $metadata->getMetaDataCurrent('saml20-idp-hosted');
if (!array_key_exists('auth', $idpmetadata)) {
throw new Exception('Missing mandatory parameter in SAML 2.0 IdP Hosted Metadata: [auth]');
}
} catch (Exception $exception) {
SimpleSAML_Utilities::fatalError($session->getTrackID(), 'METADATA', $exception);
}
/// SimpleSAML_Logger::info('SAML2.0 - IdP.SSOService: Accessing SAML 2.0 IdP endpoint SSOService');
if (!$config->getValue('enable.saml20-idp', false)) {
SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS');
}
$rawRequest = $samldata;
if (!empty($SESSION->samlrelaystate)) {
$relaystate = $SESSION->samlrelaystate;
} else {
$relaystate = NULL;
}
$decodedRequest = @base64_decode($rawRequest);
if (!$decodedRequest) {
throw new Exception('Could not base64 decode SAMLRequest GET parameter');
}
$samlRequestXML = @gzinflate($decodedRequest);
if (!$samlRequestXML) {
$error = error_get_last();
throw new Exception('Could not gzinflate base64 decoded SAMLRequest: ' . $error['message']);
}
SimpleSAML_Utilities::validateXMLDocument($samlRequestXML, 'saml20');
$samlRequest = new SimpleSAML_XML_SAML20_AuthnRequest($config, $metadata);
$samlRequest->setXML($samlRequestXML);
if (!is_null($relaystate)) {
$samlRequest->setRelayState($relaystate);
}
// $samlRequest presenting the request object
$authnrequest = $samlRequest;
if ($session == NULL) {
debugging('No SAML Session gsaml_send_auth_response', DEBUG_DEVELOPER);
return false;
// if this func returns we Know it's an error
}
if (!empty($USER->id)) {
// TODO: if moodle user is not the same as google user
// use the mapping
$username = $USER->username;
} else {
debugging('No User given to gsaml_send_auth_response', DEBUG_DEVELOPER);
return false;
}
//TODO: better errors
if (!($domain = get_config('auth/gsaml', 'domainname'))) {
debugging('No domain set in gsaml_send_auth_response', DEBUG_DEVELOPER);
return false;
// if this func returns we Know it's an error
}
$attributes['useridemail'] = array($username . '@' . $domain);
$session->doLogin('login');
// was login
$session->setAttributes($attributes);
$session->setNameID(array('value' => SimpleSAML_Utilities::generateID(), 'Format' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient'));
$requestcache = array('RequestID' => $authnrequest->getRequestID(), 'Issuer' => $authnrequest->getIssuer(), 'ConsentCookie' => SimpleSAML_Utilities::generateID(), 'RelayState' => $authnrequest->getRelayState());
try {
$spentityid = $requestcache['Issuer'];
$spmetadata = $metadata->getMetaData($spentityid, 'saml20-sp-remote');
$sp_name = isset($spmetadata['name']) ? $spmetadata['name'] : $spentityid;
// TODO: Are we really tracking SP's???
//
// Adding this service provider to the list of sessions.
// Right now the list is used for SAML 2.0 only.
$session->add_sp_session($spentityid);
/// SimpleSAML_Logger::info('SAML2.0 - IdP.SSOService: Sending back AuthnResponse to ' . $spentityid);
// TODO: handle passive situtation
// Rigth now I replaced $isPassive with isset($isPassive) to prevent notice on debug mode
if (isset($isPassive)) {
/* Generate an SAML 2.0 AuthNResponse message
With statusCode: urn:oasis:names:tc:SAML:2.0:status:NoPassive
*/
$ar = new SimpleSAML_XML_SAML20_AuthnResponse($config, $metadata);
$authnResponseXML = $ar->generate($idpentityid, $spentityid, $requestcache['RequestID'], null, array(), 'NoPassive');
// Sending the AuthNResponse using HTTP-Post SAML 2.0 binding
$httppost = new SimpleSAML_Bindings_SAML20_HTTPPost($config, $metadata);
$httppost->sendResponse($authnResponseXML, $idpentityid, $spentityid, $requestcache['RelayState']);
exit;
}
/*
* Attribute handling
*/
//.........这里部分代码省略.........
请发表评论