openid.inc 26 KB

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