]>
Commit | Line | Data |
---|---|---|
e4d2565e | 1 | <?php |
2 | /** | |
3 | * Session management class | |
f6597c7c | 4 | * |
e4d2565e | 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 | |
f6597c7c | 8 | * |
e4d2565e | 9 | * Features: |
10 | * - Everything is stored on server-side (we do not trust client-side data, | |
11 | * such as cookie expiration) | |
f6597c7c NL |
12 | * - IP addresses are checked on each access to prevent session cookie hijacking |
13 | * (such as Firesheep) | |
e4d2565e | 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 | |
f6597c7c NL |
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 | |
e4d2565e | 21 | * |
f6597c7c NL |
22 | * TODOs |
23 | * - Replace globals with variables in Session class | |
e4d2565e | 24 | * |
f6597c7c NL |
25 | * How to use: |
26 | * - http://tontof.net/kriss/php5/session | |
e4d2565e | 27 | */ |
e4d2565e | 28 | class Session |
29 | { | |
f6597c7c NL |
30 | // Personnalize PHP session name |
31 | public static $sessionName = ''; | |
e4d2565e | 32 | // If the user does not access any page within this time, |
f6597c7c | 33 | // his/her session is considered expired (3600 sec. = 1 hour) |
16fd1cce | 34 | public static $inactivityTimeout = 86400; |
a0aa1504 | 35 | // Extra timeout for long sessions (if enabled) (82800 sec. = 23 hours) |
16fd1cce | 36 | public static $longSessionTimeout = 31536000; |
f6597c7c NL |
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 = ''; | |
e4d2565e | 47 | |
f6597c7c NL |
48 | /** |
49 | * Initialize session | |
50 | */ | |
51 | public static function init() | |
e4d2565e | 52 | { |
f6597c7c NL |
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); | |
e4d2565e | 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); | |
f6597c7c | 69 | if (!session_id()) { |
e4d2565e | 70 | // Prevent php to use sessionID in URL if cookies are disabled. |
71 | ini_set('session.use_trans_sid', false); | |
f6597c7c NL |
72 | if (!empty(self::$sessionName)) { |
73 | session_name(self::$sessionName); | |
74 | } | |
75 | session_start(); | |
e4d2565e | 76 | } |
77 | } | |
78 | ||
f6597c7c NL |
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() | |
e4d2565e | 86 | { |
f6597c7c NL |
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'] : ''; | |
e4d2565e | 90 | |
f6597c7c | 91 | return $ip; |
e4d2565e | 92 | } |
93 | ||
f6597c7c NL |
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, | |
a0aa1504 | 111 | $longlastingsession, |
f6597c7c | 112 | $pValues = array()) |
e4d2565e | 113 | { |
f6597c7c NL |
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; | |
a0aa1504 DS |
124 | if ($longlastingsession) { |
125 | $_SESSION['longlastingsession'] = self::$longSessionTimeout; | |
126 | $_SESSION['expires_on'] += $_SESSION['longlastingsession']; | |
127 | } | |
128 | ||
f6597c7c NL |
129 | foreach ($pValues as $key => $value) { |
130 | $_SESSION[$key] = $value; | |
131 | } | |
132 | ||
133 | return true; | |
134 | } | |
135 | self::banLoginFailed(); | |
e4d2565e | 136 | } |
f6597c7c | 137 | |
e4d2565e | 138 | return false; |
139 | } | |
140 | ||
f6597c7c NL |
141 | /** |
142 | * Unset SESSION variable to force logout | |
143 | */ | |
e4d2565e | 144 | public static function logout() |
145 | { | |
a0aa1504 | 146 | unset($_SESSION['uid'],$_SESSION['ip'],$_SESSION['expires_on'],$_SESSION['tokens'], $_SESSION['login'], $_SESSION['pass'], $_SESSION['longlastingsession'], $_SESSION['poche_user']); |
e4d2565e | 147 | } |
148 | ||
f6597c7c NL |
149 | /** |
150 | * Make sure user is logged in. | |
151 | * | |
152 | * @return true|false True if user is logged in, false otherwise | |
153 | */ | |
e4d2565e | 154 | public static function isLogged() |
155 | { | |
156 | if (!isset ($_SESSION['uid']) | |
f6597c7c NL |
157 | || (self::$disableSessionProtection === false |
158 | && $_SESSION['ip'] !== self::_allIPs()) | |
159 | || time() >= $_SESSION['expires_on']) { | |
160 | self::logout(); | |
161 | ||
e4d2565e | 162 | return false; |
163 | } | |
164 | // User accessed a page : Update his/her session expiration date. | |
f6597c7c NL |
165 | $_SESSION['expires_on'] = time() + self::$inactivityTimeout; |
166 | if (!empty($_SESSION['longlastingsession'])) { | |
167 | $_SESSION['expires_on'] += $_SESSION['longlastingsession']; | |
168 | } | |
169 | ||
e4d2565e | 170 | return true; |
171 | } | |
172 | ||
f6597c7c NL |
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 = '') | |
e4d2565e | 181 | { |
f6597c7c | 182 | if (!isset($_SESSION['tokens'])) { |
e4d2565e | 183 | $_SESSION['tokens']=array(); |
184 | } | |
185 | // We generate a random string and store it on the server side. | |
f6597c7c | 186 | $rnd = sha1(uniqid('', true).'_'.mt_rand().$salt); |
e4d2565e | 187 | $_SESSION['tokens'][$rnd]=1; |
f6597c7c | 188 | |
e4d2565e | 189 | return $rnd; |
190 | } | |
191 | ||
f6597c7c NL |
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 | */ | |
e4d2565e | 199 | public static function isToken($token) |
200 | { | |
f6597c7c | 201 | if (isset($_SESSION['tokens'][$token])) { |
e4d2565e | 202 | unset($_SESSION['tokens'][$token]); // Token is used: destroy it. |
f6597c7c | 203 | |
e4d2565e | 204 | return true; // Token is ok. |
205 | } | |
f6597c7c | 206 | |
e4d2565e | 207 | return false; // Wrong token, or already used. |
208 | } | |
f6597c7c NL |
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 | } |