Subs-OpenID.php 18 KB

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