Merge branch 'user_impersonator'

This commit is contained in:
Jan Böhmer 2023-07-08 23:07:12 +02:00
commit 2362835275
14 changed files with 381 additions and 45 deletions

View file

@ -0,0 +1,72 @@
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2022 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Controller} from "@hotwired/stimulus";
import * as bootbox from "bootbox";
import "../../css/components/bootbox_extensions.css";
export default class extends Controller
{
static values = {
message: String,
title: String
}
connect()
{
this._confirmed = false;
this.element.addEventListener('click', this._onClick.bind(this));
}
_onClick(event)
{
//If a user has not already confirmed the deletion, just let turbo do its work
if (this._confirmed) {
this._confirmed = false;
return;
}
event.preventDefault();
event.stopPropagation();
const that = this;
bootbox.confirm({
title: this.titleValue,
message: this.messageValue,
callback: (result) => {
if (result) {
//Set a flag to prevent the dialog from popping up again and allowing turbo to submit the form
that._confirmed = true;
//Click the link
that.element.click();
} else {
that._confirmed = false;
}
}
});
}
}

View file

@ -21,6 +21,9 @@ security:
user_checker: App\Security\UserChecker
entry_point: form_login
# Enable user impersonation
switch_user: { role: CAN_SWITCH_USER }
two_factor:
auth_form_path: 2fa_login
check_path: 2fa_login_check

View file

@ -190,6 +190,9 @@ perms: # Here comes a list with all Permission names (they have a perm_[name] co
set_password:
label: "perm.users.set_password"
alsoSet: 'read'
impersonate:
label: "perm.users.impersonate"
alsoSet: ['set_password']
change_user_settings:
label: "perm.users.change_user_settings"
show_history:

View file

@ -64,6 +64,7 @@ class SecurityEventLogEntry extends AbstractLogEntry
6 => SecurityEvents::GOOGLE_DISABLED,
7 => SecurityEvents::TRUSTED_DEVICE_RESET,
8 => SecurityEvents::TFA_ADMIN_RESET,
9 => SecurityEvents::USER_IMPERSONATED,
];
public function __construct(string $type, string $ip_address, bool $anonymize = true)

View file

@ -48,6 +48,7 @@ use App\Events\SecurityEvents;
use App\Services\LogSystem\EventLogger;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
/**
* This subscriber writes entries to log if a security related event happens (e.g. the user changes its password).
@ -70,6 +71,7 @@ final class SecurityEventLoggerSubscriber implements EventSubscriberInterface
SecurityEvents::GOOGLE_DISABLED => 'google_disabled',
SecurityEvents::GOOGLE_ENABLED => 'google_enabled',
SecurityEvents::TFA_ADMIN_RESET => 'tfa_admin_reset',
SecurityEvents::USER_IMPERSONATED => 'user_impersonated',
];
}
@ -103,6 +105,11 @@ final class SecurityEventLoggerSubscriber implements EventSubscriberInterface
$this->addLog(SecurityEvents::U2F_REMOVED, $event);
}
public function user_impersonated(SecurityEvent $event): void
{
$this->addLog(SecurityEvents::USER_IMPERSONATED, $event);
}
public function u2f_added(SecurityEvent $event): void
{
$this->addLog(SecurityEvents::U2F_ADDED, $event);

View file

@ -0,0 +1,64 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2023 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\UserSystem\User;
use App\Events\SecurityEvent;
use App\Events\SecurityEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class SwitchUserEventSubscriber implements EventSubscriberInterface
{
public function __construct(private readonly EventDispatcherInterface $eventDispatcher)
{
}
public static function getSubscribedEvents()
{
return [
'security.switch_user' => 'onSwitchUser',
];
}
public function onSwitchUser(SwitchUserEvent $event): void
{
$target_user = $event->getTargetUser();
// We can only handle User objects
if (!$target_user instanceof User) {
return;
}
//We are only interested in impersonation (not unimpersonation)
if (!$event->getToken() instanceof SwitchUserToken) {
return;
}
$security_event = new SecurityEvent($target_user);
$this->eventDispatcher->dispatch($security_event, SecurityEvents::USER_IMPERSONATED);
}
}

View file

@ -78,6 +78,11 @@ final class PasswordChangeNeededSubscriber implements EventSubscriberInterface
return;
}
//If the user is impersonated, we don't need to redirect him
if ($this->security->isGranted('IS_IMPERSONATOR')) {
return;
}
//Abort if we dont need to redirect the user.
if (!$user->isNeedPwChange() && !static::TFARedirectNeeded($user)) {
return;

View file

@ -52,4 +52,6 @@ class SecurityEvents
final public const GOOGLE_DISABLED = 'security.google_disabled';
final public const TRUSTED_DEVICE_RESET = 'security.trusted_device_reset';
final public const TFA_ADMIN_RESET = 'security.2fa_admin_reset';
final public const USER_IMPERSONATED = 'security.user_impersonated';
}

View file

@ -0,0 +1,60 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2023 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Security\Voter;
use App\Entity\UserSystem\User;
use App\Services\UserSystem\PermissionManager;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class ImpersonateUserVoter extends Voter
{
public function __construct(private PermissionManager $permissionManager)
{
}
protected function supports(string $attribute, mixed $subject): bool
{
return $attribute == 'CAN_SWITCH_USER'
&& $subject instanceof UserInterface;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User || !$subject instanceof UserInterface) {
return false;
}
//An disabled user is not allowed to do anything...
if ($user->isDisabled()) {
return false;
}
return $this->permissionManager->inherit($user, 'users', 'impersonate') ?? false;
}
}

View file

@ -46,6 +46,10 @@ use App\Entity\UserSystem\User;
use App\Entity\LogSystem\AbstractLogEntry;
use App\Repository\LogEntryRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
@ -57,7 +61,9 @@ final class UserExtension extends AbstractExtension
{
private readonly LogEntryRepository $repo;
public function __construct(EntityManagerInterface $em)
public function __construct(EntityManagerInterface $em,
private readonly Security $security,
private readonly UrlGeneratorInterface $urlGenerator)
{
$this->repo = $em->getRepository(AbstractLogEntry::class);
}
@ -76,9 +82,41 @@ final class UserExtension extends AbstractExtension
new TwigFunction('last_editing_user', fn(AbstractDBElement $element): ?User => $this->repo->getLastEditingUser($element)),
/* Returns the user which has created the given entity. */
new TwigFunction('creating_user', fn(AbstractDBElement $element): ?User => $this->repo->getCreatingUser($element)),
new TwigFunction('impersonator_user', $this->getImpersonatorUser(...)),
new TwigFunction('impersonation_active', $this->isImpersonationActive(...)),
new TwigFunction('impersonation_path', $this->getImpersonationPath(...)),
];
}
/**
* This function returns the user which has impersonated the current user.
* If the current user is not impersonated, null is returned.
* @return User|null
*/
public function getImpersonatorUser(): ?User
{
$token = $this->security->getToken();
if ($token instanceof SwitchUserToken) {
return $token->getOriginalToken()->getUser();
}
return null;
}
public function isImpersonationActive(): bool
{
return $this->security->isGranted('IS_IMPERSONATOR');
}
public function getImpersonationPath(User $user, string $route_name = 'homepage'): string
{
if (! $this->security->isGranted('CAN_SWITCH_USER', $user)) {
throw new AccessDeniedException('You are not allowed to impersonate this user!');
}
return $this->urlGenerator->generate($route_name, ['_switch_user' => $user->getUsername()]);
}
/**
* This function/filter generates a path.
*/

View file

@ -37,23 +37,45 @@
<li class="nav-item dropdown">
<a href="#" class="dropdown-toggle link-anchor nav-link" data-bs-toggle="dropdown" role="button"
aria-haspopup="true" aria-expanded="false" id="navbar-user-dropdown-btn" data-bs-reference="window">
{% if app.user %}<i class="fa fa-user" aria-hidden="true"></i>{% else %}<i class="far fa-user"
aria-hidden="true"></i>{% endif %}
{% if app.user %} {# Logged in #}
{% if impersonation_active() %} {# Impersonated user #}
<i class="fa-solid fa-user-secret text-warning"></i>
{% else %}
<i class="fas fa-user" aria-hidden="true"></i>
{% endif %}
{% else %} {# Not logged in #}
<i class="far fa-user" aria-hidden="true"></i>
{% endif %}
<span class="caret"></span></a>
<ul class="dropdown-menu dropdown-menu-end" id="login-menu" aria-labelledby="navbar-user-dropdown-btn">
{% if app.user %}
<a class="dropdown-item disabled" href="#">{% trans %}user.loggedin.label{% endtrans %}
{{ helper.user_icon(app.user) }} <b>{{ app.user.firstName }} {{ app.user.lastName }}</b> (@{{ app.user.name }})</a>
<a class="dropdown-item" href="{{ path("user_settings") }}"><i class="fa fa-cogs fa-fw"
aria-hidden="true"></i> {% trans %}user.settings.label{% endtrans %}
{{ helper.user_icon(app.user) }} <b>{{ app.user.firstName }} {{ app.user.lastName }}</b> (@{{ app.user.name }})</a>
{% if impersonation_active() %}
{% set impersonator = impersonator_user() %}
<a class="dropdown-item disabled text-warning" href="#">{% trans %}user.impersonated_by.label{% endtrans %}
{{ helper.user_icon(impersonator) }} <b>{{ impersonator.firstName }} {{ impersonator.lastName }}</b> (@{{ impersonator.name }})</a>
{% endif %}
<a class="dropdown-item" href="{{ path("user_settings") }}">
<i class="fa fa-cogs fa-fw" aria-hidden="true"></i> {% trans %}user.settings.label{% endtrans %}
</a>
<a class="dropdown-item" href="{{ path("user_info_self") }}"><i
class="fa fa-info-circle fa-fw"
aria-hidden="true"></i> {% trans %}user.info.label{% endtrans %}</a>
<a class="dropdown-item" href="{{ path("user_info_self") }}">
<i class="fa fa-info-circle fa-fw" aria-hidden="true"></i> {% trans %}user.info.label{% endtrans %}</a>
<li role="separator" class="dropdown-divider"></li>
<a class="dropdown-item" href="{{ path('logout') }}" data-turbo="false" data-turbo-frame="_top"><i
class="fa fa-sign-out-alt fa-fw"
aria-hidden="true"></i> {% trans %}user.logout{% endtrans %}</a>
{% if impersonation_active() %}
<a class="dropdown-item" href="{{ impersonation_exit_path() }}" data-turbo="false" data-turbo-frame="_top">
<i class="fa fa-turn-up fa-fw" aria-hidden="true"></i> {% trans %}user.stop_impersonation{% endtrans %}
</a>
{% endif %}
<a class="dropdown-item" href="{{ path('logout') }}" data-turbo="false" data-turbo-frame="_top">
<i class="fa fa-sign-out-alt fa-fw" aria-hidden="true"></i> {% trans %}user.logout{% endtrans %}
</a>
{% else %}
<a class="dropdown-item"
href="{{ path('login', {'_target_path': app.request.pathinfo | remove_locale_from_path}) }}"

View file

@ -77,21 +77,22 @@
{{ form_start(form) }}
<ul class="nav nav-pills mb-2">
<li class="nav-item">
<a data-bs-toggle="tab" class="nav-link link-anchor active" href="#common">{% trans %}admin.common{% endtrans %}</a>
</li>
{% block additional_pills %}{% endblock %}
<li class="nav-item">
<a data-bs-toggle="tab" class="nav-link link-anchor" href="#attachments">{% trans %}admin.attachments{% endtrans %}</a>
</li>
{% if entity.parameters is defined %}
{% block nav_pills_container %}
<ul class="nav nav-pills mb-2">
<li class="nav-item">
<a data-bs-toggle="tab" class="nav-link link-anchor" href="#parameters">{% trans %}admin.parameters{% endtrans %}</a>
<a data-bs-toggle="tab" class="nav-link link-anchor active" href="#common">{% trans %}admin.common{% endtrans %}</a>
</li>
{% endif %}
</ul>
{% block additional_pills %}{% endblock %}
<li class="nav-item">
<a data-bs-toggle="tab" class="nav-link link-anchor" href="#attachments">{% trans %}admin.attachments{% endtrans %}</a>
</li>
{% if entity.parameters is defined %}
<li class="nav-item">
<a data-bs-toggle="tab" class="nav-link link-anchor" href="#parameters">{% trans %}admin.parameters{% endtrans %}</a>
</li>
{% endif %}
</ul>
{% endblock %}
<!-- Tab panes -->
<div class="tab-content">
@ -183,12 +184,12 @@
</fieldset>
</div>
<div id="mass_creation" class="tab-pane fade">
<div class="row">
<p class="text-muted offset-sm-3 col-sm-9">{% trans %}mass_creation.help{% endtrans %}</p>
</div>
{{ form(mass_creation_form) }}
<div id="mass_creation" class="tab-pane fade">
<div class="row">
<p class="text-muted offset-sm-3 col-sm-9">{% trans %}mass_creation.help{% endtrans %}</p>
</div>
{{ form(mass_creation_form) }}
</div>
{% endif %}

View file

@ -16,6 +16,20 @@
<li class="nav-item"><a data-bs-toggle="tab" class="nav-link link-anchor" href="#permissions">{% trans %}user.edit.permissions{% endtrans %}</a></li>
{% endblock %}
{% block nav_pills_container %}
<div class="d-flex justify-content-between">
{{ parent() }}
<div>
{% if entity.id is not null and is_granted('CAN_SWITCH_USER', entity) %}
<a href="{{ impersonation_path(entity) }}" data-turbo="false" class="btn btn-outline-warning"
{{ stimulus_controller('elements/link_confirm', {title: 'user.impersonate.confirm.title'|trans, message: 'user.impersonate.confirm.message'|trans}) }}
>{% trans %}user.impersonate.btn{% endtrans %}</a>
{% endif %}
</div>
</div>
{% endblock %}
{% block additional_controls %}
{{ form_row(form.group) }}
{{ form_row(form.first_name) }}

View file

@ -731,10 +731,10 @@
</notes>
<segment>
<source>user.edit.tfa.disable_tfa_message</source>
<target>This will disable &lt;b&gt;all active two-factor authentication methods of the user&lt;/b&gt; and delete the &lt;b&gt;backup codes&lt;/b&gt;!
&lt;br&gt;
The user will have to set up all two-factor authentication methods again and print new backup codes! &lt;br&gt;&lt;br&gt;
&lt;b&gt;Only do this if you are absolutely sure about the identity of the user (seeking help), otherwise the account could be compromised by an attacker!&lt;/b&gt;</target>
<target><![CDATA[This will disable <b>all active two-factor authentication methods of the user</b> and delete the <b>backup codes</b>!
<br>
The user will have to set up all two-factor authentication methods again and print new backup codes! <br><br>
<b>Only do this if you are absolutely sure about the identity of the user (seeking help), otherwise the account could be compromised by an attacker!</b>]]></target>
</segment>
</unit>
<unit id="02HvwiS" name="user.edit.tfa.disable_tfa.btn">
@ -11326,70 +11326,114 @@ Element 3</target>
</segment>
</unit>
<unit id="DGczoY6" name="tfa_u2f.add_key.registration_error">
<segment state="translated">
<segment>
<source>tfa_u2f.add_key.registration_error</source>
<target>An error occurred during the registration of the security key. Try again or use another security key!</target>
</segment>
</unit>
<unit id="ie0Ca0l" name="log.target_type.none">
<segment state="translated">
<segment>
<source>log.target_type.none</source>
<target>None</target>
</segment>
</unit>
<unit id="R2nX4ip" name="ui.darkmode.light">
<segment state="translated">
<segment>
<source>ui.darkmode.light</source>
<target>Light</target>
</segment>
</unit>
<unit id="3NHpuW3" name="ui.darkmode.dark">
<segment state="translated">
<segment>
<source>ui.darkmode.dark</source>
<target>Dark</target>
</segment>
</unit>
<unit id="4TGOK5_" name="ui.darkmode.auto">
<segment state="translated">
<segment>
<source>ui.darkmode.auto</source>
<target>Auto (decide based on system settings)</target>
</segment>
</unit>
<unit id="9N0N8aL" name="label_generator.no_lines_given">
<segment state="translated">
<segment>
<source>label_generator.no_lines_given</source>
<target>No text content given! The labels will remain empty.</target>
</segment>
</unit>
<unit id="RdFvZsb" name="user.password_strength.very_weak">
<segment state="translated">
<segment>
<source>user.password_strength.very_weak</source>
<target>Very weak</target>
</segment>
</unit>
<unit id="IBjmblZ" name="user.password_strength.weak">
<segment state="translated">
<segment>
<source>user.password_strength.weak</source>
<target>Weak</target>
</segment>
</unit>
<unit id="qSm_ID0" name="user.password_strength.medium">
<segment state="translated">
<segment>
<source>user.password_strength.medium</source>
<target>Medium</target>
</segment>
</unit>
<unit id="aWAaADS" name="user.password_strength.strong">
<segment state="translated">
<segment>
<source>user.password_strength.strong</source>
<target>Strong</target>
</segment>
</unit>
<unit id="Wa9CStW" name="user.password_strength.very_strong">
<segment state="translated">
<segment>
<source>user.password_strength.very_strong</source>
<target>Very strong</target>
</segment>
</unit>
<unit id="6OHd5fv" name="perm.users.impersonate">
<segment>
<source>perm.users.impersonate</source>
<target>Impersonate other users</target>
</segment>
</unit>
<unit id="ssn1H1A" name="user.impersonated_by.label">
<segment>
<source>user.impersonated_by.label</source>
<target>Impersonated by</target>
</segment>
</unit>
<unit id="inTlSge" name="user.stop_impersonation">
<segment>
<source>user.stop_impersonation</source>
<target>Stop impersonation</target>
</segment>
</unit>
<unit id="T3yB7KF" name="user.impersonate.btn">
<segment>
<source>user.impersonate.btn</source>
<target>Impersonate</target>
</segment>
</unit>
<unit id="sFE8diE" name="user.impersonate.confirm.title">
<segment>
<source>user.impersonate.confirm.title</source>
<target>Do you really want to impersonate this user?</target>
</segment>
</unit>
<unit id="MlJJSEo" name="user.impersonate.confirm.message">
<segment>
<source>user.impersonate.confirm.message</source>
<target>This will be logged. You should only do this with a good reason.
Please note, that you can not impersonate a disabled user. If you try you will get an "Access Denied" message.</target>
</segment>
</unit>
<unit id="df2ac87" name="log.type.security.user_impersonated">
<segment>
<source>log.type.security.user_impersonated</source>
<target>User impersonated</target>
</segment>
</unit>
</file>
</xliff>