/
Session.php
654 lines (570 loc) · 18.3 KB
/
Session.php
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
<?php
/**
* Copyright 2010-2014 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @author Michael Slusarz <slusarz@horde.org>
* @category Horde
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Core
*/
/**
* The Horde_Session class provides a set of methods for handling the
* administration and contents of the Horde session variable.
*
* @author Michael Slusarz <slusarz@horde.org>
* @category Horde
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Core
*
* @property-read integer $begin The timestamp when this session began (0 if
* session is not active).
* @property-read boolean $regenerate_due True if session ID is due for
* regeneration (since 2.5.0).
* @property-read integer $regenerate_interval The regeneration interval
* (since 2.5.0).
* @property-write array $session_data Manually set session data (since
* 2.5.0).
*/
class Horde_Session
{
/* Class constants. */
const BEGIN = '_b';
const DATA = '_d';
const ENCRYPTED = '_e'; /* @since 2.7.0 */
const MODIFIED = '_m'; /* @deprecated */
const PRUNE = '_p';
const REGENERATE = '_r'; /* @since 2.5.0 */
const TYPE_ARRAY = 1;
const TYPE_OBJECT = 2;
const ENCRYPT = 4; /* @since 2.7.0 */
const NOT_SERIALIZED = "\0";
const NONCE_ID = 'session_nonce'; /* @since 2.11.0 */
const TOKEN_ID = 'session_token';
/**
* Maximum size of the pruneable data store.
*
* @var integer
*/
public $maxStore = 20;
/**
* The session handler object.
*
* @var Horde_SessionHandler
*/
public $sessionHandler = null;
/**
* Indicates that the session is active (read/write).
*
* @var boolean
*/
protected $_active = false;
/**
* Indicate that a new session ID has been generated for this page load.
*
* @var boolean
*/
protected $_cleansession = false;
/**
* Pointer to the session data.
*
* @var array
*/
protected $_data;
/**
* Indicates that session data is read-only.
*
* @var boolean
*/
protected $_readonly = false;
/**
* On re-login, indicate whether we were previously authenticated.
*
* @var integer
*/
protected $_relogin = null;
/**
* Constructor.
*/
public function __construct()
{
/* Make sure global session variable is always initialized. */
$_SESSION = array();
$this->_data = &$_SESSION;
}
/**
*/
public function __get($name)
{
switch ($name) {
case 'begin':
return ($this->_active || $this->_relogin)
? $this->_data[self::BEGIN]
: 0;
case 'regenerate_due':
return (isset($this->_data[self::REGENERATE]) &&
(time() >= $this->_data[self::REGENERATE]));
case 'regenerate_interval':
// DEFAULT: 6 hours
return 21600;
}
}
/**
*/
public function __set($name, $value)
{
switch ($name) {
case 'session_data':
$this->_data = &$value;
break;
}
}
/**
* Sets a custom session handler up, if there is one.
*
* @param boolean $start Initiate the session?
* @param string $cache_limiter Override for the session cache limiter
* value.
* @param string $session_id The session ID to use.
*
* @throws Horde_Exception
*/
public function setup($start = true, $cache_limiter = null,
$session_id = null)
{
global $conf, $injector;
ini_set('url_rewriter.tags', 0);
if (empty($conf['session']['use_only_cookies'])) {
ini_set('session.use_only_cookies', 0);
} else {
ini_set('session.use_only_cookies', 1);
if (!empty($conf['cookie']['domain']) &&
(strpos($conf['server']['name'], '.') === false)) {
throw new Horde_Exception('Session cookies will not work without a FQDN and with a non-empty cookie domain. Either use a fully qualified domain name like "http://www.example.com" instead of "http://example" only, or set the cookie domain in the Horde configuration to an empty value, or enable non-cookie (url-based) sessions in the Horde configuration.');
}
}
if (!empty($conf['session']['timeout'])) {
ini_set('session.gc_maxlifetime', $conf['session']['timeout']);
}
session_set_cookie_params(
$conf['session']['timeout'],
$conf['cookie']['path'],
$conf['cookie']['domain'],
$conf['use_ssl'] == 1 ? 1 : 0,
true
);
session_cache_limiter(is_null($cache_limiter) ? $conf['session']['cache_limiter'] : $cache_limiter);
session_name(urlencode($conf['session']['name']));
if ($session_id) {
session_id($session_id);
}
/* We want to create an instance here, not get, since we may be
* destroying the previous instances in the page. */
$this->sessionHandler = $injector->createInstance('Horde_SessionHandler');
if ($start) {
$this->start();
$this->_start();
}
}
/**
* Starts the session.
*/
public function start()
{
/* Limit session ID to 32 bytes. Session IDs are NOT cryptographically
* secure hashes. Instead, they are nothing more than a way to
* generate random strings. */
ini_set('session.hash_function', 0);
ini_set('session.hash_bits_per_character', 5);
session_start();
$this->_active = true;
$this->_data = &$_SESSION;
/* We have reopened a session. Check to make sure that authentication
* status has not changed in the meantime. */
if (!$this->_readonly &&
!is_null($this->_relogin) &&
(($GLOBALS['registry']->getAuth() !== false) !== $this->_relogin)) {
Horde::log('Previous session attempted to be reopened after authentication status change. All session modifications will be ignored.', 'DEBUG');
$this->_readonly = true;
}
}
/**
* Tasks to perform when starting a session.
*/
private function _start()
{
$curr_time = time();
/* Create internal data arrays. */
if (!isset($this->_data[self::BEGIN])) {
$this->_data[self::BEGIN] = $curr_time;
$this->_data[self::REGENERATE] = $curr_time + $this->regenerate_interval;
}
}
/**
* Regenerate the session ID.
*
* @since 2.5.0
*/
public function regenerate()
{
/* Load old encrypted data. */
$encrypted = array();
foreach ($this->_data[self::ENCRYPTED] as $app => $val) {
foreach (array_keys($val) as $val2) {
$encrypted[$app][$val2] = $this->get($app, $val2);
}
}
session_regenerate_id(true);
$this->_data[self::REGENERATE] = time() + $this->regenerate_interval;
/* Store encrypted data, since secret key may have changed. */
foreach ($encrypted as $app => $val) {
foreach ($val as $key2 => $val2) {
$this->set($app, $key2, $val2, self::ENCRYPTED);
}
}
$this->sessionHandler->changed = true;
}
/**
* Destroys any existing session on login and make sure to use a new
* session ID, to avoid session fixation issues. Should be called before
* checking a login.
*
* @return boolean True if the session was cleaned.
*/
public function clean()
{
if ($this->_cleansession) {
return false;
}
// Make sure to force a completely new session ID and clear all
// session data.
session_regenerate_id(true);
session_unset();
$this->_data = array();
$this->_start();
$GLOBALS['injector']->getInstance('Horde_Secret')->setKey();
$this->_cleansession = true;
return true;
}
/**
* Close the current session.
*/
public function close()
{
$this->_active = false;
$this->_relogin = ($GLOBALS['registry']->getAuth() !== false);
session_write_close();
}
/**
* Destroy session data.
*/
public function destroy()
{
if (isset($_SESSION)) {
session_destroy();
}
$this->_cleansession = true;
$GLOBALS['injector']->getInstance('Horde_Secret')->clearKey();
}
/**
* Is the current session active (read/write)?
*
* @return boolean True if the current session is active.
*/
public function isActive()
{
return $this->_active;
}
/* Session variable access. */
/**
* Does the session variable exist?
*
* @param string $app Application name.
* @param string $name Session variable name.
*
* @return boolean True if session variable exists.
*/
public function exists($app, $name)
{
return isset($this->_data[$app][$name]);
}
/**
* Get the value of a session variable.
*
* @param string $app Application name.
* @param string $name Session variable name.
* @param integer $mask One of:
* - Horde_Session::TYPE_ARRAY - Return an array value.
* - Horde_Session::TYPE_OBJECT - Return an object value.
*
* @return mixed The value or null if the value doesn't exist.
*/
public function get($app, $name, $mask = 0)
{
global $injector;
if ($this->exists($app, $name)) {
$value = $this->_data[$app][$name];
if (!is_string($value) || strlen($value) === 0) {
return $value;
} elseif ($value[0] === self::NOT_SERIALIZED) {
return substr($value, 1);
}
if (isset($this->_data[self::ENCRYPTED][$app][$name])) {
$secret = $injector->getInstance('Horde_Secret');
$value = strval($secret->read($secret->getKey(), $value));
}
try {
return $injector->getInstance('Horde_Pack')->unpack($value);
} catch (Horde_Pack_Exception $e) {
return null;
}
}
if ($subkeys = $this->_subkeys($app, $name)) {
$ret = array();
foreach ($subkeys as $k => $v) {
$ret[$k] = $this->get($app, $v, $mask);
}
return $ret;
}
if (strpos($name, self::DATA) === 0) {
return $this->retrieve($name);
}
switch ($mask) {
case self::TYPE_ARRAY:
return array();
case self::TYPE_OBJECT:
return new stdClass;
}
return null;
}
/**
* Sets the value of a session variable.
*
* @param string $app Application name.
* @param string $name Session variable name.
* @param mixed $value Session variable value.
* @param integer $mask One of:
* - Horde_Session::TYPE_ARRAY: Force save as an array value.
* - Horde_Session::TYPE_OBJECT: Force save as an object value.
* - Horde_Session::ENCRYPT: Encrypt the value. (since 2.7.0)
*/
public function set($app, $name, $value, $mask = 0)
{
global $injector;
if ($this->_readonly) {
return;
}
unset($this->_data[self::ENCRYPTED][$app][$name]);
/* Each particular piece of session data is generally not used on any
* given page load. Thus, for arrays and objects, it is beneficial to
* always convert to string representations so that the object/array
* does not need to be rebuilt every time the session is reloaded.
* For convenience, encrypted data is ALWAYS serialized, regardless
* of whether it is already a string. */
if (($mask & self::ENCRYPT) ||
is_object($value) || ($mask & self::TYPE_OBJECT) ||
is_array($value) || ($mask & self::TYPE_ARRAY)) {
$value = $injector->getInstance('Horde_Pack')->pack($value, array(
'compress' => 0,
'phpob' => (is_object($value) || ($mask & self::TYPE_OBJECT))
));
if ($mask & self::ENCRYPT) {
$secret = $injector->getInstance('Horde_Secret');
$value = $secret->write($secret->getKey(), $value);
$this->_data[self::ENCRYPTED][$app][$name] = true;
}
} elseif (is_string($value)) {
$value = self::NOT_SERIALIZED . $value;
}
if (!$this->exists($app, $name) ||
($this->_data[$app][$name] !== $value)) {
$this->_data[$app][$name] = $value;
$this->sessionHandler->changed = true;
}
}
/**
* Remove session key(s).
*
* @param string $app Application name.
* @param string $name Session variable name.
*/
public function remove($app, $name = null)
{
if ($this->_readonly || !isset($this->_data[$app])) {
return;
}
if (is_null($name)) {
unset($this->_data[$app]);
$this->sessionHandler->changed = true;
} elseif ($this->exists($app, $name)) {
unset(
$this->_data[$app][$name],
$this->_data[self::PRUNE][$this->_getKey($app, $name)]
);
$this->sessionHandler->changed = true;
} else {
foreach ($this->_subkeys($app, $name) as $val) {
$this->remove($app, $val);
}
}
}
/**
* Generates the unique storage key.
*
* @param string $app Application name.
* @param string $name Session variable name.
*
* @return string The unique storage key.
*/
private function _getKey($app, $name)
{
return $app . ':' . $name;
}
/**
* Return the list of subkeys for a master key.
*
* @param string $app Application name.
* @param string $name Session variable name.
*
* @return array Subkeyname (keys) and session variable name (values).
*/
private function _subkeys($app, $name)
{
$ret = array();
if ($name &&
isset($this->_data[$app]) &&
($name[strlen($name) - 1] == '/')) {
foreach (array_keys($this->_data[$app]) as $k) {
if (strpos($k, $name) === 0) {
$ret[substr($k, strlen($name))] = $k;
}
}
}
return $ret;
}
/* Session tokens. */
/**
* Returns the session token.
*
* @return string Session token.
*/
public function getToken()
{
if ($token = $this->get('horde', self::TOKEN_ID)) {
return $token;
}
$token = strval(new Horde_Support_Randomid());
$this->set('horde', self::TOKEN_ID, $token);
return $token;
}
/**
* Checks the validity of the session token.
*
* @param string $token Token to check.
*
* @throws Horde_Exception
*/
public function checkToken($token)
{
if ($this->getToken() != $token) {
throw new Horde_Exception('Invalid token!');
}
}
/* Session nonces. */
/**
* Returns a single-use, session nonce.
*
* @since 2.11.0
*
* @return string Session nonce.
*/
public function getNonce()
{
$id = strval(new Horde_Support_Randomid());
$nonces = $this->get('horde', self::NONCE_ID, self::TYPE_ARRAY);
$nonces[] = $id;
$this->set('horde', self::NONCE_ID, array_values($nonces));
return $id;
}
/**
* Checks the validity of the session nonce.
*
* @since 2.11.0
*
* @param string $nonce Nonce to check.
*
* @throws Horde_Exception
*/
public function checkNonce($nonce)
{
$nonces = $this->get('horde', self::NONCE_ID, self::TYPE_ARRAY);
if (($pos = array_search($nonce, $nonces)) === false) {
throw new Horde_Exception('Invalid token!');
}
unset($nonces[$pos]);
$this->set('horde', self::NONCE_ID, array_values($nonces));
}
/* Session object storage. */
/**
* Store an arbitrary piece of data in the session.
*
* @param mixed $data Data to save.
* @param boolean $prune Is data pruneable?
* @param string $id ID to use (otherwise, is autogenerated).
*
* @return string The session storage id (used to retrieve session data).
*/
public function store($data, $prune = true, $id = null)
{
$id = is_null($id)
? strval(new Horde_Support_Randomid())
: $this->_getStoreId($id);
$this->set(self::DATA, $id, $data);
if ($prune) {
$ptr = &$this->_data[self::PRUNE];
unset($ptr[$id]);
$ptr[$id] = 1;
if (count($ptr) > $this->maxStore) {
array_shift($ptr);
}
}
return $this->_getKey(self::DATA, $id);
}
/**
* Retrieve data from the session data store (created via store()).
*
* @param string $id The session data ID.
*
* @return mixed The session data value.
*/
public function retrieve($id)
{
return $this->get(self::DATA, $this->_getStoreId($id));
}
/**
* Purge data from the session data store (created via store()).
*
* @param string $id The session data ID.
*/
public function purge($id)
{
$this->remove(self::DATA, $this->_getStoreId($id));
}
/**
* Returns the base storage ID.
*
* @param string $id The session data ID.
*
* @return string The base storage ID (without prefix).
*/
private function _getStoreId($id)
{
$id = trim($id);
if (strpos($id, self::DATA) === 0) {
$id = substr($id, strlen(self::DATA) + 1);
}
return $id;
}
}