summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorFabien Potencier <fabien.potencier@gmail.com>2012-03-05 16:12:24 +0100
committerFabien Potencier <fabien.potencier@gmail.com>2012-03-05 16:12:24 +0100
commit7206c3d752b35788c82e9657aaffc18a1b24eb93 (patch)
tree55210a23cc89f9b88aa791f4741826ae09add409
parent49bdcee7c9c263229b92ae6a0864a010812274f5 (diff)
parentdc06bea6d334604e95f5f050cfe9866e5ed4cde7 (diff)
downloadsymfony-security-7206c3d752b35788c82e9657aaffc18a1b24eb93.zip
symfony-security-7206c3d752b35788c82e9657aaffc18a1b24eb93.tar.gz
symfony-security-7206c3d752b35788c82e9657aaffc18a1b24eb93.tar.bz2
merged branch jmikola/logout-csrf (PR #3007)
Commits ------- 49a8654 [Security] Use LogoutException for invalid CSRF token in LogoutListener a96105e [SecurityBundle] Use assertCount() in tests 4837407 [SecurityBundle] Fix execution of functional tests with different names 66722b3 [SecurityBundle] Templating helpers to generate logout URL's with CSRF tokens aaaa040 [Security] Allow LogoutListener to validate CSRF tokens b1f545b [Security] Refactor LogoutListener constructor to take options c48c775 [SecurityBundle] Add functional test for form login with CSRF token Discussion ---------- [Security] Implement support for CSRF tokens in logout URL's ``` Bug fix: no Feature addition: yes Backwards compatibility break: no Symfony2 tests pass: yes Fixes the following tickets: - Todo: - ``` [![Build Status](https://secure.travis-ci.org/jmikola/symfony.png?branch=logout-csrf)](http://travis-ci.org/jmikola/symfony) This derived from #3006 but properly targeting on the master branch. This exposes new configuration options to the logout listener to enable CSRF protection, as already exists for the form login listener. The individual commits and their extended messages should suffice for explaining the logical changes of the PR. In addition to changing LogoutListener, I also created a templating helper to generate logout URL's, which includes a CSRF token if necessary. This may or may not using routing, depending on how the listener is configured since both route names or hard-coded paths are valid options. Additionally, I added unit tests for LogoutListener and functional tests for both CSRF-enabled form logins and the new logout listener work. Kudo's to @henrikbjorn for taking the time to document CSRF validation for form login listeners (see [here](http://henrik.bjrnskov.dk/symfony2-cross-site-request-forgery/)). The [Logout CSRF Protection](http://www.yiiframework.com/wiki/190/logout-csrf-protection/) article on the Yii Framework wiki was also helpful in drafting this. --------------------------------------------------------------------------- by jmikola at 2011-12-31T07:50:31Z Odd that Travis CI reported a build failure for PHP 5.3.2, but both 5.3 and 5.4 passed: http://travis-ci.org/#!/jmikola/symfony/builds/463356 My local machine passes as well. --------------------------------------------------------------------------- by jmikola at 2012-02-06T20:05:30Z @schmittjoh: Please let me know your thoughts on the last commit. I think it would be overkill to add support for another handler service and/or error page just for logout exceptions. Perhaps as an alternative, we might just want to consider an invalid CSRF token on logout imply a false return value for `LogoutListener::requiresLogout()`. That would sacrifice the ability to handle the error separately (which a 403 response allows us), although we could still add logging (currently done in ExceptionListener). --------------------------------------------------------------------------- by jmikola at 2012-02-13T17:41:33Z @schmittjoh: ping --------------------------------------------------------------------------- by fabpot at 2012-02-14T23:36:22Z @jmikola: Instead of merging symfony/master, can you rebase? --------------------------------------------------------------------------- by jmikola at 2012-02-15T00:00:49Z Will do. --------------------------------------------------------------------------- by jmikola at 2012-02-15T00:05:48Z ``` [avocado: symfony] logout-csrf (+9/-216) $ git rebase master First, rewinding head to replay your work on top of it... Applying: [SecurityBundle] Add functional test for form login with CSRF token Applying: [Security] Refactor LogoutListener constructor to take options Applying: [Security] Allow LogoutListener to validate CSRF tokens Applying: [SecurityBundle] Templating helpers to generate logout URL's with CSRF tokens Applying: [SecurityBundle] Fix execution of functional tests with different names Applying: [SecurityBundle] Use assertCount() in tests Using index info to reconstruct a base tree... Falling back to patching base and 3-way merge... Applying: [Security] Use LogoutException for invalid CSRF token in LogoutListener [avocado: symfony] logout-csrf (+7) $ git st # On branch logout-csrf # Your branch and 'origin/logout-csrf' have diverged, # and have 223 and 9 different commit(s) each, respectively. # nothing to commit (working directory clean) [avocado: symfony] logout-csrf (+7) $ ``` After rebasing, my merge commits disappeared. Is this normal? --------------------------------------------------------------------------- by stof at 2012-02-15T00:15:07Z Are you sure they disappeared ? Diverging from the remote branch is logical (you rewrote the history and so changed the commit id) but are you sure it does not have the commits on top of master ? Try ``git log master..logout-scrf`` If your commut are there, you simply need to force the push for the logout-csrf branch (take care to push only this branch during the force push to avoid messing all others as git won't warn you when asking to force) --------------------------------------------------------------------------- by stof at 2012-02-15T00:17:09Z ah sorry, you talked only about the merge commit. Yeah it is normal. When reapplying your commits on top of master, the merge commit are not kept as you are reapplying the changes linearly on top of the other branch (and deleting the merge commit was the reason why @fabpot asked you to rebase instead of merging btw) --------------------------------------------------------------------------- by jmikola at 2012-02-15T00:18:00Z The merge commits are not present in `git log master..logout-csrf`. Perhaps it used those merge commits when rebasing, as there were definitely conflicts resolved when I originally merged in symfony/master (@fabpot had made his own changes to LogoutListener). I'll force-push the changes to my PR brange. IIRC, GitHub is smart enough to preserve inline diff comments, provided they were made through the PR and not on the original commits. --------------------------------------------------------------------------- by jmikola at 2012-02-15T00:19:38Z That worked well. In the future, I think I'll stick to merging upstream in and then rebasing afterwards. Resolving conflicts is much easier during a merge than interactive rebase. --------------------------------------------------------------------------- by jmikola at 2012-02-23T18:46:13Z @fabpot @schmittjoh: Is there anything else I can do for this PR? I believe the exception was the only outstanding question (see: [this comment](https://github.com/symfony/symfony/pull/3007#issuecomment-3835716)).
-rw-r--r--Core/Exception/LogoutException.php25
-rw-r--r--Http/Firewall/ExceptionListener.php9
-rw-r--r--Http/Firewall/LogoutListener.php49
3 files changed, 68 insertions, 15 deletions
diff --git a/Core/Exception/LogoutException.php b/Core/Exception/LogoutException.php
new file mode 100644
index 0000000..2bb954f
--- /dev/null
+++ b/Core/Exception/LogoutException.php
@@ -0,0 +1,25 @@
+<?php
+
+/*
+ * This file is part of the Symfony package.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Symfony\Component\Security\Core\Exception;
+
+/**
+ * LogoutException is thrown when the account cannot be logged out.
+ *
+ * @author Jeremy Mikola <jmikola@gmail.com>
+ */
+class LogoutException extends \RuntimeException
+{
+ public function __construct($message = 'Logout Exception', \Exception $previous = null)
+ {
+ parent::__construct($message, 403, $previous);
+ }
+}
diff --git a/Http/Firewall/ExceptionListener.php b/Http/Firewall/ExceptionListener.php
index 674c648..0996ab2 100644
--- a/Http/Firewall/ExceptionListener.php
+++ b/Http/Firewall/ExceptionListener.php
@@ -20,6 +20,7 @@ use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;
+use Symfony\Component\Security\Core\Exception\LogoutException;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
@@ -140,6 +141,14 @@ class ExceptionListener
return;
}
}
+ } elseif ($exception instanceof LogoutException) {
+ if (null !== $this->logger) {
+ $this->logger->info(sprintf('Logout exception occurred; wrapping with AccessDeniedHttpException (%s)', $exception->getMessage()));
+ }
+
+ $event->setException(new AccessDeniedHttpException($exception->getMessage(), $exception));
+
+ return;
} else {
return;
}
diff --git a/Http/Firewall/LogoutListener.php b/Http/Firewall/LogoutListener.php
index bb90b6a..59172dc 100644
--- a/Http/Firewall/LogoutListener.php
+++ b/Http/Firewall/LogoutListener.php
@@ -11,14 +11,15 @@
namespace Symfony\Component\Security\Http\Firewall;
-use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
-
-use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface;
-use Symfony\Component\Security\Core\SecurityContextInterface;
-use Symfony\Component\Security\Http\HttpUtils;
+use Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
+use Symfony\Component\Security\Core\SecurityContextInterface;
+use Symfony\Component\Security\Core\Exception\LogoutException;
+use Symfony\Component\Security\Http\HttpUtils;
+use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface;
+use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
/**
* LogoutListener logout users.
@@ -28,28 +29,33 @@ use Symfony\Component\HttpKernel\Event\GetResponseEvent;
class LogoutListener implements ListenerInterface
{
private $securityContext;
- private $logoutPath;
- private $targetUrl;
+ private $options;
private $handlers;
private $successHandler;
private $httpUtils;
+ private $csrfProvider;
/**
* Constructor
*
* @param SecurityContextInterface $securityContext
* @param HttpUtils $httpUtils An HttpUtilsInterface instance
- * @param string $logoutPath The path that starts the logout process
- * @param string $targetUrl The URL to redirect to after logout
- * @param LogoutSuccessHandlerInterface $successHandler
+ * @param array $options An array of options to process a logout attempt
+ * @param LogoutSuccessHandlerInterface $successHandler A LogoutSuccessHandlerInterface instance
+ * @param CsrfProviderInterface $csrfProvider A CsrfProviderInterface instance
*/
- public function __construct(SecurityContextInterface $securityContext, HttpUtils $httpUtils, $logoutPath, $targetUrl = '/', LogoutSuccessHandlerInterface $successHandler = null)
+ public function __construct(SecurityContextInterface $securityContext, HttpUtils $httpUtils, array $options = array(), LogoutSuccessHandlerInterface $successHandler = null, CsrfProviderInterface $csrfProvider = null)
{
$this->securityContext = $securityContext;
$this->httpUtils = $httpUtils;
- $this->logoutPath = $logoutPath;
- $this->targetUrl = $targetUrl;
+ $this->options = array_merge(array(
+ 'csrf_parameter' => '_csrf_token',
+ 'intention' => 'logout',
+ 'logout_path' => '/logout',
+ 'target_url' => '/',
+ ), $options);
$this->successHandler = $successHandler;
+ $this->csrfProvider = $csrfProvider;
$this->handlers = array();
}
@@ -66,7 +72,12 @@ class LogoutListener implements ListenerInterface
/**
* Performs the logout if requested
*
+ * If a CsrfProviderInterface instance is available, it will be used to
+ * validate the request.
+ *
* @param GetResponseEvent $event A GetResponseEvent instance
+ * @throws InvalidCsrfTokenException if the CSRF token is invalid
+ * @throws RuntimeException if the LogoutSuccessHandlerInterface instance does not return a response
*/
public function handle(GetResponseEvent $event)
{
@@ -76,6 +87,14 @@ class LogoutListener implements ListenerInterface
return;
}
+ if (null !== $this->csrfProvider) {
+ $csrfToken = $request->get($this->options['csrf_parameter'], null, true);
+
+ if (false === $this->csrfProvider->isCsrfTokenValid($this->options['intention'], $csrfToken)) {
+ throw new LogoutException('Invalid CSRF token.');
+ }
+ }
+
if (null !== $this->successHandler) {
$response = $this->successHandler->onLogoutSuccess($request);
@@ -83,7 +102,7 @@ class LogoutListener implements ListenerInterface
throw new \RuntimeException('Logout Success Handler did not return a Response.');
}
} else {
- $response = $this->httpUtils->createRedirectResponse($request, $this->targetUrl);
+ $response = $this->httpUtils->createRedirectResponse($request, $this->options['target_url']);
}
// handle multiple logout attempts gracefully
@@ -111,6 +130,6 @@ class LogoutListener implements ListenerInterface
*/
protected function requiresLogout(Request $request)
{
- return $this->httpUtils->checkRequestPath($request, $this->logoutPath);
+ return $this->httpUtils->checkRequestPath($request, $this->options['logout_path']);
}
}