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
49require_once('Auth/SASL/Common.php');
50
51class Auth_SASL_SCRAM extends Auth_SASL_Common
52{
53    /**
54    * Construct a SCRAM-H client where 'H' is a cryptographic hash function.
55    *
56    * @param string $hash The name cryptographic hash function 'H' as registered by IANA in the "Hash Function Textual
57    * Names" registry.
58    * @link http://www.iana.org/assignments/hash-function-text-names/hash-function-text-names.xml "Hash Function Textual
59    * Names"
60    * format of core PHP hash function.
61    * @access public
62    */
63    function __construct($hash)
64    {
65        // Though I could be strict, I will actually also accept the naming used in the PHP core hash framework.
66        // For instance "sha1" is accepted, while the registered hash name should be "SHA-1".
67        $hash = strtolower($hash);
68        $hashes = array('md2' => 'md2',
69            'md5' => 'md5',
70            'sha-1' => 'sha1',
71            'sha1' => 'sha1',
72            'sha-224' > 'sha224',
73            'sha224' > 'sha224',
74            'sha-256' => 'sha256',
75            'sha256' => 'sha256',
76            'sha-384' => 'sha384',
77            'sha384' => 'sha384',
78            'sha-512' => 'sha512',
79            'sha512' => 'sha512');
80        if (function_exists('hash_hmac') && isset($hashes[$hash]))
81        {
82            $this->hash = create_function('$data', 'return hash("' . $hashes[$hash] . '", $data, TRUE);');
83            $this->hmac = create_function('$key,$str,$raw', 'return hash_hmac("' . $hashes[$hash] . '", $str, $key, $raw);');
84        }
85        elseif ($hash == 'md5')
86        {
87            $this->hash = create_function('$data', 'return md5($data, true);');
88            $this->hmac = array($this, '_HMAC_MD5');
89        }
90        elseif (in_array($hash, array('sha1', 'sha-1')))
91        {
92            $this->hash = create_function('$data', 'return sha1($data, true);');
93            $this->hmac = array($this, '_HMAC_SHA1');
94        }
95        else
96            return PEAR::raiseError('Invalid SASL mechanism type');
97    }
98
99    /**
100    * Provides the (main) client response for SCRAM-H.
101    *
102    * @param  string $authcid   Authentication id (username)
103    * @param  string $pass      Password
104    * @param  string $challenge The challenge sent by the server.
105    * If the challenge is NULL or an empty string, the result will be the "initial response".
106    * @param  string $authzid   Authorization id (username to proxy as)
107    * @return string|false      The response (binary, NOT base64 encoded)
108    * @access public
109    */
110    public function getResponse($authcid, $pass, $challenge = NULL, $authzid = NULL)
111    {
112        $authcid = $this->_formatName($authcid);
113        if (empty($authcid))
114        {
115            return false;
116        }
117        if (!empty($authzid))
118        {
119            $authzid = $this->_formatName($authzid);
120            if (empty($authzid))
121            {
122                return false;
123            }
124        }
125
126        if (empty($challenge))
127        {
128            return $this->_generateInitialResponse($authcid, $authzid);
129        }
130        else
131        {
132            return $this->_generateResponse($challenge, $pass);
133        }
134
135    }
136
137    /**
138    * Prepare a name for inclusion in a SCRAM response.
139    *
140    * @param string $username a name to be prepared.
141    * @return string the reformated name.
142    * @access private
143    */
144    private function _formatName($username)
145    {
146        // TODO: prepare through the SASLprep profile of the stringprep algorithm.
147        // See RFC-4013.
148
149        $username = str_replace('=', '=3D', $username);
150        $username = str_replace(',', '=2C', $username);
151        return $username;
152    }
153
154    /**
155    * Generate the initial response which can be either sent directly in the first message or as a response to an empty
156    * server challenge.
157    *
158    * @param string $authcid Prepared authentication identity.
159    * @param string $authzid Prepared authorization identity.
160    * @return string The SCRAM response to send.
161    * @access private
162    */
163    private function _generateInitialResponse($authcid, $authzid)
164    {
165        $init_rep = '';
166        $gs2_cbind_flag = 'n,'; // TODO: support channel binding.
167        $this->gs2_header = $gs2_cbind_flag . (!empty($authzid)? 'a=' . $authzid : '') . ',';
168
169        // I must generate a client nonce and "save" it for later comparison on second response.
170        $this->cnonce = $this->_getCnonce();
171        // XXX: in the future, when mandatory and/or optional extensions are defined in any updated RFC,
172        // this message can be updated.
173        $this->first_message_bare = 'n=' . $authcid . ',r=' . $this->cnonce;
174        return $this->gs2_header . $this->first_message_bare;
175    }
176
177    /**
178    * Parses and verifies a non-empty SCRAM challenge.
179    *
180    * @param  string $challenge The SCRAM challenge
181    * @return string|false      The response to send; false in case of wrong challenge or if an initial response has not
182    * been generated first.
183    * @access private
184    */
185    private function _generateResponse($challenge, $password)
186    {
187        // XXX: as I don't support mandatory extension, I would fail on them.
188        // And I simply ignore any optional extension.
189        $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]=[^,])*$#";
190        if (!isset($this->cnonce, $this->gs2_header)
191            || !preg_match($server_message_regexp, $challenge, $matches))
192        {
193            return false;
194        }
195        $nonce = $matches[1];
196        $salt = base64_decode($matches[2]);
197        if (!$salt)
198        {
199            // Invalid Base64.
200            return false;
201        }
202        $i = intval($matches[3]);
203
204        $cnonce = substr($nonce, 0, strlen($this->cnonce));
205        if ($cnonce <> $this->cnonce)
206        {
207            // Invalid challenge! Are we under attack?
208            return false;
209        }
210
211        $channel_binding = 'c=' . base64_encode($this->gs2_header); // TODO: support channel binding.
212        $final_message = $channel_binding . ',r=' . $nonce; // XXX: no extension.
213
214        // TODO: $password = $this->normalize($password); // SASLprep profile of stringprep.
215        $saltedPassword = $this->hi($password, $salt, $i);
216        $this->saltedPassword = $saltedPassword;
217        $clientKey = call_user_func($this->hmac, $saltedPassword, "Client Key", TRUE);
218        $storedKey = call_user_func($this->hash, $clientKey, TRUE);
219        $authMessage = $this->first_message_bare . ',' . $challenge . ',' . $final_message;
220        $this->authMessage = $authMessage;
221        $clientSignature = call_user_func($this->hmac, $storedKey, $authMessage, TRUE);
222        $clientProof = $clientKey ^ $clientSignature;
223        $proof = ',p=' . base64_encode($clientProof);
224
225        return $final_message . $proof;
226    }
227
228    /**
229    * SCRAM has also a server verification step. On a successful outcome, it will send additional data which must
230    * absolutely be checked against this function. If this fails, the entity which we are communicating with is probably
231    * not the server as it has not access to your ServerKey.
232    *
233    * @param string $data The additional data sent along a successful outcome.
234    * @return bool Whether the server has been authenticated.
235    * If false, the client must close the connection and consider to be under a MITM attack.
236    * @access public
237    */
238    public function processOutcome($data)
239    {
240        $verifier_regexp = '#^v=((?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9]{3}=|[A-Xa-z0-9]{2}==)?)$#';
241        if (!isset($this->saltedPassword, $this->authMessage)
242            || !preg_match($verifier_regexp, $data, $matches))
243        {
244            // This cannot be an outcome, you never sent the challenge's response.
245            return false;
246        }
247
248        $verifier = $matches[1];
249        $proposed_serverSignature = base64_decode($verifier);
250        $serverKey = call_user_func($this->hmac, $this->saltedPassword, "Server Key", true);
251        $serverSignature = call_user_func($this->hmac, $serverKey, $this->authMessage, TRUE);
252        return ($proposed_serverSignature === $serverSignature);
253    }
254
255    /**
256    * Hi() call, which is essentially PBKDF2 (RFC-2898) with HMAC-H() as the pseudorandom function.
257    *
258    * @param string $str The string to hash.
259    * @param string $hash The hash value.
260    * @param int $i The iteration count.
261    * @access private
262    */
263    private function hi($str, $salt, $i)
264    {
265        $int1 = "\0\0\0\1";
266        $ui = call_user_func($this->hmac, $str, $salt . $int1, true);
267        $result = $ui;
268        for ($k = 1; $k < $i; $k++)
269        {
270            $ui = call_user_func($this->hmac, $str, $ui, true);
271            $result = $result ^ $ui;
272        }
273        return $result;
274    }
275
276
277    /**
278    * Creates the client nonce for the response
279    *
280    * @return string  The cnonce value
281    * @access private
282    * @author  Richard Heyes <richard@php.net>
283    */
284    private function _getCnonce()
285    {
286        // TODO: I reused the nonce function from the DigestMD5 class.
287        // I should probably make this a protected function in Common.
288        if (@file_exists('/dev/urandom') && $fd = @fopen('/dev/urandom', 'r')) {
289            return base64_encode(fread($fd, 32));
290
291        } elseif (@file_exists('/dev/random') && $fd = @fopen('/dev/random', 'r')) {
292            return base64_encode(fread($fd, 32));
293
294        } else {
295            $str = '';
296            for ($i=0; $i<32; $i++) {
297                $str .= chr(mt_rand(0, 255));
298            }
299
300            return base64_encode($str);
301        }
302    }
303
304}
305
306?>
307