DigestAuth.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. <?php
  2. /**
  3. * HTTP Digest Authentication handler
  4. *
  5. * Use this class for easy http digest authentication.
  6. * Instructions:
  7. *
  8. * 1. Create the object
  9. * 2. Call the setRealm() method with the realm you plan to use
  10. * 3. Call the init method function.
  11. * 4. Call the getUserName() function. This function may return false if no
  12. * authentication information was supplied. Based on the username you
  13. * should check your internal database for either the associated password,
  14. * or the so-called A1 hash of the digest.
  15. * 5. Call either validatePassword() or validateA1(). This will return true
  16. * or false.
  17. * 6. To make sure an authentication prompt is displayed, call the
  18. * requireLogin() method.
  19. *
  20. *
  21. * @package Sabre
  22. * @subpackage HTTP
  23. * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
  24. * @author Evert Pot (http://www.rooftopsolutions.nl/)
  25. * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
  26. */
  27. class Sabre_HTTP_DigestAuth extends Sabre_HTTP_AbstractAuth {
  28. /**
  29. * These constants are used in setQOP();
  30. */
  31. const QOP_AUTH = 1;
  32. const QOP_AUTHINT = 2;
  33. protected $nonce;
  34. protected $opaque;
  35. protected $digestParts;
  36. protected $A1;
  37. protected $qop = self::QOP_AUTH;
  38. /**
  39. * Initializes the object
  40. */
  41. public function __construct() {
  42. $this->nonce = uniqid();
  43. $this->opaque = md5($this->realm);
  44. parent::__construct();
  45. }
  46. /**
  47. * Gathers all information from the headers
  48. *
  49. * This method needs to be called prior to anything else.
  50. *
  51. * @return void
  52. */
  53. public function init() {
  54. $digest = $this->getDigest();
  55. $this->digestParts = $this->parseDigest($digest);
  56. }
  57. /**
  58. * Sets the quality of protection value.
  59. *
  60. * Possible values are:
  61. * Sabre_HTTP_DigestAuth::QOP_AUTH
  62. * Sabre_HTTP_DigestAuth::QOP_AUTHINT
  63. *
  64. * Multiple values can be specified using logical OR.
  65. *
  66. * QOP_AUTHINT ensures integrity of the request body, but this is not
  67. * supported by most HTTP clients. QOP_AUTHINT also requires the entire
  68. * request body to be md5'ed, which can put strains on CPU and memory.
  69. *
  70. * @param int $qop
  71. * @return void
  72. */
  73. public function setQOP($qop) {
  74. $this->qop = $qop;
  75. }
  76. /**
  77. * Validates the user.
  78. *
  79. * The A1 parameter should be md5($username . ':' . $realm . ':' . $password);
  80. *
  81. * @param string $A1
  82. * @return bool
  83. */
  84. public function validateA1($A1) {
  85. $this->A1 = $A1;
  86. return $this->validate();
  87. }
  88. /**
  89. * Validates authentication through a password. The actual password must be provided here.
  90. * It is strongly recommended not store the password in plain-text and use validateA1 instead.
  91. *
  92. * @param string $password
  93. * @return bool
  94. */
  95. public function validatePassword($password) {
  96. $this->A1 = md5($this->digestParts['username'] . ':' . $this->realm . ':' . $password);
  97. return $this->validate();
  98. }
  99. /**
  100. * Returns the username for the request
  101. *
  102. * @return string
  103. */
  104. public function getUsername() {
  105. return $this->digestParts['username'];
  106. }
  107. /**
  108. * Validates the digest challenge
  109. *
  110. * @return bool
  111. */
  112. protected function validate() {
  113. $A2 = $this->httpRequest->getMethod() . ':' . $this->digestParts['uri'];
  114. if ($this->digestParts['qop']=='auth-int') {
  115. // Making sure we support this qop value
  116. if (!($this->qop & self::QOP_AUTHINT)) return false;
  117. // We need to add an md5 of the entire request body to the A2 part of the hash
  118. $body = $this->httpRequest->getBody(true);
  119. $this->httpRequest->setBody($body,true);
  120. $A2 .= ':' . md5($body);
  121. } else {
  122. // We need to make sure we support this qop value
  123. if (!($this->qop & self::QOP_AUTH)) return false;
  124. }
  125. $A2 = md5($A2);
  126. $validResponse = md5("{$this->A1}:{$this->digestParts['nonce']}:{$this->digestParts['nc']}:{$this->digestParts['cnonce']}:{$this->digestParts['qop']}:{$A2}");
  127. return $this->digestParts['response']==$validResponse;
  128. }
  129. /**
  130. * Returns an HTTP 401 header, forcing login
  131. *
  132. * This should be called when username and password are incorrect, or not supplied at all
  133. *
  134. * @return void
  135. */
  136. public function requireLogin() {
  137. $qop = '';
  138. switch($this->qop) {
  139. case self::QOP_AUTH : $qop = 'auth'; break;
  140. case self::QOP_AUTHINT : $qop = 'auth-int'; break;
  141. case self::QOP_AUTH | self::QOP_AUTHINT : $qop = 'auth,auth-int'; break;
  142. }
  143. $this->httpResponse->setHeader('WWW-Authenticate','Digest realm="' . $this->realm . '",qop="'.$qop.'",nonce="' . $this->nonce . '",opaque="' . $this->opaque . '"');
  144. $this->httpResponse->sendStatus(401);
  145. }
  146. /**
  147. * This method returns the full digest string.
  148. *
  149. * It should be compatibile with mod_php format and other webservers.
  150. *
  151. * If the header could not be found, null will be returned
  152. *
  153. * @return mixed
  154. */
  155. public function getDigest() {
  156. // mod_php
  157. $digest = $this->httpRequest->getRawServerValue('PHP_AUTH_DIGEST');
  158. if ($digest) return $digest;
  159. // most other servers
  160. $digest = $this->httpRequest->getHeader('Authorization');
  161. // Apache could prefix environment variables with REDIRECT_ when urls
  162. // are passed through mod_rewrite
  163. if (!$digest) {
  164. $digest = $this->httpRequest->getRawServerValue('REDIRECT_HTTP_AUTHORIZATION');
  165. }
  166. if ($digest && strpos(strtolower($digest),'digest')===0) {
  167. return substr($digest,7);
  168. } else {
  169. return null;
  170. }
  171. }
  172. /**
  173. * Parses the different pieces of the digest string into an array.
  174. *
  175. * This method returns false if an incomplete digest was supplied
  176. *
  177. * @param string $digest
  178. * @return mixed
  179. */
  180. protected function parseDigest($digest) {
  181. // protect against missing data
  182. $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
  183. $data = array();
  184. preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $digest, $matches, PREG_SET_ORDER);
  185. foreach ($matches as $m) {
  186. $data[$m[1]] = $m[2] ? $m[2] : $m[3];
  187. unset($needed_parts[$m[1]]);
  188. }
  189. return $needed_parts ? false : $data;
  190. }
  191. }