Projet

Général

Profil

Paste
Télécharger (39,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / openid / openid.module @ 76597ebf

1
<?php
2

    
3
/**
4
 * @file
5
 * Implement OpenID Relying Party support for Drupal
6
 */
7

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

    
39
/**
40
 * Implements hook_menu_site_status_alter().
41
 */
42
function openid_menu_site_status_alter(&$menu_site_status, $path) {
43
  // Allow access to openid/authenticate even if site is in offline mode.
44
  if ($menu_site_status == MENU_SITE_OFFLINE && user_is_anonymous() && $path == 'openid/authenticate') {
45
    $menu_site_status = MENU_SITE_ONLINE;
46
  }
47
}
48

    
49
/**
50
 * Implements hook_admin_paths().
51
 */
52
function openid_admin_paths() {
53
  $paths = array(
54
    'user/*/openid' => TRUE,
55
    'user/*/openid/delete' => TRUE,
56
  );
57
  return $paths;
58
}
59

    
60
/**
61
 * Implements hook_help().
62
 */
63
function openid_help($path, $arg) {
64
  switch ($path) {
65
    case 'user/%/openid':
66
      $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>';
67
      $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>';
68
      $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>';
69
      return $output;
70
    case 'admin/help#openid':
71
      $output = '';
72
      $output .= '<h3>' . t('About') . '</h3>';
73
      $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>';
74
      $output .= '<h3>' . t('Uses') . '</h3>';
75
      $output .= '<dl>';
76
      $output .= '<dt>' . t('Logging in with OpenID') . '</dt>';
77
      $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>';
78
      $output .= '</dl>';
79
      return $output;
80
  }
81
}
82

    
83
/**
84
 * Implements hook_user_insert().
85
 */
86
function openid_user_insert(&$edit, $account, $category) {
87
  if (!empty($edit['openid_claimed_id'])) {
88
    // The user has registered after trying to log in via OpenID.
89
    if (variable_get('user_email_verification', TRUE)) {
90
      drupal_set_message(t('Once you have verified your e-mail address, you may log in via OpenID.'));
91
    }
92
    user_set_authmaps($account, array('authname_openid' => $edit['openid_claimed_id']));
93
    unset($_SESSION['openid']);
94
    unset($edit['openid_claimed_id']);
95
  }
96
}
97

    
98
/**
99
 * Implements hook_user_login().
100
 *
101
 * Save openid_identifier to visitor cookie.
102
 */
103
function openid_user_login(&$edit, $account) {
104
  if (isset($_SESSION['openid'])) {
105
    // The user has logged in via OpenID.
106
    user_cookie_save(array_intersect_key($_SESSION['openid']['user_login_values'], array_flip(array('openid_identifier'))));
107
    unset($_SESSION['openid']);
108
  }
109
}
110

    
111
/**
112
 * Implements hook_user_logout().
113
 *
114
 * Delete any openid_identifier in visitor cookie.
115
 */
116
function openid_user_logout($account) {
117
  if (isset($_COOKIE['Drupal_visitor_openid_identifier'])) {
118
    user_cookie_delete('openid_identifier');
119
  }
120
}
121

    
122
/**
123
 * Implements hook_form_FORM_ID_alter().
124
 */
125
function openid_form_user_login_block_alter(&$form, &$form_state) {
126
  _openid_user_login_form_alter($form, $form_state);
127
}
128

    
129
/**
130
 * Implements hook_form_FORM_ID_alter().
131
 */
132
function openid_form_user_login_alter(&$form, &$form_state) {
133
  _openid_user_login_form_alter($form, $form_state);
134
}
135

    
136
function _openid_user_login_form_alter(&$form, &$form_state) {
137
  $form['#attached']['css'][] = drupal_get_path('module', 'openid') . '/openid.css';
138
  $form['#attached']['js'][] = drupal_get_path('module', 'openid') . '/openid.js';
139
  $form['#attached']['library'][] = array('system', 'jquery.cookie');
140
  if (!empty($form_state['input']['openid_identifier'])) {
141
    $form['name']['#required'] = FALSE;
142
    $form['pass']['#required'] = FALSE;
143
    unset($form['#submit']);
144
    $form['#validate'] = array('openid_login_validate');
145
  }
146

    
147
  $items = array();
148
  $items[] = array(
149
    'data' => l(t('Log in using OpenID'), '#openid-login', array('external' => TRUE)),
150
    'class' => array('openid-link'),
151
  );
152
  $items[] = array(
153
    'data' => l(t('Cancel OpenID login'), '#', array('external' => TRUE)),
154
    'class' => array('user-link'),
155
  );
156

    
157
  $form['openid_links'] = array(
158
    '#theme' => 'item_list',
159
    '#items' => $items,
160
    '#attributes' => array('class' => array('openid-links')),
161
    '#weight' => 1,
162
  );
163

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

    
166
  $form['openid_identifier'] = array(
167
    '#type' => 'textfield',
168
    '#title' => t('Log in using OpenID'),
169
    '#size' => $form['name']['#size'],
170
    '#maxlength' => 255,
171
    '#weight' => -1,
172
    '#description' => l(t('What is OpenID?'), 'http://openid.net/', array('external' => TRUE)),
173
  );
174
  $form['openid.return_to'] = array('#type' => 'hidden', '#value' => url('openid/authenticate', array('absolute' => TRUE, 'query' => user_login_destination())));
175
}
176

    
177
/**
178
 * Implements hook_form_FORM_ID_alter().
179
 *
180
 * Prefills the login form with values acquired via OpenID.
181
 */
182
function openid_form_user_register_form_alter(&$form, &$form_state) {
183
  if (isset($_SESSION['openid']['response'])) {
184
    module_load_include('inc', 'openid');
185

    
186
    $response = $_SESSION['openid']['response'];
187

    
188
    // Extract Simple Registration keys from the response. We only include
189
    // signed keys as required by OpenID Simple Registration Extension 1.0,
190
    // section 4.
191
    $sreg_values = openid_extract_namespace($response, OPENID_NS_SREG, 'sreg', TRUE);
192
    // Extract Attribute Exchanges keys from the response. We only include
193
    // signed keys. This is not required by the specification, but it is
194
    // recommended by Google, see
195
    // http://googlecode.blogspot.com/2011/05/security-advisory-to-websites-using.html
196
    $ax_values = openid_extract_namespace($response, OPENID_NS_AX, 'ax', TRUE);
197

    
198
    if (!empty($sreg_values['nickname'])) {
199
      // Use the nickname returned by Simple Registration if available.
200
      $form['account']['name']['#default_value'] = $sreg_values['nickname'];
201
    }
202
    elseif ($ax_name_values = openid_extract_ax_values($ax_values, array('http://axschema.org/namePerson/friendly', 'http://schema.openid.net/namePerson/friendly'))) {
203
      // Else, use the first nickname returned by AX if available.
204
      $form['account']['name']['#default_value'] = current($ax_name_values);
205
    }
206
    else {
207
      $form['account']['name']['#default_value'] = '';
208
    }
209

    
210
    if (!empty($sreg_values['email'])) {
211
      // Use the email returned by Simple Registration if available.
212
      $form['account']['mail']['#default_value'] = $sreg_values['email'];
213
    }
214
    elseif ($ax_mail_values = openid_extract_ax_values($ax_values, array('http://axschema.org/contact/email', 'http://schema.openid.net/contact/email'))) {
215
      // Else, use the first nickname returned by AX if available.
216
      $form['account']['mail']['#default_value'] = current($ax_mail_values);
217
    }
218

    
219
    // If user_email_verification is off, hide the password field and just fill
220
    // with random password to avoid confusion.
221
    if (!variable_get('user_email_verification', TRUE)) {
222
      $form['account']['pass']['#type'] = 'hidden';
223
      $form['account']['pass']['#value'] = user_password();
224
    }
225

    
226
    $form['openid_claimed_id'] = array(
227
      '#type' => 'value',
228
      '#default_value' => $response['openid.claimed_id'],
229
    );
230
    $form['openid_display'] = array(
231
      '#type' => 'item',
232
      '#title' => t('Your OpenID'),
233
      '#description' => t('This OpenID will be attached to your account after registration.'),
234
      '#markup' => check_plain($response['openid.claimed_id']),
235
    );
236
  }
237
}
238

    
239
/**
240
 * Login form _validate hook
241
 */
242
function openid_login_validate($form, &$form_state) {
243
  $return_to = $form_state['values']['openid.return_to'];
244
  if (empty($return_to)) {
245
    $return_to = url('', array('absolute' => TRUE));
246
  }
247

    
248
  openid_begin($form_state['values']['openid_identifier'], $return_to, $form_state['values']);
249
}
250

    
251
/**
252
 * The initial step of OpenID authentication responsible for the following:
253
 *  - Perform discovery on the claimed OpenID.
254
 *  - If possible, create an association with the Provider's endpoint.
255
 *  - Create the authentication request.
256
 *  - Perform the appropriate redirect.
257
 *
258
 * @param $claimed_id The OpenID to authenticate
259
 * @param $return_to The endpoint to return to from the OpenID Provider
260
 */
261
function openid_begin($claimed_id, $return_to = '', $form_values = array()) {
262
  module_load_include('inc', 'openid');
263

    
264
  $service = NULL;
265
  $claimed_id = openid_normalize($claimed_id);
266
  $discovery = openid_discovery($claimed_id);
267

    
268
  if (!empty($discovery['services'])) {
269
    $service = _openid_select_service($discovery['services']);
270
  }
271

    
272
  // Quit if the discovery result was empty or if we can't select any service.
273
  if (!$discovery || !$service) {
274
    form_set_error('openid_identifier', t('Sorry, that is not a valid OpenID. Ensure you have spelled your ID correctly.'));
275
    return;
276
  }
277

    
278
  // Set claimed id from discovery.
279
  if (!empty($discovery['claimed_id'])) {
280
    $claimed_id = $discovery['claimed_id'];
281
  }
282

    
283
  // Store discovered information in the users' session so we don't have to rediscover.
284
  $_SESSION['openid']['service'] = $service;
285
  // Store the claimed id
286
  $_SESSION['openid']['claimed_id'] = $claimed_id;
287
  // Store the login form values so we can pass them to
288
  // user_exteral_login later.
289
  $_SESSION['openid']['user_login_values'] = $form_values;
290

    
291
  // If a supported math library is present, then create an association.
292
  $assoc_handle = '';
293
  if (_openid_get_math_library()) {
294
    $assoc_handle = openid_association($service['uri']);
295
  }
296

    
297
  if (in_array('http://specs.openid.net/auth/2.0/server', $service['types'])) {
298
    // User entered an OP Identifier.
299
    $claimed_id = $identity = 'http://specs.openid.net/auth/2.0/identifier_select';
300
  }
301
  else {
302
    // Use Claimed ID and/or OP-Local Identifier from service description, if
303
    // available.
304
    if (!empty($service['claimed_id'])) {
305
      $claimed_id = $service['claimed_id'];
306
    }
307
    $identity = !empty($service['identity']) ? $service['identity'] : $claimed_id;
308
  }
309
  $request = openid_authentication_request($claimed_id, $identity, $return_to, $assoc_handle, $service);
310

    
311
  if ($service['version'] == 2) {
312
    openid_redirect($service['uri'], $request);
313
  }
314
  else {
315
    openid_redirect_http($service['uri'], $request);
316
  }
317
}
318

    
319
/**
320
 * Completes OpenID authentication by validating returned data from the OpenID
321
 * Provider.
322
 *
323
 * @param $response Array of returned values from the OpenID Provider.
324
 *
325
 * @return $response Response values for further processing with
326
 *   $response['status'] set to one of 'success', 'failed' or 'cancel'.
327
 */
328
function openid_complete($response = array()) {
329
  module_load_include('inc', 'openid');
330

    
331
  if (count($response) == 0) {
332
    $response = _openid_response();
333
  }
334

    
335
  // Default to failed response
336
  $response['status'] = 'failed';
337
  if (isset($_SESSION['openid']['service']['uri']) && isset($_SESSION['openid']['claimed_id'])) {
338
    $service = $_SESSION['openid']['service'];
339
    $claimed_id = $_SESSION['openid']['claimed_id'];
340
    unset($_SESSION['openid']['service']);
341
    unset($_SESSION['openid']['claimed_id']);
342
    if (isset($response['openid.mode'])) {
343
      if ($response['openid.mode'] == 'cancel') {
344
        $response['status'] = 'cancel';
345
      }
346
      else {
347
        if (openid_verify_assertion($service, $response)) {
348
          // OpenID Authentication, section 7.3.2.3 and Appendix A.5:
349
          // The CanonicalID specified in the XRDS document must be used as the
350
          // account key. We rely on the XRI proxy resolver to verify that the
351
          // provider is authorized to respond on behalf of the specified
352
          // identifer (required per Extensible Resource Identifier (XRI)
353
          // (XRI) Resolution Version 2.0, section 14.3):
354
          if (!empty($service['claimed_id'])) {
355
            $response['openid.claimed_id'] = $service['claimed_id'];
356
          }
357
          elseif ($service['version'] == 2) {
358
            // Returned Claimed Identifier could contain unique fragment
359
            // identifier to allow identifier recycling so we need to preserve
360
            // it in the response.
361
            $response_claimed_id = openid_normalize($response['openid.claimed_id']);
362

    
363
            // OpenID Authentication, section 11.2:
364
            // If the returned Claimed Identifier is different from the one sent
365
            // to the OpenID Provider, we need to do discovery on the returned
366
            // identififer to make sure that the provider is authorized to
367
            // respond on behalf of this.
368
            if ($response_claimed_id != $claimed_id) {
369
              $discovery = openid_discovery($response['openid.claimed_id']);
370
              if ($discovery && !empty($discovery['services'])) {
371
                $uris = array();
372
                foreach ($discovery['services'] as $discovered_service) {
373
                  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'])) {
374
                    $uris[] = $discovered_service['uri'];
375
                  }
376
                }
377
              }
378
              if (!in_array($service['uri'], $uris)) {
379
                return $response;
380
              }
381
            }
382
          }
383
          else {
384
            $response['openid.claimed_id'] = $claimed_id;
385
          }
386
          $response['status'] = 'success';
387
        }
388
      }
389
    }
390
  }
391
  return $response;
392
}
393

    
394
/**
395
 * Perform discovery on a claimed ID to determine the OpenID provider endpoint.
396
 *
397
 * Discovery methods are provided by the hook_openid_discovery_method_info and
398
 * could be further altered using the hook_openid_discovery_method_info_alter.
399
 *
400
 * @param $claimed_id
401
 *   The OpenID URL to perform discovery on.
402
 *
403
 * @return
404
 *   The resulting discovery array from the first successful discovery method,
405
 *   which must contain following keys:
406
 *   - 'services' (required) an array of discovered services (including OpenID
407
 *   version, endpoint URI, etc).
408
 *   - 'claimed_id' (optional) new claimed identifer, found by following HTTP
409
 *   redirects during the services discovery.
410
 *   If all the discovery method fails or if no appropriate discovery method is
411
 *   found, FALSE is returned.
412
 */
413
function openid_discovery($claimed_id) {
414
  module_load_include('inc', 'openid');
415

    
416
  $methods = module_invoke_all('openid_discovery_method_info');
417
  drupal_alter('openid_discovery_method_info', $methods);
418

    
419
  // Execute each method in turn and return first successful discovery.
420
  foreach ($methods as $method) {
421
    $discovery = $method($claimed_id);
422
    if (!empty($discovery)) {
423
      return $discovery;
424
    }
425
  }
426

    
427
  return FALSE;
428
}
429

    
430
/**
431
 * Implements hook_openid_discovery_method_info().
432
 *
433
 * Define standard discovery methods.
434
 */
435
function openid_openid_discovery_method_info() {
436
  // The discovery process will stop as soon as one discovery method succeed.
437
  // We first attempt to discover XRI-based identifiers, then standard XRDS
438
  // identifiers via Yadis and HTML-based discovery, conforming to the OpenID 2.0
439
  // specification.
440
  return array(
441
    'xri' => '_openid_xri_discovery',
442
    'xrds' => '_openid_xrds_discovery',
443
  );
444
}
445

    
446
/**
447
 * OpenID discovery method: perform an XRI discovery.
448
 *
449
 * @see http://openid.net/specs/openid-authentication-2_0.html#discovery
450
 * @see hook_openid_discovery_method_info()
451
 * @see openid_discovery()
452
 *
453
 * @return
454
 *   An array of discovered services and claimed identifier or NULL. See
455
 *   openid_discovery() for more specific information.
456
 */
457
function _openid_xri_discovery($claimed_id) {
458
  if (_openid_is_xri($claimed_id)) {
459
    // Resolve XRI using a proxy resolver (Extensible Resource Identifier (XRI)
460
    // Resolution Version 2.0, section 11.2 and 14.3).
461
    $xrds_url = variable_get('xri_proxy_resolver', 'http://xri.net/') . rawurlencode($claimed_id) . '?_xrd_r=application/xrds+xml';
462
    $discovery = _openid_xrds_discovery($xrds_url);
463
    if (!empty($discovery['services']) && is_array($discovery['services'])) {
464
      foreach ($discovery['services'] as $i => &$service) {
465
        $status = $service['xrd']->children(OPENID_NS_XRD)->Status;
466
        if ($status && $status->attributes()->cid == 'verified') {
467
          $service['claimed_id'] = openid_normalize((string)$service['xrd']->children(OPENID_NS_XRD)->CanonicalID);
468
        }
469
        else {
470
          // Ignore service if the Canonical ID could not be verified.
471
          unset($discovery['services'][$i]);
472
        }
473
      }
474
      if (!empty($discovery['services'])) {
475
        return $discovery;
476
      }
477
    }
478
  }
479
}
480

    
481
/**
482
 * OpenID discovery method: perform a XRDS discovery.
483
 *
484
 * @see http://openid.net/specs/openid-authentication-2_0.html#discovery
485
 * @see hook_openid_discovery_method_info()
486
 * @see openid_discovery()
487
 *
488
 * @return
489
 *   An array of discovered services and claimed identifier or NULL. See
490
 *   openid_discovery() for more specific information.
491
 */
492
function _openid_xrds_discovery($claimed_id) {
493
  $services = array();
494

    
495
  $xrds_url = $claimed_id;
496
  $scheme = @parse_url($xrds_url, PHP_URL_SCHEME);
497
  if ($scheme == 'http' || $scheme == 'https') {
498
    // For regular URLs, try Yadis resolution first, then HTML-based discovery
499
    $headers = array('Accept' => 'application/xrds+xml');
500
    $result = drupal_http_request($xrds_url, array('headers' => $headers));
501

    
502
    // Check for HTTP error and make sure, that we reach the target. If the
503
    // maximum allowed redirects are exhausted, final destination URL isn't
504
    // reached, but drupal_http_request() doesn't return any error.
505
    // @todo Remove the check for 200 HTTP result code after the following issue
506
    // will be fixed: http://drupal.org/node/1096890.
507
    if (!isset($result->error) && $result->code == 200) {
508

    
509
      // Replace the user-entered claimed_id if we received a redirect.
510
      if (!empty($result->redirect_url)) {
511
        $claimed_id = openid_normalize($result->redirect_url);
512
      }
513

    
514
      if (isset($result->headers['content-type']) && preg_match("/application\/xrds\+xml/", $result->headers['content-type'])) {
515
        // Parse XML document to find URL
516
        $services = _openid_xrds_parse($result->data);
517
      }
518
      else {
519
        $xrds_url = NULL;
520
        if (isset($result->headers['x-xrds-location'])) {
521
          $xrds_url = $result->headers['x-xrds-location'];
522
        }
523
        else {
524
          // Look for meta http-equiv link in HTML head
525
          $xrds_url = _openid_meta_httpequiv('X-XRDS-Location', $result->data);
526
        }
527
        if (!empty($xrds_url)) {
528
          $headers = array('Accept' => 'application/xrds+xml');
529
          $xrds_result = drupal_http_request($xrds_url, array('headers' => $headers));
530
          if (!isset($xrds_result->error)) {
531
            $services = _openid_xrds_parse($xrds_result->data);
532
          }
533
        }
534
      }
535

    
536
      // Check for HTML delegation
537
      if (count($services) == 0) {
538
        // Look for 2.0 links
539
        $uri = _openid_link_href('openid2.provider', $result->data);
540
        $identity = _openid_link_href('openid2.local_id', $result->data);
541
        $type = 'http://specs.openid.net/auth/2.0/signon';
542

    
543
        // 1.x links
544
        if (empty($uri)) {
545
          $uri = _openid_link_href('openid.server', $result->data);
546
          $identity = _openid_link_href('openid.delegate', $result->data);
547
          $type = 'http://openid.net/signon/1.1';
548
        }
549
        if (!empty($uri)) {
550
          $services[] = array(
551
            'uri' => $uri,
552
            'identity' => $identity,
553
            'types' => array($type),
554
          );
555
        }
556
      }
557
    }
558
  }
559

    
560
  if (!empty($services)) {
561
    return array(
562
      'services' => $services,
563
      'claimed_id' => $claimed_id,
564
    );
565
  }
566
}
567

    
568
/**
569
 * Implements hook_openid_normalization_method_info().
570
 *
571
 * Define standard normalization methods.
572
 */
573
function openid_openid_normalization_method_info() {
574
  // OpenID Authentication 2.0, section 7.2:
575
  // If the User-supplied Identifier looks like an XRI, treat it as such;
576
  // otherwise treat it as an HTTP URL.
577
  return array(
578
    'xri' => '_openid_xri_normalize',
579
    'url' => '_openid_url_normalize',
580
  );
581
}
582

    
583
/**
584
 * Attempt to create a shared secret with the OpenID Provider.
585
 *
586
 * @param $op_endpoint URL of the OpenID Provider endpoint.
587
 *
588
 * @return $assoc_handle The association handle.
589
 */
590
function openid_association($op_endpoint) {
591
  module_load_include('inc', 'openid');
592

    
593
  // Remove Old Associations:
594
  db_delete('openid_association')
595
    ->where('created + expires_in < :request_time', array(':request_time' => REQUEST_TIME))
596
    ->execute();
597

    
598
  // Check to see if we have an association for this IdP already
599
  $assoc_handle = db_query("SELECT assoc_handle FROM {openid_association} WHERE idp_endpoint_uri = :endpoint", array(':endpoint' => $op_endpoint))->fetchField();
600
  if (empty($assoc_handle)) {
601
    $mod = OPENID_DH_DEFAULT_MOD;
602
    $gen = OPENID_DH_DEFAULT_GEN;
603
    $r = _openid_dh_rand($mod);
604
    $private = _openid_math_add($r, 1);
605
    $public = _openid_math_powmod($gen, $private, $mod);
606

    
607
    // If there is no existing association, then request one
608
    $assoc_request = openid_association_request($public);
609
    $assoc_message = _openid_encode_message(_openid_create_message($assoc_request));
610
    $assoc_options = array(
611
      'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8'),
612
      'method' => 'POST',
613
      'data' => $assoc_message,
614
    );
615
    $assoc_result = drupal_http_request($op_endpoint, $assoc_options);
616
    if (isset($assoc_result->error)) {
617
      return FALSE;
618
    }
619

    
620
    $assoc_response = _openid_parse_message($assoc_result->data);
621
    if (isset($assoc_response['mode']) && $assoc_response['mode'] == 'error') {
622
      return FALSE;
623
    }
624

    
625
    if ($assoc_response['session_type'] == 'DH-SHA1') {
626
      $spub = _openid_dh_base64_to_long($assoc_response['dh_server_public']);
627
      $enc_mac_key = base64_decode($assoc_response['enc_mac_key']);
628
      $shared = _openid_math_powmod($spub, $private, $mod);
629
      $assoc_response['mac_key'] = base64_encode(_openid_dh_xorsecret($shared, $enc_mac_key));
630
    }
631
    db_insert('openid_association')
632
      ->fields(array(
633
        'idp_endpoint_uri' => $op_endpoint,
634
        'session_type' => $assoc_response['session_type'],
635
        'assoc_handle' => $assoc_response['assoc_handle'],
636
        'assoc_type' => $assoc_response['assoc_type'],
637
        'expires_in' => $assoc_response['expires_in'],
638
        'mac_key' => $assoc_response['mac_key'],
639
        'created' => REQUEST_TIME,
640
      ))
641
      ->execute();
642
    $assoc_handle = $assoc_response['assoc_handle'];
643
  }
644
  return $assoc_handle;
645
}
646

    
647
/**
648
 * Authenticate a user or attempt registration.
649
 *
650
 * @param $response Response values from the OpenID Provider.
651
 */
652
function openid_authentication($response) {
653
  $identity = $response['openid.claimed_id'];
654
  $account = user_external_load($identity);
655

    
656
  // Tries to load user account if user_external_load fails due to possibly
657
  // incompletely stored OpenID identifier in the authmap.
658
  if (!isset($account->uid) && variable_get('openid_less_obtrusive_transition', FALSE)) {
659
    module_load_include('inc', 'openid');
660
    $account = _openid_invalid_openid_transition($identity, $response);
661
  }
662

    
663
  if (isset($account->uid)) {
664
    if (!variable_get('user_email_verification', TRUE) || $account->login) {
665
      // Check if user is blocked.
666
      $state['values']['name'] = $account->name;
667
      user_login_name_validate(array(), $state);
668
      if (!form_get_errors()) {
669
        // Load global $user and perform final login tasks.
670
        $form_state['uid'] = $account->uid;
671
        user_login_submit(array(), $form_state);
672
        // Let other modules act on OpenID login
673
        module_invoke_all('openid_response', $response, $account);
674
      }
675
    }
676
    else {
677
      drupal_set_message(t('You must validate your email address for this account before logging in via OpenID.'));
678
    }
679
  }
680
  elseif (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
681
    // Register new user.
682

    
683
    // Save response for use in openid_form_user_register_form_alter().
684
    $_SESSION['openid']['response'] = $response;
685

    
686
    $form_state['values'] = array();
687
    $form_state['values']['op'] = t('Create new account');
688
    drupal_form_submit('user_register_form', $form_state);
689

    
690
    if (!empty($form_state['user'])) {
691
      module_invoke_all('openid_response', $response, $form_state['user']);
692
      drupal_goto();
693
    }
694

    
695
    $messages = drupal_get_messages('error');
696
    if (empty($form_state['values']['name']) || empty($form_state['values']['mail'])) {
697
      // If the OpenID provider did not provide both a user name and an email
698
      // address, ask the user to complete the registration manually instead of
699
      // showing the error messages about the missing values generated by FAPI.
700
      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');
701
    }
702
    else {
703
      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');
704
      // Append form validation errors below the above warning.
705
      foreach ($messages['error'] as $message) {
706
        drupal_set_message($message, 'error');
707
      }
708
    }
709

    
710
    // We were unable to register a valid new user. Redirect to the normal
711
    // registration page and prefill with the values we received.
712
    $destination = drupal_get_destination();
713
    unset($_GET['destination']);
714
    drupal_goto('user/register', array('query' => $destination));
715
  }
716
  else {
717
    drupal_set_message(t('Only site administrators can create new user accounts.'), 'error');
718
  }
719
  drupal_goto();
720
}
721

    
722
function openid_association_request($public) {
723
  module_load_include('inc', 'openid');
724

    
725
  $request = array(
726
    'openid.ns' => OPENID_NS_2_0,
727
    'openid.mode' => 'associate',
728
    'openid.session_type' => 'DH-SHA1',
729
    'openid.assoc_type' => 'HMAC-SHA1'
730
  );
731

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

    
737
  return $request;
738
}
739

    
740
function openid_authentication_request($claimed_id, $identity, $return_to = '', $assoc_handle = '', $service) {
741
  global $base_url;
742

    
743
  module_load_include('inc', 'openid');
744

    
745
  $request =  array(
746
    'openid.mode' => 'checkid_setup',
747
    'openid.identity' => $identity,
748
    'openid.assoc_handle' => $assoc_handle,
749
    'openid.return_to' => $return_to,
750
  );
751

    
752
  if ($service['version'] == 2) {
753
    $request['openid.ns'] = OPENID_NS_2_0;
754
    $request['openid.claimed_id'] = $claimed_id;
755
    $request['openid.realm'] = $base_url .'/';
756
  }
757
  else {
758
    $request['openid.trust_root'] = $base_url .'/';
759
  }
760

    
761
  // Always request Simple Registration. The specification doesn't mandate
762
  // that the Endpoint advertise OPENID_NS_SREG in the service description.
763
  $request['openid.ns.sreg'] = OPENID_NS_SREG;
764
  $request['openid.sreg.required'] = 'nickname,email';
765

    
766
  // Request Attribute Exchange, if available.
767
  // We only request the minimum attributes we need here, contributed modules
768
  // can alter the request to add more attribute, and map them to profile fields.
769
  if (in_array(OPENID_NS_AX, $service['types'])) {
770
    $request['openid.ns.ax'] = OPENID_NS_AX;
771
    $request['openid.ax.mode'] = 'fetch_request';
772
    $request['openid.ax.required'] = 'mail_ao,name_ao,mail_son,name_son';
773

    
774
    // Implementors disagree on which URIs to use, even for simple
775
    // attributes like name and email (*sigh*). We ask for both axschema.org
776
    // attributes (which are supposed to be newer), and schema.openid.net ones
777
    // (which are supposed to be legacy).
778

    
779
    // Attributes as defined by axschema.org.
780
    $request['openid.ax.type.mail_ao'] = 'http://axschema.org/contact/email';
781
    $request['openid.ax.type.name_ao'] = 'http://axschema.org/namePerson/friendly';
782

    
783
    // Attributes as defined by schema.openid.net.
784
    $request['openid.ax.type.mail_son'] = 'http://schema.openid.net/contact/email';
785
    $request['openid.ax.type.name_son'] = 'http://schema.openid.net/namePerson/friendly';
786
  }
787

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

    
790
  // module_invoke_all() uses array_merge_recursive() which might return nested
791
  // arrays if two or more modules alter a given parameter, resulting in an
792
  // invalid request format. To ensure this doesn't happen, we flatten the returned
793
  // value by taking the last entry in the array if an array is returned.
794
  $flattened_request = array();
795
  foreach ($request as $key => $value) {
796
    if (is_array($value)) {
797
      $flattened_request[$key] = end($value);
798
    }
799
    else {
800
      $flattened_request[$key] = $value;
801
    }
802
  }
803

    
804
  return $flattened_request;
805
}
806

    
807
/**
808
 * Attempt to verify the response received from the OpenID Provider.
809
 *
810
 * @param $service
811
 *   Array describing the OpenID provider.
812
 * @param $response
813
 *   Array of response values from the provider.
814
 *
815
 * @return boolean
816
 * @see http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4
817
 */
818
function openid_verify_assertion($service, $response) {
819
  module_load_include('inc', 'openid');
820

    
821
  // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.3
822
  // Check the Nonce to protect against replay attacks.
823
  if (!openid_verify_assertion_nonce($service, $response)) {
824
    return FALSE;
825
  }
826

    
827
  // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.1
828
  // Verifying the return URL.
829
  if (!openid_verify_assertion_return_url($service, $response)) {
830
    return FALSE;
831
  }
832

    
833
  // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4
834
  // Verify the signatures.
835
  $valid = FALSE;
836
  $association = FALSE;
837

    
838
  // If the OP returned a openid.invalidate_handle, we have to proceed with
839
  // direct verification: ignore the openid.assoc_handle, even if present.
840
  // See http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.1
841
  if (!empty($response['openid.assoc_handle']) && empty($response['openid.invalidate_handle'])) {
842
    $association = db_query("SELECT * FROM {openid_association} WHERE idp_endpoint_uri = :endpoint AND assoc_handle = :assoc_handle", array(':endpoint' => $service['uri'], ':assoc_handle' => $response['openid.assoc_handle']))->fetchObject();
843
  }
844

    
845
  if ($association && isset($association->session_type)) {
846
    // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.2
847
    // Verification using an association.
848
    $valid = openid_verify_assertion_signature($service, $association, $response);
849
  }
850
  else {
851
    // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.2
852
    // Direct verification.
853
    // The verification requests contain all the fields from the response,
854
    // except openid.mode.
855
    $request = $response;
856
    $request['openid.mode'] = 'check_authentication';
857
    $message = _openid_create_message($request);
858
    $options = array(
859
      'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8'),
860
      'method' => 'POST',
861
      'data' => _openid_encode_message($message),
862
    );
863
    $result = drupal_http_request($service['uri'], $options);
864
    if (!isset($result->error)) {
865
      $response = _openid_parse_message($result->data);
866

    
867
      if (strtolower(trim($response['is_valid'])) == 'true') {
868
        $valid = TRUE;
869
        if (!empty($response['invalidate_handle'])) {
870
          // This association handle has expired on the OP side, remove it from the
871
          // database to avoid reusing it again on a subsequent authentication request.
872
          // See http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.2.2
873
          db_delete('openid_association')
874
            ->condition('idp_endpoint_uri', $service['uri'])
875
            ->condition('assoc_handle', $response['invalidate_handle'])
876
            ->execute();
877
        }
878
      }
879
      else {
880
        $valid = FALSE;
881
      }
882
    }
883
  }
884
  return $valid;
885
}
886

    
887

    
888
/**
889
 * Verify the signature of the response received from the OpenID provider.
890
 *
891
 * @param $service
892
 *   Array describing the OpenID provider.
893
 * @param $association
894
 *   Information on the association with the OpenID provider.
895
 * @param $response
896
 *   Array of response values from the provider.
897
 *
898
 * @return
899
 *   TRUE if the signature is valid and covers all fields required to be signed.
900
 * @see http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4
901
 */
902
function openid_verify_assertion_signature($service, $association, $response) {
903
  if ($service['version'] == 2) {
904
    // OpenID Authentication 2.0, section 10.1:
905
    // These keys must always be signed.
906
    $mandatory_keys = array('op_endpoint', 'return_to', 'response_nonce', 'assoc_handle');
907
    if (isset($response['openid.claimed_id'])) {
908
      // If present, these two keys must also be signed. According to the spec,
909
      // they are either both present or both absent.
910
      $mandatory_keys[] = 'claimed_id';
911
      $mandatory_keys[] = 'identity';
912
    }
913
  }
914
  else {
915
    // OpenID Authentication 1.1. section 4.3.3.
916
    $mandatory_keys = array('identity', 'return_to');
917
  }
918

    
919
  $keys_to_sign = explode(',', $response['openid.signed']);
920

    
921
  if (count(array_diff($mandatory_keys, $keys_to_sign)) > 0) {
922
    return FALSE;
923
  }
924

    
925
  return _openid_signature($association, $response, $keys_to_sign) === $response['openid.sig'];
926
}
927

    
928
/**
929
 * Verify that the nonce has not been used in earlier assertions from the same OpenID provider.
930
 *
931
 * @param $service
932
 *   Array describing the OpenID provider.
933
 * @param $response
934
 *   Array of response values from the provider.
935
 *
936
 * @return
937
 *   TRUE if the nonce has not expired and has not been used earlier.
938
 */
939
function openid_verify_assertion_nonce($service, $response) {
940
  if ($service['version'] != 2) {
941
    return TRUE;
942
  }
943

    
944
  if (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z/', $response['openid.response_nonce'], $matches)) {
945
    list(, $year, $month, $day, $hour, $minutes, $seconds) = $matches;
946
    $nonce_timestamp = gmmktime($hour, $minutes, $seconds, $month, $day, $year);
947
  }
948
  else {
949
    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);
950
    return FALSE;
951
  }
952

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

    
962
  // Record that this nonce was used.
963
  db_insert('openid_nonce')
964
    ->fields(array(
965
      'idp_endpoint_uri' => $service['uri'],
966
      'nonce' => $response['openid.response_nonce'],
967
      'expires' => $nonce_timestamp + $expiry,
968
    ))
969
    ->execute();
970

    
971
  // Count the number of times this nonce was used.
972
  $count_used = db_query("SELECT COUNT(*) FROM {openid_nonce} WHERE nonce = :nonce AND idp_endpoint_uri = :idp_endpoint_uri", array(
973
    ':nonce' => $response['openid.response_nonce'],
974
    ':idp_endpoint_uri' => $service['uri'],
975
  ))->fetchField();
976

    
977
  if ($count_used == 1) {
978
    return TRUE;
979
  }
980
  else {
981
    watchdog('openid', 'Nonce replay attempt blocked from @ip, nonce: @nonce.', array('@ip' => ip_address(), '@nonce' => $response['openid.response_nonce']), WATCHDOG_CRITICAL);
982
    return FALSE;
983
  }
984
}
985

    
986

    
987
/**
988
 * Verify that openid.return_to matches the current URL.
989
 *
990
 * See OpenID  Authentication 2.0, section 11.1. While OpenID Authentication
991
 * 1.1, section 4.3 does not mandate return_to verification, the received
992
 * return_to should still match these constraints.
993
 *
994
 * @param $service
995
 *   Array describing the OpenID provider.
996
 * @param $response
997
 *   Array of response values from the provider.
998
 *
999
 * @return
1000
 *   TRUE if return_to is valid, FALSE otherwise.
1001
 */
1002
function openid_verify_assertion_return_url($service, $response) {
1003
  global $base_url;
1004

    
1005
  $return_to_parts = parse_url($response['openid.return_to']);
1006

    
1007
  $base_url_parts = parse_url($base_url);
1008
  $current_parts = parse_url($base_url_parts['scheme'] .'://'. $base_url_parts['host'] . request_uri());
1009

    
1010
  if ($return_to_parts['scheme'] != $current_parts['scheme'] || $return_to_parts['host'] != $current_parts['host'] || $return_to_parts['path'] != $current_parts['path']) {
1011
    return FALSE;
1012
  }
1013
  // Verify that all query parameters in the openid.return_to URL have
1014
  // the same value in the current URL. In addition, the current URL
1015
  // contains a number of other parameters added by the OpenID Provider.
1016
  parse_str(isset($return_to_parts['query']) ? $return_to_parts['query'] : '', $return_to_query_parameters);
1017
  foreach ($return_to_query_parameters as $name => $value) {
1018
    if (!isset($_GET[$name]) || $_GET[$name] != $value) {
1019
      return FALSE;
1020
    }
1021
  }
1022
  return TRUE;
1023
}
1024

    
1025
/**
1026
 * Remove expired nonces from the database.
1027
 *
1028
 * Implements hook_cron().
1029
 */
1030
function openid_cron() {
1031
  db_delete('openid_nonce')
1032
    ->condition('expires', REQUEST_TIME, '<')
1033
    ->execute();
1034
}