/**
  * internal function to create a new banned ip
  * @param $initial_hits
  * @param $exception_type
  */
 protected function createBannedIP($initial_hits, $exception_type)
 {
     try {
         $remote_address = IPHelper::getUserIp();
         //try to create on cache
         $this->cache_service->addSingleValue($remote_address, $initial_hits, intval($this->server_configuration_service->getConfigValue("BlacklistSecurityPolicy.BannedIpLifeTimeSeconds")));
         Log::warning(sprintf("AbstractBlacklistSecurityPolicy: Banning ip %s by Exception %s", $remote_address, $exception_type));
         //try to create on db
         $this->tx_service->transaction(function () use($remote_address, $exception_type, $initial_hits) {
             $banned_ip = BannedIP::where("ip", "=", $remote_address)->first();
             if (!$banned_ip) {
                 $banned_ip = new BannedIP();
                 $banned_ip->ip = $remote_address;
             }
             $banned_ip->exception_type = $exception_type;
             $banned_ip->hits = $initial_hits;
             if (Auth::check()) {
                 $banned_ip->user_id = Auth::user()->getId();
             }
             $banned_ip->Save();
         });
     } catch (Exception $ex) {
         Log::error($ex);
     }
 }
Exemple #2
0
 public function __construct($len = self::DefaultByteLength)
 {
     $this->len = $len;
     $this->is_hashed = false;
     $this->issued = gmdate("Y-m-d H:i:s", time());
     $this->from_ip = IPHelper::getUserIp();
 }
 public function postLogin()
 {
     //go to authentication flow again
     $msg = $this->memento_service->getCurrentRequest();
     $this->user_action_service->addUserAction($this->auth_service->getCurrentUser(), IPHelper::getUserIp(), IUserActionService::LoginAction, $msg->getParam(OpenIdProtocol::OpenIDProtocol_Realm));
     return Redirect::action("OpenIdProviderController@endpoint");
 }
 /**
  * Apply security policy on a exception
  * @param Exception $ex
  * @return mixed
  */
 public function apply(Exception $ex)
 {
     try {
         if (get_parent_class($ex) == 'oauth2\\exceptions\\OAuth2ClientBaseException') {
             $client_id = $ex->getClientId();
             //save oauth2 exception by client id
             if (!is_null($client_id) && !empty($client_id)) {
                 $client = $this->client_service->getClientById($client_id);
                 if (is_null($client)) {
                     Log::warning(sprintf("client id %s does not exists!", $client));
                     return;
                 }
                 $exception_class = get_class($ex);
                 $trail = new OAuth2TrailException();
                 $trail->from_ip = IPHelper::getUserIp();
                 $trail->exception_type = $exception_class;
                 $trail->client_id = $client->getId();
                 $trail->Save();
                 //check exception count by type on last "MinutesWithoutExceptions" minutes...
                 $exception_count = intval(OAuth2TrailException::where('client_id', '=', intval($client->getId()))->where('exception_type', '=', $exception_class)->where('created_at', '>', DB::raw('( UTC_TIMESTAMP() - INTERVAL ' . $this->server_configuration_service->getConfigValue("OAuth2SecurityPolicy.MinutesWithoutExceptions") . ' MINUTE )'))->count());
                 if (array_key_exists($exception_class, $this->exception_dictionary)) {
                     $params = $this->exception_dictionary[$exception_class];
                     $max_attempts = !is_null($params[0]) && !empty($params[0]) ? intval($this->server_configuration_service->getConfigValue($params[0])) : 0;
                     if ($exception_count >= $max_attempts) {
                         $this->counter_measure->trigger(array('client_id' => $client->getId()));
                     }
                 }
             }
         }
     } catch (Exception $ex) {
         Log::error($ex);
     }
 }
 public function postLogin()
 {
     $user = $this->auth_service->getCurrentUser();
     $identifier = $user->getIdentifier();
     $this->user_action_service->addUserAction($this->auth_service->getCurrentUser(), IPHelper::getUserIp(), IUserActionService::LoginAction);
     $default_url = URL::action("UserController@getIdentity", array("identifier" => $identifier));
     return Redirect::intended($default_url);
 }
 public function postConsent($trust_action)
 {
     if (is_array($trust_action)) {
         $msg = $this->memento_service->getCurrentRequest();
         if (is_null($msg) || !$msg->isValid()) {
             throw new InvalidOpenIdMessageException();
         }
         $this->user_action_service->addUserAction($this->auth_service->getCurrentUser(), IPHelper::getUserIp(), IUserActionService::ConsentAction, $msg->getParam(OpenIdProtocol::OpenIDProtocol_Realm));
         $this->auth_service->setUserAuthorizationResponse($trust_action[0]);
         return Redirect::action('OpenIdProviderController@endpoint');
     }
     return Redirect::action('UserController@getConsent');
 }
 public function trigger(array $params = array())
 {
     try {
         $remote_address = IPHelper::getUserIp();
         if ($this->cache_service->exists($remote_address)) {
             Log::warning(sprintf("DelayCounterMeasure: attempt from banned ip %s", $remote_address));
             $hits = intval($this->cache_service->getSingleValue($remote_address));
             sleep(2 ^ $hits);
         }
     } catch (Exception $ex) {
         Log::error($ex);
     }
 }
Exemple #8
0
 public static function create(AccessToken $access_token, $lifetime = 0)
 {
     $instance = new self();
     $instance->value = Rand::getString($instance->len, OAuth2Protocol::VsChar, true);
     $instance->scope = $access_token->getScope();
     $instance->user_id = $access_token->getUserId();
     $instance->client_id = $access_token->getClientId();
     $instance->audience = $access_token->getAudience();
     $instance->from_ip = IPHelper::getUserIp();
     $instance->lifetime = intval($lifetime);
     $instance->is_hashed = false;
     return $instance;
 }
 /**
  * @param $user_id
  * @param $client_id
  * @param $scope
  * @param string $audience
  * @param null $redirect_uri
  * @param string $access_type
  * @param string $approval_prompt
  * @param bool $has_previous_user_consent
  * @param int $lifetime
  * @return AuthorizationCode
  */
 public static function create($user_id, $client_id, $scope, $audience = '', $redirect_uri = null, $access_type = OAuth2Protocol::OAuth2Protocol_AccessType_Online, $approval_prompt = OAuth2Protocol::OAuth2Protocol_Approval_Prompt_Auto, $has_previous_user_consent = false, $lifetime = 600)
 {
     $instance = new self();
     $instance->value = Rand::getString($instance->len, OAuth2Protocol::VsChar, true);
     $instance->scope = $scope;
     $instance->user_id = $user_id;
     $instance->redirect_uri = $redirect_uri;
     $instance->client_id = $client_id;
     $instance->lifetime = intval($lifetime);
     $instance->audience = $audience;
     $instance->is_hashed = false;
     $instance->from_ip = IPHelper::getUserIp();
     $instance->access_type = $access_type;
     $instance->approval_prompt = $approval_prompt;
     $instance->has_previous_user_consent = $has_previous_user_consent;
     return $instance;
 }
 /**
  * Keeps track of exceptions
  * @param Exception $ex
  * @return mixed
  */
 public function trackException(Exception $ex)
 {
     try {
         $remote_ip = IPHelper::getUserIp();
         $class_name = get_class($ex);
         $user_trail = new UserExceptionTrail();
         $user_trail->from_ip = $remote_ip;
         $user_trail->exception_type = $class_name;
         if (Auth::check()) {
             $user_trail->user_id = Auth::user()->getId();
         }
         $user_trail->Save();
         Log::error(sprintf("* CheckPointService - exception : << %s >> - IP Address: %s", $ex->getMessage(), $remote_ip));
         //applying policies
         foreach ($this->policies as $policy) {
             $policy->apply($ex);
         }
     } catch (Exception $ex) {
         Log::error($ex);
     }
 }
 public function logout()
 {
     $this->user_action_service->addUserAction($this->auth_service->getCurrentUser(), IPHelper::getUserIp(), IUserActionService::LogoutAction);
     Auth::logout();
     return Redirect::action("UserController@getLogin");
 }
Exemple #12
0
 /**
  * Creates a new refresh token and associate it with given access token
  * @param AccessToken $access_token
  * @return RefreshToken
  */
 public function createRefreshToken(AccessToken &$access_token)
 {
     $refresh_token = RefreshToken::create($access_token, $this->configuration_service->getConfigValue('OAuth2.RefreshToken.Lifetime'));
     $client_service = $this->client_service;
     $auth_service = $this->auth_service;
     $cache_service = $this->cache_service;
     $this_var = $this;
     $this->tx_service->transaction(function () use(&$refresh_token, &$access_token, &$this_var, &$client_service, &$auth_service, &$cache_service) {
         $value = $refresh_token->getValue();
         //hash the given value, bc tokens values are stored hashed on DB
         $hashed_value = Hash::compute('sha256', $value);
         $client_id = $refresh_token->getClientId();
         $user_id = $refresh_token->getUserId();
         $client = $client_service->getClientById($client_id);
         $user = $auth_service->getUserById($user_id);
         //stores in DB
         $refresh_token_db = new DBRefreshToken(array('value' => $hashed_value, 'lifetime' => $refresh_token->getLifetime(), 'scope' => $refresh_token->getScope(), 'from_ip' => IPHelper::getUserIp(), 'audience' => $access_token->getAudience()));
         $refresh_token_db->client()->associate($client);
         $refresh_token_db->user()->associate($user);
         $refresh_token_db->Save();
         //associate current access token to refresh token on DB
         $access_token_db = DBAccessToken::where('value', '=', Hash::compute('sha256', $access_token->getValue()))->first();
         $access_token_db->refresh_token()->associate($refresh_token_db);
         $access_token_db->Save();
         $access_token->setRefreshToken($refresh_token);
         $cache_service->incCounter($client_id . TokenService::ClientRefreshTokensQty, TokenService::ClientRefreshTokensQtyLifetime);
     });
     return $refresh_token;
 }
 /**
  * @param OAuth2Request $request
  * @return mixed|OAuth2AccessTokenValidationResponse|void
  * @throws \oauth2\exceptions\InvalidOAuth2Request
  * @throws \oauth2\exceptions\LockedClientException
  * @throws \oauth2\exceptions\InvalidApplicationType
  * @throws \oauth2\exceptions\BearerTokenDisclosureAttemptException
  */
 public function completeFlow(OAuth2Request $request)
 {
     $reflector = new ReflectionClass($request);
     $class_name = $reflector->getName();
     if ($class_name == 'oauth2\\requests\\OAuth2AccessTokenValidationRequest') {
         parent::completeFlow($request);
         $token_value = $request->getToken();
         try {
             $access_token = $this->token_service->getAccessToken($token_value);
             if (is_null($access_token)) {
                 throw new ExpiredAccessTokenException(sprintf('Access token %s is expired!', $token_value));
             }
             if (!$this->current_client->isResourceServerClient()) {
                 // if current client is not a resource server, then we could only access to our own tokens
                 if ($access_token->getClientId() !== $this->current_client_id) {
                     throw new BearerTokenDisclosureAttemptException($this->current_client_id, sprintf('access token %s does not belongs to client id %s', $token_value, $this->current_client_id));
                 }
             } else {
                 // current client is a resource server, validate client type (must be confidential)
                 if ($this->current_client->getClientType() !== IClient::ClientType_Confidential) {
                     throw new InvalidApplicationType($this->current_client_id, 'resource server client is not of confidential type!');
                 }
                 //validate resource server IP address
                 $current_ip = IPHelper::getUserIp();
                 $resource_server = $this->current_client->getResourceServer();
                 //check if resource server is active
                 if (!$resource_server->active) {
                     throw new LockedClientException($this->current_client_id, 'resource server is disabled!');
                 }
                 //check resource server ip address
                 if ($current_ip !== $resource_server->ip) {
                     throw new BearerTokenDisclosureAttemptException($this->current_client_id, sprintf('resource server ip (%s) differs from current request ip %s', $resource_server->ip, $current_ip));
                 }
                 // check if current ip belongs to a registered resource server audience
                 if (!$this->token_service->checkAccessTokenAudience($access_token, $current_ip)) {
                     throw new BearerTokenDisclosureAttemptException($this->current_client_id, sprintf('access token current audience does not match with current request ip %s', $current_ip));
                 }
             }
             $allowed_origins = array();
             $allowed_urls = array();
             $issued_client = $this->client_service->getClientById($access_token->getClientId());
             if (is_null($issued_client)) {
                 throw new BearerTokenDisclosureAttemptException($this->current_client_id, sprintf('access token %s does not belongs to client id %s', $token_value, $access_token->getClientId()));
             }
             foreach ($issued_client->getClientAllowedOrigins() as $origin) {
                 array_push($allowed_origins, $origin->allowed_origin);
             }
             foreach ($issued_client->getClientRegisteredUris() as $url) {
                 array_push($allowed_urls, $url->uri);
             }
             return new OAuth2AccessTokenValidationResponse($token_value, $access_token->getScope(), $access_token->getAudience(), $access_token->getClientId(), $access_token->getRemainingLifetime(), $access_token->getUserId(), $issued_client->getApplicationType(), $allowed_urls, $allowed_origins);
         } catch (InvalidAccessTokenException $ex1) {
             $this->log_service->error($ex1);
             throw new BearerTokenDisclosureAttemptException($this->current_client_id, $ex1->getMessage());
         } catch (InvalidGrantTypeException $ex2) {
             $this->log_service->error($ex2);
             throw new BearerTokenDisclosureAttemptException($this->current_client_id, $ex2->getMessage());
         }
     }
     throw new InvalidOAuth2Request();
 }
 /**
  * Apply security policy
  * @param Exception $ex
  * @return mixed|void
  */
 public function apply(Exception $ex)
 {
     try {
         $remote_ip = IPHelper::getUserIp();
         $exception_class = get_class($ex);
         //check exception count by type on last "MinutesWithoutExceptions" minutes...
         $exception_count = intval(UserExceptionTrail::where('from_ip', '=', $remote_ip)->where('exception_type', '=', $exception_class)->where('created_at', '>', DB::raw('( UTC_TIMESTAMP() - INTERVAL ' . $this->server_configuration_service->getConfigValue("BlacklistSecurityPolicy.MinutesWithoutExceptions") . ' MINUTE )'))->count());
         if (array_key_exists($exception_class, $this->exception_dictionary)) {
             $params = $this->exception_dictionary[$exception_class];
             $max_attempts = !is_null($params[0]) && !empty($params[0]) ? intval($this->server_configuration_service->getConfigValue($params[0])) : 0;
             $initial_delay_on_tar_pit = intval($this->server_configuration_service->getConfigValue($params[1]));
             if ($exception_count >= $max_attempts) {
                 $this->createBannedIP($initial_delay_on_tar_pit, $exception_class);
             }
         }
     } catch (Exception $ex) {
         Log::error($ex);
     }
 }
 public function postLogin()
 {
     $auth_request = $this->memento_service->getCurrentAuthorizationRequest();
     $this->user_action_service->addUserAction($this->auth_service->getCurrentUser(), IPHelper::getUserIp(), IUserActionService::LoginAction, $auth_request->getRedirectUri());
     return Redirect::action("OAuth2ProviderController@authorize");
 }