PluginProbe
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… / 3.0.0
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… v3.0.0
3.0.0 2.11.12 2.11.11 2.11.10 2.11.9 2.11.7 2.11.8 2.11.6 2.11.5 2.11.4 2.11.3 2.11.1 2.11.2 2.11.0 2.10.5 2.10.4 2.10.3 2.10.2 2.10.1 2.10.0 2.9.9 2.9.8 2.9.6 2.9.7 2.9.5 All 88 releases
← All changes | includes/class-file-integrity.php +1725 -63 2.11.43.0.0 View file →
@@ -125,8 +125,37 @@
125 125 */
126 126 const BASELINE_SWEEP_MIGRATION = 'network-sweep-done';
127 127
128 128 /**
129 + * Network option with the fingerprint of every block Vigilant itself wrote
130 + * into wp-config.php or the root .htaccess.
131 + *
132 + * The integrity scan leaves Vigilant's own blocks out of the hash, so that
133 + * rewriting them is not reported as somebody else's change. Until 2.11.5 it
134 + * left out whatever sat between the markers, without looking. From 2.11.5 a
135 + * block is left out only if its content is exactly what Vigilant wrote, as
136 + * recorded here at write time.
137 + *
138 + * @since 2.11.5
139 + */
140 + const OWNED_BLOCKS_OPTION = 'vigilante_owned_blocks';
141 +
142 + /**
143 + * Network option marking that the blocks already on disk have been claimed.
144 + *
145 + * @since 2.11.5
146 + */
147 + const OWNED_BLOCKS_CLAIM_OPTION = 'vigilante_owned_blocks_claim';
148 +
149 + /**
150 + * Value stored when the claim is done. Deliberately not a version number:
151 + * that is the lesson of BASELINE_SWEEP_MIGRATION above.
152 + *
153 + * @since 2.11.5
154 + */
155 + const OWNED_BLOCKS_CLAIMED = 'claimed';
156 +
157 + /**
129 158 * What replaces a secret value kept in the baseline.
130 159 *
131 160 * Fixed forever: if this string ever changes, every stored baseline
132 161 * suddenly differs from the freshly redacted file and every site reports a
@@ -136,13 +165,16 @@
136 165 */
137 166 const REDACTED_MARKER = '[redacted by Vigilant]';
138 167
139 168 /**
140 - * Constant names whose value never reaches the database.
169 + * Constant names whose value is checked even where the file does not name them
141 170 *
142 - * The eight WordPress keys and salts and the database credentials, plus
143 - * anything whose name reads like a credential, since a real wp-config.php
144 - * collects SMTP passwords, S3 keys and API tokens over the years.
171 + * The eight WordPress keys and salts and the database credentials. Until
172 + * 2.11.7 this list, plus names that read like a credential, was what got
173 + * redacted, and a real wp-config.php collects secrets under any name:
174 + * FTP_PASS, SMTP passwords, cloud keys inside serialize( array( ... ) ),
175 + * any const. Since 2.11.8 every value is redacted and this list only feeds
176 + * the output check of baseline_content().
145 177 *
146 178 * @since 2.11.2
147 179 *
148 180 * @var string[]
@@ -153,8 +185,36 @@
153 185 'AUTH_SALT', 'SECURE_AUTH_SALT', 'LOGGED_IN_SALT', 'NONCE_SALT',
154 186 );
155 187
156 188 /**
189 + * Core constants whose value stays readable in the baseline copy
190 + *
191 + * Where the site lives, where its folders are, how much memory it gets:
192 + * none of it is a secret and all of it is what a diff of wp-config.php is
193 + * read for. Every other value is redacted. A list of what is secret can
194 + * never be complete, which is how 2.11.2 to 2.11.7 missed FTP_PASS; a list
195 + * of what is not can be short and still be right.
196 + *
197 + * @since 2.11.8
198 + *
199 + * @var string[]
200 + */
201 + private static $readable_constants = array(
202 + 'ABSPATH', 'WPINC', 'WP_HOME', 'WP_SITEURL', 'WP_CONTENT_DIR', 'WP_CONTENT_URL',
203 + 'WP_PLUGIN_DIR', 'WP_PLUGIN_URL', 'WPMU_PLUGIN_DIR', 'WPMU_PLUGIN_URL', 'UPLOADS',
204 + 'WP_LANG_DIR', 'WP_TEMP_DIR', 'WP_DEBUG_LOG', 'WP_MEMORY_LIMIT', 'WP_MAX_MEMORY_LIMIT',
205 + 'WP_ENVIRONMENT_TYPE', 'WP_DEVELOPMENT_MODE', 'WP_AUTO_UPDATE_CORE', 'FS_METHOD',
206 + 'DB_CHARSET', 'DB_COLLATE', 'DOMAIN_CURRENT_SITE', 'PATH_CURRENT_SITE', 'NOBLOGREDIRECT',
207 + 'COOKIE_DOMAIN', 'COOKIEPATH', 'SITECOOKIEPATH', 'ADMIN_COOKIE_PATH', 'PLUGINS_COOKIE_PATH',
208 + 'WP_DEFAULT_THEME', 'WPLANG',
209 + // Numeric core settings. Since 2.11.10 a number in the value of a
210 + // define() is redacted like any other value, so the ones that are known
211 + // not to be credentials are listed here to keep the diff useful.
212 + 'AUTOSAVE_INTERVAL', 'WP_POST_REVISIONS', 'EMPTY_TRASH_DAYS', 'WP_CRON_LOCK_TIMEOUT',
213 + 'FS_CHMOD_DIR', 'FS_CHMOD_FILE', 'SITE_ID_CURRENT_SITE', 'BLOG_ID_CURRENT_SITE',
214 + );
215 +
216 + /**
157 217 * Read the critical files baseline, from where it belongs
158 218 *
159 219 * Both watched files, wp-config.php and the root .htaccess, belong to the
160 220 * whole network: there is one of each per installation, not one per site.
@@ -196,8 +256,112 @@
196 256 return update_site_option( self::BASELINE_OPTION, $baseline );
197 257 }
198 258
199 259 /**
260 + * Fingerprint of a block exactly as the integrity scan reads it back
261 + *
262 + * @since 2.11.5
263 + *
264 + * @param string $block Block from start marker to end marker, inclusive.
265 + * @return string
266 + */
267 + private static function block_fingerprint( $block ) {
268 + return md5( str_replace( array( "\r\n", "\r" ), "\n", (string) $block ) );
269 + }
270 +
271 + /**
272 + * Record a block Vigilant has just written
273 + *
274 + * Called by the writers right after a verified write, so the scan can tell
275 + * Vigilant's block from anything else carrying the same markers. By default
276 + * it replaces the earlier record for that marker: after a write, only the
277 + * block just written is Vigilant's.
278 + *
279 + * @since 2.11.5
280 + *
281 + * @param string $filename 'wp-config.php' or '.htaccess'.
282 + * @param string $marker_start Start marker of the block.
283 + * @param string $block Block from start marker to end marker, inclusive.
284 + * @param bool $replace Drop earlier records for the same marker first.
285 + * @return bool
286 + */
287 + public static function remember_owned_block( $filename, $marker_start, $block, $replace = true ) {
288 + $owned = get_site_option( self::OWNED_BLOCKS_OPTION, array() );
289 + $owned = is_array( $owned ) ? $owned : array();
290 + $file = ( isset( $owned[ $filename ] ) && is_array( $owned[ $filename ] ) ) ? $owned[ $filename ] : array();
291 +
292 + if ( $replace ) {
293 + foreach ( $file as $fingerprint => $marker ) {
294 + if ( $marker === $marker_start ) {
295 + unset( $file[ $fingerprint ] );
296 + }
297 + }
298 + }
299 +
300 + $file[ self::block_fingerprint( $block ) ] = $marker_start;
301 + $owned[ $filename ] = $file;
302 +
303 + return update_site_option( self::OWNED_BLOCKS_OPTION, $owned );
304 + }
305 +
306 + /**
307 + * Forget the blocks recorded for a marker, once Vigilant has removed them
308 + *
309 + * @since 2.11.5
310 + *
311 + * @param string $filename 'wp-config.php' or '.htaccess'.
312 + * @param string $marker_start Start marker of the block.
313 + * @return bool
314 + */
315 + public static function forget_owned_blocks( $filename, $marker_start ) {
316 + $owned = get_site_option( self::OWNED_BLOCKS_OPTION, array() );
317 +
318 + if ( ! is_array( $owned ) || empty( $owned[ $filename ] ) || ! is_array( $owned[ $filename ] ) ) {
319 + return true;
320 + }
321 +
322 + $changed = false;
323 +
324 + foreach ( $owned[ $filename ] as $fingerprint => $marker ) {
325 + if ( $marker === $marker_start ) {
326 + unset( $owned[ $filename ][ $fingerprint ] );
327 + $changed = true;
328 + }
329 + }
330 +
331 + return $changed ? update_site_option( self::OWNED_BLOCKS_OPTION, $owned ) : true;
332 + }
333 +
334 + /**
335 + * Whether a block is one Vigilant wrote
336 + *
337 + * @since 2.11.5
338 + *
339 + * @param string $filename 'wp-config.php' or '.htaccess'.
340 + * @param string $block Block from start marker to end marker, inclusive.
341 + * @return bool
342 + */
343 + private static function is_owned_block( $filename, $block ) {
344 + $owned = get_site_option( self::OWNED_BLOCKS_OPTION, array() );
345 +
346 + return is_array( $owned )
347 + && isset( $owned[ $filename ] )
348 + && is_array( $owned[ $filename ] )
349 + && isset( $owned[ $filename ][ self::block_fingerprint( $block ) ] );
350 + }
351 +
352 + /**
353 + * Whether the blocks already on disk have been claimed
354 + *
355 + * @since 2.11.5
356 + *
357 + * @return bool
358 + */
359 + private function owned_blocks_claimed() {
360 + return self::OWNED_BLOCKS_CLAIMED === get_site_option( self::OWNED_BLOCKS_CLAIM_OPTION );
361 + }
362 +
363 + /**
200 364 * The baseline copy of a critical file, with no secret in it
201 365 *
202 366 * The integrity scan keeps a copy of wp-config.php so it can show which
203 367 * lines changed. Until 2.11.1 that copy was the file itself minus the
@@ -217,35 +381,61 @@
217 381 * @param string $normalized Normalized content.
218 382 * @return string Content safe to store, or '' when it cannot be made safe.
219 383 */
220 384 private function baseline_content( $filename, $normalized ) {
385 + if ( '.htaccess' === $filename ) {
386 + return $this->redact_server_secrets( $normalized );
387 + }
388 +
221 389 if ( 'wp-config.php' !== $filename ) {
222 390 return $normalized;
223 391 }
224 392
225 - $redacted = $this->redact_secrets( $normalized );
393 + // Calculados una sola vez: los usa la redaccion (para no conservar un
394 + // numero que ademas este en vigor) y el control de salida de abajo.
395 + $live_values = $this->values_in_force( $normalized );
396 + $redacted = $this->redact_secrets( $normalized, $live_values );
226 397
227 398 /*
228 - * Belt and braces, and this is the part that matters: the regular
229 - * expression above is the thing most likely to miss a shape nobody
230 - * thought of, and the cost of missing one is a secret in the database.
231 - * So the result is checked against the values actually in force, and
232 - * if any of them survived, nothing is stored at all. The scan then
233 - * reports the change without a line diff, which the interface already
234 - * handles, instead of leaking.
399 + * Belt and braces, and this is the part that matters: the redaction
400 + * above is the thing most likely to miss a shape nobody thought of,
401 + * and the cost of missing one is a secret in the database. So the
402 + * result is checked against the values actually in force, and if any
403 + * of them survived, nothing is stored at all. The scan then reports the
404 + * change without a line diff, which the interface already handles,
405 + * instead of leaking.
235 406 *
407 + * Until 2.11.7 the check covered the twelve constants of WordPress and
408 + * nothing else, so a value the regular expression missed went straight
409 + * through it. It now covers every constant the file names and every
410 + * environment variable it reads.
411 + *
412 + * It runs against the copy that is actually stored. A value in force
413 + * that sits inside the value of a readable constant, such as a Redis
414 + * prefix equal to the domain inside WP_HOME, is not a secret left
415 + * behind, so that one alone is not looked for; without that, every such
416 + * site would lose its diff. The first version of this checked a
417 + * stricter copy instead, and a secret inside a kept include path went
418 + * straight past it (cross review of 2.11.8).
419 + *
236 420 * Only values of eight characters or more are checked: DB_NAME is
237 421 * often something like "local" or "wp", and looking for that inside a
238 422 * PHP file matches by accident every time.
239 423 */
240 - foreach ( self::$secret_constants as $name ) {
241 - if ( ! defined( $name ) ) {
242 - continue;
424 + if ( '' === $redacted ) {
425 + return '';
426 + }
427 +
428 + $shown = $this->readable_values_in_force();
429 +
430 + foreach ( $live_values as $value ) {
431 + foreach ( $shown as $readable ) {
432 + if ( false !== strpos( $readable, $value ) ) {
433 + continue 2;
434 + }
243 435 }
244 436
245 - $value = (string) constant( $name );
246 -
247 - if ( strlen( $value ) >= 8 && false !== strpos( $redacted, $value ) ) {
437 + if ( false !== strpos( $redacted, $value ) ) {
248 438 return '';
249 439 }
250 440 }
251 441
@@ -252,40 +442,523 @@
252 442 return $redacted;
253 443 }
254 444
255 445 /**
256 - * Replace the value of every credential-looking define with a marker
446 + * Replace every value in wp-config.php with a marker
257 447 *
258 - * Keeps the line and the constant name, so the diff still shows that a
259 - * credential line was touched, and drops only the value.
448 + * Reads the file as PHP tokens and replaces every string in it: quoted,
449 + * with variables inside, heredoc and nowdoc. What stays is what names a
450 + * thing rather than holding it: the name passed to define(), defined(),
451 + * constant() and getenv(), the name in putenv( 'NAME=value' ), array keys,
452 + * an index such as $_ENV['NAME'], and strings of a single character that
453 + * are not the value of a define(). Also the value of the constants in
454 + * $readable_constants, the table prefix and a path passed to require or
455 + * include, which are not secrets and are what a diff of this file is read
456 + * for. A path is kept only while it looks like one, and only up to where
457 + * its expression ends.
260 458 *
459 + * Until 2.11.7 this was a regular expression over define() with a list of
460 + * names, and it missed FTP_PASS, SMTP passwords, cloud keys inside
461 + * serialize( array( ... ) ), every const and every value read with a
462 + * fallback. Measured while preparing 2.11.8: 10 of 15 real shapes stored
463 + * their secret.
464 + *
465 + * The marker always goes in single quotes, whatever the original used, so
466 + * a copy redacted by an earlier version and the same file redacted today
467 + * read the same line for line.
468 + *
261 469 * @since 2.11.2
470 + * @since 2.11.8 Reads tokens and redacts every value.
262 471 *
263 472 * @param string $content Normalized wp-config.php content.
473 + * @return string Redacted content, or '' when it cannot be read as tokens.
474 + */
475 + private function redact_secrets( $content, $live_values = array() ) {
476 + if ( ! function_exists( 'token_get_all' ) ) {
477 + return '';
478 + }
479 +
480 + $marker = "'" . self::REDACTED_MARKER . "'";
481 + $tokens = self::merged_tokens( token_get_all( (string) $content ) );
482 + $count = count( $tokens );
483 + $names = defined( 'T_NAME_FULLY_QUALIFIED' ) ? array( T_STRING, T_NAME_FULLY_QUALIFIED ) : array( T_STRING );
484 + $includes = array( T_INCLUDE, T_INCLUDE_ONCE, T_REQUIRE, T_REQUIRE_ONCE );
485 + $out = '';
486 + $depth = 0;
487 + $keep_until = -1;
488 + $define_at = -1;
489 + $in_include = false;
490 + $include_depth = 0;
491 + $include_ends = array( T_CLOSE_TAG, T_BOOLEAN_OR, T_BOOLEAN_AND, T_LOGICAL_OR, T_LOGICAL_AND, T_COALESCE );
492 +
493 + for ( $i = 0; $i < $count; $i++ ) {
494 + list( $type, $text, $plain ) = $tokens[ $i ];
495 +
496 + if ( '(' === $type ) {
497 + $depth++;
498 + } elseif ( ')' === $type ) {
499 + // The closing parenthesis of a readable define(), or of any define().
500 + if ( $depth === $keep_until ) {
501 + $keep_until = -1;
502 + }
503 + if ( $depth === $define_at ) {
504 + $define_at = -1;
505 + }
506 + $depth--;
507 +
508 + // A parenthesis that closes around the include ends its path.
509 + if ( $in_include && $depth < $include_depth ) {
510 + $in_include = false;
511 + }
512 + } elseif ( in_array( $type, $includes, true ) ) {
513 + $in_include = true;
514 + $include_depth = $depth;
515 + } elseif ( $in_include && ( in_array( $type, array( ';', '{', '}', '?', ':', ',' ), true ) || in_array( $type, $include_ends, true ) ) ) {
516 + /*
517 + * The path of an include ends where its expression does. The
518 + * first version of this only ended it at ';', so the value in
519 + * `( include 'db.php' ) || define( 'FTP_PASS', '...' )`, in a
520 + * ternary after require, or after a closing tag, was kept.
521 + * Found by the cross review of 2.11.8.
522 + */
523 + $in_include = false;
524 + }
525 +
526 + if ( T_COMMENT === $type || T_DOC_COMMENT === $type ) {
527 + $out .= $this->redact_comment( $text );
528 + continue;
529 + }
530 +
531 + if ( T_INLINE_HTML === $type ) {
532 + $out .= ( '' === trim( $text ) ) ? $text : $marker;
533 + continue;
534 + }
535 +
536 + /*
537 + * A value that is not a quoted string is still a value. Until
538 + * 2.11.10 only string tokens were looked at, so
539 + * define( 'SERVICE_TOKEN', 12345678 ) put the live token in the copy
540 + * kept in the database. Reported by the wp.org automated review of
541 + * 2.11.9.
542 + *
543 + * The first fix here redacted a number only in the value position of
544 + * a define(), which is the shape that was reported and not the shape
545 + * of the problem. The second cross review of 2.11.10 measured nine
546 + * more: a negative number, one in parentheses, one inside
547 + * array( ... ), one in a ternary, a const, and four that are not
548 + * constants at all and so the output check cannot catch either, the
549 + * worst of them the documented way of configuring Redis,
550 + * $redis_server = array( 'auth' => 12345678 ). So a number is now
551 + * treated like a string: redacted unless the place it sits in is one
552 + * of the few that cannot hold a credential, which is how the rest of
553 + * this function has been written since 2.11.8 (a list of what may be
554 + * shown, never a list of what is secret).
555 + *
556 + * Losing a number from the diff costs little and buys the same trade
557 + * as everywhere else: the hash still covers the whole file, so a
558 + * change is detected even where the diff can no longer show it. The
559 + * numeric core settings are in $readable_constants so the diff of a
560 + * normal wp-config.php keeps saying what it used to.
561 + */
562 + if ( T_LNUMBER === $type || T_DNUMBER === $type ) {
563 + $nprev = self::significant_token( $tokens, $i, -1 );
564 + $nnext = self::significant_token( $tokens, $i, 1 );
565 + $nptype = ( null === $nprev ) ? null : $tokens[ $nprev ][0];
566 + $nntype = ( null === $nnext ) ? null : $tokens[ $nnext ][0];
567 + $nbefore = ( '[' === $nptype ) ? self::significant_token( $tokens, $nprev, -1 ) : null;
568 + $nbtoken = ( null === $nbefore ) ? array( null, null ) : $tokens[ $nbefore ];
569 + $nvalue = ( -1 !== $define_at && $depth === $define_at && ',' === $nptype );
570 +
571 + $nkeep = $keep_until >= 0
572 + || T_DOUBLE_ARROW === $nntype
573 + || ( '[' === $nptype && ']' === $nntype && in_array( $nbtoken[0], array( T_VARIABLE, T_STRING, ']', ')', '}' ), true ) )
574 + || ( strlen( $text ) <= 1 && ! $nvalue );
575 +
576 + /*
577 + * Except when that same number is a value actually in force. The
578 + * positions kept above are kept because a credential does not live
579 + * in them, which is true, but it says nothing about the number
580 + * itself: with
581 + * define( 'SERVICE_TOKEN', 12345678 );
582 + * $a = $config[12345678];
583 + * the value was redacted in the define and kept in the index, so it
584 + * survived, and the output check below did what it is there for and
585 + * threw the whole copy away. No leak, but the diff of that
586 + * wp-config.php was lost for good, which is the regression 2.11.8
587 + * fixed, coming back through the numbers added in 2.11.10. Found by
588 + * the third cross review.
589 + *
590 + * Strings are deliberately NOT treated this way: there, a value in
591 + * force sitting in a kept position (an include path, an array key)
592 + * can BE the secret, and losing the diff is the right answer. It is
593 + * what poc/wpconfig-baseline-secretos.sh checks and it stays.
594 + */
595 + if ( $nkeep && in_array( $text, $live_values, true ) ) {
596 + $nkeep = false;
597 + }
598 +
599 + $out .= $nkeep ? $text : $marker;
600 + continue;
601 + }
602 +
603 + if ( 'string' !== $type ) {
604 + $out .= $text;
605 + continue;
606 + }
607 +
608 + $prev = self::significant_token( $tokens, $i, -1 );
609 + $next = self::significant_token( $tokens, $i, 1 );
610 + $ptype = ( null === $prev ) ? null : $tokens[ $prev ][0];
611 + $ntype = ( null === $next ) ? null : $tokens[ $next ][0];
612 + $call = ( '(' === $ptype ) ? self::significant_token( $tokens, $prev, -1 ) : null;
613 + $inner = $plain ? substr( $text, 1, -1 ) : null;
614 +
615 + if ( $plain && null !== $call && in_array( $tokens[ $call ][0], $names, true ) ) {
616 + $function = strtolower( ltrim( $tokens[ $call ][1], '\\' ) );
617 +
618 + if ( in_array( $function, array( 'define', 'defined', 'constant', 'getenv' ), true ) ) {
619 + if ( 'define' === $function ) {
620 + $define_at = $depth;
621 +
622 + if ( in_array( $inner, self::$readable_constants, true ) ) {
623 + $keep_until = $depth;
624 + }
625 + }
626 + $out .= $text;
627 + continue;
628 + }
629 +
630 + if ( 'putenv' === $function && false !== strpos( $inner, '=' ) ) {
631 + $out .= "'" . substr( $inner, 0, strpos( $inner, '=' ) + 1 ) . self::REDACTED_MARKER . "'";
632 + continue;
633 + }
634 + }
635 +
636 + // The token before an opening bracket or an assignment, when there is one.
637 + $before = ( '[' === $ptype || '=' === $ptype ) ? self::significant_token( $tokens, $prev, -1 ) : null;
638 + $btoken = ( null === $before ) ? array( null, null ) : $tokens[ $before ];
639 +
640 + /*
641 + * The value of a define() is redacted whatever its length, as it was
642 + * up to 2.11.7, so an empty password reads the same in a copy stored
643 + * then as in today's; the first version of this kept strings of one
644 + * character there and a file awaiting review showed credential lines
645 + * nobody had touched (cross review of 2.11.8).
646 + */
647 + $is_define_value = ( -1 !== $define_at && $depth === $define_at && ',' === $ptype );
648 + $is_path = $in_include && $plain
649 + && preg_match( '#^[A-Za-z0-9_./\-]+$#', (string) $inner )
650 + && ( false !== strpos( (string) $inner, '/' ) || '.php' === substr( (string) $inner, -4 ) );
651 +
652 + $keep = ( $plain && strlen( $inner ) <= 1 && ! $is_define_value )
653 + || T_DOUBLE_ARROW === $ntype
654 + || ( '[' === $ptype && ']' === $ntype && in_array( $btoken[0], array( T_VARIABLE, T_STRING, ']', ')', '}' ), true ) )
655 + || $keep_until >= 0
656 + || $is_path
657 + || ( '=' === $ptype && ';' === $ntype && T_VARIABLE === $btoken[0] && '$table_prefix' === $btoken[1] );
658 +
659 + $out .= $keep ? $text : $marker;
660 + }
661 +
662 + return $out;
663 + }
664 +
665 + /**
666 + * PHP tokens with every string folded into a single token
667 + *
668 + * The tokenizer splits a string with variables inside, a heredoc and a
669 + * backtick command into several tokens. For the redaction each of them is
670 + * one value, so they come back as a single token of type 'string'. The
671 + * third field says whether it is a plain quoted literal.
672 + *
673 + * @since 2.11.8
674 + *
675 + * @param array $raw Output of token_get_all().
676 + * @return array List of array( type, text, plain ).
677 + */
678 + private static function merged_tokens( $raw ) {
679 + $tokens = array();
680 + $count = count( $raw );
681 +
682 + for ( $i = 0; $i < $count; $i++ ) {
683 + $token = $raw[ $i ];
684 +
685 + if ( '"' === $token || '`' === $token ) {
686 + $text = $token;
687 + for ( $i++; $i < $count; $i++ ) {
688 + $text .= is_array( $raw[ $i ] ) ? $raw[ $i ][1] : $raw[ $i ];
689 + if ( $raw[ $i ] === $token ) {
690 + break;
691 + }
692 + }
693 + $tokens[] = array( 'string', $text, false );
694 + continue;
695 + }
696 +
697 + if ( is_array( $token ) && T_START_HEREDOC === $token[0] ) {
698 + $text = $token[1];
699 + for ( $i++; $i < $count; $i++ ) {
700 + $text .= is_array( $raw[ $i ] ) ? $raw[ $i ][1] : $raw[ $i ];
701 + if ( is_array( $raw[ $i ] ) && T_END_HEREDOC === $raw[ $i ][0] ) {
702 + break;
703 + }
704 + }
705 + $tokens[] = array( 'string', $text, false );
706 + continue;
707 + }
708 +
709 + // An unterminated string comes back as T_ENCAPSED_AND_WHITESPACE
710 + // on its own, and it is a value like any other.
711 + if ( is_array( $token ) && ( T_CONSTANT_ENCAPSED_STRING === $token[0] || T_ENCAPSED_AND_WHITESPACE === $token[0] ) ) {
712 + $tokens[] = array( 'string', $token[1], T_CONSTANT_ENCAPSED_STRING === $token[0] );
713 + continue;
714 + }
715 +
716 + $tokens[] = is_array( $token ) ? array( $token[0], $token[1], false ) : array( $token, $token, false );
717 + }
718 +
719 + return $tokens;
720 + }
721 +
722 + /**
723 + * Index of the nearest token that is not whitespace or a comment
724 + *
725 + * @since 2.11.8
726 + *
727 + * @param array $tokens Output of merged_tokens().
728 + * @param int $from Index to start from, not included.
729 + * @param int $step -1 to look back, 1 to look ahead.
730 + * @return int|null
731 + */
732 + private static function significant_token( $tokens, $from, $step ) {
733 + $count = count( $tokens );
734 +
735 + for ( $i = $from + $step; $i >= 0 && $i < $count; $i += $step ) {
736 + if ( ! in_array( $tokens[ $i ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) {
737 + return $i;
738 + }
739 + }
740 +
741 + return null;
742 + }
743 +
744 + /**
745 + * Redact a comment, keeping its plain words
746 + *
747 + * To the tokenizer a comment is text, and wp-config.php files keep old
748 + * credentials in them, commented out or in a note. The first version of
749 + * this, in the same release, redacted what was between quotes: an
750 + * apostrophe in prose ("Don't use 'the-old-password'") paired with the
751 + * opening quote of the secret and left it out, and a secret without quotes
752 + * was never touched. Found by the cross review of 2.11.8.
753 + *
754 + * So it works the other way round. A comment keeps its plain words
755 + * (lowercase, capitalised or uppercase letters, or two capitalised parts
756 + * such as WordPress, and docblock tags), constant names, and anything
757 + * shorter than eight characters; every other run of characters, a URL, a
758 + * key, a password with a digit in it, becomes the marker. The value of a
759 + * commented-out define() goes in single quotes whatever its length, as in
760 + * code and as 2.11.2 to 2.11.7 wrote it, so a copy stored by those
761 + * versions reads the same line for line. What this cannot tell from prose
762 + * is a password made only of plain letters; the output check still
763 + * catches it when it is a value in force.
764 + *
765 + * @since 2.11.8
766 + *
767 + * @param string $comment Comment token text.
264 768 * @return string
265 769 */
266 - private function redact_secrets( $content ) {
267 - $names = implode( '|', array_map( 'preg_quote', self::$secret_constants ) );
770 + private function redact_comment( $comment ) {
771 + $marker = self::REDACTED_MARKER;
772 + $readable = self::$readable_constants;
268 773
774 + // Only the text between the delimiters is redacted: "/**#@-*/" in
775 + // wp-config-sample.php is a single run of eight characters, and
776 + // replacing it whole took the comment markers with it.
777 + if ( ! preg_match( '#\A(/\*\*?|//|\#)(.*?)(\*/)?\z#s', $comment, $parts ) ) {
778 + $parts = array( $comment, '', $comment );
779 + }
780 +
781 + $open = $parts[1];
782 + $close = isset( $parts[3] ) ? $parts[3] : '';
783 + $comment = preg_replace_callback(
784 + '/(\bdefine\s*\(\s*([\'"])((?:\\\\.|(?!\2).)*)\2\s*,\s*)([\'"])((?:\\\\.|(?!\4).)*)\4/i',
785 + function ( $match ) use ( $marker, $readable ) {
786 + return in_array( $match[3], $readable, true ) ? $match[0] : $match[1] . "'" . $marker . "'";
787 + },
788 + $parts[2]
789 + );
790 +
791 + if ( null === $comment ) {
792 + return '';
793 + }
794 +
795 + $redacted = preg_replace_callback(
796 + '/[^\s\'"`(),;\[\]{}<>=]+/u',
797 + function ( $match ) use ( $marker ) {
798 + $word = $match[0];
799 + $core = rtrim( $word, '.:!?' );
800 +
801 + // Plain words only, without hyphens: a passphrase written as
802 + // lowercase words joined by hyphens reads as prose otherwise, and
803 + // the PoC of this very fix caught one surviving.
804 + if ( strlen( $core ) < 8
805 + || preg_match( '/^@?(?:\p{Lu}?\p{Ll}+|\p{Lu}+)$/u', $core )
806 + || preg_match( '/^\p{Lu}\p{Ll}+\p{Lu}\p{Ll}+$/u', $core )
807 + || preg_match( '/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/', $core )
808 + ) {
809 + return $word;
810 + }
811 +
812 + return $marker . substr( $word, strlen( $core ) );
813 + },
814 + $comment
815 + );
816 +
817 + // A failed replacement, on invalid UTF-8 for one, drops the comment
818 + // rather than keep it whole.
819 + return ( null === $redacted ) ? '' : $open . $redacted . $close;
820 + }
821 +
822 + /**
823 + * Values in force of what a wp-config.php names
824 + *
825 + * Every user constant whose name appears in the file, the twelve of
826 + * WordPress wherever they were defined, and the environment variables the
827 + * file reads or sets. Arrays are walked to their leaves, since define()
828 + * takes arrays. Strings and numbers both: the first version of this counted
829 + * numbers and wiped the diff of any file with a large number in force (cross
830 + * review of 2.11.8), so they were dropped, and 2.11.10 had to bring them
831 + * back because a credential written as a number, which the wp.org review of
832 + * 2.11.9 reported, is exactly what this check has to be able to see. The
833 + * eight character floor is what keeps the old problem away. The readable
834 + * constants are left out, and so is anything shorter than that.
835 + *
836 + * @since 2.11.8
837 + *
838 + * @param string $content Normalized wp-config.php content.
839 + * @return string[]
840 + */
841 + private function values_in_force( $content ) {
842 + $defined = get_defined_constants( true );
843 + $user = isset( $defined['user'] ) ? $defined['user'] : array();
844 + $names = self::$secret_constants;
845 + $values = array();
846 +
847 + if ( preg_match_all( '/[A-Za-z_][A-Za-z0-9_]*/', (string) $content, $words ) ) {
848 + $names = array_merge( $names, $words[0] );
849 + }
850 +
851 + foreach ( array_unique( $names ) as $name ) {
852 + if ( array_key_exists( $name, $user ) && ! in_array( $name, self::$readable_constants, true ) ) {
853 + $values = array_merge( $values, self::string_leaves( $user[ $name ] ) );
854 + }
855 + }
856 +
857 + if ( preg_match_all( '/\b(?:getenv|putenv)\s*\(\s*[\'"]([A-Za-z_][A-Za-z0-9_]*)|\$_ENV\s*\[\s*[\'"]([A-Za-z_][A-Za-z0-9_]*)/', (string) $content, $env ) ) {
858 + foreach ( array_filter( array_merge( $env[1], $env[2] ) ) as $name ) {
859 + $value = getenv( $name );
860 +
861 + if ( is_string( $value ) ) {
862 + $values[] = $value;
863 + }
864 + }
865 + }
866 +
867 + $long = array();
868 +
869 + foreach ( $values as $value ) {
870 + if ( strlen( $value ) >= 8 ) {
871 + $long[ $value ] = $value;
872 + }
873 + }
874 +
875 + return array_values( $long );
876 + }
877 +
878 + /**
879 + * Every string inside a constant value
880 + *
881 + * @since 2.11.8
882 + *
883 + * @param mixed $value Constant value.
884 + * @return string[]
885 + */
886 + private static function string_leaves( $value ) {
887 + if ( is_array( $value ) ) {
888 + $leaves = array();
889 +
890 + foreach ( $value as $item ) {
891 + $leaves = array_merge( $leaves, self::string_leaves( $item ) );
892 + }
893 +
894 + return $leaves;
895 + }
896 +
897 + if ( is_string( $value ) ) {
898 + return array( $value );
899 + }
900 +
269 901 /*
270 - * define( 'NAME', 'value' ), matching the quoted literal itself rather
271 - * than reading up to the closing parenthesis.
272 - *
273 - * The first version of this stopped at the first ';', which looked
274 - * reasonable and failed on the very first real file it saw: the salts
275 - * WordPress generates are full of punctuation and a ';' inside one cut
276 - * the match short, so nothing was redacted. Backreference 3 is the
277 - * opening quote and the value runs to its unescaped twin. No /s
278 - * modifier on purpose, so a file with an unterminated string breaks
279 - * one line instead of swallowing the rest of the file.
902 + * A number is a value too. Until 2.11.10 this returned nothing for one,
903 + * so the output check had no way to see a credential written as
904 + * define( 'SERVICE_TOKEN', 12345678 ) and the redaction was left without
905 + * its safety net there. Booleans and null stay out on purpose: as text
906 + * they are '1' and '', which would match half the file.
280 907 */
281 - $pattern = '/(define\s*\(\s*([\'"])(?:' . $names . '|[A-Z0-9_]*(?:KEY|SALT|SECRET|PASSWORD|PASSWD|TOKEN|API)[A-Z0-9_]*)\2\s*,\s*)([\'"])(?:\\\\.|(?!\3).)*\3/i';
908 + return ( is_int( $value ) || is_float( $value ) ) ? array( (string) $value ) : array();
909 + }
282 910
283 - $redacted = preg_replace( $pattern, '${1}\'' . self::REDACTED_MARKER . '\'', $content );
911 + /**
912 + * Values in force of the readable constants, the ones kept in the copy
913 + *
914 + * @since 2.11.8
915 + *
916 + * @return string[]
917 + */
918 + private function readable_values_in_force() {
919 + $values = array();
284 920
285 - // A failed preg_replace returns null, and storing null would wipe the
286 - // baseline copy silently. Falling back to the original is not an
287 - // option either, so the caller's guard turns this into "no content".
921 + foreach ( self::$readable_constants as $name ) {
922 + if ( defined( $name ) ) {
923 + $values = array_merge( $values, self::string_leaves( constant( $name ) ) );
924 + }
925 + }
926 +
927 + return $values;
928 + }
929 +
930 + /**
931 + * Replace the values a root .htaccess can carry as credentials
932 + *
933 + * The .htaccess is not a secrets file, but it can hold a few: an
934 + * environment variable handed to PHP with SetEnv, an Authorization header
935 + * set for a backend, or a php_value with a password, a key, a licence or a
936 + * session store address with its auth in it. The directive and its name
937 + * stay, the value goes. Line based, which is how Apache reads it too. Since
938 + * the cross review of 2.11.8 also any request or response header whose name
939 + * reads like a credential (X-Api-Key, a cookie, a signature) and a
940 + * RewriteCond that compares against key=, token= or the like, the way a
941 + * staging site is opened with a secret in the query string. What it cannot
942 + * see is a credential written in any other shape.
943 + *
944 + * @since 2.11.8
945 + *
946 + * @param string $content Normalized .htaccess content.
947 + * @return string
948 + */
949 + private function redact_server_secrets( $content ) {
950 + $redacted = preg_replace(
951 + array(
952 + '/^([ \t]*SetEnv[ \t]+\S+[ \t]+)\S.*$/mi',
953 + '/^([ \t]*(?:RequestHeader|Header)[ \t]+(?:always[ \t]+)?\S+[ \t]+[\w-]*(?:auth|key|token|secret|pass|cookie|sig)[\w-]*[ \t]+)\S.*$/mi',
954 + '/^([ \t]*php_(?:admin_)?value[ \t]+\S*(?:pass|pw|secret|key|token|licen|auth|save_path)\S*[ \t]+)\S.*$/mi',
955 + '/^([ \t]*RewriteCond[ \t]+\S+[ \t]+)\S*(?:key|token|secret|pass|auth|sig)[\w-]*=\S*/mi',
956 + ),
957 + '${1}' . self::REDACTED_MARKER,
958 + (string) $content
959 + );
960 +
288 961 return ( null === $redacted ) ? '' : $redacted;
289 962 }
290 963
291 964 /**
@@ -484,8 +1157,150 @@
484 1157 }
485 1158 }
486 1159
487 1160 /**
1161 + * Network option recording the version whose results cleanup walked the network
1162 + *
1163 + * @since 2.11.8
1164 + */
1165 + const RESULTS_SWEEP_OPTION = 'vigilante_results_sweep';
1166 +
1167 + /**
1168 + * Clean the stored scan results of every site of the network, once per version
1169 + *
1170 + * redact_stored_results() runs per site from admin_init and from the scan,
1171 + * so a subsite with the module off whose dashboard nobody opens kept the
1172 + * lines of wp-config.php its last scan stored, with whatever that version
1173 + * failed to redact. Same gap 2.11.3 and 2.11.4 closed for the baseline copy;
1174 + * found for the results by the cross review of 2.11.8. It runs from the
1175 + * network sweep, for a network administrator on the main site, and has its
1176 + * own marker because the baseline sweep is already done on every network
1177 + * that updated through 2.11.4.
1178 + *
1179 + * @since 2.11.8
1180 + */
1181 + private function maybe_sweep_network_results() {
1182 + if ( VIGILANTE_VERSION === get_site_option( self::RESULTS_SWEEP_OPTION ) ) {
1183 + return;
1184 + }
1185 +
1186 + update_site_option( self::RESULTS_SWEEP_OPTION, VIGILANTE_VERSION );
1187 +
1188 + $site_ids = get_sites(
1189 + array(
1190 + 'fields' => 'ids',
1191 + 'number' => 0,
1192 + 'network_id' => get_current_network_id(),
1193 + 'update_site_meta_cache' => false,
1194 + )
1195 + );
1196 +
1197 + foreach ( $site_ids as $site_id ) {
1198 + switch_to_blog( $site_id );
1199 + $this->redact_stored_results();
1200 + restore_current_blog();
1201 + }
1202 + }
1203 +
1204 + /**
1205 + * The diff of a shared file as a site that does not own it gets it
1206 + *
1207 + * No lines, and a flag the screens read to say where the lines are.
1208 + *
1209 + * @since 2.11.8
1210 + *
1211 + * @return array
1212 + */
1213 + public static function network_only_diff() {
1214 + return array(
1215 + 'added' => array(),
1216 + 'removed' => array(),
1217 + 'unavailable' => true,
1218 + 'network' => true,
1219 + );
1220 + }
1221 +
1222 + /**
1223 + * Take out of the last stored scan what the baseline copy no longer keeps
1224 + *
1225 + * The results of the last scan are an option of each site, and the diff of
1226 + * a critical file travels inside them line by line, redacted the way the
1227 + * version that ran the scan redacted. Until 2.11.7 that let FTP_PASS and
1228 + * friends through, and on a network every subsite with the module on kept
1229 + * its own copy of the lines. This runs once per version with the rest of
1230 + * the cleanup:
1231 + *
1232 + * - Where the shared files do not belong to this site, no line is kept.
1233 + * - Lines of wp-config.php are dropped. A single line cannot be read as
1234 + * PHP reliably (half a heredoc is just words), and the next scan rebuilds
1235 + * them from the whole file.
1236 + * - Lines of .htaccess are directives, one per line, and are redacted in
1237 + * place.
1238 + *
1239 + * @since 2.11.8
1240 + */
1241 + private function redact_stored_results() {
1242 + $results = get_option( 'vigilante_last_integrity_results' );
1243 +
1244 + if ( ! is_array( $results ) || empty( $results['modified'] ) || ! is_array( $results['modified'] ) ) {
1245 + return;
1246 + }
1247 +
1248 + $owns = Vigilante_Settings::owns_shared_files();
1249 + $changed = false;
1250 +
1251 + foreach ( $results['modified'] as $index => $item ) {
1252 + if ( ! is_array( $item ) || 'critical_config' !== ( $item['type'] ?? '' ) || ! isset( $item['diff'] ) || ! is_array( $item['diff'] ) ) {
1253 + continue;
1254 + }
1255 +
1256 + if ( ! $owns ) {
1257 + if ( empty( $item['diff']['network'] ) ) {
1258 + $results['modified'][ $index ]['diff'] = self::network_only_diff();
1259 + $changed = true;
1260 + }
1261 + continue;
1262 + }
1263 +
1264 + if ( 'wp-config.php' === ( $item['file'] ?? '' ) ) {
1265 + if ( ! empty( $item['diff']['added'] ) || ! empty( $item['diff']['removed'] ) ) {
1266 + $results['modified'][ $index ]['diff'] = array(
1267 + 'added' => array(),
1268 + 'removed' => array(),
1269 + 'unavailable' => true,
1270 + 'rescan' => true,
1271 + );
1272 + $changed = true;
1273 + }
1274 + continue;
1275 + }
1276 +
1277 + foreach ( array( 'added', 'removed' ) as $side ) {
1278 + if ( empty( $item['diff'][ $side ] ) || ! is_array( $item['diff'][ $side ] ) ) {
1279 + continue;
1280 + }
1281 +
1282 + foreach ( $item['diff'][ $side ] as $line_index => $line ) {
1283 + if ( ! is_array( $line ) || ! isset( $line['content'] ) || ! is_string( $line['content'] ) ) {
1284 + continue;
1285 + }
1286 +
1287 + $safe = $this->redact_server_secrets( $line['content'] );
1288 +
1289 + if ( $safe !== $line['content'] ) {
1290 + $results['modified'][ $index ]['diff'][ $side ][ $line_index ]['content'] = $safe;
1291 + $changed = true;
1292 + }
1293 + }
1294 + }
1295 + }
1296 +
1297 + if ( $changed ) {
1298 + update_option( 'vigilante_last_integrity_results', $results );
1299 + }
1300 + }
1301 +
1302 + /**
488 1303 * Clean up what earlier versions stored, wherever they stored it
489 1304 *
490 1305 * Two jobs, and the second one only exists on a network.
491 1306 *
@@ -562,8 +1377,10 @@
562 1377 $this->write_baseline( $baseline );
563 1378 }
564 1379 }
565 1380
1381 + $this->redact_stored_results();
1382 +
566 1383 /*
567 1384 * The gate does not close while a per-site copy is still waiting to be
568 1385 * promoted. Closing it would end the retries for a whole version: the
569 1386 * copy would sit there unread, the file it records would be missing
@@ -617,8 +1434,10 @@
617 1434 if ( ! current_user_can( 'manage_network_options' ) ) {
618 1435 return;
619 1436 }
620 1437
1438 + $this->maybe_sweep_network_results();
1439 +
621 1440 $marker = get_site_option( self::BASELINE_SWEEP_OPTION );
622 1441
623 1442 /*
624 1443 * Two markers, because there are two different things to remember and
@@ -879,8 +1698,9 @@
879 1698 */
880 1699 public function init_cleanup_hooks() {
881 1700 add_action( 'admin_init', array( $this, 'maybe_redact_stored_baseline' ) );
882 1701 add_action( 'admin_init', array( $this, 'maybe_sweep_network_baselines' ) );
1702 + add_action( 'admin_init', array( $this, 'maybe_claim_owned_blocks_on_admin' ) );
883 1703 }
884 1704
885 1705 /**
886 1706 * Check if scan time limit has been exceeded
@@ -951,8 +1771,16 @@
951 1771 $files = array( $hook_extra['plugin'] );
952 1772 }
953 1773 foreach ( $files as $file ) {
954 1774 $slug = dirname( (string) $file );
1775 + // Vigilant itself is verified immediately (not after 90 s) by
1776 + // Vigilante_Self_Integrity::handle_upgrader() when the
1777 + // self-check is on; do not also open a grace window for it.
1778 + // Compared with the folder it really lives in, not the literal
1779 + // slug, so a renamed folder is skipped the same way.
1780 + if ( dirname( VIGILANTE_PLUGIN_BASENAME ) === $slug && Vigilante_Self_Integrity::is_on() ) {
1781 + continue;
1782 + }
955 1783 if ( '.' !== $slug && '' !== $slug ) {
956 1784 $targets['plugin'][] = $slug;
957 1785 }
958 1786 }
@@ -1021,8 +1849,17 @@
1021 1849 */
1022 1850 private function verify_updated_slug( $type, $slug ) {
1023 1851 $grace_key = 'vigilante_fi_grace_' . $type . '_' . md5( $slug );
1024 1852
1853 + // Defensive skip for the first 2.11.x -> 3.0.x update: the OLD code in
1854 + // memory scheduled this event including Vigilant's own slug, and by the
1855 + // time it fires the NEW code (this one) is running with the self-check
1856 + // handling Vigilant on its own.
1857 + if ( 'plugin' === $type && dirname( VIGILANTE_PLUGIN_BASENAME ) === $slug && Vigilante_Self_Integrity::is_on() ) {
1858 + delete_transient( $grace_key );
1859 + return;
1860 + }
1861 +
1025 1862 if ( 'plugin' === $type ) {
1026 1863 if ( ! function_exists( 'get_plugins' ) ) {
1027 1864 require_once ABSPATH . 'wp-admin/includes/plugin.php';
1028 1865 }
@@ -1173,8 +2010,41 @@
1173 2010
1174 2011 // Use settings from options page
1175 2012 $options = is_array( $this->options ) ? $this->options : array();
1176 2013
2014 + // Vigilant self-check runs FIRST and exempt from the time budget:
2015 + // ~60 small-file hashes cost < 50 ms and the guardian must never be
2016 + // dropped by the budget on plugin-heavy sites. User exclusions do not
2017 + // apply to it (see Vigilante_Self_Integrity::run_check()).
2018 + if ( ! class_exists( 'Vigilante_Self_Integrity' ) ) {
2019 + require_once VIGILANTE_INCLUDES_DIR . 'class-self-integrity.php';
2020 + }
2021 + if ( Vigilante_Self_Integrity::is_on() ) {
2022 + if ( ! class_exists( 'Vigilante_Self_Integrity' ) ) {
2023 + require_once VIGILANTE_INCLUDES_DIR . 'class-self-integrity.php';
2024 + }
2025 + $self = new Vigilante_Self_Integrity( $this->settings, $this->activity_log );
2026 + $self_result = $self->run_check( 'scan' );
2027 + // run_check() above updates this site's own state (status line and
2028 + // the analyzer check keep working everywhere). The plugin files are
2029 + // shared by the whole installation, so the self findings are folded
2030 + // Self-protection has its own alert, and it does not travel in the
2031 + // scan digest any more. That digest is governed by a notification
2032 + // setting that can be switched off, and switching off "tell me about
2033 + // changed files" was also switching off the alarm of the plugin
2034 + // itself. So the findings stay out of the scan results (they have
2035 + // their own block in File Integrity, with what each one means and how
2036 + // to repair it) and a critical one sends its own email from here,
2037 + // wherever the scan runs. maybe_send_self_alert() keeps it to the
2038 + // site that owns the shared files and dedupes by set of findings.
2039 + foreach ( (array) $self_result['findings'] as $self_finding ) {
2040 + if ( 'critical' === ( $self_finding['severity'] ?? '' ) ) {
2041 + $self->maybe_send_self_alert( $self_result['findings'], 'scan' );
2042 + break;
2043 + }
2044 + }
2045 + }
2046 +
1177 2047 // Scan uploads for suspicious files FIRST (highest security priority)
1178 2048 // PHP files in uploads are almost always malware
1179 2049 if ( ! empty( $options['scan_uploads'] ) && ! $this->is_time_exceeded() ) {
1180 2050 $upload_results = $this->scan_uploads();
@@ -1579,8 +2449,51 @@
1579 2449 * silently — there is nothing to compare against.
1580 2450 *
1581 2451 * @return array Array of modified file entries (same format as core modified).
1582 2452 */
2453 + /**
2454 + * Where a critical root file actually lives
2455 + *
2456 + * WordPress supports wp-config.php one directory above ABSPATH, guarded by
2457 + * wp-settings.php not being there: that is literally what the installed core
2458 + * does in wp-load.php, and it is a common hardening layout. Until 2.11.10
2459 + * this module only looked inside ABSPATH, so on those installations
2460 + * wp-config.php was never added to the baseline, never compared and never
2461 + * mentioned: the module reported the site clean without having opened the
2462 + * one file it most needs to watch. A zero is justified, never assumed. The
2463 + * plugin already resolved both locations elsewhere
2464 + * (Vigilante_Database_Prefix::find_wpconfig_path()), just not here. Found by
2465 + * the file-by-file review of 2.11.10.
2466 + *
2467 + * @since 2.11.10
2468 + *
2469 + * @param string $filename Name of the file, such as wp-config.php.
2470 + * @return string|false Absolute path, or false when it cannot be found.
2471 + */
2472 + private function critical_file_path( $filename ) {
2473 + $root = untrailingslashit( ABSPATH );
2474 + $path = $root . '/' . $filename;
2475 +
2476 + if ( file_exists( $path ) ) {
2477 + return $path;
2478 + }
2479 +
2480 + if ( 'wp-config.php' === $filename ) {
2481 + $above = dirname( $root ) . '/wp-config.php';
2482 +
2483 + // Suppressed like the core does in wp-load.php: the directory above
2484 + // the install is often outside open_basedir on shared hosting, and
2485 + // without the @ every scan emits a warning that can land in front of
2486 + // the JSON of an AJAX scan.
2487 + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- The same @ the core uses for this same check in wp-load.php:52, where a wp-config.php one directory up is looked for: open_basedir makes file_exists() warn on a path outside it, and this must not print.
2488 + if ( @file_exists( $above ) && ! @file_exists( dirname( $root ) . '/wp-settings.php' ) ) {
2489 + return $above;
2490 + }
2491 + }
2492 +
2493 + return false;
2494 + }
2495 +
1583 2496 private function scan_critical_root_files() {
1584 2497 // Before reading anything: the scan is the only thing that reaches
1585 2498 // every site of a network on its own, through wp-cron and front-end
1586 2499 // traffic. Hooking the cleanup to admin_init alone left every subsite
@@ -1587,17 +2500,20 @@
1587 2500 // whose dashboard nobody opens with its old copy of wp-config.php,
1588 2501 // credentials included, for as long as nobody visited it.
1589 2502 $this->maybe_redact_stored_baseline();
1590 2503
2504 + // And claim the blocks already on disk before anything is compared,
2505 + // so the first scan after updating uses the rule that will stay.
2506 + $this->maybe_claim_owned_blocks();
2507 +
1591 2508 $modified = array();
1592 2509 $baseline = $this->get_critical_files_baseline();
1593 2510 $baseline_changed = false;
1594 - $root_path = untrailingslashit( ABSPATH );
1595 2511
1596 2512 foreach ( $this->critical_root_files as $filename ) {
1597 - $full_path = $root_path . '/' . $filename;
2513 + $full_path = $this->critical_file_path( $filename );
1598 2514
1599 - if ( ! file_exists( $full_path ) ) {
2515 + if ( false === $full_path ) {
1600 2516 continue;
1601 2517 }
1602 2518
1603 2519 $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
@@ -1659,14 +2575,34 @@
1659 2575 *
1660 2576 * Both sides go through the same redaction, or every credential
1661 2577 * line would read as a change nobody made.
1662 2578 */
1663 - $baseline_content = $baseline[ $filename ]['content'] ?? '';
1664 - $current_content = $this->baseline_content( $filename, $normalized );
1665 - $diff = ( '' !== $baseline_content && '' !== $current_content )
1666 - ? $this->compute_simple_diff( $baseline_content, $current_content )
1667 - : array( 'added' => array(), 'removed' => array(), 'unavailable' => true );
2579 + /*
2580 + * Where the shared files do not belong to this site, the lines are
2581 + * not computed at all. The diff is shown to whoever can open this
2582 + * site's screen, the administrator of a subsite included, and it
2583 + * was stored in the options of every subsite with the module on.
2584 + * Found by the audit of the admin surface for 2.11.8. The change is
2585 + * still reported, with both sizes, and the lines are read on the
2586 + * main site, where the change is approved.
2587 + */
2588 + if ( ! Vigilante_Settings::owns_shared_files() ) {
2589 + $diff = self::network_only_diff();
2590 + } else {
2591 + $baseline_content = $baseline[ $filename ]['content'] ?? '';
2592 + $current_content = $this->baseline_content( $filename, $normalized );
2593 + $diff = ( '' !== $baseline_content && '' !== $current_content )
2594 + ? $this->compute_simple_diff( $baseline_content, $current_content )
2595 + : array( 'added' => array(), 'removed' => array(), 'unavailable' => true );
1668 2596
2597 + // Say why there are no lines when today's copy could not be
2598 + // made safe, which approving does not change: the generic
2599 + // message talks about an old baseline. Cross review of 2.11.8.
2600 + if ( '' === $current_content && 'wp-config.php' === $filename ) {
2601 + $diff['redaction'] = true;
2602 + }
2603 + }
2604 +
1669 2605 $modified[] = array(
1670 2606 'file' => $filename,
1671 2607 'type' => 'critical_config',
1672 2608 'expected_hash' => $baseline[ $filename ]['hash'],
@@ -1751,30 +2687,49 @@
1751 2687 * @param string $filename File name (e.g. 'wp-config.php').
1752 2688 * @param string $content Raw file content.
1753 2689 * @return string Normalized content for hashing.
1754 2690 */
1755 - private function normalize_critical_file( $filename, $content ) {
2691 + private function normalize_critical_file( $filename, $content, $drop_all_original = false ) {
1756 2692 // Normalize line endings first (CRLF and CR to LF)
1757 2693 $content = str_replace( array( "\r\n", "\r" ), "\n", $content );
1758 2694
2695 + /*
2696 + * Vigilant's own blocks are left out of the hash, so rewriting them is
2697 + * not reported as somebody else's change. Until 2.11.5 that covered
2698 + * everything between the markers, and every line carrying the
2699 + * [VIGILANTE_ORIGINAL] marker, whatever they contained. From 2.11.5 a
2700 + * block is left out only if it is exactly a block Vigilant wrote (see
2701 + * remember_owned_block()), and a marked line only while uncommenting it
2702 + * would still give a harmless define() (see is_vigilant_original_line()).
2703 + *
2704 + * Until the blocks already on disk have been claimed, the old rule
2705 + * applies unchanged. That is what keeps an update from changing the
2706 + * hash of a file nobody touched.
2707 + */
2708 + $claimed = $this->owned_blocks_claimed();
2709 +
1759 2710 if ( 'wp-config.php' === $filename ) {
1760 - // Remove Vigilante constants blocks (current and legacy)
2711 + // Vigilante constants blocks (current and legacy)
1761 2712 foreach ( $this->wpconfig_markers as $markers ) {
1762 - $pattern = '/' . preg_quote( $markers[0], '/' ) . '.*?' . preg_quote( $markers[1], '/' ) . '\s*/s';
1763 - $content = preg_replace( $pattern, '', $content );
2713 + $content = $this->strip_vigilant_blocks( $filename, $content, $markers, $claimed );
1764 2714 }
1765 2715
1766 - // Remove lines commented out by Vigilante (original constants)
1767 - $content = preg_replace(
2716 + // Lines commented out by Vigilante (original constants)
2717 + $content = preg_replace_callback(
1768 2718 '/^.*' . preg_quote( $this->wpconfig_original_marker, '/' ) . '.*$/m',
1769 - '',
2719 + function ( $line ) use ( $claimed, $drop_all_original ) {
2720 + // $drop_all_original reproduce la regla anterior a la 2.11.5 (quitar
2721 + // toda linea marcada) sobre los bloques de la regla nueva. Solo lo usa
2722 + // el re-base de la transicion, para decidir si la unica diferencia con
2723 + // el registro aprobado son estas lineas. Ver rebase_original_line_shift().
2724 + return ( ! $claimed || $drop_all_original || $this->is_vigilant_original_line( $line[0] ) ) ? '' : $line[0];
2725 + },
1770 2726 $content
1771 2727 );
1772 2728 } elseif ( '.htaccess' === $filename ) {
1773 - // Remove Vigilante htaccess blocks (firewall + security headers)
2729 + // Vigilante htaccess blocks (firewall + security headers)
1774 2730 foreach ( $this->htaccess_markers as $markers ) {
1775 - $pattern = '/' . preg_quote( $markers[0], '/' ) . '.*?' . preg_quote( $markers[1], '/' ) . '\s*/s';
1776 - $content = preg_replace( $pattern, '', $content );
2731 + $content = $this->strip_vigilant_blocks( $filename, $content, $markers, $claimed );
1777 2732 }
1778 2733 }
1779 2734
1780 2735 // Collapse multiple blank lines into one (blocks removal leaves gaps)
@@ -1783,8 +2738,639 @@
1783 2738 return trim( $content );
1784 2739 }
1785 2740
1786 2741 /**
2742 + * Leave Vigilant's blocks for one pair of markers out of the content
2743 + *
2744 + * Before the claim, every block, as it always was. After it, only the blocks
2745 + * whose fingerprint was recorded when Vigilant wrote them. A block that does
2746 + * not match, edited or planted, stays in the content: it counts in the hash
2747 + * and shows up in the diff.
2748 + *
2749 + * The match runs from marker to marker and the removal also takes the
2750 + * whitespace after the block, exactly as before, so a file whose blocks are
2751 + * all Vigilant's normalizes to the same text under both rules.
2752 + *
2753 + * @since 2.11.5
2754 + *
2755 + * @param string $filename 'wp-config.php' or '.htaccess'.
2756 + * @param string $content Content with normalized line endings.
2757 + * @param array $markers Start and end marker.
2758 + * @param bool $claimed Whether the claim has run.
2759 + * @return string
2760 + */
2761 + private function strip_vigilant_blocks( $filename, $content, $markers, $claimed ) {
2762 + $pattern = '/(' . preg_quote( $markers[0], '/' ) . '.*?' . preg_quote( $markers[1], '/' ) . ')\s*/s';
2763 +
2764 + if ( ! $claimed ) {
2765 + return preg_replace( $pattern, '', $content );
2766 + }
2767 +
2768 + return preg_replace_callback(
2769 + $pattern,
2770 + function ( $match ) use ( $filename ) {
2771 + return self::is_owned_block( $filename, $match[1] ) ? '' : $match[0];
2772 + },
2773 + $content
2774 + );
2775 + }
2776 +
2777 + /**
2778 + * Whether a line carrying the original-constant marker is one Vigilant wrote
2779 + *
2780 + * comment_existing_constants() puts the marker in front of a define() of a
2781 + * constant it manages, and uncomment_original_constants() takes it away
2782 + * again whenever the constants are applied or removed, so whatever follows
2783 + * the marker gets to run some day. The line is left out of the hash only
2784 + * when there is nothing but indentation before the marker, nothing after it
2785 + * but a harmless define() and at most a line comment, and no PHP tag
2786 + * anywhere on it. That keeps it a comment today and harmless once
2787 + * uncommented. Anything else counts, and shows up in the diff.
2788 + *
2789 + * @since 2.11.5
2790 + *
2791 + * @param string $line One line of wp-config.php.
2792 + * @return bool
2793 + */
2794 + /**
2795 + * Whether every marked line of a file can run nothing at all
2796 + *
2797 + * The question the re-base has to answer before adopting a file is whether
2798 + * the lines that carry the marker are only comments. Asking a stricter one
2799 + * was wrong in both directions: the first version of the guard used
2800 + * is_vigilant_original_line(), which also requires the commented define to
2801 + * match a known harmless shape, so it refused to re-base a perfectly inert
2802 + * line carrying an unusual define, which is exactly the case the re-base
2803 + * exists for, leaving the function unable to act at all. Found by the cross
2804 + * review of 2.11.10.
2805 + *
2806 + * The second version read one line at a time and reasoned that the marker
2807 + * begins with //, so a line with nothing but whitespace before it is wholly
2808 + * a comment. That is true only where PHP is already reading code, and the
2809 + * second cross review of 2.11.10 built three files where it is not, all of
2810 + * them valid PHP, all of them passing that test and all of them running or
2811 + * printing something:
2812 + *
2813 + * - the marked line placed BEFORE the opening <?php, so it is inline HTML
2814 + * that the server prints verbatim to the browser;
2815 + * - the same after a ?> that the file already had;
2816 + * - the marked line ending a block comment opened on an earlier line and
2817 + * opening another one at its end, with a statement in between, which
2818 + * runs like any other statement.
2819 + *
2820 + * So the file is read the way PHP reads it, not the way the line looks. A
2821 + * marked line is inert when every token touching it is a comment or
2822 + * whitespace, which answers the three at once: inline HTML is not a comment,
2823 + * and neither is a statement. The shape the guard was written for, code
2824 + * BEFORE the marker, is the same question from the other side.
2825 + *
2826 + * The three shapes are in the harness as cells X2, X3 and X4 of
2827 + * matriz-escondite-marcadores.sh, written out in full there. They are not
2828 + * written out here on purpose: a literal payload in a shipped file is
2829 + * signature surface for the scanners this plugin is read by, and a comment
2830 + * is a bad place to pay for it.
2831 + *
2832 + * @since 2.11.10
2833 + *
2834 + * @param string $content Whole file content.
2835 + * @return bool True when no marked line can run or print anything.
2836 + */
2837 + /**
2838 + * The lines of a file that carry the original-value marker
2839 + *
2840 + * @since 2.11.10
2841 + *
2842 + * @param string $content Whole file content, newlines already normalised.
2843 + * @return string[]
2844 + */
2845 + private function marked_lines_of( $content ) {
2846 + $out = array();
2847 +
2848 + foreach ( explode( "\n", $content ) as $text ) {
2849 + if ( false !== strpos( $text, $this->wpconfig_original_marker ) ) {
2850 + $out[] = $text;
2851 + }
2852 + }
2853 +
2854 + return $out;
2855 + }
2856 +
2857 + /**
2858 + * Whether what a marked line carries would still be harmless uncommented
2859 + *
2860 + * Only the part after the marker matters: what comes before it is answered by
2861 + * the token pass, which refuses anything that is not comment or whitespace.
2862 + * Here the question is what comes BACK when uncomment_original_constants()
2863 + * removes the marker, so the body has to be a single define() and nothing
2864 + * else, with at most a trailing line comment. Deliberately says nothing about
2865 + * WHICH constant it is: asking that was the first version of this guard, and
2866 + * it refused every define it did not recognise, which is exactly the case the
2867 + * re-base exists for.
2868 + *
2869 + * @since 2.11.10
2870 + *
2871 + * @param string $line One line carrying the marker.
2872 + * @return bool
2873 + */
2874 + private function marked_line_body_is_harmless( $line ) {
2875 + $at = strpos( $line, $this->wpconfig_original_marker );
2876 +
2877 + if ( false === $at ) {
2878 + return true;
2879 + }
2880 +
2881 + $body = trim( substr( $line, $at + strlen( $this->wpconfig_original_marker ) ) );
2882 +
2883 + if ( '' === $body ) {
2884 + return true;
2885 + }
2886 +
2887 + // Tokenised as PHP so the trailing comment, the strings and the nesting
2888 + // are read the way PHP reads them and not with a regular expression.
2889 + $tokens = @token_get_all( '<?php ' . $body ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A marked line can carry anything; a warning here must not be printed, and an unreadable body is refused below.
2890 +
2891 + if ( empty( $tokens ) ) {
2892 + return false;
2893 + }
2894 +
2895 + $statements = 0;
2896 + $depth = 0;
2897 +
2898 + foreach ( $tokens as $token ) {
2899 + $type = is_array( $token ) ? $token[0] : $token;
2900 +
2901 + if ( in_array( $type, array( T_OPEN_TAG, T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) {
2902 + continue;
2903 + }
2904 +
2905 + if ( '(' === $type ) {
2906 + $depth++;
2907 + continue;
2908 + }
2909 +
2910 + if ( ')' === $type ) {
2911 + $depth--;
2912 + continue;
2913 + }
2914 +
2915 + // A semicolon at the top level closes a statement. More than one, or
2916 + // anything after the first, means the line carries something else.
2917 + if ( ';' === $type && 0 === $depth ) {
2918 + $statements++;
2919 + continue;
2920 + }
2921 +
2922 + if ( $statements > 0 ) {
2923 + return false;
2924 + }
2925 + }
2926 +
2927 + return ( $statements <= 1 );
2928 + }
2929 +
2930 + private function marked_lines_are_inert( $content ) {
2931 + $content = str_replace( "\r\n", "\n", (string) $content );
2932 + $marker = $this->wpconfig_original_marker;
2933 +
2934 + if ( '' === $content || false === strpos( $content, $marker ) ) {
2935 + return true;
2936 + }
2937 +
2938 + $marked = array();
2939 +
2940 + foreach ( explode( "\n", $content ) as $index => $text ) {
2941 + if ( false !== strpos( $text, $marker ) ) {
2942 + $marked[ $index + 1 ] = true;
2943 + }
2944 + }
2945 +
2946 + // Lenient on purpose (no TOKEN_PARSE): a tampered file still has to be
2947 + // read, and a file that cannot be tokenised is never adopted.
2948 + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- The file read here may have been tampered with, which is the whole point, and PHP 8 emits a warning when it cannot tokenise: printing it would put a parse error on whatever page ran the scan. An unreadable file is refused four lines below.
2949 + $tokens = @token_get_all( $content );
2950 +
2951 + if ( empty( $tokens ) ) {
2952 + return false;
2953 + }
2954 +
2955 + /*
2956 + * And the other half of the question, which the first token version left
2957 + * out: a marked line is a COMMENTED OUT value, and uncommenting it is what
2958 + * the feature exists for, so "runs nothing today" is not enough. Anything
2959 + * sharing the line after the define comes back with it. The shape is real
2960 + * and needs no attacker: comment_existing_constants() takes a define and
2961 + * everything on its line, so
2962 + * define( 'WP_DEBUG', false ); @ini_set( 'display_errors', 0 );
2963 + * is commented whole, and re-basing it would adopt as approved something
2964 + * that runs the moment the value is restored. The old rule refused this
2965 + * too, but along with every define whose NAME it did not recognise, which
2966 + * is what left the function unable to act at all. Found by the third cross
2967 + * review of 2.11.10.
2968 + */
2969 + foreach ( $this->marked_lines_of( $content ) as $text ) {
2970 + if ( ! $this->marked_line_body_is_harmless( $text ) ) {
2971 + return false;
2972 + }
2973 + }
2974 +
2975 + $inocuos = array( T_COMMENT, T_DOC_COMMENT, T_WHITESPACE );
2976 + $linea = 1;
2977 +
2978 + foreach ( $tokens as $token ) {
2979 + $texto = is_array( $token ) ? $token[1] : $token;
2980 + $tipo = is_array( $token ) ? $token[0] : null;
2981 + $saltos = substr_count( $texto, "\n" );
2982 + $desde = $linea;
2983 + $hasta = $linea + $saltos;
2984 +
2985 + /*
2986 + * A token whose text ends in a newline puts nothing on the line that
2987 + * newline opens. Counting it would make the "<?php\n" of every file
2988 + * touch line 2 and refuse the legitimate case, which is what the
2989 + * first version of this did.
2990 + */
2991 + $ultima = ( $saltos > 0 && "\n" === substr( $texto, -1 ) ) ? $hasta - 1 : $hasta;
2992 + $linea = $hasta;
2993 +
2994 + if ( null !== $tipo && in_array( $tipo, $inocuos, true ) ) {
2995 + continue;
2996 + }
2997 +
2998 + for ( $l = $desde; $l <= $ultima; $l++ ) {
2999 + if ( isset( $marked[ $l ] ) ) {
3000 + return false;
3001 + }
3002 + }
3003 + }
3004 +
3005 + return true;
3006 + }
3007 +
3008 + private function is_vigilant_original_line( $line ) {
3009 + if ( false !== strpos( $line, '<?' ) || false !== strpos( $line, '?>' ) ) {
3010 + return false;
3011 + }
3012 +
3013 + return 1 === preg_match(
3014 + '/^[ \t]*' . preg_quote( $this->wpconfig_original_marker, '/' ) . self::harmless_define_pattern() . '[ \t]*(?:(?:\/\/|#(?!\[)).*)?$/',
3015 + $line
3016 + );
3017 + }
3018 +
3019 + /**
3020 + * A define() that runs nothing but itself, as a regular expression fragment
3021 + *
3022 + * The name is one of the constants Vigilant has managed in any version. The
3023 + * value is made only of literals (true, false, null, a number, a quoted
3024 + * string with nothing to interpolate) and of ABSPATH, WP_CONTENT_DIR and
3025 + * __DIR__, which is what a debug log path is usually built from, joined
3026 + * with dots. No call, no variable, no backtick, no include.
3027 + *
3028 + * @since 2.11.5
3029 + *
3030 + * @return string Pattern without delimiters.
3031 + */
3032 + private static function harmless_define_pattern() {
3033 + $names = 'DISALLOW_FILE_EDIT|DISALLOW_FILE_MODS|FORCE_SSL_ADMIN|FORCE_SSL_LOGIN|WP_DEBUG|WP_DEBUG_LOG|WP_DEBUG_DISPLAY|SCRIPT_DEBUG|DISABLE_WP_CRON'
3034 + . '|WP_POST_REVISIONS|AUTOSAVE_INTERVAL|EMPTY_TRASH_DAYS|WP_MEMORY_LIMIT|WP_MAX_MEMORY_LIMIT|WP_AUTO_UPDATE_CORE|CONCATENATE_SCRIPTS';
3035 +
3036 + $value = '(?:(?i:true|false|null)|-?\d+|\'(?:[^\'\\\\]|\\\\.)*\'|"[^"\\\\$]*"|ABSPATH|WP_CONTENT_DIR|__DIR__)';
3037 +
3038 + return 'define\s*\(\s*[\'"](?:' . $names . ')[\'"]\s*,\s*' . $value . '(?:\s*\.\s*' . $value . ')*\s*\)\s*;';
3039 + }
3040 +
3041 + /**
3042 + * Whether a wp-config.php constants block can only be one Vigilant wrote
3043 + *
3044 + * Every version of generate_constants() has written the start marker on its
3045 + * own line, then comments, blank lines and define() calls, bare or wrapped
3046 + * in if ( ! defined() ), then the end marker on its own line. A block made
3047 + * only of those lines runs nothing but the defines, whatever version wrote
3048 + * it and whatever settings it was written with. One line of anything else,
3049 + * or a PHP tag on any line, and the block is not taken.
3050 + *
3051 + * @since 2.11.5
3052 + *
3053 + * @param string $block Block from start marker to end marker, inclusive.
3054 + * @param array $markers Start and end marker.
3055 + * @return bool
3056 + */
3057 + private static function is_harmless_constants_block( $block, $markers ) {
3058 + $lines = explode( "\n", str_replace( array( "\r\n", "\r" ), "\n", (string) $block ) );
3059 +
3060 + if ( count( $lines ) < 2
3061 + || rtrim( array_shift( $lines ), " \t" ) !== $markers[0]
3062 + || ltrim( array_pop( $lines ), " \t" ) !== $markers[1]
3063 + ) {
3064 + return false;
3065 + }
3066 +
3067 + $define = self::harmless_define_pattern();
3068 + $guarded = '/^if\s*\(\s*!\s*defined\s*\(\s*[\'"][A-Z_]+[\'"]\s*\)\s*\)\s*\{\s*' . $define . '\s*\}$/';
3069 +
3070 + foreach ( $lines as $line ) {
3071 + $line = trim( $line, " \t" );
3072 +
3073 + if ( false !== strpos( $line, '<?' ) || false !== strpos( $line, '?>' ) ) {
3074 + return false;
3075 + }
3076 +
3077 + if ( '' === $line
3078 + || 0 === strpos( $line, '//' )
3079 + || preg_match( '/^' . $define . '$/', $line )
3080 + || preg_match( $guarded, $line )
3081 + ) {
3082 + continue;
3083 + }
3084 +
3085 + return false;
3086 + }
3087 +
3088 + return true;
3089 + }
3090 +
3091 + /**
3092 + * Take ownership of the blocks already on disk, once
3093 + *
3094 + * Fingerprints are recorded when Vigilant writes a block, which leaves every
3095 + * block written before 2.11.5 without one. This records the blocks that can
3096 + * be recognised as Vigilant's without having seen them written:
3097 + *
3098 + * - A .htaccess block, when it is exactly what Vigilant would write today
3099 + * with the settings it has, the timestamp and the version apart. After an
3100 + * update, maybe_sync_server_files() rewrites those blocks on the next
3101 + * request, so the claim waits for it. Unless it has already failed: a
3102 + * block Vigilant cannot rewrite is not going to start matching, and
3103 + * waiting for it would keep the old rule for good.
3104 + * - A wp-config.php constants block, when every line in it is a comment, a
3105 + * blank line or a harmless define(). Nothing rewrites that block on an
3106 + * update and its format has changed five times, so comparing it with
3107 + * today's output would report every site that has not saved those
3108 + * settings since. A line that could run anything is never accepted.
3109 + *
3110 + * A block that is not recognised stays in the hash and is reported as a
3111 + * change, so the owner gets to look at it, and the activity log says why.
3112 + * Nothing in the stored baseline is rewritten.
3113 + *
3114 + * Only where the shared files belong, a single site or the main site of a
3115 + * network, because the expected blocks come from that site's settings. Until
3116 + * it has run, normalize_critical_file() keeps the old rule on every site.
3117 + *
3118 + * @since 2.11.5
3119 + */
3120 + /**
3121 + * The admin_init entry point of the claim, which does ask for an administrator
3122 + *
3123 + * admin-ajax.php fires admin_init before it decides who is asking
3124 + * (wp-admin/admin-ajax.php:45), so without this an anonymous request chose
3125 + * the moment the claim runs. Unlike its two neighbours in
3126 + * init_cleanup_hooks(), which only drop the plugin's own copy out of the
3127 + * database, the claim writes two network options, changes for the whole
3128 + * network the rule normalize_critical_file() applies, and re-bases the
3129 + * approved baseline.
3130 + *
3131 + * The gate lives here and not inside maybe_claim_owned_blocks() because the
3132 + * scan calls that one directly and the scan runs from wp-cron, with no user:
3133 + * putting the capability check inside left the claim unable to complete on
3134 + * any site whose dashboard nobody opens, and until it completes the older,
3135 + * permissive rule is the one in force, which is the hiding place 2.11.5 was
3136 + * written to close. Found by the cross review of 2.11.10.
3137 + *
3138 + * @since 2.11.10
3139 + */
3140 + public function maybe_claim_owned_blocks_on_admin() {
3141 + if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
3142 + return;
3143 + }
3144 +
3145 + $this->maybe_claim_owned_blocks();
3146 + }
3147 +
3148 + public function maybe_claim_owned_blocks() {
3149 + if ( $this->owned_blocks_claimed() || ! Vigilante_Settings::owns_shared_files() ) {
3150 + return;
3151 + }
3152 +
3153 + $sync_due = get_option( 'vigilante_server_files_pending' )
3154 + || VIGILANTE_VERSION !== get_option( 'vigilante_server_files_version' );
3155 +
3156 + if ( $sync_due && ! get_option( 'vigilante_server_files_retry_after' ) ) {
3157 + return;
3158 + }
3159 +
3160 + $expected = null;
3161 + $unclaimed = array();
3162 +
3163 + foreach ( $this->critical_root_files as $filename ) {
3164 + $full_path = $this->critical_file_path( $filename );
3165 +
3166 + if ( false === $full_path ) {
3167 + continue;
3168 + }
3169 +
3170 + $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
3171 +
3172 + if ( false === $content ) {
3173 + // Unreadable right now: leave the claim open and try again later.
3174 + return;
3175 + }
3176 +
3177 + $content = str_replace( array( "\r\n", "\r" ), "\n", $content );
3178 + $is_config = 'wp-config.php' === $filename;
3179 +
3180 + foreach ( ( $is_config ? $this->wpconfig_markers : $this->htaccess_markers ) as $markers ) {
3181 + $pattern = '/' . preg_quote( $markers[0], '/' ) . '.*?' . preg_quote( $markers[1], '/' ) . '/s';
3182 +
3183 + if ( ! preg_match_all( $pattern, $content, $found ) ) {
3184 + continue;
3185 + }
3186 +
3187 + foreach ( $found[0] as $block ) {
3188 + if ( $is_config ) {
3189 + $ours = self::is_harmless_constants_block( $block, $markers );
3190 + } else {
3191 + $expected = null === $expected ? $this->expected_htaccess_blocks() : $expected;
3192 + $ours = isset( $expected[ $markers[0] ] )
3193 + && self::comparable_block( $block ) === self::comparable_block( $expected[ $markers[0] ] );
3194 + }
3195 +
3196 + if ( $ours ) {
3197 + self::remember_owned_block( $filename, $markers[0], $block, false );
3198 + } else {
3199 + $unclaimed[ $filename ] = $filename;
3200 + }
3201 + }
3202 + }
3203 +
3204 + // The commented-out originals are judged line by line at scan time.
3205 + // Looking at them here only keeps the log entry below complete.
3206 + if ( $is_config && preg_match_all( '/^.*' . preg_quote( $this->wpconfig_original_marker, '/' ) . '.*$/m', $content, $marked ) ) {
3207 + foreach ( $marked[0] as $line ) {
3208 + if ( ! $this->is_vigilant_original_line( $line ) ) {
3209 + $unclaimed[ $filename ] = $filename;
3210 + }
3211 + }
3212 + }
3213 + }
3214 +
3215 + update_site_option( self::OWNED_BLOCKS_CLAIM_OPTION, self::OWNED_BLOCKS_CLAIMED );
3216 +
3217 + // With the claim in place normalize uses the new rule, so a file nobody
3218 + // touched whose only difference is an original line the old rule dropped
3219 + // would read as changed. Re-base those, and only those, once.
3220 + $this->rebase_original_line_shift();
3221 +
3222 + if ( $unclaimed && $this->activity_log ) {
3223 + $this->activity_log->log(
3224 + 'file',
3225 + 'critical_file_unrecognized_block',
3226 + sprintf(
3227 + /* translators: %s: comma-separated file names, such as wp-config.php or .htaccess. */
3228 + __( 'Content marked as written by Vigilant in %s does not match what Vigilant writes. From now on it is checked like the rest of the file, so the file integrity scan reports it as a change for you to review.', 'vigilante' ),
3229 + implode( ', ', $unclaimed )
3230 + ),
3231 + array( 'files' => array_values( $unclaimed ) ),
3232 + 'warning'
3233 + );
3234 + }
3235 + }
3236 +
3237 + /**
3238 + * Re-base the critical files whose only change is a newly kept original line
3239 + *
3240 + * Until 2.11.5 the hash left out every [VIGILANTE_ORIGINAL] line; from 2.11.5
3241 + * it keeps the ones whose value is not a plain constant define, which is the
3242 + * right thing for the hash but moves it on a file nobody edited: the stored
3243 + * baseline was taken under the old rule, and nothing re-bases wp-config.php on
3244 + * an update (maybe_sync_server_files() only rewrites the .htaccess). So the
3245 + * first scan after updating would report wp-config.php as changed.
3246 + *
3247 + * This runs once, in the same pass that claims the blocks. For each file it
3248 + * re-bases to the new hash only when the baseline still matches the file with
3249 + * every original line dropped, which means the blocks are exactly the approved
3250 + * ones and the sole difference is those lines, the user's own commented-out
3251 + * defines. A block that was edited or planted does not match with the lines
3252 + * dropped, so it is left to be reported: this closes the false positive
3253 + * without adopting anything that was hidden before.
3254 + *
3255 + * @since 2.11.5
3256 + */
3257 + private function rebase_original_line_shift() {
3258 + $baseline = $this->get_critical_files_baseline();
3259 + $changed = false;
3260 +
3261 + foreach ( $this->critical_root_files as $filename ) {
3262 + $full_path = $this->critical_file_path( $filename );
3263 +
3264 + if ( false === $full_path || empty( $baseline[ $filename ]['hash'] ) ) {
3265 + continue;
3266 + }
3267 +
3268 + $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
3269 +
3270 + if ( false === $content ) {
3271 + continue;
3272 + }
3273 +
3274 + /*
3275 + * Never re-base a file that carries a marked line which is not
3276 + * wholly a comment. The test below only establishes that the
3277 + * difference lies in lines carrying the marker, and the old rule
3278 + * dropped the WHOLE line, so a line with a statement in front of the
3279 + * marker satisfies it (cell X1 of matriz-escondite-marcadores.sh,
3280 + * where the shape is written out): re-basing would write that line
3281 + * into the approved baseline and rewrite the stored content, so the
3282 + * diff would stop showing it. Adopting as approved what the previous rule
3283 + * hid is the one thing an integrity scanner must never do, and the
3284 + * log entry of maybe_claim_owned_blocks() already promises the
3285 + * opposite ("the scan reports it as a change for you to review").
3286 + * Those files are left to be reported. Found by the file-by-file
3287 + * review of 2.11.10.
3288 + *
3289 + * What counts as "wholly a comment" is decided by reading the file
3290 + * as PHP reads it, not by the shape of the line: see
3291 + * marked_lines_are_inert(). A line that is not recognised is not the
3292 + * same thing as a line that can run something, and the first
3293 + * wording of this guard confused the two.
3294 + */
3295 + if ( ! $this->marked_lines_are_inert( $content ) ) {
3296 + continue;
3297 + }
3298 +
3299 + $current = md5( $this->normalize_critical_file( $filename, $content ) );
3300 +
3301 + // Already in step, or a real change to something other than the
3302 + // original lines: nothing to re-base here.
3303 + if ( $baseline[ $filename ]['hash'] === $current
3304 + || $baseline[ $filename ]['hash'] !== md5( $this->normalize_critical_file( $filename, $content, true ) )
3305 + ) {
3306 + continue;
3307 + }
3308 +
3309 + $normalized = $this->normalize_critical_file( $filename, $content );
3310 + $baseline[ $filename ]['hash'] = $current;
3311 + $baseline[ $filename ]['size'] = strlen( $content );
3312 + $baseline[ $filename ]['content'] = $this->baseline_content( $filename, $normalized );
3313 + $baseline[ $filename ]['updated'] = time();
3314 + $changed = true;
3315 + }
3316 +
3317 + if ( $changed ) {
3318 + $this->write_baseline( $baseline );
3319 + }
3320 + }
3321 +
3322 + /**
3323 + * The .htaccess blocks Vigilant would write today, keyed by start marker
3324 + *
3325 + * @since 2.11.5
3326 + *
3327 + * @return array
3328 + */
3329 + private function expected_htaccess_blocks() {
3330 + $settings = $this->settings ? $this->settings : new Vigilante_Settings();
3331 +
3332 + $classes = array(
3333 + 'Vigilante_Htaccess_Protection' => 'class-htaccess-protection.php',
3334 + 'Vigilante_Security_Headers' => 'class-security-headers.php',
3335 + );
3336 +
3337 + foreach ( $classes as $class => $file ) {
3338 + if ( ! class_exists( $class ) ) {
3339 + require_once VIGILANTE_INCLUDES_DIR . $file;
3340 + }
3341 + }
3342 +
3343 + $headers = new Vigilante_Security_Headers( $settings );
3344 +
3345 + return array(
3346 + Vigilante_Htaccess_Protection::MARKER_START => ( new Vigilante_Htaccess_Protection( $settings ) )->generate_rules(),
3347 + Vigilante_Security_Headers::MARKER_START => Vigilante_Security_Headers::MARKER_START . "\n" . $headers->generate_rules_content() . "\n" . Vigilante_Security_Headers::MARKER_END,
3348 + );
3349 + }
3350 +
3351 + /**
3352 + * A .htaccess block with the parts that change on every write evened out
3353 + *
3354 + * Two blocks Vigilant wrote with the same settings differ only in the time
3355 + * they were generated and, across an update, in the version the firewall
3356 + * block names. Everything else has to be identical for the claim to take
3357 + * the block.
3358 + *
3359 + * @since 2.11.5
3360 + *
3361 + * @param string $block Block from start marker to end marker, inclusive.
3362 + * @return string
3363 + */
3364 + private static function comparable_block( $block ) {
3365 + $block = str_replace( array( "\r\n", "\r" ), "\n", (string) $block );
3366 + $block = preg_replace( '/^# Generated: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC$/m', '# Generated:', $block );
3367 + $block = preg_replace( '/^# Vigilante for WordPress - Firewall v[0-9][0-9A-Za-z.\-]*$/m', '# Vigilante for WordPress - Firewall v', $block );
3368 +
3369 + return rtrim( $block, "\n" );
3370 + }
3371 +
3372 + /**
1787 3373 * Get stored baseline hashes for critical files
1788 3374 *
1789 3375 * @return array Associative array keyed by filename.
1790 3376 */
@@ -1801,11 +3387,11 @@
1801 3387 * @param string $filename File name relative to ABSPATH (e.g. 'wp-config.php').
1802 3388 * @return bool True on success.
1803 3389 */
1804 3390 public function update_critical_file_baseline( $filename ) {
1805 - $full_path = untrailingslashit( ABSPATH ) . '/' . $filename;
3391 + $full_path = $this->critical_file_path( $filename );
1806 3392
1807 - if ( ! file_exists( $full_path ) ) {
3393 + if ( false === $full_path ) {
1808 3394 return false;
1809 3395 }
1810 3396
1811 3397 $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
@@ -1862,14 +3448,13 @@
1862 3448 * @return array Updated baseline data.
1863 3449 */
1864 3450 public function regenerate_all_baselines() {
1865 3451 $baseline = array();
1866 - $root_path = untrailingslashit( ABSPATH );
1867 3452
1868 3453 foreach ( $this->critical_root_files as $filename ) {
1869 - $full_path = $root_path . '/' . $filename;
3454 + $full_path = $this->critical_file_path( $filename );
1870 3455
1871 - if ( ! file_exists( $full_path ) ) {
3456 + if ( false === $full_path ) {
1872 3457 continue;
1873 3458 }
1874 3459
1875 3460 $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
@@ -1979,8 +3564,17 @@
1979 3564 if ( '.' === $plugin_slug ) {
1980 3565 continue;
1981 3566 }
1982 3567
3568 + // With the self-check on, Vigilant itself is verified by the
3569 + // sha256 triple-anchor block at the start of run_scan(): scanning
3570 + // it here again would duplicate findings and the md5 fetch. With
3571 + // the check off by filter, Vigilant is a regular plugin (legacy
3572 + // behaviour).
3573 + if ( dirname( VIGILANTE_PLUGIN_BASENAME ) === $plugin_slug && Vigilante_Self_Integrity::is_on() ) {
3574 + continue;
3575 + }
3576 +
1983 3577 // Skip slugs in their post-update grace window: wp.org may still be
1984 3578 // publishing the new version's checksums, so a scheduled scan here
1985 3579 // would raise benign "modified/extra" noise. The dedicated post-update
1986 3580 // verifier (vigilante_fi_postupdate_verify) handles these instead.
@@ -3214,8 +4808,39 @@
3214 4808 return array_values(
3215 4809 array_filter(
3216 4810 $items,
3217 4811 function ( $item ) {
4812 + /*
4813 + * On a network, wp-config.php and the root .htaccess are not a
4814 + * site's to silence: a change to them is closed by approving it,
4815 + * and approving takes a network administrator since 2.11.3. The
4816 + * ignore list is an option of each site, so until 2.11.8 the
4817 + * administrator of the main site without network rights hid a
4818 + * pending change from the network administrator's own screen by
4819 + * posting the file name to the ignore handler.
4820 + */
4821 + if ( is_multisite() && is_array( $item ) && 'critical_config' === ( $item['type'] ?? '' ) ) {
4822 + return true;
4823 + }
4824 +
4825 + // Findings about the manifest and the version of Vigilant
4826 + // itself are not about one file, so no entry of the list may
4827 + // hide them, on a single site either: ignoring the row of
4828 + // MANIFEST.sha256 took a replaced manifest out of the email.
4829 + // Vigilante_Self_Integrity::filter_ignored_findings() keeps
4830 + // them the same way.
4831 + if ( is_array( $item ) && 'vigilante_self' === ( $item['type'] ?? '' ) && in_array( $item['self_finding'] ?? '', array( 'manifest_replaced', 'manifest_unverified', 'manifest_missing', 'manifest_invalid', 'self_downgraded' ), true ) ) {
4832 + return true;
4833 + }
4834 + // Nor the findings of the walk of Vigilant's folder (a folder
4835 + // that cannot be listed, the folder that could not be walked):
4836 + // their path ends in a slash, and ignoring that row left the
4837 + // scan with no row and no email while the self-protection
4838 + // status stayed critical.
4839 + if ( is_array( $item ) && 'vigilante_self' === ( $item['type'] ?? '' ) && '/' === substr( (string) ( $item['file'] ?? '' ), -1 ) ) {
4840 + return true;
4841 + }
4842 +
3218 4843 $file = is_array( $item ) && isset( $item['file'] ) ? $item['file'] : '';
3219 4844 return ! in_array( $file, $this->ignored_files, true );
3220 4845 }
3221 4846 )
@@ -3252,9 +4877,17 @@
3252 4877 // a security-critical finding, same tier as a suspicious file.
3253 4878 $closed_plugins = $this->collect_closed_plugins_for_email();
3254 4879 $has_closed = ! empty( $closed_plugins );
3255 4880
4881 + /*
4882 + * Self-protection is not part of this decision any more. Its alert is
4883 + * its own and no setting switches it off, so this email is again about
4884 + * the files of the site: core, plugins, themes, uploads and the two
4885 + * shared configuration files.
4886 + */
3256 4887 $has_suspicious = ! empty( $results['suspicious'] ) || ! empty( $results['extra'] ) || $has_critical_config || $has_closed;
4888 + // Missing files of core, plugins or themes still do not send the email on
4889 + // their own: it has no section to list them in, so it would arrive empty.
3257 4890 $has_modified = ! empty( $results['modified'] );
3258 4891
3259 4892 // Instant alert: send for suspicious, extra, critical_config, modified
3260 4893 // files, or closed plugins.
@@ -3373,8 +5006,37 @@
3373 5006 $regular_modified[] = $item;
3374 5007 }
3375 5008 }
3376 5009
5010 + /*
5011 + * Self-protection does not travel in this email any more: it has its own
5012 + * alert, which no setting switches off (Vigilante_Self_Integrity::
5013 + * maybe_send_self_alert()). Older stored results can still carry its
5014 + * rows, so they are dropped here instead of being listed as ordinary
5015 + * files.
5016 + */
5017 + foreach ( array( 'suspicious', 'extra', 'missing' ) as $self_bucket ) {
5018 + if ( empty( $results[ $self_bucket ] ) || ! is_array( $results[ $self_bucket ] ) ) {
5019 + continue;
5020 + }
5021 + $results[ $self_bucket ] = array_values(
5022 + array_filter(
5023 + $results[ $self_bucket ],
5024 + function ( $item ) {
5025 + return ! ( is_array( $item ) && 'vigilante_self' === ( $item['type'] ?? '' ) );
5026 + }
5027 + )
5028 + );
5029 + }
5030 + $regular_modified = array_values(
5031 + array_filter(
5032 + $regular_modified,
5033 + function ( $item ) {
5034 + return ! ( is_array( $item ) && 'vigilante_self' === ( $item['type'] ?? '' ) );
5035 + }
5036 + )
5037 + );
5038 +
3377 5039 $suspicious_count = count( $results['suspicious'] ?? array() );
3378 5040 $extra_count = count( $results['extra'] ?? array() );
3379 5041 $critical_config_count = count( $critical_config );
3380 5042 $modified_count = count( $regular_modified );
@@ -3379,10 +5041,10 @@
3379 5041 $critical_config_count = count( $critical_config );
3380 5042 $modified_count = count( $regular_modified );
3381 5043 $closed_count = count( $closed_plugins );
3382 5044
3383 - // Use more urgent subject when suspicious files, critical config changes
3384 - // or closed plugins are found (all three are security-critical).
5045 + // Use more urgent subject when suspicious files, critical config changes,
5046 + // closed plugins or self-integrity findings are found (all security-critical).
3385 5047 if ( $suspicious_count > 0 || $critical_config_count > 0 || $closed_count > 0 ) {
3386 5048 $subject = sprintf(
3387 5049 /* translators: %s: Site name */
3388 5050 __( '[%s] SECURITY ALERT: File integrity issues detected', 'vigilante' ),