PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 10.5.3
Jetpack – WP Security, Backup, Speed, & Growth v10.5.3
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 14.4.2 All 500 releases
jetpack / modules / protect.php
protect.php
895 lines 26.0 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
18 include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
19
20 class Jetpack_Protect_Module {
21
22 private static $__instance = null;
23 public $api_key;
24 public $api_key_error;
25 public $whitelist;
26 public $whitelist_error;
27 public $whitelist_saved;
28 private $local_host;
29 public $last_request;
30 public $last_response_raw;
31 public $last_response;
32 private $block_login_with_math;
33
34 /**
35 * Singleton implementation
36 *
37 * @return object
38 */
39 public static function instance() {
40 if ( ! is_a( self::$__instance, 'Jetpack_Protect_Module' ) ) {
41 self::$__instance = new Jetpack_Protect_Module();
42 }
43
44 return self::$__instance;
45 }
46
47 /**
48 * Registers actions
49 */
50 private function __construct() {
51 add_action( 'jetpack_activate_module_protect', array ( $this, 'on_activation' ) );
52 add_action( 'jetpack_deactivate_module_protect', array ( $this, 'on_deactivation' ) );
53 add_action( 'jetpack_modules_loaded', array ( $this, 'modules_loaded' ) );
54 add_action( 'login_form', array ( $this, 'check_use_math' ), 0 );
55 add_filter( 'authenticate', array ( $this, 'check_preauth' ), 10, 3 );
56 add_action( 'wp_login', array ( $this, 'log_successful_login' ), 10, 2 );
57 add_action( 'wp_login_failed', array ( $this, 'log_failed_attempt' ) );
58 add_action( 'admin_init', array ( $this, 'maybe_update_headers' ) );
59 add_action( 'admin_init', array ( $this, 'maybe_display_security_warning' ) );
60
61 // This is a backup in case $pagenow fails for some reason
62 add_action( 'login_form', array ( $this, 'check_login_ability' ), 1 );
63
64 // Load math fallback after math page form submission
65 if ( isset( $_POST[ 'jetpack_protect_process_math_form' ] ) ) {
66 include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
67 new Jetpack_Protect_Math_Authenticate;
68 }
69
70 // Runs a script every day to clean up expired transients so they don't
71 // clog up our users' databases
72 require_once( JETPACK__PLUGIN_DIR . '/modules/protect/transient-cleanup.php' );
73 }
74
75 /**
76 * On module activation, try to get an api key
77 */
78 public function on_activation() {
79 if ( is_multisite() && is_main_site() && get_site_option( 'jetpack_protect_active', 0 ) == 0 ) {
80 update_site_option( 'jetpack_protect_active', 1 );
81 }
82
83 update_site_option( 'jetpack_protect_activating', 'activating' );
84
85 // Get BruteProtect's counter number
86 Jetpack_Protect_Module::protect_call( 'check_key' );
87 }
88
89 /**
90 * On module deactivation, unset protect_active
91 */
92 public function on_deactivation() {
93 if ( is_multisite() && is_main_site() ) {
94 update_site_option( 'jetpack_protect_active', 0 );
95 }
96 }
97
98 public function maybe_get_protect_key() {
99 if ( get_site_option( 'jetpack_protect_activating', false ) && ! get_site_option( 'jetpack_protect_key', false ) ) {
100 $key = $this->get_protect_key();
101 delete_site_option( 'jetpack_protect_activating' );
102 return $key;
103 }
104
105 return get_site_option( 'jetpack_protect_key' );
106 }
107
108 /**
109 * Sends a "check_key" API call once a day. This call allows us to track IP-related
110 * headers for this server via the Protect API, in order to better identify the source
111 * IP for login attempts
112 */
113 public function maybe_update_headers( $force = false ) {
114 $updated_recently = $this->get_transient( 'jpp_headers_updated_recently' );
115
116 if ( ! $force ) {
117 if ( isset( $_GET['protect_update_headers'] ) ) {
118 $force = true;
119 }
120 }
121
122 // check that current user is admin so we prevent a lower level user from adding
123 // a trusted header, allowing them to brute force an admin account
124 if ( ( $updated_recently && ! $force ) || ! current_user_can( 'update_plugins' ) ) {
125 return;
126 }
127
128 $response = Jetpack_Protect_Module::protect_call( 'check_key' );
129 $this->set_transient( 'jpp_headers_updated_recently', 1, DAY_IN_SECONDS );
130
131 if ( isset( $response['msg'] ) && $response['msg'] ) {
132 update_site_option( 'trusted_ip_header', json_decode( $response['msg'] ) );
133 }
134
135 }
136
137 public function maybe_display_security_warning() {
138 if ( is_multisite() && current_user_can( 'manage_network' ) ) {
139 if ( ! function_exists( 'is_plugin_active_for_network' ) ) {
140 require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
141 }
142
143 if ( ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_FILE ) ) ) {
144 add_action( 'load-index.php', array( $this, 'prepare_jetpack_protect_multisite_notice' ) );
145 add_action( 'wp_ajax_jetpack-protect-dismiss-multisite-banner', array( $this, 'ajax_dismiss_handler' ) );
146 }
147 }
148 }
149
150 public function prepare_jetpack_protect_multisite_notice() {
151 $dismissed = get_site_option( 'jetpack_dismissed_protect_multisite_banner' );
152 if ( $dismissed ) {
153 return;
154 }
155
156 add_action( 'admin_notices', array ( $this, 'admin_jetpack_manage_notice' ) );
157 }
158
159 public function ajax_dismiss_handler() {
160 check_ajax_referer( 'jetpack_protect_multisite_banner_opt_out' );
161
162 if ( ! current_user_can( 'manage_network' ) ) {
163 wp_send_json_error( new WP_Error( 'insufficient_permissions' ) );
164 }
165
166 update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
167
168 wp_send_json_success();
169 }
170
171 /**
172 * Displays a warning about Jetpack Protect's network activation requirement.
173 * Attaches some custom JS to Core's `is-dismissible` UI to save the dismissed state.
174 */
175 public function admin_jetpack_manage_notice() {
176 ?>
177 <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' ) ); ?>">
178 <h2><?php esc_html_e( 'Jetpack Brute Force Attack Prevention cannot keep your site secure', 'jetpack' ); ?></h2>
179
180 <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>
181
182 <p>
183 <a class="button-primary" href="<?php echo esc_url( network_admin_url( 'plugins.php' ) ); ?>">
184 <?php esc_html_e( 'View Network Admin', 'jetpack' ); ?>
185 </a>
186 <a class="button" href="<?php echo esc_url( __( 'https://jetpack.com/support/multisite-protect', 'jetpack' ) ); ?>" target="_blank">
187 <?php esc_html_e( 'Learn More' ); ?>
188 </a>
189 </p>
190 </div>
191 <script>
192 jQuery( function( $ ) {
193 $( '.jetpack-protect-warning' ).on( 'click', 'button.notice-dismiss', function( event ) {
194 event.preventDefault();
195
196 wp.ajax.post(
197 'jetpack-protect-dismiss-multisite-banner',
198 {
199 _wpnonce: $( event.delegateTarget ).data( 'dismiss-nonce' ),
200 }
201 ).fail( function( error ) { <?php
202 // A failure here is really strange, and there's not really anything a site owner can do to fix one.
203 // Just log the error for now to help debugging. ?>
204
205 if ( 'function' === typeof error.done && '-1' === error.responseText ) {
206 console.error( 'Notice dismissal failed: check_ajax_referer' );
207 } else {
208 console.error( 'Notice dismissal failed: ' + JSON.stringify( error ) );
209 }
210 } )
211 } );
212 } );
213 </script>
214 <?php
215 }
216
217 /**
218 * Request an api key from wordpress.com
219 *
220 * @return bool | string
221 */
222 public function get_protect_key() {
223
224 $protect_blog_id = Jetpack_Protect_Module::get_main_blog_jetpack_id();
225
226 // If we can't find the the blog id, that means we are on multisite, and the main site never connected
227 // the protect api key is linked to the main blog id - instruct the user to connect their main blog
228 if ( ! $protect_blog_id ) {
229 $this->api_key_error = __( 'Your main blog is not connected to WordPress.com. Please connect to get an API key.', 'jetpack' );
230
231 return false;
232 }
233
234 $request = array (
235 'jetpack_blog_id' => $protect_blog_id,
236 'bruteprotect_api_key' => get_site_option( 'bruteprotect_api_key' ),
237 'multisite' => '0',
238 );
239
240 // Send the number of blogs on the network if we are on multisite
241 if ( is_multisite() ) {
242 $request['multisite'] = get_blog_count();
243 if ( ! $request['multisite'] ) {
244 global $wpdb;
245 $request['multisite'] = $wpdb->get_var( "SELECT COUNT(blog_id) as c FROM $wpdb->blogs WHERE spam = '0' AND deleted = '0' and archived = '0'" );
246 }
247 }
248
249 // Request the key
250 $xml = new Jetpack_IXR_Client();
251 $xml->query( 'jetpack.protect.requestKey', $request );
252
253 // Hmm, can't talk to wordpress.com
254 if ( $xml->isError() ) {
255 $code = $xml->getErrorCode();
256 $message = $xml->getErrorMessage();
257 $this->api_key_error = sprintf( __( 'Error connecting to WordPress.com. Code: %1$s, %2$s', 'jetpack' ), $code, $message );
258
259 return false;
260 }
261
262 $response = $xml->getResponse();
263
264 // Hmm. Can't talk to the protect servers ( api.bruteprotect.com )
265 if ( ! isset( $response['data'] ) ) {
266 $this->api_key_error = __( 'No reply from Jetpack servers', 'jetpack' );
267
268 return false;
269 }
270
271 // There was an issue generating the key
272 if ( empty( $response['success'] ) ) {
273 $this->api_key_error = $response['data'];
274
275 return false;
276 }
277
278 // Key generation successful!
279 $active_plugins = Jetpack::get_active_plugins();
280
281 // We only want to deactivate BruteProtect if we successfully get a key
282 if ( in_array( 'bruteprotect/bruteprotect.php', $active_plugins ) ) {
283 Jetpack_Client_Server::deactivate_plugin( 'bruteprotect/bruteprotect.php', 'BruteProtect' );
284 }
285
286 $key = $response['data'];
287 update_site_option( 'jetpack_protect_key', $key );
288
289 return $key;
290 }
291
292 /**
293 * Called via WP action wp_login_failed to log failed attempt with the api
294 *
295 * Fires custom, plugable action jpp_log_failed_attempt with the IP
296 *
297 * @return void
298 */
299 function log_failed_attempt( $login_user = null ) {
300
301 /**
302 * Fires before every failed login attempt.
303 *
304 * @module protect
305 *
306 * @since 3.4.0
307 *
308 * @param array Information about failed login attempt
309 * [
310 * 'login' => (string) Username or email used in failed login attempt
311 * ]
312 */
313 do_action( 'jpp_log_failed_attempt', array( 'login' => $login_user ) );
314
315 if ( isset( $_COOKIE['jpp_math_pass'] ) ) {
316
317 $transient = $this->get_transient( 'jpp_math_pass_' . $_COOKIE['jpp_math_pass'] );
318 $transient--;
319
320 if ( ! $transient || $transient < 1 ) {
321 $this->delete_transient( 'jpp_math_pass_' . $_COOKIE['jpp_math_pass'] );
322 setcookie( 'jpp_math_pass', 0, time() - DAY_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, false );
323 } else {
324 $this->set_transient( 'jpp_math_pass_' . $_COOKIE['jpp_math_pass'], $transient, DAY_IN_SECONDS );
325 }
326
327 }
328 $this->protect_call( 'failed_attempt' );
329 }
330
331 /**
332 * Set up the Protect configuration page
333 */
334 public function modules_loaded() {
335 Jetpack::enable_module_configurable( __FILE__ );
336 }
337
338 /**
339 * Logs a successful login back to our servers, this allows us to make sure we're not blocking
340 * a busy IP that has a lot of good logins along with some forgotten passwords. Also saves current user's ip
341 * to the ip address whitelist
342 */
343 public function log_successful_login( $user_login, $user = null ) {
344 if ( ! $user ) { // For do_action( 'wp_login' ) calls that lacked passing the 2nd arg.
345 $user = get_user_by( 'login', $user_login );
346 }
347
348 $this->protect_call( 'successful_login', array ( 'roles' => $user->roles ) );
349 }
350
351
352 /**
353 * Checks for loginability BEFORE authentication so that bots don't get to go around the log in form.
354 *
355 * If we are using our math fallback, authenticate via math-fallback.php
356 *
357 * @param string $user
358 * @param string $username
359 * @param string $password
360 *
361 * @return string $user
362 */
363 function check_preauth( $user = 'Not Used By Protect', $username = 'Not Used By Protect', $password = 'Not Used By Protect' ) {
364 $allow_login = $this->check_login_ability( true );
365 $use_math = $this->get_transient( 'brute_use_math' );
366
367 if ( ! $allow_login ) {
368 $this->block_with_math();
369 }
370
371 if ( ( 1 == $use_math || 1 == $this->block_login_with_math ) && isset( $_POST['log'] ) ) {
372 include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
373 Jetpack_Protect_Math_Authenticate::math_authenticate();
374 }
375
376 return $user;
377 }
378
379 /**
380 * Get all IP headers so that we can process on our server...
381 *
382 * @return array
383 */
384 function get_headers() {
385 $output = array();
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 function get_local_host() {
861 if ( isset( $this->local_host ) ) {
862 return $this->local_host;
863 }
864
865 $uri = 'http://' . strtolower( $_SERVER['HTTP_HOST'] );
866
867 if ( is_multisite() ) {
868 $uri = network_home_url();
869 }
870
871 $uridata = wp_parse_url( $uri );
872
873 $domain = $uridata['host'];
874
875 // If we still don't have the site_url, get it
876 if ( ! $domain ) {
877 $uri = get_site_url( 1 );
878 $uridata = wp_parse_url( $uri );
879 $domain = $uridata['host'];
880 }
881
882 $this->local_host = $domain;
883
884 return $this->local_host;
885 }
886
887 }
888
889 $jetpack_protect = Jetpack_Protect_Module::instance();
890
891 global $pagenow;
892 if ( isset( $pagenow ) && 'wp-login.php' === $pagenow ) {
893 $jetpack_protect->check_login_ability();
894 }
895