/** * This is the default Policy voter, it votes for the access privilege for the given resource * * @param \TYPO3\Flow\Security\Context $securityContext The current security context * @param string $resource The resource to vote for * @return integer One of: VOTE_GRANT, VOTE_ABSTAIN, VOTE_DENY */ public function voteForResource(\TYPO3\Flow\Security\Context $securityContext, $resource) { $accessGrants = 0; $accessDenies = 0; foreach ($securityContext->getRoles() as $role) { try { $privilege = $this->policyService->getPrivilegeForResource($role, $resource); } catch (\TYPO3\Flow\Security\Exception\NoEntryInPolicyException $e) { return self::VOTE_ABSTAIN; } if ($privilege === NULL) { continue; } if ($privilege === \TYPO3\Flow\Security\Policy\PolicyService::PRIVILEGE_GRANT) { $accessGrants++; } elseif ($privilege === \TYPO3\Flow\Security\Policy\PolicyService::PRIVILEGE_DENY) { $accessDenies++; } } if ($accessDenies > 0) { return self::VOTE_DENY; } if ($accessGrants > 0) { return self::VOTE_GRANT; } return self::VOTE_ABSTAIN; }
/** * Convert an object from $source to an object. * * @param mixed $source * @param string $targetType * @param array $convertedChildProperties * @param PropertyMappingConfigurationInterface $configuration * @return object the target type */ public function convertFrom($source, $targetType, array $convertedChildProperties = array(), PropertyMappingConfigurationInterface $configuration = null) { try { $role = $this->policyService->getRole($source); } catch (NoSuchRoleException $exception) { return new Error('Could not find a role with the identifier "%s".', 1397212327, array($source)); } return $role; }
/** * @test */ public function createAccountWithPasswordCreatesANewAccountWithTheGivenIdentifierPasswordRolesAndProviderName() { $factory = new \TYPO3\Flow\Security\AccountFactory(); $actualAccount = $factory->createAccountWithPassword('username', 'password', array('TYPO3.Flow:Administrator', 'TYPO3.Flow:Customer'), 'OtherProvider'); $this->assertEquals('username', $actualAccount->getAccountIdentifier()); $this->assertEquals('OtherProvider', $actualAccount->getAuthenticationProviderName()); $this->assertTrue($actualAccount->hasRole($this->policyService->getRole('TYPO3.Flow:Administrator'))); $this->assertTrue($actualAccount->hasRole($this->policyService->getRole('TYPO3.Flow:Customer'))); }
/** * 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 \TYPO3\Flow\Security\Account A new account, not yet added to the account repository */ public function createAccountWithPassword($identifier, $password, $roleIdentifiers = array(), $authenticationProviderName = 'DefaultProvider', $passwordHashingStrategy = 'default') { $account = new \TYPO3\Flow\Security\Account(); $account->setAccountIdentifier($identifier); $account->setCredentialsSource($this->hashService->hashPassword($password, $passwordHashingStrategy)); $account->setAuthenticationProviderName($authenticationProviderName); $roles = array(); foreach ($roleIdentifiers as $roleIdentifier) { $roles[] = $this->policyService->getRole($roleIdentifier); } $account->setRoles($roles); return $account; }
public function setUp() { $this->mockRole = $this->getMockBuilder('TYPO3\\Flow\\Security\\Policy\\Role')->disableOriginalConstructor()->getMock(); $this->mockRole->expects($this->any())->method('getIdentifier')->will($this->returnValue('TYPO3.Flow:TestRoleIdentifier')); $this->mockPolicyService = $this->getMockBuilder('TYPO3\\Flow\\Security\\Policy\\PolicyService')->disableOriginalConstructor()->getMock(); $this->mockPolicyService->expects($this->any())->method('getRole')->with('TYPO3.Flow:TestRoleIdentifier')->will($this->returnValue($this->mockRole)); $this->mockHashService = $this->getMockBuilder('TYPO3\\Flow\\Security\\Cryptography\\HashService')->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('TYPO3\\Flow\\Security\\Cryptography\\FileBasedSimpleKeyService')->disableOriginalConstructor()->getMock(); $this->mockFileBasedSimpleKeyService->expects($this->any())->method('getKey')->with('testKey')->will($this->returnValue($this->testKeyHashed)); $this->mockToken = $this->getMockBuilder('TYPO3\\Flow\\Security\\Authentication\\Token\\PasswordToken')->disableOriginalConstructor()->getMock(); }
/** * @test */ public function everybodyRoleCanHaveExplicitDenies() { $mockPrivilegeClassName = get_class($this->mockPrivilege); $this->mockPolicyConfiguration = ['privilegeTargets' => [$mockPrivilegeClassName => ['Some.PrivilegeTarget:Identifier' => ['matcher' => 'someMatcher()'], 'Some.OtherPrivilegeTarget:Identifier' => ['matcher' => 'someMatcher()']]], 'roles' => ['TYPO3.Flow:Everybody' => ['privileges' => [['privilegeTarget' => 'Some.PrivilegeTarget:Identifier', 'permission' => 'DENY']]], 'Some.Other:Role' => ['privileges' => [['privilegeTarget' => 'Some.PrivilegeTarget:Identifier', 'permission' => 'GRANT']]]]]; $everybodyRole = $this->policyService->getRole('TYPO3.Flow:Everybody'); $this->assertTrue($everybodyRole->getPrivilegeForTarget('Some.PrivilegeTarget:Identifier')->isDenied()); }
/** * Check if department of logged in User match with department property of page node and hide this node if true * * @param \TYPO3\Flow\AOP\JoinPointInterface $joinPoint * @Flow\Around("method(TYPO3\TYPO3CR\Security\Authorization\Privilege\Node\___NotUse___EditNodePrivilege->matchesSubject(PrivilegeSubjectInterface $subject))") * @return boolean */ public function checkMatchesSubjectForCreatingNodes($joinPoint) { $matchesSubject = $joinPoint->getMethodArgument('subject'); $result = $joinPoint->getAdviceChain()->proceed($joinPoint); // if ($matchesSubject instanceof \TYPO3\Flow\Security\Authorization\Privilege\Method\CreateNodePrivilegeSubject === false) return false; if ($result) { if ($this->securityContext->getParty() instanceof User) { // get access rights depending on matching users and pages department if ($this->getPropertyRecursive($matchesSubject->getNode(), 'departmentName') == $this->securityContext->getParty()->getDepartment()) { return false; } else { return true; } } else { $role = $this->policyService->getRole('TYPO3.Neos:Administrator'); if ($role) { foreach ($this->securityContext->getParty()->getAccounts() as $account) { if ($account->hasRole($role)) { return false; } } } } } return $result; }
/** * Checks, if the current policy allows the retrieval of the object fetched by getObjectDataByIdentifier() * * @Flow\Around("within(TYPO3\Flow\Persistence\PersistenceManagerInterface) && method(.*->getObjectByIdentifier()) && setting(TYPO3.Flow.security.enable)") * @param \TYPO3\Flow\Aop\JoinPointInterface $joinPoint The current joinpoint * @return array The object data of the original object, or NULL if access is not permitted */ public function checkAccessAfterFetchingAnObjectByIdentifier(JoinPointInterface $joinPoint) { $result = $joinPoint->getAdviceChain()->proceed($joinPoint); if ($this->securityContext->areAuthorizationChecksDisabled() === TRUE || $this->policyService->hasPolicyEntriesForEntities() === FALSE) { return $result; } if ($this->securityContext->isInitialized() === FALSE) { if ($this->securityContext->canBeInitialized() === TRUE) { $this->securityContext->initialize(); } else { return $result; } } $authenticatedRoles = $this->securityContext->getRoles(); $entityType = $this->reflectionService->getClassNameByObject($result); if ($this->policyService->hasPolicyEntryForEntityType($entityType, $authenticatedRoles)) { if ($this->policyService->isGeneralAccessForEntityTypeGranted($entityType, $authenticatedRoles) === FALSE) { return NULL; } $policyConstraintsDefinition = $this->policyService->getResourcesConstraintsForEntityTypeAndRoles($entityType, $authenticatedRoles); if ($this->checkConstraintDefinitionsOnResultObject($policyConstraintsDefinition, $result) === FALSE) { return NULL; } } return $result; }
/** * Lists all public controller actions not covered by the active security policy * * @return void */ public function showUnprotectedActionsCommand() { $controllerClassNames = $this->reflectionService->getAllSubClassNamesForClass('TYPO3\\Flow\\Mvc\\Controller\\AbstractController'); $allActionsAreProtected = TRUE; foreach ($controllerClassNames as $controllerClassName) { if ($this->reflectionService->isClassAbstract($controllerClassName)) { continue; } $methodNames = get_class_methods($controllerClassName); $foundUnprotectedAction = FALSE; foreach ($methodNames as $methodName) { if (preg_match('/.*Action$/', $methodName) === 0 || $this->reflectionService->isMethodPublic($controllerClassName, $methodName) === FALSE) { continue; } if ($this->policyService->hasPolicyEntryForMethod($controllerClassName, $methodName) === FALSE) { if ($foundUnprotectedAction === FALSE) { $this->outputLine(PHP_EOL . '<b>' . $controllerClassName . '</b>'); $foundUnprotectedAction = TRUE; $allActionsAreProtected = FALSE; } $this->outputLine(' ' . $methodName); } } } if ($allActionsAreProtected === TRUE) { $this->outputLine('All public controller actions are covered by your security policy. Good job!'); } }
/** * renders <f:then> child if the role could be found in the security context, * otherwise renders <f:else> child. * * @param string $role The role or role identifier * @param string $packageKey PackageKey of the package defining the role * @param Account $account If specified, this subject of this check is the given Account instead of the currently authenticated account * @return string the rendered string * @api */ public function render($role, $packageKey = null, Account $account = null) { if (is_string($role)) { $roleIdentifier = $role; if (in_array($roleIdentifier, array('Everybody', 'Anonymous', 'AuthenticatedUser'))) { $roleIdentifier = 'TYPO3.Flow:' . $roleIdentifier; } if (strpos($roleIdentifier, '.') === false && strpos($roleIdentifier, ':') === false) { if ($packageKey === null) { $request = $this->controllerContext->getRequest(); $roleIdentifier = $request->getControllerPackageKey() . ':' . $roleIdentifier; } else { $roleIdentifier = $packageKey . ':' . $roleIdentifier; } } $role = $this->policyService->getRole($roleIdentifier); } if ($account instanceof Account) { $hasRole = $account->hasRole($role); } else { $hasRole = $this->securityContext->hasRole($role->getIdentifier()); } if ($hasRole) { return $this->renderThenChild(); } else { return $this->renderElseChild(); } }
/** * Authenticates against a crowd instance. * * @param \TYPO3\Flow\Security\Authentication\TokenInterface $authenticationToken The token to be authenticated * @return void * @throws \TYPO3\Flow\Security\Exception\UnsupportedAuthenticationTokenException */ public function authenticate(TokenInterface $authenticationToken) { if (!$authenticationToken instanceof UsernamePassword) { throw new UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1217339845); } $credentials = $authenticationToken->getCredentials(); if (is_array($credentials) && isset($credentials['username']) && isset($credentials['password'])) { $crowdAuthenticationResponse = $this->crowdClient->authenticate($credentials['username'], $credentials['password']); if ($crowdAuthenticationResponse !== NULL) { /** @var $account \TYPO3\Flow\Security\Account */ $account = NULL; $providerName = $this->name; $accountRepository = $this->accountRepository; $this->securityContext->withoutAuthorizationChecks(function () use($credentials, $providerName, $accountRepository, &$account) { $account = $accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($credentials['username'], $providerName); }); if ($account === NULL) { $account = new Account(); $account->setAuthenticationProviderName($providerName); $account->setAccountIdentifier($credentials['username']); $this->accountRepository->add($account); } $authenticateRole = $this->policyService->getRole($this->options['authenticateRole']); if ($account->hasRole($authenticateRole) === FALSE) { $account->addRole($authenticateRole); } $crowdUser = $this->partyService->getAssignedPartyOfAccount($account); if ($crowdUser instanceof Person) { if ($crowdUser->getName()->getFirstName() !== $crowdAuthenticationResponse['first-name']) { $crowdUser->getName()->setFirstName($crowdAuthenticationResponse['first-name']); $this->partyRepository->update($crowdUser); } if ($crowdUser->getName()->getLastName() !== $crowdAuthenticationResponse['last-name']) { $crowdUser->getName()->setLastName($crowdAuthenticationResponse['last-name']); $this->partyRepository->update($crowdUser); } if ($crowdUser->getPrimaryElectronicAddress()->getIdentifier() !== $crowdAuthenticationResponse['email']) { $crowdUser->getPrimaryElectronicAddress()->setIdentifier($crowdAuthenticationResponse['email']); $this->partyRepository->update($crowdUser); } } else { $crowdUser = new Person(); $crowdUser->setName(new PersonName('', $crowdAuthenticationResponse['first-name'], '', $crowdAuthenticationResponse['last-name'])); $email = new ElectronicAddress(); $email->setIdentifier($crowdAuthenticationResponse['email']); $email->setType(ElectronicAddress::TYPE_EMAIL); $crowdUser->setPrimaryElectronicAddress($email); $this->partyRepository->add($crowdUser); $this->partyService->assignAccountToParty($account, $crowdUser); } $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL); $authenticationToken->setAccount($account); } else { $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS); } } elseif ($authenticationToken->getAuthenticationStatus() !== TokenInterface::AUTHENTICATION_SUCCESSFUL) { $authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN); } }
public function setUp() { $package1 = $this->getMock('TYPO3\\Flow\\Package\\PackageInterface'); $package1->expects($this->any())->method('getPackageKey')->will($this->returnValue('Foo.Package1')); $package1->expects($this->any())->method('getConfigurationPath')->will($this->returnValue(__DIR__ . '/../Fixture/Roles/Foo.Package1/')); $package2 = $this->getMock('TYPO3\\Flow\\Package\\PackageInterface'); $package2->expects($this->any())->method('getPackageKey')->will($this->returnValue('Package2')); $package2->expects($this->any())->method('getConfigurationPath')->will($this->returnValue(__DIR__ . '/../Fixture/Roles/Package2/')); $this->configurationManager = new \TYPO3\Flow\Configuration\ConfigurationManager(new \TYPO3\Flow\Core\ApplicationContext('Testing')); $this->configurationManager->setPackages(array($package1->getPackageKey() => $package1, $package2->getPackageKey() => $package2)); $this->configurationManager->injectConfigurationSource(new \TYPO3\Flow\Configuration\Source\YamlSource()); $mockEnvironment = $this->getMock('TYPO3\\Flow\\Utility\\Environment', array(), array(), '', FALSE); $this->configurationManager->injectEnvironment($mockEnvironment); $this->policyService = $this->getAccessibleMock('TYPO3\\Flow\\Security\\Policy\\PolicyService', array('setAclsForEverybodyRole'), array(), '', FALSE); $this->policyService->injectConfigurationManager($this->configurationManager); $this->policyService->_set('policy', $this->configurationManager->getConfiguration(\TYPO3\Flow\Configuration\ConfigurationManager::CONFIGURATION_TYPE_POLICY)); }
/** * Returns all roles defined in the Incvisio.LostFound package * * @return array<\TYPO3\Flow\Security\Policy\Role> */ public function getRoles() { $roles = array(); foreach ($this->policyService->getRoles() as $role) { if ($role->getPackageKey() === self::CURRENT_PACKAGE_KEY) { $roles[] = $role; } } return $roles; }
/** * @param ACLCheckerDto $dto * @return array */ protected function getRolesByDto(ACLCheckerDto $dto) { $roles = []; foreach ($dto->getRoles() as $roleIdentifier) { try { $roles[] = $this->policyService->getRole($roleIdentifier); } catch (NoSuchRoleException $e) { } } return $roles; }
/** * @param string $className * @param string $methodName * @return boolean */ protected function hasPolicyEntryForMethod($className, $methodName) { $methodPrivileges = $this->policyService->getAllPrivilegesByType('TYPO3\\Flow\\Security\\Authorization\\Privilege\\Method\\MethodPrivilegeInterface'); /** @var MethodPrivilegeInterface $privilege */ foreach ($methodPrivileges as $privilege) { if ($privilege->matchesMethod($className, $methodName)) { return TRUE; } } return FALSE; }
/** * @param string $className * @param string $methodName * @return boolean */ protected function hasPolicyEntryForMethod($className, $methodName) { $methodPrivileges = $this->policyService->getAllPrivilegesByType(\TYPO3\Flow\Security\Authorization\Privilege\Method\MethodPrivilegeInterface::class); /** @var MethodPrivilegeInterface $privilege */ foreach ($methodPrivileges as $privilege) { if ($privilege->matchesMethod($className, $methodName)) { return true; } } return false; }
private function initRoles() { if (!$this->policyService->hasRole('DLigo.Animaltool:Admin')) { $this->policyService->createRole('DLigo.Animaltool:Admin'); } if (!$this->policyService->hasRole('DLigo.Animaltool:Catcher')) { $this->policyService->createRole('DLigo.Animaltool:Catcher'); } if (!$this->policyService->hasRole('DLigo.Animaltool:Doctor')) { $this->policyService->createRole('DLigo.Animaltool:Doctor'); } }
/** * Returns the processed Configuration * * @param \TYPO3\TYPO3CR\Domain\Model\NodeType $nodeType (uninitialized) The node type to process * @param array $configuration input configuration * @param array $options The processor options * @return void */ public function process(NodeType $nodeType, array &$configuration, array $options) { if ($this->securityContext->canBeInitialized()) { /* Check if user is logged in */ if ($this->securityContext->getAccount()) { $admin = false; $role = $this->policyService->getRole('TYPO3.Neos:Administrator'); if ($role && $this->securityContext->getAccount()->hasRole($role)) { $admin = true; } if (!$admin) { // foreach ($configuration['properties']['departmentName']['ui']['inspector']['editorOptions']['values'] as $key => $val) { // $configuration['properties']['departmentName']['ui']['inspector']['editorOptions']['values'][$key]['disabled'] = TRUE; // } // if ($nodeType->getName() == 'TYPO3.Neos.NodeTypes:Page') { // $configuration['constraints']['nodeTypes']['TYPO3.Neos.NodeTypes:Page'] = FALSE; // } unset($configuration['properties']['departmentName']); } } } }
/** * Creates a new account, assigns it the given roles and authenticates it. * The created account is returned for further modification, for example for attaching a Party object to it. * * @param array $roleNames A list of roles the new account should have * @return Account The created account */ protected function authenticateRoles(array $roleNames) { // FIXME this is currently needed in order to correctly import the roles. Otherwise RepositoryInterface::isConnected() returns FALSE and importing is skipped in PolicyService::initializeRolesFromPolicy() $this->objectManager->get('TYPO3\\Flow\\Security\\AccountRepository')->countAll(); $account = new Account(); $account->setAccountIdentifier('TestAccount'); $roles = array(); foreach ($roleNames as $roleName) { $roles[] = $this->policyService->getRole($roleName); } $account->setRoles($roles); $this->authenticateAccount($account); return $account; }
/** * @param \DLigo\Animaltool\Domain\Model\User $user * @param array $username * @Flow\Validate(argumentName="$username", type="notEmpty") * @param array $password * @param string $role * @Flow\Validate(argumentName="$password", type="\DLigo\Animaltool\Validation\Validator\PasswordValidator", options={"allowEmpty"=true}) * @Flow\Validate(argumentName="$username", type="\DLigo\Animaltool\Validation\Validator\AccountExistsValidator") * @return void */ public function updateAction(User $user, $username, $password = null, $role = null) { if ($role) { $roleObj = $this->policyService->getRole($role); foreach ($user->getAccounts() as $account) { $account->setRoles(array($role => $roleObj)); $account->setAccountIdentifier($username['new']); $account->setCredentialsSource($this->hashService->hashPassword($password[0], 'default')); $this->accountRepository->update($account); } } $this->userRepository->update($user); $this->addFlashMessage('Updated the user.', '', \TYPO3\Flow\Error\Message::SEVERITY_OK, array(), 'flash.user.update'); $this->redirect('index'); }
/** * Initializes the roles field by fetching the role objects referenced by the roleIdentifiers * * @return void */ protected function initializeRoles() { if ($this->roles !== null) { return; } $this->roles = []; foreach ($this->roleIdentifiers as $key => $roleIdentifier) { // check for and clean up roles no longer available if ($this->policyService->hasRole($roleIdentifier)) { $this->roles[$roleIdentifier] = $this->policyService->getRole($roleIdentifier); } else { unset($this->roleIdentifiers[$key]); } } }
/** * @param Account $account * @param array $userdata * @return \TYPO3\Flow\Security\Account */ protected function updateAccount(Account $account, array $userdata) { $person = $this->partyService->getAssignedPartyOfAccount($account); if ($person === null) { $person = new Person(); $this->partyRepository->add($person); $this->partyService->assignAccountToParty($account, $person); } if (!$account->getRoles()) { $account->setRoles(array($this->policyService->getRole('T3DD.Backend:Authenticated'))); } $this->updatePerson($person, $userdata); $this->accountRepository->update($account); $this->persistenceManager->persistAll(); return $account; }
/** * Matches a \TYPO3\Flow\Mvc\RequestInterface against the configured CSRF pattern rules and * searches for invalid csrf tokens. If this returns TRUE, the request is invalid! * * @param \TYPO3\Flow\Mvc\RequestInterface $request The request that should be matched * @return boolean TRUE if the pattern matched, FALSE otherwise * @throws \TYPO3\Flow\Security\Exception\AuthenticationRequiredException */ public function matchRequest(\TYPO3\Flow\Mvc\RequestInterface $request) { if (!$request instanceof ActionRequest || $request->getHttpRequest()->isMethodSafe()) { $this->systemLogger->log('No CSRF required, safe request', LOG_DEBUG); return FALSE; } if ($this->authenticationManager->isAuthenticated() === FALSE) { $this->systemLogger->log('No CSRF required, not authenticated', LOG_DEBUG); return FALSE; } if ($this->securityContext->areAuthorizationChecksDisabled() === TRUE) { $this->systemLogger->log('No CSRF required, authorization checks are disabled', LOG_DEBUG); return FALSE; } $controllerClassName = $this->objectManager->getClassNameByObjectName($request->getControllerObjectName()); $actionName = $request->getControllerActionName() . 'Action'; if (!$this->policyService->hasPolicyEntryForMethod($controllerClassName, $actionName)) { $this->systemLogger->log(sprintf('CSRF protection filter: allowed %s request without requiring CSRF token because action "%s" in controller "%s" is not restricted by a policy.', $request->getHttpRequest()->getMethod(), $actionName, $controllerClassName), LOG_NOTICE); return FALSE; } if ($this->reflectionService->isMethodTaggedWith($controllerClassName, $actionName, 'skipcsrfprotection')) { return FALSE; } $httpRequest = $request->getHttpRequest(); if ($httpRequest->hasHeader('X-Flow-Csrftoken')) { $csrfToken = $httpRequest->getHeader('X-Flow-Csrftoken'); } else { $internalArguments = $request->getMainRequest()->getInternalArguments(); $csrfToken = isset($internalArguments['__csrfToken']) ? $internalArguments['__csrfToken'] : NULL; } if (empty($csrfToken)) { $this->systemLogger->log('CSRF token was empty', LOG_DEBUG); return TRUE; } if (!$this->securityContext->hasCsrfProtectionTokens()) { throw new \TYPO3\Flow\Security\Exception\AuthenticationRequiredException('No tokens in security context, possible session timeout', 1317309673); } if ($this->securityContext->isCsrfProtectionTokenValid($csrfToken) === FALSE) { $this->systemLogger->log('CSRF token was invalid', LOG_DEBUG); return TRUE; } // the CSRF token was necessary and is valid return FALSE; }
/** * Shows the methods represented by the given security privilege target * * If the privilege target has parameters those can be specified separated by a colon * for example "parameter1:value1" "parameter2:value2". * But be aware that this only works for parameters that have been specified in the policy * * @param string $privilegeTarget The name of the privilegeTarget as stated in the policy * @return void */ public function showMethodsForPrivilegeTargetCommand($privilegeTarget) { $privilegeTargetInstance = $this->policyService->getPrivilegeTargetByIdentifier($privilegeTarget); if ($privilegeTargetInstance === null) { $this->outputLine('The privilegeTarget "%s" is not defined', array($privilegeTarget)); $this->quit(1); } $privilegeParameters = array(); foreach ($this->request->getExceedingArguments() as $argument) { list($argumentName, $argumentValue) = explode(':', $argument, 2); $privilegeParameters[$argumentName] = $argumentValue; } $privilege = $privilegeTargetInstance->createPrivilege(PrivilegeInterface::GRANT, $privilegeParameters); if (!$privilege instanceof MethodPrivilegeInterface) { $this->outputLine('The privilegeTarget "%s" does not refer to a MethodPrivilege but to a privilege of type "%s"', array($privilegeTarget, $privilege->getPrivilegeTarget()->getPrivilegeClassName())); $this->quit(1); } $matchedClassesAndMethods = array(); foreach ($this->reflectionService->getAllClassNames() as $className) { try { $reflectionClass = new \ReflectionClass($className); } catch (\ReflectionException $exception) { continue; } foreach ($reflectionClass->getMethods() as $reflectionMethod) { $methodName = $reflectionMethod->getName(); if ($privilege->matchesMethod($className, $methodName)) { $matchedClassesAndMethods[$className][$methodName] = $methodName; } } } if (count($matchedClassesAndMethods) === 0) { $this->outputLine('The given Resource did not match any method or is unknown.'); $this->quit(1); } foreach ($matchedClassesAndMethods as $className => $methods) { $this->outputLine($className); foreach ($methods as $methodName) { $this->outputLine(' ' . $methodName); } $this->outputLine(); } }
/** * Sets the roles for the LDAP account. * Extend this Provider class and implement this method to update the party * * @param Account $account * @param array $ldapSearchResult * @return void */ protected function setRoles(Account $account, array $ldapSearchResult) { if (is_array($this->rolesConfiguration)) { $contextVariables = array('ldapUser' => $ldapSearchResult); if (isset($this->defaultContext) && is_array($this->defaultContext)) { foreach ($this->defaultContext as $contextVariable => $objectName) { $object = $this->objectManager->get($objectName); $contextVariables[$contextVariable] = $object; } } foreach ($this->rolesConfiguration['default'] as $roleIdentifier) { $role = $this->policyService->getRole($roleIdentifier); $account->addRole($role); } $eelContext = new Context($contextVariables); if (isset($this->partyConfiguration['dn'])) { $dn = $this->eelEvaluator->evaluate($this->partyConfiguration['dn'], $eelContext); foreach ($this->rolesConfiguration['userMapping'] as $roleIdentifier => $userDns) { if (in_array($dn, $userDns)) { $role = $this->policyService->getRole($roleIdentifier); $account->addRole($role); } } } elseif (!empty($this->rolesConfiguration['userMapping'])) { $this->logger->log('User mapping found but no party mapping for dn set', LOG_ALERT); } if (isset($this->partyConfiguration['username'])) { $username = $this->eelEvaluator->evaluate($this->partyConfiguration['username'], $eelContext); $groupMembership = $this->directoryService->getGroupMembership($username); foreach ($this->rolesConfiguration['groupMapping'] as $roleIdentifier => $remoteRoleIdentifiers) { foreach ($remoteRoleIdentifiers as $remoteRoleIdentifier) { $role = $this->policyService->getRole($roleIdentifier); if (isset($groupMembership[$remoteRoleIdentifier])) { $account->addRole($role); } } } } elseif (!empty($this->rolesConfiguration['groupMapping'])) { $this->logger->log('Group mapping found but no party mapping for username set', LOG_ALERT); } } }
/** * @param string $username Crowd Username * @param string $providerName Name of the authentication provider, this account should be used with * @return Account */ public function getLocalAccountForCrowdUser($username, $providerName) { $accountRepository = $this->accountRepository; $this->securityContext->withoutAuthorizationChecks(function () use($username, $providerName, $accountRepository, &$account) { $account = $accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($username, $providerName); }); if ($account === NULL) { if ($this->getUser($username) === NULL) { return NULL; } $account = new Account(); $account->setAuthenticationProviderName($providerName); $account->setAccountIdentifier($username); $roleIdentifier = $this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'TYPO3.Flow.security.authentication.providers.' . $providerName . '.providerOptions.authenticateRole'); $account->addRole($this->policyService->getRole($roleIdentifier)); $this->accountRepository->add($account); $this->persistenceManager->persistAll(); } return $account; }
/** * Update a given account * * @param Account $account The account to update * @param array $roleIdentifiers A possibly updated list of roles for the user's primary account * @param array $password Expects an array in the format array('<password>', '<password confirmation>') * @Flow\Validate(argumentName="password", type="\TYPO3\Neos\Validation\Validator\PasswordValidator", options={ "allowEmpty"=1, "minimum"=1, "maximum"=255 }) * @return void */ public function updateAccountAction(Account $account, array $roleIdentifiers, array $password = array()) { $user = $this->userService->getUser($account->getAccountIdentifier(), $account->getAuthenticationProviderName()); if ($user === $this->currentUser) { $roles = array(); foreach ($roleIdentifiers as $roleIdentifier) { $roles[$roleIdentifier] = $this->policyService->getRole($roleIdentifier); } if (!$this->privilegeManager->isPrivilegeTargetGrantedForRoles($roles, 'TYPO3.Neos:Backend.Module.Administration.Users')) { $this->addFlashMessage('With the selected roles the currently logged in user wouldn\'t have access to this module any longer. Please adjust the assigned roles!', 'Don\'t lock yourself out', Message::SEVERITY_WARNING, array(), 1416501197); $this->forward('edit', null, null, array('user' => $this->currentUser)); } } $password = array_shift($password); if (strlen(trim(strval($password))) > 0) { $this->userService->setUserPassword($user, $password); } $this->userService->setRolesForAccount($account, $roleIdentifiers); $this->addFlashMessage('The account has been updated.', 'Account updated', Message::SEVERITY_OK); $this->redirect('edit', null, null, array('user' => $user)); }
/** * Returns Collection of roles. * * @param string $providerName Provider name to fetch roles from. * @param array $casAttributes * * @throws \Exception * @throws Exception\WrongMappingConfigurationException * * @return \Doctrine\Common\Collections\Collection<\TYPO3\Flow\Security\Policy\Role> */ public function getRoles($providerName, array $casAttributes) { $rolesSettings = $this->settings[$providerName]['Roles']; $rolesCollection = new ArrayCollection(); $iterator = 0; foreach ($rolesSettings as $roleSettings) { // Map Cas Attributes if (empty($roleSettings['staticIdentifier']) && !empty($roleSettings['identifier']) && is_string($roleSettings['identifier'])) { $roleIdentifier = ArraysUtility::getValueByPath($casAttributes, $roleSettings['identifier']); if (!is_string($roleIdentifier) && !is_int($roleIdentifier)) { throw new WrongMappingConfigurationException(sprintf('Cas attribute catched by path "%s" from CAS-Attributes array defined at ....%s.providerOptions.Mapping.Roles.%s.identifier must be a string but "%s" is given.', $roleSettings['identifier'], $providerName, $iterator, gettype($roleIdentifier)), 1371209193); } if (isset($roleSettings['rewriteRoles'])) { $roleIdentifier = $this->rewriteRole($roleIdentifier, $roleSettings['rewriteRoles']); } } // Map static Role if (isset($roleSettings['staticIdentifier']) && is_string($roleSettings['staticIdentifier'])) { $roleIdentifier = $roleSettings['staticIdentifier']; if (isset($roleSettings['rewriteRoles'])) { $roleIdentifier = $this->rewriteRole($roleIdentifier, $roleSettings['rewriteRoles']); } } if (is_string($roleIdentifier) || is_int($roleIdentifier)) { try { $role = $this->policyService->getRole($roleSettings['packageKey'] . ':' . $roleIdentifier); } catch (NoSuchRoleException $exc) { /* @var $exc \Exception */ if ($exc->getCode() === 1353085860) { $role = $this->policyService->createRole($roleSettings['packageKey'] . ':' . $roleIdentifier); } else { throw new \Exception('Unknown exception by PolicyService->getRole(). Message: ' . $exc->getMessage() . ' Code: ' . $exc->getCode(), 1371211532); } } } $rolesCollection->add($role); $iterator++; } return $rolesCollection; }
/** * 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 = array(); 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); } }
/** * Returns the roles of all authenticated accounts, including inherited roles. * * If no authenticated roles could be found the "Anonymous" role is returned. * * The "TYPO3.Flow:Everybody" roles is always returned. * * @return Role[] */ public function getRoles() { if ($this->initialized === false) { $this->initialize(); } if ($this->roles === null) { $this->roles = array('TYPO3.Flow:Everybody' => $this->policyService->getRole('TYPO3.Flow:Everybody')); if ($this->authenticationManager->isAuthenticated() === false) { $this->roles['TYPO3.Flow:Anonymous'] = $this->policyService->getRole('TYPO3.Flow:Anonymous'); } else { $this->roles['TYPO3.Flow:AuthenticatedUser'] = $this->policyService->getRole('TYPO3.Flow:AuthenticatedUser'); /** @var $token \TYPO3\Flow\Security\Authentication\TokenInterface */ foreach ($this->getAuthenticationTokens() as $token) { if ($token->isAuthenticated() !== true) { continue; } $account = $token->getAccount(); if ($account === null) { continue; } if ($account !== null) { $accountRoles = $account->getRoles(); /** @var $currentRole Role */ foreach ($accountRoles as $currentRole) { if (!in_array($currentRole, $this->roles)) { $this->roles[$currentRole->getIdentifier()] = $currentRole; } /** @var $currentParentRole Role */ foreach ($currentRole->getAllParentRoles() as $currentParentRole) { if (!in_array($currentParentRole, $this->roles)) { $this->roles[$currentParentRole->getIdentifier()] = $currentParentRole; } } } } } } } return $this->roles; }