khasinski/ai_bouncer

GitHub: khasinski/ai_bouncer

面向 Rails 的 AI 驱动 HTTP 攻击检测中间件,利用 ML 嵌入技术实时识别 SQL 注入、XSS 等多种 Web 攻击。

Stars: 10 | Forks: 0

# AiBouncer [![CI](https://static.pigsec.cn/wp-content/uploads/repos/2026/03/1a964098e7220227.svg)](https://github.com/khasinski/ai_bouncer/actions/workflows/ci.yml) [![Gem Version](https://badge.fury.io/rb/ai_bouncer.svg)](https://badge.fury.io/rb/ai_bouncer) 面向 Ruby on Rails 的 AI 驱动 HTTP 请求分类器。利用 ML 嵌入技术检测凭证填充、SQL 注入、XSS 及其他攻击。 ## 功能特性 - **快速**:约 2ms 推理时间(内存模式) - **轻量**:模型总大小约 32MB - **精准**:对常见攻击的检测率达 92% 以上 - **灵活存储**:支持内存或 PostgreSQL + pgvector - **易于集成**:开箱即用的中间件或控制器组件 - **可配置**:支持保护特定路径、自定义响应 ## 可检测的攻击类型 - SQL 注入 (SQLi) - 跨站脚本攻击 (XSS) - 路径遍历 - 命令注入 - 凭证填充 - 垃圾机器人 - 漏洞扫描器 - 服务端请求伪造 (SSRF) - XML 外部实体注入 (XXE) - NoSQL 注入 - 服务端模板注入 (SSTI) - Log4Shell (JNDI 注入) - 开放重定向 - LDAP 注入 ## 系统要求 - Ruby >= 3.2(onnxruntime 要求) - Rails 6.1+(可选,用于中间件/组件集成) ## 安装 添加到您的 Gemfile: ``` gem 'ai_bouncer' # 可选:用于数据库存储模式 gem 'neighbor' ``` 然后运行安装器: ``` bundle install rails generate ai_bouncer:install ``` 这将创建 `config/initializers/ai_bouncer.rb`。模型文件(约 32MB)会在首次请求时**自动下载**。 ### 手动下载(可选) 如果您希望将模型文件与应用程序打包在一起: ``` # 从 HuggingFace 下载 pip install huggingface_hub huggingface-cli download khasinski/ai-bouncer --local-dir vendor/ai_bouncer # 在 initializer 中禁用自动下载 config.auto_download = false ``` ## 存储模式 ### 内存模式(默认) 向量保存在内存中。快速且简单。 ``` config.storage = :memory ``` **优点**:约 2ms 延迟,无需数据库 **缺点**:约 32MB RAM 占用,模式在部署时固定 ### 数据库模式 向量使用 pgvector 存储在 PostgreSQL 中。 ``` config.storage = :database ``` **优点**:可扩展,可在运行时添加自定义模式,持久化 **缺点**:约 5ms 延迟,需要 pgvector #### 数据库设置 1. 安装 pgvector:https://github.com/pgvector/pgvector 2. 生成并运行迁移: ``` rails generate ai_bouncer:migration rails db:migrate ``` 3. 导入内置模式数据: ``` rails ai_bouncer:seed ``` 4. 验证: ``` rails ai_bouncer:stats ``` ## 配置 ``` # config/initializers/ai_bouncer.rb AiBouncer.configure do |config| config.enabled = Rails.env.production? config.storage = :memory # or :database # Paths to protect (for middleware) config.protected_paths = [ "/login", "/register", "/api/*", ] # Action when attack detected config.action = :block # :block, :challenge, or :log config.threshold = 0.3 # Model files location config.model_path = Rails.root.join("vendor", "ai_bouncer") # Callback for monitoring config.on_attack_detected = ->(request:, classification:, action:) { Rails.logger.warn "Attack: #{classification[:label]} from #{request.ip}" } end ``` ## 使用方法 ### 方式 1:中间件(自动) 中间件会自动保护配置的路径。它从 Rails 请求中提取 method、path、body、user-agent 和 params —— 无需手动格式化: ``` # 像这样的请求: # POST /login HTTP/1.1 # User-Agent: Mozilla/5.0... # Content-Type: application/x-www-form-urlencoded # # username=admin'--&password=x # 会被自动分类为: # => { label: "sqli", confidence: 0.94, is_attack: true } ``` ### 方式 2:控制器组件(细粒度) 如需更多控制,请使用控制器组件: ``` class SessionsController < ApplicationController include AiBouncer::ControllerConcern # Protect all actions protect_from_attacks # Or protect specific actions with custom options protect_from_attacks only: [:create], threshold: 0.5, action: :block end ``` 或手动检查: ``` class PaymentsController < ApplicationController include AiBouncer::ControllerConcern def create check_for_attack # Blocks if attack detected # Normal flow continues... end end ``` ### 方式 3:手动分类 ``` result = AiBouncer.classify( AiBouncer.request_to_text( method: "POST", path: "/login", body: "username=admin'--&password=x", user_agent: "python-requests/2.28" ) ) result # => { # label: "sqli", # confidence: 0.94, # is_attack: true, # latency_ms: 2.1 # } ``` ## 添加自定义模式(数据库模式) ``` # 为您见过的特定攻击添加模式 embedding = AiBouncer.model.embed("POST /admin.php?cmd=wget...") AiBouncer::AttackPattern.create!( label: "scanner", severity: "high", embedding: embedding, sample_text: "POST /admin.php?cmd=wget...", source: "incident_2024_01" ) ``` ## Rake 任务 ``` # 手动下载模型文件(默认启用自动下载) rails ai_bouncer:download # 将内置模式种子写入数据库(仅限数据库模式) rails ai_bouncer:seed # 显示统计信息 rails ai_bouncer:stats # 测试分类 rails ai_bouncer:test # 基准测试性能 rails ai_bouncer:benchmark ``` ## 真实示例 ### SQL 注入 ``` # 认证绕过 AiBouncer.classify("POST /login username=admin' OR '1'='1 password=x") # => { label: "sqli", confidence: 0.94, is_attack: true } # 基于 UNION 的数据提取 AiBouncer.classify("GET /users?id=1 UNION SELECT username,password FROM users--") # => { label: "sqli", confidence: 0.96, is_attack: true } # 盲注 SQL 注入 AiBouncer.classify("GET /products?id=1 AND SLEEP(5)") # => { label: "sqli", confidence: 0.91, is_attack: true } ``` ### 跨站脚本攻击 (XSS) ``` # 评论中的脚本注入 AiBouncer.classify("POST /comments body=") # => { label: "xss", confidence: 0.96, is_attack: true } # 事件处理程序注入 AiBouncer.classify("POST /profile bio=") # => { label: "xss", confidence: 0.93, is_attack: true } # 基于 SVG 的 XSS AiBouncer.classify("POST /upload filename=.svg") # => { label: "xss", confidence: 0.89, is_attack: true } ``` ### 凭证填充 ``` # 使用浏览器类 UA 的自动登录尝试(常见于凭证填充僵尸网络) AiBouncer.classify("POST /wp-login.php UA:Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120") # => { label: "credential_stuffing", confidence: 0.94, is_attack: true } # 高频登录模式 AiBouncer.classify("POST /wp-login.php UA:Mozilla/5.0 (X11; Ubuntu; Linux x86_64) Chrome/119") # => { label: "credential_stuffing", confidence: 0.92, is_attack: true } ``` ### 垃圾机器人 ``` # 带有 referrer 模式的评论垃圾信息 AiBouncer.classify("POST /wp-comments-post.php REF:https://example.com/blog/article UA:Mozilla/5.0 (Windows NT 6.3) Chrome/103") # => { label: "spam_bot", confidence: 0.91, is_attack: true } # 旧版浏览器(常见于僵尸网络) AiBouncer.classify("POST /contact UA:Mozilla/5.0 (Windows NT 6.1; WOW64) Chrome/56.0.2924.87") # => { label: "spam_bot", confidence: 0.87, is_attack: true } ``` ### 漏洞扫描器 ``` # 带有 bot UA 的 WordPress 插件扫描 AiBouncer.classify("GET /wp-content/plugins/register-plus-redux UA:Mozilla/5.0 Chrome/126") # => { label: "scanner", confidence: 0.89, is_attack: true } # 带有 bot UA 的注册页面探测 AiBouncer.classify("GET /wp-login.php?action=register UA:Go-http-client/2.0") # => { label: "scanner", confidence: 0.85, is_attack: true } ``` ### 路径遍历 ``` # 用于读取系统文件的目录遍历 AiBouncer.classify("GET /files?path=../../../etc/passwd") # => { label: "path_traversal", confidence: 0.89, is_attack: true } # 编码遍历 AiBouncer.classify("GET /download?file=%2e%2e%2f%2e%2e%2f%2e%2e%2fetc/shadow") # => { label: "path_traversal", confidence: 0.87, is_attack: true } # Windows 路径遍历 AiBouncer.classify("GET /files?name=....\\....\\....\\windows\\system32\\config\\sam") # => { label: "path_traversal", confidence: 0.86, is_attack: true } ``` ### 命令注入 ``` # 参数中的 Shell 命令 AiBouncer.classify("GET /ping?host=127.0.0.1;cat /etc/passwd") # => { label: "command_injection", confidence: 0.93, is_attack: true } # 反引号注入 AiBouncer.classify("POST /convert filename=`whoami`.pdf") # => { label: "command_injection", confidence: 0.90, is_attack: true } # 管道注入 AiBouncer.classify("GET /search?q=test|ls -la") # => { label: "command_injection", confidence: 0.88, is_attack: true } ``` ### 干净请求(无误报) ``` # 正常登录 AiBouncer.classify("POST /login username=john.doe@example.com password=secretpass123") # => { label: "clean", confidence: 0.92, is_attack: false } # 正常 API 请求 AiBouncer.classify("GET /api/users/123") # => { label: "clean", confidence: 0.91, is_attack: false } # 分页 API 请求 AiBouncer.classify("GET /api/products?page=1&limit=20") # => { label: "clean", confidence: 0.99, is_attack: false } # 正常表单提交 AiBouncer.classify("POST /contact name=John Smith&email=john@example.com&message=Hello") # => { label: "clean", confidence: 0.95, is_attack: false } ``` ## 分类结果 ``` { label: "sqli", # Attack type or "clean" confidence: 0.94, # 0.0 - 1.0 is_attack: true, # Boolean latency_ms: 2.1, # Inference time storage: :memory, # or :database nearest_distance: 0.06, # Distance to nearest pattern neighbors: [ # K nearest neighbors { label: "sqli", distance: 0.06 }, { label: "sqli", distance: 0.08 }, ... ] } ``` ## 性能 基于 Apple Silicon 的基准测试: | Mode | Mean | P50 | P99 | |------|------|-----|-----| | Memory | 2ms | 2ms | 3ms | | Database | 5ms | 4ms | 8ms | ## 模型文件 模型托管在 HuggingFace:[khasinski/ai-bouncer](https://huggingface.co/khasinski/ai-bouncer) 首次请求时自动下载到 `vendor/ai_bouncer/`: | File | Size | Description | |------|------|-------------| | `embedding_model.onnx` | 29 MB | Model2Vec ONNX model | | `vocab.json` | 550 KB | Tokenizer vocabulary | | `vectors.bin` | 2.5 MB | Attack pattern vectors (memory mode) | | `labels.json` | 53 KB | Labels and metadata | ## 工作原理 1. **分词**:请求 → Unigram token 2. **嵌入**:Token → 256 维向量 (Model2Vec via ONNX) 3. **搜索**:查找 k=5 个最近的攻击模式 4. **投票**:对攻击类型进行加权投票 5. **决策**:如果置信度 > 阈值则拦截 ## 贡献训练数据 **帮助 AiBouncer 变得更好!** 该模型目前使用源自以下来源的平衡数据集(约 2,600 个模式): - 公开的安全 payload(SecLists, fuzzdb) - CSIC 2010 HTTP 数据集 - 真实 nginx 日志样本 我很想收集更多**真实流量数据**以提高检测准确性。如果您有权访问: - **攻击日志** - 来自 WAF 的拦截请求、失败的登录尝试、垃圾提交 - **干净流量** - 正常的 API 请求、合法的表单提交 - **误报** - 被错误标记为攻击的请求 请考虑贡献!您可以: 1. **分享匿名日志** - 移除敏感数据(IP、邮箱、密码)并提交 issue 2. **报告错误分类** - 让我知道模型哪里判断错了 3. **添加标记样本** - 欢迎提交包含新攻击模式的 PR 我们拥有的真实世界数据越多样化,模型对所有人就会越好。 联系方式:在 [github.com/khasinski/ai_bouncer](https://github.com/khasinski/ai_bouncer/issues) 提交 issue ## 许可证 MIT License. ## 贡献代码 1. Fork 本仓库 2. 创建您的功能分支 3. 提交您的更改 4. 推送到分支 5. 创建 Pull Request
标签:Apex, CISA项目, credential stuffing, DOE合作, Gem, HTTP请求分析, ONNX, RCE, Ruby on Rails, SSRF, WAF, Web安全, XSS, 中间件, 人工智能, 内存转储, 向量数据库, 应用防火墙, 异常检测, 批量扫描, 攻击识别, 机器学习, 测试用例, 漏洞情报, 用户模式Hook绕过, 网络安全, 蓝队分析, 隐私保护