PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Zend/Auth/Adapter/Http.php

https://bitbucket.org/kdms/sh-magento
PHP | 869 lines | 408 code | 86 blank | 375 comment | 114 complexity | 8520b7be3cb6d305113373e1d2da6fc3 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Auth
  17. * @subpackage Zend_Auth_Adapter_Http
  18. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: Http.php 23088 2010-10-11 19:53:24Z padraic $
  21. */
  22. /**
  23. * @see Zend_Auth_Adapter_Interface
  24. */
  25. #require_once 'Zend/Auth/Adapter/Interface.php';
  26. /**
  27. * HTTP Authentication Adapter
  28. *
  29. * Implements a pretty good chunk of RFC 2617.
  30. *
  31. * @category Zend
  32. * @package Zend_Auth
  33. * @subpackage Zend_Auth_Adapter_Http
  34. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  35. * @license http://framework.zend.com/license/new-bsd New BSD License
  36. * @todo Support auth-int
  37. * @todo Track nonces, nonce-count, opaque for replay protection and stale support
  38. * @todo Support Authentication-Info header
  39. */
  40. class Zend_Auth_Adapter_Http implements Zend_Auth_Adapter_Interface
  41. {
  42. /**
  43. * Reference to the HTTP Request object
  44. *
  45. * @var Zend_Controller_Request_Http
  46. */
  47. protected $_request;
  48. /**
  49. * Reference to the HTTP Response object
  50. *
  51. * @var Zend_Controller_Response_Http
  52. */
  53. protected $_response;
  54. /**
  55. * Object that looks up user credentials for the Basic scheme
  56. *
  57. * @var Zend_Auth_Adapter_Http_Resolver_Interface
  58. */
  59. protected $_basicResolver;
  60. /**
  61. * Object that looks up user credentials for the Digest scheme
  62. *
  63. * @var Zend_Auth_Adapter_Http_Resolver_Interface
  64. */
  65. protected $_digestResolver;
  66. /**
  67. * List of authentication schemes supported by this class
  68. *
  69. * @var array
  70. */
  71. protected $_supportedSchemes = array('basic', 'digest');
  72. /**
  73. * List of schemes this class will accept from the client
  74. *
  75. * @var array
  76. */
  77. protected $_acceptSchemes;
  78. /**
  79. * Space-delimited list of protected domains for Digest Auth
  80. *
  81. * @var string
  82. */
  83. protected $_domains;
  84. /**
  85. * The protection realm to use
  86. *
  87. * @var string
  88. */
  89. protected $_realm;
  90. /**
  91. * Nonce timeout period
  92. *
  93. * @var integer
  94. */
  95. protected $_nonceTimeout;
  96. /**
  97. * Whether to send the opaque value in the header. True by default
  98. *
  99. * @var boolean
  100. */
  101. protected $_useOpaque;
  102. /**
  103. * List of the supported digest algorithms. I want to support both MD5 and
  104. * MD5-sess, but MD5-sess won't make it into the first version.
  105. *
  106. * @var array
  107. */
  108. protected $_supportedAlgos = array('MD5');
  109. /**
  110. * The actual algorithm to use. Defaults to MD5
  111. *
  112. * @var string
  113. */
  114. protected $_algo;
  115. /**
  116. * List of supported qop options. My intetion is to support both 'auth' and
  117. * 'auth-int', but 'auth-int' won't make it into the first version.
  118. *
  119. * @var array
  120. */
  121. protected $_supportedQops = array('auth');
  122. /**
  123. * Whether or not to do Proxy Authentication instead of origin server
  124. * authentication (send 407's instead of 401's). Off by default.
  125. *
  126. * @var boolean
  127. */
  128. protected $_imaProxy;
  129. /**
  130. * Flag indicating the client is IE and didn't bother to return the opaque string
  131. *
  132. * @var boolean
  133. */
  134. protected $_ieNoOpaque;
  135. /**
  136. * Constructor
  137. *
  138. * @param array $config Configuration settings:
  139. * 'accept_schemes' => 'basic'|'digest'|'basic digest'
  140. * 'realm' => <string>
  141. * 'digest_domains' => <string> Space-delimited list of URIs
  142. * 'nonce_timeout' => <int>
  143. * 'use_opaque' => <bool> Whether to send the opaque value in the header
  144. * 'alogrithm' => <string> See $_supportedAlgos. Default: MD5
  145. * 'proxy_auth' => <bool> Whether to do authentication as a Proxy
  146. * @throws Zend_Auth_Adapter_Exception
  147. * @return void
  148. */
  149. public function __construct(array $config)
  150. {
  151. if (!extension_loaded('hash')) {
  152. /**
  153. * @see Zend_Auth_Adapter_Exception
  154. */
  155. #require_once 'Zend/Auth/Adapter/Exception.php';
  156. throw new Zend_Auth_Adapter_Exception(__CLASS__ . ' requires the \'hash\' extension');
  157. }
  158. $this->_request = null;
  159. $this->_response = null;
  160. $this->_ieNoOpaque = false;
  161. if (empty($config['accept_schemes'])) {
  162. /**
  163. * @see Zend_Auth_Adapter_Exception
  164. */
  165. #require_once 'Zend/Auth/Adapter/Exception.php';
  166. throw new Zend_Auth_Adapter_Exception('Config key \'accept_schemes\' is required');
  167. }
  168. $schemes = explode(' ', $config['accept_schemes']);
  169. $this->_acceptSchemes = array_intersect($schemes, $this->_supportedSchemes);
  170. if (empty($this->_acceptSchemes)) {
  171. /**
  172. * @see Zend_Auth_Adapter_Exception
  173. */
  174. #require_once 'Zend/Auth/Adapter/Exception.php';
  175. throw new Zend_Auth_Adapter_Exception('No supported schemes given in \'accept_schemes\'. Valid values: '
  176. . implode(', ', $this->_supportedSchemes));
  177. }
  178. // Double-quotes are used to delimit the realm string in the HTTP header,
  179. // and colons are field delimiters in the password file.
  180. if (empty($config['realm']) ||
  181. !ctype_print($config['realm']) ||
  182. strpos($config['realm'], ':') !== false ||
  183. strpos($config['realm'], '"') !== false) {
  184. /**
  185. * @see Zend_Auth_Adapter_Exception
  186. */
  187. #require_once 'Zend/Auth/Adapter/Exception.php';
  188. throw new Zend_Auth_Adapter_Exception('Config key \'realm\' is required, and must contain only printable '
  189. . 'characters, excluding quotation marks and colons');
  190. } else {
  191. $this->_realm = $config['realm'];
  192. }
  193. if (in_array('digest', $this->_acceptSchemes)) {
  194. if (empty($config['digest_domains']) ||
  195. !ctype_print($config['digest_domains']) ||
  196. strpos($config['digest_domains'], '"') !== false) {
  197. /**
  198. * @see Zend_Auth_Adapter_Exception
  199. */
  200. #require_once 'Zend/Auth/Adapter/Exception.php';
  201. throw new Zend_Auth_Adapter_Exception('Config key \'digest_domains\' is required, and must contain '
  202. . 'only printable characters, excluding quotation marks');
  203. } else {
  204. $this->_domains = $config['digest_domains'];
  205. }
  206. if (empty($config['nonce_timeout']) ||
  207. !is_numeric($config['nonce_timeout'])) {
  208. /**
  209. * @see Zend_Auth_Adapter_Exception
  210. */
  211. #require_once 'Zend/Auth/Adapter/Exception.php';
  212. throw new Zend_Auth_Adapter_Exception('Config key \'nonce_timeout\' is required, and must be an '
  213. . 'integer');
  214. } else {
  215. $this->_nonceTimeout = (int) $config['nonce_timeout'];
  216. }
  217. // We use the opaque value unless explicitly told not to
  218. if (isset($config['use_opaque']) && false == (bool) $config['use_opaque']) {
  219. $this->_useOpaque = false;
  220. } else {
  221. $this->_useOpaque = true;
  222. }
  223. if (isset($config['algorithm']) && in_array($config['algorithm'], $this->_supportedAlgos)) {
  224. $this->_algo = $config['algorithm'];
  225. } else {
  226. $this->_algo = 'MD5';
  227. }
  228. }
  229. // Don't be a proxy unless explicitly told to do so
  230. if (isset($config['proxy_auth']) && true == (bool) $config['proxy_auth']) {
  231. $this->_imaProxy = true; // I'm a Proxy
  232. } else {
  233. $this->_imaProxy = false;
  234. }
  235. }
  236. /**
  237. * Setter for the _basicResolver property
  238. *
  239. * @param Zend_Auth_Adapter_Http_Resolver_Interface $resolver
  240. * @return Zend_Auth_Adapter_Http Provides a fluent interface
  241. */
  242. public function setBasicResolver(Zend_Auth_Adapter_Http_Resolver_Interface $resolver)
  243. {
  244. $this->_basicResolver = $resolver;
  245. return $this;
  246. }
  247. /**
  248. * Getter for the _basicResolver property
  249. *
  250. * @return Zend_Auth_Adapter_Http_Resolver_Interface
  251. */
  252. public function getBasicResolver()
  253. {
  254. return $this->_basicResolver;
  255. }
  256. /**
  257. * Setter for the _digestResolver property
  258. *
  259. * @param Zend_Auth_Adapter_Http_Resolver_Interface $resolver
  260. * @return Zend_Auth_Adapter_Http Provides a fluent interface
  261. */
  262. public function setDigestResolver(Zend_Auth_Adapter_Http_Resolver_Interface $resolver)
  263. {
  264. $this->_digestResolver = $resolver;
  265. return $this;
  266. }
  267. /**
  268. * Getter for the _digestResolver property
  269. *
  270. * @return Zend_Auth_Adapter_Http_Resolver_Interface
  271. */
  272. public function getDigestResolver()
  273. {
  274. return $this->_digestResolver;
  275. }
  276. /**
  277. * Setter for the Request object
  278. *
  279. * @param Zend_Controller_Request_Http $request
  280. * @return Zend_Auth_Adapter_Http Provides a fluent interface
  281. */
  282. public function setRequest(Zend_Controller_Request_Http $request)
  283. {
  284. $this->_request = $request;
  285. return $this;
  286. }
  287. /**
  288. * Getter for the Request object
  289. *
  290. * @return Zend_Controller_Request_Http
  291. */
  292. public function getRequest()
  293. {
  294. return $this->_request;
  295. }
  296. /**
  297. * Setter for the Response object
  298. *
  299. * @param Zend_Controller_Response_Http $response
  300. * @return Zend_Auth_Adapter_Http Provides a fluent interface
  301. */
  302. public function setResponse(Zend_Controller_Response_Http $response)
  303. {
  304. $this->_response = $response;
  305. return $this;
  306. }
  307. /**
  308. * Getter for the Response object
  309. *
  310. * @return Zend_Controller_Response_Http
  311. */
  312. public function getResponse()
  313. {
  314. return $this->_response;
  315. }
  316. /**
  317. * Authenticate
  318. *
  319. * @throws Zend_Auth_Adapter_Exception
  320. * @return Zend_Auth_Result
  321. */
  322. public function authenticate()
  323. {
  324. if (empty($this->_request) ||
  325. empty($this->_response)) {
  326. /**
  327. * @see Zend_Auth_Adapter_Exception
  328. */
  329. #require_once 'Zend/Auth/Adapter/Exception.php';
  330. throw new Zend_Auth_Adapter_Exception('Request and Response objects must be set before calling '
  331. . 'authenticate()');
  332. }
  333. if ($this->_imaProxy) {
  334. $getHeader = 'Proxy-Authorization';
  335. } else {
  336. $getHeader = 'Authorization';
  337. }
  338. $authHeader = $this->_request->getHeader($getHeader);
  339. if (!$authHeader) {
  340. return $this->_challengeClient();
  341. }
  342. list($clientScheme) = explode(' ', $authHeader);
  343. $clientScheme = strtolower($clientScheme);
  344. // The server can issue multiple challenges, but the client should
  345. // answer with only the selected auth scheme.
  346. if (!in_array($clientScheme, $this->_supportedSchemes)) {
  347. $this->_response->setHttpResponseCode(400);
  348. return new Zend_Auth_Result(
  349. Zend_Auth_Result::FAILURE_UNCATEGORIZED,
  350. array(),
  351. array('Client requested an incorrect or unsupported authentication scheme')
  352. );
  353. }
  354. // client sent a scheme that is not the one required
  355. if (!in_array($clientScheme, $this->_acceptSchemes)) {
  356. // challenge again the client
  357. return $this->_challengeClient();
  358. }
  359. switch ($clientScheme) {
  360. case 'basic':
  361. $result = $this->_basicAuth($authHeader);
  362. break;
  363. case 'digest':
  364. $result = $this->_digestAuth($authHeader);
  365. break;
  366. default:
  367. /**
  368. * @see Zend_Auth_Adapter_Exception
  369. */
  370. #require_once 'Zend/Auth/Adapter/Exception.php';
  371. throw new Zend_Auth_Adapter_Exception('Unsupported authentication scheme');
  372. }
  373. return $result;
  374. }
  375. /**
  376. * Challenge Client
  377. *
  378. * Sets a 401 or 407 Unauthorized response code, and creates the
  379. * appropriate Authenticate header(s) to prompt for credentials.
  380. *
  381. * @return Zend_Auth_Result Always returns a non-identity Auth result
  382. */
  383. protected function _challengeClient()
  384. {
  385. if ($this->_imaProxy) {
  386. $statusCode = 407;
  387. $headerName = 'Proxy-Authenticate';
  388. } else {
  389. $statusCode = 401;
  390. $headerName = 'WWW-Authenticate';
  391. }
  392. $this->_response->setHttpResponseCode($statusCode);
  393. // Send a challenge in each acceptable authentication scheme
  394. if (in_array('basic', $this->_acceptSchemes)) {
  395. $this->_response->setHeader($headerName, $this->_basicHeader());
  396. }
  397. if (in_array('digest', $this->_acceptSchemes)) {
  398. $this->_response->setHeader($headerName, $this->_digestHeader());
  399. }
  400. return new Zend_Auth_Result(
  401. Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
  402. array(),
  403. array('Invalid or absent credentials; challenging client')
  404. );
  405. }
  406. /**
  407. * Basic Header
  408. *
  409. * Generates a Proxy- or WWW-Authenticate header value in the Basic
  410. * authentication scheme.
  411. *
  412. * @return string Authenticate header value
  413. */
  414. protected function _basicHeader()
  415. {
  416. return 'Basic realm="' . $this->_realm . '"';
  417. }
  418. /**
  419. * Digest Header
  420. *
  421. * Generates a Proxy- or WWW-Authenticate header value in the Digest
  422. * authentication scheme.
  423. *
  424. * @return string Authenticate header value
  425. */
  426. protected function _digestHeader()
  427. {
  428. $wwwauth = 'Digest realm="' . $this->_realm . '", '
  429. . 'domain="' . $this->_domains . '", '
  430. . 'nonce="' . $this->_calcNonce() . '", '
  431. . ($this->_useOpaque ? 'opaque="' . $this->_calcOpaque() . '", ' : '')
  432. . 'algorithm="' . $this->_algo . '", '
  433. . 'qop="' . implode(',', $this->_supportedQops) . '"';
  434. return $wwwauth;
  435. }
  436. /**
  437. * Basic Authentication
  438. *
  439. * @param string $header Client's Authorization header
  440. * @throws Zend_Auth_Adapter_Exception
  441. * @return Zend_Auth_Result
  442. */
  443. protected function _basicAuth($header)
  444. {
  445. if (empty($header)) {
  446. /**
  447. * @see Zend_Auth_Adapter_Exception
  448. */
  449. #require_once 'Zend/Auth/Adapter/Exception.php';
  450. throw new Zend_Auth_Adapter_Exception('The value of the client Authorization header is required');
  451. }
  452. if (empty($this->_basicResolver)) {
  453. /**
  454. * @see Zend_Auth_Adapter_Exception
  455. */
  456. #require_once 'Zend/Auth/Adapter/Exception.php';
  457. throw new Zend_Auth_Adapter_Exception('A basicResolver object must be set before doing Basic '
  458. . 'authentication');
  459. }
  460. // Decode the Authorization header
  461. $auth = substr($header, strlen('Basic '));
  462. $auth = base64_decode($auth);
  463. if (!$auth) {
  464. /**
  465. * @see Zend_Auth_Adapter_Exception
  466. */
  467. #require_once 'Zend/Auth/Adapter/Exception.php';
  468. throw new Zend_Auth_Adapter_Exception('Unable to base64_decode Authorization header value');
  469. }
  470. // See ZF-1253. Validate the credentials the same way the digest
  471. // implementation does. If invalid credentials are detected,
  472. // re-challenge the client.
  473. if (!ctype_print($auth)) {
  474. return $this->_challengeClient();
  475. }
  476. // Fix for ZF-1515: Now re-challenges on empty username or password
  477. $creds = array_filter(explode(':', $auth));
  478. if (count($creds) != 2) {
  479. return $this->_challengeClient();
  480. }
  481. $password = $this->_basicResolver->resolve($creds[0], $this->_realm);
  482. if ($password && $this->_secureStringCompare($password, $creds[1])) {
  483. $identity = array('username'=>$creds[0], 'realm'=>$this->_realm);
  484. return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity);
  485. } else {
  486. return $this->_challengeClient();
  487. }
  488. }
  489. /**
  490. * Digest Authentication
  491. *
  492. * @param string $header Client's Authorization header
  493. * @throws Zend_Auth_Adapter_Exception
  494. * @return Zend_Auth_Result Valid auth result only on successful auth
  495. */
  496. protected function _digestAuth($header)
  497. {
  498. if (empty($header)) {
  499. /**
  500. * @see Zend_Auth_Adapter_Exception
  501. */
  502. #require_once 'Zend/Auth/Adapter/Exception.php';
  503. throw new Zend_Auth_Adapter_Exception('The value of the client Authorization header is required');
  504. }
  505. if (empty($this->_digestResolver)) {
  506. /**
  507. * @see Zend_Auth_Adapter_Exception
  508. */
  509. #require_once 'Zend/Auth/Adapter/Exception.php';
  510. throw new Zend_Auth_Adapter_Exception('A digestResolver object must be set before doing Digest authentication');
  511. }
  512. $data = $this->_parseDigestAuth($header);
  513. if ($data === false) {
  514. $this->_response->setHttpResponseCode(400);
  515. return new Zend_Auth_Result(
  516. Zend_Auth_Result::FAILURE_UNCATEGORIZED,
  517. array(),
  518. array('Invalid Authorization header format')
  519. );
  520. }
  521. // See ZF-1052. This code was a bit too unforgiving of invalid
  522. // usernames. Now, if the username is bad, we re-challenge the client.
  523. if ('::invalid::' == $data['username']) {
  524. return $this->_challengeClient();
  525. }
  526. // Verify that the client sent back the same nonce
  527. if ($this->_calcNonce() != $data['nonce']) {
  528. return $this->_challengeClient();
  529. }
  530. // The opaque value is also required to match, but of course IE doesn't
  531. // play ball.
  532. if (!$this->_ieNoOpaque && $this->_calcOpaque() != $data['opaque']) {
  533. return $this->_challengeClient();
  534. }
  535. // Look up the user's password hash. If not found, deny access.
  536. // This makes no assumptions about how the password hash was
  537. // constructed beyond that it must have been built in such a way as
  538. // to be recreatable with the current settings of this object.
  539. $ha1 = $this->_digestResolver->resolve($data['username'], $data['realm']);
  540. if ($ha1 === false) {
  541. return $this->_challengeClient();
  542. }
  543. // If MD5-sess is used, a1 value is made of the user's password
  544. // hash with the server and client nonce appended, separated by
  545. // colons.
  546. if ($this->_algo == 'MD5-sess') {
  547. $ha1 = hash('md5', $ha1 . ':' . $data['nonce'] . ':' . $data['cnonce']);
  548. }
  549. // Calculate h(a2). The value of this hash depends on the qop
  550. // option selected by the client and the supported hash functions
  551. switch ($data['qop']) {
  552. case 'auth':
  553. $a2 = $this->_request->getMethod() . ':' . $data['uri'];
  554. break;
  555. case 'auth-int':
  556. // Should be REQUEST_METHOD . ':' . uri . ':' . hash(entity-body),
  557. // but this isn't supported yet, so fall through to default case
  558. default:
  559. /**
  560. * @see Zend_Auth_Adapter_Exception
  561. */
  562. #require_once 'Zend/Auth/Adapter/Exception.php';
  563. throw new Zend_Auth_Adapter_Exception('Client requested an unsupported qop option');
  564. }
  565. // Using hash() should make parameterizing the hash algorithm
  566. // easier
  567. $ha2 = hash('md5', $a2);
  568. // Calculate the server's version of the request-digest. This must
  569. // match $data['response']. See RFC 2617, section 3.2.2.1
  570. $message = $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $ha2;
  571. $digest = hash('md5', $ha1 . ':' . $message);
  572. // If our digest matches the client's let them in, otherwise return
  573. // a 401 code and exit to prevent access to the protected resource.
  574. if ($this->_secureStringCompare($digest, $data['response'])) {
  575. $identity = array('username'=>$data['username'], 'realm'=>$data['realm']);
  576. return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity);
  577. } else {
  578. return $this->_challengeClient();
  579. }
  580. }
  581. /**
  582. * Calculate Nonce
  583. *
  584. * @return string The nonce value
  585. */
  586. protected function _calcNonce()
  587. {
  588. // Once subtle consequence of this timeout calculation is that it
  589. // actually divides all of time into _nonceTimeout-sized sections, such
  590. // that the value of timeout is the point in time of the next
  591. // approaching "boundary" of a section. This allows the server to
  592. // consistently generate the same timeout (and hence the same nonce
  593. // value) across requests, but only as long as one of those
  594. // "boundaries" is not crossed between requests. If that happens, the
  595. // nonce will change on its own, and effectively log the user out. This
  596. // would be surprising if the user just logged in.
  597. $timeout = ceil(time() / $this->_nonceTimeout) * $this->_nonceTimeout;
  598. $nonce = hash('md5', $timeout . ':' . $this->_request->getServer('HTTP_USER_AGENT') . ':' . __CLASS__);
  599. return $nonce;
  600. }
  601. /**
  602. * Calculate Opaque
  603. *
  604. * The opaque string can be anything; the client must return it exactly as
  605. * it was sent. It may be useful to store data in this string in some
  606. * applications. Ideally, a new value for this would be generated each time
  607. * a WWW-Authenticate header is sent (in order to reduce predictability),
  608. * but we would have to be able to create the same exact value across at
  609. * least two separate requests from the same client.
  610. *
  611. * @return string The opaque value
  612. */
  613. protected function _calcOpaque()
  614. {
  615. return hash('md5', 'Opaque Data:' . __CLASS__);
  616. }
  617. /**
  618. * Parse Digest Authorization header
  619. *
  620. * @param string $header Client's Authorization: HTTP header
  621. * @return array|false Data elements from header, or false if any part of
  622. * the header is invalid
  623. */
  624. protected function _parseDigestAuth($header)
  625. {
  626. $temp = null;
  627. $data = array();
  628. // See ZF-1052. Detect invalid usernames instead of just returning a
  629. // 400 code.
  630. $ret = preg_match('/username="([^"]+)"/', $header, $temp);
  631. if (!$ret || empty($temp[1])
  632. || !ctype_print($temp[1])
  633. || strpos($temp[1], ':') !== false) {
  634. $data['username'] = '::invalid::';
  635. } else {
  636. $data['username'] = $temp[1];
  637. }
  638. $temp = null;
  639. $ret = preg_match('/realm="([^"]+)"/', $header, $temp);
  640. if (!$ret || empty($temp[1])) {
  641. return false;
  642. }
  643. if (!ctype_print($temp[1]) || strpos($temp[1], ':') !== false) {
  644. return false;
  645. } else {
  646. $data['realm'] = $temp[1];
  647. }
  648. $temp = null;
  649. $ret = preg_match('/nonce="([^"]+)"/', $header, $temp);
  650. if (!$ret || empty($temp[1])) {
  651. return false;
  652. }
  653. if (!ctype_xdigit($temp[1])) {
  654. return false;
  655. } else {
  656. $data['nonce'] = $temp[1];
  657. }
  658. $temp = null;
  659. $ret = preg_match('/uri="([^"]+)"/', $header, $temp);
  660. if (!$ret || empty($temp[1])) {
  661. return false;
  662. }
  663. // Section 3.2.2.5 in RFC 2617 says the authenticating server must
  664. // verify that the URI field in the Authorization header is for the
  665. // same resource requested in the Request Line.
  666. $rUri = @parse_url($this->_request->getRequestUri());
  667. $cUri = @parse_url($temp[1]);
  668. if (false === $rUri || false === $cUri) {
  669. return false;
  670. } else {
  671. // Make sure the path portion of both URIs is the same
  672. if ($rUri['path'] != $cUri['path']) {
  673. return false;
  674. }
  675. // Section 3.2.2.5 seems to suggest that the value of the URI
  676. // Authorization field should be made into an absolute URI if the
  677. // Request URI is absolute, but it's vague, and that's a bunch of
  678. // code I don't want to write right now.
  679. $data['uri'] = $temp[1];
  680. }
  681. $temp = null;
  682. $ret = preg_match('/response="([^"]+)"/', $header, $temp);
  683. if (!$ret || empty($temp[1])) {
  684. return false;
  685. }
  686. if (32 != strlen($temp[1]) || !ctype_xdigit($temp[1])) {
  687. return false;
  688. } else {
  689. $data['response'] = $temp[1];
  690. }
  691. $temp = null;
  692. // The spec says this should default to MD5 if omitted. OK, so how does
  693. // that square with the algo we send out in the WWW-Authenticate header,
  694. // if it can easily be overridden by the client?
  695. $ret = preg_match('/algorithm="?(' . $this->_algo . ')"?/', $header, $temp);
  696. if ($ret && !empty($temp[1])
  697. && in_array($temp[1], $this->_supportedAlgos)) {
  698. $data['algorithm'] = $temp[1];
  699. } else {
  700. $data['algorithm'] = 'MD5'; // = $this->_algo; ?
  701. }
  702. $temp = null;
  703. // Not optional in this implementation
  704. $ret = preg_match('/cnonce="([^"]+)"/', $header, $temp);
  705. if (!$ret || empty($temp[1])) {
  706. return false;
  707. }
  708. if (!ctype_print($temp[1])) {
  709. return false;
  710. } else {
  711. $data['cnonce'] = $temp[1];
  712. }
  713. $temp = null;
  714. // If the server sent an opaque value, the client must send it back
  715. if ($this->_useOpaque) {
  716. $ret = preg_match('/opaque="([^"]+)"/', $header, $temp);
  717. if (!$ret || empty($temp[1])) {
  718. // Big surprise: IE isn't RFC 2617-compliant.
  719. if (false !== strpos($this->_request->getHeader('User-Agent'), 'MSIE')) {
  720. $temp[1] = '';
  721. $this->_ieNoOpaque = true;
  722. } else {
  723. return false;
  724. }
  725. }
  726. // This implementation only sends MD5 hex strings in the opaque value
  727. if (!$this->_ieNoOpaque &&
  728. (32 != strlen($temp[1]) || !ctype_xdigit($temp[1]))) {
  729. return false;
  730. } else {
  731. $data['opaque'] = $temp[1];
  732. }
  733. $temp = null;
  734. }
  735. // Not optional in this implementation, but must be one of the supported
  736. // qop types
  737. $ret = preg_match('/qop="?(' . implode('|', $this->_supportedQops) . ')"?/', $header, $temp);
  738. if (!$ret || empty($temp[1])) {
  739. return false;
  740. }
  741. if (!in_array($temp[1], $this->_supportedQops)) {
  742. return false;
  743. } else {
  744. $data['qop'] = $temp[1];
  745. }
  746. $temp = null;
  747. // Not optional in this implementation. The spec says this value
  748. // shouldn't be a quoted string, but apparently some implementations
  749. // quote it anyway. See ZF-1544.
  750. $ret = preg_match('/nc="?([0-9A-Fa-f]{8})"?/', $header, $temp);
  751. if (!$ret || empty($temp[1])) {
  752. return false;
  753. }
  754. if (8 != strlen($temp[1]) || !ctype_xdigit($temp[1])) {
  755. return false;
  756. } else {
  757. $data['nc'] = $temp[1];
  758. }
  759. $temp = null;
  760. return $data;
  761. }
  762. /**
  763. * Securely compare two strings for equality while avoided C level memcmp()
  764. * optimisations capable of leaking timing information useful to an attacker
  765. * attempting to iteratively guess the unknown string (e.g. password) being
  766. * compared against.
  767. *
  768. * @param string $a
  769. * @param string $b
  770. * @return bool
  771. */
  772. protected function _secureStringCompare($a, $b)
  773. {
  774. if (strlen($a) !== strlen($b)) {
  775. return false;
  776. }
  777. $result = 0;
  778. for ($i = 0; $i < strlen($a); $i++) {
  779. $result |= ord($a[$i]) ^ ord($b[$i]);
  780. }
  781. return $result == 0;
  782. }
  783. }