Plugin Directory

Changeset 3692233


Ignore:
Timestamp:
09/12/2026 12:57:28 AM (2 months ago)
Author:
fernandot
Message:

Security fixes: a trusted forwarded IP header is accepted only from a verified proxy, an expired password is enforced beyond wp-admin, the session limit closes old sessions again, and .htaccess copies no longer keep secrets in the database.

Location:
vigilante
Files:
69 added
10 edited

Legend:

Unmodified
Added
Removed
  • vigilante/trunk/admin/class-admin.php

    r3692177 r3692233  
    465465
    466466            update_option( 'vigilante_db_version', '2.11.0' );
     467        }
     468
     469        /*
     470         * 2.11.9: clear the raw .htaccess copies that older versions left in
     471         * options, on the first admin load after the update. Uninstall already
     472         * removes them, but that only fires when the plugin is deleted, so a
     473         * site that keeps the plugin carried them until now. Three stores, each
     474         * a copy of a file that can hold secrets (a SetEnv token, an
     475         * Authorization header): the same exposure the wp.org review flagged as
     476         * 4.4, on the paths its fix did not reach.
     477         *
     478         * - vigilante_htaccess_history: up to five raw copies, by design, until
     479         *   2.11.8. The writer is gone, nothing reads it, so it is deleted.
     480         * - vigilante_htaccess_backup: the single rollback buffer, normally
     481         *   cleared in the finally of each write; a copy only lingers if a write
     482         *   crashed mid-operation. Nothing outside one write reads it, so a
     483         *   leftover is deleted.
     484         * - vigilante_htaccess_pre_migration: still read by the header recovery,
     485         *   but older versions stored the whole file where only our own block is
     486         *   ever used. Truncated to that block, so the feature keeps working and
     487         *   nothing outside our markers stays in the option.
     488         */
     489        if ( version_compare( $db_version, '2.11.9', '<' ) ) {
     490            delete_option( 'vigilante_htaccess_history' );
     491            delete_option( 'vigilante_htaccess_backup' );
     492
     493            $snapshot = get_option( 'vigilante_htaccess_pre_migration' );
     494            if ( is_array( $snapshot ) && isset( $snapshot['content'] ) && '' !== (string) $snapshot['content'] ) {
     495                require_once VIGILANTE_INCLUDES_DIR . 'class-htaccess-recovery.php';
     496                $block = Vigilante_Htaccess_Recovery::get_raw_block();
     497
     498                if ( '' === $block ) {
     499                    delete_option( 'vigilante_htaccess_pre_migration' );
     500                } elseif ( $block !== $snapshot['content'] ) {
     501                    $snapshot['content'] = $block;
     502                    update_option( 'vigilante_htaccess_pre_migration', $snapshot, false );
     503                }
     504            }
     505
     506            update_option( 'vigilante_db_version', '2.11.9' );
    467507        }
    468508    }
    … …  
    34003440                    </tr>
    34013441                    <tr>
     3442                        <th scope="row"><label for="vigilante-f-firewall-trusted-proxies"><?php esc_html_e( 'Trusted proxy IPs', 'vigilante' ); ?></label></th>
     3443                        <td>
     3444                            <textarea id="vigilante-f-firewall-trusted-proxies" name="firewall[trusted_proxies]" rows="3" class="large-text code" placeholder="10.0.0.0/8&#10;192.168.1.1"><?php echo esc_textarea( implode( "\n", $options['trusted_proxies'] ?? array() ) ); ?></textarea>
     3445                            <p class="description">
     3446                                <?php esc_html_e( 'Only used with a forwarded header selected above. One IP or CIDR range per line: the addresses your proxy or load balancer connects from. The forwarded header is accepted only from these. Left empty, Vigilant accepts it from your own private network, and for Cloudflare from Cloudflare\'s own ranges automatically.', 'vigilante' ); ?>
     3447                                <?php if ( in_array( $proxy_header, array( 'x-forwarded-for', 'x-real-ip' ), true ) && empty( $options['trusted_proxies'] ) ) : ?>
     3448                                    <br><strong><?php esc_html_e( 'The header above is trusted but no proxy IPs are set. If your proxy or load balancer connects from a public address, add it here, or the header is ignored for safety and every visitor is seen as that proxy.', 'vigilante' ); ?></strong>
     3449                                <?php endif; ?>
     3450                            </p>
     3451                        </td>
     3452                    </tr>
     3453                    <tr>
    34023454                        <th scope="row"><label for="vigilante-f-firewall-ip-whitelist"><?php esc_html_e( 'IP Whitelist', 'vigilante' ); ?></label></th>
    34033455                        <td>
    … …  
    68906942        }
    68916943
    6892         $rejected_ips = array();
     6944        $rejected_ips     = array();
     6945        $rejected_proxies = array();
    68936946
    68946947        // Handle modules
    … …  
    69176970                // so the ones that cannot match are dropped and reported back
    69186971                // instead of being stored in silence.
    6919                 $rejected_ips = $this->filter_ip_lists( $section, $processed );
     6972                $rejected_ips = $this->filter_ip_lists( $section, $processed, $rejected_proxies );
    69206973
    69216974                // Save the processed section
    … …  
    69957048        }
    69967049
     7050        if ( ! empty( $rejected_proxies ) ) {
     7051            $message .= ' ' . sprintf(
     7052                /* translators: %s: comma separated list of the trusted proxy entries that were not saved. */
     7053                _n(
     7054                    'A trusted proxy must be an exact IP or a CIDR range, not a wildcard, so this entry was not saved: %s',
     7055                    'A trusted proxy must be an exact IP or a CIDR range, not a wildcard, so these entries were not saved: %s',
     7056                    count( $rejected_proxies ),
     7057                    'vigilante'
     7058                ),
     7059                implode( ', ', array_map( 'esc_html', $rejected_proxies ) )
     7060            );
     7061        }
     7062
    69977063        wp_send_json_success( $message );
    69987064    }
    … …  
    70077073     * @return array Entries that were dropped, for the message back to the user.
    70087074     */
    7009     private function filter_ip_lists( $section, &$processed ) {
     7075    private function filter_ip_lists( $section, &$processed, &$rejected_proxies = array() ) {
     7076        $rejected_proxies = array();
     7077
     7078        // Trusted proxies feed an identity decision, so only exact addresses and
     7079        // CIDR ranges belong there: a wildcard is stripped with its own message,
     7080        // never stored looking effective. The matcher ignores it anyway (see
     7081        // Vigilante_IP_Utils::in_list_ip_or_cidr), this stops it persisting.
     7082        if ( 'firewall' === $section && isset( $processed['trusted_proxies'] ) && is_array( $processed['trusted_proxies'] ) ) {
     7083            $split                          = Vigilante_IP_Utils::split_list_ip_or_cidr( $processed['trusted_proxies'] );
     7084            $processed['trusted_proxies']   = $split['valid'];
     7085            $rejected_proxies               = $split['rejected'];
     7086        }
     7087
    70107088        $lists = array(
    70117089            'firewall'       => array( 'ip_whitelist', 'ip_blacklist' ),
  • vigilante/trunk/changelog.txt

    r3692177 r3692233  
    33For each release, see the entries below. The latest version is always at the top.
    44The current release notes also live in readme.txt under "== Changelog ==".
     5
     6= 2.11.9 =
     7* Fix: when a forwarded header is trusted (X-Forwarded-For, X-Real-IP or CF-Connecting-IP), Vigilant now accepts it only from a connection it can verify as a proxy: an address in the new Trusted proxy IPs list, one of Cloudflare's own ranges for the CF-Connecting-IP header, or, when no list is set, your own private network. Until 2.11.9 the header was honoured whoever sent it, so a visitor whose request reached the origin directly could forge the address the firewall, the IP whitelist and blacklist and the rate-limit counters act on, rotating it to dodge throttling or setting a whitelisted one to skip the checks. Reported by the wordpress.org automated security review of 2.11.8. If your load balancer connects from a public address, add it to Trusted proxy IPs in the Firewall tab, or its header is ignored and every visitor is seen as that balancer.
     8* Fix: an expired password is now enforced on the REST API, admin-ajax, the front end and XML-RPC, not only on wp-admin screens. Enforcement was a wp-admin redirect that skipped AJAX and never ran on the other routes, so a session whose password had expired kept working through them; now the account can only change the password or log out until it does. The feature must be enabled for this to apply. Reported by the wordpress.org automated security review of 2.11.8.
     9* Fix: .htaccess copies no longer keep secrets in the database. A .htaccess can hold secrets such as SetEnv credentials, an Authorization header or a php_value with a key, and copies of the whole file put them within reach of anyone able to read the database or a backup of it. The rollback copy now lives only for the length of the write that creates it and is cleared straight after; the unused five-version history that kept raw copies has been removed; the header-recovery snapshot now stores only Vigilant's own block instead of the whole file; and any raw copies left in the database by earlier versions are cleared when you update. Reported by the wordpress.org automated security review of 2.11.8.
     10* Fix: the session limit set to close the oldest sessions now actually closes them. It called the core session API with values that never matched a stored session, so it removed nothing while counting and logging success, and a user could keep more concurrent sessions open than the limit allowed. The oldest sessions are now removed from the session store directly, keeping the current one. Reported by the wordpress.org automated security review of 2.11.8.
    511
    612= 2.11.8 =
  • vigilante/trunk/includes/class-htaccess-manager.php

    r3692177 r3692233  
    6161
    6262    /**
    63      * Rolling history of replaced .htaccess versions, and the one-off snapshot
    64      * taken from a site the 2.9.8 migration had already wiped.
     63     * The single-slot rollback buffer, cleared at the end of every operation.
    6564     *
    6665     * @since 2.10.0
    6766     */
    68     const HISTORY_OPTION       = 'vigilante_htaccess_history';
    69     const HISTORY_ENTRIES      = 5;
    70     const HISTORY_MAX_BYTES    = 262144;
     67    const BACKUP_OPTION = 'vigilante_htaccess_backup';
    7168
    7269    private $known_blocks = array(
    … …  
    223220            return true;
    224221        } finally {
     222            // No .htaccess content, which may hold secrets, is left in the
     223            // options table after the operation. Since 2.11.9.
     224            $this->clear_backup();
    225225            $this->release_lock();
    226226        }
    … …  
    339339            return new WP_Error( 'write_failed', __( 'Failed to write .htaccess', 'vigilante' ) );
    340340        } finally {
     341            // No .htaccess content, which may hold secrets, is left in the
     342            // options table after the operation. Since 2.11.9.
     343            $this->clear_backup();
    341344            $this->release_lock();
    342345        }
    … …  
    613616
    614617    /**
    615      * Create backup of current .htaccess
     618     * Create backup of current .htaccess, for rollback within this operation only
     619     *
     620     * A .htaccess can carry secrets (SetEnv credentials, an Authorization
     621     * header, a php_value with a key), so this rollback buffer is a live copy of
     622     * the file and is cleared at the end of every add_block/remove_block, in the
     623     * finally, rather than left sitting in the options table. Until 2.11.9 it
     624     * persisted between operations and a rolling five-version history kept the
     625     * raw content indefinitely, so anyone who read the database or a backup of
     626     * it recovered those secrets without filesystem access. Reported by the
     627     * wp.org automated review of 2.11.8. The history is gone; the buffer holds
     628     * the real content because restoring a redacted one would write the marker
     629     * into the live file, and lives only for the length of the write.
    616630     *
    617631     * @param string $content Content to backup.
    … …  
    619633     */
    620634    private function create_backup( $content ) {
    621         $this->push_history( (string) $content );
    622 
    623         // Store the backup in a private database option instead of a file under
    624         // the web root, so it can never be served over HTTP.
     635        // A private option, never a file under the web root, and dropped again
     636        // by clear_backup() in the finally of the operation that created it.
    625637        $stored = update_option(
    626             'vigilante_htaccess_backup',
     638            self::BACKUP_OPTION,
    627639            array(
    628640                'content' => (string) $content,
    … …  
    637649
    638650    /**
    639      * Keep the last few .htaccess versions, newest first.
    640      *
    641      * The single-slot backup above is the rollback buffer: it is overwritten by
    642      * the very next write, which is right for its job and useless for anything
    643      * else. Something that only becomes visible days later, such as a header
    644      * that quietly stopped being sent, needs more than one step of history.
    645      *
    646      * Kept in the database with autoload off, never in a file under the web
    647      * root. Bounded on both axes so a large .htaccess cannot inflate the
    648      * options table: oversized files are not stored at all, rather than stored
    649      * truncated, because half an .htaccess is worse than none.
    650      *
    651      * @since 2.10.0
    652      * @param string $content Content being replaced.
    653      */
    654     private function push_history( $content ) {
    655         if ( '' === $content || strlen( $content ) > self::HISTORY_MAX_BYTES ) {
    656             return;
    657         }
    658 
    659         $history = get_option( self::HISTORY_OPTION );
    660         $history = is_array( $history ) ? $history : array();
    661 
    662         // Nothing changed, nothing to record.
    663         if ( isset( $history[0]['content'] ) && $history[0]['content'] === $content ) {
    664             return;
    665         }
    666 
    667         array_unshift(
    668             $history,
    669             array(
    670                 'content' => $content,
    671                 'time'    => time(),
    672                 'version' => VIGILANTE_VERSION,
    673             )
    674         );
    675 
    676         update_option( self::HISTORY_OPTION, array_slice( $history, 0, self::HISTORY_ENTRIES ), false );
     651     * Drop the rollback buffer, so no .htaccess content lingers in the options table
     652     *
     653     * @since 2.11.9
     654     */
     655    private function clear_backup() {
     656        delete_option( self::BACKUP_OPTION );
    677657    }
    678658
    … …  
    683663     */
    684664    private function get_backup_content() {
    685         $backup = get_option( 'vigilante_htaccess_backup' );
     665        $backup = get_option( self::BACKUP_OPTION );
    686666        return ( is_array( $backup ) && isset( $backup['content'] ) ) ? (string) $backup['content'] : '';
    687667    }
  • vigilante/trunk/includes/class-htaccess-recovery.php

    r3690624 r3692233  
    140140        }
    141141
    142         if ( '' === self::extract_block( $content ) ) {
     142        // Only ever our own block is kept, never the whole file. Everything the
     143        // recovery reads later goes through extract_block() anyway, so nothing
     144        // outside our markers is used; and an .htaccess can carry secrets (a
     145        // SetEnv token, an Authorization line), which have no business sitting
     146        // in an option. Our block is response-header directives, public by
     147        // definition. Closes the raw-.htaccess-in-options report (4.4) for this
     148        // path too, without a redaction regex that could miss one.
     149        $block = self::extract_block( (string) $content );
     150
     151        if ( '' === $block ) {
    143152            return;
    144153        }
    … …  
    162171        // que el generador de cabeceras no produce y que harían diferir a
    163172        // cualquier sitio sano que tenga el cortafuegos activo.
    164         $on_disk = self::directives( self::extract_block( $content ) );
     173        $on_disk = self::directives( $block );
    165174        $would   = self::directives( ( new Vigilante_Security_Headers( $settings ) )->generate_rules_content() );
    166175
    … …  
    172181            self::SNAPSHOT_OPTION,
    173182            array(
    174                 'content' => (string) $content,
     183                'content' => $block,
    175184                'time'    => time(),
    176185                'version' => VIGILANTE_VERSION,
  • vigilante/trunk/includes/class-ip-utils.php

    r3692177 r3692233  
    8181
    8282    /**
     83     * Whether an address is in a list, matching exact addresses and CIDR only.
     84     *
     85     * The strict cousin of in_list(), for deciding identity rather than
     86     * filtering traffic. A wildcard entry (1.2.* or a bare *) is never honoured
     87     * here: a proxy the site delegates its client IP to is a specific machine
     88     * or a specific range, and a wildcard in that role is the trust-everyone
     89     * footgun that would reopen the forwarded-header spoofing (6.1) this release
     90     * closes, since matches() turns a bare * into /^.*$/ and trusts every peer.
     91     * Kept apart from in_list() on purpose, so the firewall whitelist keeps its
     92     * wildcards while the proxy-trust decision cannot grow one.
     93     *
     94     * @since 2.11.9
     95     *
     96     * @param string $ip   Address to test.
     97     * @param array  $list List of exact addresses or CIDR ranges.
     98     * @return bool
     99     */
     100    public static function in_list_ip_or_cidr( $ip, $list ) {
     101        if ( empty( $list ) || ! is_array( $list ) ) {
     102            return false;
     103        }
     104
     105        $ip = trim( (string) $ip );
     106        if ( '' === $ip ) {
     107            return false;
     108        }
     109
     110        foreach ( $list as $pattern ) {
     111            $pattern = trim( (string) $pattern );
     112
     113            if ( '' === $pattern || false !== strpos( $pattern, '*' ) ) {
     114                continue;
     115            }
     116
     117            if ( $ip === $pattern ) {
     118                return true;
     119            }
     120
     121            if ( false !== strpos( $pattern, '/' ) && self::cidr_match( $ip, $pattern ) ) {
     122                return true;
     123            }
     124        }
     125
     126        return false;
     127    }
     128
     129    /**
    83130     * Whether a string is a pattern this class can actually match.
    84131     *
    … …  
    165212
    166213            if ( self::is_valid_pattern( $entry ) ) {
     214                $valid[] = $entry;
     215            } else {
     216                $rejected[] = $entry;
     217            }
     218        }
     219
     220        return array(
     221            'valid'    => array_values( array_unique( $valid ) ),
     222            'rejected' => array_values( array_unique( $rejected ) ),
     223        );
     224    }
     225
     226    /**
     227     * Whether a string is a proxy address this class trusts to set a header.
     228     *
     229     * A valid pattern that is not a wildcard: an exact address or a CIDR range.
     230     * The counterpart of in_list_ip_or_cidr() for the save path, so a wildcard
     231     * typed into the trusted proxies field is rejected with feedback instead of
     232     * sitting there matching nothing (or, before the strict matcher, everything).
     233     *
     234     * @since 2.11.9
     235     *
     236     * @param string $pattern Candidate pattern.
     237     * @return bool
     238     */
     239    public static function is_valid_proxy( $pattern ) {
     240        $pattern = trim( (string) $pattern );
     241
     242        return false === strpos( $pattern, '*' ) && self::is_valid_pattern( $pattern );
     243    }
     244
     245    /**
     246     * Split a list into the proxy addresses that are valid and the ones that are not.
     247     *
     248     * Like split_list(), but rejecting wildcards: the trusted proxies list feeds
     249     * an identity decision, and only exact addresses and CIDR ranges belong there.
     250     *
     251     * @since 2.11.9
     252     *
     253     * @param array|string $list List of patterns, or a newline separated string.
     254     * @return array{valid: string[], rejected: string[]}
     255     */
     256    public static function split_list_ip_or_cidr( $list ) {
     257        if ( is_string( $list ) ) {
     258            $list = preg_split( '/[\r\n]+/', $list );
     259        }
     260
     261        $valid    = array();
     262        $rejected = array();
     263
     264        foreach ( (array) $list as $entry ) {
     265            $entry = trim( (string) $entry );
     266
     267            if ( '' === $entry ) {
     268                continue;
     269            }
     270
     271            if ( self::is_valid_proxy( $entry ) ) {
    167272                $valid[] = $entry;
    168273            } else {
    … …  
    358463
    359464    /**
     465     * The proxy IPs/CIDRs the admin declared their forwarded header comes from.
     466     *
     467     * @since 2.11.9
     468     *
     469     * @return string[]
     470     */
     471    public static function trusted_proxies() {
     472        $options = get_option( 'vigilante_options' );
     473        $list    = ( is_array( $options ) && isset( $options['firewall']['trusted_proxies'] ) ) ? $options['firewall']['trusted_proxies'] : array();
     474        return is_array( $list ) ? $list : array();
     475    }
     476
     477    /**
     478     * Cloudflare's published edge ranges, so CF-Connecting-IP verifies itself.
     479     *
     480     * From https://www.cloudflare.com/ips/ (stable, changes rarely). Bundled so
     481     * a site behind Cloudflare does not have to list them by hand; if they ever
     482     * change, the admin can add the new ones to the trusted proxies list.
     483     *
     484     * @since 2.11.9
     485     *
     486     * @return string[]
     487     */
     488    public static function cloudflare_ranges() {
     489        return array(
     490            '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22',
     491            '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20',
     492            '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13',
     493            '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22',
     494            '2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32',
     495            '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32',
     496        );
     497    }
     498
     499    /**
     500     * Whether the TCP peer may be trusted to have set the forwarded header
     501     *
     502     * The reviewer of 2.11.8 was right: honouring CF-Connecting-IP,
     503     * X-Forwarded-For or X-Real-IP without checking who sent them lets any
     504     * visitor whose request reaches PHP directly forge the address the firewall,
     505     * the whitelist and the rate limiter act on. So the header is honoured only
     506     * when the real connection, REMOTE_ADDR, is a proxy we have reason to trust:
     507     *
     508     * - an exact address or CIDR range in the admin's trusted proxies list
     509     *   (wins for any header); a wildcard there is ignored, see
     510     *   in_list_ip_or_cidr();
     511     * - for CF-Connecting-IP, one of Cloudflare's published ranges, since only
     512     *   Cloudflare sends that header;
     513     * - with no list configured, an address of your own network (a reverse proxy
     514     *   in front of PHP, a load balancer in a private subnet), which a visitor
     515     *   hitting a public origin directly is not.
     516     *
     517     * A public load balancer that connects from a public address needs its IPs
     518     * in the trusted proxies list; until then its header is not honoured and the
     519     * connection address is used, which is safe.
     520     *
     521     * @since 2.11.9
     522     *
     523     * @param string   $remote          Validated REMOTE_ADDR.
     524     * @param string   $header          Trusted header key.
     525     * @param string[] $trusted_proxies Configured proxy IPs/CIDRs.
     526     * @return bool
     527     */
     528    private static function peer_is_trusted_proxy( $remote, $header, $trusted_proxies ) {
     529        // A dual-stack proxy connects as ::ffff:10.0.0.5; read it as the IPv4 it
     530        // is, so a private reverse proxy is recognised as own network and a peer
     531        // listed by its IPv4 matches. client_from_chain() already unmaps, this
     532        // keeps the two sides symmetric (found by the cross review of 2.11.9).
     533        $remote = self::unmap_ipv4( $remote );
     534
     535        if ( ! empty( $trusted_proxies ) && self::in_list_ip_or_cidr( $remote, $trusted_proxies ) ) {
     536            return true;
     537        }
     538
     539        if ( 'cf-connecting-ip' === $header && self::in_list_ip_or_cidr( $remote, self::cloudflare_ranges() ) ) {
     540            return true;
     541        }
     542
     543        return empty( $trusted_proxies ) && self::is_own_network( $remote );
     544    }
     545
     546    /**
    360547     * Resolve the client IP from a $_SERVER-like array.
    361548     *
    362549     * Only the real TCP peer (REMOTE_ADDR) is trusted by default, because it
    363      * cannot be spoofed. A forwarded-for / connecting-ip header is honoured
    364      * ONLY when the admin has explicitly declared their site sits behind that
    365      * proxy; otherwise any visitor could forge the header and impersonate any
    366      * IP (bypassing the whitelist, evading the blacklist, poisoning the rate
    367      * limiter, etc.).
    368      *
    369      * @param array  $server         A $_SERVER-like array.
    370      * @param string $trusted_header One of the keys in trusted_header_map(), or '' for none.
     550     * cannot be spoofed. A forwarded-for / connecting-ip header is honoured only
     551     * when the admin has declared their site sits behind that proxy AND the
     552     * connection actually comes from a proxy we trust (see
     553     * peer_is_trusted_proxy()); otherwise any visitor could forge the header and
     554     * impersonate any IP, bypassing the whitelist, evading the blacklist and
     555     * poisoning the rate limiter. Reported by the wp.org review of 2.11.8.
     556     *
     557     * @param array    $server          A $_SERVER-like array.
     558     * @param string   $trusted_header  One of the keys in trusted_header_map(), or '' for none.
     559     * @param string[] $trusted_proxies Configured proxy IPs/CIDRs.
    371560     * @return string Validated IP, or '0.0.0.0' when none could be determined.
    372561     */
    373     public static function resolve_client_ip( $server, $trusted_header = '' ) {
    374         $map = self::trusted_header_map();
    375 
    376         if ( '' !== $trusted_header && isset( $map[ $trusted_header ] ) ) {
    377             $key = $map[ $trusted_header ];
    378             if ( ! empty( $server[ $key ] ) ) {
    379                 $value = self::client_from_chain( (string) $server[ $key ] );
    380                 if ( '' !== $value ) {
    381                     return $value;
    382                 }
    383             }
    384         }
     562    public static function resolve_client_ip( $server, $trusted_header = '', $trusted_proxies = array() ) {
     563        $map    = self::trusted_header_map();
     564        $remote = '';
    385565
    386566        if ( ! empty( $server['REMOTE_ADDR'] ) ) {
    387             $remote = trim( (string) $server['REMOTE_ADDR'] );
    388             if ( filter_var( $remote, FILTER_VALIDATE_IP ) ) {
    389                 return $remote;
    390             }
    391         }
    392 
    393         return '0.0.0.0';
     567            $candidate = trim( (string) $server['REMOTE_ADDR'] );
     568            if ( filter_var( $candidate, FILTER_VALIDATE_IP ) ) {
     569                $remote = $candidate;
     570            }
     571        }
     572
     573        if ( '' !== $trusted_header && isset( $map[ $trusted_header ] ) && '' !== $remote
     574            && ! empty( $server[ $map[ $trusted_header ] ] )
     575            && self::peer_is_trusted_proxy( $remote, $trusted_header, $trusted_proxies )
     576        ) {
     577            $value = self::client_from_chain( (string) $server[ $map[ $trusted_header ] ] );
     578            if ( '' !== $value ) {
     579                return $value;
     580            }
     581        }
     582
     583        return '' !== $remote ? $remote : '0.0.0.0';
    394584    }
    395585
    … …  
    561751        }
    562752
    563         return self::resolve_client_ip( $server, $trusted );
     753        return self::resolve_client_ip( $server, $trusted, self::trusted_proxies() );
    564754    }
    565755}
  • vigilante/trunk/includes/class-settings.php

    r3692177 r3692233  
    9494                // Empty = trust only REMOTE_ADDR (the real connection, unspoofable).
    9595                'trusted_proxy_header'      => '',
     96
     97                // Proxy / CDN: IPs or CIDR ranges the forwarded header is accepted
     98                // from. Empty = accept it only from your own network, and, for
     99                // CF-Connecting-IP, Cloudflare's own ranges. Since 2.11.9, so a
     100                // header cannot be forged by a visitor reaching the origin directly.
     101                'trusted_proxies'           => array(),
    96102
    97103                // User-Agent management
    … …  
    792798    public static function get_user_data_keys() {
    793799        return array(
    794             'firewall'       => array( 'ip_whitelist', 'ip_blacklist', 'ua_whitelist', 'ua_blacklist', 'trusted_proxy_header' ),
     800            'firewall'       => array( 'ip_whitelist', 'ip_blacklist', 'ua_whitelist', 'ua_blacklist', 'trusted_proxy_header', 'trusted_proxies' ),
    795801            'login_security' => array( 'ip_whitelist', 'custom_login_url', 'two_factor' ),
    796802            'user_security'  => array( 'insecure_usernames' ),
  • vigilante/trunk/includes/class-user-security.php

    r3692177 r3692233  
    133133            add_action( 'admin_notices', array( $this, 'show_password_expiration_notice' ) );
    134134            add_action( 'admin_init', array( $this, 'force_password_change_redirect' ) );
     135            // Enforcement beyond wp-admin: REST and the front end, so an expired
     136            // password cannot keep operating outside the redirect (2.11.9).
     137            add_filter( 'rest_authentication_errors', array( $this, 'block_expired_password_rest' ), 20 );
     138            add_action( 'template_redirect', array( $this, 'force_password_change_frontend' ) );
     139            add_filter( 'authenticate', array( $this, 'block_expired_password_xmlrpc' ), 30, 1 );
    135140            add_action( 'profile_update', array( $this, 'update_password_change_date' ), 10, 2 );
    136141            add_action( 'user_register', array( $this, 'set_initial_password_date' ) );
    … …  
    19831988
    19841989        if ( 'close_oldest' === $behavior ) {
    1985             // Sort by login time and destroy oldest
    1986             uasort( $all_sessions, function( $a, $b ) {
    1987                 return ( $a['login'] ?? 0 ) - ( $b['login'] ?? 0 );
     1990            /*
     1991             * Remove the oldest sessions by editing the session store directly.
     1992             *
     1993             * WP_Session_Tokens::get_all() returns array_values( get_sessions() ),
     1994             * so its keys are 0, 1, 2, not tokens, and destroy() expects a raw
     1995             * token, which is not stored anywhere and cannot be recovered for a
     1996             * session other than the current one. Until 2.11.9 the loop passed
     1997             * those numeric keys to destroy(), which hashed them, matched nothing
     1998             * and closed no session while still counting and logging success, so
     1999             * the cap did nothing under close_oldest. Reported by the wp.org
     2000             * automated review of 2.11.8.
     2001             *
     2002             * The store keeps the sessions as the user meta 'session_tokens',
     2003             * keyed by the verifier hash( 'sha256', token ), which is the value
     2004             * is_current_session() already compares against. So the oldest are
     2005             * removed from that map, keeping the current session whatever its age.
     2006             * On a network the meta is global (one finding of the multisite audit,
     2007             * to be reworked in 3.1.0); here the fix is only to make the removal
     2008             * actually happen.
     2009             */
     2010            $stored = get_user_meta( $user->ID, 'session_tokens', true );
     2011
     2012            if ( ! is_array( $stored ) || empty( $stored ) ) {
     2013                return;
     2014            }
     2015
     2016            $now     = time();
     2017            $changed = false;
     2018
     2019            // Expired sessions are dead weight and count for nothing; drop them first.
     2020            foreach ( $stored as $verifier => $session ) {
     2021                if ( isset( $session['expiration'] ) && (int) $session['expiration'] < $now ) {
     2022                    unset( $stored[ $verifier ] );
     2023                    $changed = true;
     2024                }
     2025            }
     2026
     2027            // Oldest first, keeping the current session whatever its login time.
     2028            uasort( $stored, function ( $a, $b ) {
     2029                return ( $a['login'] ?? 0 ) <=> ( $b['login'] ?? 0 );
    19882030            } );
    19892031
    1990             $sessions_to_remove = $session_count - $max_sessions;
    1991             $removed = 0;
    1992 
    1993             foreach ( $all_sessions as $token_hash => $session ) {
     2032            $sessions_to_remove = count( $stored ) - $max_sessions;
     2033            $removed            = 0;
     2034
     2035            foreach ( $stored as $verifier => $session ) {
    19942036                if ( $removed >= $sessions_to_remove ) {
    19952037                    break;
    19962038                }
    1997                 // Don't remove current session
    1998                 if ( ! $this->is_current_session( $token_hash ) ) {
    1999                     $sessions->destroy( $token_hash );
    2000                     $removed++;
     2039                if ( $this->is_current_session( $verifier ) ) {
     2040                    continue;
    20012041                }
     2042                unset( $stored[ $verifier ] );
     2043                $removed++;
     2044                $changed = true;
     2045            }
     2046
     2047            if ( $changed ) {
     2048                update_user_meta( $user->ID, 'session_tokens', $stored );
    20022049            }
    20032050
    … …  
    21242171
    21252172    /**
    2126      * Force redirect to password change page
     2173     * Whether this user must change an expired password before doing anything else
     2174     *
     2175     * The flag alone is not enough: it is re-checked against the current policy,
     2176     * because the admin may have taken the user's role out of affected_roles or
     2177     * added the user to the exclusion list after it was set, which would
     2178     * otherwise lock them in a redirect loop. A stale flag is cleared on a
     2179     * single site; on a network the meta is shared by every site and the policy
     2180     * checked is only this site's, so it is left alone and simply not enforced
     2181     * here (a network-wide rework is the 3.1.0 multisite item).
     2182     *
     2183     * @since 2.11.9
     2184     *
     2185     * @param int $user_id User ID.
     2186     * @return bool
     2187     */
     2188    private function must_change_password( $user_id ) {
     2189        if ( ! $user_id ) {
     2190            return false;
     2191        }
     2192
     2193        $flagged = (bool) get_user_meta( $user_id, 'vigilante_must_change_password', true );
     2194
     2195        if ( ! $this->is_password_expiration_applicable( $user_id ) ) {
     2196            if ( $flagged && ! is_multisite() ) {
     2197                delete_user_meta( $user_id, 'vigilante_must_change_password' );
     2198            }
     2199            return false;
     2200        }
     2201
     2202        if ( $flagged ) {
     2203            return true;
     2204        }
     2205
     2206        // The flag is set at interactive login (check_password_expiration on
     2207        // wp_login). A session that authenticates only through REST, XML-RPC or
     2208        // an application password never fires wp_login, so the flag can be
     2209        // absent while the password is in fact expired. Compute it on the fly
     2210        // too, so a non-interactive route is not a way around the block. The
     2211        // computation self-seeds the change date on first sight and never locks
     2212        // out a user who has no record yet (see is_password_expired()).
     2213        return $this->is_password_expired( $user_id );
     2214    }
     2215
     2216    /**
     2217     * Force a user with an expired password to change it, on wp-admin and AJAX
     2218     *
     2219     * Until 2.11.9 this only redirected wp-admin pages and skipped AJAX, so an
     2220     * expired-password session kept working through admin-ajax, and the REST API
     2221     * and the front end were not covered at all. The wp.org automated review of
     2222     * 2.11.8 flagged it: setting a flag on login is not enforcement if the flag
     2223     * is only read by one redirect. It is now enforced on every entry point,
     2224     * here for wp-admin and AJAX and in the three methods below for REST, the
     2225     * front end and XML-RPC. The only thing an affected user can still do is
     2226     * change the password on profile.php or log out.
    21272227     */
    21282228    public function force_password_change_redirect() {
    2129         if ( ! is_user_logged_in() ) {
    2130             return;
    2131         }
    2132 
    2133         // Don't redirect on AJAX or profile page
     2229        if ( ! is_user_logged_in() || ! $this->must_change_password( get_current_user_id() ) ) {
     2230            return;
     2231        }
     2232
     2233        // AJAX: a redirect is useless, so the request is refused. Changing the
     2234        // password is a profile.php form POST, not AJAX, so nothing the user
     2235        // needs to fix this is blocked.
    21342236        if ( wp_doing_ajax() ) {
    2135             return;
    2136         }
    2137 
     2237            wp_send_json_error(
     2238                array( 'message' => __( 'Your password has expired. Change it in your profile before continuing.', 'vigilante' ) ),
     2239                403
     2240            );
     2241        }
     2242
     2243        // profile.php is where the change happens; do not redirect it onto itself.
    21382244        global $pagenow;
    21392245        if ( 'profile.php' === $pagenow ) {
    … …  
    21412247        }
    21422248
    2143         $user_id = get_current_user_id();
    2144         $must_change = get_user_meta( $user_id, 'vigilante_must_change_password', true );
    2145 
    2146         if ( ! $must_change ) {
    2147             return;
    2148         }
    2149 
    2150         // Re-validate against current settings: the admin may have removed
    2151         // this user's role from affected_roles or added the user to the
    2152         // excluded list after the flag was set. Without this check the flag
    2153         // outlives the configuration change and locks the user in a redirect
    2154         // loop into profile.php.
    2155         if ( ! $this->is_password_expiration_applicable( $user_id ) ) {
    2156             // On a network the flag is a user meta that every site shares, and the
    2157             // policy just checked is only this site's: another site may have set
    2158             // it, and clearing it here let a user skip that site's forced change
    2159             // by visiting any other dashboard. It is only cleared on a single
    2160             // site (2.11.8); on a network the user is just not redirected here.
    2161             if ( ! is_multisite() ) {
    2162                 delete_user_meta( $user_id, 'vigilante_must_change_password' );
    2163             }
    2164             return;
    2165         }
    2166 
    21672249        wp_safe_redirect( admin_url( 'profile.php#password' ) );
    21682250        exit;
     2251    }
     2252
     2253    /**
     2254     * Refuse REST API requests from a user whose password has expired
     2255     *
     2256     * @since 2.11.9
     2257     *
     2258     * @param WP_Error|null|true $result Result of the earlier authentication checks.
     2259     * @return WP_Error|null|true
     2260     */
     2261    public function block_expired_password_rest( $result ) {
     2262        // Leave any decision another check already made, and do not act on
     2263        // logged-out requests to public endpoints.
     2264        if ( null !== $result && false !== $result ) {
     2265            return $result;
     2266        }
     2267
     2268        if ( is_user_logged_in() && $this->must_change_password( get_current_user_id() ) ) {
     2269            return new WP_Error(
     2270                'vigilante_password_expired',
     2271                __( 'Your password has expired. Change it in your profile before using the REST API.', 'vigilante' ),
     2272                array( 'status' => 403 )
     2273            );
     2274        }
     2275
     2276        return $result;
     2277    }
     2278
     2279    /**
     2280     * Send a user with an expired password to the change page from the front end
     2281     *
     2282     * @since 2.11.9
     2283     */
     2284    public function force_password_change_frontend() {
     2285        if ( is_admin() || ! is_user_logged_in() || ! $this->must_change_password( get_current_user_id() ) ) {
     2286            return;
     2287        }
     2288
     2289        wp_safe_redirect( admin_url( 'profile.php#password' ) );
     2290        exit;
     2291    }
     2292
     2293    /**
     2294     * Refuse XML-RPC calls from a user whose password has expired
     2295     *
     2296     * The last of the four non-wp-admin entry points. XML-RPC authenticates on
     2297     * every call with the account credentials (a password or an application
     2298     * password), so a session that never touches wp-admin could keep acting
     2299     * through xmlrpc.php while the password sits expired. Scoped to XML-RPC
     2300     * requests so an ordinary login, which the user needs to reach profile.php,
     2301     * is never blocked here. Runs late on authenticate, after core and the
     2302     * application-password handler have resolved the user.
     2303     *
     2304     * @since 2.11.9
     2305     *
     2306     * @param WP_User|WP_Error|null $user Result of the earlier authentication.
     2307     * @return WP_User|WP_Error|null
     2308     */
     2309    public function block_expired_password_xmlrpc( $user ) {
     2310        if ( ! ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) ) {
     2311            return $user;
     2312        }
     2313
     2314        if ( $user instanceof WP_User && $this->must_change_password( $user->ID ) ) {
     2315            return new WP_Error(
     2316                'vigilante_password_expired',
     2317                __( 'Your password has expired. Change it in your profile before using XML-RPC.', 'vigilante' ),
     2318                array( 'status' => 403 )
     2319            );
     2320        }
     2321
     2322        return $user;
    21692323    }
    21702324
  • vigilante/trunk/readme.txt

    r3692177 r3692233  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 2.11.8
     7Stable tag: 2.11.9
    88License: GPL v2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    415415
    416416== Changelog ==
     417
     418= 2.11.9 =
     419Security fixes: a trusted forwarded IP header is accepted only from a verified proxy, an expired password is enforced beyond wp-admin, the session limit closes old sessions again, and .htaccess copies no longer keep secrets in the database.
     420
     421* Fix: when a forwarded header is trusted (X-Forwarded-For, X-Real-IP or CF-Connecting-IP), Vigilant now accepts it only from a connection it can verify as a proxy: an address in the new Trusted proxy IPs list, one of Cloudflare's own ranges for the CF-Connecting-IP header, or, when no list is set, your own private network. Until 2.11.9 the header was honoured whoever sent it, so a visitor whose request reached the origin directly could forge the address the firewall, the IP whitelist and blacklist and the rate-limit counters act on, rotating it to dodge throttling or setting a whitelisted one to skip the checks. Reported by the wordpress.org automated security review of 2.11.8. If your load balancer connects from a public address, add it to Trusted proxy IPs in the Firewall tab, or its header is ignored and every visitor is seen as that balancer.
     422* Fix: an expired password is now enforced on the REST API, admin-ajax, the front end and XML-RPC, not only on wp-admin screens. Enforcement was a wp-admin redirect that skipped AJAX and never ran on the other routes, so a session whose password had expired kept working through them; now the account can only change the password or log out until it does. The feature must be enabled for this to apply. Reported by the wordpress.org automated security review of 2.11.8.
     423* Fix: .htaccess copies no longer keep secrets in the database. A .htaccess can hold secrets such as SetEnv credentials, an Authorization header or a php_value with a key, and copies of the whole file put them within reach of anyone able to read the database or a backup of it. The rollback copy now lives only for the length of the write that creates it and is cleared straight after; the unused five-version history that kept raw copies has been removed; the header-recovery snapshot now stores only Vigilant's own block instead of the whole file; and any raw copies left in the database by earlier versions are cleared when you update. Reported by the wordpress.org automated security review of 2.11.8.
     424* Fix: the session limit set to close the oldest sessions now actually closes them. It called the core session API with values that never matched a stored session, so it removed nothing while counting and logging success, and a user could keep more concurrent sessions open than the limit allowed. The oldest sessions are now removed from the session store directly, keeping the current one. Reported by the wordpress.org automated security review of 2.11.8.
    417425
    418426= 2.11.8 =
    … …  
    463471== Upgrade Notice ==
    464472
    465 = 2.11.8 =
    466 Security fixes: the Under Attack challenge and its rate limit, the visitor IP behind X-Forwarded-For, secrets left in the integrity scan copy of wp-config.php, and several permission checks on networks.
     473= 2.11.9 =
     474Security fixes: a trusted forwarded IP header is accepted only from a verified proxy, an expired password is enforced beyond wp-admin, the session limit closes old sessions again, and .htaccess copies no longer keep secrets in the database.
    467475
    468476== Support ==
  • vigilante/trunk/uninstall.php

    r3692177 r3692233  
    188188        // the options table long after the plugin is gone.
    189189        'vigilante_htaccess_backup',
     190        'vigilante_htaccess_history',
     191        // The pre-migration snapshot keeps our own header block so the owner can
     192        // restore it; it is still ours to remove on uninstall, along with the
     193        // recovery undo copy and the dismissed flag.
     194        'vigilante_htaccess_pre_migration',
     195        'vigilante_htaccess_recovery_undo',
     196        'vigilante_htaccess_recovery_done',
    190197        'vigilante_wpconfig_backup',
    191198        'vigilante_config_copies_purged',
  • vigilante/trunk/vigilante.php

    r3692177 r3692233  
    44 * Plugin URI: https://servicios.ayudawp.com
    55 * Description: Complete security solution for WordPress. Firewall, 2FA, security headers, login protection, file integrity monitoring, activity logging and more.
    6  * Version: 2.11.8
     6 * Version: 2.11.9
    77 * Author: Fernando Tellado
    88 * Author URI: https://ayudawp.com
    … …  
    2525 * Plugin constants
    2626 */
    27 define( 'VIGILANTE_VERSION', '2.11.8' );
     27define( 'VIGILANTE_VERSION', '2.11.9' );
    2828define( 'VIGILANTE_PLUGIN_FILE', __FILE__ );
    2929define( 'VIGILANTE_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
Note: See TracChangeset for help on using the changeset viewer.