Consumer.php 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  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 = (is_null($this->store) ? false : true);
  562. if (get_class($this->store) == "Auth_OpenID_DumbStore") {
  563. $this->_use_assocs = false;
  564. }
  565. $this->fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
  566. $this->session_types = Auth_OpenID_getAvailableSessionTypes();
  567. }
  568. /**
  569. * Called to begin OpenID authentication using the specified
  570. * {@link Auth_OpenID_ServiceEndpoint}.
  571. *
  572. * @access private
  573. */
  574. function begin($service_endpoint)
  575. {
  576. $assoc = $this->_getAssociation($service_endpoint);
  577. $r = new Auth_OpenID_AuthRequest($service_endpoint, $assoc);
  578. $r->return_to_args[$this->openid1_nonce_query_arg_name] =
  579. Auth_OpenID_mkNonce();
  580. if ($r->message->isOpenID1()) {
  581. $r->return_to_args[$this->openid1_return_to_identifier_name] =
  582. $r->endpoint->claimed_id;
  583. }
  584. return $r;
  585. }
  586. /**
  587. * Given an {@link Auth_OpenID_Message}, {@link
  588. * Auth_OpenID_ServiceEndpoint} and optional return_to URL,
  589. * complete OpenID authentication.
  590. *
  591. * @access private
  592. */
  593. function complete($message, $endpoint, $return_to)
  594. {
  595. $mode = $message->getArg(Auth_OpenID_OPENID_NS, 'mode',
  596. '<no mode set>');
  597. $mode_methods = array(
  598. 'cancel' => '_complete_cancel',
  599. 'error' => '_complete_error',
  600. 'setup_needed' => '_complete_setup_needed',
  601. 'id_res' => '_complete_id_res',
  602. );
  603. $method = Auth_OpenID::arrayGet($mode_methods, $mode,
  604. '_completeInvalid');
  605. return call_user_func_array(array($this, $method),
  606. array($message, $endpoint, $return_to));
  607. }
  608. /**
  609. * @access private
  610. */
  611. function _completeInvalid($message, $endpoint, $unused)
  612. {
  613. $mode = $message->getArg(Auth_OpenID_OPENID_NS, 'mode',
  614. '<No mode set>');
  615. return new Auth_OpenID_FailureResponse($endpoint,
  616. sprintf("Invalid openid.mode '%s'", $mode));
  617. }
  618. /**
  619. * @access private
  620. */
  621. function _complete_cancel($message, $endpoint, $unused)
  622. {
  623. return new Auth_OpenID_CancelResponse($endpoint);
  624. }
  625. /**
  626. * @access private
  627. */
  628. function _complete_error($message, $endpoint, $unused)
  629. {
  630. $error = $message->getArg(Auth_OpenID_OPENID_NS, 'error');
  631. $contact = $message->getArg(Auth_OpenID_OPENID_NS, 'contact');
  632. $reference = $message->getArg(Auth_OpenID_OPENID_NS, 'reference');
  633. return new Auth_OpenID_FailureResponse($endpoint, $error,
  634. $contact, $reference);
  635. }
  636. /**
  637. * @access private
  638. */
  639. function _complete_setup_needed($message, $endpoint, $unused)
  640. {
  641. if (!$message->isOpenID2()) {
  642. return $this->_completeInvalid($message, $endpoint);
  643. }
  644. $user_setup_url = $message->getArg(Auth_OpenID_OPENID2_NS,
  645. 'user_setup_url');
  646. return new Auth_OpenID_SetupNeededResponse($endpoint, $user_setup_url);
  647. }
  648. /**
  649. * @access private
  650. */
  651. function _complete_id_res($message, $endpoint, $return_to)
  652. {
  653. $user_setup_url = $message->getArg(Auth_OpenID_OPENID1_NS,
  654. 'user_setup_url');
  655. if ($this->_checkSetupNeeded($message)) {
  656. return new Auth_OpenID_SetupNeededResponse(
  657. $endpoint, $user_setup_url);
  658. } else {
  659. return $this->_doIdRes($message, $endpoint, $return_to);
  660. }
  661. }
  662. /**
  663. * @access private
  664. */
  665. function _checkSetupNeeded($message)
  666. {
  667. // In OpenID 1, we check to see if this is a cancel from
  668. // immediate mode by the presence of the user_setup_url
  669. // parameter.
  670. if ($message->isOpenID1()) {
  671. $user_setup_url = $message->getArg(Auth_OpenID_OPENID1_NS,
  672. 'user_setup_url');
  673. if ($user_setup_url !== null) {
  674. return true;
  675. }
  676. }
  677. return false;
  678. }
  679. /**
  680. * @access private
  681. */
  682. function _doIdRes($message, $endpoint, $return_to)
  683. {
  684. // Checks for presence of appropriate fields (and checks
  685. // signed list fields)
  686. $result = $this->_idResCheckForFields($message);
  687. if (Auth_OpenID::isFailure($result)) {
  688. return $result;
  689. }
  690. if (!$this->_checkReturnTo($message, $return_to)) {
  691. return new Auth_OpenID_FailureResponse(null,
  692. sprintf("return_to does not match return URL. Expected %s, got %s",
  693. $return_to,
  694. $message->getArg(Auth_OpenID_OPENID_NS, 'return_to')));
  695. }
  696. // Verify discovery information:
  697. $result = $this->_verifyDiscoveryResults($message, $endpoint);
  698. if (Auth_OpenID::isFailure($result)) {
  699. return $result;
  700. }
  701. $endpoint = $result;
  702. $result = $this->_idResCheckSignature($message,
  703. $endpoint->server_url);
  704. if (Auth_OpenID::isFailure($result)) {
  705. return $result;
  706. }
  707. $result = $this->_idResCheckNonce($message, $endpoint);
  708. if (Auth_OpenID::isFailure($result)) {
  709. return $result;
  710. }
  711. $signed_list_str = $message->getArg(Auth_OpenID_OPENID_NS, 'signed',
  712. Auth_OpenID_NO_DEFAULT);
  713. if (Auth_OpenID::isFailure($signed_list_str)) {
  714. return $signed_list_str;
  715. }
  716. $signed_list = explode(',', $signed_list_str);
  717. $signed_fields = Auth_OpenID::addPrefix($signed_list, "openid.");
  718. return new Auth_OpenID_SuccessResponse($endpoint, $message,
  719. $signed_fields);
  720. }
  721. /**
  722. * @access private
  723. */
  724. function _checkReturnTo($message, $return_to)
  725. {
  726. // Check an OpenID message and its openid.return_to value
  727. // against a return_to URL from an application. Return True
  728. // on success, False on failure.
  729. // Check the openid.return_to args against args in the
  730. // original message.
  731. $result = Auth_OpenID_GenericConsumer::_verifyReturnToArgs(
  732. $message->toPostArgs());
  733. if (Auth_OpenID::isFailure($result)) {
  734. return false;
  735. }
  736. // Check the return_to base URL against the one in the
  737. // message.
  738. $msg_return_to = $message->getArg(Auth_OpenID_OPENID_NS,
  739. 'return_to');
  740. if (Auth_OpenID::isFailure($return_to)) {
  741. // XXX log me
  742. return false;
  743. }
  744. $return_to_parts = parse_url(Auth_OpenID_urinorm($return_to));
  745. $msg_return_to_parts = parse_url(Auth_OpenID_urinorm($msg_return_to));
  746. // If port is absent from both, add it so it's equal in the
  747. // check below.
  748. if ((!array_key_exists('port', $return_to_parts)) &&
  749. (!array_key_exists('port', $msg_return_to_parts))) {
  750. $return_to_parts['port'] = null;
  751. $msg_return_to_parts['port'] = null;
  752. }
  753. // If path is absent from both, add it so it's equal in the
  754. // check below.
  755. if ((!array_key_exists('path', $return_to_parts)) &&
  756. (!array_key_exists('path', $msg_return_to_parts))) {
  757. $return_to_parts['path'] = null;
  758. $msg_return_to_parts['path'] = null;
  759. }
  760. // The URL scheme, authority, and path MUST be the same
  761. // between the two URLs.
  762. foreach (array('scheme', 'host', 'port', 'path') as $component) {
  763. // If the url component is absent in either URL, fail.
  764. // There should always be a scheme, host, port, and path.
  765. if (!array_key_exists($component, $return_to_parts)) {
  766. return false;
  767. }
  768. if (!array_key_exists($component, $msg_return_to_parts)) {
  769. return false;
  770. }
  771. if (Auth_OpenID::arrayGet($return_to_parts, $component) !==
  772. Auth_OpenID::arrayGet($msg_return_to_parts, $component)) {
  773. return false;
  774. }
  775. }
  776. return true;
  777. }
  778. /**
  779. * @access private
  780. */
  781. function _verifyReturnToArgs($query)
  782. {
  783. // Verify that the arguments in the return_to URL are present in this
  784. // response.
  785. $message = Auth_OpenID_Message::fromPostArgs($query);
  786. $return_to = $message->getArg(Auth_OpenID_OPENID_NS, 'return_to');
  787. if (Auth_OpenID::isFailure($return_to)) {
  788. return $return_to;
  789. }
  790. // XXX: this should be checked by _idResCheckForFields
  791. if (!$return_to) {
  792. return new Auth_OpenID_FailureResponse(null,
  793. "Response has no return_to");
  794. }
  795. $parsed_url = parse_url($return_to);
  796. $q = array();
  797. if (array_key_exists('query', $parsed_url)) {
  798. $rt_query = $parsed_url['query'];
  799. $q = Auth_OpenID::parse_str($rt_query);
  800. }
  801. foreach ($q as $rt_key => $rt_value) {
  802. if (!array_key_exists($rt_key, $query)) {
  803. return new Auth_OpenID_FailureResponse(null,
  804. sprintf("return_to parameter %s absent from query", $rt_key));
  805. } else {
  806. $value = $query[$rt_key];
  807. if ($rt_value != $value) {
  808. return new Auth_OpenID_FailureResponse(null,
  809. sprintf("parameter %s value %s does not match " .
  810. "return_to value %s", $rt_key,
  811. $value, $rt_value));
  812. }
  813. }
  814. }
  815. // Make sure all non-OpenID arguments in the response are also
  816. // in the signed return_to.
  817. $bare_args = $message->getArgs(Auth_OpenID_BARE_NS);
  818. foreach ($bare_args as $key => $value) {
  819. if (Auth_OpenID::arrayGet($q, $key) != $value) {
  820. return new Auth_OpenID_FailureResponse(null,
  821. sprintf("Parameter %s = %s not in return_to URL",
  822. $key, $value));
  823. }
  824. }
  825. return true;
  826. }
  827. /**
  828. * @access private
  829. */
  830. function _idResCheckSignature($message, $server_url)
  831. {
  832. $assoc_handle = $message->getArg(Auth_OpenID_OPENID_NS,
  833. 'assoc_handle');
  834. if (Auth_OpenID::isFailure($assoc_handle)) {
  835. return $assoc_handle;
  836. }
  837. $assoc = $this->store->getAssociation($server_url, $assoc_handle);
  838. if ($assoc) {
  839. if ($assoc->getExpiresIn() <= 0) {
  840. // XXX: It might be a good idea sometimes to re-start
  841. // the authentication with a new association. Doing it
  842. // automatically opens the possibility for
  843. // denial-of-service by a server that just returns
  844. // expired associations (or really short-lived
  845. // associations)
  846. return new Auth_OpenID_FailureResponse(null,
  847. 'Association with ' . $server_url . ' expired');
  848. }
  849. if (!$assoc->checkMessageSignature($message)) {
  850. // If we get a "bad signature" here, it means that the association
  851. // is unrecoverabley corrupted in some way. Any futher attempts
  852. // to login with this association is likely to fail. Drop it.
  853. $this->store->removeAssociation($server_url, $assoc_handle);
  854. return new Auth_OpenID_FailureResponse(null,
  855. "Bad signature");
  856. }
  857. } else {
  858. // It's not an association we know about. Stateless mode
  859. // is our only possible path for recovery. XXX - async
  860. // framework will not want to block on this call to
  861. // _checkAuth.
  862. if (!$this->_checkAuth($message, $server_url)) {
  863. return new Auth_OpenID_FailureResponse(null,
  864. "Server denied check_authentication");
  865. }
  866. }
  867. return null;
  868. }
  869. /**
  870. * @access private
  871. */
  872. function _verifyDiscoveryResults($message, $endpoint=null)
  873. {
  874. if ($message->getOpenIDNamespace() == Auth_OpenID_OPENID2_NS) {
  875. return $this->_verifyDiscoveryResultsOpenID2($message,
  876. $endpoint);
  877. } else {
  878. return $this->_verifyDiscoveryResultsOpenID1($message,
  879. $endpoint);
  880. }
  881. }
  882. /**
  883. * @access private
  884. */
  885. function _verifyDiscoveryResultsOpenID1($message, $endpoint)
  886. {
  887. $claimed_id = $message->getArg(Auth_OpenID_BARE_NS,
  888. $this->openid1_return_to_identifier_name);
  889. if (($endpoint === null) && ($claimed_id === null)) {
  890. return new Auth_OpenID_FailureResponse($endpoint,
  891. 'When using OpenID 1, the claimed ID must be supplied, ' .
  892. 'either by passing it through as a return_to parameter ' .
  893. 'or by using a session, and supplied to the GenericConsumer ' .
  894. 'as the argument to complete()');
  895. } else if (($endpoint !== null) && ($claimed_id === null)) {
  896. $claimed_id = $endpoint->claimed_id;
  897. }
  898. $to_match = new Auth_OpenID_ServiceEndpoint();
  899. $to_match->type_uris = array(Auth_OpenID_TYPE_1_1);
  900. $to_match->local_id = $message->getArg(Auth_OpenID_OPENID1_NS,
  901. 'identity');
  902. // Restore delegate information from the initiation phase
  903. $to_match->claimed_id = $claimed_id;
  904. if ($to_match->local_id === null) {
  905. return new Auth_OpenID_FailureResponse($endpoint,
  906. "Missing required field openid.identity");
  907. }
  908. $to_match_1_0 = $to_match->copy();
  909. $to_match_1_0->type_uris = array(Auth_OpenID_TYPE_1_0);
  910. if ($endpoint !== null) {
  911. $result = $this->_verifyDiscoverySingle($endpoint, $to_match);
  912. if (is_a($result, 'Auth_OpenID_TypeURIMismatch')) {
  913. $result = $this->_verifyDiscoverySingle($endpoint,
  914. $to_match_1_0);
  915. }
  916. if (Auth_OpenID::isFailure($result)) {
  917. // oidutil.log("Error attempting to use stored
  918. // discovery information: " + str(e))
  919. // oidutil.log("Attempting discovery to
  920. // verify endpoint")
  921. } else {
  922. return $endpoint;
  923. }
  924. }
  925. // Endpoint is either bad (failed verification) or None
  926. return $this->_discoverAndVerify($to_match->claimed_id,
  927. array($to_match, $to_match_1_0));
  928. }
  929. /**
  930. * @access private
  931. */
  932. function _verifyDiscoverySingle($endpoint, $to_match)
  933. {
  934. // Every type URI that's in the to_match endpoint has to be
  935. // present in the discovered endpoint.
  936. foreach ($to_match->type_uris as $type_uri) {
  937. if (!$endpoint->usesExtension($type_uri)) {
  938. return new Auth_OpenID_TypeURIMismatch($endpoint,
  939. "Required type ".$type_uri." not present");
  940. }
  941. }
  942. // Fragments do not influence discovery, so we can't compare a
  943. // claimed identifier with a fragment to discovered
  944. // information.
  945. list($defragged_claimed_id, $_) =
  946. Auth_OpenID::urldefrag($to_match->claimed_id);
  947. if ($defragged_claimed_id != $endpoint->claimed_id) {
  948. return new Auth_OpenID_FailureResponse($endpoint,
  949. sprintf('Claimed ID does not match (different subjects!), ' .
  950. 'Expected %s, got %s', $defragged_claimed_id,
  951. $endpoint->claimed_id));
  952. }
  953. if ($to_match->getLocalID() != $endpoint->getLocalID()) {
  954. return new Auth_OpenID_FailureResponse($endpoint,
  955. sprintf('local_id mismatch. Expected %s, got %s',
  956. $to_match->getLocalID(), $endpoint->getLocalID()));
  957. }
  958. // If the server URL is None, this must be an OpenID 1
  959. // response, because op_endpoint is a required parameter in
  960. // OpenID 2. In that case, we don't actually care what the
  961. // discovered server_url is, because signature checking or
  962. // check_auth should take care of that check for us.
  963. if ($to_match->server_url === null) {
  964. if ($to_match->preferredNamespace() != Auth_OpenID_OPENID1_NS) {
  965. return new Auth_OpenID_FailureResponse($endpoint,
  966. "Preferred namespace mismatch (bug)");
  967. }
  968. } else if ($to_match->server_url != $endpoint->server_url) {
  969. return new Auth_OpenID_FailureResponse($endpoint,
  970. sprintf('OP Endpoint mismatch. Expected %s, got %s',
  971. $to_match->server_url, $endpoint->server_url));
  972. }
  973. return null;
  974. }
  975. /**
  976. * @access private
  977. */
  978. function _verifyDiscoveryResultsOpenID2($message, $endpoint)
  979. {
  980. $to_match = new Auth_OpenID_ServiceEndpoint();
  981. $to_match->type_uris = array(Auth_OpenID_TYPE_2_0);
  982. $to_match->claimed_id = $message->getArg(Auth_OpenID_OPENID2_NS,
  983. 'claimed_id');
  984. $to_match->local_id = $message->getArg(Auth_OpenID_OPENID2_NS,
  985. 'identity');
  986. $to_match->server_url = $message->getArg(Auth_OpenID_OPENID2_NS,
  987. 'op_endpoint');
  988. if ($to_match->server_url === null) {
  989. return new Auth_OpenID_FailureResponse($endpoint,
  990. "OP Endpoint URL missing");
  991. }
  992. // claimed_id and identifier must both be present or both be
  993. // absent
  994. if (($to_match->claimed_id === null) &&
  995. ($to_match->local_id !== null)) {
  996. return new Auth_OpenID_FailureResponse($endpoint,
  997. 'openid.identity is present without openid.claimed_id');
  998. }
  999. if (($to_match->claimed_id !== null) &&
  1000. ($to_match->local_id === null)) {
  1001. return new Auth_OpenID_FailureResponse($endpoint,
  1002. 'openid.claimed_id is present without openid.identity');
  1003. }
  1004. if ($to_match->claimed_id === null) {
  1005. // This is a response without identifiers, so there's
  1006. // really no checking that we can do, so return an
  1007. // endpoint that's for the specified `openid.op_endpoint'
  1008. return Auth_OpenID_ServiceEndpoint::fromOPEndpointURL(
  1009. $to_match->server_url);
  1010. }
  1011. if (!$endpoint) {
  1012. // The claimed ID doesn't match, so we have to do
  1013. // discovery again. This covers not using sessions, OP
  1014. // identifier endpoints and responses that didn't match
  1015. // the original request.
  1016. // oidutil.log('No pre-discovered information supplied.')
  1017. return $this->_discoverAndVerify($to_match->claimed_id,
  1018. array($to_match));
  1019. } else {
  1020. // The claimed ID matches, so we use the endpoint that we
  1021. // discovered in initiation. This should be the most
  1022. // common case.
  1023. $result = $this->_verifyDiscoverySingle($endpoint, $to_match);
  1024. if (Auth_OpenID::isFailure($result)) {
  1025. $endpoint = $this->_discoverAndVerify($to_match->claimed_id,
  1026. array($to_match));
  1027. if (Auth_OpenID::isFailure($endpoint)) {
  1028. return $endpoint;
  1029. }
  1030. }
  1031. }
  1032. // The endpoint we return should have the claimed ID from the
  1033. // message we just verified, fragment and all.
  1034. if ($endpoint->claimed_id != $to_match->claimed_id) {
  1035. $endpoint->claimed_id = $to_match->claimed_id;
  1036. }
  1037. return $endpoint;
  1038. }
  1039. /**
  1040. * @access private
  1041. */
  1042. function _discoverAndVerify($claimed_id, $to_match_endpoints)
  1043. {
  1044. // oidutil.log('Performing discovery on %s' % (claimed_id,))
  1045. list($unused, $services) = call_user_func_array($this->discoverMethod,
  1046. array(
  1047. $claimed_id,
  1048. $this->fetcher,
  1049. ));
  1050. if (!$services) {
  1051. return new Auth_OpenID_FailureResponse(null,
  1052. sprintf("No OpenID information found at %s",
  1053. $claimed_id));
  1054. }
  1055. return $this->_verifyDiscoveryServices($claimed_id, $services,
  1056. $to_match_endpoints);
  1057. }
  1058. /**
  1059. * @access private
  1060. */
  1061. function _verifyDiscoveryServices($claimed_id,
  1062. $services, $to_match_endpoints)
  1063. {
  1064. // Search the services resulting from discovery to find one
  1065. // that matches the information from the assertion
  1066. foreach ($services as $endpoint) {
  1067. foreach ($to_match_endpoints as $to_match_endpoint) {
  1068. $result = $this->_verifyDiscoverySingle($endpoint,
  1069. $to_match_endpoint);
  1070. if (!Auth_OpenID::isFailure($result)) {
  1071. // It matches, so discover verification has
  1072. // succeeded. Return this endpoint.
  1073. return $endpoint;
  1074. }
  1075. }
  1076. }
  1077. return new Auth_OpenID_FailureResponse(null,
  1078. sprintf('No matching endpoint found after discovering %s: %s',
  1079. $claimed_id, $result->message));
  1080. }
  1081. /**
  1082. * Extract the nonce from an OpenID 1 response. Return the nonce
  1083. * from the BARE_NS since we independently check the return_to
  1084. * arguments are the same as those in the response message.
  1085. *
  1086. * See the openid1_nonce_query_arg_name class variable
  1087. *
  1088. * @returns $nonce The nonce as a string or null
  1089. *
  1090. * @access private
  1091. */
  1092. function _idResGetNonceOpenID1($message, $endpoint)
  1093. {
  1094. return $message->getArg(Auth_OpenID_BARE_NS,
  1095. $this->openid1_nonce_query_arg_name);
  1096. }
  1097. /**
  1098. * @access private
  1099. */
  1100. function _idResCheckNonce($message, $endpoint)
  1101. {
  1102. if ($message->isOpenID1()) {
  1103. // This indicates that the nonce was generated by the consumer
  1104. $nonce = $this->_idResGetNonceOpenID1($message, $endpoint);
  1105. $server_url = '';
  1106. } else {
  1107. $nonce = $message->getArg(Auth_OpenID_OPENID2_NS,
  1108. 'response_nonce');
  1109. $server_url = $endpoint->server_url;
  1110. }
  1111. if ($nonce === null) {
  1112. return new Auth_OpenID_FailureResponse($endpoint,
  1113. "Nonce missing from response");
  1114. }
  1115. $parts = Auth_OpenID_splitNonce($nonce);
  1116. if ($parts === null) {
  1117. return new Auth_OpenID_FailureResponse($endpoint,
  1118. "Malformed nonce in response");
  1119. }
  1120. list($timestamp, $salt) = $parts;
  1121. if (!$this->store->useNonce($server_url, $timestamp, $salt)) {
  1122. return new Auth_OpenID_FailureResponse($endpoint,
  1123. "Nonce already used or out of range");
  1124. }
  1125. return null;
  1126. }
  1127. /**
  1128. * @access private
  1129. */
  1130. function _idResCheckForFields($message)
  1131. {
  1132. $basic_fields = array('return_to', 'assoc_handle', 'sig', 'signed');
  1133. $basic_sig_fields = array('return_to', 'identity');
  1134. $require_fields = array(
  1135. Auth_OpenID_OPENID2_NS => array_merge($basic_fields,
  1136. array('op_endpoint')),
  1137. Auth_OpenID_OPENID1_NS => array_merge($basic_fields,
  1138. array('identity'))
  1139. );
  1140. $require_sigs = array(
  1141. Auth_OpenID_OPENID2_NS => array_merge($basic_sig_fields,
  1142. array('response_nonce',
  1143. 'claimed_id',
  1144. 'assoc_handle',
  1145. 'op_endpoint')),
  1146. Auth_OpenID_OPENID1_NS => array_merge($basic_sig_fields,
  1147. array('nonce'))
  1148. );
  1149. foreach ($require_fields[$message->getOpenIDNamespace()] as $field) {
  1150. if (!$message->hasKey(Auth_OpenID_OPENID_NS, $field)) {
  1151. return new Auth_OpenID_FailureResponse(null,
  1152. "Missing required field '".$field."'");
  1153. }
  1154. }
  1155. $signed_list_str = $message->getArg(Auth_OpenID_OPENID_NS,
  1156. 'signed',
  1157. Auth_OpenID_NO_DEFAULT);
  1158. if (Auth_OpenID::isFailure($signed_list_str)) {
  1159. return $signed_list_str;
  1160. }
  1161. $signed_list = explode(',', $signed_list_str);
  1162. foreach ($require_sigs[$message->getOpenIDNamespace()] as $field) {
  1163. // Field is present and not in signed list
  1164. if ($message->hasKey(Auth_OpenID_OPENID_NS, $field) &&
  1165. (!in_array($field, $signed_list))) {
  1166. return new Auth_OpenID_FailureResponse(null,
  1167. "'".$field."' not signed");
  1168. }
  1169. }
  1170. return null;
  1171. }
  1172. /**
  1173. * @access private
  1174. */
  1175. function _checkAuth($message, $server_url)
  1176. {
  1177. $request = $this->_createCheckAuthRequest($message);
  1178. if ($request === null) {
  1179. return false;
  1180. }
  1181. $resp_message = $this->_makeKVPost($request, $server_url);
  1182. if (($resp_message === null) ||
  1183. (is_a($resp_message, 'Auth_OpenID_ServerErrorContainer'))) {
  1184. return false;
  1185. }
  1186. return $this->_processCheckAuthResponse($resp_message, $server_url);
  1187. }
  1188. /**
  1189. * @access private
  1190. */
  1191. function _createCheckAuthRequest($message)
  1192. {
  1193. $signed = $message->getArg(Auth_OpenID_OPENID_NS, 'signed');
  1194. if ($signed) {
  1195. foreach (explode(',', $signed) as $k) {
  1196. $value = $message->getAliasedArg($k);
  1197. if ($value === null) {
  1198. return null;
  1199. }
  1200. }
  1201. }
  1202. $ca_message = $message->copy();
  1203. $ca_message->setArg(Auth_OpenID_OPENID_NS, 'mode',
  1204. 'check_authentication');
  1205. return $ca_message;
  1206. }
  1207. /**
  1208. * @access private
  1209. */
  1210. function _processCheckAuthResponse($response, $server_url)
  1211. {
  1212. $is_valid = $response->getArg(Auth_OpenID_OPENID_NS, 'is_valid',
  1213. 'false');
  1214. $invalidate_handle = $response->getArg(Auth_OpenID_OPENID_NS,
  1215. 'invalidate_handle');
  1216. if ($invalidate_handle !== null) {
  1217. $this->store->removeAssociation($server_url,
  1218. $invalidate_handle);
  1219. }
  1220. if ($is_valid == 'true') {
  1221. return true;
  1222. }
  1223. return false;
  1224. }
  1225. /**
  1226. * Adapt a POST response to a Message.
  1227. *
  1228. * @param $response Result of a POST to an OpenID endpoint.
  1229. *
  1230. * @access private
  1231. */
  1232. static function _httpResponseToMessage($response, $server_url)
  1233. {
  1234. // Should this function be named Message.fromHTTPResponse instead?
  1235. $response_message = Auth_OpenID_Message::fromKVForm($response->body);
  1236. if ($response->status == 400) {
  1237. return Auth_OpenID_ServerErrorContainer::fromMessage(
  1238. $response_message);
  1239. } else if ($response->status != 200 and $response->status != 206) {
  1240. return null;
  1241. }
  1242. return $response_message;
  1243. }
  1244. /**
  1245. * @access private
  1246. */
  1247. function _makeKVPost($message, $server_url)
  1248. {
  1249. $body = $message->toURLEncoded();
  1250. $resp = $this->fetcher->post($server_url, $body);
  1251. if ($resp === null) {
  1252. return null;
  1253. }
  1254. return $this->_httpResponseToMessage($resp, $server_url);
  1255. }
  1256. /**
  1257. * @access private
  1258. */
  1259. function _getAssociation($endpoint)
  1260. {
  1261. if (!$this->_use_assocs) {
  1262. return null;
  1263. }
  1264. $assoc = $this->store->getAssociation($endpoint->server_url);
  1265. if (($assoc === null) ||
  1266. ($assoc->getExpiresIn() <= 0)) {
  1267. $assoc = $this->_negotiateAssociation($endpoint);
  1268. if ($assoc !== null) {
  1269. $this->store->storeAssociation($endpoint->server_url,
  1270. $assoc);
  1271. }
  1272. }
  1273. return $assoc;
  1274. }
  1275. /**
  1276. * Handle ServerErrors resulting from association requests.
  1277. *
  1278. * @return $result If server replied with an C{unsupported-type}
  1279. * error, return a tuple of supported C{association_type},
  1280. * C{session_type}. Otherwise logs the error and returns null.
  1281. *
  1282. * @access private
  1283. */
  1284. function _extractSupportedAssociationType($server_error, $endpoint,
  1285. $assoc_type)
  1286. {
  1287. // Any error message whose code is not 'unsupported-type'
  1288. // should be considered a total failure.
  1289. if (($server_error->error_code != 'unsupported-type') ||
  1290. ($server_error->message->isOpenID1())) {
  1291. return null;
  1292. }
  1293. // The server didn't like the association/session type that we
  1294. // sent, and it sent us back a message that might tell us how
  1295. // to handle it.
  1296. // Extract the session_type and assoc_type from the error
  1297. // message
  1298. $assoc_type = $server_error->message->getArg(Auth_OpenID_OPENID_NS,
  1299. 'assoc_type');
  1300. $session_type = $server_error->message->getArg(Auth_OpenID_OPENID_NS,
  1301. 'session_type');
  1302. if (($assoc_type === null) || ($session_type === null)) {
  1303. return null;
  1304. } else if (!$this->negotiator->isAllowed($assoc_type,
  1305. $session_type)) {
  1306. return null;
  1307. } else {
  1308. return array($assoc_type, $session_type);
  1309. }
  1310. }
  1311. /**
  1312. * @access private
  1313. */
  1314. function _negotiateAssociation($endpoint)
  1315. {
  1316. // Get our preferred session/association type from the negotiatior.
  1317. list($assoc_type, $session_type) = $this->negotiator->getAllowedType();
  1318. $assoc = $this->_requestAssociation(
  1319. $endpoint, $assoc_type, $session_type);
  1320. if (Auth_OpenID::isFailure($assoc)) {
  1321. return null;
  1322. }
  1323. if (is_a($assoc, 'Auth_OpenID_ServerErrorContainer')) {
  1324. $why = $assoc;
  1325. $supportedTypes = $this->_extractSupportedAssociationType(
  1326. $why, $endpoint, $assoc_type);
  1327. if ($supportedTypes !== null) {
  1328. list($assoc_type, $session_type) = $supportedTypes;
  1329. // Attempt to create an association from the assoc_type
  1330. // and session_type that the server told us it
  1331. // supported.
  1332. $assoc = $this->_requestAssociation(
  1333. $endpoint, $assoc_type, $session_type);
  1334. if (is_a($assoc, 'Auth_OpenID_ServerErrorContainer')) {
  1335. // Do not keep trying, since it rejected the
  1336. // association type that it told us to use.
  1337. // oidutil.log('Server %s refused its suggested association
  1338. // 'type: session_type=%s, assoc_type=%s'
  1339. // % (endpoint.server_url, session_type,
  1340. // assoc_type))
  1341. return null;
  1342. } else {
  1343. return $assoc;
  1344. }
  1345. } else {
  1346. return null;
  1347. }
  1348. } else {
  1349. return $assoc;
  1350. }
  1351. }
  1352. /**
  1353. * @access private
  1354. */
  1355. function _requestAssociation($endpoint, $assoc_type, $session_type)
  1356. {
  1357. list($assoc_session, $args) = $this->_createAssociateRequest(
  1358. $endpoint, $assoc_type, $session_type);
  1359. $response_message = $this->_makeKVPost($args, $endpoint->server_url);
  1360. if ($response_message === null) {
  1361. // oidutil.log('openid.associate request failed: %s' % (why[0],))
  1362. return null;
  1363. } else if (is_a($response_message,
  1364. 'Auth_OpenID_ServerErrorContainer')) {
  1365. return $response_message;
  1366. }
  1367. return $this->_extractAssociation($response_message, $assoc_session);
  1368. }
  1369. /**
  1370. * @access private
  1371. */
  1372. function _extractAssociation($assoc_response, $assoc_session)
  1373. {
  1374. // Extract the common fields from the response, raising an
  1375. // exception if they are not found
  1376. $assoc_type = $assoc_response->getArg(
  1377. Auth_OpenID_OPENID_NS, 'assoc_type',
  1378. Auth_OpenID_NO_DEFAULT);
  1379. if (Auth_OpenID::isFailure($assoc_type)) {
  1380. return $assoc_type;
  1381. }
  1382. $assoc_handle = $assoc_response->getArg(
  1383. Auth_OpenID_OPENID_NS, 'assoc_handle',
  1384. Auth_OpenID_NO_DEFAULT);
  1385. if (Auth_OpenID::isFailure($assoc_handle)) {
  1386. return $assoc_handle;
  1387. }
  1388. // expires_in is a base-10 string. The Python parsing will
  1389. // accept literals that have whitespace around them and will
  1390. // accept negative values. Neither of these are really in-spec,
  1391. // but we think it's OK to accept them.
  1392. $expires_in_str = $assoc_response->getArg(
  1393. Auth_OpenID_OPENID_NS, 'expires_in',
  1394. Auth_OpenID_NO_DEFAULT);
  1395. if (Auth_OpenID::isFailure($expires_in_str)) {
  1396. return $expires_in_str;
  1397. }
  1398. $expires_in = Auth_OpenID::intval($expires_in_str);
  1399. if ($expires_in === false) {
  1400. $err = sprintf("Could not parse expires_in from association ".
  1401. "response %s", print_r($assoc_response, true));
  1402. return new Auth_OpenID_FailureResponse(null, $err);
  1403. }
  1404. // OpenID 1 has funny association session behaviour.
  1405. if ($assoc_response->isOpenID1()) {
  1406. $session_type = $this->_getOpenID1SessionType($assoc_response);
  1407. } else {
  1408. $session_type = $assoc_response->getArg(
  1409. Auth_OpenID_OPENID2_NS, 'session_type',
  1410. Auth_OpenID_NO_DEFAULT);
  1411. if (Auth_OpenID::isFailure($session_type)) {
  1412. return $session_type;
  1413. }
  1414. }
  1415. // Session type mismatch
  1416. if ($assoc_session->session_type != $session_type) {
  1417. if ($assoc_response->isOpenID1() &&
  1418. ($session_type == 'no-encryption')) {
  1419. // In OpenID 1, any association request can result in
  1420. // a 'no-encryption' association response. Setting
  1421. // assoc_session to a new no-encryption session should
  1422. // make the rest of this function work properly for
  1423. // that case.
  1424. $assoc_session = new Auth_OpenID_PlainTextConsumerSession();
  1425. } else {
  1426. // Any other mismatch, regardless of protocol version
  1427. // results in the failure of the association session
  1428. // altogether.
  1429. return null;
  1430. }
  1431. }
  1432. // Make sure assoc_type is valid for session_type
  1433. if (!in_array($assoc_type, $assoc_session->allowed_assoc_types)) {
  1434. return null;
  1435. }
  1436. // Delegate to the association session to extract the secret
  1437. // from the response, however is appropriate for that session
  1438. // type.
  1439. $secret = $assoc_session->extractSecret($assoc_response);
  1440. if ($secret === null) {
  1441. return null;
  1442. }
  1443. return Auth_OpenID_Association::fromExpiresIn(
  1444. $expires_in, $assoc_handle, $secret, $assoc_type);
  1445. }
  1446. /**
  1447. * @access private
  1448. */
  1449. function _createAssociateRequest($endpoint, $assoc_type, $session_type)
  1450. {
  1451. if (array_key_exists($session_type, $this->session_types)) {
  1452. $session_type_class = $this->session_types[$session_type];
  1453. if (is_callable($session_type_class)) {
  1454. $assoc_session = $session_type_class();
  1455. } else {
  1456. $assoc_session = new $session_type_class();
  1457. }
  1458. } else {
  1459. return null;
  1460. }
  1461. $args = array(
  1462. 'mode' => 'associate',
  1463. 'assoc_type' => $assoc_type);
  1464. if (!$endpoint->compatibilityMode()) {
  1465. $args['ns'] = Auth_OpenID_OPENID2_NS;
  1466. }
  1467. // Leave out the session type if we're in compatibility mode
  1468. // *and* it's no-encryption.
  1469. if ((!$endpoint->compatibilityMode()) ||
  1470. ($assoc_session->session_type != 'no-encryption')) {
  1471. $args['session_type'] = $assoc_session->session_type;
  1472. }
  1473. $args = array_merge($args, $assoc_session->getRequest());
  1474. $message = Auth_OpenID_Message::fromOpenIDArgs($args);
  1475. return array($assoc_session, $message);
  1476. }
  1477. /**
  1478. * Given an association response message, extract the OpenID 1.X
  1479. * session type.
  1480. *
  1481. * This function mostly takes care of the 'no-encryption' default
  1482. * behavior in OpenID 1.
  1483. *
  1484. * If the association type is plain-text, this function will
  1485. * return 'no-encryption'
  1486. *
  1487. * @access private
  1488. * @return $typ The association type for this message
  1489. */
  1490. function _getOpenID1SessionType($assoc_response)
  1491. {
  1492. // If it's an OpenID 1 message, allow session_type to default
  1493. // to None (which signifies "no-encryption")
  1494. $session_type = $assoc_response->getArg(Auth_OpenID_OPENID1_NS,
  1495. 'session_type');
  1496. // Handle the differences between no-encryption association
  1497. // respones in OpenID 1 and 2:
  1498. // no-encryption is not really a valid session type for OpenID
  1499. // 1, but we'll accept it anyway, while issuing a warning.
  1500. if ($session_type == 'no-encryption') {
  1501. // oidutil.log('WARNING: OpenID server sent "no-encryption"'
  1502. // 'for OpenID 1.X')
  1503. } else if (($session_type == '') || ($session_type === null)) {
  1504. // Missing or empty session type is the way to flag a
  1505. // 'no-encryption' response. Change the session type to
  1506. // 'no-encryption' so that it can be handled in the same
  1507. // way as OpenID 2 'no-encryption' respones.
  1508. $session_type = 'no-encryption';
  1509. }
  1510. return $session_type;
  1511. }
  1512. }
  1513. /**
  1514. * This class represents an authentication request from a consumer to
  1515. * an OpenID server.
  1516. *
  1517. * @package OpenID
  1518. */
  1519. class Auth_OpenID_AuthRequest {
  1520. /**
  1521. * Initialize an authentication request with the specified token,
  1522. * association, and endpoint.
  1523. *
  1524. * Users of this library should not create instances of this
  1525. * class. Instances of this class are created by the library when
  1526. * needed.
  1527. */
  1528. function Auth_OpenID_AuthRequest($endpoint, $assoc)
  1529. {
  1530. $this->assoc = $assoc;
  1531. $this->endpoint = $endpoint;
  1532. $this->return_to_args = array();
  1533. $this->message = new Auth_OpenID_Message(
  1534. $endpoint->preferredNamespace());
  1535. $this->_anonymous = false;
  1536. }
  1537. /**
  1538. * Add an extension to this checkid request.
  1539. *
  1540. * $extension_request: An object that implements the extension
  1541. * request interface for adding arguments to an OpenID message.
  1542. */
  1543. function addExtension($extension_request)
  1544. {
  1545. $extension_request->toMessage($this->message);
  1546. }
  1547. /**
  1548. * Add an extension argument to this OpenID authentication
  1549. * request.
  1550. *
  1551. * Use caution when adding arguments, because they will be
  1552. * URL-escaped and appended to the redirect URL, which can easily
  1553. * get quite long.
  1554. *
  1555. * @param string $namespace The namespace for the extension. For
  1556. * example, the simple registration extension uses the namespace
  1557. * 'sreg'.
  1558. *
  1559. * @param string $key The key within the extension namespace. For
  1560. * example, the nickname field in the simple registration
  1561. * extension's key is 'nickname'.
  1562. *
  1563. * @param string $value The value to provide to the server for
  1564. * this argument.
  1565. */
  1566. function addExtensionArg($namespace, $key, $value)
  1567. {
  1568. return $this->message->setArg($namespace, $key, $value);
  1569. }
  1570. /**
  1571. * Set whether this request should be made anonymously. If a
  1572. * request is anonymous, the identifier will not be sent in the
  1573. * request. This is only useful if you are making another kind of
  1574. * request with an extension in this request.
  1575. *
  1576. * Anonymous requests are not allowed when the request is made
  1577. * with OpenID 1.
  1578. */
  1579. function setAnonymous($is_anonymous)
  1580. {
  1581. if ($is_anonymous && $this->message->isOpenID1()) {
  1582. return false;
  1583. } else {
  1584. $this->_anonymous = $is_anonymous;
  1585. return true;
  1586. }
  1587. }
  1588. /**
  1589. * Produce a {@link Auth_OpenID_Message} representing this
  1590. * request.
  1591. *
  1592. * @param string $realm The URL (or URL pattern) that identifies
  1593. * your web site to the user when she is authorizing it.
  1594. *
  1595. * @param string $return_to The URL that the OpenID provider will
  1596. * send the user back to after attempting to verify her identity.
  1597. *
  1598. * Not specifying a return_to URL means that the user will not be
  1599. * returned to the site issuing the request upon its completion.
  1600. *
  1601. * @param bool $immediate If true, the OpenID provider is to send
  1602. * back a response immediately, useful for behind-the-scenes
  1603. * authentication attempts. Otherwise the OpenID provider may
  1604. * engage the user before providing a response. This is the
  1605. * default case, as the user may need to provide credentials or
  1606. * approve the request before a positive response can be sent.
  1607. */
  1608. function getMessage($realm, $return_to=null, $immediate=false)
  1609. {
  1610. if ($return_to) {
  1611. $return_to = Auth_OpenID::appendArgs($return_to,
  1612. $this->return_to_args);
  1613. } else if ($immediate) {
  1614. // raise ValueError(
  1615. // '"return_to" is mandatory when
  1616. //using "checkid_immediate"')
  1617. return new Auth_OpenID_FailureResponse(null,
  1618. "'return_to' is mandatory when using checkid_immediate");
  1619. } else if ($this->message->isOpenID1()) {
  1620. // raise ValueError('"return_to" is
  1621. // mandatory for OpenID 1 requests')
  1622. return new Auth_OpenID_FailureResponse(null,
  1623. "'return_to' is mandatory for OpenID 1 requests");
  1624. } else if ($this->return_to_args) {
  1625. // raise ValueError('extra "return_to" arguments
  1626. // were specified, but no return_to was specified')
  1627. return new Auth_OpenID_FailureResponse(null,
  1628. "extra 'return_to' arguments where specified, " .
  1629. "but no return_to was specified");
  1630. }
  1631. if ($immediate) {
  1632. $mode = 'checkid_immediate';
  1633. } else {
  1634. $mode = 'checkid_setup';
  1635. }
  1636. $message = $this->message->copy();
  1637. if ($message->isOpenID1()) {
  1638. $realm_key = 'trust_root';
  1639. } else {
  1640. $realm_key = 'realm';
  1641. }
  1642. $message->updateArgs(Auth_OpenID_OPENID_NS,
  1643. array(
  1644. $realm_key => $realm,
  1645. 'mode' => $mode,
  1646. 'return_to' => $return_to));
  1647. if (!$this->_anonymous) {
  1648. if ($this->endpoint->isOPIdentifier()) {
  1649. // This will never happen when we're in compatibility
  1650. // mode, as long as isOPIdentifier() returns False
  1651. // whenever preferredNamespace() returns OPENID1_NS.
  1652. $claimed_id = $request_identity =
  1653. Auth_OpenID_IDENTIFIER_SELECT;
  1654. } else {
  1655. $request_identity = $this->endpoint->getLocalID();
  1656. $claimed_id = $this->endpoint->claimed_id;
  1657. }
  1658. // This is true for both OpenID 1 and 2
  1659. $message->setArg(Auth_OpenID_OPENID_NS, 'identity',
  1660. $request_identity);
  1661. if ($message->isOpenID2()) {
  1662. $message->setArg(Auth_OpenID_OPENID2_NS, 'claimed_id',
  1663. $claimed_id);
  1664. }
  1665. }
  1666. if ($this->assoc) {
  1667. $message->setArg(Auth_OpenID_OPENID_NS, 'assoc_handle',
  1668. $this->assoc->handle);
  1669. }
  1670. return $message;
  1671. }
  1672. function redirectURL($realm, $return_to = null,
  1673. $immediate = false)
  1674. {
  1675. $message = $this->getMessage($realm, $return_to, $immediate);
  1676. if (Auth_OpenID::isFailure($message)) {
  1677. return $message;
  1678. }
  1679. return $message->toURL($this->endpoint->server_url);
  1680. }
  1681. /**
  1682. * Get html for a form to submit this request to the IDP.
  1683. *
  1684. * form_tag_attrs: An array of attributes to be added to the form
  1685. * tag. 'accept-charset' and 'enctype' have defaults that can be
  1686. * overridden. If a value is supplied for 'action' or 'method', it
  1687. * will be replaced.
  1688. */
  1689. function formMarkup($realm, $return_to=null, $immediate=false,
  1690. $form_tag_attrs=null)
  1691. {
  1692. $message = $this->getMessage($realm, $return_to, $immediate);
  1693. if (Auth_OpenID::isFailure($message)) {
  1694. return $message;
  1695. }
  1696. return $message->toFormMarkup($this->endpoint->server_url,
  1697. $form_tag_attrs);
  1698. }
  1699. /**
  1700. * Get a complete html document that will autosubmit the request
  1701. * to the IDP.
  1702. *
  1703. * Wraps formMarkup. See the documentation for that function.
  1704. */
  1705. function htmlMarkup($realm, $return_to=null, $immediate=false,
  1706. $form_tag_attrs=null)
  1707. {
  1708. $form = $this->formMarkup($realm, $return_to, $immediate,
  1709. $form_tag_attrs);
  1710. if (Auth_OpenID::isFailure($form)) {
  1711. return $form;
  1712. }
  1713. return Auth_OpenID::autoSubmitHTML($form);
  1714. }
  1715. function shouldSendRedirect()
  1716. {
  1717. return $this->endpoint->compatibilityMode();
  1718. }
  1719. }
  1720. /**
  1721. * The base class for responses from the Auth_OpenID_Consumer.
  1722. *
  1723. * @package OpenID
  1724. */
  1725. class Auth_OpenID_ConsumerResponse {
  1726. var $status = null;
  1727. function setEndpoint($endpoint)
  1728. {
  1729. $this->endpoint = $endpoint;
  1730. if ($endpoint === null) {
  1731. $this->identity_url = null;
  1732. } else {
  1733. $this->identity_url = $endpoint->claimed_id;
  1734. }
  1735. }
  1736. /**
  1737. * Return the display identifier for this response.
  1738. *
  1739. * The display identifier is related to the Claimed Identifier, but the
  1740. * two are not always identical. The display identifier is something the
  1741. * user should recognize as what they entered, whereas the response's
  1742. * claimed identifier (in the identity_url attribute) may have extra
  1743. * information for better persistence.
  1744. *
  1745. * URLs will be stripped of their fragments for display. XRIs will
  1746. * display the human-readable identifier (i-name) instead of the
  1747. * persistent identifier (i-number).
  1748. *
  1749. * Use the display identifier in your user interface. Use
  1750. * identity_url for querying your database or authorization server.
  1751. *
  1752. */
  1753. function getDisplayIdentifier()
  1754. {
  1755. if ($this->endpoint !== null) {
  1756. return $this->endpoint->getDisplayIdentifier();
  1757. }
  1758. return null;
  1759. }
  1760. }
  1761. /**
  1762. * A response with a status of Auth_OpenID_SUCCESS. Indicates that
  1763. * this request is a successful acknowledgement from the OpenID server
  1764. * that the supplied URL is, indeed controlled by the requesting
  1765. * agent. This has three relevant attributes:
  1766. *
  1767. * claimed_id - The identity URL that has been authenticated
  1768. *
  1769. * signed_args - The arguments in the server's response that were
  1770. * signed and verified.
  1771. *
  1772. * status - Auth_OpenID_SUCCESS.
  1773. *
  1774. * @package OpenID
  1775. */
  1776. class Auth_OpenID_SuccessResponse extends Auth_OpenID_ConsumerResponse {
  1777. var $status = Auth_OpenID_SUCCESS;
  1778. /**
  1779. * @access private
  1780. */
  1781. function Auth_OpenID_SuccessResponse($endpoint, $message, $signed_args=null)
  1782. {
  1783. $this->endpoint = $endpoint;
  1784. $this->identity_url = $endpoint->claimed_id;
  1785. $this->signed_args = $signed_args;
  1786. $this->message = $message;
  1787. if ($this->signed_args === null) {
  1788. $this->signed_args = array();
  1789. }
  1790. }
  1791. /**
  1792. * Extract signed extension data from the server's response.
  1793. *
  1794. * @param string $prefix The extension namespace from which to
  1795. * extract the extension data.
  1796. */
  1797. function extensionResponse($namespace_uri, $require_signed)
  1798. {
  1799. if ($require_signed) {
  1800. return $this->getSignedNS($namespace_uri);
  1801. } else {
  1802. return $this->message->getArgs($namespace_uri);
  1803. }
  1804. }
  1805. function isOpenID1()
  1806. {
  1807. return $this->message->isOpenID1();
  1808. }
  1809. function isSigned($ns_uri, $ns_key)
  1810. {
  1811. // Return whether a particular key is signed, regardless of
  1812. // its namespace alias
  1813. return in_array($this->message->getKey($ns_uri, $ns_key),
  1814. $this->signed_args);
  1815. }
  1816. function getSigned($ns_uri, $ns_key, $default = null)
  1817. {
  1818. // Return the specified signed field if available, otherwise
  1819. // return default
  1820. if ($this->isSigned($ns_uri, $ns_key)) {
  1821. return $this->message->getArg($ns_uri, $ns_key, $default);
  1822. } else {
  1823. return $default;
  1824. }
  1825. }
  1826. function getSignedNS($ns_uri)
  1827. {
  1828. $args = array();
  1829. $msg_args = $this->message->getArgs($ns_uri);
  1830. if (Auth_OpenID::isFailure($msg_args)) {
  1831. return null;
  1832. }
  1833. foreach ($msg_args as $key => $value) {
  1834. if (!$this->isSigned($ns_uri, $key)) {
  1835. unset($msg_args[$key]);
  1836. }
  1837. }
  1838. return $msg_args;
  1839. }
  1840. /**
  1841. * Get the openid.return_to argument from this response.
  1842. *
  1843. * This is useful for verifying that this request was initiated by
  1844. * this consumer.
  1845. *
  1846. * @return string $return_to The return_to URL supplied to the
  1847. * server on the initial request, or null if the response did not
  1848. * contain an 'openid.return_to' argument.
  1849. */
  1850. function getReturnTo()
  1851. {
  1852. return $this->getSigned(Auth_OpenID_OPENID_NS, 'return_to');
  1853. }
  1854. }
  1855. /**
  1856. * A response with a status of Auth_OpenID_FAILURE. Indicates that the
  1857. * OpenID protocol has failed. This could be locally or remotely
  1858. * triggered. This has three relevant attributes:
  1859. *
  1860. * claimed_id - The identity URL for which authentication was
  1861. * attempted, if it can be determined. Otherwise, null.
  1862. *
  1863. * message - A message indicating why the request failed, if one is
  1864. * supplied. Otherwise, null.
  1865. *
  1866. * status - Auth_OpenID_FAILURE.
  1867. *
  1868. * @package OpenID
  1869. */
  1870. class Auth_OpenID_FailureResponse extends Auth_OpenID_ConsumerResponse {
  1871. var $status = Auth_OpenID_FAILURE;
  1872. function Auth_OpenID_FailureResponse($endpoint, $message = null,
  1873. $contact = null, $reference = null)
  1874. {
  1875. $this->setEndpoint($endpoint);
  1876. $this->message = $message;
  1877. $this->contact = $contact;
  1878. $this->reference = $reference;
  1879. }
  1880. }
  1881. /**
  1882. * A specific, internal failure used to detect type URI mismatch.
  1883. *
  1884. * @package OpenID
  1885. */
  1886. class Auth_OpenID_TypeURIMismatch extends Auth_OpenID_FailureResponse {
  1887. }
  1888. /**
  1889. * Exception that is raised when the server returns a 400 response
  1890. * code to a direct request.
  1891. *
  1892. * @package OpenID
  1893. */
  1894. class Auth_OpenID_ServerErrorContainer {
  1895. function Auth_OpenID_ServerErrorContainer($error_text,
  1896. $error_code,
  1897. $message)
  1898. {
  1899. $this->error_text = $error_text;
  1900. $this->error_code = $error_code;
  1901. $this->message = $message;
  1902. }
  1903. /**
  1904. * @access private
  1905. */
  1906. static function fromMessage($message)
  1907. {
  1908. $error_text = $message->getArg(
  1909. Auth_OpenID_OPENID_NS, 'error', '<no error message supplied>');
  1910. $error_code = $message->getArg(Auth_OpenID_OPENID_NS, 'error_code');
  1911. return new Auth_OpenID_ServerErrorContainer($error_text,
  1912. $error_code,
  1913. $message);
  1914. }
  1915. }
  1916. /**
  1917. * A response with a status of Auth_OpenID_CANCEL. Indicates that the
  1918. * user cancelled the OpenID authentication request. This has two
  1919. * relevant attributes:
  1920. *
  1921. * claimed_id - The identity URL for which authentication was
  1922. * attempted, if it can be determined. Otherwise, null.
  1923. *
  1924. * status - Auth_OpenID_SUCCESS.
  1925. *
  1926. * @package OpenID
  1927. */
  1928. class Auth_OpenID_CancelResponse extends Auth_OpenID_ConsumerResponse {
  1929. var $status = Auth_OpenID_CANCEL;
  1930. function Auth_OpenID_CancelResponse($endpoint)
  1931. {
  1932. $this->setEndpoint($endpoint);
  1933. }
  1934. }
  1935. /**
  1936. * A response with a status of Auth_OpenID_SETUP_NEEDED. Indicates
  1937. * that the request was in immediate mode, and the server is unable to
  1938. * authenticate the user without further interaction.
  1939. *
  1940. * claimed_id - The identity URL for which authentication was
  1941. * attempted.
  1942. *
  1943. * setup_url - A URL that can be used to send the user to the server
  1944. * to set up for authentication. The user should be redirected in to
  1945. * the setup_url, either in the current window or in a new browser
  1946. * window. Null in OpenID 2.
  1947. *
  1948. * status - Auth_OpenID_SETUP_NEEDED.
  1949. *
  1950. * @package OpenID
  1951. */
  1952. class Auth_OpenID_SetupNeededResponse extends Auth_OpenID_ConsumerResponse {
  1953. var $status = Auth_OpenID_SETUP_NEEDED;
  1954. function Auth_OpenID_SetupNeededResponse($endpoint,
  1955. $setup_url = null)
  1956. {
  1957. $this->setEndpoint($endpoint);
  1958. $this->setup_url = $setup_url;
  1959. }
  1960. }