PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 7.5.1
Jetpack – WP Security, Backup, Speed, & Growth v7.5.1
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
885 lines 25.6 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 * Auto Activate: Yes
10 * Module Tags: Recommended
11 * Feature: Security
12 * 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
13 */
14
15 use Automattic\Jetpack\Constants;
16
17 include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
18
19 class Jetpack_Protect_Module {
20
21 private static $__instance = null;
22 public $api_key;
23 public $api_key_error;
24 public $whitelist;
25 public $whitelist_error;
26 public $whitelist_saved;
27 private $user_ip;
28 private $local_host;
29 private $api_endpoint;
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( 'jetpack/jetpack.php' ) || is_plugin_active_for_network( 'jetpack-dev/jetpack.php' ) ) ) {
145 add_action( 'load-index.php', array ( $this, 'prepare_jetpack_protect_multisite_notice' ) );
146 }
147 }
148 }
149
150 public function prepare_jetpack_protect_multisite_notice() {
151 add_action( 'admin_print_styles', array ( $this, 'admin_banner_styles' ) );
152 add_action( 'admin_notices', array ( $this, 'admin_jetpack_manage_notice' ) );
153 }
154
155 public function admin_banner_styles() {
156 global $wp_styles;
157
158 $min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
159
160 wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
161 $wp_styles->add_data( 'jetpack', 'rtl', true );
162 }
163
164 public function admin_jetpack_manage_notice() {
165
166 $dismissed = get_site_option( 'jetpack_dismissed_protect_multisite_banner' );
167
168 if ( $dismissed ) {
169 return;
170 }
171
172 $referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
173 $opt_out_url = wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-protect-multisite-opt-out' . $referer ), 'jetpack_protect_multisite_banner_opt_out' );
174
175 ?>
176 <div id="message" class="updated jetpack-message jp-banner is-opt-in protect-error"
177 style="display:block !important;">
178 <a class="jp-banner__dismiss" href="<?php echo esc_url( $opt_out_url ); ?>"
179 title="<?php esc_attr_e( 'Dismiss this notice.', 'jetpack' ); ?>"></a>
180
181 <div class="jp-banner__content">
182 <h2><?php esc_html_e( 'Protect cannot keep your site secure.', 'jetpack' ); ?></h2>
183
184 <p><?php printf( __( 'Thanks for activating Protect! To start protecting your site, please network activate Jetpack on your Multisite installation and activate Protect on your primary site. Due to the way logins are handled on WordPress Multisite, Jetpack must be network-enabled in order for Protect to work properly. <a href="%s" target="_blank">Learn More</a>', 'jetpack' ), 'http://jetpack.com/support/multisite-protect' ); ?></p>
185 </div>
186 <div class="jp-banner__action-container is-opt-in">
187 <a href="<?php echo esc_url( network_admin_url( 'plugins.php' ) ); ?>" class="jp-banner__button"
188 id="wpcom-connect"><?php _e( 'View Network Admin', 'jetpack' ); ?></a>
189 </div>
190 </div>
191 <?php
192 }
193
194 /**
195 * Request an api key from wordpress.com
196 *
197 * @return bool | string
198 */
199 public function get_protect_key() {
200
201 $protect_blog_id = Jetpack_Protect_Module::get_main_blog_jetpack_id();
202
203 // If we can't find the the blog id, that means we are on multisite, and the main site never connected
204 // the protect api key is linked to the main blog id - instruct the user to connect their main blog
205 if ( ! $protect_blog_id ) {
206 $this->api_key_error = __( 'Your main blog is not connected to WordPress.com. Please connect to get an API key.', 'jetpack' );
207
208 return false;
209 }
210
211 $request = array (
212 'jetpack_blog_id' => $protect_blog_id,
213 'bruteprotect_api_key' => get_site_option( 'bruteprotect_api_key' ),
214 'multisite' => '0',
215 );
216
217 // Send the number of blogs on the network if we are on multisite
218 if ( is_multisite() ) {
219 $request['multisite'] = get_blog_count();
220 if ( ! $request['multisite'] ) {
221 global $wpdb;
222 $request['multisite'] = $wpdb->get_var( "SELECT COUNT(blog_id) as c FROM $wpdb->blogs WHERE spam = '0' AND deleted = '0' and archived = '0'" );
223 }
224 }
225
226 // Request the key
227 Jetpack::load_xml_rpc_client();
228 $xml = new Jetpack_IXR_Client( array (
229 'user_id' => get_current_user_id()
230 ) );
231 $xml->query( 'jetpack.protect.requestKey', $request );
232
233 // Hmm, can't talk to wordpress.com
234 if ( $xml->isError() ) {
235 $code = $xml->getErrorCode();
236 $message = $xml->getErrorMessage();
237 $this->api_key_error = sprintf( __( 'Error connecting to WordPress.com. Code: %1$s, %2$s', 'jetpack' ), $code, $message );
238
239 return false;
240 }
241
242 $response = $xml->getResponse();
243
244 // Hmm. Can't talk to the protect servers ( api.bruteprotect.com )
245 if ( ! isset( $response['data'] ) ) {
246 $this->api_key_error = __( 'No reply from Jetpack servers', 'jetpack' );
247
248 return false;
249 }
250
251 // There was an issue generating the key
252 if ( empty( $response['success'] ) ) {
253 $this->api_key_error = $response['data'];
254
255 return false;
256 }
257
258 // Key generation successful!
259 $active_plugins = Jetpack::get_active_plugins();
260
261 // We only want to deactivate BruteProtect if we successfully get a key
262 if ( in_array( 'bruteprotect/bruteprotect.php', $active_plugins ) ) {
263 Jetpack_Client_Server::deactivate_plugin( 'bruteprotect/bruteprotect.php', 'BruteProtect' );
264 }
265
266 $key = $response['data'];
267 update_site_option( 'jetpack_protect_key', $key );
268
269 return $key;
270 }
271
272 /**
273 * Called via WP action wp_login_failed to log failed attempt with the api
274 *
275 * Fires custom, plugable action jpp_log_failed_attempt with the IP
276 *
277 * @return void
278 */
279 function log_failed_attempt( $login_user = null ) {
280
281 /**
282 * Fires before every failed login attempt.
283 *
284 * @module protect
285 *
286 * @since 3.4.0
287 *
288 * @param array Information about failed login attempt
289 * [
290 * 'login' => (string) Username or email used in failed login attempt
291 * ]
292 */
293 do_action( 'jpp_log_failed_attempt', array( 'login' => $login_user ) );
294
295 if ( isset( $_COOKIE['jpp_math_pass'] ) ) {
296
297 $transient = $this->get_transient( 'jpp_math_pass_' . $_COOKIE['jpp_math_pass'] );
298 $transient--;
299
300 if ( ! $transient || $transient < 1 ) {
301 $this->delete_transient( 'jpp_math_pass_' . $_COOKIE['jpp_math_pass'] );
302 setcookie( 'jpp_math_pass', 0, time() - DAY_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, false );
303 } else {
304 $this->set_transient( 'jpp_math_pass_' . $_COOKIE['jpp_math_pass'], $transient, DAY_IN_SECONDS );
305 }
306
307 }
308 $this->protect_call( 'failed_attempt' );
309 }
310
311 /**
312 * Set up the Protect configuration page
313 */
314 public function modules_loaded() {
315 Jetpack::enable_module_configurable( __FILE__ );
316 }
317
318 /**
319 * Logs a successful login back to our servers, this allows us to make sure we're not blocking
320 * a busy IP that has a lot of good logins along with some forgotten passwords. Also saves current user's ip
321 * to the ip address whitelist
322 */
323 public function log_successful_login( $user_login, $user = null ) {
324 if ( ! $user ) { // For do_action( 'wp_login' ) calls that lacked passing the 2nd arg.
325 $user = get_user_by( 'login', $user_login );
326 }
327
328 $this->protect_call( 'successful_login', array ( 'roles' => $user->roles ) );
329 }
330
331
332 /**
333 * Checks for loginability BEFORE authentication so that bots don't get to go around the log in form.
334 *
335 * If we are using our math fallback, authenticate via math-fallback.php
336 *
337 * @param string $user
338 * @param string $username
339 * @param string $password
340 *
341 * @return string $user
342 */
343 function check_preauth( $user = 'Not Used By Protect', $username = 'Not Used By Protect', $password = 'Not Used By Protect' ) {
344 $allow_login = $this->check_login_ability( true );
345 $use_math = $this->get_transient( 'brute_use_math' );
346
347 if ( ! $allow_login ) {
348 $this->block_with_math();
349 }
350
351 if ( ( 1 == $use_math || 1 == $this->block_login_with_math ) && isset( $_POST['log'] ) ) {
352 include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
353 Jetpack_Protect_Math_Authenticate::math_authenticate();
354 }
355
356 return $user;
357 }
358
359 /**
360 * Get all IP headers so that we can process on our server...
361 *
362 * @return string
363 */
364 function get_headers() {
365 $ip_related_headers = array (
366 'GD_PHP_HANDLER',
367 'HTTP_AKAMAI_ORIGIN_HOP',
368 'HTTP_CF_CONNECTING_IP',
369 'HTTP_CLIENT_IP',
370 'HTTP_FASTLY_CLIENT_IP',
371 'HTTP_FORWARDED',
372 'HTTP_FORWARDED_FOR',
373 'HTTP_INCAP_CLIENT_IP',
374 'HTTP_TRUE_CLIENT_IP',
375 'HTTP_X_CLIENTIP',
376 'HTTP_X_CLUSTER_CLIENT_IP',
377 'HTTP_X_FORWARDED',
378 'HTTP_X_FORWARDED_FOR',
379 'HTTP_X_IP_TRAIL',
380 'HTTP_X_REAL_IP',
381 'HTTP_X_VARNISH',
382 'REMOTE_ADDR'
383 );
384
385 foreach ( $ip_related_headers as $header ) {
386 if ( isset( $_SERVER[ $header ] ) ) {
387 $output[ $header ] = $_SERVER[ $header ];
388 }
389 }
390
391 return $output;
392 }
393
394 /*
395 * Checks if the IP address has been whitelisted
396 *
397 * @param string $ip
398 *
399 * @return bool
400 */
401 function ip_is_whitelisted( $ip ) {
402 // If we found an exact match in wp-config
403 if ( defined( 'JETPACK_IP_ADDRESS_OK' ) && JETPACK_IP_ADDRESS_OK == $ip ) {
404 return true;
405 }
406
407 $whitelist = jetpack_protect_get_local_whitelist();
408
409 if ( is_multisite() ) {
410 $whitelist = array_merge( $whitelist, get_site_option( 'jetpack_protect_global_whitelist', array () ) );
411 }
412
413 if ( ! empty( $whitelist ) ) :
414 foreach ( $whitelist as $item ) :
415 // If the IPs are an exact match
416 if ( ! $item->range && isset( $item->ip_address ) && $item->ip_address == $ip ) {
417 return true;
418 }
419
420 if ( $item->range && isset( $item->range_low ) && isset( $item->range_high ) ) {
421 if ( jetpack_protect_ip_address_is_in_range( $ip, $item->range_low, $item->range_high ) ) {
422 return true;
423 }
424 }
425 endforeach;
426 endif;
427
428 return false;
429 }
430
431 /**
432 * Checks the status for a given IP. API results are cached as transients
433 *
434 * @param bool $preauth Whether or not we are checking prior to authorization
435 *
436 * @return bool Either returns true, fires $this->kill_login, or includes a math fallback and returns false
437 */
438 function check_login_ability( $preauth = false ) {
439
440 /**
441 * JETPACK_ALWAYS_PROTECT_LOGIN will always disable the login page, and use a page provided by Jetpack.
442 */
443 if ( Constants::is_true( 'JETPACK_ALWAYS_PROTECT_LOGIN' ) ) {
444 $this->kill_login();
445 }
446
447 if ( $this->is_current_ip_whitelisted() ) {
448 return true;
449 }
450
451 $status = $this->get_cached_status();
452
453 if ( empty( $status ) ) {
454 // If we've reached this point, this means that the IP isn't cached.
455 // Now we check with the Protect API to see if we should allow login
456 $response = $this->protect_call( $action = 'check_ip' );
457
458 if ( isset( $response['math'] ) && ! function_exists( 'brute_math_authenticate' ) ) {
459 include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
460 new Jetpack_Protect_Math_Authenticate;
461
462 return false;
463 }
464
465 $status = $response['status'];
466 }
467
468 if ( 'blocked' == $status ) {
469 $this->block_with_math();
470 }
471
472 if ( 'blocked-hard' == $status ) {
473 $this->kill_login();
474 }
475
476 return true;
477 }
478
479 function is_current_ip_whitelisted() {
480 $ip = jetpack_protect_get_ip();
481
482 // Server is misconfigured and we can't get an IP
483 if ( ! $ip && class_exists( 'Jetpack' ) ) {
484 Jetpack::deactivate_module( 'protect' );
485 ob_start();
486 Jetpack::state( 'message', 'protect_misconfigured_ip' );
487 ob_end_clean();
488 return true;
489 }
490
491 /**
492 * Short-circuit check_login_ability.
493 *
494 * If there is an alternate way to validate the current IP such as
495 * a hard-coded list of IP addresses, we can short-circuit the rest
496 * of the login ability checks and return true here.
497 *
498 * @module protect
499 *
500 * @since 4.4.0
501 *
502 * @param bool false Should we allow all logins for the current ip? Default: false
503 */
504 if ( apply_filters( 'jpp_allow_login', false, $ip ) ) {
505 return true;
506 }
507
508 if ( jetpack_protect_ip_is_private( $ip ) ) {
509 return true;
510 }
511
512 if ( $this->ip_is_whitelisted( $ip ) ) {
513 return true;
514 }
515 }
516
517 function has_login_ability() {
518 if ( $this->is_current_ip_whitelisted() ) {
519 return true;
520 }
521 $status = $this->get_cached_status();
522 if ( empty( $status ) || $status === 'ok' ) {
523 return true;
524 }
525 return false;
526 }
527
528 function get_cached_status() {
529 $transient_name = $this->get_transient_name();
530 $value = $this->get_transient( $transient_name );
531 if ( isset( $value['status'] ) ) {
532 return $value['status'];
533 }
534 return '';
535 }
536
537 function block_with_math() {
538 /**
539 * By default, Protect will allow a user who has been blocked for too
540 * many failed logins to start answering math questions to continue logging in
541 *
542 * For added security, you can disable this.
543 *
544 * @module protect
545 *
546 * @since 3.6.0
547 *
548 * @param bool Whether to allow math for blocked users or not.
549 */
550
551 $this->block_login_with_math = 1;
552 /**
553 * Allow Math fallback for blocked IPs.
554 *
555 * @module protect
556 *
557 * @since 3.6.0
558 *
559 * @param bool true Should we fallback to the Math questions when an IP is blocked. Default to true.
560 */
561 $allow_math_fallback_on_fail = apply_filters( 'jpp_use_captcha_when_blocked', true );
562 if ( ! $allow_math_fallback_on_fail ) {
563 $this->kill_login();
564 }
565 include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
566 new Jetpack_Protect_Math_Authenticate;
567
568 return false;
569 }
570
571 /*
572 * Kill a login attempt
573 */
574 function kill_login() {
575 if (
576 isset( $_GET['action'], $_GET['_wpnonce'] ) &&
577 'logout' === $_GET['action'] &&
578 wp_verify_nonce( $_GET['_wpnonce'], 'log-out' ) &&
579 wp_get_current_user()
580
581 ) {
582 // Allow users to logout
583 return;
584 }
585
586 $ip = jetpack_protect_get_ip();
587 /**
588 * Fires before every killed login.
589 *
590 * @module protect
591 *
592 * @since 3.4.0
593 *
594 * @param string $ip IP flagged by Protect.
595 */
596 do_action( 'jpp_kill_login', $ip );
597
598 if( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
599 $die_string = sprintf( __( 'Your IP (%1$s) has been flagged for potential security violations.', 'jetpack' ), str_replace( 'http://', '', esc_url( 'http://' . $ip ) ) );
600 wp_die(
601 $die_string,
602 __( 'Login Blocked by Jetpack', 'jetpack' ),
603 array ( 'response' => 403 )
604 );
605 }
606
607 require_once dirname( __FILE__ ) . '/protect/blocked-login-page.php';
608 $blocked_login_page = Jetpack_Protect_Blocked_Login_Page::instance( $ip );
609
610 if ( $blocked_login_page->is_blocked_user_valid() ) {
611 return;
612 }
613
614 $blocked_login_page->render_and_die();
615 }
616
617 /*
618 * Checks if the protect API call has failed, and if so initiates the math captcha fallback.
619 */
620 public function check_use_math() {
621 $use_math = $this->get_transient( 'brute_use_math' );
622 if ( $use_math ) {
623 include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
624 new Jetpack_Protect_Math_Authenticate;
625 }
626 }
627
628 /**
629 * If we're in a multisite network, return the blog ID of the primary blog
630 *
631 * @return int
632 */
633 public function get_main_blog_id() {
634 if ( ! is_multisite() ) {
635 return false;
636 }
637
638 global $current_site;
639 $primary_blog_id = $current_site->blog_id;
640
641 return $primary_blog_id;
642 }
643
644 /**
645 * Get jetpack blog id, or the jetpack blog id of the main blog in the main network
646 *
647 * @return int
648 */
649 public function get_main_blog_jetpack_id() {
650 if ( ! is_main_site() ) {
651 switch_to_blog( $this->get_main_blog_id() );
652 $id = Jetpack::get_option( 'id', false );
653 restore_current_blog();
654 } else {
655 $id = Jetpack::get_option( 'id' );
656 }
657
658 return $id;
659 }
660
661 public function check_api_key() {
662 $response = $this->protect_call( 'check_key' );
663
664 if ( isset( $response['ckval'] ) ) {
665 return true;
666 }
667
668 if ( isset( $response['error'] ) ) {
669
670 if ( $response['error'] == 'Invalid API Key' ) {
671 $this->api_key_error = __( 'Your API key is invalid', 'jetpack' );
672 }
673
674 if ( $response['error'] == 'API Key Required' ) {
675 $this->api_key_error = __( 'No API key', 'jetpack' );
676 }
677 }
678
679 $this->api_key_error = __( 'There was an error contacting Jetpack servers.', 'jetpack' );
680
681 return false;
682 }
683
684 /**
685 * Calls over to the api using wp_remote_post
686 *
687 * @param string $action 'check_ip', 'check_key', or 'failed_attempt'
688 * @param array $request Any custom data to post to the api
689 *
690 * @return array
691 */
692 function protect_call( $action = 'check_ip', $request = array () ) {
693 global $wp_version;
694
695 $api_key = $this->maybe_get_protect_key();
696
697 $user_agent = "WordPress/{$wp_version} | Jetpack/" . constant( 'JETPACK__VERSION' );
698
699 $request['action'] = $action;
700 $request['ip'] = jetpack_protect_get_ip();
701 $request['host'] = $this->get_local_host();
702 $request['headers'] = json_encode( $this->get_headers() );
703 $request['jetpack_version'] = constant( 'JETPACK__VERSION' );
704 $request['wordpress_version'] = strval( $wp_version );
705 $request['api_key'] = $api_key;
706 $request['multisite'] = "0";
707
708 if ( is_multisite() ) {
709 $request['multisite'] = get_blog_count();
710 }
711
712
713 /**
714 * Filter controls maximum timeout in waiting for reponse from Protect servers.
715 *
716 * @module protect
717 *
718 * @since 4.0.4
719 *
720 * @param int $timeout Max time (in seconds) to wait for a response.
721 */
722 $timeout = apply_filters( 'jetpack_protect_connect_timeout', 30 );
723
724 $args = array (
725 'body' => $request,
726 'user-agent' => $user_agent,
727 'httpversion' => '1.0',
728 'timeout' => absint( $timeout )
729 );
730
731 $response_json = wp_remote_post( $this->get_api_host(), $args );
732 $this->last_response_raw = $response_json;
733
734 $transient_name = $this->get_transient_name();
735 $this->delete_transient( $transient_name );
736
737 if ( is_array( $response_json ) ) {
738 $response = json_decode( $response_json['body'], true );
739 }
740
741 if ( isset( $response['blocked_attempts'] ) && $response['blocked_attempts'] ) {
742 update_site_option( 'jetpack_protect_blocked_attempts', $response['blocked_attempts'] );
743 }
744
745 if ( isset( $response['status'] ) && ! isset( $response['error'] ) ) {
746 $response['expire'] = time() + $response['seconds_remaining'];
747 $this->set_transient( $transient_name, $response, $response['seconds_remaining'] );
748 $this->delete_transient( 'brute_use_math' );
749 } else { // Fallback to Math Captcha if no response from API host
750 $this->set_transient( 'brute_use_math', 1, 600 );
751 $response['status'] = 'ok';
752 $response['math'] = true;
753 }
754
755 if ( isset( $response['error'] ) ) {
756 update_site_option( 'jetpack_protect_error', $response['error'] );
757 } else {
758 delete_site_option( 'jetpack_protect_error' );
759 }
760
761 return $response;
762 }
763
764 function get_transient_name() {
765 $headers = $this->get_headers();
766 $header_hash = md5( json_encode( $headers ) );
767
768 return 'jpp_li_' . $header_hash;
769 }
770
771 /**
772 * Wrapper for WordPress set_transient function, our version sets
773 * the transient on the main site in the network if this is a multisite network
774 *
775 * We do it this way (instead of set_site_transient) because of an issue where
776 * sitewide transients are always autoloaded
777 * https://core.trac.wordpress.org/ticket/22846
778 *
779 * @param string $transient Transient name. Expected to not be SQL-escaped. Must be
780 * 45 characters or fewer in length.
781 * @param mixed $value Transient value. Must be serializable if non-scalar.
782 * Expected to not be SQL-escaped.
783 * @param int $expiration Optional. Time until expiration in seconds. Default 0.
784 *
785 * @return bool False if value was not set and true if value was set.
786 */
787 function set_transient( $transient, $value, $expiration ) {
788 if ( is_multisite() && ! is_main_site() ) {
789 switch_to_blog( $this->get_main_blog_id() );
790 $return = set_transient( $transient, $value, $expiration );
791 restore_current_blog();
792
793 return $return;
794 }
795
796 return set_transient( $transient, $value, $expiration );
797 }
798
799 /**
800 * Wrapper for WordPress delete_transient function, our version deletes
801 * the transient on the main site in the network if this is a multisite network
802 *
803 * @param string $transient Transient name. Expected to not be SQL-escaped.
804 *
805 * @return bool true if successful, false otherwise
806 */
807 function delete_transient( $transient ) {
808 if ( is_multisite() && ! is_main_site() ) {
809 switch_to_blog( $this->get_main_blog_id() );
810 $return = delete_transient( $transient );
811 restore_current_blog();
812
813 return $return;
814 }
815
816 return delete_transient( $transient );
817 }
818
819 /**
820 * Wrapper for WordPress get_transient function, our version gets
821 * the transient on the main site in the network if this is a multisite network
822 *
823 * @param string $transient Transient name. Expected to not be SQL-escaped.
824 *
825 * @return mixed Value of transient.
826 */
827 function get_transient( $transient ) {
828 if ( is_multisite() && ! is_main_site() ) {
829 switch_to_blog( $this->get_main_blog_id() );
830 $return = get_transient( $transient );
831 restore_current_blog();
832
833 return $return;
834 }
835
836 return get_transient( $transient );
837 }
838
839 function get_api_host() {
840 if ( isset( $this->api_endpoint ) ) {
841 return $this->api_endpoint;
842 }
843
844 //Check to see if we can use SSL
845 $this->api_endpoint = Jetpack::fix_url_for_bad_hosts( JETPACK_PROTECT__API_HOST );
846
847 return $this->api_endpoint;
848 }
849
850 function get_local_host() {
851 if ( isset( $this->local_host ) ) {
852 return $this->local_host;
853 }
854
855 $uri = 'http://' . strtolower( $_SERVER['HTTP_HOST'] );
856
857 if ( is_multisite() ) {
858 $uri = network_home_url();
859 }
860
861 $uridata = parse_url( $uri );
862
863 $domain = $uridata['host'];
864
865 // If we still don't have the site_url, get it
866 if ( ! $domain ) {
867 $uri = get_site_url( 1 );
868 $uridata = parse_url( $uri );
869 $domain = $uridata['host'];
870 }
871
872 $this->local_host = $domain;
873
874 return $this->local_host;
875 }
876
877 }
878
879 $jetpack_protect = Jetpack_Protect_Module::instance();
880
881 global $pagenow;
882 if ( isset( $pagenow ) && 'wp-login.php' == $pagenow ) {
883 $jetpack_protect->check_login_ability();
884 }
885