Consumer.php 77 KB

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