/** * {@inheritdoc} */ protected function attemptAuthentication(Request $request) { if ($this->options['post_only'] && 'post' !== strtolower($request->getMethod())) { if (null !== $this->logger) { $this->logger->debug(sprintf('Authentication method not supported: %s.', $request->getMethod())); } return null; } if (null !== $this->csrfProvider) { $csrfToken = $request->get($this->options['csrf_parameter'], null, true); if (false === $this->csrfProvider->isCsrfTokenValid($this->options['intention'], $csrfToken)) { throw new InvalidCsrfTokenException('Invalid CSRF token.'); } } if (null !== $this->recaptcha && false === $this->recaptchaDisabled) { try { if (true !== $this->recaptcha->checkAnswer($request->server->get('REMOTE_ADDR'), $request->get($this->recaptcha->getChallengeField()), $request->get($this->recaptcha->getResponseField()))) { throw new InvalidRecaptchaException('Invalid captcha.'); } } catch (Exception $e) { throw new AuthenticationException('Invalid captcha.', null, null, $e); } } $username = trim($request->get($this->options['username_parameter'], null, true)); $password = $request->get($this->options['password_parameter'], null, true); $request->getSession()->set(SecurityContextInterface::LAST_USERNAME, $username); return $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $password, $this->providerKey)); }
/** * @param GetResponseEvent $event */ public function handle(GetResponseEvent $event) { $request = $event->getRequest(); if (!$request->headers->has('cookie')) { return; } if (strstr($request->headers->get('cookie'), 'SimpleSAMLAuthToken') === false) { return; } if (!$request->query->has('csrf-token')) { $this->logger->notice('Ssp Firewall: Auth Token cookie but no CSRF Token'); return; } $csrfToken = $request->query->getAlnum('csrf-token'); if (!$this->csrfProvider->isCsrfTokenValid('api', $csrfToken)) { $this->logger->notice('Ssp Firewall: Invalid CSRF token for api use: ' . $csrfToken); return; } try { $authToken = $this->authenticationManager->authenticate(new SspToken()); $this->securityContext->setToken($authToken); } catch (AuthenticationException $failed) { $this->logger->warning('Ssp Firewall: failed:' . $failed->getMessage()); $token = $this->securityContext->getToken(); if ($token instanceof SspToken) { $this->securityContext->setToken(null); } return; } }
/** * Renders the legacy website toolbar template. * * If the logged in user doesn't have the required permission, an empty response is returned * * @param mixed $locationId * @param Request $request * * @return Response */ public function websiteToolbarAction($locationId, Request $request) { $response = new Response(); if (isset($this->csrfProvider)) { $parameters['form_token'] = $this->csrfProvider->generateCsrfToken('legacy'); } if ($this->previewHelper->isPreviewActive()) { $template = 'design:parts/website_toolbar_versionview.tpl'; $previewedContent = $authValueObject = $this->previewHelper->getPreviewedContent(); $previewedVersionInfo = $previewedContent->versionInfo; $parameters = array('object' => $previewedContent, 'version' => $previewedVersionInfo, 'language' => $previewedVersionInfo->initialLanguageCode, 'is_creator' => $previewedVersionInfo->creatorId === $this->getRepository()->getCurrentUser()->id); } elseif ($locationId === null) { return $response; } else { $authValueObject = $this->loadContentByLocationId($locationId); $template = 'design:parts/website_toolbar.tpl'; $parameters = array('current_node_id' => $locationId, 'redirect_uri' => $request->attributes->get('semanticPathinfo')); } $authorizationAttribute = new AuthorizationAttribute('websitetoolbar', 'use', array('valueObject' => $authValueObject)); if (!$this->authChecker->isGranted($authorizationAttribute)) { return $response; } $response->setContent($this->legacyTemplateEngine->render($template, $parameters)); return $response; }
/** * {@inheritdoc} */ public function renderCsrfToken($intention) { if (null === $this->csrfProvider) { throw new \BadMethodCallException('CSRF token can only be generated if a CsrfProviderInterface is injected in the constructor.'); } return $this->csrfProvider->generateCsrfToken($intention); }
public function onBindClientData(DataEvent $event) { $form = $event->getForm(); $data = $event->getData(); if ((!$form->hasParent() || $form->getParent()->isRoot()) && !$this->csrfProvider->isCsrfTokenValid($this->intention, $data)) { $form->addError(new FormError('The CSRF token is invalid. Please try to resubmit the form')); // If the session timed out, the token is invalid now. // Regenerate the token so that a resubmission is possible. $event->setData($this->csrfProvider->generateCsrfToken($this->intention)); } }
public function loginAction() { $session = $this->request->getSession(); if ($this->request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) { $error = $this->request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR); } else { $error = $session->get(SecurityContextInterface::AUTHENTICATION_ERROR); $session->remove(SecurityContextInterface::AUTHENTICATION_ERROR); } $csrfToken = isset($this->csrfProvider) ? $this->csrfProvider->generateCsrfToken('authenticate') : null; return new Response($this->templateEngine->render($this->configResolver->getParameter('security.login_template'), array('last_username' => $session->get(SecurityContextInterface::LAST_USERNAME), 'error' => $error, 'csrf_token' => $csrfToken, 'layout' => $this->configResolver->getParameter('security.base_layout')))); }
public function onBindClientData(FilterDataEvent $event) { $form = $event->getForm(); $data = $event->getData(); if ($form->isRoot() && $form->hasChildren() && isset($data[$this->fieldName])) { if (!$this->csrfProvider->isCsrfTokenValid($this->intention, $data[$this->fieldName])) { $form->addError(new FormError('The CSRF token is invalid. Please try to resubmit the form')); } unset($data[$this->fieldName]); } $event->setData($data); }
public function preBind(FormEvent $event) { $form = $event->getForm(); $data = $event->getData(); if ($form->isRoot() && $form->getConfig()->getOption('compound')) { if (!isset($data[$this->fieldName]) || !$this->csrfProvider->isCsrfTokenValid($this->intention, $data[$this->fieldName])) { $form->addError(new FormError('The CSRF token is invalid. Please try to resubmit the form.')); } unset($data[$this->fieldName]); } $event->setData($data); }
/** * This method validates CSRF token if CSRF protection is enabled. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * * @throws \eZ\Publish\Core\Base\Exceptions\UnauthorizedException */ public function onKernelRequest(GetResponseEvent $event) { if (!$this->container->getParameter('form.type_extension.csrf.enabled')) { return; } // skip CSRF validation if no session is running if (!$event->getRequest()->getSession()->isStarted()) { return; } if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) { return; } if (!$this->isRestRequest($event->getRequest())) { return; } if (in_array($event->getRequest()->getMethod(), array('GET', 'HEAD'))) { return; } // TODO: add CSRF token to protect against force-login attacks if ($event->getRequest()->get("_route") == "ezpublish_rest_createSession") { return; } if (!$event->getRequest()->headers->has(self::CSRF_TOKEN_HEADER) || !$this->csrfProvider->isCsrfTokenValid($this->container->getParameter('ezpublish_rest.csrf_token_intention'), $event->getRequest()->headers->get(self::CSRF_TOKEN_HEADER))) { throw new UnauthorizedException("Missing or invalid CSRF token", $event->getRequest()->getMethod() . " " . $event->getRequest()->getPathInfo()); } // Dispatching event so that CSRF token intention can be injected into Legacy Stack /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher */ $eventDispatcher = $this->container->get("event_dispatcher"); $eventDispatcher->dispatch(RestEvents::REST_CSRF_TOKEN_VALIDATED); }
/** * @param GetResponseEvent $event * * @return bool */ protected function checkCsrfToken(Request $request) { if (!$request->headers->has(self::CSRF_TOKEN_HEADER)) { return false; } return $this->csrfProvider->isCsrfTokenValid($this->csrfTokenIntention, $request->headers->get(self::CSRF_TOKEN_HEADER)); }
/** * Renders the legacy website toolbar template. * * If the logged in user doesn't have the required permission, an empty response is returned * * @param mixed $locationId */ public function websiteToolbarAction($locationId) { $response = new Response(); // Happens in PreviewController. See EZP-22823. if ($locationId === null) { return $response; } $authorizationAttribute = new AuthorizationAttribute('websitetoolbar', 'use', array('valueObject' => $this->loadContentByLocationId($locationId))); if (!$this->securityContext->isGranted($authorizationAttribute)) { return $response; } $parameters = array('current_node_id' => $locationId); if (isset($this->csrfProvider)) { $parameters['form_token'] = $this->csrfProvider->generateCsrfToken('legacy'); } $response->setContent($this->legacyTemplateEngine->render('design:parts/website_toolbar.tpl', $parameters)); return $response; }
public function preSubmit(FormEvent $event) { $form = $event->getForm(); $data = $event->getData(); if ($form->isRoot() && $form->getConfig()->getOption('compound')) { if (!isset($data[$this->fieldName]) || !$this->csrfProvider->isCsrfTokenValid($this->intention, $data[$this->fieldName])) { $errorMessage = $this->errorMessage; if (null !== $this->translator) { $errorMessage = $this->translator->trans($errorMessage, array(), $this->translationDomain); } $form->addError(new FormError($errorMessage)); } if (is_array($data)) { unset($data[$this->fieldName]); } } $event->setData($data); }
/** * {@inheritdoc} */ protected function attemptAuthentication(Request $request) { $organization = $this->getOrganization($request->get($this->options['organization_parameter'], null, true)); if (null !== $this->csrfProvider) { $csrfToken = $request->get($this->options['csrf_parameter'], null, true); if (false === $this->csrfProvider->isCsrfTokenValid($this->options['intention'], $csrfToken)) { throw new InvalidCsrfTokenException('Invalid CSRF token.'); } } if ($this->options['post_only']) { $username = trim($request->request->get($this->options['username_parameter'], null, true)); $password = $request->request->get($this->options['password_parameter'], null, true); } else { $username = trim($request->get($this->options['username_parameter'], null, true)); $password = $request->get($this->options['password_parameter'], null, true); } $request->getSession()->set(SecurityContextInterface::LAST_USERNAME, $username); return $this->authenticationManager->authenticate(new UsernamePasswordOrganizationToken($username, $password, $this->providerKey, $organization, array())); }
/** * {@inheritdoc} */ protected function attemptAuthentication(Request $request) { if (null !== $this->csrfTokenManager) { $csrfToken = $request->get($this->options['csrf_parameter'], null, true); if (false === $this->csrfTokenManager->isTokenValid(new CsrfToken($this->options['intention'], $csrfToken))) { throw new InvalidCsrfTokenException('Invalid CSRF token.'); } } if ($this->options['post_only']) { $asn = trim($request->request->get($this->options['asn_parameter'], null, true)); $username = trim($request->request->get($this->options['username_parameter'], null, true)); $password = $request->request->get($this->options['password_parameter'], null, true); } else { $asn = trim($request->get($this->options['asn_parameter'], null, true)); $username = trim($request->get($this->options['username_parameter'], null, true)); $password = $request->get($this->options['password_parameter'], null, true); } $request->getSession()->set(Security::LAST_USERNAME, $username); $request->getSession()->set(self::LAST_ASN, $asn); return $this->authenticationManager->authenticate(new AsnUsernamePasswordToken($username, $password, $this->providerKey, array(), $asn)); }
/** * {@inheritdoc} */ public function isTokenValid(CsrfToken $token) { return $this->csrfProvider->isCsrfTokenValid($token->getId(), $token->getValue()); }
/** * {@inheritdoc} */ protected function setUp() { $this->container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface'); $this->request = new Request(); $this->pool = new Pool($this->container, 'title', 'logo.png'); $this->pool->setAdminServiceIds(array('foo.admin')); $this->request->attributes->set('_sonata_admin', 'foo.admin'); $this->admin = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface'); $this->parameters = array(); $this->template = ''; // php 5.3 BC $params =& $this->parameters; $template =& $this->template; $templating = $this->getMock('Symfony\\Bundle\\FrameworkBundle\\Templating\\DelegatingEngine', array(), array($this->container, array())); $templating->expects($this->any())->method('renderResponse')->will($this->returnCallback(function ($view, array $parameters = array(), Response $response = null) use(&$params, &$template) { $template = $view; if (null === $response) { $response = new Response(); } $params = $parameters; return $response; })); $this->session = new Session(new MockArraySessionStorage()); // php 5.3 BC $pool = $this->pool; $request = $this->request; $admin = $this->admin; $session = $this->session; $twig = $this->getMockBuilder('Twig_Environment')->disableOriginalConstructor()->getMock(); $twigRenderer = $this->getMock('Symfony\\Bridge\\Twig\\Form\\TwigRendererInterface'); $formExtension = new FormExtension($twigRenderer); $twig->expects($this->any())->method('getExtension')->will($this->returnCallback(function ($name) use($formExtension) { switch ($name) { case 'form': return $formExtension; } return; })); $exporter = $this->getMock('Sonata\\AdminBundle\\Export\\Exporter'); $exporter->expects($this->any())->method('getResponse')->will($this->returnValue(new StreamedResponse())); $this->auditManager = $this->getMockBuilder('Sonata\\AdminBundle\\Model\\AuditManager')->disableOriginalConstructor()->getMock(); $this->adminObjectAclManipulator = $this->getMockBuilder('Sonata\\AdminBundle\\Util\\AdminObjectAclManipulator')->disableOriginalConstructor()->getMock(); // php 5.3 BC $auditManager = $this->auditManager; $adminObjectAclManipulator = $this->adminObjectAclManipulator; $this->csrfProvider = $this->getMockBuilder('Symfony\\Component\\Form\\Extension\\Csrf\\CsrfProvider\\CsrfProviderInterface')->getMock(); $this->csrfProvider->expects($this->any())->method('generateCsrfToken')->will($this->returnCallback(function ($intention) { return 'csrf-token-123_' . $intention; })); $this->csrfProvider->expects($this->any())->method('isCsrfTokenValid')->will($this->returnCallback(function ($intention, $token) { if ($token == 'csrf-token-123_' . $intention) { return true; } return false; })); // php 5.3 BC $csrfProvider = $this->csrfProvider; $this->logger = $this->getMock('Psr\\Log\\LoggerInterface'); $logger = $this->logger; // php 5.3 BC $requestStack = null; if (Kernel::MINOR_VERSION > 3) { $requestStack = new \Symfony\Component\HttpFoundation\RequestStack(); $requestStack->push($request); } $this->container->expects($this->any())->method('get')->will($this->returnCallback(function ($id) use($pool, $request, $admin, $templating, $twig, $session, $exporter, $auditManager, $adminObjectAclManipulator, $requestStack, $csrfProvider, $logger) { switch ($id) { case 'sonata.admin.pool': return $pool; case 'request_stack': return $requestStack; case 'request': return $request; case 'foo.admin': return $admin; case 'templating': return $templating; case 'twig': return $twig; case 'session': return $session; case 'sonata.admin.exporter': return $exporter; case 'sonata.admin.audit.manager': return $auditManager; case 'sonata.admin.object.manipulator.acl.admin': return $adminObjectAclManipulator; case 'form.csrf_provider': return $csrfProvider; case 'logger': return $logger; } return; })); // php 5.3 $tthis = $this; $this->container->expects($this->any())->method('has')->will($this->returnCallback(function ($id) use($tthis) { if ($id == 'form.csrf_provider' && $tthis->getCsrfProvider() !== null) { return true; } if ($id == 'logger') { return true; } return false; })); $this->admin->expects($this->any())->method('getTemplate')->will($this->returnCallback(function ($name) { switch ($name) { case 'ajax': return 'SonataAdminBundle::ajax_layout.html.twig'; case 'layout': return 'SonataAdminBundle::standard_layout.html.twig'; case 'show': return 'SonataAdminBundle:CRUD:show.html.twig'; case 'show_compare': return 'SonataAdminBundle:CRUD:show_compare.html.twig'; case 'edit': return 'SonataAdminBundle:CRUD:edit.html.twig'; case 'dashboard': return 'SonataAdminBundle:Core:dashboard.html.twig'; case 'search': return 'SonataAdminBundle:Core:search.html.twig'; case 'list': return 'SonataAdminBundle:CRUD:list.html.twig'; case 'preview': return 'SonataAdminBundle:CRUD:preview.html.twig'; case 'history': return 'SonataAdminBundle:CRUD:history.html.twig'; case 'acl': return 'SonataAdminBundle:CRUD:acl.html.twig'; case 'delete': return 'SonataAdminBundle:CRUD:delete.html.twig'; case 'batch': return 'SonataAdminBundle:CRUD:list__batch.html.twig'; case 'batch_confirmation': return 'SonataAdminBundle:CRUD:batch_confirmation.html.twig'; } return; })); $this->admin->expects($this->any())->method('getIdParameter')->will($this->returnValue('id')); $this->admin->expects($this->any())->method('generateUrl')->will($this->returnCallback(function ($name, array $parameters = array(), $absolute = false) { $result = $name; if (!empty($parameters)) { $result .= '?' . http_build_query($parameters); } return $result; })); $this->admin->expects($this->any())->method('generateObjectUrl')->will($this->returnCallback(function ($name, $object, array $parameters = array(), $absolute = false) { $result = get_class($object) . '_' . $name; if (!empty($parameters)) { $result .= '?' . http_build_query($parameters); } return $result; })); $this->controller = new CRUDController(); $this->controller->setContainer($this->container); // Make some methods public to test them $testedMethods = array('renderJson', 'isXmlHttpRequest', 'configure', 'getBaseTemplate', 'redirectTo', 'addFlash'); foreach ($testedMethods as $testedMethod) { $method = new \ReflectionMethod('Sonata\\AdminBundle\\Controller\\CRUDController', $testedMethod); $method->setAccessible(true); $this->protectedTestedMethods[$testedMethod] = $method; } }
/** * @param string $intention * @param string $token * @return boolean */ public function isTokenValid($intention, $token) { return $this->csrfProvider->isCsrfTokenValid($intention, $token); }
private function checkCSRFToken() { if (!$this->csrfProvider->isCsrfTokenValid($this->getConfiguration()->getCSRFIntention(), $this->getRequest()->get('_token'))) { throw new \Exception('Bad CSRF Token'); } }
public function getCsrfToken($intention) { return $this->csrfProvider->generateCsrfToken($intention); }
public function validateRequest(Request $req) { if (!$this->csrf->isCsrfTokenValid(__CLASS__, $req->query->get(self::STATE_KEY, ''))) { throw new AuthenticationException("Invalid state"); } }