PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 11.4
Jetpack – WP Security, Backup, Speed, & Growth v11.4
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / modules / sso.php

sso.php in Jetpack – WP Security, Backup, Speed, & Growth 11.4, at modules/sso.php

1,233 lines 38.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2 /**
3 * Jetpack_SSO module main class file.
4 *
5 * @package automattic/jetpack
6 */
7
8 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
9 use Automattic\Jetpack\Roles;
10 use Automattic\Jetpack\Status;
11 use Automattic\Jetpack\Tracking;
12
13 require_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php';
14 require_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-notices.php';
15
16 /**
17 * Module Name: Secure Sign On
18 * Module Description: Allow users to log in to this site using WordPress.com accounts
19 * Sort Order: 30
20 * Recommendation Order: 5
21 * First Introduced: 2.6
22 * Requires Connection: Yes
23 * Requires User Connection: Yes
24 * Auto Activate: No
25 * Module Tags: Developers
26 * Feature: Security
27 * Additional Search Queries: sso, single sign on, login, log in, 2fa, two-factor
28 */
29 class Jetpack_SSO {
30 /**
31 * Jetpack_SSO instance.
32 *
33 * @var Jetpack_SSO
34 */
35 public static $instance = null;
36
37 /**
38 * Jetpack_SSO constructor.
39 */
40 private function __construct() {
41
42 self::$instance = $this;
43
44 add_action( 'admin_init', array( $this, 'maybe_authorize_user_after_sso' ), 1 );
45 add_action( 'admin_init', array( $this, 'register_settings' ) );
46 add_action( 'login_init', array( $this, 'login_init' ) );
47 add_action( 'delete_user', array( $this, 'delete_connection_for_user' ) );
48 add_filter( 'jetpack_xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
49 add_action( 'init', array( $this, 'maybe_logout_user' ), 5 );
50 add_action( 'jetpack_modules_loaded', array( $this, 'module_configure_button' ) );
51 add_action( 'login_form_logout', array( $this, 'store_wpcom_profile_cookies_on_logout' ) );
52 add_action( 'jetpack_unlinked_user', array( $this, 'delete_connection_for_user' ) );
53 add_action( 'jetpack_site_before_disconnected', array( static::class, 'disconnect' ) );
54 add_action( 'wp_login', array( 'Jetpack_SSO', 'clear_cookies_after_login' ) );
55
56 // Adding this action so that on login_init, the action won't be sanitized out of the $action global.
57 add_action( 'login_form_jetpack-sso', '__return_true' );
58 }
59
60 /**
61 * Returns the single instance of the Jetpack_SSO object
62 *
63 * @since 2.8
64 * @return Jetpack_SSO
65 **/
66 public static function get_instance() {
67 if ( self::$instance !== null ) {
68 return self::$instance;
69 }
70
71 self::$instance = new Jetpack_SSO();
72 return self::$instance;
73 }
74
75 /**
76 * Add configure button and functionality to the module card on the Jetpack screen
77 **/
78 public static function module_configure_button() {
79 Jetpack::enable_module_configurable( __FILE__ );
80 }
81
82 /**
83 * If jetpack_force_logout == 1 in current user meta the user will be forced
84 * to logout and reauthenticate with the site.
85 **/
86 public function maybe_logout_user() {
87 global $current_user;
88
89 if ( 1 === (int) $current_user->jetpack_force_logout ) {
90 delete_user_meta( $current_user->ID, 'jetpack_force_logout' );
91 self::delete_connection_for_user( $current_user->ID );
92 wp_logout();
93 wp_safe_redirect( wp_login_url() );
94 exit;
95 }
96 }
97
98 /**
99 * Adds additional methods the WordPress xmlrpc API for handling SSO specific features
100 *
101 * @param array $methods API methods.
102 * @return array
103 **/
104 public function xmlrpc_methods( $methods ) {
105 $methods['jetpack.userDisconnect'] = array( $this, 'xmlrpc_user_disconnect' );
106 return $methods;
107 }
108
109 /**
110 * Marks a user's profile for disconnect from WordPress.com and forces a logout
111 * the next time the user visits the site.
112 *
113 * @param int $user_id User to disconnect from the site.
114 **/
115 public function xmlrpc_user_disconnect( $user_id ) {
116 $user_query = new WP_User_Query(
117 array(
118 'meta_key' => 'wpcom_user_id',
119 'meta_value' => $user_id,
120 )
121 );
122 $user = $user_query->get_results();
123 $user = $user[0];
124
125 if ( $user instanceof WP_User ) {
126 $user = wp_set_current_user( $user->ID );
127 update_user_meta( $user->ID, 'jetpack_force_logout', '1' );
128 self::delete_connection_for_user( $user->ID );
129 return true;
130 }
131 return false;
132 }
133
134 /**
135 * Enqueues scripts and styles necessary for SSO login.
136 */
137 public function login_enqueue_scripts() {
138 global $action;
139
140 if ( ! Jetpack_SSO_Helpers::display_sso_form_for_action( $action ) ) {
141 return;
142 }
143
144 if ( is_rtl() ) {
145 wp_enqueue_style( 'jetpack-sso-login', plugins_url( 'modules/sso/jetpack-sso-login-rtl.css', JETPACK__PLUGIN_FILE ), array( 'login', 'genericons' ), JETPACK__VERSION );
146 } else {
147 wp_enqueue_style( 'jetpack-sso-login', plugins_url( 'modules/sso/jetpack-sso-login.css', JETPACK__PLUGIN_FILE ), array( 'login', 'genericons' ), JETPACK__VERSION );
148 }
149
150 wp_enqueue_script( 'jetpack-sso-login', plugins_url( 'modules/sso/jetpack-sso-login.js', JETPACK__PLUGIN_FILE ), array( 'jquery' ), JETPACK__VERSION, false );
151 }
152
153 /**
154 * Adds Jetpack SSO classes to login body
155 *
156 * @param array $classes Array of classes to add to body tag.
157 * @return array Array of classes to add to body tag.
158 */
159 public function login_body_class( $classes ) {
160 global $action;
161
162 if ( ! Jetpack_SSO_Helpers::display_sso_form_for_action( $action ) ) {
163 return $classes;
164 }
165
166 // Always add the jetpack-sso class so that we can add SSO specific styling even when the SSO form isn't being displayed.
167 $classes[] = 'jetpack-sso';
168
169 if ( ! ( new Status() )->is_staging_site() ) {
170 /**
171 * Should we show the SSO login form?
172 *
173 * $_GET['jetpack-sso-default-form'] is used to provide a fallback in case JavaScript is not enabled.
174 *
175 * The default_to_sso_login() method allows us to dynamically decide whether we show the SSO login form or not.
176 * The SSO module uses the method to display the default login form if we can not find a user to log in via SSO.
177 * But, the method could be filtered by a site admin to always show the default login form if that is preferred.
178 */
179 if ( empty( $_GET['jetpack-sso-show-default-form'] ) && Jetpack_SSO_Helpers::show_sso_login() ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
180 $classes[] = 'jetpack-sso-form-display';
181 }
182 }
183
184 return $classes;
185 }
186
187 /**
188 * Inlined admin styles for SSO.
189 */
190 public function print_inline_admin_css() {
191 ?>
192 <style>
193 .jetpack-sso .message {
194 margin-top: 20px;
195 }
196
197 .jetpack-sso #login .message:first-child,
198 .jetpack-sso #login h1 + .message {
199 margin-top: 0;
200 }
201 </style>
202 <?php
203 }
204
205 /**
206 * Adds settings fields to Settings > General > Secure Sign On that allows users to
207 * turn off the login form on wp-login.php
208 *
209 * @since 2.7
210 **/
211 public function register_settings() {
212
213 add_settings_section(
214 'jetpack_sso_settings',
215 __( 'Secure Sign On', 'jetpack' ),
216 '__return_false',
217 'jetpack-sso'
218 );
219
220 /*
221 * Settings > General > Secure Sign On
222 * Require two step authentication
223 */
224 register_setting(
225 'jetpack-sso',
226 'jetpack_sso_require_two_step',
227 array( $this, 'validate_jetpack_sso_require_two_step' )
228 );
229
230 add_settings_field(
231 'jetpack_sso_require_two_step',
232 '', // Output done in render $callback: __( 'Require Two-Step Authentication' , 'jetpack' ).
233 array( $this, 'render_require_two_step' ),
234 'jetpack-sso',
235 'jetpack_sso_settings'
236 );
237
238 /*
239 * Settings > General > Secure Sign On
240 */
241 register_setting(
242 'jetpack-sso',
243 'jetpack_sso_match_by_email',
244 array( $this, 'validate_jetpack_sso_match_by_email' )
245 );
246
247 add_settings_field(
248 'jetpack_sso_match_by_email',
249 '', // Output done in render $callback: __( 'Match by Email' , 'jetpack' ).
250 array( $this, 'render_match_by_email' ),
251 'jetpack-sso',
252 'jetpack_sso_settings'
253 );
254 }
255
256 /**
257 * Builds the display for the checkbox allowing user to require two step
258 * auth be enabled on WordPress.com accounts before login. Displays in Settings > General
259 *
260 * @since 2.7
261 **/
262 public function render_require_two_step() {
263 ?>
264 <label>
265 <input
266 type="checkbox"
267 name="jetpack_sso_require_two_step"
268 <?php checked( Jetpack_SSO_Helpers::is_two_step_required() ); ?>
269 <?php disabled( Jetpack_SSO_Helpers::is_require_two_step_checkbox_disabled() ); ?>
270 >
271 <?php esc_html_e( 'Require Two-Step Authentication', 'jetpack' ); ?>
272 </label>
273 <?php
274 }
275
276 /**
277 * Validate the require two step checkbox in Settings > General.
278 *
279 * @param bool $input The jetpack_sso_require_two_step option setting.
280 *
281 * @since 2.7
282 * @return boolean
283 **/
284 public function validate_jetpack_sso_require_two_step( $input ) {
285 return ( ! empty( $input ) ) ? 1 : 0;
286 }
287
288 /**
289 * Builds the display for the checkbox allowing the user to allow matching logins by email
290 * Displays in Settings > General
291 *
292 * @since 2.9
293 **/
294 public function render_match_by_email() {
295 ?>
296 <label>
297 <input
298 type="checkbox"
299 name="jetpack_sso_match_by_email"
300 <?php checked( Jetpack_SSO_Helpers::match_by_email() ); ?>
301 <?php disabled( Jetpack_SSO_Helpers::is_match_by_email_checkbox_disabled() ); ?>
302 >
303 <?php esc_html_e( 'Match by Email', 'jetpack' ); ?>
304 </label>
305 <?php
306 }
307
308 /**
309 * Validate the match by email check in Settings > General.
310 *
311 * @param bool $input The jetpack_sso_match_by_email option setting.
312 *
313 * @since 2.9
314 * @return boolean
315 **/
316 public function validate_jetpack_sso_match_by_email( $input ) {
317 return ( ! empty( $input ) ) ? 1 : 0;
318 }
319
320 /**
321 * Checks to determine if the user wants to login on wp-login
322 *
323 * This function mostly exists to cover the exceptions to login
324 * that may exist as other parameters to $_GET[action] as $_GET[action]
325 * does not have to exist. By default WordPress assumes login if an action
326 * is not set, however this may not be true, as in the case of logout
327 * where $_GET[loggedout] is instead set
328 *
329 * @return boolean
330 **/
331 private function wants_to_login() {
332 $wants_to_login = false;
333
334 // Cover default WordPress behavior.
335 $action = isset( $_REQUEST['action'] ) ? filter_var( wp_unslash( $_REQUEST['action'] ) ) : 'login'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
336
337 // And now the exceptions.
338 $action = isset( $_GET['loggedout'] ) ? 'loggedout' : $action; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
339
340 if ( Jetpack_SSO_Helpers::display_sso_form_for_action( $action ) ) {
341 $wants_to_login = true;
342 }
343
344 return $wants_to_login;
345 }
346
347 /**
348 * Initialization for a SSO request.
349 */
350 public function login_init() {
351 global $action;
352
353 $tracking = new Tracking();
354
355 if ( Jetpack_SSO_Helpers::should_hide_login_form() ) {
356 /**
357 * Since the default authenticate filters fire at priority 20 for checking username and password,
358 * let's fire at priority 30. wp_authenticate_spam_check is fired at priority 99, but since we return a
359 * WP_Error in disable_default_login_form, then we won't trigger spam processing logic.
360 */
361 add_filter( 'authenticate', array( 'Jetpack_SSO_Notices', 'disable_default_login_form' ), 30 );
362
363 /**
364 * Filter the display of the disclaimer message appearing when default WordPress login form is disabled.
365 *
366 * @module sso
367 *
368 * @since 2.8.0
369 *
370 * @param bool true Should the disclaimer be displayed. Default to true.
371 */
372 $display_sso_disclaimer = apply_filters( 'jetpack_sso_display_disclaimer', true );
373 if ( $display_sso_disclaimer ) {
374 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'msg_login_by_jetpack' ) );
375 }
376 }
377
378 if ( 'jetpack-sso' === $action ) {
379 if ( isset( $_GET['result'], $_GET['user_id'], $_GET['sso_nonce'] ) && 'success' === $_GET['result'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
380 $this->handle_login();
381 $this->display_sso_login_form();
382 } else {
383 if ( ( new Status() )->is_staging_site() ) {
384 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'sso_not_allowed_in_staging' ) );
385 } else {
386 // Is it wiser to just use wp_redirect than do this runaround to wp_safe_redirect?
387 add_filter( 'allowed_redirect_hosts', array( 'Jetpack_SSO_Helpers', 'allowed_redirect_hosts' ) );
388 $reauth = ! empty( $_GET['force_reauth'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
389 $sso_url = $this->get_sso_url_or_die( $reauth );
390
391 $tracking->record_user_event( 'sso_login_redirect_success' );
392 wp_safe_redirect( $sso_url );
393 exit;
394 }
395 }
396 } elseif ( Jetpack_SSO_Helpers::display_sso_form_for_action( $action ) ) {
397
398 // Save cookies so we can handle redirects after SSO.
399 $this->save_cookies();
400
401 /**
402 * Check to see if the site admin wants to automagically forward the user
403 * to the WordPress.com login page AND that the request to wp-login.php
404 * is not something other than login (Like logout!)
405 */
406 if ( Jetpack_SSO_Helpers::bypass_login_forward_wpcom() && $this->wants_to_login() ) {
407 add_filter( 'allowed_redirect_hosts', array( 'Jetpack_SSO_Helpers', 'allowed_redirect_hosts' ) );
408 $reauth = ! empty( $_GET['force_reauth'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
409 $sso_url = $this->get_sso_url_or_die( $reauth );
410 $tracking->record_user_event( 'sso_login_redirect_bypass_success' );
411 wp_safe_redirect( $sso_url );
412 exit;
413 }
414
415 $this->display_sso_login_form();
416 }
417 }
418
419 /**
420 * Ensures that we can get a nonce from WordPress.com via XML-RPC before setting
421 * up the hooks required to display the SSO form.
422 */
423 public function display_sso_login_form() {
424 add_filter( 'login_body_class', array( $this, 'login_body_class' ) );
425 add_action( 'login_head', array( $this, 'print_inline_admin_css' ) );
426
427 if ( ( new Status() )->is_staging_site() ) {
428 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'sso_not_allowed_in_staging' ) );
429 return;
430 }
431
432 $sso_nonce = self::request_initial_nonce();
433 if ( is_wp_error( $sso_nonce ) ) {
434 return;
435 }
436
437 add_action( 'login_form', array( $this, 'login_form' ) );
438 add_action( 'login_enqueue_scripts', array( $this, 'login_enqueue_scripts' ) );
439 }
440
441 /**
442 * Conditionally save the redirect_to url as a cookie.
443 *
444 * @since 4.6.0 Renamed to save_cookies from maybe_save_redirect_cookies
445 */
446 public static function save_cookies() {
447 if ( headers_sent() ) {
448 return new WP_Error( 'headers_sent', __( 'Cannot deal with cookie redirects, as headers are already sent.', 'jetpack' ) );
449 }
450
451 setcookie(
452 'jetpack_sso_original_request',
453 // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sniff misses the wrapping esc_url_raw().
454 esc_url_raw( set_url_scheme( ( isset( $_SERVER['HTTP_HOST'] ) ? wp_unslash( $_SERVER['HTTP_HOST'] ) : '' ) . ( isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '' ) ) ),
455 time() + HOUR_IN_SECONDS,
456 COOKIEPATH,
457 COOKIE_DOMAIN,
458 is_ssl(),
459 true
460 );
461
462 if ( ! empty( $_GET['redirect_to'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
463 // If we have something to redirect to.
464 $url = esc_url_raw( wp_unslash( $_GET['redirect_to'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
465 setcookie( 'jetpack_sso_redirect_to', $url, time() + HOUR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
466 } elseif ( ! empty( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
467 // Otherwise, if it's already set, purge it.
468 setcookie( 'jetpack_sso_redirect_to', ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
469 }
470 }
471
472 /**
473 * Outputs the Jetpack SSO button and description as well as the toggle link
474 * for switching between Jetpack SSO and default login.
475 */
476 public function login_form() {
477 $site_name = get_bloginfo( 'name' );
478 if ( ! $site_name ) {
479 $site_name = get_bloginfo( 'url' );
480 }
481
482 $display_name = ! empty( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] )
483 ? sanitize_text_field( wp_unslash( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] ) )
484 : false;
485 $gravatar = ! empty( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] )
486 ? esc_url_raw( wp_unslash( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] ) )
487 : false;
488
489 ?>
490 <div id="jetpack-sso-wrap">
491 <?php
492 /**
493 * Allow extension above Jetpack's SSO form.
494 *
495 * @module sso
496 *
497 * @since 8.6.0
498 */
499 do_action( 'jetpack_sso_login_form_above_wpcom' );
500
501 if ( $display_name && $gravatar ) :
502 ?>
503 <div id="jetpack-sso-wrap__user">
504 <img width="72" height="72" src="<?php echo esc_html( $gravatar ); ?>" />
505
506 <h2>
507 <?php
508 echo wp_kses(
509 /* translators: %s a user display name. */
510 sprintf( __( 'Log in as <span>%s</span>', 'jetpack' ), esc_html( $display_name ) ),
511 array( 'span' => true )
512 );
513 ?>
514 </h2>
515 </div>
516
517 <?php endif; ?>
518
519
520 <div id="jetpack-sso-wrap__action">
521 <?php echo $this->build_sso_button( array(), 'is_primary' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaping done in build_sso_button() ?>
522
523 <?php if ( $display_name && $gravatar ) : ?>
524 <a rel="nofollow" class="jetpack-sso-wrap__reauth" href="<?php echo esc_url( $this->build_sso_button_url( array( 'force_reauth' => '1' ) ) ); ?>">
525 <?php esc_html_e( 'Log in as a different WordPress.com user', 'jetpack' ); ?>
526 </a>
527 <?php else : ?>
528 <p>
529 <?php
530 /**
531 * Filter the messeage displayed below the SSO button.
532 *
533 * @module sso
534 *
535 * @since 10.3.0
536 *
537 * @param string $sso_explanation Message displayed below the SSO button.
538 */
539 $sso_explanation = apply_filters(
540 'jetpack_sso_login_form_explanation_text',
541 sprintf(
542 /* Translators: %s is the name of the site. */
543 __( 'You can now save time spent logging in by connecting your WordPress.com account to %s.', 'jetpack' ),
544 esc_html( $site_name )
545 )
546 );
547 echo esc_html( $sso_explanation );
548 ?>
549 </p>
550 <?php endif; ?>
551 </div>
552
553 <?php
554 /**
555 * Allow extension below Jetpack's SSO form.
556 *
557 * @module sso
558 *
559 * @since 8.6.0
560 */
561 do_action( 'jetpack_sso_login_form_below_wpcom' );
562
563 if ( ! Jetpack_SSO_Helpers::should_hide_login_form() ) :
564 ?>
565 <div class="jetpack-sso-or">
566 <span><?php esc_html_e( 'Or', 'jetpack' ); ?></span>
567 </div>
568
569 <a href="<?php echo esc_url( add_query_arg( 'jetpack-sso-show-default-form', '1' ) ); ?>" class="jetpack-sso-toggle wpcom">
570 <?php
571 esc_html_e( 'Log in with username and password', 'jetpack' )
572 ?>
573 </a>
574
575 <a href="<?php echo esc_url( add_query_arg( 'jetpack-sso-show-default-form', '0' ) ); ?>" class="jetpack-sso-toggle default">
576 <?php
577 esc_html_e( 'Log in with WordPress.com', 'jetpack' )
578 ?>
579 </a>
580 <?php endif; ?>
581 </div>
582 <?php
583 }
584
585 /**
586 * Clear the cookies that store the profile information for the last
587 * WPCOM user to connect.
588 */
589 public static function clear_wpcom_profile_cookies() {
590 if ( isset( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] ) ) {
591 setcookie(
592 'jetpack_sso_wpcom_name_' . COOKIEHASH,
593 ' ',
594 time() - YEAR_IN_SECONDS,
595 COOKIEPATH,
596 COOKIE_DOMAIN,
597 is_ssl(),
598 true
599 );
600 }
601
602 if ( isset( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] ) ) {
603 setcookie(
604 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
605 ' ',
606 time() - YEAR_IN_SECONDS,
607 COOKIEPATH,
608 COOKIE_DOMAIN,
609 is_ssl(),
610 true
611 );
612 }
613 }
614
615 /**
616 * Clear cookies that are no longer needed once the user has logged in.
617 *
618 * @since 4.8.0
619 */
620 public static function clear_cookies_after_login() {
621 self::clear_wpcom_profile_cookies();
622 if ( isset( $_COOKIE['jetpack_sso_nonce'] ) ) {
623 setcookie(
624 'jetpack_sso_nonce',
625 ' ',
626 time() - YEAR_IN_SECONDS,
627 COOKIEPATH,
628 COOKIE_DOMAIN,
629 is_ssl(),
630 true
631 );
632 }
633
634 if ( isset( $_COOKIE['jetpack_sso_original_request'] ) ) {
635 setcookie(
636 'jetpack_sso_original_request',
637 ' ',
638 time() - YEAR_IN_SECONDS,
639 COOKIEPATH,
640 COOKIE_DOMAIN,
641 is_ssl(),
642 true
643 );
644 }
645
646 if ( isset( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
647 setcookie(
648 'jetpack_sso_redirect_to',
649 ' ',
650 time() - YEAR_IN_SECONDS,
651 COOKIEPATH,
652 COOKIE_DOMAIN,
653 is_ssl(),
654 true
655 );
656 }
657 }
658
659 /**
660 * Clean up after Jetpack gets disconnected.
661 *
662 * @since 10.7
663 */
664 public static function disconnect() {
665 if ( Jetpack::connection()->is_user_connected() ) {
666 static::delete_connection_for_user( get_current_user_id() );
667 }
668 }
669
670 /**
671 * Remove an SSO connection for a user.
672 *
673 * @param int $user_id The local user id.
674 */
675 public static function delete_connection_for_user( $user_id ) {
676 $wpcom_user_id = get_user_meta( $user_id, 'wpcom_user_id', true );
677 if ( ! $wpcom_user_id ) {
678 return;
679 }
680
681 $xml = new Jetpack_IXR_Client(
682 array(
683 'wpcom_user_id' => $user_id,
684 )
685 );
686 $xml->query( 'jetpack.sso.removeUser', $wpcom_user_id );
687
688 if ( $xml->isError() ) {
689 return false;
690 }
691
692 // Clean up local data stored for SSO.
693 delete_user_meta( $user_id, 'wpcom_user_id' );
694 delete_user_meta( $user_id, 'wpcom_user_data' );
695 self::clear_wpcom_profile_cookies();
696
697 return $xml->getResponse();
698 }
699
700 /**
701 * Retrieves nonce used for SSO form.
702 */
703 public static function request_initial_nonce() {
704 $nonce = ! empty( $_COOKIE['jetpack_sso_nonce'] )
705 ? sanitize_key( wp_unslash( $_COOKIE['jetpack_sso_nonce'] ) )
706 : false;
707
708 if ( ! $nonce ) {
709 $xml = new Jetpack_IXR_Client();
710 $xml->query( 'jetpack.sso.requestNonce' );
711
712 if ( $xml->isError() ) {
713 return new WP_Error( $xml->getErrorCode(), $xml->getErrorMessage() );
714 }
715
716 $nonce = sanitize_key( $xml->getResponse() );
717
718 setcookie(
719 'jetpack_sso_nonce',
720 $nonce,
721 time() + ( 10 * MINUTE_IN_SECONDS ),
722 COOKIEPATH,
723 COOKIE_DOMAIN,
724 is_ssl(),
725 true
726 );
727 }
728
729 return $nonce;
730 }
731
732 /**
733 * The function that actually handles the login!
734 */
735 public function handle_login() {
736 $wpcom_nonce = isset( $_GET['sso_nonce'] ) ? sanitize_key( $_GET['sso_nonce'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
737 $wpcom_user_id = isset( $_GET['user_id'] ) ? (int) $_GET['user_id'] : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
738
739 $xml = new Jetpack_IXR_Client();
740 $xml->query( 'jetpack.sso.validateResult', $wpcom_nonce, $wpcom_user_id );
741
742 $user_data = $xml->isError() ? false : $xml->getResponse();
743 if ( empty( $user_data ) ) {
744 add_filter( 'jetpack_sso_default_to_sso_login', '__return_false' );
745 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_invalid_response_data' ) );
746 return;
747 }
748
749 $user_data = (object) $user_data;
750 $user = null;
751
752 /**
753 * Fires before Jetpack's SSO modifies the log in form.
754 *
755 * @module sso
756 *
757 * @since 2.6.0
758 *
759 * @param object $user_data WordPress.com User information.
760 */
761 do_action( 'jetpack_sso_pre_handle_login', $user_data );
762
763 $tracking = new Tracking();
764
765 if ( Jetpack_SSO_Helpers::is_two_step_required() && 0 === (int) $user_data->two_step_enabled ) {
766 $this->user_data = $user_data;
767
768 $tracking->record_user_event(
769 'sso_login_failed',
770 array(
771 'error_message' => 'error_msg_enable_two_step',
772 )
773 );
774
775 $error = new WP_Error( 'two_step_required', __( 'You must have Two-Step Authentication enabled on your WordPress.com account.', 'jetpack' ) );
776
777 /** This filter is documented in core/src/wp-includes/pluggable.php */
778 do_action( 'wp_login_failed', $user_data->login, $error );
779 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_msg_enable_two_step' ) );
780 return;
781 }
782
783 $user_found_with = '';
784 if ( empty( $user ) && isset( $user_data->external_user_id ) ) {
785 $user_found_with = 'external_user_id';
786 $user = get_user_by( 'id', (int) $user_data->external_user_id );
787 if ( $user ) {
788 $expected_id = get_user_meta( $user->ID, 'wpcom_user_id', true );
789 if ( $expected_id && $expected_id != $user_data->ID ) { // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison, Universal.Operators.StrictComparisons.LooseNotEqual
790 $error = new WP_Error( 'expected_wpcom_user', __( 'Something got a little mixed up and an unexpected WordPress.com user logged in.', 'jetpack' ) );
791
792 $tracking->record_user_event(
793 'sso_login_failed',
794 array(
795 'error_message' => 'error_unexpected_wpcom_user',
796 )
797 );
798
799 /** This filter is documented in core/src/wp-includes/pluggable.php */
800 do_action( 'wp_login_failed', $user_data->login, $error );
801 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_invalid_response_data' ) ); // @todo Need to have a better notice. This is only for the sake of testing the validation.
802 return;
803 }
804 update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
805 }
806 }
807
808 // If we don't have one by wpcom_user_id, try by the email?
809 if ( empty( $user ) && Jetpack_SSO_Helpers::match_by_email() ) {
810 $user_found_with = 'match_by_email';
811 $user = get_user_by( 'email', $user_data->email );
812 if ( $user ) {
813 update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
814 }
815 }
816
817 // If we've still got nothing, create the user.
818 $new_user_override_role = Jetpack_SSO_Helpers::new_user_override( $user_data );
819 if ( empty( $user ) && ( get_option( 'users_can_register' ) || $new_user_override_role ) ) {
820 /**
821 * If not matching by email we still need to verify the email does not exist
822 * or this blows up
823 *
824 * If match_by_email is true, we know the email doesn't exist, as it would have
825 * been found in the first pass. If get_user_by( 'email' ) doesn't find the
826 * user, then we know that email is unused, so it's safe to add.
827 */
828 if ( Jetpack_SSO_Helpers::match_by_email() || ! get_user_by( 'email', $user_data->email ) ) {
829
830 if ( $new_user_override_role ) {
831 $user_data->role = $new_user_override_role;
832 }
833
834 $user = Jetpack_SSO_Helpers::generate_user( $user_data );
835 if ( ! $user ) {
836 $tracking->record_user_event(
837 'sso_login_failed',
838 array(
839 'error_message' => 'could_not_create_username',
840 )
841 );
842 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'error_unable_to_create_user' ) );
843 return;
844 }
845
846 $user_found_with = $new_user_override_role
847 ? 'user_created_new_user_override'
848 : 'user_created_users_can_register';
849 } else {
850 $tracking->record_user_event(
851 'sso_login_failed',
852 array(
853 'error_message' => 'error_msg_email_already_exists',
854 )
855 );
856
857 $this->user_data = $user_data;
858 add_action( 'login_message', array( 'Jetpack_SSO_Notices', 'error_msg_email_already_exists' ) );
859 return;
860 }
861 }
862
863 /**
864 * Fires after we got login information from WordPress.com.
865 *
866 * @module sso
867 *
868 * @since 2.6.0
869 *
870 * @param WP_User|false|null $user Local User information.
871 * @param object $user_data WordPress.com User Login information.
872 */
873 do_action( 'jetpack_sso_handle_login', $user, $user_data );
874
875 if ( $user ) {
876 // Cache the user's details, so we can present it back to them on their user screen.
877 update_user_meta( $user->ID, 'wpcom_user_data', $user_data );
878
879 add_filter( 'auth_cookie_expiration', array( 'Jetpack_SSO_Helpers', 'extend_auth_cookie_expiration_for_sso' ) );
880 wp_set_auth_cookie( $user->ID, true );
881 remove_filter( 'auth_cookie_expiration', array( 'Jetpack_SSO_Helpers', 'extend_auth_cookie_expiration_for_sso' ) );
882
883 /** This filter is documented in core/src/wp-includes/user.php */
884 do_action( 'wp_login', $user->user_login, $user );
885
886 wp_set_current_user( $user->ID );
887
888 $_request_redirect_to = isset( $_REQUEST['redirect_to'] ) ? esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
889 $redirect_to = user_can( $user, 'edit_posts' ) ? admin_url() : self::profile_page_url();
890
891 // If we have a saved redirect to request in a cookie.
892 if ( ! empty( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
893 // Set that as the requested redirect to.
894 $redirect_to = esc_url_raw( wp_unslash( $_COOKIE['jetpack_sso_redirect_to'] ) );
895 $_request_redirect_to = $redirect_to;
896 }
897
898 $json_api_auth_environment = Jetpack_SSO_Helpers::get_json_api_auth_environment();
899
900 $is_json_api_auth = ! empty( $json_api_auth_environment );
901 $is_user_connected = ( new Connection_Manager( 'jetpack' ) )->is_user_connected( $user->ID );
902 $roles = new Roles();
903 $tracking->record_user_event(
904 'sso_user_logged_in',
905 array(
906 'user_found_with' => $user_found_with,
907 'user_connected' => (bool) $is_user_connected,
908 'user_role' => $roles->translate_current_user_to_role(),
909 'is_json_api_auth' => (bool) $is_json_api_auth,
910 )
911 );
912
913 if ( $is_json_api_auth ) {
914 Jetpack::init()->verify_json_api_authorization_request( $json_api_auth_environment );
915 Jetpack::init()->store_json_api_authorization_token( $user->user_login, $user );
916
917 } elseif ( ! $is_user_connected ) {
918 wp_safe_redirect(
919 add_query_arg(
920 array(
921 'redirect_to' => $redirect_to,
922 'request_redirect_to' => $_request_redirect_to,
923 'calypso_env' => Jetpack::get_calypso_env(),
924 'jetpack-sso-auth-redirect' => '1',
925 ),
926 admin_url()
927 )
928 );
929 exit;
930 }
931
932 add_filter( 'allowed_redirect_hosts', array( 'Jetpack_SSO_Helpers', 'allowed_redirect_hosts' ) );
933 wp_safe_redirect(
934 /** This filter is documented in core/src/wp-login.php */
935 apply_filters( 'login_redirect', $redirect_to, $_request_redirect_to, $user )
936 );
937 exit;
938 }
939
940 add_filter( 'jetpack_sso_default_to_sso_login', '__return_false' );
941
942 $tracking->record_user_event(
943 'sso_login_failed',
944 array(
945 'error_message' => 'cant_find_user',
946 )
947 );
948
949 $this->user_data = $user_data;
950
951 $error = new WP_Error( 'account_not_found', __( 'Account not found. If you already have an account, make sure you have connected to WordPress.com.', 'jetpack' ) );
952
953 /** This filter is documented in core/src/wp-includes/pluggable.php */
954 do_action( 'wp_login_failed', $user_data->login, $error );
955 add_filter( 'login_message', array( 'Jetpack_SSO_Notices', 'cant_find_user' ) );
956 }
957
958 /**
959 * Retreive the admin profile page URL.
960 */
961 public static function profile_page_url() {
962 return admin_url( 'profile.php' );
963 }
964
965 /**
966 * Builds the "Login to WordPress.com" button that is displayed on the login page as well as user profile page.
967 *
968 * @param array $args An array of arguments to add to the SSO URL.
969 * @param boolean $is_primary If the button have the `button-primary` class.
970 * @return string Returns the HTML markup for the button.
971 */
972 public function build_sso_button( $args = array(), $is_primary = false ) {
973 $url = $this->build_sso_button_url( $args );
974 $classes = $is_primary
975 ? 'jetpack-sso button button-primary'
976 : 'jetpack-sso button';
977
978 return sprintf(
979 '<a rel="nofollow" href="%1$s" class="%2$s">%3$s %4$s</a>',
980 esc_url( $url ),
981 $classes,
982 '<span class="genericon genericon-wordpress"></span>',
983 esc_html__( 'Log in with WordPress.com', 'jetpack' )
984 );
985 }
986
987 /**
988 * Builds a URL with `jetpack-sso` action and option args which is used to setup SSO.
989 *
990 * @param array $args An array of arguments to add to the SSO URL.
991 * @return string The URL used for SSO.
992 */
993 public function build_sso_button_url( $args = array() ) {
994 $defaults = array(
995 'action' => 'jetpack-sso',
996 );
997
998 $args = wp_parse_args( $args, $defaults );
999
1000 if ( ! empty( $_GET['redirect_to'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1001 $args['redirect_to'] = rawurlencode( esc_url_raw( wp_unslash( $_GET['redirect_to'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1002 }
1003
1004 return add_query_arg( $args, wp_login_url() );
1005 }
1006
1007 /**
1008 * Retrieves a WordPress.com SSO URL with appropriate query parameters or dies.
1009 *
1010 * @param boolean $reauth If the user be forced to reauthenticate on WordPress.com.
1011 * @param array $args Optional query parameters.
1012 * @return string The WordPress.com SSO URL.
1013 */
1014 public function get_sso_url_or_die( $reauth = false, $args = array() ) {
1015 $custom_login_url = Jetpack_SSO_Helpers::get_custom_login_url();
1016 if ( $custom_login_url ) {
1017 $args['login_url'] = rawurlencode( $custom_login_url );
1018 }
1019
1020 if ( empty( $reauth ) ) {
1021 $sso_redirect = $this->build_sso_url( $args );
1022 } else {
1023 self::clear_wpcom_profile_cookies();
1024 $sso_redirect = $this->build_reauth_and_sso_url( $args );
1025 }
1026
1027 // If there was an error retrieving the SSO URL, then error.
1028 if ( is_wp_error( $sso_redirect ) ) {
1029 $error_message = sanitize_text_field(
1030 sprintf( '%s: %s', $sso_redirect->get_error_code(), $sso_redirect->get_error_message() )
1031 );
1032 $tracking = new Tracking();
1033 $tracking->record_user_event(
1034 'sso_login_redirect_failed',
1035 array(
1036 'error_message' => $error_message,
1037 )
1038 );
1039 wp_die( esc_html( $error_message ) );
1040 }
1041
1042 return $sso_redirect;
1043 }
1044
1045 /**
1046 * Build WordPress.com SSO URL with appropriate query parameters.
1047 *
1048 * @param array $args Optional query parameters.
1049 * @return string WordPress.com SSO URL
1050 */
1051 public function build_sso_url( $args = array() ) {
1052 $sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
1053 $defaults = array(
1054 'action' => 'jetpack-sso',
1055 'site_id' => Jetpack_Options::get_option( 'id' ),
1056 'sso_nonce' => $sso_nonce,
1057 'calypso_auth' => '1',
1058 );
1059
1060 $args = wp_parse_args( $args, $defaults );
1061
1062 if ( is_wp_error( $args['sso_nonce'] ) ) {
1063 return $args['sso_nonce'];
1064 }
1065
1066 return add_query_arg( $args, 'https://wordpress.com/wp-login.php' );
1067 }
1068
1069 /**
1070 * Build WordPress.com SSO URL with appropriate query parameters,
1071 * including the parameters necessary to force the user to reauthenticate
1072 * on WordPress.com.
1073 *
1074 * @param array $args Optional query parameters.
1075 * @return string WordPress.com SSO URL
1076 */
1077 public function build_reauth_and_sso_url( $args = array() ) {
1078 $sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
1079 $redirect = $this->build_sso_url(
1080 array(
1081 'force_auth' => '1',
1082 'sso_nonce' => $sso_nonce,
1083 )
1084 );
1085
1086 if ( is_wp_error( $redirect ) ) {
1087 return $redirect;
1088 }
1089
1090 $defaults = array(
1091 'action' => 'jetpack-sso',
1092 'site_id' => Jetpack_Options::get_option( 'id' ),
1093 'sso_nonce' => $sso_nonce,
1094 'reauth' => '1',
1095 'redirect_to' => rawurlencode( $redirect ),
1096 'calypso_auth' => '1',
1097 );
1098
1099 $args = wp_parse_args( $args, $defaults );
1100
1101 if ( is_wp_error( $args['sso_nonce'] ) ) {
1102 return $args['sso_nonce'];
1103 }
1104
1105 return add_query_arg( $args, 'https://wordpress.com/wp-login.php' );
1106 }
1107
1108 /**
1109 * Determines local user associated with a given WordPress.com user ID.
1110 *
1111 * @since 2.6.0
1112 *
1113 * @param int $wpcom_user_id User ID from WordPress.com.
1114 * @return object Local user object if found, null if not.
1115 */
1116 public static function get_user_by_wpcom_id( $wpcom_user_id ) {
1117 $user_query = new WP_User_Query(
1118 array(
1119 'meta_key' => 'wpcom_user_id',
1120 'meta_value' => (int) $wpcom_user_id,
1121 'number' => 1,
1122 )
1123 );
1124
1125 $users = $user_query->get_results();
1126 return $users ? array_shift( $users ) : null;
1127 }
1128
1129 /**
1130 * When jetpack-sso-auth-redirect query parameter is set, will redirect user to
1131 * WordPress.com authorization flow.
1132 *
1133 * We redirect here instead of in handle_login() because Jetpack::init()->build_connect_url
1134 * calls menu_page_url() which doesn't work properly until admin menus are registered.
1135 */
1136 public function maybe_authorize_user_after_sso() {
1137 if ( empty( $_GET['jetpack-sso-auth-redirect'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1138 return;
1139 }
1140
1141 $redirect_to = ! empty( $_GET['redirect_to'] ) ? esc_url_raw( wp_unslash( $_GET['redirect_to'] ) ) : admin_url(); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1142 $request_redirect_to = ! empty( $_GET['request_redirect_to'] ) ? esc_url_raw( wp_unslash( $_GET['request_redirect_to'] ) ) : $redirect_to; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1143
1144 /** This filter is documented in core/src/wp-login.php */
1145 $redirect_after_auth = apply_filters( 'login_redirect', $redirect_to, $request_redirect_to, wp_get_current_user() );
1146
1147 /**
1148 * Since we are passing this redirect to WordPress.com and therefore can not use wp_safe_redirect(),
1149 * let's sanitize it here to make sure it's safe. If the redirect is not safe, then use admin_url().
1150 */
1151 $redirect_after_auth = wp_sanitize_redirect( $redirect_after_auth );
1152 $redirect_after_auth = wp_validate_redirect( $redirect_after_auth, admin_url() );
1153
1154 /**
1155 * Return the raw connect URL with our redirect and attribute connection to SSO.
1156 * We remove any other filters that may be turning on the in-place connection
1157 * since we will be redirecting the user as opposed to iFraming.
1158 */
1159 remove_all_filters( 'jetpack_use_iframe_authorization_flow' );
1160 add_filter( 'jetpack_use_iframe_authorization_flow', '__return_false' );
1161 $connect_url = Jetpack::init()->build_connect_url( true, $redirect_after_auth, 'sso' );
1162
1163 add_filter( 'allowed_redirect_hosts', array( 'Jetpack_SSO_Helpers', 'allowed_redirect_hosts' ) );
1164 wp_safe_redirect( $connect_url );
1165 exit;
1166 }
1167
1168 /**
1169 * Cache user's display name and Gravatar so it can be displayed on the login screen. These cookies are
1170 * stored when the user logs out, and then deleted when the user logs in.
1171 */
1172 public function store_wpcom_profile_cookies_on_logout() {
1173 if ( ! ( new Connection_Manager( 'jetpack' ) )->is_user_connected( get_current_user_id() ) ) {
1174 return;
1175 }
1176
1177 $user_data = $this->get_user_data( get_current_user_id() );
1178 if ( ! $user_data ) {
1179 return;
1180 }
1181
1182 setcookie(
1183 'jetpack_sso_wpcom_name_' . COOKIEHASH,
1184 $user_data->display_name,
1185 time() + WEEK_IN_SECONDS,
1186 COOKIEPATH,
1187 COOKIE_DOMAIN,
1188 is_ssl(),
1189 true
1190 );
1191
1192 setcookie(
1193 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
1194 get_avatar_url(
1195 $user_data->email,
1196 array(
1197 'size' => 144,
1198 'default' => 'mystery',
1199 )
1200 ),
1201 time() + WEEK_IN_SECONDS,
1202 COOKIEPATH,
1203 COOKIE_DOMAIN,
1204 is_ssl(),
1205 true
1206 );
1207 }
1208
1209 /**
1210 * Determines if a local user is connected to WordPress.com
1211 *
1212 * @since 2.8
1213 * @param integer $user_id - Local user id.
1214 * @return boolean
1215 **/
1216 public function is_user_connected( $user_id ) {
1217 return $this->get_user_data( $user_id );
1218 }
1219
1220 /**
1221 * Retrieves a user's WordPress.com data
1222 *
1223 * @since 2.8
1224 * @param integer $user_id - Local user id.
1225 * @return mixed null or stdClass
1226 **/
1227 public function get_user_data( $user_id ) {
1228 return get_user_meta( $user_id, 'wpcom_user_data', true );
1229 }
1230 }
1231
1232 Jetpack_SSO::get_instance();
1233