PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 12.5
Jetpack – WP Security, Backup, Speed, & Growth v12.5
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 12.5, at modules/sso.php

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