-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuth.php
452 lines (376 loc) · 10.8 KB
/
Auth.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
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
<?php
/**
* @file Auth.php
* @author Gabriele Tozzi <[email protected]>
* @package DoPhp
* @brief Base classes for handling authentication
*/
namespace dophp;
/**
* Interface for implementing an authenticator
*/
interface AuthInterface {
/**
* Constructor
*
* @param $config array: Global config array
* @param $db object: Database instance
* @param $sess boolean: If true, use session-aware auth
*/
public function __construct(& $config, $db, $sess);
/**
* Method called automatically by DoPhp to log in an user
*
* @return boolean: True on success or False on failure
*/
public function login();
/**
* Method called to get the current user's ID
*
* @return integer: Current user's ID or null is not authenticated
*/
public function getUid();
/**
* Method called to log out the user
*/
public function logout();
}
/**
* Base class for authenticator
*/
abstract class AuthBase implements AuthInterface {
/** Name of the session variable */
const SESS_VAR = 'DoPhp::Auth';
/** Name of the session array username key */
const SESS_VUSER = 'username';
/** Name of the session array password key */
const SESS_VPASS = 'password';
/** String (char) used to concatenate salt and password */
const PWD_SALT_GLUE = '$';
/** Config array */
protected $_config;
/** Database instance */
protected $_db;
/** Current user's ID */
protected $_uid = null;
/** If true, use session for authentication caching */
protected $_sess = null;
/**
* Contrsuctor
*
* @see AuthInterface::__construct
*/
public function __construct(& $config, $db, $sess) {
$this->_config = $config;
$this->_db = $db;
$this->_sess = $sess;
}
/**
* @see AuthInterface::login
*/
public function login() {
$this->_beforeLogin();
return $this->_processLogin($this->_doLogin());
}
/**
* Does pre-login checks
*/
protected function _beforeLogin() {
if( $this->_uid )
throw new \LogicException('Must logout first');
}
/**
* Process and apply login result
*
* @param $uid mixed: The user id, ad returned from _doLogin()
* @return boolean: True on success or False on failure
*/
protected function _processLogin($uid) {
if( ! $uid )
return false;
$this->_uid = $uid;
return true;
}
/**
* Called from login(), does the real login job. Must be overridden.
* Must also take care of session save and login, if $this->_sess
*
* @return int: The user's ID on success or null on failure
*/
abstract protected function _doLogin();
/**
* @see AuthInterface::getUid
*/
public function getUid() {
return $this->_uid;
}
/**
* @see AuthInterface::logout
*/
public function logout() {
$this->_uid = null;
$this->clearSession();
}
/**
* Save login credentials in session
*
* @param $user string: The username
* @param $tok string: The hash or token (using password directly is unsafe)
* @return bool: True if session has been saved
*/
public function saveSession($user, $tok) {
if( ! $this->_sess )
return false;
if( ! isset($_SESSION[self::SESS_VAR]) || ! is_array($_SESSION[self::SESS_VAR]) )
$_SESSION[self::SESS_VAR] = [];
$_SESSION[self::SESS_VAR][self::SESS_VUSER] = $user;
$_SESSION[self::SESS_VAR][self::SESS_VPASS] = $tok;
return true;
}
/**
* Load login credentials from session
*
* @return array [ $username, $token ] or null
*/
public function loadSession() {
if( ! $this->_sess )
return null;
if( ! isset($_SESSION[self::SESS_VAR]) || ! is_array($_SESSION[self::SESS_VAR]) )
return null;
if( ! isset($_SESSION[self::SESS_VAR][self::SESS_VUSER]) || ! $_SESSION[self::SESS_VAR][self::SESS_VUSER] )
return null;
if( ! array_key_exists(self::SESS_VPASS, $_SESSION[self::SESS_VAR]) )
return null;
return [
$_SESSION[self::SESS_VAR][self::SESS_VUSER],
$_SESSION[self::SESS_VAR][self::SESS_VPASS]
];
}
/**
* Erase session credentials
*/
public function clearSession() {
if( isset($_SESSION[self::SESS_VAR]) )
unset($_SESSION[self::SESS_VAR]);
}
/**
* Creates a sha512-based password hash
*
* @param $password string: The password to be hashed
* @param $salt string: The salt; if missing, use a random one
*
* @return "{$salt}${$salt}§{$password}§{$salt}"
*/
public static function encryptPasswordSHA512(string $password, string $salt=null): string {
if( ! $salt ) {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$salt = '';
for($i = 0; $i < 8; $i++)
$salt .= $chars[rand(0, strlen($chars) - 1)];
}
$merged = "{$salt}§{$password}§{$salt}";
return $salt . self::PWD_SALT_GLUE . hash('sha512', $merged);
}
/**
* Compares a plain password with a SHA512 password
*
* @see self::encryptPasswordSHA512
* @param $plain_password The plain password
* @param $hashed_password The hashed password, in the format "salt$password"
* @return true on success
*/
public static function comparePasswordsSHA512(string $plain_password, string $hashed_password): bool {
$parts = explode(self::PWD_SALT_GLUE, $hashed_password, 2);
if( count($parts) < 2 ) {
// Missing salt
return false;
}
$salt = $parts[0];
if(trim($hashed_password) == trim(self::encryptPasswordSHA512($plain_password, $salt)))
return true;
return false;
}
}
/**
* Implements HTTP Basic authentication
*
* Uses the HTTP "Authorization" header
*
* Database MUST implement a login($user, $password) method returning the user's
* ID on succesfull login
*/
abstract class AuthBasic extends AuthBase {
/** Standard HTTP Authorization header */
const HEAD_HTTP_AUTH = 'AUTHORIZATION';
const SOURCE_HEADERS = 'headers';
const SOURCE_HAND = 'hand';
const SOURCE_USER = 'user';
const SOURCE_SESSION = 'session';
/**
* Method the may be called manually by a page script to login an user
*
* @return boolean: True on success or False on failure
*/
public function handLogin($username, $password) {
$this->_beforeLogin();
list( $uid, $token ) = $this->__checkedLogin($username, $password, self::SOURCE_HAND);
if( $uid )
$this->saveSession($username, $token);
else
$this->clearSession();
return $this->_processLogin($uid);
}
/**
* @see AuthBase::_doLogin
*/
protected function _doLogin() {
$detected = $this->_detectLogin();
if( $detected === null )
return null;
list( $user, $pwd, $source ) = $detected;
list( $uid, $token ) = $this->__checkedLogin($user, $pwd, $source);
if( $uid )
$this->saveSession($user, $token);
else
$this->clearSession();
return $uid;
}
/**
* Detect login request
*
* @return [$username, $password, $source] or null
*/
protected function _detectLogin() {
$headers = Utils::headers(true);
if( isset($headers[self::HEAD_HTTP_AUTH]) ) {
$parts = explode(' ', $headers[self::HEAD_HTTP_AUTH]);
if( count($parts) == 2 ) {
$method = strtolower(trim($parts[0]));
$auth = base64_decode(trim($parts[1]), true);
if( $method == 'basic' && $auth !== false ) {
$parts2 = explode(':', $auth);
if( count($parts2) == 2 )
return [ $parts2[0], $parts2[1], self::SOURCE_HEADERS ];
}
}
}
$sess = $this->loadSession();
if( $sess )
return [
$sess[0],
$sess[1],
self::SOURCE_SESSION
];
return null;
}
/**
* Wrapper over $this->_login, checks output for backward compatibility
*/
private function __checkedLogin($user, $pwd, $source): array {
$ret = $this->_login($user, $pwd, $source);
if( ! $ret )
return [ null, null ];
if( ! is_array($ret) )
throw new \UnexpectedValueException('Returning a single value from _login() is deprecated');
if( count($ret) != 2 )
throw new \UnexpectedValueException('_login() array must contain two values [id,token]');
return $ret;
}
/**
* Perform the login, must be implemented in child
*
* @param $user string: The username
* @param $pwd string: The password or the token, depends on $source
* @param $source string: The source for the credendials (headers|user|session|hand),
* SOURCE_* consts
* @return array The [ user's ID, session token ] array on success, null on failure
* Session token will be saved in session and passed
* back as $pwd argument on subsequent login calls
*/
abstract protected function _login($user, $pwd, $source);
}
/**
* Class for username/password authentication
*
* First checks for X-Auth-User and X-Auth-Pass headers, if not found, then
* checks $_REQUEST for 'username' and 'password' variables. 'login' must be true
* for security reasons
*
* Database MUST implement a login($user, $password) method returning the user's
* ID on succesfull login
*/
abstract class AuthPlain extends AuthBasic {
/** UserId header name ($_SERVER key name) */
const HEAD_USER = 'HTTP_X_AUTH_USER';
/** Password header name ($_SERVER key name) */
const HEAD_PASS = 'HTTP_X_AUTH_PASS';
/**
* Detect login request
*
* @return [$username, $password, $source] or null
*/
protected function _detectLogin() {
if( isset($_SERVER[self::HEAD_USER]) && isset($_SERVER[self::HEAD_PASS]) )
return [ $_SERVER[self::HEAD_USER], $_SERVER[self::HEAD_PASS], self::SOURCE_HEADERS ];
if( isset($_REQUEST['login']) && $_REQUEST['login']
&& isset($_REQUEST['username']) && isset($_REQUEST['password']) )
return [ $_REQUEST['username'], $_REQUEST['password'], self::SOURCE_USER ];
$sess = $this->loadSession();
if( $sess )
return [
$sess[0],
$sess[1],
self::SOURCE_SESSION
];
return null;
}
}
/**
* Class for Signature-based stateless authentication
*
* Authenticates against X-Auth-Username and X-Auth-Sign headers.
* X-Auth-Username: the username
* X-Auth-Sign: sha1($username . SEP . $password . SEP . $raw_content)
*
* Database MUST implement a getUserPwd($user) method returning the user's
* password (maybe encrypted)
*/
class AuthSign extends AuthBase {
/** Separator to use for hash concatenation */
const SEP = '~';
/** UserId header name ($_SERVER key name) */
const HEAD_USER = 'HTTP_X_AUTH_USER';
/** Signature header name ($_SERVER key name) */
const HEAD_SIGN = 'HTTP_X_AUTH_SIGN';
/**
* @see AuthBase::_doLogin
*/
public function _doLogin() {
$data = file_get_contents("php://input");
$user = null;
$sign = null;
$sess = $this->loadSession();
if( isset($_SERVER[self::HEAD_USER]) && isset($_SERVER[self::HEAD_SIGN]) ) {
$user = $_SERVER[self::HEAD_USER];
$sign = $_SERVER[self::HEAD_SIGN];
} elseif( $sess )
list( $user, $sign ) = $sess;
list($uid, $pwd) = $this->_getUserPwd($user);
if( ! $user || ! $sign || ! $pwd )
return null;
$countersign = hash('sha512', $user . self::SEP . $pwd . self::SEP . $data);
if( $sign !== $countersign )
return null;
$this->saveSession($user, $sign);
return $uid;
}
/**
* Reads user's ID and password from database, may be overridden
*
* @param $user string: The username
* @return array: (id, password: may be hashed)
*/
protected function _getUserPwd($user) {
return $this->_db->getUserPwd($user);
}
}