mirror of
https://gitlab.com/ArkHost/WP-Security-Pack.git
synced 2026-07-24 07:55:53 +02:00
first commit
This commit is contained in:
@@ -0,0 +1,278 @@
|
||||
<?php
|
||||
/**
|
||||
* Activity logging for WP Security Pack.
|
||||
*
|
||||
* @package WP_Security_Pack
|
||||
*/
|
||||
|
||||
// Prevent direct access.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Activity log class.
|
||||
*/
|
||||
class WPSP_Activity_Log {
|
||||
|
||||
/**
|
||||
* Event types.
|
||||
*/
|
||||
const EVENT_LOGIN_SUCCESS = 'login_success';
|
||||
const EVENT_LOGIN_FAILED = 'login_failed';
|
||||
const EVENT_LOCKOUT = 'lockout';
|
||||
const EVENT_IP_BLOCKED = 'ip_blocked';
|
||||
const EVENT_GEO_BLOCKED = 'geo_blocked';
|
||||
const EVENT_LOCKOUT_LIFTED = 'lockout_lifted';
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
// Hooks are set up by Login Protection class.
|
||||
}
|
||||
|
||||
/**
|
||||
* Log an event.
|
||||
*
|
||||
* @param string $event_type Event type.
|
||||
* @param string|null $ip_address IP address (auto-detected if null).
|
||||
* @param string|null $username Username.
|
||||
* @param string|null $details Additional details.
|
||||
* @return int|false Insert ID or false on failure.
|
||||
*/
|
||||
public static function log( $event_type, $ip_address = null, $username = null, $details = null ) {
|
||||
global $wpdb;
|
||||
|
||||
if ( null === $ip_address ) {
|
||||
$ip_address = WPSP_Helper::get_client_ip();
|
||||
}
|
||||
|
||||
// Get user agent.
|
||||
$user_agent = isset( $_SERVER['HTTP_USER_AGENT'] )
|
||||
? substr( sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ), 0, 255 )
|
||||
: '';
|
||||
|
||||
// Get country code if geo-blocking is available.
|
||||
$country_code = null;
|
||||
$geo_blocking = wpsp()->get_component( 'geo_blocking' );
|
||||
if ( $geo_blocking && $ip_address ) {
|
||||
$country_code = $geo_blocking->get_country_code( $ip_address );
|
||||
}
|
||||
|
||||
$table = WPSP_DB::get_log_table();
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$result = $wpdb->insert(
|
||||
$table,
|
||||
array(
|
||||
'event_type' => $event_type,
|
||||
'ip_address' => $ip_address ? $ip_address : '',
|
||||
'username' => $username,
|
||||
'user_agent' => $user_agent,
|
||||
'country_code' => $country_code,
|
||||
'details' => $details,
|
||||
'created_at' => current_time( 'mysql' ),
|
||||
),
|
||||
array( '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
|
||||
);
|
||||
|
||||
return $result ? $wpdb->insert_id : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recent logs.
|
||||
*
|
||||
* @param array $args Query arguments.
|
||||
* @return array
|
||||
*/
|
||||
public static function get_logs( $args = array() ) {
|
||||
global $wpdb;
|
||||
|
||||
$defaults = array(
|
||||
'limit' => 50,
|
||||
'offset' => 0,
|
||||
'event_type' => '',
|
||||
'ip_address' => '',
|
||||
'orderby' => 'created_at',
|
||||
'order' => 'DESC',
|
||||
);
|
||||
|
||||
$args = wp_parse_args( $args, $defaults );
|
||||
$table = WPSP_DB::get_log_table();
|
||||
|
||||
$where_clauses = array( '1=1' );
|
||||
$where_values = array();
|
||||
|
||||
if ( ! empty( $args['event_type'] ) ) {
|
||||
$where_clauses[] = 'event_type = %s';
|
||||
$where_values[] = $args['event_type'];
|
||||
}
|
||||
|
||||
if ( ! empty( $args['ip_address'] ) ) {
|
||||
$where_clauses[] = 'ip_address = %s';
|
||||
$where_values[] = $args['ip_address'];
|
||||
}
|
||||
|
||||
$where_sql = implode( ' AND ', $where_clauses );
|
||||
|
||||
// Sanitize orderby.
|
||||
$allowed_orderby = array( 'id', 'event_type', 'ip_address', 'username', 'created_at' );
|
||||
$orderby = in_array( $args['orderby'], $allowed_orderby, true ) ? $args['orderby'] : 'created_at';
|
||||
$order = 'ASC' === strtoupper( $args['order'] ) ? 'ASC' : 'DESC';
|
||||
|
||||
$limit = absint( $args['limit'] );
|
||||
$offset = absint( $args['offset'] );
|
||||
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$sql = "SELECT * FROM {$table} WHERE {$where_sql} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d";
|
||||
|
||||
$where_values[] = $limit;
|
||||
$where_values[] = $offset;
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.NotPrepared
|
||||
return $wpdb->get_results( $wpdb->prepare( $sql, $where_values ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total log count.
|
||||
*
|
||||
* @param array $args Query arguments.
|
||||
* @return int
|
||||
*/
|
||||
public static function get_log_count( $args = array() ) {
|
||||
global $wpdb;
|
||||
|
||||
$table = WPSP_DB::get_log_table();
|
||||
|
||||
$where_clauses = array( '1=1' );
|
||||
$where_values = array();
|
||||
|
||||
if ( ! empty( $args['event_type'] ) ) {
|
||||
$where_clauses[] = 'event_type = %s';
|
||||
$where_values[] = $args['event_type'];
|
||||
}
|
||||
|
||||
if ( ! empty( $args['ip_address'] ) ) {
|
||||
$where_clauses[] = 'ip_address = %s';
|
||||
$where_values[] = $args['ip_address'];
|
||||
}
|
||||
|
||||
$where_sql = implode( ' AND ', $where_clauses );
|
||||
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$sql = "SELECT COUNT(*) FROM {$table} WHERE {$where_sql}";
|
||||
|
||||
if ( ! empty( $where_values ) ) {
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.NotPrepared
|
||||
return (int) $wpdb->get_var( $wpdb->prepare( $sql, $where_values ) );
|
||||
}
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.NotPrepared
|
||||
return (int) $wpdb->get_var( $sql );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get log statistics.
|
||||
*
|
||||
* @param int $days Number of days to look back.
|
||||
* @return array
|
||||
*/
|
||||
public static function get_stats( $days = 30 ) {
|
||||
global $wpdb;
|
||||
|
||||
$table = WPSP_DB::get_log_table();
|
||||
$cutoff = gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) );
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$results = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
"SELECT event_type, COUNT(*) as count FROM {$table} WHERE created_at >= %s GROUP BY event_type",
|
||||
$cutoff
|
||||
)
|
||||
);
|
||||
|
||||
$stats = array(
|
||||
'login_success' => 0,
|
||||
'login_failed' => 0,
|
||||
'lockout' => 0,
|
||||
'ip_blocked' => 0,
|
||||
'geo_blocked' => 0,
|
||||
'total' => 0,
|
||||
);
|
||||
|
||||
foreach ( $results as $row ) {
|
||||
$stats[ $row->event_type ] = (int) $row->count;
|
||||
$stats['total'] += (int) $row->count;
|
||||
}
|
||||
|
||||
return $stats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup old logs (cron job).
|
||||
*/
|
||||
public static function cleanup_old_logs() {
|
||||
global $wpdb;
|
||||
|
||||
$retention_days = WP_Security_Pack::get_setting( 'log_retention_days', 30 );
|
||||
$cutoff = gmdate( 'Y-m-d H:i:s', strtotime( "-{$retention_days} days" ) );
|
||||
|
||||
$log_table = WPSP_DB::get_log_table();
|
||||
$lockout_table = WPSP_DB::get_lockout_table();
|
||||
|
||||
// Delete old logs.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$wpdb->query(
|
||||
$wpdb->prepare(
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
"DELETE FROM {$log_table} WHERE created_at < %s",
|
||||
$cutoff
|
||||
)
|
||||
);
|
||||
|
||||
// Delete expired lockouts (lockout_until stores Unix timestamp as integer).
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$wpdb->query(
|
||||
$wpdb->prepare(
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
"DELETE FROM {$lockout_table} WHERE lockout_until IS NOT NULL AND lockout_until > 0 AND lockout_until < %d",
|
||||
time()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all logs.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function clear_all_logs() {
|
||||
global $wpdb;
|
||||
|
||||
$table = WPSP_DB::get_log_table();
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
return false !== $wpdb->query( "TRUNCATE TABLE {$table}" );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get event type label.
|
||||
*
|
||||
* @param string $event_type Event type.
|
||||
* @return string
|
||||
*/
|
||||
public static function get_event_label( $event_type ) {
|
||||
$labels = array(
|
||||
self::EVENT_LOGIN_SUCCESS => __( 'Login Success', 'wp-security-pack' ),
|
||||
self::EVENT_LOGIN_FAILED => __( 'Login Failed', 'wp-security-pack' ),
|
||||
self::EVENT_LOCKOUT => __( 'Lockout', 'wp-security-pack' ),
|
||||
self::EVENT_IP_BLOCKED => __( 'IP Blocked', 'wp-security-pack' ),
|
||||
self::EVENT_GEO_BLOCKED => __( 'Geo Blocked', 'wp-security-pack' ),
|
||||
self::EVENT_LOCKOUT_LIFTED => __( 'Lockout Lifted', 'wp-security-pack' ),
|
||||
);
|
||||
|
||||
return isset( $labels[ $event_type ] ) ? $labels[ $event_type ] : $event_type;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
/**
|
||||
* Database management for WP Security Pack.
|
||||
*
|
||||
* @package WP_Security_Pack
|
||||
*/
|
||||
|
||||
// Prevent direct access.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Database class for table creation and management.
|
||||
*/
|
||||
class WPSP_DB {
|
||||
|
||||
/**
|
||||
* Database version.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const DB_VERSION = '1.0.1';
|
||||
|
||||
/**
|
||||
* Get activity log table name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function get_log_table() {
|
||||
global $wpdb;
|
||||
return $wpdb->prefix . 'wpsp_activity_log';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get lockouts table name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function get_lockout_table() {
|
||||
global $wpdb;
|
||||
return $wpdb->prefix . 'wpsp_lockouts';
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin activation.
|
||||
*/
|
||||
public static function activate() {
|
||||
self::create_tables();
|
||||
self::set_default_options();
|
||||
|
||||
// Store DB version.
|
||||
update_option( 'wpsp_db_version', self::DB_VERSION );
|
||||
|
||||
// Clear rewrite rules for custom login URL.
|
||||
flush_rewrite_rules();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if database needs upgrading.
|
||||
*/
|
||||
public static function maybe_upgrade() {
|
||||
$current_version = get_option( 'wpsp_db_version', '0' );
|
||||
|
||||
if ( version_compare( $current_version, self::DB_VERSION, '<' ) ) {
|
||||
self::create_tables();
|
||||
update_option( 'wpsp_db_version', self::DB_VERSION );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin deactivation.
|
||||
*/
|
||||
public static function deactivate() {
|
||||
// Clear scheduled events.
|
||||
wp_clear_scheduled_hook( 'wpsp_daily_cleanup' );
|
||||
|
||||
// Flush rewrite rules.
|
||||
flush_rewrite_rules();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create database tables.
|
||||
*/
|
||||
public static function create_tables() {
|
||||
global $wpdb;
|
||||
|
||||
$charset_collate = $wpdb->get_charset_collate();
|
||||
|
||||
$log_table = self::get_log_table();
|
||||
$lockout_table = self::get_lockout_table();
|
||||
|
||||
// Activity log table.
|
||||
$sql_log = "CREATE TABLE {$log_table} (
|
||||
id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
event_type varchar(50) NOT NULL,
|
||||
ip_address varchar(45) NOT NULL,
|
||||
username varchar(60) DEFAULT NULL,
|
||||
user_agent varchar(255) DEFAULT NULL,
|
||||
country_code varchar(2) DEFAULT NULL,
|
||||
details text DEFAULT NULL,
|
||||
created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (id),
|
||||
KEY event_type (event_type),
|
||||
KEY ip_address (ip_address),
|
||||
KEY created_at (created_at)
|
||||
) {$charset_collate};";
|
||||
|
||||
// Lockouts table.
|
||||
// Note: lockout_until stores Unix timestamp as BIGINT for reliable comparisons.
|
||||
$sql_lockout = "CREATE TABLE {$lockout_table} (
|
||||
id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
ip_address varchar(45) NOT NULL,
|
||||
failed_attempts int(11) NOT NULL DEFAULT 0,
|
||||
lockout_until bigint(20) DEFAULT NULL,
|
||||
created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY ip_address (ip_address),
|
||||
KEY lockout_until (lockout_until)
|
||||
) {$charset_collate};";
|
||||
|
||||
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
|
||||
dbDelta( $sql_log );
|
||||
dbDelta( $sql_lockout );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set default options on activation.
|
||||
*/
|
||||
private static function set_default_options() {
|
||||
$existing = get_option( 'wpsp_settings', false );
|
||||
|
||||
if ( false === $existing ) {
|
||||
$defaults = WP_Security_Pack::get_default_settings();
|
||||
update_option( 'wpsp_settings', $defaults );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstall plugin (called from uninstall.php).
|
||||
*/
|
||||
public static function uninstall() {
|
||||
global $wpdb;
|
||||
|
||||
// Drop tables.
|
||||
$log_table = self::get_log_table();
|
||||
$lockout_table = self::get_lockout_table();
|
||||
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$wpdb->query( "DROP TABLE IF EXISTS {$log_table}" );
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$wpdb->query( "DROP TABLE IF EXISTS {$lockout_table}" );
|
||||
|
||||
// Delete options.
|
||||
delete_option( 'wpsp_settings' );
|
||||
delete_option( 'wpsp_db_version' );
|
||||
|
||||
// Delete transients.
|
||||
delete_transient( 'wpsp_geo_cache' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
<?php
|
||||
/**
|
||||
* File integrity monitoring for WP Security Pack.
|
||||
*
|
||||
* @package WP_Security_Pack
|
||||
*/
|
||||
|
||||
// Prevent direct access.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* File integrity monitoring class.
|
||||
*/
|
||||
class WPSP_File_Integrity {
|
||||
|
||||
/**
|
||||
* Option key for file hashes.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const HASHES_OPTION = 'wpsp_file_hashes';
|
||||
|
||||
/**
|
||||
* Option key for last scan time.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const LAST_SCAN_OPTION = 'wpsp_file_integrity_last_scan';
|
||||
|
||||
/**
|
||||
* Option key for changed files.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const CHANGES_OPTION = 'wpsp_file_changes';
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
if ( ! WP_Security_Pack::get_setting( 'file_integrity_enabled', true ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Schedule daily scan.
|
||||
add_action( 'wpsp_daily_file_scan', array( $this, 'run_scheduled_scan' ) );
|
||||
|
||||
if ( ! wp_next_scheduled( 'wpsp_daily_file_scan' ) ) {
|
||||
wp_schedule_event( time(), 'daily', 'wpsp_daily_file_scan' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run scheduled scan.
|
||||
*/
|
||||
public function run_scheduled_scan() {
|
||||
$changes = $this->scan_core_files();
|
||||
|
||||
if ( ! empty( $changes['modified'] ) || ! empty( $changes['added'] ) || ! empty( $changes['removed'] ) ) {
|
||||
// Store changes.
|
||||
update_option( self::CHANGES_OPTION, $changes );
|
||||
|
||||
// Send alert if enabled.
|
||||
$this->send_alert( $changes );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan WordPress core files.
|
||||
*
|
||||
* @param bool $update_baseline Whether to update the baseline.
|
||||
* @return array
|
||||
*/
|
||||
public function scan_core_files( $update_baseline = false ) {
|
||||
global $wp_version;
|
||||
|
||||
$changes = array(
|
||||
'modified' => array(),
|
||||
'added' => array(),
|
||||
'removed' => array(),
|
||||
);
|
||||
|
||||
// Get stored hashes.
|
||||
$stored_hashes = get_option( self::HASHES_OPTION, array() );
|
||||
|
||||
// Get official checksums from WordPress.org.
|
||||
$official_checksums = $this->get_official_checksums( $wp_version );
|
||||
|
||||
// Current file hashes.
|
||||
$current_hashes = array();
|
||||
|
||||
// Core directories to scan.
|
||||
$core_paths = array(
|
||||
ABSPATH . 'wp-admin/',
|
||||
ABSPATH . 'wp-includes/',
|
||||
ABSPATH . 'index.php',
|
||||
ABSPATH . 'wp-activate.php',
|
||||
ABSPATH . 'wp-blog-header.php',
|
||||
ABSPATH . 'wp-comments-post.php',
|
||||
ABSPATH . 'wp-cron.php',
|
||||
ABSPATH . 'wp-links-opml.php',
|
||||
ABSPATH . 'wp-load.php',
|
||||
ABSPATH . 'wp-login.php',
|
||||
ABSPATH . 'wp-mail.php',
|
||||
ABSPATH . 'wp-settings.php',
|
||||
ABSPATH . 'wp-signup.php',
|
||||
ABSPATH . 'wp-trackback.php',
|
||||
ABSPATH . 'xmlrpc.php',
|
||||
);
|
||||
|
||||
// Scan each path.
|
||||
foreach ( $core_paths as $path ) {
|
||||
if ( is_file( $path ) ) {
|
||||
$relative_path = str_replace( ABSPATH, '', $path );
|
||||
$hash = md5_file( $path );
|
||||
|
||||
$current_hashes[ $relative_path ] = $hash;
|
||||
} elseif ( is_dir( $path ) ) {
|
||||
$files = $this->get_directory_files( $path );
|
||||
|
||||
foreach ( $files as $file ) {
|
||||
$relative_path = str_replace( ABSPATH, '', $file );
|
||||
$hash = md5_file( $file );
|
||||
|
||||
$current_hashes[ $relative_path ] = $hash;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Compare with official checksums if available.
|
||||
if ( ! empty( $official_checksums ) ) {
|
||||
foreach ( $current_hashes as $file => $hash ) {
|
||||
if ( isset( $official_checksums[ $file ] ) ) {
|
||||
if ( $hash !== $official_checksums[ $file ] ) {
|
||||
$changes['modified'][] = array(
|
||||
'file' => $file,
|
||||
'expected' => $official_checksums[ $file ],
|
||||
'actual' => $hash,
|
||||
'source' => 'official',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} elseif ( ! empty( $stored_hashes ) ) {
|
||||
// Compare with stored baseline.
|
||||
foreach ( $current_hashes as $file => $hash ) {
|
||||
if ( isset( $stored_hashes[ $file ] ) ) {
|
||||
if ( $hash !== $stored_hashes[ $file ] ) {
|
||||
$changes['modified'][] = array(
|
||||
'file' => $file,
|
||||
'previous' => $stored_hashes[ $file ],
|
||||
'current' => $hash,
|
||||
'source' => 'baseline',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
$changes['added'][] = $file;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for removed files.
|
||||
foreach ( $stored_hashes as $file => $hash ) {
|
||||
if ( ! isset( $current_hashes[ $file ] ) ) {
|
||||
$changes['removed'][] = $file;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update baseline if requested or first scan.
|
||||
if ( $update_baseline || empty( $stored_hashes ) ) {
|
||||
update_option( self::HASHES_OPTION, $current_hashes );
|
||||
}
|
||||
|
||||
// Update last scan time.
|
||||
update_option( self::LAST_SCAN_OPTION, time() );
|
||||
|
||||
return $changes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get official checksums from WordPress.org.
|
||||
*
|
||||
* @param string $version WordPress version.
|
||||
* @return array
|
||||
*/
|
||||
private function get_official_checksums( $version ) {
|
||||
$locale = get_locale();
|
||||
|
||||
// Try to get from cache.
|
||||
$cache_key = 'wpsp_checksums_' . md5( $version . $locale );
|
||||
$cached = get_transient( $cache_key );
|
||||
|
||||
if ( false !== $cached ) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
// Fetch from WordPress.org.
|
||||
$url = sprintf(
|
||||
'https://api.wordpress.org/core/checksums/1.0/?version=%s&locale=%s',
|
||||
$version,
|
||||
$locale
|
||||
);
|
||||
|
||||
$response = wp_remote_get( $url, array( 'timeout' => 30 ) );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$body = wp_remote_retrieve_body( $response );
|
||||
$data = json_decode( $body, true );
|
||||
|
||||
if ( ! isset( $data['checksums'] ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$checksums = $data['checksums'];
|
||||
|
||||
// Cache for 1 day.
|
||||
set_transient( $cache_key, $checksums, DAY_IN_SECONDS );
|
||||
|
||||
return $checksums;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all PHP files in a directory recursively.
|
||||
*
|
||||
* @param string $dir Directory path.
|
||||
* @return array
|
||||
*/
|
||||
private function get_directory_files( $dir ) {
|
||||
$files = array();
|
||||
$iterator = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator( $dir, RecursiveDirectoryIterator::SKIP_DOTS ),
|
||||
RecursiveIteratorIterator::SELF_FIRST
|
||||
);
|
||||
|
||||
foreach ( $iterator as $file ) {
|
||||
if ( $file->isFile() ) {
|
||||
$ext = strtolower( $file->getExtension() );
|
||||
// Only track PHP files and critical files.
|
||||
if ( in_array( $ext, array( 'php', 'js', 'css' ), true ) ) {
|
||||
$files[] = $file->getPathname();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send email alert about file changes.
|
||||
*
|
||||
* @param array $changes File changes.
|
||||
*/
|
||||
private function send_alert( $changes ) {
|
||||
if ( ! WP_Security_Pack::get_setting( 'email_alerts_enabled', false ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$email = WP_Security_Pack::get_setting( 'email_alerts_address', get_option( 'admin_email' ) );
|
||||
$site_name = get_bloginfo( 'name' );
|
||||
$site_url = home_url();
|
||||
|
||||
$subject = sprintf(
|
||||
/* translators: %s: Site name */
|
||||
__( '[%s] File Integrity Alert - Core Files Changed', 'wp-security-pack' ),
|
||||
$site_name
|
||||
);
|
||||
|
||||
$message = sprintf(
|
||||
/* translators: %s: Site URL */
|
||||
__( "WP Security Pack has detected changes to WordPress core files on %s.\n\n", 'wp-security-pack' ),
|
||||
$site_url
|
||||
);
|
||||
|
||||
if ( ! empty( $changes['modified'] ) ) {
|
||||
$message .= __( "Modified files:\n", 'wp-security-pack' );
|
||||
foreach ( $changes['modified'] as $file ) {
|
||||
$message .= '- ' . ( is_array( $file ) ? $file['file'] : $file ) . "\n";
|
||||
}
|
||||
$message .= "\n";
|
||||
}
|
||||
|
||||
if ( ! empty( $changes['added'] ) ) {
|
||||
$message .= __( "New files detected:\n", 'wp-security-pack' );
|
||||
foreach ( $changes['added'] as $file ) {
|
||||
$message .= '- ' . $file . "\n";
|
||||
}
|
||||
$message .= "\n";
|
||||
}
|
||||
|
||||
if ( ! empty( $changes['removed'] ) ) {
|
||||
$message .= __( "Removed files:\n", 'wp-security-pack' );
|
||||
foreach ( $changes['removed'] as $file ) {
|
||||
$message .= '- ' . $file . "\n";
|
||||
}
|
||||
$message .= "\n";
|
||||
}
|
||||
|
||||
$message .= __( "This could indicate:\n", 'wp-security-pack' );
|
||||
$message .= __( "- A recent WordPress update (normal)\n", 'wp-security-pack' );
|
||||
$message .= __( "- Unauthorized modifications (investigate)\n", 'wp-security-pack' );
|
||||
$message .= __( "- Plugin/theme conflicts (rare)\n\n", 'wp-security-pack' );
|
||||
$message .= __( "Review these changes in your WordPress admin panel.", 'wp-security-pack' );
|
||||
|
||||
wp_mail( $email, $subject, $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get last scan results.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_last_scan_results() {
|
||||
return array(
|
||||
'time' => get_option( self::LAST_SCAN_OPTION, 0 ),
|
||||
'changes' => get_option( self::CHANGES_OPTION, array() ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear file changes.
|
||||
*/
|
||||
public function clear_changes() {
|
||||
delete_option( self::CHANGES_OPTION );
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset baseline.
|
||||
*/
|
||||
public function reset_baseline() {
|
||||
delete_option( self::HASHES_OPTION );
|
||||
delete_option( self::CHANGES_OPTION );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
<?php
|
||||
/**
|
||||
* Geo-blocking for WP Security Pack.
|
||||
*
|
||||
* @package WP_Security_Pack
|
||||
*/
|
||||
|
||||
// Prevent direct access.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Geo-blocking class using IP2Location Lite database.
|
||||
*/
|
||||
class WPSP_Geo_Blocking {
|
||||
|
||||
/**
|
||||
* IP2Location database file path.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $db_path = '';
|
||||
|
||||
/**
|
||||
* IP2Location database object.
|
||||
*
|
||||
* @var object|null
|
||||
*/
|
||||
private $db = null;
|
||||
|
||||
/**
|
||||
* Country lookup cache.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $cache = array();
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->db_path = WP_Security_Pack::get_setting( 'geo_database_path', '' );
|
||||
|
||||
if ( empty( $this->db_path ) ) {
|
||||
// Default path in plugin directory.
|
||||
$this->db_path = WPSP_PLUGIN_DIR . 'data/IP2LOCATION-LITE-DB1.BIN';
|
||||
}
|
||||
|
||||
// Check geo-blocking immediately (constructor runs during init).
|
||||
// This blocks access to the entire website for blocked countries.
|
||||
if ( WP_Security_Pack::get_setting( 'geo_blocking_enabled', false ) ) {
|
||||
$this->check_geo_access();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if geo-blocking should apply.
|
||||
*/
|
||||
public function check_geo_access() {
|
||||
$ip = WPSP_Helper::get_client_ip();
|
||||
|
||||
if ( ! $ip ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if IP is whitelisted.
|
||||
$ip_control = wpsp()->get_component( 'ip_control' );
|
||||
if ( $ip_control && $ip_control->is_whitelisted( $ip ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get country code.
|
||||
$country_code = $this->get_country_code( $ip );
|
||||
|
||||
if ( ! $country_code ) {
|
||||
return; // Can't determine country, allow access.
|
||||
}
|
||||
|
||||
// Check if country is blocked.
|
||||
$blocked_countries = WP_Security_Pack::get_setting( 'geo_blocked_countries', array() );
|
||||
|
||||
if ( ! empty( $blocked_countries ) && in_array( $country_code, $blocked_countries, true ) ) {
|
||||
WPSP_Activity_Log::log(
|
||||
WPSP_Activity_Log::EVENT_GEO_BLOCKED,
|
||||
$ip,
|
||||
null,
|
||||
sprintf(
|
||||
/* translators: %s: Country code */
|
||||
__( 'Blocked country: %s', 'wp-security-pack' ),
|
||||
$country_code
|
||||
)
|
||||
);
|
||||
|
||||
$this->block_access( $country_code );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get country code for an IP address.
|
||||
*
|
||||
* @param string $ip IP address.
|
||||
* @return string|null Two-letter country code or null.
|
||||
*/
|
||||
public function get_country_code( $ip ) {
|
||||
// Check cache first.
|
||||
if ( isset( $this->cache[ $ip ] ) ) {
|
||||
return $this->cache[ $ip ];
|
||||
}
|
||||
|
||||
// Check transient cache.
|
||||
$cache_key = 'wpsp_geo_' . md5( $ip );
|
||||
$cached = get_transient( $cache_key );
|
||||
|
||||
if ( false !== $cached ) {
|
||||
$this->cache[ $ip ] = $cached;
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$country_code = null;
|
||||
|
||||
// Try IP2Location database first.
|
||||
$country_code = $this->lookup_ip2location( $ip );
|
||||
|
||||
// Fallback to PHP geoip extension.
|
||||
if ( ! $country_code && function_exists( 'geoip_country_code_by_name' ) ) {
|
||||
// phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.geoip_country_code_by_nameDeprecated
|
||||
$country_code = @geoip_country_code_by_name( $ip );
|
||||
}
|
||||
|
||||
// Cache the result.
|
||||
if ( $country_code ) {
|
||||
$country_code = strtoupper( $country_code );
|
||||
$this->cache[ $ip ] = $country_code;
|
||||
set_transient( $cache_key, $country_code, HOUR_IN_SECONDS );
|
||||
}
|
||||
|
||||
return $country_code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lookup IP using IP2Location database.
|
||||
*
|
||||
* @param string $ip IP address.
|
||||
* @return string|null
|
||||
*/
|
||||
private function lookup_ip2location( $ip ) {
|
||||
if ( ! file_exists( $this->db_path ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Load the database reader.
|
||||
if ( null === $this->db ) {
|
||||
require_once WPSP_PLUGIN_DIR . 'includes/class-wpsp-ip2location.php';
|
||||
$this->db = new WPSP_IP2Location( $this->db_path );
|
||||
}
|
||||
|
||||
if ( ! $this->db ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$record = $this->db->lookup( $ip );
|
||||
|
||||
if ( $record && ! empty( $record['country_code'] ) && '-' !== $record['country_code'] ) {
|
||||
return $record['country_code'];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Block access for geo-blocked countries.
|
||||
*
|
||||
* @param string $country_code Country code.
|
||||
*/
|
||||
private function block_access( $country_code ) {
|
||||
status_header( 403 );
|
||||
nocache_headers();
|
||||
|
||||
$countries = WPSP_Helper::get_countries();
|
||||
$country_name = isset( $countries[ $country_code ] ) ? $countries[ $country_code ] : $country_code;
|
||||
|
||||
$message = sprintf(
|
||||
/* translators: %s: Country name */
|
||||
__( 'Access from %s is not permitted.', 'wp-security-pack' ),
|
||||
$country_name
|
||||
);
|
||||
|
||||
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
|
||||
wp_send_json_error( array( 'message' => $message ), 403 );
|
||||
}
|
||||
|
||||
wp_die(
|
||||
esc_html( $message ),
|
||||
esc_html__( 'Access Denied', 'wp-security-pack' ),
|
||||
array(
|
||||
'response' => 403,
|
||||
'back_link' => false,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if geo-database exists.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function database_exists() {
|
||||
return file_exists( $this->db_path );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get database info.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_database_info() {
|
||||
$info = array(
|
||||
'exists' => false,
|
||||
'path' => $this->db_path,
|
||||
'size' => 0,
|
||||
'modified' => null,
|
||||
'type' => '',
|
||||
);
|
||||
|
||||
if ( file_exists( $this->db_path ) ) {
|
||||
$info['exists'] = true;
|
||||
$info['size'] = filesize( $this->db_path );
|
||||
$info['modified'] = filemtime( $this->db_path );
|
||||
|
||||
// Try to get database type.
|
||||
if ( null === $this->db ) {
|
||||
require_once WPSP_PLUGIN_DIR . 'includes/class-wpsp-ip2location.php';
|
||||
$this->db = new WPSP_IP2Location( $this->db_path );
|
||||
}
|
||||
|
||||
if ( $this->db ) {
|
||||
$info['type'] = $this->db->get_database_type();
|
||||
}
|
||||
}
|
||||
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Download IP2Location Lite database.
|
||||
*
|
||||
* @param string $download_token IP2Location download token (optional for LITE).
|
||||
* @return bool|WP_Error
|
||||
*/
|
||||
public function download_database( $download_token = '' ) {
|
||||
// IP2Location LITE DB1 (Country only) - free, no token required.
|
||||
$download_url = 'https://download.ip2location.com/lite/IP2LOCATION-LITE-DB1.BIN.ZIP';
|
||||
|
||||
// If token provided, use the authenticated endpoint.
|
||||
if ( ! empty( $download_token ) ) {
|
||||
$download_url = 'https://www.ip2location.com/download/?token=' . urlencode( $download_token ) . '&file=DB1LITEBIN';
|
||||
}
|
||||
|
||||
// Create data directory.
|
||||
$data_dir = WPSP_PLUGIN_DIR . 'data';
|
||||
if ( ! file_exists( $data_dir ) ) {
|
||||
wp_mkdir_p( $data_dir );
|
||||
}
|
||||
|
||||
// Download the file.
|
||||
$tmp_file = download_url( $download_url, 300 );
|
||||
|
||||
if ( is_wp_error( $tmp_file ) ) {
|
||||
return $tmp_file;
|
||||
}
|
||||
|
||||
// Check if it's a ZIP file.
|
||||
$finfo = finfo_open( FILEINFO_MIME_TYPE );
|
||||
$mime = finfo_file( $finfo, $tmp_file );
|
||||
finfo_close( $finfo );
|
||||
|
||||
$target_path = $data_dir . '/IP2LOCATION-LITE-DB1.BIN';
|
||||
|
||||
if ( 'application/zip' === $mime || 'application/x-zip-compressed' === $mime ) {
|
||||
// Extract ZIP.
|
||||
$zip = new ZipArchive();
|
||||
if ( true === $zip->open( $tmp_file ) ) {
|
||||
// Find the BIN file.
|
||||
for ( $i = 0; $i < $zip->numFiles; $i++ ) {
|
||||
$filename = $zip->getNameIndex( $i );
|
||||
if ( preg_match( '/\.BIN$/i', $filename ) ) {
|
||||
$content = $zip->getFromIndex( $i );
|
||||
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
|
||||
file_put_contents( $target_path, $content );
|
||||
break;
|
||||
}
|
||||
}
|
||||
$zip->close();
|
||||
}
|
||||
// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink
|
||||
unlink( $tmp_file );
|
||||
} else {
|
||||
// Direct BIN file.
|
||||
// phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename
|
||||
rename( $tmp_file, $target_path );
|
||||
}
|
||||
|
||||
if ( file_exists( $target_path ) ) {
|
||||
// Update database path setting.
|
||||
WP_Security_Pack::update_setting( 'geo_database_path', $target_path );
|
||||
return true;
|
||||
}
|
||||
|
||||
return new WP_Error( 'download_failed', __( 'Failed to download or extract database.', 'wp-security-pack' ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
<?php
|
||||
/**
|
||||
* Security hardening for WP Security Pack.
|
||||
*
|
||||
* @package WP_Security_Pack
|
||||
*/
|
||||
|
||||
// Prevent direct access.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hardening class for security enhancements.
|
||||
*/
|
||||
class WPSP_Hardening {
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
// Disable XML-RPC.
|
||||
if ( WP_Security_Pack::get_setting( 'disable_xmlrpc', true ) ) {
|
||||
add_filter( 'xmlrpc_enabled', '__return_false' );
|
||||
add_filter( 'wp_headers', array( $this, 'remove_xmlrpc_headers' ) );
|
||||
add_action( 'wp', array( $this, 'block_xmlrpc_requests' ), 1 );
|
||||
}
|
||||
|
||||
// Disable file editing.
|
||||
if ( WP_Security_Pack::get_setting( 'disable_file_editing', true ) ) {
|
||||
$this->disable_file_editing();
|
||||
}
|
||||
|
||||
// Remove WordPress version.
|
||||
if ( WP_Security_Pack::get_setting( 'remove_wp_version', true ) ) {
|
||||
add_filter( 'the_generator', '__return_empty_string' );
|
||||
remove_action( 'wp_head', 'wp_generator' );
|
||||
add_filter( 'style_loader_src', array( $this, 'remove_version_strings' ), 10, 2 );
|
||||
add_filter( 'script_loader_src', array( $this, 'remove_version_strings' ), 10, 2 );
|
||||
}
|
||||
|
||||
// Add security headers.
|
||||
if ( WP_Security_Pack::get_setting( 'add_security_headers', true ) ) {
|
||||
add_action( 'send_headers', array( $this, 'add_security_headers' ) );
|
||||
}
|
||||
|
||||
// Restrict REST API.
|
||||
if ( WP_Security_Pack::get_setting( 'restrict_rest_api', true ) ) {
|
||||
add_filter( 'rest_authentication_errors', array( $this, 'restrict_rest_api' ) );
|
||||
}
|
||||
|
||||
// Disable application passwords for non-admins.
|
||||
if ( WP_Security_Pack::get_setting( 'disable_application_passwords', false ) ) {
|
||||
add_filter( 'wp_is_application_passwords_available', '__return_false' );
|
||||
}
|
||||
|
||||
// Remove unnecessary headers.
|
||||
add_action( 'init', array( $this, 'remove_unnecessary_headers' ) );
|
||||
|
||||
// Disable user enumeration.
|
||||
if ( WP_Security_Pack::get_setting( 'disable_user_enumeration', true ) ) {
|
||||
add_action( 'init', array( $this, 'block_author_scanning' ) );
|
||||
add_filter( 'rest_endpoints', array( $this, 'restrict_users_endpoint' ) );
|
||||
add_filter( 'oembed_response_data', array( $this, 'remove_author_from_oembed' ) );
|
||||
}
|
||||
|
||||
// Disable pingbacks/trackbacks.
|
||||
if ( WP_Security_Pack::get_setting( 'disable_pingbacks', true ) ) {
|
||||
add_filter( 'xmlrpc_methods', array( $this, 'disable_pingback_methods' ) );
|
||||
add_filter( 'wp_headers', array( $this, 'remove_pingback_header' ) );
|
||||
add_filter( 'pings_open', '__return_false', 20, 2 );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove XML-RPC related headers.
|
||||
*
|
||||
* @param array $headers HTTP headers.
|
||||
* @return array
|
||||
*/
|
||||
public function remove_xmlrpc_headers( $headers ) {
|
||||
unset( $headers['X-Pingback'] );
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Block direct XML-RPC requests.
|
||||
*/
|
||||
public function block_xmlrpc_requests() {
|
||||
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
|
||||
$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '';
|
||||
|
||||
if ( strpos( $request_uri, 'xmlrpc.php' ) !== false ) {
|
||||
status_header( 403 );
|
||||
exit( 'XML-RPC is disabled.' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable file editing in dashboard.
|
||||
*/
|
||||
private function disable_file_editing() {
|
||||
if ( ! defined( 'DISALLOW_FILE_EDIT' ) ) {
|
||||
define( 'DISALLOW_FILE_EDIT', true );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove version strings from scripts and styles.
|
||||
*
|
||||
* @param string $src Source URL.
|
||||
* @param string $handle Handle name.
|
||||
* @return string
|
||||
*/
|
||||
public function remove_version_strings( $src, $handle ) {
|
||||
if ( strpos( $src, 'ver=' ) !== false ) {
|
||||
$src = remove_query_arg( 'ver', $src );
|
||||
}
|
||||
return $src;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add security headers.
|
||||
*/
|
||||
public function add_security_headers() {
|
||||
// Don't add headers for admin pages if user is logged in.
|
||||
if ( is_admin() && is_user_logged_in() ) {
|
||||
// Still add some basic headers.
|
||||
header( 'X-Content-Type-Options: nosniff' );
|
||||
return;
|
||||
}
|
||||
|
||||
// Get header settings.
|
||||
$headers = WP_Security_Pack::get_setting( 'security_headers', $this->get_default_headers() );
|
||||
|
||||
// X-Content-Type-Options.
|
||||
if ( ! empty( $headers['x_content_type_options'] ) ) {
|
||||
header( 'X-Content-Type-Options: ' . $headers['x_content_type_options'] );
|
||||
}
|
||||
|
||||
// X-Frame-Options.
|
||||
if ( ! empty( $headers['x_frame_options'] ) ) {
|
||||
header( 'X-Frame-Options: ' . $headers['x_frame_options'] );
|
||||
}
|
||||
|
||||
// X-XSS-Protection.
|
||||
if ( ! empty( $headers['x_xss_protection'] ) ) {
|
||||
header( 'X-XSS-Protection: ' . $headers['x_xss_protection'] );
|
||||
}
|
||||
|
||||
// Referrer-Policy.
|
||||
if ( ! empty( $headers['referrer_policy'] ) ) {
|
||||
header( 'Referrer-Policy: ' . $headers['referrer_policy'] );
|
||||
}
|
||||
|
||||
// Permissions-Policy.
|
||||
if ( ! empty( $headers['permissions_policy'] ) ) {
|
||||
header( 'Permissions-Policy: ' . $headers['permissions_policy'] );
|
||||
}
|
||||
|
||||
// Content-Security-Policy.
|
||||
if ( ! empty( $headers['content_security_policy'] ) ) {
|
||||
header( 'Content-Security-Policy: ' . $headers['content_security_policy'] );
|
||||
}
|
||||
|
||||
// Strict-Transport-Security (HSTS).
|
||||
if ( ! empty( $headers['strict_transport_security'] ) && is_ssl() ) {
|
||||
header( 'Strict-Transport-Security: ' . $headers['strict_transport_security'] );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default security headers.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_default_headers() {
|
||||
return array(
|
||||
'x_content_type_options' => 'nosniff',
|
||||
'x_frame_options' => 'SAMEORIGIN',
|
||||
'x_xss_protection' => '1; mode=block',
|
||||
'referrer_policy' => 'strict-origin-when-cross-origin',
|
||||
'permissions_policy' => 'geolocation=(), microphone=(), camera=()',
|
||||
'content_security_policy' => '',
|
||||
'strict_transport_security' => 'max-age=31536000; includeSubDomains',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restrict REST API to authenticated users.
|
||||
*
|
||||
* @param WP_Error|null|bool $result Authentication result.
|
||||
* @return WP_Error|null|bool
|
||||
*/
|
||||
public function restrict_rest_api( $result ) {
|
||||
// If there's already an error, return it.
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Allow if user is logged in.
|
||||
if ( is_user_logged_in() ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Get allowed REST routes.
|
||||
$allowed_routes = WP_Security_Pack::get_setting( 'rest_api_allowed_routes', array() );
|
||||
|
||||
// Always allow some essential routes.
|
||||
$essential_routes = array(
|
||||
'/wp/v2/oembed',
|
||||
'/wp-site-health',
|
||||
);
|
||||
|
||||
$allowed_routes = array_merge( $allowed_routes, $essential_routes );
|
||||
|
||||
// Get current route.
|
||||
$current_route = $GLOBALS['wp']->query_vars['rest_route'] ?? '';
|
||||
|
||||
// Check if current route is allowed.
|
||||
foreach ( $allowed_routes as $route ) {
|
||||
if ( strpos( $current_route, $route ) === 0 ) {
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
// Block unauthenticated access.
|
||||
return new WP_Error(
|
||||
'rest_not_logged_in',
|
||||
__( 'You must be authenticated to access this endpoint.', 'wp-security-pack' ),
|
||||
array( 'status' => 401 )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove unnecessary headers.
|
||||
*/
|
||||
public function remove_unnecessary_headers() {
|
||||
// Remove Really Simple Discovery link.
|
||||
remove_action( 'wp_head', 'rsd_link' );
|
||||
|
||||
// Remove Windows Live Writer manifest link.
|
||||
remove_action( 'wp_head', 'wlwmanifest_link' );
|
||||
|
||||
// Remove shortlink.
|
||||
remove_action( 'wp_head', 'wp_shortlink_wp_head' );
|
||||
|
||||
// Remove feed links.
|
||||
if ( WP_Security_Pack::get_setting( 'remove_feed_links', false ) ) {
|
||||
remove_action( 'wp_head', 'feed_links', 2 );
|
||||
remove_action( 'wp_head', 'feed_links_extra', 3 );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Block author scanning via ?author=N URLs.
|
||||
*/
|
||||
public function block_author_scanning() {
|
||||
if ( is_admin() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Block ?author=N requests for non-logged-in users.
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
if ( ! is_user_logged_in() && isset( $_GET['author'] ) ) {
|
||||
wp_safe_redirect( home_url(), 301 );
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restrict REST API users endpoint to authenticated users.
|
||||
*
|
||||
* @param array $endpoints REST API endpoints.
|
||||
* @return array
|
||||
*/
|
||||
public function restrict_users_endpoint( $endpoints ) {
|
||||
if ( is_user_logged_in() ) {
|
||||
return $endpoints;
|
||||
}
|
||||
|
||||
// Remove users endpoint for unauthenticated requests.
|
||||
if ( isset( $endpoints['/wp/v2/users'] ) ) {
|
||||
unset( $endpoints['/wp/v2/users'] );
|
||||
}
|
||||
if ( isset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] ) ) {
|
||||
unset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] );
|
||||
}
|
||||
|
||||
return $endpoints;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove author information from oEmbed responses.
|
||||
*
|
||||
* @param array $data oEmbed response data.
|
||||
* @return array
|
||||
*/
|
||||
public function remove_author_from_oembed( $data ) {
|
||||
if ( isset( $data['author_name'] ) ) {
|
||||
unset( $data['author_name'] );
|
||||
}
|
||||
if ( isset( $data['author_url'] ) ) {
|
||||
unset( $data['author_url'] );
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable pingback XML-RPC methods.
|
||||
*
|
||||
* @param array $methods XML-RPC methods.
|
||||
* @return array
|
||||
*/
|
||||
public function disable_pingback_methods( $methods ) {
|
||||
unset( $methods['pingback.ping'] );
|
||||
unset( $methods['pingback.extensions.getPingbacks'] );
|
||||
return $methods;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove X-Pingback header.
|
||||
*
|
||||
* @param array $headers HTTP headers.
|
||||
* @return array
|
||||
*/
|
||||
public function remove_pingback_header( $headers ) {
|
||||
unset( $headers['X-Pingback'] );
|
||||
return $headers;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
<?php
|
||||
/**
|
||||
* Helper functions for WP Security Pack.
|
||||
*
|
||||
* @package WP_Security_Pack
|
||||
*/
|
||||
|
||||
// Prevent direct access.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper class with utility functions.
|
||||
*/
|
||||
class WPSP_Helper {
|
||||
|
||||
/**
|
||||
* Get the real client IP address.
|
||||
*
|
||||
* Handles proxies and CDNs like Cloudflare.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public static function get_client_ip() {
|
||||
$ip = null;
|
||||
|
||||
// Priority order for IP detection.
|
||||
$headers = array(
|
||||
'HTTP_CF_CONNECTING_IP', // Cloudflare.
|
||||
'HTTP_X_REAL_IP', // Nginx reverse proxy.
|
||||
'HTTP_X_FORWARDED_FOR', // Generic proxy.
|
||||
'REMOTE_ADDR', // Direct connection.
|
||||
);
|
||||
|
||||
foreach ( $headers as $header ) {
|
||||
if ( ! empty( $_SERVER[ $header ] ) ) {
|
||||
// X-Forwarded-For can contain multiple IPs, get the first one.
|
||||
$ip = sanitize_text_field( wp_unslash( $_SERVER[ $header ] ) );
|
||||
if ( 'HTTP_X_FORWARDED_FOR' === $header && strpos( $ip, ',' ) !== false ) {
|
||||
$ips = explode( ',', $ip );
|
||||
$ip = trim( $ips[0] );
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Validate IP.
|
||||
if ( $ip && filter_var( $ip, FILTER_VALIDATE_IP ) ) {
|
||||
return $ip;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an IP is in a CIDR range.
|
||||
*
|
||||
* @param string $ip IP address to check.
|
||||
* @param string $cidr CIDR notation (e.g., 192.168.1.0/24).
|
||||
* @return bool
|
||||
*/
|
||||
public static function ip_in_cidr( $ip, $cidr ) {
|
||||
// Handle exact IP match (no CIDR notation).
|
||||
if ( strpos( $cidr, '/' ) === false ) {
|
||||
return $ip === $cidr;
|
||||
}
|
||||
|
||||
list( $network, $mask ) = explode( '/', $cidr );
|
||||
|
||||
// Detect IP version.
|
||||
$ip_is_v6 = filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 );
|
||||
$network_is_v6 = filter_var( $network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 );
|
||||
|
||||
// Both must be same version.
|
||||
if ( $ip_is_v6 !== $network_is_v6 ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( $ip_is_v6 ) {
|
||||
return self::ipv6_in_cidr( $ip, $network, (int) $mask );
|
||||
}
|
||||
|
||||
return self::ipv4_in_cidr( $ip, $network, (int) $mask );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if IPv4 is in CIDR range.
|
||||
*
|
||||
* @param string $ip IPv4 address.
|
||||
* @param string $network Network address.
|
||||
* @param int $mask CIDR mask.
|
||||
* @return bool
|
||||
*/
|
||||
private static function ipv4_in_cidr( $ip, $network, $mask ) {
|
||||
$ip_long = ip2long( $ip );
|
||||
$network_long = ip2long( $network );
|
||||
|
||||
if ( false === $ip_long || false === $network_long ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Calculate network mask.
|
||||
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
|
||||
$network_mask = ~( ( 1 << ( 32 - $mask ) ) - 1 );
|
||||
|
||||
return ( $ip_long & $network_mask ) === ( $network_long & $network_mask );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if IPv6 is in CIDR range.
|
||||
*
|
||||
* @param string $ip IPv6 address.
|
||||
* @param string $network Network address.
|
||||
* @param int $mask CIDR mask.
|
||||
* @return bool
|
||||
*/
|
||||
private static function ipv6_in_cidr( $ip, $network, $mask ) {
|
||||
$ip_bin = inet_pton( $ip );
|
||||
$network_bin = inet_pton( $network );
|
||||
|
||||
if ( false === $ip_bin || false === $network_bin ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Compare full bytes.
|
||||
$full_bytes = (int) floor( $mask / 8 );
|
||||
for ( $i = 0; $i < $full_bytes; $i++ ) {
|
||||
if ( $ip_bin[ $i ] !== $network_bin[ $i ] ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Compare remaining bits.
|
||||
$remaining_bits = $mask % 8;
|
||||
if ( $remaining_bits > 0 && $full_bytes < 16 ) {
|
||||
$bit_mask = ( ( 1 << $remaining_bits ) - 1 ) << ( 8 - $remaining_bits );
|
||||
if ( ( ord( $ip_bin[ $full_bytes ] ) & $bit_mask ) !== ( ord( $network_bin[ $full_bytes ] ) & $bit_mask ) ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an IP matches any rule in a list.
|
||||
*
|
||||
* @param string $ip IP address to check.
|
||||
* @param array $rules Array of IP addresses or CIDR ranges.
|
||||
* @return bool
|
||||
*/
|
||||
public static function ip_matches_rules( $ip, $rules ) {
|
||||
if ( empty( $rules ) || ! is_array( $rules ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ( $rules as $rule ) {
|
||||
$rule = trim( $rule );
|
||||
if ( empty( $rule ) || strpos( $rule, '#' ) === 0 ) {
|
||||
continue; // Skip empty lines and comments.
|
||||
}
|
||||
|
||||
if ( self::ip_in_cidr( $ip, $rule ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse IP list from textarea.
|
||||
*
|
||||
* @param string $text Textarea content with IPs/CIDRs.
|
||||
* @return array
|
||||
*/
|
||||
public static function parse_ip_list( $text ) {
|
||||
if ( empty( $text ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$lines = explode( "\n", $text );
|
||||
$ips = array();
|
||||
|
||||
foreach ( $lines as $line ) {
|
||||
$line = trim( $line );
|
||||
|
||||
// Skip empty lines and comments.
|
||||
if ( empty( $line ) || strpos( $line, '#' ) === 0 ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Remove inline comments.
|
||||
if ( strpos( $line, '#' ) !== false ) {
|
||||
$line = trim( substr( $line, 0, strpos( $line, '#' ) ) );
|
||||
}
|
||||
|
||||
// Validate IP or CIDR.
|
||||
if ( self::is_valid_ip_or_cidr( $line ) ) {
|
||||
$ips[] = $line;
|
||||
}
|
||||
}
|
||||
|
||||
return $ips;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a string is a valid IP or CIDR.
|
||||
*
|
||||
* @param string $value Value to check.
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_valid_ip_or_cidr( $value ) {
|
||||
// Plain IP.
|
||||
if ( filter_var( $value, FILTER_VALIDATE_IP ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// CIDR notation.
|
||||
if ( strpos( $value, '/' ) !== false ) {
|
||||
list( $ip, $mask ) = explode( '/', $value );
|
||||
|
||||
if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$mask = (int) $mask;
|
||||
$is_ipv6 = filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 );
|
||||
$max_mask = $is_ipv6 ? 128 : 32;
|
||||
|
||||
return $mask >= 0 && $mask <= $max_mask;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get country list for geo-blocking UI.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_countries() {
|
||||
return array(
|
||||
'AF' => __( 'Afghanistan', 'wp-security-pack' ),
|
||||
'AL' => __( 'Albania', 'wp-security-pack' ),
|
||||
'DZ' => __( 'Algeria', 'wp-security-pack' ),
|
||||
'AS' => __( 'American Samoa', 'wp-security-pack' ),
|
||||
'AD' => __( 'Andorra', 'wp-security-pack' ),
|
||||
'AO' => __( 'Angola', 'wp-security-pack' ),
|
||||
'AI' => __( 'Anguilla', 'wp-security-pack' ),
|
||||
'AQ' => __( 'Antarctica', 'wp-security-pack' ),
|
||||
'AG' => __( 'Antigua and Barbuda', 'wp-security-pack' ),
|
||||
'AR' => __( 'Argentina', 'wp-security-pack' ),
|
||||
'AM' => __( 'Armenia', 'wp-security-pack' ),
|
||||
'AW' => __( 'Aruba', 'wp-security-pack' ),
|
||||
'AU' => __( 'Australia', 'wp-security-pack' ),
|
||||
'AT' => __( 'Austria', 'wp-security-pack' ),
|
||||
'AZ' => __( 'Azerbaijan', 'wp-security-pack' ),
|
||||
'BS' => __( 'Bahamas', 'wp-security-pack' ),
|
||||
'BH' => __( 'Bahrain', 'wp-security-pack' ),
|
||||
'BD' => __( 'Bangladesh', 'wp-security-pack' ),
|
||||
'BB' => __( 'Barbados', 'wp-security-pack' ),
|
||||
'BY' => __( 'Belarus', 'wp-security-pack' ),
|
||||
'BE' => __( 'Belgium', 'wp-security-pack' ),
|
||||
'BZ' => __( 'Belize', 'wp-security-pack' ),
|
||||
'BJ' => __( 'Benin', 'wp-security-pack' ),
|
||||
'BM' => __( 'Bermuda', 'wp-security-pack' ),
|
||||
'BT' => __( 'Bhutan', 'wp-security-pack' ),
|
||||
'BO' => __( 'Bolivia', 'wp-security-pack' ),
|
||||
'BA' => __( 'Bosnia and Herzegovina', 'wp-security-pack' ),
|
||||
'BW' => __( 'Botswana', 'wp-security-pack' ),
|
||||
'BR' => __( 'Brazil', 'wp-security-pack' ),
|
||||
'BN' => __( 'Brunei', 'wp-security-pack' ),
|
||||
'BG' => __( 'Bulgaria', 'wp-security-pack' ),
|
||||
'BF' => __( 'Burkina Faso', 'wp-security-pack' ),
|
||||
'BI' => __( 'Burundi', 'wp-security-pack' ),
|
||||
'KH' => __( 'Cambodia', 'wp-security-pack' ),
|
||||
'CM' => __( 'Cameroon', 'wp-security-pack' ),
|
||||
'CA' => __( 'Canada', 'wp-security-pack' ),
|
||||
'CV' => __( 'Cape Verde', 'wp-security-pack' ),
|
||||
'KY' => __( 'Cayman Islands', 'wp-security-pack' ),
|
||||
'CF' => __( 'Central African Republic', 'wp-security-pack' ),
|
||||
'TD' => __( 'Chad', 'wp-security-pack' ),
|
||||
'CL' => __( 'Chile', 'wp-security-pack' ),
|
||||
'CN' => __( 'China', 'wp-security-pack' ),
|
||||
'CO' => __( 'Colombia', 'wp-security-pack' ),
|
||||
'KM' => __( 'Comoros', 'wp-security-pack' ),
|
||||
'CG' => __( 'Congo', 'wp-security-pack' ),
|
||||
'CD' => __( 'Congo (DRC)', 'wp-security-pack' ),
|
||||
'CR' => __( 'Costa Rica', 'wp-security-pack' ),
|
||||
'CI' => __( 'Ivory Coast', 'wp-security-pack' ),
|
||||
'HR' => __( 'Croatia', 'wp-security-pack' ),
|
||||
'CU' => __( 'Cuba', 'wp-security-pack' ),
|
||||
'CY' => __( 'Cyprus', 'wp-security-pack' ),
|
||||
'CZ' => __( 'Czech Republic', 'wp-security-pack' ),
|
||||
'DK' => __( 'Denmark', 'wp-security-pack' ),
|
||||
'DJ' => __( 'Djibouti', 'wp-security-pack' ),
|
||||
'DM' => __( 'Dominica', 'wp-security-pack' ),
|
||||
'DO' => __( 'Dominican Republic', 'wp-security-pack' ),
|
||||
'EC' => __( 'Ecuador', 'wp-security-pack' ),
|
||||
'EG' => __( 'Egypt', 'wp-security-pack' ),
|
||||
'SV' => __( 'El Salvador', 'wp-security-pack' ),
|
||||
'GQ' => __( 'Equatorial Guinea', 'wp-security-pack' ),
|
||||
'ER' => __( 'Eritrea', 'wp-security-pack' ),
|
||||
'EE' => __( 'Estonia', 'wp-security-pack' ),
|
||||
'ET' => __( 'Ethiopia', 'wp-security-pack' ),
|
||||
'FJ' => __( 'Fiji', 'wp-security-pack' ),
|
||||
'FI' => __( 'Finland', 'wp-security-pack' ),
|
||||
'FR' => __( 'France', 'wp-security-pack' ),
|
||||
'GA' => __( 'Gabon', 'wp-security-pack' ),
|
||||
'GM' => __( 'Gambia', 'wp-security-pack' ),
|
||||
'GE' => __( 'Georgia', 'wp-security-pack' ),
|
||||
'DE' => __( 'Germany', 'wp-security-pack' ),
|
||||
'GH' => __( 'Ghana', 'wp-security-pack' ),
|
||||
'GR' => __( 'Greece', 'wp-security-pack' ),
|
||||
'GL' => __( 'Greenland', 'wp-security-pack' ),
|
||||
'GD' => __( 'Grenada', 'wp-security-pack' ),
|
||||
'GU' => __( 'Guam', 'wp-security-pack' ),
|
||||
'GT' => __( 'Guatemala', 'wp-security-pack' ),
|
||||
'GN' => __( 'Guinea', 'wp-security-pack' ),
|
||||
'GW' => __( 'Guinea-Bissau', 'wp-security-pack' ),
|
||||
'GY' => __( 'Guyana', 'wp-security-pack' ),
|
||||
'HT' => __( 'Haiti', 'wp-security-pack' ),
|
||||
'HN' => __( 'Honduras', 'wp-security-pack' ),
|
||||
'HK' => __( 'Hong Kong', 'wp-security-pack' ),
|
||||
'HU' => __( 'Hungary', 'wp-security-pack' ),
|
||||
'IS' => __( 'Iceland', 'wp-security-pack' ),
|
||||
'IN' => __( 'India', 'wp-security-pack' ),
|
||||
'ID' => __( 'Indonesia', 'wp-security-pack' ),
|
||||
'IR' => __( 'Iran', 'wp-security-pack' ),
|
||||
'IQ' => __( 'Iraq', 'wp-security-pack' ),
|
||||
'IE' => __( 'Ireland', 'wp-security-pack' ),
|
||||
'IL' => __( 'Israel', 'wp-security-pack' ),
|
||||
'IT' => __( 'Italy', 'wp-security-pack' ),
|
||||
'JM' => __( 'Jamaica', 'wp-security-pack' ),
|
||||
'JP' => __( 'Japan', 'wp-security-pack' ),
|
||||
'JO' => __( 'Jordan', 'wp-security-pack' ),
|
||||
'KZ' => __( 'Kazakhstan', 'wp-security-pack' ),
|
||||
'KE' => __( 'Kenya', 'wp-security-pack' ),
|
||||
'KI' => __( 'Kiribati', 'wp-security-pack' ),
|
||||
'KP' => __( 'North Korea', 'wp-security-pack' ),
|
||||
'KR' => __( 'South Korea', 'wp-security-pack' ),
|
||||
'KW' => __( 'Kuwait', 'wp-security-pack' ),
|
||||
'KG' => __( 'Kyrgyzstan', 'wp-security-pack' ),
|
||||
'LA' => __( 'Laos', 'wp-security-pack' ),
|
||||
'LV' => __( 'Latvia', 'wp-security-pack' ),
|
||||
'LB' => __( 'Lebanon', 'wp-security-pack' ),
|
||||
'LS' => __( 'Lesotho', 'wp-security-pack' ),
|
||||
'LR' => __( 'Liberia', 'wp-security-pack' ),
|
||||
'LY' => __( 'Libya', 'wp-security-pack' ),
|
||||
'LI' => __( 'Liechtenstein', 'wp-security-pack' ),
|
||||
'LT' => __( 'Lithuania', 'wp-security-pack' ),
|
||||
'LU' => __( 'Luxembourg', 'wp-security-pack' ),
|
||||
'MO' => __( 'Macao', 'wp-security-pack' ),
|
||||
'MK' => __( 'North Macedonia', 'wp-security-pack' ),
|
||||
'MG' => __( 'Madagascar', 'wp-security-pack' ),
|
||||
'MW' => __( 'Malawi', 'wp-security-pack' ),
|
||||
'MY' => __( 'Malaysia', 'wp-security-pack' ),
|
||||
'MV' => __( 'Maldives', 'wp-security-pack' ),
|
||||
'ML' => __( 'Mali', 'wp-security-pack' ),
|
||||
'MT' => __( 'Malta', 'wp-security-pack' ),
|
||||
'MH' => __( 'Marshall Islands', 'wp-security-pack' ),
|
||||
'MR' => __( 'Mauritania', 'wp-security-pack' ),
|
||||
'MU' => __( 'Mauritius', 'wp-security-pack' ),
|
||||
'MX' => __( 'Mexico', 'wp-security-pack' ),
|
||||
'FM' => __( 'Micronesia', 'wp-security-pack' ),
|
||||
'MD' => __( 'Moldova', 'wp-security-pack' ),
|
||||
'MC' => __( 'Monaco', 'wp-security-pack' ),
|
||||
'MN' => __( 'Mongolia', 'wp-security-pack' ),
|
||||
'ME' => __( 'Montenegro', 'wp-security-pack' ),
|
||||
'MA' => __( 'Morocco', 'wp-security-pack' ),
|
||||
'MZ' => __( 'Mozambique', 'wp-security-pack' ),
|
||||
'MM' => __( 'Myanmar', 'wp-security-pack' ),
|
||||
'NA' => __( 'Namibia', 'wp-security-pack' ),
|
||||
'NR' => __( 'Nauru', 'wp-security-pack' ),
|
||||
'NP' => __( 'Nepal', 'wp-security-pack' ),
|
||||
'NL' => __( 'Netherlands', 'wp-security-pack' ),
|
||||
'NZ' => __( 'New Zealand', 'wp-security-pack' ),
|
||||
'NI' => __( 'Nicaragua', 'wp-security-pack' ),
|
||||
'NE' => __( 'Niger', 'wp-security-pack' ),
|
||||
'NG' => __( 'Nigeria', 'wp-security-pack' ),
|
||||
'NO' => __( 'Norway', 'wp-security-pack' ),
|
||||
'OM' => __( 'Oman', 'wp-security-pack' ),
|
||||
'PK' => __( 'Pakistan', 'wp-security-pack' ),
|
||||
'PW' => __( 'Palau', 'wp-security-pack' ),
|
||||
'PS' => __( 'Palestine', 'wp-security-pack' ),
|
||||
'PA' => __( 'Panama', 'wp-security-pack' ),
|
||||
'PG' => __( 'Papua New Guinea', 'wp-security-pack' ),
|
||||
'PY' => __( 'Paraguay', 'wp-security-pack' ),
|
||||
'PE' => __( 'Peru', 'wp-security-pack' ),
|
||||
'PH' => __( 'Philippines', 'wp-security-pack' ),
|
||||
'PL' => __( 'Poland', 'wp-security-pack' ),
|
||||
'PT' => __( 'Portugal', 'wp-security-pack' ),
|
||||
'PR' => __( 'Puerto Rico', 'wp-security-pack' ),
|
||||
'QA' => __( 'Qatar', 'wp-security-pack' ),
|
||||
'RO' => __( 'Romania', 'wp-security-pack' ),
|
||||
'RU' => __( 'Russia', 'wp-security-pack' ),
|
||||
'RW' => __( 'Rwanda', 'wp-security-pack' ),
|
||||
'SA' => __( 'Saudi Arabia', 'wp-security-pack' ),
|
||||
'SN' => __( 'Senegal', 'wp-security-pack' ),
|
||||
'RS' => __( 'Serbia', 'wp-security-pack' ),
|
||||
'SC' => __( 'Seychelles', 'wp-security-pack' ),
|
||||
'SL' => __( 'Sierra Leone', 'wp-security-pack' ),
|
||||
'SG' => __( 'Singapore', 'wp-security-pack' ),
|
||||
'SK' => __( 'Slovakia', 'wp-security-pack' ),
|
||||
'SI' => __( 'Slovenia', 'wp-security-pack' ),
|
||||
'SB' => __( 'Solomon Islands', 'wp-security-pack' ),
|
||||
'SO' => __( 'Somalia', 'wp-security-pack' ),
|
||||
'ZA' => __( 'South Africa', 'wp-security-pack' ),
|
||||
'SS' => __( 'South Sudan', 'wp-security-pack' ),
|
||||
'ES' => __( 'Spain', 'wp-security-pack' ),
|
||||
'LK' => __( 'Sri Lanka', 'wp-security-pack' ),
|
||||
'SD' => __( 'Sudan', 'wp-security-pack' ),
|
||||
'SR' => __( 'Suriname', 'wp-security-pack' ),
|
||||
'SZ' => __( 'Eswatini', 'wp-security-pack' ),
|
||||
'SE' => __( 'Sweden', 'wp-security-pack' ),
|
||||
'CH' => __( 'Switzerland', 'wp-security-pack' ),
|
||||
'SY' => __( 'Syria', 'wp-security-pack' ),
|
||||
'TW' => __( 'Taiwan', 'wp-security-pack' ),
|
||||
'TJ' => __( 'Tajikistan', 'wp-security-pack' ),
|
||||
'TZ' => __( 'Tanzania', 'wp-security-pack' ),
|
||||
'TH' => __( 'Thailand', 'wp-security-pack' ),
|
||||
'TL' => __( 'Timor-Leste', 'wp-security-pack' ),
|
||||
'TG' => __( 'Togo', 'wp-security-pack' ),
|
||||
'TO' => __( 'Tonga', 'wp-security-pack' ),
|
||||
'TT' => __( 'Trinidad and Tobago', 'wp-security-pack' ),
|
||||
'TN' => __( 'Tunisia', 'wp-security-pack' ),
|
||||
'TR' => __( 'Turkey', 'wp-security-pack' ),
|
||||
'TM' => __( 'Turkmenistan', 'wp-security-pack' ),
|
||||
'TV' => __( 'Tuvalu', 'wp-security-pack' ),
|
||||
'UG' => __( 'Uganda', 'wp-security-pack' ),
|
||||
'UA' => __( 'Ukraine', 'wp-security-pack' ),
|
||||
'AE' => __( 'United Arab Emirates', 'wp-security-pack' ),
|
||||
'GB' => __( 'United Kingdom', 'wp-security-pack' ),
|
||||
'US' => __( 'United States', 'wp-security-pack' ),
|
||||
'UY' => __( 'Uruguay', 'wp-security-pack' ),
|
||||
'UZ' => __( 'Uzbekistan', 'wp-security-pack' ),
|
||||
'VU' => __( 'Vanuatu', 'wp-security-pack' ),
|
||||
'VE' => __( 'Venezuela', 'wp-security-pack' ),
|
||||
'VN' => __( 'Vietnam', 'wp-security-pack' ),
|
||||
'YE' => __( 'Yemen', 'wp-security-pack' ),
|
||||
'ZM' => __( 'Zambia', 'wp-security-pack' ),
|
||||
'ZW' => __( 'Zimbabwe', 'wp-security-pack' ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a custom login URL slug.
|
||||
*
|
||||
* @param string $slug The slug to sanitize.
|
||||
* @return string
|
||||
*/
|
||||
public static function sanitize_login_slug( $slug ) {
|
||||
$slug = sanitize_title( $slug );
|
||||
$slug = preg_replace( '/[^a-z0-9\-]/', '', $slug );
|
||||
|
||||
// Prevent common reserved slugs.
|
||||
$reserved = array( 'wp-admin', 'wp-login', 'admin', 'login', 'wp-content', 'wp-includes' );
|
||||
if ( in_array( $slug, $reserved, true ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get country flag emoji from country code.
|
||||
*
|
||||
* Converts ISO 3166-1 alpha-2 country codes to Unicode flag emojis.
|
||||
*
|
||||
* @param string $country_code Two-letter country code (e.g., "US", "GB").
|
||||
* @return string Flag emoji or globe emoji for invalid codes.
|
||||
*/
|
||||
public static function get_country_flag( $country_code ) {
|
||||
if ( empty( $country_code ) || strlen( $country_code ) !== 2 ) {
|
||||
return '🌐'; // Globe emoji for invalid codes.
|
||||
}
|
||||
|
||||
$country_code = strtoupper( $country_code );
|
||||
|
||||
// Convert country code to Unicode regional indicator symbols.
|
||||
// Regional indicators are U+1F1E6 (A) through U+1F1FF (Z).
|
||||
$first_letter = mb_chr( ord( $country_code[0] ) - ord( 'A' ) + 0x1F1E6, 'UTF-8' );
|
||||
$second_letter = mb_chr( ord( $country_code[1] ) - ord( 'A' ) + 0x1F1E6, 'UTF-8' );
|
||||
|
||||
return $first_letter . $second_letter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get countries array with flags.
|
||||
*
|
||||
* @return array Country code => "Flag Name" format.
|
||||
*/
|
||||
public static function get_countries_with_flags() {
|
||||
$countries = self::get_countries();
|
||||
$countries_flags = array();
|
||||
|
||||
foreach ( $countries as $code => $name ) {
|
||||
$flag = self::get_country_flag( $code );
|
||||
$countries_flags[ $code ] = $flag . ' ' . $name;
|
||||
}
|
||||
|
||||
return $countries_flags;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
<?php
|
||||
/**
|
||||
* IP access control for WP Security Pack.
|
||||
*
|
||||
* @package WP_Security_Pack
|
||||
*/
|
||||
|
||||
// Prevent direct access.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* IP control class for whitelist/blacklist management.
|
||||
*/
|
||||
class WPSP_IP_Control {
|
||||
|
||||
/**
|
||||
* Cached whitelist IPs.
|
||||
*
|
||||
* @var array|null
|
||||
*/
|
||||
private $whitelist_cache = null;
|
||||
|
||||
/**
|
||||
* Cached blacklist IPs.
|
||||
*
|
||||
* @var array|null
|
||||
*/
|
||||
private $blacklist_cache = null;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
// Run IP check immediately (constructor runs during init).
|
||||
// This blocks blacklisted IPs from accessing the entire website.
|
||||
$this->check_ip_access();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check IP access on every request.
|
||||
*/
|
||||
public function check_ip_access() {
|
||||
$ip = WPSP_Helper::get_client_ip();
|
||||
|
||||
if ( ! $ip ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Always allow whitelisted IPs.
|
||||
if ( $this->is_whitelisted( $ip ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Block blacklisted IPs.
|
||||
if ( $this->is_blacklisted( $ip ) ) {
|
||||
WPSP_Activity_Log::log( WPSP_Activity_Log::EVENT_IP_BLOCKED, $ip, null, __( 'IP blacklisted', 'wp-security-pack' ) );
|
||||
$this->block_access( __( 'Your IP address has been blocked.', 'wp-security-pack' ) );
|
||||
}
|
||||
|
||||
// Check auto-blocked IPs.
|
||||
if ( $this->is_auto_blocked( $ip ) ) {
|
||||
WPSP_Activity_Log::log( WPSP_Activity_Log::EVENT_IP_BLOCKED, $ip, null, __( 'IP auto-blocked', 'wp-security-pack' ) );
|
||||
$this->block_access( __( 'Your IP address has been temporarily blocked due to suspicious activity.', 'wp-security-pack' ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if IP is whitelisted.
|
||||
*
|
||||
* @param string $ip IP address to check.
|
||||
* @return bool
|
||||
*/
|
||||
public function is_whitelisted( $ip ) {
|
||||
$whitelist = $this->get_whitelist();
|
||||
return WPSP_Helper::ip_matches_rules( $ip, $whitelist );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if IP is blacklisted.
|
||||
*
|
||||
* @param string $ip IP address to check.
|
||||
* @return bool
|
||||
*/
|
||||
public function is_blacklisted( $ip ) {
|
||||
$blacklist = $this->get_blacklist();
|
||||
return WPSP_Helper::ip_matches_rules( $ip, $blacklist );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if IP is auto-blocked (temporary block from failed logins).
|
||||
*
|
||||
* @param string $ip IP address to check.
|
||||
* @return bool
|
||||
*/
|
||||
public function is_auto_blocked( $ip ) {
|
||||
global $wpdb;
|
||||
|
||||
$table = WPSP_DB::get_lockout_table();
|
||||
$max_attempts = (int) WP_Security_Pack::get_setting( 'login_max_attempts', 5 );
|
||||
$lockout_minutes = (int) WP_Security_Pack::get_setting( 'login_lockout_duration', 15 );
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$lockout = $wpdb->get_row(
|
||||
$wpdb->prepare(
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
"SELECT * FROM {$table} WHERE ip_address = %s",
|
||||
$ip
|
||||
)
|
||||
);
|
||||
|
||||
if ( ! $lockout ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if IP has reached max attempts and is still within lockout window.
|
||||
if ( (int) $lockout->failed_attempts >= $max_attempts ) {
|
||||
// Calculate if lockout is still active based on updated_at + duration.
|
||||
$updated_time = strtotime( $lockout->updated_at );
|
||||
$lockout_expires = $updated_time + ( $lockout_minutes * 60 );
|
||||
$current_time = time();
|
||||
|
||||
if ( $current_time < $lockout_expires ) {
|
||||
return true; // Still locked out.
|
||||
}
|
||||
}
|
||||
|
||||
// Also check lockout_until for honeypot/manual blocks (stored as Unix timestamp).
|
||||
if ( ! empty( $lockout->lockout_until ) && is_numeric( $lockout->lockout_until ) ) {
|
||||
if ( time() < (int) $lockout->lockout_until ) {
|
||||
return true; // Still locked out via lockout_until.
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whitelist IPs.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_whitelist() {
|
||||
if ( null === $this->whitelist_cache ) {
|
||||
$whitelist_text = WP_Security_Pack::get_setting( 'ip_whitelist', '' );
|
||||
$this->whitelist_cache = WPSP_Helper::parse_ip_list( $whitelist_text );
|
||||
}
|
||||
return $this->whitelist_cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get blacklist IPs.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_blacklist() {
|
||||
if ( null === $this->blacklist_cache ) {
|
||||
$blacklist_text = WP_Security_Pack::get_setting( 'ip_blacklist', '' );
|
||||
$this->blacklist_cache = WPSP_Helper::parse_ip_list( $blacklist_text );
|
||||
}
|
||||
return $this->blacklist_cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear internal caches (call after modifying whitelist/blacklist).
|
||||
*/
|
||||
public function clear_cache() {
|
||||
$this->whitelist_cache = null;
|
||||
$this->blacklist_cache = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add IP to auto-block list (temporary lockout).
|
||||
*
|
||||
* @param string $ip IP address.
|
||||
* @param int $duration Duration in minutes.
|
||||
* @param string $reason Reason for blocking.
|
||||
* @return bool
|
||||
*/
|
||||
public function auto_block_ip( $ip, $duration = 15, $reason = '' ) {
|
||||
global $wpdb;
|
||||
|
||||
$table = WPSP_DB::get_lockout_table();
|
||||
// Store as Unix timestamp for consistency with lockout_ip().
|
||||
$lockout_until = time() + ( $duration * 60 );
|
||||
|
||||
// Check if already exists.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$existing = $wpdb->get_var(
|
||||
$wpdb->prepare(
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
"SELECT id FROM {$table} WHERE ip_address = %s",
|
||||
$ip
|
||||
)
|
||||
);
|
||||
|
||||
if ( $existing ) {
|
||||
// Update existing record.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
return false !== $wpdb->update(
|
||||
$table,
|
||||
array(
|
||||
'lockout_until' => $lockout_until,
|
||||
'updated_at' => current_time( 'mysql' ),
|
||||
),
|
||||
array( 'ip_address' => $ip ),
|
||||
array( '%d', '%s' ),
|
||||
array( '%s' )
|
||||
);
|
||||
}
|
||||
|
||||
// Insert new record.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
return false !== $wpdb->insert(
|
||||
$table,
|
||||
array(
|
||||
'ip_address' => $ip,
|
||||
'failed_attempts' => 0,
|
||||
'lockout_until' => $lockout_until,
|
||||
'created_at' => current_time( 'mysql' ),
|
||||
'updated_at' => current_time( 'mysql' ),
|
||||
),
|
||||
array( '%s', '%d', '%d', '%s', '%s' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove IP from auto-block list.
|
||||
*
|
||||
* @param string $ip IP address.
|
||||
* @return bool
|
||||
*/
|
||||
public function unblock_ip( $ip ) {
|
||||
global $wpdb;
|
||||
|
||||
$table = WPSP_DB::get_lockout_table();
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
return false !== $wpdb->delete(
|
||||
$table,
|
||||
array( 'ip_address' => $ip ),
|
||||
array( '%s' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all currently blocked IPs.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_blocked_ips() {
|
||||
global $wpdb;
|
||||
|
||||
$table = WPSP_DB::get_lockout_table();
|
||||
$max_attempts = (int) WP_Security_Pack::get_setting( 'login_max_attempts', 5 );
|
||||
$lockout_minutes = (int) WP_Security_Pack::get_setting( 'login_lockout_duration', 15 );
|
||||
$current_time = time();
|
||||
|
||||
// Get all lockout records.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$lockouts = $wpdb->get_results(
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
"SELECT * FROM {$table} ORDER BY updated_at DESC"
|
||||
);
|
||||
|
||||
$blocked = array();
|
||||
foreach ( $lockouts as $lockout ) {
|
||||
$is_blocked = false;
|
||||
$lockout_expires = 0;
|
||||
|
||||
// Check login-based lockout (failed_attempts >= max and within time window).
|
||||
if ( (int) $lockout->failed_attempts >= $max_attempts ) {
|
||||
$updated_time = strtotime( $lockout->updated_at );
|
||||
$lockout_expires = $updated_time + ( $lockout_minutes * 60 );
|
||||
if ( $current_time < $lockout_expires ) {
|
||||
$is_blocked = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check honeypot/manual lockout (lockout_until as Unix timestamp).
|
||||
if ( ! empty( $lockout->lockout_until ) && is_numeric( $lockout->lockout_until ) ) {
|
||||
$lockout_until_ts = (int) $lockout->lockout_until;
|
||||
if ( $current_time < $lockout_until_ts ) {
|
||||
$is_blocked = true;
|
||||
// Use the later expiry time.
|
||||
if ( $lockout_until_ts > $lockout_expires ) {
|
||||
$lockout_expires = $lockout_until_ts;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( $is_blocked ) {
|
||||
// Add computed lockout_until field for display.
|
||||
$lockout->lockout_until = gmdate( 'Y-m-d H:i:s', $lockout_expires );
|
||||
$blocked[] = $lockout;
|
||||
}
|
||||
}
|
||||
|
||||
return $blocked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Block access and exit.
|
||||
*
|
||||
* @param string $message Error message.
|
||||
*/
|
||||
private function block_access( $message ) {
|
||||
status_header( 403 );
|
||||
nocache_headers();
|
||||
|
||||
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
|
||||
wp_send_json_error( array( 'message' => $message ), 403 );
|
||||
}
|
||||
|
||||
// Simple blocked page.
|
||||
wp_die(
|
||||
esc_html( $message ),
|
||||
esc_html__( 'Access Denied', 'wp-security-pack' ),
|
||||
array(
|
||||
'response' => 403,
|
||||
'back_link' => false,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
<?php
|
||||
/**
|
||||
* IP2Location database reader for WP Security Pack.
|
||||
*
|
||||
* Reads IP2Location BIN format databases.
|
||||
*
|
||||
* @package WP_Security_Pack
|
||||
*/
|
||||
|
||||
// Prevent direct access.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* IP2Location BIN database reader.
|
||||
*
|
||||
* Based on IP2Location PHP Module but simplified for our needs.
|
||||
*/
|
||||
class WPSP_IP2Location {
|
||||
|
||||
/**
|
||||
* Database file handle.
|
||||
*
|
||||
* @var resource|null
|
||||
*/
|
||||
private $handle = null;
|
||||
|
||||
/**
|
||||
* Database type.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $db_type = 0;
|
||||
|
||||
/**
|
||||
* Database column count.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $db_column = 0;
|
||||
|
||||
/**
|
||||
* Database year.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $db_year = 0;
|
||||
|
||||
/**
|
||||
* Database month.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $db_month = 0;
|
||||
|
||||
/**
|
||||
* Database day.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $db_day = 0;
|
||||
|
||||
/**
|
||||
* IPv4 database count.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $ipv4_count = 0;
|
||||
|
||||
/**
|
||||
* IPv4 database address.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $ipv4_addr = 0;
|
||||
|
||||
/**
|
||||
* IPv6 database count.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $ipv6_count = 0;
|
||||
|
||||
/**
|
||||
* IPv6 database address.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $ipv6_addr = 0;
|
||||
|
||||
/**
|
||||
* IPv4 index base address.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $ipv4_index_addr = 0;
|
||||
|
||||
/**
|
||||
* IPv6 index base address.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $ipv6_index_addr = 0;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param string $db_path Path to database file.
|
||||
*/
|
||||
public function __construct( $db_path ) {
|
||||
if ( ! file_exists( $db_path ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen
|
||||
$this->handle = fopen( $db_path, 'rb' );
|
||||
|
||||
if ( ! $this->handle ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Read database header.
|
||||
$this->db_type = $this->read_byte( 1 );
|
||||
$this->db_column = $this->read_byte( 2 );
|
||||
$this->db_year = $this->read_byte( 3 );
|
||||
$this->db_month = $this->read_byte( 4 );
|
||||
$this->db_day = $this->read_byte( 5 );
|
||||
|
||||
$this->ipv4_count = $this->read_word( 6 );
|
||||
$this->ipv4_addr = $this->read_word( 10 );
|
||||
$this->ipv6_count = $this->read_word( 14 );
|
||||
$this->ipv6_addr = $this->read_word( 18 );
|
||||
|
||||
$this->ipv4_index_addr = $this->read_word( 22 );
|
||||
$this->ipv6_index_addr = $this->read_word( 26 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Destructor.
|
||||
*/
|
||||
public function __destruct() {
|
||||
if ( $this->handle ) {
|
||||
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
|
||||
fclose( $this->handle );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lookup an IP address.
|
||||
*
|
||||
* @param string $ip IP address.
|
||||
* @return array|null
|
||||
*/
|
||||
public function lookup( $ip ) {
|
||||
if ( ! $this->handle ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Determine IP version.
|
||||
$ip_version = filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ? 6 : 4;
|
||||
|
||||
if ( 4 === $ip_version ) {
|
||||
return $this->lookup_ipv4( $ip );
|
||||
}
|
||||
|
||||
return $this->lookup_ipv6( $ip );
|
||||
}
|
||||
|
||||
/**
|
||||
* Lookup IPv4 address.
|
||||
*
|
||||
* @param string $ip IPv4 address.
|
||||
* @return array|null
|
||||
*/
|
||||
private function lookup_ipv4( $ip ) {
|
||||
if ( $this->ipv4_count <= 0 ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ip_num = sprintf( '%u', ip2long( $ip ) );
|
||||
|
||||
// Use index for faster lookup.
|
||||
$index = ( $ip_num >> 16 );
|
||||
|
||||
$low = 0;
|
||||
$high = $this->ipv4_count;
|
||||
|
||||
if ( $this->ipv4_index_addr > 0 ) {
|
||||
$low = $this->read_word( $this->ipv4_index_addr + ( $index * 8 ) );
|
||||
$high = $this->read_word( $this->ipv4_index_addr + ( $index * 8 ) + 4 );
|
||||
}
|
||||
|
||||
// Binary search.
|
||||
while ( $low <= $high ) {
|
||||
$mid = (int) ( ( $low + $high ) / 2 );
|
||||
$ip_from = $this->read_word( $this->ipv4_addr + $mid * $this->db_column * 4 );
|
||||
$ip_to = $this->read_word( $this->ipv4_addr + ( $mid + 1 ) * $this->db_column * 4 );
|
||||
|
||||
if ( $ip_num >= $ip_from && $ip_num < $ip_to ) {
|
||||
return $this->read_record( $this->ipv4_addr + $mid * $this->db_column * 4, 4 );
|
||||
}
|
||||
|
||||
if ( $ip_num < $ip_from ) {
|
||||
$high = $mid - 1;
|
||||
} else {
|
||||
$low = $mid + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lookup IPv6 address.
|
||||
*
|
||||
* @param string $ip IPv6 address.
|
||||
* @return array|null
|
||||
*/
|
||||
private function lookup_ipv6( $ip ) {
|
||||
if ( $this->ipv6_count <= 0 ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ip_num = $this->ipv6_to_number( $ip );
|
||||
|
||||
$low = 0;
|
||||
$high = $this->ipv6_count;
|
||||
|
||||
if ( $this->ipv6_index_addr > 0 ) {
|
||||
$index_value = bcdiv( $ip_num, bcpow( '2', '112' ) );
|
||||
$index = bcmod( $index_value, '65536' );
|
||||
|
||||
$low = $this->read_word( $this->ipv6_index_addr + (int) $index * 8 );
|
||||
$high = $this->read_word( $this->ipv6_index_addr + (int) $index * 8 + 4 );
|
||||
}
|
||||
|
||||
// Binary search.
|
||||
while ( $low <= $high ) {
|
||||
$mid = (int) ( ( $low + $high ) / 2 );
|
||||
$ip_from = $this->read_ipv6( $this->ipv6_addr + $mid * ( $this->db_column * 4 + 12 ) );
|
||||
$ip_to = $this->read_ipv6( $this->ipv6_addr + ( $mid + 1 ) * ( $this->db_column * 4 + 12 ) );
|
||||
|
||||
if ( bccomp( $ip_num, $ip_from ) >= 0 && bccomp( $ip_num, $ip_to ) < 0 ) {
|
||||
return $this->read_record( $this->ipv6_addr + $mid * ( $this->db_column * 4 + 12 ) + 12, 6 );
|
||||
}
|
||||
|
||||
if ( bccomp( $ip_num, $ip_from ) < 0 ) {
|
||||
$high = $mid - 1;
|
||||
} else {
|
||||
$low = $mid + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read record from database.
|
||||
*
|
||||
* @param int $row_addr Row address.
|
||||
* @param int $ip_version IP version.
|
||||
* @return array
|
||||
*/
|
||||
private function read_record( $row_addr, $ip_version ) {
|
||||
$record = array(
|
||||
'country_code' => '-',
|
||||
'country_name' => '-',
|
||||
);
|
||||
|
||||
// Country is always at column 0 for DB1-DB24.
|
||||
$country_pos = $row_addr + 4;
|
||||
|
||||
if ( 6 === $ip_version ) {
|
||||
$country_pos = $row_addr;
|
||||
}
|
||||
|
||||
$country_offset = $this->read_word( $country_pos );
|
||||
|
||||
if ( $country_offset > 0 ) {
|
||||
$record['country_code'] = $this->read_string( $country_offset );
|
||||
$record['country_name'] = $this->read_string( $country_offset + 3 );
|
||||
}
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a byte from database.
|
||||
*
|
||||
* @param int $pos Position.
|
||||
* @return int
|
||||
*/
|
||||
private function read_byte( $pos ) {
|
||||
fseek( $this->handle, $pos - 1, SEEK_SET );
|
||||
$data = fread( $this->handle, 1 );
|
||||
return unpack( 'C', $data )[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a 32-bit word from database.
|
||||
*
|
||||
* @param int $pos Position.
|
||||
* @return int
|
||||
*/
|
||||
private function read_word( $pos ) {
|
||||
fseek( $this->handle, $pos - 1, SEEK_SET );
|
||||
$data = fread( $this->handle, 4 );
|
||||
return unpack( 'V', $data )[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a string from database.
|
||||
*
|
||||
* @param int $pos Position.
|
||||
* @return string
|
||||
*/
|
||||
private function read_string( $pos ) {
|
||||
fseek( $this->handle, $pos, SEEK_SET );
|
||||
$length = unpack( 'C', fread( $this->handle, 1 ) )[1];
|
||||
return fread( $this->handle, $length );
|
||||
}
|
||||
|
||||
/**
|
||||
* Read IPv6 address from database.
|
||||
*
|
||||
* @param int $pos Position.
|
||||
* @return string
|
||||
*/
|
||||
private function read_ipv6( $pos ) {
|
||||
fseek( $this->handle, $pos - 1, SEEK_SET );
|
||||
$data = fread( $this->handle, 16 );
|
||||
$int = unpack( 'V4', $data );
|
||||
|
||||
$result = bcadd( bcadd( bcmul( $int[4], bcpow( '4294967296', '3' ) ), bcmul( $int[3], bcpow( '4294967296', '2' ) ) ), bcadd( bcmul( $int[2], '4294967296' ), $int[1] ) );
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert IPv6 to number.
|
||||
*
|
||||
* @param string $ip IPv6 address.
|
||||
* @return string
|
||||
*/
|
||||
private function ipv6_to_number( $ip ) {
|
||||
$bin = inet_pton( $ip );
|
||||
$hex = bin2hex( $bin );
|
||||
|
||||
$result = '0';
|
||||
for ( $i = 0; $i < strlen( $hex ); $i++ ) {
|
||||
$result = bcadd( bcmul( $result, '16' ), hexdec( $hex[ $i ] ) );
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get database type string.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_database_type() {
|
||||
if ( ! $this->handle ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$types = array(
|
||||
1 => 'DB1 (Country)',
|
||||
2 => 'DB2 (Country + ISP)',
|
||||
3 => 'DB3 (Country + Region + City)',
|
||||
4 => 'DB4 (Country + Region + City + ISP)',
|
||||
5 => 'DB5 (Country + Region + City + Lat/Long)',
|
||||
11 => 'DB11 (Full)',
|
||||
24 => 'DB24 (Full)',
|
||||
);
|
||||
|
||||
$date = sprintf( '%04d-%02d-%02d', 2000 + $this->db_year, $this->db_month, $this->db_day );
|
||||
|
||||
$type = isset( $types[ $this->db_type ] ) ? $types[ $this->db_type ] : 'DB' . $this->db_type;
|
||||
|
||||
return $type . ' (' . $date . ')';
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,766 @@
|
||||
<?php
|
||||
/**
|
||||
* Malware scanner for WP Security Pack.
|
||||
*
|
||||
* @package WP_Security_Pack
|
||||
*/
|
||||
|
||||
// Prevent direct access.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Malware scanner with signature and hash-based detection.
|
||||
*
|
||||
* Uses two detection methods:
|
||||
* 1. Pattern-based: Regex signatures for suspicious code patterns
|
||||
* 2. Hash-based: Known malware file hashes (100% accurate, no false positives)
|
||||
*
|
||||
* Only scans plugins, themes, and uploads - NOT WordPress core.
|
||||
*/
|
||||
class WPSP_Malware_Scanner {
|
||||
|
||||
/**
|
||||
* Option key for scan results.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const RESULTS_OPTION = 'wpsp_malware_scan_results';
|
||||
|
||||
/**
|
||||
* Option key for last scan time.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const LAST_SCAN_OPTION = 'wpsp_malware_last_scan';
|
||||
|
||||
/**
|
||||
* Option key for malware hash database.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const HASH_DB_OPTION = 'wpsp_malware_hashes';
|
||||
|
||||
/**
|
||||
* Option key for hash database last update.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const HASH_DB_UPDATED_OPTION = 'wpsp_malware_hashes_updated';
|
||||
|
||||
/**
|
||||
* Malware signatures (patterns to detect).
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $signatures = array();
|
||||
|
||||
/**
|
||||
* Known malware file hashes (MD5).
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $malware_hashes = array();
|
||||
|
||||
/**
|
||||
* Paths/patterns to skip (legitimate libraries and tools).
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $skip_paths = array(
|
||||
// This plugin's own files.
|
||||
'wp-security-pack',
|
||||
|
||||
// Common libraries that legitimately use shell/network functions.
|
||||
'phpseclib',
|
||||
'php-curl-class',
|
||||
|
||||
// Package managers.
|
||||
'/vendor/',
|
||||
'/node_modules/',
|
||||
|
||||
// Known backup/security plugins.
|
||||
'updraftplus',
|
||||
'backwpup',
|
||||
'duplicator',
|
||||
);
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->load_signatures();
|
||||
$this->load_malware_hashes();
|
||||
|
||||
if ( ! WP_Security_Pack::get_setting( 'malware_scan_enabled', true ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Schedule weekly scan.
|
||||
add_action( 'wpsp_weekly_malware_scan', array( $this, 'run_scheduled_scan' ) );
|
||||
|
||||
if ( ! wp_next_scheduled( 'wpsp_weekly_malware_scan' ) ) {
|
||||
wp_schedule_event( time(), 'weekly', 'wpsp_weekly_malware_scan' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load known malware file hashes.
|
||||
*
|
||||
* These are MD5 hashes of known malicious files. When a file matches,
|
||||
* it's 100% confirmed malware - no false positives possible.
|
||||
*/
|
||||
private function load_malware_hashes() {
|
||||
// Try to load from database (updated hashes).
|
||||
$stored_hashes = get_option( self::HASH_DB_OPTION, array() );
|
||||
|
||||
if ( ! empty( $stored_hashes ) ) {
|
||||
$this->malware_hashes = $stored_hashes;
|
||||
return;
|
||||
}
|
||||
|
||||
// Hash database starts empty - relies on signature detection.
|
||||
// Users can add hashes via the 'wpsp_malware_hashes' filter or
|
||||
// by updating from a trusted source using update_hash_database().
|
||||
$this->malware_hashes = array();
|
||||
|
||||
// Allow adding custom hashes via filter.
|
||||
$this->malware_hashes = apply_filters( 'wpsp_malware_hashes', $this->malware_hashes );
|
||||
}
|
||||
|
||||
/**
|
||||
* Update malware hash database from remote source.
|
||||
*
|
||||
* @param string $source_url URL to fetch hashes from (JSON format).
|
||||
* @return bool|WP_Error
|
||||
*/
|
||||
public function update_hash_database( $source_url = '' ) {
|
||||
if ( empty( $source_url ) ) {
|
||||
// Default: Could be a GitHub raw URL or your own endpoint.
|
||||
// For now, just return - users can provide their own source.
|
||||
return new WP_Error( 'no_source', __( 'No hash database source URL provided.', 'wp-security-pack' ) );
|
||||
}
|
||||
|
||||
$response = wp_remote_get( $source_url, array( 'timeout' => 30 ) );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$body = wp_remote_retrieve_body( $response );
|
||||
$data = json_decode( $body, true );
|
||||
|
||||
if ( ! is_array( $data ) ) {
|
||||
return new WP_Error( 'invalid_data', __( 'Invalid hash database format.', 'wp-security-pack' ) );
|
||||
}
|
||||
|
||||
// Merge with existing hashes.
|
||||
$current_hashes = $this->malware_hashes;
|
||||
$new_hashes = array_merge( $current_hashes, $data );
|
||||
|
||||
update_option( self::HASH_DB_OPTION, $new_hashes );
|
||||
update_option( self::HASH_DB_UPDATED_OPTION, time() );
|
||||
|
||||
$this->malware_hashes = $new_hashes;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file matches a known malware hash.
|
||||
*
|
||||
* @param string $file_path Path to file.
|
||||
* @return array|false Malware info if matched, false otherwise.
|
||||
*/
|
||||
public function check_file_hash( $file_path ) {
|
||||
if ( ! file_exists( $file_path ) || ! is_readable( $file_path ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$md5_hash = md5_file( $file_path );
|
||||
|
||||
if ( isset( $this->malware_hashes[ $md5_hash ] ) ) {
|
||||
return array(
|
||||
'hash' => $md5_hash,
|
||||
'name' => $this->malware_hashes[ $md5_hash ],
|
||||
'method' => 'hash',
|
||||
);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get hash database info.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_hash_database_info() {
|
||||
return array(
|
||||
'count' => count( $this->malware_hashes ),
|
||||
'last_updated' => get_option( self::HASH_DB_UPDATED_OPTION, 0 ),
|
||||
'source' => empty( get_option( self::HASH_DB_OPTION ) ) ? 'built-in' : 'updated',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load malware signatures.
|
||||
*
|
||||
* Patterns are organized by category and designed to minimize false positives
|
||||
* while catching real threats. We do NOT scan WordPress core files.
|
||||
*/
|
||||
private function load_signatures() {
|
||||
$this->signatures = array(
|
||||
|
||||
// =====================================================================
|
||||
// CRITICAL: Code Execution with Obfuscation
|
||||
// These patterns are almost always malicious.
|
||||
// =====================================================================
|
||||
array(
|
||||
'name' => 'Base64 Decode Execution',
|
||||
'pattern' => '/\beval\s*\(\s*base64_decode\s*\(/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Executing base64-encoded PHP code',
|
||||
),
|
||||
array(
|
||||
'name' => 'Gzinflate Execution',
|
||||
'pattern' => '/\beval\s*\(\s*gzinflate\s*\(/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Executing gzip-compressed PHP code',
|
||||
),
|
||||
array(
|
||||
'name' => 'Gzuncompress Execution',
|
||||
'pattern' => '/\beval\s*\(\s*gzuncompress\s*\(/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Executing compressed PHP code',
|
||||
),
|
||||
array(
|
||||
'name' => 'Str_rot13 Execution',
|
||||
'pattern' => '/\beval\s*\(\s*str_rot13\s*\(/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Executing ROT13-obfuscated PHP code',
|
||||
),
|
||||
array(
|
||||
'name' => 'Multiple Decode Layers',
|
||||
'pattern' => '/base64_decode\s*\([^)]*base64_decode/is',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Multiple layers of encoding (heavy obfuscation)',
|
||||
),
|
||||
array(
|
||||
'name' => 'Preg_replace /e Modifier',
|
||||
'pattern' => '/preg_replace\s*\(\s*["\'][^"\']*\/[a-z]*e[a-z]*["\']/',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Code execution via deprecated preg_replace /e modifier',
|
||||
),
|
||||
|
||||
// =====================================================================
|
||||
// CRITICAL: User Input to Code Execution
|
||||
// Direct path from user input to code execution.
|
||||
// =====================================================================
|
||||
array(
|
||||
'name' => 'Eval with User Input',
|
||||
'pattern' => '/\beval\s*\(\s*[\$\.\s]*\$_(POST|GET|REQUEST|COOKIE|SERVER|FILES)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Direct code execution from user input',
|
||||
),
|
||||
array(
|
||||
'name' => 'Assert with User Input',
|
||||
'pattern' => '/\bassert\s*\(\s*[\$\.\s]*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Code execution via assert() from user input',
|
||||
),
|
||||
array(
|
||||
'name' => 'Create_function with User Input',
|
||||
'pattern' => '/\bcreate_function\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Dynamic function creation with user input',
|
||||
),
|
||||
array(
|
||||
'name' => 'Call_user_func with User Input',
|
||||
'pattern' => '/\bcall_user_func(_array)?\s*\(\s*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Calling arbitrary function from user input',
|
||||
),
|
||||
array(
|
||||
'name' => 'Variable Function with User Input',
|
||||
'pattern' => '/\$_(POST|GET|REQUEST|COOKIE)\s*\[[^\]]+\]\s*\(/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Calling function name from user input',
|
||||
),
|
||||
|
||||
// =====================================================================
|
||||
// CRITICAL: Shell Command Execution with User Input
|
||||
// =====================================================================
|
||||
array(
|
||||
'name' => 'Shell_exec with User Input',
|
||||
'pattern' => '/\bshell_exec\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Shell command execution with user input',
|
||||
),
|
||||
array(
|
||||
'name' => 'System with User Input',
|
||||
'pattern' => '/\bsystem\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'System command execution with user input',
|
||||
),
|
||||
array(
|
||||
'name' => 'Passthru with User Input',
|
||||
'pattern' => '/\bpassthru\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Passthru command execution with user input',
|
||||
),
|
||||
array(
|
||||
'name' => 'Exec with User Input',
|
||||
'pattern' => '/\bexec\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Exec command execution with user input',
|
||||
),
|
||||
array(
|
||||
'name' => 'Popen with User Input',
|
||||
'pattern' => '/\bpopen\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Process opened with user-controlled command',
|
||||
),
|
||||
array(
|
||||
'name' => 'Proc_open with User Input',
|
||||
'pattern' => '/\bproc_open\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Process opened with user-controlled command',
|
||||
),
|
||||
|
||||
// =====================================================================
|
||||
// CRITICAL: File Inclusion Vulnerabilities
|
||||
// =====================================================================
|
||||
array(
|
||||
'name' => 'Include with User Input',
|
||||
'pattern' => '/\b(include|require|include_once|require_once)\s*\(?\s*[\$\.\s]*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Local/Remote File Inclusion vulnerability',
|
||||
),
|
||||
|
||||
// =====================================================================
|
||||
// CRITICAL: File Write Vulnerabilities
|
||||
// =====================================================================
|
||||
array(
|
||||
'name' => 'File_put_contents with User Input',
|
||||
'pattern' => '/\bfile_put_contents\s*\([^,]*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Writing to user-controlled file path',
|
||||
),
|
||||
array(
|
||||
'name' => 'Fwrite with User Content',
|
||||
'pattern' => '/\bfwrite\s*\([^,]+,\s*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'high',
|
||||
'description' => 'Writing user content to file',
|
||||
),
|
||||
array(
|
||||
'name' => 'Fopen with User Path',
|
||||
'pattern' => '/\bfopen\s*\(\s*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Opening user-controlled file path',
|
||||
),
|
||||
array(
|
||||
'name' => 'Unrestricted File Upload Path',
|
||||
'pattern' => '/move_uploaded_file\s*\([^,]+,\s*[^)]*\$_(POST|GET|REQUEST)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Uploading file to user-controlled path',
|
||||
),
|
||||
|
||||
// =====================================================================
|
||||
// HIGH: Known Backdoor Patterns
|
||||
// Specific patterns that indicate known malware structures.
|
||||
// =====================================================================
|
||||
array(
|
||||
'name' => 'Web Shell Upload Form',
|
||||
'pattern' => '/<form[^>]*enctype=["\']multipart\/form-data["\'][^>]*>.*<input[^>]*type=["\']file["\'].*\$_FILES/is',
|
||||
'severity' => 'high',
|
||||
'description' => 'File upload form with immediate processing (potential backdoor)',
|
||||
),
|
||||
array(
|
||||
'name' => 'Eval POST/GET Pattern',
|
||||
'pattern' => '/\beval\s*\(\s*\$_(POST|GET)\s*\[\s*["\'][a-z0-9_]+["\']\s*\]\s*\)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Classic backdoor pattern: eval($_POST[key])',
|
||||
),
|
||||
array(
|
||||
'name' => 'Base64 POST Execution',
|
||||
'pattern' => '/\beval\s*\(\s*base64_decode\s*\(\s*\$_(POST|GET|REQUEST)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Executing base64-encoded user input',
|
||||
),
|
||||
array(
|
||||
'name' => 'Gunzip Eval Chain',
|
||||
'pattern' => '/\beval\s*\(\s*gzuncompress\s*\(\s*base64_decode/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Multi-layer deobfuscation chain',
|
||||
),
|
||||
|
||||
// =====================================================================
|
||||
// HIGH: Obfuscation Indicators
|
||||
// =====================================================================
|
||||
array(
|
||||
'name' => 'Very Long Encoded String',
|
||||
'pattern' => '/["\'][A-Za-z0-9+\/=]{1500,}["\']/s',
|
||||
'severity' => 'high',
|
||||
'description' => 'Extremely long encoded string (likely obfuscated malware)',
|
||||
),
|
||||
array(
|
||||
'name' => 'Hex Escape Sequence',
|
||||
'pattern' => '/(\\\\x[0-9a-fA-F]{2}){20,}/i',
|
||||
'severity' => 'high',
|
||||
'description' => 'Long hex-encoded string (obfuscation technique)',
|
||||
),
|
||||
array(
|
||||
'name' => 'Chr() Obfuscation',
|
||||
'pattern' => '/(\bchr\s*\(\s*\d+\s*\)\s*\.?\s*){10,}/i',
|
||||
'severity' => 'high',
|
||||
'description' => 'Building string from chr() calls (obfuscation)',
|
||||
),
|
||||
array(
|
||||
'name' => 'Array Character Building',
|
||||
'pattern' => '/\$\w+\s*=\s*["\'][A-Za-z]+["\'];\s*\$\w+\s*=\s*\$\w+\[\d+\]\s*\.\s*\$\w+\[\d+\]/i',
|
||||
'severity' => 'medium',
|
||||
'description' => 'Building function names from array indices (obfuscation)',
|
||||
),
|
||||
|
||||
// =====================================================================
|
||||
// HIGH: WordPress-Specific Attacks
|
||||
// =====================================================================
|
||||
array(
|
||||
'name' => 'WP User Creation Backdoor',
|
||||
'pattern' => '/wp_create_user\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Creating WordPress user from user input',
|
||||
),
|
||||
array(
|
||||
'name' => 'WP Insert User Backdoor',
|
||||
'pattern' => '/wp_insert_user\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Inserting WordPress user from user input',
|
||||
),
|
||||
array(
|
||||
'name' => 'WP Option Injection',
|
||||
'pattern' => '/update_option\s*\(\s*\$_(POST|GET|REQUEST)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Updating arbitrary WordPress option from user input',
|
||||
),
|
||||
array(
|
||||
'name' => 'WP Auth Cookie Manipulation',
|
||||
'pattern' => '/wp_set_auth_cookie\s*\([^)]*\$_(POST|GET|REQUEST)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Setting auth cookie from user input (authentication bypass)',
|
||||
),
|
||||
array(
|
||||
'name' => 'WP Role Escalation',
|
||||
'pattern' => '/->set_role\s*\(\s*["\']administrator["\']\s*\)|->add_cap\s*\([^)]*\$_(POST|GET|REQUEST)/i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Privilege escalation attempt',
|
||||
),
|
||||
|
||||
// =====================================================================
|
||||
// HIGH: Suspicious Patterns with Context
|
||||
// These require specific dangerous context to trigger.
|
||||
// =====================================================================
|
||||
array(
|
||||
'name' => 'Error Suppression with Eval',
|
||||
'pattern' => '/@\s*eval\s*\(/i',
|
||||
'severity' => 'high',
|
||||
'description' => 'Eval with error suppression (hiding malicious activity)',
|
||||
),
|
||||
array(
|
||||
'name' => 'Remote Code Fetch and Execute',
|
||||
'pattern' => '/eval\s*\(\s*file_get_contents\s*\(\s*["\']https?:\/\//i',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Fetching and executing remote code',
|
||||
),
|
||||
array(
|
||||
'name' => 'CURL Fetch and Execute',
|
||||
'pattern' => '/eval\s*\([^)]*curl_exec/is',
|
||||
'severity' => 'critical',
|
||||
'description' => 'Executing code fetched via CURL',
|
||||
),
|
||||
array(
|
||||
'name' => 'Dynamic URL Fetch with User Input',
|
||||
'pattern' => '/file_get_contents\s*\(\s*\$_(POST|GET|REQUEST|COOKIE)/i',
|
||||
'severity' => 'high',
|
||||
'description' => 'Fetching content from user-controlled URL',
|
||||
),
|
||||
);
|
||||
|
||||
// Allow adding custom signatures via filter.
|
||||
$this->signatures = apply_filters( 'wpsp_malware_signatures', $this->signatures );
|
||||
}
|
||||
|
||||
/**
|
||||
* Run scheduled scan.
|
||||
*/
|
||||
public function run_scheduled_scan() {
|
||||
$results = $this->scan_files();
|
||||
|
||||
if ( ! empty( $results ) ) {
|
||||
update_option( self::RESULTS_OPTION, $results );
|
||||
$this->send_alert( $results );
|
||||
}
|
||||
|
||||
update_option( self::LAST_SCAN_OPTION, time() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan files for malware signatures.
|
||||
*
|
||||
* Only scans plugins, themes, and uploads directories.
|
||||
* Does NOT scan WordPress core to avoid false positives.
|
||||
*
|
||||
* @param array $paths Paths to scan (default: wp-content directories only).
|
||||
* @return array
|
||||
*/
|
||||
public function scan_files( $paths = array() ) {
|
||||
if ( empty( $paths ) ) {
|
||||
// Only scan wp-content directories, NOT WordPress core.
|
||||
$paths = array(
|
||||
WP_CONTENT_DIR . '/plugins/',
|
||||
WP_CONTENT_DIR . '/themes/',
|
||||
WP_CONTENT_DIR . '/uploads/',
|
||||
WP_CONTENT_DIR . '/mu-plugins/',
|
||||
);
|
||||
}
|
||||
|
||||
$results = array();
|
||||
$file_count = 0;
|
||||
$max_files = 10000; // Limit to prevent timeout.
|
||||
|
||||
foreach ( $paths as $path ) {
|
||||
if ( ! file_exists( $path ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( is_file( $path ) ) {
|
||||
if ( ! $this->should_skip_file( $path ) ) {
|
||||
$file_results = $this->scan_file( $path );
|
||||
if ( ! empty( $file_results ) ) {
|
||||
$results[ $path ] = $file_results;
|
||||
}
|
||||
}
|
||||
$file_count++;
|
||||
} else {
|
||||
$iterator = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator( $path, RecursiveDirectoryIterator::SKIP_DOTS ),
|
||||
RecursiveIteratorIterator::SELF_FIRST
|
||||
);
|
||||
|
||||
foreach ( $iterator as $file ) {
|
||||
if ( $file_count >= $max_files ) {
|
||||
break 2;
|
||||
}
|
||||
|
||||
if ( ! $file->isFile() ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$file_path = $file->getPathname();
|
||||
$ext = strtolower( $file->getExtension() );
|
||||
|
||||
// Only scan PHP files.
|
||||
if ( 'php' !== $ext ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip large files (> 2MB).
|
||||
if ( $file->getSize() > 2 * 1024 * 1024 ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip known safe paths.
|
||||
if ( $this->should_skip_file( $file_path ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$file_results = $this->scan_file( $file_path );
|
||||
if ( ! empty( $file_results ) ) {
|
||||
$results[ $file_path ] = $file_results;
|
||||
}
|
||||
|
||||
$file_count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
update_option( self::LAST_SCAN_OPTION, time() );
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file should be skipped (known legitimate libraries).
|
||||
*
|
||||
* @param string $file_path File path to check.
|
||||
* @return bool True if file should be skipped.
|
||||
*/
|
||||
private function should_skip_file( $file_path ) {
|
||||
foreach ( $this->skip_paths as $skip ) {
|
||||
if ( stripos( $file_path, $skip ) !== false ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan a single file.
|
||||
*
|
||||
* @param string $file_path File path.
|
||||
* @return array
|
||||
*/
|
||||
public function scan_file( $file_path ) {
|
||||
if ( ! file_exists( $file_path ) || ! is_readable( $file_path ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$findings = array();
|
||||
|
||||
// First: Check against known malware hashes (100% accurate).
|
||||
$hash_match = $this->check_file_hash( $file_path );
|
||||
if ( $hash_match ) {
|
||||
$findings[] = array(
|
||||
'name' => 'Known Malware: ' . $hash_match['name'],
|
||||
'severity' => 'critical',
|
||||
'description' => 'File matches known malware hash (MD5: ' . $hash_match['hash'] . ')',
|
||||
'match' => 'Hash match - confirmed malware',
|
||||
'confirmed' => true,
|
||||
);
|
||||
// Hash match is definitive - still scan for patterns but mark as confirmed.
|
||||
}
|
||||
|
||||
// Second: Pattern-based detection.
|
||||
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
|
||||
$content = file_get_contents( $file_path );
|
||||
|
||||
if ( ! empty( $content ) ) {
|
||||
foreach ( $this->signatures as $signature ) {
|
||||
if ( preg_match( $signature['pattern'], $content, $matches ) ) {
|
||||
$findings[] = array(
|
||||
'name' => $signature['name'],
|
||||
'severity' => $signature['severity'],
|
||||
'description' => $signature['description'],
|
||||
'match' => substr( $matches[0], 0, 100 ),
|
||||
'confirmed' => false,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $findings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send email alert about scan results.
|
||||
*
|
||||
* @param array $results Scan results.
|
||||
*/
|
||||
private function send_alert( $results ) {
|
||||
if ( ! WP_Security_Pack::get_setting( 'email_alerts_enabled', false ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$email = WP_Security_Pack::get_setting( 'email_alerts_address', get_option( 'admin_email' ) );
|
||||
$site_name = get_bloginfo( 'name' );
|
||||
$site_url = home_url();
|
||||
|
||||
// Count by severity.
|
||||
$counts = array(
|
||||
'critical' => 0,
|
||||
'high' => 0,
|
||||
'medium' => 0,
|
||||
'low' => 0,
|
||||
);
|
||||
|
||||
foreach ( $results as $file => $findings ) {
|
||||
foreach ( $findings as $finding ) {
|
||||
$counts[ $finding['severity'] ]++;
|
||||
}
|
||||
}
|
||||
|
||||
$subject = sprintf(
|
||||
/* translators: %s: Site name */
|
||||
__( '[%s] Malware Scan Alert - Suspicious Files Found', 'wp-security-pack' ),
|
||||
$site_name
|
||||
);
|
||||
|
||||
$message = sprintf(
|
||||
/* translators: %s: Site URL */
|
||||
__( "WP Security Pack malware scan has detected suspicious files on %s.\n\n", 'wp-security-pack' ),
|
||||
$site_url
|
||||
);
|
||||
|
||||
$message .= __( "Summary:\n", 'wp-security-pack' );
|
||||
$message .= sprintf( __( "- Critical: %d\n", 'wp-security-pack' ), $counts['critical'] );
|
||||
$message .= sprintf( __( "- High: %d\n", 'wp-security-pack' ), $counts['high'] );
|
||||
$message .= sprintf( __( "- Medium: %d\n", 'wp-security-pack' ), $counts['medium'] );
|
||||
$message .= sprintf( __( "- Low: %d\n\n", 'wp-security-pack' ), $counts['low'] );
|
||||
|
||||
$message .= __( "Files with issues:\n", 'wp-security-pack' );
|
||||
|
||||
$count = 0;
|
||||
foreach ( $results as $file => $findings ) {
|
||||
if ( $count >= 20 ) {
|
||||
$message .= sprintf(
|
||||
/* translators: %d: Number of additional files */
|
||||
__( "... and %d more files\n", 'wp-security-pack' ),
|
||||
count( $results ) - 20
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
$relative_path = str_replace( ABSPATH, '', $file );
|
||||
$message .= "\n" . $relative_path . ":\n";
|
||||
|
||||
foreach ( $findings as $finding ) {
|
||||
$message .= sprintf( " - [%s] %s\n", strtoupper( $finding['severity'] ), $finding['name'] );
|
||||
}
|
||||
|
||||
$count++;
|
||||
}
|
||||
|
||||
$message .= "\n" . __( "Please review these files in your WordPress admin panel under Settings > WP Security Pack.", 'wp-security-pack' );
|
||||
$message .= "\n\n" . __( "Note: Some detections may be false positives. Review each file carefully before taking action.", 'wp-security-pack' );
|
||||
|
||||
wp_mail( $email, $subject, $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get last scan results.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_last_scan_results() {
|
||||
return array(
|
||||
'time' => get_option( self::LAST_SCAN_OPTION, 0 ),
|
||||
'results' => get_option( self::RESULTS_OPTION, array() ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear scan results.
|
||||
*/
|
||||
public function clear_results() {
|
||||
delete_option( self::RESULTS_OPTION );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get severity color.
|
||||
*
|
||||
* @param string $severity Severity level.
|
||||
* @return string
|
||||
*/
|
||||
public static function get_severity_color( $severity ) {
|
||||
$colors = array(
|
||||
'critical' => '#dc3545',
|
||||
'high' => '#fd7e14',
|
||||
'medium' => '#ffc107',
|
||||
'low' => '#17a2b8',
|
||||
);
|
||||
|
||||
return isset( $colors[ $severity ] ) ? $colors[ $severity ] : '#6c757d';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
<?php
|
||||
/**
|
||||
* Two-Factor Authentication for WP Security Pack.
|
||||
*
|
||||
* @package WP_Security_Pack
|
||||
*/
|
||||
|
||||
// Prevent direct access.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Two-Factor Authentication class using TOTP.
|
||||
*/
|
||||
class WPSP_Two_Factor {
|
||||
|
||||
/**
|
||||
* User meta key for 2FA secret.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const SECRET_META_KEY = '_wpsp_2fa_secret';
|
||||
|
||||
/**
|
||||
* User meta key for 2FA enabled status.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const ENABLED_META_KEY = '_wpsp_2fa_enabled';
|
||||
|
||||
/**
|
||||
* User meta key for backup codes.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const BACKUP_CODES_META_KEY = '_wpsp_2fa_backup_codes';
|
||||
|
||||
/**
|
||||
* TOTP code length.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
const CODE_LENGTH = 6;
|
||||
|
||||
/**
|
||||
* TOTP time step (30 seconds).
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
const TIME_STEP = 30;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
if ( ! WP_Security_Pack::get_setting( 'two_factor_enabled', false ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Intercept authentication to check for 2FA - runs before cookies are set.
|
||||
add_filter( 'authenticate', array( $this, 'check_2fa_on_authenticate' ), 100, 3 );
|
||||
|
||||
// Handle the 2FA verification form.
|
||||
// Use login_form_wpsp_2fa for standard wp-login.php.
|
||||
add_action( 'login_form_wpsp_2fa', array( $this, 'render_2fa_form' ) );
|
||||
// Also check on login_init for custom login URLs.
|
||||
add_action( 'login_init', array( $this, 'maybe_render_2fa_form' ), 5 );
|
||||
|
||||
// User profile settings.
|
||||
add_action( 'show_user_profile', array( $this, 'show_user_2fa_settings' ) );
|
||||
add_action( 'edit_user_profile', array( $this, 'show_user_2fa_settings' ) );
|
||||
add_action( 'personal_options_update', array( $this, 'save_user_2fa_settings' ) );
|
||||
add_action( 'edit_user_profile_update', array( $this, 'save_user_2fa_settings' ) );
|
||||
|
||||
// AJAX handlers.
|
||||
add_action( 'wp_ajax_wpsp_generate_2fa_secret', array( $this, 'ajax_generate_secret' ) );
|
||||
add_action( 'wp_ajax_wpsp_verify_2fa_setup', array( $this, 'ajax_verify_setup' ) );
|
||||
add_action( 'wp_ajax_wpsp_disable_2fa', array( $this, 'ajax_disable_2fa' ) );
|
||||
add_action( 'wp_ajax_wpsp_regenerate_backup_codes', array( $this, 'ajax_regenerate_backup_codes' ) );
|
||||
|
||||
// Enforce 2FA for admins.
|
||||
if ( WP_Security_Pack::get_setting( 'two_factor_enforce_admin', false ) ) {
|
||||
add_action( 'admin_init', array( $this, 'enforce_admin_2fa' ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if 2FA is required during authentication.
|
||||
* This runs BEFORE cookies are set, making it reliable for 2FA.
|
||||
*
|
||||
* @param WP_User|WP_Error|null $user User object or error.
|
||||
* @param string $username Username.
|
||||
* @param string $password Password.
|
||||
* @return WP_User|WP_Error
|
||||
*/
|
||||
public function check_2fa_on_authenticate( $user, $username, $password ) {
|
||||
// If not a valid user, let WordPress handle it.
|
||||
if ( ! $user instanceof WP_User ) {
|
||||
return $user;
|
||||
}
|
||||
|
||||
// Check if 2FA is enabled for this user.
|
||||
if ( ! $this->is_2fa_enabled_for_user( $user->ID ) ) {
|
||||
return $user;
|
||||
}
|
||||
|
||||
// Generate a token for the 2FA session.
|
||||
$token = wp_generate_password( 32, false );
|
||||
|
||||
set_transient( 'wpsp_2fa_' . $token, array(
|
||||
'user_id' => $user->ID,
|
||||
'redirect' => isset( $_REQUEST['redirect_to'] ) ? esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) ) : admin_url(),
|
||||
), 5 * MINUTE_IN_SECONDS );
|
||||
|
||||
// Redirect to 2FA form immediately.
|
||||
wp_safe_redirect( add_query_arg( array(
|
||||
'action' => 'wpsp_2fa',
|
||||
'token' => $token,
|
||||
), wp_login_url() ) );
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforce 2FA setup for administrators.
|
||||
*/
|
||||
public function enforce_admin_2fa() {
|
||||
// Skip AJAX requests.
|
||||
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$user = wp_get_current_user();
|
||||
|
||||
// Only apply to administrators.
|
||||
if ( ! $user || ! user_can( $user, 'manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip if already has 2FA enabled.
|
||||
if ( $this->is_2fa_enabled_for_user( $user->ID ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Allow access to profile page for setup.
|
||||
global $pagenow;
|
||||
if ( 'profile.php' === $pagenow || 'admin-ajax.php' === $pagenow ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Redirect to profile page with notice.
|
||||
wp_safe_redirect( add_query_arg( 'wpsp_2fa_required', '1', admin_url( 'profile.php' ) ) );
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if we should render the 2FA form (for custom login URLs).
|
||||
*/
|
||||
public function maybe_render_2fa_form() {
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
if ( isset( $_GET['action'] ) && 'wpsp_2fa' === $_GET['action'] ) {
|
||||
$this->render_2fa_form();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render 2FA verification form.
|
||||
*/
|
||||
public function render_2fa_form() {
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
$token = isset( $_GET['token'] ) ? sanitize_text_field( wp_unslash( $_GET['token'] ) ) : '';
|
||||
|
||||
if ( empty( $token ) ) {
|
||||
wp_safe_redirect( wp_login_url() );
|
||||
exit;
|
||||
}
|
||||
|
||||
$data = get_transient( 'wpsp_2fa_' . $token );
|
||||
|
||||
if ( ! $data ) {
|
||||
wp_safe_redirect( wp_login_url() );
|
||||
exit;
|
||||
}
|
||||
|
||||
$error = '';
|
||||
|
||||
// Handle form submission.
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Missing
|
||||
if ( isset( $_POST['wpsp_2fa_code'] ) || isset( $_POST['wpsp_backup_code'] ) ) {
|
||||
// Check TOTP code first, then backup code.
|
||||
$code = '';
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Missing
|
||||
if ( ! empty( $_POST['wpsp_2fa_code'] ) ) {
|
||||
$code = sanitize_text_field( wp_unslash( $_POST['wpsp_2fa_code'] ) );
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Missing
|
||||
} elseif ( ! empty( $_POST['wpsp_backup_code'] ) ) {
|
||||
$code = sanitize_text_field( wp_unslash( $_POST['wpsp_backup_code'] ) );
|
||||
}
|
||||
|
||||
$user_id = $data['user_id'];
|
||||
|
||||
if ( ! empty( $code ) && $this->verify_code( $user_id, $code ) ) {
|
||||
// Delete the token.
|
||||
delete_transient( 'wpsp_2fa_' . $token );
|
||||
|
||||
// Log the user in.
|
||||
wp_set_auth_cookie( $user_id, false );
|
||||
wp_set_current_user( $user_id );
|
||||
|
||||
// Redirect.
|
||||
wp_safe_redirect( $data['redirect'] );
|
||||
exit;
|
||||
}
|
||||
|
||||
$error = __( 'Invalid verification code.', 'wp-security-pack' );
|
||||
}
|
||||
|
||||
// Render the form.
|
||||
login_header( __( 'Two-Factor Authentication', 'wp-security-pack' ) );
|
||||
?>
|
||||
<form name="wpsp_2fa_form" id="wpsp_2fa_form" action="" method="post">
|
||||
<?php if ( $error ) : ?>
|
||||
<div id="login_error"><?php echo esc_html( $error ); ?></div>
|
||||
<?php endif; ?>
|
||||
|
||||
<p><?php esc_html_e( 'Enter the verification code from your authenticator app.', 'wp-security-pack' ); ?></p>
|
||||
|
||||
<p>
|
||||
<label for="wpsp_2fa_code"><?php esc_html_e( 'Verification Code', 'wp-security-pack' ); ?></label>
|
||||
<input type="text" name="wpsp_2fa_code" id="wpsp_2fa_code" class="input" size="20" autocomplete="one-time-code" inputmode="numeric" pattern="[0-9]*" autofocus />
|
||||
</p>
|
||||
|
||||
<p class="submit">
|
||||
<input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="<?php esc_attr_e( 'Verify', 'wp-security-pack' ); ?>" />
|
||||
</p>
|
||||
|
||||
<p class="wpsp-backup-code-link">
|
||||
<a href="#" onclick="document.getElementById('wpsp-backup-field').style.display='block';this.style.display='none';return false;">
|
||||
<?php esc_html_e( 'Use a backup code', 'wp-security-pack' ); ?>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<div id="wpsp-backup-field" style="display:none;">
|
||||
<p><?php esc_html_e( 'Or enter a backup code:', 'wp-security-pack' ); ?></p>
|
||||
<p>
|
||||
<input type="text" name="wpsp_backup_code" id="wpsp_backup_code" class="input" size="20" />
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
<?php
|
||||
login_footer();
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show 2FA settings on user profile.
|
||||
*
|
||||
* @param WP_User $user User object.
|
||||
*/
|
||||
public function show_user_2fa_settings( $user ) {
|
||||
if ( ! WP_Security_Pack::get_setting( 'two_factor_enabled', false ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$is_enabled = $this->is_2fa_enabled_for_user( $user->ID );
|
||||
|
||||
// Show notice if 2FA is required.
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
if ( isset( $_GET['wpsp_2fa_required'] ) && ! $is_enabled ) :
|
||||
?>
|
||||
<div class="notice notice-warning" style="margin-bottom: 20px;">
|
||||
<p><strong><?php esc_html_e( 'Two-Factor Authentication Required', 'wp-security-pack' ); ?></strong></p>
|
||||
<p><?php esc_html_e( 'As an administrator, you are required to set up Two-Factor Authentication before you can access the dashboard.', 'wp-security-pack' ); ?></p>
|
||||
</div>
|
||||
<?php
|
||||
endif;
|
||||
?>
|
||||
<h2><?php esc_html_e( 'Two-Factor Authentication', 'wp-security-pack' ); ?></h2>
|
||||
<table class="form-table" role="presentation">
|
||||
<tr>
|
||||
<th scope="row"><?php esc_html_e( 'Status', 'wp-security-pack' ); ?></th>
|
||||
<td>
|
||||
<?php if ( $is_enabled ) : ?>
|
||||
<?php $remaining_codes = $this->get_backup_codes_count( $user->ID ); ?>
|
||||
<span class="wpsp-2fa-status wpsp-2fa-enabled"><?php esc_html_e( 'Enabled', 'wp-security-pack' ); ?></span>
|
||||
<p>
|
||||
<button type="button" class="button" id="wpsp-disable-2fa"><?php esc_html_e( 'Disable 2FA', 'wp-security-pack' ); ?></button>
|
||||
<button type="button" class="button" id="wpsp-regenerate-backup-codes"><?php esc_html_e( 'Regenerate Backup Codes', 'wp-security-pack' ); ?></button>
|
||||
</p>
|
||||
<p class="description">
|
||||
<?php
|
||||
printf(
|
||||
/* translators: %d: number of remaining backup codes */
|
||||
esc_html__( 'You have %d backup codes remaining.', 'wp-security-pack' ),
|
||||
$remaining_codes
|
||||
);
|
||||
?>
|
||||
<?php if ( $remaining_codes < 3 ) : ?>
|
||||
<strong style="color: #dc3232;"><?php esc_html_e( 'Consider regenerating your backup codes.', 'wp-security-pack' ); ?></strong>
|
||||
<?php endif; ?>
|
||||
</p>
|
||||
<div id="wpsp-backup-codes-display" style="display:none; background: #f6f7f7; padding: 15px; margin-top: 10px; border-radius: 4px;">
|
||||
<p><strong><?php esc_html_e( 'New Backup Codes:', 'wp-security-pack' ); ?></strong></p>
|
||||
<pre id="wpsp-new-backup-codes" style="background: #fff; padding: 10px;"></pre>
|
||||
<p class="description" style="color: #dc3232;">
|
||||
<strong><?php esc_html_e( 'IMPORTANT: Save these codes now!', 'wp-security-pack' ); ?></strong><br>
|
||||
<?php esc_html_e( 'These codes will NOT be shown again. Store them in a safe place.', 'wp-security-pack' ); ?>
|
||||
</p>
|
||||
</div>
|
||||
<?php else : ?>
|
||||
<span class="wpsp-2fa-status wpsp-2fa-disabled"><?php esc_html_e( 'Disabled', 'wp-security-pack' ); ?></span>
|
||||
<p>
|
||||
<button type="button" class="button button-primary" id="wpsp-setup-2fa"><?php esc_html_e( 'Set Up 2FA', 'wp-security-pack' ); ?></button>
|
||||
</p>
|
||||
<div id="wpsp-2fa-setup" style="display:none;">
|
||||
<p><?php esc_html_e( 'Scan this QR code with your authenticator app:', 'wp-security-pack' ); ?></p>
|
||||
<div id="wpsp-2fa-qr"></div>
|
||||
<p><strong><?php esc_html_e( 'Manual entry key:', 'wp-security-pack' ); ?></strong> <code id="wpsp-2fa-secret"></code></p>
|
||||
<p>
|
||||
<label for="wpsp-2fa-verify-code"><?php esc_html_e( 'Enter verification code to confirm:', 'wp-security-pack' ); ?></label>
|
||||
<input type="text" id="wpsp-2fa-verify-code" class="regular-text" autocomplete="off" />
|
||||
<button type="button" class="button button-primary" id="wpsp-verify-2fa-setup"><?php esc_html_e( 'Verify & Enable', 'wp-security-pack' ); ?></button>
|
||||
</p>
|
||||
<div id="wpsp-2fa-setup-result"></div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<script src="https://cdn.jsdelivr.net/npm/qrcode-generator@1.4.4/qrcode.min.js"></script>
|
||||
<script>
|
||||
jQuery(document).ready(function($) {
|
||||
$('#wpsp-setup-2fa').on('click', function() {
|
||||
$('#wpsp-2fa-setup').show();
|
||||
$(this).hide();
|
||||
|
||||
// Generate new secret.
|
||||
$.post(ajaxurl, {
|
||||
action: 'wpsp_generate_2fa_secret',
|
||||
user_id: <?php echo (int) $user->ID; ?>,
|
||||
_ajax_nonce: '<?php echo esc_js( wp_create_nonce( 'wpsp_2fa_setup' ) ); ?>'
|
||||
}, function(response) {
|
||||
if (response.success) {
|
||||
$('#wpsp-2fa-secret').text(response.data.secret);
|
||||
|
||||
// Generate QR code client-side.
|
||||
var qr = qrcode(0, 'M');
|
||||
qr.addData(response.data.otpauth);
|
||||
qr.make();
|
||||
$('#wpsp-2fa-qr').html(qr.createSvgTag(5, 0));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$('#wpsp-verify-2fa-setup').on('click', function() {
|
||||
var code = $('#wpsp-2fa-verify-code').val();
|
||||
$.post(ajaxurl, {
|
||||
action: 'wpsp_verify_2fa_setup',
|
||||
user_id: <?php echo (int) $user->ID; ?>,
|
||||
code: code,
|
||||
_ajax_nonce: '<?php echo esc_js( wp_create_nonce( 'wpsp_2fa_setup' ) ); ?>'
|
||||
}, function(response) {
|
||||
if (response.success && response.data.backup_codes) {
|
||||
// Show backup codes - user MUST save these.
|
||||
var codesHtml = '<div style="background:#d4edda;border:1px solid #c3e6cb;padding:20px;margin:10px 0;border-radius:4px;">';
|
||||
codesHtml += '<h3 style="margin-top:0;color:#155724;"><?php echo esc_js( __( '2FA Enabled! Save Your Backup Codes', 'wp-security-pack' ) ); ?></h3>';
|
||||
codesHtml += '<p style="color:#dc3232;font-weight:bold;"><?php echo esc_js( __( 'IMPORTANT: These codes will NOT be shown again!', 'wp-security-pack' ) ); ?></p>';
|
||||
codesHtml += '<pre style="background:#fff;padding:15px;font-size:14px;line-height:1.8;">' + response.data.backup_codes.join('\n') + '</pre>';
|
||||
codesHtml += '<p><?php echo esc_js( __( 'Store these codes in a safe place. Each code can only be used once.', 'wp-security-pack' ) ); ?></p>';
|
||||
codesHtml += '<button type="button" class="button button-primary" onclick="location.reload();"><?php echo esc_js( __( 'I have saved my codes', 'wp-security-pack' ) ); ?></button>';
|
||||
codesHtml += '</div>';
|
||||
$('#wpsp-2fa-setup').html(codesHtml);
|
||||
} else if (response.success) {
|
||||
location.reload();
|
||||
} else {
|
||||
$('#wpsp-2fa-setup-result').html('<p style="color:red;">' + response.data.message + '</p>');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$('#wpsp-disable-2fa').on('click', function() {
|
||||
if (confirm('<?php echo esc_js( __( 'Are you sure you want to disable 2FA?', 'wp-security-pack' ) ); ?>')) {
|
||||
$.post(ajaxurl, {
|
||||
action: 'wpsp_disable_2fa',
|
||||
user_id: <?php echo (int) $user->ID; ?>,
|
||||
_ajax_nonce: '<?php echo esc_js( wp_create_nonce( 'wpsp_2fa_setup' ) ); ?>'
|
||||
}, function(response) {
|
||||
if (response.success) {
|
||||
location.reload();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
$('#wpsp-regenerate-backup-codes').on('click', function() {
|
||||
if (confirm('<?php echo esc_js( __( 'This will invalidate all existing backup codes. Are you sure?', 'wp-security-pack' ) ); ?>')) {
|
||||
$.post(ajaxurl, {
|
||||
action: 'wpsp_regenerate_backup_codes',
|
||||
user_id: <?php echo (int) $user->ID; ?>,
|
||||
_ajax_nonce: '<?php echo esc_js( wp_create_nonce( 'wpsp_2fa_setup' ) ); ?>'
|
||||
}, function(response) {
|
||||
if (response.success) {
|
||||
$('#wpsp-new-backup-codes').text(response.data.codes.join('\n'));
|
||||
$('#wpsp-backup-codes-display').show();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Save user 2FA settings.
|
||||
*
|
||||
* @param int $user_id User ID.
|
||||
*/
|
||||
public function save_user_2fa_settings( $user_id ) {
|
||||
// Settings are saved via AJAX.
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate new 2FA secret via AJAX.
|
||||
*/
|
||||
public function ajax_generate_secret() {
|
||||
check_ajax_referer( 'wpsp_2fa_setup' );
|
||||
|
||||
$user_id = isset( $_POST['user_id'] ) ? (int) $_POST['user_id'] : 0;
|
||||
|
||||
if ( ! current_user_can( 'edit_user', $user_id ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Permission denied.', 'wp-security-pack' ) ) );
|
||||
}
|
||||
|
||||
$secret = $this->generate_secret();
|
||||
|
||||
// Store temporarily (not enabled yet).
|
||||
update_user_meta( $user_id, self::SECRET_META_KEY . '_pending', $secret );
|
||||
|
||||
$user = get_user_by( 'id', $user_id );
|
||||
$site = wp_parse_url( home_url(), PHP_URL_HOST );
|
||||
|
||||
// Generate otpauth URL for QR code.
|
||||
$otpauth = sprintf(
|
||||
'otpauth://totp/%s:%s?secret=%s&issuer=%s',
|
||||
rawurlencode( $site ),
|
||||
rawurlencode( $user->user_email ),
|
||||
$secret,
|
||||
rawurlencode( $site )
|
||||
);
|
||||
|
||||
wp_send_json_success( array(
|
||||
'secret' => $secret,
|
||||
'otpauth' => $otpauth,
|
||||
) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify 2FA setup via AJAX.
|
||||
*/
|
||||
public function ajax_verify_setup() {
|
||||
check_ajax_referer( 'wpsp_2fa_setup' );
|
||||
|
||||
$user_id = isset( $_POST['user_id'] ) ? (int) $_POST['user_id'] : 0;
|
||||
$code = isset( $_POST['code'] ) ? sanitize_text_field( wp_unslash( $_POST['code'] ) ) : '';
|
||||
|
||||
if ( ! current_user_can( 'edit_user', $user_id ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Permission denied.', 'wp-security-pack' ) ) );
|
||||
}
|
||||
|
||||
$pending_secret = get_user_meta( $user_id, self::SECRET_META_KEY . '_pending', true );
|
||||
|
||||
if ( empty( $pending_secret ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'No pending setup found.', 'wp-security-pack' ) ) );
|
||||
}
|
||||
|
||||
// Verify the code.
|
||||
if ( ! $this->verify_totp( $pending_secret, $code ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Invalid code. Please try again.', 'wp-security-pack' ) ) );
|
||||
}
|
||||
|
||||
// Enable 2FA.
|
||||
update_user_meta( $user_id, self::SECRET_META_KEY, $pending_secret );
|
||||
update_user_meta( $user_id, self::ENABLED_META_KEY, '1' );
|
||||
delete_user_meta( $user_id, self::SECRET_META_KEY . '_pending' );
|
||||
|
||||
// Generate backup codes - show plain to user, store hashed.
|
||||
$plain_codes = $this->generate_backup_codes();
|
||||
$hashed_codes = array_map( array( $this, 'hash_backup_code' ), $plain_codes );
|
||||
update_user_meta( $user_id, self::BACKUP_CODES_META_KEY, $hashed_codes );
|
||||
|
||||
wp_send_json_success( array(
|
||||
'message' => __( '2FA enabled successfully. Save your backup codes now - they will not be shown again!', 'wp-security-pack' ),
|
||||
'backup_codes' => $plain_codes,
|
||||
'show_codes' => true,
|
||||
) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable 2FA via AJAX.
|
||||
*/
|
||||
public function ajax_disable_2fa() {
|
||||
check_ajax_referer( 'wpsp_2fa_setup' );
|
||||
|
||||
$user_id = isset( $_POST['user_id'] ) ? (int) $_POST['user_id'] : 0;
|
||||
|
||||
if ( ! current_user_can( 'edit_user', $user_id ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Permission denied.', 'wp-security-pack' ) ) );
|
||||
}
|
||||
|
||||
delete_user_meta( $user_id, self::SECRET_META_KEY );
|
||||
delete_user_meta( $user_id, self::ENABLED_META_KEY );
|
||||
delete_user_meta( $user_id, self::BACKUP_CODES_META_KEY );
|
||||
|
||||
wp_send_json_success( array( 'message' => __( '2FA disabled.', 'wp-security-pack' ) ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate backup codes via AJAX.
|
||||
*/
|
||||
public function ajax_regenerate_backup_codes() {
|
||||
check_ajax_referer( 'wpsp_2fa_setup' );
|
||||
|
||||
$user_id = isset( $_POST['user_id'] ) ? (int) $_POST['user_id'] : 0;
|
||||
|
||||
if ( ! current_user_can( 'edit_user', $user_id ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Permission denied.', 'wp-security-pack' ) ) );
|
||||
}
|
||||
|
||||
// Generate new codes.
|
||||
$plain_codes = $this->generate_backup_codes();
|
||||
|
||||
// Hash them before storing.
|
||||
$hashed_codes = array_map( array( $this, 'hash_backup_code' ), $plain_codes );
|
||||
update_user_meta( $user_id, self::BACKUP_CODES_META_KEY, $hashed_codes );
|
||||
|
||||
// Return plain codes to show user ONCE.
|
||||
wp_send_json_success( array(
|
||||
'codes' => $plain_codes,
|
||||
'message' => __( 'Backup codes regenerated. Save these codes now - they will not be shown again.', 'wp-security-pack' ),
|
||||
) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if 2FA is enabled for a user.
|
||||
*
|
||||
* @param int $user_id User ID.
|
||||
* @return bool
|
||||
*/
|
||||
public function is_2fa_enabled_for_user( $user_id ) {
|
||||
return '1' === get_user_meta( $user_id, self::ENABLED_META_KEY, true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a code (TOTP or backup).
|
||||
*
|
||||
* @param int $user_id User ID.
|
||||
* @param string $code Code to verify.
|
||||
* @return bool
|
||||
*/
|
||||
public function verify_code( $user_id, $code ) {
|
||||
$code = preg_replace( '/\s+/', '', $code );
|
||||
|
||||
// Try TOTP first.
|
||||
$secret = get_user_meta( $user_id, self::SECRET_META_KEY, true );
|
||||
|
||||
if ( $this->verify_totp( $secret, $code ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Try backup code.
|
||||
return $this->verify_backup_code( $user_id, $code );
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify TOTP code.
|
||||
*
|
||||
* @param string $secret Secret key.
|
||||
* @param string $code Code to verify.
|
||||
* @param int $window Time window tolerance.
|
||||
* @return bool
|
||||
*/
|
||||
private function verify_totp( $secret, $code, $window = 1 ) {
|
||||
if ( empty( $secret ) || empty( $code ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$time = floor( time() / self::TIME_STEP );
|
||||
|
||||
for ( $i = -$window; $i <= $window; $i++ ) {
|
||||
$calculated = $this->calculate_totp( $secret, $time + $i );
|
||||
if ( hash_equals( $calculated, $code ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate TOTP code.
|
||||
*
|
||||
* @param string $secret Secret key.
|
||||
* @param int $time Time counter.
|
||||
* @return string
|
||||
*/
|
||||
private function calculate_totp( $secret, $time ) {
|
||||
// Decode base32 secret.
|
||||
$secret_decoded = $this->base32_decode( $secret );
|
||||
|
||||
// Pack time.
|
||||
$time_packed = pack( 'N*', 0, $time );
|
||||
|
||||
// Calculate HMAC.
|
||||
$hash = hash_hmac( 'sha1', $time_packed, $secret_decoded, true );
|
||||
|
||||
// Dynamic truncation.
|
||||
$offset = ord( substr( $hash, -1 ) ) & 0x0F;
|
||||
$code = ( ord( $hash[ $offset ] ) & 0x7F ) << 24;
|
||||
$code |= ( ord( $hash[ $offset + 1 ] ) & 0xFF ) << 16;
|
||||
$code |= ( ord( $hash[ $offset + 2 ] ) & 0xFF ) << 8;
|
||||
$code |= ( ord( $hash[ $offset + 3 ] ) & 0xFF );
|
||||
$code = $code % pow( 10, self::CODE_LENGTH );
|
||||
|
||||
return str_pad( $code, self::CODE_LENGTH, '0', STR_PAD_LEFT );
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate secret key.
|
||||
*
|
||||
* @param int $length Length in bytes (16 = 26 base32 chars).
|
||||
* @return string
|
||||
*/
|
||||
private function generate_secret( $length = 16 ) {
|
||||
$random = wp_generate_password( $length, false, false );
|
||||
return $this->base32_encode( $random );
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate backup codes.
|
||||
*
|
||||
* @param int $count Number of codes.
|
||||
* @return array
|
||||
*/
|
||||
private function generate_backup_codes( $count = 10 ) {
|
||||
$codes = array();
|
||||
for ( $i = 0; $i < $count; $i++ ) {
|
||||
$codes[] = strtoupper( wp_generate_password( 8, false, false ) );
|
||||
}
|
||||
return $codes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get backup codes count for user (hashed codes stored).
|
||||
*
|
||||
* @param int $user_id User ID.
|
||||
* @return int
|
||||
*/
|
||||
public function get_backup_codes_count( $user_id ) {
|
||||
$codes = get_user_meta( $user_id, self::BACKUP_CODES_META_KEY, true );
|
||||
return is_array( $codes ) ? count( $codes ) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get backup codes for user (internal use only).
|
||||
*
|
||||
* @param int $user_id User ID.
|
||||
* @return array
|
||||
*/
|
||||
private function get_backup_codes( $user_id ) {
|
||||
$codes = get_user_meta( $user_id, self::BACKUP_CODES_META_KEY, true );
|
||||
return is_array( $codes ) ? $codes : array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash a backup code for secure storage.
|
||||
*
|
||||
* @param string $code Plain backup code.
|
||||
* @return string Hashed code.
|
||||
*/
|
||||
private function hash_backup_code( $code ) {
|
||||
return wp_hash( strtoupper( $code ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify and consume a backup code.
|
||||
*
|
||||
* @param int $user_id User ID.
|
||||
* @param string $code Backup code.
|
||||
* @return bool
|
||||
*/
|
||||
private function verify_backup_code( $user_id, $code ) {
|
||||
$stored_codes = $this->get_backup_codes( $user_id );
|
||||
$code = strtoupper( preg_replace( '/[^A-Z0-9]/', '', $code ) );
|
||||
$hashed_input = $this->hash_backup_code( $code );
|
||||
|
||||
// Check against hashed codes.
|
||||
foreach ( $stored_codes as $index => $stored_code ) {
|
||||
// Support both hashed (new) and plain (legacy) codes.
|
||||
if ( hash_equals( $stored_code, $hashed_input ) || hash_equals( $stored_code, $code ) ) {
|
||||
// Remove used code.
|
||||
unset( $stored_codes[ $index ] );
|
||||
update_user_meta( $user_id, self::BACKUP_CODES_META_KEY, array_values( $stored_codes ) );
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base32 encode.
|
||||
*
|
||||
* @param string $data Data to encode.
|
||||
* @return string
|
||||
*/
|
||||
private function base32_encode( $data ) {
|
||||
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
$binary = '';
|
||||
$encoded = '';
|
||||
|
||||
foreach ( str_split( $data ) as $char ) {
|
||||
$binary .= str_pad( decbin( ord( $char ) ), 8, '0', STR_PAD_LEFT );
|
||||
}
|
||||
|
||||
$chunks = str_split( $binary, 5 );
|
||||
|
||||
foreach ( $chunks as $chunk ) {
|
||||
$chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT );
|
||||
$encoded .= $alphabet[ bindec( $chunk ) ];
|
||||
}
|
||||
|
||||
return $encoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base32 decode.
|
||||
*
|
||||
* @param string $data Data to decode.
|
||||
* @return string
|
||||
*/
|
||||
private function base32_decode( $data ) {
|
||||
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
$data = strtoupper( $data );
|
||||
$binary = '';
|
||||
$decoded = '';
|
||||
|
||||
foreach ( str_split( $data ) as $char ) {
|
||||
$pos = strpos( $alphabet, $char );
|
||||
if ( false !== $pos ) {
|
||||
$binary .= str_pad( decbin( $pos ), 5, '0', STR_PAD_LEFT );
|
||||
}
|
||||
}
|
||||
|
||||
$chunks = str_split( $binary, 8 );
|
||||
|
||||
foreach ( $chunks as $chunk ) {
|
||||
if ( strlen( $chunk ) === 8 ) {
|
||||
$decoded .= chr( bindec( $chunk ) );
|
||||
}
|
||||
}
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
/**
|
||||
* Silence is golden.
|
||||
*
|
||||
* @package WP_Security_Pack
|
||||
*/
|
||||
Reference in New Issue
Block a user