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