Completed
Push — update/editor-blocks-icon-colo... ( 093ab2...3cfb5e )
by
unknown
08:47
created

Jetpack_Protect_Module   F

Complexity

Total Complexity 133

Size/Duplication

Total Lines 880
Duplicated Lines 2.5 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
dl 22
loc 880
rs 1.72
c 0
b 0
f 0
wmc 133
lcom 1
cbo 8

34 Methods

Rating   Name   Duplication   Size   Complexity  
A instance() 0 7 2
A __construct() 0 24 2
A on_activation() 0 10 4
A on_deactivation() 0 5 3
A maybe_get_protect_key() 0 9 3
B maybe_update_headers() 0 23 8
A maybe_display_security_warning() 0 12 5
A prepare_jetpack_protect_multisite_notice() 0 8 2
A ajax_dismiss_handler() 0 11 2
A admin_jetpack_manage_notice() 0 41 1
B get_protect_key() 0 69 8
A log_failed_attempt() 0 31 4
A modules_loaded() 0 3 1
A log_successful_login() 0 7 2
A check_preauth() 0 15 5
A get_headers() 0 29 3
C ip_is_whitelisted() 0 29 13
B check_login_ability() 0 40 8
B is_current_ip_whitelisted() 0 37 6
A has_login_ability() 0 10 4
A get_cached_status() 0 8 2
A block_with_math() 0 33 2
B kill_login() 0 42 8
A check_use_math() 0 7 2
A get_main_blog_id() 0 10 2
A get_main_blog_jetpack_id() 0 11 2
A check_api_key() 0 22 5
B protect_call() 0 71 8
A get_transient_name() 0 6 1
A set_transient() 0 11 3
A delete_transient() 11 11 3
A get_transient() 11 11 3
A get_api_host() 0 10 2
A get_local_host() 0 26 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Jetpack_Protect_Module often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack_Protect_Module, and based on these observations, apply Extract Interface, too.

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
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
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 $user_ip;
29
	private $local_host;
30
	private $api_endpoint;
31
	public $last_request;
32
	public $last_response_raw;
33
	public $last_response;
34
	private $block_login_with_math;
35
36
	/**
37
	 * Singleton implementation
38
	 *
39
	 * @return object
40
	 */
41
	public static function instance() {
42
		if ( ! is_a( self::$__instance, 'Jetpack_Protect_Module' ) ) {
43
			self::$__instance = new Jetpack_Protect_Module();
44
		}
45
46
		return self::$__instance;
47
	}
48
49
	/**
50
	 * Registers actions
51
	 */
52
	private function __construct() {
53
		add_action( 'jetpack_activate_module_protect', array ( $this, 'on_activation' ) );
54
		add_action( 'jetpack_deactivate_module_protect', array ( $this, 'on_deactivation' ) );
55
		add_action( 'jetpack_modules_loaded', array ( $this, 'modules_loaded' ) );
56
		add_action( 'login_form', array ( $this, 'check_use_math' ), 0 );
57
		add_filter( 'authenticate', array ( $this, 'check_preauth' ), 10, 3 );
58
		add_action( 'wp_login', array ( $this, 'log_successful_login' ), 10, 2 );
59
		add_action( 'wp_login_failed', array ( $this, 'log_failed_attempt' ) );
60
		add_action( 'admin_init', array ( $this, 'maybe_update_headers' ) );
61
		add_action( 'admin_init', array ( $this, 'maybe_display_security_warning' ) );
62
63
		// This is a backup in case $pagenow fails for some reason
64
		add_action( 'login_form', array ( $this, 'check_login_ability' ), 1 );
65
66
		// Load math fallback after math page form submission
67
		if ( isset( $_POST[ 'jetpack_protect_process_math_form' ] ) ) {
68
			include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
69
			new Jetpack_Protect_Math_Authenticate;
70
		}
71
72
		// Runs a script every day to clean up expired transients so they don't
73
		// clog up our users' databases
74
		require_once( JETPACK__PLUGIN_DIR . '/modules/protect/transient-cleanup.php' );
75
	}
76
77
	/**
78
	 * On module activation, try to get an api key
79
	 */
80
	public function on_activation() {
81
		if ( is_multisite() && is_main_site() && get_site_option( 'jetpack_protect_active', 0 ) == 0 ) {
82
			update_site_option( 'jetpack_protect_active', 1 );
83
		}
84
85
		update_site_option( 'jetpack_protect_activating', 'activating' );
86
87
		// Get BruteProtect's counter number
88
		Jetpack_Protect_Module::protect_call( 'check_key' );
89
	}
90
91
	/**
92
	 * On module deactivation, unset protect_active
93
	 */
94
	public function on_deactivation() {
95
		if ( is_multisite() && is_main_site() ) {
96
			update_site_option( 'jetpack_protect_active', 0 );
97
		}
98
	}
99
100
	public function maybe_get_protect_key() {
101
		if ( get_site_option( 'jetpack_protect_activating', false ) && ! get_site_option( 'jetpack_protect_key', false ) ) {
102
			$key = $this->get_protect_key();
103
			delete_site_option( 'jetpack_protect_activating' );
104
			return $key;
105
		}
106
107
		return get_site_option( 'jetpack_protect_key' );
108
	}
109
110
	/**
111
	 * Sends a "check_key" API call once a day.  This call allows us to track IP-related
112
	 * headers for this server via the Protect API, in order to better identify the source
113
	 * IP for login attempts
114
	 */
115
	public function maybe_update_headers( $force = false ) {
116
		$updated_recently = $this->get_transient( 'jpp_headers_updated_recently' );
117
118
		if ( ! $force ) {
119
			if ( isset( $_GET['protect_update_headers'] ) ) {
120
				$force = true;
121
			}
122
		}
123
124
		// check that current user is admin so we prevent a lower level user from adding
125
		// a trusted header, allowing them to brute force an admin account
126
		if ( ( $updated_recently && ! $force ) || ! current_user_can( 'update_plugins' ) ) {
127
			return;
128
		}
129
130
		$response = Jetpack_Protect_Module::protect_call( 'check_key' );
131
		$this->set_transient( 'jpp_headers_updated_recently', 1, DAY_IN_SECONDS );
132
133
		if ( isset( $response['msg'] ) && $response['msg'] ) {
134
			update_site_option( 'trusted_ip_header', json_decode( $response['msg'] ) );
135
		}
136
137
	}
138
139
	public function maybe_display_security_warning() {
140
		if ( is_multisite() && current_user_can( 'manage_network' ) ) {
141
			if ( ! function_exists( 'is_plugin_active_for_network' ) ) {
142
				require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
143
			}
144
145
			if ( ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_FILE ) ) ) {
146
				add_action( 'load-index.php', array( $this, 'prepare_jetpack_protect_multisite_notice' ) );
147
				add_action( 'wp_ajax_jetpack-protect-dismiss-multisite-banner', array( $this, 'ajax_dismiss_handler' ) );
148
			}
149
		}
150
	}
151
152
	public function prepare_jetpack_protect_multisite_notice() {
153
		$dismissed = get_site_option( 'jetpack_dismissed_protect_multisite_banner' );
154
		if ( $dismissed ) {
155
			return;
156
		}
157
158
		add_action( 'admin_notices', array ( $this, 'admin_jetpack_manage_notice' ) );
159
	}
160
161
	public function ajax_dismiss_handler() {
162
		check_ajax_referer( 'jetpack_protect_multisite_banner_opt_out' );
163
164
		if ( ! current_user_can( 'manage_network' ) ) {
165
			wp_send_json_error( new WP_Error( 'insufficient_permissions' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'insufficient_permissions'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
166
		}
167
168
		update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
169
170
		wp_send_json_success();
171
	}
172
173
	/**
174
	 * Displays a warning about Jetpack Protect's network activation requirement.
175
	 * Attaches some custom JS to Core's `is-dismissible` UI to save the dismissed state.
176
	 */
177
	public function admin_jetpack_manage_notice() {
178
		?>
179
		<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' ) ); ?>">
180
			<h2><?php esc_html_e( 'Jetpack Brute Force Attack Prevention cannot keep your site secure', 'jetpack' ); ?></h2>
181
182
			<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>
183
184
			<p>
185
				<a class="button-primary" href="<?php echo esc_url( network_admin_url( 'plugins.php' ) ); ?>">
186
					<?php esc_html_e( 'View Network Admin', 'jetpack' ); ?>
187
				</a>
188
				<a class="button" href="<?php echo esc_url( __( 'https://jetpack.com/support/multisite-protect', 'jetpack' ) ); ?>" target="_blank">
189
					<?php esc_html_e( 'Learn More' ); ?>
190
				</a>
191
			</p>
192
		</div>
193
		<script>
194
			jQuery( function( $ ) {
195
				$( '.jetpack-protect-warning' ).on( 'click', 'button.notice-dismiss', function( event ) {
196
					event.preventDefault();
197
198
					wp.ajax.post(
199
						'jetpack-protect-dismiss-multisite-banner',
200
						{
201
							_wpnonce: $( event.delegateTarget ).data( 'dismiss-nonce' ),
202
						}
203
					).fail( function( error ) { <?php
204
						// A failure here is really strange, and there's not really anything a site owner can do to fix one.
205
						// Just log the error for now to help debugging. ?>
206
207
						if ( 'function' === typeof error.done && '-1' === error.responseText ) {
208
							console.error( 'Notice dismissal failed: check_ajax_referer' );
209
						} else {
210
							console.error( 'Notice dismissal failed: ' + JSON.stringify( error ) );
211
						}
212
					} )
213
				} );
214
			} );
215
		</script>
216
		<?php
217
	}
218
219
	/**
220
	 * Request an api key from wordpress.com
221
	 *
222
	 * @return bool | string
223
	 */
224
	public function get_protect_key() {
225
226
		$protect_blog_id = Jetpack_Protect_Module::get_main_blog_jetpack_id();
227
228
		// If we can't find the the blog id, that means we are on multisite, and the main site never connected
229
		// the protect api key is linked to the main blog id - instruct the user to connect their main blog
230
		if ( ! $protect_blog_id ) {
231
			$this->api_key_error = __( 'Your main blog is not connected to WordPress.com. Please connect to get an API key.', 'jetpack' );
232
233
			return false;
234
		}
235
236
		$request = array (
237
			'jetpack_blog_id'      => $protect_blog_id,
238
			'bruteprotect_api_key' => get_site_option( 'bruteprotect_api_key' ),
239
			'multisite'            => '0',
240
		);
241
242
		// Send the number of blogs on the network if we are on multisite
243
		if ( is_multisite() ) {
244
			$request['multisite'] = get_blog_count();
245
			if ( ! $request['multisite'] ) {
246
				global $wpdb;
247
				$request['multisite'] = $wpdb->get_var( "SELECT COUNT(blog_id) as c FROM $wpdb->blogs WHERE spam = '0' AND deleted = '0' and archived = '0'" );
248
			}
249
		}
250
251
		// Request the key
252
		$xml = new Jetpack_IXR_Client();
253
		$xml->query( 'jetpack.protect.requestKey', $request );
254
255
		// Hmm, can't talk to wordpress.com
256
		if ( $xml->isError() ) {
257
			$code                = $xml->getErrorCode();
258
			$message             = $xml->getErrorMessage();
259
			$this->api_key_error = sprintf( __( 'Error connecting to WordPress.com. Code: %1$s, %2$s', 'jetpack' ), $code, $message );
260
261
			return false;
262
		}
263
264
		$response = $xml->getResponse();
265
266
		// Hmm. Can't talk to the protect servers ( api.bruteprotect.com )
267
		if ( ! isset( $response['data'] ) ) {
268
			$this->api_key_error = __( 'No reply from Jetpack servers', 'jetpack' );
269
270
			return false;
271
		}
272
273
		// There was an issue generating the key
274
		if ( empty( $response['success'] ) ) {
275
			$this->api_key_error = $response['data'];
276
277
			return false;
278
		}
279
280
		// Key generation successful!
281
		$active_plugins = Jetpack::get_active_plugins();
282
283
		// We only want to deactivate BruteProtect if we successfully get a key
284
		if ( in_array( 'bruteprotect/bruteprotect.php', $active_plugins ) ) {
285
			Jetpack_Client_Server::deactivate_plugin( 'bruteprotect/bruteprotect.php', 'BruteProtect' );
286
		}
287
288
		$key = $response['data'];
289
		update_site_option( 'jetpack_protect_key', $key );
290
291
		return $key;
292
	}
293
294
	/**
295
	 * Called via WP action wp_login_failed to log failed attempt with the api
296
	 *
297
	 * Fires custom, plugable action jpp_log_failed_attempt with the IP
298
	 *
299
	 * @return void
300
	 */
301
	function log_failed_attempt( $login_user = null ) {
302
303
		/**
304
		 * Fires before every failed login attempt.
305
		 *
306
		 * @module protect
307
		 *
308
		 * @since 3.4.0
309
		 *
310
		 * @param array Information about failed login attempt
311
		 *   [
312
		 *     'login' => (string) Username or email used in failed login attempt
313
		 *   ]
314
		 */
315
		do_action( 'jpp_log_failed_attempt', array( 'login' => $login_user ) );
316
317
		if ( isset( $_COOKIE['jpp_math_pass'] ) ) {
318
319
			$transient = $this->get_transient( 'jpp_math_pass_' . $_COOKIE['jpp_math_pass'] );
320
			$transient--;
321
322
			if ( ! $transient || $transient < 1 ) {
323
				$this->delete_transient( 'jpp_math_pass_' . $_COOKIE['jpp_math_pass'] );
324
				setcookie( 'jpp_math_pass', 0, time() - DAY_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, false );
325
			} else {
326
				$this->set_transient( 'jpp_math_pass_' . $_COOKIE['jpp_math_pass'], $transient, DAY_IN_SECONDS );
327
			}
328
329
		}
330
		$this->protect_call( 'failed_attempt' );
331
	}
332
333
	/**
334
	 * Set up the Protect configuration page
335
	 */
336
	public function modules_loaded() {
337
		Jetpack::enable_module_configurable( __FILE__ );
338
	}
339
340
	/**
341
	 * Logs a successful login back to our servers, this allows us to make sure we're not blocking
342
	 * a busy IP that has a lot of good logins along with some forgotten passwords. Also saves current user's ip
343
	 * to the ip address whitelist
344
	 */
345
	public function log_successful_login( $user_login, $user = null ) {
346
		if ( ! $user ) { // For do_action( 'wp_login' ) calls that lacked passing the 2nd arg.
347
			$user = get_user_by( 'login', $user_login );
348
		}
349
350
		$this->protect_call( 'successful_login', array ( 'roles' => $user->roles ) );
351
	}
352
353
354
	/**
355
	 * Checks for loginability BEFORE authentication so that bots don't get to go around the log in form.
356
	 *
357
	 * If we are using our math fallback, authenticate via math-fallback.php
358
	 *
359
	 * @param string $user
360
	 * @param string $username
361
	 * @param string $password
362
	 *
363
	 * @return string $user
364
	 */
365
	function check_preauth( $user = 'Not Used By Protect', $username = 'Not Used By Protect', $password = 'Not Used By Protect' ) {
366
		$allow_login = $this->check_login_ability( true );
367
		$use_math    = $this->get_transient( 'brute_use_math' );
368
369
		if ( ! $allow_login ) {
370
			$this->block_with_math();
371
		}
372
373
		if ( ( 1 == $use_math || 1 == $this->block_login_with_math ) && isset( $_POST['log'] ) ) {
374
			include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
375
			Jetpack_Protect_Math_Authenticate::math_authenticate();
376
		}
377
378
		return $user;
379
	}
380
381
	/**
382
	 * Get all IP headers so that we can process on our server...
383
	 *
384
	 * @return string
385
	 */
386
	function get_headers() {
387
		$ip_related_headers = array (
388
			'GD_PHP_HANDLER',
389
			'HTTP_AKAMAI_ORIGIN_HOP',
390
			'HTTP_CF_CONNECTING_IP',
391
			'HTTP_CLIENT_IP',
392
			'HTTP_FASTLY_CLIENT_IP',
393
			'HTTP_FORWARDED',
394
			'HTTP_FORWARDED_FOR',
395
			'HTTP_INCAP_CLIENT_IP',
396
			'HTTP_TRUE_CLIENT_IP',
397
			'HTTP_X_CLIENTIP',
398
			'HTTP_X_CLUSTER_CLIENT_IP',
399
			'HTTP_X_FORWARDED',
400
			'HTTP_X_FORWARDED_FOR',
401
			'HTTP_X_IP_TRAIL',
402
			'HTTP_X_REAL_IP',
403
			'HTTP_X_VARNISH',
404
			'REMOTE_ADDR'
405
		);
406
407
		foreach ( $ip_related_headers as $header ) {
408
			if ( ! empty( $_SERVER[ $header ] ) ) {
409
				$output[ $header ] = $_SERVER[ $header ];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$output was never initialized. Although not strictly required by PHP, it is generally a good practice to add $output = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
410
			}
411
		}
412
413
		return $output;
0 ignored issues
show
Bug introduced by
The variable $output does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
414
	}
415
416
	/*
417
	 * Checks if the IP address has been whitelisted
418
	 *
419
	 * @param string $ip
420
	 *
421
	 * @return bool
422
	 */
423
	function ip_is_whitelisted( $ip ) {
424
		// If we found an exact match in wp-config
425
		if ( defined( 'JETPACK_IP_ADDRESS_OK' ) && JETPACK_IP_ADDRESS_OK == $ip ) {
426
			return true;
427
		}
428
429
		$whitelist = jetpack_protect_get_local_whitelist();
430
431
		if ( is_multisite() ) {
432
			$whitelist = array_merge( $whitelist, get_site_option( 'jetpack_protect_global_whitelist', array () ) );
433
		}
434
435
		if ( ! empty( $whitelist ) ) :
436
			foreach ( $whitelist as $item ) :
437
				// If the IPs are an exact match
438
				if ( ! $item->range && isset( $item->ip_address ) && $item->ip_address == $ip ) {
439
					return true;
440
				}
441
442
				if ( $item->range && isset( $item->range_low ) && isset( $item->range_high ) ) {
443
					if ( jetpack_protect_ip_address_is_in_range( $ip, $item->range_low, $item->range_high ) ) {
444
						return true;
445
					}
446
				}
447
			endforeach;
448
		endif;
449
450
		return false;
451
	}
452
453
	/**
454
	 * Checks the status for a given IP. API results are cached as transients
455
	 *
456
	 * @param bool $preauth Whether or not we are checking prior to authorization
457
	 *
458
	 * @return bool Either returns true, fires $this->kill_login, or includes a math fallback and returns false
459
	 */
460
	function check_login_ability( $preauth = false ) {
461
462
		/**
463
		 * JETPACK_ALWAYS_PROTECT_LOGIN will always disable the login page, and use a page provided by Jetpack.
464
		 */
465
		if ( Constants::is_true( 'JETPACK_ALWAYS_PROTECT_LOGIN' ) ) {
466
			$this->kill_login();
467
		}
468
469
		if ( $this->is_current_ip_whitelisted() ) {
470
		    return true;
471
        }
472
473
		$status = $this->get_cached_status();
474
475
		if ( empty( $status ) ) {
476
			// If we've reached this point, this means that the IP isn't cached.
477
			// Now we check with the Protect API to see if we should allow login
478
			$response = $this->protect_call( $action = 'check_ip' );
479
480
			if ( isset( $response['math'] ) && ! function_exists( 'brute_math_authenticate' ) ) {
481
				include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
482
				new Jetpack_Protect_Math_Authenticate;
483
484
				return false;
485
			}
486
487
			$status = $response['status'];
488
		}
489
490
		if ( 'blocked' == $status ) {
491
			$this->block_with_math();
492
		}
493
494
		if ( 'blocked-hard' == $status ) {
495
			$this->kill_login();
496
		}
497
498
		return true;
499
	}
500
501
	function is_current_ip_whitelisted() {
502
		$ip = jetpack_protect_get_ip();
503
504
		// Server is misconfigured and we can't get an IP
505
		if ( ! $ip && class_exists( 'Jetpack' ) ) {
506
			Jetpack::deactivate_module( 'protect' );
507
			ob_start();
508
			Jetpack::state( 'message', 'protect_misconfigured_ip' );
509
			ob_end_clean();
510
			return true;
511
		}
512
513
		/**
514
		 * Short-circuit check_login_ability.
515
		 *
516
		 * If there is an alternate way to validate the current IP such as
517
		 * a hard-coded list of IP addresses, we can short-circuit the rest
518
		 * of the login ability checks and return true here.
519
		 *
520
		 * @module protect
521
		 *
522
		 * @since 4.4.0
523
		 *
524
		 * @param bool false Should we allow all logins for the current ip? Default: false
525
		 */
526
		if ( apply_filters( 'jpp_allow_login', false, $ip ) ) {
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $ip.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
527
			return true;
528
		}
529
530
		if ( jetpack_protect_ip_is_private( $ip ) ) {
531
			return true;
532
		}
533
534
		if ( $this->ip_is_whitelisted( $ip ) ) {
535
			return true;
536
		}
537
    }
538
539
    function has_login_ability() {
540
	    if ( $this->is_current_ip_whitelisted() ) {
541
		    return true;
542
	    }
543
	    $status = $this->get_cached_status();
544
	    if ( empty( $status ) || $status === 'ok' ) {
545
	        return true;
546
        }
547
        return false;
548
    }
549
550
	function get_cached_status() {
551
		$transient_name  = $this->get_transient_name();
552
		$value = $this->get_transient( $transient_name );
553
		if ( isset( $value['status'] ) ) {
554
		    return $value['status'];
555
        }
556
        return '';
557
	}
558
559
	function block_with_math() {
560
		/**
561
		 * By default, Protect will allow a user who has been blocked for too
562
		 * many failed logins to start answering math questions to continue logging in
563
		 *
564
		 * For added security, you can disable this.
565
		 *
566
		 * @module protect
567
		 *
568
		 * @since 3.6.0
569
		 *
570
		 * @param bool Whether to allow math for blocked users or not.
571
		 */
572
573
		$this->block_login_with_math = 1;
574
		/**
575
		 * Allow Math fallback for blocked IPs.
576
		 *
577
		 * @module protect
578
		 *
579
		 * @since 3.6.0
580
		 *
581
		 * @param bool true Should we fallback to the Math questions when an IP is blocked. Default to true.
582
		 */
583
		$allow_math_fallback_on_fail = apply_filters( 'jpp_use_captcha_when_blocked', true );
584
		if ( ! $allow_math_fallback_on_fail  ) {
585
			$this->kill_login();
586
		}
587
		include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
588
		new Jetpack_Protect_Math_Authenticate;
589
590
		return false;
591
	}
592
593
	/*
594
	 * Kill a login attempt
595
	 */
596
	function kill_login() {
597
		if (
598
			isset( $_GET['action'], $_GET['_wpnonce'] ) &&
599
			'logout' === $_GET['action'] &&
600
			wp_verify_nonce( $_GET['_wpnonce'], 'log-out' ) &&
601
			wp_get_current_user()
602
603
		) {
604
			// Allow users to logout
605
			return;
606
		}
607
608
		$ip = jetpack_protect_get_ip();
609
		/**
610
		 * Fires before every killed login.
611
		 *
612
		 * @module protect
613
		 *
614
		 * @since 3.4.0
615
		 *
616
		 * @param string $ip IP flagged by Protect.
617
		 */
618
		do_action( 'jpp_kill_login', $ip );
619
620
		if( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
621
			$die_string = sprintf( __( 'Your IP (%1$s) has been flagged for potential security violations.', 'jetpack' ), str_replace( 'http://', '', esc_url( 'http://' . $ip ) ) );
622
			wp_die(
623
				$die_string,
624
				__( 'Login Blocked by Jetpack', 'jetpack' ),
625
				array ( 'response' => 403 )
626
			);
627
		}
628
629
		require_once dirname( __FILE__ ) . '/protect/blocked-login-page.php';
630
		$blocked_login_page = Jetpack_Protect_Blocked_Login_Page::instance( $ip );
631
632
		if ( $blocked_login_page->is_blocked_user_valid() ) {
633
			return;
634
		}
635
636
		$blocked_login_page->render_and_die();
637
	}
638
639
	/*
640
	 * Checks if the protect API call has failed, and if so initiates the math captcha fallback.
641
	 */
642
	public function check_use_math() {
643
		$use_math = $this->get_transient( 'brute_use_math' );
644
		if ( $use_math ) {
645
			include_once dirname( __FILE__ ) . '/protect/math-fallback.php';
646
			new Jetpack_Protect_Math_Authenticate;
647
		}
648
	}
649
650
	/**
651
	 * If we're in a multisite network, return the blog ID of the primary blog
652
	 *
653
	 * @return int
654
	 */
655
	public function get_main_blog_id() {
656
		if ( ! is_multisite() ) {
657
			return false;
658
		}
659
660
		global $current_site;
661
		$primary_blog_id = $current_site->blog_id;
662
663
		return $primary_blog_id;
664
	}
665
666
	/**
667
	 * Get jetpack blog id, or the jetpack blog id of the main blog in the main network
668
	 *
669
	 * @return int
670
	 */
671
	public function get_main_blog_jetpack_id() {
672
		if ( ! is_main_site() ) {
673
			switch_to_blog( $this->get_main_blog_id() );
674
			$id = Jetpack::get_option( 'id', false );
675
			restore_current_blog();
676
		} else {
677
			$id = Jetpack::get_option( 'id' );
678
		}
679
680
		return $id;
681
	}
682
683
	public function check_api_key() {
684
		$response = $this->protect_call( 'check_key' );
685
686
		if ( isset( $response['ckval'] ) ) {
687
			return true;
688
		}
689
690
		if ( isset( $response['error'] ) ) {
691
692
			if ( $response['error'] == 'Invalid API Key' ) {
693
				$this->api_key_error = __( 'Your API key is invalid', 'jetpack' );
694
			}
695
696
			if ( $response['error'] == 'API Key Required' ) {
697
				$this->api_key_error = __( 'No API key', 'jetpack' );
698
			}
699
		}
700
701
		$this->api_key_error = __( 'There was an error contacting Jetpack servers.', 'jetpack' );
702
703
		return false;
704
	}
705
706
	/**
707
	 * Calls over to the api using wp_remote_post
708
	 *
709
	 * @param string $action 'check_ip', 'check_key', or 'failed_attempt'
710
	 * @param array $request Any custom data to post to the api
711
	 *
712
	 * @return array
713
	 */
714
	function protect_call( $action = 'check_ip', $request = array () ) {
715
		global $wp_version;
716
717
		$api_key = $this->maybe_get_protect_key();
718
719
		$user_agent = "WordPress/{$wp_version} | Jetpack/" . constant( 'JETPACK__VERSION' );
720
721
		$request['action']            = $action;
722
		$request['ip']                = jetpack_protect_get_ip();
723
		$request['host']              = $this->get_local_host();
724
		$request['headers']           = json_encode( $this->get_headers() );
725
		$request['jetpack_version']   = constant( 'JETPACK__VERSION' );
726
		$request['wordpress_version'] = strval( $wp_version );
727
		$request['api_key']           = $api_key;
728
		$request['multisite']         = "0";
729
730
		if ( is_multisite() ) {
731
			$request['multisite'] = get_blog_count();
732
		}
733
734
735
		/**
736
		 * Filter controls maximum timeout in waiting for reponse from Protect servers.
737
		 *
738
		 * @module protect
739
		 *
740
		 * @since 4.0.4
741
		 *
742
		 * @param int $timeout Max time (in seconds) to wait for a response.
743
		 */
744
		$timeout = apply_filters( 'jetpack_protect_connect_timeout', 30 );
745
746
		$args = array (
747
			'body'        => $request,
748
			'user-agent'  => $user_agent,
749
			'httpversion' => '1.0',
750
			'timeout'     => absint( $timeout )
751
		);
752
753
		$response_json           = wp_remote_post( $this->get_api_host(), $args );
754
		$this->last_response_raw = $response_json;
755
756
		$transient_name = $this->get_transient_name();
757
		$this->delete_transient( $transient_name );
758
759
		if ( is_array( $response_json ) ) {
760
			$response = json_decode( $response_json['body'], true );
761
		}
762
763
		if ( isset( $response['blocked_attempts'] ) && $response['blocked_attempts'] ) {
764
			update_site_option( 'jetpack_protect_blocked_attempts', $response['blocked_attempts'] );
765
		}
766
767
		if ( isset( $response['status'] ) && ! isset( $response['error'] ) ) {
768
			$response['expire'] = time() + $response['seconds_remaining'];
769
			$this->set_transient( $transient_name, $response, $response['seconds_remaining'] );
770
			$this->delete_transient( 'brute_use_math' );
771
		} else { // Fallback to Math Captcha if no response from API host
772
			$this->set_transient( 'brute_use_math', 1, 600 );
773
			$response['status'] = 'ok';
0 ignored issues
show
Bug introduced by
The variable $response does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
774
			$response['math']   = true;
775
		}
776
777
		if ( isset( $response['error'] ) ) {
778
			update_site_option( 'jetpack_protect_error', $response['error'] );
779
		} else {
780
			delete_site_option( 'jetpack_protect_error' );
781
		}
782
783
		return $response;
784
	}
785
786
	function get_transient_name() {
787
		$headers     = $this->get_headers();
788
		$header_hash = md5( json_encode( $headers ) );
789
790
		return 'jpp_li_' . $header_hash;
791
	}
792
793
	/**
794
	 * Wrapper for WordPress set_transient function, our version sets
795
	 * the transient on the main site in the network if this is a multisite network
796
	 *
797
	 * We do it this way (instead of set_site_transient) because of an issue where
798
	 * sitewide transients are always autoloaded
799
	 * https://core.trac.wordpress.org/ticket/22846
800
	 *
801
	 * @param string $transient Transient name. Expected to not be SQL-escaped. Must be
802
	 *                           45 characters or fewer in length.
803
	 * @param mixed $value Transient value. Must be serializable if non-scalar.
804
	 *                           Expected to not be SQL-escaped.
805
	 * @param int $expiration Optional. Time until expiration in seconds. Default 0.
806
	 *
807
	 * @return bool False if value was not set and true if value was set.
808
	 */
809
	function set_transient( $transient, $value, $expiration ) {
810
		if ( is_multisite() && ! is_main_site() ) {
811
			switch_to_blog( $this->get_main_blog_id() );
812
			$return = set_transient( $transient, $value, $expiration );
813
			restore_current_blog();
814
815
			return $return;
816
		}
817
818
		return set_transient( $transient, $value, $expiration );
819
	}
820
821
	/**
822
	 * Wrapper for WordPress delete_transient function, our version deletes
823
	 * the transient on the main site in the network if this is a multisite network
824
	 *
825
	 * @param string $transient Transient name. Expected to not be SQL-escaped.
826
	 *
827
	 * @return bool true if successful, false otherwise
828
	 */
829 View Code Duplication
	function delete_transient( $transient ) {
830
		if ( is_multisite() && ! is_main_site() ) {
831
			switch_to_blog( $this->get_main_blog_id() );
832
			$return = delete_transient( $transient );
833
			restore_current_blog();
834
835
			return $return;
836
		}
837
838
		return delete_transient( $transient );
839
	}
840
841
	/**
842
	 * Wrapper for WordPress get_transient function, our version gets
843
	 * the transient on the main site in the network if this is a multisite network
844
	 *
845
	 * @param string $transient Transient name. Expected to not be SQL-escaped.
846
	 *
847
	 * @return mixed Value of transient.
848
	 */
849 View Code Duplication
	function get_transient( $transient ) {
850
		if ( is_multisite() && ! is_main_site() ) {
851
			switch_to_blog( $this->get_main_blog_id() );
852
			$return = get_transient( $transient );
853
			restore_current_blog();
854
855
			return $return;
856
		}
857
858
		return get_transient( $transient );
859
	}
860
861
	function get_api_host() {
862
		if ( isset( $this->api_endpoint ) ) {
863
			return $this->api_endpoint;
864
		}
865
866
		//Check to see if we can use SSL
867
		$this->api_endpoint = Connection_Utils::fix_url_for_bad_hosts( JETPACK_PROTECT__API_HOST );
868
869
		return $this->api_endpoint;
870
	}
871
872
	function get_local_host() {
873
		if ( isset( $this->local_host ) ) {
874
			return $this->local_host;
875
		}
876
877
		$uri = 'http://' . strtolower( $_SERVER['HTTP_HOST'] );
878
879
		if ( is_multisite() ) {
880
			$uri = network_home_url();
881
		}
882
883
		$uridata = wp_parse_url( $uri );
884
885
		$domain = $uridata['host'];
886
887
		// If we still don't have the site_url, get it
888
		if ( ! $domain ) {
889
			$uri     = get_site_url( 1 );
890
			$uridata = wp_parse_url( $uri );
891
			$domain  = $uridata['host'];
892
		}
893
894
		$this->local_host = $domain;
895
896
		return $this->local_host;
897
	}
898
899
}
900
901
$jetpack_protect = Jetpack_Protect_Module::instance();
902
903
global $pagenow;
904
if ( isset( $pagenow ) && 'wp-login.php' == $pagenow ) {
905
	$jetpack_protect->check_login_ability();
906
}
907