DigestAuthenticate.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. namespace Cake\Controller\Component\Auth;
  17. use Cake\Controller\ComponentRegistry;
  18. use Cake\Controller\Component\Auth\BasicAuthenticate;
  19. use Cake\Network\Request;
  20. use Cake\Network\Response;
  21. use Cake\Utility\ClassRegistry;
  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 settings.
  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. * @since 2.0
  59. */
  60. class DigestAuthenticate extends BasicAuthenticate {
  61. /**
  62. * Settings for this object.
  63. *
  64. * - `fields` The fields to use to identify a user by.
  65. * - `userModel` The model name of the User, defaults to User.
  66. * - `scope` Additional conditions to use when looking up and authenticating users,
  67. * i.e. `array('User.is_active' => 1).`
  68. * - `recursive` The value of the recursive key passed to find(). Defaults to 0.
  69. * - `contain` Extra models to contain and store in session.
  70. * - `realm` The realm authentication is for, Defaults to the servername.
  71. * - `nonce` A nonce used for authentication. Defaults to `uniqid()`.
  72. * - `qop` Defaults to auth, no other values are supported at this time.
  73. * - `opaque` A string that must be returned unchanged by clients.
  74. * Defaults to `md5($settings['realm'])`
  75. *
  76. * @var array
  77. */
  78. public $settings = array(
  79. 'fields' => array(
  80. 'username' => 'username',
  81. 'password' => 'password'
  82. ),
  83. 'userModel' => 'User',
  84. 'scope' => array(),
  85. 'recursive' => 0,
  86. 'contain' => null,
  87. 'realm' => '',
  88. 'qop' => 'auth',
  89. 'nonce' => '',
  90. 'opaque' => '',
  91. 'passwordHasher' => 'Simple',
  92. );
  93. /**
  94. * Constructor, completes configuration for digest authentication.
  95. *
  96. * @param ComponentRegistry $registry The Component registry used on this request.
  97. * @param array $settings An array of settings.
  98. */
  99. public function __construct(ComponentRegistry $registry, $settings) {
  100. parent::__construct($registry, $settings);
  101. if (empty($this->settings['nonce'])) {
  102. $this->settings['nonce'] = uniqid('');
  103. }
  104. if (empty($this->settings['opaque'])) {
  105. $this->settings['opaque'] = md5($this->settings['realm']);
  106. }
  107. }
  108. /**
  109. * Get a user based on information in the request. Used by cookie-less auth for stateless clients.
  110. *
  111. * @param Cake\Network\Request $request Request object.
  112. * @return mixed Either false or an array of user information
  113. */
  114. public function getUser(Request $request) {
  115. $digest = $this->_getDigest();
  116. if (empty($digest)) {
  117. return false;
  118. }
  119. list(, $model) = pluginSplit($this->settings['userModel']);
  120. $user = $this->_findUser(array(
  121. $model . '.' . $this->settings['fields']['username'] => $digest['username']
  122. ));
  123. if (empty($user)) {
  124. return false;
  125. }
  126. $password = $user[$this->settings['fields']['password']];
  127. unset($user[$this->settings['fields']['password']]);
  128. if ($digest['response'] === $this->generateResponseHash($digest, $password)) {
  129. return $user;
  130. }
  131. return false;
  132. }
  133. /**
  134. * Gets the digest headers from the request/environment.
  135. *
  136. * @return array Array of digest information.
  137. */
  138. protected function _getDigest() {
  139. $digest = env('PHP_AUTH_DIGEST');
  140. if (empty($digest) && function_exists('apache_request_headers')) {
  141. $headers = apache_request_headers();
  142. if (!empty($headers['Authorization']) && substr($headers['Authorization'], 0, 7) === 'Digest ') {
  143. $digest = substr($headers['Authorization'], 7);
  144. }
  145. }
  146. if (empty($digest)) {
  147. return false;
  148. }
  149. return $this->parseAuthData($digest);
  150. }
  151. /**
  152. * Parse the digest authentication headers and split them up.
  153. *
  154. * @param string $digest The raw digest authentication headers.
  155. * @return array An array of digest authentication headers
  156. */
  157. public function parseAuthData($digest) {
  158. if (substr($digest, 0, 7) === 'Digest ') {
  159. $digest = substr($digest, 7);
  160. }
  161. $keys = $match = array();
  162. $req = array('nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1);
  163. preg_match_all('/(\w+)=([\'"]?)([a-zA-Z0-9@=.\/_-]+)\2/', $digest, $match, PREG_SET_ORDER);
  164. foreach ($match as $i) {
  165. $keys[$i[1]] = $i[3];
  166. unset($req[$i[1]]);
  167. }
  168. if (empty($req)) {
  169. return $keys;
  170. }
  171. return null;
  172. }
  173. /**
  174. * Generate the response hash for a given digest array.
  175. *
  176. * @param array $digest Digest information containing data from DigestAuthenticate::parseAuthData().
  177. * @param string $password The digest hash password generated with DigestAuthenticate::password()
  178. * @return string Response hash
  179. */
  180. public function generateResponseHash($digest, $password) {
  181. return md5(
  182. $password .
  183. ':' . $digest['nonce'] . ':' . $digest['nc'] . ':' . $digest['cnonce'] . ':' . $digest['qop'] . ':' .
  184. md5(env('REQUEST_METHOD') . ':' . $digest['uri'])
  185. );
  186. }
  187. /**
  188. * Creates an auth digest password hash to store
  189. *
  190. * @param string $username The username to use in the digest hash.
  191. * @param string $password The unhashed password to make a digest hash for.
  192. * @param string $realm The realm the password is for.
  193. * @return string the hashed password that can later be used with Digest authentication.
  194. */
  195. public static function password($username, $password, $realm) {
  196. return md5($username . ':' . $realm . ':' . $password);
  197. }
  198. /**
  199. * Generate the login headers
  200. *
  201. * @return string Headers for logging in.
  202. */
  203. public function loginHeaders() {
  204. $options = array(
  205. 'realm' => $this->settings['realm'],
  206. 'qop' => $this->settings['qop'],
  207. 'nonce' => $this->settings['nonce'],
  208. 'opaque' => $this->settings['opaque']
  209. );
  210. $opts = array();
  211. foreach ($options as $k => $v) {
  212. $opts[] = sprintf('%s="%s"', $k, $v);
  213. }
  214. return 'WWW-Authenticate: Digest ' . implode(',', $opts);
  215. }
  216. }