Digest.php 6.0 KB

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