Server.php 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766
  1. <?php
  2. /**
  3. * OpenID server protocol and logic.
  4. *
  5. * Overview
  6. *
  7. * An OpenID server must perform three tasks:
  8. *
  9. * 1. Examine the incoming request to determine its nature and validity.
  10. * 2. Make a decision about how to respond to this request.
  11. * 3. Format the response according to the protocol.
  12. *
  13. * The first and last of these tasks may performed by the {@link
  14. * Auth_OpenID_Server::decodeRequest()} and {@link
  15. * Auth_OpenID_Server::encodeResponse} methods. Who gets to do the
  16. * intermediate task -- deciding how to respond to the request -- will
  17. * depend on what type of request it is.
  18. *
  19. * If it's a request to authenticate a user (a 'checkid_setup' or
  20. * 'checkid_immediate' request), you need to decide if you will assert
  21. * that this user may claim the identity in question. Exactly how you
  22. * do that is a matter of application policy, but it generally
  23. * involves making sure the user has an account with your system and
  24. * is logged in, checking to see if that identity is hers to claim,
  25. * and verifying with the user that she does consent to releasing that
  26. * information to the party making the request.
  27. *
  28. * Examine the properties of the {@link Auth_OpenID_CheckIDRequest}
  29. * object, and if and when you've come to a decision, form a response
  30. * by calling {@link Auth_OpenID_CheckIDRequest::answer()}.
  31. *
  32. * Other types of requests relate to establishing associations between
  33. * client and server and verifing the authenticity of previous
  34. * communications. {@link Auth_OpenID_Server} contains all the logic
  35. * and data necessary to respond to such requests; just pass it to
  36. * {@link Auth_OpenID_Server::handleRequest()}.
  37. *
  38. * OpenID Extensions
  39. *
  40. * Do you want to provide other information for your users in addition
  41. * to authentication? Version 1.2 of the OpenID protocol allows
  42. * consumers to add extensions to their requests. For example, with
  43. * sites using the Simple Registration
  44. * Extension
  45. * (http://openid.net/specs/openid-simple-registration-extension-1_0.html),
  46. * a user can agree to have their nickname and e-mail address sent to
  47. * a site when they sign up.
  48. *
  49. * Since extensions do not change the way OpenID authentication works,
  50. * code to handle extension requests may be completely separate from
  51. * the {@link Auth_OpenID_Request} class here. But you'll likely want
  52. * data sent back by your extension to be signed. {@link
  53. * Auth_OpenID_ServerResponse} provides methods with which you can add
  54. * data to it which can be signed with the other data in the OpenID
  55. * signature.
  56. *
  57. * For example:
  58. *
  59. * <pre> // when request is a checkid_* request
  60. * $response = $request->answer(true);
  61. * // this will a signed 'openid.sreg.timezone' parameter to the response
  62. * response.addField('sreg', 'timezone', 'America/Los_Angeles')</pre>
  63. *
  64. * Stores
  65. *
  66. * The OpenID server needs to maintain state between requests in order
  67. * to function. Its mechanism for doing this is called a store. The
  68. * store interface is defined in Interface.php. Additionally, several
  69. * concrete store implementations are provided, so that most sites
  70. * won't need to implement a custom store. For a store backed by flat
  71. * files on disk, see {@link Auth_OpenID_FileStore}. For stores based
  72. * on MySQL, SQLite, or PostgreSQL, see the {@link
  73. * Auth_OpenID_SQLStore} subclasses.
  74. *
  75. * Upgrading
  76. *
  77. * The keys by which a server looks up associations in its store have
  78. * changed in version 1.2 of this library. If your store has entries
  79. * created from version 1.0 code, you should empty it.
  80. *
  81. * PHP versions 4 and 5
  82. *
  83. * LICENSE: See the COPYING file included in this distribution.
  84. *
  85. * @package OpenID
  86. * @author JanRain, Inc. <openid@janrain.com>
  87. * @copyright 2005-2008 Janrain, Inc.
  88. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
  89. */
  90. /**
  91. * Required imports
  92. */
  93. require_once "Auth/OpenID.php";
  94. require_once "Auth/OpenID/Association.php";
  95. require_once "Auth/OpenID/CryptUtil.php";
  96. require_once "Auth/OpenID/BigMath.php";
  97. require_once "Auth/OpenID/DiffieHellman.php";
  98. require_once "Auth/OpenID/KVForm.php";
  99. require_once "Auth/OpenID/TrustRoot.php";
  100. require_once "Auth/OpenID/ServerRequest.php";
  101. require_once "Auth/OpenID/Message.php";
  102. require_once "Auth/OpenID/Nonce.php";
  103. define('AUTH_OPENID_HTTP_OK', 200);
  104. define('AUTH_OPENID_HTTP_REDIRECT', 302);
  105. define('AUTH_OPENID_HTTP_ERROR', 400);
  106. /**
  107. * @access private
  108. */
  109. global $_Auth_OpenID_Request_Modes;
  110. $_Auth_OpenID_Request_Modes = array('checkid_setup',
  111. 'checkid_immediate');
  112. /**
  113. * @access private
  114. */
  115. define('Auth_OpenID_ENCODE_KVFORM', 'kfvorm');
  116. /**
  117. * @access private
  118. */
  119. define('Auth_OpenID_ENCODE_URL', 'URL/redirect');
  120. /**
  121. * @access private
  122. */
  123. define('Auth_OpenID_ENCODE_HTML_FORM', 'HTML form');
  124. /**
  125. * @access private
  126. */
  127. function Auth_OpenID_isError($obj, $cls = 'Auth_OpenID_ServerError')
  128. {
  129. return is_a($obj, $cls);
  130. }
  131. /**
  132. * An error class which gets instantiated and returned whenever an
  133. * OpenID protocol error occurs. Be prepared to use this in place of
  134. * an ordinary server response.
  135. *
  136. * @package OpenID
  137. */
  138. class Auth_OpenID_ServerError {
  139. /**
  140. * @access private
  141. */
  142. function Auth_OpenID_ServerError($message = null, $text = null,
  143. $reference = null, $contact = null)
  144. {
  145. $this->message = $message;
  146. $this->text = $text;
  147. $this->contact = $contact;
  148. $this->reference = $reference;
  149. }
  150. function getReturnTo()
  151. {
  152. if ($this->message &&
  153. $this->message->hasKey(Auth_OpenID_OPENID_NS, 'return_to')) {
  154. return $this->message->getArg(Auth_OpenID_OPENID_NS,
  155. 'return_to');
  156. } else {
  157. return null;
  158. }
  159. }
  160. /**
  161. * Returns the return_to URL for the request which caused this
  162. * error.
  163. */
  164. function hasReturnTo()
  165. {
  166. return $this->getReturnTo() !== null;
  167. }
  168. /**
  169. * Encodes this error's response as a URL suitable for
  170. * redirection. If the response has no return_to, another
  171. * Auth_OpenID_ServerError is returned.
  172. */
  173. function encodeToURL()
  174. {
  175. if (!$this->message) {
  176. return null;
  177. }
  178. $msg = $this->toMessage();
  179. return $msg->toURL($this->getReturnTo());
  180. }
  181. /**
  182. * Encodes the response to key-value form. This is a
  183. * machine-readable format used to respond to messages which came
  184. * directly from the consumer and not through the user-agent. See
  185. * the OpenID specification.
  186. */
  187. function encodeToKVForm()
  188. {
  189. return Auth_OpenID_KVForm::fromArray(
  190. array('mode' => 'error',
  191. 'error' => $this->toString()));
  192. }
  193. function toFormMarkup($form_tag_attrs=null)
  194. {
  195. $msg = $this->toMessage();
  196. return $msg->toFormMarkup($this->getReturnTo(), $form_tag_attrs);
  197. }
  198. function toHTML($form_tag_attrs=null)
  199. {
  200. return Auth_OpenID::autoSubmitHTML(
  201. $this->toFormMarkup($form_tag_attrs));
  202. }
  203. function toMessage()
  204. {
  205. // Generate a Message object for sending to the relying party,
  206. // after encoding.
  207. $namespace = $this->message->getOpenIDNamespace();
  208. $reply = new Auth_OpenID_Message($namespace);
  209. $reply->setArg(Auth_OpenID_OPENID_NS, 'mode', 'error');
  210. $reply->setArg(Auth_OpenID_OPENID_NS, 'error', $this->toString());
  211. if ($this->contact !== null) {
  212. $reply->setArg(Auth_OpenID_OPENID_NS, 'contact', $this->contact);
  213. }
  214. if ($this->reference !== null) {
  215. $reply->setArg(Auth_OpenID_OPENID_NS, 'reference',
  216. $this->reference);
  217. }
  218. return $reply;
  219. }
  220. /**
  221. * Returns one of Auth_OpenID_ENCODE_URL,
  222. * Auth_OpenID_ENCODE_KVFORM, or null, depending on the type of
  223. * encoding expected for this error's payload.
  224. */
  225. function whichEncoding()
  226. {
  227. global $_Auth_OpenID_Request_Modes;
  228. if ($this->hasReturnTo()) {
  229. if ($this->message->isOpenID2() &&
  230. (strlen($this->encodeToURL()) >
  231. Auth_OpenID_OPENID1_URL_LIMIT)) {
  232. return Auth_OpenID_ENCODE_HTML_FORM;
  233. } else {
  234. return Auth_OpenID_ENCODE_URL;
  235. }
  236. }
  237. if (!$this->message) {
  238. return null;
  239. }
  240. $mode = $this->message->getArg(Auth_OpenID_OPENID_NS,
  241. 'mode');
  242. if ($mode) {
  243. if (!in_array($mode, $_Auth_OpenID_Request_Modes)) {
  244. return Auth_OpenID_ENCODE_KVFORM;
  245. }
  246. }
  247. return null;
  248. }
  249. /**
  250. * Returns this error message.
  251. */
  252. function toString()
  253. {
  254. if ($this->text) {
  255. return $this->text;
  256. } else {
  257. return get_class($this) . " error";
  258. }
  259. }
  260. }
  261. /**
  262. * Error returned by the server code when a return_to is absent from a
  263. * request.
  264. *
  265. * @package OpenID
  266. */
  267. class Auth_OpenID_NoReturnToError extends Auth_OpenID_ServerError {
  268. function Auth_OpenID_NoReturnToError($message = null,
  269. $text = "No return_to URL available")
  270. {
  271. parent::Auth_OpenID_ServerError($message, $text);
  272. }
  273. function toString()
  274. {
  275. return "No return_to available";
  276. }
  277. }
  278. /**
  279. * An error indicating that the return_to URL is malformed.
  280. *
  281. * @package OpenID
  282. */
  283. class Auth_OpenID_MalformedReturnURL extends Auth_OpenID_ServerError {
  284. function Auth_OpenID_MalformedReturnURL($message, $return_to)
  285. {
  286. $this->return_to = $return_to;
  287. parent::Auth_OpenID_ServerError($message, "malformed return_to URL");
  288. }
  289. }
  290. /**
  291. * This error is returned when the trust_root value is malformed.
  292. *
  293. * @package OpenID
  294. */
  295. class Auth_OpenID_MalformedTrustRoot extends Auth_OpenID_ServerError {
  296. function Auth_OpenID_MalformedTrustRoot($message = null,
  297. $text = "Malformed trust root")
  298. {
  299. parent::Auth_OpenID_ServerError($message, $text);
  300. }
  301. function toString()
  302. {
  303. return "Malformed trust root";
  304. }
  305. }
  306. /**
  307. * The base class for all server request classes.
  308. *
  309. * @package OpenID
  310. */
  311. class Auth_OpenID_Request {
  312. var $mode = null;
  313. }
  314. /**
  315. * A request to verify the validity of a previous response.
  316. *
  317. * @package OpenID
  318. */
  319. class Auth_OpenID_CheckAuthRequest extends Auth_OpenID_Request {
  320. var $mode = "check_authentication";
  321. var $invalidate_handle = null;
  322. function Auth_OpenID_CheckAuthRequest($assoc_handle, $signed,
  323. $invalidate_handle = null)
  324. {
  325. $this->assoc_handle = $assoc_handle;
  326. $this->signed = $signed;
  327. if ($invalidate_handle !== null) {
  328. $this->invalidate_handle = $invalidate_handle;
  329. }
  330. $this->namespace = Auth_OpenID_OPENID2_NS;
  331. $this->message = null;
  332. }
  333. static function fromMessage($message, $server=null)
  334. {
  335. $required_keys = array('assoc_handle', 'sig', 'signed');
  336. foreach ($required_keys as $k) {
  337. if (!$message->getArg(Auth_OpenID_OPENID_NS, $k)) {
  338. return new Auth_OpenID_ServerError($message,
  339. sprintf("%s request missing required parameter %s from \
  340. query", "check_authentication", $k));
  341. }
  342. }
  343. $assoc_handle = $message->getArg(Auth_OpenID_OPENID_NS, 'assoc_handle');
  344. $sig = $message->getArg(Auth_OpenID_OPENID_NS, 'sig');
  345. $signed_list = $message->getArg(Auth_OpenID_OPENID_NS, 'signed');
  346. $signed_list = explode(",", $signed_list);
  347. $signed = $message;
  348. if ($signed->hasKey(Auth_OpenID_OPENID_NS, 'mode')) {
  349. $signed->setArg(Auth_OpenID_OPENID_NS, 'mode', 'id_res');
  350. }
  351. $result = new Auth_OpenID_CheckAuthRequest($assoc_handle, $signed);
  352. $result->message = $message;
  353. $result->sig = $sig;
  354. $result->invalidate_handle = $message->getArg(Auth_OpenID_OPENID_NS,
  355. 'invalidate_handle');
  356. return $result;
  357. }
  358. function answer($signatory)
  359. {
  360. $is_valid = $signatory->verify($this->assoc_handle, $this->signed);
  361. // Now invalidate that assoc_handle so it this checkAuth
  362. // message cannot be replayed.
  363. $signatory->invalidate($this->assoc_handle, true);
  364. $response = new Auth_OpenID_ServerResponse($this);
  365. $response->fields->setArg(Auth_OpenID_OPENID_NS,
  366. 'is_valid',
  367. ($is_valid ? "true" : "false"));
  368. if ($this->invalidate_handle) {
  369. $assoc = $signatory->getAssociation($this->invalidate_handle,
  370. false);
  371. if (!$assoc) {
  372. $response->fields->setArg(Auth_OpenID_OPENID_NS,
  373. 'invalidate_handle',
  374. $this->invalidate_handle);
  375. }
  376. }
  377. return $response;
  378. }
  379. }
  380. /**
  381. * A class implementing plaintext server sessions.
  382. *
  383. * @package OpenID
  384. */
  385. class Auth_OpenID_PlainTextServerSession {
  386. /**
  387. * An object that knows how to handle association requests with no
  388. * session type.
  389. */
  390. var $session_type = 'no-encryption';
  391. var $needs_math = false;
  392. var $allowed_assoc_types = array('HMAC-SHA1', 'HMAC-SHA256');
  393. static function fromMessage($unused_request)
  394. {
  395. return new Auth_OpenID_PlainTextServerSession();
  396. }
  397. function answer($secret)
  398. {
  399. return array('mac_key' => base64_encode($secret));
  400. }
  401. }
  402. /**
  403. * A class implementing DH-SHA1 server sessions.
  404. *
  405. * @package OpenID
  406. */
  407. class Auth_OpenID_DiffieHellmanSHA1ServerSession {
  408. /**
  409. * An object that knows how to handle association requests with
  410. * the Diffie-Hellman session type.
  411. */
  412. var $session_type = 'DH-SHA1';
  413. var $needs_math = true;
  414. var $allowed_assoc_types = array('HMAC-SHA1');
  415. var $hash_func = 'Auth_OpenID_SHA1';
  416. function Auth_OpenID_DiffieHellmanSHA1ServerSession($dh, $consumer_pubkey)
  417. {
  418. $this->dh = $dh;
  419. $this->consumer_pubkey = $consumer_pubkey;
  420. }
  421. static function getDH($message)
  422. {
  423. $dh_modulus = $message->getArg(Auth_OpenID_OPENID_NS, 'dh_modulus');
  424. $dh_gen = $message->getArg(Auth_OpenID_OPENID_NS, 'dh_gen');
  425. if ((($dh_modulus === null) && ($dh_gen !== null)) ||
  426. (($dh_gen === null) && ($dh_modulus !== null))) {
  427. if ($dh_modulus === null) {
  428. $missing = 'modulus';
  429. } else {
  430. $missing = 'generator';
  431. }
  432. return new Auth_OpenID_ServerError($message,
  433. 'If non-default modulus or generator is '.
  434. 'supplied, both must be supplied. Missing '.
  435. $missing);
  436. }
  437. $lib = Auth_OpenID_getMathLib();
  438. if ($dh_modulus || $dh_gen) {
  439. $dh_modulus = $lib->base64ToLong($dh_modulus);
  440. $dh_gen = $lib->base64ToLong($dh_gen);
  441. if ($lib->cmp($dh_modulus, 0) == 0 ||
  442. $lib->cmp($dh_gen, 0) == 0) {
  443. return new Auth_OpenID_ServerError(
  444. $message, "Failed to parse dh_mod or dh_gen");
  445. }
  446. $dh = new Auth_OpenID_DiffieHellman($dh_modulus, $dh_gen);
  447. } else {
  448. $dh = new Auth_OpenID_DiffieHellman();
  449. }
  450. $consumer_pubkey = $message->getArg(Auth_OpenID_OPENID_NS,
  451. 'dh_consumer_public');
  452. if ($consumer_pubkey === null) {
  453. return new Auth_OpenID_ServerError($message,
  454. 'Public key for DH-SHA1 session '.
  455. 'not found in query');
  456. }
  457. $consumer_pubkey =
  458. $lib->base64ToLong($consumer_pubkey);
  459. if ($consumer_pubkey === false) {
  460. return new Auth_OpenID_ServerError($message,
  461. "dh_consumer_public is not base64");
  462. }
  463. return array($dh, $consumer_pubkey);
  464. }
  465. static function fromMessage($message)
  466. {
  467. $result = Auth_OpenID_DiffieHellmanSHA1ServerSession::getDH($message);
  468. if (is_a($result, 'Auth_OpenID_ServerError')) {
  469. return $result;
  470. } else {
  471. list($dh, $consumer_pubkey) = $result;
  472. return new Auth_OpenID_DiffieHellmanSHA1ServerSession($dh,
  473. $consumer_pubkey);
  474. }
  475. }
  476. function answer($secret)
  477. {
  478. $lib = Auth_OpenID_getMathLib();
  479. $mac_key = $this->dh->xorSecret($this->consumer_pubkey, $secret,
  480. $this->hash_func);
  481. return array(
  482. 'dh_server_public' =>
  483. $lib->longToBase64($this->dh->public),
  484. 'enc_mac_key' => base64_encode($mac_key));
  485. }
  486. }
  487. /**
  488. * A class implementing DH-SHA256 server sessions.
  489. *
  490. * @package OpenID
  491. */
  492. class Auth_OpenID_DiffieHellmanSHA256ServerSession
  493. extends Auth_OpenID_DiffieHellmanSHA1ServerSession {
  494. var $session_type = 'DH-SHA256';
  495. var $hash_func = 'Auth_OpenID_SHA256';
  496. var $allowed_assoc_types = array('HMAC-SHA256');
  497. static function fromMessage($message)
  498. {
  499. $result = Auth_OpenID_DiffieHellmanSHA1ServerSession::getDH($message);
  500. if (is_a($result, 'Auth_OpenID_ServerError')) {
  501. return $result;
  502. } else {
  503. list($dh, $consumer_pubkey) = $result;
  504. return new Auth_OpenID_DiffieHellmanSHA256ServerSession($dh,
  505. $consumer_pubkey);
  506. }
  507. }
  508. }
  509. /**
  510. * A request to associate with the server.
  511. *
  512. * @package OpenID
  513. */
  514. class Auth_OpenID_AssociateRequest extends Auth_OpenID_Request {
  515. var $mode = "associate";
  516. static function getSessionClasses()
  517. {
  518. return array(
  519. 'no-encryption' => 'Auth_OpenID_PlainTextServerSession',
  520. 'DH-SHA1' => 'Auth_OpenID_DiffieHellmanSHA1ServerSession',
  521. 'DH-SHA256' => 'Auth_OpenID_DiffieHellmanSHA256ServerSession');
  522. }
  523. function Auth_OpenID_AssociateRequest($session, $assoc_type)
  524. {
  525. $this->session = $session;
  526. $this->namespace = Auth_OpenID_OPENID2_NS;
  527. $this->assoc_type = $assoc_type;
  528. }
  529. static function fromMessage($message, $server=null)
  530. {
  531. if ($message->isOpenID1()) {
  532. $session_type = $message->getArg(Auth_OpenID_OPENID_NS,
  533. 'session_type');
  534. if ($session_type == 'no-encryption') {
  535. // oidutil.log('Received OpenID 1 request with a no-encryption '
  536. // 'assocaition session type. Continuing anyway.')
  537. } else if (!$session_type) {
  538. $session_type = 'no-encryption';
  539. }
  540. } else {
  541. $session_type = $message->getArg(Auth_OpenID_OPENID_NS,
  542. 'session_type');
  543. if ($session_type === null) {
  544. return new Auth_OpenID_ServerError($message,
  545. "session_type missing from request");
  546. }
  547. }
  548. $session_class = Auth_OpenID::arrayGet(
  549. Auth_OpenID_AssociateRequest::getSessionClasses(),
  550. $session_type);
  551. if ($session_class === null) {
  552. return new Auth_OpenID_ServerError($message,
  553. "Unknown session type " .
  554. $session_type);
  555. }
  556. $session = call_user_func(array($session_class, 'fromMessage'),
  557. $message);
  558. if (is_a($session, 'Auth_OpenID_ServerError')) {
  559. return $session;
  560. }
  561. $assoc_type = $message->getArg(Auth_OpenID_OPENID_NS,
  562. 'assoc_type', 'HMAC-SHA1');
  563. if (!in_array($assoc_type, $session->allowed_assoc_types)) {
  564. $fmt = "Session type %s does not support association type %s";
  565. return new Auth_OpenID_ServerError($message,
  566. sprintf($fmt, $session_type, $assoc_type));
  567. }
  568. $obj = new Auth_OpenID_AssociateRequest($session, $assoc_type);
  569. $obj->message = $message;
  570. $obj->namespace = $message->getOpenIDNamespace();
  571. return $obj;
  572. }
  573. function answer($assoc)
  574. {
  575. $response = new Auth_OpenID_ServerResponse($this);
  576. $response->fields->updateArgs(Auth_OpenID_OPENID_NS,
  577. array(
  578. 'expires_in' => sprintf('%d', $assoc->getExpiresIn()),
  579. 'assoc_type' => $this->assoc_type,
  580. 'assoc_handle' => $assoc->handle));
  581. $response->fields->updateArgs(Auth_OpenID_OPENID_NS,
  582. $this->session->answer($assoc->secret));
  583. if (! ($this->session->session_type == 'no-encryption'
  584. && $this->message->isOpenID1())) {
  585. $response->fields->setArg(Auth_OpenID_OPENID_NS,
  586. 'session_type',
  587. $this->session->session_type);
  588. }
  589. return $response;
  590. }
  591. function answerUnsupported($text_message,
  592. $preferred_association_type=null,
  593. $preferred_session_type=null)
  594. {
  595. if ($this->message->isOpenID1()) {
  596. return new Auth_OpenID_ServerError($this->message);
  597. }
  598. $response = new Auth_OpenID_ServerResponse($this);
  599. $response->fields->setArg(Auth_OpenID_OPENID_NS,
  600. 'error_code', 'unsupported-type');
  601. $response->fields->setArg(Auth_OpenID_OPENID_NS,
  602. 'error', $text_message);
  603. if ($preferred_association_type) {
  604. $response->fields->setArg(Auth_OpenID_OPENID_NS,
  605. 'assoc_type',
  606. $preferred_association_type);
  607. }
  608. if ($preferred_session_type) {
  609. $response->fields->setArg(Auth_OpenID_OPENID_NS,
  610. 'session_type',
  611. $preferred_session_type);
  612. }
  613. $response->code = AUTH_OPENID_HTTP_ERROR;
  614. return $response;
  615. }
  616. }
  617. /**
  618. * A request to confirm the identity of a user.
  619. *
  620. * @package OpenID
  621. */
  622. class Auth_OpenID_CheckIDRequest extends Auth_OpenID_Request {
  623. /**
  624. * Return-to verification callback. Default is
  625. * Auth_OpenID_verifyReturnTo from TrustRoot.php.
  626. */
  627. var $verifyReturnTo = 'Auth_OpenID_verifyReturnTo';
  628. /**
  629. * The mode of this request.
  630. */
  631. var $mode = "checkid_setup"; // or "checkid_immediate"
  632. /**
  633. * Whether this request is for immediate mode.
  634. */
  635. var $immediate = false;
  636. /**
  637. * The trust_root value for this request.
  638. */
  639. var $trust_root = null;
  640. /**
  641. * The OpenID namespace for this request.
  642. * deprecated since version 2.0.2
  643. */
  644. var $namespace;
  645. static function make($message, $identity, $return_to, $trust_root = null,
  646. $immediate = false, $assoc_handle = null, $server = null)
  647. {
  648. if ($server === null) {
  649. return new Auth_OpenID_ServerError($message,
  650. "server must not be null");
  651. }
  652. if ($return_to &&
  653. !Auth_OpenID_TrustRoot::_parse($return_to)) {
  654. return new Auth_OpenID_MalformedReturnURL($message, $return_to);
  655. }
  656. $r = new Auth_OpenID_CheckIDRequest($identity, $return_to,
  657. $trust_root, $immediate,
  658. $assoc_handle, $server);
  659. $r->namespace = $message->getOpenIDNamespace();
  660. $r->message = $message;
  661. if (!$r->trustRootValid()) {
  662. return new Auth_OpenID_UntrustedReturnURL($message,
  663. $return_to,
  664. $trust_root);
  665. } else {
  666. return $r;
  667. }
  668. }
  669. function Auth_OpenID_CheckIDRequest($identity, $return_to,
  670. $trust_root = null, $immediate = false,
  671. $assoc_handle = null, $server = null,
  672. $claimed_id = null)
  673. {
  674. $this->namespace = Auth_OpenID_OPENID2_NS;
  675. $this->assoc_handle = $assoc_handle;
  676. $this->identity = $identity;
  677. if ($claimed_id === null) {
  678. $this->claimed_id = $identity;
  679. } else {
  680. $this->claimed_id = $claimed_id;
  681. }
  682. $this->return_to = $return_to;
  683. $this->trust_root = $trust_root;
  684. $this->server = $server;
  685. if ($immediate) {
  686. $this->immediate = true;
  687. $this->mode = "checkid_immediate";
  688. } else {
  689. $this->immediate = false;
  690. $this->mode = "checkid_setup";
  691. }
  692. }
  693. function equals($other)
  694. {
  695. return (
  696. (is_a($other, 'Auth_OpenID_CheckIDRequest')) &&
  697. ($this->namespace == $other->namespace) &&
  698. ($this->assoc_handle == $other->assoc_handle) &&
  699. ($this->identity == $other->identity) &&
  700. ($this->claimed_id == $other->claimed_id) &&
  701. ($this->return_to == $other->return_to) &&
  702. ($this->trust_root == $other->trust_root));
  703. }
  704. /*
  705. * Does the relying party publish the return_to URL for this
  706. * response under the realm? It is up to the provider to set a
  707. * policy for what kinds of realms should be allowed. This
  708. * return_to URL verification reduces vulnerability to data-theft
  709. * attacks based on open proxies, corss-site-scripting, or open
  710. * redirectors.
  711. *
  712. * This check should only be performed after making sure that the
  713. * return_to URL matches the realm.
  714. *
  715. * @return true if the realm publishes a document with the
  716. * return_to URL listed, false if not or if discovery fails
  717. */
  718. function returnToVerified()
  719. {
  720. $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
  721. return call_user_func_array($this->verifyReturnTo,
  722. array($this->trust_root, $this->return_to, $fetcher));
  723. }
  724. static function fromMessage($message, $server)
  725. {
  726. $mode = $message->getArg(Auth_OpenID_OPENID_NS, 'mode');
  727. $immediate = null;
  728. if ($mode == "checkid_immediate") {
  729. $immediate = true;
  730. $mode = "checkid_immediate";
  731. } else {
  732. $immediate = false;
  733. $mode = "checkid_setup";
  734. }
  735. $return_to = $message->getArg(Auth_OpenID_OPENID_NS,
  736. 'return_to');
  737. if (($message->isOpenID1()) &&
  738. (!$return_to)) {
  739. $fmt = "Missing required field 'return_to' from checkid request";
  740. return new Auth_OpenID_ServerError($message, $fmt);
  741. }
  742. $identity = $message->getArg(Auth_OpenID_OPENID_NS,
  743. 'identity');
  744. $claimed_id = $message->getArg(Auth_OpenID_OPENID_NS, 'claimed_id');
  745. if ($message->isOpenID1()) {
  746. if ($identity === null) {
  747. $s = "OpenID 1 message did not contain openid.identity";
  748. return new Auth_OpenID_ServerError($message, $s);
  749. }
  750. } else {
  751. if ($identity && !$claimed_id) {
  752. $s = "OpenID 2.0 message contained openid.identity but not " .
  753. "claimed_id";
  754. return new Auth_OpenID_ServerError($message, $s);
  755. } else if ($claimed_id && !$identity) {
  756. $s = "OpenID 2.0 message contained openid.claimed_id " .
  757. "but not identity";
  758. return new Auth_OpenID_ServerError($message, $s);
  759. }
  760. }
  761. // There's a case for making self.trust_root be a TrustRoot
  762. // here. But if TrustRoot isn't currently part of the
  763. // "public" API, I'm not sure it's worth doing.
  764. if ($message->isOpenID1()) {
  765. $trust_root_param = 'trust_root';
  766. } else {
  767. $trust_root_param = 'realm';
  768. }
  769. $trust_root = $message->getArg(Auth_OpenID_OPENID_NS,
  770. $trust_root_param);
  771. if (! $trust_root) {
  772. $trust_root = $return_to;
  773. }
  774. if (! $message->isOpenID1() &&
  775. ($return_to === null) &&
  776. ($trust_root === null)) {
  777. return new Auth_OpenID_ServerError($message,
  778. "openid.realm required when openid.return_to absent");
  779. }
  780. $assoc_handle = $message->getArg(Auth_OpenID_OPENID_NS,
  781. 'assoc_handle');
  782. $obj = Auth_OpenID_CheckIDRequest::make($message,
  783. $identity,
  784. $return_to,
  785. $trust_root,
  786. $immediate,
  787. $assoc_handle,
  788. $server);
  789. if (is_a($obj, 'Auth_OpenID_ServerError')) {
  790. return $obj;
  791. }
  792. $obj->claimed_id = $claimed_id;
  793. return $obj;
  794. }
  795. function idSelect()
  796. {
  797. // Is the identifier to be selected by the IDP?
  798. // So IDPs don't have to import the constant
  799. return $this->identity == Auth_OpenID_IDENTIFIER_SELECT;
  800. }
  801. function trustRootValid()
  802. {
  803. if (!$this->trust_root) {
  804. return true;
  805. }
  806. $tr = Auth_OpenID_TrustRoot::_parse($this->trust_root);
  807. if ($tr === false) {
  808. return new Auth_OpenID_MalformedTrustRoot($this->message,
  809. $this->trust_root);
  810. }
  811. if ($this->return_to !== null) {
  812. return Auth_OpenID_TrustRoot::match($this->trust_root,
  813. $this->return_to);
  814. } else {
  815. return true;
  816. }
  817. }
  818. /**
  819. * Respond to this request. Return either an
  820. * {@link Auth_OpenID_ServerResponse} or
  821. * {@link Auth_OpenID_ServerError}.
  822. *
  823. * @param bool $allow Allow this user to claim this identity, and
  824. * allow the consumer to have this information?
  825. *
  826. * @param string $server_url DEPRECATED. Passing $op_endpoint to
  827. * the {@link Auth_OpenID_Server} constructor makes this optional.
  828. *
  829. * When an OpenID 1.x immediate mode request does not succeed, it
  830. * gets back a URL where the request may be carried out in a
  831. * not-so-immediate fashion. Pass my URL in here (the fully
  832. * qualified address of this server's endpoint, i.e.
  833. * http://example.com/server), and I will use it as a base for the
  834. * URL for a new request.
  835. *
  836. * Optional for requests where {@link $immediate} is false or
  837. * $allow is true.
  838. *
  839. * @param string $identity The OP-local identifier to answer with.
  840. * Only for use when the relying party requested identifier
  841. * selection.
  842. *
  843. * @param string $claimed_id The claimed identifier to answer
  844. * with, for use with identifier selection in the case where the
  845. * claimed identifier and the OP-local identifier differ,
  846. * i.e. when the claimed_id uses delegation.
  847. *
  848. * If $identity is provided but this is not, $claimed_id will
  849. * default to the value of $identity. When answering requests
  850. * that did not ask for identifier selection, the response
  851. * $claimed_id will default to that of the request.
  852. *
  853. * This parameter is new in OpenID 2.0.
  854. *
  855. * @return mixed
  856. */
  857. function answer($allow, $server_url = null, $identity = null,
  858. $claimed_id = null)
  859. {
  860. if (!$this->return_to) {
  861. return new Auth_OpenID_NoReturnToError();
  862. }
  863. if (!$server_url) {
  864. if ((!$this->message->isOpenID1()) &&
  865. (!$this->server->op_endpoint)) {
  866. return new Auth_OpenID_ServerError(null,
  867. "server should be constructed with op_endpoint to " .
  868. "respond to OpenID 2.0 messages.");
  869. }
  870. $server_url = $this->server->op_endpoint;
  871. }
  872. if ($allow) {
  873. $mode = 'id_res';
  874. } else if ($this->message->isOpenID1()) {
  875. if ($this->immediate) {
  876. $mode = 'id_res';
  877. } else {
  878. $mode = 'cancel';
  879. }
  880. } else {
  881. if ($this->immediate) {
  882. $mode = 'setup_needed';
  883. } else {
  884. $mode = 'cancel';
  885. }
  886. }
  887. if (!$this->trustRootValid()) {
  888. return new Auth_OpenID_UntrustedReturnURL(null,
  889. $this->return_to,
  890. $this->trust_root);
  891. }
  892. $response = new Auth_OpenID_ServerResponse($this);
  893. if ($claimed_id &&
  894. ($this->message->isOpenID1())) {
  895. return new Auth_OpenID_ServerError(null,
  896. "claimed_id is new in OpenID 2.0 and not " .
  897. "available for ".$this->namespace);
  898. }
  899. if ($identity && !$claimed_id) {
  900. $claimed_id = $identity;
  901. }
  902. if ($allow) {
  903. if ($this->identity == Auth_OpenID_IDENTIFIER_SELECT) {
  904. if (!$identity) {
  905. return new Auth_OpenID_ServerError(null,
  906. "This request uses IdP-driven identifier selection. " .
  907. "You must supply an identifier in the response.");
  908. }
  909. $response_identity = $identity;
  910. $response_claimed_id = $claimed_id;
  911. } else if ($this->identity) {
  912. if ($identity &&
  913. ($this->identity != $identity)) {
  914. $fmt = "Request was for %s, cannot reply with identity %s";
  915. return new Auth_OpenID_ServerError(null,
  916. sprintf($fmt, $this->identity, $identity));
  917. }
  918. $response_identity = $this->identity;
  919. $response_claimed_id = $this->claimed_id;
  920. } else {
  921. if ($identity) {
  922. return new Auth_OpenID_ServerError(null,
  923. "This request specified no identity and " .
  924. "you supplied ".$identity);
  925. }
  926. $response_identity = null;
  927. }
  928. if (($this->message->isOpenID1()) &&
  929. ($response_identity === null)) {
  930. return new Auth_OpenID_ServerError(null,
  931. "Request was an OpenID 1 request, so response must " .
  932. "include an identifier.");
  933. }
  934. $response->fields->updateArgs(Auth_OpenID_OPENID_NS,
  935. array('mode' => $mode,
  936. 'return_to' => $this->return_to,
  937. 'response_nonce' => Auth_OpenID_mkNonce()));
  938. if (!$this->message->isOpenID1()) {
  939. $response->fields->setArg(Auth_OpenID_OPENID_NS,
  940. 'op_endpoint', $server_url);
  941. }
  942. if ($response_identity !== null) {
  943. $response->fields->setArg(
  944. Auth_OpenID_OPENID_NS,
  945. 'identity',
  946. $response_identity);
  947. if ($this->message->isOpenID2()) {
  948. $response->fields->setArg(
  949. Auth_OpenID_OPENID_NS,
  950. 'claimed_id',
  951. $response_claimed_id);
  952. }
  953. }
  954. } else {
  955. $response->fields->setArg(Auth_OpenID_OPENID_NS,
  956. 'mode', $mode);
  957. if ($this->immediate) {
  958. if (($this->message->isOpenID1()) &&
  959. (!$server_url)) {
  960. return new Auth_OpenID_ServerError(null,
  961. 'setup_url is required for $allow=false \
  962. in OpenID 1.x immediate mode.');
  963. }
  964. $setup_request = new Auth_OpenID_CheckIDRequest(
  965. $this->identity,
  966. $this->return_to,
  967. $this->trust_root,
  968. false,
  969. $this->assoc_handle,
  970. $this->server,
  971. $this->claimed_id);
  972. $setup_request->message = $this->message;
  973. $setup_url = $setup_request->encodeToURL($server_url);
  974. if ($setup_url === null) {
  975. return new Auth_OpenID_NoReturnToError();
  976. }
  977. $response->fields->setArg(Auth_OpenID_OPENID_NS,
  978. 'user_setup_url',
  979. $setup_url);
  980. }
  981. }
  982. return $response;
  983. }
  984. function encodeToURL($server_url)
  985. {
  986. if (!$this->return_to) {
  987. return new Auth_OpenID_NoReturnToError();
  988. }
  989. // Imported from the alternate reality where these classes are
  990. // used in both the client and server code, so Requests are
  991. // Encodable too. That's right, code imported from alternate
  992. // realities all for the love of you, id_res/user_setup_url.
  993. $q = array('mode' => $this->mode,
  994. 'identity' => $this->identity,
  995. 'claimed_id' => $this->claimed_id,
  996. 'return_to' => $this->return_to);
  997. if ($this->trust_root) {
  998. if ($this->message->isOpenID1()) {
  999. $q['trust_root'] = $this->trust_root;
  1000. } else {
  1001. $q['realm'] = $this->trust_root;
  1002. }
  1003. }
  1004. if ($this->assoc_handle) {
  1005. $q['assoc_handle'] = $this->assoc_handle;
  1006. }
  1007. $response = new Auth_OpenID_Message(
  1008. $this->message->getOpenIDNamespace());
  1009. $response->updateArgs(Auth_OpenID_OPENID_NS, $q);
  1010. return $response->toURL($server_url);
  1011. }
  1012. function getCancelURL()
  1013. {
  1014. if (!$this->return_to) {
  1015. return new Auth_OpenID_NoReturnToError();
  1016. }
  1017. if ($this->immediate) {
  1018. return new Auth_OpenID_ServerError(null,
  1019. "Cancel is not an appropriate \
  1020. response to immediate mode \
  1021. requests.");
  1022. }
  1023. $response = new Auth_OpenID_Message(
  1024. $this->message->getOpenIDNamespace());
  1025. $response->setArg(Auth_OpenID_OPENID_NS, 'mode', 'cancel');
  1026. return $response->toURL($this->return_to);
  1027. }
  1028. }
  1029. /**
  1030. * This class encapsulates the response to an OpenID server request.
  1031. *
  1032. * @package OpenID
  1033. */
  1034. class Auth_OpenID_ServerResponse {
  1035. function Auth_OpenID_ServerResponse($request)
  1036. {
  1037. $this->request = $request;
  1038. $this->fields = new Auth_OpenID_Message($this->request->namespace);
  1039. }
  1040. function whichEncoding()
  1041. {
  1042. global $_Auth_OpenID_Request_Modes;
  1043. if (in_array($this->request->mode, $_Auth_OpenID_Request_Modes)) {
  1044. if ($this->fields->isOpenID2() &&
  1045. (strlen($this->encodeToURL()) >
  1046. Auth_OpenID_OPENID1_URL_LIMIT)) {
  1047. return Auth_OpenID_ENCODE_HTML_FORM;
  1048. } else {
  1049. return Auth_OpenID_ENCODE_URL;
  1050. }
  1051. } else {
  1052. return Auth_OpenID_ENCODE_KVFORM;
  1053. }
  1054. }
  1055. /*
  1056. * Returns the form markup for this response.
  1057. *
  1058. * @return str
  1059. */
  1060. function toFormMarkup($form_tag_attrs=null)
  1061. {
  1062. return $this->fields->toFormMarkup($this->request->return_to,
  1063. $form_tag_attrs);
  1064. }
  1065. /*
  1066. * Returns an HTML document containing the form markup for this
  1067. * response that autosubmits with javascript.
  1068. */
  1069. function toHTML()
  1070. {
  1071. return Auth_OpenID::autoSubmitHTML($this->toFormMarkup());
  1072. }
  1073. /*
  1074. * Returns True if this response's encoding is ENCODE_HTML_FORM.
  1075. * Convenience method for server authors.
  1076. *
  1077. * @return bool
  1078. */
  1079. function renderAsForm()
  1080. {
  1081. return $this->whichEncoding() == Auth_OpenID_ENCODE_HTML_FORM;
  1082. }
  1083. function encodeToURL()
  1084. {
  1085. return $this->fields->toURL($this->request->return_to);
  1086. }
  1087. function addExtension($extension_response)
  1088. {
  1089. $extension_response->toMessage($this->fields);
  1090. }
  1091. function needsSigning()
  1092. {
  1093. return $this->fields->getArg(Auth_OpenID_OPENID_NS,
  1094. 'mode') == 'id_res';
  1095. }
  1096. function encodeToKVForm()
  1097. {
  1098. return $this->fields->toKVForm();
  1099. }
  1100. }
  1101. /**
  1102. * A web-capable response object which you can use to generate a
  1103. * user-agent response.
  1104. *
  1105. * @package OpenID
  1106. */
  1107. class Auth_OpenID_WebResponse {
  1108. var $code = AUTH_OPENID_HTTP_OK;
  1109. var $body = "";
  1110. function Auth_OpenID_WebResponse($code = null, $headers = null,
  1111. $body = null)
  1112. {
  1113. if ($code) {
  1114. $this->code = $code;
  1115. }
  1116. if ($headers !== null) {
  1117. $this->headers = $headers;
  1118. } else {
  1119. $this->headers = array();
  1120. }
  1121. if ($body !== null) {
  1122. $this->body = $body;
  1123. }
  1124. }
  1125. }
  1126. /**
  1127. * Responsible for the signature of query data and the verification of
  1128. * OpenID signature values.
  1129. *
  1130. * @package OpenID
  1131. */
  1132. class Auth_OpenID_Signatory {
  1133. // = 14 * 24 * 60 * 60; # 14 days, in seconds
  1134. var $SECRET_LIFETIME = 1209600;
  1135. // keys have a bogus server URL in them because the filestore
  1136. // really does expect that key to be a URL. This seems a little
  1137. // silly for the server store, since I expect there to be only one
  1138. // server URL.
  1139. var $normal_key = 'http://localhost/|normal';
  1140. var $dumb_key = 'http://localhost/|dumb';
  1141. /**
  1142. * Create a new signatory using a given store.
  1143. */
  1144. function Auth_OpenID_Signatory($store)
  1145. {
  1146. // assert store is not None
  1147. $this->store = $store;
  1148. }
  1149. /**
  1150. * Verify, using a given association handle, a signature with
  1151. * signed key-value pairs from an HTTP request.
  1152. */
  1153. function verify($assoc_handle, $message)
  1154. {
  1155. $assoc = $this->getAssociation($assoc_handle, true);
  1156. if (!$assoc) {
  1157. // oidutil.log("failed to get assoc with handle %r to verify sig %r"
  1158. // % (assoc_handle, sig))
  1159. return false;
  1160. }
  1161. return $assoc->checkMessageSignature($message);
  1162. }
  1163. /**
  1164. * Given a response, sign the fields in the response's 'signed'
  1165. * list, and insert the signature into the response.
  1166. */
  1167. function sign($response)
  1168. {
  1169. $signed_response = $response;
  1170. $assoc_handle = $response->request->assoc_handle;
  1171. if ($assoc_handle) {
  1172. // normal mode
  1173. $assoc = $this->getAssociation($assoc_handle, false, false);
  1174. if (!$assoc || ($assoc->getExpiresIn() <= 0)) {
  1175. // fall back to dumb mode
  1176. $signed_response->fields->setArg(Auth_OpenID_OPENID_NS,
  1177. 'invalidate_handle', $assoc_handle);
  1178. $assoc_type = ($assoc ? $assoc->assoc_type : 'HMAC-SHA1');
  1179. if ($assoc && ($assoc->getExpiresIn() <= 0)) {
  1180. $this->invalidate($assoc_handle, false);
  1181. }
  1182. $assoc = $this->createAssociation(true, $assoc_type);
  1183. }
  1184. } else {
  1185. // dumb mode.
  1186. $assoc = $this->createAssociation(true);
  1187. }
  1188. $signed_response->fields = $assoc->signMessage(
  1189. $signed_response->fields);
  1190. return $signed_response;
  1191. }
  1192. /**
  1193. * Make a new association.
  1194. */
  1195. function createAssociation($dumb = true, $assoc_type = 'HMAC-SHA1')
  1196. {
  1197. $secret = Auth_OpenID_CryptUtil::getBytes(
  1198. Auth_OpenID_getSecretSize($assoc_type));
  1199. $uniq = base64_encode(Auth_OpenID_CryptUtil::getBytes(4));
  1200. $handle = sprintf('{%s}{%x}{%s}', $assoc_type, intval(time()), $uniq);
  1201. $assoc = Auth_OpenID_Association::fromExpiresIn(
  1202. $this->SECRET_LIFETIME, $handle, $secret, $assoc_type);
  1203. if ($dumb) {
  1204. $key = $this->dumb_key;
  1205. } else {
  1206. $key = $this->normal_key;
  1207. }
  1208. $this->store->storeAssociation($key, $assoc);
  1209. return $assoc;
  1210. }
  1211. /**
  1212. * Given an association handle, get the association from the
  1213. * store, or return a ServerError or null if something goes wrong.
  1214. */
  1215. function getAssociation($assoc_handle, $dumb, $check_expiration=true)
  1216. {
  1217. if ($assoc_handle === null) {
  1218. return new Auth_OpenID_ServerError(null,
  1219. "assoc_handle must not be null");
  1220. }
  1221. if ($dumb) {
  1222. $key = $this->dumb_key;
  1223. } else {
  1224. $key = $this->normal_key;
  1225. }
  1226. $assoc = $this->store->getAssociation($key, $assoc_handle);
  1227. if (($assoc !== null) && ($assoc->getExpiresIn() <= 0)) {
  1228. if ($check_expiration) {
  1229. $this->store->removeAssociation($key, $assoc_handle);
  1230. $assoc = null;
  1231. }
  1232. }
  1233. return $assoc;
  1234. }
  1235. /**
  1236. * Invalidate a given association handle.
  1237. */
  1238. function invalidate($assoc_handle, $dumb)
  1239. {
  1240. if ($dumb) {
  1241. $key = $this->dumb_key;
  1242. } else {
  1243. $key = $this->normal_key;
  1244. }
  1245. $this->store->removeAssociation($key, $assoc_handle);
  1246. }
  1247. }
  1248. /**
  1249. * Encode an {@link Auth_OpenID_ServerResponse} to an
  1250. * {@link Auth_OpenID_WebResponse}.
  1251. *
  1252. * @package OpenID
  1253. */
  1254. class Auth_OpenID_Encoder {
  1255. var $responseFactory = 'Auth_OpenID_WebResponse';
  1256. /**
  1257. * Encode an {@link Auth_OpenID_ServerResponse} and return an
  1258. * {@link Auth_OpenID_WebResponse}.
  1259. */
  1260. function encode($response)
  1261. {
  1262. $cls = $this->responseFactory;
  1263. $encode_as = $response->whichEncoding();
  1264. if ($encode_as == Auth_OpenID_ENCODE_KVFORM) {
  1265. $wr = new $cls(null, null, $response->encodeToKVForm());
  1266. if (is_a($response, 'Auth_OpenID_ServerError')) {
  1267. $wr->code = AUTH_OPENID_HTTP_ERROR;
  1268. }
  1269. } else if ($encode_as == Auth_OpenID_ENCODE_URL) {
  1270. $location = $response->encodeToURL();
  1271. $wr = new $cls(AUTH_OPENID_HTTP_REDIRECT,
  1272. array('location' => $location));
  1273. } else if ($encode_as == Auth_OpenID_ENCODE_HTML_FORM) {
  1274. $wr = new $cls(AUTH_OPENID_HTTP_OK, array(),
  1275. $response->toHTML());
  1276. } else {
  1277. return new Auth_OpenID_EncodingError($response);
  1278. }
  1279. /* Allow the response to carry a custom error code (ex: for Association errors) */
  1280. if(isset($response->code)) {
  1281. $wr->code = $response->code;
  1282. }
  1283. return $wr;
  1284. }
  1285. }
  1286. /**
  1287. * An encoder which also takes care of signing fields when required.
  1288. *
  1289. * @package OpenID
  1290. */
  1291. class Auth_OpenID_SigningEncoder extends Auth_OpenID_Encoder {
  1292. function Auth_OpenID_SigningEncoder($signatory)
  1293. {
  1294. $this->signatory = $signatory;
  1295. }
  1296. /**
  1297. * Sign an {@link Auth_OpenID_ServerResponse} and return an
  1298. * {@link Auth_OpenID_WebResponse}.
  1299. */
  1300. function encode($response)
  1301. {
  1302. // the isinstance is a bit of a kludge... it means there isn't
  1303. // really an adapter to make the interfaces quite match.
  1304. if (!is_a($response, 'Auth_OpenID_ServerError') &&
  1305. $response->needsSigning()) {
  1306. if (!$this->signatory) {
  1307. return new Auth_OpenID_ServerError(null,
  1308. "Must have a store to sign request");
  1309. }
  1310. if ($response->fields->hasKey(Auth_OpenID_OPENID_NS, 'sig')) {
  1311. return new Auth_OpenID_AlreadySigned($response);
  1312. }
  1313. $response = $this->signatory->sign($response);
  1314. }
  1315. return parent::encode($response);
  1316. }
  1317. }
  1318. /**
  1319. * Decode an incoming query into an Auth_OpenID_Request.
  1320. *
  1321. * @package OpenID
  1322. */
  1323. class Auth_OpenID_Decoder {
  1324. function Auth_OpenID_Decoder($server)
  1325. {
  1326. $this->server = $server;
  1327. $this->handlers = array(
  1328. 'checkid_setup' => 'Auth_OpenID_CheckIDRequest',
  1329. 'checkid_immediate' => 'Auth_OpenID_CheckIDRequest',
  1330. 'check_authentication' => 'Auth_OpenID_CheckAuthRequest',
  1331. 'associate' => 'Auth_OpenID_AssociateRequest'
  1332. );
  1333. }
  1334. /**
  1335. * Given an HTTP query in an array (key-value pairs), decode it
  1336. * into an Auth_OpenID_Request object.
  1337. */
  1338. function decode($query)
  1339. {
  1340. if (!$query) {
  1341. return null;
  1342. }
  1343. $message = Auth_OpenID_Message::fromPostArgs($query);
  1344. if ($message === null) {
  1345. /*
  1346. * It's useful to have a Message attached to a
  1347. * ProtocolError, so we override the bad ns value to build
  1348. * a Message out of it. Kinda kludgy, since it's made of
  1349. * lies, but the parts that aren't lies are more useful
  1350. * than a 'None'.
  1351. */
  1352. $old_ns = $query['openid.ns'];
  1353. $query['openid.ns'] = Auth_OpenID_OPENID2_NS;
  1354. $message = Auth_OpenID_Message::fromPostArgs($query);
  1355. return new Auth_OpenID_ServerError(
  1356. $message,
  1357. sprintf("Invalid OpenID namespace URI: %s", $old_ns));
  1358. }
  1359. $mode = $message->getArg(Auth_OpenID_OPENID_NS, 'mode');
  1360. if (!$mode) {
  1361. return new Auth_OpenID_ServerError($message,
  1362. "No mode value in message");
  1363. }
  1364. if (Auth_OpenID::isFailure($mode)) {
  1365. return new Auth_OpenID_ServerError($message,
  1366. $mode->message);
  1367. }
  1368. $handlerCls = Auth_OpenID::arrayGet($this->handlers, $mode,
  1369. $this->defaultDecoder($message));
  1370. if (!is_a($handlerCls, 'Auth_OpenID_ServerError')) {
  1371. return call_user_func_array(array($handlerCls, 'fromMessage'),
  1372. array($message, $this->server));
  1373. } else {
  1374. return $handlerCls;
  1375. }
  1376. }
  1377. function defaultDecoder($message)
  1378. {
  1379. $mode = $message->getArg(Auth_OpenID_OPENID_NS, 'mode');
  1380. if (Auth_OpenID::isFailure($mode)) {
  1381. return new Auth_OpenID_ServerError($message,
  1382. $mode->message);
  1383. }
  1384. return new Auth_OpenID_ServerError($message,
  1385. sprintf("Unrecognized OpenID mode %s", $mode));
  1386. }
  1387. }
  1388. /**
  1389. * An error that indicates an encoding problem occurred.
  1390. *
  1391. * @package OpenID
  1392. */
  1393. class Auth_OpenID_EncodingError {
  1394. function Auth_OpenID_EncodingError($response)
  1395. {
  1396. $this->response = $response;
  1397. }
  1398. }
  1399. /**
  1400. * An error that indicates that a response was already signed.
  1401. *
  1402. * @package OpenID
  1403. */
  1404. class Auth_OpenID_AlreadySigned extends Auth_OpenID_EncodingError {
  1405. // This response is already signed.
  1406. }
  1407. /**
  1408. * An error that indicates that the given return_to is not under the
  1409. * given trust_root.
  1410. *
  1411. * @package OpenID
  1412. */
  1413. class Auth_OpenID_UntrustedReturnURL extends Auth_OpenID_ServerError {
  1414. function Auth_OpenID_UntrustedReturnURL($message, $return_to,
  1415. $trust_root)
  1416. {
  1417. parent::Auth_OpenID_ServerError($message, "Untrusted return_to URL");
  1418. $this->return_to = $return_to;
  1419. $this->trust_root = $trust_root;
  1420. }
  1421. function toString()
  1422. {
  1423. return sprintf("return_to %s not under trust_root %s",
  1424. $this->return_to, $this->trust_root);
  1425. }
  1426. }
  1427. /**
  1428. * I handle requests for an OpenID server.
  1429. *
  1430. * Some types of requests (those which are not checkid requests) may
  1431. * be handed to my {@link handleRequest} method, and I will take care
  1432. * of it and return a response.
  1433. *
  1434. * For your convenience, I also provide an interface to {@link
  1435. * Auth_OpenID_Decoder::decode()} and {@link
  1436. * Auth_OpenID_SigningEncoder::encode()} through my methods {@link
  1437. * decodeRequest} and {@link encodeResponse}.
  1438. *
  1439. * All my state is encapsulated in an {@link Auth_OpenID_OpenIDStore}.
  1440. *
  1441. * Example:
  1442. *
  1443. * <pre> $oserver = new Auth_OpenID_Server(Auth_OpenID_FileStore($data_path),
  1444. * "http://example.com/op");
  1445. * $request = $oserver->decodeRequest();
  1446. * if (in_array($request->mode, array('checkid_immediate',
  1447. * 'checkid_setup'))) {
  1448. * if ($app->isAuthorized($request->identity, $request->trust_root)) {
  1449. * $response = $request->answer(true);
  1450. * } else if ($request->immediate) {
  1451. * $response = $request->answer(false);
  1452. * } else {
  1453. * $app->showDecidePage($request);
  1454. * return;
  1455. * }
  1456. * } else {
  1457. * $response = $oserver->handleRequest($request);
  1458. * }
  1459. *
  1460. * $webresponse = $oserver->encode($response);</pre>
  1461. *
  1462. * @package OpenID
  1463. */
  1464. class Auth_OpenID_Server {
  1465. function Auth_OpenID_Server($store, $op_endpoint=null)
  1466. {
  1467. $this->store = $store;
  1468. $this->signatory = new Auth_OpenID_Signatory($this->store);
  1469. $this->encoder = new Auth_OpenID_SigningEncoder($this->signatory);
  1470. $this->decoder = new Auth_OpenID_Decoder($this);
  1471. $this->op_endpoint = $op_endpoint;
  1472. $this->negotiator = Auth_OpenID_getDefaultNegotiator();
  1473. }
  1474. /**
  1475. * Handle a request. Given an {@link Auth_OpenID_Request} object,
  1476. * call the appropriate {@link Auth_OpenID_Server} method to
  1477. * process the request and generate a response.
  1478. *
  1479. * @param Auth_OpenID_Request $request An {@link Auth_OpenID_Request}
  1480. * returned by {@link Auth_OpenID_Server::decodeRequest()}.
  1481. *
  1482. * @return Auth_OpenID_ServerResponse $response A response object
  1483. * capable of generating a user-agent reply.
  1484. */
  1485. function handleRequest($request)
  1486. {
  1487. if (method_exists($this, "openid_" . $request->mode)) {
  1488. $handler = array($this, "openid_" . $request->mode);
  1489. return call_user_func_array($handler, array($request));
  1490. }
  1491. return null;
  1492. }
  1493. /**
  1494. * The callback for 'check_authentication' messages.
  1495. */
  1496. function openid_check_authentication($request)
  1497. {
  1498. return $request->answer($this->signatory);
  1499. }
  1500. /**
  1501. * The callback for 'associate' messages.
  1502. */
  1503. function openid_associate($request)
  1504. {
  1505. $assoc_type = $request->assoc_type;
  1506. $session_type = $request->session->session_type;
  1507. if ($this->negotiator->isAllowed($assoc_type, $session_type)) {
  1508. $assoc = $this->signatory->createAssociation(false,
  1509. $assoc_type);
  1510. return $request->answer($assoc);
  1511. } else {
  1512. $message = sprintf('Association type %s is not supported with '.
  1513. 'session type %s', $assoc_type, $session_type);
  1514. list($preferred_assoc_type, $preferred_session_type) =
  1515. $this->negotiator->getAllowedType();
  1516. return $request->answerUnsupported($message,
  1517. $preferred_assoc_type,
  1518. $preferred_session_type);
  1519. }
  1520. }
  1521. /**
  1522. * Encodes as response in the appropriate format suitable for
  1523. * sending to the user agent.
  1524. */
  1525. function encodeResponse($response)
  1526. {
  1527. return $this->encoder->encode($response);
  1528. }
  1529. /**
  1530. * Decodes a query args array into the appropriate
  1531. * {@link Auth_OpenID_Request} object.
  1532. */
  1533. function decodeRequest($query=null)
  1534. {
  1535. if ($query === null) {
  1536. $query = Auth_OpenID::getQuery();
  1537. }
  1538. return $this->decoder->decode($query);
  1539. }
  1540. }