Subs-OpenID.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.0
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. /* This file handles all of the OpenID interfacing and communications.
  15. void smf_openID_validate(string openid_url, bool allow_immediate_validation = true)
  16. - openid_uri is the URI given by the user
  17. - Validates the URI and changes it to a fully canonicalize URL
  18. - Determines the IDP server and delegation
  19. - optional array of fields to restore when validation complete.
  20. - Redirects the user to the IDP for validation
  21. */
  22. function smf_openID_validate($openid_uri, $return = false, $save_fields = array(), $return_action = null)
  23. {
  24. global $sourcedir, $scripturl, $boardurl, $modSettings;
  25. $openid_url = smf_openID_canonize($openid_uri);
  26. $response_data = smf_openID_getServerInfo($openid_url);
  27. if ($response_data === false)
  28. return 'no_data';
  29. if (($assoc = smf_openID_getAssociation($response_data['server'])) == null)
  30. $assoc = smf_openID_makeAssociation($response_data['server']);
  31. // Before we go wherever it is we are going, store the GET and POST data, because it might be useful when we get back.
  32. $request_time = time();
  33. // Just in case they are doing something else at this time.
  34. while (isset($_SESSION['openid']['saved_data'][$request_time]))
  35. $request_time = md5($request_time);
  36. $_SESSION['openid']['saved_data'][$request_time] = array(
  37. 'get' => $_GET,
  38. 'post' => $_POST,
  39. 'openid_uri' => $openid_url,
  40. 'cookieTime' => $modSettings['cookieTime'],
  41. );
  42. $parameters = array(
  43. 'openid.mode=checkid_setup',
  44. 'openid.trust_root=' . urlencode($scripturl),
  45. 'openid.identity=' . urlencode(empty($response_data['delegate']) ? $openid_url : $response_data['delegate']),
  46. 'openid.assoc_handle=' . urlencode($assoc['handle']),
  47. 'openid.return_to=' . urlencode($scripturl . '?action=openidreturn&sa=' . (!empty($return_action) ? $return_action : $_REQUEST['action']) . '&t=' . $request_time . (!empty($save_fields) ? '&sf=' . base64_encode(serialize($save_fields)) : '')),
  48. );
  49. // If they are logging in but don't yet have an account or they are registering, let's request some additional information
  50. if (($_REQUEST['action'] == 'login2' && !smf_openid_member_exists($openid_url)) || ($_REQUEST['action'] == 'register' || $_REQUEST['action'] == 'register2'))
  51. {
  52. // Email is required.
  53. $parameters[] = 'openid.sreg.required=email';
  54. // The rest is just optional.
  55. $parameters[] = 'openid.sreg.optional=nickname,dob,gender';
  56. }
  57. $redir_url = $response_data['server'] . '?' . implode('&', $parameters);
  58. if ($return)
  59. return $redir_url;
  60. else
  61. redirectexit($redir_url);
  62. }
  63. // Revalidate a user using OpenID. Note that this function will not return when authentication is required.
  64. function smf_openID_revalidate()
  65. {
  66. global $user_settings;
  67. if (isset($_SESSION['openid_revalidate_time']) && $_SESSION['openid_revalidate_time'] > time() - 60)
  68. {
  69. unset($_SESSION['openid_revalidate_time']);
  70. return true;
  71. }
  72. else
  73. smf_openID_validate($user_settings['openid_uri'], false, null, 'revalidate');
  74. // We shouldn't get here.
  75. trigger_error('Hacking attempt...', E_USER_ERROR);
  76. }
  77. function smf_openID_getAssociation($server, $handle = null, $no_delete = false)
  78. {
  79. global $smcFunc;
  80. if (!$no_delete)
  81. {
  82. // Delete the already expired associations.
  83. $smcFunc['db_query']('openid_delete_assoc_old', '
  84. DELETE FROM {db_prefix}openid_assoc
  85. WHERE expires <= {int:current_time}',
  86. array(
  87. 'current_time' => time(),
  88. )
  89. );
  90. }
  91. // Get the association that has the longest lifetime from now.
  92. $request = $smcFunc['db_query']('openid_select_assoc', '
  93. SELECT server_url, handle, secret, issued, expires, assoc_type
  94. FROM {db_prefix}openid_assoc
  95. WHERE server_url = {string:server_url}' . ($handle === null ? '' : '
  96. AND handle = {string:handle}') . '
  97. ORDER BY expires DESC',
  98. array(
  99. 'server_url' => $server,
  100. 'handle' => $handle,
  101. )
  102. );
  103. if ($smcFunc['db_num_rows']($request) == 0)
  104. return null;
  105. $return = $smcFunc['db_fetch_assoc']($request);
  106. $smcFunc['db_free_result']($request);
  107. return $return;
  108. }
  109. function smf_openID_makeAssociation($server)
  110. {
  111. global $smcFunc, $modSettings, $p;
  112. $parameters = array(
  113. 'openid.mode=associate',
  114. );
  115. // We'll need to get our keys for the Diffie-Hellman key exchange.
  116. $dh_keys = smf_openID_setup_DH();
  117. // If we don't support DH we'll have to see if the provider will accept no encryption.
  118. if ($dh_keys === false)
  119. $parameters[] = 'openid.session_type=';
  120. else
  121. {
  122. $parameters[] = 'openid.session_type=DH-SHA1';
  123. $parameters[] = 'openid.dh_consumer_public=' . urlencode(base64_encode(long_to_binary($dh_keys['public'])));
  124. $parameters[] = 'openid.assoc_type=HMAC-SHA1';
  125. }
  126. // The data to post to the server.
  127. $post_data = implode('&', $parameters);
  128. $data = fetch_web_data($server, $post_data);
  129. // Parse the data given.
  130. preg_match_all('~^([^:]+):(.+)$~m', $data, $matches);
  131. $assoc_data = array();
  132. foreach ($matches[1] as $key => $match)
  133. $assoc_data[$match] = $matches[2][$key];
  134. if (!isset($assoc_data['assoc_type']) || (empty($assoc_data['mac_key']) && empty($assoc_data['enc_mac_key'])))
  135. fatal_lang_error('openid_server_bad_response');
  136. // Clean things up a bit.
  137. $handle = isset($assoc_data['assoc_handle']) ? $assoc_data['assoc_handle'] : '';
  138. $issued = time();
  139. $expires = $issued + min((int)$assoc_data['expires_in'], 60);
  140. $assoc_type = isset($assoc_data['assoc_type']) ? $assoc_data['assoc_type'] : '';
  141. // !!! Is this really needed?
  142. foreach (array('dh_server_public', 'enc_mac_key') as $key)
  143. if (isset($assoc_data[$key]))
  144. $assoc_data[$key] = str_replace(' ', '+', $assoc_data[$key]);
  145. // Figure out the Diffie-Hellman secret.
  146. if (!empty($assoc_data['enc_mac_key']))
  147. {
  148. $dh_secret = bcpowmod(binary_to_long(base64_decode($assoc_data['dh_server_public'])), $dh_keys['private'], $p);
  149. $secret = base64_encode(binary_xor(sha1_raw(long_to_binary($dh_secret)), base64_decode($assoc_data['enc_mac_key'])));
  150. }
  151. else
  152. $secret = $assoc_data['mac_key'];
  153. // Store the data
  154. $smcFunc['db_insert']('replace',
  155. '{db_prefix}openid_assoc',
  156. array('server_url' => 'string', 'handle' => 'string', 'secret' => 'string', 'issued' => 'int', 'expires' => 'int', 'assoc_type' => 'string'),
  157. array($server, $handle, $secret, $issued, $expires, $assoc_type),
  158. array('server_url', 'handle')
  159. );
  160. return array(
  161. 'server' => $server,
  162. 'handle' => $assoc_data['assoc_handle'],
  163. 'secret' => $secret,
  164. 'issued' => $issued,
  165. 'expires' => $expires,
  166. 'assoc_type' => $assoc_data['assoc_type'],
  167. );
  168. }
  169. function smf_openID_removeAssociation($handle)
  170. {
  171. global $smcFunc;
  172. $smcFunc['db_query']('openid_remove_association', '
  173. DELETE FROM {db_prefix}openid_assoc
  174. WHERE handle = {string:handle}',
  175. array(
  176. 'handle' => $handle,
  177. )
  178. );
  179. }
  180. function smf_openID_return()
  181. {
  182. global $smcFunc, $user_info, $user_profile, $sourcedir, $modSettings, $context, $sc, $user_settings;
  183. // Is OpenID even enabled?
  184. if (empty($modSettings['enableOpenID']))
  185. fatal_lang_error('no_access', false);
  186. if (!isset($_GET['openid_mode']))
  187. fatal_lang_error('openid_return_no_mode', false);
  188. // !!! Check for error status!
  189. if ($_GET['openid_mode'] != 'id_res')
  190. fatal_lang_error('openid_not_resolved');
  191. // SMF has this annoying habit of removing the + from the base64 encoding. So lets put them back.
  192. foreach (array('openid_assoc_handle', 'openid_invalidate_handle', 'openid_sig', 'sf') as $key)
  193. if (isset($_GET[$key]))
  194. $_GET[$key] = str_replace(' ', '+', $_GET[$key]);
  195. // Did they tell us to remove any associations?
  196. if (!empty($_GET['openid_invalidate_handle']))
  197. smf_openid_removeAssociation($_GET['openid_invalidate_handle']);
  198. $server_info = smf_openid_getServerInfo($_GET['openid_identity']);
  199. // Get the association data.
  200. $assoc = smf_openID_getAssociation($server_info['server'], $_GET['openid_assoc_handle'], true);
  201. if ($assoc === null)
  202. fatal_lang_error('openid_no_assoc');
  203. $secret = base64_decode($assoc['secret']);
  204. $signed = explode(',', $_GET['openid_signed']);
  205. $verify_str = '';
  206. foreach ($signed as $sign)
  207. {
  208. $verify_str .= $sign . ':' . strtr($_GET['openid_' . str_replace('.', '_', $sign)], array('&amp;' => '&')) . "\n";
  209. }
  210. $verify_str = base64_encode(sha1_hmac($verify_str, $secret));
  211. if ($verify_str != $_GET['openid_sig'])
  212. {
  213. fatal_lang_error('openid_sig_invalid', 'critical');
  214. }
  215. if (!isset($_SESSION['openid']['saved_data'][$_GET['t']]))
  216. fatal_lang_error('openid_load_data');
  217. $openid_uri = $_SESSION['openid']['saved_data'][$_GET['t']]['openid_uri'];
  218. $modSettings['cookieTime'] = $_SESSION['openid']['saved_data'][$_GET['t']]['cookieTime'];
  219. if (empty($openid_uri))
  220. fatal_lang_error('openid_load_data');
  221. // Any save fields to restore?
  222. $context['openid_save_fields'] = isset($_GET['sf']) ? unserialize(base64_decode($_GET['sf'])) : array();
  223. // Is there a user with this OpenID_uri?
  224. $result = $smcFunc['db_query']('', '
  225. SELECT passwd, id_member, id_group, lngfile, is_activated, email_address, additional_groups, member_name, password_salt,
  226. openid_uri
  227. FROM {db_prefix}members
  228. WHERE openid_uri = {string:openid_uri}',
  229. array(
  230. 'openid_uri' => $openid_uri,
  231. )
  232. );
  233. $member_found = $smcFunc['db_num_rows']($result);
  234. if (!$member_found && isset($_GET['sa']) && $_GET['sa'] == 'change_uri' && !empty($_SESSION['new_openid_uri']) && $_SESSION['new_openid_uri'] == $openid_uri)
  235. {
  236. // Update the member.
  237. updateMemberData($user_settings['id_member'], array('openid_uri' => $openid_uri));
  238. unset($_SESSION['new_openid_uri']);
  239. $_SESSION['openid'] = array(
  240. 'verified' => true,
  241. 'openid_uri' => $openid_uri,
  242. );
  243. // Send them back to profile.
  244. redirectexit('action=profile;area=authentication;updated');
  245. }
  246. elseif (!$member_found)
  247. {
  248. // Store the received openid info for the user when returned to the registration page.
  249. $_SESSION['openid'] = array(
  250. 'verified' => true,
  251. 'openid_uri' => $openid_uri,
  252. );
  253. if (isset($_GET['openid_sreg_nickname']))
  254. $_SESSION['openid']['nickname'] = $_GET['openid_sreg_nickname'];
  255. if (isset($_GET['openid_sreg_email']))
  256. $_SESSION['openid']['email'] = $_GET['openid_sreg_email'];
  257. if (isset($_GET['openid_sreg_dob']))
  258. $_SESSION['openid']['dob'] = $_GET['openid_sreg_dob'];
  259. if (isset($_GET['openid_sreg_gender']))
  260. $_SESSION['openid']['gender'] = $_GET['openid_sreg_gender'];
  261. // Were we just verifying the registration state?
  262. if (isset($_GET['sa']) && $_GET['sa'] == 'register2')
  263. {
  264. require_once($sourcedir . '/Register.php');
  265. return Register2(true);
  266. }
  267. else
  268. redirectexit('action=register');
  269. }
  270. elseif (isset($_GET['sa']) && $_GET['sa'] == 'revalidate' && $user_settings['openid_uri'] == $openid_uri)
  271. {
  272. $_SESSION['openid_revalidate_time'] = time();
  273. // Restore the get data.
  274. require_once($sourcedir . '/Subs-Auth.php');
  275. $_SESSION['openid']['saved_data'][$_GET['t']]['get']['openid_restore_post'] = $_GET['t'];
  276. $query_string = construct_query_string($_SESSION['openid']['saved_data'][$_GET['t']]['get']);
  277. redirectexit($query_string);
  278. }
  279. else
  280. {
  281. $user_settings = $smcFunc['db_fetch_assoc']($result);
  282. $smcFunc['db_free_result']($result);
  283. $user_settings['passwd'] = sha1(strtolower($user_settings['member_name']) . $secret);
  284. $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
  285. updateMemberData($user_settings['id_member'], array('passwd' => $user_settings['passwd'], 'password_salt' => $user_settings['password_salt']));
  286. // Cleanup on Aisle 5.
  287. $_SESSION['openid'] = array(
  288. 'verified' => true,
  289. 'openid_uri' => $openid_uri,
  290. );
  291. require_once($sourcedir . '/LogInOut.php');
  292. if (!checkActivation())
  293. return;
  294. DoLogin();
  295. }
  296. }
  297. function smf_openID_canonize($uri)
  298. {
  299. // !!! Add in discovery.
  300. if (strpos($uri, 'http://') !== 0 && strpos($uri, 'https://') !== 0)
  301. $uri = 'http://' . $uri;
  302. if (strpos(substr($uri, strpos($uri, '://') + 3), '/') === false)
  303. $uri .= '/';
  304. return $uri;
  305. }
  306. function smf_openid_member_exists($url)
  307. {
  308. global $smcFunc;
  309. $request = $smcFunc['db_query']('openid_member_exists', '
  310. SELECT mem.id_member, mem.member_name
  311. FROM {db_prefix}members AS mem
  312. WHERE mem.openid_uri = {string:openid_uri}',
  313. array(
  314. 'openid_uri' => $url,
  315. )
  316. );
  317. $member = $smcFunc['db_fetch_assoc']($request);
  318. $smcFunc['db_free_result']($request);
  319. return $member;
  320. }
  321. // Prepare for a Diffie-Hellman key exchange.
  322. function smf_openID_setup_DH($regenerate = false)
  323. {
  324. global $p, $g;
  325. // First off, do we have BC Math available?
  326. if (!function_exists('bcpow'))
  327. return false;
  328. // Defined in OpenID spec.
  329. $p = '155172898181473697471232257763715539915724801966915404479707795314057629378541917580651227423698188993727816152646631438561595825688188889951272158842675419950341258706556549803580104870537681476726513255747040765857479291291572334510643245094715007229621094194349783925984760375594985848253359305585439638443';
  330. $g = '2';
  331. // Make sure the scale is set.
  332. bcscale(0);
  333. return smf_openID_get_keys($regenerate);
  334. }
  335. function smf_openID_get_keys($regenerate)
  336. {
  337. global $modSettings, $p, $g;
  338. // Ok lets take the easy way out, are their any keys already defined for us? They are changed in the daily maintenance scheduled task.
  339. if (!empty($modSettings['dh_keys']) && !$regenerate)
  340. {
  341. // Sweeeet!
  342. list ($public, $private) = explode("\n", $modSettings['dh_keys']);
  343. return array(
  344. 'public' => base64_decode($public),
  345. 'private' => base64_decode($private),
  346. );
  347. }
  348. // Dang it, now I have to do math. And it's not just ordinary math, its the evil big interger math. This will take a few seconds.
  349. $private = smf_openid_generate_private_key();
  350. $public = bcpowmod($g, $private, $p);
  351. // Now that we did all that work, lets save it so we don't have to keep doing it.
  352. $keys = array('dh_keys' => base64_encode($public) . "\n" . base64_encode($private));
  353. updateSettings($keys);
  354. return array(
  355. 'public' => $public,
  356. 'private' => $private,
  357. );
  358. }
  359. function smf_openid_generate_private_key()
  360. {
  361. global $p;
  362. static $cache = array();
  363. $byte_string = long_to_binary($p);
  364. if (isset($cache[$byte_string]))
  365. list ($dup, $num_bytes) = $cache[$byte_string];
  366. else
  367. {
  368. $num_bytes = strlen($byte_string) - ($byte_string[0] == "\x00" ? 1 : 0);
  369. $max_rand = bcpow(256, $num_bytes);
  370. $dup = bcmod($max_rand, $num_bytes);
  371. $cache[$byte_string] = array($dup, $num_bytes);
  372. }
  373. do
  374. {
  375. $str = '';
  376. for ($i = 0; $i < $num_bytes; $i += 4)
  377. $str .= pack('L', mt_rand());
  378. $bytes = "\x00" . $str;
  379. $num = binary_to_long($bytes);
  380. } while (bccomp($num, $dup) < 0);
  381. return bcadd(bcmod($num, $p), 1);
  382. }
  383. function smf_openID_getServerInfo($openid_url)
  384. {
  385. global $sourcedir;
  386. require_once($sourcedir . '/Subs-Package.php');
  387. // Get the html and parse it for the openid variable which will tell us where to go.
  388. $webdata = fetch_web_data($openid_url);
  389. if (empty($webdata))
  390. return false;
  391. $response_data = array();
  392. // Some OpenID servers have strange but still valid HTML which makes our job hard.
  393. if (preg_match_all('~<link([\s\S]*?)/?>~i', $webdata, $link_matches) == 0)
  394. fatal_lang_error('openid_server_bad_response');
  395. foreach ($link_matches[1] as $link_match)
  396. {
  397. if (preg_match('~rel="([\s\S]*?)"~i', $link_match, $rel_match) == 0 || preg_match('~href="([\s\S]*?)"~i', $link_match, $href_match) == 0)
  398. continue;
  399. $rels = preg_split('~\s+~', $rel_match[1]);
  400. foreach ($rels as $rel)
  401. if (preg_match('~openid2?\.(server|delegate|provider)~i', $rel, $match) != 0)
  402. $response_data[$match[1]] = $href_match[1];
  403. }
  404. if (empty($response_data['server']))
  405. if (empty($response_data['provider']))
  406. fatal_lang_error('openid_server_bad_response');
  407. else
  408. $response_data['server'] = $response_data['provider'];
  409. return $response_data;
  410. }
  411. function sha1_hmac($data, $key)
  412. {
  413. if (strlen($key) > 64)
  414. $key = sha1_raw($key);
  415. // Pad the key if need be.
  416. $key = str_pad($key, 64, chr(0x00));
  417. $ipad = str_repeat(chr(0x36), 64);
  418. $opad = str_repeat(chr(0x5c), 64);
  419. $hash1 = sha1_raw(($key ^ $ipad) . $data);
  420. $hmac = sha1_raw(($key ^ $opad) . $hash1);
  421. return $hmac;
  422. }
  423. function sha1_raw($text)
  424. {
  425. if (version_compare(PHP_VERSION, '5.0.0') >= 0)
  426. return sha1($text, true);
  427. $hex = sha1($text);
  428. $raw = '';
  429. for ($i = 0; $i < 40; $i += 2)
  430. {
  431. $hexcode = substr($hex, $i, 2);
  432. $charcode = (int) base_convert($hexcode, 16, 10);
  433. $raw .= chr($charcode);
  434. }
  435. return $raw;
  436. }
  437. function binary_to_long($str)
  438. {
  439. $bytes = array_merge(unpack('C*', $str));
  440. $n = 0;
  441. foreach ($bytes as $byte)
  442. {
  443. $n = bcmul($n, 256);
  444. $n = bcadd($n, $byte);
  445. }
  446. return $n;
  447. }
  448. function long_to_binary($value)
  449. {
  450. $cmp = bccomp($value, 0);
  451. if ($cmp < 0)
  452. fatal_error('Only non-negative integers allowed.');
  453. if ($cmp == 0)
  454. return "\x00";
  455. $bytes = array();
  456. while (bccomp($value, 0) > 0)
  457. {
  458. array_unshift($bytes, bcmod($value, 256));
  459. $value = bcdiv($value, 256);
  460. }
  461. if ($bytes && ($bytes[0] > 127))
  462. array_unshift($bytes, 0);
  463. $return = '';
  464. foreach ($bytes as $byte)
  465. $return .= pack('C', $byte);
  466. return $return;
  467. }
  468. function binary_xor($num1, $num2)
  469. {
  470. $return = '';
  471. for ($i = 0; $i < strlen($num2); $i++)
  472. $return .= $num1[$i] ^ $num2[$i];
  473. return $return;
  474. }
  475. // PHP 4 didn't have bcpowmod.
  476. if (!function_exists('bcpowmod') && function_exists('bcpow'))
  477. {
  478. function bcpowmod($num1, $num2, $num3)
  479. {
  480. return bcmod(bcpow($num1, $num2), $num3);
  481. }
  482. }
  483. ?>