My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
<?php

/**
* Store tamper-proof strings in an HTTP cookie
*
* Requires MrClay_Hmac (and MrClay_Rand)
*
* <code>
* $storage = new MrClay_CookieStorage(array(
* 'secret' => '67676kmcuiekihbfyhbtfitfytrdo=op-p-=[hH8'
* ));
* if ($storage->store('user', 'id:62572,email:bob@yahoo.com,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>
*
* @author Steve Clay <steve@mrclay.org>
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
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(), MrClay_Hmac $hmac = null)
{
$this->_o = array_merge(self::getDefaults(), $options);
if (empty($this->_o['secret'])) {
throw new Exception('secret must be set in $options.');
}
if (! $hmac) {
$hmac = new MrClay_Hmac($this->_o['secret'], $this->_o['hashAlgo']);
} else {
$hmac->setSecret($this->_o['secret']);
}
$this->_hmac = $hmac;
}

/*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')
,'hashAlgo' => 'ripemd160'
,'mode' => self::MODE_VISIBLE
);
}

public function setOption($name, $value)
{
$this->_o[$name] = $value;
}

/**
* @return bool success
*/
public function store($name, $str)
{
return ($this->_o['mode'] === self::MODE_ENCRYPT)
? $this->_storeEncrypted($name, $str)
: $this->_store($name, $str);
}

private function _store($name, $str)
{
$time = base_convert($_SERVER['REQUEST_TIME'], 10, 36); // pack time
// tie sig to this cookie name and timestamp
list($val, $salt, $hash) = $this->_hmac->sign($name . $time . $str);

$raw = $salt . '|' . $hash . '|' . $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']);
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

// tie sig to this cookie name and timestamp
list($val, $salt, $hash) = $this->_hmac->sign($name . $time . $str);

$cryptKey = hash('ripemd160', $this->_o['secret'], true);
$encrypted = call_user_func($this->_o['encryptFunc'], $cryptKey, '1' . $str);

$raw = $salt . '|' . $hash . '|' . $time . '|' . $encrypted;
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']);
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, 4);
if (4 !== count($parts)) {
$this->errors[] = 'Cookie was tampered with.';
return false;
}
list($salt, $hash, $time, $str) = $parts;

if (! $this->_hmac->isValid(array($name . $time . $str, $salt, $hash))) {
$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];
$parts = explode('|', $cookie, 4);
if (4 !== count($parts)) {
$this->errors[] = 'Cookie was tampered with.';
return false;
}
list($salt, $hash, $time, $encrypted) = $parts;

$cryptKey = hash('ripemd160', $this->_o['secret'], true);
$str = call_user_func($this->_o['decryptFunc'], $cryptKey, $encrypted);
if (! $str) {
$this->errors[] = 'Cookie was tampered with.';
return false;
}
$str = substr($str, 1); // remove leading "1"
$str = rtrim($str, "\x00"); // remove trailing null bytes

if (! $this->_hmac->isValid(array($name . $time . $str, $salt, $hash))) {
$this->errors[] = 'Cookie was tampered with.';
return false;
}
$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']);
}

/**
* @var array options
*/
private $_o;

private $_returns = array();

/**
* @var MrClay_Hmac
*/
protected $_hmac;
}

Change log

r58 by mrclay.org on Sep 6, 2011   Diff
improved HMAC implementation w/ standard
key derivation. Added SignedRequest
Go to: 
Project members, sign in to write a code review

Older revisions

r55 by st...@mrclay.org on Jul 14, 2011   Diff
Updated CookieStorage to use Hmac (and
now include HMAC on encrypted storage)
r8 by st...@mrclay.org on Oct 12, 2008   Diff
CookieStorage.php : + 'mode' option
for encrypted cookies
r7 by st...@mrclay.org on Oct 12, 2008   Diff
CookieStorage.php : hash now done by
callback with more secure default,
E_NOTICE avoided when cookie tampered
with, timestamp compacted to base 32.
All revisions of this file

File info

Size: 8758 bytes, 271 lines
Powered by Google Project Hosting