|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* eduVPN - End-user friendly VPN. |
|
5
|
|
|
* |
|
6
|
|
|
* Copyright: 2016-2017, The Commons Conservancy eduVPN Programme |
|
7
|
|
|
* SPDX-License-Identifier: AGPL-3.0+ |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace SURFnet\VPN\Common\Http; |
|
11
|
|
|
|
|
12
|
|
|
use SURFnet\VPN\Common\Http\Exception\HttpException; |
|
13
|
|
|
|
|
14
|
|
|
class CsrfProtectionHook implements BeforeHookInterface |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @return bool false if the CSRF protection was not used, i.e. not a |
|
18
|
|
|
* browser request, or a safe request method, true if the CSRF protection |
|
19
|
|
|
* was used, and successful |
|
20
|
|
|
*/ |
|
21
|
|
|
public function executeBefore(Request $request, array $hookData) |
|
22
|
|
|
{ |
|
23
|
|
|
if (!$request->isBrowser()) { |
|
24
|
|
|
// not a browser, no CSRF protected needed |
|
25
|
|
|
return false; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
// safe methods |
|
29
|
|
|
if (in_array($request->getRequestMethod(), ['GET', 'HEAD', 'OPTIONS'])) { |
|
30
|
|
|
return false; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
$uriAuthority = $request->getAuthority(); |
|
34
|
|
|
$httpOrigin = $request->getHeader('HTTP_ORIGIN', false, null); |
|
35
|
|
|
if (!is_null($httpOrigin)) { |
|
36
|
|
|
return $this->verifyOrigin($uriAuthority, $httpOrigin); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
$httpReferrer = $request->getHeader('HTTP_REFERER', false, null); |
|
40
|
|
|
if (!is_null($httpReferrer)) { |
|
41
|
|
|
return $this->verifyReferrer($uriAuthority, $httpReferrer); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
throw new HttpException('CSRF protection failed, no HTTP_ORIGIN or HTTP_REFERER', 400); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function verifyOrigin($uriAuthority, $httpOrigin) |
|
48
|
|
|
{ |
|
49
|
|
|
// the HTTP_ORIGIN MUST be equal to uriAuthority |
|
50
|
|
|
if ($uriAuthority !== $httpOrigin) { |
|
51
|
|
|
throw new HttpException('CSRF protection failed: unexpected HTTP_ORIGIN', 400); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
return true; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public function verifyReferrer($uriAuthority, $httpReferrer) |
|
58
|
|
|
{ |
|
59
|
|
|
// the HTTP_REFERER MUST start with uriAuthority |
|
60
|
|
|
if (0 !== strpos($httpReferrer, sprintf('%s/', $uriAuthority))) { |
|
61
|
|
|
throw new HttpException('CSRF protection failed: unexpected HTTP_REFERER', 400); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return true; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|