'anthropic', 'model' => '', 'custom_base_url' => '', 'custom_model' => '', 'custom_needs_key' => 1, 'ai_effort' => 'medium', 'ai_max_tokens' => 6000, 'ai_snippet_chars' => 12000, 'ai_timeout' => 120, 'ai_auto_after_scan' => 0, 'ai_max_items' => 20, 'ai_consent' => 0, // Scanner. 'scan_schedule' => 'daily', 'scan_hour' => 3, 'scan_max_file_size' => 5, 'scan_skip_dirs' => "wp-content/cache\nwp-content/uploads/ai-guardwall\nwp-content/backups\nwp-content/updraft\nwp-content/ai1wm-backups\nwp-content/upgrade\nnode_modules\n.git", 'scan_time_budget' => 12, 'scan_deep_media' => 0, 'scan_file_changes' => 1, 'scan_vulnerabilities' => 0, 'scan_abandoned' => 1, 'scan_exposed_files' => 1, 'scan_weak_passwords' => 1, 'scan_reputation' => 0, 'scan_custom_signatures' => '', 'scan_exclude' => '', // Firewall. 'firewall_mode' => 'block', 'firewall_inspect_logged_in' => 0, 'firewall_rules' => array( 'sqli' => 1, 'xss' => 1, 'lfi' => 1, 'rce' => 1, 'upload' => 1, 'scanner_ua' => 1, 'bad_paths' => 1, 'php_in_uploads' => 1, 'xmlrpc_multicall' => 1, ), 'firewall_allowlist_urls' => '', 'firewall_allowlist_ips' => '', 'firewall_blocklist_ips' => '', 'firewall_block_countries' => '', 'firewall_block_empty_ua' => 1, 'firewall_hits_to_block' => 5, 'firewall_hits_window' => 10, 'firewall_block_minutes' => 60, 'firewall_rate_requests' => 0, 'firewall_rate_404' => 40, 'firewall_rate_window' => 60, 'firewall_rate_block_minutes' => 15, 'firewall_extended' => 0, 'ip_source' => 'auto', 'trusted_proxies' => '', 'firewall_learning_until' => '', 'firewall_block_uas' => '', 'firewall_block_referrers' => '', 'firewall_block_hosts' => '', 'firewall_block_methods' => 1, 'firewall_block_blank_post' => 0, 'firewall_trap_urls' => '', 'firewall_trap_minutes' => 1440, 'firewall_fake_bots' => 1, 'firewall_verified_bots_exempt' => 1, 'firewall_rate_crawlers' => 0, 'firewall_rate_404_crawlers' => 0, 'firewall_block_message' => '', 'firewall_feed_urls' => '', 'country_mode' => 'block', 'country_scope' => 'site', 'country_action' => 'block', 'country_redirect_url' => '', 'country_bypass_key' => '', 'country_logged_in' => 0, 'country_source' => 'auto', // Live traffic. 'traffic_mode' => 'security', 'traffic_ignore_logged_in' => 1, 'traffic_ignore_ips' => '', 'traffic_ignore_uas' => '', 'traffic_max_days' => 14, 'traffic_max_rows' => 50000, // Login security. 'login_max_attempts' => 5, 'login_lockout_minutes' => 20, 'login_count_window_minutes' => 60, 'login_max_lockouts' => 3, 'login_long_lockout_hours' => 24, 'login_block_usernames' => "admin\nadministrator\ntest\nroot\nuser\ndemo\nwpadmin", 'login_min_password_length' => 12, 'login_allowlist_ips' => '', 'login_max_lostpw' => 10, 'login_unlock_requests' => 1, 'login_door_word' => '', 'http_auth_user' => '', 'http_auth_scope' => 'admin', 'session_max_hours' => 72, 'passkeys_roles' => array(), 'twofa_xmlrpc' => 'block_2fa', 'twofa_brand_logo' => 1, 'twofa_brand_color' => '', 'twofa_brand_message' => '', // CAPTCHA, comments, registration. 'captcha_provider' => 'math', 'captcha_site_key' => '', 'captcha_v3_threshold' => 5, 'captcha_forms' => array( 'login', 'register', 'lostpassword' ), 'captcha_hide_badge' => 0, 'comment_spam_action' => 'spam', 'comment_min_seconds' => 3, 'comment_trash_days' => 14, 'comment_block_after' => 3, 'comment_block_minutes' => 1440, 'comment_block_proxies' => 0, 'reg_honeypot' => 1, 'reg_block_names' => "admin\nadministrator\nroot\nwebmaster\nsupport\nsysadmin", // Two-factor. 'twofa_roles' => array( 'administrator' ), 'twofa_methods' => array( 'totp', 'email' ), 'twofa_grace_days' => 7, 'twofa_remember_days' => 0, // Hidden login URL. 'login_slug' => 'secure-login', 'login_redirect_slug' => '404', 'hide_wp_admin' => 1, // Hardening (rule id => on/off), merged with the registry defaults. 'hardening' => array(), 'headers_csp' => '', 'headers_hsts_max_age' => 31536000, 'rest_allowlist' => "oembed/1.0\ncontact-form-7/v1\njetpack/v4\nwc/store\nwc/store/v1\nelementor/v1\nwp-site-health/v1\nwp/v2/block-renderer\nsoftvoltai-voice-agent/v1", 'idle_logout_minutes' => 60, 'upload_block_svg' => 0, 'upload_block_html' => 1, 'admin_ip_allowlist' => '', // Alerts. 'alert_email' => '', 'alert_on_scan' => 1, 'alert_on_lockout' => 0, 'alert_on_admin_login' => 0, 'alert_on_new_admin' => 1, 'alert_on_plugin_change' => 0, 'alert_on_file_change' => 1, 'alert_on_attack_surge' => 1, 'alert_surge_count' => 100, 'alert_surge_minutes' => 10, 'alert_on_nonadmin_login' => 0, 'alert_login_first_only' => 1, 'alert_on_lost_password' => 0, 'alert_on_breached' => 1, 'alert_on_firewall_off' => 1, 'alert_on_vulnerable' => 1, 'alert_on_monitor' => 1, 'alert_max_per_hour' => 10, 'alert_summary' => 'off', 'monitor_slow_ms' => 4000, 'salt_rotate_days' => 0, // Advanced. 'activity_log_enabled' => 1, 'log_retention_days' => 30, 'delete_on_uninstall' => 0, 'activated_at' => 0, ); } /** * The settings, merged with the defaults. * * @since 1.0.0 * @param string|null $key One setting, or all of them. * @param mixed $default Returned when the key is unknown. * @return mixed */ public static function get( $key = null, $default = null ) { if ( null === self::$cache ) { $saved = get_option( self::OPTION, array() ); $saved = is_array( $saved ) ? $saved : array(); self::$cache = wp_parse_args( $saved, self::defaults() ); // Nested maps: new rule ids get their defaults. self::$cache['firewall_rules'] = array_merge( self::defaults()['firewall_rules'], isset( $saved['firewall_rules'] ) && is_array( $saved['firewall_rules'] ) ? $saved['firewall_rules'] : array() ); if ( ! is_array( self::$cache['hardening'] ) ) { self::$cache['hardening'] = array(); } /** * The settings in use for this request. An add-on can change them; * call flush() after changing what the filter returns. * * @since 1.0.0 * @param array $settings The saved settings merged with the defaults. */ $filtered = apply_filters( 'svabg_settings', self::$cache ); self::$cache = is_array( $filtered ) ? wp_parse_args( $filtered, self::defaults() ) : self::$cache; // Safe mode (define( 'SVABG_SAFE_MODE', true ) in wp-config.php): no request inspection. if ( self::safe_mode() ) { self::$cache['firewall_mode'] = 'off'; } } if ( null === $key ) { return self::$cache; } return array_key_exists( $key, self::$cache ) ? self::$cache[ $key ] : $default; } /** * All settings. * * @since 1.0.0 * @return array */ public static function all() { return self::get(); } /** * Save one setting straight away (used by the REST actions; the settings * form goes through sanitize()). * * @since 1.0.0 * @param string $key Setting. * @param mixed $value Value. */ public static function set( $key, $value ) { self::update( array( $key => $value ) ); } /** * Save several settings straight away. * * @since 1.0.0 * @param array $pairs key => value. */ public static function update( array $pairs ) { $saved = get_option( self::OPTION, array() ); $saved = is_array( $saved ) ? $saved : array(); foreach ( $pairs as $key => $value ) { $saved[ $key ] = $value; } update_option( self::OPTION, $saved ); self::flush(); } /** * Forget the settings read for this request, after they change. * * @since 1.0.0 */ public static function flush() { self::$cache = null; } /** * True when a hardening rule is switched on (falls back to the registry default). * * @since 1.0.0 * @param string $rule_id Rule id. * @return bool */ public static function hardening_enabled( $rule_id ) { if ( self::safe_mode() ) { return false; // Every protection is off while the owner repairs a lockout. } $map = self::get( 'hardening', array() ); if ( is_array( $map ) && array_key_exists( $rule_id, $map ) ) { return (bool) $map[ $rule_id ]; } $defaults = Softvolt_Ai_Bodyguard_Hardening::defaults(); return ! empty( $defaults[ $rule_id ] ); } /** * The way back in after a lockout: define( 'SVABG_SAFE_MODE', true ) in wp-config.php * switches every protection off in PHP (server rules in .htaccess stay). * * @since 1.4.0 * @return bool */ public static function safe_mode() { return defined( 'SVABG_SAFE_MODE' ) && SVABG_SAFE_MODE; } /** * Switch one hardening rule on or off. * * @since 1.0.0 * @param string $rule_id Rule id. * @param bool $enabled On or off. */ public static function set_hardening( $rule_id, $enabled ) { $map = self::get( 'hardening', array() ); $map = is_array( $map ) ? $map : array(); $map[ $rule_id ] = (bool) $enabled; self::set( 'hardening', $map ); } /** * Where alerts go. * * @since 1.0.0 * @return string */ public static function alert_email() { $email = self::get( 'alert_email', '' ); return is_email( $email ) ? $email : get_option( 'admin_email' ); } /** * A newline/comma separated text as a list. * * @since 1.0.0 * @param string $text Text. * @return array */ public static function list_to_array( $text ) { $items = preg_split( '/[\r\n,]+/', (string) $text ); $out = array(); foreach ( $items as $item ) { $item = trim( $item ); if ( '' !== $item ) { $out[] = $item; } } return array_values( array_unique( $out ) ); } /** * The model in use: the chosen one, or the provider's default. * * @since 1.0.0 * @return string */ public static function model() { $provider_id = (string) self::get( 'provider' ); if ( 'custom' === $provider_id ) { return (string) self::get( 'custom_model' ); } $model = (string) self::get( 'model' ); if ( '' !== $model ) { return $model; } $provider = Softvolt_Ai_Bodyguard_Catalog::provider( $provider_id ); return $provider ? (string) $provider['default_model'] : ''; } /** * Whether an AI provider, model and key are in place. * * @since 1.0.0 * @return bool */ public static function is_configured() { $provider_id = (string) self::get( 'provider' ); // Claude Desktop needs no key and no model here: Claude chooses its model in the chat. if ( Softvolt_Ai_Bodyguard_Claude::PROVIDER === $provider_id ) { return Softvolt_Ai_Bodyguard_Claude::abilities_api(); } if ( '' === self::model() ) { return false; } if ( 'custom' === $provider_id ) { if ( '' === (string) self::get( 'custom_base_url' ) ) { return false; } return ! self::get( 'custom_needs_key' ) || self::has_secret( 'key_custom' ); } if ( ! Softvolt_Ai_Bodyguard_Catalog::provider( $provider_id ) ) { return false; } return self::has_secret( 'key_' . $provider_id ); } /* * --------------------------------------------------------------------- * Cleaning what the settings form sends. * --------------------------------------------------------------------- */ /** * Field types for the settings form. * * @return array key => type definition */ private static function schema() { return array( 'provider' => 'provider', 'model' => 'model', 'custom_base_url' => 'url', 'custom_model' => 'model', 'custom_needs_key' => 'bool', 'ai_effort' => array( 'select', array( 'low', 'medium', 'high' ) ), 'ai_max_tokens' => array( 'int', 1000, 64000 ), 'ai_snippet_chars' => array( 'int', 2000, 60000 ), 'ai_timeout' => array( 'int', 30, 300 ), 'ai_auto_after_scan' => 'bool', 'ai_max_items' => array( 'int', 1, 200 ), 'ai_consent' => 'bool', 'scan_schedule' => array( 'select', array( 'off', 'twicedaily', 'daily', 'every_other_day', 'weekdays', 'weekends', 'weekly' ) ), 'scan_hour' => array( 'int', 0, 23 ), 'scan_max_file_size' => array( 'int', 1, 50 ), 'scan_skip_dirs' => 'lines', 'scan_time_budget' => array( 'int', 5, 60 ), 'scan_deep_media' => 'bool', 'scan_file_changes' => 'bool', 'scan_vulnerabilities' => 'bool', 'scan_abandoned' => 'bool', 'scan_exposed_files' => 'bool', 'scan_weak_passwords' => 'bool', 'scan_reputation' => 'bool', 'scan_custom_signatures' => 'patterns', 'scan_exclude' => 'lines', 'firewall_mode' => array( 'select', array( 'off', 'log', 'block' ) ), 'firewall_inspect_logged_in' => 'bool', 'firewall_rules' => 'boolmap', 'firewall_allowlist_urls' => 'lines', 'firewall_allowlist_ips' => 'iplist', 'firewall_blocklist_ips' => 'iplist', 'firewall_block_countries' => 'countries', 'firewall_block_empty_ua' => 'bool', 'firewall_hits_to_block' => array( 'int', 1, 100 ), 'firewall_hits_window' => array( 'int', 1, 120 ), 'firewall_block_minutes' => array( 'int', 1, 43200 ), 'firewall_rate_requests' => array( 'int', 0, 10000 ), 'firewall_rate_404' => array( 'int', 0, 10000 ), 'firewall_rate_window' => array( 'int', 10, 3600 ), 'firewall_rate_block_minutes' => array( 'int', 1, 43200 ), 'firewall_extended' => 'bool', 'ip_source' => array( 'select', array( 'auto', 'REMOTE_ADDR', 'HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP' ) ), 'trusted_proxies' => 'iplist', 'firewall_learning_until' => 'date', 'firewall_block_uas' => 'patterns', 'firewall_block_referrers' => 'patterns', 'firewall_block_hosts' => 'lines', 'firewall_block_methods' => 'bool', 'firewall_block_blank_post' => 'bool', 'firewall_trap_urls' => 'lines', 'firewall_trap_minutes' => array( 'int', 1, 525600 ), 'firewall_fake_bots' => 'bool', 'firewall_verified_bots_exempt' => 'bool', 'firewall_rate_crawlers' => array( 'int', 0, 10000 ), 'firewall_rate_404_crawlers' => array( 'int', 0, 10000 ), 'firewall_block_message' => 'textarea', 'firewall_feed_urls' => 'urls', 'country_mode' => array( 'select', array( 'block', 'allow' ) ), 'country_scope' => array( 'select', array( 'site', 'login' ) ), 'country_action' => array( 'select', array( 'block', 'redirect' ) ), 'country_redirect_url' => 'url', 'country_bypass_key' => 'slug', 'country_logged_in' => 'bool', 'country_source' => array( 'select', array( 'auto', 'header', 'database' ) ), 'traffic_mode' => array( 'select', array( 'off', 'security', 'all' ) ), 'traffic_ignore_logged_in' => 'bool', 'traffic_ignore_ips' => 'iplist', 'traffic_ignore_uas' => 'patterns', 'traffic_max_days' => array( 'int', 1, 90 ), 'traffic_max_rows' => array( 'int', 1000, 1000000 ), 'login_max_attempts' => array( 'int', 1, 100 ), 'login_lockout_minutes' => array( 'int', 1, 43200 ), 'login_count_window_minutes' => array( 'int', 1, 1440 ), 'login_max_lockouts' => array( 'int', 1, 100 ), 'login_long_lockout_hours' => array( 'int', 1, 720 ), 'login_block_usernames' => 'lines', 'login_min_password_length' => array( 'int', 8, 64 ), 'login_allowlist_ips' => 'iplist', 'login_max_lostpw' => array( 'int', 0, 100 ), 'login_unlock_requests' => 'bool', 'login_door_word' => 'slug', 'http_auth_user' => 'username', 'http_auth_scope' => array( 'select', array( 'admin', 'site' ) ), 'session_max_hours' => array( 'int', 0, 720 ), 'passkeys_roles' => 'roles', 'twofa_xmlrpc' => array( 'select', array( 'allow', 'block_2fa', 'block_all' ) ), 'twofa_brand_logo' => 'bool', 'twofa_brand_color' => 'hex', 'twofa_brand_message' => 'textarea', 'captcha_provider' => array( 'select', array( 'math', 'turnstile', 'recaptcha_v2', 'recaptcha_v3' ) ), 'captcha_site_key' => 'token', 'captcha_v3_threshold' => array( 'int', 1, 9 ), 'captcha_hide_badge' => 'bool', 'captcha_forms' => array( 'multi', array( 'login', 'register', 'lostpassword', 'comments', 'woo_login', 'woo_register', 'woo_lostpassword', 'woo_checkout', 'cf7', 'wpforms', 'elementor' ) ), 'comment_spam_action' => array( 'select', array( 'spam', 'discard' ) ), 'comment_min_seconds' => array( 'int', 0, 120 ), 'comment_trash_days' => array( 'int', 0, 365 ), 'comment_block_after' => array( 'int', 0, 100 ), 'comment_block_minutes' => array( 'int', 0, 525600 ), 'comment_block_proxies' => 'bool', 'reg_honeypot' => 'bool', 'reg_block_names' => 'lines', 'twofa_roles' => 'roles', 'twofa_methods' => array( 'multi', array( 'totp', 'email' ) ), 'twofa_grace_days' => array( 'int', 0, 90 ), 'twofa_remember_days' => array( 'int', 0, 90 ), 'login_slug' => 'slug', 'login_redirect_slug' => 'slug', 'hide_wp_admin' => 'bool', 'hardening' => 'hardening', 'headers_csp' => 'textarea', 'headers_hsts_max_age' => array( 'int', 300, 63072000 ), 'rest_allowlist' => 'lines', 'idle_logout_minutes' => array( 'int', 5, 1440 ), 'upload_block_svg' => 'bool', 'upload_block_html' => 'bool', 'admin_ip_allowlist' => 'iplist', 'alert_email' => 'email', 'alert_on_scan' => 'bool', 'alert_on_lockout' => 'bool', 'alert_on_admin_login' => 'bool', 'alert_on_new_admin' => 'bool', 'alert_on_plugin_change' => 'bool', 'alert_on_file_change' => 'bool', 'alert_on_attack_surge' => 'bool', 'alert_surge_count' => array( 'int', 5, 100000 ), 'alert_surge_minutes' => array( 'int', 1, 1440 ), 'alert_on_nonadmin_login' => 'bool', 'alert_login_first_only' => 'bool', 'alert_on_lost_password' => 'bool', 'alert_on_breached' => 'bool', 'alert_on_firewall_off' => 'bool', 'alert_on_vulnerable' => 'bool', 'alert_on_monitor' => 'bool', 'alert_max_per_hour' => array( 'int', 0, 1000 ), 'alert_summary' => array( 'select', array( 'off', 'daily', 'weekly' ) ), 'monitor_slow_ms' => array( 'int', 500, 60000 ), 'salt_rotate_days' => array( 'int', 0, 365 ), 'activity_log_enabled' => 'bool', 'log_retention_days' => array( 'int', 1, 365 ), 'delete_on_uninstall' => 'bool', ); } /** * Clean what the settings form sends. * * @since 1.0.0 * @param array $input Raw input. * @return array */ public static function sanitize( $input ) { $input = is_array( $input ) ? wp_unslash( $input ) : array(); $defaults = self::defaults(); $current = self::get(); $out = array(); // Only the tabs that were on the form are changed; a REST save of one key never wipes the rest. $partial = ! empty( $input['_partial'] ); $tab_keys = null; if ( $partial && ! empty( $input['_tabs'] ) ) { $tab_keys = self::keys_on_tabs( array_map( 'sanitize_key', explode( ',', (string) $input['_tabs'] ) ) ); } foreach ( self::schema() as $key => $type ) { $present = array_key_exists( $key, $input ); if ( $partial && ! $present && ! in_array( $type, array( 'bool' ), true ) ) { $out[ $key ] = $current[ $key ]; continue; } // An unticked checkbox is simply absent, but only on a tab that was on the form. if ( $partial && ! $present && 'bool' === $type && ( null === $tab_keys || ! in_array( $key, $tab_keys, true ) ) ) { $out[ $key ] = $current[ $key ]; continue; } $value = $present ? $input[ $key ] : null; $out[ $key ] = self::clean_value( $key, $type, $value, $current, $defaults ); } $out['activated_at'] = (int) $current['activated_at']; // The API key for the chosen provider (never echoed back). if ( ! empty( $input['api_key'] ) ) { self::set_secret( 'key_' . $out['provider'], self::token( $input['api_key'] ) ); } elseif ( ! empty( $input['clear_api_key'] ) ) { self::set_secret( 'key_' . $out['provider'], '' ); } // Secrets typed on the security forms (never echoed back). if ( ! empty( $input['captcha_secret_new'] ) ) { self::set_secret( 'captcha_secret', self::token( $input['captcha_secret_new'] ) ); } elseif ( ! empty( $input['captcha_secret_clear'] ) ) { self::set_secret( 'captcha_secret', '' ); } if ( ! empty( $input['gsb_key_new'] ) ) { self::set_secret( 'gsb_key', self::token( $input['gsb_key_new'] ) ); } elseif ( ! empty( $input['gsb_key_clear'] ) ) { self::set_secret( 'gsb_key', '' ); } if ( isset( $input['http_auth_pass_new'] ) && '' !== (string) $input['http_auth_pass_new'] ) { self::set_secret( 'http_auth_hash', wp_hash_password( (string) $input['http_auth_pass_new'] ) ); } // The HTTP password needs both a user name and a password. if ( ! empty( $out['hardening']['http_auth'] ) && ( '' === $out['http_auth_user'] || ! self::has_secret( 'http_auth_hash' ) ) ) { $out['hardening']['http_auth'] = false; add_settings_error( self::OPTION, 'svabg_http_auth', __( 'The HTTP password was not switched on: enter a user name and a password first.', 'ai-guardwall' ) ); } // The login door needs a secret word. if ( ! empty( $out['hardening']['login_door'] ) && '' === $out['login_door_word'] ) { $out['hardening']['login_door'] = false; add_settings_error( self::OPTION, 'svabg_login_door', __( 'The login door was not switched on: choose a secret word first.', 'ai-guardwall' ) ); } // A CAPTCHA service needs its keys. if ( 'math' !== $out['captcha_provider'] && ( '' === $out['captcha_site_key'] || ! self::has_secret( 'captcha_secret' ) ) ) { $out['captcha_provider'] = 'math'; add_settings_error( self::OPTION, 'svabg_captcha', __( 'The CAPTCHA stays on the built-in maths question until both the site key and the secret key are saved.', 'ai-guardwall' ) ); } // An allow-list of countries must contain the administrator's own country. if ( 'allow' === $out['country_mode'] && '' !== $out['firewall_block_countries'] && ! empty( $out['hardening']['country_block'] ) && class_exists( 'Softvolt_Ai_Bodyguard_Geoip' ) ) { $mine = Softvolt_Ai_Bodyguard_Geoip::country( Softvolt_Ai_Bodyguard_Helpers::client_ip() ); if ( '' !== $mine && ! in_array( $mine, explode( ',', $out['firewall_block_countries'] ), true ) && 'site' === $out['country_scope'] ) { $out['firewall_block_countries'] .= ',' . $mine; add_settings_error( self::OPTION, 'svabg_country_self', sprintf( /* translators: %s: mine */ __( 'Your own country (%s) was added to the allowed countries so you are not locked out.', 'ai-guardwall' ), $mine ), 'warning' ); } } // Never lock the administrator who is saving out of wp-admin. if ( '' !== trim( (string) $out['admin_ip_allowlist'] ) && ! Softvolt_Ai_Bodyguard_Helpers::ip_in_list( Softvolt_Ai_Bodyguard_Helpers::client_ip(), $out['admin_ip_allowlist'] ) ) { $out['admin_ip_allowlist'] = $current['admin_ip_allowlist']; if ( ! empty( $out['hardening']['admin_ip_allowlist'] ) ) { $out['hardening']['admin_ip_allowlist'] = $current['hardening']['admin_ip_allowlist'] ?? false; } add_settings_error( self::OPTION, 'svabg_admin_ip', sprintf( /* translators: %s: the administrator's IP address. */ __( 'The wp-admin IP allowlist was not saved because it would lock you out: your current address %s is not on it.', 'ai-guardwall' ), Softvolt_Ai_Bodyguard_Helpers::client_ip() ) ); } // A hidden login needs a usable slug. if ( ! empty( $out['hardening']['custom_login_url'] ) && '' === $out['login_slug'] ) { $out['hardening']['custom_login_url'] = false; add_settings_error( self::OPTION, 'svabg_login_slug', __( 'The hidden login URL was not switched on: choose a login slug first.', 'ai-guardwall' ) ); } if ( '' === $out['login_slug'] ) { $out['login_slug'] = $current['login_slug']; } self::flush(); return $out; } /** * The setting keys a set of settings tabs puts on the form (read from the * tab partials, so a new field never has to be registered twice). * * @since 1.1.0 * @param array $tabs Tab ids. * @return array */ public static function keys_on_tabs( array $tabs ) { $keys = array(); $dir = plugin_dir_path( SOFTVOLT_AI_BODYGUARD_FILE ) . 'admin/partials/'; foreach ( $tabs as $tab ) { $file = $dir . 'tab-' . $tab . '.php'; if ( ! is_file( $file ) ) { continue; } if ( preg_match_all( '/' . preg_quote( self::OPTION, '/' ) . '\[([a-z0-9_]+)\]/', (string) file_get_contents( $file ), $m ) ) { $keys = array_merge( $keys, $m[1] ); } } return array_values( array_unique( $keys ) ); } /** * Clean one value by its schema type. * * @param string $key Setting. * @param string|array $type Schema type. * @param mixed $value Raw value (null when absent). * @param array $current Current settings. * @param array $defaults Defaults. * @return mixed */ private static function clean_value( $key, $type, $value, $current, $defaults ) { $kind = is_array( $type ) ? $type[0] : $type; switch ( $kind ) { case 'bool': return empty( $value ) ? 0 : 1; case 'int': return self::number( null === $value ? $current[ $key ] : $value, $type[1], $type[2] ); case 'select': $value = is_scalar( $value ) ? (string) $value : ''; return in_array( $value, $type[1], true ) ? $value : $defaults[ $key ]; case 'multi': $out = array(); foreach ( is_array( $value ) ? $value : array() as $v ) { $v = sanitize_key( $v ); if ( in_array( $v, $type[1], true ) ) { $out[] = $v; } } return $out; case 'roles': $out = array(); $roles = array_keys( wp_roles()->roles ); foreach ( is_array( $value ) ? $value : array() as $v ) { $v = sanitize_key( $v ); if ( in_array( $v, $roles, true ) ) { $out[] = $v; } } return $out; case 'provider': $value = is_scalar( $value ) ? sanitize_key( $value ) : ''; $providers = Softvolt_Ai_Bodyguard_Catalog::providers(); return ( 'custom' === $value || Softvolt_Ai_Bodyguard_Claude::PROVIDER === $value || isset( $providers[ $value ] ) ) ? $value : $defaults['provider']; case 'model': return self::model_id( $value ); case 'url': return self::url( $value ); case 'email': $email = sanitize_email( is_scalar( $value ) ? (string) $value : '' ); return is_email( $email ) ? $email : ''; case 'token': return self::token( $value ); case 'slug': $slug = sanitize_title( is_scalar( $value ) ? (string) $value : '' ); $slug = trim( $slug, '/-' ); if ( in_array( $slug, array( 'wp-admin', 'wp-login', 'wp-login.php', 'admin', 'login', 'dashboard', 'wp-content', 'wp-includes', 'wp-json', 'feed', 'index', '' ), true ) ) { return '' === $slug ? '' : $current[ $key ]; } return mb_substr( $slug, 0, 60 ); case 'textarea': return self::textarea( $value, 4000 ); case 'hex': $value = is_scalar( $value ) ? strtolower( trim( (string) $value ) ) : ''; return preg_match( '/^#[0-9a-f]{6}$/', $value ) ? $value : ''; case 'date': $value = is_scalar( $value ) ? trim( (string) $value ) : ''; return preg_match( '/^\d{4}-\d{2}-\d{2}$/', $value ) && strtotime( $value ) ? $value : ''; case 'username': return mb_substr( sanitize_user( is_scalar( $value ) ? (string) $value : '', true ), 0, 60 ); case 'patterns': // Like lines, but keeps < > and % so regular expressions survive. $out = array(); foreach ( preg_split( '/[\r\n]+/', is_scalar( $value ) ? (string) $value : '' ) as $line ) { $line = trim( wp_check_invalid_utf8( preg_replace( '/[\x00-\x1F\x7F]/', '', $line ) ) ); if ( '' !== $line && count( $out ) < 500 ) { $out[] = mb_substr( $line, 0, 300 ); } } return implode( "\n", array_values( array_unique( $out ) ) ); case 'urls': $out = array(); foreach ( self::lines( $value, 20, 500 ) as $line ) { $url = esc_url_raw( $line, array( 'https', 'http' ) ); if ( $url ) { $out[] = $url; } } return implode( "\n", $out ); case 'rawtext': // Server rules: kept as typed (only administrators reach this form), without control characters. $value = is_scalar( $value ) ? str_replace( "\r\n", "\n", (string) $value ) : ''; $value = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $value ); return mb_substr( trim( wp_check_invalid_utf8( $value ) ), 0, 20000 ); case 'lines': return implode( "\n", self::lines( $value, 500, 300 ) ); case 'iplist': $out = array(); foreach ( self::lines( $value, 500, 64 ) as $entry ) { if ( preg_match( '/^[0-9a-fA-F:.\/*\-\s]+$/', $entry ) ) { $out[] = preg_replace( '/\s+/', '', $entry ); } } return implode( "\n", $out ); case 'countries': $out = array(); foreach ( preg_split( '/[\s,]+/', is_scalar( $value ) ? strtoupper( (string) $value ) : '' ) as $code ) { if ( preg_match( '/^[A-Z]{2}$/', $code ) ) { $out[] = $code; } } return implode( ',', array_unique( $out ) ); case 'boolmap': $out = array(); foreach ( $defaults[ $key ] as $id => $default ) { $out[ $id ] = ( is_array( $value ) && ! empty( $value[ $id ] ) ) ? 1 : 0; } return $out; case 'hardening': $out = array(); foreach ( Softvolt_Ai_Bodyguard_Hardening::rules() as $id => $rule ) { if ( 'check' === $rule['type'] ) { continue; } $out[ $id ] = ( is_array( $value ) && ! empty( $value[ $id ] ) ); } return $out; } return $current[ $key ]; } private static function textarea( $value, $max, $fallback = '' ) { $value = trim( sanitize_textarea_field( is_scalar( $value ) ? (string) $value : '' ) ); $value = mb_substr( $value, 0, $max ); return '' === $value ? (string) $fallback : $value; } private static function number( $value, $min, $max ) { return min( $max, max( $min, (int) $value ) ); } private static function url( $value ) { $url = esc_url_raw( is_string( $value ) ? trim( $value ) : '', array( 'http', 'https' ) ); return $url ? untrailingslashit( $url ) : ''; } public static function model_id( $value ) { $value = is_string( $value ) ? trim( $value ) : ''; return (string) preg_replace( '/[^A-Za-z0-9._:\/@+\-]/', '', mb_substr( $value, 0, 200 ) ); } private static function token( $value ) { $value = is_string( $value ) ? trim( $value ) : ''; return (string) preg_replace( '/[^\x21-\x7E]/', '', mb_substr( $value, 0, 400 ) ); } private static function lines( $value, $limit, $max_len ) { $out = array(); foreach ( preg_split( '/[\r\n]+/', is_scalar( $value ) ? (string) $value : '' ) as $line ) { $line = trim( sanitize_text_field( $line ) ); if ( '' !== $line && count( $out ) < $limit ) { $out[] = mb_substr( $line, 0, $max_len ); } } return array_values( array_unique( $out ) ); } /* * --------------------------------------------------------------------- * Secrets: encrypted at rest with the site's own salts. * --------------------------------------------------------------------- */ public static function secret( $name ) { $all = get_option( self::SECRETS, array() ); if ( ! is_array( $all ) || empty( $all[ $name ] ) ) { return ''; } return self::decrypt( (string) $all[ $name ] ); } public static function has_secret( $name ) { return '' !== self::secret( $name ); } public static function secret_hint( $name ) { $secret = self::secret( $name ); return '' === $secret ? '' : mb_substr( $secret, -4 ); } public static function set_secret( $name, $value ) { $all = get_option( self::SECRETS, array() ); $all = is_array( $all ) ? $all : array(); if ( '' === $value ) { unset( $all[ $name ] ); } else { $all[ $name ] = self::encrypt( $value ); } if ( false === get_option( self::SECRETS, false ) ) { add_option( self::SECRETS, $all, '', false ); } else { update_option( self::SECRETS, $all, false ); } } public static function new_secret() { return wp_generate_password( 40, false, false ); } public static function secrets_unreadable() { return self::$unreadable; } /** * The API key of the chosen provider. * * @since 1.0.0 * @return string */ public static function api_key() { return self::secret( 'key_' . (string) self::get( 'provider' ) ); } private static function crypto_key() { if ( function_exists( 'sodium_crypto_generichash' ) ) { return sodium_crypto_generichash( 'svabg|' . wp_salt( 'secure_auth' ), '', 32 ); } return hash( 'sha256', 'svabg|' . wp_salt( 'secure_auth' ), true ); } private static function encrypt( $plain ) { if ( function_exists( 'sodium_crypto_secretbox' ) ) { try { $nonce = random_bytes( 24 ); return 'sv1:' . bin2hex( $nonce . sodium_crypto_secretbox( $plain, $nonce, self::crypto_key() ) ); } catch ( Exception $e ) { unset( $e ); } } return 'raw:' . bin2hex( $plain ); } private static function decrypt( $stored ) { $hex = substr( $stored, 4 ); if ( '' === $hex || 0 !== strlen( $hex ) % 2 || ! ctype_xdigit( $hex ) ) { return ''; } if ( 0 === strpos( $stored, 'raw:' ) ) { $plain = hex2bin( $hex ); return false === $plain ? '' : $plain; } if ( 0 !== strpos( $stored, 'sv1:' ) || ! function_exists( 'sodium_crypto_secretbox_open' ) ) { return ''; } $raw = hex2bin( $hex ); if ( false === $raw || strlen( $raw ) < 25 ) { return ''; } try { $plain = sodium_crypto_secretbox_open( substr( $raw, 24 ), substr( $raw, 0, 24 ), self::crypto_key() ); } catch ( Exception $e ) { $plain = false; } if ( false === $plain ) { self::$unreadable = true; return ''; } return $plain; } }