DigestAuthenticate.php 8.8 KB

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