PluginProbe
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… / 2.11.12
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… v2.11.12
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 +2485 -46 2.9.42.11.12 View file →
@@ -82,8 +82,1439 @@
82 82 */
83 83 const BASELINE_OPTION = 'vigilante_critical_files_baseline';
84 84
85 85 /**
86 + * Option that records which version last redacted the stored baseline.
87 + *
88 + * @since 2.11.2
89 + */
90 + const BASELINE_REDACTION_OPTION = 'vigilante_baseline_redaction';
91 +
92 + /**
93 + * Network option recording that the one-off sweep of per-site baselines ran.
94 + *
95 + * @since 2.11.3
96 + */
97 + const BASELINE_SWEEP_OPTION = 'vigilante_baseline_sweep';
98 +
99 + /**
100 + * The migration the sweep marker stands for.
101 + *
102 + * A literal, not VIGILANTE_VERSION, and the difference is the whole point.
103 + * 2.11.3 stored the running version, so every release after it rearmed the
104 + * sweep: the first dashboard load on the main site walked the network with
105 + * switch_to_blog() to find nothing, because there was nothing left to find,
106 + * for ever, at the price of the one walk the marker exists to avoid.
107 + *
108 + * A plain boolean would fix that too, and would also leave no way to fire a
109 + * second network sweep the day another migration needs one. A literal costs
110 + * nothing today and keeps that door open. The redaction marker keeps the
111 + * running version on purpose: there the point IS to run again when the list
112 + * of what has to be redacted grows, and the cost of reopening it is one
113 + * option read rather than a walk of the network.
114 + *
115 + * And it must be a value NO version ever wrote into this option. The first
116 + * draft used '2.11.3', which is precisely what 2.11.3 wrote there, as its
117 + * own VIGILANTE_VERSION and BEFORE starting the walk: out in the wild that
118 + * value means "started, maybe unfinished". Reading it as "finished" left
119 + * every network whose 2.11.3 walk was cut short unswept for good, subsites
120 + * still holding the database password and the eight keys. Reproduced on the
121 + * Multisite install by a third cross review. The price of the new value is
122 + * that networks that did finish in 2.11.3 walk once more and find nothing.
123 + *
124 + * @since 2.11.4
125 + */
126 + const BASELINE_SWEEP_MIGRATION = 'network-sweep-done';
127 +
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 + /**
158 + * What replaces a secret value kept in the baseline.
159 + *
160 + * Fixed forever: if this string ever changes, every stored baseline
161 + * suddenly differs from the freshly redacted file and every site reports a
162 + * change to wp-config.php that never happened.
163 + *
164 + * @since 2.11.2
165 + */
166 + const REDACTED_MARKER = '[redacted by Vigilant]';
167 +
168 + /**
169 + * Constant names whose value is checked even where the file does not name them
170 + *
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().
177 + *
178 + * @since 2.11.2
179 + *
180 + * @var string[]
181 + */
182 + private static $secret_constants = array(
183 + 'DB_NAME', 'DB_USER', 'DB_PASSWORD', 'DB_HOST',
184 + 'AUTH_KEY', 'SECURE_AUTH_KEY', 'LOGGED_IN_KEY', 'NONCE_KEY',
185 + 'AUTH_SALT', 'SECURE_AUTH_SALT', 'LOGGED_IN_SALT', 'NONCE_SALT',
186 + );
187 +
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 + /**
217 + * Read the critical files baseline, from where it belongs
218 + *
219 + * Both watched files, wp-config.php and the root .htaccess, belong to the
220 + * whole network: there is one of each per installation, not one per site.
221 + * Keeping the baseline in a per-site option meant every site of a network
222 + * stored its own copy of the same wp-config.php, so a network of fifty
223 + * sites held fifty copies of the same credentials, and a cleanup that ran
224 + * on one site left the other forty nine untouched. Reported by @calzbert on
225 + * 10 sep 2026 and reproduced on the Multisite install. Since 2.11.3 there
226 + * is one baseline per network.
227 + *
228 + * No is_multisite() branch on purpose, and this is worth reading before
229 + * anyone adds one back: the core functions already make the distinction.
230 + * Verified in the installed core, wp-includes/option.php, where
231 + * get_network_option() falls back to get_option() on a single site and
232 + * update_network_option() falls back to update_option( $option, $value,
233 + * false ), autoload already off, which is exactly what this needs. Two
234 + * branches doing the same thing are two branches that can drift apart,
235 + * and one of them did during this very change.
236 + *
237 + * @since 2.11.3
238 + *
239 + * @return array
240 + */
241 + private function read_baseline() {
242 + $baseline = get_site_option( self::BASELINE_OPTION, array() );
243 +
244 + return is_array( $baseline ) ? $baseline : array();
245 + }
246 +
247 + /**
248 + * Store the critical files baseline where read_baseline() looks for it
249 + *
250 + * @since 2.11.3
251 + *
252 + * @param array $baseline Baseline to store.
253 + * @return bool
254 + */
255 + private function write_baseline( $baseline ) {
256 + return update_site_option( self::BASELINE_OPTION, $baseline );
257 + }
258 +
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 + /**
364 + * The baseline copy of a critical file, with no secret in it
365 + *
366 + * The integrity scan keeps a copy of wp-config.php so it can show which
367 + * lines changed. Until 2.11.1 that copy was the file itself minus the
368 + * plugin's own blocks, so the options table held the database password and
369 + * the eight authentication keys and salts, and anybody who later read the
370 + * database or a backup of it got them without ever touching the
371 + * filesystem. Reported by the automated security review of wp.org on 9 sep
372 + * 2026 and fixed in 2.11.2.
373 + *
374 + * The hash is still taken over the whole file, so a change to a secret is
375 + * still detected; what changes is that the diff cannot show it, which is
376 + * the right trade.
377 + *
378 + * @since 2.11.2
379 + *
380 + * @param string $filename Critical file name.
381 + * @param string $normalized Normalized content.
382 + * @return string Content safe to store, or '' when it cannot be made safe.
383 + */
384 + private function baseline_content( $filename, $normalized ) {
385 + if ( '.htaccess' === $filename ) {
386 + return $this->redact_server_secrets( $normalized );
387 + }
388 +
389 + if ( 'wp-config.php' !== $filename ) {
390 + return $normalized;
391 + }
392 +
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 );
397 +
398 + /*
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.
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 + *
420 + * Only values of eight characters or more are checked: DB_NAME is
421 + * often something like "local" or "wp", and looking for that inside a
422 + * PHP file matches by accident every time.
423 + */
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 + }
435 + }
436 +
437 + if ( false !== strpos( $redacted, $value ) ) {
438 + return '';
439 + }
440 + }
441 +
442 + return $redacted;
443 + }
444 +
445 + /**
446 + * Replace every value in wp-config.php with a marker
447 + *
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.
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 + *
469 + * @since 2.11.2
470 + * @since 2.11.8 Reads tokens and redacts every value.
471 + *
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.
768 + * @return string
769 + */
770 + private function redact_comment( $comment ) {
771 + $marker = self::REDACTED_MARKER;
772 + $readable = self::$readable_constants;
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 +
901 + /*
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.
907 + */
908 + return ( is_int( $value ) || is_float( $value ) ) ? array( (string) $value ) : array();
909 + }
910 +
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();
920 +
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 +
961 + return ( null === $redacted ) ? '' : $redacted;
962 + }
963 +
964 + /**
965 + * Promote a per-site baseline to the network record before dropping it
966 + *
967 + * Up to 2.11.2 the baseline was a per-site option, so on a network every
968 + * site kept its own copy of the same two files. Those copies go, but what a
969 + * copy records is which version of the file the owner approved, and that
970 + * has to survive: rebuilding the baseline from disk would take whatever is
971 + * there right now as approved, so a wp-config.php modified and still
972 + * awaiting review would be blessed in silence.
973 + *
974 + * WHICH copy becomes the network record is not a detail, and 2.11.3 got it
975 + * wrong. This runs from the scan, under wp-cron, on whichever site gets
976 + * traffic first, and the sweep from the main site can be hours away because
977 + * it waits for a network administrator to open a dashboard. So on a network
978 + * with traffic spread around, the record of the whole installation was
979 + * whatever the first subsite to scan happened to hold.
980 + *
981 + * That is harmless while every copy agrees, which is the ordinary case. The
982 + * reason they can disagree is the very thing 2.11.3 fixed: until then,
983 + * approving a change to wp-config.php took manage_options, which on a
984 + * network the administrator of every subsite holds. If a change was
985 + * approved on some subsite while the main site still had it pending review,
986 + * promoting that subsite's copy retires a warning nobody decided to retire.
987 + *
988 + * Hence the order, file by file: what the network record already holds
989 + * wins, then the main site, then the site this runs on. Between the copies,
990 + * the main site beats a subsite, which is @calzbert's point, reported after
991 + * reading the 2.11.3 diff.
992 + *
993 + * What this does NOT protect, said plainly because an earlier wording
994 + * claimed more: if the network record already holds a file, that entry
995 + * wins, even when it was written from disk by the .htaccess writer on
996 + * init:20 while a third-party edit was pending review. What survives is a
997 + * file the network record does not hold yet, which is the wp-config.php
998 + * case that 2.11.3 lost. The .htaccess case is pre-existing and needs the
999 + * writers to pass their before-hash, see update_critical_file_baseline().
1000 + *
1001 + * @since 2.11.4
1002 + *
1003 + * @param array|null $per_site Baseline stored for the site this runs on.
1004 + * @return bool True when the network record covers everything the per-site
1005 + * copy had, which is the only case where dropping it is safe.
1006 + */
1007 + private function promote_per_site_baseline( $per_site ) {
1008 + $network = get_site_option( self::BASELINE_OPTION, array() );
1009 +
1010 + if ( ! is_array( $network ) ) {
1011 + $network = array();
1012 + }
1013 +
1014 + /*
1015 + * Three sources, filled in one from another, file by file. It used to
1016 + * be all or nothing: if the network record existed at all, this
1017 + * returned at once and the caller dropped the per-site copy anyway.
1018 + *
1019 + * That looked safe and was not, because the network record can be born
1020 + * holding ONE of the two files. maybe_sync_server_files() runs on init
1021 + * and rewrites the root .htaccess by itself, and the writer calls
1022 + * update_critical_file_baseline( '.htaccess' ), which creates the
1023 + * network option with that single entry. init runs before admin_init,
1024 + * so on a network on Apache this is the ordinary order of an update,
1025 + * not a race: the cleanup then found the option "already there", kept
1026 + * nothing, and deleted the per-site copies that held the approved
1027 + * record of wp-config.php. The next scan met a file it had never seen
1028 + * and stored whatever was on disk as approved, which is the silent
1029 + * blessing this whole function exists to prevent. Reproduced on the
1030 + * Multisite install on 10 sep 2026, found by a cross review.
1031 + *
1032 + * Order of authority: what the network already says wins, then the main
1033 + * site, then the site this runs on. Nothing is ever overwritten and
1034 + * nothing is dropped for being late.
1035 + */
1036 + $sources = array( $network );
1037 +
1038 + if ( ! is_main_site() ) {
1039 + $from_main = get_blog_option( get_main_site_id(), self::BASELINE_OPTION, null );
1040 +
1041 + if ( is_array( $from_main ) ) {
1042 + $sources[] = $from_main;
1043 + }
1044 + }
1045 +
1046 + if ( is_array( $per_site ) ) {
1047 + $sources[] = $per_site;
1048 + }
1049 +
1050 + $merged = array();
1051 +
1052 + foreach ( $sources as $source ) {
1053 + foreach ( $source as $filename => $data ) {
1054 + if ( isset( $merged[ $filename ] ) || ! is_array( $data ) || ! isset( $data['hash'] ) ) {
1055 + continue;
1056 + }
1057 +
1058 + // Only the content carries secrets; the hash and the size,
1059 + // which are what say "this is the version that was approved",
1060 + // go over untouched.
1061 + if ( isset( $data['content'] ) && is_string( $data['content'] ) ) {
1062 + $data['content'] = $this->baseline_content( $filename, $data['content'] );
1063 + }
1064 +
1065 + $merged[ $filename ] = $data;
1066 + }
1067 + }
1068 +
1069 + if ( array_diff_key( $merged, $network ) ) {
1070 + $this->write_baseline( $merged );
1071 + }
1072 +
1073 + if ( ! is_array( $per_site ) ) {
1074 + return true;
1075 + }
1076 +
1077 + /*
1078 + * Is every file this copy had a record of now on the network record?
1079 + * Only then may the caller drop it. And the question is asked of what
1080 + * is STORED, not of $merged, which is only what this request MEANT to
1081 + * store. Asking $merged makes the answer true by construction, because
1082 + * the copy is one of the sources above, so the guard could never fire
1083 + * and redact_in_place() in the caller was unreachable code.
1084 + *
1085 + * The write does not always land, and the case that matters is not a
1086 + * broken database, it is the same race as the bug this function fixes.
1087 + * On a network updating from 2.11.2 the network option does not exist
1088 + * yet, so update_network_option() takes the $old_value === false branch
1089 + * and delegates to add_network_option() (wp-includes/option.php:2434).
1090 + * If another request created the option in between, that call either
1091 + * returns false without writing (option.php:2201) or, when this process
1092 + * still holds "does not exist" in its own notoptions cache, skips the
1093 + * check and INSERTs a second row: wp_sitemeta has no unique index on
1094 + * meta_key, so the record ends up duplicated and get_network_option()
1095 + * hands back whichever row comes first. Reproduced on the Multisite
1096 + * install on 10 sep 2026, with the .htaccess writer of init:20 racing a
1097 + * promotion: two rows, the approved hash of wp-config.php out of reach,
1098 + * and the per-site copy deleted all the same. Found by a cross review.
1099 + *
1100 + * Both cache keys go before rereading, and that is not belt and braces.
1101 + * add_network_option() caches the value it believes it wrote
1102 + * (option.php:2221), so a plain read hands back the very array that did
1103 + * not survive; and a stale notoptions would answer "no such option"
1104 + * without touching the database, which reads as "nothing is covered".
1105 + * Measured: without dropping the cache this guard still returns true.
1106 + */
1107 + $network_id = get_current_network_id();
1108 + wp_cache_delete( $network_id . ':' . self::BASELINE_OPTION, 'site-options' );
1109 + wp_cache_delete( $network_id . ':notoptions', 'site-options' );
1110 +
1111 + $stored = get_site_option( self::BASELINE_OPTION, array() );
1112 +
1113 + if ( ! is_array( $stored ) ) {
1114 + return false;
1115 + }
1116 +
1117 + foreach ( $per_site as $filename => $data ) {
1118 + if ( is_array( $data ) && isset( $data['hash'] ) && ! isset( $stored[ $filename ] ) ) {
1119 + return false;
1120 + }
1121 + }
1122 +
1123 + return true;
1124 + }
1125 +
1126 + /**
1127 + * Strip the secrets from a per-site copy that cannot be dropped yet
1128 + *
1129 + * The copy stays because it holds the only record of an approved file, but
1130 + * what it must not keep for one more minute is the database password and
1131 + * the eight keys and salts. The two things are separable and this is where
1132 + * they get separated.
1133 + *
1134 + * @since 2.11.4
1135 + *
1136 + * @param array $per_site Baseline stored for the current site.
1137 + * @return void
1138 + */
1139 + private function redact_in_place( $per_site ) {
1140 + $changed = false;
1141 +
1142 + foreach ( $per_site as $filename => $data ) {
1143 + if ( ! is_array( $data ) || ! isset( $data['content'] ) || ! is_string( $data['content'] ) ) {
1144 + continue;
1145 + }
1146 +
1147 + $safe = $this->baseline_content( $filename, $data['content'] );
1148 +
1149 + if ( $safe !== $data['content'] ) {
1150 + $per_site[ $filename ]['content'] = $safe;
1151 + $changed = true;
1152 + }
1153 + }
1154 +
1155 + if ( $changed ) {
1156 + update_option( self::BASELINE_OPTION, $per_site );
1157 + }
1158 + }
1159 +
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 + /**
1303 + * Clean up what earlier versions stored, wherever they stored it
1304 + *
1305 + * Two jobs, and the second one only exists on a network.
1306 + *
1307 + * The first: versions up to 2.11.1 kept the contents of wp-config.php in
1308 + * the baseline, credentials included, so what is already on disk is
1309 + * redacted in place.
1310 + *
1311 + * The second: up to 2.11.2 that baseline was a per-site option, so on a
1312 + * network every site had its own copy of the same file. This runs per site
1313 + * and removes that copy, because the baseline now lives in a single
1314 + * network option. Doing it here is what makes the cleanup reach a site
1315 + * whose dashboard nobody ever opens: this method is called from the scan
1316 + * as well as from admin_init, and the scan runs on every site through
1317 + * wp-cron with front-end traffic alone.
1318 + *
1319 + * The gate option stays per site on purpose. It records that THIS site has
1320 + * been cleaned, which is exactly the per-site fact being tracked.
1321 + *
1322 + * @since 2.11.2
1323 + */
1324 + public function maybe_redact_stored_baseline() {
1325 + if ( VIGILANTE_VERSION === get_option( self::BASELINE_REDACTION_OPTION ) ) {
1326 + return;
1327 + }
1328 +
1329 + /*
1330 + * The per-site copy left behind by 2.11.2 and earlier. On a network it
1331 + * holds the database password and the eight keys and salts, so it goes,
1332 + * but never before what it records has been carried over:
1333 + * promote_per_site_baseline() explains why the record has to outlive
1334 + * the copy, and which copy wins when they disagree. Measured on the
1335 + * Multisite install while writing 2.11.3: without that, the first scan
1336 + * after the migration reported zero modified files where it had to
1337 + * report one.
1338 + */
1339 + $pending = false;
1340 +
1341 + if ( is_multisite() ) {
1342 + $per_site = get_option( self::BASELINE_OPTION, null );
1343 +
1344 + if ( null !== $per_site ) {
1345 + if ( $this->promote_per_site_baseline( $per_site ) ) {
1346 + delete_option( self::BASELINE_OPTION );
1347 + } elseif ( is_array( $per_site ) ) {
1348 + // Something this copy recorded is not on the network record
1349 + // yet, so it does not go: it is the only evidence of what
1350 + // was approved. The secrets do go, right now, because that
1351 + // part cannot wait for the next pass.
1352 + $this->redact_in_place( $per_site );
1353 + $pending = true;
1354 + }
1355 + }
1356 + }
1357 +
1358 + $baseline = $this->read_baseline();
1359 +
1360 + if ( is_array( $baseline ) ) {
1361 + $changed = false;
1362 +
1363 + foreach ( $baseline as $filename => $data ) {
1364 + if ( ! is_array( $data ) || ! isset( $data['content'] ) || ! is_string( $data['content'] ) ) {
1365 + continue;
1366 + }
1367 +
1368 + $safe = $this->baseline_content( $filename, $data['content'] );
1369 +
1370 + if ( $safe !== $data['content'] ) {
1371 + $baseline[ $filename ]['content'] = $safe;
1372 + $changed = true;
1373 + }
1374 + }
1375 +
1376 + if ( $changed ) {
1377 + $this->write_baseline( $baseline );
1378 + }
1379 + }
1380 +
1381 + $this->redact_stored_results();
1382 +
1383 + /*
1384 + * The gate does not close while a per-site copy is still waiting to be
1385 + * promoted. Closing it would end the retries for a whole version: the
1386 + * copy would sit there unread, the file it records would be missing
1387 + * from the network record, and the next scan would take whatever is on
1388 + * disk as approved. Not closing it is not free, though, and the first
1389 + * wording here said "one option read": measured cold on the Multisite
1390 + * install, it is 6 SQL queries per admin request against 0 with the gate
1391 + * closed, admin-ajax.php and the heartbeat included, two of them from the
1392 + * cache invalidation in promote_per_site_baseline(). Acceptable only
1393 + * because it converges: the stuck case this guards against resolves on
1394 + * the next pass that gets its write through.
1395 + */
1396 + if ( ! $pending ) {
1397 + update_option( self::BASELINE_REDACTION_OPTION, VIGILANTE_VERSION, false );
1398 + }
1399 + }
1400 +
1401 + /**
1402 + * Sweep the whole network once, so it does not wait for each site's cron
1403 + *
1404 + * The per-site cleanup above reaches a site when that site runs a scan or
1405 + * someone opens its dashboard, which on a quiet subsite can take a while.
1406 + * This walks every site once and gets it over with, and its marker is a
1407 + * network option so it does not repeat per site.
1408 + *
1409 + * Runs only on the main site of the network, where a network administrator
1410 + * works, and only there does it cost anything.
1411 + *
1412 + * @since 2.11.3
1413 + */
1414 + public function maybe_sweep_network_baselines() {
1415 + if ( ! is_multisite() || ! is_main_site() ) {
1416 + return;
1417 + }
1418 +
1419 + /*
1420 + * A network administrator, and nobody else. admin_init fires for any
1421 + * logged-in visitor, a subscriber opening their own profile included,
1422 + * and this walks every site of the network writing to each one. What it
1423 + * removes is stale data that rebuilds itself, so the harm is small, but
1424 + * an action over the whole network belongs to whoever administers the
1425 + * network. The surface inventory cannot see this: it reads wp_ajax_*,
1426 + * admin_post_* and REST routes, and a hook on admin_init is outside its
1427 + * coverage by construction, which is exactly the blind spot written
1428 + * down as rule 23.
1429 + *
1430 + * The per-site cleanup is deliberately not gated the same way: it also
1431 + * runs from the scan, under wp-cron with no user at all, and it only
1432 + * touches the site it runs on.
1433 + */
1434 + if ( ! current_user_can( 'manage_network_options' ) ) {
1435 + return;
1436 + }
1437 +
1438 + $this->maybe_sweep_network_results();
1439 +
1440 + $marker = get_site_option( self::BASELINE_SWEEP_OPTION );
1441 +
1442 + /*
1443 + * Two markers, because there are two different things to remember and
1444 + * 2.11.3 only remembered one of them.
1445 + *
1446 + * The walk is marked BEFORE it starts, on purpose: on a very large
1447 + * network it may not finish inside one request, and repeating it on
1448 + * every admin page load would be worse than leaving the rest to each
1449 + * site's own scan. But 2.11.3 wrote VIGILANTE_VERSION there, so an
1450 + * interrupted walk was retried by the next release, which was the only
1451 + * thing that ever finished it. Writing a fixed literal instead, as the
1452 + * first draft of 2.11.4 did, stopped the pointless rearming and took
1453 + * that retry away with it: a walk cut short would never be resumed by
1454 + * any version. And "each site's own scan cleans the rest" only holds
1455 + * where the module is on; with it off, the cleanup is registered under
1456 + * is_admin() alone, so a subsite nobody opens is exactly what the sweep
1457 + * exists for. Found by a cross review on 10 sep 2026.
1458 + *
1459 + * So: the running version means "started here and did not finish", and
1460 + * the migration literal means "finished, never again".
1461 + */
1462 + if ( self::BASELINE_SWEEP_MIGRATION === $marker ) {
1463 + return;
1464 + }
1465 +
1466 + if ( VIGILANTE_VERSION === $marker ) {
1467 + return;
1468 + }
1469 +
1470 + update_site_option( self::BASELINE_SWEEP_OPTION, VIGILANTE_VERSION );
1471 +
1472 + // Only this network. WP_Site_Query filters by network solely when
1473 + // network_id is given, so on a multi-network install the walk would
1474 + // otherwise reach the sites of other networks and promote their copies
1475 + // into this network's record (get_current_network_id() below does not
1476 + // change with switch_to_blog()).
1477 + $site_ids = get_sites(
1478 + array(
1479 + 'fields' => 'ids',
1480 + 'number' => 0,
1481 + 'network_id' => get_current_network_id(),
1482 + 'update_site_meta_cache' => false,
1483 + )
1484 + );
1485 +
1486 + $pending = 0;
1487 +
1488 + foreach ( $site_ids as $site_id ) {
1489 + switch_to_blog( $site_id );
1490 +
1491 + $per_site = get_option( self::BASELINE_OPTION, null );
1492 +
1493 + if ( null !== $per_site ) {
1494 + // Same care as the per-site cleanup, and the same helper, so
1495 + // the two paths cannot drift apart the way they nearly did.
1496 + if ( $this->promote_per_site_baseline( $per_site ) ) {
1497 + delete_option( self::BASELINE_OPTION );
1498 + } elseif ( is_array( $per_site ) ) {
1499 + $this->redact_in_place( $per_site );
1500 + $pending++;
1501 + }
1502 + }
1503 +
1504 + restore_current_blog();
1505 + }
1506 +
1507 + // Finished, and with nothing left behind, so it never has to run again
1508 + // in any version. A site whose copy could not be promoted keeps the
1509 + // marker on the running version instead, which is what gets the walk
1510 + // retried by the next release.
1511 + if ( ! $pending ) {
1512 + update_site_option( self::BASELINE_SWEEP_OPTION, self::BASELINE_SWEEP_MIGRATION );
1513 + }
1514 + }
1515 +
1516 + /**
86 1517 * Critical root files to monitor against a stored baseline.
87 1518 * These files have no official WordPress.org checksum because their
88 1519 * content is unique per installation.
89 1520 *
@@ -212,9 +1643,24 @@
212 1643 $this->activity_log = $activity_log;
213 1644 $this->options = $settings ? $settings->get_section( 'file_integrity' ) : array();
214 1645 $this->wp_version = get_bloginfo( 'version' );
215 1646 $this->ignored_files = get_option( 'vigilante_ignored_files', array() );
1647 + }
216 1648
1649 + /**
1650 + * Register the hooks of the scanner itself
1651 + *
1652 + * Until 2.11.4 all of this lived in the constructor, and the constructor is
1653 + * called from a dozen places: the module gate, the activator, the hook that
1654 + * runs after Vigilant writes a watched file, and the admin handlers that
1655 + * only want the class as a tool. Every
1656 + * one of them registered these hooks again, and one runs during admin_init
1657 + * itself. Registering apart from constructing means a `new` is only a
1658 + * `new`, and it is what lets the cleanup below stand on its own.
1659 + *
1660 + * @since 2.11.4
1661 + */
1662 + public function init_hooks() {
217 1663 // Schedule automated scans only if options available
218 1664 if ( ! empty( $this->options['auto_scan'] ) ) {
219 1665 add_action( 'vigilante_file_integrity_scan', array( $this, 'run_scheduled_scan' ) );
220 1666 $this->schedule_scan();
@@ -229,8 +1675,35 @@
229 1675 add_action( 'vigilante_fi_postupdate_verify', array( $this, 'run_postupdate_verify' ) );
230 1676 }
231 1677
232 1678 /**
1679 + * Register the cleanup of what earlier versions stored, module on or off
1680 + *
1681 + * These two are not integrity monitoring. They take out of the database
1682 + * something the plugin stored and should not have, which is the copy of
1683 + * wp-config.php carrying the database password and the eight keys and
1684 + * salts. Whoever switched the module off did not decide to keep that, and
1685 + * for that person the cleanup matters more, not less: they are not going
1686 + * to pass through the scanner again.
1687 + *
1688 + * Until 2.11.4 these were registered in the constructor, so they only ran
1689 + * where the module was on. A site with the module off kept the credentials
1690 + * with 2.11.3 installed, and a network whose main site had it off lost the
1691 + * sweep too, which was the one path that reached the sites nobody visits.
1692 + * Reported by @calzbert after reading the 2.11.3 diff.
1693 + *
1694 + * On admin_init because that is where the baseline is looked at, and it
1695 + * does one option read per admin request until it has run once.
1696 + *
1697 + * @since 2.11.4
1698 + */
1699 + public function init_cleanup_hooks() {
1700 + add_action( 'admin_init', array( $this, 'maybe_redact_stored_baseline' ) );
1701 + add_action( 'admin_init', array( $this, 'maybe_sweep_network_baselines' ) );
1702 + add_action( 'admin_init', array( $this, 'maybe_claim_owned_blocks_on_admin' ) );
1703 + }
1704 +
1705 + /**
233 1706 * Check if scan time limit has been exceeded
234 1707 *
235 1708 * @return bool True if time exceeded.
236 1709 */
@@ -670,8 +2143,20 @@
670 2143 if ( in_array( $file, $this->core_known_false_positives, true ) ) {
671 2144 continue;
672 2145 }
673 2146
2147 + // Skip translations that travel inside the localized core ZIP but do
2148 + // not belong to core. WordPress.org's localized checksum manifest
2149 + // lists Akismet and the default themes' language files (8 entries on
2150 + // every non-en_US locale, none on en_US), yet they are updated on the
2151 + // plugin and theme cycle and are absent from the core language pack.
2152 + // Deleting an unused plugin or theme, which this plugin's own audit
2153 + // recommends, otherwise left permanent "missing core file" findings.
2154 + if ( 0 === strpos( $file, 'wp-content/languages/plugins/' )
2155 + || 0 === strpos( $file, 'wp-content/languages/themes/' ) ) {
2156 + continue;
2157 + }
2158 +
674 2159 $results['scanned']++;
675 2160
676 2161 if ( ! file_exists( $file_path ) ) {
677 2162 $results['missing'][] = array(
@@ -694,12 +2179,78 @@
694 2179 $results['ok']++;
695 2180 }
696 2181 }
697 2182
2183 + $results['modified'] = $this->drop_stale_language_mismatches( $results['modified'], $results );
2184 +
698 2185 return $results;
699 2186 }
700 2187
701 2188 /**
2189 + * Drop language files that only mismatch because the manifest was stale
2190 + *
2191 + * wp.org rebuilds the checksum manifest every time GlotPress rebuilds a
2192 + * language pack, and that happens without the WordPress version moving. The
2193 + * cache key here is version plus locale, so it does not expire when that
2194 + * happens, and the site spends up to a day comparing today's translation
2195 + * files against yesterday's manifest. That is where the bursts of "modified
2196 + * core files" under wp-content/languages/ come from, and they are not
2197 + * modifications at all.
2198 + *
2199 + * So before reporting one, the manifest is fetched again bypassing the
2200 + * cache, once per scan, and whatever matches the fresh copy is dropped.
2201 + * Anything still mismatching is reported as before.
2202 + *
2203 + * @since 2.9.9
2204 + *
2205 + * @param array $modified Entries flagged as modified.
2206 + * @param array $results Scan results, to move the recovered files to 'ok'.
2207 + * @return array Entries that are still modified.
2208 + */
2209 + private function drop_stale_language_mismatches( $modified, &$results ) {
2210 + if ( empty( $modified ) ) {
2211 + return $modified;
2212 + }
2213 +
2214 + $suspects = array();
2215 + foreach ( $modified as $entry ) {
2216 + if ( 0 === strpos( $entry['file'], 'wp-content/languages/' ) ) {
2217 + $suspects[ $entry['file'] ] = true;
2218 + }
2219 + }
2220 +
2221 + if ( empty( $suspects ) ) {
2222 + return $modified;
2223 + }
2224 +
2225 + $fresh = $this->get_core_checksums( true );
2226 +
2227 + if ( is_wp_error( $fresh ) || empty( $fresh ) ) {
2228 + return $modified;
2229 + }
2230 +
2231 + $kept = array();
2232 +
2233 + foreach ( $modified as $entry ) {
2234 + $file = $entry['file'];
2235 +
2236 + if ( ! isset( $suspects[ $file ] ) || ! isset( $fresh[ $file ] ) ) {
2237 + $kept[] = $entry;
2238 + continue;
2239 + }
2240 +
2241 + if ( $this->hash_matches_published( ABSPATH . $file, $fresh[ $file ] ) ) {
2242 + $results['ok']++;
2243 + continue;
2244 + }
2245 +
2246 + $kept[] = $entry;
2247 + }
2248 +
2249 + return $kept;
2250 + }
2251 +
2252 + /**
702 2253 * Scan WordPress root directory for non-core files
703 2254 *
704 2255 * Compares files in ABSPATH (non-recursive) against the official core
705 2256 * checksums list. PHP files not in the core distribution are flagged as
@@ -848,18 +2399,71 @@
848 2399 * silently — there is nothing to compare against.
849 2400 *
850 2401 * @return array Array of modified file entries (same format as core modified).
851 2402 */
2403 + /**
2404 + * Where a critical root file actually lives
2405 + *
2406 + * WordPress supports wp-config.php one directory above ABSPATH, guarded by
2407 + * wp-settings.php not being there: that is literally what the installed core
2408 + * does in wp-load.php, and it is a common hardening layout. Until 2.11.10
2409 + * this module only looked inside ABSPATH, so on those installations
2410 + * wp-config.php was never added to the baseline, never compared and never
2411 + * mentioned: the module reported the site clean without having opened the
2412 + * one file it most needs to watch. A zero is justified, never assumed. The
2413 + * plugin already resolved both locations elsewhere
2414 + * (Vigilante_Database_Prefix::find_wpconfig_path()), just not here. Found by
2415 + * the file-by-file review of 2.11.10.
2416 + *
2417 + * @since 2.11.10
2418 + *
2419 + * @param string $filename Name of the file, such as wp-config.php.
2420 + * @return string|false Absolute path, or false when it cannot be found.
2421 + */
2422 + private function critical_file_path( $filename ) {
2423 + $root = untrailingslashit( ABSPATH );
2424 + $path = $root . '/' . $filename;
2425 +
2426 + if ( file_exists( $path ) ) {
2427 + return $path;
2428 + }
2429 +
2430 + if ( 'wp-config.php' === $filename ) {
2431 + $above = dirname( $root ) . '/wp-config.php';
2432 +
2433 + // Suppressed like the core does in wp-load.php: the directory above
2434 + // the install is often outside open_basedir on shared hosting, and
2435 + // without the @ every scan emits a warning that can land in front of
2436 + // the JSON of an AJAX scan.
2437 + // 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.
2438 + if ( @file_exists( $above ) && ! @file_exists( dirname( $root ) . '/wp-settings.php' ) ) {
2439 + return $above;
2440 + }
2441 + }
2442 +
2443 + return false;
2444 + }
2445 +
852 2446 private function scan_critical_root_files() {
2447 + // Before reading anything: the scan is the only thing that reaches
2448 + // every site of a network on its own, through wp-cron and front-end
2449 + // traffic. Hooking the cleanup to admin_init alone left every subsite
2450 + // whose dashboard nobody opens with its old copy of wp-config.php,
2451 + // credentials included, for as long as nobody visited it.
2452 + $this->maybe_redact_stored_baseline();
2453 +
2454 + // And claim the blocks already on disk before anything is compared,
2455 + // so the first scan after updating uses the rule that will stay.
2456 + $this->maybe_claim_owned_blocks();
2457 +
853 2458 $modified = array();
854 2459 $baseline = $this->get_critical_files_baseline();
855 2460 $baseline_changed = false;
856 - $root_path = untrailingslashit( ABSPATH );
857 2461
858 2462 foreach ( $this->critical_root_files as $filename ) {
859 - $full_path = $root_path . '/' . $filename;
2463 + $full_path = $this->critical_file_path( $filename );
860 2464
861 - if ( ! file_exists( $full_path ) ) {
2465 + if ( false === $full_path ) {
862 2466 continue;
863 2467 }
864 2468
865 2469 $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
@@ -874,9 +2478,9 @@
874 2478 // First time seeing this file — store baseline silently
875 2479 $baseline[ $filename ] = array(
876 2480 'hash' => $current_hash,
877 2481 'size' => strlen( $content ),
878 - 'content' => $normalized,
2482 + 'content' => $this->baseline_content( $filename, $normalized ),
879 2483 'updated' => time(),
880 2484 );
881 2485 $baseline_changed = true;
882 2486 continue;
@@ -883,34 +2487,85 @@
883 2487 }
884 2488
885 2489 // Upgrade legacy baseline entries that lack content (pre-diff format)
886 2490 if ( ! isset( $baseline[ $filename ]['content'] ) && $baseline[ $filename ]['hash'] === $current_hash ) {
887 - $baseline[ $filename ]['content'] = $normalized;
2491 + $baseline[ $filename ]['content'] = $this->baseline_content( $filename, $normalized );
888 2492 $baseline_changed = true;
889 2493 continue;
890 2494 }
891 2495
892 - // Compare against stored baseline
893 - if ( $baseline[ $filename ]['hash'] !== $current_hash ) {
2496 + /*
2497 + * The file has not changed, but the copy on record is not the copy
2498 + * that would be stored today: an entry written before 2.11.2 with
2499 + * the credentials in it, or one written before the redaction list
2500 + * grew. Rewrite it.
2501 + *
2502 + * Only when the hash matches, and that condition is the whole
2503 + * point: if the file HAD changed, this entry is the evidence of
2504 + * the change that the administrator still has to review, and
2505 + * rewriting it here would quietly destroy that evidence.
2506 + */
2507 + if ( $baseline[ $filename ]['hash'] === $current_hash ) {
2508 + $expected = $this->baseline_content( $filename, $normalized );
2509 +
2510 + if ( $expected !== $baseline[ $filename ]['content'] ) {
2511 + $baseline[ $filename ]['content'] = $expected;
2512 + $baseline_changed = true;
2513 + }
2514 +
2515 + continue;
2516 + }
2517 +
2518 + /*
2519 + * Everything from here down is the changed file, and only that: the
2520 + * branch above returns on every matching hash, so there is no third
2521 + * case and no condition left to test. It used to be wrapped in an
2522 + * `if` repeating the opposite comparison, which read as if some
2523 + * other path could reach this point. It could not. Flagged by
2524 + * @calzbert, and worth the two lines it costs to say so.
2525 + *
2526 + * Both sides go through the same redaction, or every credential
2527 + * line would read as a change nobody made.
2528 + */
2529 + /*
2530 + * Where the shared files do not belong to this site, the lines are
2531 + * not computed at all. The diff is shown to whoever can open this
2532 + * site's screen, the administrator of a subsite included, and it
2533 + * was stored in the options of every subsite with the module on.
2534 + * Found by the audit of the admin surface for 2.11.8. The change is
2535 + * still reported, with both sizes, and the lines are read on the
2536 + * main site, where the change is approved.
2537 + */
2538 + if ( ! Vigilante_Settings::owns_shared_files() ) {
2539 + $diff = self::network_only_diff();
2540 + } else {
894 2541 $baseline_content = $baseline[ $filename ]['content'] ?? '';
895 - $diff = '' !== $baseline_content
896 - ? $this->compute_simple_diff( $baseline_content, $normalized )
2542 + $current_content = $this->baseline_content( $filename, $normalized );
2543 + $diff = ( '' !== $baseline_content && '' !== $current_content )
2544 + ? $this->compute_simple_diff( $baseline_content, $current_content )
897 2545 : array( 'added' => array(), 'removed' => array(), 'unavailable' => true );
898 2546
899 - $modified[] = array(
900 - 'file' => $filename,
901 - 'type' => 'critical_config',
902 - 'expected_hash' => $baseline[ $filename ]['hash'],
903 - 'actual_hash' => $current_hash,
904 - 'baseline_size' => $baseline[ $filename ]['size'],
905 - 'current_size' => strlen( $content ),
906 - 'diff' => $diff,
907 - );
2547 + // Say why there are no lines when today's copy could not be
2548 + // made safe, which approving does not change: the generic
2549 + // message talks about an old baseline. Cross review of 2.11.8.
2550 + if ( '' === $current_content && 'wp-config.php' === $filename ) {
2551 + $diff['redaction'] = true;
2552 + }
908 2553 }
2554 +
2555 + $modified[] = array(
2556 + 'file' => $filename,
2557 + 'type' => 'critical_config',
2558 + 'expected_hash' => $baseline[ $filename ]['hash'],
2559 + 'actual_hash' => $current_hash,
2560 + 'baseline_size' => $baseline[ $filename ]['size'],
2561 + 'current_size' => strlen( $content ),
2562 + 'diff' => $diff,
2563 + );
909 2564 }
910 2565
911 2566 if ( $baseline_changed ) {
912 - update_option( self::BASELINE_OPTION, $baseline, false );
2567 + $this->write_baseline( $baseline );
913 2568 }
914 2569
915 2570 return $modified;
916 2571 }
@@ -982,30 +2637,49 @@
982 2637 * @param string $filename File name (e.g. 'wp-config.php').
983 2638 * @param string $content Raw file content.
984 2639 * @return string Normalized content for hashing.
985 2640 */
986 - private function normalize_critical_file( $filename, $content ) {
2641 + private function normalize_critical_file( $filename, $content, $drop_all_original = false ) {
987 2642 // Normalize line endings first (CRLF and CR to LF)
988 2643 $content = str_replace( array( "\r\n", "\r" ), "\n", $content );
989 2644
2645 + /*
2646 + * Vigilant's own blocks are left out of the hash, so rewriting them is
2647 + * not reported as somebody else's change. Until 2.11.5 that covered
2648 + * everything between the markers, and every line carrying the
2649 + * [VIGILANTE_ORIGINAL] marker, whatever they contained. From 2.11.5 a
2650 + * block is left out only if it is exactly a block Vigilant wrote (see
2651 + * remember_owned_block()), and a marked line only while uncommenting it
2652 + * would still give a harmless define() (see is_vigilant_original_line()).
2653 + *
2654 + * Until the blocks already on disk have been claimed, the old rule
2655 + * applies unchanged. That is what keeps an update from changing the
2656 + * hash of a file nobody touched.
2657 + */
2658 + $claimed = $this->owned_blocks_claimed();
2659 +
990 2660 if ( 'wp-config.php' === $filename ) {
991 - // Remove Vigilante constants blocks (current and legacy)
2661 + // Vigilante constants blocks (current and legacy)
992 2662 foreach ( $this->wpconfig_markers as $markers ) {
993 - $pattern = '/' . preg_quote( $markers[0], '/' ) . '.*?' . preg_quote( $markers[1], '/' ) . '\s*/s';
994 - $content = preg_replace( $pattern, '', $content );
2663 + $content = $this->strip_vigilant_blocks( $filename, $content, $markers, $claimed );
995 2664 }
996 2665
997 - // Remove lines commented out by Vigilante (original constants)
998 - $content = preg_replace(
2666 + // Lines commented out by Vigilante (original constants)
2667 + $content = preg_replace_callback(
999 2668 '/^.*' . preg_quote( $this->wpconfig_original_marker, '/' ) . '.*$/m',
1000 - '',
2669 + function ( $line ) use ( $claimed, $drop_all_original ) {
2670 + // $drop_all_original reproduce la regla anterior a la 2.11.5 (quitar
2671 + // toda linea marcada) sobre los bloques de la regla nueva. Solo lo usa
2672 + // el re-base de la transicion, para decidir si la unica diferencia con
2673 + // el registro aprobado son estas lineas. Ver rebase_original_line_shift().
2674 + return ( ! $claimed || $drop_all_original || $this->is_vigilant_original_line( $line[0] ) ) ? '' : $line[0];
2675 + },
1001 2676 $content
1002 2677 );
1003 2678 } elseif ( '.htaccess' === $filename ) {
1004 - // Remove Vigilante htaccess blocks (firewall + security headers)
2679 + // Vigilante htaccess blocks (firewall + security headers)
1005 2680 foreach ( $this->htaccess_markers as $markers ) {
1006 - $pattern = '/' . preg_quote( $markers[0], '/' ) . '.*?' . preg_quote( $markers[1], '/' ) . '\s*/s';
1007 - $content = preg_replace( $pattern, '', $content );
2681 + $content = $this->strip_vigilant_blocks( $filename, $content, $markers, $claimed );
1008 2682 }
1009 2683 }
1010 2684
1011 2685 // Collapse multiple blank lines into one (blocks removal leaves gaps)
@@ -1014,15 +2688,645 @@
1014 2688 return trim( $content );
1015 2689 }
1016 2690
1017 2691 /**
2692 + * Leave Vigilant's blocks for one pair of markers out of the content
2693 + *
2694 + * Before the claim, every block, as it always was. After it, only the blocks
2695 + * whose fingerprint was recorded when Vigilant wrote them. A block that does
2696 + * not match, edited or planted, stays in the content: it counts in the hash
2697 + * and shows up in the diff.
2698 + *
2699 + * The match runs from marker to marker and the removal also takes the
2700 + * whitespace after the block, exactly as before, so a file whose blocks are
2701 + * all Vigilant's normalizes to the same text under both rules.
2702 + *
2703 + * @since 2.11.5
2704 + *
2705 + * @param string $filename 'wp-config.php' or '.htaccess'.
2706 + * @param string $content Content with normalized line endings.
2707 + * @param array $markers Start and end marker.
2708 + * @param bool $claimed Whether the claim has run.
2709 + * @return string
2710 + */
2711 + private function strip_vigilant_blocks( $filename, $content, $markers, $claimed ) {
2712 + $pattern = '/(' . preg_quote( $markers[0], '/' ) . '.*?' . preg_quote( $markers[1], '/' ) . ')\s*/s';
2713 +
2714 + if ( ! $claimed ) {
2715 + return preg_replace( $pattern, '', $content );
2716 + }
2717 +
2718 + return preg_replace_callback(
2719 + $pattern,
2720 + function ( $match ) use ( $filename ) {
2721 + return self::is_owned_block( $filename, $match[1] ) ? '' : $match[0];
2722 + },
2723 + $content
2724 + );
2725 + }
2726 +
2727 + /**
2728 + * Whether a line carrying the original-constant marker is one Vigilant wrote
2729 + *
2730 + * comment_existing_constants() puts the marker in front of a define() of a
2731 + * constant it manages, and uncomment_original_constants() takes it away
2732 + * again whenever the constants are applied or removed, so whatever follows
2733 + * the marker gets to run some day. The line is left out of the hash only
2734 + * when there is nothing but indentation before the marker, nothing after it
2735 + * but a harmless define() and at most a line comment, and no PHP tag
2736 + * anywhere on it. That keeps it a comment today and harmless once
2737 + * uncommented. Anything else counts, and shows up in the diff.
2738 + *
2739 + * @since 2.11.5
2740 + *
2741 + * @param string $line One line of wp-config.php.
2742 + * @return bool
2743 + */
2744 + /**
2745 + * Whether every marked line of a file can run nothing at all
2746 + *
2747 + * The question the re-base has to answer before adopting a file is whether
2748 + * the lines that carry the marker are only comments. Asking a stricter one
2749 + * was wrong in both directions: the first version of the guard used
2750 + * is_vigilant_original_line(), which also requires the commented define to
2751 + * match a known harmless shape, so it refused to re-base a perfectly inert
2752 + * line carrying an unusual define, which is exactly the case the re-base
2753 + * exists for, leaving the function unable to act at all. Found by the cross
2754 + * review of 2.11.10.
2755 + *
2756 + * The second version read one line at a time and reasoned that the marker
2757 + * begins with //, so a line with nothing but whitespace before it is wholly
2758 + * a comment. That is true only where PHP is already reading code, and the
2759 + * second cross review of 2.11.10 built three files where it is not, all of
2760 + * them valid PHP, all of them passing that test and all of them running or
2761 + * printing something:
2762 + *
2763 + * - the marked line placed BEFORE the opening <?php, so it is inline HTML
2764 + * that the server prints verbatim to the browser;
2765 + * - the same after a ?> that the file already had;
2766 + * - the marked line ending a block comment opened on an earlier line and
2767 + * opening another one at its end, with a statement in between, which
2768 + * runs like any other statement.
2769 + *
2770 + * So the file is read the way PHP reads it, not the way the line looks. A
2771 + * marked line is inert when every token touching it is a comment or
2772 + * whitespace, which answers the three at once: inline HTML is not a comment,
2773 + * and neither is a statement. The shape the guard was written for, code
2774 + * BEFORE the marker, is the same question from the other side.
2775 + *
2776 + * The three shapes are in the harness as cells X2, X3 and X4 of
2777 + * matriz-escondite-marcadores.sh, written out in full there. They are not
2778 + * written out here on purpose: a literal payload in a shipped file is
2779 + * signature surface for the scanners this plugin is read by, and a comment
2780 + * is a bad place to pay for it.
2781 + *
2782 + * @since 2.11.10
2783 + *
2784 + * @param string $content Whole file content.
2785 + * @return bool True when no marked line can run or print anything.
2786 + */
2787 + /**
2788 + * The lines of a file that carry the original-value marker
2789 + *
2790 + * @since 2.11.10
2791 + *
2792 + * @param string $content Whole file content, newlines already normalised.
2793 + * @return string[]
2794 + */
2795 + private function marked_lines_of( $content ) {
2796 + $out = array();
2797 +
2798 + foreach ( explode( "\n", $content ) as $text ) {
2799 + if ( false !== strpos( $text, $this->wpconfig_original_marker ) ) {
2800 + $out[] = $text;
2801 + }
2802 + }
2803 +
2804 + return $out;
2805 + }
2806 +
2807 + /**
2808 + * Whether what a marked line carries would still be harmless uncommented
2809 + *
2810 + * Only the part after the marker matters: what comes before it is answered by
2811 + * the token pass, which refuses anything that is not comment or whitespace.
2812 + * Here the question is what comes BACK when uncomment_original_constants()
2813 + * removes the marker, so the body has to be a single define() and nothing
2814 + * else, with at most a trailing line comment. Deliberately says nothing about
2815 + * WHICH constant it is: asking that was the first version of this guard, and
2816 + * it refused every define it did not recognise, which is exactly the case the
2817 + * re-base exists for.
2818 + *
2819 + * @since 2.11.10
2820 + *
2821 + * @param string $line One line carrying the marker.
2822 + * @return bool
2823 + */
2824 + private function marked_line_body_is_harmless( $line ) {
2825 + $at = strpos( $line, $this->wpconfig_original_marker );
2826 +
2827 + if ( false === $at ) {
2828 + return true;
2829 + }
2830 +
2831 + $body = trim( substr( $line, $at + strlen( $this->wpconfig_original_marker ) ) );
2832 +
2833 + if ( '' === $body ) {
2834 + return true;
2835 + }
2836 +
2837 + // Tokenised as PHP so the trailing comment, the strings and the nesting
2838 + // are read the way PHP reads them and not with a regular expression.
2839 + $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.
2840 +
2841 + if ( empty( $tokens ) ) {
2842 + return false;
2843 + }
2844 +
2845 + $statements = 0;
2846 + $depth = 0;
2847 +
2848 + foreach ( $tokens as $token ) {
2849 + $type = is_array( $token ) ? $token[0] : $token;
2850 +
2851 + if ( in_array( $type, array( T_OPEN_TAG, T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) {
2852 + continue;
2853 + }
2854 +
2855 + if ( '(' === $type ) {
2856 + $depth++;
2857 + continue;
2858 + }
2859 +
2860 + if ( ')' === $type ) {
2861 + $depth--;
2862 + continue;
2863 + }
2864 +
2865 + // A semicolon at the top level closes a statement. More than one, or
2866 + // anything after the first, means the line carries something else.
2867 + if ( ';' === $type && 0 === $depth ) {
2868 + $statements++;
2869 + continue;
2870 + }
2871 +
2872 + if ( $statements > 0 ) {
2873 + return false;
2874 + }
2875 + }
2876 +
2877 + return ( $statements <= 1 );
2878 + }
2879 +
2880 + private function marked_lines_are_inert( $content ) {
2881 + $content = str_replace( "\r\n", "\n", (string) $content );
2882 + $marker = $this->wpconfig_original_marker;
2883 +
2884 + if ( '' === $content || false === strpos( $content, $marker ) ) {
2885 + return true;
2886 + }
2887 +
2888 + $marked = array();
2889 +
2890 + foreach ( explode( "\n", $content ) as $index => $text ) {
2891 + if ( false !== strpos( $text, $marker ) ) {
2892 + $marked[ $index + 1 ] = true;
2893 + }
2894 + }
2895 +
2896 + // Lenient on purpose (no TOKEN_PARSE): a tampered file still has to be
2897 + // read, and a file that cannot be tokenised is never adopted.
2898 + // 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.
2899 + $tokens = @token_get_all( $content );
2900 +
2901 + if ( empty( $tokens ) ) {
2902 + return false;
2903 + }
2904 +
2905 + /*
2906 + * And the other half of the question, which the first token version left
2907 + * out: a marked line is a COMMENTED OUT value, and uncommenting it is what
2908 + * the feature exists for, so "runs nothing today" is not enough. Anything
2909 + * sharing the line after the define comes back with it. The shape is real
2910 + * and needs no attacker: comment_existing_constants() takes a define and
2911 + * everything on its line, so
2912 + * define( 'WP_DEBUG', false ); @ini_set( 'display_errors', 0 );
2913 + * is commented whole, and re-basing it would adopt as approved something
2914 + * that runs the moment the value is restored. The old rule refused this
2915 + * too, but along with every define whose NAME it did not recognise, which
2916 + * is what left the function unable to act at all. Found by the third cross
2917 + * review of 2.11.10.
2918 + */
2919 + foreach ( $this->marked_lines_of( $content ) as $text ) {
2920 + if ( ! $this->marked_line_body_is_harmless( $text ) ) {
2921 + return false;
2922 + }
2923 + }
2924 +
2925 + $inocuos = array( T_COMMENT, T_DOC_COMMENT, T_WHITESPACE );
2926 + $linea = 1;
2927 +
2928 + foreach ( $tokens as $token ) {
2929 + $texto = is_array( $token ) ? $token[1] : $token;
2930 + $tipo = is_array( $token ) ? $token[0] : null;
2931 + $saltos = substr_count( $texto, "\n" );
2932 + $desde = $linea;
2933 + $hasta = $linea + $saltos;
2934 +
2935 + /*
2936 + * A token whose text ends in a newline puts nothing on the line that
2937 + * newline opens. Counting it would make the "<?php\n" of every file
2938 + * touch line 2 and refuse the legitimate case, which is what the
2939 + * first version of this did.
2940 + */
2941 + $ultima = ( $saltos > 0 && "\n" === substr( $texto, -1 ) ) ? $hasta - 1 : $hasta;
2942 + $linea = $hasta;
2943 +
2944 + if ( null !== $tipo && in_array( $tipo, $inocuos, true ) ) {
2945 + continue;
2946 + }
2947 +
2948 + for ( $l = $desde; $l <= $ultima; $l++ ) {
2949 + if ( isset( $marked[ $l ] ) ) {
2950 + return false;
2951 + }
2952 + }
2953 + }
2954 +
2955 + return true;
2956 + }
2957 +
2958 + private function is_vigilant_original_line( $line ) {
2959 + if ( false !== strpos( $line, '<?' ) || false !== strpos( $line, '?>' ) ) {
2960 + return false;
2961 + }
2962 +
2963 + return 1 === preg_match(
2964 + '/^[ \t]*' . preg_quote( $this->wpconfig_original_marker, '/' ) . self::harmless_define_pattern() . '[ \t]*(?:(?:\/\/|#(?!\[)).*)?$/',
2965 + $line
2966 + );
2967 + }
2968 +
2969 + /**
2970 + * A define() that runs nothing but itself, as a regular expression fragment
2971 + *
2972 + * The name is one of the constants Vigilant has managed in any version. The
2973 + * value is made only of literals (true, false, null, a number, a quoted
2974 + * string with nothing to interpolate) and of ABSPATH, WP_CONTENT_DIR and
2975 + * __DIR__, which is what a debug log path is usually built from, joined
2976 + * with dots. No call, no variable, no backtick, no include.
2977 + *
2978 + * @since 2.11.5
2979 + *
2980 + * @return string Pattern without delimiters.
2981 + */
2982 + private static function harmless_define_pattern() {
2983 + $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'
2984 + . '|WP_POST_REVISIONS|AUTOSAVE_INTERVAL|EMPTY_TRASH_DAYS|WP_MEMORY_LIMIT|WP_MAX_MEMORY_LIMIT|WP_AUTO_UPDATE_CORE|CONCATENATE_SCRIPTS';
2985 +
2986 + $value = '(?:(?i:true|false|null)|-?\d+|\'(?:[^\'\\\\]|\\\\.)*\'|"[^"\\\\$]*"|ABSPATH|WP_CONTENT_DIR|__DIR__)';
2987 +
2988 + return 'define\s*\(\s*[\'"](?:' . $names . ')[\'"]\s*,\s*' . $value . '(?:\s*\.\s*' . $value . ')*\s*\)\s*;';
2989 + }
2990 +
2991 + /**
2992 + * Whether a wp-config.php constants block can only be one Vigilant wrote
2993 + *
2994 + * Every version of generate_constants() has written the start marker on its
2995 + * own line, then comments, blank lines and define() calls, bare or wrapped
2996 + * in if ( ! defined() ), then the end marker on its own line. A block made
2997 + * only of those lines runs nothing but the defines, whatever version wrote
2998 + * it and whatever settings it was written with. One line of anything else,
2999 + * or a PHP tag on any line, and the block is not taken.
3000 + *
3001 + * @since 2.11.5
3002 + *
3003 + * @param string $block Block from start marker to end marker, inclusive.
3004 + * @param array $markers Start and end marker.
3005 + * @return bool
3006 + */
3007 + private static function is_harmless_constants_block( $block, $markers ) {
3008 + $lines = explode( "\n", str_replace( array( "\r\n", "\r" ), "\n", (string) $block ) );
3009 +
3010 + if ( count( $lines ) < 2
3011 + || rtrim( array_shift( $lines ), " \t" ) !== $markers[0]
3012 + || ltrim( array_pop( $lines ), " \t" ) !== $markers[1]
3013 + ) {
3014 + return false;
3015 + }
3016 +
3017 + $define = self::harmless_define_pattern();
3018 + $guarded = '/^if\s*\(\s*!\s*defined\s*\(\s*[\'"][A-Z_]+[\'"]\s*\)\s*\)\s*\{\s*' . $define . '\s*\}$/';
3019 +
3020 + foreach ( $lines as $line ) {
3021 + $line = trim( $line, " \t" );
3022 +
3023 + if ( false !== strpos( $line, '<?' ) || false !== strpos( $line, '?>' ) ) {
3024 + return false;
3025 + }
3026 +
3027 + if ( '' === $line
3028 + || 0 === strpos( $line, '//' )
3029 + || preg_match( '/^' . $define . '$/', $line )
3030 + || preg_match( $guarded, $line )
3031 + ) {
3032 + continue;
3033 + }
3034 +
3035 + return false;
3036 + }
3037 +
3038 + return true;
3039 + }
3040 +
3041 + /**
3042 + * Take ownership of the blocks already on disk, once
3043 + *
3044 + * Fingerprints are recorded when Vigilant writes a block, which leaves every
3045 + * block written before 2.11.5 without one. This records the blocks that can
3046 + * be recognised as Vigilant's without having seen them written:
3047 + *
3048 + * - A .htaccess block, when it is exactly what Vigilant would write today
3049 + * with the settings it has, the timestamp and the version apart. After an
3050 + * update, maybe_sync_server_files() rewrites those blocks on the next
3051 + * request, so the claim waits for it. Unless it has already failed: a
3052 + * block Vigilant cannot rewrite is not going to start matching, and
3053 + * waiting for it would keep the old rule for good.
3054 + * - A wp-config.php constants block, when every line in it is a comment, a
3055 + * blank line or a harmless define(). Nothing rewrites that block on an
3056 + * update and its format has changed five times, so comparing it with
3057 + * today's output would report every site that has not saved those
3058 + * settings since. A line that could run anything is never accepted.
3059 + *
3060 + * A block that is not recognised stays in the hash and is reported as a
3061 + * change, so the owner gets to look at it, and the activity log says why.
3062 + * Nothing in the stored baseline is rewritten.
3063 + *
3064 + * Only where the shared files belong, a single site or the main site of a
3065 + * network, because the expected blocks come from that site's settings. Until
3066 + * it has run, normalize_critical_file() keeps the old rule on every site.
3067 + *
3068 + * @since 2.11.5
3069 + */
3070 + /**
3071 + * The admin_init entry point of the claim, which does ask for an administrator
3072 + *
3073 + * admin-ajax.php fires admin_init before it decides who is asking
3074 + * (wp-admin/admin-ajax.php:45), so without this an anonymous request chose
3075 + * the moment the claim runs. Unlike its two neighbours in
3076 + * init_cleanup_hooks(), which only drop the plugin's own copy out of the
3077 + * database, the claim writes two network options, changes for the whole
3078 + * network the rule normalize_critical_file() applies, and re-bases the
3079 + * approved baseline.
3080 + *
3081 + * The gate lives here and not inside maybe_claim_owned_blocks() because the
3082 + * scan calls that one directly and the scan runs from wp-cron, with no user:
3083 + * putting the capability check inside left the claim unable to complete on
3084 + * any site whose dashboard nobody opens, and until it completes the older,
3085 + * permissive rule is the one in force, which is the hiding place 2.11.5 was
3086 + * written to close. Found by the cross review of 2.11.10.
3087 + *
3088 + * @since 2.11.10
3089 + */
3090 + public function maybe_claim_owned_blocks_on_admin() {
3091 + if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
3092 + return;
3093 + }
3094 +
3095 + $this->maybe_claim_owned_blocks();
3096 + }
3097 +
3098 + public function maybe_claim_owned_blocks() {
3099 + if ( $this->owned_blocks_claimed() || ! Vigilante_Settings::owns_shared_files() ) {
3100 + return;
3101 + }
3102 +
3103 + $sync_due = get_option( 'vigilante_server_files_pending' )
3104 + || VIGILANTE_VERSION !== get_option( 'vigilante_server_files_version' );
3105 +
3106 + if ( $sync_due && ! get_option( 'vigilante_server_files_retry_after' ) ) {
3107 + return;
3108 + }
3109 +
3110 + $expected = null;
3111 + $unclaimed = array();
3112 +
3113 + foreach ( $this->critical_root_files as $filename ) {
3114 + $full_path = $this->critical_file_path( $filename );
3115 +
3116 + if ( false === $full_path ) {
3117 + continue;
3118 + }
3119 +
3120 + $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
3121 +
3122 + if ( false === $content ) {
3123 + // Unreadable right now: leave the claim open and try again later.
3124 + return;
3125 + }
3126 +
3127 + $content = str_replace( array( "\r\n", "\r" ), "\n", $content );
3128 + $is_config = 'wp-config.php' === $filename;
3129 +
3130 + foreach ( ( $is_config ? $this->wpconfig_markers : $this->htaccess_markers ) as $markers ) {
3131 + $pattern = '/' . preg_quote( $markers[0], '/' ) . '.*?' . preg_quote( $markers[1], '/' ) . '/s';
3132 +
3133 + if ( ! preg_match_all( $pattern, $content, $found ) ) {
3134 + continue;
3135 + }
3136 +
3137 + foreach ( $found[0] as $block ) {
3138 + if ( $is_config ) {
3139 + $ours = self::is_harmless_constants_block( $block, $markers );
3140 + } else {
3141 + $expected = null === $expected ? $this->expected_htaccess_blocks() : $expected;
3142 + $ours = isset( $expected[ $markers[0] ] )
3143 + && self::comparable_block( $block ) === self::comparable_block( $expected[ $markers[0] ] );
3144 + }
3145 +
3146 + if ( $ours ) {
3147 + self::remember_owned_block( $filename, $markers[0], $block, false );
3148 + } else {
3149 + $unclaimed[ $filename ] = $filename;
3150 + }
3151 + }
3152 + }
3153 +
3154 + // The commented-out originals are judged line by line at scan time.
3155 + // Looking at them here only keeps the log entry below complete.
3156 + if ( $is_config && preg_match_all( '/^.*' . preg_quote( $this->wpconfig_original_marker, '/' ) . '.*$/m', $content, $marked ) ) {
3157 + foreach ( $marked[0] as $line ) {
3158 + if ( ! $this->is_vigilant_original_line( $line ) ) {
3159 + $unclaimed[ $filename ] = $filename;
3160 + }
3161 + }
3162 + }
3163 + }
3164 +
3165 + update_site_option( self::OWNED_BLOCKS_CLAIM_OPTION, self::OWNED_BLOCKS_CLAIMED );
3166 +
3167 + // With the claim in place normalize uses the new rule, so a file nobody
3168 + // touched whose only difference is an original line the old rule dropped
3169 + // would read as changed. Re-base those, and only those, once.
3170 + $this->rebase_original_line_shift();
3171 +
3172 + if ( $unclaimed && $this->activity_log ) {
3173 + $this->activity_log->log(
3174 + 'file',
3175 + 'critical_file_unrecognized_block',
3176 + sprintf(
3177 + /* translators: %s: comma-separated file names, such as wp-config.php or .htaccess. */
3178 + __( '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' ),
3179 + implode( ', ', $unclaimed )
3180 + ),
3181 + array( 'files' => array_values( $unclaimed ) ),
3182 + 'warning'
3183 + );
3184 + }
3185 + }
3186 +
3187 + /**
3188 + * Re-base the critical files whose only change is a newly kept original line
3189 + *
3190 + * Until 2.11.5 the hash left out every [VIGILANTE_ORIGINAL] line; from 2.11.5
3191 + * it keeps the ones whose value is not a plain constant define, which is the
3192 + * right thing for the hash but moves it on a file nobody edited: the stored
3193 + * baseline was taken under the old rule, and nothing re-bases wp-config.php on
3194 + * an update (maybe_sync_server_files() only rewrites the .htaccess). So the
3195 + * first scan after updating would report wp-config.php as changed.
3196 + *
3197 + * This runs once, in the same pass that claims the blocks. For each file it
3198 + * re-bases to the new hash only when the baseline still matches the file with
3199 + * every original line dropped, which means the blocks are exactly the approved
3200 + * ones and the sole difference is those lines, the user's own commented-out
3201 + * defines. A block that was edited or planted does not match with the lines
3202 + * dropped, so it is left to be reported: this closes the false positive
3203 + * without adopting anything that was hidden before.
3204 + *
3205 + * @since 2.11.5
3206 + */
3207 + private function rebase_original_line_shift() {
3208 + $baseline = $this->get_critical_files_baseline();
3209 + $changed = false;
3210 +
3211 + foreach ( $this->critical_root_files as $filename ) {
3212 + $full_path = $this->critical_file_path( $filename );
3213 +
3214 + if ( false === $full_path || empty( $baseline[ $filename ]['hash'] ) ) {
3215 + continue;
3216 + }
3217 +
3218 + $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
3219 +
3220 + if ( false === $content ) {
3221 + continue;
3222 + }
3223 +
3224 + /*
3225 + * Never re-base a file that carries a marked line which is not
3226 + * wholly a comment. The test below only establishes that the
3227 + * difference lies in lines carrying the marker, and the old rule
3228 + * dropped the WHOLE line, so a line with a statement in front of the
3229 + * marker satisfies it (cell X1 of matriz-escondite-marcadores.sh,
3230 + * where the shape is written out): re-basing would write that line
3231 + * into the approved baseline and rewrite the stored content, so the
3232 + * diff would stop showing it. Adopting as approved what the previous rule
3233 + * hid is the one thing an integrity scanner must never do, and the
3234 + * log entry of maybe_claim_owned_blocks() already promises the
3235 + * opposite ("the scan reports it as a change for you to review").
3236 + * Those files are left to be reported. Found by the file-by-file
3237 + * review of 2.11.10.
3238 + *
3239 + * What counts as "wholly a comment" is decided by reading the file
3240 + * as PHP reads it, not by the shape of the line: see
3241 + * marked_lines_are_inert(). A line that is not recognised is not the
3242 + * same thing as a line that can run something, and the first
3243 + * wording of this guard confused the two.
3244 + */
3245 + if ( ! $this->marked_lines_are_inert( $content ) ) {
3246 + continue;
3247 + }
3248 +
3249 + $current = md5( $this->normalize_critical_file( $filename, $content ) );
3250 +
3251 + // Already in step, or a real change to something other than the
3252 + // original lines: nothing to re-base here.
3253 + if ( $baseline[ $filename ]['hash'] === $current
3254 + || $baseline[ $filename ]['hash'] !== md5( $this->normalize_critical_file( $filename, $content, true ) )
3255 + ) {
3256 + continue;
3257 + }
3258 +
3259 + $normalized = $this->normalize_critical_file( $filename, $content );
3260 + $baseline[ $filename ]['hash'] = $current;
3261 + $baseline[ $filename ]['size'] = strlen( $content );
3262 + $baseline[ $filename ]['content'] = $this->baseline_content( $filename, $normalized );
3263 + $baseline[ $filename ]['updated'] = time();
3264 + $changed = true;
3265 + }
3266 +
3267 + if ( $changed ) {
3268 + $this->write_baseline( $baseline );
3269 + }
3270 + }
3271 +
3272 + /**
3273 + * The .htaccess blocks Vigilant would write today, keyed by start marker
3274 + *
3275 + * @since 2.11.5
3276 + *
3277 + * @return array
3278 + */
3279 + private function expected_htaccess_blocks() {
3280 + $settings = $this->settings ? $this->settings : new Vigilante_Settings();
3281 +
3282 + $classes = array(
3283 + 'Vigilante_Htaccess_Protection' => 'class-htaccess-protection.php',
3284 + 'Vigilante_Security_Headers' => 'class-security-headers.php',
3285 + );
3286 +
3287 + foreach ( $classes as $class => $file ) {
3288 + if ( ! class_exists( $class ) ) {
3289 + require_once VIGILANTE_INCLUDES_DIR . $file;
3290 + }
3291 + }
3292 +
3293 + $headers = new Vigilante_Security_Headers( $settings );
3294 +
3295 + return array(
3296 + Vigilante_Htaccess_Protection::MARKER_START => ( new Vigilante_Htaccess_Protection( $settings ) )->generate_rules(),
3297 + Vigilante_Security_Headers::MARKER_START => Vigilante_Security_Headers::MARKER_START . "\n" . $headers->generate_rules_content() . "\n" . Vigilante_Security_Headers::MARKER_END,
3298 + );
3299 + }
3300 +
3301 + /**
3302 + * A .htaccess block with the parts that change on every write evened out
3303 + *
3304 + * Two blocks Vigilant wrote with the same settings differ only in the time
3305 + * they were generated and, across an update, in the version the firewall
3306 + * block names. Everything else has to be identical for the claim to take
3307 + * the block.
3308 + *
3309 + * @since 2.11.5
3310 + *
3311 + * @param string $block Block from start marker to end marker, inclusive.
3312 + * @return string
3313 + */
3314 + private static function comparable_block( $block ) {
3315 + $block = str_replace( array( "\r\n", "\r" ), "\n", (string) $block );
3316 + $block = preg_replace( '/^# Generated: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC$/m', '# Generated:', $block );
3317 + $block = preg_replace( '/^# Vigilante for WordPress - Firewall v[0-9][0-9A-Za-z.\-]*$/m', '# Vigilante for WordPress - Firewall v', $block );
3318 +
3319 + return rtrim( $block, "\n" );
3320 + }
3321 +
3322 + /**
1018 3323 * Get stored baseline hashes for critical files
1019 3324 *
1020 3325 * @return array Associative array keyed by filename.
1021 3326 */
1022 3327 public function get_critical_files_baseline() {
1023 - $baseline = get_option( self::BASELINE_OPTION, array() );
1024 - return is_array( $baseline ) ? $baseline : array();
3328 + return $this->read_baseline();
1025 3329 }
1026 3330
1027 3331 /**
1028 3332 * Update baseline hash for a single critical file
@@ -1033,11 +3337,11 @@
1033 3337 * @param string $filename File name relative to ABSPATH (e.g. 'wp-config.php').
1034 3338 * @return bool True on success.
1035 3339 */
1036 3340 public function update_critical_file_baseline( $filename ) {
1037 - $full_path = untrailingslashit( ABSPATH ) . '/' . $filename;
3341 + $full_path = $this->critical_file_path( $filename );
1038 3342
1039 - if ( ! file_exists( $full_path ) ) {
3343 + if ( false === $full_path ) {
1040 3344 return false;
1041 3345 }
1042 3346
1043 3347 $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
@@ -1047,16 +3351,44 @@
1047 3351
1048 3352 $normalized = $this->normalize_critical_file( $filename, $content );
1049 3353
1050 3354 $baseline = $this->get_critical_files_baseline();
3355 +
3356 + /*
3357 + * No guard here, and there was one for a few hours during 2.11.4 that
3358 + * had to come out. It refused to rewrite the record when the stored hash
3359 + * no longer matched the file, meant to stop a write of ours from
3360 + * approving somebody else's pending edit. Two things were wrong with it,
3361 + * both measured on 10 sep 2026 by a third cross review:
3362 + *
3363 + * - This is also the Approve button (Vigilante_Admin_Ajax::
3364 + * ajax_approve_critical_file). A moved hash is exactly the state in
3365 + * which Approve is pressed, so the guard made Approve fail every time
3366 + * and the warning could never be closed.
3367 + * - Its premise, "our own write cannot move the normalized hash", holds
3368 + * for the block and not for the rest of what the writers do.
3369 + * comment_existing_constants() turns a define() into a
3370 + * [VIGILANTE_ORIGINAL] line that normalize_critical_file() leaves as
3371 + * an empty line, and remove_old_rules() deletes legacy .htaccess blocks
3372 + * that normalize_critical_file() does not know. Both move the hash, so
3373 + * the guard would have raised a false "file modified" after Vigilant's
3374 + * own work, on sites that updated.
3375 + *
3376 + * The real fix is to know what the hash was before WE touched the file:
3377 + * the writers capture it and pass it along vigilante_critical_file_
3378 + * written, and this compares against that instead of against the
3379 + * record. Until then this behaves as it always has, which does mean a
3380 + * write of ours can adopt a third-party edit that was pending review.
3381 + * That is pre-existing, and written down in the roadmap.
3382 + */
1051 3383 $baseline[ $filename ] = array(
1052 3384 'hash' => md5( $normalized ),
1053 3385 'size' => strlen( $content ),
1054 - 'content' => $normalized,
3386 + 'content' => $this->baseline_content( $filename, $normalized ),
1055 3387 'updated' => time(),
1056 3388 );
1057 3389
1058 - return update_option( self::BASELINE_OPTION, $baseline, false );
3390 + return $this->write_baseline( $baseline );
1059 3391 }
1060 3392
1061 3393 /**
1062 3394 * Regenerate baseline for all critical files
@@ -1066,14 +3398,13 @@
1066 3398 * @return array Updated baseline data.
1067 3399 */
1068 3400 public function regenerate_all_baselines() {
1069 3401 $baseline = array();
1070 - $root_path = untrailingslashit( ABSPATH );
1071 3402
1072 3403 foreach ( $this->critical_root_files as $filename ) {
1073 - $full_path = $root_path . '/' . $filename;
3404 + $full_path = $this->critical_file_path( $filename );
1074 3405
1075 - if ( ! file_exists( $full_path ) ) {
3406 + if ( false === $full_path ) {
1076 3407 continue;
1077 3408 }
1078 3409
1079 3410 $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
@@ -1084,14 +3415,14 @@
1084 3415 $normalized = $this->normalize_critical_file( $filename, $content );
1085 3416 $baseline[ $filename ] = array(
1086 3417 'hash' => md5( $normalized ),
1087 3418 'size' => strlen( $content ),
1088 - 'content' => $normalized,
3419 + 'content' => $this->baseline_content( $filename, $normalized ),
1089 3420 'updated' => time(),
1090 3421 );
1091 3422 }
1092 3423
1093 - update_option( self::BASELINE_OPTION, $baseline, false );
3424 + $this->write_baseline( $baseline );
1094 3425
1095 3426 return $baseline;
1096 3427 }
1097 3428
@@ -1097,16 +3428,22 @@
1097 3428
1098 3429 /**
1099 3430 * Get core checksums from WordPress.org API
1100 3431 *
3432 + * @param bool $force_refresh Skip the cached copy and ask wp.org again.
1101 3433 * @return array|WP_Error Checksums or error.
1102 3434 */
1103 - private function get_core_checksums() {
3435 + private function get_core_checksums( $force_refresh = false ) {
1104 3436 $locale = get_locale();
1105 3437 $version = $this->wp_version;
1106 3438
1107 3439 // Check cache first
1108 3440 $cache_key = 'vigilante_core_checksums_' . md5( $version . $locale );
3441 +
3442 + if ( $force_refresh ) {
3443 + delete_transient( $cache_key );
3444 + }
3445 +
1109 3446 $cached = get_transient( $cache_key );
1110 3447 if ( false !== $cached ) {
1111 3448 return $cached;
1112 3449 }
@@ -2268,12 +4605,48 @@
2268 4605 * @return bool
2269 4606 */
2270 4607 private function is_path_excluded( $path ) {
2271 4608 $excluded = $this->options['excluded_paths'] ?? array();
2272 - $relative = str_replace( ABSPATH, '', $path );
2273 4609
4610 + if ( empty( $excluded ) ) {
4611 + return false;
4612 + }
4613 +
4614 + $relative = $this->relative_path( $path );
4615 +
2274 4616 foreach ( $excluded as $exclude ) {
2275 - if ( strpos( $relative, $exclude ) !== false ) {
4617 + $exclude = trim( trim( str_replace( '\\', '/', (string) $exclude ) ), '/' );
4618 +
4619 + if ( '' === $exclude ) {
4620 + continue;
4621 + }
4622 +
4623 + /*
4624 + * Two forms, both with real boundaries. Until 2.9.9 this was a plain
4625 + * strpos() over the relative path, so an exclusion matched anywhere
4626 + * inside it: "cache" also silenced a plugin folder named mycache,
4627 + * "logs" silenced catalogs, and nothing told the user how much had
4628 + * stopped being watched.
4629 + *
4630 + * Anything with a slash is a path: it excludes exactly that file, or
4631 + * everything under it, anchored at the root of the installation.
4632 + */
4633 + if ( false !== strpos( $exclude, '/' ) ) {
4634 + if ( $relative === $exclude || 0 === strpos( $relative, $exclude . '/' ) ) {
4635 + return true;
4636 + }
4637 +
4638 + continue;
4639 + }
4640 +
4641 + /*
4642 + * A bare name excludes any folder called exactly that, at any depth,
4643 + * which is what someone typing "languages" means. It has to be the
4644 + * whole segment, not a fragment of one.
4645 + */
4646 + if ( $relative === $exclude
4647 + || 0 === strpos( $relative, $exclude . '/' )
4648 + || false !== strpos( $relative, '/' . $exclude . '/' ) ) {
2276 4649 return true;
2277 4650 }
2278 4651 }
2279 4652
@@ -2280,8 +4653,27 @@
2280 4653 return false;
2281 4654 }
2282 4655
2283 4656 /**
4657 + * Path relative to the WordPress directory, with forward slashes
4658 + *
4659 + * @since 2.9.9
4660 + *
4661 + * @param string $path Absolute path.
4662 + * @return string
4663 + */
4664 + private function relative_path( $path ) {
4665 + $path = str_replace( '\\', '/', (string) $path );
4666 + $root = str_replace( '\\', '/', ABSPATH );
4667 +
4668 + if ( 0 === strpos( $path, $root ) ) {
4669 + $path = substr( $path, strlen( $root ) );
4670 + }
4671 +
4672 + return ltrim( $path, '/' );
4673 + }
4674 +
4675 + /**
2284 4676 * Check if a file extension is excluded from scanning
2285 4677 *
2286 4678 * @param string $path File path.
2287 4679 * @return bool
@@ -2293,18 +4685,52 @@
2293 4685 return false;
2294 4686 }
2295 4687
2296 4688 $extension = '.' . strtolower( pathinfo( $path, PATHINFO_EXTENSION ) );
4689 + $relative = strtolower( $this->relative_path( $path ) );
2297 4690
2298 4691 foreach ( $excluded as $exclude ) {
2299 - $exclude = strtolower( trim( $exclude ) );
4692 + $exclude = strtolower( trim( (string) $exclude ) );
4693 +
4694 + if ( '' === $exclude ) {
4695 + continue;
4696 + }
4697 +
4698 + /*
4699 + * An extension on its own is global, as it has always been. Since
4700 + * 2.9.9 it can also be scoped to a folder, written as
4701 + * wp-content/languages/*.json, because the global form is a blunt
4702 + * instrument: excluding .json to quiet the translation files also
4703 + * stopped watching the 173 block.json files of core.
4704 + */
4705 + $scope = '';
4706 +
4707 + if ( false !== strpos( $exclude, '*' ) ) {
4708 + $parts = explode( '*', $exclude, 2 );
4709 + $scope = trim( $parts[0], '/' );
4710 + $exclude = $parts[1];
4711 + }
4712 +
4713 + if ( '' === $exclude ) {
4714 + continue;
4715 + }
4716 +
2300 4717 // Support both ".log" and "log" formats
2301 4718 if ( 0 !== strpos( $exclude, '.' ) ) {
2302 4719 $exclude = '.' . $exclude;
2303 4720 }
2304 - if ( $exclude === $extension ) {
4721 +
4722 + if ( $exclude !== $extension ) {
4723 + continue;
4724 + }
4725 +
4726 + if ( '' === $scope ) {
2305 4727 return true;
2306 4728 }
4729 +
4730 + if ( $relative === $scope || 0 === strpos( $relative, $scope . '/' ) ) {
4731 + return true;
4732 + }
2307 4733 }
2308 4734
2309 4735 return false;
2310 4736 }
@@ -2323,8 +4749,21 @@
2323 4749 return array_values(
2324 4750 array_filter(
2325 4751 $items,
2326 4752 function ( $item ) {
4753 + /*
4754 + * On a network, wp-config.php and the root .htaccess are not a
4755 + * site's to silence: a change to them is closed by approving it,
4756 + * and approving takes a network administrator since 2.11.3. The
4757 + * ignore list is an option of each site, so until 2.11.8 the
4758 + * administrator of the main site without network rights hid a
4759 + * pending change from the network administrator's own screen by
4760 + * posting the file name to the ignore handler.
4761 + */
4762 + if ( is_multisite() && is_array( $item ) && 'critical_config' === ( $item['type'] ?? '' ) ) {
4763 + return true;
4764 + }
4765 +
2327 4766 $file = is_array( $item ) && isset( $item['file'] ) ? $item['file'] : '';
2328 4767 return ! in_array( $file, $this->ignored_files, true );
2329 4768 }
2330 4769 )
@@ -2590,9 +5029,9 @@
2590 5029 }
2591 5030
2592 5031 // CTA button
2593 5032 $inner .= Vigilante_Email_Template::button(
2594 - admin_url( 'admin.php?page=vigilante&tab=file-integrity' ),
5033 + admin_url( 'admin.php?page=vigilante&tab=file-integrity#vigilante-section-fi-last-scan' ),
2595 5034 __( 'Review in Vigilant', 'vigilante' )
2596 5035 );
2597 5036
2598 5037 $is_alert = ( $suspicious_count > 0 || $critical_config_count > 0 || $closed_count > 0 );