1<?php
2// +-----------------------------------------------------------------------+
3// | Copyright (c) 2011 Jehan                                              |
4// | All rights reserved.                                                  |
5// |                                                                       |
6// | Redistribution and use in source and binary forms, with or without    |
7// | modification, are permitted provided that the following conditions    |
8// | are met:                                                              |
9// |                                                                       |
10// | o Redistributions of source code must retain the above copyright      |
11// |   notice, this list of conditions and the following disclaimer.       |
12// | o Redistributions in binary form must reproduce the above copyright   |
13// |   notice, this list of conditions and the following disclaimer in the |
14// |   documentation and/or other materials provided with the distribution.|
15// | o The names of the authors may not be used to endorse or promote      |
16// |   products derived from this software without specific prior written  |
17// |   permission.                                                         |
18// |                                                                       |
19// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
20// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
21// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
22// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
23// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
24// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
25// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
26// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
27// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
28// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
29// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
30// |                                                                       |
31// +-----------------------------------------------------------------------+
32// | Author: Jehan <jehan.marmottard@gmail.com                             |
33// +-----------------------------------------------------------------------+
34//
35// $Id$
36
37/**
38* Implementation of SCRAM-* SASL mechanisms.
39* SCRAM mechanisms have 3 main steps (initial response, response to the server challenge, then server signature
40* verification) which keep state-awareness. Therefore a single class instanciation must be done and reused for the whole
41* authentication process.
42*
43* @author  Jehan <jehan.marmottard@gmail.com>
44* @access  public
45* @version 1.0
46* @package Auth_SASL
47*/
48
49class Auth_SASL_SCRAM extends Auth_SASL_Common
50{
51    /**
52    * Construct a SCRAM-H client where 'H' is a cryptographic hash function.
53    *
54    * @param string $hash The name cryptographic hash function 'H' as registered by IANA in the "Hash Function Textual
55    * Names" registry.
56    * @link http://www.iana.org/assignments/hash-function-text-names/hash-function-text-names.xml "Hash Function Textual
57    * Names"
58    * format of core PHP hash function.
59    * @access public
60    */
61    function __construct($hash)
62    {
63        // Though I could be strict, I will actually also accept the naming used in the PHP core hash framework.
64        // For instance "sha1" is accepted, while the registered hash name should be "SHA-1".
65        $hash = strtolower($hash);
66        $hashes = array('md2' => 'md2',
67            'md5' => 'md5',
68            'sha-1' => 'sha1',
69            'sha1' => 'sha1',
70            'sha-224' > 'sha224',
71            'sha224' > 'sha224',
72            'sha-256' => 'sha256',
73            'sha256' => 'sha256',
74            'sha-384' => 'sha384',
75            'sha384' => 'sha384',
76            'sha-512' => 'sha512',
77            'sha512' => 'sha512');
78        if (function_exists('hash_hmac') && isset($hashes[$hash]))
79        {
80            $this->hash = function($data) use ($hashes, $hash) {return hash($hashes[$hash], $data, true);};
81            $this->hmac = function($key, $str, $raw) use ($hashes, $hash) {return hash_hmac($hashes[$hash], $str, $key, $raw);};
82        }
83        elseif ($hash == 'md5')
84        {
85            $this->hash = function($data) {return md5($data, true);};
86            $this->hmac = array($this, '_HMAC_MD5');
87        }
88        elseif (in_array($hash, array('sha1', 'sha-1')))
89        {
90            $this->hash = function($data) {return sha1($data, true);};
91            $this->hmac = array($this, '_HMAC_SHA1');
92        }
93        else
94            return $this->raiseError('Invalid SASL mechanism type');
95    }
96
97    /**
98    * Provides the (main) client response for SCRAM-H.
99    *
100    * @param  string $authcid   Authentication id (username)
101    * @param  string $pass      Password
102    * @param  string $challenge The challenge sent by the server.
103    * If the challenge is NULL or an empty string, the result will be the "initial response".
104    * @param  string $authzid   Authorization id (username to proxy as)
105    * @return string|false      The response (binary, NOT base64 encoded)
106    * @access public
107    */
108    public function getResponse($authcid, $pass, $challenge = NULL, $authzid = NULL)
109    {
110        $authcid = $this->_formatName($authcid);
111        if (empty($authcid))
112        {
113            return false;
114        }
115        if (!empty($authzid))
116        {
117            $authzid = $this->_formatName($authzid);
118            if (empty($authzid))
119            {
120                return false;
121            }
122        }
123
124        if (empty($challenge))
125        {
126            return $this->_generateInitialResponse($authcid, $authzid);
127        }
128        else
129        {
130            return $this->_generateResponse($challenge, $pass);
131        }
132
133    }
134
135    /**
136    * Prepare a name for inclusion in a SCRAM response.
137    *
138    * @param string $username a name to be prepared.
139    * @return string the reformated name.
140    * @access private
141    */
142    private function _formatName($username)
143    {
144        // TODO: prepare through the SASLprep profile of the stringprep algorithm.
145        // See RFC-4013.
146
147        $username = str_replace('=', '=3D', $username);
148        $username = str_replace(',', '=2C', $username);
149        return $username;
150    }
151
152    /**
153    * Generate the initial response which can be either sent directly in the first message or as a response to an empty
154    * server challenge.
155    *
156    * @param string $authcid Prepared authentication identity.
157    * @param string $authzid Prepared authorization identity.
158    * @return string The SCRAM response to send.
159    * @access private
160    */
161    private function _generateInitialResponse($authcid, $authzid)
162    {
163        $init_rep = '';
164        $gs2_cbind_flag = 'n,'; // TODO: support channel binding.
165        $this->gs2_header = $gs2_cbind_flag . (!empty($authzid)? 'a=' . $authzid : '') . ',';
166
167        // I must generate a client nonce and "save" it for later comparison on second response.
168        $this->cnonce = $this->_getCnonce();
169        // XXX: in the future, when mandatory and/or optional extensions are defined in any updated RFC,
170        // this message can be updated.
171        $this->first_message_bare = 'n=' . $authcid . ',r=' . $this->cnonce;
172        return $this->gs2_header . $this->first_message_bare;
173    }
174
175    /**
176    * Parses and verifies a non-empty SCRAM challenge.
177    *
178    * @param  string $challenge The SCRAM challenge
179    * @return string|false      The response to send; false in case of wrong challenge or if an initial response has not
180    * been generated first.
181    * @access private
182    */
183    private function _generateResponse($challenge, $password)
184    {
185        // XXX: as I don't support mandatory extension, I would fail on them.
186        // And I simply ignore any optional extension.
187        $server_message_regexp = "#^r=([\x21-\x2B\x2D-\x7E]+),s=((?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9]{3}=|[A-Xa-z0-9]{2}==)?),i=([0-9]*)(,[A-Za-z]=[^,])*$#";
188        if (!isset($this->cnonce, $this->gs2_header)
189            || !preg_match($server_message_regexp, $challenge, $matches))
190        {
191            return false;
192        }
193        $nonce = $matches[1];
194        $salt = base64_decode($matches[2]);
195        if (!$salt)
196        {
197            // Invalid Base64.
198            return false;
199        }
200        $i = intval($matches[3]);
201
202        $cnonce = substr($nonce, 0, strlen($this->cnonce));
203        if ($cnonce <> $this->cnonce)
204        {
205            // Invalid challenge! Are we under attack?
206            return false;
207        }
208
209        $channel_binding = 'c=' . base64_encode($this->gs2_header); // TODO: support channel binding.
210        $final_message = $channel_binding . ',r=' . $nonce; // XXX: no extension.
211
212        // TODO: $password = $this->normalize($password); // SASLprep profile of stringprep.
213        $saltedPassword = $this->hi($password, $salt, $i);
214        $this->saltedPassword = $saltedPassword;
215        $clientKey = call_user_func($this->hmac, $saltedPassword, "Client Key", TRUE);
216        $storedKey = call_user_func($this->hash, $clientKey, TRUE);
217        $authMessage = $this->first_message_bare . ',' . $challenge . ',' . $final_message;
218        $this->authMessage = $authMessage;
219        $clientSignature = call_user_func($this->hmac, $storedKey, $authMessage, TRUE);
220        $clientProof = $clientKey ^ $clientSignature;
221        $proof = ',p=' . base64_encode($clientProof);
222
223        return $final_message . $proof;
224    }
225
226    /**
227    * SCRAM has also a server verification step. On a successful outcome, it will send additional data which must
228    * absolutely be checked against this function. If this fails, the entity which we are communicating with is probably
229    * not the server as it has not access to your ServerKey.
230    *
231    * @param string $data The additional data sent along a successful outcome.
232    * @return bool Whether the server has been authenticated.
233    * If false, the client must close the connection and consider to be under a MITM attack.
234    * @access public
235    */
236    public function processOutcome($data)
237    {
238        $verifier_regexp = '#^v=((?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9]{3}=|[A-Xa-z0-9]{2}==)?)$#';
239        if (!isset($this->saltedPassword, $this->authMessage)
240            || !preg_match($verifier_regexp, $data, $matches))
241        {
242            // This cannot be an outcome, you never sent the challenge's response.
243            return false;
244        }
245
246        $verifier = $matches[1];
247        $proposed_serverSignature = base64_decode($verifier);
248        $serverKey = call_user_func($this->hmac, $this->saltedPassword, "Server Key", true);
249        $serverSignature = call_user_func($this->hmac, $serverKey, $this->authMessage, TRUE);
250        return ($proposed_serverSignature === $serverSignature);
251    }
252
253    /**
254    * Hi() call, which is essentially PBKDF2 (RFC-2898) with HMAC-H() as the pseudorandom function.
255    *
256    * @param string $str The string to hash.
257    * @param string $hash The hash value.
258    * @param int $i The iteration count.
259    * @access private
260    */
261    private function hi($str, $salt, $i)
262    {
263        $int1 = "\0\0\0\1";
264        $ui = call_user_func($this->hmac, $str, $salt . $int1, true);
265        $result = $ui;
266        for ($k = 1; $k < $i; $k++)
267        {
268            $ui = call_user_func($this->hmac, $str, $ui, true);
269            $result = $result ^ $ui;
270        }
271        return $result;
272    }
273
274
275    /**
276    * Creates the client nonce for the response
277    *
278    * @return string  The cnonce value
279    * @access private
280    * @author  Richard Heyes <richard@php.net>
281    */
282    private function _getCnonce()
283    {
284        // TODO: I reused the nonce function from the DigestMD5 class.
285        // I should probably make this a protected function in Common.
286        if (@file_exists('/dev/urandom') && $fd = @fopen('/dev/urandom', 'r')) {
287            return base64_encode(fread($fd, 32));
288
289        } elseif (@file_exists('/dev/random') && $fd = @fopen('/dev/random', 'r')) {
290            return base64_encode(fread($fd, 32));
291
292        } else {
293            $str = '';
294            for ($i=0; $i<32; $i++) {
295                $str .= chr(mt_rand(0, 255));
296            }
297
298            return base64_encode($str);
299        }
300    }
301}