-
-
Notifications
You must be signed in to change notification settings - Fork 213
/
session_handler.php
1266 lines (1112 loc) · 30.8 KB
/
session_handler.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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* e107 website system
*
* Copyright (C) 2008-2012 e107 Inc (e107.org)
* Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
*
* Session handler
*
* $URL$
* $Id$
*/
if (!defined('e107_INIT'))
{
exit;
}
/**
* @package e107
* @subpackage e107_handlers
* @version $Id$
* @author SecretR
*
* Dependencies:
* - direct: language handler
* - indirect: system preferences (required by language handler)
*
* What could break it?
* If session is started before the first system session call (see class2.php
* 'Start: Set User Language' phase), session config will not be applied!
* This could happen if included $CLASS2_INCLUDE script (see class2.php)
* calls session_start(). However, sessions will not be broken, just not secured
* as per e_SECURITY_LEVEL setting.
*
* Security levels:
* - SECURITY_LEVEL_NONE [0]: security disabled - no token checks, all session validation settings dsiabled
* - SECURITY_LEVEL_BALANCED [5]: ValidateRemoteAddr, ValidateHttpXForwardedFor are on,
* session token is created/checked, but not regenerated on every page load
* - SECURITY_LEVEL_HIGH [7]: Same as above but ValidateHttpVia, ValidateHttpUserAgent are on.
* - SECURITY_LEVEL_PARANOID [9]: Same as SECURITY_LEVEL_HIGH except session token is regenerated on
* every page load. 'httponly' is on, which means JS is unable to retrieve session cookie, this may cause
* troubles with some browsers.
* - SECURITY_LEVEL_INSANE [10]: Same as SECURITY_LEVEL_HIGH plus session id is regenerated at the end
* of every page request.
*
* Session objects are created by namespace:
* $_SESSION['e107'] is default namesapce auto created with
* <code><?php e107::getSession();</code>
* Session handler is validating corresponding session COOKIE
* (named as current session name, keeping the session id)
* on regular basis (session lifetime/4). If validation
* fails, corresponding cookie is destroyed (not the session itself).
*
* Initial system Session is started after language detection (see class2.php) to
* ensure proper session handling for sites using language sub-domains (e.g. fr.site.com)
*
* Some important system session data will be kept outside of the object for now (e.g. user validation data)
*
*/
class e_session
{
/**
* No protection, label 'Looking for trouble'
* @var integer
*/
const SECURITY_LEVEL_NONE = 0;
/**
* Default system protection, balanced for best user experience,
* label 'Safe mode - Balanced'
* @var integer
*/
const SECURITY_LEVEL_BALANCED = 5;
/**
* Adds more system security, but there is a chance (minimal) to break stuff,
* label 'High Security'
* @var integer
*/
const SECURITY_LEVEL_HIGH = 7;
/**
* High system protection, session id is regenerated on every page request,
* label 'Paranoid'
* @var integer
*/
const SECURITY_LEVEL_PARANOID = 9;
/**
* Highest system protection, session id and token values are regenerated on every page request,
* label 'Insane'
* @var unknown_type
*/
const SECURITY_LEVEL_INSANE = 10;
/**
* Session save path
* @var string
*/
protected $_sessionSavePath = false;
/**
* Session save method
* @var string files|db
*/
protected $_sessionSaveMethod = 'files';
/**
* Session cache limiter, ignored if empty
* php.net/manual/en/function.session-cache-limiter.php
* @var string public|private_no_expire|private|nocache
*/
protected $_sessionCacheLimiter = '';
protected $_namespace;
protected $_name;
protected $_sessionStarted = false; // Fixes lost $_SESSION value problem.
/**
* Validation options
* @var boolean
*/
protected $_sessionValidateRemoteAddr = true;
protected $_sessionValidateHttpVia = true;
protected $_sessionValidateHttpXForwardedFor = true;
protected $_sessionValidateHttpUserAgent = true;
/**
* Skip validation
* @var array
*/
protected $_sessionValidateRemoteAddrSkip = array();
protected $_sessionValidateHttpViaSkip = array();
protected $_sessionValidateHttpXForwardedForSkip = array();
protected $_sessionValidateHttpUserAgentSkip = array();
/**
* Default session options
* @var array
*/
protected $_options = array(
'lifetime' => 3600 , // 1 hour
'path' => '',
'domain' => '',
'secure' => false,
'httponly' => true,
);
/**
* Session data
* @var array
*/
protected $_data = array();
/**
* Set session options
* @param string $key
* @param mixed $value
* @return e_session
*/
public function setOption($key, $value)
{
$this->setOptions(array($key => $value));
return $this;
}
public function getOptions()
{
return $this->_options;
}
/**
* Get session option
* @param string $key
* @param mixed $default
* @return mixed value
*/
public function getOption($key, $default = null)
{
return (isset($this->_options[$key]) ? $this->_options[$key] : $default);
}
/**
* Set default settings/options based on the current security level
* NOTE: new prefs 'session_save_path', 'session_save_method', 'session_lifetime' introduced,
* still not added to preference administration
* @return e_session
*/
public function setDefaultSystemConfig()
{
if(!$this->getSessionId())
{
$config = array(
'ValidateRemoteAddr' => (e_SECURITY_LEVEL >= self::SECURITY_LEVEL_BALANCED),
'ValidateHttpVia' => (e_SECURITY_LEVEL >= self::SECURITY_LEVEL_HIGH),
'ValidateHttpXForwardedFor' => (e_SECURITY_LEVEL >= self::SECURITY_LEVEL_BALANCED),
'ValidateHttpUserAgent' => (e_SECURITY_LEVEL >= self::SECURITY_LEVEL_HIGH),
);
$options = array(
// 'httponly' => (e_SECURITY_LEVEL >= self::SECURITY_LEVEL_PARANOID),
'httponly' => true,
);
if(!defined('E107_INSTALL'))
{
$systemSaveMethod = ini_get('session.save_handler');
// e107::getDebug()->log("Save Method:".$systemSaveMethod);
$saveMethod = (!empty($systemSaveMethod)) ? $systemSaveMethod : 'files';
$config['SavePath'] = e107::getPref('session_save_path', false); // FIXME - new pref
$config['SaveMethod'] = e107::getPref('session_save_method', $saveMethod); // FIXME - new pref
$options['lifetime'] = (integer) e107::getPref('session_lifetime', 86400); //
$options['path'] = e107::getPref('session_cookie_path', ''); // FIXME - new pref
$options['secure'] = e107::getPref('ssl_enabled', false); //
if(!empty($options['secure']))
{
ini_set('session.cookie_secure', 1);
}
}
if(defined('SESSION_SAVE_PATH')) // safer than a pref.
{
$config['SavePath'] = e_BASE. SESSION_SAVE_PATH;
}
$hashes = hash_algos();
if((e_SECURITY_LEVEL >= self::SECURITY_LEVEL_BALANCED) && in_array('sha512',$hashes))
{
ini_set('session.hash_function', 'sha512');
ini_set('session.hash_bits_per_character', 5);
}
$this->setConfig($config)
->setOptions($options);
}
return $this;
}
/**
* Retrieve value from current session namespace
* Equals to $_SESSION[NAMESPACE][$key]
* @param string $key
* @param boolean $clear unset key
* @return mixed
*/
public function get($key, $clear = false)
{
$ret = isset($this->_data[$key]) ? $this->_data[$key] : null;
if($clear) $this->clear($key);
return $ret;
}
/**
* Retrieve value from current session namespace
* If key is null, returns all current session namespace data
*
* @param string|null $key
* @param boolean $clear
* @return mixed
*/
public function getData($key = null, $clear = false)
{
if(null === $key)
{
$ret = $this->_data;
if($clear) $this->clearData();
return $ret;
}
return $this->get($key, $clear);
}
/**
* Set value in current session namespace
* Equals to $_SESSION[NAMESPACE][$key] = $value
* @param string $key
* @param mixed $value
* @return e_session
*/
public function set($key, $value)
{
$this->_data[$key] = $value;
return $this;
}
/**
* Set value in current session namespace
* If $key is array, the whole namespace array will be replaced with it,
* $value will be ignored
* @param string|null $key
* @param mixed $value
* @return e_session
*/
public function setData($key, $value = null)
{
if(is_array($key))
{
$this->_data = $key;
return $this;
}
return $this->set($key, $value);
}
/**
* Check if given key is set in current session namespace
* Equals to isset($_SESSION[NAMESPACE][$key])
* @param string $key
* @return boolean
*/
public function is($key)
{
return isset($this->_data[$key]);
}
/**
* Check if given key is set and not empty in current session namespace
* Equals to !empty($_SESSION[NAMESPACE][$key]) check
* @param string $key
* @return boolean
*/
public function has($key)
{
return (isset($this->_data[$key]) && $this->_data[$key]);
}
/**
* Checks if current session namespace contains any data
* Equals to !empty($_SESSION[NAMESPACE]) check
* @return boolean
*/
public function hasData()
{
return !empty($this->_data);
}
/**
* Unset member of current session namespace array
* Equals to unset($_SESSION[NAMESPACE][$key])
* @param string $key
* @return e_session
*/
public function clear($key=null)
{
if($key == null) // clear all under this namespace.
{
$this->_data = array(); // must be set to array() not unset.
}
unset($this->_data[$key]);
return $this;
}
/**
* Reset current session namespace to empty array
* @return e_session
*/
public function clearData()
{
$this->_data = array();
return $this;
}
/**
* Set protected class vars, prefixed with _session
* @param array $config
* @return e_session
*/
public function setConfig($config)
{
foreach ($config as $k => $v)
{
$key = '_session'.$k;
if (isset($this->$key)) $this->$key = $v;
}
return $this;
}
/**
* Get registered namespace key
* @return string
*/
public function getNamespaceKey()
{
return $this->_namespace;
}
/**
* Reset session options
* @param array $options
* @return e_session
*/
public function setOptions($options)
{
if (empty($options) || !is_array($options)) return $this;
foreach ($options as $k => $v)
{
switch ($k)
{
case 'lifetime':
$v = intval($v);
break;
case 'path':
case 'domain':
$v = (string) $v;
break;
case 'secure':
case 'httponly':
$v = $v ? true : false;
break;
default:
$v = null;
break;
}
if($v !== null)
{
$this->_options[$k] = $v;
}
}
return $this;
}
public function init($namespace, $sessionName = null)
{
$this->start($sessionName);
if (!isset($_SESSION[$namespace]))
{
$_SESSION[$namespace] = array();
}
$this->_data =& $_SESSION[$namespace];
$this->_namespace = $namespace;
$this->validate();
$this->validateSessionCookie();
}
/**
* Conigure and start session
*
* @param string $sessionName optional session name
* @return e_session
*/
public function start($sessionName = null)
{
if (isset($_SESSION) && ($this->_sessionStarted == true))
{
return $this;
}
if (false !== $this->_sessionSavePath && is_writable($this->_sessionSavePath))
{
session_save_path($this->_sessionSavePath);
}
switch ($this->_sessionSaveMethod)
{
case 'db': // TODO session db handling, more methods (e.g. memcache)
ini_set('session.save_handler', 'user');
$session = new e_db_session;
$session->setSaveHandler();
break;
default:
if(!isset($_SESSION))
{
session_module_name($this->_sessionSaveMethod);
}
break;
}
if (empty($this->_options['domain']))
{
// MULTILANG_SUBDOMAIN set during initial language detection in language handler
$doma = ((deftrue('e_SUBDOMAIN') || deftrue('MULTILANG_SUBDOMAIN')) && e_DOMAIN != FALSE) ? ".".e_DOMAIN : FALSE; // from v1.x
$this->_options['domain'] = $doma;
}
if (empty($this->_options['path']))
{
if(defined('e_MULTISITE_MATCH')) // multisite support.
{
$this->_options['path'] = '/';
}
else
{
$this->_options['path'] = defined('e_HTTP') ? e_HTTP : '/';
}
}
// session name before options - problems reported on php.net
if (!empty($sessionName))
{
$this->setSessionName($sessionName);
}
// set session cookie params
session_set_cookie_params($this->_options['lifetime'],
$this->_options['path'],
$this->_options['domain'],
$this->_options['secure'],
$this->_options['httponly']);
if ($this->_sessionCacheLimiter)
{
session_cache_limiter((string) $this->_sessionCacheLimiter); //XXX Remove and have e_headers class handle it?
}
session_start();
$this->_sessionStarted = true;
return $this;
}
/**
* Set session ID
* @param string $sid
* @return e_session
*/
public function setSessionId($sid = null)
{
// comma and minus allowed since 5.0
if (!empty($sid) && preg_match('#^[0-9a-zA-Z,-]+$#', $sid))
{
session_id($sid);
}
return $this;
}
/**
* Retrieve current session id
* @return string
*/
public function getSessionId()
{
return session_id();
}
/**
* Retrieve current session save method.
* @return string
*/
public function getSaveMethod()
{
return $this->_sessionSaveMethod;
}
/**
* Set new session name
* @param string $name alphanumeric characters only
* @return string old session name or false on error
*/
public function setSessionName($name)
{
if (!empty($name) && preg_match('#^[0-9a-z_]+$#i', $name))
{
$this->_name = $name;
return session_name($name);
}
return false;
}
/**
* Retrieve current session name
* @return string
*/
public function getSessionName()
{
return session_name();
}
/**
* Reset session cookie lifetime
* We reset session cookie on every (session_lifetime / 4) seconds
* It's done by all session handler instances, they all share
* one and the same '_cookie_session_validate' variable (global session namespace)
* @return e_session
*/
public function validateSessionCookie()
{
if (!$this->_options['lifetime'])
{
return $this;
}
if (empty($_SESSION['_cookie_session_validate']))
{
$time = time() + round($this->_options['lifetime'] / 4);
$_SESSION['_cookie_session_validate'] = $time;
}
elseif ($_SESSION['_cookie_session_validate'] < time())
{
if (!headers_sent())
{
cookie(session_name(), session_id(), time() + $this->_options['lifetime'], $this->_options['path'], $this->_options['domain'], $this->_options['secure']);
$time = time() + round($this->_options['lifetime'] / 4);
$_SESSION['_cookie_session_validate'] = $time;
}
}
return $this;
}
/**
* Delete session cookie
* @return e_session
*/
public function cookieDelete()
{
cookie(session_name(), null, null, $this->_options['path'], $this->_options['domain'], $this->_options['secure']);
return $this;
}
/**
* Validate current session
* @return e_session
*/
public function validate()
{
if (!isset($this->_data['_session_validate_data']))
{
$this->_data['_session_validate_data'] = $this->getValidateData();
}
elseif (!$this->_validate())
{
$sessionData = $this->_data['_session_validate_data'];
$validateData = $this->getValidateData();
$details = 'USER INFORMATION: '.(isset($_COOKIE[e_COOKIE]) ? $_COOKIE[e_COOKIE] : (isset($_SESSION[e_COOKIE]) ? $_SESSION[e_COOKIE] : 'n/a'))."\n";
$details .= "HOST: ".$_SERVER['HTTP_HOST']."\n";
$details .= "REQUEST_URI: ".$_SERVER['REQUEST_URI']."\n";
$details .= "SESSION OPTIONS: ".print_r($this->_options, true)."\n";
$details .= "SESSION NAMESPACE: ".$this->_namespace."\n";
$details .= "SESSION VALIDATION DATA SAVED: ".print_r($sessionData, true)."\n";
$details .= "SESSION VALIDATION DATA CURRENT: ".print_r($validateData, true)."\n";
$details .= "CURRENT NAMESPACE SESSION DATA:\n";
$this->clear('_session_validate_data'); // already logged
$details .= print_r($this->_data, true);
$this->close(false);
$details .= "SESSION GLOBAL DATA:\n";
$details .= print_r($_SESSION, true);
// delete cookie, destroy session
$this->cookieDelete()->destroy();
// TODO event trigger
// e107::getAdminLog()->log_event('Session validation failed!', $details, E_LOG_FATAL);
// TODO session exception, handle it proper on live site
// throw new Exception('');
// just for now
$msg = 'Session validation failed! <a href="'.strip_tags($_SERVER['REQUEST_URI']).'">Go Back</a>';
// die($msg); //FIXME not functioning as intended.
}
return $this;
}
/**
* Validate current session based on config options
*
* @return bool
*/
protected function _validate()
{
$sessionData = $this->_data['_session_validate_data'];
$validateData = $this->getValidateData();
$keyvar = '_sessionValidate';
foreach ($validateData as $vkey => $value)
{
$var = $keyvar.$vkey;
$varskip = $var.'Skip';
if ($this->$var && $sessionData[$vkey] != $value && !in_array($value, $this->$varskip))
{
return false;
}
}
return true;
}
/**
* Retrieve data for validator
* @return array
*/
public function getValidateData()
{
$data = array(
'RemoteAddr' => '',
'HttpVia' => '',
'HttpXForwardedFor' => '',
'HttpUserAgent' => ''
);
// collect ip data
if (isset($_SERVER['REMOTE_ADDR']))
{
$data['RemoteAddr'] = (string) $_SERVER['REMOTE_ADDR'];
}
if (isset($_ENV['HTTP_VIA']))
{
$data['HttpVia'] = (string) $_ENV['HTTP_VIA'];
}
if (isset($_ENV['HTTP_X_FORWARDED_FOR']))
{
$data['HttpXForwardedFor'] = (string) $_ENV['HTTP_X_FORWARDED_FOR'];
}
// collect user agent data
if (isset($_SERVER['HTTP_USER_AGENT']))
{
$data['HttpUserAgent'] = (string) $_SERVER['HTTP_USER_AGENT'];
}
return $data;
}
/**
* Retrieve (create if doesn't exist) XSF protection token
* @param boolean $in_form if true (default) - value for forms, else raw session value
* @return string
*/
public function getFormToken($in_form = true)
{
if(!$this->has('__form_token') && !defined('e_TOKEN_DISABLE')) // TODO FIXME: SEF URL of Error page causes e-token refresh.
{
$this->set('__form_token', uniqid(md5(rand()), true));
if(deftrue('e_DEBUG_SESSION')) // XXX enable to troubleshoot "Unauthorized Access!" issues.
{
$message = date('r')."\t\t".e_REQUEST_URI."\n";
file_put_contents(__DIR__.'/session.log', $message, FILE_APPEND);
}
}
return ($in_form ? md5($this->get('__form_token')) : $this->get('__form_token'));
}
/**
* Regenerate form token value
* TODO - save old token
* @return e_session
*/
protected function _regenerateFormToken()
{
$this->set('__form_token', uniqid(md5(rand()), true));
return $this;
}
/**
* Do a check against passed token
* @param string $token
* @return boolean
*/
public function checkFormToken($token)
{
$utoken = $this->getFormToken(false);
return ($token === md5($utoken));
}
/**
* Clear and Unset current namespace, unregister session singleton
* e107::getSession('namespace') if needed.
* @param boolean $unregister if true (default) - unregister Singleton, destroy namespace,
* else alias of self::clearData()
* @return void
*/
public function close($unregister = true)
{
$this->clearData();
if($unregister)
{
unset($_SESSION[$this->_namespace]);
e107::setRegistry('core/e107/session/'.$this->_namespace, null);
}
}
/**
* Save session data to disk, end session.
* Sessions can't be used after this point.
* Method should be called before every header redirect.
* @return void
*/
public function end()
{
session_write_close();
}
/**
* Destroy all session data
* @return e_session
*/
public function destroy()
{
$this->cookieDelete()->close();
//unset($_SESSION);
// cleanup
cookie(e_COOKIE, null, null); // remove user auth cookie
// unset($_SESSION['_cookie_session_validate']);
session_destroy();
return $this;
}
public function replaceRegistry()
{
e107::setRegistry('core/e107/session/'.$this->_namespace, $this, true);
}
}
class e_core_session extends e_session
{
/**
* Constructor
* 3rd party code and/or other system areas are
* able to extend the base e_session class and
* add more or override the implemented functionality, has their own
* namespace, add more session security etc.
* @param array $data session config data
*/
public function __construct($data = array())
{
// default system configuration
$this->setDefaultSystemConfig();
$namespace = 'e107sess'; // Quick Fix for Fatal Error "Cannot use object of type e107 as array" on line 550
$name = (isset($data['name']) && !empty($data['name']) ? $data['name'] : deftrue('e_COOKIE', 'e107')).'SID';
if(isset($data['namespace']) && !empty($data['namespace'])) $namespace = $data['namespace'];
// create $_SESSION['e107'] namespace by default
$this->init($namespace, $name);
}
/**
* Session shutdown - called at the top of footer_default.php by default
* @return void
*/
public function shutdown()
{
if(!session_id()) // someone closed the session?
{
$this->init($this->_namespace, $this->_name); // restart
}
// give 3rd party code a way to prevent token re-generation
if(e_SECURITY_LEVEL >= e_session::SECURITY_LEVEL_PARANOID && !deftrue('e_TOKEN_FREEZE'))
{
if(e_SECURITY_LEVEL == e_session::SECURITY_LEVEL_INSANE)
{
// regenerate SID
$oldSID = session_id(); // old SID
$oldSData = $_SESSION; // old session data
session_regenerate_id(false); // true don't work on php4 - so time to move on people!
$newSID = session_id(); // new SID
// Clean
session_id($oldSID); // switch to the old session
session_destroy(); // destroy it
// set new ID, reopen the session, set saved data
session_id($newSID);
session_start();
$_SESSION = $oldSData;
}
$this->set('__form_token_regenerate', time()); // check() needs it to re-create token on the next request
}
// write session data
$this->end();
}
private function log($status, $type=E_LOG_FATAL)
{
if(!deftrue('e_DEBUG_SESSION'))
{
return null;
}
// $details = "USER: ".USERNAME."\n";
$details = "HOST: ".$_SERVER['HTTP_HOST']."\n";
$details .= "REQUEST_URI: ".$_SERVER['REQUEST_URI']."\n";
$details .= ($_POST['e-token']) ? "e-token (POST): ".$_POST['e-token']."\n" : "";
$details .= ($_GET['e-token']) ? "e-token (GET): ".$_GET['e-token']."\n" : "";
$details .= ($_POST['e_token']) ? "AJAX e_token (POST): ".$_POST['e_token']."\n" : "";
/*
$utoken = $this->getFormToken(false);
$details .= "raw token: ".$utoken."\n";
$details .= "checkFormToken (e-token should match this): ".md5($utoken)."\n";
$details .= "md5(e-token): ".md5($_POST['e-token'])."\n";*/
/*
$regenerate = $this->get('__form_token_regenerate');
$details .= "Regenerate after: ".date('r', $regenerate)." (".$regenerate.")\n";
*/
$details .= "has __form_token: ";
$hasToken = $this->has('__form_token');
$details .= empty($hasToken) ? 'false' : 'true';
$details .= "\n";
$details .= "_SESSION:\n";
$details .= print_r($_SESSION,true);
/* if($pref['plug_installed'])
{
$details .= "\nPlugins:\n";
$details .= print_r($pref['plug_installed'],true);
}*/
$details .= $status."\n\n---------------------------------\n\n";
$log = e107::getAdminLog();
$log->addDebug($details);
if(deftrue('e_DEBUG_SESSION'))
{
$log->toFile('Unauthorized_access','Unauthorized access Log', true);
}
$log->add($status, $details, $type);
}
/**
* Core CSF protection, see class2.php
* Could be adopted by plugins for their own (different) protection logic
* @param boolean $die
* @return boolean
*/
public function check($die = true)
{
// define('e_TOKEN_NAME', 'e107_token_'.md5($_SERVER['HTTP_HOST'].e_HTTP));
// TODO e-token required for all system forms?
// only if not disabled and not in 'cli' mod
if(e_SECURITY_LEVEL < e_session::SECURITY_LEVEL_BALANCED || e107::getE107('cli')) return true;
if($this->getSessionId())
{
if((isset($_POST['e-token']) && !$this->checkFormToken($_POST['e-token']))
|| (isset($_GET['e-token']) && !$this->checkFormToken($_GET['e-token']))
|| (isset($_POST['e_token']) && !$this->checkFormToken($_POST['e_token']))) // '-' is not allowed in jquery. b
{
$this->log('Unauthorized access!');
// do not redirect, prevent dead loop, save server resources
if($die == true)
{
die('Unauthorized access!');
}
return false;
}
$this->log('Session Token Okay!', E_LOG_NOTICE);
}
if(!defined('e_TOKEN'))
{
// FREEZE token regeneration if minimal, ajax or iframe (ajax and iframe not implemented yet) request
$_toFreeze = (e107::getE107('minimal') || e107::getE107('ajax') || e107::getE107('iframe'));
if(!defined('e_TOKEN_FREEZE') && $_toFreeze)
{
define('e_TOKEN_FREEZE', true);
}
// __form_token_regenerate set in footer, so if footer is not called, token will be never regenerated!
if(e_SECURITY_LEVEL == e_session::SECURITY_LEVEL_INSANE && !deftrue('e_TOKEN_FREEZE') && $this->has('__form_token_regenerate'))
{
$this->_regenerateFormToken()
->clear('__form_token_regenerate');
}
define('e_TOKEN', $this->getFormToken());
}
return true;
}
/**
* Manually Reset the Token.