prefix . 'aisfg_ban'; } /* ================= IP アドレスの扱い ================= */ /** * Normalize. * * @param mixed $ip Parameter. */ public static function normalize( $ip ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- inet_pton returns false on invalid input. $b = @inet_pton( trim( (string) $ip ) ); return ( false === $b ) ? '' : (string) inet_ntop( $b ); } /** * Parse list. * * @param mixed $text Parameter. */ public static function parse_list( $text ) { $out = array(); foreach ( preg_split( '/[\s,]+/', (string) $text, -1, PREG_SPLIT_NO_EMPTY ) as $item ) { if ( false !== strpos( $item, '/' ) ) { list( $ip, $bits ) = explode( '/', $item, 2 ); $n = self::normalize( $ip ); if ( '' === $n || ! ctype_digit( $bits ) ) { continue; } $max = ( false !== strpos( $n, ':' ) ) ? 128 : 32; if ( (int) $bits > $max ) { continue; } $out[] = $n . '/' . (int) $bits; } else { $n = self::normalize( $item ); if ( '' !== $n ) { $out[] = $n; } } } return array_values( array_unique( $out ) ); } /** * Clean list. * * @param mixed $text Parameter. */ public static function clean_list( $text ) { return implode( "\n", self::parse_list( $text ) ); } /** * In cidr. * * @param mixed $ip Parameter. * @param mixed $cidr Parameter. */ private static function in_cidr( $ip, $cidr ) { if ( false === strpos( $cidr, '/' ) ) { return $ip === $cidr; } list( $sub, $bits ) = explode( '/', $cidr, 2 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- inet_pton returns false on invalid input. $a = @inet_pton( $ip ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- inet_pton returns false on invalid input. $b = @inet_pton( $sub ); $bits = (int) $bits; if ( false === $a || false === $b || strlen( $a ) !== strlen( $b ) || $bits < 0 || $bits > strlen( $a ) * 8 ) { return false; } $bytes = intdiv( $bits, 8 ); $rem = $bits % 8; if ( $bytes > 0 && substr( $a, 0, $bytes ) !== substr( $b, 0, $bytes ) ) { return false; } if ( $rem > 0 ) { $mask = ( 0xFF << ( 8 - $rem ) ) & 0xFF; if ( ( ord( $a[ $bytes ] ) & $mask ) !== ( ord( $b[ $bytes ] ) & $mask ) ) { return false; } } return true; } /** * In list. * * @param mixed $ip Parameter. * @param array $items Parameter. */ public static function in_list( $ip, array $items ) { foreach ( $items as $entry ) { if ( self::in_cidr( $ip, $entry ) ) { return true; } } return false; } /** * Is public. * * @param mixed $ip Parameter. */ public static function is_public( $ip ) { return false !== filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ); } /** * Is allowed. * * @param mixed $ip Parameter. * @param array $s Parameter. */ public static function is_allowed( $ip, array $s ) { return self::in_list( $ip, self::parse_list( $s['ban_allow'] ) ); } /** * Client. * * @param ?array $server Parameter. * @param ?array $s Parameter. */ public static function client( ?array $server = null, ?array $s = null ) { $server = ( null === $server ) ? $_SERVER : $server; $s = ( null === $s ) ? AISFG_Settings::get() : $s; $remote = self::normalize( isset( $server['REMOTE_ADDR'] ) ? $server['REMOTE_ADDR'] : '' ); $res = array( 'ip' => $remote, 'safe' => false, 'proxied' => false, ); if ( '' === $remote ) { return $res; } $has = false; foreach ( array( 'HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_FORWARDED', 'HTTP_TRUE_CLIENT_IP' ) as $h ) { if ( ! empty( $server[ $h ] ) ) { $has = true; } } $res['proxied'] = $has; $trusted = self::parse_list( $s['trusted_proxies'] ); if ( self::in_list( $remote, $trusted ) ) { $ip = ''; if ( ! empty( $server['HTTP_CF_CONNECTING_IP'] ) ) { $ip = self::normalize( $server['HTTP_CF_CONNECTING_IP'] ); } if ( '' === $ip && ! empty( $server['HTTP_X_FORWARDED_FOR'] ) ) { // 右(サーバーに近い側)から見て、最初の「信頼しないアドレス」が訪問者. foreach ( array_reverse( explode( ',', (string) $server['HTTP_X_FORWARDED_FOR'] ) ) as $p ) { $n = self::normalize( $p ); if ( '' === $n || self::in_list( $n, $trusted ) ) { continue; } $ip = $n; break; } } if ( '' === $ip ) { return $res; // 訪問者の IP が分からない → 自動ブロックしない. } $res['ip'] = $ip; } elseif ( $has ) { return $res; // プロキシ経由の形跡があるのに、信頼する設定がない → 自動ブロックしない. } $res['safe'] = self::is_public( $res['ip'] ); return $res; } /* ================= ブロックの記録と判定 ================= */ /** * Now. */ private static function now() { return gmdate( 'Y-m-d H:i:s' ); } /** * Strike. * * @param mixed $ip Parameter. * @param mixed $reason Parameter. * @param array $s Parameter. */ public static function strike( $ip, $reason, array $s ) { $key = 'aisfg_st_' . md5( $ip ); $n = (int) get_transient( $key ) + 1; if ( $n >= max( 1, (int) $s['ban_threshold'] ) ) { delete_transient( $key ); self::ban( $ip, $reason, $n, (int) $s['ban_hours'] ); return true; } set_transient( $key, $n, max( 1, (int) $s['ban_window_min'] ) * MINUTE_IN_SECONDS ); return false; } /** * Ban. * * @param mixed $ip Parameter. * @param mixed $reason Parameter. * @param mixed $strikes Parameter. * @param mixed $hours Parameter. */ public static function ban( $ip, $reason, $strikes, $hours ) { global $wpdb; $now = self::now(); $expires = gmdate( 'Y-m-d H:i:s', time() + max( 1, (int) $hours ) * HOUR_IN_SECONDS ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- aisfg_ban custom table; no WP API $wpdb->query( $wpdb->prepare( 'INSERT INTO %i (ip, reason, strikes, blocked, first_at, last_at, expires_at) VALUES (%s, %s, %d, 0, %s, %s, %s) ' . 'ON DUPLICATE KEY UPDATE reason = VALUES(reason), strikes = strikes + VALUES(strikes), last_at = VALUES(last_at), expires_at = VALUES(expires_at)', self::table(), $ip, substr( (string) $reason, 0, 40 ), (int) $strikes, $now, $now, $expires ) ); wp_cache_set( 'aisfg_ban_' . md5( $ip ), strtotime( $expires . ' UTC' ), 'aisfg', max( 1, (int) $hours ) * HOUR_IN_SECONDS ); AISFG_Logger::log( 0, 'block', array( 'AUTO_BAN' ), $ip ); } /** * Is banned. * * @param mixed $ip Parameter. */ public static function is_banned( $ip ) { global $wpdb; $k = 'aisfg_ban_' . md5( $ip ); $c = wp_cache_get( $k, 'aisfg' ); if ( false !== $c ) { return (int) $c > time(); } $old = $wpdb->suppress_errors( true ); // 表がまだ無い更新直後でも、エラーを出さない. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- aisfg_ban custom table; cache miss fallback $exp = $wpdb->get_var( $wpdb->prepare( 'SELECT expires_at FROM %i WHERE ip = %s LIMIT 1', self::table(), $ip ) ); $wpdb->suppress_errors( $old ); $ts = $exp ? (int) strtotime( $exp . ' UTC' ) : 0; wp_cache_set( $k, $ts, 'aisfg', 60 ); return $ts > time(); } /** * Touch blocked. * * @param mixed $ip Parameter. */ public static function touch_blocked( $ip ) { global $wpdb; $old = $wpdb->suppress_errors( true ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- aisfg_ban custom table; no WP API $wpdb->query( $wpdb->prepare( 'UPDATE %i SET blocked = blocked + 1, last_at = %s WHERE ip = %s', self::table(), self::now(), $ip ) ); $wpdb->suppress_errors( $old ); } /** * Unban. * * @param mixed $ip Parameter. */ public static function unban( $ip ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- aisfg_ban custom table; no WP API $wpdb->delete( self::table(), array( 'ip' => $ip ), array( '%s' ) ); wp_cache_delete( 'aisfg_ban_' . md5( $ip ), 'aisfg' ); } /** * Unban all. */ public static function unban_all() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- aisfg_ban custom table; no WP API $ips = (array) $wpdb->get_col( $wpdb->prepare( 'SELECT ip FROM %i', self::table() ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- aisfg_ban custom table; no WP API $wpdb->query( $wpdb->prepare( 'DELETE FROM %i', self::table() ) ); foreach ( $ips as $ip ) { wp_cache_delete( 'aisfg_ban_' . md5( $ip ), 'aisfg' ); } } /** * Active. * * @param mixed $limit Parameter. */ public static function active( $limit = 200 ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- aisfg_ban custom table; admin/one-off query return (array) $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE expires_at > %s ORDER BY last_at DESC LIMIT %d', self::table(), self::now(), (int) $limit ) ); } /** * Summary. */ public static function summary() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- aisfg_ban custom table; admin/one-off aggregate $row = $wpdb->get_row( $wpdb->prepare( 'SELECT COUNT(*) AS active, COALESCE(SUM(blocked), 0) AS blocked FROM %i WHERE expires_at > %s', self::table(), self::now() ) ); return array( 'active' => $row ? (int) $row->active : 0, 'blocked' => $row ? (int) $row->blocked : 0, ); } /** * Delete expired rows. */ public static function purge() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- aisfg_ban custom table; retention purge $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE expires_at < %s', self::table(), gmdate( 'Y-m-d H:i:s', time() - 7 * DAY_IN_SECONDS ) ) ); } /** * Return the client IP when it is banned for form submissions; otherwise empty. * * @param array $server Server vars (usually $_SERVER). * @param ?array $s Settings. * @return string */ public static function banned_client_ip( array $server, ?array $s = null ) { $s = ( null === $s ) ? AISFG_Settings::get() : $s; if ( empty( $s['ban_enabled'] ) || 'enforce' !== $s['mode'] ) { return ''; } $c = self::client( $server, $s ); if ( ! $c['safe'] || self::is_allowed( $c['ip'], $s ) ) { return ''; } return self::is_banned( $c['ip'] ) ? $c['ip'] : ''; } }