PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 9.6.1
Jetpack – WP Security, Backup, Speed, & Growth v9.6.1
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 / protect.php
protect.php
908 lines 26.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Module Name: Protect
4 * Module Description: Enabling brute force protection will prevent bots and hackers from attempting to log in to your website with common username and password combinations.
5 * Sort Order: 1
6 * Recommendation Order: 4
7 * First Introduced: 3.4
8 * Requires Connection: Yes
9 * Requires User Connection: Yes
10 * Auto Activate: Yes
11 * Module Tags: Recommended
12 * Feature: Security
13 * Additional Search Queries: security, jetpack protect, secure, protection, botnet, brute force, protect, login, bot, password, passwords, strong passwords, strong password, wp-login.php, protect admin
14 */
15
16 use Automattic\Jetpack\Constants;
17 use Automattic\Jetpack\Connection\Utils as Connection_Utils;
18
19 include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
20
21 class Jetpack_Protect_Module {
22
23 private static $__instance = null;
24 public $api_key;
25 public $api_key_error;
26 public $whitelist;
27 public $whitelist_error;
28 public $whitelist_saved;
29 private $local_host;
30 public $last_request;
31 public $last_response_raw;
32 public $last_response;
33 private $block_login_with_math;
34
35 /**
36 * Singleton implementation
37 *
38 * @return object
39 */
40 public static function instance() {
41 if ( ! is_a( self::$__instance, 'Jetpack_Protect_Module' ) ) {
42 self::$__instance = new Jetpack_Protect_Module();
43 }
44
45 return self::$__instance;
46 }
47
48 /**
49 * Registers actions
50 */
51 private function __construct() {
52 add_action( 'jetpack_activate_module_protect', array ( $this, 'on_activation' ) );
53 add_action( 'jetpack_deactivate_module_protect', array ( $this, 'on_deactivation' ) );
54 add_action( 'jetpack_modules_loaded', array ( $this, 'modules_loaded' ) );
55 add_action( 'login_form', array ( $this, 'check_use_math' ), 0 );
56 add_filter( 'authenticate', array ( $this, 'check_preauth' ), 10, 3 );
57 add_action( 'wp_login', array ( $this, 'log_successful_login' ), 10, 2 );
58 add_action( 'wp_login_failed', array ( $this, 'log_failed_attempt' ) );
59 add_action( 'admin_init', array ( $this, 'maybe_update_headers' ) );
60 add_action( 'admin_init', array ( $this, 'maybe_display_security_warning' ) );
61
62 // This is a backup in case $pagenow fails for some reason
63 add_action( 'login_form', array ( $this, 'check_login_ability' ), 1 );
64
65 // Load math fallback after math page form submission
66 if ( isset( $_POST[ 'jetpack_protect_process_math_form' ] ) ) {
67 include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
68 new Jetpack_Protect_Math_Authenticate;
69 }
70
71 // Runs a script every day to clean up expired transients so they don't
72 // clog up our users' databases
73 require_once( JETPACK__PLUGIN_DIR . '/modules/protect/transient-cleanup.php' );
74 }
75
76 /**
77 * On module activation, try to get an api key
78 */
79 public function on_activation() {
80 if ( is_multisite() && is_main_site() && get_site_option( 'jetpack_protect_active', 0 ) == 0 ) {
81 update_site_option( 'jetpack_protect_active', 1 );
82 }
83
84 update_site_option( 'jetpack_protect_activating', 'activating' );
85
86 // Get BruteProtect's counter number
87 Jetpack_Protect_Module::protect_call( 'check_key' );
88 }
89
90 /**
91 * On module deactivation, unset protect_active
92 */
93 public function on_deactivation() {
94 if ( is_multisite() && is_main_site() ) {
95 update_site_option( 'jetpack_protect_active', 0 );
96 }
97 }
98
99 public function maybe_get_protect_key() {
100 if ( get_site_option( 'jetpack_protect_activating', false ) && ! get_site_option( 'jetpack_protect_key', false ) ) {
101 $key = $this->get_protect_key();
102 delete_site_option( 'jetpack_protect_activating' );
103 return $key;
104 }
105
106 return get_site_option( 'jetpack_protect_key' );
107 }
108
109 /**
110 * Sends a "check_key" API call once a day. This call allows us to track IP-related
111 * headers for this server via the Protect API, in order to better identify the source
112 * IP for login attempts
113 */
114 public function maybe_update_headers( $force = false ) {
115 $updated_recently = $this->get_transient( 'jpp_headers_updated_recently' );
116
117 if ( ! $force ) {
118 if ( isset( $_GET['protect_update_headers'] ) ) {
119 $force = true;
120 }
121 }
122
123 // check that current user is admin so we prevent a lower level user from adding
124 // a trusted header, allowing them to brute force an admin account
125 if ( ( $updated_recently && ! $force ) || ! current_user_can( 'update_plugins' ) ) {
126 return;
127 }
128
129 $response = Jetpack_Protect_Module::protect_call( 'check_key' );
130 $this->set_transient( 'jpp_headers_updated_recently', 1, DAY_IN_SECONDS );
131
132 if ( isset( $response['msg'] ) && $response['msg'] ) {
133 update_site_option( 'trusted_ip_header', json_decode( $response['msg'] ) );
134 }
135
136 }
137
138 public function maybe_display_security_warning() {
139 if ( is_multisite() && current_user_can( 'manage_network' ) ) {
140 if ( ! function_exists( 'is_plugin_active_for_network' ) ) {
141 require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
142 }
143
144 if ( ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_FILE ) ) ) {
145 add_action( 'load-index.php', array( $this, 'prepare_jetpack_protect_multisite_notice' ) );
146 add_action( 'wp_ajax_jetpack-protect-dismiss-multisite-banner', array( $this, 'ajax_dismiss_handler' ) );
147 }
148 }
149 }
150
151 public function prepare_jetpack_protect_multisite_notice() {
152 $dismissed = get_site_option( 'jetpack_dismissed_protect_multisite_banner' );
153 if ( $dismissed ) {
154 return;
155 }
156
157 add_action( 'admin_notices', array ( $this, 'admin_jetpack_manage_notice' ) );
158 }
159
160 public function ajax_dismiss_handler() {
161 check_ajax_referer( 'jetpack_protect_multisite_banner_opt_out' );
162
163 if ( ! current_user_can( 'manage_network' ) ) {
164 wp_send_json_error( new WP_Error( 'insufficient_permissions' ) );
165 }
166
167 update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
168
169 wp_send_json_success();
170 }
171
172 /**
173 * Displays a warning about Jetpack Protect's network activation requirement.
174 * Attaches some custom JS to Core's `is-dismissible` UI to save the dismissed state.
175 */
176 public function admin_jetpack_manage_notice() {
177 ?>
178 <div class="jetpack-protect-warning notice notice-warning is-dismissible" data-dismiss-nonce="<?php echo esc_attr( wp_create_nonce( 'jetpack_protect_multisite_banner_opt_out' ) ); ?>">
179 <h2><?php esc_html_e( 'Jetpack Brute Force Attack Prevention cannot keep your site secure', 'jetpack' ); ?></h2>
180
181 <p><?php esc_html_e( "Thanks for activating Jetpack's brute force attack prevention feature! To start protecting your whole WordPress Multisite Network, please network activate the Jetpack plugin. Due to the way logins are handled on WordPress Multisite Networks, Jetpack must be network activated in order for the brute force attack prevention feature to work properly.", 'jetpack' ); ?></p>
182
183 <p>
184 <a class="button-primary" href="<?php echo esc_url( network_admin_url( 'plugins.php' ) ); ?>">
185 <?php esc_html_e( 'View Network Admin', 'jetpack' ); ?>
186 </a>
187 <a class="button" href="<?php echo esc_url( __( 'https://jetpack.com/support/multisite-protect', 'jetpack' ) ); ?>" target="_blank">
188 <?php esc_html_e( 'Learn More' ); ?>
189 </a>
190 </p>
191 </div>
192 <script>
193 jQuery( function( $ ) {
194 $( '.jetpack-protect-warning' ).on( 'click', 'button.notice-dismiss', function( event ) {
195 event.preventDefault();
196
197 wp.ajax.post(
198 'jetpack-protect-dismiss-multisite-banner',
199 {
200 _wpnonce: $( event.delegateTarget ).data( 'dismiss-nonce' ),
201 }
202 ).fail( function( error ) { <?php
203 // A failure here is really strange, and there's not really anything a site owner can do to fix one.
204 // Just log the error for now to help debugging. ?>
205
206 if ( 'function' === typeof error.done && '-1' === error.responseText ) {
207 console.error( 'Notice dismissal failed: check_ajax_referer' );
208 } else {
209 console.error( 'Notice dismissal failed: ' + JSON.stringify( error ) );
210 }
211 } )
212 } );
213 } );
214 </script>
215 <?php
216 }
217
218 /**
219 * Request an api key from wordpress.com
220 *
221 * @return bool | string
222 */
223 public function get_protect_key() {
224
225 $protect_blog_id = Jetpack_Protect_Module::get_main_blog_jetpack_id();
226
227 // If we can't find the the blog id, that means we are on multisite, and the main site never connected
228 // the protect api key is linked to the main blog id - instruct the user to connect their main blog
229 if ( ! $protect_blog_id ) {
230 $this->api_key_error = __( 'Your main blog is not connected to WordPress.com. Please connect to get an API key.', 'jetpack' );
231
232 return false;
233 }
234
235 $request = array (
236 'jetpack_blog_id' => $protect_blog_id,
237 'bruteprotect_api_key' => get_site_option( 'bruteprotect_api_key' ),
238 'multisite' => '0',
239 );
240
241 // Send the number of blogs on the network if we are on multisite
242 if ( is_multisite() ) {
243 $request['multisite'] = get_blog_count();
244 if ( ! $request['multisite'] ) {
245 global $wpdb;
246 $request['multisite'] = $wpdb->get_var( "SELECT COUNT(blog_id) as c FROM $wpdb->blogs WHERE spam = '0' AND deleted = '0' and archived = '0'" );
247 }
248 }
249
250 // Request the key
251 $xml = new Jetpack_IXR_Client();
252 $xml->query( 'jetpack.protect.requestKey', $request );
253
254 // Hmm, can't talk to wordpress.com
255 if ( $xml->isError() ) {
256 $code = $xml->getErrorCode();
257 $message = $xml->getErrorMessage();
258 $this->api_key_error = sprintf( __( 'Error connecting to WordPress.com. Code: %1$s, %2$s', 'jetpack' ), $code, $message );
259
260 return false;
261 }
262
263 $response = $xml->getResponse();
264
265 // Hmm. Can't talk to the protect servers ( api.bruteprotect.com )
266 if ( ! isset( $response['data'] ) ) {
267 $this->api_key_error = __( 'No reply from Jetpack servers', 'jetpack' );
268
269 return false;
270 }
271
272 // There was an issue generating the key
273 if ( empty( $response['success'] ) ) {
274 $this->api_key_error = $response['data'];
275
276 return false;
277 }
278
279 // Key generation successful!
280 $active_plugins = Jetpack::get_active_plugins();
281
282 // We only want to deactivate BruteProtect if we successfully get a key
283 if ( in_array( 'bruteprotect/bruteprotect.php', $active_plugins ) ) {
284 Jetpack_Client_Server::deactivate_plugin( 'bruteprotect/bruteprotect.php', 'BruteProtect' );
285 }
286
287 $key = $response['data'];
288 update_site_option( 'jetpack_protect_key', $key );
289
290 return $key;
291 }
292
293 /**
294 * Called via WP action wp_login_failed to log failed attempt with the api
295 *
296 * Fires custom, plugable action jpp_log_failed_attempt with the IP
297 *
298 * @return void
299 */
300 function log_failed_attempt( $login_user = null ) {
301
302 /**
303 * Fires before every failed login attempt.
304 *
305 * @module protect
306 *
307 * @since 3.4.0
308 *
309 * @param array Information about failed login attempt
310 * [
311 * 'login' => (string) Username or email used in failed login attempt
312 * ]
313 */
314 do_action( 'jpp_log_failed_attempt', array( 'login' => $login_user ) );
315
316 if ( isset( $_COOKIE['jpp_math_pass'] ) ) {
317
318 $transient = $this->get_transient( 'jpp_math_pass_' . $_COOKIE['jpp_math_pass'] );
319 $transient--;
320
321 if ( ! $transient || $transient < 1 ) {
322 $this->delete_transient( 'jpp_math_pass_' . $_COOKIE['jpp_math_pass'] );
323 setcookie( 'jpp_math_pass', 0, time() - DAY_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, false );
324 } else {
325 $this->set_transient( 'jpp_math_pass_' . $_COOKIE['jpp_math_pass'], $transient, DAY_IN_SECONDS );
326 }
327
328 }
329 $this->protect_call( 'failed_attempt' );
330 }
331
332 /**
333 * Set up the Protect configuration page
334 */
335 public function modules_loaded() {
336 Jetpack::enable_module_configurable( __FILE__ );
337 }
338
339 /**
340 * Logs a successful login back to our servers, this allows us to make sure we're not blocking
341 * a busy IP that has a lot of good logins along with some forgotten passwords. Also saves current user's ip
342 * to the ip address whitelist
343 */
344 public function log_successful_login( $user_login, $user = null ) {
345 if ( ! $user ) { // For do_action( 'wp_login' ) calls that lacked passing the 2nd arg.
346 $user = get_user_by( 'login', $user_login );
347 }
348
349 $this->protect_call( 'successful_login', array ( 'roles' => $user->roles ) );
350 }
351
352
353 /**
354 * Checks for loginability BEFORE authentication so that bots don't get to go around the log in form.
355 *
356 * If we are using our math fallback, authenticate via math-fallback.php
357 *
358 * @param string $user
359 * @param string $username
360 * @param string $password
361 *
362 * @return string $user
363 */
364 function check_preauth( $user = 'Not Used By Protect', $username = 'Not Used By Protect', $password = 'Not Used By Protect' ) {
365 $allow_login = $this->check_login_ability( true );
366 $use_math = $this->get_transient( 'brute_use_math' );
367
368 if ( ! $allow_login ) {
369 $this->block_with_math();
370 }
371
372 if ( ( 1 == $use_math || 1 == $this->block_login_with_math ) && isset( $_POST['log'] ) ) {
373 include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
374 Jetpack_Protect_Math_Authenticate::math_authenticate();
375 }
376
377 return $user;
378 }
379
380 /**
381 * Get all IP headers so that we can process on our server...
382 *
383 * @return string
384 */
385 function get_headers() {
386 $ip_related_headers = array (
387 'GD_PHP_HANDLER',
388 'HTTP_AKAMAI_ORIGIN_HOP',
389 'HTTP_CF_CONNECTING_IP',
390 'HTTP_CLIENT_IP',
391 'HTTP_FASTLY_CLIENT_IP',
392 'HTTP_FORWARDED',
393 'HTTP_FORWARDED_FOR',
394 'HTTP_INCAP_CLIENT_IP',
395 'HTTP_TRUE_CLIENT_IP',
396 'HTTP_X_CLIENTIP',
397 'HTTP_X_CLUSTER_CLIENT_IP',
398 'HTTP_X_FORWARDED',
399 'HTTP_X_FORWARDED_FOR',
400 'HTTP_X_IP_TRAIL',
401 'HTTP_X_REAL_IP',
402 'HTTP_X_VARNISH',
403 'REMOTE_ADDR'
404 );
405
406 foreach ( $ip_related_headers as $header ) {
407 if ( ! empty( $_SERVER[ $header ] ) ) {
408 $output[ $header ] = $_SERVER[ $header ];
409 }
410 }
411
412 return $output;
413 }
414
415 /*
416 * Checks if the IP address has been whitelisted
417 *
418 * @param string $ip
419 *
420 * @return bool
421 */
422 function ip_is_whitelisted( $ip ) {
423 // If we found an exact match in wp-config
424 if ( defined( 'JETPACK_IP_ADDRESS_OK' ) && JETPACK_IP_ADDRESS_OK == $ip ) {
425 return true;
426 }
427
428 $whitelist = jetpack_protect_get_local_whitelist();
429
430 if ( is_multisite() ) {
431 $whitelist = array_merge( $whitelist, get_site_option( 'jetpack_protect_global_whitelist', array () ) );
432 }
433
434 if ( ! empty( $whitelist ) ) :
435 foreach ( $whitelist as $item ) :
436 // If the IPs are an exact match
437 if ( ! $item->range && isset( $item->ip_address ) && $item->ip_address == $ip ) {
438 return true;
439 }
440
441 if ( $item->range && isset( $item->range_low ) && isset( $item->range_high ) ) {
442 if ( jetpack_protect_ip_address_is_in_range( $ip, $item->range_low, $item->range_high ) ) {
443 return true;
444 }
445 }
446 endforeach;
447 endif;
448
449 return false;
450 }
451
452 /**
453 * Checks the status for a given IP. API results are cached as transients
454 *
455 * @param bool $preauth Whether or not we are checking prior to authorization
456 *
457 * @return bool Either returns true, fires $this->kill_login, or includes a math fallback and returns false
458 */
459 function check_login_ability( $preauth = false ) {
460
461 /**
462 * JETPACK_ALWAYS_PROTECT_LOGIN will always disable the login page, and use a page provided by Jetpack.
463 */
464 if ( Constants::is_true( 'JETPACK_ALWAYS_PROTECT_LOGIN' ) ) {
465 $this->kill_login();
466 }
467
468 if ( $this->is_current_ip_whitelisted() ) {
469 return true;
470 }
471
472 $status = $this->get_cached_status();
473
474 if ( empty( $status ) ) {
475 // If we've reached this point, this means that the IP isn't cached.
476 // Now we check with the Protect API to see if we should allow login
477 $response = $this->protect_call( $action = 'check_ip' );
478
479 if ( isset( $response['math'] ) && ! function_exists( 'brute_math_authenticate' ) ) {
480 include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
481 new Jetpack_Protect_Math_Authenticate;
482
483 return false;
484 }
485
486 $status = $response['status'];
487 }
488
489 if ( 'blocked' == $status ) {
490 $this->block_with_math();
491 }
492
493 if ( 'blocked-hard' == $status ) {
494 $this->kill_login();
495 }
496
497 return true;
498 }
499
500 function is_current_ip_whitelisted() {
501 $ip = jetpack_protect_get_ip();
502
503 // Server is misconfigured and we can't get an IP
504 if ( ! $ip && class_exists( 'Jetpack' ) ) {
505 Jetpack::deactivate_module( 'protect' );
506 ob_start();
507 Jetpack::state( 'message', 'protect_misconfigured_ip' );
508 ob_end_clean();
509 return true;
510 }
511
512 /**
513 * Short-circuit check_login_ability.
514 *
515 * If there is an alternate way to validate the current IP such as
516 * a hard-coded list of IP addresses, we can short-circuit the rest
517 * of the login ability checks and return true here.
518 *
519 * @module protect
520 *
521 * @since 4.4.0
522 *
523 * @param bool false Should we allow all logins for the current ip? Default: false
524 */
525 if ( apply_filters( 'jpp_allow_login', false, $ip ) ) {
526 return true;
527 }
528
529 if ( jetpack_protect_ip_is_private( $ip ) ) {
530 return true;
531 }
532
533 if ( $this->ip_is_whitelisted( $ip ) ) {
534 return true;
535 }
536 }
537
538 function has_login_ability() {
539 if ( $this->is_current_ip_whitelisted() ) {
540 return true;
541 }
542 $status = $this->get_cached_status();
543 if ( empty( $status ) || $status === 'ok' ) {
544 return true;
545 }
546 return false;
547 }
548
549 function get_cached_status() {
550 $transient_name = $this->get_transient_name();
551 $value = $this->get_transient( $transient_name );
552 if ( isset( $value['status'] ) ) {
553 return $value['status'];
554 }
555 return '';
556 }
557
558 function block_with_math() {
559 /**
560 * By default, Protect will allow a user who has been blocked for too
561 * many failed logins to start answering math questions to continue logging in
562 *
563 * For added security, you can disable this.
564 *
565 * @module protect
566 *
567 * @since 3.6.0
568 *
569 * @param bool Whether to allow math for blocked users or not.
570 */
571
572 $this->block_login_with_math = 1;
573 /**
574 * Allow Math fallback for blocked IPs.
575 *
576 * @module protect
577 *
578 * @since 3.6.0
579 *
580 * @param bool true Should we fallback to the Math questions when an IP is blocked. Default to true.
581 */
582 $allow_math_fallback_on_fail = apply_filters( 'jpp_use_captcha_when_blocked', true );
583 if ( ! $allow_math_fallback_on_fail ) {
584 $this->kill_login();
585 }
586 include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
587 new Jetpack_Protect_Math_Authenticate;
588
589 return false;
590 }
591
592 /*
593 * Kill a login attempt
594 */
595 function kill_login() {
596 if (
597 isset( $_GET['action'], $_GET['_wpnonce'] ) &&
598 'logout' === $_GET['action'] &&
599 wp_verify_nonce( $_GET['_wpnonce'], 'log-out' ) &&
600 wp_get_current_user()
601
602 ) {
603 // Allow users to logout
604 return;
605 }
606
607 $ip = jetpack_protect_get_ip();
608 /**
609 * Fires before every killed login.
610 *
611 * @module protect
612 *
613 * @since 3.4.0
614 *
615 * @param string $ip IP flagged by Protect.
616 */
617 do_action( 'jpp_kill_login', $ip );
618
619 if( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
620 $die_string = sprintf( __( 'Your IP (%1$s) has been flagged for potential security violations.', 'jetpack' ), str_replace( 'http://', '', esc_url( 'http://' . $ip ) ) );
621 wp_die(
622 $die_string,
623 __( 'Login Blocked by Jetpack', 'jetpack' ),
624 array ( 'response' => 403 )
625 );
626 }
627
628 require_once dirname( __FILE__ ) . '/protect/blocked-login-page.php';
629 $blocked_login_page = Jetpack_Protect_Blocked_Login_Page::instance( $ip );
630
631 if ( $blocked_login_page->is_blocked_user_valid() ) {
632 return;
633 }
634
635 $blocked_login_page->render_and_die();
636 }
637
638 /*
639 * Checks if the protect API call has failed, and if so initiates the math captcha fallback.
640 */
641 public function check_use_math() {
642 $use_math = $this->get_transient( 'brute_use_math' );
643 if ( $use_math ) {
644 include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
645 new Jetpack_Protect_Math_Authenticate;
646 }
647 }
648
649 /**
650 * If we're in a multisite network, return the blog ID of the primary blog
651 *
652 * @return int
653 */
654 public function get_main_blog_id() {
655 if ( ! is_multisite() ) {
656 return false;
657 }
658
659 global $current_site;
660 $primary_blog_id = $current_site->blog_id;
661
662 return $primary_blog_id;
663 }
664
665 /**
666 * Get jetpack blog id, or the jetpack blog id of the main blog in the main network
667 *
668 * @return int
669 */
670 public function get_main_blog_jetpack_id() {
671 if ( ! is_main_site() ) {
672 switch_to_blog( $this->get_main_blog_id() );
673 $id = Jetpack::get_option( 'id', false );
674 restore_current_blog();
675 } else {
676 $id = Jetpack::get_option( 'id' );
677 }
678
679 return $id;
680 }
681
682 public function check_api_key() {
683 $response = $this->protect_call( 'check_key' );
684
685 if ( isset( $response['ckval'] ) ) {
686 return true;
687 }
688
689 if ( isset( $response['error'] ) ) {
690
691 if ( $response['error'] == 'Invalid API Key' ) {
692 $this->api_key_error = __( 'Your API key is invalid', 'jetpack' );
693 }
694
695 if ( $response['error'] == 'API Key Required' ) {
696 $this->api_key_error = __( 'No API key', 'jetpack' );
697 }
698 }
699
700 $this->api_key_error = __( 'There was an error contacting Jetpack servers.', 'jetpack' );
701
702 return false;
703 }
704
705 /**
706 * Calls over to the api using wp_remote_post
707 *
708 * @param string $action 'check_ip', 'check_key', or 'failed_attempt'
709 * @param array $request Any custom data to post to the api
710 *
711 * @return array
712 */
713 function protect_call( $action = 'check_ip', $request = array () ) {
714 global $wp_version;
715
716 $api_key = $this->maybe_get_protect_key();
717
718 $user_agent = "WordPress/{$wp_version} | Jetpack/" . constant( 'JETPACK__VERSION' );
719
720 $request['action'] = $action;
721 $request['ip'] = jetpack_protect_get_ip();
722 $request['host'] = $this->get_local_host();
723 $request['headers'] = json_encode( $this->get_headers() );
724 $request['jetpack_version'] = constant( 'JETPACK__VERSION' );
725 $request['wordpress_version'] = (string) $wp_version ;
726 $request['api_key'] = $api_key;
727 $request['multisite'] = "0";
728
729 if ( is_multisite() ) {
730 $request['multisite'] = get_blog_count();
731 }
732
733
734 /**
735 * Filter controls maximum timeout in waiting for reponse from Protect servers.
736 *
737 * @module protect
738 *
739 * @since 4.0.4
740 *
741 * @param int $timeout Max time (in seconds) to wait for a response.
742 */
743 $timeout = apply_filters( 'jetpack_protect_connect_timeout', 30 );
744
745 $args = array (
746 'body' => $request,
747 'user-agent' => $user_agent,
748 'httpversion' => '1.0',
749 'timeout' => absint( $timeout )
750 );
751
752 $response_json = wp_remote_post( JETPACK_PROTECT__API_HOST, $args );
753 $this->last_response_raw = $response_json;
754
755 $transient_name = $this->get_transient_name();
756 $this->delete_transient( $transient_name );
757
758 if ( is_array( $response_json ) ) {
759 $response = json_decode( $response_json['body'], true );
760 }
761
762 if ( isset( $response['blocked_attempts'] ) && $response['blocked_attempts'] ) {
763 update_site_option( 'jetpack_protect_blocked_attempts', $response['blocked_attempts'] );
764 }
765
766 if ( isset( $response['status'] ) && ! isset( $response['error'] ) ) {
767 $response['expire'] = time() + $response['seconds_remaining'];
768 $this->set_transient( $transient_name, $response, $response['seconds_remaining'] );
769 $this->delete_transient( 'brute_use_math' );
770 } else { // Fallback to Math Captcha if no response from API host
771 $this->set_transient( 'brute_use_math', 1, 600 );
772 $response['status'] = 'ok';
773 $response['math'] = true;
774 }
775
776 if ( isset( $response['error'] ) ) {
777 update_site_option( 'jetpack_protect_error', $response['error'] );
778 } else {
779 delete_site_option( 'jetpack_protect_error' );
780 }
781
782 return $response;
783 }
784
785 function get_transient_name() {
786 $headers = $this->get_headers();
787 $header_hash = md5( json_encode( $headers ) );
788
789 return 'jpp_li_' . $header_hash;
790 }
791
792 /**
793 * Wrapper for WordPress set_transient function, our version sets
794 * the transient on the main site in the network if this is a multisite network
795 *
796 * We do it this way (instead of set_site_transient) because of an issue where
797 * sitewide transients are always autoloaded
798 * https://core.trac.wordpress.org/ticket/22846
799 *
800 * @param string $transient Transient name. Expected to not be SQL-escaped. Must be
801 * 45 characters or fewer in length.
802 * @param mixed $value Transient value. Must be serializable if non-scalar.
803 * Expected to not be SQL-escaped.
804 * @param int $expiration Optional. Time until expiration in seconds. Default 0.
805 *
806 * @return bool False if value was not set and true if value was set.
807 */
808 function set_transient( $transient, $value, $expiration ) {
809 if ( is_multisite() && ! is_main_site() ) {
810 switch_to_blog( $this->get_main_blog_id() );
811 $return = set_transient( $transient, $value, $expiration );
812 restore_current_blog();
813
814 return $return;
815 }
816
817 return set_transient( $transient, $value, $expiration );
818 }
819
820 /**
821 * Wrapper for WordPress delete_transient function, our version deletes
822 * the transient on the main site in the network if this is a multisite network
823 *
824 * @param string $transient Transient name. Expected to not be SQL-escaped.
825 *
826 * @return bool true if successful, false otherwise
827 */
828 function delete_transient( $transient ) {
829 if ( is_multisite() && ! is_main_site() ) {
830 switch_to_blog( $this->get_main_blog_id() );
831 $return = delete_transient( $transient );
832 restore_current_blog();
833
834 return $return;
835 }
836
837 return delete_transient( $transient );
838 }
839
840 /**
841 * Wrapper for WordPress get_transient function, our version gets
842 * the transient on the main site in the network if this is a multisite network
843 *
844 * @param string $transient Transient name. Expected to not be SQL-escaped.
845 *
846 * @return mixed Value of transient.
847 */
848 function get_transient( $transient ) {
849 if ( is_multisite() && ! is_main_site() ) {
850 switch_to_blog( $this->get_main_blog_id() );
851 $return = get_transient( $transient );
852 restore_current_blog();
853
854 return $return;
855 }
856
857 return get_transient( $transient );
858 }
859
860 /**
861 * Get the API host.
862 *
863 * @return string
864 *
865 * @deprecated 9.1.0 Use constant `JETPACK_PROTECT__API_HOST` instead.
866 */
867 function get_api_host() {
868 _deprecated_function( __METHOD__, 'jetpack-9.1.0' );
869
870 return JETPACK_PROTECT__API_HOST;
871 }
872
873 function get_local_host() {
874 if ( isset( $this->local_host ) ) {
875 return $this->local_host;
876 }
877
878 $uri = 'http://' . strtolower( $_SERVER['HTTP_HOST'] );
879
880 if ( is_multisite() ) {
881 $uri = network_home_url();
882 }
883
884 $uridata = wp_parse_url( $uri );
885
886 $domain = $uridata['host'];
887
888 // If we still don't have the site_url, get it
889 if ( ! $domain ) {
890 $uri = get_site_url( 1 );
891 $uridata = wp_parse_url( $uri );
892 $domain = $uridata['host'];
893 }
894
895 $this->local_host = $domain;
896
897 return $this->local_host;
898 }
899
900 }
901
902 $jetpack_protect = Jetpack_Protect_Module::instance();
903
904 global $pagenow;
905 if ( isset( $pagenow ) && 'wp-login.php' == $pagenow ) {
906 $jetpack_protect->check_login_ability();
907 }
908