forked from StartupAPI/users
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCookieStorage.php
More file actions
249 lines (229 loc) · 7.98 KB
/
CookieStorage.php
File metadata and controls
249 lines (229 loc) · 7.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
<?php
/**
* Store tamper-proof strings in an HTTP cookie
*
* Source: http://code.google.com/p/mrclay/source/browse/trunk/php/MrClay/CookieStorage.php
*
* <code>
* $storage = new MrClay_CookieStorage(array(
* 'secret' => '67676kmcuiekihbfyhbtfitfytrdo=op-p-=[hH8'
* ));
* if ($storage->store('user', 'id:62572,email:[email protected],name:Bob')) {
* // cookie OK length and no complaints from setcookie()
* } else {
* // check $storage->errors
* }
*
* // later request
* $user = $storage->fetch('user');
* if (is_string($user)) {
* // valid cookie
* $age = time() - $storage->getTimestamp('user');
* } else {
* if (false === $user) {
* // data was altered!
* } else {
* // cookie not present
* }
* }
*
* // encrypt cookie contents
* $storage = new MrClay_CookieStorage(array(
* 'secret' => '67676kmcuiekihbfyhbtfitfytrdo=op-p-=[hH8'
* ,'mode' => MrClay_CookieStorage::MODE_ENCRYPT
* ));
* </code>
*/
class MrClay_CookieStorage {
// conservative storage limit considering variable-length Set-Cookie header
const LENGTH_LIMIT = 3896;
const MODE_VISIBLE = 0;
const MODE_ENCRYPT = 1;
/**
* @var array errors that occured
*/
public $errors = array();
public function __construct($options = array())
{
$this->_o = array_merge(self::getDefaults(), $options);
}
public static function hash($input)
{
return str_replace('=', '', base64_encode(hash('ripemd160', $input, true)));
}
public static function encrypt($key, $str)
{
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$data = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $str, MCRYPT_MODE_ECB, $iv);
return base64_encode($data);
}
public static function decrypt($key, $data)
{
if (false === ($data = base64_decode($data))) {
return false;
}
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_ECB, $iv);
}
public function getDefaults()
{
return array(
'secret' => ''
,'domain' => ''
,'secure' => false
,'path' => '/'
,'expire' => '2147368447' // Sun, 17-Jan-2038 19:14:07 GMT (Google)
,'hashFunc' => array('MrClay_CookieStorage', 'hash')
,'encryptFunc' => array('MrClay_CookieStorage', 'encrypt')
,'decryptFunc' => array('MrClay_CookieStorage', 'decrypt')
,'mode' => self::MODE_VISIBLE
,'httponly' => false
);
}
public function setOption($name, $value)
{
$this->_o[$name] = $value;
}
/**
* @return bool success
*/
public function store($name, $str)
{
if (empty($this->_o['secret'])) {
$this->errors[] = 'Must first set the option: secret.';
return false;
}
return ($this->_o['mode'] === self::MODE_ENCRYPT)
? $this->_storeEncrypted($name, $str)
: $this->_store($name, $str);
}
private function _store($name, $str)
{
if (! is_callable($this->_o['hashFunc'])) {
$this->errors[] = 'Hash function not callable';
return false;
}
$time = base_convert($_SERVER['REQUEST_TIME'], 10, 36); // pack time
// tie sig to this cookie name
$hashInput = $this->_o['secret'] . $name . $time . $str;
$sig = call_user_func($this->_o['hashFunc'], $hashInput);
$raw = $sig . '|' . $time . '|' . $str;
if (strlen($name . $raw) > self::LENGTH_LIMIT) {
$this->errors[] = 'Cookie is likely too large to store.';
return false;
}
$res = setcookie($name, $raw, $this->_o['expire'], $this->_o['path'],
$this->_o['domain'], $this->_o['secure'], $this->_o['httponly']);
if ($res) {
return true;
} else {
$this->errors[] = 'Setcookie() returned false. Headers may have been sent.';
return false;
}
}
private function _storeEncrypted($name, $str)
{
if (! is_callable($this->_o['encryptFunc'])) {
$this->errors[] = 'Encrypt function not callable';
return false;
}
$time = base_convert($_SERVER['REQUEST_TIME'], 10, 36); // pack time
$key = self::hash($this->_o['secret']);
$raw = call_user_func($this->_o['encryptFunc'], $key, $key . $time . '|' . $str);
if (strlen($name . $raw) > self::LENGTH_LIMIT) {
$this->errors[] = 'Cookie is likely too large to store.';
return false;
}
$res = setcookie($name, $raw, $this->_o['expire'], $this->_o['path'],
$this->_o['domain'], $this->_o['secure'], $this->_o['httponly']);
if ($res) {
return true;
} else {
$this->errors[] = 'Setcookie() returned false. Headers may have been sent.';
return false;
}
}
/**
* @return string null if cookie not set, false if tampering occured
*/
public function fetch($name)
{
if (!isset($_COOKIE[$name])) {
return null;
}
return ($this->_o['mode'] === self::MODE_ENCRYPT)
? $this->_fetchEncrypted($name)
: $this->_fetch($name);
}
private function _fetch($name)
{
if (isset($this->_returns[self::MODE_VISIBLE][$name])) {
return $this->_returns[self::MODE_VISIBLE][$name][0];
}
$cookie = get_magic_quotes_gpc()
? stripslashes($_COOKIE[$name])
: $_COOKIE[$name];
$parts = explode('|', $cookie, 3);
if (3 !== count($parts)) {
$this->errors[] = 'Cookie was tampered with.';
return false;
}
list($sig, $time, $str) = $parts;
$hashInput = $this->_o['secret'] . $name . $time . $str;
if ($sig !== call_user_func($this->_o['hashFunc'], $hashInput)) {
$this->errors[] = 'Cookie was tampered with.';
return false;
}
$time = base_convert($time, 36, 10); // unpack time
$this->_returns[self::MODE_VISIBLE][$name] = array($str, $time);
return $str;
}
private function _fetchEncrypted($name)
{
if (isset($this->_returns[self::MODE_ENCRYPT][$name])) {
return $this->_returns[self::MODE_ENCRYPT][$name][0];
}
if (! is_callable($this->_o['decryptFunc'])) {
$this->errors[] = 'Decrypt function not callable';
return false;
}
$cookie = get_magic_quotes_gpc()
? stripslashes($_COOKIE[$name])
: $_COOKIE[$name];
$key = self::hash($this->_o['secret']);
$timeStr = call_user_func($this->_o['decryptFunc'], $key, $cookie);
if (! $timeStr) {
$this->errors[] = 'Cookie was tampered with.';
return false;
}
$timeStr = rtrim($timeStr, "\x00");
// verify decryption
if (0 !== strpos($timeStr, $key)) {
$this->errors[] = 'Cookie was tampered with.';
return false;
}
$timeStr = substr($timeStr, strlen($key));
list($time, $str) = explode('|', $timeStr, 2);
$time = base_convert($time, 36, 10); // unpack time
$this->_returns[self::MODE_ENCRYPT][$name] = array($str, $time);
return $str;
}
public function getTimestamp($name)
{
if (is_string($this->fetch($name))) {
return $this->_returns[$this->_o['mode']][$name][1];
}
return false;
}
public function delete($name)
{
setcookie($name, '', time() - 3600, $this->_o['path'], $this->_o['domain'], $this->_o['secure'], $this->_o['httponly']);
}
/**
* @var array options
*/
private $_o;
private $_returns = array();
}