forked from emaijala/MLInvoice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsessionfuncs.php
executable file
·350 lines (329 loc) · 8.46 KB
/
sessionfuncs.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
<?php
/**
* Session handling
*
* PHP version 5
*
* Copyright (C) 2004-2008 Samu Reinikainen
* Copyright (C) 2010-2018 Ere Maijala
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category MLInvoice
* @package MLInvoice\Base
* @author Ere Maijala <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://labs.fi/mlinvoice.eng.php
*/
require_once 'config.php';
require_once 'sqlfuncs.php';
require_once 'miscfuncs.php';
define('ROLE_READONLY', 0);
define('ROLE_USER', 1);
define('ROLE_BACKUPMGR', 90);
define('ROLE_ADMIN', 99);
/**
* Create a session
*
* @param string $strLogin Login name
* @param string $strPasswd Password
* @param string $strCsrf CSRF token
*
* @return string OK|TIMEOUT|FAIL
*/
function sesCreateSession($strLogin, $strPasswd, $strCsrf)
{
if ($strLogin && $strPasswd) {
if (!isset($_SESSION['csrf']) || !isset($_SESSION['csrfip'])) {
error_log('No key information in session, timeout or session problem');
return 'TIMEOUT';
}
$csrfIp = $_SESSION['csrfip'];
if ($_SERVER['REMOTE_ADDR'] != $csrfIp) {
// Delay so that brute-force attacks become unpractical
error_log("Login failed for $strLogin due to IP address change");
sleep(2);
return 'FAIL';
}
$csrf = $_SESSION['csrf'];
unset($_SESSION['csrf']);
$csrfTime = $_SESSION['csrftime'];
if ($csrf !== $strCsrf || time() - $csrfTime > 300) {
error_log(
'Key not found or timeout, ' . (time() - $csrfTime)
. ' seconds since login form was created'
);
return 'TIMEOUT';
}
$strQuery = 'SELECT u.id AS user_id, u.type_id, u.passwd, st.time_out, st.access_level '
. 'FROM {prefix}users u '
. 'INNER JOIN {prefix}session_type st ON st.id = u.type_id '
. 'WHERE u.deleted=0 AND u.login=?';
$rows = dbParamQuery($strQuery, [$strLogin]);
if ($rows) {
$row = $rows[0];
if (!password_verify($strPasswd, $row['passwd'])
&& md5($strPasswd) != $row['passwd']
) {
// Delay so that brute-force attacks become unpractical
sleep(2);
error_log("Login failed for $strLogin");
return 'FAIL';
}
$_SESSION['sesTYPEID'] = $row['type_id'];
$_SESSION['sesUSERID'] = $row['user_id'];
$_SESSION['sesACCESSLEVEL'] = $row['access_level'];
$_SESSION['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['ACCESSTIME'] = time();
return 'OK';
}
}
// Delay so that brute-force attacks become unpractical
error_log('Login failed due to missing user name or password');
sleep(2);
return 'FAIL';
}
/**
* End a session
*
* @return bool
*/
function sesEndSession()
{
session_destroy();
unset($_SESSION);
return true;
}
/**
* Verify current session
*
* @param bool $redirect Whether to redirect to login if verification fails
*
* @return bool
*/
function sesVerifySession($redirect = true)
{
if (!session_id()) {
session_start();
}
if (isset($_SESSION['REMOTE_ADDR'])
&& $_SESSION['REMOTE_ADDR'] == $_SERVER['REMOTE_ADDR']
) {
$_SESSION['ACCESSTIME'] = time();
return true;
}
if ($redirect) {
if (substr($_SERVER['SCRIPT_FILENAME'], -9, 9) == 'index.php'
&& $_SERVER['QUERY_STRING'] && getRequest('func', '') != 'logout'
) {
$_SESSION['BACKLINK'] = 'index.php?' . $_SERVER['QUERY_STRING'];
header('Location: login.php?backlink=1');
} else {
header('Location: login.php');
}
} else {
header('HTTP/1.1 403 Forbidden');
}
exit();
}
/**
* Create a session CSRF hash
*
* @return string
*/
function sesCreateCsrf()
{
$_SESSION['csrf'] = createRandomString(20);
$_SESSION['csrftime'] = time();
$_SESSION['csrfip'] = $_SERVER['REMOTE_ADDR'];
return $_SESSION['csrf'];
}
/**
* Create a random character string
*
* @param int $length Length
*
* @return string
*/
function createRandomString($length)
{
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$str = '';
for ($i = 0; $i < $length; $i ++) {
$idx = mt_rand(0, strlen($chars) - 1);
$str .= substr($chars, $idx, 1);
}
return $str;
}
/**
* Check if current session has write access
*
* @return bool
*/
function sesWriteAccess()
{
if (!isset($_SESSION['sesACCESSLEVEL'])) {
ob_clean();
die();
}
return in_array(
$_SESSION['sesACCESSLEVEL'],
[
ROLE_USER,
ROLE_BACKUPMGR,
ROLE_ADMIN
]
);
}
/**
* Check if current session has admin access
*
* @return bool
*/
function sesAdminAccess()
{
if (!isset($_SESSION['sesACCESSLEVEL'])) {
ob_clean();
die();
}
return $_SESSION['sesACCESSLEVEL'] == ROLE_ADMIN;
}
/**
* Check if current session's access level is one of the allowed levels
*
* @param array $allowedLevels Allowed levels
*
* @return bool
*/
function sesAccessLevel($allowedLevels)
{
if (!isset($_SESSION['sesACCESSLEVEL'])) {
ob_clean();
die();
}
return in_array($_SESSION['sesACCESSLEVEL'], $allowedLevels);
}
// Database-based session management
/**
* Open a session
*
* @param string $savePath Save path
* @param string $sessionID Session ID
*
* @return bool
*/
function dbSessionOpen($savePath, $sessionID)
{
return true;
}
/**
* Close a session
*
* @return bool
*/
function dbSessionClose()
{
return true;
}
/**
* Read session data
*
* @param string $sessionID Session ID
*
* @return bool
*/
function dbSessionRead($sessionID)
{
$rows = dbParamQuery(
'SELECT data, session_timestamp FROM {prefix}session where id=?', [$sessionID]
);
if (isset($rows[0])) {
// Check for expiration
$sessionMaxAge = get_cfg_var('session.gc_maxlifetime');
$minTimestamp = date(
'Y-m-d H:i:s',
time() - ($sessionMaxAge ? $sessionMaxAge : 900)
);
if ($rows[0]['session_timestamp'] >= $minTimestamp) {
return $rows[0]['data'];
}
}
return '';
}
/**
* Write session data
*
* @param string $sessionID Session ID
* @param string $sessionData Session data
*
* @return bool
*/
function dbSessionWrite($sessionID, $sessionData)
{
dbParamQuery(
'REPLACE INTO {prefix}session (id, data, session_timestamp) VALUES'
. ' (?, ?, ?)',
[
$sessionID,
$sessionData,
date('Y-m-d H:i:s', time())
]
);
return true;
}
/**
* Delete a session
*
* @param string $sessionID Session ID
*
* @return bool
*/
function dbSessionDestroy($sessionID)
{
dbParamQuery('DELETE FROM {prefix}session WHERE id=?', [$sessionID]);
// Some distributions have gc disabled, need to do it manually
dbSessionGc(get_cfg_var('session.gc_maxlifetime'));
return true;
}
/**
* Collect session garbage
*
* @param int $sessionMaxAge Session maximum age
*
* @return bool
*/
function dbSessionGc($sessionMaxAge)
{
if (!$sessionMaxAge) {
$sessionMaxAge = 900;
}
// The query may fail if there are simultaneous requests, so don't let it cause
// the request to fail
dbParamQuery(
'DELETE FROM {prefix}session WHERE session_timestamp<?',
[
date('Y-m-d H:i:s', time() - $sessionMaxAge)
],
true
);
return true;
}
session_set_save_handler(
'dbSessionOpen', 'dbSessionClose', 'dbSessionRead',
'dbSessionWrite', 'dbSessionDestroy', 'dbSessionGc'
);
session_name(_SESSION_NAME_);
if (_SESSION_RESTRICT_PATH_) {
session_set_cookie_params(0, getSelfDirectory() . '/');
}