Subs-OpenID.php 18 KB

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