1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ubiquity\utils\http\session\protection; |
4
|
|
|
|
5
|
|
|
use Ubiquity\utils\http\session\AbstractSession; |
6
|
|
|
use Ubiquity\utils\http\UCookie; |
7
|
|
|
use Ubiquity\log\Logger; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Ubiquity\utils\http\session\protection$VerifyCsrfToken |
11
|
|
|
* This class is part of Ubiquity |
12
|
|
|
* |
13
|
|
|
* @author jc |
14
|
|
|
* @version 1.0.1 |
15
|
|
|
* |
16
|
|
|
*/ |
17
|
|
|
class VerifyCsrfToken implements VerifySessionCsrfInterface { |
18
|
|
|
private AbstractSession $sessionInstance; |
19
|
|
|
private const TOKEN_KEY = 'X-XSRF-TOKEN'; |
20
|
|
|
|
21
|
41 |
|
public function __construct(AbstractSession $sessionInstance) { |
22
|
41 |
|
$this->sessionInstance = $sessionInstance; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
protected function csrfErrorLog() { |
26
|
|
|
$context = []; |
27
|
|
|
$context ['HOST'] = $_SERVER ['HTTP_HOST']; |
28
|
|
|
$context ['REQUEST_URI'] = $_SERVER ['REQUEST_URI']; |
29
|
|
|
$context ['REQUEST_METHOD'] = $_SERVER ['REQUEST_METHOD']; |
30
|
|
|
$context ['cookie'] = $_COOKIE; |
31
|
|
|
Logger::error ( 'Session', 'CSRF protector validation failure!', 'startSession', $context ); |
32
|
|
|
} |
33
|
|
|
|
34
|
4 |
|
public function init(): void { |
35
|
4 |
|
$token = new CsrfToken (); |
36
|
4 |
|
$this->sessionInstance->set ( self::TOKEN_KEY, $token ); |
37
|
4 |
|
UCookie::set ( $token->getName (), $token->getValue (), null ); |
38
|
|
|
} |
39
|
|
|
|
40
|
3 |
|
public function clear(): void { |
41
|
3 |
|
$token = $this->sessionInstance->get ( self::TOKEN_KEY ); |
42
|
3 |
|
$this->sessionInstance->delete ( self::TOKEN_KEY ); |
43
|
3 |
|
if (isset ( $token )) { |
44
|
2 |
|
UCookie::delete ( $token->getName () ); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
41 |
|
public function start(): void { |
49
|
41 |
|
$token = $this->sessionInstance->get ( self::TOKEN_KEY ); |
50
|
41 |
|
if (isset ( $token )) { |
51
|
39 |
|
if (! $token instanceof CsrfToken || ! hash_equals ( $token->getValue (), '' . UCookie::get ( $token->getName () ) )) { |
52
|
|
|
if (Logger::isActive ()) { |
53
|
|
|
$this->csrfErrorLog (); |
54
|
|
|
} |
55
|
|
|
$this->clear(); |
56
|
|
|
$this->sessionInstance->terminate (); |
57
|
|
|
} |
58
|
39 |
|
return; |
59
|
|
|
} |
60
|
4 |
|
$this->init (); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public static function getLevel(): int { |
64
|
|
|
return 1; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
|