PageRenderTime 42ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/monica/vendor/zendframework/zendframework/library/Zend/Authentication/Adapter/Http.php

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