openid.inc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  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. function _openid_nonce() {
  330. // YYYY-MM-DDThh:mm:ssZ, plus some optional extra unique characters.
  331. return gmdate('Y-m-d\TH:i:s\Z') .
  332. chr(mt_rand(0, 25) + 65) .
  333. chr(mt_rand(0, 25) + 65) .
  334. chr(mt_rand(0, 25) + 65) .
  335. chr(mt_rand(0, 25) + 65);
  336. }
  337. /**
  338. * Pull the href attribute out of an html link element.
  339. */
  340. function _openid_link_href($rel, $html) {
  341. $rel = preg_quote($rel);
  342. preg_match('|<link\s+rel=["\'](.*)' . $rel . '(.*)["\'](.*)/?>|iUs', $html, $matches);
  343. if (isset($matches[3])) {
  344. preg_match('|href=["\']([^"]+)["\']|iU', $matches[3], $href);
  345. return trim($href[1]);
  346. }
  347. return FALSE;
  348. }
  349. /**
  350. * Pull the http-equiv attribute out of an html meta element
  351. */
  352. function _openid_meta_httpequiv($equiv, $html) {
  353. preg_match('|<meta\s+http-equiv=["\']' . $equiv . '["\'](.*)/?>|iUs', $html, $matches);
  354. if (isset($matches[1])) {
  355. preg_match('|content=["\']([^"]+)["\']|iUs', $matches[1], $content);
  356. if (isset($content[1])) {
  357. return $content[1];
  358. }
  359. }
  360. return FALSE;
  361. }
  362. /**
  363. * Sign certain keys in a message
  364. * @param $association - object loaded from openid_association or openid_server_association table
  365. * - important fields are ->assoc_type and ->mac_key
  366. * @param $message_array - array of entire message about to be sent
  367. * @param $keys_to_sign - keys in the message to include in signature (without
  368. * 'openid.' appended)
  369. */
  370. function _openid_signature($association, $message_array, $keys_to_sign) {
  371. $signature = '';
  372. $sign_data = array();
  373. foreach ($keys_to_sign as $key) {
  374. if (isset($message_array['openid.' . $key])) {
  375. $sign_data[$key] = $message_array['openid.' . $key];
  376. }
  377. }
  378. $message = _openid_create_message($sign_data);
  379. $secret = base64_decode($association->mac_key);
  380. $signature = _openid_hmac($secret, $message);
  381. return base64_encode($signature);
  382. }
  383. function _openid_hmac($key, $text) {
  384. if (strlen($key) > OPENID_SHA1_BLOCKSIZE) {
  385. $key = sha1($key, TRUE);
  386. }
  387. $key = str_pad($key, OPENID_SHA1_BLOCKSIZE, chr(0x00));
  388. $ipad = str_repeat(chr(0x36), OPENID_SHA1_BLOCKSIZE);
  389. $opad = str_repeat(chr(0x5c), OPENID_SHA1_BLOCKSIZE);
  390. $hash1 = sha1(($key ^ $ipad) . $text, TRUE);
  391. $hmac = sha1(($key ^ $opad) . $hash1, TRUE);
  392. return $hmac;
  393. }
  394. function _openid_dh_base64_to_long($str) {
  395. $b64 = base64_decode($str);
  396. return _openid_dh_binary_to_long($b64);
  397. }
  398. function _openid_dh_long_to_base64($str) {
  399. return base64_encode(_openid_dh_long_to_binary($str));
  400. }
  401. function _openid_dh_binary_to_long($str) {
  402. $bytes = array_merge(unpack('C*', $str));
  403. $n = 0;
  404. foreach ($bytes as $byte) {
  405. $n = _openid_math_mul($n, pow(2, 8));
  406. $n = _openid_math_add($n, $byte);
  407. }
  408. return $n;
  409. }
  410. function _openid_dh_long_to_binary($long) {
  411. $cmp = _openid_math_cmp($long, 0);
  412. if ($cmp < 0) {
  413. return FALSE;
  414. }
  415. if ($cmp == 0) {
  416. return "\x00";
  417. }
  418. $bytes = array();
  419. while (_openid_math_cmp($long, 0) > 0) {
  420. array_unshift($bytes, _openid_math_mod($long, 256));
  421. $long = _openid_math_div($long, pow(2, 8));
  422. }
  423. if ($bytes && ($bytes[0] > 127)) {
  424. array_unshift($bytes, 0);
  425. }
  426. $string = '';
  427. foreach ($bytes as $byte) {
  428. $string .= pack('C', $byte);
  429. }
  430. return $string;
  431. }
  432. function _openid_dh_xorsecret($shared, $secret) {
  433. $dh_shared_str = _openid_dh_long_to_binary($shared);
  434. $sha1_dh_shared = sha1($dh_shared_str, TRUE);
  435. $xsecret = "";
  436. for ($i = 0; $i < strlen($secret); $i++) {
  437. $xsecret .= chr(ord($secret[$i]) ^ ord($sha1_dh_shared[$i]));
  438. }
  439. return $xsecret;
  440. }
  441. function _openid_dh_rand($stop) {
  442. $duplicate_cache = &drupal_static(__FUNCTION__, array());
  443. // Used as the key for the duplicate cache
  444. $rbytes = _openid_dh_long_to_binary($stop);
  445. if (isset($duplicate_cache[$rbytes])) {
  446. list($duplicate, $nbytes) = $duplicate_cache[$rbytes];
  447. }
  448. else {
  449. if ($rbytes[0] == "\x00") {
  450. $nbytes = strlen($rbytes) - 1;
  451. }
  452. else {
  453. $nbytes = strlen($rbytes);
  454. }
  455. $mxrand = _openid_math_pow(256, $nbytes);
  456. // If we get a number less than this, then it is in the
  457. // duplicated range.
  458. $duplicate = _openid_math_mod($mxrand, $stop);
  459. if (count($duplicate_cache) > 10) {
  460. $duplicate_cache = array();
  461. }
  462. $duplicate_cache[$rbytes] = array($duplicate, $nbytes);
  463. }
  464. do {
  465. $bytes = "\x00" . _openid_get_bytes($nbytes);
  466. $n = _openid_dh_binary_to_long($bytes);
  467. // Keep looping if this value is in the low duplicated range.
  468. } while (_openid_math_cmp($n, $duplicate) < 0);
  469. return _openid_math_mod($n, $stop);
  470. }
  471. function _openid_get_bytes($num_bytes) {
  472. $f = &drupal_static(__FUNCTION__);
  473. $bytes = '';
  474. if (!isset($f)) {
  475. $f = @fopen(OPENID_RAND_SOURCE, "r");
  476. }
  477. if (!$f) {
  478. // pseudorandom used
  479. $bytes = '';
  480. for ($i = 0; $i < $num_bytes; $i += 4) {
  481. $bytes .= pack('L', mt_rand());
  482. }
  483. $bytes = substr($bytes, 0, $num_bytes);
  484. }
  485. else {
  486. $bytes = fread($f, $num_bytes);
  487. }
  488. return $bytes;
  489. }
  490. function _openid_response($str = NULL) {
  491. $data = array();
  492. if (isset($_SERVER['REQUEST_METHOD'])) {
  493. $data = _openid_get_params($_SERVER['QUERY_STRING']);
  494. if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  495. $str = file_get_contents('php://input');
  496. $post = array();
  497. if ($str !== FALSE) {
  498. $post = _openid_get_params($str);
  499. }
  500. $data = array_merge($data, $post);
  501. }
  502. }
  503. return $data;
  504. }
  505. function _openid_get_params($str) {
  506. $chunks = explode("&", $str);
  507. $data = array();
  508. foreach ($chunks as $chunk) {
  509. $parts = explode("=", $chunk, 2);
  510. if (count($parts) == 2) {
  511. list($k, $v) = $parts;
  512. $data[$k] = urldecode($v);
  513. }
  514. }
  515. return $data;
  516. }
  517. /**
  518. * Extract all the parameters belonging to an extension in a response message.
  519. *
  520. * OpenID 2.0 defines a simple extension mechanism, based on a namespace prefix.
  521. *
  522. * Each request or response can define a prefix using:
  523. * @code
  524. * openid.ns.[prefix] = [extension_namespace]
  525. * openid.[prefix].[key1] = [value1]
  526. * openid.[prefix].[key2] = [value2]
  527. * ...
  528. * @endcode
  529. *
  530. * This function extracts all the keys belonging to an extension namespace in a
  531. * response, optionally using a fallback prefix if none is provided in the response.
  532. *
  533. * Note that you cannot assume that a given extension namespace will use the same
  534. * prefix on the response and the request: each party may use a different prefix
  535. * to refer to the same namespace.
  536. *
  537. * @param $response
  538. * The response array.
  539. * @param $extension_namespace
  540. * The namespace of the extension.
  541. * @param $fallback_prefix
  542. * An optional prefix that will be used in case no prefix is found for the
  543. * target extension namespace.
  544. * @param $only_signed
  545. * Return only keys that are included in the message signature in openid.sig.
  546. * Unsigned fields may have been modified or added by other parties than the
  547. * OpenID Provider.
  548. *
  549. * @return
  550. * An associative array containing all the parameters in the response message
  551. * that belong to the extension. The keys are stripped from their namespace
  552. * prefix.
  553. *
  554. * @see http://openid.net/specs/openid-authentication-2_0.html#extensions
  555. */
  556. function openid_extract_namespace($response, $extension_namespace, $fallback_prefix = NULL, $only_signed = FALSE) {
  557. $signed_keys = explode(',', $response['openid.signed']);
  558. // Find the namespace prefix.
  559. $prefix = $fallback_prefix;
  560. foreach ($response as $key => $value) {
  561. if ($value == $extension_namespace && preg_match('/^openid\.ns\.([^.]+)$/', $key, $matches)) {
  562. $prefix = $matches[1];
  563. if ($only_signed && !in_array('ns.' . $matches[1], $signed_keys)) {
  564. // The namespace was defined but was not signed as required. In this
  565. // case we do not fall back to $fallback_prefix.
  566. $prefix = NULL;
  567. }
  568. break;
  569. }
  570. }
  571. // Now extract the namespace keys from the response.
  572. $output = array();
  573. if (!isset($prefix)) {
  574. return $output;
  575. }
  576. foreach ($response as $key => $value) {
  577. if (preg_match('/^openid\.' . $prefix . '\.(.+)$/', $key, $matches)) {
  578. $local_key = $matches[1];
  579. if (!$only_signed || in_array($prefix . '.' . $local_key, $signed_keys)) {
  580. $output[$local_key] = $value;
  581. }
  582. }
  583. }
  584. return $output;
  585. }
  586. /**
  587. * Extracts values from an OpenID AX Response.
  588. *
  589. * The values can be returned in two forms:
  590. * - only openid.ax.value.<alias> (for single-valued answers)
  591. * - both openid.ax.count.<alias> and openid.ax.value.<alias>.<count> (for both
  592. * single and multiple-valued answers)
  593. *
  594. * @param $values
  595. * An array as returned by openid_extract_namespace(..., OPENID_NS_AX).
  596. * @param $uris
  597. * An array of identifier URIs.
  598. * @return
  599. * An array of values.
  600. * @see http://openid.net/specs/openid-attribute-exchange-1_0.html#fetch_response
  601. */
  602. function openid_extract_ax_values($values, $uris) {
  603. $output = array();
  604. foreach ($values as $key => $value) {
  605. if (in_array($value, $uris) && preg_match('/^type\.([^.]+)$/', $key, $matches)) {
  606. $alias = $matches[1];
  607. if (isset($values['count.' . $alias])) {
  608. for ($i = 1; $i <= $values['count.' . $alias]; $i++) {
  609. $output[] = $values['value.' . $alias . '.' . $i];
  610. }
  611. }
  612. elseif (isset($values['value.' . $alias])) {
  613. $output[] = $values['value.' . $alias];
  614. }
  615. break;
  616. }
  617. }
  618. return $output;
  619. }
  620. /**
  621. * Determine the available math library GMP vs. BCMath, favouring GMP for performance.
  622. */
  623. function _openid_get_math_library() {
  624. // Not drupal_static(), because a function is not going to disappear and
  625. // change the output of this under any circumstances.
  626. static $library;
  627. if (empty($library)) {
  628. if (function_exists('gmp_add')) {
  629. $library = 'gmp';
  630. }
  631. elseif (function_exists('bcadd')) {
  632. $library = 'bcmath';
  633. }
  634. }
  635. return $library;
  636. }
  637. /**
  638. * Calls the add function from the available math library for OpenID.
  639. */
  640. function _openid_math_add($x, $y) {
  641. $library = _openid_get_math_library();
  642. switch ($library) {
  643. case 'gmp':
  644. return gmp_strval(gmp_add($x, $y));
  645. case 'bcmath':
  646. return bcadd($x, $y);
  647. }
  648. }
  649. /**
  650. * Calls the mul function from the available math library for OpenID.
  651. */
  652. function _openid_math_mul($x, $y) {
  653. $library = _openid_get_math_library();
  654. switch ($library) {
  655. case 'gmp':
  656. return gmp_mul($x, $y);
  657. case 'bcmath':
  658. return bcmul($x, $y);
  659. }
  660. }
  661. /**
  662. * Calls the div function from the available math library for OpenID.
  663. */
  664. function _openid_math_div($x, $y) {
  665. $library = _openid_get_math_library();
  666. switch ($library) {
  667. case 'gmp':
  668. return gmp_div($x, $y);
  669. case 'bcmath':
  670. return bcdiv($x, $y);
  671. }
  672. }
  673. /**
  674. * Calls the cmp function from the available math library for OpenID.
  675. */
  676. function _openid_math_cmp($x, $y) {
  677. $library = _openid_get_math_library();
  678. switch ($library) {
  679. case 'gmp':
  680. return gmp_cmp($x, $y);
  681. case 'bcmath':
  682. return bccomp($x, $y);
  683. }
  684. }
  685. /**
  686. * Calls the mod function from the available math library for OpenID.
  687. */
  688. function _openid_math_mod($x, $y) {
  689. $library = _openid_get_math_library();
  690. switch ($library) {
  691. case 'gmp':
  692. return gmp_mod($x, $y);
  693. case 'bcmath':
  694. return bcmod($x, $y);
  695. }
  696. }
  697. /**
  698. * Calls the pow function from the available math library for OpenID.
  699. */
  700. function _openid_math_pow($x, $y) {
  701. $library = _openid_get_math_library();
  702. switch ($library) {
  703. case 'gmp':
  704. return gmp_pow($x, $y);
  705. case 'bcmath':
  706. return bcpow($x, $y);
  707. }
  708. }
  709. /**
  710. * Calls the mul function from the available math library for OpenID.
  711. */
  712. function _openid_math_powmod($x, $y, $z) {
  713. $library = _openid_get_math_library();
  714. switch ($library) {
  715. case 'gmp':
  716. return gmp_powm($x, $y, $z);
  717. case 'bcmath':
  718. return bcpowmod($x, $y, $z);
  719. }
  720. }
  721. /**
  722. * Provides transition for accounts with possibly invalid OpenID identifiers in authmap.
  723. *
  724. * This function provides a less safe but more unobtrusive procedure for users
  725. * who cannot login with their OpenID identifiers. OpenID identifiers in the
  726. * authmap could be incomplete due to invalid OpenID implementation in previous
  727. * versions of Drupal (e.g. fragment part of the identifier could be missing).
  728. * For more information see http://drupal.org/node/1120290.
  729. *
  730. * @param string $identity
  731. * The user's claimed OpenID identifier.
  732. *
  733. * @return
  734. * A fully-loaded user object if the user is found or FALSE if not found.
  735. */
  736. function _openid_invalid_openid_transition($identity, $response) {
  737. $account = FALSE;
  738. $fallback_account = NULL;
  739. $fallback_identity = $identity;
  740. // Try to strip the fragment if it is present.
  741. if (strpos($fallback_identity, '#') !== FALSE) {
  742. $fallback_identity = preg_replace('/#.*/', '', $fallback_identity);
  743. $fallback_account = user_external_load($fallback_identity);
  744. }
  745. // Try to replace HTTPS with HTTP. OpenID providers often redirect
  746. // from http to https, but Drupal didn't follow the redirect.
  747. if (!$fallback_account && strpos($fallback_identity, 'https://') !== FALSE) {
  748. $fallback_identity = str_replace('https://', 'http://', $fallback_identity);
  749. $fallback_account = user_external_load($fallback_identity);
  750. }
  751. // Try to use original identifier.
  752. if (!$fallback_account && isset($_SESSION['openid']['user_login_values']['openid_identifier'])) {
  753. $fallback_identity = openid_normalize($_SESSION['openid']['user_login_values']['openid_identifier']);
  754. $fallback_account = user_external_load($fallback_identity);
  755. }
  756. if ($fallback_account) {
  757. // Try to extract e-mail address from Simple Registration (SREG) or
  758. // Attribute Exchanges (AX) keys.
  759. $email = '';
  760. $sreg_values = openid_extract_namespace($response, OPENID_NS_SREG, 'sreg', TRUE);
  761. $ax_values = openid_extract_namespace($response, OPENID_NS_AX, 'ax', TRUE);
  762. if (!empty($sreg_values['email']) && valid_email_address($sreg_values['email'])) {
  763. $email = $sreg_values['email'];
  764. }
  765. elseif ($ax_mail_values = openid_extract_ax_values($ax_values, array('http://axschema.org/contact/email', 'http://schema.openid.net/contact/email'))) {
  766. $email = current($ax_mail_values);
  767. }
  768. // If this e-mail address is the same as the e-mail address found in user
  769. // account, login the user and update the claimed identifier.
  770. if ($email && ($email == $fallback_account->mail || $email == $fallback_account->init)) {
  771. $query = db_insert('authmap')
  772. ->fields(array(
  773. 'authname' => $identity,
  774. 'uid' => $fallback_account->uid,
  775. 'module' => 'openid',
  776. ))
  777. ->execute();
  778. 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')));
  779. // Set the account to the found one.
  780. $account = $fallback_account;
  781. }
  782. else {
  783. 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');
  784. }
  785. }
  786. return $account;
  787. }