/**
  * Save a session to the data store.
  *
  * @param SimpleSAML_Session $session The session object we should save.
  */
 public function saveSession(SimpleSAML_Session $session)
 {
     $sessionId = $session->getSessionId();
     $config = SimpleSAML_Configuration::getInstance();
     $sessionDuration = $config->getInteger('session.duration', 8 * 60 * 60);
     $expire = time() + $sessionDuration;
     $this->store->set('session', $sessionId, $session, $expire);
 }
예제 #2
0
 /**
  * Retrieve our singleton instance.
  *
  * @return SimpleSAML_Store|FALSE  The datastore, or FALSE if it isn't enabled.
  */
 public static function getInstance()
 {
     if (self::$instance !== NULL) {
         return self::$instance;
     }
     $config = SimpleSAML_Configuration::getInstance();
     $storeType = $config->getString('store.type', NULL);
     if ($storeType === NULL) {
         $storeType = $config->getString('session.handler', 'phpsession');
     }
     switch ($storeType) {
         case 'phpsession':
             /* We cannot support advanced features with the PHP session store. */
             self::$instance = FALSE;
             break;
         case 'memcache':
             self::$instance = new SimpleSAML_Store_Memcache();
             break;
         case 'sql':
             self::$instance = new SimpleSAML_Store_SQL();
             break;
         default:
             if (strpos($storeType, ':') === FALSE) {
                 throw new SimpleSAML_Error_Exception('Unknown datastore type: ' . var_export($storeType, TRUE));
             }
             /* Datastore from module. */
             $className = SimpleSAML_Module::resolveClass($storeType, 'Store', 'SimpleSAML_Store');
             self::$instance = new $className();
     }
     return self::$instance;
 }
예제 #3
0
 /**
  * Retrieve our singleton instance.
  *
  * @return SimpleSAML_Store|false  The data store, or false if it isn't enabled.
  */
 public static function getInstance()
 {
     if (self::$instance !== null) {
         return self::$instance;
     }
     $config = SimpleSAML_Configuration::getInstance();
     $storeType = $config->getString('store.type', null);
     if ($storeType === null) {
         $storeType = $config->getString('session.handler', 'phpsession');
     }
     switch ($storeType) {
         case 'phpsession':
             // we cannot support advanced features with the PHP session store
             self::$instance = false;
             break;
         case 'memcache':
             self::$instance = new SimpleSAML_Store_Memcache();
             break;
         case 'sql':
             self::$instance = new SimpleSAML_Store_SQL();
             break;
         default:
             // datastore from module
             $className = SimpleSAML_Module::resolveClass($storeType, 'Store', 'SimpleSAML_Store');
             self::$instance = new $className();
     }
     return self::$instance;
 }
function oauth2_hook_cron(&$croninfo)
{
    assert('is_array($croninfo)');
    assert('array_key_exists("summary", $croninfo)');
    assert('array_key_exists("tag", $croninfo)');
    $oauth2config = SimpleSAML_Configuration::getOptionalConfig('module_oauth2.php');
    if (is_null($oauth2config->getValue('cron_tag', 'hourly'))) {
        return;
    }
    if ($oauth2config->getValue('cron_tag', NULL) !== $croninfo['tag']) {
        return;
    }
    try {
        $store = SimpleSAML_Store::getInstance();
        if (!$store instanceof \SimpleSAML\Modules\DBAL\Store\DBAL) {
            throw new \SimpleSAML_Error_Exception('OAuth2 module: Only DBAL Store is supported');
        }
        $accessTokenRepository = new AccessTokenRepository();
        $accessTokenRepository->removeExpiredAccessTokens();
        $authTokenRepository = new AuthCodeRepository();
        $authTokenRepository->removeExpiredAuthCodes();
        $refreshTokenRepository = new RefreshTokenRepository();
        $refreshTokenRepository->removeExpiredRefreshTokens();
        $croninfo['summary'][] = 'OAuth2 clean up. Removed expired entries from OAuth2 storage.';
    } catch (Exception $e) {
        $message = 'OAuth2 clean up cron script failed: ' . $e->getMessage();
        SimpleSAML\Logger::warning($message);
        $croninfo['summary'][] = $message;
    }
}
예제 #5
0
 /**
  * Retrieve our singleton instance.
  *
  * @return SimpleSAML_Store|false  The data store, or false if it isn't enabled.
  */
 public static function getInstance()
 {
     if (self::$instance !== null) {
         return self::$instance;
     }
     $config = SimpleSAML_Configuration::getInstance();
     $storeType = $config->getString('store.type', null);
     if ($storeType === null) {
         $storeType = $config->getString('session.handler', 'phpsession');
     }
     switch ($storeType) {
         case 'phpsession':
             // we cannot support advanced features with the PHP session store
             self::$instance = false;
             break;
         case 'memcache':
             self::$instance = new SimpleSAML_Store_Memcache();
             break;
         case 'sql':
             self::$instance = new SimpleSAML_Store_SQL();
             break;
         default:
             // datastore from module
             try {
                 $className = SimpleSAML\Module::resolveClass($storeType, 'Store', 'SimpleSAML_Store');
             } catch (Exception $e) {
                 $c = $config->toArray();
                 $c['store.type'] = 'phpsession';
                 throw new SimpleSAML\Error\CriticalConfigurationError("Invalid 'store.type' configuration option. Cannot find store '{$storeType}'.", null, $c);
             }
             self::$instance = new $className();
     }
     return self::$instance;
 }
예제 #6
0
 /**
  * Initialize the session handler.
  *
  * This function creates an instance of the session handler which is
  * selected in the 'session.handler' configuration directive. If no
  * session handler is selected, then we will fall back to the default
  * PHP session handler.
  */
 private static function createSessionHandler()
 {
     $store = SimpleSAML_Store::getInstance();
     if ($store === FALSE) {
         self::$sessionHandler = new SimpleSAML_SessionHandlerPHP();
     } else {
         self::$sessionHandler = new SimpleSAML_SessionHandlerStore($store);
     }
 }
예제 #7
0
 /**
  * Retrieve the SQL datastore.
  *
  * Will also ensure that the NameID table is present.
  *
  * @return SimpleSAML_Store_SQL  SQL datastore.
  */
 private static function getStore()
 {
     $store = SimpleSAML_Store::getInstance();
     if (!$store instanceof SimpleSAML_Store_SQL) {
         throw new SimpleSAML_Error_Exception('SQL NameID store requires simpleSAMLphp to be configured with a SQL datastore.');
     }
     self::createTable($store);
     return $store;
 }
 /**
  * ClientRepository constructor.
  */
 public function __construct()
 {
     $this->config = \SimpleSAML_Configuration::getOptionalConfig('module_oauth2.php');
     $this->store = \SimpleSAML_Store::getInstance();
     if (!$this->store instanceof DBAL) {
         throw new \SimpleSAML_Error_Exception('OAuth2 module: Only DBAL Store is supported');
     }
     $this->conn = $this->store->getConnection();
 }
function dbal_hook_cron(&$croninfo)
{
    $store = SimpleSAML_Store::getInstance();
    if (!$store instanceof \SimpleSAML\Modules\DBAL\Store\DBAL) {
        throw new \SimpleSAML_Error_Exception('OAuth2 module: Only DBAL Store is supported');
    }
    $store->cleanKVStore();
    $dbinfo['summary'][] = 'Cleaned Key-Value Store';
}
예제 #10
0
 public function __construct($config)
 {
     parent::__construct($config);
     $this->store = SimpleSAML_Store::getInstance();
     if ($this->store === FALSE) {
         throw new Exception('Datastore not configured.');
     }
     if (isset($config['data.type']) && is_string($config['data.type'])) {
         $this->dataType = $config['data.type'];
     }
 }
function oauth2_hook_dbal(&$dbinfo)
{
    $store = SimpleSAML_Store::getInstance();
    if (!$store instanceof \SimpleSAML\Modules\DBAL\Store\DBAL) {
        throw new \SimpleSAML_Error_Exception('OAuth2 module: Only DBAL Store is supported');
    }
    $schema = new \Doctrine\DBAL\Schema\Schema();
    $clientTable = $store->getPrefix() . '_oauth2_client';
    $client = $schema->createTable($clientTable);
    $client->addColumn('id', 'string', ['length' => 255]);
    $client->addColumn('secret', 'string', ['length' => 255]);
    $client->addColumn('name', 'string', ['length' => 255]);
    $client->addColumn('description', 'text', ['notnull' => false]);
    $client->addColumn('redirect_uri', 'json_array');
    $client->addColumn('scopes', 'json_array');
    $client->setPrimaryKey(['id']);
    $accesstokenTable = $store->getPrefix() . '_oauth2_accesstoken';
    $accesstoken = $schema->createTable($accesstokenTable);
    $accesstoken->addColumn('id', 'string', ['length' => 255]);
    $accesstoken->addColumn('scopes', 'json_array', ['notnull' => false]);
    $accesstoken->addColumn('attributes', 'json_array', ['notnull' => false]);
    $accesstoken->addColumn('expires_at', 'datetime');
    $accesstoken->addColumn('user_id', 'string', ['length' => 255]);
    $accesstoken->addColumn('client_id', 'string', ['length' => 255]);
    $accesstoken->addColumn('is_revoked', 'boolean', ['default' => false]);
    $accesstoken->setPrimaryKey(['id']);
    $accesstoken->addForeignKeyConstraint($clientTable, ['client_id'], ['id'], ['onDelete' => 'CASCADE']);
    $refreshtokenTable = $store->getPrefix() . '_oauth2_refreshtoken';
    $refreshtoken = $schema->createTable($refreshtokenTable);
    $refreshtoken->addColumn('id', 'string', ['length' => 255]);
    $refreshtoken->addColumn('expires_at', 'datetime');
    $refreshtoken->addColumn('accesstoken_id', 'string', ['length' => 255]);
    $refreshtoken->addColumn('is_revoked', 'boolean', ['default' => false]);
    $refreshtoken->setPrimaryKey(['id']);
    $refreshtoken->addForeignKeyConstraint($accesstokenTable, ['accesstoken_id'], ['id'], ['onDelete' => 'CASCADE']);
    $authcodeTable = $store->getPrefix() . '_oauth2_authcode';
    $authcode = $schema->createTable($authcodeTable);
    $authcode->addColumn('id', 'string', ['length' => 255]);
    $authcode->addColumn('scopes', 'json_array');
    $authcode->addColumn('expires_at', 'datetime');
    $authcode->addColumn('user_id', 'string', ['length' => 255]);
    $authcode->addColumn('client_id', 'string', ['length' => 255]);
    $authcode->addColumn('is_revoked', 'boolean', ['default' => false]);
    $authcode->addColumn('redirect_uri', 'text');
    $authcode->addForeignKeyConstraint($clientTable, ['client_id'], ['id'], ['onDelete' => 'CASCADE']);
    $store->createOrUpdateSchema($schema, $store->getPrefix() . '_oauth2');
    $dbinfo['summary'][] = 'Created OAuth2 Schema';
}
예제 #12
0
 /**
  * Create the redirect URL for a message.
  *
  * @param  SAML2_Message $message The message.
  * @return string        The URL the user should be redirected to in order to send a message.
  * @throws Exception
  */
 public function getRedirectURL(SAML2_Message $message)
 {
     $store = SimpleSAML_Store::getInstance();
     if ($store === FALSE) {
         throw new Exception('Unable to send artifact without a datastore configured.');
     }
     $generatedId = pack('H*', (string) SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(20)));
     $artifact = base64_encode("" . sha1($message->getIssuer(), TRUE) . $generatedId);
     $artifactData = $message->toUnsignedXML();
     $artifactDataString = $artifactData->ownerDocument->saveXML($artifactData);
     $store->set('artifact', $artifact, $artifactDataString, time() + 15 * 60);
     $params = array('SAMLart' => $artifact);
     $relayState = $message->getRelayState();
     if ($relayState !== NULL) {
         $params['RelayState'] = $relayState;
     }
     return SimpleSAML_Utilities::addURLparameter($message->getDestination(), $params);
 }
예제 #13
0
function dbal_hook_dbal(&$dbinfo)
{
    $store = SimpleSAML_Store::getInstance();
    if (!$store instanceof \SimpleSAML\Modules\DBAL\Store\DBAL) {
        throw new \SimpleSAML_Error_Exception('OAuth2 module: Only DBAL Store is supported');
    }
    $prefix = $store->getPrefix() . '_kvstore';
    $schema = new \Doctrine\DBAL\Schema\Schema();
    $kvstore = $schema->createTable($prefix);
    $kvstore->addColumn('_type', 'string', array('length' => 30, 'notnull' => true));
    $kvstore->addColumn('_key', 'string', array('length' => 50, 'notnull' => true));
    $kvstore->addColumn('_value', 'text', array('notnull' => true));
    $kvstore->addColumn('_expire', 'datetime', array('notnull' => false));
    $kvstore->setPrimaryKey(array('_key', '_type'));
    $kvstore->addIndex(array('_expire'));
    // Update schema
    $store->createOrUpdateSchema($schema, $prefix);
    $dbinfo['summary'][] = 'Created Key-Value Schema';
}
예제 #14
0
try {
    $assertions = sspmod_saml_Message::processResponse($spMetadata, $idpMetadata, $response);
} catch (sspmod_saml_Error $e) {
    /* The status of the response wasn't "success". */
    $e = $e->toException();
    SimpleSAML_Auth_State::throwException($state, $e);
}
$authenticatingAuthority = NULL;
$nameId = NULL;
$sessionIndex = NULL;
$expire = NULL;
$attributes = array();
$foundAuthnStatement = FALSE;
foreach ($assertions as $assertion) {
    /* Check for duplicate assertion (replay attack). */
    $store = SimpleSAML_Store::getInstance();
    if ($store !== FALSE) {
        $aID = $assertion->getId();
        if ($store->get('saml.AssertionReceived', $aID) !== NULL) {
            $e = new SimpleSAML_Error_Exception('Received duplicate assertion.');
            SimpleSAML_Auth_State::throwException($state, $e);
        }
        $notOnOrAfter = $assertion->getNotOnOrAfter();
        if ($notOnOrAfter === NULL) {
            $notOnOrAfter = time() + 24 * 60 * 60;
        } else {
            $notOnOrAfter += 60;
            /* We allow 60 seconds clock skew, so add it here also. */
        }
        $store->set('saml.AssertionReceived', $aID, TRUE, $notOnOrAfter);
    }
예제 #15
0
 /**
  * Log out of the given sessions.
  *
  * @param string $authId  The authsource ID.
  * @param array $nameId  The NameID of the user.
  * @param array $sessionIndexes  The SessionIndexes we should log out of. Logs out of all if this is empty.
  * @returns int|FALSE  Number of sessions logged out, or FALSE if not supported.
  */
 public static function logoutSessions($authId, array $nameId, array $sessionIndexes)
 {
     assert('is_string($authId)');
     $store = SimpleSAML_Store::getInstance();
     if ($store === FALSE) {
         /* We don't have a datastore. */
         return FALSE;
     }
     /* Normalize NameID. */
     ksort($nameId);
     $strNameId = serialize($nameId);
     $strNameId = sha1($strNameId);
     /* Normalize SessionIndexes. */
     foreach ($sessionIndexes as &$sessionIndex) {
         assert('is_string($sessionIndex)');
         if (strlen($sessionIndex) > 50) {
             $sessionIndex = sha1($sessionIndex);
         }
     }
     unset($sessionIndex);
     // Remove reference
     if ($store instanceof SimpleSAML_Store_SQL) {
         $sessions = self::getSessionsSQL($store, $authId, $strNameId);
     } elseif (empty($sessionIndexes)) {
         /* We cannot fetch all sessions without a SQL store. */
         return FALSE;
     } else {
         $sessions = self::getSessionsStore($store, $authId, $strNameId, $sessionIndexes);
     }
     if (empty($sessionIndexes)) {
         $sessionIndexes = array_keys($sessions);
     }
     $sessionHandler = SimpleSAML_SessionHandler::getSessionHandler();
     $numLoggedOut = 0;
     foreach ($sessionIndexes as $sessionIndex) {
         if (!isset($sessions[$sessionIndex])) {
             SimpleSAML_Logger::info('saml.LogoutStore: Logout requested for unknown SessionIndex.');
             continue;
         }
         $sessionId = $sessions[$sessionIndex];
         $session = SimpleSAML_Session::getSession($sessionId);
         if ($session === NULL) {
             SimpleSAML_Logger::info('saml.LogoutStore: Skipping logout of missing session.');
             continue;
         }
         if (!$session->isValid($authId)) {
             SimpleSAML_Logger::info('saml.LogoutStore: Skipping logout of session because it isn\'t authenticated.');
             continue;
         }
         SimpleSAML_Logger::info('saml.LogoutStore: Logging out of session with trackId [' . $session->getTrackId() . '].');
         $session->doLogout($authId);
         $numLoggedOut += 1;
     }
     return $numLoggedOut;
 }
예제 #16
0
 /**
  * Initialize the session handler.
  *
  * This function creates an instance of the session handler which is
  * selected in the 'session.handler' configuration directive. If no
  * session handler is selected, then we will fall back to the default
  * PHP session handler.
  */
 private static function createSessionHandler()
 {
     $store = SimpleSAML_Store::getInstance();
     if ($store === false) {
         self::$sessionHandler = new SimpleSAML_SessionHandlerPHP();
     } else {
         /** @var SimpleSAML_Store $store At this point, $store can only be an object */
         self::$sessionHandler = new SimpleSAML_SessionHandlerStore($store);
     }
 }