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: * - `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: 'realm' => '',
83: 'qop' => 'auth',
84: 'nonce' => '',
85: 'opaque' => ''
86: );
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['realm'])) {
97: $this->settings['realm'] = env('SERVER_NAME');
98: }
99: if (empty($this->settings['nonce'])) {
100: $this->settings['nonce'] = uniqid('');
101: }
102: if (empty($this->settings['opaque'])) {
103: $this->settings['opaque'] = md5($this->settings['realm']);
104: }
105: }
106:
107: /**
108: * Authenticate a user using Digest HTTP auth. Will use the configured User model and attempt a
109: * login using Digest HTTP auth.
110: *
111: * @param CakeRequest $request The request to authenticate with.
112: * @param CakeResponse $response The response to add headers to.
113: * @return mixed Either false on failure, or an array of user data on success.
114: */
115: public function authenticate(CakeRequest $request, CakeResponse $response) {
116: $user = $this->getUser($request);
117:
118: if (empty($user)) {
119: $response->header($this->loginHeaders());
120: $response->statusCode(401);
121: $response->send();
122: return false;
123: }
124: return $user;
125: }
126:
127: /**
128: * Get a user based on information in the request. Used by cookie-less auth for stateless clients.
129: *
130: * @param CakeRequest $request Request object.
131: * @return mixed Either false or an array of user information
132: */
133: public function getUser($request) {
134: $digest = $this->_getDigest();
135: if (empty($digest)) {
136: return false;
137: }
138: $user = $this->_findUser($digest['username'], null);
139: if (empty($user)) {
140: return false;
141: }
142: $password = $user[$this->settings['fields']['password']];
143: unset($user[$this->settings['fields']['password']]);
144: if ($digest['response'] === $this->generateResponseHash($digest, $password)) {
145: return $user;
146: }
147: return false;
148: }
149:
150: /**
151: * Find a user record using the standard options.
152: *
153: * @param string $username The username/identifier.
154: * @param string $password Unused password, digest doesn't require passwords.
155: * @return Mixed Either false on failure, or an array of user data.
156: */
157: protected function _findUser($username, $password) {
158: $userModel = $this->settings['userModel'];
159: list($plugin, $model) = pluginSplit($userModel);
160: $fields = $this->settings['fields'];
161:
162: $conditions = array(
163: $model . '.' . $fields['username'] => $username,
164: );
165: if (!empty($this->settings['scope'])) {
166: $conditions = array_merge($conditions, $this->settings['scope']);
167: }
168: $result = ClassRegistry::init($userModel)->find('first', array(
169: 'conditions' => $conditions,
170: 'recursive' => (int)$this->settings['recursive']
171: ));
172: if (empty($result) || empty($result[$model])) {
173: return false;
174: }
175: return $result[$model];
176: }
177:
178: /**
179: * Gets the digest headers from the request/environment.
180: *
181: * @return array Array of digest information.
182: */
183: protected function _getDigest() {
184: $digest = env('PHP_AUTH_DIGEST');
185: if (empty($digest) && function_exists('apache_request_headers')) {
186: $headers = apache_request_headers();
187: if (!empty($headers['Authorization']) && substr($headers['Authorization'], 0, 7) == 'Digest ') {
188: $digest = substr($headers['Authorization'], 7);
189: }
190: }
191: if (empty($digest)) {
192: return false;
193: }
194: return $this->parseAuthData($digest);
195: }
196:
197: /**
198: * Parse the digest authentication headers and split them up.
199: *
200: * @param string $digest The raw digest authentication headers.
201: * @return array An array of digest authentication headers
202: */
203: public function parseAuthData($digest) {
204: if (substr($digest, 0, 7) == 'Digest ') {
205: $digest = substr($digest, 7);
206: }
207: $keys = $match = array();
208: $req = array('nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1);
209: preg_match_all('/(\w+)=([\'"]?)([a-zA-Z0-9@=.\/_-]+)\2/', $digest, $match, PREG_SET_ORDER);
210:
211: foreach ($match as $i) {
212: $keys[$i[1]] = $i[3];
213: unset($req[$i[1]]);
214: }
215:
216: if (empty($req)) {
217: return $keys;
218: }
219: return null;
220: }
221:
222: /**
223: * Generate the response hash for a given digest array.
224: *
225: * @param array $digest Digest information containing data from DigestAuthenticate::parseAuthData().
226: * @param string $password The digest hash password generated with DigestAuthenticate::password()
227: * @return string Response hash
228: */
229: public function generateResponseHash($digest, $password) {
230: return md5(
231: $password .
232: ':' . $digest['nonce'] . ':' . $digest['nc'] . ':' . $digest['cnonce'] . ':' . $digest['qop'] . ':' .
233: md5(env('REQUEST_METHOD') . ':' . $digest['uri'])
234: );
235: }
236:
237: /**
238: * Creates an auth digest password hash to store
239: *
240: * @param string $username The username to use in the digest hash.
241: * @param string $password The unhashed password to make a digest hash for.
242: * @param string $realm The realm the password is for.
243: * @return string the hashed password that can later be used with Digest authentication.
244: */
245: public static function password($username, $password, $realm) {
246: return md5($username . ':' . $realm . ':' . $password);
247: }
248:
249: /**
250: * Generate the login headers
251: *
252: * @return string Headers for logging in.
253: */
254: public function loginHeaders() {
255: $options = array(
256: 'realm' => $this->settings['realm'],
257: 'qop' => $this->settings['qop'],
258: 'nonce' => $this->settings['nonce'],
259: 'opaque' => $this->settings['opaque']
260: );
261: $opts = array();
262: foreach ($options as $k => $v) {
263: $opts[] = sprintf('%s="%s"', $k, $v);
264: }
265: return 'WWW-Authenticate: Digest ' . implode(',', $opts);
266: }
267:
268: }
269: