0 && substr( $ip_bin, 0, $full ) !== substr( $sub_bin, 0, $full ) ) { return false; } if ( $rest > 0 ) { $mask = ( 0xFF << ( 8 - $rest ) ) & 0xFF; if ( ( ord( $ip_bin[ $full ] ) & $mask ) !== ( ord( $sub_bin[ $full ] ) & $mask ) ) { return false; } } return true; } if ( false !== strpos( $pattern, '-' ) && false === strpos( $pattern, ':' ) ) { list( $start, $end ) = array_map( 'trim', explode( '-', $pattern, 2 ) ); $ip_l = ip2long( $ip ); $s_l = ip2long( $start ); $e_l = ip2long( $end ); if ( false !== $ip_l && false !== $s_l && false !== $e_l ) { return $ip_l >= $s_l && $ip_l <= $e_l; } } return false; } /** * Cloudflare's published edge ranges (https://www.cloudflare.com/ips/). */ public static function is_cloudflare_ip( $ip ) { static $ranges = array( '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13', '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22', '2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32' ); return self::ip_in_list( $ip, apply_filters( 'svabg_cloudflare_ranges', $ranges ) ); } public static function is_private_ip( $ip ) { return ! filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ); } /** * Request path without the query string, with the site sub-directory stripped. */ public static function request_path() { $uri = self::request_uri(); $path = (string) wp_parse_url( $uri, PHP_URL_PATH ); $path = rawurldecode( $path ); return '' === $path ? '/' : $path; } public static function user_agent() { return substr( self::server( 'HTTP_USER_AGENT' ), 0, 512 ); } public static function request_method() { $method = strtoupper( sanitize_key( self::server( 'REQUEST_METHOD' ) ) ); return '' === $method ? 'GET' : $method; } /** * A $_SERVER value (request header or server variable) as plain text: unslashed and passed * through sanitize_text_field(); '' when it is missing. * * @since 1.5.0 * @param string $key Key in $_SERVER. * @return string */ public static function server( $key ) { if ( ! isset( $_SERVER[ $key ] ) || ! is_scalar( $_SERVER[ $key ] ) ) { return ''; } return sanitize_text_field( wp_unslash( (string) $_SERVER[ $key ] ) ); } /** * The requested URI (path and query string), unslashed and passed through esc_url_raw(), which * keeps percent-encoding (sanitize_text_field() would remove it). * * @since 1.5.0 * @return string */ public static function request_uri() { $uri = isset( $_SERVER['REQUEST_URI'] ) && is_scalar( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( (string) $_SERVER['REQUEST_URI'] ) ) : ''; return '' === $uri ? '/' : $uri; } /** * The query string of the request, sanitized as part of a URL ('' when there is none). * * @since 1.5.0 * @return string */ public static function query_string() { if ( empty( $_SERVER['QUERY_STRING'] ) || ! is_scalar( $_SERVER['QUERY_STRING'] ) ) { return ''; } return (string) wp_parse_url( esc_url_raw( '/?' . wp_unslash( (string) $_SERVER['QUERY_STRING'] ) ), PHP_URL_QUERY ); } /** * The referring address, sanitized as a URL. * * @since 1.5.0 * @return string */ public static function referer() { return isset( $_SERVER['HTTP_REFERER'] ) && is_scalar( $_SERVER['HTTP_REFERER'] ) ? esc_url_raw( wp_unslash( (string) $_SERVER['HTTP_REFERER'] ) ) : ''; } /** * The URI exactly as the client sent it, for the firewall's attack patterns only: sanitizing would * remove the very code they look for. Never stored or printed; logs use request_uri(). * * @since 1.5.0 * @return string */ public static function raw_request_uri() { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- inspected by the firewall rules as sent; see above. return isset( $_SERVER['REQUEST_URI'] ) && is_scalar( $_SERVER['REQUEST_URI'] ) ? (string) wp_unslash( $_SERVER['REQUEST_URI'] ) : '/'; } /** * The user agent exactly as sent, for the firewall's attack patterns only (see raw_request_uri()). * * @since 1.5.0 * @return string */ public static function raw_user_agent() { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- inspected by the firewall rules as sent; see raw_request_uri(). return isset( $_SERVER['HTTP_USER_AGENT'] ) && is_scalar( $_SERVER['HTTP_USER_AGENT'] ) ? substr( (string) wp_unslash( $_SERVER['HTTP_USER_AGENT'] ), 0, 512 ) : ''; } /** * Text from a request (an attack sample, a path) made safe to store: angle brackets become look-alike * characters so the sample stays readable, then sanitize_text_field() and a length limit. * * @since 1.5.0 * @param string $text Text. * @param int $max Characters at most. * @return string */ /** * The style tag of a page the plugin prints by itself (block page, maintenance page, 2FA form), * printed by WordPress: the CSS is an inline style of a registered handle. Uses its own WP_Styles * instance because the firewall's block page can come before init, where wp_register_style() * and friends report "doing it wrong". * * @since 1.5.0 * @param string $handle Style handle. * @param string $css CSS. * @return string HTML printed by WP_Styles. */ public static function page_style( $handle, $css ) { $styles = new WP_Styles(); $styles->add( $handle, false, array(), SOFTVOLT_AI_BODYGUARD_VERSION ); $styles->add_inline_style( $handle, $css ); ob_start(); $styles->do_items( array( $handle ) ); return (string) ob_get_clean(); } public static function sample_text( $text, $max = 200 ) { return self::trim_text( sanitize_text_field( str_replace( array( '<', '>' ), array( '‹', '›' ), (string) $text ) ), $max ); } /** * The folders of this site the plugin scans and names, as normalized paths without a trailing slash, keyed * by the site-relative name used for them ('wp-content/plugins', …, '' for the WordPress folder). The * specific folders come first, so plugins, themes or uploads that were moved somewhere else (even inside a * renamed content folder) still get their usual name, and the WordPress folder comes last. * * @since 1.5.1 * @return array */ public static function site_dirs() { static $dirs = null; if ( null !== $dirs ) { return $dirs; } $norm = function ( $path ) { return untrailingslashit( wp_normalize_path( (string) $path ) ); }; $content = $norm( WP_CONTENT_DIR ); $uploads = $content . '/uploads'; if ( function_exists( 'wp_upload_dir' ) ) { $upload = wp_upload_dir( null, false ); $uploads = $norm( $upload['basedir'] ); // On a multisite network every site has uploads/sites/: name the folder of the whole network. if ( is_multisite() && preg_match( '#^(.+)/sites/\d+$#', $uploads, $m ) ) { $uploads = $m[1]; } } $dirs = array( 'wp-content/plugins' => $norm( WP_PLUGIN_DIR ), 'wp-content/mu-plugins' => $norm( WPMU_PLUGIN_DIR ), 'wp-content/themes' => function_exists( 'get_theme_root' ) ? $norm( get_theme_root() ) : $content . '/themes', 'wp-content/uploads' => $uploads, 'wp-content' => $content, '' => $norm( ABSPATH ), ); return $dirs; } /** * One folder of site_dirs() by its name ('wp-content/plugins', 'wp-content/themes', …). * * @since 1.5.1 * @param string $name Name. * @return string Normalized path without a trailing slash. */ public static function site_dir( $name ) { $dirs = self::site_dirs(); return isset( $dirs[ $name ] ) ? $dirs[ $name ] : $dirs['']; } /** * Site-relative path for a file (e.g. wp-content/plugins/x/y.php). A file outside the folders of * site_dirs() keeps its full path, so a name can never point at two files. */ public static function rel_path( $abs ) { $abs = wp_normalize_path( (string) $abs ); foreach ( self::site_dirs() as $name => $dir ) { if ( '' === $dir ) { continue; } if ( $abs === $dir ) { return $name; } if ( 0 !== strpos( $abs, $dir . '/' ) ) { continue; } $rest = substr( $abs, strlen( $dir ) + 1 ); if ( '' !== $name ) { return $name . '/' . $rest; } // A folder called wp-content in the WordPress folder that is not the content folder (it was moved): // keep the full path, or it would be taken for the real one. if ( ( 'wp-content' === $rest || 0 === strpos( $rest, 'wp-content/' ) ) && self::site_dirs()['wp-content'] !== $dir . '/wp-content' ) { return $abs; } return $rest; } return $abs; } /** * The full path for a site-relative name made by rel_path(). */ public static function abs_path( $rel ) { $rel = wp_normalize_path( (string) $rel ); if ( path_is_absolute( $rel ) ) { return $rel; } $rel = ltrim( $rel, '/' ); $dirs = self::site_dirs(); foreach ( $dirs as $name => $dir ) { if ( '' === $name ) { break; } if ( $rel === $name ) { return $dir; } if ( 0 === strpos( $rel, $name . '/' ) ) { return $dir . '/' . substr( $rel, strlen( $name ) + 1 ); } } return $dirs[''] . '/' . $rel; } /** * The full path for a site-relative name, only when the file really lies in one of the site's folders: * traversal is refused, and symbolic links are resolved (realpath) and compared with the resolved folders, * so a link cannot lead a cleanup action outside the site. False otherwise. */ public static function safe_abs_path( $rel ) { $rel = (string) $rel; if ( '' === $rel || false !== strpos( $rel, "\0" ) || preg_match( '#(^|[\\\\/])\.\.([\\\\/]|$)#', $rel ) ) { return false; } $abs = self::abs_path( $rel ); if ( file_exists( $abs ) ) { $real = realpath( $abs ); } else { $parent = realpath( dirname( $abs ) ); $real = false === $parent ? false : $parent . '/' . basename( $abs ); } if ( false === $real ) { return false; } $real = wp_normalize_path( $real ); foreach ( self::site_dirs() as $dir ) { $root = realpath( $dir ); if ( false === $root ) { continue; } $root = untrailingslashit( wp_normalize_path( $root ) ); if ( 0 === strpos( $real, $root . '/' ) ) { return $abs; } } // wp-config.php may sit one folder above WordPress. $up = realpath( dirname( self::site_dirs()[''] ) . '/wp-config.php' ); if ( false !== $up && wp_normalize_path( $up ) === $real ) { return $abs; } return false; } /** * Where work_dir() keeps $sub, without creating anything ('' before the folder exists). * * @since 1.5.1 * @param string $sub Sub-folder. * @return string */ public static function work_dir_path( $sub = '' ) { $key = get_option( 'svabg_work_key' ); if ( ! is_string( $key ) || ! preg_match( '/^[a-z0-9]{24}$/', $key ) ) { return ''; } $upload = wp_upload_dir( null, false ); $base = trailingslashit( wp_normalize_path( $upload['basedir'] ) ) . self::WORK_FOLDER . '/' . $key; return '' === $sub ? $base : $base . '/' . trim( $sub, '/' ); } /** * The plugin's private working folder: uploads// (database backups, IP range * lists). The key is kept in the database, so nobody can guess the address even on servers that ignore * .htaccess and web.config; directory listing is blocked too, and nothing in it is code. */ public static function work_dir( $sub = '' ) { $upload = wp_upload_dir( null, false ); $parent = trailingslashit( wp_normalize_path( $upload['basedir'] ) ); $key = get_option( 'svabg_work_key' ); if ( ! is_string( $key ) || ! preg_match( '/^[a-z0-9]{24}$/', $key ) ) { $key = strtolower( wp_generate_password( 24, false, false ) ); update_option( 'svabg_work_key', $key, false ); } $slug = $parent . self::WORK_FOLDER; $base = $slug . '/' . $key; // The folder of 1.5.0 and older had a name anybody could guess: move it. if ( ! is_dir( $base ) && is_dir( $parent . self::LEGACY_FOLDER ) && wp_mkdir_p( $slug ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename -- renames the plugin's own folder inside uploads. @rename( $parent . self::LEGACY_FOLDER, $base ); wp_delete_file( $base . '/index.php' ); } $dir = '' === $sub ? $base : $base . '/' . trim( $sub, '/' ); if ( ! is_dir( $dir ) ) { wp_mkdir_p( $dir ); } foreach ( array( $slug, $base ) as $folder ) { $protect = array( $folder . '/.htaccess' => "\nRequire all denied\n\n\nOrder deny,allow\nDeny from all\n\n", $folder . '/web.config' => "\n\n", $folder . '/index.html' => '', ); foreach ( $protect as $file => $content ) { if ( ! file_exists( $file ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- small protection files in the plugin's own uploads folder. @file_put_contents( $file, $content ); } } } return $dir; } public static function human_size( $bytes ) { // size_format() returns false for 0 (and for floats below 1). if ( (float) $bytes < 1 ) { return '0 B'; } return size_format( (float) $bytes, 1 ); } public static function severity_rank( $severity ) { $map = array( 'critical' => 5, 'high' => 4, 'medium' => 3, 'low' => 2, 'info' => 1, ); return isset( $map[ $severity ] ) ? $map[ $severity ] : 0; } public static function severities() { return array( 'critical', 'high', 'medium', 'low', 'info' ); } /** * Text without secrets or personal data, for an AI provider or for the code kept with a finding: the * values of passwords, keys, salts and tokens in code and configuration, private keys, password hashes, * logins in URLs, and email addresses. The code around them stays, so it still shows what it does. * * @since 1.5.1 * @param string $text Code, content or details. * @param bool $emails Remove email addresses too (since 1.5.2; off for findings). * @return string */ public static function redact( $text, $emails = true ) { $text = (string) $text; // define( 'DB_PASSWORD', '…' ), the security keys and salts, and any constant whose name says it is secret. $text = (string) preg_replace( '/(define\s*\(\s*([\'"])(?:DB_(?:NAME|USER|PASSWORD|HOST)|[A-Z0-9_]*(?:KEY|SALT|PASS|PASSWORD|SECRET|TOKEN|NONCE|AUTH)[A-Z0-9_]*)\2\s*,\s*)([\'"])(?:\\\\.|(?!\3).)*\3/is', '$1$3[removed]$3', $text ); // $password = '…', 'api_key' => '…', "client_secret": "…" and the like. $text = (string) preg_replace( '/((?:pass(?:word|wd|phrase)?|pwd|secret|token|api[_-]?key|apikey|auth[_-]?key|private[_-]?key|client[_-]?secret|access[_-]?key|salt)[\'"]?\s*(?:=>|=|:)\s*)([\'"])(?:\\\\.|(?!\2)[^\r\n]){1,800}?\2/i', '$1$2[removed]$2', $text ); // The same in serialized option values: s:7:"api_key";s:32:"…" (the length stays right for "[removed]"). $text = (string) preg_replace( '/(s:\d+:"[^"]{0,60}?(?:pass(?:word|wd|phrase)?|pwd|secret|token|api[_-]?key|apikey|auth[_-]?key|private[_-]?key|client[_-]?secret|access[_-]?key|salt)[^"]{0,60}";s:)\d+:"[^"]*"/i', '${1}9:"[removed]"', $text ); // Private keys and certificates' keys. $text = (string) preg_replace( '/-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----/s', '[private key removed]', $text ); // Password hashes (phpass, bcrypt, argon2) as they sit in the users table. $text = (string) preg_replace( '/\$(?:P|H|wp\$2y|2[aby]|argon2i?d?)\$[.\/A-Za-z0-9$=,+]{20,}/', '[password hash removed]', $text ); // user:password@ in URLs and database addresses. $text = (string) preg_replace( '#\b([a-z][a-z0-9+.-]*://)[^/\s:@\'"]+:[^/\s@\'"]+@#i', '$1[removed]@', $text ); // Email addresses (kept in a finding the site owner reads: an attacker's address can be the evidence). return $emails ? (string) preg_replace( '/[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,24}/i', '[email removed]', $text ) : $text; } /** * An address as it may be logged: the values of parameters that carry secrets (password-reset keys, * nonces, tokens, passwords, codes) are replaced, the rest stays readable. * * @since 1.5.2 * @param string $url Address or path with a query string. * @return string */ public static function loggable_url( $url ) { return (string) preg_replace( '/([?&;](?:[^=&#;]*(?:key|pass|pwd|token|secret|nonce|auth|session|sig|hash|code|otp))=)[^&#;]*/i', '$1[removed]', (string) $url ); } /** * Seconds elapsed since $start are compared to the budget. */ public static function out_of_time( $start, $budget ) { return ( microtime( true ) - $start ) >= $budget; } /** * Raises time limits for long-running scan steps when the host allows it. */ public static function raise_limits( $seconds = 120 ) { if ( function_exists( 'set_time_limit' ) ) { @set_time_limit( $seconds ); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- only for the long step that asked for it (a scan step, a database cleanup), never globally. } if ( function_exists( 'wp_raise_memory_limit' ) ) { wp_raise_memory_limit( 'admin' ); } } /** * redact() for code that is shown with line numbers: the same secrets are * removed and the number of lines stays the same, so the numbers stay right. * * A define() that runs over several lines (the keys and salts in wp-config.php * are sometimes written that way) and private key blocks are handled first, * because they are the secrets that can span lines. * * @since 1.5.3 * @param string $text Code or configuration. * @return string */ public static function redact_keep_lines( $text ) { $text = (string) $text; $text = (string) preg_replace_callback( '/(define\s*\(\s*([\'"])(?:DB_(?:NAME|USER|PASSWORD|HOST)|[A-Z0-9_]*(?:KEY|SALT|PASS|PASSWORD|SECRET|TOKEN|NONCE|AUTH)[A-Z0-9_]*)\2)\s*,\s*([\'"])(?:\\\\.|(?!\3).)*\3/is', static function ( $m ) { return $m[1] . ", '[removed]'" . str_repeat( "\n", substr_count( $m[0], "\n" ) ); }, $text ); $text = (string) preg_replace_callback( '/-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----/s', static function ( $m ) { return '[private key removed]' . str_repeat( "\n", substr_count( $m[0], "\n" ) ); }, $text ); return self::redact( $text, false ); } public static function lines_around( $content, $line, $context = 12, $max_chars = 12000 ) { // Secrets are removed BEFORE the line numbers are added. A number in front of // every line would stop redact() from matching a define() over several lines. $content = self::redact_keep_lines( $content ); $lines = preg_split( '/\r\n|\r|\n/', $content ); $total = count( $lines ); $line = max( 1, min( $total, (int) $line ) ); $from = max( 1, $line - $context ); $to = min( $total, $line + $context ); $out = array(); for ( $i = $from; $i <= $to; $i++ ) { $text = $lines[ $i - 1 ]; if ( strlen( $text ) > 600 ) { $text = substr( $text, 0, 600 ) . ' …[line truncated]'; } $out[] = sprintf( '%5d | %s', $i, $text ); } $snippet = implode( "\n", $out ); if ( strlen( $snippet ) > $max_chars ) { $snippet = substr( $snippet, 0, $max_chars ) . "\n…[truncated]"; } return $snippet; } /** * Up to 220 characters around a match, for a finding: from 60 characters before it, but never from * inside the line before the match, and never ending inside a line after it, so a key or a password * next to the match is either whole (and redact() can name and remove it) or not there at all. * * @since 1.5.2 * @param string $content Text that was scanned. * @param int $offset Byte offset of the match. * @return string One line of text, white space collapsed. */ public static function excerpt( $content, $offset ) { $content = (string) $content; $offset = max( 0, min( strlen( $content ), (int) $offset ) ); $from = max( 0, $offset - 60 ); $nl = strrpos( substr( $content, $from, $offset - $from ), "\n" ); if ( false !== $nl ) { $from += $nl + 1; } $text = substr( $content, $from, 220 ); if ( $from + 220 < strlen( $content ) ) { $cut = strrpos( $text, "\n", $offset - $from ); if ( false !== $cut ) { $text = substr( $text, 0, $cut ); } } return (string) preg_replace( '/\s+/', ' ', trim( $text ) ); } public static function line_of_offset( $content, $offset ) { return substr_count( substr( $content, 0, max( 0, (int) $offset ) ), "\n" ) + 1; } public static function now() { return current_time( 'mysql', true ); } public static function esc_json( $data ) { return wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); } /** * Extension of a path (lower-case). */ public static function ext( $path ) { return strtolower( (string) pathinfo( $path, PATHINFO_EXTENSION ) ); } public static function is_php_ext( $ext ) { return in_array( $ext, array( 'php', 'phtml', 'php3', 'php4', 'php5', 'php7', 'php8', 'phps', 'phar', 'pht', 'phpt', 'inc', 'module' ), true ); } public static function plugin_slug_from_rel( $rel ) { if ( preg_match( '#^wp-content/plugins/([^/]+)/#', $rel, $m ) ) { return $m[1]; } return ''; } public static function theme_slug_from_rel( $rel ) { if ( preg_match( '#^wp-content/themes/([^/]+)/#', $rel, $m ) ) { return $m[1]; } return ''; } /** * Returns the current WordPress version string. */ public static function wp_version() { global $wp_version; return (string) $wp_version; } /** * Whether the running PHP still gets security fixes: 'ok' for PHP 8.3 or newer and for 8.2.35 or * newer (the 8.2 security release of 21 Oct 2026), 'outdated' for an older 8.2, 'unsupported' for * anything older and for every 8.2 once its security support ends (31 Dec 2026). * * @since 1.5.0 * @return string */ public static function php_status() { if ( version_compare( PHP_VERSION, '8.3', '>=' ) ) { return 'ok'; } if ( version_compare( PHP_VERSION, '8.2', '<' ) || time() >= 1798761600 ) { // 1 Jan 2027 UTC. return 'unsupported'; } return version_compare( PHP_VERSION, '8.2.35', '>=' ) ? 'ok' : 'outdated'; } public static function admin_url_page( $page, $args = array() ) { $args['page'] = $page; return add_query_arg( $args, admin_url( 'admin.php' ) ); } public static function bool( $value ) { return in_array( $value, array( true, 1, '1', 'true', 'on', 'yes' ), true ); } public static function random_slug( $length = 10 ) { return strtolower( wp_generate_password( $length, false, false ) ); } public static function trim_text( $text, $max = 200 ) { $text = (string) $text; return strlen( $text ) > $max ? substr( $text, 0, $max ) . '…' : $text; } }