Completed
Push — master ( 91fdab...75a7b9 )
by
unknown
13:37
created

EventListener/SessionSecurityListener.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\AdminBundle\EventListener;
4
5
use Psr\Log\LoggerInterface;
6
use Symfony\Component\HttpFoundation\Request;
7
use Symfony\Component\HttpFoundation\Session\SessionInterface;
8
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
9
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
10
use Symfony\Component\HttpKernel\HttpKernelInterface;
11
12
class SessionSecurityListener
13
{
14
    /**
15
     * @var LoggerInterface
16
     */
17
    private $logger;
18
19
    /**
20
     * @var bool
21
     */
22
    private $ipCheck;
23
24
    /**
25
     * @var bool
26
     */
27
    private $userAgentCheck;
28
29
    /**
30
     * @var string
31
     */
32
    private $ip;
33
34
    /**
35
     * @var string
36
     */
37
    private $userAgent;
38
39
    /**
40
     * @param bool $ipCheck
41
     * @param bool $userAgentCheck
42
     * @param LoggerInterface $logger
43
     */
44
    public function __construct($ipCheck, $userAgentCheck, LoggerInterface $logger)
45
    {
46
        $this->ipCheck = $ipCheck;
47
        $this->userAgentCheck = $userAgentCheck;
48
        $this->logger = $logger;
49
    }
50
51
    /**
52
     * @param FilterResponseEvent $event
53
     */
54
    public function onKernelResponse(FilterResponseEvent $event)
55
    {
56
        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
57
            return;
58
        }
59
60
        // Make sure the ip and user agent is stored in the session
61
        $request = $event->getRequest();
62
        if ($request->hasSession() && $request->getSession()->isStarted()) {
63
            $session = $request->getSession();
64
            if ($this->ipCheck && !$session->has('kuma_ip')) {
65
                $session->set('kuma_ip', $this->getIp($request));
66
            }
67
            if ($this->userAgentCheck && !$session->has('kuma_ua')) {
68
                $session->set('kuma_ua', $this->getUserAgent($request));
69
            }
70
        }
71
    }
72
73
    /**
74
     * @param GetResponseEvent $event
75
     */
76
    public function onKernelRequest(GetResponseEvent $event)
77
    {
78
        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
79
            return;
80
        }
81
82
        $request = $event->getRequest();
83
        if ($request->hasSession() && $request->getSession()->isStarted()) {
84
            $session = $request->getSession();
85
86
            // Check that the ip matches
87 View Code Duplication
            if ($this->ipCheck && $session->has('kuma_ip') && $session->get('kuma_ip') != $this->getIp($request)) {
88
                $this->logger->error(sprintf(
89
                    "Session ip '%s' does not match with request ip '%s', invalidating the current session",
90
                    $session->get('kuma_ip'),
91
                    $this->getIp($request)
92
                ));
93
                $this->invalidateSession($session, $request);
94
            }
95
96
            // Check that the user agent matches
97 View Code Duplication
            if ($this->userAgentCheck && $session->has('kuma_ua') && $session->get('kuma_ua') != $this->getUserAgent($request)) {
98
                $this->logger->error(sprintf(
99
                    "Session user agent '%s' does not match with request user agent '%s', invalidating the current session",
100
                    $session->get('kuma_ua'),
101
                    $this->getUserAgent($request)
102
                ));
103
                $this->invalidateSession($session, $request);
104
            }
105
        }
106
    }
107
108
    /**
109
     * @param SessionInterface $session
110
     * @param Request $request
111
     */
112
    private function invalidateSession(SessionInterface $session, Request $request)
113
    {
114
        $session->invalidate();
115
        $session->set('kuma_ip', $this->getIp($request));
116
        $session->set('kuma_ua', $this->getUserAgent($request));
117
    }
118
119
    /**
120
     * @param Request $request
121
     * @return string
122
     */
123
    private function getIp(Request $request)
124
    {
125
        if (!$this->ip) {
126
            $forwarded = $request->server->get('HTTP_X_FORWARDED_FOR');
127
            if (strlen($forwarded) > 0) {
128
                $parts = explode(',', $forwarded);
129
                $parts = array_map('trim', $parts);
130
                $parts = array_filter($parts);
131
                if (count($parts) > 0) {
132
                    $ip = $parts[0];
133
                }
134
            }
135
            if (empty($ip)) {
136
                $ip = $request->getClientIp();
137
            }
138
            $this->ip = $ip;
139
        }
140
141
        return $this->ip;
142
    }
143
144
    /**
145
     * @param Request $request
146
     * @return array|string
0 ignored issues
show
Consider making the return type a bit more specific; maybe use string|string[].

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
147
     */
148
    private function getUserAgent(Request $request)
149
    {
150
        if (!$this->userAgent) {
151
            $this->userAgent = $request->headers->get('User-Agent');
0 ignored issues
show
Documentation Bug introduced by
It seems like $request->headers->get('User-Agent') can also be of type array<integer,string>. However, the property $userAgent is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
152
        }
153
154
        return $this->userAgent;
155
    }
156
}
157