openid.module 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. <?php
  2. /**
  3. * @file
  4. * Implement OpenID Relying Party support for Drupal
  5. */
  6. /**
  7. * Implements 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. 'file' => 'openid.pages.inc',
  33. );
  34. return $items;
  35. }
  36. /**
  37. * Implements hook_menu_site_status_alter().
  38. */
  39. function openid_menu_site_status_alter(&$menu_site_status, $path) {
  40. // Allow access to openid/authenticate even if site is in offline mode.
  41. if ($menu_site_status == MENU_SITE_OFFLINE && user_is_anonymous() && $path == 'openid/authenticate') {
  42. $menu_site_status = MENU_SITE_ONLINE;
  43. }
  44. }
  45. /**
  46. * Implements hook_admin_paths().
  47. */
  48. function openid_admin_paths() {
  49. $paths = array(
  50. 'user/*/openid' => TRUE,
  51. 'user/*/openid/delete' => TRUE,
  52. );
  53. return $paths;
  54. }
  55. /**
  56. * Implements hook_help().
  57. */
  58. function openid_help($path, $arg) {
  59. switch ($path) {
  60. case 'user/%/openid':
  61. $output = '<p>' . t('This site supports <a href="@openid-net">OpenID</a>, a secure way to log in to 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>';
  62. $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>';
  63. $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 log in, 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>';
  64. return $output;
  65. case 'admin/help#openid':
  66. $output = '';
  67. $output .= '<h3>' . t('About') . '</h3>';
  68. $output .= '<p>' . t('The OpenID module allows users to log in using the OpenID single sign on service. <a href="@openid-net">OpenID</a> 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 the site being logged into. The main benefit to users is that they 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. For more information, see the online handbook entry for <a href="@handbook">OpenID module</a>.', array('@openid-net' => 'http://openid.net', '@handbook' => 'http://drupal.org/documentation/modules/openid')) . '</p>';
  69. $output .= '<h3>' . t('Uses') . '</h3>';
  70. $output .= '<dl>';
  71. $output .= '<dt>' . t('Logging in with OpenID') . '</dt>';
  72. $output .= '<dd>' . t("To log in using OpenID, a user must already have an OpenID account. Users can then create site 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 helps increase the user base, and offers convenience and security to the users. Because OpenID cannot guarantee a user is legitimate, email verification is still necessary. When logging in, users are presented with the option of entering their OpenID URL, which will look like <em>myusername.openidprovider.com</em>. The 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 the site being logged into record the user's OpenID password.") . '</dd>';
  73. $output .= '</dl>';
  74. return $output;
  75. }
  76. }
  77. /**
  78. * Implements hook_user_insert().
  79. */
  80. function openid_user_insert(&$edit, $account, $category) {
  81. if (!empty($edit['openid_claimed_id'])) {
  82. // The user has registered after trying to log in via OpenID.
  83. if (variable_get('user_email_verification', TRUE)) {
  84. drupal_set_message(t('Once you have verified your e-mail address, you may log in via OpenID.'));
  85. }
  86. user_set_authmaps($account, array('authname_openid' => $edit['openid_claimed_id']));
  87. unset($_SESSION['openid']);
  88. unset($edit['openid_claimed_id']);
  89. }
  90. }
  91. /**
  92. * Implements hook_user_login().
  93. *
  94. * Save openid_identifier to visitor cookie.
  95. */
  96. function openid_user_login(&$edit, $account) {
  97. if (isset($_SESSION['openid'])) {
  98. // The user has logged in via OpenID.
  99. user_cookie_save(array_intersect_key($_SESSION['openid']['user_login_values'], array_flip(array('openid_identifier'))));
  100. unset($_SESSION['openid']);
  101. }
  102. }
  103. /**
  104. * Implements hook_user_logout().
  105. *
  106. * Delete any openid_identifier in visitor cookie.
  107. */
  108. function openid_user_logout($account) {
  109. if (isset($_COOKIE['Drupal_visitor_openid_identifier'])) {
  110. user_cookie_delete('openid_identifier');
  111. }
  112. }
  113. /**
  114. * Implements hook_form_FORM_ID_alter().
  115. */
  116. function openid_form_user_login_block_alter(&$form, &$form_state) {
  117. _openid_user_login_form_alter($form, $form_state);
  118. }
  119. /**
  120. * Implements hook_form_FORM_ID_alter().
  121. */
  122. function openid_form_user_login_alter(&$form, &$form_state) {
  123. _openid_user_login_form_alter($form, $form_state);
  124. }
  125. function _openid_user_login_form_alter(&$form, &$form_state) {
  126. $form['#attached']['css'][] = drupal_get_path('module', 'openid') . '/openid.css';
  127. $form['#attached']['js'][] = drupal_get_path('module', 'openid') . '/openid.js';
  128. $form['#attached']['library'][] = array('system', 'jquery.cookie');
  129. if (!empty($form_state['input']['openid_identifier'])) {
  130. $form['name']['#required'] = FALSE;
  131. $form['pass']['#required'] = FALSE;
  132. unset($form['#submit']);
  133. $form['#validate'] = array('openid_login_validate');
  134. }
  135. $items = array();
  136. $items[] = array(
  137. 'data' => l(t('Log in using OpenID'), '#openid-login', array('external' => TRUE)),
  138. 'class' => array('openid-link'),
  139. );
  140. $items[] = array(
  141. 'data' => l(t('Cancel OpenID login'), '#', array('external' => TRUE)),
  142. 'class' => array('user-link'),
  143. );
  144. $form['openid_links'] = array(
  145. '#theme' => 'item_list',
  146. '#items' => $items,
  147. '#attributes' => array('class' => array('openid-links')),
  148. '#weight' => 1,
  149. );
  150. $form['links']['#weight'] = 2;
  151. $form['openid_identifier'] = array(
  152. '#type' => 'textfield',
  153. '#title' => t('Log in using OpenID'),
  154. '#size' => $form['name']['#size'],
  155. '#maxlength' => 255,
  156. '#weight' => -1,
  157. '#description' => l(t('What is OpenID?'), 'http://openid.net/', array('external' => TRUE)),
  158. );
  159. $form['openid.return_to'] = array('#type' => 'hidden', '#value' => url('openid/authenticate', array('absolute' => TRUE, 'query' => user_login_destination())));
  160. }
  161. /**
  162. * Implements hook_form_FORM_ID_alter().
  163. *
  164. * Prefills the login form with values acquired via OpenID.
  165. */
  166. function openid_form_user_register_form_alter(&$form, &$form_state) {
  167. if (isset($_SESSION['openid']['response'])) {
  168. module_load_include('inc', 'openid');
  169. $response = $_SESSION['openid']['response'];
  170. // Extract Simple Registration keys from the response. We only include
  171. // signed keys as required by OpenID Simple Registration Extension 1.0,
  172. // section 4.
  173. $sreg_values = openid_extract_namespace($response, OPENID_NS_SREG, 'sreg', TRUE);
  174. // Extract Attribute Exchanges keys from the response. We only include
  175. // signed keys. This is not required by the specification, but it is
  176. // recommended by Google, see
  177. // http://googlecode.blogspot.com/2011/05/security-advisory-to-websites-using.html
  178. $ax_values = openid_extract_namespace($response, OPENID_NS_AX, 'ax', TRUE);
  179. if (!empty($sreg_values['nickname'])) {
  180. // Use the nickname returned by Simple Registration if available.
  181. $form['account']['name']['#default_value'] = $sreg_values['nickname'];
  182. }
  183. elseif ($ax_name_values = openid_extract_ax_values($ax_values, array('http://axschema.org/namePerson/friendly', 'http://schema.openid.net/namePerson/friendly'))) {
  184. // Else, use the first nickname returned by AX if available.
  185. $form['account']['name']['#default_value'] = current($ax_name_values);
  186. }
  187. else {
  188. $form['account']['name']['#default_value'] = '';
  189. }
  190. if (!empty($sreg_values['email'])) {
  191. // Use the email returned by Simple Registration if available.
  192. $form['account']['mail']['#default_value'] = $sreg_values['email'];
  193. }
  194. elseif ($ax_mail_values = openid_extract_ax_values($ax_values, array('http://axschema.org/contact/email', 'http://schema.openid.net/contact/email'))) {
  195. // Else, use the first nickname returned by AX if available.
  196. $form['account']['mail']['#default_value'] = current($ax_mail_values);
  197. }
  198. // If user_email_verification is off, hide the password field and just fill
  199. // with random password to avoid confusion.
  200. if (!variable_get('user_email_verification', TRUE)) {
  201. $form['account']['pass']['#type'] = 'hidden';
  202. $form['account']['pass']['#value'] = user_password();
  203. }
  204. $form['openid_claimed_id'] = array(
  205. '#type' => 'value',
  206. '#default_value' => $response['openid.claimed_id'],
  207. );
  208. $form['openid_display'] = array(
  209. '#type' => 'item',
  210. '#title' => t('Your OpenID'),
  211. '#description' => t('This OpenID will be attached to your account after registration.'),
  212. '#markup' => check_plain($response['openid.claimed_id']),
  213. );
  214. }
  215. }
  216. /**
  217. * Login form _validate hook
  218. */
  219. function openid_login_validate($form, &$form_state) {
  220. $return_to = $form_state['values']['openid.return_to'];
  221. if (empty($return_to)) {
  222. $return_to = url('', array('absolute' => TRUE));
  223. }
  224. openid_begin($form_state['values']['openid_identifier'], $return_to, $form_state['values']);
  225. }
  226. /**
  227. * The initial step of OpenID authentication responsible for the following:
  228. * - Perform discovery on the claimed OpenID.
  229. * - If possible, create an association with the Provider's endpoint.
  230. * - Create the authentication request.
  231. * - Perform the appropriate redirect.
  232. *
  233. * @param $claimed_id The OpenID to authenticate
  234. * @param $return_to The endpoint to return to from the OpenID Provider
  235. */
  236. function openid_begin($claimed_id, $return_to = '', $form_values = array()) {
  237. module_load_include('inc', 'openid');
  238. $service = NULL;
  239. $claimed_id = openid_normalize($claimed_id);
  240. $discovery = openid_discovery($claimed_id);
  241. if (!empty($discovery['services'])) {
  242. $service = _openid_select_service($discovery['services']);
  243. }
  244. // Quit if the discovery result was empty or if we can't select any service.
  245. if (!$discovery || !$service) {
  246. form_set_error('openid_identifier', t('Sorry, that is not a valid OpenID. Ensure you have spelled your ID correctly.'));
  247. return;
  248. }
  249. // Set claimed id from discovery.
  250. if (!empty($discovery['claimed_id'])) {
  251. $claimed_id = $discovery['claimed_id'];
  252. }
  253. // Store discovered information in the users' session so we don't have to rediscover.
  254. $_SESSION['openid']['service'] = $service;
  255. // Store the claimed id
  256. $_SESSION['openid']['claimed_id'] = $claimed_id;
  257. // Store the login form values so we can pass them to
  258. // user_exteral_login later.
  259. $_SESSION['openid']['user_login_values'] = $form_values;
  260. // If a supported math library is present, then create an association.
  261. $assoc_handle = '';
  262. if (_openid_get_math_library()) {
  263. $assoc_handle = openid_association($service['uri']);
  264. }
  265. if (in_array('http://specs.openid.net/auth/2.0/server', $service['types'])) {
  266. // User entered an OP Identifier.
  267. $claimed_id = $identity = 'http://specs.openid.net/auth/2.0/identifier_select';
  268. }
  269. else {
  270. // Use Claimed ID and/or OP-Local Identifier from service description, if
  271. // available.
  272. if (!empty($service['claimed_id'])) {
  273. $claimed_id = $service['claimed_id'];
  274. }
  275. $identity = !empty($service['identity']) ? $service['identity'] : $claimed_id;
  276. }
  277. $request = openid_authentication_request($claimed_id, $identity, $return_to, $assoc_handle, $service);
  278. if ($service['version'] == 2) {
  279. openid_redirect($service['uri'], $request);
  280. }
  281. else {
  282. openid_redirect_http($service['uri'], $request);
  283. }
  284. }
  285. /**
  286. * Completes OpenID authentication by validating returned data from the OpenID
  287. * Provider.
  288. *
  289. * @param $response Array of returned values from the OpenID Provider.
  290. *
  291. * @return $response Response values for further processing with
  292. * $response['status'] set to one of 'success', 'failed' or 'cancel'.
  293. */
  294. function openid_complete($response = array()) {
  295. module_load_include('inc', 'openid');
  296. if (count($response) == 0) {
  297. $response = _openid_response();
  298. }
  299. // Default to failed response
  300. $response['status'] = 'failed';
  301. if (isset($_SESSION['openid']['service']['uri']) && isset($_SESSION['openid']['claimed_id'])) {
  302. $service = $_SESSION['openid']['service'];
  303. $claimed_id = $_SESSION['openid']['claimed_id'];
  304. unset($_SESSION['openid']['service']);
  305. unset($_SESSION['openid']['claimed_id']);
  306. if (isset($response['openid.mode'])) {
  307. if ($response['openid.mode'] == 'cancel') {
  308. $response['status'] = 'cancel';
  309. }
  310. else {
  311. if (openid_verify_assertion($service, $response)) {
  312. // OpenID Authentication, section 7.3.2.3 and Appendix A.5:
  313. // The CanonicalID specified in the XRDS document must be used as the
  314. // account key. We rely on the XRI proxy resolver to verify that the
  315. // provider is authorized to respond on behalf of the specified
  316. // identifer (required per Extensible Resource Identifier (XRI)
  317. // (XRI) Resolution Version 2.0, section 14.3):
  318. if (!empty($service['claimed_id'])) {
  319. $response['openid.claimed_id'] = $service['claimed_id'];
  320. }
  321. elseif ($service['version'] == 2) {
  322. // Returned Claimed Identifier could contain unique fragment
  323. // identifier to allow identifier recycling so we need to preserve
  324. // it in the response.
  325. $response_claimed_id = openid_normalize($response['openid.claimed_id']);
  326. // OpenID Authentication, section 11.2:
  327. // If the returned Claimed Identifier is different from the one sent
  328. // to the OpenID Provider, we need to do discovery on the returned
  329. // identififer to make sure that the provider is authorized to
  330. // respond on behalf of this.
  331. if ($response_claimed_id != $claimed_id) {
  332. $discovery = openid_discovery($response['openid.claimed_id']);
  333. if ($discovery && !empty($discovery['services'])) {
  334. $uris = array();
  335. foreach ($discovery['services'] as $discovered_service) {
  336. if (in_array('http://specs.openid.net/auth/2.0/server', $discovered_service['types']) || in_array('http://specs.openid.net/auth/2.0/signon', $discovered_service['types'])) {
  337. $uris[] = $discovered_service['uri'];
  338. }
  339. }
  340. }
  341. if (!in_array($service['uri'], $uris)) {
  342. return $response;
  343. }
  344. }
  345. }
  346. else {
  347. $response['openid.claimed_id'] = $claimed_id;
  348. }
  349. $response['status'] = 'success';
  350. }
  351. }
  352. }
  353. }
  354. return $response;
  355. }
  356. /**
  357. * Perform discovery on a claimed ID to determine the OpenID provider endpoint.
  358. *
  359. * Discovery methods are provided by the hook_openid_discovery_method_info and
  360. * could be further altered using the hook_openid_discovery_method_info_alter.
  361. *
  362. * @param $claimed_id
  363. * The OpenID URL to perform discovery on.
  364. *
  365. * @return
  366. * The resulting discovery array from the first successful discovery method,
  367. * which must contain following keys:
  368. * - 'services' (required) an array of discovered services (including OpenID
  369. * version, endpoint URI, etc).
  370. * - 'claimed_id' (optional) new claimed identifer, found by following HTTP
  371. * redirects during the services discovery.
  372. * If all the discovery method fails or if no appropriate discovery method is
  373. * found, FALSE is returned.
  374. */
  375. function openid_discovery($claimed_id) {
  376. module_load_include('inc', 'openid');
  377. $methods = module_invoke_all('openid_discovery_method_info');
  378. drupal_alter('openid_discovery_method_info', $methods);
  379. // Execute each method in turn and return first successful discovery.
  380. foreach ($methods as $method) {
  381. $discovery = $method($claimed_id);
  382. if (!empty($discovery)) {
  383. return $discovery;
  384. }
  385. }
  386. return FALSE;
  387. }
  388. /**
  389. * Implements hook_openid_discovery_method_info().
  390. *
  391. * Define standard discovery methods.
  392. */
  393. function openid_openid_discovery_method_info() {
  394. // The discovery process will stop as soon as one discovery method succeed.
  395. // We first attempt to discover XRI-based identifiers, then standard XRDS
  396. // identifiers via Yadis and HTML-based discovery, conforming to the OpenID 2.0
  397. // specification.
  398. return array(
  399. 'xri' => '_openid_xri_discovery',
  400. 'xrds' => '_openid_xrds_discovery',
  401. );
  402. }
  403. /**
  404. * OpenID discovery method: perform an XRI discovery.
  405. *
  406. * @see http://openid.net/specs/openid-authentication-2_0.html#discovery
  407. * @see hook_openid_discovery_method_info()
  408. * @see openid_discovery()
  409. *
  410. * @return
  411. * An array of discovered services and claimed identifier or NULL. See
  412. * openid_discovery() for more specific information.
  413. */
  414. function _openid_xri_discovery($claimed_id) {
  415. if (_openid_is_xri($claimed_id)) {
  416. // Resolve XRI using a proxy resolver (Extensible Resource Identifier (XRI)
  417. // Resolution Version 2.0, section 11.2 and 14.3).
  418. $xrds_url = variable_get('xri_proxy_resolver', 'http://xri.net/') . rawurlencode($claimed_id) . '?_xrd_r=application/xrds+xml';
  419. $discovery = _openid_xrds_discovery($xrds_url);
  420. if (!empty($discovery['services']) && is_array($discovery['services'])) {
  421. foreach ($discovery['services'] as $i => &$service) {
  422. $status = $service['xrd']->children(OPENID_NS_XRD)->Status;
  423. if ($status && $status->attributes()->cid == 'verified') {
  424. $service['claimed_id'] = openid_normalize((string)$service['xrd']->children(OPENID_NS_XRD)->CanonicalID);
  425. }
  426. else {
  427. // Ignore service if the Canonical ID could not be verified.
  428. unset($discovery['services'][$i]);
  429. }
  430. }
  431. if (!empty($discovery['services'])) {
  432. return $discovery;
  433. }
  434. }
  435. }
  436. }
  437. /**
  438. * OpenID discovery method: perform a XRDS discovery.
  439. *
  440. * @see http://openid.net/specs/openid-authentication-2_0.html#discovery
  441. * @see hook_openid_discovery_method_info()
  442. * @see openid_discovery()
  443. *
  444. * @return
  445. * An array of discovered services and claimed identifier or NULL. See
  446. * openid_discovery() for more specific information.
  447. */
  448. function _openid_xrds_discovery($claimed_id) {
  449. $services = array();
  450. $xrds_url = $claimed_id;
  451. $scheme = @parse_url($xrds_url, PHP_URL_SCHEME);
  452. if ($scheme == 'http' || $scheme == 'https') {
  453. // For regular URLs, try Yadis resolution first, then HTML-based discovery
  454. $headers = array('Accept' => 'application/xrds+xml');
  455. $result = drupal_http_request($xrds_url, array('headers' => $headers));
  456. // Check for HTTP error and make sure, that we reach the target. If the
  457. // maximum allowed redirects are exhausted, final destination URL isn't
  458. // reached, but drupal_http_request() doesn't return any error.
  459. // @todo Remove the check for 200 HTTP result code after the following issue
  460. // will be fixed: http://drupal.org/node/1096890.
  461. if (!isset($result->error) && $result->code == 200) {
  462. // Replace the user-entered claimed_id if we received a redirect.
  463. if (!empty($result->redirect_url)) {
  464. $claimed_id = openid_normalize($result->redirect_url);
  465. }
  466. if (isset($result->headers['content-type']) && preg_match("/application\/xrds\+xml/", $result->headers['content-type'])) {
  467. // Parse XML document to find URL
  468. $services = _openid_xrds_parse($result->data);
  469. }
  470. else {
  471. $xrds_url = NULL;
  472. if (isset($result->headers['x-xrds-location'])) {
  473. $xrds_url = $result->headers['x-xrds-location'];
  474. }
  475. else {
  476. // Look for meta http-equiv link in HTML head
  477. $xrds_url = _openid_meta_httpequiv('X-XRDS-Location', $result->data);
  478. }
  479. if (!empty($xrds_url)) {
  480. $headers = array('Accept' => 'application/xrds+xml');
  481. $xrds_result = drupal_http_request($xrds_url, array('headers' => $headers));
  482. if (!isset($xrds_result->error)) {
  483. $services = _openid_xrds_parse($xrds_result->data);
  484. }
  485. }
  486. }
  487. // Check for HTML delegation
  488. if (count($services) == 0) {
  489. // Look for 2.0 links
  490. $uri = _openid_link_href('openid2.provider', $result->data);
  491. $identity = _openid_link_href('openid2.local_id', $result->data);
  492. $type = 'http://specs.openid.net/auth/2.0/signon';
  493. // 1.x links
  494. if (empty($uri)) {
  495. $uri = _openid_link_href('openid.server', $result->data);
  496. $identity = _openid_link_href('openid.delegate', $result->data);
  497. $type = 'http://openid.net/signon/1.1';
  498. }
  499. if (!empty($uri)) {
  500. $services[] = array(
  501. 'uri' => $uri,
  502. 'identity' => $identity,
  503. 'types' => array($type),
  504. );
  505. }
  506. }
  507. }
  508. }
  509. if (!empty($services)) {
  510. return array(
  511. 'services' => $services,
  512. 'claimed_id' => $claimed_id,
  513. );
  514. }
  515. }
  516. /**
  517. * Implements hook_openid_normalization_method_info().
  518. *
  519. * Define standard normalization methods.
  520. */
  521. function openid_openid_normalization_method_info() {
  522. // OpenID Authentication 2.0, section 7.2:
  523. // If the User-supplied Identifier looks like an XRI, treat it as such;
  524. // otherwise treat it as an HTTP URL.
  525. return array(
  526. 'xri' => '_openid_xri_normalize',
  527. 'url' => '_openid_url_normalize',
  528. );
  529. }
  530. /**
  531. * Attempt to create a shared secret with the OpenID Provider.
  532. *
  533. * @param $op_endpoint URL of the OpenID Provider endpoint.
  534. *
  535. * @return $assoc_handle The association handle.
  536. */
  537. function openid_association($op_endpoint) {
  538. module_load_include('inc', 'openid');
  539. // Remove Old Associations:
  540. db_delete('openid_association')
  541. ->where('created + expires_in < :request_time', array(':request_time' => REQUEST_TIME))
  542. ->execute();
  543. // Check to see if we have an association for this IdP already
  544. $assoc_handle = db_query("SELECT assoc_handle FROM {openid_association} WHERE idp_endpoint_uri = :endpoint", array(':endpoint' => $op_endpoint))->fetchField();
  545. if (empty($assoc_handle)) {
  546. $mod = OPENID_DH_DEFAULT_MOD;
  547. $gen = OPENID_DH_DEFAULT_GEN;
  548. $r = _openid_dh_rand($mod);
  549. $private = _openid_math_add($r, 1);
  550. $public = _openid_math_powmod($gen, $private, $mod);
  551. // If there is no existing association, then request one
  552. $assoc_request = openid_association_request($public);
  553. $assoc_message = _openid_encode_message(_openid_create_message($assoc_request));
  554. $assoc_options = array(
  555. 'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8'),
  556. 'method' => 'POST',
  557. 'data' => $assoc_message,
  558. );
  559. $assoc_result = drupal_http_request($op_endpoint, $assoc_options);
  560. if (isset($assoc_result->error)) {
  561. return FALSE;
  562. }
  563. $assoc_response = _openid_parse_message($assoc_result->data);
  564. if (isset($assoc_response['mode']) && $assoc_response['mode'] == 'error') {
  565. return FALSE;
  566. }
  567. if ($assoc_response['session_type'] == 'DH-SHA1') {
  568. $spub = _openid_dh_base64_to_long($assoc_response['dh_server_public']);
  569. $enc_mac_key = base64_decode($assoc_response['enc_mac_key']);
  570. $shared = _openid_math_powmod($spub, $private, $mod);
  571. $assoc_response['mac_key'] = base64_encode(_openid_dh_xorsecret($shared, $enc_mac_key));
  572. }
  573. db_insert('openid_association')
  574. ->fields(array(
  575. 'idp_endpoint_uri' => $op_endpoint,
  576. 'session_type' => $assoc_response['session_type'],
  577. 'assoc_handle' => $assoc_response['assoc_handle'],
  578. 'assoc_type' => $assoc_response['assoc_type'],
  579. 'expires_in' => $assoc_response['expires_in'],
  580. 'mac_key' => $assoc_response['mac_key'],
  581. 'created' => REQUEST_TIME,
  582. ))
  583. ->execute();
  584. $assoc_handle = $assoc_response['assoc_handle'];
  585. }
  586. return $assoc_handle;
  587. }
  588. /**
  589. * Authenticate a user or attempt registration.
  590. *
  591. * @param $response Response values from the OpenID Provider.
  592. */
  593. function openid_authentication($response) {
  594. $identity = $response['openid.claimed_id'];
  595. $account = user_external_load($identity);
  596. // Tries to load user account if user_external_load fails due to possibly
  597. // incompletely stored OpenID identifier in the authmap.
  598. if (!isset($account->uid) && variable_get('openid_less_obtrusive_transition', FALSE)) {
  599. module_load_include('inc', 'openid');
  600. $account = _openid_invalid_openid_transition($identity, $response);
  601. }
  602. if (isset($account->uid)) {
  603. if (!variable_get('user_email_verification', TRUE) || $account->login) {
  604. // Check if user is blocked.
  605. $state['values']['name'] = $account->name;
  606. user_login_name_validate(array(), $state);
  607. if (!form_get_errors()) {
  608. // Load global $user and perform final login tasks.
  609. $form_state['uid'] = $account->uid;
  610. user_login_submit(array(), $form_state);
  611. // Let other modules act on OpenID login
  612. module_invoke_all('openid_response', $response, $account);
  613. }
  614. }
  615. else {
  616. drupal_set_message(t('You must validate your email address for this account before logging in via OpenID.'));
  617. }
  618. }
  619. elseif (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
  620. // Register new user.
  621. // Save response for use in openid_form_user_register_form_alter().
  622. $_SESSION['openid']['response'] = $response;
  623. $form_state['values'] = array();
  624. $form_state['values']['op'] = t('Create new account');
  625. drupal_form_submit('user_register_form', $form_state);
  626. if (!empty($form_state['user'])) {
  627. module_invoke_all('openid_response', $response, $form_state['user']);
  628. drupal_goto();
  629. }
  630. $messages = drupal_get_messages('error');
  631. if (empty($form_state['values']['name']) || empty($form_state['values']['mail'])) {
  632. // If the OpenID provider did not provide both a user name and an email
  633. // address, ask the user to complete the registration manually instead of
  634. // showing the error messages about the missing values generated by FAPI.
  635. drupal_set_message(t('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');
  636. }
  637. else {
  638. drupal_set_message(t('Account registration using the information provided by your OpenID provider failed due to the reasons listed below. 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');
  639. // Append form validation errors below the above warning.
  640. foreach ($messages['error'] as $message) {
  641. drupal_set_message($message, 'error');
  642. }
  643. }
  644. // We were unable to register a valid new user. Redirect to the normal
  645. // registration page and prefill with the values we received.
  646. $destination = drupal_get_destination();
  647. unset($_GET['destination']);
  648. drupal_goto('user/register', array('query' => $destination));
  649. }
  650. else {
  651. drupal_set_message(t('Only site administrators can create new user accounts.'), 'error');
  652. }
  653. drupal_goto();
  654. }
  655. function openid_association_request($public) {
  656. module_load_include('inc', 'openid');
  657. $request = array(
  658. 'openid.ns' => OPENID_NS_2_0,
  659. 'openid.mode' => 'associate',
  660. 'openid.session_type' => 'DH-SHA1',
  661. 'openid.assoc_type' => 'HMAC-SHA1'
  662. );
  663. if ($request['openid.session_type'] == 'DH-SHA1' || $request['openid.session_type'] == 'DH-SHA256') {
  664. $cpub = _openid_dh_long_to_base64($public);
  665. $request['openid.dh_consumer_public'] = $cpub;
  666. }
  667. return $request;
  668. }
  669. function openid_authentication_request($claimed_id, $identity, $return_to = '', $assoc_handle = '', $service) {
  670. global $base_url;
  671. module_load_include('inc', 'openid');
  672. $request = array(
  673. 'openid.mode' => 'checkid_setup',
  674. 'openid.identity' => $identity,
  675. 'openid.assoc_handle' => $assoc_handle,
  676. 'openid.return_to' => $return_to,
  677. );
  678. if ($service['version'] == 2) {
  679. $request['openid.ns'] = OPENID_NS_2_0;
  680. $request['openid.claimed_id'] = $claimed_id;
  681. $request['openid.realm'] = $base_url .'/';
  682. }
  683. else {
  684. $request['openid.trust_root'] = $base_url .'/';
  685. }
  686. // Always request Simple Registration. The specification doesn't mandate
  687. // that the Endpoint advertise OPENID_NS_SREG in the service description.
  688. $request['openid.ns.sreg'] = OPENID_NS_SREG;
  689. $request['openid.sreg.required'] = 'nickname,email';
  690. // Request Attribute Exchange, if available.
  691. // We only request the minimum attributes we need here, contributed modules
  692. // can alter the request to add more attribute, and map them to profile fields.
  693. if (in_array(OPENID_NS_AX, $service['types'])) {
  694. $request['openid.ns.ax'] = OPENID_NS_AX;
  695. $request['openid.ax.mode'] = 'fetch_request';
  696. $request['openid.ax.required'] = 'mail_ao,name_ao,mail_son,name_son';
  697. // Implementors disagree on which URIs to use, even for simple
  698. // attributes like name and email (*sigh*). We ask for both axschema.org
  699. // attributes (which are supposed to be newer), and schema.openid.net ones
  700. // (which are supposed to be legacy).
  701. // Attributes as defined by axschema.org.
  702. $request['openid.ax.type.mail_ao'] = 'http://axschema.org/contact/email';
  703. $request['openid.ax.type.name_ao'] = 'http://axschema.org/namePerson/friendly';
  704. // Attributes as defined by schema.openid.net.
  705. $request['openid.ax.type.mail_son'] = 'http://schema.openid.net/contact/email';
  706. $request['openid.ax.type.name_son'] = 'http://schema.openid.net/namePerson/friendly';
  707. }
  708. $request = array_merge($request, module_invoke_all('openid', 'request', $request));
  709. // module_invoke_all() uses array_merge_recursive() which might return nested
  710. // arrays if two or more modules alter a given parameter, resulting in an
  711. // invalid request format. To ensure this doesn't happen, we flatten the returned
  712. // value by taking the last entry in the array if an array is returned.
  713. $flattened_request = array();
  714. foreach ($request as $key => $value) {
  715. if (is_array($value)) {
  716. $flattened_request[$key] = end($value);
  717. }
  718. else {
  719. $flattened_request[$key] = $value;
  720. }
  721. }
  722. return $flattened_request;
  723. }
  724. /**
  725. * Attempt to verify the response received from the OpenID Provider.
  726. *
  727. * @param $service
  728. * Array describing the OpenID provider.
  729. * @param $response
  730. * Array of response values from the provider.
  731. *
  732. * @return boolean
  733. * @see http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4
  734. */
  735. function openid_verify_assertion($service, $response) {
  736. module_load_include('inc', 'openid');
  737. // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.3
  738. // Check the Nonce to protect against replay attacks.
  739. if (!openid_verify_assertion_nonce($service, $response)) {
  740. return FALSE;
  741. }
  742. // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.1
  743. // Verifying the return URL.
  744. if (!openid_verify_assertion_return_url($service, $response)) {
  745. return FALSE;
  746. }
  747. // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4
  748. // Verify the signatures.
  749. $valid = FALSE;
  750. $association = FALSE;
  751. // If the OP returned a openid.invalidate_handle, we have to proceed with
  752. // direct verification: ignore the openid.assoc_handle, even if present.
  753. // See http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.1
  754. if (!empty($response['openid.assoc_handle']) && empty($response['openid.invalidate_handle'])) {
  755. $association = db_query("SELECT * FROM {openid_association} WHERE assoc_handle = :assoc_handle", array(':assoc_handle' => $response['openid.assoc_handle']))->fetchObject();
  756. }
  757. if ($association && isset($association->session_type)) {
  758. // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.2
  759. // Verification using an association.
  760. $valid = openid_verify_assertion_signature($service, $association, $response);
  761. }
  762. else {
  763. // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.2
  764. // Direct verification.
  765. // The verification requests contain all the fields from the response,
  766. // except openid.mode.
  767. $request = $response;
  768. $request['openid.mode'] = 'check_authentication';
  769. $message = _openid_create_message($request);
  770. $options = array(
  771. 'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8'),
  772. 'method' => 'POST',
  773. 'data' => _openid_encode_message($message),
  774. );
  775. $result = drupal_http_request($service['uri'], $options);
  776. if (!isset($result->error)) {
  777. $response = _openid_parse_message($result->data);
  778. if (strtolower(trim($response['is_valid'])) == 'true') {
  779. $valid = TRUE;
  780. if (!empty($response['invalidate_handle'])) {
  781. // This association handle has expired on the OP side, remove it from the
  782. // database to avoid reusing it again on a subsequent authentication request.
  783. // See http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.2.2
  784. db_delete('openid_association')
  785. ->condition('assoc_handle', $response['invalidate_handle'])
  786. ->execute();
  787. }
  788. }
  789. else {
  790. $valid = FALSE;
  791. }
  792. }
  793. }
  794. return $valid;
  795. }
  796. /**
  797. * Verify the signature of the response received from the OpenID provider.
  798. *
  799. * @param $service
  800. * Array describing the OpenID provider.
  801. * @param $association
  802. * Information on the association with the OpenID provider.
  803. * @param $response
  804. * Array of response values from the provider.
  805. *
  806. * @return
  807. * TRUE if the signature is valid and covers all fields required to be signed.
  808. * @see http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4
  809. */
  810. function openid_verify_assertion_signature($service, $association, $response) {
  811. if ($service['version'] == 2) {
  812. // OpenID Authentication 2.0, section 10.1:
  813. // These keys must always be signed.
  814. $mandatory_keys = array('op_endpoint', 'return_to', 'response_nonce', 'assoc_handle');
  815. if (isset($response['openid.claimed_id'])) {
  816. // If present, these two keys must also be signed. According to the spec,
  817. // they are either both present or both absent.
  818. $mandatory_keys[] = 'claimed_id';
  819. $mandatory_keys[] = 'identity';
  820. }
  821. }
  822. else {
  823. // OpenID Authentication 1.1. section 4.3.3.
  824. $mandatory_keys = array('identity', 'return_to');
  825. }
  826. $keys_to_sign = explode(',', $response['openid.signed']);
  827. if (count(array_diff($mandatory_keys, $keys_to_sign)) > 0) {
  828. return FALSE;
  829. }
  830. return _openid_signature($association, $response, $keys_to_sign) === $response['openid.sig'];
  831. }
  832. /**
  833. * Verify that the nonce has not been used in earlier assertions from the same OpenID provider.
  834. *
  835. * @param $service
  836. * Array describing the OpenID provider.
  837. * @param $response
  838. * Array of response values from the provider.
  839. *
  840. * @return
  841. * TRUE if the nonce has not expired and has not been used earlier.
  842. */
  843. function openid_verify_assertion_nonce($service, $response) {
  844. if ($service['version'] != 2) {
  845. return TRUE;
  846. }
  847. if (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z/', $response['openid.response_nonce'], $matches)) {
  848. list(, $year, $month, $day, $hour, $minutes, $seconds) = $matches;
  849. $nonce_timestamp = gmmktime($hour, $minutes, $seconds, $month, $day, $year);
  850. }
  851. else {
  852. 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);
  853. return FALSE;
  854. }
  855. // A nonce with a timestamp to far in the past or future will already have
  856. // been removed and cannot be checked for single use anymore.
  857. $time = time();
  858. $expiry = 900;
  859. if ($nonce_timestamp <= $time - $expiry || $nonce_timestamp >= $time + $expiry) {
  860. 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);
  861. return FALSE;
  862. }
  863. // Record that this nonce was used.
  864. db_insert('openid_nonce')
  865. ->fields(array(
  866. 'idp_endpoint_uri' => $service['uri'],
  867. 'nonce' => $response['openid.response_nonce'],
  868. 'expires' => $nonce_timestamp + $expiry,
  869. ))
  870. ->execute();
  871. // Count the number of times this nonce was used.
  872. $count_used = db_query("SELECT COUNT(*) FROM {openid_nonce} WHERE nonce = :nonce AND idp_endpoint_uri = :idp_endpoint_uri", array(
  873. ':nonce' => $response['openid.response_nonce'],
  874. ':idp_endpoint_uri' => $service['uri'],
  875. ))->fetchField();
  876. if ($count_used == 1) {
  877. return TRUE;
  878. }
  879. else {
  880. watchdog('openid', 'Nonce replay attempt blocked from @ip, nonce: @nonce.', array('@ip' => ip_address(), '@nonce' => $response['openid.response_nonce']), WATCHDOG_CRITICAL);
  881. return FALSE;
  882. }
  883. }
  884. /**
  885. * Verify that openid.return_to matches the current URL.
  886. *
  887. * See OpenID Authentication 2.0, section 11.1. While OpenID Authentication
  888. * 1.1, section 4.3 does not mandate return_to verification, the received
  889. * return_to should still match these constraints.
  890. *
  891. * @param $service
  892. * Array describing the OpenID provider.
  893. * @param $response
  894. * Array of response values from the provider.
  895. *
  896. * @return
  897. * TRUE if return_to is valid, FALSE otherwise.
  898. */
  899. function openid_verify_assertion_return_url($service, $response) {
  900. global $base_url;
  901. $return_to_parts = parse_url($response['openid.return_to']);
  902. $base_url_parts = parse_url($base_url);
  903. $current_parts = parse_url($base_url_parts['scheme'] .'://'. $base_url_parts['host'] . request_uri());
  904. if ($return_to_parts['scheme'] != $current_parts['scheme'] || $return_to_parts['host'] != $current_parts['host'] || $return_to_parts['path'] != $current_parts['path']) {
  905. return FALSE;
  906. }
  907. // Verify that all query parameters in the openid.return_to URL have
  908. // the same value in the current URL. In addition, the current URL
  909. // contains a number of other parameters added by the OpenID Provider.
  910. parse_str(isset($return_to_parts['query']) ? $return_to_parts['query'] : '', $return_to_query_parameters);
  911. foreach ($return_to_query_parameters as $name => $value) {
  912. if (!isset($_GET[$name]) || $_GET[$name] != $value) {
  913. return FALSE;
  914. }
  915. }
  916. return TRUE;
  917. }
  918. /**
  919. * Remove expired nonces from the database.
  920. *
  921. * Implements hook_cron().
  922. */
  923. function openid_cron() {
  924. db_delete('openid_nonce')
  925. ->condition('expires', REQUEST_TIME, '<')
  926. ->execute();
  927. }