openid.inc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. <?php
  2. /**
  3. * @file
  4. * OpenID utility functions.
  5. */
  6. /**
  7. * Diffie-Hellman Key Exchange Default Value.
  8. *
  9. * This is used to establish an association between the Relying Party and the
  10. * OpenID Provider.
  11. *
  12. * See RFC 2631: http://www.ietf.org/rfc/rfc2631.txt
  13. */
  14. define('OPENID_DH_DEFAULT_MOD', '155172898181473697471232257763715539915724801' .
  15. '966915404479707795314057629378541917580651227423698188993727816152646631' .
  16. '438561595825688188889951272158842675419950341258706556549803580104870537' .
  17. '681476726513255747040765857479291291572334510643245094715007229621094194' .
  18. '349783925984760375594985848253359305585439638443');
  19. /**
  20. * Diffie-Hellman generator; used for Diffie-Hellman key exchange computations.
  21. */
  22. define('OPENID_DH_DEFAULT_GEN', '2');
  23. /**
  24. * SHA-1 hash block size; used for Diffie-Hellman key exchange computations.
  25. */
  26. define('OPENID_SHA1_BLOCKSIZE', 64);
  27. /**
  28. * Random number generator; used for Diffie-Hellman key exchange computations.
  29. */
  30. define('OPENID_RAND_SOURCE', '/dev/urandom');
  31. /**
  32. * OpenID Authentication 2.0 namespace URL.
  33. */
  34. define('OPENID_NS_2_0', 'http://specs.openid.net/auth/2.0');
  35. /**
  36. * OpenID Authentication 1.1 namespace URL; used for backwards-compatibility.
  37. */
  38. define('OPENID_NS_1_1', 'http://openid.net/signon/1.1');
  39. /**
  40. * OpenID Authentication 1.0 namespace URL; used for backwards-compatibility.
  41. */
  42. define('OPENID_NS_1_0', 'http://openid.net/signon/1.0');
  43. /**
  44. * OpenID namespace used in Yadis documents.
  45. */
  46. define('OPENID_NS_OPENID', 'http://openid.net/xmlns/1.0');
  47. /**
  48. * OpenID Simple Registration extension.
  49. */
  50. define('OPENID_NS_SREG', 'http://openid.net/extensions/sreg/1.1');
  51. /**
  52. * OpenID Attribute Exchange extension.
  53. */
  54. define('OPENID_NS_AX', 'http://openid.net/srv/ax/1.0');
  55. /**
  56. * Extensible Resource Descriptor documents.
  57. */
  58. define('OPENID_NS_XRD', 'xri://$xrd*($v*2.0)');
  59. /**
  60. * Performs an HTTP 302 redirect (for the 1.x protocol).
  61. */
  62. function openid_redirect_http($url, $message) {
  63. $query = array();
  64. foreach ($message as $key => $val) {
  65. $query[] = $key . '=' . urlencode($val);
  66. }
  67. $sep = (strpos($url, '?') === FALSE) ? '?' : '&';
  68. header('Location: ' . $url . $sep . implode('&', $query), TRUE, 302);
  69. drupal_exit();
  70. }
  71. /**
  72. * Creates a js auto-submit redirect for (for the 2.x protocol)
  73. */
  74. function openid_redirect($url, $message) {
  75. global $language;
  76. $output = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
  77. $output .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="' . $language->language . '" lang="' . $language->language . '">' . "\n";
  78. $output .= "<head>\n";
  79. $output .= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
  80. $output .= "<title>" . t('OpenID redirect') . "</title>\n";
  81. $output .= "</head>\n";
  82. $output .= "<body>\n";
  83. $elements = drupal_get_form('openid_redirect_form', $url, $message);
  84. $output .= drupal_render($elements);
  85. $output .= '<script type="text/javascript">document.getElementById("openid-redirect-form").submit();</script>' . "\n";
  86. $output .= "</body>\n";
  87. $output .= "</html>\n";
  88. print $output;
  89. drupal_exit();
  90. }
  91. function openid_redirect_form($form, &$form_state, $url, $message) {
  92. $form['#action'] = $url;
  93. $form['#method'] = "post";
  94. foreach ($message as $key => $value) {
  95. $form[$key] = array(
  96. '#type' => 'hidden',
  97. '#name' => $key,
  98. '#value' => $value,
  99. );
  100. }
  101. $form['actions'] = array('#type' => 'actions');
  102. $form['actions']['submit'] = array(
  103. '#type' => 'submit',
  104. '#prefix' => '<noscript><div>',
  105. '#suffix' => '</div></noscript>',
  106. '#value' => t('Send'),
  107. );
  108. return $form;
  109. }
  110. /**
  111. * Parse an XRDS document.
  112. *
  113. * @param $raw_xml
  114. * A string containing the XRDS document.
  115. * @return
  116. * An array of service entries.
  117. */
  118. function _openid_xrds_parse($raw_xml) {
  119. $services = array();
  120. // For PHP version >= 5.2.11, we can use this function to protect against
  121. // malicious doctype declarations and other unexpected entity loading.
  122. // However, we will not rely on it, and reject any XML with a DOCTYPE.
  123. $disable_entity_loader = function_exists('libxml_disable_entity_loader');
  124. if ($disable_entity_loader) {
  125. $load_entities = libxml_disable_entity_loader(TRUE);
  126. }
  127. // Load the XML into a DOM document.
  128. $dom = new DOMDocument();
  129. @$dom->loadXML($raw_xml);
  130. // Since DOCTYPE declarations from an untrusted source could be malicious, we
  131. // stop parsing here and treat the XML as invalid since XRDS documents do not
  132. // require, and are not expected to have, a DOCTYPE.
  133. if (isset($dom->doctype)) {
  134. return array();
  135. }
  136. // Parse the DOM document for the information we need.
  137. if ($xml = simplexml_import_dom($dom)) {
  138. foreach ($xml->children(OPENID_NS_XRD)->XRD as $xrd) {
  139. foreach ($xrd->children(OPENID_NS_XRD)->Service as $service_element) {
  140. $service = array(
  141. 'priority' => $service_element->attributes()->priority ? (int)$service_element->attributes()->priority : PHP_INT_MAX,
  142. 'types' => array(),
  143. 'uri' => (string)$service_element->children(OPENID_NS_XRD)->URI,
  144. 'service' => $service_element,
  145. 'xrd' => $xrd,
  146. );
  147. foreach ($service_element->Type as $type) {
  148. $service['types'][] = (string)$type;
  149. }
  150. if ($service_element->children(OPENID_NS_XRD)->LocalID) {
  151. $service['identity'] = (string)$service_element->children(OPENID_NS_XRD)->LocalID;
  152. }
  153. elseif ($service_element->children(OPENID_NS_OPENID)->Delegate) {
  154. $service['identity'] = (string)$service_element->children(OPENID_NS_OPENID)->Delegate;
  155. }
  156. else {
  157. $service['identity'] = FALSE;
  158. }
  159. $services[] = $service;
  160. }
  161. }
  162. }
  163. // Return the LIBXML options to the previous state before returning.
  164. if ($disable_entity_loader) {
  165. libxml_disable_entity_loader($load_entities);
  166. }
  167. return $services;
  168. }
  169. /**
  170. * Select a service element.
  171. *
  172. * The procedure is described in OpenID Authentication 2.0, section 7.3.2.
  173. *
  174. * A new entry is added to the returned array with the key 'version' and the
  175. * value 1 or 2 specifying the protocol version used by the service.
  176. *
  177. * @param $services
  178. * An array of service arrays as returned by openid_discovery().
  179. * @return
  180. * The selected service array, or NULL if no valid services were found.
  181. */
  182. function _openid_select_service(array $services) {
  183. // Extensible Resource Identifier (XRI) Resolution Version 2.0, section 4.3.3:
  184. // Find the service with the highest priority (lowest integer value). If there
  185. // is a tie, select a random one, not just the first in the XML document.
  186. shuffle($services);
  187. $selected_service = NULL;
  188. $selected_type_priority = FALSE;
  189. // Search for an OP Identifier Element.
  190. foreach ($services as $service) {
  191. if (!empty($service['uri'])) {
  192. $type_priority = FALSE;
  193. if (in_array('http://specs.openid.net/auth/2.0/server', $service['types'])) {
  194. $service['version'] = 2;
  195. $type_priority = 1;
  196. }
  197. elseif (in_array('http://specs.openid.net/auth/2.0/signon', $service['types'])) {
  198. $service['version'] = 2;
  199. $type_priority = 2;
  200. }
  201. elseif (in_array(OPENID_NS_1_0, $service['types']) || in_array(OPENID_NS_1_1, $service['types'])) {
  202. $service['version'] = 1;
  203. $type_priority = 3;
  204. }
  205. if ($type_priority
  206. && (!$selected_service
  207. || $type_priority < $selected_type_priority
  208. || ($type_priority == $selected_type_priority && $service['priority'] < $selected_service['priority']))) {
  209. $selected_service = $service;
  210. $selected_type_priority = $type_priority;
  211. }
  212. }
  213. }
  214. if ($selected_service) {
  215. // Unset SimpleXMLElement instances that cannot be saved in $_SESSION.
  216. unset($selected_service['xrd']);
  217. unset($selected_service['service']);
  218. }
  219. return $selected_service;
  220. }
  221. /**
  222. * Determine if the given identifier is an XRI ID.
  223. */
  224. function _openid_is_xri($identifier) {
  225. // Strip the xri:// scheme from the identifier if present.
  226. if (stripos($identifier, 'xri://') === 0) {
  227. $identifier = substr($identifier, 6);
  228. }
  229. // Test whether the identifier starts with an XRI global context symbol or (.
  230. $firstchar = substr($identifier, 0, 1);
  231. if (strpos("=@+$!(", $firstchar) !== FALSE) {
  232. return TRUE;
  233. }
  234. return FALSE;
  235. }
  236. /**
  237. * Normalize the given identifier.
  238. *
  239. * The procedure is described in OpenID Authentication 2.0, section 7.2.
  240. */
  241. function openid_normalize($identifier) {
  242. $methods = module_invoke_all('openid_normalization_method_info');
  243. drupal_alter('openid_normalization_method_info', $methods);
  244. // Execute each method in turn, stopping after the first method accepted
  245. // the identifier.
  246. foreach ($methods as $method) {
  247. $result = $method($identifier);
  248. if ($result !== NULL) {
  249. $identifier = $result;
  250. break;
  251. }
  252. }
  253. return $identifier;
  254. }
  255. /**
  256. * OpenID normalization method: normalize XRI identifiers.
  257. */
  258. function _openid_xri_normalize($identifier) {
  259. if (_openid_is_xri($identifier)) {
  260. if (stristr($identifier, 'xri://') !== FALSE) {
  261. $identifier = substr($identifier, 6);
  262. }
  263. return $identifier;
  264. }
  265. }
  266. /**
  267. * OpenID normalization method: normalize URL identifiers.
  268. */
  269. function _openid_url_normalize($url) {
  270. $normalized_url = $url;
  271. if (stristr($url, '://') === FALSE) {
  272. $normalized_url = 'http://' . $url;
  273. }
  274. // Strip the fragment and fragment delimiter if present.
  275. $normalized_url = strtok($normalized_url, '#');
  276. if (substr_count($normalized_url, '/') < 3) {
  277. $normalized_url .= '/';
  278. }
  279. return $normalized_url;
  280. }
  281. /**
  282. * Create a serialized message packet as per spec: $key:$value\n .
  283. */
  284. function _openid_create_message($data) {
  285. $serialized = '';
  286. foreach ($data as $key => $value) {
  287. if ((strpos($key, ':') !== FALSE) || (strpos($key, "\n") !== FALSE) || (strpos($value, "\n") !== FALSE)) {
  288. return NULL;
  289. }
  290. $serialized .= "$key:$value\n";
  291. }
  292. return $serialized;
  293. }
  294. /**
  295. * Encode a message from _openid_create_message for HTTP Post
  296. */
  297. function _openid_encode_message($message) {
  298. $encoded_message = '';
  299. $items = explode("\n", $message);
  300. foreach ($items as $item) {
  301. $parts = explode(':', $item, 2);
  302. if (count($parts) == 2) {
  303. if ($encoded_message != '') {
  304. $encoded_message .= '&';
  305. }
  306. $encoded_message .= rawurlencode(trim($parts[0])) . '=' . rawurlencode(trim($parts[1]));
  307. }
  308. }
  309. return $encoded_message;
  310. }
  311. /**
  312. * Convert a direct communication message
  313. * into an associative array.
  314. */
  315. function _openid_parse_message($message) {
  316. $parsed_message = array();
  317. $items = explode("\n", $message);
  318. foreach ($items as $item) {
  319. $parts = explode(':', $item, 2);
  320. if (count($parts) == 2) {
  321. $parsed_message[$parts[0]] = $parts[1];
  322. }
  323. }
  324. return $parsed_message;
  325. }
  326. /**
  327. * Return a nonce value - formatted per OpenID spec.
  328. *
  329. * NOTE: This nonce is not cryptographically secure and only suitable for use
  330. * by the test framework.
  331. */
  332. function _openid_nonce() {
  333. // YYYY-MM-DDThh:mm:ssZ, plus some optional extra unique characters.
  334. return gmdate('Y-m-d\TH:i:s\Z') .
  335. chr(mt_rand(0, 25) + 65) .
  336. chr(mt_rand(0, 25) + 65) .
  337. chr(mt_rand(0, 25) + 65) .
  338. chr(mt_rand(0, 25) + 65);
  339. }
  340. /**
  341. * Pull the href attribute out of an html link element.
  342. */
  343. function _openid_link_href($rel, $html) {
  344. $rel = preg_quote($rel);
  345. preg_match('|<link\s+rel=["\'](.*)' . $rel . '(.*)["\'](.*)/?>|iUs', $html, $matches);
  346. if (isset($matches[3])) {
  347. preg_match('|href=["\']([^"]+)["\']|iU', $matches[3], $href);
  348. return trim($href[1]);
  349. }
  350. return FALSE;
  351. }
  352. /**
  353. * Pull the http-equiv attribute out of an html meta element
  354. */
  355. function _openid_meta_httpequiv($equiv, $html) {
  356. preg_match('|<meta\s+http-equiv=["\']' . $equiv . '["\'](.*)/?>|iUs', $html, $matches);
  357. if (isset($matches[1])) {
  358. preg_match('|content=["\']([^"]+)["\']|iUs', $matches[1], $content);
  359. if (isset($content[1])) {
  360. return $content[1];
  361. }
  362. }
  363. return FALSE;
  364. }
  365. /**
  366. * Sign certain keys in a message
  367. * @param $association - object loaded from openid_association or openid_server_association table
  368. * - important fields are ->assoc_type and ->mac_key
  369. * @param $message_array - array of entire message about to be sent
  370. * @param $keys_to_sign - keys in the message to include in signature (without
  371. * 'openid.' appended)
  372. */
  373. function _openid_signature($association, $message_array, $keys_to_sign) {
  374. $signature = '';
  375. $sign_data = array();
  376. foreach ($keys_to_sign as $key) {
  377. if (isset($message_array['openid.' . $key])) {
  378. $sign_data[$key] = $message_array['openid.' . $key];
  379. }
  380. }
  381. $message = _openid_create_message($sign_data);
  382. $secret = base64_decode($association->mac_key);
  383. $signature = _openid_hmac($secret, $message);
  384. return base64_encode($signature);
  385. }
  386. function _openid_hmac($key, $text) {
  387. if (strlen($key) > OPENID_SHA1_BLOCKSIZE) {
  388. $key = sha1($key, TRUE);
  389. }
  390. $key = str_pad($key, OPENID_SHA1_BLOCKSIZE, chr(0x00));
  391. $ipad = str_repeat(chr(0x36), OPENID_SHA1_BLOCKSIZE);
  392. $opad = str_repeat(chr(0x5c), OPENID_SHA1_BLOCKSIZE);
  393. $hash1 = sha1(($key ^ $ipad) . $text, TRUE);
  394. $hmac = sha1(($key ^ $opad) . $hash1, TRUE);
  395. return $hmac;
  396. }
  397. function _openid_dh_base64_to_long($str) {
  398. $b64 = base64_decode($str);
  399. return _openid_dh_binary_to_long($b64);
  400. }
  401. function _openid_dh_long_to_base64($str) {
  402. return base64_encode(_openid_dh_long_to_binary($str));
  403. }
  404. function _openid_dh_binary_to_long($str) {
  405. $bytes = array_merge(unpack('C*', $str));
  406. $n = 0;
  407. foreach ($bytes as $byte) {
  408. $n = _openid_math_mul($n, pow(2, 8));
  409. $n = _openid_math_add($n, $byte);
  410. }
  411. return $n;
  412. }
  413. function _openid_dh_long_to_binary($long) {
  414. $cmp = _openid_math_cmp($long, 0);
  415. if ($cmp < 0) {
  416. return FALSE;
  417. }
  418. if ($cmp == 0) {
  419. return "\x00";
  420. }
  421. $bytes = array();
  422. while (_openid_math_cmp($long, 0) > 0) {
  423. array_unshift($bytes, _openid_math_mod($long, 256));
  424. $long = _openid_math_div($long, pow(2, 8));
  425. }
  426. if ($bytes && ($bytes[0] > 127)) {
  427. array_unshift($bytes, 0);
  428. }
  429. $string = '';
  430. foreach ($bytes as $byte) {
  431. $string .= pack('C', $byte);
  432. }
  433. return $string;
  434. }
  435. function _openid_dh_xorsecret($shared, $secret) {
  436. $dh_shared_str = _openid_dh_long_to_binary($shared);
  437. $sha1_dh_shared = sha1($dh_shared_str, TRUE);
  438. $xsecret = "";
  439. for ($i = 0; $i < strlen($secret); $i++) {
  440. $xsecret .= chr(ord($secret[$i]) ^ ord($sha1_dh_shared[$i]));
  441. }
  442. return $xsecret;
  443. }
  444. function _openid_dh_rand($stop) {
  445. $duplicate_cache = &drupal_static(__FUNCTION__, array());
  446. // Used as the key for the duplicate cache
  447. $rbytes = _openid_dh_long_to_binary($stop);
  448. if (isset($duplicate_cache[$rbytes])) {
  449. list($duplicate, $nbytes) = $duplicate_cache[$rbytes];
  450. }
  451. else {
  452. if ($rbytes[0] == "\x00") {
  453. $nbytes = strlen($rbytes) - 1;
  454. }
  455. else {
  456. $nbytes = strlen($rbytes);
  457. }
  458. $mxrand = _openid_math_pow(256, $nbytes);
  459. // If we get a number less than this, then it is in the
  460. // duplicated range.
  461. $duplicate = _openid_math_mod($mxrand, $stop);
  462. if (count($duplicate_cache) > 10) {
  463. $duplicate_cache = array();
  464. }
  465. $duplicate_cache[$rbytes] = array($duplicate, $nbytes);
  466. }
  467. do {
  468. $bytes = "\x00" . drupal_random_bytes($nbytes);
  469. $n = _openid_dh_binary_to_long($bytes);
  470. // Keep looping if this value is in the low duplicated range.
  471. } while (_openid_math_cmp($n, $duplicate) < 0);
  472. return _openid_math_mod($n, $stop);
  473. }
  474. function _openid_get_bytes($num_bytes) {
  475. return drupal_random_bytes($num_bytes);
  476. }
  477. function _openid_response($str = NULL) {
  478. $data = array();
  479. if (isset($_SERVER['REQUEST_METHOD'])) {
  480. $data = _openid_get_params($_SERVER['QUERY_STRING']);
  481. if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  482. $str = file_get_contents('php://input');
  483. $post = array();
  484. if ($str !== FALSE) {
  485. $post = _openid_get_params($str);
  486. }
  487. $data = array_merge($data, $post);
  488. }
  489. }
  490. return $data;
  491. }
  492. function _openid_get_params($str) {
  493. $chunks = explode("&", $str);
  494. $data = array();
  495. foreach ($chunks as $chunk) {
  496. $parts = explode("=", $chunk, 2);
  497. if (count($parts) == 2) {
  498. list($k, $v) = $parts;
  499. $data[$k] = urldecode($v);
  500. }
  501. }
  502. return $data;
  503. }
  504. /**
  505. * Extract all the parameters belonging to an extension in a response message.
  506. *
  507. * OpenID 2.0 defines a simple extension mechanism, based on a namespace prefix.
  508. *
  509. * Each request or response can define a prefix using:
  510. * @code
  511. * openid.ns.[prefix] = [extension_namespace]
  512. * openid.[prefix].[key1] = [value1]
  513. * openid.[prefix].[key2] = [value2]
  514. * ...
  515. * @endcode
  516. *
  517. * This function extracts all the keys belonging to an extension namespace in a
  518. * response, optionally using a fallback prefix if none is provided in the response.
  519. *
  520. * Note that you cannot assume that a given extension namespace will use the same
  521. * prefix on the response and the request: each party may use a different prefix
  522. * to refer to the same namespace.
  523. *
  524. * @param $response
  525. * The response array.
  526. * @param $extension_namespace
  527. * The namespace of the extension.
  528. * @param $fallback_prefix
  529. * An optional prefix that will be used in case no prefix is found for the
  530. * target extension namespace.
  531. * @param $only_signed
  532. * Return only keys that are included in the message signature in openid.sig.
  533. * Unsigned fields may have been modified or added by other parties than the
  534. * OpenID Provider.
  535. *
  536. * @return
  537. * An associative array containing all the parameters in the response message
  538. * that belong to the extension. The keys are stripped from their namespace
  539. * prefix.
  540. *
  541. * @see http://openid.net/specs/openid-authentication-2_0.html#extensions
  542. */
  543. function openid_extract_namespace($response, $extension_namespace, $fallback_prefix = NULL, $only_signed = FALSE) {
  544. $signed_keys = explode(',', $response['openid.signed']);
  545. // Find the namespace prefix.
  546. $prefix = $fallback_prefix;
  547. foreach ($response as $key => $value) {
  548. if ($value == $extension_namespace && preg_match('/^openid\.ns\.([^.]+)$/', $key, $matches)) {
  549. $prefix = $matches[1];
  550. if ($only_signed && !in_array('ns.' . $matches[1], $signed_keys)) {
  551. // The namespace was defined but was not signed as required. In this
  552. // case we do not fall back to $fallback_prefix.
  553. $prefix = NULL;
  554. }
  555. break;
  556. }
  557. }
  558. // Now extract the namespace keys from the response.
  559. $output = array();
  560. if (!isset($prefix)) {
  561. return $output;
  562. }
  563. foreach ($response as $key => $value) {
  564. if (preg_match('/^openid\.' . $prefix . '\.(.+)$/', $key, $matches)) {
  565. $local_key = $matches[1];
  566. if (!$only_signed || in_array($prefix . '.' . $local_key, $signed_keys)) {
  567. $output[$local_key] = $value;
  568. }
  569. }
  570. }
  571. return $output;
  572. }
  573. /**
  574. * Extracts values from an OpenID AX Response.
  575. *
  576. * The values can be returned in two forms:
  577. * - only openid.ax.value.<alias> (for single-valued answers)
  578. * - both openid.ax.count.<alias> and openid.ax.value.<alias>.<count> (for both
  579. * single and multiple-valued answers)
  580. *
  581. * @param $values
  582. * An array as returned by openid_extract_namespace(..., OPENID_NS_AX).
  583. * @param $uris
  584. * An array of identifier URIs.
  585. * @return
  586. * An array of values.
  587. * @see http://openid.net/specs/openid-attribute-exchange-1_0.html#fetch_response
  588. */
  589. function openid_extract_ax_values($values, $uris) {
  590. $output = array();
  591. foreach ($values as $key => $value) {
  592. if (in_array($value, $uris) && preg_match('/^type\.([^.]+)$/', $key, $matches)) {
  593. $alias = $matches[1];
  594. if (isset($values['count.' . $alias])) {
  595. for ($i = 1; $i <= $values['count.' . $alias]; $i++) {
  596. $output[] = $values['value.' . $alias . '.' . $i];
  597. }
  598. }
  599. elseif (isset($values['value.' . $alias])) {
  600. $output[] = $values['value.' . $alias];
  601. }
  602. break;
  603. }
  604. }
  605. return $output;
  606. }
  607. /**
  608. * Determine the available math library GMP vs. BCMath, favouring GMP for performance.
  609. */
  610. function _openid_get_math_library() {
  611. // Not drupal_static(), because a function is not going to disappear and
  612. // change the output of this under any circumstances.
  613. static $library;
  614. if (empty($library)) {
  615. if (function_exists('gmp_add')) {
  616. $library = 'gmp';
  617. }
  618. elseif (function_exists('bcadd')) {
  619. $library = 'bcmath';
  620. }
  621. }
  622. return $library;
  623. }
  624. /**
  625. * Calls the add function from the available math library for OpenID.
  626. */
  627. function _openid_math_add($x, $y) {
  628. $library = _openid_get_math_library();
  629. switch ($library) {
  630. case 'gmp':
  631. return gmp_strval(gmp_add($x, $y));
  632. case 'bcmath':
  633. return bcadd($x, $y);
  634. }
  635. }
  636. /**
  637. * Calls the mul function from the available math library for OpenID.
  638. */
  639. function _openid_math_mul($x, $y) {
  640. $library = _openid_get_math_library();
  641. switch ($library) {
  642. case 'gmp':
  643. return gmp_mul($x, $y);
  644. case 'bcmath':
  645. return bcmul($x, $y);
  646. }
  647. }
  648. /**
  649. * Calls the div function from the available math library for OpenID.
  650. */
  651. function _openid_math_div($x, $y) {
  652. $library = _openid_get_math_library();
  653. switch ($library) {
  654. case 'gmp':
  655. return gmp_div($x, $y);
  656. case 'bcmath':
  657. return bcdiv($x, $y);
  658. }
  659. }
  660. /**
  661. * Calls the cmp function from the available math library for OpenID.
  662. */
  663. function _openid_math_cmp($x, $y) {
  664. $library = _openid_get_math_library();
  665. switch ($library) {
  666. case 'gmp':
  667. return gmp_cmp($x, $y);
  668. case 'bcmath':
  669. return bccomp($x, $y);
  670. }
  671. }
  672. /**
  673. * Calls the mod function from the available math library for OpenID.
  674. */
  675. function _openid_math_mod($x, $y) {
  676. $library = _openid_get_math_library();
  677. switch ($library) {
  678. case 'gmp':
  679. return gmp_mod($x, $y);
  680. case 'bcmath':
  681. return bcmod($x, $y);
  682. }
  683. }
  684. /**
  685. * Calls the pow function from the available math library for OpenID.
  686. */
  687. function _openid_math_pow($x, $y) {
  688. $library = _openid_get_math_library();
  689. switch ($library) {
  690. case 'gmp':
  691. return gmp_pow($x, $y);
  692. case 'bcmath':
  693. return bcpow($x, $y);
  694. }
  695. }
  696. /**
  697. * Calls the mul function from the available math library for OpenID.
  698. */
  699. function _openid_math_powmod($x, $y, $z) {
  700. $library = _openid_get_math_library();
  701. switch ($library) {
  702. case 'gmp':
  703. return gmp_powm($x, $y, $z);
  704. case 'bcmath':
  705. return bcpowmod($x, $y, $z);
  706. }
  707. }
  708. /**
  709. * Provides transition for accounts with possibly invalid OpenID identifiers in authmap.
  710. *
  711. * This function provides a less safe but more unobtrusive procedure for users
  712. * who cannot login with their OpenID identifiers. OpenID identifiers in the
  713. * authmap could be incomplete due to invalid OpenID implementation in previous
  714. * versions of Drupal (e.g. fragment part of the identifier could be missing).
  715. * For more information see http://drupal.org/node/1120290.
  716. *
  717. * @param string $identity
  718. * The user's claimed OpenID identifier.
  719. *
  720. * @return
  721. * A fully-loaded user object if the user is found or FALSE if not found.
  722. */
  723. function _openid_invalid_openid_transition($identity, $response) {
  724. $account = FALSE;
  725. $fallback_account = NULL;
  726. $fallback_identity = $identity;
  727. // Try to strip the fragment if it is present.
  728. if (strpos($fallback_identity, '#') !== FALSE) {
  729. $fallback_identity = preg_replace('/#.*/', '', $fallback_identity);
  730. $fallback_account = user_external_load($fallback_identity);
  731. }
  732. // Try to replace HTTPS with HTTP. OpenID providers often redirect
  733. // from http to https, but Drupal didn't follow the redirect.
  734. if (!$fallback_account && strpos($fallback_identity, 'https://') !== FALSE) {
  735. $fallback_identity = str_replace('https://', 'http://', $fallback_identity);
  736. $fallback_account = user_external_load($fallback_identity);
  737. }
  738. // Try to use original identifier.
  739. if (!$fallback_account && isset($_SESSION['openid']['user_login_values']['openid_identifier'])) {
  740. $fallback_identity = openid_normalize($_SESSION['openid']['user_login_values']['openid_identifier']);
  741. $fallback_account = user_external_load($fallback_identity);
  742. }
  743. if ($fallback_account) {
  744. // Try to extract e-mail address from Simple Registration (SREG) or
  745. // Attribute Exchanges (AX) keys.
  746. $email = '';
  747. $sreg_values = openid_extract_namespace($response, OPENID_NS_SREG, 'sreg', TRUE);
  748. $ax_values = openid_extract_namespace($response, OPENID_NS_AX, 'ax', TRUE);
  749. if (!empty($sreg_values['email']) && valid_email_address($sreg_values['email'])) {
  750. $email = $sreg_values['email'];
  751. }
  752. elseif ($ax_mail_values = openid_extract_ax_values($ax_values, array('http://axschema.org/contact/email', 'http://schema.openid.net/contact/email'))) {
  753. $email = current($ax_mail_values);
  754. }
  755. // If this e-mail address is the same as the e-mail address found in user
  756. // account, login the user and update the claimed identifier.
  757. if ($email && ($email == $fallback_account->mail || $email == $fallback_account->init)) {
  758. $query = db_insert('authmap')
  759. ->fields(array(
  760. 'authname' => $identity,
  761. 'uid' => $fallback_account->uid,
  762. 'module' => 'openid',
  763. ))
  764. ->execute();
  765. drupal_set_message(t('New OpenID identifier %identity was added as a replacement for invalid identifier %invalid_identity. To finish the invalid OpenID transition process, please go to your <a href="@openid_url">OpenID identities page</a> and remove the old identifier %invalid_identity.', array('%invalid_identity' => $fallback_identity, '%identity' => $identity, '@openid_url' => 'user/' . $fallback_account->uid . '/openid')));
  766. // Set the account to the found one.
  767. $account = $fallback_account;
  768. }
  769. else {
  770. drupal_set_message(t('There is already an existing account associated with the OpenID identifier that you have provided. However, due to a bug in the previous version of the authentication system, we can\'t be sure that this account belongs to you. If you are new on this site, please continue registering the new user account. If you already have a registered account on this site associated with the provided OpenID identifier, please try to <a href="@url_password">reset the password</a> or contact the site administrator.', array('@url_password' => 'user/password')), 'warning');
  771. }
  772. }
  773. return $account;
  774. }