Nessuna descrizione

protect.php 26KB

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