openid.module

You are here

  1. 7 modules/openid/openid.module
  2. 6 modules/openid/openid.module

Implement OpenID Relying Party support for Drupal

Functions

Namesort descending Description
openid_association Attempt to create a shared secret with the OpenID Provider.
openid_association_request
openid_authentication Authenticate a user or attempt registration.
openid_authentication_request
openid_begin The initial step of OpenID authentication responsible for the following:
openid_complete Completes OpenID authentication by validating returned data from the OpenID Provider.
openid_cron Remove expired nonces from the database.
openid_discovery Perform discovery on a claimed ID to determine the OpenID provider endpoint.
openid_form_alter Implementation of hook_form_alter : adds OpenID login to the login forms.
openid_help Implementation of hook_help().
openid_login_validate Login form _validate hook
openid_menu Implementation of hook_menu.
openid_user Implementation of hook_user().
openid_verify_assertion Attempt to verify the response received from the OpenID Provider.
openid_verify_assertion_nonce Verify that the nonce has not been used in earlier assertions from the same OpenID provider.
openid_verify_assertion_signature Verify the signature of the response received from the OpenID provider.

File

modules/openid/openid.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Implement OpenID Relying Party support for Drupal
  5. */
  6. /**
  7. * Implementation of hook_menu.
  8. */
  9. function openid_menu() {
  10. $items['openid/authenticate'] = array(
  11. 'title' => 'OpenID Login',
  12. 'page callback' => 'openid_authentication_page',
  13. 'access callback' => 'user_is_anonymous',
  14. 'type' => MENU_CALLBACK,
  15. 'file' => 'openid.pages.inc',
  16. );
  17. $items['user/%user/openid'] = array(
  18. 'title' => 'OpenID identities',
  19. 'page callback' => 'openid_user_identities',
  20. 'page arguments' => array(1),
  21. 'access callback' => 'user_edit_access',
  22. 'access arguments' => array(1),
  23. 'type' => MENU_LOCAL_TASK,
  24. 'file' => 'openid.pages.inc',
  25. );
  26. $items['user/%user/openid/delete'] = array(
  27. 'title' => 'Delete OpenID',
  28. 'page callback' => 'drupal_get_form',
  29. 'page arguments' => array('openid_user_delete_form', 1),
  30. 'access callback' => 'user_edit_access',
  31. 'access arguments' => array(1),
  32. 'type' => MENU_CALLBACK,
  33. 'file' => 'openid.pages.inc',
  34. );
  35. return $items;
  36. }
  37. /**
  38. * Implementation of hook_help().
  39. */
  40. function openid_help($path, $arg) {
  41. switch ($path) {
  42. case 'user/%/openid':
  43. $output = '<p>'. t('This site supports <a href="@openid-net">OpenID</a>, a secure way to log into many websites using a single username and password. OpenID can reduce the necessity of managing many usernames and passwords for many websites.', array('@openid-net' => 'http://openid.net')) .'</p>';
  44. $output .= '<p>'. t('To use OpenID you must first establish an identity on a public or private OpenID server. If you do not have an OpenID and would like one, look into one of the <a href="@openid-providers">free public providers</a>. You can find out more about OpenID at <a href="@openid-net">this website</a>.', array('@openid-providers' => 'http://openid.net/get/', '@openid-net' => 'http://openid.net')) .'</p>';
  45. $output .= '<p>'. t('If you already have an OpenID, enter the URL to your OpenID server below (e.g. myusername.openidprovider.com). Next time you login, you will be able to use this URL instead of a regular username and password. You can have multiple OpenID servers if you like; just keep adding them here.') .'</p>';
  46. return $output;
  47. case 'admin/help#openid':
  48. $output = '<p>'. t('OpenID is a secure method for logging into many websites with a single username and password. It does not require special software, and it does not share passwords with any site to which it is associated; including your site.') .'</p>';
  49. $output .= '<p>'. t('Users can create accounts using their OpenID, assign one or more OpenIDs to an existing account, and log in using an OpenID. This lowers the barrier to registration, which is good for the site, and offers convenience and security to the users. OpenID is not a trust system, so email verification is still necessary. The benefit stems from the fact that users can have a single password that they can use on many websites. This means they can easily update their single password from a centralized location, rather than having to change dozens of passwords individually.') .'</p>';
  50. $output .= '<p>'. t('The basic concept is as follows: A user has an account on an OpenID server. This account provides them with a unique URL (such as myusername.openidprovider.com). When the user comes to your site, they are presented with the option of entering this URL. Your site then communicates with the OpenID server, asking it to verify the identity of the user. If the user is logged into their OpenID server, the server communicates back to your site, verifying the user. If they are not logged in, the OpenID server will ask the user for their password. At no point does your site record, or need to record the user\'s password.') .'</p>';
  51. $output .= '<p>'. t('More information on OpenID is available at <a href="@openid-net">OpenID.net</a>.', array('@openid-net' => url('http://openid.net'))) .'</p>';
  52. $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@handbook">OpenID module</a>.', array('@handbook' => 'http://drupal.org/handbook/modules/openid')) .'</p>';
  53. return $output;
  54. }
  55. }
  56. /**
  57. * Implementation of hook_user().
  58. */
  59. function openid_user($op, &$edit, &$account, $category = NULL) {
  60. if ($op == 'insert' && isset($_SESSION['openid']['values'])) {
  61. // The user has registered after trying to login via OpenID.
  62. if (variable_get('user_email_verification', TRUE)) {
  63. drupal_set_message(t('Once you have verified your email address, you may log in via OpenID.'));
  64. }
  65. unset($_SESSION['openid']);
  66. }
  67. }
  68. /**
  69. * Implementation of hook_form_alter : adds OpenID login to the login forms.
  70. */
  71. function openid_form_alter(&$form, $form_state, $form_id) {
  72. if ($form_id == 'user_login_block' || $form_id == 'user_login') {
  73. drupal_add_css(drupal_get_path('module', 'openid') .'/openid.css', 'module');
  74. drupal_add_js(drupal_get_path('module', 'openid') .'/openid.js');
  75. if (!empty($form_state['post']['openid_identifier'])) {
  76. $form['name']['#required'] = FALSE;
  77. $form['pass']['#required'] = FALSE;
  78. unset($form['#submit']);
  79. $form['#validate'] = array('openid_login_validate');
  80. }
  81. $items = array();
  82. $items[] = array(
  83. 'data' => l(t('Log in using OpenID'), '#'),
  84. 'class' => 'openid-link',
  85. );
  86. $items[] = array(
  87. 'data' => l(t('Cancel OpenID login'), '#'),
  88. 'class' => 'user-link',
  89. );
  90. $form['openid_links'] = array(
  91. '#value' => theme('item_list', $items),
  92. '#weight' => 1,
  93. );
  94. $form['links']['#weight'] = 2;
  95. $form['openid_identifier'] = array(
  96. '#type' => 'textfield',
  97. '#title' => t('Log in using OpenID'),
  98. '#size' => ($form_id == 'user_login') ? 58 : 13,
  99. '#maxlength' => 255,
  100. '#weight' => -1,
  101. '#description' => l(t('What is OpenID?'), 'http://openid.net/', array('external' => TRUE)),
  102. );
  103. $form['openid.return_to'] = array('#type' => 'hidden', '#value' => url('openid/authenticate', array('absolute' => TRUE, 'query' => user_login_destination())));
  104. }
  105. elseif ($form_id == 'user_register' && isset($_SESSION['openid']['values'])) {
  106. // We were unable to auto-register a new user. Prefill the registration
  107. // form with the values we have.
  108. $form['name']['#default_value'] = $_SESSION['openid']['values']['name'];
  109. $form['mail']['#default_value'] = $_SESSION['openid']['values']['mail'];
  110. // If user_email_verification is off, hide the password field and just fill
  111. // with random password to avoid confusion.
  112. if (!variable_get('user_email_verification', TRUE)) {
  113. $form['pass']['#type'] = 'hidden';
  114. $form['pass']['#value'] = user_password();
  115. }
  116. $form['auth_openid'] = array('#type' => 'hidden', '#value' => $_SESSION['openid']['values']['auth_openid']);
  117. $form['openid_display'] = array(
  118. '#type' => 'item',
  119. '#title' => t('Your OpenID'),
  120. '#description' => t('This OpenID will be attached to your account after registration.'),
  121. '#value' => check_plain($_SESSION['openid']['values']['auth_openid']),
  122. );
  123. }
  124. return $form;
  125. }
  126. /**
  127. * Login form _validate hook
  128. */
  129. function openid_login_validate($form, &$form_state) {
  130. $return_to = $form_state['values']['openid.return_to'];
  131. if (empty($return_to)) {
  132. $return_to = url('', array('absolute' => TRUE));
  133. }
  134. openid_begin($form_state['values']['openid_identifier'], $return_to, $form_state['values']);
  135. }
  136. /**
  137. * The initial step of OpenID authentication responsible for the following:
  138. * - Perform discovery on the claimed OpenID.
  139. * - If possible, create an association with the Provider's endpoint.
  140. * - Create the authentication request.
  141. * - Perform the appropriate redirect.
  142. *
  143. * @param $claimed_id The OpenID to authenticate
  144. * @param $return_to The endpoint to return to from the OpenID Provider
  145. */
  146. function openid_begin($claimed_id, $return_to = '', $form_values = array()) {
  147. module_load_include('inc', 'openid');
  148. $claimed_id = _openid_normalize($claimed_id);
  149. $services = openid_discovery($claimed_id);
  150. if (count($services) == 0) {
  151. form_set_error('openid_identifier', t('Sorry, that is not a valid OpenID. Please ensure you have spelled your ID correctly.'));
  152. return;
  153. }
  154. // Store discovered information in the users' session so we don't have to rediscover.
  155. $_SESSION['openid']['service'] = $services[0];
  156. // Store the claimed id
  157. $_SESSION['openid']['claimed_id'] = $claimed_id;
  158. // Store the login form values so we can pass them to
  159. // user_exteral_login later.
  160. $_SESSION['openid']['user_login_values'] = $form_values;
  161. $op_endpoint = $services[0]['uri'];
  162. // If bcmath is present, then create an association
  163. $assoc_handle = '';
  164. if (function_exists('bcadd')) {
  165. $assoc_handle = openid_association($op_endpoint);
  166. }
  167. // Now that there is an association created, move on
  168. // to request authentication from the IdP
  169. // First check for LocalID. If not found, check for Delegate. Fall
  170. // back to $claimed_id if neither is found.
  171. if (!empty($services[0]['localid'])) {
  172. $identity = $services[0]['localid'];
  173. }
  174. else if (!empty($services[0]['delegate'])) {
  175. $identity = $services[0]['delegate'];
  176. }
  177. else {
  178. $identity = $claimed_id;
  179. }
  180. if (isset($services[0]['types']) && is_array($services[0]['types']) && in_array(OPENID_NS_2_0 .'/server', $services[0]['types'])) {
  181. $claimed_id = $identity = 'http://specs.openid.net/auth/2.0/identifier_select';
  182. }
  183. $authn_request = openid_authentication_request($claimed_id, $identity, $return_to, $assoc_handle, $services[0]['version']);
  184. if ($services[0]['version'] == 2) {
  185. openid_redirect($op_endpoint, $authn_request);
  186. }
  187. else {
  188. openid_redirect_http($op_endpoint, $authn_request);
  189. }
  190. }
  191. /**
  192. * Completes OpenID authentication by validating returned data from the OpenID
  193. * Provider.
  194. *
  195. * @param $response Array of returned values from the OpenID Provider.
  196. *
  197. * @return $response Response values for further processing with
  198. * $response['status'] set to one of 'success', 'failed' or 'cancel'.
  199. */
  200. function openid_complete($response = array()) {
  201. global $base_url;
  202. module_load_include('inc', 'openid');
  203. if (count($response) == 0) {
  204. $response = _openid_response();
  205. }
  206. // Default to failed response
  207. $response['status'] = 'failed';
  208. if (isset($_SESSION['openid']['service']['uri']) && isset($_SESSION['openid']['claimed_id'])) {
  209. $service = $_SESSION['openid']['service'];
  210. $claimed_id = $_SESSION['openid']['claimed_id'];
  211. unset($_SESSION['openid']['service']);
  212. unset($_SESSION['openid']['claimed_id']);
  213. if (isset($response['openid.mode'])) {
  214. if ($response['openid.mode'] == 'cancel') {
  215. $response['status'] = 'cancel';
  216. }
  217. else {
  218. if (openid_verify_assertion($service, $response)) {
  219. // If the returned claimed_id is different from the session claimed_id,
  220. // then we need to do discovery and make sure the op_endpoint matches.
  221. if ($service['version'] == 2 && $response['openid.claimed_id'] != $claimed_id) {
  222. $disco = openid_discovery($response['openid.claimed_id']);
  223. if ($disco[0]['uri'] != $service['uri']) {
  224. return $response;
  225. }
  226. }
  227. else {
  228. $response['openid.claimed_id'] = $claimed_id;
  229. }
  230. // Verify that openid.return_to matches the current URL (see OpenID
  231. // Authentication 2.0, section 11.1).
  232. // While OpenID Authentication 1.1, section 4.3 does not mandate
  233. // return_to verification, the received return_to should still
  234. // match these constraints.
  235. $return_to_parts = parse_url($response['openid.return_to']);
  236. $base_url_parts = parse_url($base_url);
  237. $current_parts = parse_url($base_url_parts['scheme'] .'://'. $base_url_parts['host'] . request_uri());
  238. if ($return_to_parts['scheme'] != $current_parts['scheme'] ||
  239. $return_to_parts['host'] != $current_parts['host'] ||
  240. $return_to_parts['path'] != $current_parts['path']) {
  241. return $response;
  242. }
  243. // Verify that all query parameters in the openid.return_to URL have
  244. // the same value in the current URL. In addition, the current URL
  245. // contains a number of other parameters added by the OpenID Provider.
  246. parse_str(isset($return_to_parts['query']) ? $return_to_parts['query'] : '', $return_to_query_parameters);
  247. foreach ($return_to_query_parameters as $name => $value) {
  248. if (!array_key_exists($name, $_GET) || $_GET[$name] != $value) {
  249. return $response;
  250. }
  251. }
  252. $response['status'] = 'success';
  253. }
  254. }
  255. }
  256. }
  257. return $response;
  258. }
  259. /**
  260. * Perform discovery on a claimed ID to determine the OpenID provider endpoint.
  261. *
  262. * @param $claimed_id The OpenID URL to perform discovery on.
  263. *
  264. * @return Array of services discovered (including OpenID version, endpoint
  265. * URI, etc).
  266. */
  267. function openid_discovery($claimed_id) {
  268. module_load_include('inc', 'openid');
  269. module_load_include('inc', 'openid', 'xrds');
  270. $services = array();
  271. $xrds_url = $claimed_id;
  272. if (_openid_is_xri($claimed_id)) {
  273. $xrds_url = 'http://xri.net/'. $claimed_id;
  274. }
  275. $url = @parse_url($xrds_url);
  276. if ($url['scheme'] == 'http' || $url['scheme'] == 'https') {
  277. // For regular URLs, try Yadis resolution first, then HTML-based discovery
  278. $headers = array('Accept' => 'application/xrds+xml');
  279. $result = drupal_http_request($xrds_url, $headers);
  280. if (!isset($result->error)) {
  281. if (isset($result->headers['Content-Type']) && preg_match("/application\/xrds\+xml/", $result->headers['Content-Type'])) {
  282. // Parse XML document to find URL
  283. $services = xrds_parse($result->data);
  284. }
  285. else {
  286. $xrds_url = NULL;
  287. if (isset($result->headers['X-XRDS-Location'])) {
  288. $xrds_url = $result->headers['X-XRDS-Location'];
  289. }
  290. else {
  291. // Look for meta http-equiv link in HTML head
  292. $xrds_url = _openid_meta_httpequiv('X-XRDS-Location', $result->data);
  293. }
  294. if (!empty($xrds_url)) {
  295. $headers = array('Accept' => 'application/xrds+xml');
  296. $xrds_result = drupal_http_request($xrds_url, $headers);
  297. if (!isset($xrds_result->error)) {
  298. $services = xrds_parse($xrds_result->data);
  299. }
  300. }
  301. }
  302. // Check for HTML delegation
  303. if (count($services) == 0) {
  304. // Look for 2.0 links
  305. $uri = _openid_link_href('openid2.provider', $result->data);
  306. $delegate = _openid_link_href('openid2.local_id', $result->data);
  307. $version = 2;
  308. // 1.0 links
  309. if (empty($uri)) {
  310. $uri = _openid_link_href('openid.server', $result->data);
  311. $delegate = _openid_link_href('openid.delegate', $result->data);
  312. $version = 1;
  313. }
  314. if (!empty($uri)) {
  315. $services[] = array('uri' => $uri, 'delegate' => $delegate, 'version' => $version);
  316. }
  317. }
  318. }
  319. }
  320. return $services;
  321. }
  322. /**
  323. * Attempt to create a shared secret with the OpenID Provider.
  324. *
  325. * @param $op_endpoint URL of the OpenID Provider endpoint.
  326. *
  327. * @return $assoc_handle The association handle.
  328. */
  329. function openid_association($op_endpoint) {
  330. module_load_include('inc', 'openid');
  331. // Remove Old Associations:
  332. db_query("DELETE FROM {openid_association} WHERE created + expires_in < %d", time());
  333. // Check to see if we have an association for this IdP already
  334. $assoc_handle = db_result(db_query("SELECT assoc_handle FROM {openid_association} WHERE idp_endpoint_uri = '%s'", $op_endpoint));
  335. if (empty($assoc_handle)) {
  336. $mod = OPENID_DH_DEFAULT_MOD;
  337. $gen = OPENID_DH_DEFAULT_GEN;
  338. $r = _openid_dh_rand($mod);
  339. $private = bcadd($r, 1);
  340. $public = bcpowmod($gen, $private, $mod);
  341. // If there is no existing association, then request one
  342. $assoc_request = openid_association_request($public);
  343. $assoc_message = _openid_encode_message(_openid_create_message($assoc_request));
  344. $assoc_headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
  345. $assoc_result = drupal_http_request($op_endpoint, $assoc_headers, 'POST', $assoc_message);
  346. if (isset($assoc_result->error)) {
  347. return FALSE;
  348. }
  349. $assoc_response = _openid_parse_message($assoc_result->data);
  350. if (isset($assoc_response['mode']) && $assoc_response['mode'] == 'error') {
  351. return FALSE;
  352. }
  353. if ($assoc_response['session_type'] == 'DH-SHA1') {
  354. $spub = _openid_dh_base64_to_long($assoc_response['dh_server_public']);
  355. $enc_mac_key = base64_decode($assoc_response['enc_mac_key']);
  356. $shared = bcpowmod($spub, $private, $mod);
  357. $assoc_response['mac_key'] = base64_encode(_openid_dh_xorsecret($shared, $enc_mac_key));
  358. }
  359. db_query("INSERT INTO {openid_association} (idp_endpoint_uri, session_type, assoc_handle, assoc_type, expires_in, mac_key, created) VALUES('%s', '%s', '%s', '%s', %d, '%s', %d)",
  360. $op_endpoint, $assoc_response['session_type'], $assoc_response['assoc_handle'], $assoc_response['assoc_type'], $assoc_response['expires_in'], $assoc_response['mac_key'], time());
  361. $assoc_handle = $assoc_response['assoc_handle'];
  362. }
  363. return $assoc_handle;
  364. }
  365. /**
  366. * Authenticate a user or attempt registration.
  367. *
  368. * @param $response Response values from the OpenID Provider.
  369. */
  370. function openid_authentication($response) {
  371. module_load_include('inc', 'openid');
  372. $identity = $response['openid.claimed_id'];
  373. $account = user_external_load($identity);
  374. if (isset($account->uid)) {
  375. if (!variable_get('user_email_verification', TRUE) || $account->login) {
  376. user_external_login($account, $_SESSION['openid']['user_login_values']);
  377. }
  378. else {
  379. drupal_set_message(t('You must validate your email address for this account before logging in via OpenID'));
  380. }
  381. }
  382. elseif (variable_get('user_register', 1)) {
  383. // Register new user
  384. $form_state['redirect'] = NULL;
  385. // Only signed SREG keys are included as required by OpenID Simple
  386. // Registration Extension 1.0, section 4.
  387. $signed_keys = explode(',', $response['openid.signed']);
  388. $form_state['values']['name'] = in_array('sreg.nickname', $signed_keys) ? $response['openid.sreg.nickname'] : '';
  389. $form_state['values']['mail'] = in_array('sreg.email', $signed_keys) ? $response['openid.sreg.email'] : '';
  390. $form_state['values']['pass'] = user_password();
  391. $form_state['values']['status'] = variable_get('user_register', 1) == 1;
  392. $form_state['values']['response'] = $response;
  393. $form_state['values']['auth_openid'] = $identity;
  394. if (empty($form_state['values']['name']) && empty($form_state['values']['mail'])) {
  395. drupal_set_message(t('Please complete the registration by filling out the form below. If you already have an account, you can <a href="@login">log in</a> now and add your OpenID under "My account".', array('@login' => url('user/login'))), 'warning');
  396. $success = FALSE;
  397. }
  398. else {
  399. $form = drupal_retrieve_form('user_register', $form_state);
  400. drupal_prepare_form('user_register', $form, $form_state);
  401. drupal_validate_form('user_register', $form, $form_state);
  402. $success = !form_get_errors();
  403. if (!$success) {
  404. drupal_set_message(t('Account registration using the information provided by your OpenID provider failed due to the reasons listed below. Please complete the registration by filling out the form below. If you already have an account, you can <a href="@login">log in</a> now and add your OpenID under "My account".', array('@login' => url('user/login'))), 'warning');
  405. // Append form validation errors below the above warning.
  406. $messages = drupal_get_messages('error');
  407. foreach ($messages['error'] as $message) {
  408. drupal_set_message( $message, 'error');
  409. }
  410. }
  411. }
  412. if (!$success) {
  413. // We were unable to register a valid new user, redirect to standard
  414. // user/register and prefill with the values we received.
  415. $_SESSION['openid']['values'] = $form_state['values'];
  416. // We'll want to redirect back to the same place.
  417. $destination = drupal_get_destination();
  418. unset($_REQUEST['destination']);
  419. drupal_goto('user/register', $destination);
  420. }
  421. else {
  422. unset($form_state['values']['response']);
  423. $account = user_save('', $form_state['values']);
  424. // Terminate if an error occured during user_save().
  425. if (!$account) {
  426. drupal_set_message(t("Error saving user account."), 'error');
  427. drupal_goto();
  428. }
  429. user_external_login($account);
  430. }
  431. drupal_redirect_form($form, $form_state['redirect']);
  432. }
  433. else {
  434. drupal_set_message(t('Only site administrators can create new user accounts.'), 'error');
  435. }
  436. drupal_goto();
  437. }
  438. function openid_association_request($public) {
  439. module_load_include('inc', 'openid');
  440. $request = array(
  441. 'openid.ns' => OPENID_NS_2_0,
  442. 'openid.mode' => 'associate',
  443. 'openid.session_type' => 'DH-SHA1',
  444. 'openid.assoc_type' => 'HMAC-SHA1'
  445. );
  446. if ($request['openid.session_type'] == 'DH-SHA1' || $request['openid.session_type'] == 'DH-SHA256') {
  447. $cpub = _openid_dh_long_to_base64($public);
  448. $request['openid.dh_consumer_public'] = $cpub;
  449. }
  450. return $request;
  451. }
  452. function openid_authentication_request($claimed_id, $identity, $return_to = '', $assoc_handle = '', $version = 2) {
  453. global $base_url;
  454. module_load_include('inc', 'openid');
  455. $ns = ($version == 2) ? OPENID_NS_2_0 : OPENID_NS_1_0;
  456. $request = array(
  457. 'openid.ns' => $ns,
  458. 'openid.mode' => 'checkid_setup',
  459. 'openid.identity' => $identity,
  460. 'openid.claimed_id' => $claimed_id,
  461. 'openid.assoc_handle' => $assoc_handle,
  462. 'openid.return_to' => $return_to,
  463. );
  464. if ($version == 2) {
  465. $request['openid.realm'] = $base_url . '/';
  466. }
  467. else {
  468. $request['openid.trust_root'] = $base_url . '/';
  469. }
  470. // Simple Registration
  471. $request['openid.sreg.required'] = 'nickname,email';
  472. $request['openid.ns.sreg'] = "http://openid.net/extensions/sreg/1.1";
  473. $request = array_merge($request, module_invoke_all('openid', 'request', $request));
  474. return $request;
  475. }
  476. /**
  477. * Attempt to verify the response received from the OpenID Provider.
  478. *
  479. * @param $service
  480. * Array describing the OpenID provider.
  481. * @param $response
  482. * Array of response values from the provider.
  483. *
  484. * @return boolean
  485. */
  486. function openid_verify_assertion($service, $response) {
  487. module_load_include('inc', 'openid');
  488. // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.3
  489. // Check the Nonce to protect against replay attacks.
  490. if (!openid_verify_assertion_nonce($service, $response)) {
  491. return FALSE;
  492. }
  493. // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4
  494. // Verify the signatures.
  495. $valid = FALSE;
  496. $association = db_fetch_object(db_query("SELECT * FROM {openid_association} WHERE idp_endpoint_uri = '%s' AND assoc_handle = '%s'", $service['uri'], $response['openid.assoc_handle']));
  497. if ($association && isset($association->session_type)) {
  498. // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.2
  499. // Verification using an association.
  500. $valid = openid_verify_assertion_signature($service, $association, $response);
  501. }
  502. else {
  503. // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.3
  504. // Direct verification.
  505. $request = $response;
  506. $request['openid.mode'] = 'check_authentication';
  507. $message = _openid_create_message($request);
  508. $headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
  509. $result = drupal_http_request($service['uri'], $headers, 'POST', _openid_encode_message($message));
  510. if (!isset($result->error)) {
  511. $response = _openid_parse_message($result->data);
  512. if (strtolower(trim($response['is_valid'])) == 'true') {
  513. $valid = TRUE;
  514. }
  515. else {
  516. $valid = FALSE;
  517. }
  518. }
  519. }
  520. return $valid;
  521. }
  522. /**
  523. * Verify the signature of the response received from the OpenID provider.
  524. *
  525. * @param $service
  526. * Array describing the OpenID provider.
  527. * @param $association
  528. * Information on the association with the OpenID provider.
  529. * @param $response
  530. * Array of response values from the provider.
  531. *
  532. * @return
  533. * TRUE if the signature is valid and covers all fields required to be signed.
  534. * @see http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4
  535. */
  536. function openid_verify_assertion_signature($service, $association, $response) {
  537. if ($service['version'] == 2) {
  538. // OpenID Authentication 2.0, section 10.1:
  539. // These keys must always be signed.
  540. $mandatory_keys = array('op_endpoint', 'return_to', 'response_nonce', 'assoc_handle');
  541. if (isset($response['openid.claimed_id'])) {
  542. // If present, these two keys must also be signed. According to the spec,
  543. // they are either both present or both absent.
  544. $mandatory_keys[] = 'claimed_id';
  545. $mandatory_keys[] = 'identity';
  546. }
  547. }
  548. else {
  549. // OpenID Authentication 1.1. section 4.3.3.
  550. $mandatory_keys = array('identity', 'return_to');
  551. }
  552. $keys_to_sign = explode(',', $response['openid.signed']);
  553. if (count(array_diff($mandatory_keys, $keys_to_sign)) > 0) {
  554. return FALSE;
  555. }
  556. return _openid_signature($association, $response, $keys_to_sign) == $response['openid.sig'];
  557. }
  558. /**
  559. * Verify that the nonce has not been used in earlier assertions from the same OpenID provider.
  560. *
  561. * @param $service
  562. * Array describing the OpenID provider.
  563. * @param $response
  564. * Array of response values from the provider.
  565. *
  566. * @return
  567. * TRUE if the nonce has not expired and has not been used earlier.
  568. */
  569. function openid_verify_assertion_nonce($service, $response) {
  570. if ($service['version'] != 2) {
  571. return TRUE;
  572. }
  573. if (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z/', $response['openid.response_nonce'], $matches)) {
  574. list(, $year, $month, $day, $hour, $minutes, $seconds) = $matches;
  575. $nonce_timestamp = gmmktime($hour, $minutes, $seconds, $month, $day, $year);
  576. }
  577. else {
  578. watchdog('openid', 'Nonce from @endpoint rejected because it is not correctly formatted, nonce: @nonce.', array('@endpoint' => $service['uri'], '@nonce' => $response['openid.response_nonce']), WATCHDOG_WARNING);
  579. return FALSE;
  580. }
  581. // A nonce with a timestamp to far in the past or future will already have
  582. // been removed and cannot be checked for single use anymore.
  583. $time = time();
  584. $expiry = 900;
  585. if ($nonce_timestamp <= $time - $expiry || $nonce_timestamp >= $time + $expiry) {
  586. watchdog('openid', 'Nonce received from @endpoint is out of range (time difference: @intervals). Check possible clock skew.', array('@endpoint' => $service['uri'], '@interval' => $time - $nonce_timestamp), WATCHDOG_WARNING);
  587. return FALSE;
  588. }
  589. // Record that this nonce was used.
  590. db_query("INSERT INTO {openid_nonce} (idp_endpoint_uri, nonce, expires) VALUES ('%s', '%s', %d)", $service['uri'], $response['openid.response_nonce'], $nonce_timestamp + $expiry);
  591. // Count the number of times this nonce was used.
  592. $count_used = db_result(db_query("SELECT COUNT(*) FROM {openid_nonce} WHERE nonce = '%s' AND idp_endpoint_uri = '%s'", $response['openid.response_nonce'], $service['uri']));
  593. if ($count_used == 1) {
  594. return TRUE;
  595. }
  596. else {
  597. watchdog('openid', 'Nonce replay attempt blocked from @ip, nonce: @nonce.', array('@ip' => ip_address(), '@nonce' => $response['openid.response_nonce']), WATCHDOG_CRITICAL);
  598. return FALSE;
  599. }
  600. }
  601. /**
  602. * Remove expired nonces from the database.
  603. *
  604. * Implementation of hook_cron().
  605. */
  606. function openid_cron() {
  607. db_query("DELETE FROM {openid_nonce} WHERE expires < %d", time());
  608. }