Ejemplo n.º 1
0
 public function finalStep(&$state)
 {
     $requestToken = unserialize($state['requestToken']);
     #echo '<pre>'; print_r($requestToken); exit;
     $consumer = new sspmod_oauth_Consumer($this->key, $this->secret);
     SimpleSAML_Logger::debug("oauth: Using this request token [" . $requestToken->key . "] with the secret [" . $requestToken->secret . "]");
     // Replace the request token with an access token
     $accessToken = $consumer->getAccessToken('http://twitter.com/oauth/access_token', $requestToken);
     SimpleSAML_Logger::debug("Got an access token from the OAuth service provider [" . $accessToken->key . "] with the secret [" . $accessToken->secret . "]");
     $userdata = $consumer->getUserInfo('http://twitter.com/account/verify_credentials.json', $accessToken);
     $attributes = array();
     foreach ($userdata as $key => $value) {
         if (is_string($value)) {
             $attributes[$key] = array((string) $value);
         }
     }
     if (array_key_exists('screen_name', $userdata)) {
         $attributes['eduPersonPrincipalName'] = array('@' . $userdata['screen_name']);
     }
     if (array_key_exists('name', $userdata)) {
         $attributes['displayName'] = array($userdata['name']);
     }
     if (array_key_exists('profile_image_url', $userdata)) {
         $attributes['jpegPhoto'] = array(base64_encode(file_get_contents($userdata['profile_image_url'])));
     }
     if (array_key_exists('url', $userdata)) {
         $attributes['labeledURI'] = array($userdata['url']);
     }
     $state['Attributes'] = $attributes;
 }
Ejemplo n.º 2
0
 /**
  * Apply filter to add groups attribute.
  *
  * @param array &$request  The current request
  */
 public function process(&$request)
 {
     assert('is_array($request)');
     assert('array_key_exists("Attributes", $request)');
     $groups = array();
     $attributes =& $request['Attributes'];
     $realm = self::getRealm($attributes);
     if ($realm !== NULL) {
         $groups[] = 'realm-' . $realm;
     }
     foreach ($this->generateGroupsFrom as $name) {
         if (!array_key_exists($name, $attributes)) {
             SimpleSAML_Logger::debug('GenerateGroups - attribute \'' . $name . '\' not found.');
             /* Attribute not present. */
             continue;
         }
         foreach ($attributes[$name] as $value) {
             $value = self::escapeIllegalChars($value);
             $groups[] = $name . '-' . $value;
             if ($realm !== NULL) {
                 $groups[] = $name . '-' . $realm . '-' . $value;
             }
         }
     }
     if (count($groups) > 0) {
         $attributes['groups'] = $groups;
     }
 }
Ejemplo n.º 3
0
 public function finalStep(&$state)
 {
     $requestToken = $state['authtwitter:authdata:requestToken'];
     $parameters = array();
     if (!isset($_REQUEST['oauth_token'])) {
         throw new SimpleSAML_Error_BadRequest("Missing oauth_token parameter.");
     }
     if ($requestToken->key !== (string) $_REQUEST['oauth_token']) {
         throw new SimpleSAML_Error_BadRequest("Invalid oauth_token parameter.");
     }
     if (!isset($_REQUEST['oauth_verifier'])) {
         throw new SimpleSAML_Error_BadRequest("Missing oauth_verifier parameter.");
     }
     $parameters['oauth_verifier'] = (string) $_REQUEST['oauth_verifier'];
     $consumer = new sspmod_oauth_Consumer($this->key, $this->secret);
     SimpleSAML_Logger::debug("oauth: Using this request token [" . $requestToken->key . "] with the secret [" . $requestToken->secret . "]");
     // Replace the request token with an access token
     $accessToken = $consumer->getAccessToken('https://api.twitter.com/oauth/access_token', $requestToken, $parameters);
     SimpleSAML_Logger::debug("Got an access token from the OAuth service provider [" . $accessToken->key . "] with the secret [" . $accessToken->secret . "]");
     $userdata = $consumer->getUserInfo('https://api.twitter.com/1.1/account/verify_credentials.json', $accessToken);
     if (!isset($userdata['id_str']) || !isset($userdata['screen_name'])) {
         throw new SimpleSAML_Error_AuthSource($this->authId, 'Authentication error: id_str and screen_name not set.');
     }
     $attributes = array();
     foreach ($userdata as $key => $value) {
         if (is_string($value)) {
             $attributes['twitter.' . $key] = array((string) $value);
         }
     }
     $attributes['twitter_at_screen_name'] = array('@' . $userdata['screen_name']);
     $attributes['twitter_screen_n_realm'] = array($userdata['screen_name'] . '@twitter.com');
     $attributes['twitter_targetedID'] = array('http://twitter.com!' . $userdata['id_str']);
     $state['Attributes'] = $attributes;
 }
Ejemplo n.º 4
0
 /**
  * Returns a list of entities with metadata
  */
 public function getSources()
 {
     $sourcesDef = $this->aConfig->getArray('sources');
     try {
         $sources = SimpleSAML_Metadata_MetaDataStorageSource::parseSources($sourcesDef);
     } catch (Exception $e) {
         throw new Exception('Invalid aggregator source configuration for aggregator ' . var_export($id, TRUE) . ': ' . $e->getMessage());
     }
     #echo $exclude; exit;
     /* Find list of all available entities. */
     $entities = array();
     #echo '<pre>'; print_r($this->sets); exit;
     foreach ($sources as $source) {
         foreach ($this->sets as $set) {
             foreach ($source->getMetadataSet($set) as $entityId => $metadata) {
                 if (isset($metadata['tags']) && count(array_intersect($this->excludeTags, $metadata['tags'])) > 0) {
                     SimpleSAML_Logger::debug('Excluding entity ID [' . $entityId . '] becuase it is tagged with one of [' . var_export($this->excludeTags, TRUE) . ']');
                     continue;
                 } else {
                     #echo('<pre>'); print_r($metadata); exit;
                 }
                 if (!array_key_exists($entityId, $entities)) {
                     $entities[$entityId] = array();
                 }
                 if (array_key_exists($set, $entities[$entityId])) {
                     /* Entity already has metadata for the given set. */
                     continue;
                 }
                 $entities[$entityId][$set] = $metadata;
             }
         }
     }
     return $entities;
 }
Ejemplo n.º 5
0
function handleResponse()
{
    try {
        $binding = SAML2_Binding::getCurrentBinding();
        $response = $binding->receive();
    } catch (Exception $e) {
        return;
    }
    SimpleSAML_Logger::debug('attributequery - received message.');
    if (!$response instanceof SAML2_Response) {
        throw new SimpleSAML_Error_Exception('Unexpected message received to attribute query example.');
    }
    $idpEntityId = $response->getIssuer();
    if ($idpEntityId === NULL) {
        throw new SimpleSAML_Error_Exception('Missing issuer in response.');
    }
    $idpMetadata = $GLOBALS['metadata']->getMetaDataConfig($idpEntityId, 'saml20-idp-remote');
    $spMetadata = $GLOBALS['metadata']->getMetaDataConfig($GLOBALS['spEntityId'], 'saml20-sp-hosted');
    $assertion = sspmod_saml_Message::processResponse($spMetadata, $idpMetadata, $response);
    if (count($assertion) > 1) {
        throw new SimpleSAML_Error_Exception('More than one assertion in received response.');
    }
    $assertion = $assertion[0];
    $dataId = $response->getRelayState();
    if ($dataId === NULL) {
        throw new SimpleSAML_Error_Exception('RelayState was lost during request.');
    }
    $data = $GLOBALS['session']->getData('attributequeryexample:data', $dataId);
    $data['attributes'] = $assertion->getAttributes();
    $GLOBALS['session']->setData('attributequeryexample:data', $dataId, $data, 3600);
    SimpleSAML_Utilities::redirect(SimpleSAML_Utilities::selfURLNoQuery(), array('dataId' => $dataId));
}
Ejemplo n.º 6
0
 public function getAttributes($nameId, $spid, $attributes = array())
 {
     // Generate API key
     $time = new \DateTime();
     date_timezone_set($time, new \DateTimeZone('UTC'));
     $stamp = $time->format('Y-m-d H:i');
     $apiKey = hash('sha256', $this->as_config['hexaa_master_secret'] . $stamp);
     // Make the call
     // The data to send to the API
     $postData = array("apikey" => $apiKey, "fedid" => $nameId, "entityid" => $spid);
     // Setup cURL
     $ch = curl_init($this->as_config['hexaa_api_url'] . '/attributes.json');
     curl_setopt_array($ch, array(CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_HTTPHEADER => array('Content-Type: application/json'), CURLOPT_POSTFIELDS => json_encode($postData), CURLOPT_FOLLOWLOCATION => TRUE, CURLOPT_POSTREDIR => 3));
     // Send the request
     $response = curl_exec($ch);
     $http_response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     // Check for error; not even redirects are allowed here
     if ($response === FALSE || !($http_response >= 200 && $http_response < 300)) {
         SimpleSAML_Logger::error('[aa] HEXAA API query failed: HTTP response code: ' . $http_response . ', curl error: "' . curl_error($ch)) . '"';
         SimpleSAML_Logger::debug('[aa] HEXAA API query failed: curl info: ' . var_export(curl_getinfo($ch), 1));
         SimpleSAML_Logger::debug('[aa] HEXAA API query failed: HTTP response: ' . var_export($response, 1));
         $data = array();
     } else {
         $data = json_decode($response, true);
         SimpleSAML_Logger::info('[aa] got reply from HEXAA API');
         SimpleSAML_Logger::debug('[aa] HEXAA API query postData: ' . var_export($postData, TRUE));
         SimpleSAML_Logger::debug('[aa] HEXAA API query result: ' . var_export($data, TRUE));
     }
     return $data;
 }
 public function getAttributes($nameId, $attributes = array())
 {
     // Set up config
     $config = $this->config;
     // Setup cURL
     $url = $this->as_config['api_url'] . '/' . $nameId;
     $ch = curl_init($url);
     curl_setopt_array($ch, array(CURLOPT_CUSTOMREQUEST => 'GET', CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array('Content-Type: application/json')));
     // Send the request
     $response = curl_exec($ch);
     $http_response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     // Check for error; not even redirects are allowed here
     if ($http_response == 507) {
         throw new SimpleSAML_Error_Exception("Out of resources: " . $response);
     } elseif ($response === false || !($http_response >= 200 && $http_response < 300)) {
         SimpleSAML_Logger::error('[afra] API query failed: HTTP response code: ' . $http_response . ', curl error: "' . curl_error($ch)) . '"';
         SimpleSAML_Logger::debug('[afra] API query failed: curl info: ' . var_export(curl_getinfo($ch), 1));
         SimpleSAML_Logger::debug('[afra] API query failed: HTTP response: ' . var_export($response, 1));
         throw new SimpleSAML_Error_Exception("Error at REST API response: " . $response . $http_response);
     } else {
         $data = json_decode($response, true);
         SimpleSAML_Logger::info('[afra] got reply from API');
         SimpleSAML_Logger::debug('[afra] API query url: ' . var_export($url, true));
         SimpleSAML_Logger::debug('[afra] API query result: ' . var_export($data, true));
     }
     $attributes = $data['data'];
     return $attributes;
 }
Ejemplo n.º 8
0
 /**
  * Attempt to log in using the given username and password.
  *
  * On a successful login, this function should return the username as 'uid' attribute,
  * and merged attributes from the configuration file.
  * On failure, it should throw an exception. A SimpleSAML_Error_Error('WRONGUSERPASS')
  * should be thrown in case of a wrong username OR a wrong password, to prevent the
  * enumeration of usernames.
  *
  * @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)');
     foreach ($this->users as $userpass) {
         $matches = explode(':', $userpass, 2);
         if ($matches[0] == $username) {
             $crypted = $matches[1];
             // This is about the only attribute we can add
             $attributes = array_merge(array('uid' => array($username)), $this->attributes);
             // Traditional crypt(3)
             if (crypt($password, $crypted) == $crypted) {
                 SimpleSAML_Logger::debug('User ' . $username . ' authenticated successfully');
                 return $attributes;
             }
             // Apache's custom MD5
             if (SimpleSAML_Utils_Crypto::apr1Md5Valid($crypted, $password)) {
                 SimpleSAML_Logger::debug('User ' . $username . ' authenticated successfully');
                 return $attributes;
             }
             // SHA1 or plain-text
             if (SimpleSAML_Utils_Crypto::pwValid($crypted, $password)) {
                 SimpleSAML_Logger::debug('User ' . $username . ' authenticated successfully');
                 return $attributes;
             }
             throw new SimpleSAML_Error_Error('WRONGUSERPASS');
         }
     }
     throw new SimpleSAML_Error_Error('WRONGUSERPASS');
 }
Ejemplo n.º 9
0
 public function finalStep(&$state)
 {
     $requestToken = unserialize($state['requestToken']);
     #echo '<pre>'; print_r($requestToken); exit;
     $consumer = new sspmod_oauth_Consumer($this->key, $this->secret);
     SimpleSAML_Logger::debug("oauth: Using this request token [" . $requestToken->key . "] with the secret [" . $requestToken->secret . "]");
     // Replace the request token with an access token
     $accessToken = $consumer->getAccessToken('http://twitter.com/oauth/access_token', $requestToken);
     SimpleSAML_Logger::debug("Got an access token from the OAuth service provider [" . $accessToken->key . "] with the secret [" . $accessToken->secret . "]");
     $userdata = $consumer->getUserInfo('http://twitter.com/account/verify_credentials.json', $accessToken);
     $attributes = array();
     foreach ($userdata as $key => $value) {
         if (is_string($value)) {
             $attributes['twitter.' . $key] = array((string) $value);
         }
     }
     if (array_key_exists('screen_name', $userdata)) {
         $attributes['twitter_at_screen_name'] = array('@' . $userdata['screen_name']);
         $attributes['twitter_screen_n_realm'] = array($userdata['screen_name'] . '@twitter.com');
     }
     if (array_key_exists('id_str', $userdata)) {
         $attributes['twitter_targetedID'] = array('http://twitter.com!' . $userdata['id_str']);
     }
     $state['Attributes'] = $attributes;
 }
Ejemplo n.º 10
0
 /**
  * Apply this filter.
  *
  * @param array &$request  The current request
  */
 public function process(&$request)
 {
     assert('is_array($request)');
     assert('array_key_exists("Attributes", $request)');
     $attributes =& $request['Attributes'];
     if (!isset($attributes[$this->sourceAttribute])) {
         return;
     }
     // will not overwrite existing attribute
     if (isset($attributes[$this->targetAttribute])) {
         return;
     }
     $sourceAttrVal = $attributes[$this->sourceAttribute][0];
     /* the last position of an @ is usually the beginning of the scope
      * string */
     $scopeIndex = strrpos($sourceAttrVal, '@');
     if ($scopeIndex !== FALSE) {
         $attributes[$this->targetAttribute] = array();
         $scope = substr($sourceAttrVal, $scopeIndex + 1);
         $attributes[$this->targetAttribute][] = $scope;
         SimpleSAML_Logger::debug('ScopeFromAttribute: Inserted new attribute ' . $this->targetAttribute . ', with scope ' . $scope);
     } else {
         SimpleSAML_Logger::warning('ScopeFromAttribute: The configured source attribute ' . $this->sourceAttribute . ' does not have a scope. Did not add attribute ' . $this->targetAttribute . '.');
     }
 }
Ejemplo n.º 11
0
 /**
  * Log-in using Facebook cronus
  *
  * @param array &$state  Information about the current authentication.
  */
 public function authenticate(&$state)
 {
     assert('is_array($state)');
     /* We are going to need the authId in order to retrieve this authentication source later. */
     $state[self::AUTHID] = $this->authId;
     $stateID = SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT);
     SimpleSAML_Logger::debug('facebook auth state id = ' . $stateID);
     $facebook = new Facebook($this->api_key, $this->secret);
     $u = $facebook->require_login(SimpleSAML_Module::getModuleUrl('authfacebook') . '/linkback.php?next=' . $stateID);
     # http://developers.facebook.com/documentation.php?v=1.0&method=users.getInfo
     /* Causes an notice / warning...
     		if ($facebook->api_client->error_code) {
     			throw new Exception('Unable to load profile from facebook');
     		}
     		*/
     // http://developers.facebook.com/docs/reference/rest/users.getInfo
     $info = $facebook->api_client->users_getInfo($u, array('uid', 'first_name', 'middle_name', 'last_name', 'name', 'locale', 'current_location', 'affiliations', 'pic_square', 'profile_url', 'sex', 'email', 'pic', 'username', 'about_me', 'status', 'profile_blurb'));
     $attributes = array();
     foreach ($info[0] as $key => $value) {
         if (is_string($value) && !empty($value)) {
             $attributes['facebook.' . $key] = array((string) $value);
         }
     }
     if (array_key_exists('username', $info[0])) {
         $attributes['facebook_user'] = array($info[0]['username'] . '@facebook.com');
     } else {
         $attributes['facebook_user'] = array($u . '@facebook.com');
     }
     $attributes['facebook_targetedID'] = array('http://facebook.com!' . $u);
     $attributes['facebook_cn'] = array($info[0]['name']);
     SimpleSAML_Logger::debug('Facebook Returned Attributes: ' . implode(", ", array_keys($attributes)));
     $state['Attributes'] = $attributes;
 }
Ejemplo n.º 12
0
 /**
  * Attempt to log in using the given username and password.
  *
  * @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)');
     $curl_instance = curl_init();
     $escPassword = urlencode($password);
     $escUsername = urlencode($username);
     $url = $this->privacyideaserver . '/validate/samlcheck?user='******'&pass='******'&realm=' . $this->realm;
     //throw new Exception("url: ". $url);
     SimpleSAML_Logger::debug("privacyidea URL:" . $url);
     curl_setopt($curl_instance, CURLOPT_URL, $url);
     curl_setopt($curl_instance, CURLOPT_HEADER, TRUE);
     curl_setopt($curl_instance, CURLOPT_RETURNTRANSFER, TRUE);
     if ($this->sslverifyhost) {
         curl_setopt($curl_instance, CURLOPT_SSL_VERIFYHOST, 1);
     } else {
         curl_setopt($curl_instance, CURLOPT_SSL_VERIFYHOST, 0);
     }
     if ($this->sslverifypeer) {
         curl_setopt($curl_instance, CURLOPT_SSL_VERIFYPEER, 1);
     } else {
         curl_setopt($curl_instance, CURLOPT_SSL_VERIFYPEER, 0);
     }
     $response = curl_exec($curl_instance);
     $header_size = curl_getinfo($curl_instance, CURLINFO_HEADER_SIZE);
     $body = json_decode(substr($response, $header_size));
     $status = True;
     $value = True;
     try {
         $status = $body->result->status;
         $value = $body->result->value->auth;
     } catch (Exception $e) {
         throw new SimpleSAML_Error_BadRequest("We were not able to read the response from the privacyidea server:" . $e);
     }
     if (False === $status) {
         /* We got a valid JSON respnse, but the STATUS is false */
         throw new SimpleSAML_Error_BadRequest("Valid JSON response, but some internal error occured in privacyidea server.");
     } else {
         /* The STATUS is true, so we need to check the value */
         if (False === $value) {
             throw new SimpleSAML_Error_Error("WRONGUSERPASS");
         }
     }
     /* status and value are true
      * We can go on and fill attributes
      */
     /* If we get this far, we have a valid login. */
     $attributes = array();
     $arr = array("username", "surname", "email", "givenname", "mobile", "phone", "realm", "resolver");
     reset($arr);
     foreach ($arr as $key) {
         if (array_key_exists($key, $this->attributemap)) {
             $attributes[$this->attributemap[$key]] = array($body->result->value->attributes->{$key});
         } else {
             $attributes[$key] = array($body->result->value->attributes->{$key});
         }
     }
     return $attributes;
 }
Ejemplo n.º 13
0
 /**
  * Clean the logout table of expired entries.
  *
  * @param SimpleSAML_Store_SQL $store  The datastore.
  */
 private static function cleanLogoutStore(SimpleSAML_Store_SQL $store)
 {
     SimpleSAML_Logger::debug('saml.LogoutStore: Cleaning logout store.');
     $query = 'DELETE FROM ' . $store->prefix . '_saml_LogoutStore WHERE _expire < :now';
     $params = array('now' => gmdate('Y-m-d H:i:s'));
     $query = $store->pdo->prepare($query);
     $query->execute($params);
 }
Ejemplo n.º 14
0
 public function log($str)
 {
     if ($this->debugOutput) {
         echo '<p>' . $str;
     } else {
         SimpleSAML_Logger::debug($str);
     }
     flush();
 }
 public function serve($entityId)
 {
     if (!$this->_loadEntity($entityId)) {
         SimpleSAML_Logger::debug('No entity found!');
         return $this->_sendResponse();
     }
     $this->_checkMetadataValidity();
     return $this->_sendResponse();
 }
 public function processFilter($idpmetadata, $spmetadata)
 {
     /**
      * Filter away attributes that are not allowed for this SP.
      */
     if (isset($spmetadata['attributes'])) {
         SimpleSAML_Logger::debug('Applying SP specific attribute filter: ' . join(',', $spmetadata['attributes']));
         $this->filter($spmetadata['attributes']);
     }
 }
Ejemplo n.º 17
0
 /**
  * Check that the user has access to the statistics.
  *
  * If the user doesn't have access, send the user to the login page.
  */
 public static function checkAccess(SimpleSAML_Configuration $statconfig)
 {
     $protected = $statconfig->getBoolean('protected', FALSE);
     $authsource = $statconfig->getString('auth', NULL);
     $allowedusers = $statconfig->getValue('allowedUsers', NULL);
     $useridattr = $statconfig->getString('useridattr', 'eduPersonPrincipalName');
     $acl = $statconfig->getValue('acl', NULL);
     if ($acl !== NULL && !is_string($acl) && !is_array($acl)) {
         throw new SimpleSAML_Error_Exception('Invalid value for \'acl\'-option. Should be an array or a string.');
     }
     if (!$protected) {
         return;
     }
     if (SimpleSAML\Utils\Auth::isAdmin()) {
         // User logged in as admin. OK.
         SimpleSAML_Logger::debug('Statistics auth - logged in as admin, access granted');
         return;
     }
     if (!isset($authsource)) {
         // If authsource is not defined, init admin login.
         SimpleSAML\Utils\Auth::requireAdmin();
     }
     /* We are using an authsource for login. */
     $as = new SimpleSAML_Auth_Simple($authsource);
     $as->requireAuth();
     // User logged in with auth source.
     SimpleSAML_Logger::debug('Statistics auth - valid login with auth source [' . $authsource . ']');
     // Retrieving attributes
     $attributes = $as->getAttributes();
     if (!empty($allowedusers)) {
         // Check if userid exists
         if (!isset($attributes[$useridattr][0])) {
             throw new Exception('User ID is missing');
         }
         // Check if userid is allowed access..
         if (in_array($attributes[$useridattr][0], $allowedusers)) {
             SimpleSAML_Logger::debug('Statistics auth - User granted access by user ID [' . $attributes[$useridattr][0] . ']');
             return;
         }
         SimpleSAML_Logger::debug('Statistics auth - User denied access by user ID [' . $attributes[$useridattr][0] . ']');
     } else {
         SimpleSAML_Logger::debug('Statistics auth - no allowedUsers list.');
     }
     if (!is_null($acl)) {
         $acl = new sspmod_core_ACL($acl);
         if ($acl->allows($attributes)) {
             SimpleSAML_Logger::debug('Statistics auth - allowed access by ACL.');
             return;
         }
         SimpleSAML_Logger::debug('Statistics auth - denied access by ACL.');
     } else {
         SimpleSAML_Logger::debug('Statistics auth - no ACL configured.');
     }
     throw new SimpleSAML_Error_Exception('Access denied to the current user.');
 }
Ejemplo n.º 18
0
 protected function clearPersistentData($key)
 {
     if (!in_array($key, self::$kSupportedKeys)) {
         SimpleSAML_Logger::debug("Unsupported key passed to clearPersistentData: " . var_export($key, TRUE));
         return;
     }
     $session_var_name = $this->constructSessionVariableName($key);
     if (isset($this->ssp_state[$session_var_name])) {
         unset($this->ssp_state[$session_var_name]);
     }
 }
 /**
  * Returns the name of the transform class based on a given URI
  *
  * @throws Exception
  * @param string $uri The transform URI
  * @return string The transform implementation class name
  */
 protected function _findClassbyURI($uri)
 {
     switch ($uri) {
         case 'http://www.w3.org/2000/09/xmldsig#enveloped-signature':
             return 'Zend_InfoCard_Xml_Security_Transform_EnvelopedSignature';
         case 'http://www.w3.org/2001/10/xml-exc-c14n#':
             return 'Zend_InfoCard_Xml_Security_Transform_XmlExcC14N';
         default:
             SimpleSAML_Logger::debug("Unknown or Unsupported Transformation Requested");
     }
 }
 /**
  * Transforms the XML Document according to the EnvelopedSignature Transform
  *
  * @throws Exception
  * @param string $strXMLData The input XML data
  * @return string the transformed XML data
  */
 public function transform($strXMLData)
 {
     $sxe = simplexml_load_string($strXMLData);
     $sxe->registerXPathNamespace('ds', 'http://www.w3.org/2000/09/xmldsig#');
     list($signature) = $sxe->xpath("//ds:Signature");
     if (!isset($signature)) {
         SimpleSAML_Logger::debug("Unable to locate Signature Block for EnvelopedSignature Transform");
     }
     $transformed_xml = str_replace($signature->asXML(), "", $sxe->asXML());
     return $transformed_xml;
 }
Ejemplo n.º 21
0
 /**
  * Save consent.
  *
  * Called when the user asks for the consent to be saved. If consent information
  * for the given user and destination already exists, it should be overwritten.
  *
  * @param string $userId        The hash identifying the user at an IdP.
  * @param string $destinationId A string which identifies the destination.
  * @param string $attributeSet  A hash which identifies the attributes.
  *
  * @return void
  */
 public function saveConsent($userId, $destinationId, $attributeSet)
 {
     assert('is_string($userId)');
     assert('is_string($destinationId)');
     assert('is_string($attributeSet)');
     $name = self::_getCookieName($userId, $destinationId);
     $value = $userId . ':' . $attributeSet . ':' . $destinationId;
     SimpleSAML_Logger::debug('Consent cookie - Set [' . $value . ']');
     $value = self::_sign($value);
     $this->_setConsentCookie($name, $value);
 }
Ejemplo n.º 22
0
 /**
  * Constructor for this authentication source.
  *
  * @param array $info   Information about this authentication source.
  * @param array $config Configuration.
  */
 public function __construct($info, $config)
 {
     assert('is_array($info)');
     assert('is_array($config)');
     /* Call the parent constructor first, as required by the interface. */
     parent::__construct($info, $config);
     if (!array_key_exists('uid', $config) || !is_string($config['uid'])) {
         throw new SimpleSAML_Error_Exception("AA configuration error, 'uid' not found or not a string.");
     }
     SimpleSAML_Logger::debug('[aa] auth source Bypass: config uid: ' . $config['uid']);
     $this->uid = $config['uid'];
 }
 public function process(&$request)
 {
     assert('is_array($request)');
     assert('array_key_exists("Attributes", $request)');
     $attributes =& $request['Attributes'];
     if (array_key_exists($this->in_attribute, $attributes)) {
         SimpleSAML_Logger::debug("PolyPseud generating pseudonym from attribute {$this->in_attribute}");
         $attributes[$this->out_attribute] = array(polypseud_generate_pp($this->y_k, $attributes[$this->in_attribute][0]));
     } else {
         throw new SimpleSAML_Error_Exception('Could not generate a polymorphic pseudonym. inAttribute is missing');
     }
 }
Ejemplo n.º 24
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.
  */
 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 Execption('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.');
     }
     SimpleSAML_Logger::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']);
     /* Sign the request */
     sspmod_saml_Message::addSign($this->spMetadata, $idpmetadata, $ar);
     // Shoaib - moved from the SOAPClient.
     $soap = new SAML2_SOAPClient();
     // Send message through SoapClient
     $artifactResponse = $soap->send($ar, $this->spMetadata);
     if (!$artifactResponse->isSuccess()) {
         throw new Exception('Received error from ArtifactResolutionService.');
     }
     $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;
 }
 public function addUser($entry)
 {
     SimpleSAML_Logger::debug('entry var: ' . var_export($entry, 1));
     if ($this->isRegistered('email', $entry['email'])) {
         throw new sspmod_selfregister_Error_UserException('email_taken');
     } elseif ($this->isRegistered('userid', $entry['username'])) {
         throw new sspmod_selfregister_Error_UserException('uid_taken');
     } else {
         //$userid = $this->createUniqueUserId($entry['email']);
         $userid = $entry['username'];
         $sth = $this->dbh->prepare("\n\t\t\t\tINSERT INTO users\n\t\t\t\t(userid, email, password, salt, firstname, lastname, created, updated)\n\t\t\t\tVALUES\n\t\t\t\t(?, ?, ?, ?, ?, ?, now(), now())\n\t\t\t");
         $sth->execute(array($userid, strtolower($entry['email']), $this->hash_pass($entry['userPassword']), $this->salt, $entry['firstname'], $entry['lastname']));
     }
 }
Ejemplo n.º 26
0
 public function getAccessToken($url, $requestToken)
 {
     $acc_req = OAuthRequest::from_consumer_and_token($this->consumer, $requestToken, "GET", $url, NULL);
     $acc_req->sign_request($this->signer, $this->consumer, $requestToken);
     $response_acc = SimpleSAML_Utilities::fetch($acc_req->to_url());
     SimpleSAML_Logger::debug('oauth: Reponse to get access token: ' . $response_acc);
     parse_str($response_acc, $accessResponseParsed);
     if (array_key_exists('error', $accessResponseParsed)) {
         throw new Exception('Error getting request token: ') . $accessResponseParsed['error'];
     }
     $accessToken = $accessResponseParsed['oauth_token'];
     $accessTokenSecret = $accessResponseParsed['oauth_token_secret'];
     return new OAuthToken($accessToken, $accessTokenSecret);
 }
Ejemplo n.º 27
0
 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';
     }
 }
 /**
  * Get en instance of the exporter
  *
  * @param string $type   The exporter type
  * @param array  $option Options for the exporter
  *
  * @return ssmod_janus_Exporter An instance
  */
 public static final function getInstance($type, array $option = null)
 {
     assert('is_string($type)');
     assert('is_array($option) || is_null($option)');
     // Resolve classname of exporter
     try {
         $className = SimpleSAML_Module::resolveClass($type, 'Exporter', 'sspmod_janus_Exporter');
         SimpleSAML_Logger::debug('External exporter class found: ' . $className);
     } catch (Exception $e) {
         SimpleSAML_Logger::debug('External exporter class not found: ' . $type);
         throw $e;
     }
     // Return new instance of exporter
     return new $className($option);
 }
 /**
  * Transform the input XML based on C14n XML Exclusive Canonicalization rules
  *
  * @throws Exception
  * @param string $strXMLData The input XML
  * @return string The output XML
  */
 public function transform($strXMLData)
 {
     $dom = new DOMDocument();
     $dom->loadXML($strXMLData);
     if ($strXMLData == NULL) {
         SimpleSAML_Logger::debug("NOXML: " . $dom->saveXML());
     } else {
         SimpleSAML_Logger::debug("XMLcan: " . $dom->saveXML());
     }
     if (method_exists($dom, 'C14N')) {
         return $dom->C14N(true, false);
     }
     SimpleSAML_Logger::debug("This transform requires the C14N() method to exist in the DOM extension");
     throw new Exception('This transform requires the C14N() method to exist in the DOM extension');
 }
 /**
  * Filter out YubiKey 'otp' attribute and replace it with
  * a 'yubiPrefix' attribute that leaves out the dynamic part.
  *
  * @param array &$state  The state we should update.
  */
 public function process(&$state)
 {
     assert('is_array($state)');
     assert('array_key_exists("Attributes", $state)');
     $attributes = $state['Attributes'];
     SimpleSAML_Logger::debug('OTP2YubiPrefix: enter with attributes: ' . implode(',', array_keys($attributes)));
     $otps = $attributes['otp'];
     $otp = $otps['0'];
     $token_size = 32;
     $identity = substr($otp, 0, strlen($otp) - $token_size);
     $attributes['yubiPrefix'] = array($identity);
     SimpleSAML_Logger::info('OTP2YubiPrefix: otp: ' . $otp . ' identity: ' . $identity . ' (otp keys: ' . implode(',', array_keys($otps)) . ')');
     unset($attributes['otp']);
     SimpleSAML_Logger::debug('OTP2YubiPrefix: leaving with attributes: ' . implode(',', array_keys($attributes)));
 }