DigestAuthenticate.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Auth;
  16. use Cake\Auth\BasicAuthenticate;
  17. use Cake\Controller\ComponentRegistry;
  18. use Cake\Network\Request;
  19. /**
  20. * Digest Authentication adapter for AuthComponent.
  21. *
  22. * Provides Digest HTTP authentication support for AuthComponent.
  23. *
  24. * ### Using Digest auth
  25. *
  26. * In your controller's components array, add auth + the required config
  27. * {{{
  28. * public $components = [
  29. * 'Auth' => [
  30. * 'authenticate' => ['Digest']
  31. * ]
  32. * ];
  33. * }}}
  34. *
  35. * You should also set `AuthComponent::$sessionKey = false;` in your AppController's
  36. * beforeFilter() to prevent CakePHP from sending a session cookie to the client.
  37. *
  38. * Since HTTP Digest Authentication is stateless you don't need a login() action
  39. * in your controller. The user credentials will be checked on each request. If
  40. * valid credentials are not provided, required authentication headers will be sent
  41. * by this authentication provider which triggers the login dialog in the browser/client.
  42. *
  43. * You may also want to use `$this->Auth->unauthorizedRedirect = false;`.
  44. * This causes AuthComponent to throw a ForbiddenException exception instead of
  45. * redirecting to another page.
  46. *
  47. * ### Generating passwords compatible with Digest authentication.
  48. *
  49. * DigestAuthenticate requires a special password hash that conforms to RFC2617.
  50. * You can generate this password using `DigestAuthenticate::password()`
  51. *
  52. * `$digestPass = DigestAuthenticate::password($username, env('SERVER_NAME'), $password);`
  53. *
  54. * If you wish to use digest authentication alongside other authentication methods,
  55. * its recommended that you store the digest authentication separately. For
  56. * example `User.digest_pass` could be used for a digest password, while
  57. * `User.password` would store the password hash for use with other methods like
  58. * Basic or Form.
  59. */
  60. class DigestAuthenticate extends BasicAuthenticate {
  61. /**
  62. * Constructor
  63. *
  64. * Besides the keys specified in BaseAuthenticate::$_defaultConfig,
  65. * DigestAuthenticate uses the following extra keys:
  66. *
  67. * - `realm` The realm authentication is for, Defaults to the servername.
  68. * - `nonce` A nonce used for authentication. Defaults to `uniqid()`.
  69. * - `qop` Defaults to 'auth', no other values are supported at this time.
  70. * - `opaque` A string that must be returned unchanged by clients.
  71. * Defaults to `md5($config['realm'])`
  72. *
  73. * @param \Cake\Controller\ComponentRegistry $registry The Component registry
  74. * used on this request.
  75. * @param array $config Array of config to use.
  76. */
  77. public function __construct(ComponentRegistry $registry, $config) {
  78. $this->_registry = $registry;
  79. $this->config([
  80. 'realm' => null,
  81. 'qop' => 'auth',
  82. 'nonce' => uniqid(''),
  83. 'opaque' => null,
  84. ]);
  85. $this->config($config);
  86. }
  87. /**
  88. * Get a user based on information in the request. Used by cookie-less auth for stateless clients.
  89. *
  90. * @param \Cake\Network\Request $request Request object.
  91. * @return mixed Either false or an array of user information
  92. */
  93. public function getUser(Request $request) {
  94. $digest = $this->_getDigest($request);
  95. if (empty($digest)) {
  96. return false;
  97. }
  98. list(, $model) = pluginSplit($this->_config['userModel']);
  99. $user = $this->_findUser($digest['username']);
  100. if (empty($user)) {
  101. return false;
  102. }
  103. $field = $this->_config['fields']['password'];
  104. $password = $user[$field];
  105. unset($user[$field]);
  106. $hash = $this->generateResponseHash($digest, $password, $request->env('REQUEST_METHOD'));
  107. if ($digest['response'] === $hash) {
  108. return $user;
  109. }
  110. return false;
  111. }
  112. /**
  113. * Gets the digest headers from the request/environment.
  114. *
  115. * @param \Cake\Network\Request $request Request object.
  116. * @return array Array of digest information.
  117. */
  118. protected function _getDigest(Request $request) {
  119. $digest = $request->env('PHP_AUTH_DIGEST');
  120. if (empty($digest) && function_exists('apache_request_headers')) {
  121. $headers = apache_request_headers();
  122. if (!empty($headers['Authorization']) && substr($headers['Authorization'], 0, 7) === 'Digest ') {
  123. $digest = substr($headers['Authorization'], 7);
  124. }
  125. }
  126. if (empty($digest)) {
  127. return false;
  128. }
  129. return $this->parseAuthData($digest);
  130. }
  131. /**
  132. * Parse the digest authentication headers and split them up.
  133. *
  134. * @param string $digest The raw digest authentication headers.
  135. * @return array An array of digest authentication headers
  136. */
  137. public function parseAuthData($digest) {
  138. if (substr($digest, 0, 7) === 'Digest ') {
  139. $digest = substr($digest, 7);
  140. }
  141. $keys = $match = array();
  142. $req = array('nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1);
  143. preg_match_all('/(\w+)=([\'"]?)([a-zA-Z0-9\:\#\%@=.\/_-]+)\2/', $digest, $match, PREG_SET_ORDER);
  144. foreach ($match as $i) {
  145. $keys[$i[1]] = $i[3];
  146. unset($req[$i[1]]);
  147. }
  148. if (empty($req)) {
  149. return $keys;
  150. }
  151. return null;
  152. }
  153. /**
  154. * Generate the response hash for a given digest array.
  155. *
  156. * @param array $digest Digest information containing data from DigestAuthenticate::parseAuthData().
  157. * @param string $password The digest hash password generated with DigestAuthenticate::password()
  158. * @param string $method Request method
  159. * @return string Response hash
  160. */
  161. public function generateResponseHash($digest, $password, $method) {
  162. return md5(
  163. $password .
  164. ':' . $digest['nonce'] . ':' . $digest['nc'] . ':' . $digest['cnonce'] . ':' . $digest['qop'] . ':' .
  165. md5($method . ':' . $digest['uri'])
  166. );
  167. }
  168. /**
  169. * Creates an auth digest password hash to store
  170. *
  171. * @param string $username The username to use in the digest hash.
  172. * @param string $password The unhashed password to make a digest hash for.
  173. * @param string $realm The realm the password is for.
  174. * @return string the hashed password that can later be used with Digest authentication.
  175. */
  176. public static function password($username, $password, $realm) {
  177. return md5($username . ':' . $realm . ':' . $password);
  178. }
  179. /**
  180. * Generate the login headers
  181. *
  182. * @param \Cake\Network\Request $request Request object.
  183. * @return string Headers for logging in.
  184. */
  185. public function loginHeaders(Request $request) {
  186. $realm = $this->_config['realm'] ?: $request->env('SERVER_NAME');
  187. $options = array(
  188. 'realm' => $realm,
  189. 'qop' => $this->_config['qop'],
  190. 'nonce' => $this->_config['nonce'],
  191. 'opaque' => $this->_config['opaque'] ?: md5($realm)
  192. );
  193. $opts = array();
  194. foreach ($options as $k => $v) {
  195. $opts[] = sprintf('%s="%s"', $k, $v);
  196. }
  197. return 'WWW-Authenticate: Digest ' . implode(',', $opts);
  198. }
  199. }