/**
  * {@inheritdoc}
  */
 public function isTokenValid(CsrfToken $token)
 {
     if (!$this->storage->hasToken($token->getId())) {
         return false;
     }
     return StringUtils::equals($this->storage->getToken($token->getId()), $token->getValue());
 }
 /**
  * {@inheritdoc}
  */
 public function connect(Application $app)
 {
     $controllers = $app['controllers_factory'];
     $controllers->post('/oauth/token', function (Request $request) use($app) {
         $grantType = $request->request->get('grant_type');
         $clientId = $request->server->get('PHP_AUTH_USER', $request->request->get('client_id'));
         $secret = $request->server->get('PHP_AUTH_PW', $request->request->get('client_secret'));
         if (empty($clientId)) {
             throw new OAuthInvalidRequestException('Missing client_id parameter.');
         }
         if (empty($grantType)) {
             throw new OAuthInvalidRequestException('Missing grant_type parameter.');
         }
         $client = $app['oauth2.client.provider']->get($clientId);
         if (empty($client)) {
             throw new OAuthInvalidClientException('Unknown client');
         }
         if (!empty($secret) && !StringUtils::equals($client->getSecret(), $secret)) {
             throw new OAuthUnauthorizedClientException();
         }
         $grantType = $app['oauth2.grant_types']->get($grantType);
         if (!in_array($grantType->getName(), $client->getGrantTypes())) {
             throw new OAuthUnauthorizedClientException();
         }
         return $grantType->handle($request, $client);
     });
     return $controllers;
 }
 /**
  * {@inheritdoc}
  */
 protected function processAutoLoginCookie(array $cookieParts, Request $request)
 {
     if (count($cookieParts) !== 4) {
         throw new AuthenticationException('The cookie is invalid.');
     }
     list($class, $username, $expires, $hash) = $cookieParts;
     if (false === ($username = base64_decode($username, true))) {
         throw new AuthenticationException('$username contains a character from outside the base64 alphabet.');
     }
     try {
         $user = $this->getUserProvider($class)->loadUserByUsername($username);
     } catch (\Exception $e) {
         if (!$e instanceof AuthenticationException) {
             $e = new AuthenticationException($e->getMessage(), $e->getCode(), $e);
         }
         throw $e;
     }
     if (!$user instanceof UserInterface) {
         throw new \RuntimeException(sprintf('The UserProviderInterface implementation must return an instance of UserInterface, but returned "%s".', get_class($user)));
     }
     if (true !== StringUtils::equals($this->generateCookieHash($class, $username, $expires, $user->getPassword()), $hash)) {
         throw new AuthenticationException('The cookie\'s hash is invalid.');
     }
     if ($expires < time()) {
         throw new AuthenticationException('The cookie has expired.');
     }
     return $user;
 }
Example #4
0
 function tokensMatch($request)
 {
     $token = $request->session()->token();
     $header = $request->header('x-xsrf-token');
     //in keys case sensitivity is important!!!!
     return StringUtils::equals($token, $request->input('_token')) || $header && StringUtils::equals($token, $header);
 }
 /**
  * {@InheritDoc}
  *
  * @throws NonceExpiredException
  */
 public function validateDigest(WsseUserToken $wsseToken, UserInterface $user)
 {
     $created = $wsseToken->created;
     $nonce = $wsseToken->nonce;
     $digest = $wsseToken->digest;
     $secret = $user->getPassword();
     // Check created time is not too far in the future (leaves 5 minutes margin)
     if (strtotime($created) > time() + 300) {
         throw new WsseAuthenticationException(sprintf('Token created date cannot be in future (%d seconds in the future).', time() - strtotime($created)));
     }
     // Expire timestamp after 5 minutes
     if (strtotime($created) < time() - 300) {
         throw new WsseAuthenticationException(sprintf('Token created date has expired its 300 seconds of validity (%d seconds).', strtotime($created) - time()));
     }
     // Validate that the nonce is *not* used in the last 10 minutes
     // if it has, this could be a replay attack
     if (file_exists($this->cacheDir . '/' . $nonce) && file_get_contents($this->cacheDir . '/' . $nonce) + 600 > time()) {
         throw new NonceExpiredException('Previously used nonce detected.');
     }
     // If cache directory does not exist we create it
     if (!is_dir($this->cacheDir)) {
         mkdir($this->cacheDir, 0777, true);
     }
     file_put_contents($this->cacheDir . '/' . $nonce, time());
     // Validate Secret
     $expected = base64_encode(sha1(base64_decode($nonce) . $created . $secret, true));
     if (!StringUtils::equals($expected, $digest)) {
         throw new WsseAuthenticationException('Token digest is not valid.');
     }
     return true;
 }
 /**
  * This function is specific to Wsse authentication and is only used to help this example
  *
  * For more information specific to the logic here, see
  * https://github.com/symfony/symfony-docs/pull/3134#issuecomment-27699129
  */
 protected function validateDigest($digest, $nonce, $created, $secret)
 {
     // Check created time is not in the future
     if (strtotime($created) > time()) {
         return false;
     }
     // Expire timestamp after 5 minutes
     if (time() - strtotime($created) > 300) {
         return false;
     }
     // Validate that the nonce is *not* used in the last 5 minutes
     // if it has, this could be a replay attack
     if (file_exists($this->cacheDir . '/' . $nonce) && file_get_contents($this->cacheDir . '/' . $nonce) + 300 > time()) {
         throw new NonceExpiredException('Previously used nonce detected');
     }
     // If cache directory does not exist we create it
     if (!is_dir($this->cacheDir)) {
         mkdir($this->cacheDir, 0777, true);
     }
     file_put_contents($this->cacheDir . '/' . $nonce, time());
     // Validate Secret
     //$expected = base64_encode(sha1(base64_decode($nonce).$created.$secret, true));
     $expected = base64_encode(self::createDigest(base64_decode($nonce), $created, $secret));
     return StringUtils::equals($expected, $digest);
 }
 /**
  * Determine if the session and input CSRF tokens match.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return bool
  */
 protected function tokensMatch($request)
 {
     $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');
     if (!$token && ($header = $request->header('X-XSRF-TOKEN'))) {
         $token = $this->encrypter->decrypt($header);
     }
     return StringUtils::equals($request->session()->token(), $token);
 }
 public function handle()
 {
     $token = app('request')->input('_token') ?: app('request')->header('X-CSRF-TOKEN');
     if (!$token && ($header = app('request')->header('X-XSRF-TOKEN'))) {
         $token = app('encrypter')->decrypt($header);
     }
     if (StringUtils::equals(app('request')->session()->token(), $token)) {
         return true;
     }
     return false;
 }
 /**
  * {@inheritdoc}
  */
 public function isCsrfTokenValid($intention, $token)
 {
     $expectedToken = $this->generateCsrfToken($intention);
     if (function_exists('hash_equals')) {
         return hash_equals($expectedToken, $token);
     }
     if (class_exists('Symfony\\Component\\Security\\Core\\Util\\StringUtils')) {
         return StringUtils::equals($expectedToken, $token);
     }
     return $token === $expectedToken;
 }
 /**
  * @Route("/sso_callback", name="sso_callback")
  */
 public function callbackAction(Request $request)
 {
     $state = $request->query->get('state', null);
     $code = $request->query->get('code', null);
     $session = $this->get('session');
     $nonce = $session->get('eve_sso_nonce');
     $session->remove('eve_sso_nonce');
     if (!StringUtils::equals($nonce, $state)) {
         $session->getFlashBag()->add('danger', 'Invalid CSRF Token - Refresh the page.');
         return $this->redirect($this->generateUrl('default'));
     }
     $auth_uri = "https://login.eveonline.com/oauth/token";
     $creds = [trim($this->container->getParameter('eve_client_id')), trim($this->container->getParameter('eve_client_secret'))];
     /*
      * LOOK OUT FOR THE SPACE
      */
     $auth_request = new \GuzzleHttp\Psr7\Request('POST', $auth_uri, ['Content-Type' => 'application/x-www-form-urlencoded', 'Authorization' => 'Basic ' . base64_encode(implode(":", $creds))], "grant_type=authorization_code&code={$code}");
     try {
         $response = $this->tryRequest($auth_request);
     } catch (\Exception $e) {
         $session->getFlashBag()->add('danger', 'There was a problem with your request<i>Try Again - if this persists - Submit an issue ticket using the link in the footer.</i></b>');
         return $this->redirect($this->generateUrl('eve.register'));
     }
     $response_content = json_decode($response->getBody()->getContents());
     $token = $response_content->access_token;
     $verify_uri = "https://login.eveonline.com/oauth/verify";
     $verfiyRequest = new \GuzzleHttp\Psr7\Request('GET', $verify_uri, ['Authorization' => 'Bearer ' . $token]);
     try {
         $charResponse = $this->tryRequest($verfiyRequest);
     } catch (\Exception $e) {
         $session->getFlashBag()->add('danger', 'There was a problem with your request<i>Try Again - if this persists - Submit an issue ticket using the link in the footer.</i></b>');
         return $this->redirect($this->generateUrl('eve.register'));
     }
     $decoded = json_decode($charResponse->getBody()->getContents());
     $cId = $decoded->CharacterID;
     $cName = $decoded->CharacterName;
     $exists = $this->getDoctrine()->getRepository('AppBundle:CorporationMember')->findOneBy(['character_id' => intval($cId)]);
     // character isnt in a corp that is registered by an admin
     if ($exists === null) {
         $session->getFlashBag()->add('warning', 'Sorry we do not support non-alpha tester registrations at this time.<br><b>COME BACK SOON</b> or make a request to add your corproation through a support ticket below.');
         $this->get('logger')->info(sprintf("ATTEMPTED REGISTRATION: char_id = %s char_name = %s", $cId, $cName));
         return $this->redirect($this->generateUrl('eve.register'));
     } else {
         $user = $this->getDoctrine()->getRepository('AppBundle:User')->findOneBy(['username' => strtolower(str_replace(' ', '_', trim($exists->getCharacterName())))]);
         if ($user instanceof User) {
             $session->getFlashBag()->add('warning', 'This character is already associated with a user. IF you have forgot your username or password please see the link below');
             return $this->redirect($this->generateUrl('eve.register'));
         }
         // all is well
         $session->set('registration_authorized', ['id' => $cId, 'name' => $cName]);
         return $this->redirect($this->generateUrl('fos_user_registration_register'));
     }
 }
Example #11
0
 public function filter(Route $route, Request $request)
 {
     $token = $request->input('_token');
     if (!$token) {
         $token = $request->headers->get('X-XSRF-TOKEN');
     }
     if (!$token) {
         $token = $request->cookie('XSRF-TOKEN');
     }
     if (!StringUtils::equals($this->session->token(), $token)) {
         throw new TokenMismatchException();
     }
     if ($this->regenerate) {
         $this->session->regenerateToken();
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function processAutoLoginCookie(array $cookieParts, Request $request)
 {
     if (count($cookieParts) !== 2) {
         throw new AuthenticationException('The cookie is invalid.');
     }
     list($series, $tokenValue) = $cookieParts;
     $persistentToken = $this->tokenProvider->loadTokenBySeries($series);
     if (!StringUtils::equals($persistentToken->getTokenValue(), $tokenValue)) {
         throw new CookieTheftException('This token was already used. The account is possibly compromised.');
     }
     if ($persistentToken->getLastUsed()->getTimestamp() + $this->options['lifetime'] < time()) {
         throw new AuthenticationException('The cookie has expired.');
     }
     $tokenValue = base64_encode($this->secureRandom->nextBytes(64));
     $this->tokenProvider->updateToken($series, $tokenValue, new \DateTime());
     $request->attributes->set(self::COOKIE_ATTR_NAME, new Cookie($this->options['name'], $this->encodeCookie(array($series, $tokenValue)), time() + $this->options['lifetime'], $this->options['path'], $this->options['domain'], $this->options['secure'], $this->options['httponly']));
     return $this->getUserProvider($persistentToken->getClass())->loadUserByUsername($persistentToken->getUsername());
 }
 /**
  * {@inheritdoc}
  */
 public function verify($url, $key, $signature = null)
 {
     if (strpos($url, 'sign=') !== false) {
         $params = [];
         parse_str(parse_url($url, PHP_URL_QUERY), $params);
         if (isset($params['sign'])) {
             if (empty($signature)) {
                 $signature = $params['sign'];
             }
             unset($params['sign']);
         }
         $url = http_build_url($url, ['query' => http_build_query($params)], HTTP_URL_STRIP_FRAGMENT | HTTP_URL_REPLACE);
     }
     if (empty($signature)) {
         throw new InvalidArgumentException('Signature argument not found.');
     }
     $expected = $this->sign($url, $key);
     return StringUtils::equals($expected, $signature);
 }
Example #14
0
 /**
  * @Route("/sso_callback", name="sso_callback")
  */
 public function callbackAction(Request $request)
 {
     $state = $request->query->get('state', null);
     $code = $request->query->get('code', null);
     $session = $this->get('session');
     $nonce = $session->get('eve_sso_nonce');
     $session->remove('eve_sso_nonce');
     if (!StringUtils::equals($nonce, $state)) {
         return $this->redirect($this->generateUrl('eve.register'));
     }
     $auth_request = $this->buildAuthRequest($code);
     try {
         $response = $this->tryRequest($auth_request);
         return $this->verifySSOResponse($response);
     } catch (\Exception $e) {
         $session->getFlashBag()->add('danger', 'There was a problem with your request<i>Try Again - if this persists - Submit an issue ticket using the link in the footer.</i></b>');
         return $this->redirect($this->generateUrl('eve.register'));
     }
 }
Example #15
0
 protected function validateDigest($digest, $nonce, $created, $secret)
 {
     //        if (strtotime($created) > time()) {
     //            return false;
     //        }
     //        if (time() - strtotime($created) > 300) {
     //            return false;
     //        }
     //        if (file_exists($this->cacheDir . '/' . $nonce) && file_get_contents($this->cacheDir . '/' . $nonce) + 300 > time()) {
     //            throw new NonceExpiredException('Previously used nonce detected');
     //        }
     //        if (!is_dir($this->cacheDir)) {
     //            mkdir($this->cacheDir, 0777, true);
     //        }
     //        file_put_contents($this->cacheDir . '/' . $nonce, time());
     //        $expected = base64_encode(sha1(base64_decode($nonce) . $created . $secret, true));
     //        $expected = base64_encode(sha256($created . $secret, true));
     $expected = $secret;
     return StringUtils::equals($expected, $digest);
 }
Example #16
0
 public function authenticate($email, $password)
 {
     /** @var MemberManager $mm */
     $mm = $this->container['member.manager'];
     /** @var Member $member */
     $member = $mm->findMemberByEmail($email);
     /** @var MessageDigestPasswordEncoder $encoder */
     $encoder = $this->container['security.encoder'];
     /** @var UserChecker $userChecker */
     $userChecker = $this->container['security.user_checker'];
     try {
         if ($member) {
             $userChecker->checkPreAuth($member);
             if ($encoder->isPasswordValid($member->getPassword(), $password, $member->getSalt())) {
                 $encodedPassword = $encoder->encodePassword($password, $member->getSalt());
                 $match = StringUtils::equals($member->getPassword(), $encodedPassword);
                 $userChecker->checkPostAuth($member);
                 if ($match) {
                     $authenticatedToken = new UsernamePasswordToken($member, $password, self::PROVIDER_KEY, $member->getRoles());
                     $this->container['security.token_storage']->setToken($authenticatedToken);
                 } else {
                     throw new AuthenticationCredentialsNotFoundException('Wrong email and password combination.', 401);
                 }
             }
         }
     } catch (AuthenticationException $failed) {
         $this->container->get('logger')->error(sprintf('Authentication failed for user "%s" (using password - "%s")', $email, !empty($password) ? 'yes' : 'no'), ['email' => $email, 'description' => $failed->getMessage()]);
         throw new $failed();
     }
     if (null === $this->container['member']) {
         if (empty($email) || empty($password)) {
             throw new AuthenticationCredentialsNotFoundException('Authentication credentials could not be found.', 400);
         }
         throw new AuthenticationCredentialsNotFoundException('Wrong email and password combination.', 401);
     }
     return $this->container['member'];
 }
 /**
  * Compares two passwords.
  *
  * This method implements a constant-time algorithm to compare passwords to
  * avoid (remote) timing attacks.
  *
  * @param string $password1 The first password
  * @param string $password2 The second password
  *
  * @return bool    true if the two passwords are the same, false otherwise
  */
 protected function comparePasswords($password1, $password2)
 {
     return StringUtils::equals($password1, $password2);
 }
Example #18
0
 /**
  * {@inheritDoc}
  */
 public function stringsAreEqual($s1, $s2)
 {
     return StringUtils::equals($s1, $s2);
 }
Example #19
0
 /**
  * Checks the request data / headers for a valid CSRF token.
  * Returns false if a valid token is not found. Override this
  * method to disable the check.
  * @return bool
  */
 protected function verifyCsrfToken()
 {
     if (!Config::get('cms.enableCsrfProtection')) {
         return true;
     }
     if (in_array(Request::method(), ['HEAD', 'GET', 'OPTIONS'])) {
         return true;
     }
     $token = Request::input('_token') ?: Request::header('X-CSRF-TOKEN');
     return \Symfony\Component\Security\Core\Util\StringUtils::equals(Session::getToken(), $token);
 }
Example #20
0
 /**
  * Determine if the session and input CSRF tokens match.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return bool
  */
 protected function tokensMatch($request)
 {
     $token = $request->session()->token();
     $header = $request->header('X-XSRF-TOKEN');
     return StringUtils::equals($token, $request->input('_token')) || $header && StringUtils::equals($token, $this->encrypter->decrypt($header));
 }
 /**
  * Handles digest authentication.
  *
  * @param GetResponseEvent $event A GetResponseEvent instance
  *
  * @throws AuthenticationServiceException
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!($header = $request->server->get('PHP_AUTH_DIGEST'))) {
         return;
     }
     $digestAuth = new DigestData($header);
     if (null !== ($token = $this->tokenStorage->getToken())) {
         if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && $token->getUsername() === $digestAuth->getUsername()) {
             return;
         }
     }
     if (null !== $this->logger) {
         $this->logger->debug('Digest Authorization header received from user agent.', array('header' => $header));
     }
     try {
         $digestAuth->validateAndDecode($this->authenticationEntryPoint->getKey(), $this->authenticationEntryPoint->getRealmName());
     } catch (BadCredentialsException $e) {
         $this->fail($event, $request, $e);
         return;
     }
     try {
         $user = $this->provider->loadUserByUsername($digestAuth->getUsername());
         if (null === $user) {
             throw new AuthenticationServiceException('Digest User provider returned null, which is an interface contract violation');
         }
         $serverDigestMd5 = $digestAuth->calculateServerDigest($user->getPassword(), $request->getMethod());
     } catch (UsernameNotFoundException $e) {
         $this->fail($event, $request, new BadCredentialsException(sprintf('Username %s not found.', $digestAuth->getUsername())));
         return;
     }
     if (!StringUtils::equals($serverDigestMd5, $digestAuth->getResponse())) {
         if (null !== $this->logger) {
             $this->logger->debug('Unexpected response from the DigestAuth received; is the header returning a clear text passwords?', array('expected' => $serverDigestMd5, 'received' => $digestAuth->getResponse()));
         }
         $this->fail($event, $request, new BadCredentialsException('Incorrect response'));
         return;
     }
     if ($digestAuth->isNonceExpired()) {
         $this->fail($event, $request, new NonceExpiredException('Nonce has expired/timed out.'));
         return;
     }
     if (null !== $this->logger) {
         $this->logger->info('Digest authentication successful.', array('username' => $digestAuth->getUsername(), 'received' => $digestAuth->getResponse()));
     }
     $this->tokenStorage->setToken(new UsernamePasswordToken($user, $user->getPassword(), $this->providerKey));
 }
Example #22
0
 /**
  * Find out whether the specified confirmation code is correct
  *
  * This method protects against timing attacks
  *
  * @return bool `true` for a correct e-mail verification code
  */
 public function isCorrectConfirmCode($code)
 {
     $this->lazyLoad();
     if ($this->confirmCode === null) {
         return false;
     }
     return StringUtils::equals($code, $this->confirmCode);
 }
 /**
  * Checks if the presented signature is valid or not according to token.
  *
  * @param BBUserToken $token
  * @param string      $signaturePresented signature we want to check if it's correct
  *
  * @return boolean true if signature is valid, else false
  */
 public function isApiSignatureValid(BBUserToken $token, $signaturePresented)
 {
     return StringUtils::equals($this->createSignature($token), $signaturePresented);
 }
<?php

use Egulias\EmailValidator\EmailValidator;
use PhpDraft\Domain\Models\PhpDraftResponse;
use Symfony\Component\Security\Core\Util\StringUtils;
if (!$app instanceof Silex\Application) {
    throw new Exception('Invalid application setup.');
}
//Factories
//Factories are services or classes that return a different instance each time its called.
$app['phpdraft.ResponseFactory'] = $app->factory(function () {
    return function ($success, $errors) {
        return new PhpDraftResponse($success, $errors);
    };
});
$app['phpdraft.EmailValidator'] = $app->factory(function () {
    return new EmailValidator();
});
$app['phpdraft.StringsEqual'] = $app->factory(function () {
    return function ($string1, $string2) {
        return StringUtils::equals($string1, $string2);
    };
});
Example #25
0
 /**
  * @dataProvider dataProviderFalse
  */
 public function testEqualsFalse($known, $user)
 {
     $this->assertFalse(StringUtils::equals($known, $user));
 }
 /**
  * @see StringUtils::equals
  */
 public function compareHashes($hash1, $hash2)
 {
     return StringUtils::equals($hash1, $hash2);
 }
Example #27
0
 /**
  * Determine if the MAC for the given payload is valid.
  *
  * @param  array  $payload
  * @return bool
  */
 protected function validMac(array $payload)
 {
     $bytes = with(new SecureRandom())->nextBytes(16);
     $calcMac = hash_hmac('sha256', $this->hash($payload['iv'], $payload['value']), $bytes, true);
     return StringUtils::equals(hash_hmac('sha256', $payload['mac'], $bytes, true), $calcMac);
 }
Example #28
0
 public function testEquals()
 {
     $this->assertTrue(StringUtils::equals('password', 'password'));
     $this->assertFalse(StringUtils::equals('password', 'foo'));
 }
Example #29
0
 protected function validMac(array $payload)
 {
     if (!function_exists('openssl_random_pseudo_bytes')) {
         throw new \RuntimeException('OpenSSL extension is required.');
     }
     $bytes = (new SecureRandom())->nextBytes(16);
     $calcMac = hash_hmac('sha256', $this->hash($payload['iv'], $payload['value']), $bytes, true);
     return StringUtils::equals(hash_hmac('sha256', $payload['mac'], $bytes, true), $calcMac);
 }
Example #30
0
|
| The "guest" filter is the counterpart of the authentication filters as
| it simply checks that the current user is not logged in. A redirect
| response will be issued if they are, which you may freely change.
|
*/
Route::filter('guest', function () {
    if (Auth::check()) {
        return Redirect::to('/');
    }
});
/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function () {
    if (!StringUtils::equals(Session::token(), Input::get('_token'))) {
        $user = Auth::user() ? Auth::user()->name : false;
        $browser = App::make('browser');
        Log::error("Token Mismatch (User): {$user}");
        Log::error("Token Mismatch (Request): " . Request::instance()->fullUrl());
        Log::error("Token Mismatch (Browser): " . $browser->getBrowser() . " " . $browser->getVersion());
        throw new Illuminate\Session\TokenMismatchException();
    }
});