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