Example #1
0
 /**
  * Renders hidden form fields for referrer information about
  * the current request.
  *
  * @return string Hidden fields with referrer information
  */
 protected function renderHiddenReferrerFields()
 {
     $tagBuilder = new TagBuilder('input');
     $tagBuilder->addAttribute('type', 'hidden');
     $tagBuilder->addAttribute('name', $this->prefixFieldName('__state'));
     $serializedFormState = base64_encode(serialize($this->arguments['object']->getFormState()));
     $tagBuilder->addAttribute('value', $this->hashService->appendHmac($serializedFormState));
     return $tagBuilder->render();
 }
 /**
  * Extracts the WidgetContext from the given $httpRequest.
  * If the request contains an argument "__widgetId" the context is fetched from the session (AjaxWidgetContextHolder).
  * Otherwise the argument "__widgetContext" is expected to contain the serialized WidgetContext (protected by a HMAC suffix)
  *
  * @param Request $httpRequest
  * @return WidgetContext
  */
 protected function extractWidgetContext(Request $httpRequest)
 {
     if ($httpRequest->hasArgument('__widgetId')) {
         return $this->ajaxWidgetContextHolder->get($httpRequest->getArgument('__widgetId'));
     } elseif ($httpRequest->hasArgument('__widgetContext')) {
         $serializedWidgetContextWithHmac = $httpRequest->getArgument('__widgetContext');
         $serializedWidgetContext = $this->hashService->validateAndStripHmac($serializedWidgetContextWithHmac);
         return unserialize(base64_decode($serializedWidgetContext));
     }
     return null;
 }
 /**
  * Creates a new account and sets the given password and roles
  *
  * @param string $identifier Identifier of the account, must be unique
  * @param string $password The clear text password
  * @param array $roleIdentifiers Optionally an array of role identifiers to assign to the new account
  * @param string $authenticationProviderName Optional name of the authentication provider the account is affiliated with
  * @param string $passwordHashingStrategy Optional password hashing strategy to use for the password
  * @return Account A new account, not yet added to the account repository
  */
 public function createAccountWithPassword($identifier, $password, $roleIdentifiers = [], $authenticationProviderName = 'DefaultProvider', $passwordHashingStrategy = 'default')
 {
     $account = new Account();
     $account->setAccountIdentifier($identifier);
     $account->setCredentialsSource($this->hashService->hashPassword($password, $passwordHashingStrategy));
     $account->setAuthenticationProviderName($authenticationProviderName);
     $roles = [];
     foreach ($roleIdentifiers as $roleIdentifier) {
         $roles[] = $this->policyService->getRole($roleIdentifier);
     }
     $account->setRoles($roles);
     return $account;
 }
 /**
  * Checks the given token for validity and sets the token authentication status
  * accordingly (success, wrong credentials or no credentials given).
  *
  * @param TokenInterface $authenticationToken The token to be authenticated
  * @return void
  * @throws UnsupportedAuthenticationTokenException
  */
 public function authenticate(TokenInterface $authenticationToken)
 {
     if (!$authenticationToken instanceof UsernamePassword) {
         throw new UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1217339840);
     }
     /** @var $account Account */
     $account = null;
     $credentials = $authenticationToken->getCredentials();
     if ($authenticationToken->getAuthenticationStatus() !== TokenInterface::AUTHENTICATION_SUCCESSFUL) {
         $authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN);
     }
     if (!is_array($credentials) || !isset($credentials['username']) || !isset($credentials['password'])) {
         return;
     }
     $providerName = $this->name;
     $accountRepository = $this->accountRepository;
     $this->securityContext->withoutAuthorizationChecks(function () use($credentials, $providerName, $accountRepository, &$account) {
         $account = $accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($credentials['username'], $providerName);
     });
     $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS);
     if ($account === null) {
         $this->hashService->validatePassword($credentials['password'], 'bcrypt=>$2a$14$DummySaltToPreventTim,.ingAttacksOnThisProvider');
         return;
     }
     if ($this->hashService->validatePassword($credentials['password'], $account->getCredentialsSource())) {
         $account->authenticationAttempted(TokenInterface::AUTHENTICATION_SUCCESSFUL);
         $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
         $authenticationToken->setAccount($account);
     } else {
         $account->authenticationAttempted(TokenInterface::WRONG_CREDENTIALS);
     }
     $this->accountRepository->update($account);
     $this->persistenceManager->whitelistObject($account);
 }
 /**
  * Returns an ActionRequest which referred to this request, if any.
  *
  * The referring request is not set or determined automatically but must be
  * explicitly set through the corresponding internal argument "__referrer".
  * This mechanism is used by Flow's form and validation mechanisms.
  *
  * @return ActionRequest the referring request, or NULL if no referrer found
  */
 public function getReferringRequest()
 {
     if ($this->referringRequest !== null) {
         return $this->referringRequest;
     }
     if (!isset($this->internalArguments['__referrer'])) {
         return null;
     }
     if (is_array($this->internalArguments['__referrer'])) {
         $referrerArray = $this->internalArguments['__referrer'];
         $referringRequest = new ActionRequest($this->getHttpRequest());
         $arguments = [];
         if (isset($referrerArray['arguments'])) {
             $serializedArgumentsWithHmac = $referrerArray['arguments'];
             $serializedArguments = $this->hashService->validateAndStripHmac($serializedArgumentsWithHmac);
             $arguments = unserialize(base64_decode($serializedArguments));
             unset($referrerArray['arguments']);
         }
         $referringRequest->setArguments(Arrays::arrayMergeRecursiveOverrule($arguments, $referrerArray));
         return $referringRequest;
     } else {
         $this->referringRequest = $this->internalArguments['__referrer'];
     }
     return $this->referringRequest;
 }
 /**
  * @test
  */
 public function validateAndStripHmacReturnsTheStringWithoutHmac()
 {
     $string = ' Some arbitrary string with special characters: öäüß!"§$ ';
     $hashedString = $this->hashService->appendHmac($string);
     $actualResult = $this->hashService->validateAndStripHmac($hashedString);
     $this->assertSame($string, $actualResult);
 }
 /**
  * Renders hidden form fields for referrer information about
  * the current controller and action.
  *
  * @return string Hidden fields with referrer information
  * @todo filter out referrer information that is equal to the target (e.g. same packageKey)
  */
 protected function renderHiddenReferrerFields()
 {
     $result = chr(10);
     $request = $this->controllerContext->getRequest();
     $argumentNamespace = null;
     if (!$request->isMainRequest()) {
         $argumentNamespace = $request->getArgumentNamespace();
         $referrer = array('@package' => $request->getControllerPackageKey(), '@subpackage' => $request->getControllerSubpackageKey(), '@controller' => $request->getControllerName(), '@action' => $request->getControllerActionName(), 'arguments' => $this->hashService->appendHmac(base64_encode(serialize($request->getArguments()))));
         foreach ($referrer as $referrerKey => $referrerValue) {
             $referrerValue = htmlspecialchars($referrerValue);
             $result .= '<input type="hidden" name="' . $argumentNamespace . '[__referrer][' . $referrerKey . ']" value="' . $referrerValue . '" />' . chr(10);
         }
         $request = $request->getParentRequest();
     }
     $arguments = $request->getArguments();
     if ($argumentNamespace !== null && isset($arguments[$argumentNamespace])) {
         // A sub request was there; thus we can unset the sub requests arguments,
         // as they are transferred separately via the code block shown above.
         unset($arguments[$argumentNamespace]);
     }
     $referrer = array('@package' => $request->getControllerPackageKey(), '@subpackage' => $request->getControllerSubpackageKey(), '@controller' => $request->getControllerName(), '@action' => $request->getControllerActionName(), 'arguments' => $this->hashService->appendHmac(base64_encode(serialize($arguments))));
     foreach ($referrer as $referrerKey => $referrerValue) {
         $result .= '<input type="hidden" name="__referrer[' . $referrerKey . ']" value="' . htmlspecialchars($referrerValue) . '" />' . chr(10);
     }
     return $result;
 }
 public function setUp()
 {
     $this->mockRole = $this->getMockBuilder(Role::class)->disableOriginalConstructor()->getMock();
     $this->mockRole->expects($this->any())->method('getIdentifier')->will($this->returnValue('Neos.Flow:TestRoleIdentifier'));
     $this->mockPolicyService = $this->getMockBuilder(PolicyService::class)->disableOriginalConstructor()->getMock();
     $this->mockPolicyService->expects($this->any())->method('getRole')->with('Neos.Flow:TestRoleIdentifier')->will($this->returnValue($this->mockRole));
     $this->mockHashService = $this->getMockBuilder(HashService::class)->disableOriginalConstructor()->getMock();
     $expectedPassword = $this->testKeyClearText;
     $expectedHashedPasswordAndSalt = $this->testKeyHashed;
     $this->mockHashService->expects($this->any())->method('validatePassword')->will($this->returnCallback(function ($password, $hashedPasswordAndSalt) use($expectedPassword, $expectedHashedPasswordAndSalt) {
         return $hashedPasswordAndSalt === $expectedHashedPasswordAndSalt && $password === $expectedPassword;
     }));
     $this->mockFileBasedSimpleKeyService = $this->getMockBuilder(FileBasedSimpleKeyService::class)->disableOriginalConstructor()->getMock();
     $this->mockFileBasedSimpleKeyService->expects($this->any())->method('getKey')->with('testKey')->will($this->returnValue($this->testKeyHashed));
     $this->mockToken = $this->getMockBuilder(PasswordToken::class)->disableOriginalConstructor()->getMock();
 }
 /**
  * @test
  */
 public function authenticationFailsWithWrongCredentialsInAnUsernamePasswordToken()
 {
     $this->mockHashService->expects($this->once())->method('validatePassword')->with('wrong password', '8bf0abbb93000e2e47f0e0a80721e834,80f117a78cff75f3f73793fd02aa9086')->will($this->returnValue(false));
     $this->mockAccount->expects($this->once())->method('getCredentialsSource')->will($this->returnValue('8bf0abbb93000e2e47f0e0a80721e834,80f117a78cff75f3f73793fd02aa9086'));
     $this->mockAccountRepository->expects($this->once())->method('findActiveByAccountIdentifierAndAuthenticationProviderName')->with('admin', 'myProvider')->will($this->returnValue($this->mockAccount));
     $this->mockToken->expects($this->once())->method('getCredentials')->will($this->returnValue(['username' => 'admin', 'password' => 'wrong password']));
     $this->mockToken->expects($this->at(2))->method('setAuthenticationStatus')->with(\Neos\Flow\Security\Authentication\TokenInterface::NO_CREDENTIALS_GIVEN);
     $this->mockToken->expects($this->at(3))->method('setAuthenticationStatus')->with(\Neos\Flow\Security\Authentication\TokenInterface::WRONG_CREDENTIALS);
     $this->persistedUsernamePasswordProvider->authenticate($this->mockToken);
 }
 /**
  * Persists a key to the file system
  *
  * @param string $name
  * @param string $password
  * @return void
  * @throws SecurityException
  */
 protected function persistKey($name, $password)
 {
     $hashedPassword = $this->hashService->hashPassword($password, $this->passwordHashingStrategy);
     $keyPathAndFilename = $this->getKeyPathAndFilename($name);
     if (!is_dir($this->getPath())) {
         Utility\Files::createDirectoryRecursively($this->getPath());
     }
     $result = file_put_contents($keyPathAndFilename, $hashedPassword);
     if ($result === false) {
         throw new SecurityException(sprintf('The key could not be stored ("%s").', $keyPathAndFilename), 1305812921);
     }
 }
 /**
  * Sets isAuthenticated to TRUE for all tokens.
  *
  * @param TokenInterface $authenticationToken The token to be authenticated
  * @return void
  * @throws UnsupportedAuthenticationTokenException
  */
 public function authenticate(TokenInterface $authenticationToken)
 {
     if (!$authenticationToken instanceof PasswordToken) {
         throw new UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1217339840);
     }
     $credentials = $authenticationToken->getCredentials();
     if (is_array($credentials) && isset($credentials['password'])) {
         if ($this->hashService->validatePassword($credentials['password'], $this->fileBasedSimpleKeyService->getKey($this->options['keyName']))) {
             $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
             $account = new Account();
             $roles = [];
             foreach ($this->options['authenticateRoles'] as $roleIdentifier) {
                 $roles[] = $this->policyService->getRole($roleIdentifier);
             }
             $account->setRoles($roles);
             $authenticationToken->setAccount($account);
         } else {
             $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS);
         }
     } elseif ($authenticationToken->getAuthenticationStatus() !== TokenInterface::AUTHENTICATION_SUCCESSFUL) {
         $authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN);
     }
 }
 /**
  * @test
  */
 public function extractWidgetContextDecodesSerializedWidgetContextIfPresent()
 {
     $ajaxWidgetComponent = $this->getAccessibleMock(\Neos\FluidAdaptor\Core\Widget\AjaxWidgetComponent::class, array('dummy'));
     $this->inject($ajaxWidgetComponent, 'hashService', $this->mockHashService);
     $mockWidgetContext = 'SomeWidgetContext';
     $mockSerializedWidgetContext = base64_encode(serialize($mockWidgetContext));
     $mockSerializedWidgetContextWithHmac = $mockSerializedWidgetContext . 'HMAC';
     $this->mockHttpRequest->expects($this->at(0))->method('hasArgument')->with('__widgetId')->will($this->returnValue(false));
     $this->mockHttpRequest->expects($this->at(1))->method('hasArgument')->with('__widgetContext')->will($this->returnValue(true));
     $this->mockHttpRequest->expects($this->atLeastOnce())->method('getArgument')->with('__widgetContext')->will($this->returnValue($mockSerializedWidgetContextWithHmac));
     $this->mockHashService->expects($this->atLeastOnce())->method('validateAndStripHmac')->with($mockSerializedWidgetContextWithHmac)->will($this->returnValue($mockSerializedWidgetContext));
     $actualResult = $ajaxWidgetComponent->_call('extractWidgetContext', $this->mockHttpRequest);
     $this->assertEquals($mockWidgetContext, $actualResult);
 }
 /**
  * Initialize the property mapping configuration in $controllerArguments if
  * the trusted properties are set inside the request.
  *
  * @param ActionRequest $request
  * @param Arguments $controllerArguments
  * @return void
  */
 public function initializePropertyMappingConfigurationFromRequest(ActionRequest $request, Arguments $controllerArguments)
 {
     $trustedPropertiesToken = $request->getInternalArgument('__trustedProperties');
     if (!is_string($trustedPropertiesToken)) {
         return;
     }
     $serializedTrustedProperties = $this->hashService->validateAndStripHmac($trustedPropertiesToken);
     $trustedProperties = unserialize($serializedTrustedProperties);
     foreach ($trustedProperties as $propertyName => $propertyConfiguration) {
         if (!$controllerArguments->hasArgument($propertyName)) {
             continue;
         }
         $propertyMappingConfiguration = $controllerArguments->getArgument($propertyName)->getPropertyMappingConfiguration();
         $this->modifyPropertyMappingConfiguration($propertyConfiguration, $propertyMappingConfiguration);
     }
 }
 /**
  * Get the URI for an AJAX Request.
  *
  * @return string the AJAX URI
  * @throws WidgetContextNotFoundException
  */
 protected function getAjaxUri()
 {
     $action = $this->arguments['action'];
     $arguments = $this->arguments['arguments'];
     if ($action === null) {
         $action = $this->controllerContext->getRequest()->getControllerActionName();
     }
     $arguments['@action'] = $action;
     if (strlen($this->arguments['format']) > 0) {
         $arguments['@format'] = $this->arguments['format'];
     }
     /** @var $widgetContext WidgetContext */
     $widgetContext = $this->controllerContext->getRequest()->getInternalArgument('__widgetContext');
     if ($widgetContext === null) {
         throw new WidgetContextNotFoundException('Widget context not found in <f:widget.link>', 1307450686);
     }
     if ($this->arguments['includeWidgetContext'] === true) {
         $serializedWidgetContext = serialize($widgetContext);
         $arguments['__widgetContext'] = $this->hashService->appendHmac($serializedWidgetContext);
     } else {
         $arguments['__widgetId'] = $widgetContext->getAjaxWidgetIdentifier();
     }
     return '?' . http_build_query($arguments, null, '&');
 }
Example #15
0
 /**
  * @return void
  * @internal
  */
 protected function initializeFormStateFromRequest()
 {
     $serializedFormStateWithHmac = $this->request->getInternalArgument('__state');
     if ($serializedFormStateWithHmac === null) {
         $this->formState = new FormState();
     } else {
         $serializedFormState = $this->hashService->validateAndStripHmac($serializedFormStateWithHmac);
         $this->formState = unserialize(base64_decode($serializedFormState));
     }
 }
 /**
  * Sets a new password for the given user
  *
  * This method will iterate over all accounts owned by the given user and, if the account uses a UsernamePasswordToken,
  * sets a new password accordingly.
  *
  * @param User $user The user to set the password for
  * @param string $password A new password
  * @return void
  * @api
  */
 public function setUserPassword(User $user, $password)
 {
     $tokens = $this->authenticationManager->getTokens();
     $indexedTokens = array();
     foreach ($tokens as $token) {
         /** @var TokenInterface $token */
         $indexedTokens[$token->getAuthenticationProviderName()] = $token;
     }
     foreach ($user->getAccounts() as $account) {
         /** @var Account $account */
         $authenticationProviderName = $account->getAuthenticationProviderName();
         if (isset($indexedTokens[$authenticationProviderName]) && $indexedTokens[$authenticationProviderName] instanceof UsernamePassword) {
             $account->setCredentialsSource($this->hashService->hashPassword($password));
             $this->accountRepository->update($account);
         }
     }
 }