How to allow to use the master password in Laravel 8 by overriding Auth structure?
Asked Answered
G

4

7

I've got a website written in pure PHP and now I'm learning Laravel, so I'm remaking this website again to learn the framework. I have used built-in Auth Fasade to make authentication. I would like to understand, what's going on inside, so I decided to learn more by customization. Now I try to make a master password, which would allow direct access to every single account (as it was done in the past).

Unfortunately, I can't find any help, how to do that. When I was looking for similar issues I found only workaround solutions like login by admin and then switching to another account or solution for an older version of Laravel etc.

I started studying the Auth structure by myself, but I lost and I can't even find a place where the password is checked. I also found the very expanded solution on GitHub, so I tried following it step by step, but I failed to make my own, shorter implementation of this. In my old website I needed only one row of code for making a master password, but in Laravel is a huge mountain of code with no change for me to climb on it.

As far I was trying for example changing all places with hasher->check part like here:

protected function validateCurrentPassword($attribute, $value, $parameters)
{
    $auth = $this->container->make('auth');
    $hasher = $this->container->make('hash');

    $guard = $auth->guard(Arr::first($parameters));

    if ($guard->guest()) {
        return false;
    }

    return $hasher->check($value, $guard->user()->getAuthPassword());
}

for

return ($hasher->check($value, $guard->user()->getAuthPassword()) || $hasher->check($value, 'myHashedMasterPasswordString'));

in ValidatesAttributes, DatabaseUserProvider, EloquentUserProvider and DatabaseTokenRepository. But it didn't work. I was following also all instances of the getAuthPassword() code looking for more clues.

My other solution was to place somewhere a code like this:

if(Hash::check('myHashedMasterPasswordString',$given_password))
   Auth::login($user);

But I can't find a good place for that in middlewares, providers, or controllers.

I already learned some Auth features, for example, I succeed in changing email authentication for using user login, but I can't figure out, how the passwords are working here. Could you help me with the part that I'm missing? I would appreciate it if someone could explain to me which parts of code should I change and why (if it's not so obvious).

I would like to follow code execution line by line, file by file, so maybe I would find a solution by myself, but I feel like I'm jumping everywhere without any idea, how this all is connected with each other.

Galenism answered 17/12, 2021 at 13:5 Comment(8)
I can't help you with the specific parts, but the general concept of one user acting as if they were another user (usually of equal or lesser privileges) is called "impersonation", and if you search for that you'll find a bunch of examples. As a system administrator, a master password is scary, and although impersonation is also scary, it is at least auditable.Overgrow
@ChrisHaas Thanks for pointing that out, I didn't know that it is called so, I check it by the way with pleasure even if it doesn't fully solve my problem. In my case, I would like to log in directly to any account without logging into the admin account first. Maybe I should add, that we are using LAN and it's for internal purposes only, so this time I value quick access more than the security issues.Galenism
the password is checked against the hash in the 'User Provider', EloquentUserProvider for example, at validateCredentials ... if you were looking for where that happened ... SessionGuard@attempt -> @hasValidCredentials -> UserProvider@validateCredentialsMeridional
I have already changed validateCredentials methods in two places, in DatabaseUserProvider and EloquentUserProvider (I simply add there return true every time just for tests), but it still shows These credentials do not match our records message.Galenism
@Galenism so simply asking, if the logged in user is system administrator, he/she can impersonate as any other user, right?Fruin
Try this: github.com/404labfr/laravel-impersonateFruin
@Fruin As I pointed out in previous comment _ I would like to log in directly to any account without logging into the admin account first_. So short answer is: if the user is logging using master password, log in him even if it doesn't match his own password.Galenism
@Fruin Advantages of this approach will be i. a. 1) saving time, 2) if real user is standing next to admin, he won't see his admin-home page, 3) there will be no chance to reimpersonate back to admin.Galenism
I
2

First of all, before answering the question, I must say that I read the comments following your question and I got surprised that the test you made returning true in validateCredentials() method in EloquentUserProvider and DatabaseUserProvider classes had failed.

I tried it and it worked as expected (at least in Laravel 8). You just need a an existing user (email) and you will pass the login with any non-empty password you submit.

Which of both classes are you really using (because you don't need to edit both)? It depends of the driver configuration in your auth.php configuration file.

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

As you already thought, you can simply add an "or" to the validation in the validateCredentials() method, comparing the $credentials['password'] to your custom master password.

Having said that, and confirming that's the place where you'd have to add your master password validation, I think the best (at least my recommended) way to accomplish your goal is that you track the classes/methods, starting from the official documentation, which recommends you to execute the login through the Auth facade:

use Illuminate\Support\Facades\Auth;

class YourController extends Controller
{
    public function authenticate(Request $request)
    {
        //
        if (Auth::attempt($credentials)) {
            //
        }
        //
    }
}

You would start by creating your own controller (or modifying an existing one), and creating your own Auth class, extending from the facade (which uses the __callStatic method to handle calls dynamically):

use YourNamespace\YourAuth;

class YourController extends Controller
{
    //
    public function authenticate(Request $request)
    {
        //
        if (YourAuth::attempt($credentials)) {
            //
        }
        //
    }
}
//
 * @method static \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard guard(string|null $name = null)
//

class YourAuth extends Illuminate\Support\Facades\Facade
{
// 
}

And use the same logic, overriding all the related methods in the stack trace until you get to use the validateCredentials() method, which in the end will also be overrided in your own CustomEloquentUserProvider class which will be extending fron the original EloquentUserProvider.

This way, you will have accomplished your goal, and kept a correct override of the whole process, being able to update your laravel installation without the risk of loosing your work. Worst case scenario? You'll have to fix any of your overriding methods in case that any of them has drastically changed in the original classes (which has a ver low chance to happen).

Tips

When making the full overriding, maybe you'll prefer to add some significant changes, like evading the interfaces and going straight for the classes and methods you really need. For example: Illuminate/Auth/SessionGuard::validate.

You would also wish to save your master password in an environment variable in your .env file. For example:

// .env
MASTER_PASSWORD=abcdefgh

and then call it with the env() helper:

if ($credentials['password'] === env('MASTER_PASSWORD')) {
//
}

Nice journey!

Interaction answered 30/12, 2021 at 0:59 Comment(1)
Thank you for referring to the comments and for wide explanations :)Galenism
F
1

A more complete solution would be the define a custom guard and use that instead of trying to create your own custom auth mechanism.

Firstly, define a new guard within config/auth.php:

'guards' => [
    'master' => [
        'driver' => 'session',
        'provider' => 'users',
    ]
],

Note: It uses the exact same setup as the default web guard.

Secondly, create a new guard located at App\Guards\MasterPasswordGuard:

<?php

namespace App\Guards;

use Illuminate\Auth\SessionGuard;
use Illuminate\Support\Facades\Auth;

class MasterPasswordGuard extends SessionGuard
{
    public function attempt(array $credentials = [], $remember = false): bool
    {
        if ($credentials['password'] === 'master pass') {
            return true;
        } else {
            return Auth::guard('web')->attempt($credentials, $remember);
        }
    }
}

Note:

  • You can replace 'master pass' with an env/config variable or simply hardcode it. In this case I'm only checking for a specific password. You might want to pair that with an email check too
  • If the master pass isn't matched it falls back to the default guard which checks the db

Thirdly, register this new guard in the boot method of AuthServiceProvider:

Auth::extend('master', function ($app, $name, array $config) {
    return new MasterPasswordGuard(
        $name,
        Auth::createUserProvider($config['provider']),
        $app->make('session.store'),
        $app->request
    );
});

Fourthly, in your controller or wherever you wish to verify the credentials, use:

Auth::guard('master')->attempt([
    'email' => 'email',
    'password' => 'pass'
]);

Example

Register the route:

Route::get('test', [LoginController::class, 'login']);

Create your controller:

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;

class LoginController
{
    public function login()
    {
        dd(
            Auth::guard('master')->attempt([
                'email' => '[email protected]',
                'password' => 'master pass'
            ]),

            Auth::guard('master')->attempt([
                'email' => '[email protected]',
                'password' => 'non master'
            ]),
        );
    }
}

and if you hit this endpoint, you'll see:

Where true is where the master password was used and false is where it tried searching for a user.


Final Thoughts

  • From a security standpoint you're opening yourself up to another attack vector and one which is extremely detrimental to the security of your system and the privacy of your users' data. It would be wise to reconsider.
  • This validation of credentials should ideally be separated from your controller and moved to a Request class. It'll help keep your codebase more clean and maintainable.
Fico answered 3/1, 2022 at 4:29 Comment(2)
The most elegant might be, to only permit this on a staging site, but not the live site.Halle
Thank you for your efforts. I appreciate your literal step-by-step guide. Since I'm a beginner in Laravel, Anibal's answer helped me the most, thanks to wide explanations, but your answer also gave me a lot of knowledge about the inner structure of the framework.Galenism
H
0

Instead of trying to roll your own, you could as well as use a library, which does just that:
laravel-impersonate (it's better tested already). This also comes with Blade directives; just make sure to configure it properly, because by default anybody can impersonate anybody else.


There even is (or was) rudimentary support available with: Auth::loginAsId().

Halle answered 3/1, 2022 at 5:14 Comment(0)
S
-1

Here is a possible solution.

To use a master password, you can use the loginUsingId function

Search the user by username, then check if the password matches the master password, and if so, log in with the user ID that it found

public function loginUser($parameters)
{
    $myMasterHashPassword = "abcde";
    $username = $parameters->username;
    $password = $parameters->password;
    $user = User::where('username', $username)->first();
    if (!$user) {
        return response("Username not found", 404);
    }
    if (Hash::check($myMasterHashPassword, $password)) {
        Auth::loginUsingId($user->id);
    }
}
Stubbs answered 29/12, 2021 at 2:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.