PageRenderTime 40ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Sabre/HTTP/DigestAuth.php

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