-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathHttpDigestAuthenticator.php
More file actions
282 lines (252 loc) · 9.91 KB
/
HttpDigestAuthenticator.php
File metadata and controls
282 lines (252 loc) · 9.91 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
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @license https://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Authentication\Authenticator;
use Authentication\Identifier\IdentifierInterface;
use Authentication\Identifier\PasswordIdentifier;
use Cake\Utility\Security;
use InvalidArgumentException;
use Psr\Http\Message\ServerRequestInterface;
/**
* HttpDigest Authenticator
*
* Provides Digest HTTP authentication support.
*
* ### Generating passwords compatible with Digest authentication.
*
* DigestAuthenticate requires a special password hash that conforms to RFC2617.
* You can generate this password using `HttpDigestAuthenticate::password()`
*
* ```
* $digestPass = HttpDigestAuthenticator::password($username, $password, env('SERVER_NAME'));
* ```
*
* If you wish to use digest authentication alongside other authentication methods,
* it's recommended that you store the digest authentication separately. For
* example `User.digest_pass` could be used for a digest password, while
* `User.password` would store the password hash for use with other methods like
* BasicHttp or Form.
*/
class HttpDigestAuthenticator extends HttpBasicAuthenticator
{
/**
* Constructor
*
* Besides the keys specified in AbstractAuthenticator::$_defaultConfig,
* HttpDigestAuthenticate uses the following extra keys:
*
* - `realm` The realm authentication is for, Defaults to the servername.
* - `nonceLifetime` The number of seconds that nonces are valid for. Defaults to 300.
* - `qop` Defaults to 'auth', no other values are supported at this time.
* - `opaque` A string that must be returned unchanged by clients.
* Defaults to `md5($config['realm'])`
*
* @param \Authentication\Identifier\IdentifierInterface|null $identifier Identifier instance.
* @param array<string, mixed> $config Configuration settings.
*/
public function __construct(?IdentifierInterface $identifier, array $config = [])
{
$secret = '';
if (class_exists(Security::class)) {
$secret = Security::getSalt();
}
$this->setConfig([
'realm' => null,
'qop' => 'auth',
'nonceLifetime' => 300,
'opaque' => null,
'secret' => $secret,
]);
$this->setConfig($config);
parent::__construct($identifier, $config);
$secret = $this->getConfig('secret');
if (!is_string($secret) || strlen($secret) === 0) {
throw new InvalidArgumentException('Secret key must be a non-empty string.');
}
}
/**
* Get a user based on information in the request. Used by cookie-less auth for stateless clients.
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request that contains login information.
* @return \Authentication\Authenticator\ResultInterface
*/
public function authenticate(ServerRequestInterface $request): ResultInterface
{
$digest = $this->_getDigest($request);
if ($digest === null) {
return new Result(null, Result::FAILURE_CREDENTIALS_MISSING);
}
$user = $this->getIdentifier()->identify([
PasswordIdentifier::CREDENTIAL_USERNAME => $digest['username'],
]);
if (!$user) {
return new Result(null, Result::FAILURE_IDENTITY_NOT_FOUND);
}
if (!$this->validNonce($digest['nonce'])) {
return new Result(null, Result::FAILURE_CREDENTIALS_INVALID);
}
$field = $this->_config['fields'][PasswordIdentifier::CREDENTIAL_PASSWORD];
$password = $user[$field];
$server = $request->getServerParams();
if (!isset($server['ORIGINAL_REQUEST_METHOD'])) {
$server['ORIGINAL_REQUEST_METHOD'] = $server['REQUEST_METHOD'];
}
$hash = $this->generateResponseHash($digest, $password, $server['ORIGINAL_REQUEST_METHOD']);
if (hash_equals($hash, $digest['response'])) {
return new Result($user, Result::SUCCESS);
}
return new Result(null, Result::FAILURE_CREDENTIALS_INVALID);
}
/**
* Gets the digest headers from the request/environment.
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request that contains login information.
* @return array<string>|null Array of digest information.
*/
protected function _getDigest(ServerRequestInterface $request): ?array
{
$server = $request->getServerParams();
$digest = empty($server['PHP_AUTH_DIGEST']) ? null : $server['PHP_AUTH_DIGEST'];
if (!$digest && function_exists('apache_request_headers')) {
$headers = apache_request_headers();
if (!empty($headers['Authorization']) && substr($headers['Authorization'], 0, 7) === 'Digest ') {
$digest = substr($headers['Authorization'], 7);
}
}
if (!$digest) {
return null;
}
return $this->parseAuthData($digest);
}
/**
* Parse the digest authentication headers and split them up.
*
* @param string $digest The raw digest authentication headers.
* @return array<string>|null An array of digest authentication headers
*/
public function parseAuthData(string $digest): ?array
{
if (substr($digest, 0, 7) === 'Digest ') {
$digest = substr($digest, 7);
}
$keys = $match = [];
$req = ['nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1];
preg_match_all('/(\w+)=([\'"]?)([a-zA-Z0-9\:\#\%\?\&@=\.\/_-]+)\2/', $digest, $match, PREG_SET_ORDER);
foreach ($match as $i) {
$keys[$i[1]] = $i[3];
unset($req[$i[1]]);
}
if (!$req) {
return $keys;
}
return null;
}
/**
* Generate the response hash for a given digest array.
*
* @param array<string> $digest Digest information containing data from HttpDigestAuthenticate::parseAuthData().
* @param string $password The digest hash password generated with HttpDigestAuthenticate::password()
* @param string $method Request method
* @return string Response hash
*/
public function generateResponseHash(array $digest, string $password, string $method): string
{
return md5(
$password .
':' . $digest['nonce'] . ':' . $digest['nc'] . ':' . $digest['cnonce'] . ':' . $digest['qop'] . ':' .
md5($method . ':' . $digest['uri']),
);
}
/**
* Creates an auth digest password hash to store
*
* @param string $username The username to use in the digest hash.
* @param string $password The unhashed password to make a digest hash for.
* @param string $realm The realm the password is for.
* @return string the hashed password that can later be used with Digest authentication.
*/
public static function password(string $username, string $password, string $realm): string
{
return md5($username . ':' . $realm . ':' . $password);
}
/**
* Generate the login headers
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request that contains login information.
* @return array<string, string> Headers for logging in.
*/
protected function loginHeaders(ServerRequestInterface $request): array
{
$server = $request->getServerParams();
$realm = $this->_config['realm'] ?: $server['SERVER_NAME'];
$options = [
'realm' => $realm,
'qop' => $this->_config['qop'],
'nonce' => $this->generateNonce(),
'opaque' => $this->_config['opaque'] ?: md5($realm),
];
$digest = $this->_getDigest($request);
if ($digest !== null && isset($digest['nonce']) && !$this->validNonce($digest['nonce'])) {
$options['stale'] = true;
}
$opts = [];
foreach ($options as $k => $v) {
if (is_bool($v)) {
$v = $v ? 'true' : 'false';
$opts[] = sprintf('%s=%s', $k, $v);
} else {
$opts[] = sprintf('%s="%s"', $k, (string)$v);
}
}
return ['WWW-Authenticate' => 'Digest ' . implode(',', $opts)];
}
/**
* Generate a nonce value that is validated in future requests.
*
* @return string
*/
protected function generateNonce(): string
{
$expiryTime = microtime(true) + $this->getConfig('nonceLifetime');
$secret = $this->getConfig('secret');
$signatureValue = hash_hmac('sha1', $expiryTime . ':' . $secret, $secret);
$nonceValue = $expiryTime . ':' . $signatureValue;
return base64_encode($nonceValue);
}
/**
* Check the nonce to ensure it is valid and not expired.
*
* @param string $nonce The nonce value to check.
* @return bool
*/
protected function validNonce(string $nonce): bool
{
$value = base64_decode($nonce);
/** @phpstan-ignore identical.alwaysFalse */
if ($value === false) {
return false;
}
$parts = explode(':', $value);
if (count($parts) !== 2) {
return false;
}
[$expires, $checksum] = $parts;
if ($expires < microtime(true)) {
return false;
}
$secret = $this->getConfig('secret');
$check = hash_hmac('sha1', $expires . ':' . $secret, $secret);
return hash_equals($check, $checksum);
}
}