DigestMD5.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. <?php
  2. // +-----------------------------------------------------------------------+
  3. // | Copyright (c) 2002-2003 Richard Heyes |
  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: Richard Heyes <richard@php.net> |
  33. // +-----------------------------------------------------------------------+
  34. //
  35. // $Id: DigestMD5.php,v 1.6 2003/02/21 16:07:17 mj Exp $
  36. /**
  37. * Implmentation of DIGEST-MD5 SASL mechanism
  38. *
  39. * @author Richard Heyes <richard@php.net>
  40. * @access public
  41. * @version 1.0
  42. * @package Auth_SASL
  43. */
  44. require_once('Auth/SASL/Common.php');
  45. class Auth_SASL_DigestMD5 extends Auth_SASL_Common
  46. {
  47. /**
  48. * Provides the (main) client response for DIGEST-MD5
  49. * requires a few extra parameters than the other
  50. * mechanisms, which are unavoidable.
  51. *
  52. * @param string $authcid Authentication id (username)
  53. * @param string $pass Password
  54. * @param string $challenge The digest challenge sent by the server
  55. * @param string $hostname The hostname of the machine you're connecting to
  56. * @param string $service The servicename (eg. imap, pop, acap etc)
  57. * @param string $authzid Authorization id (username to proxy as)
  58. * @return string The digest response (NOT base64 encoded)
  59. * @access public
  60. */
  61. function getResponse($authcid, $pass, $challenge, $hostname, $service, $authzid = '')
  62. {
  63. $challenge = $this->_parseChallenge($challenge);
  64. $authzid_string = '';
  65. if ($authzid != '') {
  66. $authzid_string = ',authzid="' . $authzid . '"';
  67. }
  68. if (!empty($challenge)) {
  69. $cnonce = $this->_getCnonce();
  70. $digest_uri = sprintf('%s/%s', $service, $hostname);
  71. $response_value = $this->_getResponseValue($authcid, $pass, $challenge['realm'], $challenge['nonce'], $cnonce, $digest_uri, $authzid);
  72. return sprintf('username="%s",realm="%s"' . $authzid_string . ',nonce="%s",cnonce="%s",nc="00000001",qop=auth,digest-uri="%s",response=%s,%d', $authcid, $challenge['realm'], $challenge['nonce'], $cnonce, $digest_uri, $response_value, $challenge['maxbuf']);
  73. } else {
  74. return PEAR::raiseError('Invalid digest challenge');
  75. }
  76. }
  77. /**
  78. * Parses and verifies the digest challenge*
  79. *
  80. * @param string $challenge The digest challenge
  81. * @return array The parsed challenge as an assoc
  82. * array in the form "directive => value".
  83. * @access private
  84. */
  85. function _parseChallenge($challenge)
  86. {
  87. $tokens = array();
  88. while (preg_match('/^([a-z-]+)=("[^"]+(?<!\\\)"|[^,]+)/i', $challenge, $matches)) {
  89. // Ignore these as per rfc2831
  90. if ($matches[1] == 'opaque' OR $matches[1] == 'domain') {
  91. $challenge = substr($challenge, strlen($matches[0]) + 1);
  92. continue;
  93. }
  94. // Allowed multiple "realm" and "auth-param"
  95. if (!empty($tokens[$matches[1]]) AND ($matches[1] == 'realm' OR $matches[1] == 'auth-param')) {
  96. if (is_array($tokens[$matches[1]])) {
  97. $tokens[$matches[1]][] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
  98. } else {
  99. $tokens[$matches[1]] = array($tokens[$matches[1]], preg_replace('/^"(.*)"$/', '\\1', $matches[2]));
  100. }
  101. // Any other multiple instance = failure
  102. } elseif (!empty($tokens[$matches[1]])) {
  103. $tokens = array();
  104. break;
  105. } else {
  106. $tokens[$matches[1]] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
  107. }
  108. // Remove the just parsed directive from the challenge
  109. $challenge = substr($challenge, strlen($matches[0]) + 1);
  110. }
  111. /**
  112. * Defaults and required directives
  113. */
  114. // Realm
  115. if (empty($tokens['realm'])) {
  116. $uname = posix_uname();
  117. $tokens['realm'] = $uname['nodename'];
  118. }
  119. // Maxbuf
  120. if (empty($tokens['maxbuf'])) {
  121. $tokens['maxbuf'] = 65536;
  122. }
  123. // Required: nonce, algorithm
  124. if (empty($tokens['nonce']) OR empty($tokens['algorithm'])) {
  125. return array();
  126. }
  127. return $tokens;
  128. }
  129. /**
  130. * Creates the response= part of the digest response
  131. *
  132. * @param string $authcid Authentication id (username)
  133. * @param string $pass Password
  134. * @param string $realm Realm as provided by the server
  135. * @param string $nonce Nonce as provided by the server
  136. * @param string $cnonce Client nonce
  137. * @param string $digest_uri The digest-uri= value part of the response
  138. * @param string $authzid Authorization id
  139. * @return string The response= part of the digest response
  140. * @access private
  141. */
  142. function _getResponseValue($authcid, $pass, $realm, $nonce, $cnonce, $digest_uri, $authzid = '')
  143. {
  144. if ($authzid == '') {
  145. $A1 = sprintf('%s:%s:%s', pack('H32', md5(sprintf('%s:%s:%s', $authcid, $realm, $pass))), $nonce, $cnonce);
  146. } else {
  147. $A1 = sprintf('%s:%s:%s:%s', pack('H32', md5(sprintf('%s:%s:%s', $authcid, $realm, $pass))), $nonce, $cnonce, $authzid);
  148. }
  149. $A2 = 'AUTHENTICATE:' . $digest_uri;
  150. return md5(sprintf('%s:%s:00000001:%s:auth:%s', md5($A1), $nonce, $cnonce, md5($A2)));
  151. }
  152. /**
  153. * Creates the client nonce for the response
  154. *
  155. * @return string The cnonce value
  156. * @access private
  157. */
  158. function _getCnonce()
  159. {
  160. if (file_exists('/dev/urandom')) {
  161. return base64_encode(fread(fopen('/dev/urandom', 'r'), 32));
  162. } elseif (file_exists('/dev/random')) {
  163. return base64_encode(fread(fopen('/dev/random', 'r'), 32));
  164. } else {
  165. $str = '';
  166. mt_srand((double)microtime()*10000000);
  167. for ($i=0; $i<32; $i++) {
  168. $str .= chr(mt_rand(0, 255));
  169. }
  170. return base64_encode($str);
  171. }
  172. }
  173. }
  174. ?>