Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
61.39% |
97 / 158 |
|
46.67% |
7 / 15 |
CRAP | |
0.00% |
0 / 1 |
| Firewall | |
62.18% |
97 / 156 |
|
46.67% |
7 / 15 |
285.59 | |
0.00% |
0 / 1 |
| get_key | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| get_state | |
0.00% |
0 / 11 |
|
0.00% |
0 / 1 |
2 | |||
| register_routes | |
0.00% |
0 / 18 |
|
0.00% |
0 / 1 |
2 | |||
| start_test | |
0.00% |
0 / 14 |
|
0.00% |
0 / 1 |
12 | |||
| get_blocks | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
5 | |||
| get_rules_updated_at | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
4 | |||
| get_current_ip | |
91.67% |
11 / 12 |
|
0.00% |
0 / 1 |
7.03 | |||
| validate_ip_block_list | |
100.00% |
22 / 22 |
|
100.00% |
1 / 1 |
6 | |||
| ip_list_covers | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
5 | |||
| get_ip_rules | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
6 | |||
| shares_data | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| get_recent_blocks | |
85.71% |
6 / 7 |
|
0.00% |
0 / 1 |
4.05 | |||
| add_request_details | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
11 | |||
| truncate | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| read_request_log | |
81.48% |
22 / 27 |
|
0.00% |
0 / 1 |
10.64 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * Protect dashboard: the Firewall section. |
| 4 | * |
| 5 | * @package automattic/jetpack-protect |
| 6 | */ |
| 7 | |
| 8 | namespace Automattic\Jetpack\Protect\Sections; |
| 9 | |
| 10 | use Automattic\Jetpack\IP\Utils as IP_Utils; |
| 11 | use Automattic\Jetpack\Protect\Dashboard; |
| 12 | use Automattic\Jetpack\Protect\Dashboard_Section; |
| 13 | use Automattic\Jetpack\Waf\Waf_Blocklog_Manager; |
| 14 | use Automattic\Jetpack\Waf\Waf_Constants; |
| 15 | use Automattic\Jetpack\Waf\Waf_Request; |
| 16 | use Automattic\Jetpack\Waf\Waf_Rules_Manager; |
| 17 | use Automattic\Jetpack\Waf\Waf_Runner; |
| 18 | use Automattic\Jetpack\Waf\Waf_Self_Check; |
| 19 | use Automattic\Jetpack\Waf\Waf_Stats; |
| 20 | use WP_Error; |
| 21 | use WP_REST_Server; |
| 22 | |
| 23 | if ( ! defined( 'ABSPATH' ) ) { |
| 24 | exit( 0 ); |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * The firewall's on/off state, blocked requests, IP lists and a one-time request to test it with. |
| 29 | * |
| 30 | * @since 0.2.0 |
| 31 | */ |
| 32 | class Firewall implements Dashboard_Section { |
| 33 | |
| 34 | /** |
| 35 | * Headers a proxy names the visitor in. One that disagrees with the firewall's address means that address is the proxy's. |
| 36 | */ |
| 37 | const FORWARDING_HEADERS = array( |
| 38 | 'HTTP_X_FORWARDED_FOR', |
| 39 | 'HTTP_X_REAL_IP', |
| 40 | 'HTTP_CF_CONNECTING_IP', |
| 41 | 'HTTP_TRUE_CLIENT_IP', |
| 42 | 'HTTP_CLIENT_IP', |
| 43 | ); |
| 44 | |
| 45 | /** |
| 46 | * The key the section's state is printed under. |
| 47 | * |
| 48 | * @return string |
| 49 | */ |
| 50 | public function get_key() { |
| 51 | return 'firewall'; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * The firewall module's state, its blocked requests and whether a Scan plan is active. |
| 56 | * |
| 57 | * @return array |
| 58 | */ |
| 59 | public function get_state() { |
| 60 | // The block counts persist while the firewall is off, so they are sent either way. |
| 61 | return array_merge( |
| 62 | Dashboard::get_module_state( 'waf' ), |
| 63 | self::get_blocks(), |
| 64 | array( |
| 65 | 'hasScan' => Dashboard::has_scan_plan(), |
| 66 | 'upgradeUrl' => Dashboard::get_scan_upgrade_url(), |
| 67 | 'currentIp' => self::get_current_ip(), |
| 68 | 'ipRules' => self::get_ip_rules(), |
| 69 | 'rulesUpdatedAt' => self::get_rules_updated_at(), |
| 70 | ) |
| 71 | ); |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * Register `jetpack/v4/protect-dashboard/firewall/test` and `…/firewall/blocks`. |
| 76 | * |
| 77 | * The firewall's settings are saved through existing endpoints. |
| 78 | * |
| 79 | * @return void |
| 80 | */ |
| 81 | public function register_routes() { |
| 82 | register_rest_route( |
| 83 | 'jetpack/v4', |
| 84 | '/protect-dashboard/firewall/test', |
| 85 | array( |
| 86 | 'methods' => WP_REST_Server::CREATABLE, |
| 87 | 'callback' => array( __CLASS__, 'start_test' ), |
| 88 | 'permission_callback' => array( Dashboard::class, 'can_manage' ), |
| 89 | ) |
| 90 | ); |
| 91 | |
| 92 | register_rest_route( |
| 93 | 'jetpack/v4', |
| 94 | '/protect-dashboard/firewall/blocks', |
| 95 | array( |
| 96 | 'methods' => WP_REST_Server::READABLE, |
| 97 | 'callback' => array( __CLASS__, 'get_blocks' ), |
| 98 | 'permission_callback' => array( Dashboard::class, 'can_manage' ), |
| 99 | ) |
| 100 | ); |
| 101 | } |
| 102 | |
| 103 | /** |
| 104 | * A one-time URL the firewall blocks, for the browser to request. |
| 105 | * |
| 106 | * @return array|WP_Error |
| 107 | */ |
| 108 | public static function start_test() { |
| 109 | // The WAF package bundled by another plugin can predate the self-check. |
| 110 | if ( ! class_exists( Waf_Self_Check::class ) ) { |
| 111 | return new WP_Error( |
| 112 | 'firewall_test_unavailable', |
| 113 | __( 'Update Jetpack to test the firewall.', 'jetpack-protect-pkg' ), |
| 114 | array( 'status' => 501 ) |
| 115 | ); |
| 116 | } |
| 117 | |
| 118 | $token = Waf_Self_Check::create_token(); |
| 119 | if ( ! $token ) { |
| 120 | return new WP_Error( |
| 121 | 'firewall_test_failed', |
| 122 | __( 'The firewall test couldn’t start.', 'jetpack-protect-pkg' ), |
| 123 | array( 'status' => 500 ) |
| 124 | ); |
| 125 | } |
| 126 | |
| 127 | return array( 'url' => add_query_arg( Waf_Self_Check::QUERY_PARAM, $token, home_url( '/' ) ) ); |
| 128 | } |
| 129 | |
| 130 | /** |
| 131 | * The recent blocks and the block counts, refreshed after a test. |
| 132 | * |
| 133 | * Today and the last 30 days are UTC days, as the firewall records them. |
| 134 | * |
| 135 | * @return array |
| 136 | */ |
| 137 | public static function get_blocks() { |
| 138 | $counts = class_exists( Waf_Stats::class ) ? Waf_Stats::get_blocked_requests() : array(); |
| 139 | |
| 140 | return array( |
| 141 | 'recentBlocks' => self::get_recent_blocks(), |
| 142 | 'blockedCount' => isset( $counts['all_time'] ) ? (int) $counts['all_time'] : null, |
| 143 | 'blockedToday' => isset( $counts['current_day'] ) ? (int) $counts['current_day'] : null, |
| 144 | 'blockedLast30Days' => isset( $counts['thirty_days'] ) ? (int) $counts['thirty_days'] : null, |
| 145 | ); |
| 146 | } |
| 147 | |
| 148 | /** |
| 149 | * When the automatic rules were last downloaded, as a Unix timestamp, or null while they're off or never were. |
| 150 | * |
| 151 | * @return int|null |
| 152 | */ |
| 153 | public static function get_rules_updated_at() { |
| 154 | if ( ! class_exists( Waf_Stats::class ) || ! Waf_Rules_Manager::automatic_rules_enabled() ) { |
| 155 | return null; |
| 156 | } |
| 157 | |
| 158 | $timestamp = (int) Waf_Stats::get_automatic_rules_last_updated(); |
| 159 | |
| 160 | return $timestamp > 0 ? $timestamp : null; |
| 161 | } |
| 162 | |
| 163 | /** |
| 164 | * The visitor's IP address as the firewall sees it, to offer on the allow list and keep off the block list. |
| 165 | * |
| 166 | * Empty when it may be a proxy's: allowing that address would let every visitor behind the proxy past the rules. |
| 167 | * |
| 168 | * @return string |
| 169 | */ |
| 170 | public static function get_current_ip() { |
| 171 | if ( ! class_exists( Waf_Request::class ) ) { |
| 172 | return ''; |
| 173 | } |
| 174 | |
| 175 | $ip = (string) ( new Waf_Request() )->get_real_user_ip_address(); |
| 176 | if ( ! filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) { |
| 177 | return ''; |
| 178 | } |
| 179 | |
| 180 | foreach ( self::FORWARDING_HEADERS as $header ) { |
| 181 | if ( empty( $_SERVER[ $header ] ) ) { |
| 182 | continue; |
| 183 | } |
| 184 | |
| 185 | $forwarded = trim( explode( ',', wp_unslash( $_SERVER[ $header ] ) )[0] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Validated as an IP address below. |
| 186 | if ( ! filter_var( $forwarded, FILTER_VALIDATE_IP ) || inet_pton( $forwarded ) !== inet_pton( $ip ) ) { |
| 187 | return ''; |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | return $ip; |
| 192 | } |
| 193 | |
| 194 | /** |
| 195 | * Refuse a block list that covers the visitor's own address, which would lock them out of the site. |
| 196 | * |
| 197 | * A list is allowed when the address is unknown, so a wrong guess can't stop a legitimate save. |
| 198 | * |
| 199 | * @param string $list The block list being saved: addresses, ranges or CIDR blocks. |
| 200 | * @return true|WP_Error |
| 201 | */ |
| 202 | public static function validate_ip_block_list( $list ) { |
| 203 | $ip = self::get_current_ip(); |
| 204 | if ( '' === $ip ) { |
| 205 | return true; |
| 206 | } |
| 207 | |
| 208 | if ( ! self::ip_list_covers( $list, $ip ) ) { |
| 209 | return true; |
| 210 | } |
| 211 | |
| 212 | // The firewall checks the allow list first, so this address would never actually be blocked. |
| 213 | if ( |
| 214 | class_exists( Waf_Rules_Manager::class ) |
| 215 | && Waf_Rules_Manager::ip_allow_list_enabled() |
| 216 | && self::ip_list_covers( (string) get_option( Waf_Rules_Manager::IP_ALLOW_LIST_OPTION_NAME, '' ), $ip ) |
| 217 | ) { |
| 218 | return new WP_Error( |
| 219 | 'ip_block_list_includes_allowed_ip', |
| 220 | sprintf( |
| 221 | /* translators: %s is the visitor's IP address. */ |
| 222 | __( 'Your IP address (%s) is on your allow list, so it can\'t be added to the block list. Remove it, or the range that includes it, from the block list and try again.', 'jetpack-protect-pkg' ), |
| 223 | $ip |
| 224 | ) |
| 225 | ); |
| 226 | } |
| 227 | |
| 228 | return new WP_Error( |
| 229 | 'ip_block_list_includes_current_ip', |
| 230 | sprintf( |
| 231 | /* translators: %s is the visitor's IP address. */ |
| 232 | __( 'Your IP address (%s) is on the block list, so saving it would block you from your own site. Remove it, or the range that includes it, and try again.', 'jetpack-protect-pkg' ), |
| 233 | $ip |
| 234 | ) |
| 235 | ); |
| 236 | } |
| 237 | |
| 238 | /** |
| 239 | * Whether an IP list includes an address, through the address itself, a range or a CIDR block. |
| 240 | * |
| 241 | * @param string $list Addresses, ranges or CIDR blocks. |
| 242 | * @param string $ip The address to look for. |
| 243 | * @return bool |
| 244 | */ |
| 245 | private static function ip_list_covers( $list, $ip ) { |
| 246 | foreach ( IP_Utils::get_ip_addresses_from_string( $list ) as $entry ) { |
| 247 | // Split as the firewall does: a CIDR block, a hyphenated range or a single address. |
| 248 | $range = strpos( $entry, '/' ) !== false ? array( $entry, null ) : explode( '-', $entry ); |
| 249 | $is_match = count( $range ) === 2 |
| 250 | ? IP_Utils::ip_address_is_in_range( $ip, $range[0], $range[1] ) |
| 251 | : inet_pton( $entry ) === inet_pton( $ip ); |
| 252 | |
| 253 | if ( $is_match ) { |
| 254 | return true; |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | return false; |
| 259 | } |
| 260 | |
| 261 | /** |
| 262 | * The firewall's IP lists, keyed like the Jetpack settings that hold them. |
| 263 | * |
| 264 | * @return array<string, string|bool>|object An empty object when the WAF package isn't loaded, so it's `{}` in JSON. |
| 265 | */ |
| 266 | private static function get_ip_rules() { |
| 267 | if ( ! class_exists( Waf_Rules_Manager::class ) ) { |
| 268 | return (object) array(); |
| 269 | } |
| 270 | |
| 271 | return array( |
| 272 | Waf_Rules_Manager::IP_BLOCK_LIST_OPTION_NAME => (string) get_option( Waf_Rules_Manager::IP_BLOCK_LIST_OPTION_NAME, '' ), |
| 273 | Waf_Rules_Manager::IP_BLOCK_LIST_ENABLED_OPTION_NAME => (bool) Waf_Rules_Manager::ip_block_list_enabled(), |
| 274 | Waf_Rules_Manager::IP_ALLOW_LIST_OPTION_NAME => (string) get_option( Waf_Rules_Manager::IP_ALLOW_LIST_OPTION_NAME, '' ), |
| 275 | Waf_Rules_Manager::IP_ALLOW_LIST_ENABLED_OPTION_NAME => (bool) Waf_Rules_Manager::ip_allow_list_enabled(), |
| 276 | ); |
| 277 | } |
| 278 | |
| 279 | /** |
| 280 | * Whether the firewall keeps its request log, the "Share basic data" setting. |
| 281 | * |
| 282 | * @return bool |
| 283 | */ |
| 284 | private static function shares_data() { |
| 285 | return class_exists( Waf_Runner::class ) && (bool) get_option( Waf_Runner::SHARE_DATA_OPTION_NAME ); |
| 286 | } |
| 287 | |
| 288 | /** |
| 289 | * The last 10 blocked requests, newest first, with their request details when the request log has them. |
| 290 | * |
| 291 | * @return array |
| 292 | */ |
| 293 | private static function get_recent_blocks() { |
| 294 | if ( ! method_exists( Waf_Blocklog_Manager::class, 'get_recent_blocks' ) ) { |
| 295 | return array(); |
| 296 | } |
| 297 | |
| 298 | $blocks = Waf_Blocklog_Manager::get_recent_blocks( 10 ); |
| 299 | |
| 300 | if ( ! $blocks || ! self::shares_data() ) { |
| 301 | return $blocks; |
| 302 | } |
| 303 | |
| 304 | $oldest = end( $blocks )['timestamp']; |
| 305 | |
| 306 | return self::add_request_details( $blocks, self::read_request_log( $oldest ) ); |
| 307 | } |
| 308 | |
| 309 | /** |
| 310 | * Match each block to its entry in the request log, by second and rule. |
| 311 | * |
| 312 | * @param array $blocks Blocks from the blocklog table, newest first. |
| 313 | * @param array $entries Decoded request log entries, oldest first. |
| 314 | * @return array The blocks, with `uri` and `userAgent` where an entry matched. |
| 315 | */ |
| 316 | public static function add_request_details( array $blocks, array $entries ) { |
| 317 | $by_key = array(); |
| 318 | foreach ( $entries as $entry ) { |
| 319 | if ( isset( $entry['rule_id'] ) && is_string( $entry['timestamp'] ?? null ) ) { |
| 320 | $by_key[ str_replace( ' ', 'T', $entry['timestamp'] ) . 'Z|' . (int) $entry['rule_id'] ][] = $entry; |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | foreach ( $blocks as &$block ) { |
| 325 | $key = $block['timestamp'] . '|' . $block['ruleId']; |
| 326 | // Several blocks in one second: the newest block takes the newest entry. |
| 327 | $entry = empty( $by_key[ $key ] ) ? null : array_pop( $by_key[ $key ] ); |
| 328 | if ( ! $entry ) { |
| 329 | continue; |
| 330 | } |
| 331 | if ( ! empty( $entry['request_uri'] ) && is_string( $entry['request_uri'] ) ) { |
| 332 | $block['uri'] = self::truncate( $entry['request_uri'], 2048 ); |
| 333 | } |
| 334 | if ( ! empty( $entry['user_agent'] ) && is_string( $entry['user_agent'] ) ) { |
| 335 | $block['userAgent'] = self::truncate( $entry['user_agent'], 512 ); |
| 336 | } |
| 337 | } |
| 338 | unset( $block ); |
| 339 | |
| 340 | return $blocks; |
| 341 | } |
| 342 | |
| 343 | /** |
| 344 | * A string cut to a byte length, without splitting a multibyte character. |
| 345 | * |
| 346 | * @param string $value The string. |
| 347 | * @param int $length The most bytes to keep. |
| 348 | * @return string |
| 349 | */ |
| 350 | private static function truncate( $value, $length ) { |
| 351 | return function_exists( 'mb_strcut' ) ? mb_strcut( $value, 0, $length, 'UTF-8' ) : substr( $value, 0, $length ); |
| 352 | } |
| 353 | |
| 354 | /** |
| 355 | * The firewall's request log entries since a block, oldest first. |
| 356 | * |
| 357 | * @param string $since The oldest block's timestamp, as `get_recent_blocks()` formats it. |
| 358 | * @return array |
| 359 | */ |
| 360 | private static function read_request_log( $since ) { |
| 361 | if ( ! class_exists( Waf_Constants::class ) ) { |
| 362 | return array(); |
| 363 | } |
| 364 | Waf_Constants::define_waf_directory(); |
| 365 | |
| 366 | $path = Waf_Blocklog_Manager::get_blocklog_file_path(); |
| 367 | $size = is_readable( $path ) ? filesize( $path ) : 0; |
| 368 | if ( ! $size ) { |
| 369 | return array(); |
| 370 | } |
| 371 | |
| 372 | // The log can grow to 100 MB; its tail holds the last 10 blocks. |
| 373 | $tail_size = 256 * 1024; |
| 374 | // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Read-only, from an offset. |
| 375 | $handle = fopen( $path, 'rb' ); |
| 376 | if ( ! $handle ) { |
| 377 | return array(); |
| 378 | } |
| 379 | fseek( $handle, max( 0, $size - $tail_size ) ); |
| 380 | $tail = (string) fread( $handle, $tail_size ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread |
| 381 | fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose |
| 382 | |
| 383 | $lines = explode( "\n", $tail ); |
| 384 | if ( $size > $tail_size ) { |
| 385 | array_shift( $lines ); // Starts mid-entry. |
| 386 | } |
| 387 | |
| 388 | // The log's timestamps are `Y-m-d H:i:s`, which sort as text. |
| 389 | $since = str_replace( array( 'T', 'Z' ), array( ' ', '' ), $since ); |
| 390 | $entries = array(); |
| 391 | foreach ( array_reverse( $lines ) as $line ) { |
| 392 | $entry = json_decode( $line, true ); |
| 393 | if ( ! is_array( $entry ) ) { |
| 394 | continue; |
| 395 | } |
| 396 | if ( is_string( $entry['timestamp'] ?? null ) && $entry['timestamp'] < $since ) { |
| 397 | break; |
| 398 | } |
| 399 | $entries[] = $entry; |
| 400 | } |
| 401 | |
| 402 | return array_reverse( $entries ); |
| 403 | } |
| 404 | } |