PageRenderTime 60ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/inc/lib/Auth/OpenID/Consumer.php

https://bitbucket.org/yoander/mtrack
PHP | 2230 lines | 1121 code | 278 blank | 831 comment | 192 complexity | 8b9446deaf7e84fdb814f02d7c7e4079 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * This module documents the main interface with the OpenID consumer
  4. * library. The only part of the library which has to be used and
  5. * isn't documented in full here is the store required to create an
  6. * Auth_OpenID_Consumer instance. More on the abstract store type and
  7. * concrete implementations of it that are provided in the
  8. * documentation for the Auth_OpenID_Consumer constructor.
  9. *
  10. * OVERVIEW
  11. *
  12. * The OpenID identity verification process most commonly uses the
  13. * following steps, as visible to the user of this library:
  14. *
  15. * 1. The user enters their OpenID into a field on the consumer's
  16. * site, and hits a login button.
  17. * 2. The consumer site discovers the user's OpenID server using the
  18. * YADIS protocol.
  19. * 3. The consumer site sends the browser a redirect to the identity
  20. * server. This is the authentication request as described in
  21. * the OpenID specification.
  22. * 4. The identity server's site sends the browser a redirect back
  23. * to the consumer site. This redirect contains the server's
  24. * response to the authentication request.
  25. *
  26. * The most important part of the flow to note is the consumer's site
  27. * must handle two separate HTTP requests in order to perform the full
  28. * identity check.
  29. *
  30. * LIBRARY DESIGN
  31. *
  32. * This consumer library is designed with that flow in mind. The goal
  33. * is to make it as easy as possible to perform the above steps
  34. * securely.
  35. *
  36. * At a high level, there are two important parts in the consumer
  37. * library. The first important part is this module, which contains
  38. * the interface to actually use this library. The second is the
  39. * Auth_OpenID_Interface class, which describes the interface to use
  40. * if you need to create a custom method for storing the state this
  41. * library needs to maintain between requests.
  42. *
  43. * In general, the second part is less important for users of the
  44. * library to know about, as several implementations are provided
  45. * which cover a wide variety of situations in which consumers may use
  46. * the library.
  47. *
  48. * This module contains a class, Auth_OpenID_Consumer, with methods
  49. * corresponding to the actions necessary in each of steps 2, 3, and 4
  50. * described in the overview. Use of this library should be as easy
  51. * as creating an Auth_OpenID_Consumer instance and calling the
  52. * methods appropriate for the action the site wants to take.
  53. *
  54. * STORES AND DUMB MODE
  55. *
  56. * OpenID is a protocol that works best when the consumer site is able
  57. * to store some state. This is the normal mode of operation for the
  58. * protocol, and is sometimes referred to as smart mode. There is
  59. * also a fallback mode, known as dumb mode, which is available when
  60. * the consumer site is not able to store state. This mode should be
  61. * avoided when possible, as it leaves the implementation more
  62. * vulnerable to replay attacks.
  63. *
  64. * The mode the library works in for normal operation is determined by
  65. * the store that it is given. The store is an abstraction that
  66. * handles the data that the consumer needs to manage between http
  67. * requests in order to operate efficiently and securely.
  68. *
  69. * Several store implementation are provided, and the interface is
  70. * fully documented so that custom stores can be used as well. See
  71. * the documentation for the Auth_OpenID_Consumer class for more
  72. * information on the interface for stores. The implementations that
  73. * are provided allow the consumer site to store the necessary data in
  74. * several different ways, including several SQL databases and normal
  75. * files on disk.
  76. *
  77. * There is an additional concrete store provided that puts the system
  78. * in dumb mode. This is not recommended, as it removes the library's
  79. * ability to stop replay attacks reliably. It still uses time-based
  80. * checking to make replay attacks only possible within a small
  81. * window, but they remain possible within that window. This store
  82. * should only be used if the consumer site has no way to retain data
  83. * between requests at all.
  84. *
  85. * IMMEDIATE MODE
  86. *
  87. * In the flow described above, the user may need to confirm to the
  88. * lidentity server that it's ok to authorize his or her identity.
  89. * The server may draw pages asking for information from the user
  90. * before it redirects the browser back to the consumer's site. This
  91. * is generally transparent to the consumer site, so it is typically
  92. * ignored as an implementation detail.
  93. *
  94. * There can be times, however, where the consumer site wants to get a
  95. * response immediately. When this is the case, the consumer can put
  96. * the library in immediate mode. In immediate mode, there is an
  97. * extra response possible from the server, which is essentially the
  98. * server reporting that it doesn't have enough information to answer
  99. * the question yet.
  100. *
  101. * USING THIS LIBRARY
  102. *
  103. * Integrating this library into an application is usually a
  104. * relatively straightforward process. The process should basically
  105. * follow this plan:
  106. *
  107. * Add an OpenID login field somewhere on your site. When an OpenID
  108. * is entered in that field and the form is submitted, it should make
  109. * a request to the your site which includes that OpenID URL.
  110. *
  111. * First, the application should instantiate the Auth_OpenID_Consumer
  112. * class using the store of choice (Auth_OpenID_FileStore or one of
  113. * the SQL-based stores). If the application has a custom
  114. * session-management implementation, an object implementing the
  115. * {@link Auth_Yadis_PHPSession} interface should be passed as the
  116. * second parameter. Otherwise, the default uses $_SESSION.
  117. *
  118. * Next, the application should call the Auth_OpenID_Consumer object's
  119. * 'begin' method. This method takes the OpenID URL. The 'begin'
  120. * method returns an Auth_OpenID_AuthRequest object.
  121. *
  122. * Next, the application should call the 'redirectURL' method of the
  123. * Auth_OpenID_AuthRequest object. The 'return_to' URL parameter is
  124. * the URL that the OpenID server will send the user back to after
  125. * attempting to verify his or her identity. The 'trust_root' is the
  126. * URL (or URL pattern) that identifies your web site to the user when
  127. * he or she is authorizing it. Send a redirect to the resulting URL
  128. * to the user's browser.
  129. *
  130. * That's the first half of the authentication process. The second
  131. * half of the process is done after the user's ID server sends the
  132. * user's browser a redirect back to your site to complete their
  133. * login.
  134. *
  135. * When that happens, the user will contact your site at the URL given
  136. * as the 'return_to' URL to the Auth_OpenID_AuthRequest::redirectURL
  137. * call made above. The request will have several query parameters
  138. * added to the URL by the identity server as the information
  139. * necessary to finish the request.
  140. *
  141. * Lastly, instantiate an Auth_OpenID_Consumer instance as above and
  142. * call its 'complete' method, passing in all the received query
  143. * arguments.
  144. *
  145. * There are multiple possible return types possible from that
  146. * method. These indicate the whether or not the login was successful,
  147. * and include any additional information appropriate for their type.
  148. *
  149. * PHP versions 4 and 5
  150. *
  151. * LICENSE: See the COPYING file included in this distribution.
  152. *
  153. * @package OpenID
  154. * @author JanRain, Inc. <openid@janrain.com>
  155. * @copyright 2005-2008 Janrain, Inc.
  156. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
  157. */
  158. /**
  159. * Require utility classes and functions for the consumer.
  160. */
  161. require_once "Auth/OpenID.php";
  162. require_once "Auth/OpenID/Message.php";
  163. require_once "Auth/OpenID/HMAC.php";
  164. require_once "Auth/OpenID/Association.php";
  165. require_once "Auth/OpenID/CryptUtil.php";
  166. require_once "Auth/OpenID/DiffieHellman.php";
  167. require_once "Auth/OpenID/KVForm.php";
  168. require_once "Auth/OpenID/Nonce.php";
  169. require_once "Auth/OpenID/Discover.php";
  170. require_once "Auth/OpenID/URINorm.php";
  171. require_once "Auth/Yadis/Manager.php";
  172. require_once "Auth/Yadis/XRI.php";
  173. /**
  174. * This is the status code returned when the complete method returns
  175. * successfully.
  176. */
  177. define('Auth_OpenID_SUCCESS', 'success');
  178. /**
  179. * Status to indicate cancellation of OpenID authentication.
  180. */
  181. define('Auth_OpenID_CANCEL', 'cancel');
  182. /**
  183. * This is the status code completeAuth returns when the value it
  184. * received indicated an invalid login.
  185. */
  186. define('Auth_OpenID_FAILURE', 'failure');
  187. /**
  188. * This is the status code completeAuth returns when the
  189. * {@link Auth_OpenID_Consumer} instance is in immediate mode, and the
  190. * identity server sends back a URL to send the user to to complete his
  191. * or her login.
  192. */
  193. define('Auth_OpenID_SETUP_NEEDED', 'setup needed');
  194. /**
  195. * This is the status code beginAuth returns when the page fetched
  196. * from the entered OpenID URL doesn't contain the necessary link tags
  197. * to function as an identity page.
  198. */
  199. define('Auth_OpenID_PARSE_ERROR', 'parse error');
  200. /**
  201. * An OpenID consumer implementation that performs discovery and does
  202. * session management. See the Consumer.php file documentation for
  203. * more information.
  204. *
  205. * @package OpenID
  206. */
  207. class Auth_OpenID_Consumer {
  208. /**
  209. * @access private
  210. */
  211. var $discoverMethod = 'Auth_OpenID_discover';
  212. /**
  213. * @access private
  214. */
  215. var $session_key_prefix = "_openid_consumer_";
  216. /**
  217. * @access private
  218. */
  219. var $_token_suffix = "last_token";
  220. /**
  221. * Initialize a Consumer instance.
  222. *
  223. * You should create a new instance of the Consumer object with
  224. * every HTTP request that handles OpenID transactions.
  225. *
  226. * @param Auth_OpenID_OpenIDStore $store This must be an object
  227. * that implements the interface in {@link
  228. * Auth_OpenID_OpenIDStore}. Several concrete implementations are
  229. * provided, to cover most common use cases. For stores backed by
  230. * MySQL, PostgreSQL, or SQLite, see the {@link
  231. * Auth_OpenID_SQLStore} class and its sublcasses. For a
  232. * filesystem-backed store, see the {@link Auth_OpenID_FileStore}
  233. * module. As a last resort, if it isn't possible for the server
  234. * to store state at all, an instance of {@link
  235. * Auth_OpenID_DumbStore} can be used.
  236. *
  237. * @param mixed $session An object which implements the interface
  238. * of the {@link Auth_Yadis_PHPSession} class. Particularly, this
  239. * object is expected to have these methods: get($key), set($key),
  240. * $value), and del($key). This defaults to a session object
  241. * which wraps PHP's native session machinery. You should only
  242. * need to pass something here if you have your own sessioning
  243. * implementation.
  244. *
  245. * @param str $consumer_cls The name of the class to instantiate
  246. * when creating the internal consumer object. This is used for
  247. * testing.
  248. */
  249. function Auth_OpenID_Consumer(&$store, $session = null,
  250. $consumer_cls = null)
  251. {
  252. if ($session === null) {
  253. $session = new Auth_Yadis_PHPSession();
  254. }
  255. $this->session =& $session;
  256. if ($consumer_cls !== null) {
  257. $this->consumer = new $consumer_cls($store);
  258. } else {
  259. $this->consumer = new Auth_OpenID_GenericConsumer($store);
  260. }
  261. $this->_token_key = $this->session_key_prefix . $this->_token_suffix;
  262. }
  263. /**
  264. * Used in testing to define the discovery mechanism.
  265. *
  266. * @access private
  267. */
  268. function getDiscoveryObject(&$session, $openid_url,
  269. $session_key_prefix)
  270. {
  271. return new Auth_Yadis_Discovery($session, $openid_url,
  272. $session_key_prefix);
  273. }
  274. /**
  275. * Start the OpenID authentication process. See steps 1-2 in the
  276. * overview at the top of this file.
  277. *
  278. * @param string $user_url Identity URL given by the user. This
  279. * method performs a textual transformation of the URL to try and
  280. * make sure it is normalized. For example, a user_url of
  281. * example.com will be normalized to http://example.com/
  282. * normalizing and resolving any redirects the server might issue.
  283. *
  284. * @param bool $anonymous True if the OpenID request is to be sent
  285. * to the server without any identifier information. Use this
  286. * when you want to transport data but don't want to do OpenID
  287. * authentication with identifiers.
  288. *
  289. * @return Auth_OpenID_AuthRequest $auth_request An object
  290. * containing the discovered information will be returned, with a
  291. * method for building a redirect URL to the server, as described
  292. * in step 3 of the overview. This object may also be used to add
  293. * extension arguments to the request, using its 'addExtensionArg'
  294. * method.
  295. */
  296. function begin($user_url, $anonymous=false)
  297. {
  298. $openid_url = $user_url;
  299. $disco = $this->getDiscoveryObject($this->session,
  300. $openid_url,
  301. $this->session_key_prefix);
  302. // Set the 'stale' attribute of the manager. If discovery
  303. // fails in a fatal way, the stale flag will cause the manager
  304. // to be cleaned up next time discovery is attempted.
  305. $m = $disco->getManager();
  306. $loader = new Auth_Yadis_ManagerLoader();
  307. if ($m) {
  308. if ($m->stale) {
  309. $disco->destroyManager();
  310. } else {
  311. $m->stale = true;
  312. $disco->session->set($disco->session_key,
  313. serialize($loader->toSession($m)));
  314. }
  315. }
  316. $endpoint = $disco->getNextService($this->discoverMethod,
  317. $this->consumer->fetcher);
  318. // Reset the 'stale' attribute of the manager.
  319. $m =& $disco->getManager();
  320. if ($m) {
  321. $m->stale = false;
  322. $disco->session->set($disco->session_key,
  323. serialize($loader->toSession($m)));
  324. }
  325. if ($endpoint === null) {
  326. return null;
  327. } else {
  328. return $this->beginWithoutDiscovery($endpoint,
  329. $anonymous);
  330. }
  331. }
  332. /**
  333. * Start OpenID verification without doing OpenID server
  334. * discovery. This method is used internally by Consumer.begin
  335. * after discovery is performed, and exists to provide an
  336. * interface for library users needing to perform their own
  337. * discovery.
  338. *
  339. * @param Auth_OpenID_ServiceEndpoint $endpoint an OpenID service
  340. * endpoint descriptor.
  341. *
  342. * @param bool anonymous Set to true if you want to perform OpenID
  343. * without identifiers.
  344. *
  345. * @return Auth_OpenID_AuthRequest $auth_request An OpenID
  346. * authentication request object.
  347. */
  348. function &beginWithoutDiscovery($endpoint, $anonymous=false)
  349. {
  350. $loader = new Auth_OpenID_ServiceEndpointLoader();
  351. $auth_req = $this->consumer->begin($endpoint);
  352. $this->session->set($this->_token_key,
  353. $loader->toSession($auth_req->endpoint));
  354. if (!$auth_req->setAnonymous($anonymous)) {
  355. return new Auth_OpenID_FailureResponse(null,
  356. "OpenID 1 requests MUST include the identifier " .
  357. "in the request.");
  358. }
  359. return $auth_req;
  360. }
  361. /**
  362. * Called to interpret the server's response to an OpenID
  363. * request. It is called in step 4 of the flow described in the
  364. * consumer overview.
  365. *
  366. * @param string $current_url The URL used to invoke the application.
  367. * Extract the URL from your application's web
  368. * request framework and specify it here to have it checked
  369. * against the openid.current_url value in the response. If
  370. * the current_url URL check fails, the status of the
  371. * completion will be FAILURE.
  372. *
  373. * @param array $query An array of the query parameters (key =>
  374. * value pairs) for this HTTP request. Defaults to null. If
  375. * null, the GET or POST data are automatically gotten from the
  376. * PHP environment. It is only useful to override $query for
  377. * testing.
  378. *
  379. * @return Auth_OpenID_ConsumerResponse $response A instance of an
  380. * Auth_OpenID_ConsumerResponse subclass. The type of response is
  381. * indicated by the status attribute, which will be one of
  382. * SUCCESS, CANCEL, FAILURE, or SETUP_NEEDED.
  383. */
  384. function complete($current_url, $query=null)
  385. {
  386. if ($current_url && !is_string($current_url)) {
  387. // This is ugly, but we need to complain loudly when
  388. // someone uses the API incorrectly.
  389. trigger_error("current_url must be a string; see NEWS file " .
  390. "for upgrading notes.",
  391. E_USER_ERROR);
  392. }
  393. if ($query === null) {
  394. $query = Auth_OpenID::getQuery();
  395. }
  396. $loader = new Auth_OpenID_ServiceEndpointLoader();
  397. $endpoint_data = $this->session->get($this->_token_key);
  398. $endpoint =
  399. $loader->fromSession($endpoint_data);
  400. $message = Auth_OpenID_Message::fromPostArgs($query);
  401. $response = $this->consumer->complete($message, $endpoint,
  402. $current_url);
  403. $this->session->del($this->_token_key);
  404. if (in_array($response->status, array(Auth_OpenID_SUCCESS,
  405. Auth_OpenID_CANCEL))) {
  406. if ($response->identity_url !== null) {
  407. $disco = $this->getDiscoveryObject($this->session,
  408. $response->identity_url,
  409. $this->session_key_prefix);
  410. $disco->cleanup(true);
  411. }
  412. }
  413. return $response;
  414. }
  415. }
  416. /**
  417. * A class implementing HMAC/DH-SHA1 consumer sessions.
  418. *
  419. * @package OpenID
  420. */
  421. class Auth_OpenID_DiffieHellmanSHA1ConsumerSession {
  422. var $session_type = 'DH-SHA1';
  423. var $hash_func = 'Auth_OpenID_SHA1';
  424. var $secret_size = 20;
  425. var $allowed_assoc_types = array('HMAC-SHA1');
  426. function Auth_OpenID_DiffieHellmanSHA1ConsumerSession($dh = null)
  427. {
  428. if ($dh === null) {
  429. $dh = new Auth_OpenID_DiffieHellman();
  430. }
  431. $this->dh = $dh;
  432. }
  433. function getRequest()
  434. {
  435. $math =& Auth_OpenID_getMathLib();
  436. $cpub = $math->longToBase64($this->dh->public);
  437. $args = array('dh_consumer_public' => $cpub);
  438. if (!$this->dh->usingDefaultValues()) {
  439. $args = array_merge($args, array(
  440. 'dh_modulus' =>
  441. $math->longToBase64($this->dh->mod),
  442. 'dh_gen' =>
  443. $math->longToBase64($this->dh->gen)));
  444. }
  445. return $args;
  446. }
  447. function extractSecret($response)
  448. {
  449. if (!$response->hasKey(Auth_OpenID_OPENID_NS,
  450. 'dh_server_public')) {
  451. return null;
  452. }
  453. if (!$response->hasKey(Auth_OpenID_OPENID_NS,
  454. 'enc_mac_key')) {
  455. return null;
  456. }
  457. $math =& Auth_OpenID_getMathLib();
  458. $spub = $math->base64ToLong($response->getArg(Auth_OpenID_OPENID_NS,
  459. 'dh_server_public'));
  460. $enc_mac_key = base64_decode($response->getArg(Auth_OpenID_OPENID_NS,
  461. 'enc_mac_key'));
  462. return $this->dh->xorSecret($spub, $enc_mac_key, $this->hash_func);
  463. }
  464. }
  465. /**
  466. * A class implementing HMAC/DH-SHA256 consumer sessions.
  467. *
  468. * @package OpenID
  469. */
  470. class Auth_OpenID_DiffieHellmanSHA256ConsumerSession extends
  471. Auth_OpenID_DiffieHellmanSHA1ConsumerSession {
  472. var $session_type = 'DH-SHA256';
  473. var $hash_func = 'Auth_OpenID_SHA256';
  474. var $secret_size = 32;
  475. var $allowed_assoc_types = array('HMAC-SHA256');
  476. }
  477. /**
  478. * A class implementing plaintext consumer sessions.
  479. *
  480. * @package OpenID
  481. */
  482. class Auth_OpenID_PlainTextConsumerSession {
  483. var $session_type = 'no-encryption';
  484. var $allowed_assoc_types = array('HMAC-SHA1', 'HMAC-SHA256');
  485. function getRequest()
  486. {
  487. return array();
  488. }
  489. function extractSecret($response)
  490. {
  491. if (!$response->hasKey(Auth_OpenID_OPENID_NS, 'mac_key')) {
  492. return null;
  493. }
  494. return base64_decode($response->getArg(Auth_OpenID_OPENID_NS,
  495. 'mac_key'));
  496. }
  497. }
  498. /**
  499. * Returns available session types.
  500. */
  501. function Auth_OpenID_getAvailableSessionTypes()
  502. {
  503. $types = array(
  504. 'no-encryption' => 'Auth_OpenID_PlainTextConsumerSession',
  505. 'DH-SHA1' => 'Auth_OpenID_DiffieHellmanSHA1ConsumerSession',
  506. 'DH-SHA256' => 'Auth_OpenID_DiffieHellmanSHA256ConsumerSession');
  507. return $types;
  508. }
  509. /**
  510. * This class is the interface to the OpenID consumer logic.
  511. * Instances of it maintain no per-request state, so they can be
  512. * reused (or even used by multiple threads concurrently) as needed.
  513. *
  514. * @package OpenID
  515. */
  516. class Auth_OpenID_GenericConsumer {
  517. /**
  518. * @access private
  519. */
  520. var $discoverMethod = 'Auth_OpenID_discover';
  521. /**
  522. * This consumer's store object.
  523. */
  524. var $store;
  525. /**
  526. * @access private
  527. */
  528. var $_use_assocs;
  529. /**
  530. * @access private
  531. */
  532. var $openid1_nonce_query_arg_name = 'janrain_nonce';
  533. /**
  534. * Another query parameter that gets added to the return_to for
  535. * OpenID 1; if the user's session state is lost, use this claimed
  536. * identifier to do discovery when verifying the response.
  537. */
  538. var $openid1_return_to_identifier_name = 'openid1_claimed_id';
  539. /**
  540. * This method initializes a new {@link Auth_OpenID_Consumer}
  541. * instance to access the library.
  542. *
  543. * @param Auth_OpenID_OpenIDStore $store This must be an object
  544. * that implements the interface in {@link Auth_OpenID_OpenIDStore}.
  545. * Several concrete implementations are provided, to cover most common use
  546. * cases. For stores backed by MySQL, PostgreSQL, or SQLite, see
  547. * the {@link Auth_OpenID_SQLStore} class and its sublcasses. For a
  548. * filesystem-backed store, see the {@link Auth_OpenID_FileStore} module.
  549. * As a last resort, if it isn't possible for the server to store
  550. * state at all, an instance of {@link Auth_OpenID_DumbStore} can be used.
  551. *
  552. * @param bool $immediate This is an optional boolean value. It
  553. * controls whether the library uses immediate mode, as explained
  554. * in the module description. The default value is False, which
  555. * disables immediate mode.
  556. */
  557. function Auth_OpenID_GenericConsumer(&$store)
  558. {
  559. $this->store =& $store;
  560. $this->negotiator =& Auth_OpenID_getDefaultNegotiator();
  561. $this->_use_assocs = ($this->store ? true : false);
  562. $this->fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
  563. $this->session_types = Auth_OpenID_getAvailableSessionTypes();
  564. }
  565. /**
  566. * Called to begin OpenID authentication using the specified
  567. * {@link Auth_OpenID_ServiceEndpoint}.
  568. *
  569. * @access private
  570. */
  571. function begin($service_endpoint)
  572. {
  573. $assoc = $this->_getAssociation($service_endpoint);
  574. $r = new Auth_OpenID_AuthRequest($service_endpoint, $assoc);
  575. $r->return_to_args[$this->openid1_nonce_query_arg_name] =
  576. Auth_OpenID_mkNonce();
  577. if ($r->message->isOpenID1()) {
  578. $r->return_to_args[$this->openid1_return_to_identifier_name] =
  579. $r->endpoint->claimed_id;
  580. }
  581. return $r;
  582. }
  583. /**
  584. * Given an {@link Auth_OpenID_Message}, {@link
  585. * Auth_OpenID_ServiceEndpoint} and optional return_to URL,
  586. * complete OpenID authentication.
  587. *
  588. * @access private
  589. */
  590. function complete($message, $endpoint, $return_to)
  591. {
  592. $mode = $message->getArg(Auth_OpenID_OPENID_NS, 'mode',
  593. '<no mode set>');
  594. $mode_methods = array(
  595. 'cancel' => '_complete_cancel',
  596. 'error' => '_complete_error',
  597. 'setup_needed' => '_complete_setup_needed',
  598. 'id_res' => '_complete_id_res',
  599. );
  600. $method = Auth_OpenID::arrayGet($mode_methods, $mode,
  601. '_completeInvalid');
  602. return call_user_func_array(array(&$this, $method),
  603. array($message, &$endpoint, $return_to));
  604. }
  605. /**
  606. * @access private
  607. */
  608. function _completeInvalid($message, &$endpoint, $unused)
  609. {
  610. $mode = $message->getArg(Auth_OpenID_OPENID_NS, 'mode',
  611. '<No mode set>');
  612. return new Auth_OpenID_FailureResponse($endpoint,
  613. sprintf("Invalid openid.mode '%s'", $mode));
  614. }
  615. /**
  616. * @access private
  617. */
  618. function _complete_cancel($message, &$endpoint, $unused)
  619. {
  620. return new Auth_OpenID_CancelResponse($endpoint);
  621. }
  622. /**
  623. * @access private
  624. */
  625. function _complete_error($message, &$endpoint, $unused)
  626. {
  627. $error = $message->getArg(Auth_OpenID_OPENID_NS, 'error');
  628. $contact = $message->getArg(Auth_OpenID_OPENID_NS, 'contact');
  629. $reference = $message->getArg(Auth_OpenID_OPENID_NS, 'reference');
  630. return new Auth_OpenID_FailureResponse($endpoint, $error,
  631. $contact, $reference);
  632. }
  633. /**
  634. * @access private
  635. */
  636. function _complete_setup_needed($message, &$endpoint, $unused)
  637. {
  638. if (!$message->isOpenID2()) {
  639. return $this->_completeInvalid($message, $endpoint);
  640. }
  641. $user_setup_url = $message->getArg(Auth_OpenID_OPENID2_NS,
  642. 'user_setup_url');
  643. return new Auth_OpenID_SetupNeededResponse($endpoint, $user_setup_url);
  644. }
  645. /**
  646. * @access private
  647. */
  648. function _complete_id_res($message, &$endpoint, $return_to)
  649. {
  650. $user_setup_url = $message->getArg(Auth_OpenID_OPENID1_NS,
  651. 'user_setup_url');
  652. if ($this->_checkSetupNeeded($message)) {
  653. return new Auth_OpenID_SetupNeededResponse(
  654. $endpoint, $user_setup_url);
  655. } else {
  656. return $this->_doIdRes($message, $endpoint, $return_to);
  657. }
  658. }
  659. /**
  660. * @access private
  661. */
  662. function _checkSetupNeeded($message)
  663. {
  664. // In OpenID 1, we check to see if this is a cancel from
  665. // immediate mode by the presence of the user_setup_url
  666. // parameter.
  667. if ($message->isOpenID1()) {
  668. $user_setup_url = $message->getArg(Auth_OpenID_OPENID1_NS,
  669. 'user_setup_url');
  670. if ($user_setup_url !== null) {
  671. return true;
  672. }
  673. }
  674. return false;
  675. }
  676. /**
  677. * @access private
  678. */
  679. function _doIdRes($message, $endpoint, $return_to)
  680. {
  681. // Checks for presence of appropriate fields (and checks
  682. // signed list fields)
  683. $result = $this->_idResCheckForFields($message);
  684. if (Auth_OpenID::isFailure($result)) {
  685. return $result;
  686. }
  687. if (!$this->_checkReturnTo($message, $return_to)) {
  688. return new Auth_OpenID_FailureResponse(null,
  689. sprintf("return_to does not match return URL. Expected %s, got %s",
  690. $return_to,
  691. $message->getArg(Auth_OpenID_OPENID_NS, 'return_to')));
  692. }
  693. // Verify discovery information:
  694. $result = $this->_verifyDiscoveryResults($message, $endpoint);
  695. if (Auth_OpenID::isFailure($result)) {
  696. return $result;
  697. }
  698. $endpoint = $result;
  699. $result = $this->_idResCheckSignature($message,
  700. $endpoint->server_url);
  701. if (Auth_OpenID::isFailure($result)) {
  702. return $result;
  703. }
  704. $result = $this->_idResCheckNonce($message, $endpoint);
  705. if (Auth_OpenID::isFailure($result)) {
  706. return $result;
  707. }
  708. $signed_list_str = $message->getArg(Auth_OpenID_OPENID_NS, 'signed',
  709. Auth_OpenID_NO_DEFAULT);
  710. if (Auth_OpenID::isFailure($signed_list_str)) {
  711. return $signed_list_str;
  712. }
  713. $signed_list = explode(',', $signed_list_str);
  714. $signed_fields = Auth_OpenID::addPrefix($signed_list, "openid.");
  715. return new Auth_OpenID_SuccessResponse($endpoint, $message,
  716. $signed_fields);
  717. }
  718. /**
  719. * @access private
  720. */
  721. function _checkReturnTo($message, $return_to)
  722. {
  723. // Check an OpenID message and its openid.return_to value
  724. // against a return_to URL from an application. Return True
  725. // on success, False on failure.
  726. // Check the openid.return_to args against args in the
  727. // original message.
  728. $result = Auth_OpenID_GenericConsumer::_verifyReturnToArgs(
  729. $message->toPostArgs());
  730. if (Auth_OpenID::isFailure($result)) {
  731. return false;
  732. }
  733. // Check the return_to base URL against the one in the
  734. // message.
  735. $msg_return_to = $message->getArg(Auth_OpenID_OPENID_NS,
  736. 'return_to');
  737. if (Auth_OpenID::isFailure($return_to)) {
  738. // XXX log me
  739. return false;
  740. }
  741. $return_to_parts = parse_url(Auth_OpenID_urinorm($return_to));
  742. $msg_return_to_parts = parse_url(Auth_OpenID_urinorm($msg_return_to));
  743. // If port is absent from both, add it so it's equal in the
  744. // check below.
  745. if ((!array_key_exists('port', $return_to_parts)) &&
  746. (!array_key_exists('port', $msg_return_to_parts))) {
  747. $return_to_parts['port'] = null;
  748. $msg_return_to_parts['port'] = null;
  749. }
  750. // If path is absent from both, add it so it's equal in the
  751. // check below.
  752. if ((!array_key_exists('path', $return_to_parts)) &&
  753. (!array_key_exists('path', $msg_return_to_parts))) {
  754. $return_to_parts['path'] = null;
  755. $msg_return_to_parts['path'] = null;
  756. }
  757. // The URL scheme, authority, and path MUST be the same
  758. // between the two URLs.
  759. foreach (array('scheme', 'host', 'port', 'path') as $component) {
  760. // If the url component is absent in either URL, fail.
  761. // There should always be a scheme, host, port, and path.
  762. if (!array_key_exists($component, $return_to_parts)) {
  763. return false;
  764. }
  765. if (!array_key_exists($component, $msg_return_to_parts)) {
  766. return false;
  767. }
  768. if (Auth_OpenID::arrayGet($return_to_parts, $component) !==
  769. Auth_OpenID::arrayGet($msg_return_to_parts, $component)) {
  770. return false;
  771. }
  772. }
  773. return true;
  774. }
  775. /**
  776. * @access private
  777. */
  778. function _verifyReturnToArgs($query)
  779. {
  780. // Verify that the arguments in the return_to URL are present in this
  781. // response.
  782. $message = Auth_OpenID_Message::fromPostArgs($query);
  783. $return_to = $message->getArg(Auth_OpenID_OPENID_NS, 'return_to');
  784. if (Auth_OpenID::isFailure($return_to)) {
  785. return $return_to;
  786. }
  787. // XXX: this should be checked by _idResCheckForFields
  788. if (!$return_to) {
  789. return new Auth_OpenID_FailureResponse(null,
  790. "Response has no return_to");
  791. }
  792. $parsed_url = parse_url($return_to);
  793. $q = array();
  794. if (array_key_exists('query', $parsed_url)) {
  795. $rt_query = $parsed_url['query'];
  796. $q = Auth_OpenID::parse_str($rt_query);
  797. }
  798. foreach ($q as $rt_key => $rt_value) {
  799. if (!array_key_exists($rt_key, $query)) {
  800. return new Auth_OpenID_FailureResponse(null,
  801. sprintf("return_to parameter %s absent from query", $rt_key));
  802. } else {
  803. $value = $query[$rt_key];
  804. if ($rt_value != $value) {
  805. return new Auth_OpenID_FailureResponse(null,
  806. sprintf("parameter %s value %s does not match " .
  807. "return_to value %s", $rt_key,
  808. $value, $rt_value));
  809. }
  810. }
  811. }
  812. // Make sure all non-OpenID arguments in the response are also
  813. // in the signed return_to.
  814. $bare_args = $message->getArgs(Auth_OpenID_BARE_NS);
  815. foreach ($bare_args as $key => $value) {
  816. if (Auth_OpenID::arrayGet($q, $key) != $value) {
  817. return new Auth_OpenID_FailureResponse(null,
  818. sprintf("Parameter %s = %s not in return_to URL",
  819. $key, $value));
  820. }
  821. }
  822. return true;
  823. }
  824. /**
  825. * @access private
  826. */
  827. function _idResCheckSignature($message, $server_url)
  828. {
  829. $assoc_handle = $message->getArg(Auth_OpenID_OPENID_NS,
  830. 'assoc_handle');
  831. if (Auth_OpenID::isFailure($assoc_handle)) {
  832. return $assoc_handle;
  833. }
  834. $assoc = $this->store->getAssociation($server_url, $assoc_handle);
  835. if ($assoc) {
  836. if ($assoc->getExpiresIn() <= 0) {
  837. // XXX: It might be a good idea sometimes to re-start
  838. // the authentication with a new association. Doing it
  839. // automatically opens the possibility for
  840. // denial-of-service by a server that just returns
  841. // expired associations (or really short-lived
  842. // associations)
  843. return new Auth_OpenID_FailureResponse(null,
  844. 'Association with ' . $server_url . ' expired');
  845. }
  846. if (!$assoc->checkMessageSignature($message)) {
  847. return new Auth_OpenID_FailureResponse(null,
  848. "Bad signature");
  849. }
  850. } else {
  851. // It's not an association we know about. Stateless mode
  852. // is our only possible path for recovery. XXX - async
  853. // framework will not want to block on this call to
  854. // _checkAuth.
  855. if (!$this->_checkAuth($message, $server_url)) {
  856. return new Auth_OpenID_FailureResponse(null,
  857. "Server denied check_authentication");
  858. }
  859. }
  860. return null;
  861. }
  862. /**
  863. * @access private
  864. */
  865. function _verifyDiscoveryResults($message, $endpoint=null)
  866. {
  867. if ($message->getOpenIDNamespace() == Auth_OpenID_OPENID2_NS) {
  868. return $this->_verifyDiscoveryResultsOpenID2($message,
  869. $endpoint);
  870. } else {
  871. return $this->_verifyDiscoveryResultsOpenID1($message,
  872. $endpoint);
  873. }
  874. }
  875. /**
  876. * @access private
  877. */
  878. function _verifyDiscoveryResultsOpenID1($message, $endpoint)
  879. {
  880. $claimed_id = $message->getArg(Auth_OpenID_BARE_NS,
  881. $this->openid1_return_to_identifier_name);
  882. if (($endpoint === null) && ($claimed_id === null)) {
  883. return new Auth_OpenID_FailureResponse($endpoint,
  884. 'When using OpenID 1, the claimed ID must be supplied, ' .
  885. 'either by passing it through as a return_to parameter ' .
  886. 'or by using a session, and supplied to the GenericConsumer ' .
  887. 'as the argument to complete()');
  888. } else if (($endpoint !== null) && ($claimed_id === null)) {
  889. $claimed_id = $endpoint->claimed_id;
  890. }
  891. $to_match = new Auth_OpenID_ServiceEndpoint();
  892. $to_match->type_uris = array(Auth_OpenID_TYPE_1_1);
  893. $to_match->local_id = $message->getArg(Auth_OpenID_OPENID1_NS,
  894. 'identity');
  895. // Restore delegate information from the initiation phase
  896. $to_match->claimed_id = $claimed_id;
  897. if ($to_match->local_id === null) {
  898. return new Auth_OpenID_FailureResponse($endpoint,
  899. "Missing required field openid.identity");
  900. }
  901. $to_match_1_0 = $to_match->copy();
  902. $to_match_1_0->type_uris = array(Auth_OpenID_TYPE_1_0);
  903. if ($endpoint !== null) {
  904. $result = $this->_verifyDiscoverySingle($endpoint, $to_match);
  905. if (is_a($result, 'Auth_OpenID_TypeURIMismatch')) {
  906. $result = $this->_verifyDiscoverySingle($endpoint,
  907. $to_match_1_0);
  908. }
  909. if (Auth_OpenID::isFailure($result)) {
  910. // oidutil.log("Error attempting to use stored
  911. // discovery information: " + str(e))
  912. // oidutil.log("Attempting discovery to
  913. // verify endpoint")
  914. } else {
  915. return $endpoint;
  916. }
  917. }
  918. // Endpoint is either bad (failed verification) or None
  919. return $this->_discoverAndVerify($to_match->claimed_id,
  920. array($to_match, $to_match_1_0));
  921. }
  922. /**
  923. * @access private
  924. */
  925. function _verifyDiscoverySingle($endpoint, $to_match)
  926. {
  927. // Every type URI that's in the to_match endpoint has to be
  928. // present in the discovered endpoint.
  929. foreach ($to_match->type_uris as $type_uri) {
  930. if (!$endpoint->usesExtension($type_uri)) {
  931. return new Auth_OpenID_TypeURIMismatch($endpoint,
  932. "Required type ".$type_uri." not present");
  933. }
  934. }
  935. // Fragments do not influence discovery, so we can't compare a
  936. // claimed identifier with a fragment to discovered
  937. // information.
  938. list($defragged_claimed_id, $_) =
  939. Auth_OpenID::urldefrag($to_match->claimed_id);
  940. if ($defragged_claimed_id != $endpoint->claimed_id) {
  941. return new Auth_OpenID_FailureResponse($endpoint,
  942. sprintf('Claimed ID does not match (different subjects!), ' .
  943. 'Expected %s, got %s', $defragged_claimed_id,
  944. $endpoint->claimed_id));
  945. }
  946. if ($to_match->getLocalID() != $endpoint->getLocalID()) {
  947. return new Auth_OpenID_FailureResponse($endpoint,
  948. sprintf('local_id mismatch. Expected %s, got %s',
  949. $to_match->getLocalID(), $endpoint->getLocalID()));
  950. }
  951. // If the server URL is None, this must be an OpenID 1
  952. // response, because op_endpoint is a required parameter in
  953. // OpenID 2. In that case, we don't actually care what the
  954. // discovered server_url is, because signature checking or
  955. // check_auth should take care of that check for us.
  956. if ($to_match->server_url === null) {
  957. if ($to_match->preferredNamespace() != Auth_OpenID_OPENID1_NS) {
  958. return new Auth_OpenID_FailureResponse($endpoint,
  959. "Preferred namespace mismatch (bug)");
  960. }
  961. } else if ($to_match->server_url != $endpoint->server_url) {
  962. return new Auth_OpenID_FailureResponse($endpoint,
  963. sprintf('OP Endpoint mismatch. Expected %s, got %s',
  964. $to_match->server_url, $endpoint->server_url));
  965. }
  966. return null;
  967. }
  968. /**
  969. * @access private
  970. */
  971. function _verifyDiscoveryResultsOpenID2($message, $endpoint)
  972. {
  973. $to_match = new Auth_OpenID_ServiceEndpoint();
  974. $to_match->type_uris = array(Auth_OpenID_TYPE_2_0);
  975. $to_match->claimed_id = $message->getArg(Auth_OpenID_OPENID2_NS,
  976. 'claimed_id');
  977. $to_match->local_id = $message->getArg(Auth_OpenID_OPENID2_NS,
  978. 'identity');
  979. $to_match->server_url = $message->getArg(Auth_OpenID_OPENID2_NS,
  980. 'op_endpoint');
  981. if ($to_match->server_url === null) {
  982. return new Auth_OpenID_FailureResponse($endpoint,
  983. "OP Endpoint URL missing");
  984. }
  985. // claimed_id and identifier must both be present or both be
  986. // absent
  987. if (($to_match->claimed_id === null) &&
  988. ($to_match->local_id !== null)) {
  989. return new Auth_OpenID_FailureResponse($endpoint,
  990. 'openid.identity is present without openid.claimed_id');
  991. }
  992. if (($to_match->claimed_id !== null) &&
  993. ($to_match->local_id === null)) {
  994. return new Auth_OpenID_FailureResponse($endpoint,
  995. 'openid.claimed_id is present without openid.identity');
  996. }
  997. if ($to_match->claimed_id === null) {
  998. // This is a response without identifiers, so there's
  999. // really no checking that we can do, so return an
  1000. // endpoint that's for the specified `openid.op_endpoint'
  1001. return Auth_OpenID_ServiceEndpoint::fromOPEndpointURL(
  1002. $to_match->server_url);
  1003. }
  1004. if (!$endpoint) {
  1005. // The claimed ID doesn't match, so we have to do
  1006. // discovery again. This covers not using sessions, OP
  1007. // identifier endpoints and responses that didn't match
  1008. // the original request.
  1009. // oidutil.log('No pre-discovered information supplied.')
  1010. return $this->_discoverAndVerify($to_match->claimed_id,
  1011. array($to_match));
  1012. } else {
  1013. // The claimed ID matches, so we use the endpoint that we
  1014. // discovered in initiation. This should be the most
  1015. // common case.
  1016. $result = $this->_verifyDiscoverySingle($endpoint, $to_match);
  1017. if (Auth_OpenID::isFailure($result)) {
  1018. $endpoint = $this->_discoverAndVerify($to_match->claimed_id,
  1019. array($to_match));
  1020. if (Auth_OpenID::isFailure($endpoint)) {
  1021. return $endpoint;
  1022. }
  1023. }
  1024. }
  1025. // The endpoint we return should have the claimed ID from the
  1026. // message we just verified, fragment and all.
  1027. if ($endpoint->claimed_id != $to_match->claimed_id) {
  1028. $endpoint->claimed_id = $to_match->claimed_id;
  1029. }
  1030. return $endpoint;
  1031. }
  1032. /**
  1033. * @access private
  1034. */
  1035. function _discoverAndVerify($claimed_id, $to_match_endpoints)
  1036. {
  1037. // oidutil.log('Performing discovery on %s' % (claimed_id,))
  1038. list($unused, $services) = call_user_func($this->discoverMethod,
  1039. $claimed_id,
  1040. &$this->fetcher);
  1041. if (!$services) {
  1042. return new Auth_OpenID_FailureResponse(null,
  1043. sprintf("No OpenID information found at %s",
  1044. $claimed_id));
  1045. }
  1046. return $this->_verifyDiscoveryServices($claimed_id, $services,
  1047. $to_match_endpoints);
  1048. }
  1049. /**
  1050. * @access private
  1051. */
  1052. function _verifyDiscoveryServices($claimed_id,
  1053. &$services, &$to_match_endpoints)
  1054. {
  1055. // Search the services resulting from discovery to find one
  1056. // that matches the information from the assertion
  1057. foreach ($services as $endpoint) {
  1058. foreach ($to_match_endpoints as $to_match_endpoint) {
  1059. $result = $this->_verifyDiscoverySingle($endpoint,
  1060. $to_match_endpoint);
  1061. if (!Auth_OpenID::isFailure($result)) {
  1062. // It matches, so discover verification has
  1063. // succeeded. Return this endpoint.
  1064. return $endpoint;
  1065. }
  1066. }
  1067. }
  1068. return new Auth_OpenID_FailureResponse(null,
  1069. sprintf('No matching endpoint found after discovering %s',
  1070. $claimed_id));
  1071. }
  1072. /**
  1073. * Extract the nonce from an OpenID 1 response. Return the nonce
  1074. * from the BARE_NS since we independently check the return_to
  1075. * arguments are the same as those in the response message.
  1076. *
  1077. * See the openid1_nonce_query_arg_name class variable
  1078. *
  1079. * @returns $nonce The nonce as a string or null
  1080. *
  1081. * @access private
  1082. */
  1083. function _idResGetNonceOpenID1($message, $endpoint)
  1084. {
  1085. return $message->getArg(Auth_OpenID_BARE_NS,
  1086. $this->openid1_nonce_query_arg_name);
  1087. }
  1088. /**
  1089. * @access private
  1090. */
  1091. function _idResCheckNonce($message, $endpoint)
  1092. {
  1093. if ($message->isOpenID1()) {
  1094. // This indicates that the nonce was generated by the consumer
  1095. $nonce = $this->_idResGetNonceOpenID1($message, $endpoint);
  1096. $server_url = '';
  1097. } else {
  1098. $nonce = $message->getArg(Auth_OpenID_OPENID2_NS,
  1099. 'response_nonce');
  1100. $server_url = $endpoint->server_url;
  1101. }
  1102. if ($nonce === null) {
  1103. return new Auth_OpenID_FailureResponse($endpoint,
  1104. "Nonce missing from response");
  1105. }
  1106. $parts = Auth_OpenID_splitNonce($nonce);
  1107. if ($parts === null) {
  1108. return new Auth_OpenID_FailureResponse($endpoint,
  1109. "Malformed nonce in response");
  1110. }
  1111. list($timestamp, $salt) = $parts;
  1112. if (!$this->store->useNonce($server_url, $timestamp, $salt)) {
  1113. return new Auth_OpenID_FailureResponse($endpoint,
  1114. "Nonce already used or out of range");
  1115. }
  1116. return null;
  1117. }
  1118. /**
  1119. * @access private
  1120. */
  1121. function _idResCheckForFields($message)
  1122. {
  1123. $basic_fields = array('return_to', 'assoc_handle', 'sig', 'signed');
  1124. $basic_sig_fields = array('return_to', 'identity');
  1125. $require_fields = array(
  1126. Auth_OpenID_OPENID2_NS => array_merge($basic_fields,
  1127. array('op_endpoint')),
  1128. Auth_OpenID_OPENID1_NS => array_merge($basic_fields,
  1129. array('identity'))
  1130. );
  1131. $require_sigs = array(
  1132. Auth_OpenID_OPENID2_NS => array_merge($basic_sig_fields,
  1133. array('response_nonce',
  1134. 'claimed_id',
  1135. 'assoc_handle',
  1136. 'op_endpoint')),
  1137. Auth_OpenID_OPENID1_NS => array_merge($basic_sig_fields,
  1138. array('nonce'))
  1139. );
  1140. foreach ($require_fields[$message->getOpenIDNamespace()] as $field) {
  1141. if (!$message->hasKey(Auth_OpenID_OPENID_NS, $field)) {
  1142. return new Auth_OpenID_FailureResponse(null,
  1143. "Missing required field '".$field."'");
  1144. }
  1145. }
  1146. $signed_list_str = $message->getArg(Auth_OpenID_OPENID_NS,
  1147. 'signed',
  1148. Auth_OpenID_NO_DEFAULT);
  1149. if (Auth_OpenID::isFailure($signed_list_str)) {
  1150. return $signed_list_str;
  1151. }
  1152. $signed_list = explode(',', $signed_list_str);
  1153. foreach ($require_sigs[$message->getOpenIDNamespace()] as $field) {
  1154. // Field is present and not in signed list
  1155. if ($message->hasKey(Auth_OpenID_OPENID_NS, $field) &&
  1156. (!in_array($field, $signed_list))) {
  1157. return new Auth_OpenID_FailureResponse(null,
  1158. "'".$field."' not signed");
  1159. }
  1160. }
  1161. return null;
  1162. }
  1163. /**
  1164. * @access private
  1165. */
  1166. function _checkAuth($message, $server_url)
  1167. {
  1168. $request = $this->_createCheckAuthRequest($message);
  1169. if ($request === null) {
  1170. return false;
  1171. }
  1172. $resp_message = $this->_makeKVPost($request, $server_url);
  1173. if (($resp_message === null) ||
  1174. (is_a($resp_message, 'Auth_OpenID_ServerErrorContainer'))) {
  1175. return false;
  1176. }
  1177. return $this->_processCheckAuthResponse($resp_message, $server_url);
  1178. }
  1179. /**
  1180. * @access private
  1181. */
  1182. function _createCheckAuthRequest($message)
  1183. {
  1184. $signed = $message->getArg(Auth_OpenID_OPENID_NS, 'signed');
  1185. if ($signed) {
  1186. foreach (explode(',', $signed) as $k) {
  1187. $value = $message->getAliasedArg($k);
  1188. if ($value === null) {
  1189. return null;
  1190. }
  1191. }
  1192. }
  1193. $ca_message = $message->copy();
  1194. $ca_message->setArg(Auth_OpenID_OPENID_NS, 'mode',
  1195. 'check_authentication');
  1196. return $ca_message;
  1197. }
  1198. /**
  1199. * @access private
  1200. */
  1201. function _processCheckAuthResponse($response,

Large files files are truncated, but you can click here to view the full file