openid.module 21.4 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php
// $Id$

/**
 * @file
 * Implement OpenID Relying Party support for Drupal
 */

/**
10
 * Implement hook_menu().
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 */
function openid_menu() {
  $items['openid/authenticate'] = array(
    'title' => 'OpenID Login',
    'page callback' => 'openid_authentication_page',
    'access callback' => 'user_is_anonymous',
    'type' => MENU_CALLBACK,
  );
  $items['user/%user/openid'] = array(
    'title' => 'OpenID identities',
    'page callback' => 'openid_user_identities',
    'page arguments' => array(1),
    'access callback' => 'user_edit_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );
  $items['user/%user/openid/delete'] = array(
    'title' => 'Delete OpenID',
29 30
    'page callback' => 'drupal_get_form',
    'page arguments' => array('openid_user_delete_form', 1),
31 32
    'access callback' => 'user_edit_access',
    'access arguments' => array(1),
33 34 35 36 37 38
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
39
 * Implement hook_help().
40
 */
41 42
function openid_help($path, $arg) {
  switch ($path) {
43
    case 'user/%/openid':
44 45
      $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>';
      $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>';
46
      $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>';
47 48
      return $output;

49
    case 'admin/help#openid':
50 51 52
      $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>';
      $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>';
      $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>';
53
      $output .= '<p>' . t('More information on OpenID is available at <a href="@openid-net">OpenID.net</a>.', array('@openid-net' => 'http://openid.net')) . '</p>';
54
      $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>';
55
      return $output;
56 57 58 59
  }
}

/**
60
 * Implement hook_user_insert().
61
 */
62
function openid_user_insert(&$edit, $account, $category) {
63
  if (isset($_SESSION['openid']['values'])) {
64 65 66 67 68 69 70 71 72
    // The user has registered after trying to login via OpenID.
    if (variable_get('user_email_verification', TRUE)) {
      drupal_set_message(t('Once you have verified your email address, you may log in via OpenID.'));
    }
    unset($_SESSION['openid']);
  }
}

/**
73
 * Implement hook_form_FORM_ID_alter().
74
 */
75 76 77 78 79
function openid_form_user_login_block_alter(&$form, &$form_state) {
  _openid_user_login_form_alter($form, $form_state);
}

/**
80
 * Implement hook_form_FORM_ID_alter().
81 82 83 84
 */
function openid_form_user_login_alter(&$form, &$form_state) {
  _openid_user_login_form_alter($form, $form_state);
}
85

86 87 88
function _openid_user_login_form_alter(&$form, &$form_state) {
  drupal_add_css(drupal_get_path('module', 'openid') . '/openid.css');
  drupal_add_js(drupal_get_path('module', 'openid') . '/openid.js');
89
  if (!empty($form_state['input']['openid_identifier'])) {
90 91 92 93
    $form['name']['#required'] = FALSE;
    $form['pass']['#required'] = FALSE;
    unset($form['#submit']);
    $form['#validate'] = array('openid_login_validate');
94
  }
95 96 97 98

  $items = array();
  $items[] = array(
    'data' => l(t('Log in using OpenID'), '#'),
99
    'class' => array('openid-link'),
100 101 102
  );
  $items[] = array(
    'data' => l(t('Cancel OpenID login'), '#'),
103
    'class' => array('user-link'),
104 105 106 107 108 109 110 111 112 113 114 115
  );

  $form['openid_links'] = array(
    '#markup' => theme('item_list', $items),
    '#weight' => 1,
  );

  $form['links']['#weight'] = 2;

  $form['openid_identifier'] = array(
    '#type' => 'textfield',
    '#title' => t('Log in using OpenID'),
116
    '#size' => $form['name']['#size'],
117 118 119 120 121 122 123 124
    '#maxlength' => 255,
    '#weight' => -1,
    '#description' => l(t('What is OpenID?'), 'http://openid.net/', array('external' => TRUE)),
  );
  $form['openid.return_to'] = array('#type' => 'hidden', '#value' => url('openid/authenticate', array('absolute' => TRUE, 'query' => drupal_get_destination())));
}

/**
125
 * Implement hook_form_alter(). Adds OpenID login to the login forms.
126 127
 */
function openid_form_user_register_alter(&$form, &$form_state) {
128
  if (isset($_SESSION['openid']['values'])) {
129 130
    // We were unable to auto-register a new user. Prefill the registration
    // form with the values we have.
131 132
    $form['name']['#default_value'] = $_SESSION['openid']['values']['name'];
    $form['mail']['#default_value'] = $_SESSION['openid']['values']['mail'];
133 134 135 136 137 138
    // If user_email_verification is off, hide the password field and just fill
    // with random password to avoid confusion.
    if (!variable_get('user_email_verification', TRUE)) {
      $form['pass']['#type'] = 'hidden';
      $form['pass']['#value'] = user_password();
    }
139
    $form['auth_openid'] = array('#type' => 'hidden', '#value' => $_SESSION['openid']['values']['auth_openid']);
140 141 142 143 144 145 146 147 148 149 150 151
  }
}

/**
 * Login form _validate hook
 */
function openid_login_validate($form, &$form_state) {
  $return_to = $form_state['values']['openid.return_to'];
  if (empty($return_to)) {
    $return_to = url('', array('absolute' => TRUE));
  }

152
  openid_begin($form_state['values']['openid_identifier'], $return_to, $form_state['values']);
153 154 155 156 157 158 159 160 161 162 163 164
}

/**
 * The initial step of OpenID authentication responsible for the following:
 *  - Perform discovery on the claimed OpenID.
 *  - If possible, create an association with the Provider's endpoint.
 *  - Create the authentication request.
 *  - Perform the appropriate redirect.
 *
 * @param $claimed_id The OpenID to authenticate
 * @param $return_to The endpoint to return to from the OpenID Provider
 */
165
function openid_begin($claimed_id, $return_to = '', $form_values = array()) {
166
  module_load_include('inc', 'openid');
167 168 169 170 171

  $claimed_id = _openid_normalize($claimed_id);

  $services = openid_discovery($claimed_id);
  if (count($services) == 0) {
172
    form_set_error('openid_identifier', t('Sorry, that is not a valid OpenID. Please ensure you have spelled your ID correctly.'));
173 174 175
    return;
  }

176 177 178 179
  // Store discovered information in the users' session so we don't have to rediscover.
  $_SESSION['openid']['service'] = $services[0];
  // Store the claimed id
  $_SESSION['openid']['claimed_id'] = $claimed_id;
180 181
  // Store the login form values so we can pass them to
  // user_exteral_login later.
182
  $_SESSION['openid']['user_login_values'] = $form_values;
183

184
  $op_endpoint = $services[0]['uri'];
185 186 187 188 189 190 191 192
  // If bcmath is present, then create an association
  $assoc_handle = '';
  if (function_exists('bcadd')) {
    $assoc_handle = openid_association($op_endpoint);
  }

  // Now that there is an association created, move on
  // to request authentication from the IdP
193 194 195 196 197
  // First check for LocalID. If not found, check for Delegate. Fall
  // back to $claimed_id if neither is found.
  if (!empty($services[0]['localid'])) {
    $identity = $services[0]['localid'];
  }
198
  elseif (!empty($services[0]['delegate'])) {
199 200 201 202 203
    $identity = $services[0]['delegate'];
  }
  else {
    $identity = $claimed_id;
  }
204

205
  if (isset($services[0]['types']) && is_array($services[0]['types']) && in_array(OPENID_NS_2_0 . '/server', $services[0]['types'])) {
206
    $identity = 'http://specs.openid.net/auth/2.0/identifier_select';
207
  }
208 209 210 211 212 213 214 215 216 217 218 219 220 221
  $authn_request = openid_authentication_request($claimed_id, $identity, $return_to, $assoc_handle, $services[0]['version']);

  if ($services[0]['version'] == 2) {
    openid_redirect($op_endpoint, $authn_request);
  }
  else {
    openid_redirect_http($op_endpoint, $authn_request);
  }
}

/**
 * Completes OpenID authentication by validating returned data from the OpenID
 * Provider.
 *
222
 * @param $response Array of returned values from the OpenID Provider.
223 224 225 226
 *
 * @return $response Response values for further processing with
 *   $response['status'] set to one of 'success', 'failed' or 'cancel'.
 */
227
function openid_complete($response = array()) {
228
  module_load_include('inc', 'openid');
229

230 231 232
  if (count($response) == 0) {
    $response = _openid_response();
  }
233

234 235
  // Default to failed response
  $response['status'] = 'failed';
236 237 238 239 240
  if (isset($_SESSION['openid']['service']['uri']) && isset($_SESSION['openid']['claimed_id'])) {
    $service = $_SESSION['openid']['service'];
    $claimed_id = $_SESSION['openid']['claimed_id'];
    unset($_SESSION['openid']['service']);
    unset($_SESSION['openid']['claimed_id']);
241 242 243 244 245
    if (isset($response['openid.mode'])) {
      if ($response['openid.mode'] == 'cancel') {
        $response['status'] = 'cancel';
      }
      else {
246 247 248 249 250 251 252 253 254 255 256 257
        if (openid_verify_assertion($service['uri'], $response)) {
          // If the returned claimed_id is different from the session claimed_id,
          // then we need to do discovery and make sure the op_endpoint matches.
          if ($service['version'] == 2 && $response['openid.claimed_id'] != $claimed_id) {
            $disco = openid_discovery($response['openid.claimed_id']);
            if ($disco[0]['uri'] != $service['uri']) {
              return $response;
            }
          }
          else {
            $response['openid.claimed_id'] = $claimed_id;
          }
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
          $response['status'] = 'success';
        }
      }
    }
  }
  return $response;
}

/**
 * Perform discovery on a claimed ID to determine the OpenID provider endpoint.
 *
 * @param $claimed_id The OpenID URL to perform discovery on.
 *
 * @return Array of services discovered (including OpenID version, endpoint
 * URI, etc).
 */
function openid_discovery($claimed_id) {
275 276
  module_load_include('inc', 'openid');
  module_load_include('inc', 'openid', 'xrds');
277 278 279 280 281

  $services = array();

  $xrds_url = $claimed_id;
  if (_openid_is_xri($claimed_id)) {
282
    $xrds_url = 'http://xri.net/' . $claimed_id;
283
  }
284 285
  $scheme = @parse_url($xrds_url, PHP_URL_SCHEME);
  if ($scheme == 'http' || $scheme == 'https') {
286 287
    // For regular URLs, try Yadis resolution first, then HTML-based discovery
    $headers = array('Accept' => 'application/xrds+xml');
288
    $result = drupal_http_request($xrds_url, array('headers' => $headers));
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

    if (!isset($result->error)) {
      if (isset($result->headers['Content-Type']) && preg_match("/application\/xrds\+xml/", $result->headers['Content-Type'])) {
        // Parse XML document to find URL
        $services = xrds_parse($result->data);
      }
      else {
        $xrds_url = NULL;
        if (isset($result->headers['X-XRDS-Location'])) {
          $xrds_url = $result->headers['X-XRDS-Location'];
        }
        else {
          // Look for meta http-equiv link in HTML head
          $xrds_url = _openid_meta_httpequiv('X-XRDS-Location', $result->data);
        }
        if (!empty($xrds_url)) {
          $headers = array('Accept' => 'application/xrds+xml');
306
          $xrds_result = drupal_http_request($xrds_url, array('headers' => $headers));
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
          if (!isset($xrds_result->error)) {
            $services = xrds_parse($xrds_result->data);
          }
        }
      }

      // Check for HTML delegation
      if (count($services) == 0) {
        // Look for 2.0 links
        $uri = _openid_link_href('openid2.provider', $result->data);
        $delegate = _openid_link_href('openid2.local_id', $result->data);
        $version = 2;

        // 1.0 links
        if (empty($uri)) {
          $uri = _openid_link_href('openid.server', $result->data);
          $delegate = _openid_link_href('openid.delegate', $result->data);
          $version = 1;
        }
        if (!empty($uri)) {
          $services[] = array('uri' => $uri, 'delegate' => $delegate, 'version' => $version);
        }
      }
    }
  }
  return $services;
}

/**
 * Attempt to create a shared secret with the OpenID Provider.
 *
 * @param $op_endpoint URL of the OpenID Provider endpoint.
 *
 * @return $assoc_handle The association handle.
 */
function openid_association($op_endpoint) {
343
  module_load_include('inc', 'openid');
344 345

  // Remove Old Associations:
346 347 348
  db_delete('openid_association')
    ->condition('created + expires_in', REQUEST_TIME, '<')
    ->execute();
349 350

  // Check to see if we have an association for this IdP already
351
  $assoc_handle = db_query("SELECT assoc_handle FROM {openid_association} WHERE idp_endpoint_uri = :endpoint", array(':endpoint' => $op_endpoint))->fetchField();
352 353 354 355 356 357 358 359 360 361
  if (empty($assoc_handle)) {
    $mod = OPENID_DH_DEFAULT_MOD;
    $gen = OPENID_DH_DEFAULT_GEN;
    $r = _openid_dh_rand($mod);
    $private = bcadd($r, 1);
    $public = bcpowmod($gen, $private, $mod);

    // If there is no existing association, then request one
    $assoc_request = openid_association_request($public);
    $assoc_message = _openid_encode_message(_openid_create_message($assoc_request));
362 363 364 365 366 367
    $assoc_options = array(
      'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8'),
      'method' => 'POST',
      'data' => $assoc_message,
    );
    $assoc_result = drupal_http_request($op_endpoint, $assoc_options);
368 369 370 371 372 373
    if (isset($assoc_result->error)) {
      return FALSE;
    }

    $assoc_response = _openid_parse_message($assoc_result->data);
    if (isset($assoc_response['mode']) && $assoc_response['mode'] == 'error') {
374
      return FALSE;
375 376 377 378 379 380 381 382
    }

    if ($assoc_response['session_type'] == 'DH-SHA1') {
      $spub = _openid_dh_base64_to_long($assoc_response['dh_server_public']);
      $enc_mac_key = base64_decode($assoc_response['enc_mac_key']);
      $shared = bcpowmod($spub, $private, $mod);
      $assoc_response['mac_key'] = base64_encode(_openid_dh_xorsecret($shared, $enc_mac_key));
    }
383
    db_insert('openid_association')
384 385 386 387 388 389 390 391
      ->fields(array(
        'idp_endpoint_uri' => $op_endpoint,
        'session_type' => $assoc_response['session_type'],
        'assoc_handle' => $assoc_response['assoc_handle'],
        'assoc_type' => $assoc_response['assoc_type'],
        'expires_in' => $assoc_response['expires_in'],
        'mac_key' => $assoc_response['mac_key'],
        'created' => REQUEST_TIME,
392 393
      ))
      ->execute();
394 395 396 397 398 399 400 401 402 403 404
    $assoc_handle = $assoc_response['assoc_handle'];
  }
  return $assoc_handle;
}

/**
 * Authenticate a user or attempt registration.
 *
 * @param $response Response values from the OpenID Provider.
 */
function openid_authentication($response) {
405
  module_load_include('inc', 'openid');
406

407
  $identity = $response['openid.claimed_id'];
408 409 410 411

  $account = user_external_load($identity);
  if (isset($account->uid)) {
    if (!variable_get('user_email_verification', TRUE) || $account->login) {
412 413 414 415 416 417 418
      // Check if user is blocked.
      user_login_name_validate(array(), $state, (array)$account);
      if (!form_get_errors()) {
        // Load global $user and perform final login tasks.
        $form_state['uid'] = $account->uid;
        user_login_submit(array(), $form_state);
      }
419 420 421 422 423
    }
    else {
      drupal_set_message(t('You must validate your email address for this account before logging in via OpenID'));
    }
  }
424
  elseif (variable_get('user_register', 1)) {
425
    // Register new user
426
    $form_state['args'] = array();
427 428 429 430 431 432 433 434 435 436 437 438 439
    $form_state['redirect'] = NULL;
    $form_state['values']['name'] = (empty($response['openid.sreg.nickname'])) ? $identity : $response['openid.sreg.nickname'];
    $form_state['values']['mail'] = (empty($response['openid.sreg.email'])) ? '' : $response['openid.sreg.email'];
    $form_state['values']['pass']  = user_password();
    $form_state['values']['status'] = variable_get('user_register', 1) == 1;
    $form_state['values']['response'] = $response;
    $form = drupal_retrieve_form('user_register', $form_state);
    drupal_prepare_form('user_register', $form, $form_state);
    drupal_validate_form('user_register', $form, $form_state);
    if (form_get_errors()) {
      // We were unable to register a valid new user, redirect to standard
      // user/register and prefill with the values we received.
      drupal_set_message(t('OpenID registration failed for the reasons listed. You may register now, or 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'))), 'error');
440
      $_SESSION['openid']['values'] = $form_state['values'];
441 442 443 444 445 446 447 448
      // We'll want to redirect back to the same place.
      $destination = drupal_get_destination();
      unset($_REQUEST['destination']);
      drupal_goto('user/register', $destination);
    }
    else {
      unset($form_state['values']['response']);
      $account = user_save('', $form_state['values']);
449
      // Terminate if an error occurred during user_save().
450 451 452 453
      if (!$account) {
        drupal_set_message(t("Error saving user account."), 'error');
        drupal_goto();
      }
454
      user_set_authmaps($account, array("authname_openid" => $identity));
455 456 457
      // Load global $user and perform final login tasks.
      $form_state['uid'] = $account->uid;
      user_login_submit(array(), $form_state);
458 459 460
    }
    drupal_redirect_form($form, $form_state['redirect']);
  }
461 462 463
  else {
    drupal_set_message(t('Only site administrators can create new user accounts.'), 'error');
  }
464 465 466 467
  drupal_goto();
}

function openid_association_request($public) {
468
  module_load_include('inc', 'openid');
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485

  $request = array(
    'openid.ns' => OPENID_NS_2_0,
    'openid.mode' => 'associate',
    'openid.session_type' => 'DH-SHA1',
    'openid.assoc_type' => 'HMAC-SHA1'
  );

  if ($request['openid.session_type'] == 'DH-SHA1' || $request['openid.session_type'] == 'DH-SHA256') {
    $cpub = _openid_dh_long_to_base64($public);
    $request['openid.dh_consumer_public'] = $cpub;
  }

  return $request;
}

function openid_authentication_request($claimed_id, $identity, $return_to = '', $assoc_handle = '', $version = 2) {
486
  module_load_include('inc', 'openid');
487 488 489 490 491 492 493 494 495

  $request =  array(
    'openid.mode' => 'checkid_setup',
    'openid.identity' => $identity,
    'openid.assoc_handle' => $assoc_handle,
    'openid.return_to' => $return_to,
  );

  if ($version == 2) {
496 497
    $request['openid.ns'] = OPENID_NS_2_0;
    $request['openid.claimed_id'] = $claimed_id;
498
    $request['openid.realm'] = url('', array('absolute' => TRUE));
499 500
  }
  else {
501
    $request['openid.trust_root'] = url('', array('absolute' => TRUE));
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
  }

  // Simple Registration
  $request['openid.sreg.required'] = 'nickname,email';
  $request['openid.ns.sreg'] = "http://openid.net/extensions/sreg/1.1";

  $request = array_merge($request, module_invoke_all('openid', 'request', $request));

  return $request;
}

/**
 * Attempt to verify the response received from the OpenID Provider.
 *
 * @param $op_endpoint The OpenID Provider URL.
517
 * @param $response Array of response values from the provider.
518 519 520 521
 *
 * @return boolean
 */
function openid_verify_assertion($op_endpoint, $response) {
522
  module_load_include('inc', 'openid');
523 524 525

  $valid = FALSE;

526
  $association = db_query("SELECT * FROM {openid_association} WHERE assoc_handle = :assoc_handle", array(':assoc_handle' => $response['openid.assoc_handle']))->fetchObject();
527 528 529 530 531 532 533 534 535 536 537 538 539 540
  if ($association && isset($association->session_type)) {
    $keys_to_sign = explode(',', $response['openid.signed']);
    $self_sig = _openid_signature($association, $response, $keys_to_sign);
    if ($self_sig == $response['openid.sig']) {
      $valid = TRUE;
    }
    else {
      $valid = FALSE;
    }
  }
  else {
    $request = $response;
    $request['openid.mode'] = 'check_authentication';
    $message = _openid_create_message($request);
541 542 543 544 545 546
    $options = array(
      'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8'),
      'method' => 'POST',
      'data' => _openid_encode_message($message),
    );
    $result = drupal_http_request($op_endpoint, $options);
547 548 549 550 551 552 553 554 555 556 557 558
    if (!isset($result->error)) {
      $response = _openid_parse_message($result->data);
      if (strtolower(trim($response['is_valid'])) == 'true') {
        $valid = TRUE;
      }
      else {
        $valid = FALSE;
      }
    }
  }
  return $valid;
}