Same name and namespace in other branches
  1. 7.x modules/openid/openid.module \openid_verify_assertion_nonce()

Verify that the nonce has not been used in earlier assertions from the same OpenID provider.

Parameters

$service: Array describing the OpenID provider.

$response: Array of response values from the provider.

Return value

TRUE if the nonce has not expired and has not been used earlier.

File

modules/openid/openid.module, line 656
Implement OpenID Relying Party support for Drupal

Code

function openid_verify_assertion_nonce($service, $response) {
  if ($service['version'] != 2) {
    return TRUE;
  }
  if (preg_match('/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})Z/', $response['openid.response_nonce'], $matches)) {
    list(, $year, $month, $day, $hour, $minutes, $seconds) = $matches;
    $nonce_timestamp = gmmktime($hour, $minutes, $seconds, $month, $day, $year);
  }
  else {
    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);
    return FALSE;
  }

  // A nonce with a timestamp to far in the past or future will already have
  // been removed and cannot be checked for single use anymore.
  $time = time();
  $expiry = 900;
  if ($nonce_timestamp <= $time - $expiry || $nonce_timestamp >= $time + $expiry) {
    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);
    return FALSE;
  }

  // Record that this nonce was used.
  db_query("INSERT INTO {openid_nonce} (idp_endpoint_uri, nonce, expires) VALUES ('%s', '%s', %d)", $service['uri'], $response['openid.response_nonce'], $nonce_timestamp + $expiry);

  // Count the number of times this nonce was used.
  $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']));
  if ($count_used == 1) {
    return TRUE;
  }
  else {
    watchdog('openid', 'Nonce replay attempt blocked from @ip, nonce: @nonce.', array(
      '@ip' => ip_address(),
      '@nonce' => $response['openid.response_nonce'],
    ), WATCHDOG_CRITICAL);
    return FALSE;
  }
}