LDAP authentication support (#815)

This commit is contained in:
Kevin Papst
2019-06-07 22:48:39 +02:00
committed by GitHub
parent bcf1ebd778
commit 0c0e9c2f71
99 changed files with 3542 additions and 926 deletions

View File

@@ -0,0 +1,72 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Ldap;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Inspired by https://github.com/Maks3w/FR3DLdapBundle @ MIT License
*/
class FormLoginLdapFactory implements SecurityFactoryInterface
{
public function create(ContainerBuilder $container, $id, $config, $userProviderId, $defaultEntryPointId)
{
$authProviderId = $this->createAuthProvider($container, $id, $userProviderId);
$listenerId = $this->createListener($container, $id, $config);
return [$authProviderId, $listenerId, $defaultEntryPointId];
}
public function getPosition()
{
return 'pre_auth';
}
public function getKey()
{
return 'kimai_ldap';
}
public function addConfiguration(NodeDefinition $node)
{
}
protected function createAuthProvider(ContainerBuilder $container, $id, $userProviderId)
{
$provider = 'kimai_ldap.security.authentication.provider';
$providerId = $provider . '.' . $id;
$container
->setDefinition($providerId, new ChildDefinition($provider))
->replaceArgument(1, $id)
->replaceArgument(2, new Reference($userProviderId))
;
return $providerId;
}
protected function createListener(ContainerBuilder $container, $id, $config)
{
$listenerId = 'security.authentication.listener.form';
$listener = new ChildDefinition($listenerId);
$listener->replaceArgument(4, $id);
$listener->replaceArgument(5, $config);
$listenerId .= '.' . $id;
$container->setDefinition($listenerId, $listener);
return $listenerId;
}
}

View File

@@ -0,0 +1,131 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Ldap;
use App\Configuration\LdapConfiguration;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AuthenticationServiceException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* Inspired by https://github.com/Maks3w/FR3DLdapBundle @ MIT License
*/
class LdapAuthenticationProvider extends UserAuthenticationProvider
{
/**
* @var UserProviderInterface
*/
private $userProvider;
/**
* @var LdapManager
*/
private $ldapManager;
/**
* @var LdapConfiguration
*/
private $config;
public function __construct(UserCheckerInterface $userChecker, $providerKey, UserProviderInterface $userProvider, LdapManager $ldapManager, LdapConfiguration $config, $hideUserNotFoundExceptions = true)
{
parent::__construct($userChecker, $providerKey, $hideUserNotFoundExceptions);
$this->ldapManager = $ldapManager;
$this->config = $config;
$this->userProvider = $userProvider;
}
public function supports(TokenInterface $token)
{
if (!$this->config->isActivated()) {
return false;
}
return parent::supports($token);
}
protected function retrieveUser($username, UsernamePasswordToken $token)
{
$user = $token->getUser();
if ($user instanceof UserInterface) {
return $user;
}
try {
// this will always query the FOSUserBundle first...
// only first-time logins from LDAP user (not yet existing in local user database)
// will actually hit the LdapUserProvider
$user = $this->userProvider->loadUserByUsername($username);
// do not update the user here from LDAP, as we don't know if the user can be authenticated
} catch (UsernameNotFoundException $notFound) {
throw $notFound;
} catch (\Exception $repositoryProblem) {
$e = new AuthenticationServiceException($repositoryProblem->getMessage(), (int) $repositoryProblem->getCode(), $repositoryProblem);
$e->setToken($token);
throw $e;
}
return $user;
}
/**
* The updateUser() call should theoretically happen in retrieveUser() but that would require an additional
* $this->ldapManager->bind($user, $token->getCredentials())
* to check if the user is still valid.
*
* Symfony calls retrieveUser() before checkAuthentication()
* and we should not used ldap->search() before ldap->bind()
*
* @param UserInterface $user
* @param UsernamePasswordToken $token
* @throws LdapDriverException
*/
protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token)
{
$currentUser = $token->getUser();
$presentedPassword = $token->getCredentials();
if ($currentUser instanceof UserInterface) {
if ('' === $presentedPassword) {
throw new BadCredentialsException(
'The password in the token is empty. Check `erase_credentials` in your `security.yaml`'
);
}
if (!$this->ldapManager->bind($currentUser, $presentedPassword)) {
throw new BadCredentialsException('The credentials were changed from another session.');
}
} else {
if ('' === $presentedPassword) {
throw new BadCredentialsException('The presented password cannot be empty.');
}
if (!$this->ldapManager->bind($user, $presentedPassword)) {
throw new BadCredentialsException('The presented password is invalid.');
}
}
if ($user instanceof User && null !== $user->getPreferenceValue('ldap.dn')) {
try {
$this->ldapManager->updateUser($user);
} catch (LdapDriverException $ex) {
throw new BadCredentialsException('Fetching user data/roles failed, probably DN is expired.');
}
}
}
}

129
src/Ldap/LdapDriver.php Normal file
View File

@@ -0,0 +1,129 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Ldap;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Zend\Ldap\Exception\LdapException;
use Zend\Ldap\Ldap;
/**
* Inspired by https://github.com/Maks3w/FR3DLdapBundle @ MIT License
*/
class LdapDriver
{
/**
* @var Ldap
*/
private $driver;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @param Ldap $driver Initialized Zend::Ldap Object
* @param LoggerInterface $logger optional logger for write debug messages
*/
public function __construct(Ldap $driver, LoggerInterface $logger = null)
{
$this->driver = $driver;
$this->logger = $logger;
}
/**
* @param string $baseDn
* @param string $filter
* @param array $attributes
* @return array
* @throws LdapDriverException
*/
public function search(string $baseDn, string $filter, array $attributes = []): array
{
$attributes = array_unique(array_merge($attributes, ['+', '*']));
$this->logDebug('{action}({base_dn}, {filter}, {attributes})', [
'action' => 'ldap_search',
'base_dn' => $baseDn,
'filter' => $filter,
'attributes' => $attributes,
]);
try {
$this->driver->bind();
$entries = $this->driver->searchEntries($filter, $baseDn, Ldap::SEARCH_SCOPE_SUB, $attributes);
// searchEntries don't return 'count' key as specified by php native function ldap_get_entries()
$entries['count'] = count($entries);
} catch (LdapException $exception) {
$this->zendExceptionHandler($exception);
throw new LdapDriverException('An error occurred with the search operation.');
}
return $entries;
}
public function bind(UserInterface $user, string $password): bool
{
$bindDn = $user->getUsername();
try {
$this->logDebug('{action}({bindDn}, ****)', [
'action' => 'ldap_bind',
'bindDn' => $bindDn,
]);
$bind = $this->driver->bind($bindDn, $password);
return $bind instanceof Ldap;
} catch (LdapException $exception) {
$this->zendExceptionHandler($exception, $password);
}
return false;
}
/**
* Treat a Zend Ldap Exception.
*/
protected function zendExceptionHandler(LdapException $exception, string $password = null): void
{
$sanitizedException = null !== $password ? new SanitizingException($exception, $password) : $exception;
switch ($exception->getCode()) {
// Error level codes
case LdapException::LDAP_SERVER_DOWN:
if ($this->logger) {
$this->logger->error('{exception}', ['exception' => $sanitizedException]);
}
break;
// Other level codes
default:
$this->logDebug('{exception}', ['exception' => $sanitizedException]);
break;
}
}
/**
* Log debug messages if the logger is set.
*
* @param string $message
* @param array $context
*/
private function logDebug(string $message, array $context = []): void
{
if (null === $this->logger) {
return;
}
$this->logger->debug($message, $context);
}
}

View File

@@ -0,0 +1,18 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Ldap;
class LdapDriverException extends \Exception
{
public function __construct($message)
{
parent::__construct($message);
}
}

165
src/Ldap/LdapManager.php Normal file
View File

@@ -0,0 +1,165 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Ldap;
use App\Configuration\LdapConfiguration;
use App\Entity\User;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Inspired by https://github.com/Maks3w/FR3DLdapBundle @ MIT License
*/
class LdapManager
{
/**
* @var LdapConfiguration
*/
protected $config;
/**
* @var LdapDriver
*/
protected $driver;
/**
* @var array
*/
protected $params = [];
/**
* @var LdapUserHydrator
*/
protected $hydrator;
public function __construct(LdapDriver $driver, LdapUserHydrator $hydrator, LdapConfiguration $config)
{
$this->params = $config->getUserParameters();
$this->config = $config;
$this->driver = $driver;
$this->hydrator = $hydrator;
}
/**
* Only executed for unknown local users.
*
* @param string $username
* @return User|null
* @throws \Exception
*/
public function findUserByUsername(string $username): ?UserInterface
{
return $this->findUserBy([$this->params['usernameAttribute'] => $username]);
}
/**
* @param array $criteria
* @return User|null
* @throws LdapDriverException
*/
public function findUserBy(array $criteria): ?UserInterface
{
$filter = $this->buildFilter($criteria);
$entries = $this->driver->search($this->params['baseDn'], $filter);
if ($entries['count'] > 1) {
throw new LdapDriverException('This search must only return a single user');
}
if (0 === $entries['count']) {
return null;
}
// do not updateUser() here, as this would happen before bind()
return $this->hydrator->hydrate($entries[0]);
}
protected function buildFilter(array $criteria, string $condition = '&'): string
{
$filters = [];
$filters[] = $this->params['filter'];
foreach ($criteria as $key => $value) {
$value = ldap_escape($value, '', LDAP_ESCAPE_FILTER);
$filters[] = sprintf('(%s=%s)', $key, $value);
}
return sprintf('(%s%s)', $condition, implode($filters));
}
public function bind(UserInterface $user, string $password): bool
{
return $this->driver->bind($user, $password);
}
/**
* This method does all the heavy lifting:
* - searching for latest 'dn'
* - syncing user attributes
* - syncing roles
*
* @param User $user
* @throws LdapDriverException
*/
public function updateUser(User $user)
{
$baseDn = $user->getPreferenceValue('ldap.dn');
$filter = '(objectClass=*)';
if (null === $baseDn) {
throw new LdapDriverException('This account is not a registered LDAP user');
}
// always look up the users current DN first, as the cached DN might have been renamed in LDAP
$userFresh = $this->findUserByUsername($user->getUsername());
if (null === $userFresh || null === ($baseDn = $userFresh->getPreferenceValue('ldap.dn'))) {
throw new LdapDriverException(sprintf('Failed fetching user DN for %s', $user->getUsername()));
}
$user->setPreferenceValue('ldap.dn', $baseDn);
$entries = $this->driver->search($baseDn, $filter);
if ($entries['count'] > 1) {
throw new LdapDriverException('This search must only return a single user');
}
if (0 === $entries['count']) {
return;
}
$this->hydrator->hydrateUser($user, $entries[0]);
$roleParameter = $this->config->getRoleParameters();
if (null === $roleParameter['baseDn']) {
return;
}
$param = $roleParameter['usernameAttribute'];
if (!isset($entries[0][$param]) && $param !== 'dn') {
$param = 'dn';
}
$roleValue = $entries[0][$param];
if (is_array($roleValue)) {
$roleValue = $roleValue[0];
}
$roles = $this->getRoles($roleValue, $roleParameter);
if (!empty($roles)) {
$this->hydrator->hydrateRoles($user, $roles);
}
}
protected function getRoles(string $dn, array $roleParameter): array
{
$filter = $roleParameter['filter'] ?? '';
return $this->driver->search(
$roleParameter['baseDn'],
sprintf('(&%s(%s=%s))', $filter, $roleParameter['userDnAttribute'], $dn),
[$roleParameter['nameAttribute']]
);
}
}

View File

@@ -0,0 +1,144 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Ldap;
use App\Configuration\LdapConfiguration;
use App\Entity\User;
use App\Security\RoleService;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Inspired by https://github.com/Maks3w/FR3DLdapBundle @ MIT License
*/
class LdapUserHydrator
{
/**
* @var LdapConfiguration
*/
private $config;
/**
* @var RoleService
*/
private $roles;
public function __construct(LdapConfiguration $config, RoleService $roles)
{
$this->config = $config;
$this->roles = $roles;
}
protected function createUser(): User
{
$user = new User();
$user->setEnabled(true);
return $user;
}
public function hydrate(array $ldapEntry): User
{
$user = $this->createUser();
$this->hydrateUser($user, $ldapEntry);
return $user;
}
public function hydrateUser(User $user, array $ldapEntry)
{
$userParams = $this->config->getUserParameters();
$attributeMap = $userParams['attributes'];
$attributeMap = array_merge(
[
['ldap_attr' => $userParams['usernameAttribute'], 'user_method' => 'setUsername'],
],
$attributeMap
);
$this->hydrateUserWithAttributesMap($user, $ldapEntry, $attributeMap);
if (null === $user->getEmail()) {
$user->setEmail($user->getUsername());
}
// prevent that users will define a password for the internal account
$user->setPassword('');
$user->setPreferenceValue('ldap.dn', $ldapEntry['dn']);
}
/**
* @param User $user
* @param array $entries
*/
public function hydrateRoles(User $user, array $entries)
{
$roleParams = $this->config->getRoleParameters();
$allowedRoles = $this->roles->getAvailableNames();
$groupNameMapping = $roleParams['groups'];
$roleNameAttr = $roleParams['nameAttribute'];
$roles = [];
for ($i = 0; $i < $entries['count']; $i++) {
$roleName = $entries[$i][$roleNameAttr][0];
$mapped = false;
foreach ($groupNameMapping as $attr) {
if ($roleName === $attr['ldap_value']) {
$roleName = $attr['role'];
$mapped = true;
}
}
if (!$mapped) {
$roleName = sprintf('ROLE_%s', self::slugify($roleName));
}
if (!in_array($roleName, $allowedRoles)) {
continue;
}
$roles[] = $roleName;
}
$user->setRoles($roles);
}
private static function slugify(string $role): string
{
$role = preg_replace('/\W+/', '_', $role);
$role = trim($role, '_');
$role = strtoupper($role);
return $role;
}
protected function hydrateUserWithAttributesMap(UserInterface $user, array $ldapUserAttributes, array $attributeMap)
{
/** @var array $attr */
foreach ($attributeMap as $attr) {
if (!array_key_exists($attr['ldap_attr'], $ldapUserAttributes)) {
continue;
}
$ldapValue = $ldapUserAttributes[$attr['ldap_attr']];
if (array_key_exists('count', $ldapValue)) {
unset($ldapValue['count']);
}
if (1 === count($ldapValue)) {
$value = array_shift($ldapValue);
} else {
$value = $ldapValue;
}
$user->{$attr['user_method']}($value);
}
}
}

View File

@@ -0,0 +1,120 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Ldap;
use App\Configuration\LdapConfiguration;
use App\Entity\User;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* Overwritten to be able to deactivate LDAP via config switch.
*
* Inspired by https://github.com/Maks3w/FR3DLdapBundle @ MIT License
*/
class LdapUserProvider implements UserProviderInterface
{
/**
* @var bool
*/
protected $activated = false;
/**
* @var LdapManager
*/
protected $ldapManager;
/**
* @var LoggerInterface|null
*/
protected $logger;
public function __construct(LdapManager $ldapManager, LdapConfiguration $config, LoggerInterface $logger = null)
{
$this->ldapManager = $ldapManager;
$this->logger = $logger;
$this->activated = $config->isActivated();
}
public function loadUserByUsername($username)
{
// this method is called at least for unknown user, no matter what supportsClass() returns,
// so we have to check if LDAP is activated here as well
if (!$this->activated) {
$ex = new UsernameNotFoundException(sprintf('LDAP is deactivated, user "%s" not searched', $username));
$ex->setUsername($username);
throw $ex;
}
$user = $this->ldapManager->findUserByUsername($username);
if (empty($user)) {
$this->logInfo('User {username} {result} on LDAP', [
'action' => 'loadUserByUsername',
'username' => $username,
'result' => 'not found',
]);
$ex = new UsernameNotFoundException(sprintf('User "%s" not found', $username));
$ex->setUsername($username);
throw $ex;
}
$this->logInfo('User {username} {result} on LDAP', [
'action' => 'loadUserByUsername',
'username' => $username,
'result' => 'found',
]);
return $user;
}
public function refreshUser(UserInterface $user)
{
if (!($user instanceof User) || !$this->supportsClass(get_class($user))) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}
if (null === $user->getPreferenceValue('ldap.dn')) {
throw new UnsupportedUserException(sprintf('Account "%s" is not a registered LDAP user.', $user->getUsername()));
}
try {
$this->ldapManager->updateUser($user);
} catch (LdapDriverException $ex) {
throw new UnsupportedUserException(sprintf('Failed to refresh user "%s", probably DN is expired.', $user->getUsername()));
}
return $user;
}
public function supportsClass($class)
{
if (!$this->activated) {
return false;
}
return $class === User::class || $class === 'App\Entity\User';
}
/**
* Log a message into the logger if this exists.
*/
private function logInfo(string $message, array $context = []): void
{
if (!$this->logger) {
return;
}
$this->logger->info($message, $context);
}
}

View File

@@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Ldap;
/**
* Inspired by https://github.com/Maks3w/FR3DLdapBundle @ MIT License
*/
class SanitizingException extends \Exception
{
protected $actualException;
protected $secret;
public function __construct(\Exception $actualException, $secret)
{
parent::__construct(
$this->stripSecret($actualException->getMessage(), $secret),
$actualException->getCode()
);
$this->actualException = $actualException;
$this->secret = $secret;
}
protected function stripSecret(string $message, string $secret)
{
return str_replace($secret, '****', $message);
}
public function __toString()
{
return $this->stripSecret($this->actualException->__toString(), $this->secret);
}
}

29
src/Ldap/ZendLdap.php Normal file
View File

@@ -0,0 +1,29 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Ldap;
use App\Configuration\LdapConfiguration;
use Zend\Ldap\Ldap;
/**
* Overwritten to prevent errors in case:
* LDAP is deactivated and LDAP extension is not loaded
*/
class ZendLdap extends Ldap
{
public function __construct(LdapConfiguration $config)
{
if (!$config->isActivated()) {
return;
}
parent::__construct($config->getConnectionParameters());
}
}