]>
git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/3rdparty/Session.class.php
b56e4c545b23fa815d53c63b7c8e2a66e33cd0b7
3 * Session management class
5 * http://www.developpez.net/forums/d51943/php/langage/sessions/
6 * http://sebsauvage.net/wiki/doku.php?id=php:session
7 * http://sebsauvage.net/wiki/doku.php?id=php:shaarli
10 * - Everything is stored on server-side (we do not trust client-side data,
11 * such as cookie expiration)
12 * - IP addresses are checked on each access to prevent session cookie hijacking
14 * - Session expires on user inactivity (Session expiration date is
15 * automatically updated everytime the user accesses a page.)
16 * - A unique secret key is generated on server-side for this session
17 * (and never sent over the wire) which can be used to sign forms (HMAC)
18 * (See $_SESSION['uid'])
19 * - Token management to prevent XSRF attacks
20 * - Brute force protection with ban management
23 * - Replace globals with variables in Session class
26 * - http://tontof.net/kriss/php5/session
30 // Personnalize PHP session name
31 public static $sessionName = '' ;
32 // If the user does not access any page within this time,
33 // his/her session is considered expired (3600 sec. = 1 hour)
34 public static $inactivityTimeout = 3600 ;
35 // Extra timeout for long sessions (if enabled) (82800 sec. = 23 hours)
36 public static $longSessionTimeout = 7776000 ; // 7776000 = 90 days
37 // If you get disconnected often or if your IP address changes often.
38 // Let you disable session cookie hijacking protection
39 public static $disableSessionProtection = false ;
40 // Ban IP after this many failures.
41 public static $banAfter = 4 ;
42 // Ban duration for IP address after login failures (in seconds).
43 // (1800 sec. = 30 minutes)
44 public static $banDuration = 1800 ;
45 // File storage for failures and bans. If empty, no ban management.
46 public static $banFile = '' ;
51 public static function init ( $longlastingsession = false )
53 //check if session name is correct
54 if ( ( session_id () && ! empty ( self
:: $sessionName ) && session_name ()!= self
:: $sessionName ) || $longlastingsession ) {
58 // Force cookie path (but do not change lifetime)
59 $cookie = session_get_cookie_params ();
60 // Default cookie expiration and path.
62 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) {
63 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
66 if ( isset ( $_SERVER [ "HTTPS" ]) && $_SERVER [ "HTTPS" ] == "on" ) {
70 if ( $longlastingsession ) {
71 session_set_cookie_params ( self
:: $longSessionTimeout , $cookiedir , null , $ssl , true );
74 session_set_cookie_params ( 0 , $cookiedir , null , $ssl , true );
76 //set server side valid session timeout
77 //WARNING! this may not work in shared session environment. See http://www.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime about min value: it can be set in any application
78 ini_set ( 'session.gc_maxlifetime' , self
:: $longSessionTimeout );
80 // Use cookies to store session.
81 ini_set ( 'session.use_cookies' , 1 );
82 // Force cookies for session (phpsessionID forbidden in URL)
83 ini_set ( 'session.use_only_cookies' , 1 );
84 if ( ! session_id () ) {
85 // Prevent php to use sessionID in URL if cookies are disabled.
86 ini_set ( 'session.use_trans_sid' , false );
87 if (! empty ( self
:: $sessionName )) {
88 session_name ( self
:: $sessionName );
95 * Returns the IP address
96 * (Used to prevent session cookie hijacking.)
98 * @return string IP addresses
100 private static function _allIPs ()
102 $ip = $_SERVER [ "REMOTE_ADDR" ];
103 $ip .= isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ]) ? '_' . $_SERVER [ 'HTTP_X_FORWARDED_FOR' ] : '' ;
104 $ip .= isset ( $_SERVER [ 'HTTP_CLIENT_IP' ]) ? '_' . $_SERVER [ 'HTTP_CLIENT_IP' ] : '' ;
110 * Check that user/password is correct and then init some SESSION variables.
112 * @param string $login Login reference
113 * @param string $password Password reference
114 * @param string $loginTest Login to compare with login reference
115 * @param string $passwordTest Password to compare with password reference
116 * @param array $pValues Array of variables to store in SESSION
118 * @return true|false True if login and password are correct, false
121 public static function login (
130 if ( self
:: banCanLogin ()) {
131 if ( $login === $loginTest && $password === $passwordTest ) {
134 self
:: init ( $longlastingsession );
136 // Generate unique random number to sign forms (HMAC)
137 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ());
138 $_SESSION [ 'ip' ] = self
:: _allIPs ();
139 $_SESSION [ 'username' ] = $login ;
140 // Set session expiration.
141 $_SESSION [ 'expires_on' ] = time () + self
:: $inactivityTimeout ;
142 if ( $longlastingsession ) {
143 $_SESSION [ 'longlastingsession' ] = self
:: $longSessionTimeout ;
144 $_SESSION [ 'expires_on' ] +
= $_SESSION [ 'longlastingsession' ];
147 foreach ( $pValues as $key => $value ) {
148 $_SESSION [ $key ] = $value ;
153 self
:: banLoginFailed ();
161 * Unset SESSION variable to force logout
163 public static function logout ()
165 // unset($_SESSION['uid'],$_SESSION['ip'],$_SESSION['expires_on'],$_SESSION['tokens'], $_SESSION['login'], $_SESSION['pass'], $_SESSION['longlastingsession'], $_SESSION['poche_user']);
167 // Destruction du cookie (le code peut paraître complexe mais c'est pour être certain de reprendre les mêmes paramètres)
168 $args = array_merge ( array ( session_name (), '' ), array_values ( session_get_cookie_params ()));
169 $args [ 2 ] = time () - 3600 ;
170 call_user_func_array ( 'setcookie' , $args );
171 // Suppression physique de la session
176 * Make sure user is logged in.
178 * @return true|false True if user is logged in, false otherwise
180 public static function isLogged ()
182 if (! isset ( $_SESSION [ 'uid' ])
183 || ( self
:: $disableSessionProtection === false
184 && $_SESSION [ 'ip' ] !== self
:: _allIPs ())
185 || time () >= $_SESSION [ 'expires_on' ]) {
190 // User accessed a page : Update his/her session expiration date.
191 $_SESSION [ 'expires_on' ] = time () + self
:: $inactivityTimeout ;
192 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
193 $_SESSION [ 'expires_on' ] +
= $_SESSION [ 'longlastingsession' ];
200 * Create a token, store it in SESSION and return it
202 * @param string $salt to prevent birthday attack
204 * @return string Token created
206 public static function getToken ( $salt = '' )
208 if (! isset ( $_SESSION [ 'tokens' ])) {
209 $_SESSION [ 'tokens' ]= array ();
211 // We generate a random string and store it on the server side.
212 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand (). $salt );
213 $_SESSION [ 'tokens' ][ $rnd ]= 1 ;
219 * Tells if a token is ok. Using this function will destroy the token.
221 * @param string $token Token to test
223 * @return true|false True if token is correct, false otherwise
225 public static function isToken ( $token )
227 if ( isset ( $_SESSION [ 'tokens' ][ $token ])) {
228 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
230 return true ; // Token is ok.
233 return false ; // Wrong token, or already used.
237 * Signal a failed login. Will ban the IP if too many failures:
239 public static function banLoginFailed ()
241 if ( self
:: $banFile !== '' ) {
242 $ip = $_SERVER [ "REMOTE_ADDR" ];
243 $gb = $GLOBALS [ 'IPBANS' ];
245 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) {
246 $gb [ 'FAILURES' ][ $ip ] = 0 ;
248 $gb [ 'FAILURES' ][ $ip ] ++
;
249 if ( $gb [ 'FAILURES' ][ $ip ] > ( self
:: $banAfter - 1 )) {
250 $gb [ 'BANS' ][ $ip ]= time () + self
:: $banDuration ;
253 $GLOBALS [ 'IPBANS' ] = $gb ;
254 file_put_contents ( self
:: $banFile , "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
259 * Signals a successful login. Resets failed login counter.
261 public static function banLoginOk ()
263 if ( self
:: $banFile !== '' ) {
264 $ip = $_SERVER [ "REMOTE_ADDR" ];
265 $gb = $GLOBALS [ 'IPBANS' ];
266 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
267 $GLOBALS [ 'IPBANS' ] = $gb ;
268 file_put_contents ( self
:: $banFile , "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
275 public static function banInit ()
277 if ( self
:: $banFile !== '' ) {
278 if (! is_file ( self
:: $banFile )) {
279 file_put_contents ( self
:: $banFile , "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( array ( 'FAILURES' => array (), 'BANS' => array ()), true ). "; \n ?>" );
281 include self
:: $banFile ;
286 * Checks if the user CAN login. If 'true', the user can try to login.
288 * @return boolean true if user is banned, false otherwise
290 public static function banCanLogin ()
292 if ( self
:: $banFile !== '' ) {
293 $ip = $_SERVER [ "REMOTE_ADDR" ];
294 $gb = $GLOBALS [ 'IPBANS' ];
295 if ( isset ( $gb [ 'BANS' ][ $ip ])) {
296 // User is banned. Check if the ban has expired:
297 if ( $gb [ 'BANS' ][ $ip ] <= time ()) {
298 // Ban expired, user can try to login again.
299 unset ( $gb [ 'FAILURES' ][ $ip ]);
300 unset ( $gb [ 'BANS' ][ $ip ]);
301 file_put_contents ( self
:: $banFile , "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
303 return true ; // Ban has expired, user can login.
306 return false ; // User is banned.
310 return true ; // User is not banned.
315 * Tells if a param exists in session
317 * @param $name name of the param to test
320 public static function isInSession ( $name )
322 return ( isset ( $_SESSION [ $name ]) ? : FALSE );
326 * Returns param in session
328 * @param $name name of the param to return
329 * @return mixed param or null
331 public static function getParam ( $name )
333 return ( self
:: isInSession ( $name ) ? $_SESSION [ $name ] : NULL );
337 * Store value in session
339 * @param $name name of the variable to store
340 * @param $value value to store
342 public static function setParam ( $name , $value )
344 $_SESSION [ $name ] = $value ;