Passed
Push — develop ( de7ad2...74fd77 )
by Fabian
06:12 queued 02:00
created

SCRAM::downgradeProtection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Sasl library.
5
 *
6
 * Copyright (c) 2002-2003 Richard Heyes,
7
 *               2014-2023 Fabian Grutschus
8
 * All rights reserved.
9
 *
10
 * Redistribution and use in source and binary forms, with or without
11
 * modification, are permitted provided that the following conditions
12
 * are met:
13
 *
14
 * o Redistributions of source code must retain the above copyright
15
 *   notice, this list of conditions and the following disclaimer.
16
 * o Redistributions in binary form must reproduce the above copyright
17
 *   notice, this list of conditions and the following disclaimer in the
18
 *   documentation and/or other materials provided with the distribution.|
19
 * o The names of the authors may not be used to endorse or promote
20
 *   products derived from this software without specific prior written
21
 *   permission.
22
 *
23
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
 *
35
 * @author Jehan <[email protected]>
36
 */
37
38
namespace Fabiang\Sasl\Authentication;
39
40
use Fabiang\Sasl\Authentication\AbstractAuthentication;
41
use Fabiang\Sasl\Options;
42
use Fabiang\Sasl\Exception\InvalidArgumentException;
43
44
/**
45
 * Implementation of SCRAM-* SASL mechanisms.
46
 * SCRAM mechanisms have 3 main steps (initial response, response to the server challenge, then server signature
47
 * verification) which keep state-awareness. Therefore a single class instanciation must be done
48
 * and reused for the whole authentication process.
49
 *
50
 * @author Jehan <[email protected]>
51
 */
52
class SCRAM extends AbstractAuthentication implements ChallengeAuthenticationInterface, VerificationInterface
53
{
54
    private $hashAlgo;
55
    private $hash;
56
    private $hmac;
57
    private $gs2Header;
58
    private $cnonce;
59
    private $firstMessageBare;
60
    private $saltedPassword;
61
    private $authMessage;
62
63
    /**
64
     * Construct a SCRAM-H client where 'H' is a cryptographic hash function.
65
     *
66
     * @link http://www.iana.org/assignments/hash-function-text-names/hash-function-text-names.xml "Hash Function
67
     * Textual Names" format of core PHP hash function.
68
     * @param Options $options
69
     * @param string  $hash The name cryptographic hash function 'H' as registered by IANA in the "Hash Function Textual
70
     * Names" registry.
71
     * @throws InvalidArgumentException
72
     */
73 8
    public function __construct(Options $options, $hash)
74
    {
75 8
        parent::__construct($options);
76
77
        // Though I could be strict, I will actually also accept the naming used in the PHP core hash framework.
78
        // For instance "sha1" is accepted, while the registered hash name should be "SHA-1".
79 8
        $normalizedHash = strtolower(preg_replace('#^sha-(\d+)#i', 'sha\1', $hash));
80
81 8
        $hashAlgos = hash_algos();
82 8
        if (!in_array($normalizedHash, $hashAlgos)) {
83 2
            throw new InvalidArgumentException("Invalid SASL mechanism type '$hash'");
84
        }
85
86 8
        $this->hash = function ($data) use ($normalizedHash) {
87 2
            return hash($normalizedHash, $data, true);
88
        };
89
90 8
        $this->hmac = function ($key, $str, $raw) use ($normalizedHash) {
91 2
            return hash_hmac($normalizedHash, $str, $key, $raw);
92
        };
93
94 8
        $this->hashAlgo = $normalizedHash;
95
    }
96
97
    /**
98
     * Provides the (main) client response for SCRAM-H.
99
     *
100
     * @param  string $challenge The challenge sent by the server.
101
     * If the challenge is null or an empty string, the result will be the "initial response".
102
     * @return string|false      The response (binary, NOT base64 encoded)
103
     */
104 6
    public function createResponse($challenge = null)
105
    {
106 6
        $authcid = $this->formatName($this->options->getAuthcid());
107 6
        if (empty($authcid)) {
108 2
            return false;
109
        }
110
111 4
        $authzid = $this->options->getAuthzid();
112 4
        if (!empty($authzid)) {
113 4
            $authzid = $this->formatName($authzid);
114
        }
115
116 4
        if (empty($challenge)) {
117 4
            return $this->generateInitialResponse($authcid, $authzid);
118
        } else {
119 2
            return $this->generateResponse($challenge, $this->options->getSecret());
120
        }
121
    }
122
123
    /**
124
     * Prepare a name for inclusion in a SCRAM response.
125
     *
126
     * @param string $username a name to be prepared.
127
     * @return string the reformated name.
128
     */
129 2
    private function formatName($username)
130
    {
131 2
        return str_replace(array('=', ','), array('=3D', '=2C'), $username);
132
    }
133
134
    /**
135
     * Generate the initial response which can be either sent directly in the first message or as a response to an empty
136
     * server challenge.
137
     *
138
     * @param string $authcid Prepared authentication identity.
139
     * @param string $authzid Prepared authorization identity.
140
     * @return string The SCRAM response to send.
141
     */
142 2
    private function generateInitialResponse($authcid, $authzid)
143
    {
144 2
        $gs2CbindFlag   = 'n,';
145 2
        $this->gs2Header = $gs2CbindFlag . (!empty($authzid) ? 'a=' . $authzid : '') . ',';
146
147
        // I must generate a client nonce and "save" it for later comparison on second response.
148 2
        $this->cnonce = $this->generateCnonce();
149
150 2
        $this->firstMessageBare = 'n=' . $authcid . ',r=' . $this->cnonce;
151 2
        return $this->gs2Header . $this->firstMessageBare;
152
    }
153
154
    /**
155
     * Parses and verifies a non-empty SCRAM challenge.
156
     *
157
     * @param  string $challenge The SCRAM challenge
158
     * @return string|false      The response to send; false in case of wrong challenge or if an initial response has
159
     * not been generated first.
160
     */
161 6
    private function generateResponse($challenge, $password)
162
    {
163 6
        $matches = array();
164
165
        $serverMessageRegexp = "#^r=(?<nonce>[\x21-\x2B\x2D-\x7E/]+)"
166
            . ",s=(?<salt>(?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9/+]{3}=|[A-Za-z0-9/+]{2}==)?)"
167
            . ",i=(?<iteration>[0-9]*)"
168 6
            . "(?:,d=(?<downgradeProtection>(?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9/+]{3}=|[A-Za-z0-9/+]{2}==)))?"
169 2
            . "(,[A-Za-z]=[^,])*$#";
170
171 4
        if (!isset($this->cnonce, $this->gs2Header) || !preg_match($serverMessageRegexp, $challenge, $matches)) {
172 4
            return false;
173 4
        }
174
175
        $nonce = $matches['nonce'];
176
        $salt  = base64_decode($matches['salt']);
177 4
        if (!$salt) {
178
            // Invalid Base64.
179 4
            return false;
180 4
        }
181
        $i = intval($matches['iteration']);
182 2
183
        $cnonce = substr($nonce, 0, strlen($this->cnonce));
184
        if ($cnonce !== $this->cnonce) {
185 2
            // Invalid challenge! Are we under attack?
186 2
            return false;
187 2
        }
188 2
189 2
        if (!empty($matches['downgradeProtection'])) {
190 2
            if (!$this->downgradeProtection($matches['downgradeProtection'])) {
191 2
                return false;
192 2
            }
193 2
        }
194 2
195 2
        $channelBinding       = 'c=' . base64_encode($this->gs2Header);
196
        $finalMessage         = $channelBinding . ',r=' . $nonce;
197 2
        $saltedPassword       = $this->hi($password, $salt, $i);
198
        $this->saltedPassword = $saltedPassword;
199
        $clientKey            = call_user_func($this->hmac, $saltedPassword, "Client Key", true);
200
        $storedKey            = call_user_func($this->hash, $clientKey, true);
201
        $authMessage          = $this->firstMessageBare . ',' . $challenge . ',' . $finalMessage;
202
        $this->authMessage    = $authMessage;
203
        $clientSignature      = call_user_func($this->hmac, $storedKey, $authMessage, true);
204
        $clientProof          = $clientKey ^ $clientSignature;
205
        $proof                = ',p=' . base64_encode($clientProof);
206
207 2
        return $finalMessage . $proof;
208
    }
209 2
210 2
    /**
211 2
     * @param string $expectedDowngradeProtectionHash
212 2
     * @return bool
213 2
     */
214 2
    private function downgradeProtection($expectedDowngradeProtectionHash)
215
    {
216 2
        if ($this->options->getDowngradeProtection() === null) {
217
            return true;
218
        }
219
220
        $actualDgPHash = base64_encode(call_user_func($this->hash, $this->generateDowngradeProtectionVerification()));
221
        return $expectedDowngradeProtectionHash === $actualDgPHash;
222
    }
223
224
    /**
225
     * Hi() call, which is essentially PBKDF2 (RFC-2898) with HMAC-H() as the pseudorandom function.
226
     *
227
     * @param string $str  The string to hash.
228 4
     * @param string $salt The salt value.
229
     * @param int $i The   iteration count.
230 4
     */
231
    private function hi($str, $salt, $i)
232 4
    {
233 4
        $int1   = "\0\0\0\1";
234
        $ui     = call_user_func($this->hmac, $str, $salt . $int1, true);
235 2
        $result = $ui;
236
        for ($k = 1; $k < $i; $k++) {
237
            $ui     = call_user_func($this->hmac, $str, $ui, true);
238 2
            $result = $result ^ $ui;
239 2
        }
240 2
        return $result;
241 2
    }
242
243 2
    /**
244
     * SCRAM has also a server verification step. On a successful outcome, it will send additional data which must
245
     * absolutely be checked against this function. If this fails, the entity which we are communicating with is
246
     * probably not the server as it has not access to your ServerKey.
247
     *
248
     * @param string $data The additional data sent along a successful outcome.
249 2
     * @return bool Whether the server has been authenticated.
250
     * If false, the client must close the connection and consider to be under a MITM attack.
251 2
     */
252
    public function verify($data)
253
    {
254 2
        $verifierRegexp = '#^v=((?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9/+]{3}=|[A-Za-z0-9/+]{2}==)?)$#';
255
256 2
        $matches = array();
257
        if (!isset($this->saltedPassword, $this->authMessage) || !preg_match($verifierRegexp, $data, $matches)) {
258
            // This cannot be an outcome, you never sent the challenge's response.
259 2
            return false;
260
        }
261 2
262
        $verifier                = $matches[1];
263
        $proposedServerSignature = base64_decode($verifier);
264 2
        $serverKey               = call_user_func($this->hmac, $this->saltedPassword, "Server Key", true);
265
        $serverSignature         = call_user_func($this->hmac, $serverKey, $this->authMessage, true);
266 2
267
        return $proposedServerSignature === $serverSignature;
268
    }
269
270
    /**
271
     * @return string
272
     */
273
    public function getCnonce()
274
    {
275
        return $this->cnonce;
276
    }
277
278
    public function getSaltedPassword()
279
    {
280
        return $this->saltedPassword;
281
    }
282
283
    public function getAuthMessage()
284
    {
285
        return $this->authMessage;
286
    }
287
288
    public function getHashAlgo()
289
    {
290
        return $this->hashAlgo;
291
    }
292
}
293