DigestAuthenticate.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 MIT License (http://www.opensource.org/licenses/mit-license.php)
  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. );
  88. /**
  89. * Constructor, completes configuration for digest authentication.
  90. *
  91. * @param ComponentCollection $collection The Component collection used on this request.
  92. * @param array $settings An array of settings.
  93. */
  94. public function __construct(ComponentCollection $collection, $settings) {
  95. parent::__construct($collection, $settings);
  96. if (empty($this->settings['nonce'])) {
  97. $this->settings['nonce'] = uniqid('');
  98. }
  99. if (empty($this->settings['opaque'])) {
  100. $this->settings['opaque'] = md5($this->settings['realm']);
  101. }
  102. }
  103. /**
  104. * Get a user based on information in the request. Used by cookie-less auth for stateless clients.
  105. *
  106. * @param CakeRequest $request Request object.
  107. * @return mixed Either false or an array of user information
  108. */
  109. public function getUser(CakeRequest $request) {
  110. $digest = $this->_getDigest();
  111. if (empty($digest)) {
  112. return false;
  113. }
  114. $user = $this->_findUser($digest['username']);
  115. if (empty($user)) {
  116. return false;
  117. }
  118. $password = $user[$this->settings['fields']['password']];
  119. unset($user[$this->settings['fields']['password']]);
  120. if ($digest['response'] === $this->generateResponseHash($digest, $password)) {
  121. return $user;
  122. }
  123. return false;
  124. }
  125. /**
  126. * Find a user record using the standard options.
  127. *
  128. * @param string $username The username/identifier.
  129. * @param string $password Unused password, digest doesn't require passwords.
  130. * @return Mixed Either false on failure, or an array of user data.
  131. */
  132. protected function _findUser($username, $password = null) {
  133. $userModel = $this->settings['userModel'];
  134. list(, $model) = pluginSplit($userModel);
  135. $fields = $this->settings['fields'];
  136. $conditions = array(
  137. $model . '.' . $fields['username'] => $username,
  138. );
  139. if (!empty($this->settings['scope'])) {
  140. $conditions = array_merge($conditions, $this->settings['scope']);
  141. }
  142. $result = ClassRegistry::init($userModel)->find('first', array(
  143. 'conditions' => $conditions,
  144. 'recursive' => $this->settings['recursive']
  145. ));
  146. if (empty($result) || empty($result[$model])) {
  147. return false;
  148. }
  149. return $result[$model];
  150. }
  151. /**
  152. * Gets the digest headers from the request/environment.
  153. *
  154. * @return array Array of digest information.
  155. */
  156. protected function _getDigest() {
  157. $digest = env('PHP_AUTH_DIGEST');
  158. if (empty($digest) && function_exists('apache_request_headers')) {
  159. $headers = apache_request_headers();
  160. if (!empty($headers['Authorization']) && substr($headers['Authorization'], 0, 7) === 'Digest ') {
  161. $digest = substr($headers['Authorization'], 7);
  162. }
  163. }
  164. if (empty($digest)) {
  165. return false;
  166. }
  167. return $this->parseAuthData($digest);
  168. }
  169. /**
  170. * Parse the digest authentication headers and split them up.
  171. *
  172. * @param string $digest The raw digest authentication headers.
  173. * @return array An array of digest authentication headers
  174. */
  175. public function parseAuthData($digest) {
  176. if (substr($digest, 0, 7) === 'Digest ') {
  177. $digest = substr($digest, 7);
  178. }
  179. $keys = $match = array();
  180. $req = array('nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1);
  181. preg_match_all('/(\w+)=([\'"]?)([a-zA-Z0-9@=.\/_-]+)\2/', $digest, $match, PREG_SET_ORDER);
  182. foreach ($match as $i) {
  183. $keys[$i[1]] = $i[3];
  184. unset($req[$i[1]]);
  185. }
  186. if (empty($req)) {
  187. return $keys;
  188. }
  189. return null;
  190. }
  191. /**
  192. * Generate the response hash for a given digest array.
  193. *
  194. * @param array $digest Digest information containing data from DigestAuthenticate::parseAuthData().
  195. * @param string $password The digest hash password generated with DigestAuthenticate::password()
  196. * @return string Response hash
  197. */
  198. public function generateResponseHash($digest, $password) {
  199. return md5(
  200. $password .
  201. ':' . $digest['nonce'] . ':' . $digest['nc'] . ':' . $digest['cnonce'] . ':' . $digest['qop'] . ':' .
  202. md5(env('REQUEST_METHOD') . ':' . $digest['uri'])
  203. );
  204. }
  205. /**
  206. * Creates an auth digest password hash to store
  207. *
  208. * @param string $username The username to use in the digest hash.
  209. * @param string $password The unhashed password to make a digest hash for.
  210. * @param string $realm The realm the password is for.
  211. * @return string the hashed password that can later be used with Digest authentication.
  212. */
  213. public static function password($username, $password, $realm) {
  214. return md5($username . ':' . $realm . ':' . $password);
  215. }
  216. /**
  217. * Generate the login headers
  218. *
  219. * @return string Headers for logging in.
  220. */
  221. public function loginHeaders() {
  222. $options = array(
  223. 'realm' => $this->settings['realm'],
  224. 'qop' => $this->settings['qop'],
  225. 'nonce' => $this->settings['nonce'],
  226. 'opaque' => $this->settings['opaque']
  227. );
  228. $opts = array();
  229. foreach ($options as $k => $v) {
  230. $opts[] = sprintf('%s="%s"', $k, $v);
  231. }
  232. return 'WWW-Authenticate: Digest ' . implode(',', $opts);
  233. }
  234. }