1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* |
4
|
|
|
* This file is part of Aura for PHP. |
5
|
|
|
* |
6
|
|
|
* @license http://opensource.org/licenses/bsd-license.php BSD |
7
|
|
|
* |
8
|
|
|
*/ |
9
|
|
|
namespace Aura\Session; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* |
13
|
|
|
* Cross-site request forgery token tools. |
14
|
|
|
* |
15
|
|
|
* @package Aura.Session |
16
|
|
|
* |
17
|
|
|
*/ |
18
|
|
|
class CsrfToken |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* |
22
|
|
|
* A cryptographically-secure random value generator. |
23
|
|
|
* |
24
|
|
|
* @var RandvalInterface |
25
|
|
|
* |
26
|
|
|
*/ |
27
|
|
|
protected $randval; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* |
31
|
|
|
* Session segment for values in this class. |
32
|
|
|
* |
33
|
|
|
* @var Segment |
34
|
|
|
* |
35
|
|
|
*/ |
36
|
|
|
protected $segment; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* |
40
|
|
|
* Constructor. |
41
|
|
|
* |
42
|
|
|
* @param Segment $segment A segment for values in this class. |
43
|
|
|
* |
44
|
|
|
* @param RandvalInterface $randval A cryptographically-secure random |
45
|
|
|
* value generator. |
46
|
|
|
* |
47
|
|
|
*/ |
48
|
5 |
|
public function __construct(Segment $segment, RandvalInterface $randval) |
49
|
|
|
{ |
50
|
5 |
|
$this->segment = $segment; |
51
|
5 |
|
$this->randval = $randval; |
52
|
5 |
|
if (! $this->segment->get('value')) { |
53
|
5 |
|
$this->regenerateValue(); |
54
|
5 |
|
} |
55
|
5 |
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* |
59
|
|
|
* Checks whether an incoming CSRF token value is valid. |
60
|
|
|
* |
61
|
|
|
* @param string $value The incoming token value. |
62
|
|
|
* |
63
|
|
|
* @return bool True if valid, false if not. |
64
|
|
|
* |
65
|
|
|
*/ |
66
|
1 |
|
public function isValid($value) |
67
|
|
|
{ |
68
|
1 |
|
if (function_exists('hash_equals')) { |
69
|
|
|
return hash_equals($value, $this->getValue()); |
70
|
|
|
} |
71
|
|
|
|
72
|
1 |
|
return $value === $this->getValue(); |
73
|
1 |
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* |
77
|
|
|
* Gets the value of the outgoing CSRF token. |
78
|
|
|
* |
79
|
|
|
* @return string |
80
|
|
|
* |
81
|
|
|
*/ |
82
|
3 |
|
public function getValue() |
83
|
|
|
{ |
84
|
3 |
|
return $this->segment->get('value'); |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
/** |
88
|
|
|
* |
89
|
|
|
* Regenerates the value of the outgoing CSRF token. |
90
|
|
|
* |
91
|
|
|
* @return null |
92
|
|
|
* |
93
|
|
|
*/ |
94
|
5 |
|
public function regenerateValue() |
95
|
|
|
{ |
96
|
5 |
|
$hash = hash('sha512', $this->randval->generate()); |
97
|
5 |
|
$this->segment->set('value', $hash); |
98
|
5 |
|
} |
99
|
|
|
} |
100
|
|
|
|