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
| <?php
//=================================================================================================
/**
* @Project : BEANZ FRAMEWORK for PHP
* @Version : 1.0
* @Licence : AGPL
*
* @package : BEANZ
* @subpackage : FRAMEWORK
* @category : CORE
* @Last_Update : 21/08/2016
*
* @Desc : Class gestionaire de session sécurisé CRSF, XSS, Fixation, Anti-hijacking
* @SeeAlso :
* @Example :
*
* @Todo :
**/
//=================================================================================================
/**
* _____________________________________________________________________________
*
* @name : SessionHandlerInterface
* @desc : Interface IO pour les sessions sin PHP <5.3
* _____________________________________________________________________________
**/
if (!PHP5)
{
interface SessionHandlerInterface
{
public function open($savePath, $sessionName);
public function close();
public function read($id);
public function write($id, $data);
public function destroy($id);
public function gc($maxlifetime);
}
}
/**
* _____________________________________________________________________________
*
* @name : Core_File_SessionHandler
* @desc : Adaptater IO pour l'ecriture des sessions dans un fichier
* _____________________________________________________________________________
**/
class Core_File_SessionHandler implements SessionHandlerInterface
{
private $_savePath;
private $_sessionName;
public function open($savePath, $sessionName)
{
$this->_savePath = $savePath;
$this->_sessionName = $sessionName;
if (!is_dir($this->savePath))
{
mkdir($this->savePath, 0777);
}
return TRUE;
}
public function close()
{
return TRUE;
}
public function read($id)
{
return (string )@file_get_contents("$this->savePath/sess_$this->sessionName_$id");
}
public function write($id, $data)
{
return file_put_contents("$this->savePath/sess_$this->sessionName_$id", $data) === FALSE ? FALSE : TRUE;
}
public function destroy($id)
{
$file = "$this->savePath/sess_$this->sessionName_$id";
if (file_exists($file))
{
unlink($file);
}
return TRUE;
}
public function gc($maxlifetime)
{
foreach (glob("$this->savePath/sess_$this->sessionName_*") as $file)
{
if (filemtime($file) + $maxlifetime < time() && file_exists($file))
{
unlink($file);
}
}
return TRUE;
}
}
/**
* _____________________________________________________________________________
*
* @name : Core_DB_SessionHandler
* @desc : Adaptater IO pour l'ecriture des sessions dans une BDD via PDO
* _____________________________________________________________________________
**/
class Core_DB_SessionHandler implements SessionHandlerInterface
{
protected $options = array(); // Options de la session
protected static $db = NULL; // Acceder a la BDD
public function __construct($options, $pdo)
{
$this->options = $options;
self::$db = $pdo;
}
/**
* _______________________________________________________
*
* @name : SessionOpen
* @desc : Handler, ouvre une session
*
* @param :
*
* @return :
* @example :
*/
public function open($savePath, $sessionName)
{
DebugTool::Log('Ouverture de la session : ' . $sessionName);
$now = time();
$req = self::$db->prepare("DELETE FROM bnz_sessions WHERE expire < :expire ");
$req->execute(array('expire' => $now));
return TRUE;
}
/**
* _______________________________________________________
*
* @name : SessionClose
* @desc : Handler, ferme la session
*
* @param :
*
* @return :
* @example :
*/
public function close()
{
DebugTool::Log('Fermeture de la session');
$this->gc(ini_get('session.gc_maxlifetime'));
}
/**
* _______________________________________________________
*
* @name : SessionRead
* @desc : Handler, lit la session
*
* @param :
*
* @return :
* @example :
*/
public function read($id)
{
DebugTool::Log('Lecture de la session : ' . $id);
// $this->id = $id;
//$now = time();
try
{
$stmt = self::$db->query("SELECT data FROM bnz_sessions WHERE sid = '$id'");
// AND expire < '$now'");
$result = $stmt->fetchColumn();
//DebugTool::Log('-----> Read Data: ' . $result.$id,'info');
}
catch (PDOException $e)
{
throw new Core_Exception(sprintf('PDOException was thrown when trying to read the session data: %s', $e->getMessage()), 0, $e);
}
return $result;
}
/**
* _______________________________________________________
*
* @name : SessionWrite
* @desc : Handler, ecrit la session
*
* @param :
*
* @return :
* @example :
*/
public function write($id, $data)
{
DebugTool::Log('Ecriture de la session : ' . $id);
DebugTool::Log('WRITING SESSION...');
//DebugTool::Log(' -----> Write Data '.$data,'info');
//$this->id = $id;
if (array_key_exists('TIMEOUT', $_SESSION))
{
$newExp = $_SESSION['TIMEOUT'];
}
else
{
$newExp = time() + $this->options['time_limiter'];
}
DebugTool::Log('Session -> Write Expire : '.$newExp,'warning');
try
{
DebugTool::Log('WRITING SESSION...');
$req = self::$db->prepare('INSERT INTO bnz_sessions (sid, data, expire) VALUES (:sid, :data, :expire)
ON DUPLICATE KEY UPDATE data = :data, expire = :expire');
$vals = array('sid' => $id, 'data' => $data, 'expire' => $newExp);
$req->execute($vals);
DebugTool::Log('WRITING SESSION : ' .$_SESSION);
return TRUE;
//return ($stmt->rowCount() === 1) ? true : false;
}
catch (PDOException $e)
{
throw new Core_Exception(sprintf('PDOException was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e);
}
}
/**
* _______________________________________________________
*
* @name : SessionDestroy
* @desc : Handler, detruit la session
*
* @param :
*
* @return :
* @example :
*/
public function destroy($id)
{
DebugTool::Log('Destruction de la session : ' . $id);
$stmt = self::$db->prepare("DELETE FROM bnz_sessions WHERE sid = :sid");
$stmt->execute(array('sid' => $id));
//return ($stmt->rowCount() === 1) ? true : false;
return TRUE;
}
/**
* _______________________________________________________
*
* @name : SessionGC
* @desc : Handler, GC, efface une session si celle-ci est expir�e
*
* @param :
*
* @return :
* @example :
*/
public function gc($maxlifetime)
{
DebugTool::Log('Session GC : ' . $maxlifetime);
$now = time();
$req = self::$db->prepare("DELETE FROM bnz_sessions WHERE expire < ? ");
$req->execute(array($now));
//$row = $req->fetch(PDO::FETCH_ASSOC);
// $this->db->execute($_SESSION[self::TIMEOUT]);
// return self::$db->affected_rows();
return TRUE;
}
}
/**
* _____________________________________________________________________________
*
* @name : Core_SessionManager
* @desc : Class utilitaire pour gérer les sessions
* _____________________________________________________________________________
**/
class Core_SessionManager extends Core_Singleton_Object implements Iterator, Countable, ArrayAccess
{
//=============================================================================================================================================*/
//=============================================================================================================================================*/
// PROPRIETES
//=============================================================================================================================================*/
//--------------------------------------------------------------------------------------------------------
// CONSTANTE --------------------------------------------
//-------------------------------------------------------
const // Nom des elements de sessions par defaut
CREATE = 'CREATE', IP = 'USER_IP', // UID = 'USER_ID',
NAV = 'USER_BROWSER', TIMEOUT = 'TIMEOUT', LANGUAGE = 'LANG', REFERER = 'REFERER';
//--------------------------------------------------------------------------------------------------------
// PRIVATE ----------------------------------------------
//-------------------------------------------------------
//private $SALT_LENGTH = 64; // Longeur du hash "grain de sel"
private $_iCount; // Nombre d'élément du tableau
private $_iIndex; // Index de l'itérateur
private static $fingerprint = NULL; // Securité Anti-hijacking
private $_cryptkey;
//--------------------------------------------------------------------------------------------------------
// PROTECTED --------------------------------------------
//-------------------------------------------------------
protected $name; // Nom de la session
protected $useCookies = FALSE;
protected $options = array(); // Options de la session
protected static $db = NULL; // Acceder a la BDD
protected static $isStarted = FALSE;
//--------------------------------------------------------------------------------------------------------
// PUBLIC -----------------------------------------------
//-------------------------------------------------------
public $id; // ID de la session en cours
//=============================================================================================================================================*/
//=============================================================================================================================================*/
// FONCTIONS
//=============================================================================================================================================*/
private function getSecureKey($Key)
{
return Core_SecurityTool::GetUniqid(8, $Key, FALSE);
}
//--------------------------------------------------------------------------------------------------------
// CONSTRUCTOR / DESTRUCTOR -----------------------------
//-------------------------------------------------------
/**
* _______________________________________________________
*
* @name : __construct
* @desc : Constructeur de la classe
*
* @param : Core_Pdo $pdo
* @param : string $name Nom de la session Optionnel
* @param : array $options Options de la session Optionnel
*
* @return : Core_SessionManager
* @example : $Session = new Core_SessionManager($pdo,'sessionname')
*/
public function __construct(Core_Pdo $pdo, $name = 'BEANZSESSION', array $options = array())
{
DebugTool::Log('Creation du gestionnaire de sessions');
session_abort(); // fermeture de la session en cours
self::$db = $pdo;
$this->_iIndex = 0;
$this->_iCount = 0;
$this->name = $name;
$this->useCookies = (boolean)ini_get('session.use_cookies');
$cookie = session_get_cookie_params();
//$Cache = array('public', 'private', 'nocache','private_no_expire');
$CFG = BEANZ::$ConfigManager->APPLICATION->SYSTEM->SESSION;
$this->options = array_merge(array('auto_start' => TRUE,
'use_DB' => $CFG->UseDB, //$this -> Config['CACHE_LIMIT'] = $Cache[(int)$cacheLimit];
'cache_limiter' => $CFG->CacheLimiter,
'time_limiter' => $CFG->LifeTime,
'time_cookie_limiter' => $CFG->COOKIE->LifeTime,
'session_secure' => TRUE, //protection CRSF et XSS
'session_save_path' => NULL,
'session_id' => NULL,
'REGENERATE_ID' => TRUE, // protection session fixation
'session_cookie_lifetime' => $CFG->COOKIE->LifeTime,
'session_cookie_path' => $CFG->COOKIE->Path,
'session_cookie_domain' => $CFG->COOKIE->Domain,
'session_cookie_secure' => $CFG->COOKIE->Secure, //$cookie['secure'],
'session_cookie_httponly' => isset($cookie['httponly']) ? $cookie['httponly'] : FALSE
), $options);
if (ini_get('session.auto_start'))
{
session_name($this->name);
if ($this->options['session_id'])
{
session_id($this->options['session_id']);
}
if ($this->options['session_save_path'])
{
session_save_path($this->options['session_save_path']);
}
if ($this->options['cache_limiter'])
{
session_cache_limiter($this->options['cache_limiter']);
}
if ('nocache' !== $this->options['cache_limiter'] && $this->options['time_limiter'])
{
session_cache_expire($this->options['time_limiter']);
}
if ($this->useCookies)
{
session_set_cookie_params($this->options['session_cookie_lifetime'], $this->options['session_cookie_path'], $this->options['session_cookie_domain'], $this->options['session_cookie_secure'], $this->options['session_cookie_httponly']);
}
}
$handler = new Core_DB_SessionHandler($this->options, self::$db);
if (PHP5) //si Version PHP >= 5.3
{
if (!session_set_save_handler($handler, TRUE))
{
throw new Core_Exception('Erreur lors de l\'init des sessions !');
}
}
else
{
if (!session_set_save_handler(array(&$handler, 'Open'), array(&$handler, 'Close'), array(&$handler, 'Read'), array(&$handler, 'Write'), array(&$handler, 'Destroy'), array(&$handler, 'Gc'))
)
{
throw new Core_Exception('Erreur lors de l\'init des sessions !');
}
}
register_shutdown_function('session_write_close');
$this->start();
}
//--------------------------------------------------------------------------------------------------------
// PRIVATE ----------------------------------------------
//-------------------------------------------------------
/**
* _______________________________________________________
*
* @name : generateHash
* @desc : Genere un hash
*
* @param : string $str
*
* @return :
* @example : $hash = self::_generateHash('masession')
*/
private function _generateHash($str)
{
$salt = substr(md5(uniqid(mt_rand(), TRUE)), 0, 32);
$salt2 = substr(md5(uniqid(mt_rand(), TRUE)), 0, 32);
return $salt . hash('sha256', strrev($salt) . $str) . $salt2;
}
/**
* _______________________________________________________
*
* @name : getUserCheckId
* @desc : Recupere l'ID de la session en cours
*
* @param : -
*
* @return : string
* @example : $id self::_geUserCheckId
*/
private function _getUserCheckId()
{
// On recupere l'ip
$checkKey = Core_IPTool::Get_IP();
DebugTool::Log('IP {@4} : ' . $checkKey, 'info');
// On recupere des variables d'environnement
$checkKey .= DevTool::GetEnvVar('HTTP_ACCEPT_CHARSET');
$checkKey .= DevTool::GetEnvVar('HTTP_ACCEPT_ENCODING');
$checkKey .= DevTool::GetEnvVar('HTTP_ACCEPT_LANGUAGE');
$checkKey .= DevTool::GetEnvVar('HTTP_USER_AGENT');
DebugTool::Log('Navigateur {@4} : ' . implode('{/}{@16} - ', explode(';', DevTool::GetEnvVar('HTTP_USER_AGENT'))), 'info');
// Retourne un hash
return $this->_generateHash($checkKey);
}
/**
* _______________________________________________________
*
* @name : checkHost
* @desc : Vérification contre les attaques CRSF
*
* @param : -
*
* @return : Bool
* @example : $ok=self::_checkCRSF
*/
private function _checkCRSF()
{
$result = TRUE;
if (http_Request::isPost())
{
$referer = $this->getSecureKey(self::REFERER);
if (!isset($_SESSION[$referer]))
{
if (isset($_SERVER['HTTP_REFERER']))
{
$_SESSION[$referer] = $this->_cryptdatas(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST));
$result = TRUE;
}
else
{
if (isset($_SERVER['HTTP_HOST']))
{
$_SESSION[$referer] = $this->_cryptdatas($_SERVER['HTTP_HOST']);
$result = TRUE;
}
elseif (isset($_SERVER['SERVER_NAME']))
{
$_SESSION[$referer] = $this->_cryptdatas($_SERVER['SERVER_NAME']);
$result = TRUE;
}
}
}
else
{
//if (isset($_SERVER['HTTP_REFERER'])) {
$refdatas = $this->_decryptdatas($_SESSION[$referer]);
DebugTool::Log('CHECK REFERER DATA ('.$referer.') = '. $refdatas,'info');
DebugTool::Log('CHECK REFERER referer = '. parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST),'info');
DebugTool::Log('CHECK REFERER host = '. $_SERVER['HTTP_HOST'],'info');
DebugTool::Log('CHECK REFERER server = '. $_SERVER['SERVER_NAME'],'info');
if (($refdatas !== parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST)) || ($refdatas !== $_SERVER['SERVER_NAME']) || (strpos($_SERVER['HTTP_HOST'] , $refdatas) === false))
{
$result = FALSE;
throw new Core_Exception('The query referer is redirected from another website : ' . $refdatas);
}
/*else {
if (isset($_SERVER['HTTP_HOST'])) {
if ($_SESSION[self::REFERER] !== $_SERVER['HTTP_HOST'])
{
//$result = false;
throw new Core_Exception('The query host is redirected from another website : '.$_SERVER['HTTP_HOST']);
}
else
{
$result = true;
}
}
elseif (isset($_SERVER['SERVER_NAME'])) {
if ($_SESSION[self::REFERER] !== $_SERVER['SERVER_NAME'])
{
//$result = false;
throw new Core_Exception('The query server is redirected from another website : '.$_SERVER['SERVER_NAME']);
}
else
{
$result = true;
}
}
}*/
}
}
return $result;
}
/**
* _______________________________________________________
*
* @name : secure
* @desc : Securise la session
*
* @param : -
*
* @return : -
* @example : $this->_secure()
*/
private function _secure()
{
//On définit qu'elle a déja ete créée
//BEANZ::LogManager()->Write('----> Secure Session');
DebugTool::Log('Secure Session');
$create = $this->getSecureKey(self::CREATE);
$ip = $this->getSecureKey(self::IP);
$nav = $this->getSecureKey(self::NAV);
$language = $this->getSecureKey(self::LANGUAGE);
$timeout = $this->getSecureKey(self::TIMEOUT);
$_SESSION[$create] = $this->_cryptdatas(1);
$_SESSION[$ip] = $this->_cryptdatas(Core_IPTool::Get_IP());
$_SESSION[$nav] = $this->_cryptdatas(http_Request::getServer('HTTP_USER_AGENT'));
$_SESSION[$language] = $this->_cryptdatas(http_Request::getServer('HTTP_ACCEPT_LANGUAGE'));
$_SESSION[$timeout] = $this->_cryptdatas(time() + $this->options['time_limiter']);
if ($this->options['session_secure'])
{
$this->_checkCRSF();
}
self::$fingerprint = self::_getUserCheckId();
}
//--------------------------------------------------------------------------------------------------------
// PROTECTED --------------------------------------------
//-------------------------------------------------------
/**
* _______________________________________________________
*
* @name : checkSession
* @desc : Verifie si la session est valide
*
* @param : -
*
* @return : Bool
* @example : $o = $this->CheckSession
*/
protected function _checkSession()
{
//BEANZ::LogManager()->Write('----> Check Session ');
DebugTool::Log('Vérification de la Session', 'info');
//Vérifie que c'est le même utilisateur
$create = $this->getSecureKey(self::CREATE); // @TODO : Ajouter grain de sel
$ip = $this->getSecureKey(self::IP);
$nav = $this->getSecureKey(self::NAV);
$language = $this->getSecureKey(self::LANGUAGE);
$timeout = $this->getSecureKey(self::TIMEOUT);
$httlang = (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : 'unknown';
$Session_OK = ($this->_decryptdatas($_SESSION[$ip]) === Core_IPTool::Get_IP()) && ($this->_decryptdatas($_SESSION[$nav]) === $_SERVER['HTTP_USER_AGENT']) && ($this->_decryptdatas($_SESSION[$language]) === $httlang);
$sok = ($Session_OK == TRUE) ? 'OK' : 'ERREUR';
//BEANZ::LogManager()->Write('-----> Check Default : ' . $sok);
DebugTool::Log('Vérification Session de base : ' . $sok, 'info');
// Si CSRF est activer et que l'utilisateur a un referer (dans le cas ou il arrive via un favoris, directement via la barre d'adresse, ...)
if ($this->options['session_secure'])
{
$Session_OK = $this->_checkCRSF();
$sok = ($Session_OK == TRUE) ? 'OK' : 'ERREUR';
DebugTool::Log('Sécurisation Session CRSF : ' . $sok, 'info');
//BEANZ::LogManager()->Write('-----> Check CRSF : ' . $sok);
}
$Session_OK &= ($this->_decryptdatas($_SESSION[$timeout]) > time());
$sok = ($Session_OK == TRUE) ? 'OK' : 'ERREUR';
DebugTool::Log('Vérification Session délai d\'expiration : ' . $sok, 'info');
//BEANZ::LogManager()->Write('-----> Check TIMEOUT : (' . $_SESSION[self::TIMEOUT] . ') > ' . time() . ' : ' . $sok);
// prevent session hijacking
if (!is_null(self::$fingerprint))
{
if (self::$fingerprint !== $this->_getUserCheckId())
{
$Session_OK = FALSE;
}
}
else
{
self::$fingerprint = $this->_getUserCheckId();
//BEANZ::LogManager()->Write('-----> Check Fingerprint : OK');
}
$sok = ($Session_OK == TRUE) ? 'OK' : 'NOK';
DebugTool::Log('Vérification Session Empreinte : ' . $sok, 'info');
//Si la session est valable
if ($Session_OK)
{
//$_SESSION[self::TIMEOUT] = time() + $this->options['time_limiter'];
//BEANZ::LogManager()->Write('----> Check Session : SUCCESS');
DebugTool::Log(' --> Vérification de la session passé avec succes', 'info');
return TRUE;
//Sinon
}
else
{
//on détruit la session, et on réinitialise tout
//BEANZ::LogManager()->Write('----> Check Session : FAILED');
DebugTool::Log(' --> Vérification de la session échoué', 'warning');
$this->destruct();
return FALSE;
}
}
/**
* _______________________________________________________
*
* @name : start
* @desc : Demarrage de la session
*
* @param : -
*
* @return : -
* @example : $this->Start()
*/
protected function start()
{
/* if ( ($this->options['auto_start']) && (!self::$isStarted) ) { */
DebugTool::Log('Lancement du gestionnaire de session == '.self::CREATE);
$create = $this->getSecureKey(self::CREATE); // @TODO : Ajouter grain de sel pseudo-aleatoire ????
//$create = 'ABC10DEF77';
DebugTool::Log('CREATE ID = '.$create);
if (!session_start()) {
throw new Core_Exception('Erreur lors du démarrage de la session !');
}
/* include('core_sessionstart_handler.php'); --- CODE = "<?php session_start(); ?>"
--> ne fonctionne pas également et renvoi en plus :
Header may not contain more than a single header, new line detected in C:\wamp64\www\beanzdev\framework\lib\core\components\sessionmanager\core_sessionmanager.class.php on line 696
*/
$this->Flush();
//Si la session existe déja
if (isset($_SESSION[$create]) && ($this->_decryptdatas($_SESSION[$create]) == 1))
{
//Si la session n'est pas conforme
if (!$this->_checkSession())
{
$this->destruct();
if ($this->options['REGENERATE_ID'])
{
session_regenerate_id(FALSE);
}
$this->_secure();
}
}
else
{
$this->destruct();
if ($this->options['REGENERATE_ID'])
{
session_regenerate_id(TRUE);
}
$this->_secure();
}
self::$isStarted = TRUE;
}
private function _decryptdatas($datas)
{
$Key = Core_IPTool::Get_IP() . date('Y-m-d') . $_SERVER['HTTP_USER_AGENT'];
$Key = Core_SecurityTool::GetSecureKey($Key);
return Core_SecurityTool::decrypt($datas, $Key);
}
private function _cryptdatas($datas)
{
$Key = Core_IPTool::Get_IP() . date('Y-m-d') . $_SERVER['HTTP_USER_AGENT'];
$Key = Core_SecurityTool::GetSecureKey($Key);
return Core_SecurityTool::encrypt($datas, $Key);
}
//--------------------------------------------------------------------------------------------------------
// MAGIC ------------------------------------------------
//-------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// PUBLIC -----------------------------------------------
//-------------------------------------------------------
public function __get($offset)
{
return isset($_SESSION[$offset]) ? ($this->_decryptdatas($_SESSION[$offset])) : NULL;
}
public function __set($offset, $value)
{
$_SESSION[$offset] = $this->_cryptdatas($value);
}
public function __isset($offset)
{
return isset($_SESSION[$offset]);
}
public function __unset($offset)
{
unset($_SESSION[$offset]);
}
/**
* _______________________________________________________
*
* @name : Count
* @desc : Retourne le nombre d'élément du tableau MAP
*
* @param :
*
* @return :
* @example :
*/
public function count()
{
$this->_iCount = count($_SESSION);
return $this->_iCount;
}
/**
* _______________________________________________________
*
* @name : current
* @desc : Retourne l'élément courrant du tableau MAP
*
* @param :
*
* @return :
* @example :
*/
public function current()
{
return current($_SESSION);
}
/**
* _______________________________________________________
*
* @name : key
* @desc : Retourne la clé de l'élément courant du tableau MAP
*
* @param :
*
* @return :
* @example :
*/
public function key()
{
return key($_SESSION);
}
/**
* _______________________________________________________
*
* @name : next
* @desc : Passe le pointeur sur l'élément suivant dans le tableau MAP
*
* @param :
*
* @return :
* @example :
*/
public function next()
{
next($_SESSION);
$this->_iIndex++;
}
/**
* _______________________________________________________
*
* @name : rewind
* @desc : Met le pointeur au début du tableau MAP
*
* @param :
*
* @return :
* @example :
*/
public function rewind()
{
// reset(array($_SESSION));
$this->_iIndex = 0;
}
/**
* _______________________________________________________
*
* @name : valid
* @desc : Test si l'iterateur courant du tableau MAP est valide
*
* @param :
*
* @return :
* @example :
*/
public function valid()
{
return $this->_iIndex < $this->_iCount;
}
/**
* _______________________________________________________
*
* @name : offsetExists
* @desc : Test l'existance de l'élément dans le tableau MAP
*
* @param :
*
* @return :
* @example :
*/
public function offsetExists($mOffset)
{
return isset($_SESSION[$mOffset]);
}
/**
* _______________________________________________________
*
* @name : offsetGet
* @desc : Retourne un élément du tableau MAP
*
* @param :
*
* @return :
* @example :
*/
public function offsetGet($mOffset)
{
return isset($_SESSION[$mOffset]) ? $this->_decryptdatas($_SESSION[$mOffset]) : NULL;
}
/**
* _______________________________________________________
*
* @name : offsetSet
* @desc : Modifie un élément du tableau MAP
*
* @param :
*
* @return :
* @example :
*/
public function offsetSet($mOffset, $mValue)
{
$_SESSION[$mOffset] = $this->_cryptdatas($mValue);
}
/**
* _______________________________________________________
*
* @name : offsetUnset
* @desc : Efface un élément du tableau MAP
*
* @param :
*
* @return :
* @example :
*/
public function offsetUnset($mOffset)
{
unset($_SESSION[$mOffset]);
}
public function Flush()
{
DebugTool::Log('Gestionnaire de sessions > Effacement des données obsolètes', 'info');
$now = time();
$req = self::$db->prepare("DELETE FROM bnz_sessions WHERE expire < ? ");
$req->execute(array($now));
}
/**
* _______________________________________________________
*
* @name : destruct
* @desc : Detruit et remet a zero la session
*
* @param :
*
* @return :
* @example :
*/
public function destruct()
{
//BEANZ::LogManager()->Write('----> Session Force Destruct');
DebugTool::Log('Gestionnaire de sessions > Destruction', 'info');
$_SESSION = array();
session_unset();
//session_destroy();
/*if ($this->useCookies) {
setcookie($this->name, '', time() + 42000, $this->options['session_cookie_path'], $this->options['session_cookie_domain'], $this->options['session_cookie_secure'], $this->options['session_cookie_httponly']);
}*/
$this->Flush();
$sid = $this->sid();
$req = self::$db->prepare("DELETE FROM bnz_sessions WHERE sid = '{1}' ");
$req->execute(array($sid));
if ($this->options['REGENERATE_ID'])
{
session_regenerate_id(TRUE);
$this->_secure();
}
self::$isStarted = TRUE;
//return true;
// $_SESSION = array();
// session_regenerate_id(false);
}
/**
* _______________________________________________________
*
* @name : sid
* @desc : Retourne l'id de la session
*
* @param :
*
* @return :
* @example :
*/
public function sid()
{
return session_id();
}
//--------------------------------------------------------------------------------------------------------
} |
Partager