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