1
|
|
|
<?php |
2
|
|
|
namespace WebStream\Annotation\Attributes; |
3
|
|
|
|
4
|
|
|
use WebStream\Annotation\Base\Annotation; |
5
|
|
|
use WebStream\Annotation\Base\IAnnotatable; |
6
|
|
|
use WebStream\Annotation\Base\IMethod; |
7
|
|
|
use WebStream\Container\Container; |
8
|
|
|
use WebStream\Exception\Extend\CsrfException; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* CsrfProtection |
12
|
|
|
* @author Ryuichi TANAKA. |
13
|
|
|
* @since 2015/05/08 |
14
|
|
|
* @version 0.7 |
15
|
|
|
* |
16
|
|
|
* @Annotation |
17
|
|
|
* @Target("METHOD") |
18
|
|
|
*/ |
19
|
|
|
class CsrfProtection extends Annotation implements IMethod |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var array<string> 注入アノテーション情報 |
23
|
|
|
*/ |
24
|
|
|
private $injectAnnotation; |
|
|
|
|
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var array<string> 読み込みアノテーション情報 |
28
|
|
|
*/ |
29
|
|
|
private $readAnnotation; |
|
|
|
|
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var array<string, string> CSRF定数定義 |
33
|
|
|
*/ |
34
|
|
|
private $csrfProtectionDefinitions = [ |
35
|
|
|
'tokenKey' => '__CSRF_TOKEN__', |
36
|
|
|
'tokenHeader' => 'X-CSRF-Token' |
37
|
|
|
]; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* {@inheritdoc} |
41
|
|
|
*/ |
42
|
|
|
public function onInject(array $injectAnnotation) |
43
|
|
|
{ |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* {@inheritdoc} |
48
|
|
|
*/ |
49
|
|
|
public function onMethodInject(IAnnotatable $instance, \ReflectionMethod $method, Container $container) |
50
|
|
|
{ |
51
|
|
|
$tokenByRequest = null; |
52
|
|
|
if (array_key_exists($this->csrfProtectionDefinitions['tokenKey'], $container->post)) { |
|
|
|
|
53
|
|
|
$tokenByRequest = $container->post[$this->csrfProtectionDefinitions['tokenKey']]; |
54
|
|
|
} elseif (array_key_exists($this->csrfProtectionDefinitions['tokenHeader'], $container->header)) { |
|
|
|
|
55
|
|
|
$tokenByRequest = $container->header[$this->csrfProtectionDefinitions['tokenHeader']]; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$tokenInSession = $container->session->get($this->csrfProtectionDefinitions['tokenKey']); |
|
|
|
|
59
|
|
|
$container->session->delete($this->csrfProtectionDefinitions['tokenKey']); |
60
|
|
|
|
61
|
|
|
// POSTリクエスト以外はチェックしない |
62
|
|
|
if ($container->requestMethod !== 'POST') { |
|
|
|
|
63
|
|
|
return; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
// リクエストトークン、セッショントークンが両方空はNG |
67
|
|
|
if ($tokenInSession === null && $tokenByRequest === null) { |
68
|
|
|
throw new CsrfException("Sent invalid CSRF token"); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
// リクエストトークンとセッショントークンが一致しない場合NG |
72
|
|
|
if ($tokenInSession !== $tokenByRequest) { |
73
|
|
|
throw new CsrfException("Sent invalid CSRF token"); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
This check marks private properties in classes that are never used. Those properties can be removed.