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