You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SCRAM.php 12KB

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