Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.38% covered (warning)
78.38%
261 / 333
57.14% covered (warning)
57.14%
16 / 28
CRAP
0.00% covered (danger)
0.00%
0 / 1
Waf_Runtime
78.31% covered (warning)
78.31%
260 / 332
57.14% covered (warning)
57.14%
16 / 28
351.57
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 rule_removed
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 update_targets
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
9
 match_targets
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
72
 get_ip_hash
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 is_ip_allowed_for_recovery
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 allow_login_or_prompt_recovery
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 block
41.18% covered (danger)
41.18%
7 / 17
0.00% covered (danger)
0.00%
0 / 1
30.35
 redirect
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 flag_rule_for_removal
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 flag_target_for_removal
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 get_var
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 set_var
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 inc_var
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 dec_var
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 unset_var
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 meta
88.37% covered (warning)
88.37%
76 / 86
0.00% covered (danger)
0.00%
0 / 1
29.23
 state_values
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 get_body_processor
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 set_body_processor
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
12
 normalize_header_name
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 normalize_targets
97.26% covered (success)
97.26%
71 / 73
0.00% covered (danger)
0.00%
0 / 1
31
 reset_matched_vars
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 is_ip_in_array
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
42
 normalize_array_target
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
10
 args_names
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 key_matches
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 sanitize_output
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Runtime for Jetpack Waf
4 *
5 * @package automattic/jetpack-waf
6 */
7
8namespace Automattic\Jetpack\Waf;
9
10use Automattic\Jetpack\IP\Utils as IP_Utils;
11
12require_once __DIR__ . '/functions.php';
13
14// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- This class is all about sanitizing input.
15
16/**
17 * The environment variable that defined the WAF running mode.
18 *
19 * @var string JETPACK_WAF_MODE
20 */
21
22// Type aliases for this file.
23<<<'PHAN'
24@phan-type Target = array{ only?: string[], except?: string[], count?: boolean }
25@phan-type TargetBag = array<string, Target>
26PHAN;
27
28/**
29 * Waf_Runtime class
30 */
31class Waf_Runtime {
32    /**
33     * If used, normalize_array_targets() will just return the number of matching values, instead of the values themselves.
34     */
35    const NORMALIZE_ARRAY_COUNT = 1;
36    /**
37     * If used, normalize_array_targets() will apply "only" and "except" filters to the values of the source array, instead of the keys.
38     */
39    const NORMALIZE_ARRAY_MATCH_VALUES = 2;
40
41    /**
42     * The version of this runtime class. Used by rule files to ensure compatibility.
43     *
44     * @since 0.21.0
45     *
46     * @var int
47     */
48    public $version = 1;
49    /**
50     * Last rule.
51     *
52     * @var string
53     */
54    public $last_rule = '';
55    /**
56     * Matched vars.
57     *
58     * @var array
59     */
60    public $matched_vars = array();
61    /**
62     * Matched var.
63     *
64     * @var string
65     */
66    public $matched_var = '';
67    /**
68     * Matched var names.
69     *
70     * @var array
71     */
72    public $matched_vars_names = array();
73    /**
74     * Matched var name.
75     *
76     * @var string
77     */
78    public $matched_var_name = '';
79    /**
80     * Body Processor.
81     *
82     * @var string 'URLENCODED' | 'JSON' | ''
83     */
84    private $body_processor = '';
85
86    /**
87     * State.
88     *
89     * @var array
90     */
91    private $state = array();
92    /**
93     * Metadata.
94     *
95     * @var array
96     */
97    private $metadata = array();
98
99    /**
100     * Transforms.
101     *
102     * @var Waf_Transforms
103     */
104    private $transforms;
105    /**
106     * Operators.
107     *
108     * @var Waf_Operators
109     */
110    private $operators;
111
112    /**
113     * The request
114     *
115     * @var Waf_Request
116     */
117    private $request;
118
119    /**
120     * Rules to remove.
121     *
122     * @var array[]
123     */
124    private $rules_to_remove = array(
125        'id'  => array(),
126        'tag' => array(),
127    );
128
129    /**
130     * Targets to remove.
131     *
132     * @var array[]
133     */
134    private $targets_to_remove = array(
135        'id'  => array(),
136        'tag' => array(),
137    );
138
139    /**
140     * Constructor method.
141     *
142     * @param Waf_Transforms $transforms Transforms.
143     * @param Waf_Operators  $operators  Operators.
144     * @param ?Waf_Request   $request    Information about the request.
145     */
146    public function __construct( $transforms, $operators, $request = null ) {
147        $this->transforms = $transforms;
148        $this->operators  = $operators;
149        $this->request    = null === $request
150            ? new Waf_Request()
151            : $request;
152    }
153
154    /**
155     * Rule removed method.
156     *
157     * @param string   $id Ids.
158     * @param string[] $tags Tags.
159     */
160    public function rule_removed( $id, $tags ) {
161        if ( isset( $this->rules_to_remove['id'][ $id ] ) ) {
162            return true;
163        }
164        foreach ( $tags as $tag ) {
165            if ( isset( $this->rules_to_remove['tag'][ $tag ] ) ) {
166                return true;
167            }
168        }
169        return false;
170    }
171
172    /**
173     * Update Targets.
174     *
175     * @param array    $targets Targets.
176     * @param string   $rule_id Rule id.
177     * @param string[] $rule_tags Rule tags.
178     */
179    public function update_targets( $targets, $rule_id, $rule_tags ) {
180        $updates = array();
181        // look for target updates based on the rule's ID.
182        if ( isset( $this->targets_to_remove['id'][ $rule_id ] ) ) {
183            foreach ( $this->targets_to_remove['id'][ $rule_id ] as $name => $props ) {
184                $updates[] = array( $name, $props );
185            }
186        }
187        // look for target updates based on the rule's tags.
188        foreach ( $rule_tags as $tag ) {
189            if ( isset( $this->targets_to_remove['tag'][ $tag ] ) ) {
190                foreach ( $this->targets_to_remove['tag'][ $tag ] as $name => $props ) {
191                    $updates[] = array( $name, $props );
192                }
193            }
194        }
195        // apply any found target updates.
196
197        foreach ( $updates as list( $name, $props ) ) {
198            if ( isset( $targets[ $name ] ) ) {
199                // we only need to remove targets that exist.
200                if ( true === $props ) {
201                    // if the entire target is being removed, remove it.
202                    unset( $targets[ $name ] );
203                } else {
204                    // otherwise just mark single props to ignore.
205                    $targets[ $name ]['except'] = array_merge(
206                        $targets[ $name ]['except'] ?? array(),
207                        $props
208                    );
209                }
210            }
211        }
212        return $targets;
213    }
214
215    /**
216     * Return TRUE if at least one of the targets matches the rule.
217     *
218     * @param string[]  $transforms One of the transform methods defined in the Jetpack Waf_Transforms class.
219     * @param TargetBag $targets Targets.
220     * @param string    $match_operator Match operator.
221     * @param mixed     $match_value Match value.
222     * @param bool      $match_not Match not.
223     * @param bool      $capture Capture.
224     * @return bool
225     */
226    public function match_targets( $transforms, $targets, $match_operator, $match_value, $match_not, $capture = false ) {
227        $match_found = false;
228
229        // get values.
230        $values = $this->normalize_targets( $targets );
231
232        // apply transforms.
233        foreach ( $transforms as $t ) {
234            foreach ( $values as &$v ) {
235                $v['value'] = $this->transforms->$t( $v['value'] );
236            }
237        }
238        unset( $v );
239        // pass each target value to the operator to find any that match.
240        $matched  = array();
241        $captures = array();
242        foreach ( $values as $v ) {
243            $match     = $this->operators->{$match_operator}( $v['value'], $match_value );
244            $did_match = false !== $match;
245            if ( $match_not !== $did_match ) {
246                // If either:
247                // - rule is negated ("not" flag set) and the target was not matched
248                // - rule not negated and the target was matched
249                // then this is considered a match.
250                $match_found                = true;
251                $this->matched_vars_names[] = $v['name'];
252                $this->matched_vars[]       = $v['value'];
253                $this->matched_var_name     = end( $this->matched_vars_names );
254                $this->matched_var          = end( $this->matched_vars );
255                $matched[]                  = array( $v, $match );
256                // Set any captured matches into state if the rule has the "capture" flag.
257                if ( $capture ) {
258                    $captures = is_array( $match ) ? $match : array( $match );
259                    foreach ( array_slice( $captures, 0, 10 )  as $i => $c ) {
260                        $this->set_var( "tx.$i", $c );
261                    }
262                }
263            }
264        }
265
266        return $match_found;
267    }
268
269    /**
270     * Generate a secure hash for an IP address.
271     *
272     * @param string $ip IP address.
273     * @return string Hashed IP.
274     */
275    private function get_ip_hash( string $ip ): string {
276        $hash_key = wp_salt( 'auth' );
277        return hash_hmac( 'sha256', $ip, $hash_key );
278    }
279
280    /**
281     * Check if the IP is allowed for recovery.
282     *
283     * @param string $ip IP address.
284     * @return bool
285     */
286    public function is_ip_allowed_for_recovery( string $ip ): bool {
287        $allow_hash = get_transient( 'jetpack_waf_recovery_' . $ip );
288        return $allow_hash && hash_equals( $allow_hash, $this->get_ip_hash( $ip ) );
289    }
290
291    /**
292     * Process a recovery attempt.
293     *
294     * @param string $real_ip The real IP address of the request.
295     */
296    private function allow_login_or_prompt_recovery( $real_ip ) {
297        $blocked_login_page = Waf_Blocked_Login_Page::instance( $real_ip );
298
299        if ( $blocked_login_page->is_blocked_user_valid() ) {
300            // Allow the IP to bypass the block for 15 minutes.
301            set_transient( 'jetpack_waf_recovery_' . $real_ip, $this->get_ip_hash( $real_ip ), 15 * 60 );
302            return;
303        }
304
305        $blocked_login_page->render_and_die();
306    }
307
308    /**
309     * Block.
310     *
311     * @param string $action Action.
312     * @param string $rule_id Rule id.
313     * @param string $reason Block reason.
314     * @param int    $status_code Http status code.
315     */
316    public function block( $action, $rule_id, $reason, $status_code = 403 ) {
317        // The recovery flow needs transients, `wp_salt()` and `$pagenow`, so it cannot run in
318        // standalone mode, where the WAF executes from `auto_prepend_file` before WordPress.
319        if ( 'ip block list' === $reason && defined( 'ABSPATH' ) ) {
320            $real_ip = $this->request->get_real_user_ip_address();
321
322            if ( $this->is_ip_allowed_for_recovery( $real_ip ) ) {
323                return;
324            }
325
326            global $pagenow;
327            if ( isset( $pagenow ) && 'wp-login.php' === $pagenow ) {
328                $this->allow_login_or_prompt_recovery( $real_ip );
329                return;
330            }
331        }
332
333        if ( ! $reason ) {
334            $reason = "rule $rule_id";
335        } else {
336            $reason = $this->sanitize_output( $reason );
337        }
338
339        Waf_Blocklog_Manager::write_blocklog( $rule_id, $reason );
340        error_log( "Jetpack WAF Blocked Request\t$action\t$rule_id\t$status_code\t$reason" );
341        header( "X-JetpackWAF-Blocked: $status_code - rule $rule_id" );
342        if ( defined( 'JETPACK_WAF_MODE' ) && 'normal' === JETPACK_WAF_MODE ) {
343            $protocol = isset( $_SERVER['SERVER_PROTOCOL'] ) ? wp_unslash( $_SERVER['SERVER_PROTOCOL'] ) : 'HTTP';
344            header( $protocol . ' 403 Forbidden', true, $status_code );
345            die( "rule $rule_id - reason $reason" );
346        }
347    }
348
349    /**
350     * Redirect.
351     *
352     * @param string $rule_id Rule id.
353     * @param string $url Url.
354     * @return never
355     */
356    public function redirect( $rule_id, $url ) {
357        error_log( "Jetpack WAF Redirected Request.\tRule:$rule_id\t$url" );
358        header( "Location: $url" );
359        exit( 0 );
360    }
361
362    /**
363     * Flag rule for removal.
364     *
365     * @param string $prop Prop.
366     * @param string $value Value.
367     */
368    public function flag_rule_for_removal( $prop, $value ) {
369        if ( 'id' === $prop ) {
370            $this->rules_to_remove['id'][ $value ] = true;
371        } else {
372            $this->rules_to_remove['tag'][ $value ] = true;
373        }
374    }
375
376    /**
377     * Flag target for removal.
378     *
379     * @param string $id_or_tag Id or tag.
380     * @param string $id_or_tag_value Id or tag value.
381     * @param string $name Name.
382     * @param string $prop Prop.
383     */
384    public function flag_target_for_removal( $id_or_tag, $id_or_tag_value, $name, $prop = null ) {
385        if ( null === $prop ) {
386            $this->targets_to_remove[ $id_or_tag ][ $id_or_tag_value ][ $name ] = true;
387        } elseif (
388            ! isset( $this->targets_to_remove[ $id_or_tag ][ $id_or_tag_value ][ $name ] )
389            // if the entire target is already being removed then it would be redundant to remove a single property.
390            || true !== $this->targets_to_remove[ $id_or_tag ][ $id_or_tag_value ][ $name ]
391        ) {
392            $this->targets_to_remove[ $id_or_tag ][ $id_or_tag_value ][ $name ][] = $prop;
393        }
394    }
395
396    /**
397     * Get variable value.
398     *
399     * @param string $key Key.
400     */
401    public function get_var( $key ) {
402        return $this->state[ $key ] ?? '';
403    }
404
405    /**
406     * Set variable value.
407     *
408     * @param string $key Key.
409     * @param string $value Value.
410     */
411    public function set_var( $key, $value ) {
412        $this->state[ $key ] = $value;
413    }
414
415    /**
416     * Increment variable.
417     *
418     * @param string $key Key.
419     * @param mixed  $value Value.
420     */
421    public function inc_var( $key, $value ) {
422        if ( ! isset( $this->state[ $key ] ) ) {
423            $this->state[ $key ] = 0;
424        }
425        $this->state[ $key ] += floatval( $value );
426    }
427
428    /**
429     * Decrement variable.
430     *
431     * @param string $key Key.
432     * @param mixed  $value Value.
433     */
434    public function dec_var( $key, $value ) {
435        if ( ! isset( $this->state[ $key ] ) ) {
436            $this->state[ $key ] = 0;
437        }
438        $this->state[ $key ] -= floatval( $value );
439    }
440
441    /**
442     * Unset variable.
443     *
444     * @param string $key Key.
445     */
446    public function unset_var( $key ) {
447        unset( $this->state[ $key ] );
448    }
449
450    /**
451     * A cache of metadata about the incoming request.
452     *
453     * @param string $key The type of metadata to request ('headers', 'request_method', etc.).
454     */
455    public function meta( $key ) {
456        if ( ! isset( $this->metadata[ $key ] ) ) {
457            $value = null;
458            switch ( $key ) {
459                case 'headers':
460                    $value = $this->request->get_headers();
461                    break;
462                case 'headers_names':
463                    $value = $this->args_names( $this->meta( 'headers' ) );
464                    break;
465                case 'request_method':
466                    $value = $this->request->get_method();
467                    break;
468                case 'request_protocol':
469                    $value = $this->request->get_protocol();
470                    break;
471                case 'request_uri':
472                    $value = $this->request->get_uri( false );
473                    break;
474                case 'request_uri_raw':
475                    $value = $this->request->get_uri( true );
476                    break;
477                case 'request_filename':
478                    $value = $this->request->get_filename();
479                    break;
480                case 'request_line':
481                    $value = sprintf(
482                        '%s %s %s',
483                        $this->request->get_method(),
484                        $this->request->get_uri( false ),
485                        $this->request->get_protocol()
486                    );
487                    break;
488                case 'request_basename':
489                    $value = $this->request->get_basename();
490                    break;
491                case 'request_body':
492                    $value = $this->request->get_body();
493                    break;
494                case 'query_string':
495                    $value = $this->request->get_query_string();
496                    break;
497                case 'args_get':
498                    $value = $this->request->get_get_vars();
499                    break;
500                case 'args_get_names':
501                    $value = $this->args_names( $this->meta( 'args_get' ) );
502                    break;
503                case 'args_post':
504                    $value = $this->request->get_post_vars( $this->get_body_processor() );
505                    break;
506                case 'args_post_names':
507                    $value = $this->args_names( $this->meta( 'args_post' ) );
508                    break;
509                case 'args':
510                    $value = array_merge( $this->meta( 'args_get' ), $this->meta( 'args_post' ) );
511                    break;
512                case 'args_names':
513                    $value = $this->args_names( $this->meta( 'args' ) );
514                    break;
515                case 'request_cookies':
516                    $value = $this->request->get_cookies();
517                    break;
518                case 'request_cookies_names':
519                    $value = $this->args_names( $this->meta( 'request_cookies' ) );
520                    break;
521                case 'files':
522                    $value = array();
523                    foreach ( $this->request->get_files() as $f ) {
524                        $value[] = array( $f['name'], $f['filename'] );
525                    }
526                    break;
527                case 'files_names':
528                    $value = $this->args_names( $this->meta( 'files' ) );
529                    break;
530                case 'matched_vars':
531                    $value = array_combine( $this->matched_vars_names, $this->matched_vars );
532                    break;
533                case 'matched_var':
534                    $value = array( $this->matched_var_name => $this->matched_var );
535                    break;
536                case 'matched_vars_names':
537                    $value = $this->matched_vars_names;
538                    break;
539                case 'matched_var_name':
540                    $value = array( $this->matched_var_name );
541                    break;
542            }
543            $this->metadata[ $key ] = $value;
544        }
545
546        return $this->metadata[ $key ];
547    }
548
549    /**
550     * State values.
551     *
552     * @param string $prefix Prefix.
553     */
554    private function state_values( $prefix ) {
555        $output = array();
556        $len    = strlen( $prefix );
557        foreach ( $this->state as $k => $v ) {
558            if ( 0 === stripos( $k, $prefix ) ) {
559                $output[ substr( $k, $len ) ] = $v;
560            }
561        }
562
563        return $output;
564    }
565
566    /**
567     * Get the body processor.
568     *
569     * @return string
570     */
571    private function get_body_processor() {
572        return $this->body_processor;
573    }
574
575    /**
576     * Set the body processor.
577     *
578     * @param string $processor Processor to set. Either 'URLENCODED' or 'JSON'.
579     *
580     * @return void
581     */
582    public function set_body_processor( $processor ) {
583        if ( $processor === 'URLENCODED' || $processor === 'JSON' ) {
584            $this->body_processor = $processor;
585        }
586    }
587
588    /**
589     * Change a string to all lowercase and replace spaces and underscores with dashes.
590     *
591     * @param string $name Name.
592     * @return string
593     */
594    public function normalize_header_name( $name ) {
595        return str_replace( array( ' ', '_' ), '-', strtolower( $name ) );
596    }
597
598    /**
599     * Get match-able values from a collection of targets.
600     *
601     * This function expects an associative array of target items, and returns an array of possible values from those targets that can be used to match against.
602     * The key is the lowercase target name (i.e. `args`, `request_headers`, etc) - see https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual-(v3.x)#Variables
603     * The value is an associative array of options that define how to narrow down the returned values for that target if it's an array (ARGS, for example). The possible options are:
604     *   count:  If `true`, then the returned value will a count of how many matched targets were found, rather then the actual values of those targets.
605     *           For example, &ARGS_GET will return the number of keys the query string.
606     *   only:   If specified, then only values in that target that match the given key will be returned.
607     *           For example, ARGS_GET:id|ARGS_GET:/^name/ will only return the values for `$_GET['id']` and any key in `$_GET` that starts with `name`
608     *   except: If specified, then values in that target will be left out from the returned values (even if they were included in an `only` option)
609     *           For example, ARGS_GET|!ARGS_GET:z will return every value from `$_GET` except for `$_GET['z']`.
610     *
611     * This function will return an array of associative arrays. Each with:
612     *   name:   The target name that this value came from (i.e. the key in the input `$targets` argument )
613     *   source: For targets that are associative arrays (like ARGS), this will be the target name AND the key in that target (i.e. "args:z" for ARGS:z)
614     *   value:  The value that was found in the associated target.
615     *
616     * @param TargetBag $targets An assoc. array with keys that are target name(s) and values are options for how to process that target (include/exclude rules, whether to return values or counts).
617     * @return array{name: string, source: string, value: mixed}[]
618     */
619    public function normalize_targets( $targets ) {
620        $return = array();
621        foreach ( $targets as $k => $v ) {
622            $count_only = isset( $v['count'] ) ? self::NORMALIZE_ARRAY_COUNT : 0;
623            $only       = $v['only'] ?? array();
624            $except     = $v['except'] ?? array();
625            $_k         = strtolower( $k );
626            switch ( $_k ) {
627                case 'request_headers':
628                    $this->normalize_array_target(
629                        // get the headers that came in with this request
630                        $this->meta( 'headers' ),
631                        // ensure only and exclude filters are normalized
632                        array_map( array( $this->request, 'normalize_header_name' ), $only ),
633                        array_map( array( $this->request, 'normalize_header_name' ), $except ),
634                        $k,
635                        $return,
636                        // flags
637                        $count_only
638                    );
639                    continue 2;
640                case 'request_headers_names':
641                    $this->normalize_array_target( $this->meta( 'headers_names' ), $only, $except, $k, $return, $count_only | self::NORMALIZE_ARRAY_MATCH_VALUES );
642                    continue 2;
643                case 'request_method':
644                case 'request_protocol':
645                case 'request_uri':
646                case 'request_uri_raw':
647                case 'request_filename':
648                case 'request_basename':
649                case 'request_body':
650                case 'query_string':
651                case 'request_line':
652                    $v = $this->meta( $_k );
653                    break;
654                case 'tx':
655                case 'ip':
656                    $this->normalize_array_target( $this->state_values( "$k." ), $only, $except, $k, $return, $count_only );
657                    continue 2;
658                case 'request_cookies':
659                case 'args':
660                case 'args_get':
661                case 'args_post':
662                case 'files':
663                    $this->normalize_array_target( $this->meta( $_k ), $only, $except, $k, $return, $count_only );
664                    continue 2;
665                case 'request_cookies_names':
666                case 'args_names':
667                case 'args_get_names':
668                case 'args_post_names':
669                case 'files_names':
670                    // get the "full" data (for 'args_names' get data for 'args') and stripe it down to just the key names
671                    $data = array_map(
672                        function ( $item ) {
673                            return $item[0]; },
674                        $this->meta( substr( $_k, 0, -6 ) )
675                    );
676                    $this->normalize_array_target( $data, $only, $except, $k, $return, $count_only | self::NORMALIZE_ARRAY_MATCH_VALUES );
677                    continue 2;
678                case 'matched_var':
679                    $this->normalize_array_target( $this->meta( $k ), $only, $except, $k, $return, $count_only );
680                    continue 2;
681
682                case 'matched_var_name':
683                    $this->normalize_array_target( $this->meta( $k ), $only, $except, $k, $return, $count_only | self::NORMALIZE_ARRAY_MATCH_VALUES );
684                    continue 2;
685
686                case 'matched_vars':
687                    $this->normalize_array_target( $this->meta( $k ), $only, $except, $k, $return, $count_only );
688                    continue 2;
689
690                case 'matched_vars_names':
691                    $this->normalize_array_target( $this->meta( $k ), $only, $except, $k, $return, $count_only | self::NORMALIZE_ARRAY_MATCH_VALUES );
692                    continue 2;
693
694                default:
695                    var_dump( 'Unknown target', $k, $v );
696                    exit( 0 );
697            }
698            $return[] = array(
699                'name'   => $k,
700                'value'  => $v,
701                'source' => $k,
702            );
703        }
704
705        return $return;
706    }
707
708    /**
709     * Reset matched vars after processing a rule.
710     *
711     * @return void
712     */
713    public function reset_matched_vars() {
714            $this->matched_vars       = array();
715            $this->matched_vars_names = array();
716            $this->matched_var        = '';
717            $this->matched_var_name   = '';
718            unset(
719                $this->metadata['matched_var'],
720                $this->metadata['matched_vars'],
721                $this->metadata['matched_vars_names'],
722                $this->metadata['matched_var_name']
723            );
724    }
725
726    /**
727     * Verifies if the IP from the current request is in an array.
728     *
729     * @param array $array Array of IP addresses to verify the request IP against.
730     * @return bool
731     */
732    public function is_ip_in_array( $array ) {
733        $real_ip      = $this->request->get_real_user_ip_address();
734        $array_length = count( $array );
735
736        for ( $i = 0; $i < $array_length; $i++ ) {
737            // Check if the IP matches a provided range or CIDR notation.
738            $range = strpos( $array[ $i ], '/' ) !== false ? array( $array[ $i ], null ) : explode( '-', $array[ $i ] );
739            if ( count( $range ) === 2 ) {
740                if ( IP_Utils::ip_address_is_in_range( $real_ip, $range[0], $range[1] ) ) {
741                    return true;
742                }
743                continue;
744            }
745
746            // Check if the IP is an exact match.
747            if ( $real_ip === $array[ $i ] ) {
748                return true;
749            }
750        }
751
752        return false;
753    }
754
755    /**
756     * Extract values from an associative array, potentially applying filters and/or counting results.
757     *
758     * @param array{0: string, 1: scalar}|scalar[] $source      The source assoc. array of values (i.e. $_GET, $_SERVER, etc.).
759     * @param string[]                             $only        Only include the values for these keys in the output.
760     * @param string[]                             $excl        Never include the values for these keys in the output.
761     * @param string                               $name        The name of this target (see https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual-(v3.x)#Variables).
762     * @param array                                $results     Array to add output values to, will be modified by this method.
763     * @param int                                  $flags       Any of the NORMALIZE_ARRAY_* constants defined at the top of the class.
764     */
765    private function normalize_array_target( $source, $only, $excl, $name, &$results, $flags = 0 ) {
766        $output   = array();
767        $has_only = isset( $only[0] );
768        $has_excl = isset( $excl[0] );
769
770        foreach ( $source as $source_key => $source_val ) {
771            if ( is_array( $source_val ) ) {
772                // if $source_val looks like a tuple from flatten_array(), then use the tuple as the key and value
773                $source_key = $source_val[0];
774                $source_val = $source_val[1];
775            }
776            $filter_match = ( $flags & self::NORMALIZE_ARRAY_MATCH_VALUES ) > 0 ? $source_val : $source_key;
777            // if this key is on the "exclude" list, skip it
778            if ( $has_excl && $this->key_matches( $filter_match, $excl ) ) {
779                continue;
780            }
781            // if this key isn't in our "only" list, then skip it
782            if ( $has_only && ! $this->key_matches( $filter_match, $only ) ) {
783                continue;
784            }
785            // otherwise add this key/value to our output
786            $output[] = array( $source_key, $source_val );
787        }
788
789        if ( ( $flags & self::NORMALIZE_ARRAY_COUNT ) > 0 ) {
790            // If we've been told to just count the values, then just count them.
791            $results[] = array(
792                'name'   => (string) $name,
793                'value'  => count( $output ),
794                'source' => '&' . $name,
795            );
796        } else {
797            foreach ( $output as list( $item_name, $item_value ) ) {
798                $results[] = array(
799                    'name'   => (string) $item_name,
800                    'value'  => $item_value,
801                    'source' => "$name:$item_name",
802                );
803            }
804        }
805
806        return $results;
807    }
808
809    /**
810     * Given an array of tuples - probably from flatten_array() - return a new array
811     * consisting of only the first value (the key name) from each tuple.
812     *
813     * @param array{0:string, 1:scalar}[] $flat_array An array of tuples.
814     * @return string[]
815     */
816    private function args_names( $flat_array ) {
817        $names = array_map(
818            function ( $tuple ) {
819                return $tuple[0];
820            },
821            $flat_array
822        );
823        return array_unique( $names );
824    }
825
826    /**
827     * Return whether or not a given $input key matches one of the given $patterns.
828     *
829     * @param string   $input    Key name to test against patterns.
830     * @param string[] $patterns Patterns to test key name with.
831     * @return bool
832     */
833    private function key_matches( $input, $patterns ) {
834        foreach ( $patterns as $p ) {
835            if ( '/' === $p[0] ) {
836                if ( 1 === preg_match( $p, $input ) ) {
837                    return true;
838                }
839            } elseif ( 0 === strcasecmp( $p, $input ) ) {
840                return true;
841            }
842        }
843
844        return false;
845    }
846
847    /**
848     * Sanitize output generated from the request that was blocked.
849     *
850     * @param string $output Output to sanitize.
851     */
852    public function sanitize_output( $output ) {
853        $url_decoded_output   = rawurldecode( $output );
854        $html_entities_output = htmlentities( $url_decoded_output, ENT_QUOTES, 'UTF-8' );
855        // @phpcs:disable Squiz.Strings.DoubleQuoteUsage.NotRequired
856        $escapers     = array( "\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c" );
857        $replacements = array( "\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b" );
858        // @phpcs:enable Squiz.Strings.DoubleQuoteUsage.NotRequired
859
860        return( str_replace( $escapers, $replacements, $html_entities_output ) );
861    }
862}