implements security on recovering password and redis connector

This commit is contained in:
Julien Fastré 2018-08-17 17:54:17 +02:00
parent 35683a7289
commit 480655f31b
12 changed files with 630 additions and 15 deletions

View File

@ -16,6 +16,9 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Chill\MainBundle\Security\PasswordRecover\RecoverPasswordHelper;
use Symfony\Component\HttpFoundation\Response;
use Chill\MainBundle\Security\PasswordRecover\TokenManager;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Chill\MainBundle\Security\PasswordRecover\PasswordRecoverEvent;
use Chill\MainBundle\Security\PasswordRecover\PasswordRecoverVoter;
class PasswordController extends Controller
{
@ -49,18 +52,26 @@ class PasswordController extends Controller
*/
protected $tokenManager;
/**
*
* @var EventDispatcherInterface
*/
protected $eventDispatcher;
public function __construct(
LoggerInterface $chillLogger,
UserPasswordEncoderInterface $passwordEncoder,
RecoverPasswordHelper $recoverPasswordHelper,
TokenManager $tokenManager,
TranslatorInterface $translator
TranslatorInterface $translator,
EventDispatcherInterface $eventDispatcher
) {
$this->chillLogger = $chillLogger;
$this->passwordEncoder = $passwordEncoder;
$this->translator = $translator;
$this->tokenManager = $tokenManager;
$this->recoverPasswordHelper = $recoverPasswordHelper;
$this->eventDispatcher = $eventDispatcher;
}
/**
@ -132,6 +143,12 @@ class PasswordController extends Controller
public function recoverAction(Request $request)
{
if (FALSE === $this->isGranted(PasswordRecoverVoter::ASK_TOKEN)) {
return (new Response($this->translator->trans("You are not allowed "
. "to try to recover password, due to mitigating possible "
. "attack. Try to contact your system administrator"), Response::HTTP_FORBIDDEN));
}
$query = $request->query;
$username = $query->get(TokenManager::USERNAME_CANONICAL);
$hash = $query->getAlnum(TokenManager::HASH);
@ -141,10 +158,16 @@ class PasswordController extends Controller
->findOneByUsernameCanonical($username);
if (NULL === $user) {
$this->eventDispatcher->dispatch(PasswordRecoverEvent::INVALID_TOKEN,
new PasswordRecoverEvent($token, null, $request->getClientIp()));
throw $this->createNotFoundException(sprintf('User %s not found', $username));
}
if (TRUE !== $this->tokenManager->verify($hash, $token, $user, $timestamp)) {
$this->eventDispatcher->dispatch(PasswordRecoverEvent::INVALID_TOKEN,
new PasswordRecoverEvent($token, $user, $request->getClientIp()));
return new Response("Invalid token", Response::HTTP_FORBIDDEN);
}
@ -184,6 +207,12 @@ class PasswordController extends Controller
public function requestRecoverAction(Request $request)
{
if (FALSE === $this->isGranted(PasswordRecoverVoter::ASK_TOKEN)) {
return (new Response($this->translator->trans("You are not allowed "
. "to try to recover password, due to mitigating possible "
. "attack. Try to contact your system administrator"), Response::HTTP_FORBIDDEN));
}
$form = $this->requestRecoverForm();
$form->handleRequest($request);
@ -205,6 +234,12 @@ class PasswordController extends Controller
$this->addFlash('error', $this->translator->trans('This account does not have an email address. '
. 'Please ask your administrator to renew your password.'));
} else {
if (FALSE === $this->isGranted(PasswordRecoverVoter::ASK_TOKEN, $user)) {
return (new Response($this->translator->trans("You are not allowed "
. "to try to recover password, due to mitigating possible "
. "attack. Try to contact your system administrator"), Response::HTTP_FORBIDDEN));
}
$this->recoverPasswordHelper->sendRecoverEmail($user,
(new \DateTimeImmutable('now'))->add(new \DateInterval('PT30M')));
@ -218,8 +253,18 @@ class PasswordController extends Controller
)
);
$this->eventDispatcher->dispatch(
PasswordRecoverEvent::ASK_TOKEN_SUCCESS,
new PasswordRecoverEvent(null, $user, $request->getClientIp())
);
return $this->redirectToRoute('password_request_recover_confirm');
}
} elseif ($form->isSubmitted() && FALSE === $form->isValid()) {
$this->eventDispatcher->dispatch(
PasswordRecoverEvent::ASK_TOKEN_INVALID_FORM,
new PasswordRecoverEvent(null, null, $request->getClientIp())
);
}
return $this->render('@ChillMain/Password/request_recover_password.html.twig', [

View File

@ -82,6 +82,9 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
$container->setParameter('chill_main.notifications',
$config['notifications']);
$container->setParameter('chill_main.redis',
$config['redis']);
// add the key 'widget' without the key 'enable'
$container->setParameter('chill_main.widgets',
isset($config['widgets']['homepage']) ?
@ -104,6 +107,7 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
$loader->load('services/menu.yml');
$loader->load('services/security.yml');
$loader->load('services/notification.yml');
$loader->load('services/redis.yml');
}
public function getConfiguration(array $config, ContainerBuilder $container)

View File

@ -85,6 +85,19 @@ class Configuration implements ConfigurationInterface
->end()
->end()
->end() // end of notifications
->arrayNode('redis')
->children()
->scalarNode('host')
->cannotBeEmpty()
->end()
->scalarNode('port')
->defaultValue(6379)
->end()
->scalarNode('timeout')
->defaultValue(1)
->end()
->end()
->end()
->arrayNode('widgets')
->canBeEnabled()
->canBeUnset()

26
Redis/ChillRedis.php Normal file
View File

@ -0,0 +1,26 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Redis;
/**
* Redis client configured by chill main
*
*/
class ChillRedis extends \Redis
{
}

View File

@ -0,0 +1,78 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Redis;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class RedisConnectionFactory implements EventSubscriberInterface
{
protected $host;
protected $port;
protected $timeout;
/**
*
* @var Redis
*/
protected $redis;
public function __construct($parameters)
{
$this->host = $parameters['host'];
$this->port = $parameters['port'];
$this->timeout = $parameters['timeout'];
}
public static function getSubscribedEvents(): array
{
return [
'kernel.finish_request' => [
[ 'onKernelFinishRequest' ]
]
];
}
public function create()
{
$redis = $this->redis = new ChillRedis();
$result = $redis->connect($this->host, $this->port, $this->timeout);
if (FALSE === $result) {
throw new \RuntimeException("Could not connect to redis instance");
}
return $redis;
}
public function onKernelFinishRequest()
{
if ($this->redis !== null) {
$this->redis->close();
}
}
}

View File

@ -0,0 +1,10 @@
services:
Chill\MainBundle\Redis\RedisConnectionFactory:
arguments:
$parameters: "%chill_main.redis%"
tags:
- { name: kernel.event_subcriber }
Chill\MainBundle\Redis\ChillRedis:
factory: 'Chill\MainBundle\Redis\RedisConnectionFactory:create'

View File

@ -31,4 +31,21 @@ services:
$tokenManager: '@Chill\MainBundle\Security\PasswordRecover\TokenManager'
$urlGenerator: '@Symfony\Component\Routing\Generator\UrlGeneratorInterface'
$mailer: '@Chill\MainBundle\Notification\Mailer'
Chill\MainBundle\Security\PasswordRecover\PasswordRecoverEventSubscriber:
arguments:
$locker: '@Chill\MainBundle\Security\PasswordRecover\PasswordRecoverLocker'
tags:
- { name: kernel.event_subscriber }
Chill\MainBundle\Security\PasswordRecover\PasswordRecoverLocker:
arguments:
$chillRedis: '@Chill\MainBundle\Redis\ChillRedis'
$logger: '@Psr\Log\LoggerInterface'
Chill\MainBundle\Security\PasswordRecover\PasswordRecoverVoter:
arguments:
$locker: '@Chill\MainBundle\Security\PasswordRecover\PasswordRecoverLocker'
$requestStack: '@Symfony\Component\HttpFoundation\RequestStack'
tags:
- { name: security.voter }

View File

@ -9,4 +9,7 @@ The password must be greater than {{ limit }} characters: "[1,Inf] Le mot de pas
A permission is already present for the same role and scope: Une permission est déjà présente pour le même rôle et cercle.
#UserCircleConsistency
"{{ username }} is not allowed to see entities published in this circle": "{{ username }} n'est pas autorisé à voir l'élément publié dans ce cercle."
"{{ username }} is not allowed to see entities published in this circle": "{{ username }} n'est pas autorisé à voir l'élément publié dans ce cercle."
#password request
This username or email does not exists: Cet utilisateur ou email n'est pas présent dans la base de donnée

View File

@ -0,0 +1,118 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Security\PasswordRecover;
use Chill\MainBundle\Entity\User;
use Symfony\Component\EventDispatcher\Event;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class PasswordRecoverEvent extends Event
{
/**
*
* @var User
*/
protected $user;
/**
*
* @var string
*/
protected $token;
/**
*
* @var string
*/
protected $ip;
/**
*
* @var boolean
*/
protected $safelyGenerated;
const ASK_TOKEN_INVALID_FORM = 'chill_main.ask_token_invalid_form';
const INVALID_TOKEN = 'chill_main.password_recover_invalid_token';
const ASK_TOKEN_SUCCESS = 'chill_main.ask_token_success';
/**
*
* @param type $token
* @param User $user
* @param type $ip
* @param bool $safelyGenerated true if generated safely (from console command, etc.)
*/
public function __construct($token = null, User $user = null, $ip = null, bool $safelyGenerated = false)
{
$this->user = $user;
$this->token = $token;
$this->ip = $ip;
$this->safelyGenerated = $safelyGenerated;
}
/**
*
* @return User|null
*/
public function getUser()
{
return $this->user;
}
/**
*
* @return string
*/
public function getToken()
{
return $this->token;
}
public function getIp()
{
return $this->ip;
}
/**
*
* @return boolean
*/
public function hasIp(): bool
{
return !empty($this->ip);
}
/**
*
* @return boolean
*/
public function hasUser(): bool
{
return $this->user instanceof User;
}
public function isSafelyGenerated(): bool
{
return $this->safelyGenerated;
}
}

View File

@ -0,0 +1,83 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Security\PasswordRecover;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class PasswordRecoverEventSubscriber implements EventSubscriberInterface
{
/**
*
* @var PasswordRecoverLocker
*/
protected $locker;
public function __construct(PasswordRecoverLocker $locker)
{
$this->locker = $locker;
}
public static function getSubscribedEvents(): array
{
return [
PasswordRecoverEvent::INVALID_TOKEN => [
[ 'onInvalidToken' ]
],
PasswordRecoverEvent::ASK_TOKEN_INVALID_FORM => [
[ 'onAskTokenInvalidForm' ]
],
PasswordRecoverEvent::ASK_TOKEN_SUCCESS => [
[ 'onAskTokenSuccess']
]
];
}
public function onInvalidToken(PasswordRecoverEvent $event)
{
// set global lock
$this->locker->createLock('invalid_token_global', null);
// set ip lock
if ($event->hasIp()) {
$this->locker->createLock('invalid_token_by_ip', $event->getIp());
}
}
public function onAskTokenInvalidForm(PasswordRecoverEvent $event)
{
// set global lock
$this->locker->createLock('ask_token_invalid_form_global', null);
// set ip lock
if ($event->hasIp()) {
$this->locker->createLock('ask_token_invalid_form_by_ip', $event->getIp());
}
}
public function onAskTokenSuccess(PasswordRecoverEvent $event)
{
$this->locker->createLock('ask_token_success_by_user', $event->getUser());
}
}

View File

@ -0,0 +1,170 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Security\PasswordRecover;
use Chill\MainBundle\Redis\ChillRedis;
use Psr\Log\LoggerInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class PasswordRecoverLocker
{
/**
* The maximum of invalid token globally (across all ip)
*/
const MAX_INVALID_TOKEN_GLOBAL = 50;
/**
* The maximum of invalid token by ip
*/
const MAX_INVALID_TOKEN_BY_IP = 10;
/**
* TTL to keep invalid token recorded
*/
const INVALID_TOKEN_TTL = 3600;
const MAX_ASK_TOKEN_INVALID_FORM_GLOBAL = 50;
const MAX_ASK_TOKEN_INVALID_FORM_BY_IP = 10;
const MAX_ASK_TOKEN_BY_USER = 10;
const ASK_TOKEN_INVALID_FORM_TTL = 3600;
/**
*
* @var ChillRedis
*/
protected $chillRedis;
/**
*
* @var LoggerInterface
*/
protected $logger;
public function __construct(ChillRedis $chillRedis, LoggerInterface $logger)
{
$this->chillRedis = $chillRedis;
$this->logger = $logger;
}
public function createLock($usage, $discriminator = null)
{
$max = $this->getMax($usage);
$ttl = $this->getTtl($usage);
for ($i = 0; $i < $max; $i++) {
$key = self::generateLockKey($usage, $i, $discriminator);
if (0 === $this->chillRedis->exists($key)) {
$this->chillRedis->set($key, 1);
$this->chillRedis->setTimeout($key, $ttl);
break;
}
}
}
public function isLocked($usage, $discriminator = null)
{
$max = $this->getMax($usage);
for ($i = 0; $i < $max; $i++) {
$key = self::generateLockKey($usage, $i, $discriminator);
if ($this->chillRedis->exists($key) === 0) {
return false;
}
}
$this->logger->warning("locking reaching for password recovery", [
'usage' => $usage,
'discriminator' => $discriminator
]);
return true;
}
public function getMax($usage)
{
switch ($usage) {
case 'invalid_token_global':
return self::MAX_INVALID_TOKEN_GLOBAL;
case 'invalid_token_by_ip':
return self::MAX_INVALID_TOKEN_BY_IP;
case 'ask_token_invalid_form_global':
return self::MAX_ASK_TOKEN_INVALID_FORM_GLOBAL;
case 'ask_token_invalid_form_by_ip':
return self::MAX_ASK_TOKEN_INVALID_FORM_BY_IP;
case 'ask_token_success_by_user':
return self::MAX_ASK_TOKEN_BY_USER;
default:
throw new \UnexpectedValueException("this usage '$usage' is not yet implemented");
}
}
public function getTtl($usage)
{
switch ($usage) {
case 'invalid_token_global':
case 'invalid_token_by_ip':
return self::INVALID_TOKEN_TTL;
case 'ask_token_invalid_form_global':
case 'ask_token_invalid_form_by_ip':
return self::ASK_TOKEN_INVALID_FORM_TTL;
case 'ask_token_success_by_user':
return self::ASK_TOKEN_INVALID_FORM_TTL * 24;
default:
throw new \UnexpectedValueException("this usage '$usage' is not yet implemented");
}
}
/**
*
* @param string $usage 'invalid_token_global' or ...
* @param int $number
*/
public static function generateLockKey($usage, int $number, $discriminator = null)
{
switch($usage) {
case "invalid_token_global":
return sprintf('invalid_token_global_%d', $number);
case "invalid_token_by_ip":
return sprintf('invalid_token_ip_%s_%d', $discriminator, $number);
case "ask_token_invalid_form_global":
return sprintf('ask_token_invalid_form_global_%d', $number);
case "ask_token_invalid_form_by_ip":
return sprintf('ask_token_invalid_form_by_ip_%s_%d', $discriminator, $number);
case 'ask_token_success_by_user':
return sprintf('ask_token_success_by_user_%s_%d', $discriminator->getId(), $number);
default:
throw new \LogicException("this usage is not implemented");
}
}
}

View File

@ -20,6 +20,7 @@ namespace Chill\MainBundle\Security\PasswordRecover;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Chill\MainBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
*
@ -28,27 +29,74 @@ use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
*/
class PasswordRecoverVoter extends Voter
{
const CHANGE_PASSWORD = 'CHILL_CHANGE_PASSWORD';
const TRY_TOKEN = 'CHILL_PASSWORD_TRY_TOKEN';
const ASK_TOKEN = 'CHILL_PASSWORD_ASK_TOKEN';
protected $supported = [
self::TRY_TOKEN,
self::ASK_TOKEN
];
/**
*
* @var PasswordRecoverLocker
*/
protected $locker;
/**
*
* @var RequestStack
*/
protected $requestStack;
public function __construct(PasswordRecoverLocker $locker, RequestStack $requestStack)
{
$this->locker = $locker;
$this->requestStack = $requestStack;
}
protected function supports($attribute, $subject): bool
{
if ($attribute !== self::CHANGE_PASSWORD) {
if (!in_array($attribute, $this->supported)) {
return false;
}
if (!$subject['user'] instanceof User) {
throw new \UnexpectedValueException("The subject must contains an "
. "".User::class." under the 'user' key");
}
if (empty($subject['token'])) {
throw new \UnexpectedValueException("The subject must contains a "
. "token key");
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
switch ($attribute) {
case self::TRY_TOKEN:
if (TRUE === $this->locker->isLocked('invalid_token_global')) {
return false;
}
$ip = $this->requestStack->getCurrentRequest()->getClientIp();
if (TRUE === $this->locker->isLocked('invalid_token_by_ip', $ip)) {
return false;
}
return true;
case self::ASK_TOKEN:
if (TRUE === $this->locker->isLocked('ask_token_invalid_form_global')) {
return false;
}
$ip = $this->requestStack->getCurrentRequest()->getClientIp();
if (TRUE === $this->locker->isLocked('ask_token_invalid_form_by_ip', $ip)) {
return false;
}
if ($subject instanceof User) {
if (TRUE === $this->locker->isLocked('ask_token_success_by_user', $subject)) {
return false;
}
}
return true;
}
}
}