]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/3rdparty/Session.class.php
[change] time for session
[github/wallabag/wallabag.git] / inc / 3rdparty / Session.class.php
1 <?php
2 /**
3 * Session management class
4 *
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
8 *
9 * Features:
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
13 * (such as Firesheep)
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
21 *
22 * TODOs
23 * - Replace globals with variables in Session class
24 *
25 * How to use:
26 * - http://tontof.net/kriss/php5/session
27 */
28 class Session
29 {
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 = 86400;
35 // Extra timeout for long sessions (if enabled) (82800 sec. = 23 hours)
36 public static $longSessionTimeout = 31536000;
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 = '';
47
48 /**
49 * Initialize session
50 */
51 public static function init()
52 {
53 // Force cookie path (but do not change lifetime)
54 $cookie = session_get_cookie_params();
55 // Default cookie expiration and path.
56 $cookiedir = '';
57 if (dirname($_SERVER['SCRIPT_NAME'])!='/') {
58 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
59 }
60 $ssl = false;
61 if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
62 $ssl = true;
63 }
64 session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['HTTP_HOST'], $ssl);
65 // Use cookies to store session.
66 ini_set('session.use_cookies', 1);
67 // Force cookies for session (phpsessionID forbidden in URL)
68 ini_set('session.use_only_cookies', 1);
69 if (!session_id()) {
70 // Prevent php to use sessionID in URL if cookies are disabled.
71 ini_set('session.use_trans_sid', false);
72 if (!empty(self::$sessionName)) {
73 session_name(self::$sessionName);
74 }
75 session_start();
76 }
77 }
78
79 /**
80 * Returns the IP address
81 * (Used to prevent session cookie hijacking.)
82 *
83 * @return string IP addresses
84 */
85 private static function _allIPs()
86 {
87 $ip = $_SERVER["REMOTE_ADDR"];
88 $ip.= isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? '_'.$_SERVER['HTTP_X_FORWARDED_FOR'] : '';
89 $ip.= isset($_SERVER['HTTP_CLIENT_IP']) ? '_'.$_SERVER['HTTP_CLIENT_IP'] : '';
90
91 return $ip;
92 }
93
94 /**
95 * Check that user/password is correct and then init some SESSION variables.
96 *
97 * @param string $login Login reference
98 * @param string $password Password reference
99 * @param string $loginTest Login to compare with login reference
100 * @param string $passwordTest Password to compare with password reference
101 * @param array $pValues Array of variables to store in SESSION
102 *
103 * @return true|false True if login and password are correct, false
104 * otherwise
105 */
106 public static function login (
107 $login,
108 $password,
109 $loginTest,
110 $passwordTest,
111 $longlastingsession,
112 $pValues = array())
113 {
114 self::banInit();
115 if (self::banCanLogin()) {
116 if ($login === $loginTest && $password === $passwordTest) {
117 self::banLoginOk();
118 // Generate unique random number to sign forms (HMAC)
119 $_SESSION['uid'] = sha1(uniqid('', true).'_'.mt_rand());
120 $_SESSION['ip'] = self::_allIPs();
121 $_SESSION['username'] = $login;
122 // Set session expiration.
123 $_SESSION['expires_on'] = time() + self::$inactivityTimeout;
124 if ($longlastingsession) {
125 $_SESSION['longlastingsession'] = self::$longSessionTimeout;
126 $_SESSION['expires_on'] += $_SESSION['longlastingsession'];
127 }
128
129 foreach ($pValues as $key => $value) {
130 $_SESSION[$key] = $value;
131 }
132
133 return true;
134 }
135 self::banLoginFailed();
136 }
137
138 return false;
139 }
140
141 /**
142 * Unset SESSION variable to force logout
143 */
144 public static function logout()
145 {
146 unset($_SESSION['uid'],$_SESSION['ip'],$_SESSION['expires_on'],$_SESSION['tokens'], $_SESSION['login'], $_SESSION['pass'], $_SESSION['longlastingsession'], $_SESSION['poche_user']);
147 }
148
149 /**
150 * Make sure user is logged in.
151 *
152 * @return true|false True if user is logged in, false otherwise
153 */
154 public static function isLogged()
155 {
156 if (!isset ($_SESSION['uid'])
157 || (self::$disableSessionProtection === false
158 && $_SESSION['ip'] !== self::_allIPs())
159 || time() >= $_SESSION['expires_on']) {
160 self::logout();
161
162 return false;
163 }
164 // User accessed a page : Update his/her session expiration date.
165 $_SESSION['expires_on'] = time() + self::$inactivityTimeout;
166 if (!empty($_SESSION['longlastingsession'])) {
167 $_SESSION['expires_on'] += $_SESSION['longlastingsession'];
168 }
169
170 return true;
171 }
172
173 /**
174 * Create a token, store it in SESSION and return it
175 *
176 * @param string $salt to prevent birthday attack
177 *
178 * @return string Token created
179 */
180 public static function getToken($salt = '')
181 {
182 if (!isset($_SESSION['tokens'])) {
183 $_SESSION['tokens']=array();
184 }
185 // We generate a random string and store it on the server side.
186 $rnd = sha1(uniqid('', true).'_'.mt_rand().$salt);
187 $_SESSION['tokens'][$rnd]=1;
188
189 return $rnd;
190 }
191
192 /**
193 * Tells if a token is ok. Using this function will destroy the token.
194 *
195 * @param string $token Token to test
196 *
197 * @return true|false True if token is correct, false otherwise
198 */
199 public static function isToken($token)
200 {
201 if (isset($_SESSION['tokens'][$token])) {
202 unset($_SESSION['tokens'][$token]); // Token is used: destroy it.
203
204 return true; // Token is ok.
205 }
206
207 return false; // Wrong token, or already used.
208 }
209
210 /**
211 * Signal a failed login. Will ban the IP if too many failures:
212 */
213 public static function banLoginFailed()
214 {
215 if (self::$banFile !== '') {
216 $ip = $_SERVER["REMOTE_ADDR"];
217 $gb = $GLOBALS['IPBANS'];
218
219 if (!isset($gb['FAILURES'][$ip])) {
220 $gb['FAILURES'][$ip] = 0;
221 }
222 $gb['FAILURES'][$ip]++;
223 if ($gb['FAILURES'][$ip] > (self::$banAfter - 1)) {
224 $gb['BANS'][$ip]= time() + self::$banDuration;
225 }
226
227 $GLOBALS['IPBANS'] = $gb;
228 file_put_contents(self::$banFile, "<?php\n\$GLOBALS['IPBANS']=".var_export($gb, true).";\n?>");
229 }
230 }
231
232 /**
233 * Signals a successful login. Resets failed login counter.
234 */
235 public static function banLoginOk()
236 {
237 if (self::$banFile !== '') {
238 $ip = $_SERVER["REMOTE_ADDR"];
239 $gb = $GLOBALS['IPBANS'];
240 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
241 $GLOBALS['IPBANS'] = $gb;
242 file_put_contents(self::$banFile, "<?php\n\$GLOBALS['IPBANS']=".var_export($gb, true).";\n?>");
243 }
244 }
245
246 /**
247 * Ban init
248 */
249 public static function banInit()
250 {
251 if (self::$banFile !== '') {
252 if (!is_file(self::$banFile)) {
253 file_put_contents(self::$banFile, "<?php\n\$GLOBALS['IPBANS']=".var_export(array('FAILURES'=>array(), 'BANS'=>array()), true).";\n?>");
254 }
255 include self::$banFile;
256 }
257 }
258
259 /**
260 * Checks if the user CAN login. If 'true', the user can try to login.
261 *
262 * @return boolean true if user is banned, false otherwise
263 */
264 public static function banCanLogin()
265 {
266 if (self::$banFile !== '') {
267 $ip = $_SERVER["REMOTE_ADDR"];
268 $gb = $GLOBALS['IPBANS'];
269 if (isset($gb['BANS'][$ip])) {
270 // User is banned. Check if the ban has expired:
271 if ($gb['BANS'][$ip] <= time()) {
272 // Ban expired, user can try to login again.
273 unset($gb['FAILURES'][$ip]);
274 unset($gb['BANS'][$ip]);
275 file_put_contents(self::$banFile, "<?php\n\$GLOBALS['IPBANS']=".var_export($gb, true).";\n?>");
276
277 return true; // Ban has expired, user can login.
278 }
279
280 return false; // User is banned.
281 }
282 }
283
284 return true; // User is not banned.
285 }
286 }