protect.php 27 KB

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