-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathHmacSha256.php
More file actions
348 lines (290 loc) · 9.5 KB
/
HmacSha256.php
File metadata and controls
348 lines (290 loc) · 9.5 KB
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
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Shield\Authentication\Authenticators;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\AuthenticationException;
use CodeIgniter\Shield\Authentication\AuthenticatorInterface;
use CodeIgniter\Shield\Authentication\HMAC\HmacEncrypter;
use CodeIgniter\Shield\Config\Auth;
use CodeIgniter\Shield\Config\AuthToken;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Shield\Exceptions\InvalidArgumentException;
use CodeIgniter\Shield\Models\TokenLoginModel;
use CodeIgniter\Shield\Models\UserIdentityModel;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Shield\Result;
class HmacSha256 implements AuthenticatorInterface
{
public const ID_TYPE_HMAC_TOKEN = 'hmac_sha256';
protected ?User $user = null;
protected TokenLoginModel $loginModel;
protected AuthToken $authTokenConfig;
/**
* @param UserModel $provider The persistence engine
*/
public function __construct(
protected UserModel $provider,
) {
$this->authTokenConfig = config('AuthToken');
$this->loginModel = model(TokenLoginModel::class);
}
/**
* Attempts to authenticate a user with the given $credentials.
* Logs the user in with a successful check.
*
* @throws AuthenticationException
*/
public function attempt(array $credentials): Result
{
/** @var IncomingRequest $request */
$request = service('request');
$ipAddress = $request->getIPAddress();
$userAgent = (string) $request->getUserAgent();
$result = $this->check($credentials);
if (! $result->isOK()) {
if ($this->authTokenConfig->recordLoginAttempt >= Auth::RECORD_LOGIN_ATTEMPT_FAILURE) {
// Record all failed login attempts.
$this->loginModel->recordLoginAttempt(
self::ID_TYPE_HMAC_TOKEN,
$credentials['token'] ?? '',
false,
$ipAddress,
$userAgent,
);
}
return $result;
}
$user = $result->extraInfo();
$token = $user->getHmacToken($this->getHmacKeyFromToken());
if ($user->isBanned()) {
if ($this->authTokenConfig->recordLoginAttempt >= Auth::RECORD_LOGIN_ATTEMPT_FAILURE) {
// Record a banned login attempt.
$this->loginModel->recordLoginAttempt(
self::ID_TYPE_HMAC_TOKEN,
$token->name ?? '',
false,
$ipAddress,
$userAgent,
$user->id,
);
}
$this->user = null;
return new Result([
'success' => false,
'reason' => $user->getBanMessage() ?? lang('Auth.bannedUser'),
]);
}
$user = $user->setHmacToken($token);
$this->login($user);
if ($this->authTokenConfig->recordLoginAttempt === Auth::RECORD_LOGIN_ATTEMPT_ALL) {
// Record a successful login attempt.
$this->loginModel->recordLoginAttempt(
self::ID_TYPE_HMAC_TOKEN,
$token->name ?? '',
true,
$ipAddress,
$userAgent,
$this->user->id,
);
}
return $result;
}
/**
* Checks a user's $credentials to see if they match an
* existing user.
*
* In this case, $credentials has only a single valid value: token,
* which is the plain text token to return.
*/
public function check(array $credentials): Result
{
if (! array_key_exists('token', $credentials) || $credentials['token'] === '') {
return new Result([
'success' => false,
'reason' => lang(
'Auth.noToken',
[$this->authTokenConfig->authenticatorHeader['hmac']],
),
]);
}
if (str_starts_with((string) $credentials['token'], 'HMAC-SHA256')) {
$credentials['token'] = trim(substr((string) $credentials['token'], 11)); // HMAC-SHA256
}
// Extract UserToken and HMACSHA256 Signature from Authorization token
[$userToken, $signature] = $this->getHmacAuthTokens($credentials['token']);
/** @var UserIdentityModel $identityModel */
$identityModel = model(UserIdentityModel::class);
$token = $identityModel->getHmacTokenByKey($userToken);
if ($token === null) {
return new Result([
'success' => false,
'reason' => lang('Auth.badToken'),
]);
}
$encrypter = new HmacEncrypter();
$secretKey = $encrypter->decrypt($token->secret2);
// Check signature...
$hash = hash_hmac('sha256', (string) $credentials['body'], $secretKey);
if ($hash !== $signature) {
return new Result([
'success' => false,
'reason' => lang('Auth.badToken'),
]);
}
assert($token->last_used_at instanceof Time || $token->last_used_at === null);
// Hasn't been used in a long time
if (
isset($token->last_used_at)
&& $token->last_used_at->isBefore(
Time::now()->subSeconds($this->authTokenConfig->unusedTokenLifetime),
)
) {
return new Result([
'success' => false,
'reason' => lang('Auth.oldToken'),
]);
}
$token->last_used_at = Time::now();
if ($token->hasChanged()) {
$identityModel->save($token);
}
// Ensure the token is set as the current token
$user = $token->user();
$user->setHmacToken($token);
return new Result([
'success' => true,
'extraInfo' => $user,
]);
}
/**
* Checks if the user is currently logged in.
* Since AccessToken usage is inherently stateless,
* it runs $this->attempt on each usage.
*/
public function loggedIn(): bool
{
if (isset($this->user)) {
return true;
}
/** @var IncomingRequest $request */
$request = service('request');
return $this->attempt([
'token' => $request->getHeaderLine(
$this->authTokenConfig->authenticatorHeader['hmac'],
),
])->isOK();
}
/**
* Logs the given user in by saving them to the class.
*/
public function login(User $user): void
{
$this->user = $user;
}
/**
* Logs a user in based on their ID.
*
* @param int|string $userId User ID
*
* @throws AuthenticationException
*/
public function loginById($userId): void
{
$user = $this->provider->findById($userId);
if ($user === null) {
throw AuthenticationException::forInvalidUser();
}
$user->setHmacToken(
$user->getHmacToken($this->getHmacKeyFromToken()),
);
$this->login($user);
}
/**
* Logs the current user out.
*/
public function logout(): void
{
$this->user = null;
}
/**
* Returns the currently logged-in user.
*/
public function getUser(): ?User
{
return $this->user;
}
/**
* Returns the Full HMAC Authorization token from the Authorization header
*
* @return ?string Trimmed Authorization Token from Header
*/
public function getFullHmacToken(): ?string
{
/** @var IncomingRequest $request */
$request = service('request');
$header = $request->getHeaderLine($this->authTokenConfig->authenticatorHeader['hmac']);
if ($header === '') {
return null;
}
return trim(substr($header, 11)); // 'HMAC-SHA256'
}
/**
* Get Key and HMAC hash from Auth token
*
* @param ?string $fullToken Full Token
*
* @return ?array [key, hmacHash]
*/
public function getHmacAuthTokens(?string $fullToken = null): ?array
{
if (! isset($fullToken)) {
$fullToken = $this->getFullHmacToken();
}
if (isset($fullToken)) {
return preg_split('/:/', $fullToken, -1, PREG_SPLIT_NO_EMPTY);
}
return null;
}
/**
* Retrieve the key from the Auth token
*
* @return ?string HMAC token key
*/
public function getHmacKeyFromToken(): ?string
{
[$key, $secretKey] = $this->getHmacAuthTokens();
return $key;
}
/**
* Retrieve the HMAC Hash from the Auth token
*
* @return ?string HMAC Hash
*/
public function getHmacHashFromToken(): ?string
{
[$key, $hash] = $this->getHmacAuthTokens();
return $hash;
}
/**
* Updates the user's last active date.
*/
public function recordActiveDate(): void
{
if (! $this->user instanceof User) {
throw new InvalidArgumentException(
__METHOD__ . '() requires logged in user before calling.',
);
}
$this->user->last_active = Time::now();
$this->provider->updateActiveDate($this->user);
}
}