[ Index ]

PHP Cross Reference of Drupal 6 (gatewave)

title

Body

[close]

/modules/openid/ -> openid.module (source)

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


Generated: Thu Mar 24 11:18:33 2011 Cross-referenced by PHPXref 0.7