openid.inc 25 KB

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