1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22:
23:
24: App::uses('Hash', 'Utility');
25: App::uses('Security', 'Utility');
26:
27: 28: 29: 30: 31: 32: 33: 34:
35: class CakeSession {
36:
37: 38: 39: 40: 41:
42: public static $valid = false;
43:
44: 45: 46: 47: 48:
49: public static $error = false;
50:
51: 52: 53: 54: 55:
56: protected static $_userAgent = '';
57:
58: 59: 60: 61: 62:
63: public static $path = '/';
64:
65: 66: 67: 68: 69:
70: public static $lastError = null;
71:
72: 73: 74: 75: 76:
77: public static $time = false;
78:
79: 80: 81: 82: 83:
84: public static $cookieLifeTime;
85:
86: 87: 88: 89: 90:
91: public static $sessionTime = false;
92:
93: 94: 95: 96: 97:
98: public static $id = null;
99:
100: 101: 102: 103: 104:
105: public static $host = null;
106:
107: 108: 109: 110: 111:
112: public static $timeout = null;
113:
114: 115: 116: 117: 118: 119: 120:
121: public static $requestCountdown = 10;
122:
123: 124: 125: 126: 127:
128: protected static $_initialized = false;
129:
130: 131: 132: 133: 134: 135:
136: public static function init($base = null) {
137: self::$time = time();
138:
139: if (env('HTTP_USER_AGENT')) {
140: self::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
141: }
142:
143: self::_setPath($base);
144: self::_setHost(env('HTTP_HOST'));
145:
146: if (!self::$_initialized) {
147: register_shutdown_function('session_write_close');
148: }
149:
150: self::$_initialized = true;
151: }
152:
153: 154: 155: 156: 157: 158:
159: protected static function _setPath($base = null) {
160: if (empty($base)) {
161: self::$path = '/';
162: return;
163: }
164: if (strpos($base, 'index.php') !== false) {
165: $base = str_replace('index.php', '', $base);
166: }
167: if (strpos($base, '?') !== false) {
168: $base = str_replace('?', '', $base);
169: }
170: self::$path = $base;
171: }
172:
173: 174: 175: 176: 177: 178:
179: protected static function _setHost($host) {
180: self::$host = $host;
181: if (strpos(self::$host, ':') !== false) {
182: self::$host = substr(self::$host, 0, strpos(self::$host, ':'));
183: }
184: }
185:
186: 187: 188: 189: 190:
191: public static function start() {
192: if (self::started()) {
193: return true;
194: }
195:
196: $id = self::id();
197: self::_startSession();
198:
199: if (!$id && self::started()) {
200: self::_checkValid();
201: }
202:
203: self::$error = false;
204: self::$valid = true;
205: return self::started();
206: }
207:
208: 209: 210: 211: 212:
213: public static function started() {
214: return isset($_SESSION) && session_id();
215: }
216:
217: 218: 219: 220: 221: 222:
223: public static function check($name = null) {
224: if (!self::start()) {
225: return false;
226: }
227: if (empty($name)) {
228: return false;
229: }
230: return Hash::get($_SESSION, $name) !== null;
231: }
232:
233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246:
247: public static function id($id = null) {
248: if ($id) {
249: self::$id = $id;
250: session_id(self::$id);
251: }
252: if (self::started()) {
253: return session_id();
254: }
255: return self::$id;
256: }
257:
258: 259: 260: 261: 262: 263:
264: public static function delete($name) {
265: if (self::check($name)) {
266: self::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
267: return !self::check($name);
268: }
269: return false;
270: }
271:
272: 273: 274: 275: 276: 277: 278:
279: protected static function _overwrite(&$old, $new) {
280: if (!empty($old)) {
281: foreach ($old as $key => $var) {
282: if (!isset($new[$key])) {
283: unset($old[$key]);
284: }
285: }
286: }
287: foreach ($new as $key => $var) {
288: $old[$key] = $var;
289: }
290: }
291:
292: 293: 294: 295: 296: 297:
298: protected static function _error($errorNumber) {
299: if (!is_array(self::$error) || !array_key_exists($errorNumber, self::$error)) {
300: return false;
301: }
302: return self::$error[$errorNumber];
303: }
304:
305: 306: 307: 308: 309:
310: public static function error() {
311: if (self::$lastError) {
312: return self::_error(self::$lastError);
313: }
314: return false;
315: }
316:
317: 318: 319: 320: 321:
322: public static function valid() {
323: if (self::read('Config')) {
324: if (self::_validAgentAndTime() && self::$error === false) {
325: self::$valid = true;
326: } else {
327: self::$valid = false;
328: self::_setError(1, 'Session Highjacking Attempted !!!');
329: }
330: }
331: return self::$valid;
332: }
333:
334: 335: 336: 337: 338: 339: 340: 341:
342: protected static function _validAgentAndTime() {
343: $config = self::read('Config');
344: $validAgent = (
345: Configure::read('Session.checkAgent') === false ||
346: self::$_userAgent == $config['userAgent']
347: );
348: return ($validAgent && self::$time <= $config['time']);
349: }
350:
351: 352: 353: 354: 355: 356:
357: public static function userAgent($userAgent = null) {
358: if ($userAgent) {
359: self::$_userAgent = $userAgent;
360: }
361: if (empty(self::$_userAgent)) {
362: CakeSession::init(self::$path);
363: }
364: return self::$_userAgent;
365: }
366:
367: 368: 369: 370: 371: 372:
373: public static function read($name = null) {
374: if (!self::start()) {
375: return false;
376: }
377: if ($name === null) {
378: return self::_returnSessionVars();
379: }
380: if (empty($name)) {
381: return false;
382: }
383: $result = Hash::get($_SESSION, $name);
384:
385: if (isset($result)) {
386: return $result;
387: }
388: return null;
389: }
390:
391: 392: 393: 394: 395:
396: protected static function _returnSessionVars() {
397: if (!empty($_SESSION)) {
398: return $_SESSION;
399: }
400: self::_setError(2, 'No Session vars set');
401: return false;
402: }
403:
404: 405: 406: 407: 408: 409: 410:
411: public static function write($name, $value = null) {
412: if (!self::start()) {
413: return false;
414: }
415: if (empty($name)) {
416: return false;
417: }
418: $write = $name;
419: if (!is_array($name)) {
420: $write = array($name => $value);
421: }
422: foreach ($write as $key => $val) {
423: self::_overwrite($_SESSION, Hash::insert($_SESSION, $key, $val));
424: if (Hash::get($_SESSION, $key) !== $val) {
425: return false;
426: }
427: }
428: return true;
429: }
430:
431: 432: 433: 434: 435:
436: public static function destroy() {
437: if (!self::started()) {
438: self::_startSession();
439: }
440:
441: session_destroy();
442:
443: $_SESSION = null;
444: self::$id = null;
445: }
446:
447: 448: 449: 450: 451:
452: public static function clear() {
453: $_SESSION = null;
454: self::$id = null;
455: self::renew();
456: }
457:
458: 459: 460: 461: 462: 463: 464: 465:
466: protected static function _configureSession() {
467: $sessionConfig = Configure::read('Session');
468:
469: if (isset($sessionConfig['defaults'])) {
470: $defaults = self::_defaultConfig($sessionConfig['defaults']);
471: if ($defaults) {
472: $sessionConfig = Hash::merge($defaults, $sessionConfig);
473: }
474: }
475: if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) {
476: $sessionConfig['ini']['session.cookie_secure'] = 1;
477: }
478: if (isset($sessionConfig['timeout']) && !isset($sessionConfig['cookieTimeout'])) {
479: $sessionConfig['cookieTimeout'] = $sessionConfig['timeout'];
480: }
481: if (!isset($sessionConfig['ini']['session.cookie_lifetime'])) {
482: $sessionConfig['ini']['session.cookie_lifetime'] = $sessionConfig['cookieTimeout'] * 60;
483: }
484: if (!isset($sessionConfig['ini']['session.name'])) {
485: $sessionConfig['ini']['session.name'] = $sessionConfig['cookie'];
486: }
487: if (!empty($sessionConfig['handler'])) {
488: $sessionConfig['ini']['session.save_handler'] = 'user';
489: }
490: if (!isset($sessionConfig['ini']['session.gc_maxlifetime'])) {
491: $sessionConfig['ini']['session.gc_maxlifetime'] = $sessionConfig['timeout'] * 60;
492: }
493: if (!isset($sessionConfig['ini']['session.cookie_httponly'])) {
494: $sessionConfig['ini']['session.cookie_httponly'] = 1;
495: }
496:
497: if (empty($_SESSION)) {
498: if (!empty($sessionConfig['ini']) && is_array($sessionConfig['ini'])) {
499: foreach ($sessionConfig['ini'] as $setting => $value) {
500: if (ini_set($setting, $value) === false) {
501: throw new CakeSessionException(__d('cake_dev', 'Unable to configure the session, setting %s failed.', $setting));
502: }
503: }
504: }
505: }
506: if (!empty($sessionConfig['handler']) && !isset($sessionConfig['handler']['engine'])) {
507: call_user_func_array('session_set_save_handler', $sessionConfig['handler']);
508: }
509: if (!empty($sessionConfig['handler']['engine'])) {
510: $handler = self::_getHandler($sessionConfig['handler']['engine']);
511: session_set_save_handler(
512: array($handler, 'open'),
513: array($handler, 'close'),
514: array($handler, 'read'),
515: array($handler, 'write'),
516: array($handler, 'destroy'),
517: array($handler, 'gc')
518: );
519: }
520: Configure::write('Session', $sessionConfig);
521: self::$sessionTime = self::$time + ($sessionConfig['timeout'] * 60);
522: }
523:
524: 525: 526: 527: 528: 529: 530:
531: protected static function _getHandler($handler) {
532: list($plugin, $class) = pluginSplit($handler, true);
533: App::uses($class, $plugin . 'Model/Datasource/Session');
534: if (!class_exists($class)) {
535: throw new CakeSessionException(__d('cake_dev', 'Could not load %s to handle the session.', $class));
536: }
537: $handler = new $class();
538: if ($handler instanceof CakeSessionHandlerInterface) {
539: return $handler;
540: }
541: throw new CakeSessionException(__d('cake_dev', 'Chosen SessionHandler does not implement CakeSessionHandlerInterface it cannot be used with an engine key.'));
542: }
543:
544: 545: 546: 547: 548: 549:
550: protected static function _defaultConfig($name) {
551: $defaults = array(
552: 'php' => array(
553: 'cookie' => 'CAKEPHP',
554: 'timeout' => 240,
555: 'ini' => array(
556: 'session.use_trans_sid' => 0,
557: 'session.cookie_path' => self::$path
558: )
559: ),
560: 'cake' => array(
561: 'cookie' => 'CAKEPHP',
562: 'timeout' => 240,
563: 'ini' => array(
564: 'session.use_trans_sid' => 0,
565: 'url_rewriter.tags' => '',
566: 'session.serialize_handler' => 'php',
567: 'session.use_cookies' => 1,
568: 'session.cookie_path' => self::$path,
569: 'session.save_path' => TMP . 'sessions',
570: 'session.save_handler' => 'files'
571: )
572: ),
573: 'cache' => array(
574: 'cookie' => 'CAKEPHP',
575: 'timeout' => 240,
576: 'ini' => array(
577: 'session.use_trans_sid' => 0,
578: 'url_rewriter.tags' => '',
579: 'session.use_cookies' => 1,
580: 'session.cookie_path' => self::$path,
581: 'session.save_handler' => 'user',
582: ),
583: 'handler' => array(
584: 'engine' => 'CacheSession',
585: 'config' => 'default'
586: )
587: ),
588: 'database' => array(
589: 'cookie' => 'CAKEPHP',
590: 'timeout' => 240,
591: 'ini' => array(
592: 'session.use_trans_sid' => 0,
593: 'url_rewriter.tags' => '',
594: 'session.use_cookies' => 1,
595: 'session.cookie_path' => self::$path,
596: 'session.save_handler' => 'user',
597: 'session.serialize_handler' => 'php',
598: ),
599: 'handler' => array(
600: 'engine' => 'DatabaseSession',
601: 'model' => 'Session'
602: )
603: )
604: );
605: if (isset($defaults[$name])) {
606: return $defaults[$name];
607: }
608: return false;
609: }
610:
611: 612: 613: 614: 615:
616: protected static function _startSession() {
617: self::init();
618: session_write_close();
619: self::_configureSession();
620:
621: if (headers_sent()) {
622: if (empty($_SESSION)) {
623: $_SESSION = array();
624: }
625: } else {
626:
627: session_cache_limiter("must-revalidate");
628: session_start();
629: }
630: return true;
631: }
632:
633: 634: 635: 636: 637:
638: protected static function _checkValid() {
639: $config = self::read('Config');
640: if ($config) {
641: $sessionConfig = Configure::read('Session');
642:
643: if (self::valid()) {
644: self::write('Config.time', self::$sessionTime);
645: if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) {
646: $check = $config['countdown'];
647: $check -= 1;
648: self::write('Config.countdown', $check);
649:
650: if ($check < 1) {
651: self::renew();
652: self::write('Config.countdown', self::$requestCountdown);
653: }
654: }
655: } else {
656: $_SESSION = array();
657: self::destroy();
658: self::_setError(1, 'Session Highjacking Attempted !!!');
659: self::_startSession();
660: self::_writeConfig();
661: }
662: } else {
663: self::_writeConfig();
664: }
665: }
666:
667: 668: 669: 670: 671:
672: protected static function _writeConfig() {
673: self::write('Config.userAgent', self::$_userAgent);
674: self::write('Config.time', self::$sessionTime);
675: self::write('Config.countdown', self::$requestCountdown);
676: }
677:
678: 679: 680: 681: 682:
683: public static function renew() {
684: if (session_id()) {
685: if (session_id() || isset($_COOKIE[session_name()])) {
686: setcookie(Configure::read('Session.cookie'), '', time() - 42000, self::$path);
687: }
688: session_regenerate_id(true);
689: }
690: }
691:
692: 693: 694: 695: 696: 697: 698:
699: protected static function _setError($errorNumber, $errorMessage) {
700: if (self::$error === false) {
701: self::$error = array();
702: }
703: self::$error[$errorNumber] = $errorMessage;
704: self::$lastError = $errorNumber;
705: }
706:
707: }
708: