/**
  * 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()
 {
     $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');
 }
Esempio n. 3
0
 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'));
 }
Esempio n. 4
0
 public function createRedirect($destination, $shire)
 {
     $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $idpmetadata = $metadata->getMetaDataConfig($destination, 'shib13-idp-remote');
     $desturl = $idpmetadata->getDefaultEndpoint('SingleSignOnService', array('urn:mace:shibboleth:1.0:profiles:AuthnRequest'));
     $desturl = $desturl['Location'];
     $target = $this->getRelayState();
     $url = $desturl . '?' . 'providerId=' . urlencode($this->getIssuer()) . '&shire=' . urlencode($shire) . (isset($target) ? '&target=' . urlencode($target) : '');
     return $url;
 }
Esempio n. 5
0
 /**
  * Receive a SAML 2 message sent using the HTTP-Artifact binding.
  *
  * Throws an exception if it is unable receive the message.
  *
  * @return SAML2_Message The received message.
  * @throws Exception
  */
 public function receive()
 {
     if (array_key_exists('SAMLart', $_REQUEST)) {
         $artifact = base64_decode($_REQUEST['SAMLart']);
         $endpointIndex = bin2hex(substr($artifact, 2, 2));
         $sourceId = bin2hex(substr($artifact, 4, 20));
     } else {
         throw new Exception('Missing SAMLArt parameter.');
     }
     $metadataHandler = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $idpMetadata = $metadataHandler->getMetaDataConfigForSha1($sourceId, 'saml20-idp-remote');
     if ($idpMetadata === NULL) {
         throw new Exception('No metadata found for remote provider with SHA1 ID: ' . var_export($sourceId, TRUE));
     }
     $endpoint = NULL;
     foreach ($idpMetadata->getEndpoints('ArtifactResolutionService') as $ep) {
         if ($ep['index'] === hexdec($endpointIndex)) {
             $endpoint = $ep;
             break;
         }
     }
     if ($endpoint === NULL) {
         throw new Exception('No ArtifactResolutionService with the correct index.');
     }
     SAML2_Utils::getContainer()->getLogger()->debug("ArtifactResolutionService endpoint being used is := " . $endpoint['Location']);
     //Construct the ArtifactResolve Request
     $ar = new SAML2_ArtifactResolve();
     /* Set the request attributes */
     $ar->setIssuer($this->spMetadata->getString('entityid'));
     $ar->setArtifact($_REQUEST['SAMLart']);
     $ar->setDestination($endpoint['Location']);
     require_once realpath(__DIR__ . '/../../../simplesamlphp/modules/saml/lib/Message.php');
     /* Sign the request */
     sspmod_saml_Message::addSign($this->spMetadata, $idpMetadata, $ar);
     // Shoaib - moved from the SOAPClient.
     $soap = new SAML2_SOAPClient();
     // Send message through SoapClient
     /** @var SAML2_ArtifactResponse $artifactResponse */
     $artifactResponse = $soap->send($ar, $this->spMetadata);
     if (!$artifactResponse->isSuccess()) {
         return false;
     }
     $xml = $artifactResponse->getAny();
     if ($xml === NULL) {
         /* Empty ArtifactResponse - possibly because of Artifact replay? */
         return NULL;
     }
     $samlResponse = SAML2_Message::fromXML($xml);
     $samlResponse->addValidator(array(get_class($this), 'validateSignature'), $artifactResponse);
     if (isset($_REQUEST['RelayState'])) {
         $samlResponse->setRelayState($_REQUEST['RelayState']);
     }
     return $samlResponse;
 }
Esempio n. 6
0
 /**
  * Retrieve the list of IdPs which are stored in the metadata.
  *
  * @return array An array with entityid => metadata mappings.
  */
 protected function getIdPList()
 {
     $idpList = array();
     foreach ($this->metadataSets as $metadataSet) {
         $newList = $this->metadata->getList($metadataSet);
         /*
          * Note that we merge the entities in reverse order. This ensures that it is the entity in the first
          * metadata set that "wins" if two metadata sets have the same entity.
          */
         $idpList = array_merge($newList, $idpList);
     }
     return $idpList;
 }
Esempio n. 7
0
 public function getPresentation()
 {
     $mh = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $metadata = $mh->getList($this->config);
     $translation = array('_' => 'All services');
     foreach ($this->fields as $field) {
         if (array_key_exists($field, $metadata)) {
             if (array_key_exists('name', $metadata[$field])) {
                 $translation[$field] = $this->template->t($metadata[$field]['name'], array(), FALSE);
             }
         }
     }
     return $translation;
 }
Esempio n. 8
0
 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;
 }
Esempio n. 9
0
 /**
  * Receive an authentication request.
  *
  * @param SimpleSAML_IdP $idp  The IdP we are receiving it for.
  */
 public static function receiveAuthnRequest(SimpleSAML_IdP $idp)
 {
     if (isset($_REQUEST['cookieTime'])) {
         $cookieTime = (int) $_REQUEST['cookieTime'];
         if ($cookieTime + 5 > time()) {
             /*
              * Less than five seconds has passed since we were
              * here the last time. Cookies are probably disabled.
              */
             \SimpleSAML\Utils\HTTP::checkSessionCookie(\SimpleSAML\Utils\HTTP::getSelfURL());
         }
     }
     if (!isset($_REQUEST['providerId'])) {
         throw new SimpleSAML_Error_BadRequest('Missing providerId parameter.');
     }
     $spEntityId = (string) $_REQUEST['providerId'];
     if (!isset($_REQUEST['shire'])) {
         throw new SimpleSAML_Error_BadRequest('Missing shire parameter.');
     }
     $shire = (string) $_REQUEST['shire'];
     if (isset($_REQUEST['target'])) {
         $target = $_REQUEST['target'];
     } else {
         $target = NULL;
     }
     SimpleSAML\Logger::info('Shib1.3 - IdP.SSOService: Got incoming Shib authnRequest from ' . var_export($spEntityId, TRUE) . '.');
     $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'shib13-sp-remote');
     $found = FALSE;
     foreach ($spMetadata->getEndpoints('AssertionConsumerService') as $ep) {
         if ($ep['Binding'] !== 'urn:oasis:names:tc:SAML:1.0:profiles:browser-post') {
             continue;
         }
         if ($ep['Location'] !== $shire) {
             continue;
         }
         $found = TRUE;
         break;
     }
     if (!$found) {
         throw new Exception('Invalid AssertionConsumerService for SP ' . var_export($spEntityId, TRUE) . ': ' . var_export($shire, TRUE));
     }
     SimpleSAML_Stats::log('saml:idp:AuthnRequest', array('spEntityID' => $spEntityId, 'protocol' => 'saml1'));
     $sessionLostURL = \SimpleSAML\Utils\HTTP::addURLParameters(\SimpleSAML\Utils\HTTP::getSelfURL(), array('cookieTime' => time()));
     $state = array('Responder' => array('sspmod_saml_IdP_SAML1', 'sendResponse'), 'SPMetadata' => $spMetadata->toArray(), SimpleSAML_Auth_State::RESTART => $sessionLostURL, 'saml:shire' => $shire, 'saml:target' => $target, 'saml:AuthnRequestReceivedAt' => microtime(TRUE));
     $idp->handleAuthenticationRequest($state);
 }
Esempio n. 10
0
 /**
  * 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));
 }
Esempio n. 12
0
 public function configure()
 {
     $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $entitylist = $metadata->getList('saml20-sp-remote');
     foreach ($entitylist as $key => $value) {
         $spidlist[$key] = $key;
     }
     $i18n = sfContext::getInstance()->getI18N();
     $this->widgetSchema['description'] = new sfWidgetFormTextarea();
     $this->widgetSchema['entityId'] = new sfWidgetFormChoice(array('choices' => $spidlist));
     $this->widgetSchema->setLabel('description', $i18n->__('Service description'));
     $this->widgetSchema->setLabel('url', $i18n->__('Service homepage'));
     $this->widgetSchema->setLabel('entityId', $i18n->__('SAML SP entity id'));
     $this->widgetSchema->setLabel('name', $i18n->__('Service name'));
     //$this->widgetSchema->setLabel('type', $i18n->__('Registration type'));
     unset($this['type']);
     unset($this['organization_list']);
     unset($this['principal_id']);
     unset($this['created_at']);
     unset($this['updated_at']);
     unset($this['token']);
 }
Esempio n. 13
0
 /**
  * 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;
 }
Esempio n. 14
0
 /**
  * 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));
 }
Esempio n. 15
0
 /**
  * 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));
 }
Esempio n. 16
0
 /**
  * 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);
     }
 }
Esempio n. 17
0
/**
 * Accept a SAML Request and form a Response
 * NOTE: that this function is Google Specific
 * 
 */
function gsaml_send_auth_response($samldata)
{
    global $CFG, $SESSION, $USER;
    SimpleSAML_Configuration::init($CFG->dirroot . '/auth/gsaml/config');
    $config = SimpleSAML_Configuration::getInstance();
    $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
    $session = SimpleSAML_Session::getInstance();
    try {
        $idpentityid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
        $idmetaindex = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted', 'metaindex');
        $idpmetadata = $metadata->getMetaDataCurrent('saml20-idp-hosted');
        if (!array_key_exists('auth', $idpmetadata)) {
            throw new Exception('Missing mandatory parameter in SAML 2.0 IdP Hosted Metadata: [auth]');
        }
    } catch (Exception $exception) {
        SimpleSAML_Utilities::fatalError($session->getTrackID(), 'METADATA', $exception);
    }
    ///	SimpleSAML_Logger::info('SAML2.0 - IdP.SSOService: Accessing SAML 2.0 IdP endpoint SSOService');
    if (!$config->getValue('enable.saml20-idp', false)) {
        SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS');
    }
    $rawRequest = $samldata;
    if (!empty($SESSION->samlrelaystate)) {
        $relaystate = $SESSION->samlrelaystate;
    } else {
        $relaystate = NULL;
    }
    $decodedRequest = @base64_decode($rawRequest);
    if (!$decodedRequest) {
        throw new Exception('Could not base64 decode SAMLRequest GET parameter');
    }
    $samlRequestXML = @gzinflate($decodedRequest);
    if (!$samlRequestXML) {
        $error = error_get_last();
        throw new Exception('Could not gzinflate base64 decoded SAMLRequest: ' . $error['message']);
    }
    SimpleSAML_Utilities::validateXMLDocument($samlRequestXML, 'saml20');
    $samlRequest = new SimpleSAML_XML_SAML20_AuthnRequest($config, $metadata);
    $samlRequest->setXML($samlRequestXML);
    if (!is_null($relaystate)) {
        $samlRequest->setRelayState($relaystate);
    }
    // $samlRequest presenting the request object
    $authnrequest = $samlRequest;
    if ($session == NULL) {
        debugging('No SAML Session gsaml_send_auth_response', DEBUG_DEVELOPER);
        return false;
        // if this func returns we Know it's an error
    }
    if (!empty($USER->id)) {
        // TODO: if moodle user is not the same as google user
        //       use the mapping
        $username = $USER->username;
    } else {
        debugging('No User given to gsaml_send_auth_response', DEBUG_DEVELOPER);
        return false;
    }
    //TODO: better errors
    if (!($domain = get_config('auth/gsaml', 'domainname'))) {
        debugging('No domain set in gsaml_send_auth_response', DEBUG_DEVELOPER);
        return false;
        // if this func returns we Know it's an error
    }
    $attributes['useridemail'] = array($username . '@' . $domain);
    $session->doLogin('login');
    // was login
    $session->setAttributes($attributes);
    $session->setNameID(array('value' => SimpleSAML_Utilities::generateID(), 'Format' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient'));
    $requestcache = array('RequestID' => $authnrequest->getRequestID(), 'Issuer' => $authnrequest->getIssuer(), 'ConsentCookie' => SimpleSAML_Utilities::generateID(), 'RelayState' => $authnrequest->getRelayState());
    try {
        $spentityid = $requestcache['Issuer'];
        $spmetadata = $metadata->getMetaData($spentityid, 'saml20-sp-remote');
        $sp_name = isset($spmetadata['name']) ? $spmetadata['name'] : $spentityid;
        // TODO: Are we really tracking SP's???
        //
        // Adding this service provider to the list of sessions.
        // Right now the list is used for SAML 2.0 only.
        $session->add_sp_session($spentityid);
        ///		SimpleSAML_Logger::info('SAML2.0 - IdP.SSOService: Sending back AuthnResponse to ' . $spentityid);
        // TODO: handle passive situtation
        // Rigth now I replaced $isPassive with isset($isPassive) to prevent notice on debug mode
        if (isset($isPassive)) {
            /* Generate an SAML 2.0 AuthNResponse message
            			   With statusCode: urn:oasis:names:tc:SAML:2.0:status:NoPassive
            			*/
            $ar = new SimpleSAML_XML_SAML20_AuthnResponse($config, $metadata);
            $authnResponseXML = $ar->generate($idpentityid, $spentityid, $requestcache['RequestID'], null, array(), 'NoPassive');
            // Sending the AuthNResponse using HTTP-Post SAML 2.0 binding
            $httppost = new SimpleSAML_Bindings_SAML20_HTTPPost($config, $metadata);
            $httppost->sendResponse($authnResponseXML, $idpentityid, $spentityid, $requestcache['RelayState']);
            exit;
        }
        /*
         * Attribute handling
         */
        $attributes = $session->getAttributes();
        $afilter = new SimpleSAML_XML_AttributeFilter($config, $attributes);
        $afilter->process($idpmetadata, $spmetadata);
        // KEEP this code for REFERENCE
        //		/**
        //		 * Make a log entry in the statistics for this SSO login.
        //		 */
        //		$tempattr = $afilter->getAttributes();
        //		$realmattr = $config->getValue('statistics.realmattr', null);
        //		$realmstr = 'NA';
        //		if (!empty($realmattr)) {
        //			//error_log('SSO 420: if (!empty($realmattr)) {\n ',0);
        //			if (array_key_exists($realmattr, $tempattr) && is_array($tempattr[$realmattr]) ) {
        //				$realmstr = $tempattr[$realmattr][0];
        //			} else {
        //				SimpleSAML_Logger::warning('Could not get realm attribute to log [' . $realmattr. ']');
        //			}
        //		}
        //		SimpleSAML_Logger::stats('saml20-idp-SSO ' . $spentityid . ' ' . $idpentityid . ' ' . $realmstr);
        //
        //
        $afilter->processFilter($idpmetadata, $spmetadata);
        $filteredattributes = $afilter->getAttributes();
        //
        //		KEEP THIS CODE FOR RERFERENCE
        //		/*
        //		 * Dealing with attribute release consent.
        //		 */
        //		$requireconsent = false;
        //		if (isset($idpmetadata['requireconsent'])) {
        //			//error_log('SSO 453: if (isset($idpmetadata[\'requireconsent\']))\n ',0);
        //			if (is_bool($idpmetadata['requireconsent'])) {
        //				$requireconsent = $idpmetadata['requireconsent'];
        //			} else {
        //				throw new Exception('SAML 2.0 IdP hosted metadata parameter [requireconsent] is in illegal format, must be a PHP boolean type.');
        //			}
        //		}
        //		if ($requireconsent) {
        //
        //			$consent = new SimpleSAML_Consent_Consent($config, $session, $spentityid, $idpentityid, $attributes, $filteredattributes, $requestcache['ConsentCookie']);
        //
        //			if (!$consent->consent()) {
        //				/* Save the request information. */
        //				$authId = SimpleSAML_Utilities::generateID();
        //				$session->setAuthnRequest('saml2', $authId, $requestcache);
        //
        //				$t = new SimpleSAML_XHTML_Template($config, 'consent.php', 'attributes.php');
        //				$t->data['header'] = 'Consent';
        //				$t->data['sp_name'] = $sp_name;
        //				$t->data['attributes'] = $filteredattributes;
        //				$t->data['consenturl'] = SimpleSAML_Utilities::selfURLNoQuery();//$selfURLNoQuery; //SimpleSAML_Utilities::selfURLNoQuery(); DEBUG
        //				$t->data['requestid'] = $authId;
        //				$t->data['consent_cookie'] = $requestcache['ConsentCookie'];
        //				$t->data['usestorage'] = $consent->useStorage();
        //				$t->data['noconsent'] = '/' . $config->getBaseURL() . 'noconsent.php';
        //				$t->show();
        //				exit;
        //			}
        //
        //		}
        //		// END ATTRIBUTE CONSENT CODE
        // Generate the SAML 2.0 AuthNResponse message
        $ar = new SimpleSAML_XML_SAML20_AuthnResponse($config, $metadata);
        $authnResponseXML = $ar->generate($idpentityid, $spentityid, $requestcache['RequestID'], null, $filteredattributes);
        // TODO: clean the $SESSION->samlrelaystate so we don't accidently call it again
        // Sending the AuthNResponse using HTTP-Post SAML 2.0 binding
        $httppost = new SimpleSAML_Bindings_SAML20_HTTPPost($config, $metadata);
        $httppost->sendResponse($authnResponseXML, $idmetaindex, $spentityid, $requestcache['RelayState']);
        die;
        // VERY IMPORTANT BUG FIX to stop outputing the rest of the page.
    } catch (Exception $exception) {
        // TODO: better error reporting
        debugging('<pre>' . print_r($exception, true) . '</pre>', DEBUG_DEVELOPER);
        return false;
    }
}
Esempio n. 18
0
 public function executeProcessValidateForm(sfWebRequest $request)
 {
     $i18n = sfContext::getInstance()->getI18N();
     $formarray = $request->getParameter('token');
     $s_id = $formarray['s_id'];
     $s = Doctrine::getTable('Service')->find($s_id);
     $s_entityId = $s->getEntityId();
     $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $entity = $metadata->getMetaData($s_entityId, 'saml20-sp-remote');
     $form = new SendTokenToSPOwnerForm(array('s_id' => $s_id, 'entity' => $entity));
     $form->bind($request->getParameter($form->getName()));
     if (!$form->isValid()) {
         $this->getUser()->setFlash('notice', $i18n->__('Could not send the invitation, please check the e-mail address and try again!'));
         $this->redirect("show/index?id=" . $s_id);
     }
     $emails = $form->getValue('email');
     $s_id = $form->getValue('s_id');
     $m = $form->getValue('message');
     $s = Doctrine::getTable('Service')->find($s_id);
     $this->checkIsMy($s);
     /* Set the token to Service */
     $token = uniqid();
     $s->setToken($token);
     $s->save();
     /* Send validating emails */
     $params = array("s" => $s, "p" => $this->getUser()->getPrincipal(), "m" => $m);
     $email_params = array("to" => $emails, "subject" => $i18n->__('Validating code to %service% service.', array("%service%" => $s)), "bodyhtml" => $this->getPartial('service/validatingHtml', $params));
     $this->sendEmail($email_params);
     /* Set the notice to user */
     $this->getUser()->setFlash('notice', $i18n->__('The validation code is sent, please check your e-mails!'));
     $this->redirect("show/index?id=" . $s_id);
 }
Esempio n. 19
0
<?php

require_once '../../www/_include.php';
$config = SimpleSAML_Configuration::getInstance();
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$session = SimpleSAML_Session::getInstance();
$ldapconfigfile = $config->getBaseDir() . 'config/ldapmulti.php';
require_once $ldapconfigfile;
SimpleSAML_Logger::info('AUTH - ldap-multi: Accessing auth endpoint login-ldapmulti');
if (empty($session)) {
    SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOSESSION');
}
$error = null;
$attributes = array();
/* Load the RelayState argument. The RelayState argument contains the address
 * we should redirect the user to after a successful authentication.
 */
if (!array_key_exists('RelayState', $_REQUEST)) {
    SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE');
}
if (isset($_POST['username'])) {
    try {
        $ldapconfig = $ldapmulti[$_POST['org']];
        if ($ldapconfig['search.enable'] === TRUE) {
            if (!$ldap->bind($ldapconfig['search.username'], $ldapconfig['search.password'])) {
                throw new Exception('Error authenticating using search username & password.');
            }
            $dn = $ldap->searchfordn($ldapconfig['search.base'], $ldapconfig['search.attributes'], $_POST['username']);
        } else {
            $dn = str_replace('%username%', $_POST['username'], $ldapconfig['dnpattern']);
        }
Esempio n. 20
0
 /**
  * Retrieve a logout URL for a given logout association.
  *
  * @param SimpleSAML_IdP $idp  The IdP we are sending a logout request from.
  * @param array $association  The association that should be terminated.
  * @param string|NULL $relayState  An id that should be carried across the logout.
  */
 public static function getLogoutURL(SimpleSAML_IdP $idp, array $association, $relayState)
 {
     assert('is_string($relayState) || is_null($relayState)');
     SimpleSAML_Logger::info('Sending SAML 2.0 LogoutRequest to: ' . var_export($association['saml:entityID'], TRUE));
     $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $idpMetadata = $idp->getConfig();
     $spMetadata = $metadata->getMetaDataConfig($association['saml:entityID'], 'saml20-sp-remote');
     $lr = sspmod_saml_Message::buildLogoutRequest($idpMetadata, $spMetadata);
     $lr->setRelayState($relayState);
     $lr->setSessionIndex($association['saml:SessionIndex']);
     $lr->setNameId($association['saml:NameID']);
     $binding = new SAML2_HTTPRedirect();
     return $binding->getRedirectURL($lr);
 }
Esempio n. 21
0
 /**
  * Retrieve the metadata of an IdP.
  *
  * @param string $entityId  The entity id of the IdP.
  * @return SimpleSAML_Configuration  The metadata of the IdP.
  */
 public function getIdPMetadata($entityId)
 {
     assert('is_string($entityId)');
     if ($this->idp !== NULL && $this->idp !== $entityId) {
         throw new SimpleSAML_Error_Exception('Cannot retrieve metadata for IdP ' . var_export($entityId, TRUE) . ' because it isn\'t a valid IdP for this SP.');
     }
     $metadataHandler = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     /* First, look in saml20-idp-remote. */
     try {
         return $metadataHandler->getMetaDataConfig($entityId, 'saml20-idp-remote');
     } catch (Exception $e) {
         /* Metadata wasn't found. */
     }
     /* Not found in saml20-idp-remote, look in shib13-idp-remote. */
     try {
         return $metadataHandler->getMetaDataConfig($entityId, 'shib13-idp-remote');
     } catch (Exception $e) {
         /* Metadata wasn't found. */
     }
     /* Not found. */
     throw new SimpleSAML_Error_Exception('Could not find the metadata of an IdP with entity ID ' . var_export($entityId, TRUE));
 }
Esempio n. 22
0
 public static function getLogoutURL(SimpleSAML_IdP $idp, array $association, $relayState)
 {
     $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $idpMetadata = $idp->getConfig();
     $spMetadata = $metadata->getMetaDataConfig($association['adfs:entityID'], 'adfs-sp-remote');
     $returnTo = SimpleSAML\Module::getModuleURL('adfs/idp/prp.php?assocId=' . urlencode($association["id"]) . '&relayState=' . urlencode($relayState));
     return $spMetadata->getValue('prp') . '?' . 'wa=wsignoutcleanup1.0&wreply=' . urlencode($returnTo);
 }
Esempio n. 23
0
 public static function getLogoutURL(SimpleSAML_IdP $idp, array $association, $relayState)
 {
     $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $idpMetadata = $idp->getConfig();
     $spMetadata = $metadata->getMetaDataConfig($association['adfs:entityID'], 'adfs-sp-remote');
     // 'https://adfs-test.showcase.surfnet.nl/adfs/ls/?wa=wsignoutcleanup1.0&wreply=https%3A%2F%2Flocalhost%2Fsimplesaml');
     $returnTo = SimpleSAML_Module::getModuleURL('adfs/idp/prp.php?assocId=' . urlencode($association["id"]) . '&relayState=' . urlencode($relayState));
     return $spMetadata->getValue('prp') . '?' . 'wa=wsignoutcleanup1.0&wreply=' . urlencode($returnTo);
 }
function updateslostatus()
{
    SimpleSAML_Logger::info('SAML2.0 - IdP.SingleLogoutServiceiFrame: Accessing SAML 2.0 IdP endpoint SingleLogoutService (iFrame version) within updateslostatus() ');
    $config = SimpleSAML_Configuration::getInstance();
    $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
    $session = SimpleSAML_Session::getInstance();
    $idpentityid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
    $templistofsps = $session->get_sp_list(SimpleSAML_Session::STATE_ONLINE);
    $listofsps = array();
    foreach ($templistofsps as $spentityid) {
        if (!empty($_COOKIE['spstate-' . sha1($spentityid)])) {
            $listofsps[] = $spentityid;
            continue;
        }
        try {
            $spmetadata = $metadata->getMetaData($spentityid, 'saml20-sp-remote');
        } catch (Exception $e) {
            /*
             * For some reason, the metadata for this SP is no longer available. Most
             * likely it was deleted from the IdP while the user had a session to it.
             * In any case - skip this SP.
             */
            $listofsps[] = $spentityid;
            continue;
        }
        if (!isset($spmetadata['SingleLogoutService'])) {
            /* No logout endpoint. */
            $listofsps[] = $spentityid;
            continue;
        }
        /* This SP isn't ready yet. */
    }
    SimpleSAML_Logger::debug('SAML2.0 - IdP.SingleLogoutServiceiFrame: templistofsps ' . join(',', $templistofsps));
    SimpleSAML_Logger::debug('SAML2.0 - IdP.SingleLogoutServiceiFrame:     listofsps ' . join(',', $listofsps));
    // Using template object to be able to translate name of service provider.
    $t = new SimpleSAML_XHTML_Template($config, 'logout-iframe.php');
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    foreach ($listofsps as $spentityid) {
        SimpleSAML_Logger::debug('SAML2.0 - IdP.SingleLogoutServiceiFrame: Completed ' . $spentityid);
        // add a command to the response to assign the innerHTML attribute of
        // the element with id="SomeElementId" to whatever the new content is
        try {
            $spmetadata = $metadata->getMetaData($spentityid, 'saml20-sp-remote');
        } catch (Exception $e) {
            /*
             * For some reason, the metadata for this SP is no longer available. Most
             * likely it was deleted from the IdP while the user had a session to it.
             * In any case - skip this SP.
             */
            continue;
        }
        $name = array_key_exists('name', $spmetadata) ? $spmetadata['name'] : $spentityid;
        $spname = is_array($name) ? $t->getTranslation($name) : $name;
        $objResponse->addScriptCall('slocompletesp', 'e' . sha1($spentityid));
    }
    if (count($templistofsps) === count($listofsps)) {
        $templistofsps = $session->get_sp_list(SimpleSAML_Session::STATE_ONLINE);
        foreach ($templistofsps as $spentityid) {
            $session->set_sp_logout_completed($spentityid);
            setcookie('spstate-' . sha1($spentityid), '', time() - 3600);
            // Delete cookie
        }
        $objResponse->addScriptCall('slocompleted');
        /**
         * Clean up session object to save storage.
         */
        if ($config->getBoolean('debug', false)) {
            SimpleSAML_Logger::info('SAML2.0 - IdP.SingleLogoutService: Session Size before cleaning: ' . $session->getSize());
        }
        $session->clean();
        if ($config->getBoolean('debug', false)) {
            SimpleSAML_Logger::info('SAML2.0 - IdP.SingleLogoutService: Session Size after cleaning: ' . $session->getSize());
        }
    } else {
        SimpleSAML_Logger::debug('SAML2.0 - sp_logout_completed FALSE');
    }
    //return the  xajaxResponse object
    return $objResponse;
}
Esempio n. 25
0
 /**
  * Get SP name.
  *
  * @param string $assocId  The association identifier.
  * @return array|NULL  The name of the SP, as an associative array of language=>text, or NULL if this isn't an SP.
  */
 public function getSPName($assocId)
 {
     assert('is_string($assocId)');
     $prefix = substr($assocId, 0, 4);
     $spEntityId = substr($assocId, strlen($prefix) + 1);
     $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     if ($prefix === 'saml') {
         try {
             $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'saml20-sp-remote');
         } catch (Exception $e) {
             try {
                 $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'shib13-sp-remote');
             } catch (Exception $e) {
                 return NULL;
             }
         }
     } else {
         if ($prefix === 'adfs') {
             $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'adfs-sp-remote');
         } else {
             return NULL;
         }
     }
     if ($spMetadata->hasValue('name')) {
         return $spMetadata->getLocalizedString('name');
     } elseif ($spMetadata->hasValue('OrganizationDisplayName')) {
         return $spMetadata->getLocalizedString('OrganizationDisplayName');
     } else {
         return array('en' => $spEntityId);
     }
 }
 /**
  * This function is used to generate a non-revesible unique identifier for a user.
  * The identifier should be persistent (unchanging) for a given SP-IdP federation.
  * The identifier can be shared between several different SPs connected to the same IdP, or it
  * can be unique for each SP.
  *
  * @param $idpEntityId  The entity id of the IdP.
  * @param $spEntityId   The entity id of the SP.
  * @param $attributes   The attributes of the user.
  * @return A non-reversible unique identifier for the user.
  */
 public static function generateUserIdentifier($idpEntityId, $spEntityId, $attributes)
 {
     $metadataHandler = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $idpMetadata = $metadataHandler->getMetaData($idpEntityId, 'saml20-idp-hosted');
     $spMetadata = $metadataHandler->getMetaData($spEntityId, 'saml20-sp-remote');
     if (array_key_exists('userid.attribute', $spMetadata)) {
         $attributeName = $spMetadata['userid.attribute'];
     } elseif (array_key_exists('userid.attribute', $idpMetadata)) {
         $attributeName = $idpMetadata['userid.attribute'];
     } else {
         $attributeName = 'eduPersonPrincipalName';
     }
     if (!array_key_exists($attributeName, $attributes)) {
         throw new Exception('Missing attribute "' . $attributeName . '" for user. Cannot' . ' generate user id.');
     }
     $attributeValue = $attributes[$attributeName];
     if (count($attributeValue) !== 1) {
         throw new Exception('Attribute "' . $attributeName . '" for user did not contain exactly' . ' one value. Cannot generate user id.');
     }
     $attributeValue = $attributeValue[0];
     if (empty($attributeValue)) {
         throw new Exception('Attribute "' . $attributeName . '" for user was empty. Cannot' . ' generate user id.');
     }
     $secretSalt = SimpleSAML_Configuration::getInstance()->getValue('secretsalt');
     if (empty($secretSalt)) {
         throw new Exception('The "secretsalt" configuration option must be set before user' . ' ids can be generated.');
     }
     if ($secretSalt === 'defaultsecretsalt') {
         throw new Exception('The "secretsalt" configuration option must be set to a secret' . ' value.');
     }
     $uidData = 'uidhashbase' . $secretSalt;
     $uidData .= strlen($idpEntityId) . ':' . $idpEntityId;
     $uidData .= strlen($spEntityId) . ':' . $spEntityId;
     $uidData .= strlen($attributeValue) . ':' . $attributeValue;
     $uidData .= $secretSalt;
     $userid = hash('sha1', $uidData);
     return $userid;
 }
Esempio n. 27
0
 /**
  * Retrieve the metadata for the given SP association.
  *
  * @param SimpleSAML_IdP $idp  The IdP the association belongs to.
  * @param array $association  The SP association.
  * @return SimpleSAML_Configuration  Configuration object for the SP metadata.
  */
 public static function getAssociationConfig(SimpleSAML_IdP $idp, array $association)
 {
     $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     try {
         return $metadata->getMetaDataConfig($association['saml:entityID'], 'saml20-sp-remote');
     } catch (Exception $e) {
         return SimpleSAML_Configuration::loadFromArray(array(), 'Unknown SAML 2 entity.');
     }
 }
Esempio n. 28
0
 /**
  * Handle logout operation.
  *
  * @param array $state  The logout state.
  */
 public function logout(&$state)
 {
     assert('is_array($state)');
     assert('array_key_exists(self::LOGOUT_IDP, $state)');
     assert('array_key_exists(self::LOGOUT_NAMEID, $state)');
     assert('array_key_exists(self::LOGOUT_SESSIONINDEX, $state)');
     $id = SimpleSAML_Auth_State::saveState($state, self::STAGE_LOGOUTSENT);
     $idp = $state[self::LOGOUT_IDP];
     $nameId = $state[self::LOGOUT_NAMEID];
     $sessionIndex = $state[self::LOGOUT_SESSIONINDEX];
     if (array_key_exists('value', $nameId)) {
         /*
          * This session was saved by an old version of simpleSAMLphp.
          * Convert to the new NameId format.
          *
          * TODO: Remove this conversion once every session should use the new format.
          */
         $nameId['Value'] = $nameId['value'];
         unset($nameId['value']);
     }
     $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $idpMetadata = $metadata->getMetaDataConfig($idp, 'saml20-idp-remote');
     $lr = sspmod_saml2_Message::buildLogoutRequest($this->metadata, $idpMetadata);
     $lr->setNameId($nameId);
     $lr->setSessionIndex($sessionIndex);
     $lr->setRelayState($id);
     $b = new SAML2_HTTPRedirect();
     $b->setDestination(sspmod_SAML2_Message::getDebugDestination());
     $b->send($lr);
     assert('FALSE');
 }
Esempio n. 29
0
 public function getAttributes()
 {
     $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $md = $metadata->getMetadata($this->getIssuer(), 'shib13-idp-remote');
     $base64 = isset($md['base64attributes']) ? $md['base64attributes'] : false;
     if (!$this->dom instanceof DOMDocument) {
         return array();
     }
     $attributes = array();
     $assertions = $this->doXPathQuery('/shibp:Response/shib:Assertion');
     foreach ($assertions as $assertion) {
         if (!$this->isNodeValidated($assertion)) {
             throw new Exception('Shib13 AuthnResponse contained an unsigned assertion.');
         }
         $conditions = $this->doXPathQuery('shib:Conditions', $assertion);
         if ($conditions && $conditions->length > 0) {
             $condition = $conditions->item(0);
             $start = $condition->getAttribute('NotBefore');
             $end = $condition->getAttribute('NotOnOrAfter');
             if ($start && $end) {
                 if (!self::checkDateConditions($start, $end)) {
                     error_log('Date check failed ... (from ' . $start . ' to ' . $end . ')');
                     continue;
                 }
             }
         }
         $attribute_nodes = $this->doXPathQuery('shib:AttributeStatement/shib:Attribute/shib:AttributeValue', $assertion);
         foreach ($attribute_nodes as $attribute) {
             $value = $attribute->textContent;
             $name = $attribute->parentNode->getAttribute('AttributeName');
             if ($attribute->hasAttribute('Scope')) {
                 $scopePart = '@' . $attribute->getAttribute('Scope');
             } else {
                 $scopePart = '';
             }
             if (!is_string($name)) {
                 throw new Exception('Shib13 Attribute node without an AttributeName.');
             }
             if (!array_key_exists($name, $attributes)) {
                 $attributes[$name] = array();
             }
             if ($base64) {
                 $encodedvalues = explode('_', $value);
                 foreach ($encodedvalues as $v) {
                     $attributes[$name][] = base64_decode($v) . $scopePart;
                 }
             } else {
                 $attributes[$name][] = $value . $scopePart;
             }
         }
     }
     return $attributes;
 }
Esempio n. 30
0
	function __construct() {
	
		$this->config = SimpleSAML_Configuration::getInstance();
		$this->djconfig = SimpleSAML_Configuration::getOptionalConfig('discojuicefeed.php');

		$metadatah = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
		
		$saml2 = $metadatah->getList('saml20-idp-remote');
		$shib = $metadatah->getList('shib13-idp-remote');
		
		foreach($shib AS $s) {
			$this->metadata[$s['entityid']] = $s;
		}
		foreach($saml2 AS $s) {
			$this->metadata[$s['entityid']] = $s;
		}
		// $this->metadata = array_merge($this->metadata, $shib);
		
		
		$this->idplist = $this->getIdPList();
		
		SimpleSAML_Logger::info('IdP List contained : ' . count($this->idplist)  . ' entries.');
		
		$this->excludes = array_flip($this->djconfig->getValue('exclude'));
		$this->insert = $this->djconfig->getValue('insert');
		$this->overrides = $this->djconfig->getValue('overrides');
		
		$this->countrytags = array(
			'croatia' => 'HR',
			'czech' => 'CZ',
			'denmark' => 'DK',
			'finland' => 'FI',
			'france' => 'FR',
			'germany' => 'DE',
			'greece' => 'GR',
			'ireland' => 'IE',
			'italy' => 'IT',
			'luxembourg' => 'LU',
			'hungary' => 'HU',
			'netherlands' => 'NL',
			'norway' => 'NO',
			'portugal' => 'PT',
			'poland' => 'PL',
			'slovenia' => 'SI',
			'spain' => 'ES',
			'sweden' => 'SE',
			'switzerland' => 'CH',
			'turkey' => 'TR',
			'us' => 'US',
			'uk' => 'GB',
			'japan'  => 'JP',
		);
		
		$this->countryTLDs = array(
			'lp.' => 'PL',
			'uh.' => 'HU',
			'es.' => 'SE',
			'ed.' => 'DE',
			'if.' => 'FI',
			'zc.' => 'CZ',
			'rt.' => 'TR',
			'kd.' => 'DK',
			'on.' => 'NO',
			'ude.' => 'US',
			'ku.oc.' => 'GB',
		);
	}