DigestAuthenticate.php 7.5 KB

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