ALERT!
Click here to register with a few steps and explore all our cool stuff we have to offer!

Jump to content



Photo

[PHP/Symfony] Simple session hijack protection


  • Please log in to reply
[PHP/Symfony] Simple session hijack protection

#1

inao
inao
    Offline
    17
    Rep
    171
    Likes

    Hello xd

Posts: 214
Threads: 48
Joined: Jan 21, 2017
Credits: 0

Seven years registered
#1

Hello y'all,

after some inactivity here, I've decided to post my session protection solution. I guess it's not the best one, but I would say it's really secure one. Also, this is inspired by the last events that happened to LinusTechTips tbh. Unsure why Google doesn't to something like this already lol

What will this code do is, it will save client IP address on login and on every kernel.request event, take it from session and from current request. If there is a mismatch, session will get destroyed immediately. This should in theory prevent any info-stealers from yoinking sessions from your clients.

 

This works on events that are built-in to Symfony, meaning there is little effort to implement this solution to your existing project and it's an effective one I would say..

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class SessionSecurityListener implements EventSubscriberInterface
{
    public function onKernelRequest(RequestEvent $requestEvent): RequestEvent
    {
        $request = $requestEvent->getRequest();
        $ipSession = $request->getSession()->get("security.login_ip");
        if($ipSession !== null){
            $ipRequest = $request->getClientIp();
            if(strcmp($ipSession, $ipRequest) !== 0){
                $request->getSession()->invalidate();
                $requestEvent->setResponse(new RedirectResponse('/'));
            }
        }
        return $requestEvent;
    }

    public static function getSubscribedEvents(): array
    {
        return [KernelEvents::REQUEST => 'onKernelRequest'];
    }
}

This was your event. But now, you will need to set the IP somewhere. I suggest to you to save it on successful user login. So, something like this.

    #[Route(path: '/login', name: 'security-login')]
    public function login(): Response
    {
        //your flow..
        $request->getSession()->set("security.login_ip", $request->getClientIp());
        
        return $this->render(..); //last render in the function
    }

I hope this will help you to protect your apps :)

Good luck with your development.


Edited by inao, 24 March 2023 - 11:06 PM.

  • 0


 Users browsing this thread: