Improved password storage schema
[PHPCredLocker.git] / lib / auth.class.php
Ben Tasker









Ben Tasker

Ben Tasker











Ben Tasker
Ben Tasker






Ben Tasker








Ben Tasker
Ben Tasker

Ben Tasker
Ben Tasker

Ben Tasker





Ben Tasker
Ben Tasker



Ben Tasker
Ben Tasker


Ben Tasker




Ben Tasker
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
<?php
/** Authentication processing
*
* Copyright (c) 2012 B Tasker
* Released under GNU GPL V2
* See LICENSE
*
*/
defined('_CREDLOCK') or die;
 
require_once 'lib/db/authdb.class.php';
 
class ProgAuth{
 
 
/** Add a user group
*
* @arg name string - New groups name
*
*/
function addGroup($name){
$authdb = new AuthDB;
return $authdb->addGroup($name);
}
 
 
/** Create a salt for the user
*
* @return string
*/
function createSalt(){
 
$x=0;
 
    while ($x <= 100){
 
    $salt .= mt_rand(10,10000);
    $x++;
    }
 
return md5($salt.date('y-m-dHis'));
 
}
 
 
/** bcrypt the pass
*
* Ta to Jon Hulka on stackoverflow for this function!
*
*/
function blowfishCrypt($password,$cost)
{
    $chars='./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $salt=sprintf('$2a$%02d$',$cost);
//For PHP >= PHP 5.3.7 use this instead (as per martinstoeckli's suggestion)
//    $salt=sprintf('$2y$%02d$',$cost);
    //Create a 22 character salt -edit- 2013.01.15 - replaced rand with mt_rand
    mt_srand();
    for($i=0;$i<22;$i++) $salt.=$chars[mt_rand(0,63)];
    return crypt($password,$salt);
}
 
 
/** Generate a random password of the specified length
*
* @arg length - INT
*
* @return string
*
*/
function generatePassword($length = 8){
 
 $key="(=?)+.,abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 $x = 0;
 $p = '';
 
  while ($x < $length){
  $select = mt_rand(1,strlen($key)) - 1;
  $p .= $key[$select];
  $x++;
  }
 
return $p;
  
}
 
 
/** Generate a unique value and add to the session
*
* Moved here to allow easy improvement on randomness at a later date
*
* @return string
*/
function generateFormToken(){
 
$frmToken = sha1(mt_rand(0,90000) . chr(mt_rand(32,254)) . chr(mt_rand(32,254)) . date('YMDHis') . chr(mt_rand(32,254)) . mt_rand(0,999999));
BTMain::setSessVar("FormToken",$frmToken);
return $frmToken;
 
}
 
 
/** Append a group ID to a user
*
* @arg user - string
* @arg group - Int
*
*/
function addUserToGroup($user,$group){
$db = new AuthDB;
return $db->userAppendGroup($user,$group);
}
 
 
 
/** Edit the specified User
*
* @arg username - string
* @arg pass - string
* @arg RealName - String
* @arg groups - array
*/
function editUser($username,$pass,$RName, $groups){
 
 
    if (!empty($pass)){
        // We need to create a salt for the password
        $user->salt = $this->createSalt();
 
        // Salt the password - why the hell was I using MD5 here?? I don't remember doing that - embarassing
        $user->pass = $this->blowfishCrypt($pass.$user->salt,12);
 
        // Get the plaintext password out of memory
        unset($pass);
 
    }else{
        $user->pass = false;
    }
 
 
$user->RealName = $RName;
$user->groups = $groups;
$user->username = $username;
 
$db = new AuthDB;
return $db->editUser($user);
}
 
 
 
 
 
/** Create a user with the specified Username
*
* @arg username - string
* @arg plaintextpass - string
* @arg RealName - String
* @arg groups - array
*/
function createUser($username,$plaintextPass,$RealName, $groups){
 
// We need to create a salt for the password
$user->salt = $this->createSalt();
 
// Salt the password
$user->pass = $this->blowfishCrypt($plaintextPass.$user->salt,12);
$user->RealName = $RealName;
$user->groups = $groups;
$user->username = $username;
 
 
// Get the plaintext password out of memory
unset($plaintextPass);
 
 
$db = new AuthDB;
return $db->addUser($user);
}
 
 
 
 
 
/** Log a failed attempt to login as a valid user
*
*.@arg username -string
* @arg db - object
*
*/
function logFailedAttempt($username,$db){
 
$db->LogFailedAttempt($username,BTMain::getip());
 
$threshdate = date("Y-m-d H:i:s",strtotime("-" . BTMain::getConf()->banProximity . " hours"));
$bantime = date("Y-m-d H:i:s",strtotime("+" . BTMain::getConf()->banLength . " hours"));
 
$db->implementBan(BTMain::getConf()->banThresh,$threshdate,$bantime,BTMain::getip());
 
return false;
}
 
 
 
 
/** Process an authentication request
*
* @arg username - string
* @arg plaintextpass - Supplied Password
*
* @return boolean
*/
function ProcessLogIn($username,&$password){
 
    // Check the form token
    $sessvar = BTMain::getSessVar('FormToken');
 
    BTMain::unsetSessVar('FormToken');
    if ($sessvar != BTMain::getVar('FormToken')){
    header('Location: index.php?notif=frmTokenInvalid');
    die;
    return false;
     }
 
 
  $db = new AuthDB;
 
 if ($db->checkForBan(BTMain::getip())){
  BTMain::setSessVar('Banned',"1");
  return false;
  }
 
 
// Trim trailing space from username & password (issue on mobiles with auto-predict)
$password = rtrim($password," ");
$username = rtrim($username," ");
 
  if (!$user = $db->retrieveUserCreds($username)){
    // Not a user, user. Check the Portal login
    $cust = new CredLockCust;
    if ((!BTMain::getConf()->custPortalEnabled) || (!$user = $cust->checkLogin($username))){
      return false;
    }
  }
 
 
 
$crypt = new Crypto;
$pass = explode(":",$crypt->decrypt($user->pass,'auth'));
unset($crypt);
 
// Get the valid hash out of memory as we have it in an array anyway
unset($user->pass);
 
 
    if (crypt($password.$pass[1],$pass[0]) != $pass[0]){
        // Check for a match on the old schema, there's only a risk of hash collision if the stored password is MD5
        if (md5($password.$pass[1]) == $pass[0]){
          // We need to update the stored hash to use the new schema. Still don't remember going with MD5. Should know better!
          $db->updPass($username,$this->blowfishCrypt($password.$pass[1],12),$pass[1]);
        }else{
          return $this->logFailedAttempt($username,$db);
        }
 
      }
 
// Create a Session ID
    $sessID = sha1(date('YmdHis') . mt_rand(10,80000) . mt_rand(11,500) . $username . mt_rand(0,90000));
 
// Get the hashes out of memory
    unset($password);
    unset($pass);
 
 
 
if ($user->membergroup != "-99,"){
    $groups = explode(",","0,".$user->membergroup);
    }else{
    $groups = array("-99");
    BTMain::setUserDetails('PortalLogin','1');
    $username = $user->id;
  }
 
// Log the user in
BTMain::setUser($username);
 
BTMain::setUserDetails('groups',$groups);
 
BTMain::setUserDetails('RealName',$user->Name);
 
 
// Create the expiry time
$expires = strtotime("+".BTMain::getConf()->sessionexpiry.' Minutes');
$expiry = date('Y-m-d H:i:s',$expires);
 
 
// Create a secret key
$str = '';
while ($X < 300){
 
$key = mt_rand(32,254);
$str .= chr($key);
 
$X++;
}
 
$sesskey = sha1($key);
 
 
// Create the database session
$db->EstablishSession($sessID,$expiry,$sesskey);
 
// Update the audit log
$log = new Logging;
    $log->logEntry('',11);
 
// Set the session variable
BTMain::setSessVar('Session',$sessID);
 
// Generate a key for the auth cookie
 
$X=0;
$str = '';
 
      while ($X < 100){
      $key = mt_rand(32,254);
      $str .= chr($key);
      $X++;
      }
 
// Create a string for the cookie
$cookieVal = md5($str . mt_rand(10,80000) . mt_rand(11,500) . mt_rand(0,90000) );
 
// Set the cookie
setcookie("PHPCredLocker", $cookieVal, $expires, dirname($_SERVER["REQUEST_URI"]), $_SERVER['HTTP_HOST'], BTMain::getConf()->forceSSL);
 
// Write to the sessions directory
$filename = "$expires-$cookieVal";
$fh = fopen(dirname(__FILE__)."/../sessions/sessions-$filename.session.php",'w');
 
$str = "<?php\n defined('_CREDLOCK') or die;\n \$sessKey='$sesskey';\n?>";
 
fwrite($fh,$str);
fclose($fh);
 
 
return true;
}
 
 
 
/** Invalid Login
*
*/
function LoginInvalid(){
 
// Don't redirect API requests, it breaks things!
if (strpos(BTMain::getEntryPoint(),'api.php') !== false){
return;
}
 
  session_destroy();
  header('Location: index.php?notif=InvalidSession');
  die;
 
 
 
 
}
 
 
 
/** Use the provided session ID to set the relevant globals
*
* @arg sessid - string
*
* @return boolean
*/
function SetUserDets($sessID){
 
    if (!isset($_COOKIE['PHPCredLocker'])){
        $this->LoginInvalid();
      }
 
 
 $db = new AuthDB;
 $user = $db->getUserSession($sessID);
 
  if (!$user){
      $this->LoginInvalid();  
  }
 
$cust = new CredLockCust;
if (is_numeric($user->User) && (BTMain::getConf()->custPortalEnabled) && ($usedets = $cust->checkSession($user->User))){
$user->username = $usedets->email;
$user->Name = $usedets->Name;
$user->membergroup = "-99,";
}
 
$expiry = strtotime($user->Expires);
 
  // Check for a session file
    if(file_exists(dirname(__FILE__)."/../sessions/sessions-$expiry-{$_COOKIE['PHPCredLocker']}.session.php")){
 
      require "sessions/sessions-$expiry-{$_COOKIE['PHPCredLocker']}.session.php";
 
          if ($sessKey != $user->SessKey){
              $this->LoginInvalid();
            }
 
    }else{
      // Session file doesn't exist, so can't be valid
      $this->LoginInvalid();
    }
 
 
 
 
// Users session is valid
BTMain::setUser($user->username);
 
 
if ($user->membergroup != "-99,"){
    $groups = explode(",","0,".$user->membergroup);
    }else{
    $groups = array("-99");
    BTMain::setUserDetails('PortalLogin','1');
    BTMain::setUserDetails('PortalID',$user->User);
  }
 
 
BTMain::setUserDetails('groups',$groups);
BTMain::setUserDetails('RealName',$user->Name);
 
 
return true;
}
 
 
 
 
/** Log the user out
* Need to remove the session from the database as well as removing the sessions file and killing the cookie
* 
* @return boolean
*
*/
function killSession(){
 
$sessID = BTMain::getSessVar('Session');
$tls = BTMain::getSessVar('tls');
session_destroy();
 
$db = new AuthDB;
$exp = strtotime($db->KillSession($sessID));
 
 
// Remove the session file
$filename = "sessions-$exp-{$_COOKIE['PHPCredLocker']}.session.php";
unlink(dirname(__FILE__)."/../sessions/$filename");
 
 
// unset the auth cookie
$expires = strtotime("-2 days");
setcookie("PHPCredLocker", $_COOKIE['PHPCredLocker'], $expires, dirname($_SERVER["REQUEST_URI"]), $_SERVER['HTTP_HOST'], BTMain::getConf()->forceSSL);
 
// Redirect the user
header('Location: index.php?notif=LoggedOut');
return true;
}
 
 
 
 
 
 
}
 
 
 
?>