Passed
Branch refactoring (9be877)
by Fabian
16:03
created

SCRAM::generateResponse()   B

Complexity

Conditions 9
Paths 6

Size

Total Lines 54
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 34
nc 6
nop 2
dl 0
loc 54
rs 8.0555
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Sasl library.
7
 *
8
 * Copyright (c) 2002-2003 Richard Heyes,
9
 *               2014-2025 Fabian Grutschus
10
 * All rights reserved.
11
 *
12
 * Redistribution and use in source and binary forms, with or without
13
 * modification, are permitted provided that the following conditions
14
 * are met:
15
 *
16
 * o Redistributions of source code must retain the above copyright
17
 *   notice, this list of conditions and the following disclaimer.
18
 * o Redistributions in binary form must reproduce the above copyright
19
 *   notice, this list of conditions and the following disclaimer in the
20
 *   documentation and/or other materials provided with the distribution.|
21
 * o The names of the authors may not be used to endorse or promote
22
 *   products derived from this software without specific prior written
23
 *   permission.
24
 *
25
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
 *
37
 * @author Jehan <[email protected]>
38
 */
39
40
namespace Fabiang\SASL\Authentication;
41
42
use Fabiang\SASL\Authentication\AbstractAuthentication;
43
use Fabiang\SASL\Options;
44
use Fabiang\SASL\Exception\InvalidArgumentException;
45
use SensitiveParameterValue;
0 ignored issues
show
Bug introduced by
The type SensitiveParameterValue was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
46
47
/**
48
 * Implementation of SCRAM-* SASL mechanisms.
49
 * SCRAM mechanisms have 3 main steps (initial response, response to the server challenge, then server signature
50
 * verification) which keep state-awareness. Therefore a single class instanciation must be done
51
 * and reused for the whole authentication process.
52
 *
53
 * @author Jehan <[email protected]>
54
 */
55
class SCRAM extends AbstractAuthentication implements ChallengeAuthenticationInterface, VerificationInterface
56
{
57
    private string $hashAlgo;
58
59
    private ?string $gs2Header = null;
60
    private ?string $cnonce = null;
61
    private ?string $firstMessageBare = null;
62
    private ?SensitiveParameterValue $saltedSecret = null;
63
    private ?string $authMessage = null;
64
65
    /**
66
     * Construct a SCRAM-H client where 'H' is a cryptographic hash function.
67
     *
68
     * @link http://www.iana.org/assignments/hash-function-text-names/hash-function-text-names.xml "Hash Function
69
     * Textual Names" format of core PHP hash function.
70
     * @param Options $options
71
     * @param string  $hash The name cryptographic hash function 'H' as registered by IANA in the "Hash Function Textual
72
     * Names" registry.
73
     * @throws InvalidArgumentException
74
     */
75
    public function __construct(Options $options, string $hash)
76
    {
77
        parent::__construct($options);
78
79
        // Though I could be strict, I will actually also accept the naming used in the PHP core hash framework.
80
        // For instance "sha1" is accepted, while the registered hash name should be "SHA-1".
81
        $replaced = preg_replace('#^sha-(\d+)#i', 'sha\1', $hash);
82
        if ($replaced === null) {
83
            throw new InvalidArgumentException("Could not normalize hash '$hash'");
84
        }
85
        $normalizedHash = strtolower($replaced);
86
87
        $hashAlgos = hash_algos();
88
        if (!in_array($normalizedHash, $hashAlgos)) {
89
            throw new InvalidArgumentException("Invalid SASL mechanism type '$hash'");
90
        }
91
92
        $this->hashAlgo = $normalizedHash;
93
    }
94
95
    /**
96
     * Provides the (main) client response for SCRAM-H.
97
     *
98
     * @param  string $challenge The challenge sent by the server.
99
     * If the challenge is null or an empty string, the result will be the "initial response".
100
     * @return string|false      The response (binary, NOT base64 encoded)
101
     */
102
    public function createResponse(?string $challenge = null): string|false
103
    {
104
        $authcid = $this->options->getAuthcid();
105
        if ($authcid === null || $authcid === '') {
106
            return false;
107
        }
108
109
        $authcid = $this->formatName($authcid);
110
111
        $secret = $this->options->getSecret();
112
        if ($secret === null || $secret === '') {
113
            return false;
114
        }
115
116
        $authzid = $this->options->getAuthzid();
117
        if ($authzid !== null && $authzid !== '') {
118
            $authzid = $this->formatName($authzid);
119
        }
120
121
        if ($challenge === null) {
122
            return $this->generateInitialResponse($authcid, $authzid);
123
        } else {
124
            return $this->generateResponse($challenge, $secret);
125
        }
126
    }
127
128
    /**
129
     * Prepare a name for inclusion in a SCRAM response.
130
     *
131
     * @param string $username a name to be prepared.
132
     * @return string the reformated name.
133
     */
134
    private function formatName(string $username): string
135
    {
136
        return str_replace(['=', ','], ['=3D', '=2C'], $username);
137
    }
138
139
    /**
140
     * Generate the initial response which can be either sent directly in the first message or as a response to an empty
141
     * server challenge.
142
     *
143
     * @param string $authcid Prepared authentication identity.
144
     * @param string $authzid Prepared authorization identity.
145
     * @return string The SCRAM response to send.
146
     */
147
    private function generateInitialResponse(string $authcid, ?string $authzid): string
148
    {
149
        $gs2Header = 'n,';
150
        if ($authzid !== null && $authzid !== '') {
151
            $gs2Header .= 'a=' . $authzid;
152
        }
153
        $gs2Header .= ',';
154
155
        $this->gs2Header = $gs2Header;
156
157
        // I must generate a client nonce and "save" it for later comparison on second response.
158
        $this->cnonce = $this->generateCnonce();
159
160
        $this->firstMessageBare = 'n=' . $authcid . ',r=' . $this->cnonce;
161
        return $this->gs2Header . $this->firstMessageBare;
162
    }
163
164
    /**
165
     * Parses and verifies a non-empty SCRAM challenge.
166
     *
167
     * @param  string       $challenge The SCRAM challenge
168
     * @return string|false $secret The response to send; false in case of wrong challenge or if an initial response has
169
     * not been generated first.
170
     */
171
    private function generateResponse(
172
        string $challenge,
173
        #[\SensitiveParameter]
174
        string $secret
175
    ): string|false {
176
        /* @psalm-var array<int,string> $matches */
177
        $matches = [];
178
179
        $serverMessageRegexp = "#^r=(?<nonce>[\x21-\x2B\x2D-\x7E/]+)"
180
            . ",s=(?<salt>(?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9/+]{3}=|[A-Za-z0-9/+]{2}==)?)"
181
            . ",i=(?<iteration>[0-9]*)"
182
            . "(?:,d=(?<downgradeProtection>(?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9/+]{3}=|[A-Za-z0-9/+]{2}==)))?"
183
            . "(,[A-Za-z]=[^,])*$#";
184
185
        if ($this->cnonce === null ||
186
            $this->gs2Header === null ||
187
            $this->firstMessageBare === null ||
188
            !preg_match($serverMessageRegexp, $challenge, $matches)) {
189
            return false;
190
        }
191
192
        $nonce = $matches['nonce'];
193
        $salt  = base64_decode($matches['salt']);
194
        if (!$salt) {
195
            // Invalid Base64.
196
            return false;
197
        }
198
        $i = intval($matches['iteration']);
199
200
        $cnonce = substr($nonce, 0, strlen($this->cnonce));
201
        if ($cnonce !== $this->cnonce) {
202
            // Invalid challenge! Are we under attack?
203
            return false;
204
        }
205
206
        if ($matches['downgradeProtection'] !== '') {
207
            if (!$this->downgradeProtection($matches['downgradeProtection'])) {
208
                return false;
209
            }
210
        }
211
212
        $channelBinding       = 'c=' . base64_encode($this->gs2Header);
213
        $finalMessage         = $channelBinding . ',r=' . $nonce;
214
        $saltedSecret         = $this->hi($secret, $salt, $i);
215
        $this->saltedSecret   = new SensitiveParameterValue($saltedSecret);
216
        $clientKey            = $this->hmac($saltedSecret, "Client Key", true);
217
        $storedKey            = $this->hash($clientKey);
218
        $authMessage          = $this->firstMessageBare . ',' . $challenge . ',' . $finalMessage;
219
        $this->authMessage    = $authMessage;
220
        $clientSignature      = $this->hmac($storedKey, $authMessage, true);
221
        $clientProof          = $clientKey ^ $clientSignature;
222
        $proof                = ',p=' . base64_encode($clientProof);
223
224
        return $finalMessage . $proof;
225
    }
226
227
    private function downgradeProtection(string $expectedDowngradeProtectionHash): bool
228
    {
229
        if ($this->options->getDowngradeProtection() === null) {
230
            return true;
231
        }
232
233
        $actualDgPHash = base64_encode($this->hash($this->generateDowngradeProtectionVerification()));
234
        return $expectedDowngradeProtectionHash === $actualDgPHash;
235
    }
236
237
    /**
238
     * Hi() call, which is essentially PBKDF2 (RFC-2898) with HMAC-H() as the pseudorandom function.
239
     *
240
     * @param string $str  The string to hash.
241
     * @param string $salt The salt value.
242
     * @param int $i The   iteration count.
243
     */
244
    private function hi(
245
        #[\SensitiveParameter]
246
        string $str,
247
        string $salt,
248
        int $i
249
    ): string {
250
        $int1   = "\0\0\0\1";
251
        $ui     = $this->hmac($str, $salt . $int1, true);
252
        $result = $ui;
253
        for ($k = 1; $k < $i; $k++) {
254
            $ui     = $this->hmac($str, $ui, true);
255
            $result = $result ^ $ui;
256
        }
257
        return $result;
258
    }
259
260
    /**
261
     * SCRAM has also a server verification step. On a successful outcome, it will send additional data which must
262
     * absolutely be checked against this function. If this fails, the entity which we are communicating with is
263
     * probably not the server as it has not access to your ServerKey.
264
     *
265
     * @param string $data The additional data sent along a successful outcome.
266
     * @return bool Whether the server has been authenticated.
267
     * If false, the client must close the connection and consider to be under a MITM attack.
268
     */
269
    public function verify(string $data): bool
270
    {
271
        $verifierRegexp = '#^v=(?<verifier>(?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9/+]{3}=|[A-Za-z0-9/+]{2}==)?)$#';
272
273
        $matches = [];
274
        if (empty($this->saltedSecret) ||
275
            $this->authMessage === null ||
276
            !preg_match($verifierRegexp, $data, $matches)) {
277
            // This cannot be an outcome, you never sent the challenge's response.
278
            return false;
279
        }
280
281
        $saltedSecret = $this->saltedSecret->getValue();
282
283
        $verifier                = $matches['verifier'];
284
        $proposedServerSignature = base64_decode($verifier);
285
        $serverKey               = $this->hmac($saltedSecret, "Server Key", true);
286
        $serverSignature         = $this->hmac($serverKey, $this->authMessage, true);
287
288
        return $proposedServerSignature === $serverSignature;
289
    }
290
291
    private function hash(string $data): string
292
    {
293
        return hash($this->hashAlgo, $data, true);
294
    }
295
296
    private function hmac(string $key, string $str, bool $raw): string
297
    {
298
        return hash_hmac($this->hashAlgo, $str, $key, $raw);
299
    }
300
301
    public function getCnonce(): ?string
302
    {
303
        return $this->cnonce;
304
    }
305
306
    public function getSaltedSecret(): ?string
307
    {
308
        if ($this->saltedSecret === null) {
309
            return null;
310
        }
311
312
        return $this->saltedSecret->getValue();
313
    }
314
315
    public function getAuthMessage(): ?string
316
    {
317
        return $this->authMessage;
318
    }
319
320
    public function getHashAlgo(): string
321
    {
322
        return $this->hashAlgo;
323
    }
324
}
325