DigestMD5.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 294702 2010-02-07 16:03:55Z cweiske $
  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. if ($challenge['realm']) {
  73. return sprintf('username="%s",realm="%s"' . $authzid_string .
  74. ',nonce="%s",cnonce="%s",nc=00000001,qop=auth,digest-uri="%s",response=%s,maxbuf=%d', $authcid, $challenge['realm'], $challenge['nonce'], $cnonce, $digest_uri, $response_value, $challenge['maxbuf']);
  75. } else {
  76. return sprintf('username="%s"' . $authzid_string . ',nonce="%s",cnonce="%s",nc=00000001,qop=auth,digest-uri="%s",response=%s,maxbuf=%d', $authcid, $challenge['nonce'], $cnonce, $digest_uri, $response_value, $challenge['maxbuf']);
  77. }
  78. } else {
  79. return PEAR::raiseError('Invalid digest challenge');
  80. }
  81. }
  82. /**
  83. * Parses and verifies the digest challenge*
  84. *
  85. * @param string $challenge The digest challenge
  86. * @return array The parsed challenge as an assoc
  87. * array in the form "directive => value".
  88. * @access private
  89. */
  90. function _parseChallenge($challenge)
  91. {
  92. $tokens = array();
  93. while (preg_match('/^([a-z-]+)=("[^"]+(?<!\\\)"|[^,]+)/i', $challenge, $matches)) {
  94. // Ignore these as per rfc2831
  95. if ($matches[1] == 'opaque' OR $matches[1] == 'domain') {
  96. $challenge = substr($challenge, strlen($matches[0]) + 1);
  97. continue;
  98. }
  99. // Allowed multiple "realm" and "auth-param"
  100. if (!empty($tokens[$matches[1]]) AND ($matches[1] == 'realm' OR $matches[1] == 'auth-param')) {
  101. if (is_array($tokens[$matches[1]])) {
  102. $tokens[$matches[1]][] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
  103. } else {
  104. $tokens[$matches[1]] = array($tokens[$matches[1]], preg_replace('/^"(.*)"$/', '\\1', $matches[2]));
  105. }
  106. // Any other multiple instance = failure
  107. } elseif (!empty($tokens[$matches[1]])) {
  108. $tokens = array();
  109. break;
  110. } else {
  111. $tokens[$matches[1]] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
  112. }
  113. // Remove the just parsed directive from the challenge
  114. $challenge = substr($challenge, strlen($matches[0]) + 1);
  115. }
  116. /**
  117. * Defaults and required directives
  118. */
  119. // Realm
  120. if (empty($tokens['realm'])) {
  121. $tokens['realm'] = "";
  122. }
  123. // Maxbuf
  124. if (empty($tokens['maxbuf'])) {
  125. $tokens['maxbuf'] = 65536;
  126. }
  127. // Required: nonce, algorithm
  128. if (empty($tokens['nonce']) OR empty($tokens['algorithm'])) {
  129. return array();
  130. }
  131. return $tokens;
  132. }
  133. /**
  134. * Creates the response= part of the digest response
  135. *
  136. * @param string $authcid Authentication id (username)
  137. * @param string $pass Password
  138. * @param string $realm Realm as provided by the server
  139. * @param string $nonce Nonce as provided by the server
  140. * @param string $cnonce Client nonce
  141. * @param string $digest_uri The digest-uri= value part of the response
  142. * @param string $authzid Authorization id
  143. * @return string The response= part of the digest response
  144. * @access private
  145. */
  146. function _getResponseValue($authcid, $pass, $realm, $nonce, $cnonce, $digest_uri, $authzid = '')
  147. {
  148. if ($authzid == '') {
  149. $A1 = sprintf('%s:%s:%s', pack('H32', md5(sprintf('%s:%s:%s', $authcid, $realm, $pass))), $nonce, $cnonce);
  150. } else {
  151. $A1 = sprintf('%s:%s:%s:%s', pack('H32', md5(sprintf('%s:%s:%s', $authcid, $realm, $pass))), $nonce, $cnonce, $authzid);
  152. }
  153. $A2 = 'AUTHENTICATE:' . $digest_uri;
  154. return md5(sprintf('%s:%s:00000001:%s:auth:%s', md5($A1), $nonce, $cnonce, md5($A2)));
  155. }
  156. /**
  157. * Creates the client nonce for the response
  158. *
  159. * @return string The cnonce value
  160. * @access private
  161. */
  162. function _getCnonce()
  163. {
  164. if (@file_exists('/dev/urandom') && $fd = @fopen('/dev/urandom', 'r')) {
  165. return base64_encode(fread($fd, 32));
  166. } elseif (@file_exists('/dev/random') && $fd = @fopen('/dev/random', 'r')) {
  167. return base64_encode(fread($fd, 32));
  168. } else {
  169. $str = '';
  170. for ($i=0; $i<32; $i++) {
  171. $str .= chr(mt_rand(0, 255));
  172. }
  173. return base64_encode($str);
  174. }
  175. }
  176. }
  177. ?>