DigestAuthenticate.php 7.3 KB

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