1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Enjoys\Forms\Elements; |
6
|
|
|
|
7
|
|
|
use Enjoys\Forms\Exception\CsrfAttackDetected; |
8
|
|
|
use Enjoys\Forms\Exception\ExceptionRule; |
9
|
|
|
use Enjoys\Forms\Form; |
10
|
|
|
use Enjoys\Forms\Rules; |
11
|
|
|
use Enjoys\Session\Session; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Включает защиту от CSRF. |
15
|
|
|
* Сross Site Request Forgery — «Подделка межсайтовых запросов», также известен как XSRF |
16
|
|
|
*/ |
17
|
|
|
class Csrf extends Hidden |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @throws ExceptionRule |
21
|
|
|
* @throws \Exception |
22
|
|
|
*/ |
23
|
81 |
|
public function __construct(private Session $session) |
24
|
|
|
{ |
25
|
81 |
|
$csrfSecret = $this->getCsrfSecret(); |
26
|
80 |
|
$token = $this->getCsrfToken($csrfSecret); |
27
|
|
|
|
28
|
|
|
|
29
|
80 |
|
parent::__construct(Form::_TOKEN_CSRF_, $token); |
30
|
|
|
|
31
|
80 |
|
$this->addRule( |
32
|
|
|
Rules::CALLBACK, |
33
|
|
|
'CSRF Attack detected', |
34
|
|
|
[ |
35
|
80 |
|
function (string $key) { |
36
|
2 |
|
if (password_verify($key, $this->getRequest()->getPostData(Form::_TOKEN_CSRF_, ''))) { |
|
|
|
|
37
|
1 |
|
return true; |
38
|
|
|
} |
39
|
1 |
|
throw new CsrfAttackDetected('CSRF Token is invalid'); |
40
|
|
|
}, |
41
|
|
|
$csrfSecret |
42
|
|
|
] |
43
|
|
|
); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @return true|void |
48
|
|
|
*/ |
49
|
77 |
|
public function prepare() |
50
|
|
|
{ |
51
|
77 |
|
if (!in_array($this->getForm()->getMethod(), ['POST', 'PUT', 'DELETE', 'PATCH'])) { |
52
|
|
|
//удаляем элемент, если был заранее создан |
53
|
|
|
//$this->getForm()->removeElement($this->getForm()->getElement(\Enjoys\Forms\Form::_TOKEN_CSRF_)); |
54
|
12 |
|
$this->getForm()->removeElement($this); |
55
|
|
|
|
56
|
|
|
//возвращаем true, чтобы не добавлять элемент. |
57
|
12 |
|
return true; |
58
|
|
|
} |
59
|
69 |
|
$this->unsetForm(); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @throws \Exception |
64
|
|
|
*/ |
65
|
81 |
|
private function getCsrfSecret(): string |
66
|
|
|
{ |
67
|
81 |
|
$secret = (string) $this->session->get('csrf_secret'); |
68
|
|
|
|
69
|
80 |
|
if (empty($secret)) { |
70
|
57 |
|
$secret = $this->generateSecret(); |
71
|
|
|
} |
72
|
|
|
|
73
|
80 |
|
return $secret; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
|
77
|
|
|
|
78
|
80 |
|
public function getCsrfToken(string $secret): string |
79
|
|
|
{ |
80
|
80 |
|
return password_hash($secret, PASSWORD_DEFAULT); |
|
|
|
|
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* @return string |
85
|
|
|
* @throws \Exception |
86
|
|
|
*/ |
87
|
57 |
|
private function generateSecret(): string |
88
|
|
|
{ |
89
|
57 |
|
$secret = base64_encode(random_bytes(32)); |
90
|
57 |
|
$this->session->set([ |
91
|
|
|
'csrf_secret' => $secret |
92
|
|
|
]); |
93
|
57 |
|
return $secret; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|