PluginProbe
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… / 3.0.0
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… v3.0.0
3.0.0 2.11.12 2.11.11 2.11.10 2.11.9 2.11.7 2.11.8 2.11.6 2.11.5 2.11.4 2.11.3 2.11.1 2.11.2 2.11.0 2.10.5 2.10.4 2.10.3 2.10.2 2.10.1 2.10.0 2.9.9 2.9.8 2.9.6 2.9.7 2.9.5 All 88 releases
← All changes | includes/class-file-integrity.php +2423 -43 2.10.53.0.0 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 */
@@ -298,8 +1771,16 @@
298 1771 $files = array( $hook_extra['plugin'] );
299 1772 }
300 1773 foreach ( $files as $file ) {
301 1774 $slug = dirname( (string) $file );
1775 + // Vigilant itself is verified immediately (not after 90 s) by
1776 + // Vigilante_Self_Integrity::handle_upgrader() when the
1777 + // self-check is on; do not also open a grace window for it.
1778 + // Compared with the folder it really lives in, not the literal
1779 + // slug, so a renamed folder is skipped the same way.
1780 + if ( dirname( VIGILANTE_PLUGIN_BASENAME ) === $slug && Vigilante_Self_Integrity::is_on() ) {
1781 + continue;
1782 + }
302 1783 if ( '.' !== $slug && '' !== $slug ) {
303 1784 $targets['plugin'][] = $slug;
304 1785 }
305 1786 }
@@ -368,8 +1849,17 @@
368 1849 */
369 1850 private function verify_updated_slug( $type, $slug ) {
370 1851 $grace_key = 'vigilante_fi_grace_' . $type . '_' . md5( $slug );
371 1852
1853 + // Defensive skip for the first 2.11.x -> 3.0.x update: the OLD code in
1854 + // memory scheduled this event including Vigilant's own slug, and by the
1855 + // time it fires the NEW code (this one) is running with the self-check
1856 + // handling Vigilant on its own.
1857 + if ( 'plugin' === $type && dirname( VIGILANTE_PLUGIN_BASENAME ) === $slug && Vigilante_Self_Integrity::is_on() ) {
1858 + delete_transient( $grace_key );
1859 + return;
1860 + }
1861 +
372 1862 if ( 'plugin' === $type ) {
373 1863 if ( ! function_exists( 'get_plugins' ) ) {
374 1864 require_once ABSPATH . 'wp-admin/includes/plugin.php';
375 1865 }
@@ -520,8 +2010,41 @@
520 2010
521 2011 // Use settings from options page
522 2012 $options = is_array( $this->options ) ? $this->options : array();
523 2013
2014 + // Vigilant self-check runs FIRST and exempt from the time budget:
2015 + // ~60 small-file hashes cost < 50 ms and the guardian must never be
2016 + // dropped by the budget on plugin-heavy sites. User exclusions do not
2017 + // apply to it (see Vigilante_Self_Integrity::run_check()).
2018 + if ( ! class_exists( 'Vigilante_Self_Integrity' ) ) {
2019 + require_once VIGILANTE_INCLUDES_DIR . 'class-self-integrity.php';
2020 + }
2021 + if ( Vigilante_Self_Integrity::is_on() ) {
2022 + if ( ! class_exists( 'Vigilante_Self_Integrity' ) ) {
2023 + require_once VIGILANTE_INCLUDES_DIR . 'class-self-integrity.php';
2024 + }
2025 + $self = new Vigilante_Self_Integrity( $this->settings, $this->activity_log );
2026 + $self_result = $self->run_check( 'scan' );
2027 + // run_check() above updates this site's own state (status line and
2028 + // the analyzer check keep working everywhere). The plugin files are
2029 + // shared by the whole installation, so the self findings are folded
2030 + // Self-protection has its own alert, and it does not travel in the
2031 + // scan digest any more. That digest is governed by a notification
2032 + // setting that can be switched off, and switching off "tell me about
2033 + // changed files" was also switching off the alarm of the plugin
2034 + // itself. So the findings stay out of the scan results (they have
2035 + // their own block in File Integrity, with what each one means and how
2036 + // to repair it) and a critical one sends its own email from here,
2037 + // wherever the scan runs. maybe_send_self_alert() keeps it to the
2038 + // site that owns the shared files and dedupes by set of findings.
2039 + foreach ( (array) $self_result['findings'] as $self_finding ) {
2040 + if ( 'critical' === ( $self_finding['severity'] ?? '' ) ) {
2041 + $self->maybe_send_self_alert( $self_result['findings'], 'scan' );
2042 + break;
2043 + }
2044 + }
2045 + }
2046 +
524 2047 // Scan uploads for suspicious files FIRST (highest security priority)
525 2048 // PHP files in uploads are almost always malware
526 2049 if ( ! empty( $options['scan_uploads'] ) && ! $this->is_time_exceeded() ) {
527 2050 $upload_results = $this->scan_uploads();
@@ -926,18 +2449,71 @@
926 2449 * silently — there is nothing to compare against.
927 2450 *
928 2451 * @return array Array of modified file entries (same format as core modified).
929 2452 */
2453 + /**
2454 + * Where a critical root file actually lives
2455 + *
2456 + * WordPress supports wp-config.php one directory above ABSPATH, guarded by
2457 + * wp-settings.php not being there: that is literally what the installed core
2458 + * does in wp-load.php, and it is a common hardening layout. Until 2.11.10
2459 + * this module only looked inside ABSPATH, so on those installations
2460 + * wp-config.php was never added to the baseline, never compared and never
2461 + * mentioned: the module reported the site clean without having opened the
2462 + * one file it most needs to watch. A zero is justified, never assumed. The
2463 + * plugin already resolved both locations elsewhere
2464 + * (Vigilante_Database_Prefix::find_wpconfig_path()), just not here. Found by
2465 + * the file-by-file review of 2.11.10.
2466 + *
2467 + * @since 2.11.10
2468 + *
2469 + * @param string $filename Name of the file, such as wp-config.php.
2470 + * @return string|false Absolute path, or false when it cannot be found.
2471 + */
2472 + private function critical_file_path( $filename ) {
2473 + $root = untrailingslashit( ABSPATH );
2474 + $path = $root . '/' . $filename;
2475 +
2476 + if ( file_exists( $path ) ) {
2477 + return $path;
2478 + }
2479 +
2480 + if ( 'wp-config.php' === $filename ) {
2481 + $above = dirname( $root ) . '/wp-config.php';
2482 +
2483 + // Suppressed like the core does in wp-load.php: the directory above
2484 + // the install is often outside open_basedir on shared hosting, and
2485 + // without the @ every scan emits a warning that can land in front of
2486 + // the JSON of an AJAX scan.
2487 + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- The same @ the core uses for this same check in wp-load.php:52, where a wp-config.php one directory up is looked for: open_basedir makes file_exists() warn on a path outside it, and this must not print.
2488 + if ( @file_exists( $above ) && ! @file_exists( dirname( $root ) . '/wp-settings.php' ) ) {
2489 + return $above;
2490 + }
2491 + }
2492 +
2493 + return false;
2494 + }
2495 +
930 2496 private function scan_critical_root_files() {
2497 + // Before reading anything: the scan is the only thing that reaches
2498 + // every site of a network on its own, through wp-cron and front-end
2499 + // traffic. Hooking the cleanup to admin_init alone left every subsite
2500 + // whose dashboard nobody opens with its old copy of wp-config.php,
2501 + // credentials included, for as long as nobody visited it.
2502 + $this->maybe_redact_stored_baseline();
2503 +
2504 + // And claim the blocks already on disk before anything is compared,
2505 + // so the first scan after updating uses the rule that will stay.
2506 + $this->maybe_claim_owned_blocks();
2507 +
931 2508 $modified = array();
932 2509 $baseline = $this->get_critical_files_baseline();
933 2510 $baseline_changed = false;
934 - $root_path = untrailingslashit( ABSPATH );
935 2511
936 2512 foreach ( $this->critical_root_files as $filename ) {
937 - $full_path = $root_path . '/' . $filename;
2513 + $full_path = $this->critical_file_path( $filename );
938 2514
939 - if ( ! file_exists( $full_path ) ) {
2515 + if ( false === $full_path ) {
940 2516 continue;
941 2517 }
942 2518
943 2519 $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
@@ -952,9 +2528,9 @@
952 2528 // First time seeing this file — store baseline silently
953 2529 $baseline[ $filename ] = array(
954 2530 'hash' => $current_hash,
955 2531 'size' => strlen( $content ),
956 - 'content' => $normalized,
2532 + 'content' => $this->baseline_content( $filename, $normalized ),
957 2533 'updated' => time(),
958 2534 );
959 2535 $baseline_changed = true;
960 2536 continue;
@@ -961,34 +2537,85 @@
961 2537 }
962 2538
963 2539 // Upgrade legacy baseline entries that lack content (pre-diff format)
964 2540 if ( ! isset( $baseline[ $filename ]['content'] ) && $baseline[ $filename ]['hash'] === $current_hash ) {
965 - $baseline[ $filename ]['content'] = $normalized;
2541 + $baseline[ $filename ]['content'] = $this->baseline_content( $filename, $normalized );
966 2542 $baseline_changed = true;
967 2543 continue;
968 2544 }
969 2545
970 - // Compare against stored baseline
971 - if ( $baseline[ $filename ]['hash'] !== $current_hash ) {
2546 + /*
2547 + * The file has not changed, but the copy on record is not the copy
2548 + * that would be stored today: an entry written before 2.11.2 with
2549 + * the credentials in it, or one written before the redaction list
2550 + * grew. Rewrite it.
2551 + *
2552 + * Only when the hash matches, and that condition is the whole
2553 + * point: if the file HAD changed, this entry is the evidence of
2554 + * the change that the administrator still has to review, and
2555 + * rewriting it here would quietly destroy that evidence.
2556 + */
2557 + if ( $baseline[ $filename ]['hash'] === $current_hash ) {
2558 + $expected = $this->baseline_content( $filename, $normalized );
2559 +
2560 + if ( $expected !== $baseline[ $filename ]['content'] ) {
2561 + $baseline[ $filename ]['content'] = $expected;
2562 + $baseline_changed = true;
2563 + }
2564 +
2565 + continue;
2566 + }
2567 +
2568 + /*
2569 + * Everything from here down is the changed file, and only that: the
2570 + * branch above returns on every matching hash, so there is no third
2571 + * case and no condition left to test. It used to be wrapped in an
2572 + * `if` repeating the opposite comparison, which read as if some
2573 + * other path could reach this point. It could not. Flagged by
2574 + * @calzbert, and worth the two lines it costs to say so.
2575 + *
2576 + * Both sides go through the same redaction, or every credential
2577 + * line would read as a change nobody made.
2578 + */
2579 + /*
2580 + * Where the shared files do not belong to this site, the lines are
2581 + * not computed at all. The diff is shown to whoever can open this
2582 + * site's screen, the administrator of a subsite included, and it
2583 + * was stored in the options of every subsite with the module on.
2584 + * Found by the audit of the admin surface for 2.11.8. The change is
2585 + * still reported, with both sizes, and the lines are read on the
2586 + * main site, where the change is approved.
2587 + */
2588 + if ( ! Vigilante_Settings::owns_shared_files() ) {
2589 + $diff = self::network_only_diff();
2590 + } else {
972 2591 $baseline_content = $baseline[ $filename ]['content'] ?? '';
973 - $diff = '' !== $baseline_content
974 - ? $this->compute_simple_diff( $baseline_content, $normalized )
2592 + $current_content = $this->baseline_content( $filename, $normalized );
2593 + $diff = ( '' !== $baseline_content && '' !== $current_content )
2594 + ? $this->compute_simple_diff( $baseline_content, $current_content )
975 2595 : array( 'added' => array(), 'removed' => array(), 'unavailable' => true );
976 2596
977 - $modified[] = array(
978 - 'file' => $filename,
979 - 'type' => 'critical_config',
980 - 'expected_hash' => $baseline[ $filename ]['hash'],
981 - 'actual_hash' => $current_hash,
982 - 'baseline_size' => $baseline[ $filename ]['size'],
983 - 'current_size' => strlen( $content ),
984 - 'diff' => $diff,
985 - );
2597 + // Say why there are no lines when today's copy could not be
2598 + // made safe, which approving does not change: the generic
2599 + // message talks about an old baseline. Cross review of 2.11.8.
2600 + if ( '' === $current_content && 'wp-config.php' === $filename ) {
2601 + $diff['redaction'] = true;
2602 + }
986 2603 }
2604 +
2605 + $modified[] = array(
2606 + 'file' => $filename,
2607 + 'type' => 'critical_config',
2608 + 'expected_hash' => $baseline[ $filename ]['hash'],
2609 + 'actual_hash' => $current_hash,
2610 + 'baseline_size' => $baseline[ $filename ]['size'],
2611 + 'current_size' => strlen( $content ),
2612 + 'diff' => $diff,
2613 + );
987 2614 }
988 2615
989 2616 if ( $baseline_changed ) {
990 - update_option( self::BASELINE_OPTION, $baseline, false );
2617 + $this->write_baseline( $baseline );
991 2618 }
992 2619
993 2620 return $modified;
994 2621 }
@@ -1060,30 +2687,49 @@
1060 2687 * @param string $filename File name (e.g. 'wp-config.php').
1061 2688 * @param string $content Raw file content.
1062 2689 * @return string Normalized content for hashing.
1063 2690 */
1064 - private function normalize_critical_file( $filename, $content ) {
2691 + private function normalize_critical_file( $filename, $content, $drop_all_original = false ) {
1065 2692 // Normalize line endings first (CRLF and CR to LF)
1066 2693 $content = str_replace( array( "\r\n", "\r" ), "\n", $content );
1067 2694
2695 + /*
2696 + * Vigilant's own blocks are left out of the hash, so rewriting them is
2697 + * not reported as somebody else's change. Until 2.11.5 that covered
2698 + * everything between the markers, and every line carrying the
2699 + * [VIGILANTE_ORIGINAL] marker, whatever they contained. From 2.11.5 a
2700 + * block is left out only if it is exactly a block Vigilant wrote (see
2701 + * remember_owned_block()), and a marked line only while uncommenting it
2702 + * would still give a harmless define() (see is_vigilant_original_line()).
2703 + *
2704 + * Until the blocks already on disk have been claimed, the old rule
2705 + * applies unchanged. That is what keeps an update from changing the
2706 + * hash of a file nobody touched.
2707 + */
2708 + $claimed = $this->owned_blocks_claimed();
2709 +
1068 2710 if ( 'wp-config.php' === $filename ) {
1069 - // Remove Vigilante constants blocks (current and legacy)
2711 + // Vigilante constants blocks (current and legacy)
1070 2712 foreach ( $this->wpconfig_markers as $markers ) {
1071 - $pattern = '/' . preg_quote( $markers[0], '/' ) . '.*?' . preg_quote( $markers[1], '/' ) . '\s*/s';
1072 - $content = preg_replace( $pattern, '', $content );
2713 + $content = $this->strip_vigilant_blocks( $filename, $content, $markers, $claimed );
1073 2714 }
1074 2715
1075 - // Remove lines commented out by Vigilante (original constants)
1076 - $content = preg_replace(
2716 + // Lines commented out by Vigilante (original constants)
2717 + $content = preg_replace_callback(
1077 2718 '/^.*' . preg_quote( $this->wpconfig_original_marker, '/' ) . '.*$/m',
1078 - '',
2719 + function ( $line ) use ( $claimed, $drop_all_original ) {
2720 + // $drop_all_original reproduce la regla anterior a la 2.11.5 (quitar
2721 + // toda linea marcada) sobre los bloques de la regla nueva. Solo lo usa
2722 + // el re-base de la transicion, para decidir si la unica diferencia con
2723 + // el registro aprobado son estas lineas. Ver rebase_original_line_shift().
2724 + return ( ! $claimed || $drop_all_original || $this->is_vigilant_original_line( $line[0] ) ) ? '' : $line[0];
2725 + },
1079 2726 $content
1080 2727 );
1081 2728 } elseif ( '.htaccess' === $filename ) {
1082 - // Remove Vigilante htaccess blocks (firewall + security headers)
2729 + // Vigilante htaccess blocks (firewall + security headers)
1083 2730 foreach ( $this->htaccess_markers as $markers ) {
1084 - $pattern = '/' . preg_quote( $markers[0], '/' ) . '.*?' . preg_quote( $markers[1], '/' ) . '\s*/s';
1085 - $content = preg_replace( $pattern, '', $content );
2731 + $content = $this->strip_vigilant_blocks( $filename, $content, $markers, $claimed );
1086 2732 }
1087 2733 }
1088 2734
1089 2735 // Collapse multiple blank lines into one (blocks removal leaves gaps)
@@ -1092,15 +2738,645 @@
1092 2738 return trim( $content );
1093 2739 }
1094 2740
1095 2741 /**
2742 + * Leave Vigilant's blocks for one pair of markers out of the content
2743 + *
2744 + * Before the claim, every block, as it always was. After it, only the blocks
2745 + * whose fingerprint was recorded when Vigilant wrote them. A block that does
2746 + * not match, edited or planted, stays in the content: it counts in the hash
2747 + * and shows up in the diff.
2748 + *
2749 + * The match runs from marker to marker and the removal also takes the
2750 + * whitespace after the block, exactly as before, so a file whose blocks are
2751 + * all Vigilant's normalizes to the same text under both rules.
2752 + *
2753 + * @since 2.11.5
2754 + *
2755 + * @param string $filename 'wp-config.php' or '.htaccess'.
2756 + * @param string $content Content with normalized line endings.
2757 + * @param array $markers Start and end marker.
2758 + * @param bool $claimed Whether the claim has run.
2759 + * @return string
2760 + */
2761 + private function strip_vigilant_blocks( $filename, $content, $markers, $claimed ) {
2762 + $pattern = '/(' . preg_quote( $markers[0], '/' ) . '.*?' . preg_quote( $markers[1], '/' ) . ')\s*/s';
2763 +
2764 + if ( ! $claimed ) {
2765 + return preg_replace( $pattern, '', $content );
2766 + }
2767 +
2768 + return preg_replace_callback(
2769 + $pattern,
2770 + function ( $match ) use ( $filename ) {
2771 + return self::is_owned_block( $filename, $match[1] ) ? '' : $match[0];
2772 + },
2773 + $content
2774 + );
2775 + }
2776 +
2777 + /**
2778 + * Whether a line carrying the original-constant marker is one Vigilant wrote
2779 + *
2780 + * comment_existing_constants() puts the marker in front of a define() of a
2781 + * constant it manages, and uncomment_original_constants() takes it away
2782 + * again whenever the constants are applied or removed, so whatever follows
2783 + * the marker gets to run some day. The line is left out of the hash only
2784 + * when there is nothing but indentation before the marker, nothing after it
2785 + * but a harmless define() and at most a line comment, and no PHP tag
2786 + * anywhere on it. That keeps it a comment today and harmless once
2787 + * uncommented. Anything else counts, and shows up in the diff.
2788 + *
2789 + * @since 2.11.5
2790 + *
2791 + * @param string $line One line of wp-config.php.
2792 + * @return bool
2793 + */
2794 + /**
2795 + * Whether every marked line of a file can run nothing at all
2796 + *
2797 + * The question the re-base has to answer before adopting a file is whether
2798 + * the lines that carry the marker are only comments. Asking a stricter one
2799 + * was wrong in both directions: the first version of the guard used
2800 + * is_vigilant_original_line(), which also requires the commented define to
2801 + * match a known harmless shape, so it refused to re-base a perfectly inert
2802 + * line carrying an unusual define, which is exactly the case the re-base
2803 + * exists for, leaving the function unable to act at all. Found by the cross
2804 + * review of 2.11.10.
2805 + *
2806 + * The second version read one line at a time and reasoned that the marker
2807 + * begins with //, so a line with nothing but whitespace before it is wholly
2808 + * a comment. That is true only where PHP is already reading code, and the
2809 + * second cross review of 2.11.10 built three files where it is not, all of
2810 + * them valid PHP, all of them passing that test and all of them running or
2811 + * printing something:
2812 + *
2813 + * - the marked line placed BEFORE the opening <?php, so it is inline HTML
2814 + * that the server prints verbatim to the browser;
2815 + * - the same after a ?> that the file already had;
2816 + * - the marked line ending a block comment opened on an earlier line and
2817 + * opening another one at its end, with a statement in between, which
2818 + * runs like any other statement.
2819 + *
2820 + * So the file is read the way PHP reads it, not the way the line looks. A
2821 + * marked line is inert when every token touching it is a comment or
2822 + * whitespace, which answers the three at once: inline HTML is not a comment,
2823 + * and neither is a statement. The shape the guard was written for, code
2824 + * BEFORE the marker, is the same question from the other side.
2825 + *
2826 + * The three shapes are in the harness as cells X2, X3 and X4 of
2827 + * matriz-escondite-marcadores.sh, written out in full there. They are not
2828 + * written out here on purpose: a literal payload in a shipped file is
2829 + * signature surface for the scanners this plugin is read by, and a comment
2830 + * is a bad place to pay for it.
2831 + *
2832 + * @since 2.11.10
2833 + *
2834 + * @param string $content Whole file content.
2835 + * @return bool True when no marked line can run or print anything.
2836 + */
2837 + /**
2838 + * The lines of a file that carry the original-value marker
2839 + *
2840 + * @since 2.11.10
2841 + *
2842 + * @param string $content Whole file content, newlines already normalised.
2843 + * @return string[]
2844 + */
2845 + private function marked_lines_of( $content ) {
2846 + $out = array();
2847 +
2848 + foreach ( explode( "\n", $content ) as $text ) {
2849 + if ( false !== strpos( $text, $this->wpconfig_original_marker ) ) {
2850 + $out[] = $text;
2851 + }
2852 + }
2853 +
2854 + return $out;
2855 + }
2856 +
2857 + /**
2858 + * Whether what a marked line carries would still be harmless uncommented
2859 + *
2860 + * Only the part after the marker matters: what comes before it is answered by
2861 + * the token pass, which refuses anything that is not comment or whitespace.
2862 + * Here the question is what comes BACK when uncomment_original_constants()
2863 + * removes the marker, so the body has to be a single define() and nothing
2864 + * else, with at most a trailing line comment. Deliberately says nothing about
2865 + * WHICH constant it is: asking that was the first version of this guard, and
2866 + * it refused every define it did not recognise, which is exactly the case the
2867 + * re-base exists for.
2868 + *
2869 + * @since 2.11.10
2870 + *
2871 + * @param string $line One line carrying the marker.
2872 + * @return bool
2873 + */
2874 + private function marked_line_body_is_harmless( $line ) {
2875 + $at = strpos( $line, $this->wpconfig_original_marker );
2876 +
2877 + if ( false === $at ) {
2878 + return true;
2879 + }
2880 +
2881 + $body = trim( substr( $line, $at + strlen( $this->wpconfig_original_marker ) ) );
2882 +
2883 + if ( '' === $body ) {
2884 + return true;
2885 + }
2886 +
2887 + // Tokenised as PHP so the trailing comment, the strings and the nesting
2888 + // are read the way PHP reads them and not with a regular expression.
2889 + $tokens = @token_get_all( '<?php ' . $body ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A marked line can carry anything; a warning here must not be printed, and an unreadable body is refused below.
2890 +
2891 + if ( empty( $tokens ) ) {
2892 + return false;
2893 + }
2894 +
2895 + $statements = 0;
2896 + $depth = 0;
2897 +
2898 + foreach ( $tokens as $token ) {
2899 + $type = is_array( $token ) ? $token[0] : $token;
2900 +
2901 + if ( in_array( $type, array( T_OPEN_TAG, T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) {
2902 + continue;
2903 + }
2904 +
2905 + if ( '(' === $type ) {
2906 + $depth++;
2907 + continue;
2908 + }
2909 +
2910 + if ( ')' === $type ) {
2911 + $depth--;
2912 + continue;
2913 + }
2914 +
2915 + // A semicolon at the top level closes a statement. More than one, or
2916 + // anything after the first, means the line carries something else.
2917 + if ( ';' === $type && 0 === $depth ) {
2918 + $statements++;
2919 + continue;
2920 + }
2921 +
2922 + if ( $statements > 0 ) {
2923 + return false;
2924 + }
2925 + }
2926 +
2927 + return ( $statements <= 1 );
2928 + }
2929 +
2930 + private function marked_lines_are_inert( $content ) {
2931 + $content = str_replace( "\r\n", "\n", (string) $content );
2932 + $marker = $this->wpconfig_original_marker;
2933 +
2934 + if ( '' === $content || false === strpos( $content, $marker ) ) {
2935 + return true;
2936 + }
2937 +
2938 + $marked = array();
2939 +
2940 + foreach ( explode( "\n", $content ) as $index => $text ) {
2941 + if ( false !== strpos( $text, $marker ) ) {
2942 + $marked[ $index + 1 ] = true;
2943 + }
2944 + }
2945 +
2946 + // Lenient on purpose (no TOKEN_PARSE): a tampered file still has to be
2947 + // read, and a file that cannot be tokenised is never adopted.
2948 + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- The file read here may have been tampered with, which is the whole point, and PHP 8 emits a warning when it cannot tokenise: printing it would put a parse error on whatever page ran the scan. An unreadable file is refused four lines below.
2949 + $tokens = @token_get_all( $content );
2950 +
2951 + if ( empty( $tokens ) ) {
2952 + return false;
2953 + }
2954 +
2955 + /*
2956 + * And the other half of the question, which the first token version left
2957 + * out: a marked line is a COMMENTED OUT value, and uncommenting it is what
2958 + * the feature exists for, so "runs nothing today" is not enough. Anything
2959 + * sharing the line after the define comes back with it. The shape is real
2960 + * and needs no attacker: comment_existing_constants() takes a define and
2961 + * everything on its line, so
2962 + * define( 'WP_DEBUG', false ); @ini_set( 'display_errors', 0 );
2963 + * is commented whole, and re-basing it would adopt as approved something
2964 + * that runs the moment the value is restored. The old rule refused this
2965 + * too, but along with every define whose NAME it did not recognise, which
2966 + * is what left the function unable to act at all. Found by the third cross
2967 + * review of 2.11.10.
2968 + */
2969 + foreach ( $this->marked_lines_of( $content ) as $text ) {
2970 + if ( ! $this->marked_line_body_is_harmless( $text ) ) {
2971 + return false;
2972 + }
2973 + }
2974 +
2975 + $inocuos = array( T_COMMENT, T_DOC_COMMENT, T_WHITESPACE );
2976 + $linea = 1;
2977 +
2978 + foreach ( $tokens as $token ) {
2979 + $texto = is_array( $token ) ? $token[1] : $token;
2980 + $tipo = is_array( $token ) ? $token[0] : null;
2981 + $saltos = substr_count( $texto, "\n" );
2982 + $desde = $linea;
2983 + $hasta = $linea + $saltos;
2984 +
2985 + /*
2986 + * A token whose text ends in a newline puts nothing on the line that
2987 + * newline opens. Counting it would make the "<?php\n" of every file
2988 + * touch line 2 and refuse the legitimate case, which is what the
2989 + * first version of this did.
2990 + */
2991 + $ultima = ( $saltos > 0 && "\n" === substr( $texto, -1 ) ) ? $hasta - 1 : $hasta;
2992 + $linea = $hasta;
2993 +
2994 + if ( null !== $tipo && in_array( $tipo, $inocuos, true ) ) {
2995 + continue;
2996 + }
2997 +
2998 + for ( $l = $desde; $l <= $ultima; $l++ ) {
2999 + if ( isset( $marked[ $l ] ) ) {
3000 + return false;
3001 + }
3002 + }
3003 + }
3004 +
3005 + return true;
3006 + }
3007 +
3008 + private function is_vigilant_original_line( $line ) {
3009 + if ( false !== strpos( $line, '<?' ) || false !== strpos( $line, '?>' ) ) {
3010 + return false;
3011 + }
3012 +
3013 + return 1 === preg_match(
3014 + '/^[ \t]*' . preg_quote( $this->wpconfig_original_marker, '/' ) . self::harmless_define_pattern() . '[ \t]*(?:(?:\/\/|#(?!\[)).*)?$/',
3015 + $line
3016 + );
3017 + }
3018 +
3019 + /**
3020 + * A define() that runs nothing but itself, as a regular expression fragment
3021 + *
3022 + * The name is one of the constants Vigilant has managed in any version. The
3023 + * value is made only of literals (true, false, null, a number, a quoted
3024 + * string with nothing to interpolate) and of ABSPATH, WP_CONTENT_DIR and
3025 + * __DIR__, which is what a debug log path is usually built from, joined
3026 + * with dots. No call, no variable, no backtick, no include.
3027 + *
3028 + * @since 2.11.5
3029 + *
3030 + * @return string Pattern without delimiters.
3031 + */
3032 + private static function harmless_define_pattern() {
3033 + $names = 'DISALLOW_FILE_EDIT|DISALLOW_FILE_MODS|FORCE_SSL_ADMIN|FORCE_SSL_LOGIN|WP_DEBUG|WP_DEBUG_LOG|WP_DEBUG_DISPLAY|SCRIPT_DEBUG|DISABLE_WP_CRON'
3034 + . '|WP_POST_REVISIONS|AUTOSAVE_INTERVAL|EMPTY_TRASH_DAYS|WP_MEMORY_LIMIT|WP_MAX_MEMORY_LIMIT|WP_AUTO_UPDATE_CORE|CONCATENATE_SCRIPTS';
3035 +
3036 + $value = '(?:(?i:true|false|null)|-?\d+|\'(?:[^\'\\\\]|\\\\.)*\'|"[^"\\\\$]*"|ABSPATH|WP_CONTENT_DIR|__DIR__)';
3037 +
3038 + return 'define\s*\(\s*[\'"](?:' . $names . ')[\'"]\s*,\s*' . $value . '(?:\s*\.\s*' . $value . ')*\s*\)\s*;';
3039 + }
3040 +
3041 + /**
3042 + * Whether a wp-config.php constants block can only be one Vigilant wrote
3043 + *
3044 + * Every version of generate_constants() has written the start marker on its
3045 + * own line, then comments, blank lines and define() calls, bare or wrapped
3046 + * in if ( ! defined() ), then the end marker on its own line. A block made
3047 + * only of those lines runs nothing but the defines, whatever version wrote
3048 + * it and whatever settings it was written with. One line of anything else,
3049 + * or a PHP tag on any line, and the block is not taken.
3050 + *
3051 + * @since 2.11.5
3052 + *
3053 + * @param string $block Block from start marker to end marker, inclusive.
3054 + * @param array $markers Start and end marker.
3055 + * @return bool
3056 + */
3057 + private static function is_harmless_constants_block( $block, $markers ) {
3058 + $lines = explode( "\n", str_replace( array( "\r\n", "\r" ), "\n", (string) $block ) );
3059 +
3060 + if ( count( $lines ) < 2
3061 + || rtrim( array_shift( $lines ), " \t" ) !== $markers[0]
3062 + || ltrim( array_pop( $lines ), " \t" ) !== $markers[1]
3063 + ) {
3064 + return false;
3065 + }
3066 +
3067 + $define = self::harmless_define_pattern();
3068 + $guarded = '/^if\s*\(\s*!\s*defined\s*\(\s*[\'"][A-Z_]+[\'"]\s*\)\s*\)\s*\{\s*' . $define . '\s*\}$/';
3069 +
3070 + foreach ( $lines as $line ) {
3071 + $line = trim( $line, " \t" );
3072 +
3073 + if ( false !== strpos( $line, '<?' ) || false !== strpos( $line, '?>' ) ) {
3074 + return false;
3075 + }
3076 +
3077 + if ( '' === $line
3078 + || 0 === strpos( $line, '//' )
3079 + || preg_match( '/^' . $define . '$/', $line )
3080 + || preg_match( $guarded, $line )
3081 + ) {
3082 + continue;
3083 + }
3084 +
3085 + return false;
3086 + }
3087 +
3088 + return true;
3089 + }
3090 +
3091 + /**
3092 + * Take ownership of the blocks already on disk, once
3093 + *
3094 + * Fingerprints are recorded when Vigilant writes a block, which leaves every
3095 + * block written before 2.11.5 without one. This records the blocks that can
3096 + * be recognised as Vigilant's without having seen them written:
3097 + *
3098 + * - A .htaccess block, when it is exactly what Vigilant would write today
3099 + * with the settings it has, the timestamp and the version apart. After an
3100 + * update, maybe_sync_server_files() rewrites those blocks on the next
3101 + * request, so the claim waits for it. Unless it has already failed: a
3102 + * block Vigilant cannot rewrite is not going to start matching, and
3103 + * waiting for it would keep the old rule for good.
3104 + * - A wp-config.php constants block, when every line in it is a comment, a
3105 + * blank line or a harmless define(). Nothing rewrites that block on an
3106 + * update and its format has changed five times, so comparing it with
3107 + * today's output would report every site that has not saved those
3108 + * settings since. A line that could run anything is never accepted.
3109 + *
3110 + * A block that is not recognised stays in the hash and is reported as a
3111 + * change, so the owner gets to look at it, and the activity log says why.
3112 + * Nothing in the stored baseline is rewritten.
3113 + *
3114 + * Only where the shared files belong, a single site or the main site of a
3115 + * network, because the expected blocks come from that site's settings. Until
3116 + * it has run, normalize_critical_file() keeps the old rule on every site.
3117 + *
3118 + * @since 2.11.5
3119 + */
3120 + /**
3121 + * The admin_init entry point of the claim, which does ask for an administrator
3122 + *
3123 + * admin-ajax.php fires admin_init before it decides who is asking
3124 + * (wp-admin/admin-ajax.php:45), so without this an anonymous request chose
3125 + * the moment the claim runs. Unlike its two neighbours in
3126 + * init_cleanup_hooks(), which only drop the plugin's own copy out of the
3127 + * database, the claim writes two network options, changes for the whole
3128 + * network the rule normalize_critical_file() applies, and re-bases the
3129 + * approved baseline.
3130 + *
3131 + * The gate lives here and not inside maybe_claim_owned_blocks() because the
3132 + * scan calls that one directly and the scan runs from wp-cron, with no user:
3133 + * putting the capability check inside left the claim unable to complete on
3134 + * any site whose dashboard nobody opens, and until it completes the older,
3135 + * permissive rule is the one in force, which is the hiding place 2.11.5 was
3136 + * written to close. Found by the cross review of 2.11.10.
3137 + *
3138 + * @since 2.11.10
3139 + */
3140 + public function maybe_claim_owned_blocks_on_admin() {
3141 + if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
3142 + return;
3143 + }
3144 +
3145 + $this->maybe_claim_owned_blocks();
3146 + }
3147 +
3148 + public function maybe_claim_owned_blocks() {
3149 + if ( $this->owned_blocks_claimed() || ! Vigilante_Settings::owns_shared_files() ) {
3150 + return;
3151 + }
3152 +
3153 + $sync_due = get_option( 'vigilante_server_files_pending' )
3154 + || VIGILANTE_VERSION !== get_option( 'vigilante_server_files_version' );
3155 +
3156 + if ( $sync_due && ! get_option( 'vigilante_server_files_retry_after' ) ) {
3157 + return;
3158 + }
3159 +
3160 + $expected = null;
3161 + $unclaimed = array();
3162 +
3163 + foreach ( $this->critical_root_files as $filename ) {
3164 + $full_path = $this->critical_file_path( $filename );
3165 +
3166 + if ( false === $full_path ) {
3167 + continue;
3168 + }
3169 +
3170 + $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
3171 +
3172 + if ( false === $content ) {
3173 + // Unreadable right now: leave the claim open and try again later.
3174 + return;
3175 + }
3176 +
3177 + $content = str_replace( array( "\r\n", "\r" ), "\n", $content );
3178 + $is_config = 'wp-config.php' === $filename;
3179 +
3180 + foreach ( ( $is_config ? $this->wpconfig_markers : $this->htaccess_markers ) as $markers ) {
3181 + $pattern = '/' . preg_quote( $markers[0], '/' ) . '.*?' . preg_quote( $markers[1], '/' ) . '/s';
3182 +
3183 + if ( ! preg_match_all( $pattern, $content, $found ) ) {
3184 + continue;
3185 + }
3186 +
3187 + foreach ( $found[0] as $block ) {
3188 + if ( $is_config ) {
3189 + $ours = self::is_harmless_constants_block( $block, $markers );
3190 + } else {
3191 + $expected = null === $expected ? $this->expected_htaccess_blocks() : $expected;
3192 + $ours = isset( $expected[ $markers[0] ] )
3193 + && self::comparable_block( $block ) === self::comparable_block( $expected[ $markers[0] ] );
3194 + }
3195 +
3196 + if ( $ours ) {
3197 + self::remember_owned_block( $filename, $markers[0], $block, false );
3198 + } else {
3199 + $unclaimed[ $filename ] = $filename;
3200 + }
3201 + }
3202 + }
3203 +
3204 + // The commented-out originals are judged line by line at scan time.
3205 + // Looking at them here only keeps the log entry below complete.
3206 + if ( $is_config && preg_match_all( '/^.*' . preg_quote( $this->wpconfig_original_marker, '/' ) . '.*$/m', $content, $marked ) ) {
3207 + foreach ( $marked[0] as $line ) {
3208 + if ( ! $this->is_vigilant_original_line( $line ) ) {
3209 + $unclaimed[ $filename ] = $filename;
3210 + }
3211 + }
3212 + }
3213 + }
3214 +
3215 + update_site_option( self::OWNED_BLOCKS_CLAIM_OPTION, self::OWNED_BLOCKS_CLAIMED );
3216 +
3217 + // With the claim in place normalize uses the new rule, so a file nobody
3218 + // touched whose only difference is an original line the old rule dropped
3219 + // would read as changed. Re-base those, and only those, once.
3220 + $this->rebase_original_line_shift();
3221 +
3222 + if ( $unclaimed && $this->activity_log ) {
3223 + $this->activity_log->log(
3224 + 'file',
3225 + 'critical_file_unrecognized_block',
3226 + sprintf(
3227 + /* translators: %s: comma-separated file names, such as wp-config.php or .htaccess. */
3228 + __( 'Content marked as written by Vigilant in %s does not match what Vigilant writes. From now on it is checked like the rest of the file, so the file integrity scan reports it as a change for you to review.', 'vigilante' ),
3229 + implode( ', ', $unclaimed )
3230 + ),
3231 + array( 'files' => array_values( $unclaimed ) ),
3232 + 'warning'
3233 + );
3234 + }
3235 + }
3236 +
3237 + /**
3238 + * Re-base the critical files whose only change is a newly kept original line
3239 + *
3240 + * Until 2.11.5 the hash left out every [VIGILANTE_ORIGINAL] line; from 2.11.5
3241 + * it keeps the ones whose value is not a plain constant define, which is the
3242 + * right thing for the hash but moves it on a file nobody edited: the stored
3243 + * baseline was taken under the old rule, and nothing re-bases wp-config.php on
3244 + * an update (maybe_sync_server_files() only rewrites the .htaccess). So the
3245 + * first scan after updating would report wp-config.php as changed.
3246 + *
3247 + * This runs once, in the same pass that claims the blocks. For each file it
3248 + * re-bases to the new hash only when the baseline still matches the file with
3249 + * every original line dropped, which means the blocks are exactly the approved
3250 + * ones and the sole difference is those lines, the user's own commented-out
3251 + * defines. A block that was edited or planted does not match with the lines
3252 + * dropped, so it is left to be reported: this closes the false positive
3253 + * without adopting anything that was hidden before.
3254 + *
3255 + * @since 2.11.5
3256 + */
3257 + private function rebase_original_line_shift() {
3258 + $baseline = $this->get_critical_files_baseline();
3259 + $changed = false;
3260 +
3261 + foreach ( $this->critical_root_files as $filename ) {
3262 + $full_path = $this->critical_file_path( $filename );
3263 +
3264 + if ( false === $full_path || empty( $baseline[ $filename ]['hash'] ) ) {
3265 + continue;
3266 + }
3267 +
3268 + $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
3269 +
3270 + if ( false === $content ) {
3271 + continue;
3272 + }
3273 +
3274 + /*
3275 + * Never re-base a file that carries a marked line which is not
3276 + * wholly a comment. The test below only establishes that the
3277 + * difference lies in lines carrying the marker, and the old rule
3278 + * dropped the WHOLE line, so a line with a statement in front of the
3279 + * marker satisfies it (cell X1 of matriz-escondite-marcadores.sh,
3280 + * where the shape is written out): re-basing would write that line
3281 + * into the approved baseline and rewrite the stored content, so the
3282 + * diff would stop showing it. Adopting as approved what the previous rule
3283 + * hid is the one thing an integrity scanner must never do, and the
3284 + * log entry of maybe_claim_owned_blocks() already promises the
3285 + * opposite ("the scan reports it as a change for you to review").
3286 + * Those files are left to be reported. Found by the file-by-file
3287 + * review of 2.11.10.
3288 + *
3289 + * What counts as "wholly a comment" is decided by reading the file
3290 + * as PHP reads it, not by the shape of the line: see
3291 + * marked_lines_are_inert(). A line that is not recognised is not the
3292 + * same thing as a line that can run something, and the first
3293 + * wording of this guard confused the two.
3294 + */
3295 + if ( ! $this->marked_lines_are_inert( $content ) ) {
3296 + continue;
3297 + }
3298 +
3299 + $current = md5( $this->normalize_critical_file( $filename, $content ) );
3300 +
3301 + // Already in step, or a real change to something other than the
3302 + // original lines: nothing to re-base here.
3303 + if ( $baseline[ $filename ]['hash'] === $current
3304 + || $baseline[ $filename ]['hash'] !== md5( $this->normalize_critical_file( $filename, $content, true ) )
3305 + ) {
3306 + continue;
3307 + }
3308 +
3309 + $normalized = $this->normalize_critical_file( $filename, $content );
3310 + $baseline[ $filename ]['hash'] = $current;
3311 + $baseline[ $filename ]['size'] = strlen( $content );
3312 + $baseline[ $filename ]['content'] = $this->baseline_content( $filename, $normalized );
3313 + $baseline[ $filename ]['updated'] = time();
3314 + $changed = true;
3315 + }
3316 +
3317 + if ( $changed ) {
3318 + $this->write_baseline( $baseline );
3319 + }
3320 + }
3321 +
3322 + /**
3323 + * The .htaccess blocks Vigilant would write today, keyed by start marker
3324 + *
3325 + * @since 2.11.5
3326 + *
3327 + * @return array
3328 + */
3329 + private function expected_htaccess_blocks() {
3330 + $settings = $this->settings ? $this->settings : new Vigilante_Settings();
3331 +
3332 + $classes = array(
3333 + 'Vigilante_Htaccess_Protection' => 'class-htaccess-protection.php',
3334 + 'Vigilante_Security_Headers' => 'class-security-headers.php',
3335 + );
3336 +
3337 + foreach ( $classes as $class => $file ) {
3338 + if ( ! class_exists( $class ) ) {
3339 + require_once VIGILANTE_INCLUDES_DIR . $file;
3340 + }
3341 + }
3342 +
3343 + $headers = new Vigilante_Security_Headers( $settings );
3344 +
3345 + return array(
3346 + Vigilante_Htaccess_Protection::MARKER_START => ( new Vigilante_Htaccess_Protection( $settings ) )->generate_rules(),
3347 + Vigilante_Security_Headers::MARKER_START => Vigilante_Security_Headers::MARKER_START . "\n" . $headers->generate_rules_content() . "\n" . Vigilante_Security_Headers::MARKER_END,
3348 + );
3349 + }
3350 +
3351 + /**
3352 + * A .htaccess block with the parts that change on every write evened out
3353 + *
3354 + * Two blocks Vigilant wrote with the same settings differ only in the time
3355 + * they were generated and, across an update, in the version the firewall
3356 + * block names. Everything else has to be identical for the claim to take
3357 + * the block.
3358 + *
3359 + * @since 2.11.5
3360 + *
3361 + * @param string $block Block from start marker to end marker, inclusive.
3362 + * @return string
3363 + */
3364 + private static function comparable_block( $block ) {
3365 + $block = str_replace( array( "\r\n", "\r" ), "\n", (string) $block );
3366 + $block = preg_replace( '/^# Generated: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC$/m', '# Generated:', $block );
3367 + $block = preg_replace( '/^# Vigilante for WordPress - Firewall v[0-9][0-9A-Za-z.\-]*$/m', '# Vigilante for WordPress - Firewall v', $block );
3368 +
3369 + return rtrim( $block, "\n" );
3370 + }
3371 +
3372 + /**
1096 3373 * Get stored baseline hashes for critical files
1097 3374 *
1098 3375 * @return array Associative array keyed by filename.
1099 3376 */
1100 3377 public function get_critical_files_baseline() {
1101 - $baseline = get_option( self::BASELINE_OPTION, array() );
1102 - return is_array( $baseline ) ? $baseline : array();
3378 + return $this->read_baseline();
1103 3379 }
1104 3380
1105 3381 /**
1106 3382 * Update baseline hash for a single critical file
@@ -1111,11 +3387,11 @@
1111 3387 * @param string $filename File name relative to ABSPATH (e.g. 'wp-config.php').
1112 3388 * @return bool True on success.
1113 3389 */
1114 3390 public function update_critical_file_baseline( $filename ) {
1115 - $full_path = untrailingslashit( ABSPATH ) . '/' . $filename;
3391 + $full_path = $this->critical_file_path( $filename );
1116 3392
1117 - if ( ! file_exists( $full_path ) ) {
3393 + if ( false === $full_path ) {
1118 3394 return false;
1119 3395 }
1120 3396
1121 3397 $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
@@ -1125,16 +3401,44 @@
1125 3401
1126 3402 $normalized = $this->normalize_critical_file( $filename, $content );
1127 3403
1128 3404 $baseline = $this->get_critical_files_baseline();
3405 +
3406 + /*
3407 + * No guard here, and there was one for a few hours during 2.11.4 that
3408 + * had to come out. It refused to rewrite the record when the stored hash
3409 + * no longer matched the file, meant to stop a write of ours from
3410 + * approving somebody else's pending edit. Two things were wrong with it,
3411 + * both measured on 10 sep 2026 by a third cross review:
3412 + *
3413 + * - This is also the Approve button (Vigilante_Admin_Ajax::
3414 + * ajax_approve_critical_file). A moved hash is exactly the state in
3415 + * which Approve is pressed, so the guard made Approve fail every time
3416 + * and the warning could never be closed.
3417 + * - Its premise, "our own write cannot move the normalized hash", holds
3418 + * for the block and not for the rest of what the writers do.
3419 + * comment_existing_constants() turns a define() into a
3420 + * [VIGILANTE_ORIGINAL] line that normalize_critical_file() leaves as
3421 + * an empty line, and remove_old_rules() deletes legacy .htaccess blocks
3422 + * that normalize_critical_file() does not know. Both move the hash, so
3423 + * the guard would have raised a false "file modified" after Vigilant's
3424 + * own work, on sites that updated.
3425 + *
3426 + * The real fix is to know what the hash was before WE touched the file:
3427 + * the writers capture it and pass it along vigilante_critical_file_
3428 + * written, and this compares against that instead of against the
3429 + * record. Until then this behaves as it always has, which does mean a
3430 + * write of ours can adopt a third-party edit that was pending review.
3431 + * That is pre-existing, and written down in the roadmap.
3432 + */
1129 3433 $baseline[ $filename ] = array(
1130 3434 'hash' => md5( $normalized ),
1131 3435 'size' => strlen( $content ),
1132 - 'content' => $normalized,
3436 + 'content' => $this->baseline_content( $filename, $normalized ),
1133 3437 'updated' => time(),
1134 3438 );
1135 3439
1136 - return update_option( self::BASELINE_OPTION, $baseline, false );
3440 + return $this->write_baseline( $baseline );
1137 3441 }
1138 3442
1139 3443 /**
1140 3444 * Regenerate baseline for all critical files
@@ -1144,14 +3448,13 @@
1144 3448 * @return array Updated baseline data.
1145 3449 */
1146 3450 public function regenerate_all_baselines() {
1147 3451 $baseline = array();
1148 - $root_path = untrailingslashit( ABSPATH );
1149 3452
1150 3453 foreach ( $this->critical_root_files as $filename ) {
1151 - $full_path = $root_path . '/' . $filename;
3454 + $full_path = $this->critical_file_path( $filename );
1152 3455
1153 - if ( ! file_exists( $full_path ) ) {
3456 + if ( false === $full_path ) {
1154 3457 continue;
1155 3458 }
1156 3459
1157 3460 $content = file_get_contents( $full_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
@@ -1162,14 +3465,14 @@
1162 3465 $normalized = $this->normalize_critical_file( $filename, $content );
1163 3466 $baseline[ $filename ] = array(
1164 3467 'hash' => md5( $normalized ),
1165 3468 'size' => strlen( $content ),
1166 - 'content' => $normalized,
3469 + 'content' => $this->baseline_content( $filename, $normalized ),
1167 3470 'updated' => time(),
1168 3471 );
1169 3472 }
1170 3473
1171 - update_option( self::BASELINE_OPTION, $baseline, false );
3474 + $this->write_baseline( $baseline );
1172 3475
1173 3476 return $baseline;
1174 3477 }
1175 3478
@@ -1261,8 +3564,17 @@
1261 3564 if ( '.' === $plugin_slug ) {
1262 3565 continue;
1263 3566 }
1264 3567
3568 + // With the self-check on, Vigilant itself is verified by the
3569 + // sha256 triple-anchor block at the start of run_scan(): scanning
3570 + // it here again would duplicate findings and the md5 fetch. With
3571 + // the check off by filter, Vigilant is a regular plugin (legacy
3572 + // behaviour).
3573 + if ( dirname( VIGILANTE_PLUGIN_BASENAME ) === $plugin_slug && Vigilante_Self_Integrity::is_on() ) {
3574 + continue;
3575 + }
3576 +
1265 3577 // Skip slugs in their post-update grace window: wp.org may still be
1266 3578 // publishing the new version's checksums, so a scheduled scan here
1267 3579 // would raise benign "modified/extra" noise. The dedicated post-update
1268 3580 // verifier (vigilante_fi_postupdate_verify) handles these instead.
@@ -2496,8 +4808,39 @@
2496 4808 return array_values(
2497 4809 array_filter(
2498 4810 $items,
2499 4811 function ( $item ) {
4812 + /*
4813 + * On a network, wp-config.php and the root .htaccess are not a
4814 + * site's to silence: a change to them is closed by approving it,
4815 + * and approving takes a network administrator since 2.11.3. The
4816 + * ignore list is an option of each site, so until 2.11.8 the
4817 + * administrator of the main site without network rights hid a
4818 + * pending change from the network administrator's own screen by
4819 + * posting the file name to the ignore handler.
4820 + */
4821 + if ( is_multisite() && is_array( $item ) && 'critical_config' === ( $item['type'] ?? '' ) ) {
4822 + return true;
4823 + }
4824 +
4825 + // Findings about the manifest and the version of Vigilant
4826 + // itself are not about one file, so no entry of the list may
4827 + // hide them, on a single site either: ignoring the row of
4828 + // MANIFEST.sha256 took a replaced manifest out of the email.
4829 + // Vigilante_Self_Integrity::filter_ignored_findings() keeps
4830 + // them the same way.
4831 + if ( is_array( $item ) && 'vigilante_self' === ( $item['type'] ?? '' ) && in_array( $item['self_finding'] ?? '', array( 'manifest_replaced', 'manifest_unverified', 'manifest_missing', 'manifest_invalid', 'self_downgraded' ), true ) ) {
4832 + return true;
4833 + }
4834 + // Nor the findings of the walk of Vigilant's folder (a folder
4835 + // that cannot be listed, the folder that could not be walked):
4836 + // their path ends in a slash, and ignoring that row left the
4837 + // scan with no row and no email while the self-protection
4838 + // status stayed critical.
4839 + if ( is_array( $item ) && 'vigilante_self' === ( $item['type'] ?? '' ) && '/' === substr( (string) ( $item['file'] ?? '' ), -1 ) ) {
4840 + return true;
4841 + }
4842 +
2500 4843 $file = is_array( $item ) && isset( $item['file'] ) ? $item['file'] : '';
2501 4844 return ! in_array( $file, $this->ignored_files, true );
2502 4845 }
2503 4846 )
@@ -2534,9 +4877,17 @@
2534 4877 // a security-critical finding, same tier as a suspicious file.
2535 4878 $closed_plugins = $this->collect_closed_plugins_for_email();
2536 4879 $has_closed = ! empty( $closed_plugins );
2537 4880
4881 + /*
4882 + * Self-protection is not part of this decision any more. Its alert is
4883 + * its own and no setting switches it off, so this email is again about
4884 + * the files of the site: core, plugins, themes, uploads and the two
4885 + * shared configuration files.
4886 + */
2538 4887 $has_suspicious = ! empty( $results['suspicious'] ) || ! empty( $results['extra'] ) || $has_critical_config || $has_closed;
4888 + // Missing files of core, plugins or themes still do not send the email on
4889 + // their own: it has no section to list them in, so it would arrive empty.
2539 4890 $has_modified = ! empty( $results['modified'] );
2540 4891
2541 4892 // Instant alert: send for suspicious, extra, critical_config, modified
2542 4893 // files, or closed plugins.
@@ -2655,8 +5006,37 @@
2655 5006 $regular_modified[] = $item;
2656 5007 }
2657 5008 }
2658 5009
5010 + /*
5011 + * Self-protection does not travel in this email any more: it has its own
5012 + * alert, which no setting switches off (Vigilante_Self_Integrity::
5013 + * maybe_send_self_alert()). Older stored results can still carry its
5014 + * rows, so they are dropped here instead of being listed as ordinary
5015 + * files.
5016 + */
5017 + foreach ( array( 'suspicious', 'extra', 'missing' ) as $self_bucket ) {
5018 + if ( empty( $results[ $self_bucket ] ) || ! is_array( $results[ $self_bucket ] ) ) {
5019 + continue;
5020 + }
5021 + $results[ $self_bucket ] = array_values(
5022 + array_filter(
5023 + $results[ $self_bucket ],
5024 + function ( $item ) {
5025 + return ! ( is_array( $item ) && 'vigilante_self' === ( $item['type'] ?? '' ) );
5026 + }
5027 + )
5028 + );
5029 + }
5030 + $regular_modified = array_values(
5031 + array_filter(
5032 + $regular_modified,
5033 + function ( $item ) {
5034 + return ! ( is_array( $item ) && 'vigilante_self' === ( $item['type'] ?? '' ) );
5035 + }
5036 + )
5037 + );
5038 +
2659 5039 $suspicious_count = count( $results['suspicious'] ?? array() );
2660 5040 $extra_count = count( $results['extra'] ?? array() );
2661 5041 $critical_config_count = count( $critical_config );
2662 5042 $modified_count = count( $regular_modified );
@@ -2661,10 +5041,10 @@
2661 5041 $critical_config_count = count( $critical_config );
2662 5042 $modified_count = count( $regular_modified );
2663 5043 $closed_count = count( $closed_plugins );
2664 5044
2665 - // Use more urgent subject when suspicious files, critical config changes
2666 - // or closed plugins are found (all three are security-critical).
5045 + // Use more urgent subject when suspicious files, critical config changes,
5046 + // closed plugins or self-integrity findings are found (all security-critical).
2667 5047 if ( $suspicious_count > 0 || $critical_config_count > 0 || $closed_count > 0 ) {
2668 5048 $subject = sprintf(
2669 5049 /* translators: %s: Site name */
2670 5050 __( '[%s] SECURITY ALERT: File integrity issues detected', 'vigilante' ),
@@ -2763,9 +5143,9 @@
2763 5143 }
2764 5144
2765 5145 // CTA button
2766 5146 $inner .= Vigilante_Email_Template::button(
2767 - admin_url( 'admin.php?page=vigilante&tab=file-integrity' ),
5147 + admin_url( 'admin.php?page=vigilante&tab=file-integrity#vigilante-section-fi-last-scan' ),
2768 5148 __( 'Review in Vigilant', 'vigilante' )
2769 5149 );
2770 5150
2771 5151 $is_alert = ( $suspicious_count > 0 || $critical_config_count > 0 || $closed_count > 0 );