影像注入技術
在影像中嵌入隱形或半隱形指令,使視覺語言模型誤將其視為合法提示詞。
概述
在影像中嵌入隱形或半隱形指令,使視覺語言模型誤將其視為合法提示詞。
此主題對於理解當前的 AI 安全態勢至關重要,並已成為大量研究關注的焦點。 Mehrotra et al. 2023 — "Tree of Attacks: Jailbreaking Black-Box LLMs with Auto-Generated Subtrees" (TAP) 為本文所探討的概念提供了基礎脈絡。
核心概念
基本原理
「this topic area」的安全影響源自於現代語言模型的設計、訓練與部署方式所具有的基本性質。這些問題並非孤立的漏洞,而是反映了以 Transformer 為基礎之語言模型的系統性特徵,必須整體性地加以理解。
在架構層級上,語言模型會以相同的注意力與前饋機制處理所有輸入符元 (token),不論其來源或預期的權限等級為何。這意味著系統提示詞、使用者輸入、工具輸出與檢索到的文件,都在相同的表徵空間中競爭模型的注意力。因此,安全邊界必須在外部強制執行,因為模型本身並沒有信任等級或資料分類的原生概念。
技術深入剖析
這類漏洞背後的機制,運作於模型的指令遵循能力與其無法驗證指令來源之間的互動。在訓練過程中,模型學會以特定格式與風格遵循指令。若攻擊者能以符合模型所學指令遵循模式的格式呈現對抗性內容,便可能影響模型行為。
# Demonstration of the core concept
from openai import OpenAI
client = OpenAI()
def demonstrate_concept(system_prompt: str, user_input: str) -> str:
"""Demonstrate the fundamental behavior pattern."""
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_input},
],
temperature=0.0,
)
return response.choices[0].message.content
# Baseline behavior
baseline = demonstrate_concept(
system_prompt="You are a helpful assistant that only discusses cooking.",
user_input="What is the capital of France?",
)
print(f"Baseline: {baseline}")攻擊面分析
此類漏洞的攻擊面包括:
| 攻擊向量 | 說明 | 難度 | 影響 |
|---|---|---|---|
| 直接輸入 | 使用者訊息中的對抗性內容 | 低 | 視情況而定 |
| 間接輸入 | 外部資料中的對抗性內容 | 中 | 高 |
| 工具輸出 | 函式結果中的對抗性內容 | 中 | 高 |
| 上下文操縱 | 利用上下文視窗動態 | 高 | 高 |
| 訓練階段 | 投毒訓練或微調資料 | 非常高 | 嚴重 |
實務應用
技術實作
在實務中實作此技術,需要同時理解攻擊方法論與目標系統的防禦態勢。
import json
from typing import Optional
class TechniqueFramework:
"""Framework for implementing and testing the described technique."""
def __init__(self, target_config: dict):
self.config = target_config
self.results = []
def prepare_payload(self, objective: str, constraints: dict) -> str:
"""Prepare the attack payload based on the objective and target constraints."""
# Adapt payload to target's defensive posture
payload = self._base_payload(objective)
if constraints.get("input_classifier"):
payload = self._apply_obfuscation(payload)
if constraints.get("output_filter"):
payload = self._add_extraction_channel(payload)
return payload
def execute(self, payload: str) -> dict:
"""Execute the technique and collect results."""
response = self._send_to_target(payload)
success = self._evaluate_response(response)
result = {
"payload_hash": hash(payload),
"success": success,
"response_length": len(str(response)),
}
self.results.append(result)
return result
def report(self) -> dict:
"""Generate a summary report of all execution results."""
total = len(self.results)
successes = sum(1 for r in self.results if r["success"])
return {
"total_attempts": total,
"successes": successes,
"success_rate": successes / total if total > 0 else 0,
}防禦考量
對於攻擊與防禦雙方的實務工作者而言,理解防禦措施都是必要的:
- 輸入驗證:透過分類模型對使用者輸入進行預處理,在其抵達目標 LLM 之前偵測對抗性模式
- 輸出過濾:對模型輸出進行後處理,以偵測並移除敏感資料、指令殘跡,以及其他成功利用的指標
- 行為監控:即時監控模型行為模式,以偵測可能代表攻擊正在進行的異常回應
- 架構設計:設計應用程式架構,以最小化對模型輸出的信任,並在外部強制執行安全邊界
真實世界的關聯
此主題領域與各產業的正式環境 AI 部署直接相關。 Chao et al. 2023 — "Jailbreaking Black-Box Large Language Models in Twenty Queries" (PAIR) 記錄了已部署系統中此類漏洞在真實世界中的利用情況。
部署 LLM 驅動應用程式的組織應:
- 評估:針對此類漏洞執行專門的紅隊評估
- 防禦:實施與風險等級相稱的縱深防禦措施
- 監控:部署能即時偵測利用嘗試的監控機制
- 回應:維護針對 AI 系統遭入侵的事件回應程序
- 迭代:隨著攻擊與模型持續演進,定期重新測試防禦能力
目前的研究方向
此領域的前沿研究集中於下列幾個方向:
- 形式化驗證:為模型在對抗條件下的行為發展數學保證
- 穩健性訓練:產生對此攻擊類型更具抗性的訓練流程
- 偵測方法:以低誤報率偵測利用嘗試的改良技術
- 標準化評估:使用 HarmBench、JailbreakBench 等基準測試套件來衡量進展
實作考量
架構模式
在實作與 LLM 互動的系統時,有幾種架構模式會影響整體應用程式的安全態勢:
閘道器模式:在使用者與 LLM 之間設置專用的 API 閘道器,負責認證、速率限制、輸入驗證與輸出過濾。這種設計讓安全控制集中化,但也形成單一故障點。
from dataclasses import dataclass
from typing import Optional
import time
@dataclass
class SecurityGateway:
"""Gateway pattern for securing LLM application access."""
input_classifier: object # ML-based input classifier
output_filter: object # Output content filter
rate_limiter: object # Rate limiting service
audit_logger: object # Audit trail logger
def process_request(self, user_id: str, message: str, session_id: str) -> dict:
"""Process a request through all security layers."""
request_id = self._generate_request_id()
# Layer 1: Rate limiting
if not self.rate_limiter.allow(user_id):
self.audit_logger.log(request_id, "rate_limited", user_id)
return {"error": "Rate limit exceeded", "retry_after": 60}
# Layer 2: Input classification
classification = self.input_classifier.classify(message)
if classification.is_adversarial:
self.audit_logger.log(
request_id, "input_blocked",
user_id, classification.category
)
return {"error": "Request could not be processed"}
# Layer 3: LLM processing
response = self._call_llm(message, session_id)
# Layer 4: Output filtering
filtered = self.output_filter.filter(response)
if filtered.was_modified:
self.audit_logger.log(
request_id, "output_filtered",
user_id, filtered.reason
)
# Layer 5: Audit logging
self.audit_logger.log(
request_id, "completed",
user_id, len(message), len(filtered.content)
)
return {"response": filtered.content}
def _generate_request_id(self) -> str:
import uuid
return str(uuid.uuid4())
def _call_llm(self, message: str, session_id: str) -> str:
# LLM API call implementation
pass邊車 (Sidecar) 模式:安全元件以獨立服務的形式與 LLM 並行運作,各自負責特定的安全面向。這種方式提供更好的隔離與獨立擴展性,但會增加系統複雜度。
網格 (Mesh) 模式:對於多代理系統,每個代理都擁有自己的安全邊界,包含認證、授權與稽核。代理之間的通訊遵循零信任原則。
效能影響
安全措施不可避免地會增加延遲與運算開銷。理解這些取捨對正式環境部署至關重要:
| 安全層 | 典型延遲 | 運算成本 | 對使用者體驗的影響 |
|---|---|---|---|
| 關鍵字過濾 | <1ms | 可忽略 | 無 |
| 正規表達式過濾 | 1-5ms | 低 | 無 |
| ML 分類器 (小型) | 10-50ms | 中等 | 極小 |
| ML 分類器 (大型) | 50-200ms | 高 | 可察覺 |
| LLM 作為裁判 | 500-2000ms | 非常高 | 顯著 |
| 完整流水線 | 100-500ms | 高 | 中等 |
建議採用的方式是先使用快速、輕量的檢查 (關鍵字與正規表達式過濾) 攔截明顯的攻擊,再對通過初步過濾的輸入進行更昂貴的 ML 分析。這種級聯式做法能在可接受的效能下提供良好的安全性。
監控與可觀測性
對 LLM 應用程式進行有效的安全監控,需要追蹤能捕捉對抗性行為模式的指標:
from dataclasses import dataclass
from collections import defaultdict
import time
@dataclass
class SecurityMetrics:
"""Track security-relevant metrics for LLM applications."""
# Counters
total_requests: int = 0
blocked_requests: int = 0
filtered_outputs: int = 0
anomalous_sessions: int = 0
# Rate tracking
_request_times: list = None
_block_times: list = None
def __post_init__(self):
self._request_times = []
self._block_times = []
def record_request(self, was_blocked: bool = False, was_filtered: bool = False):
"""Record a request and its disposition."""
now = time.time()
self.total_requests += 1
self._request_times.append(now)
if was_blocked:
self.blocked_requests += 1
self._block_times.append(now)
if was_filtered:
self.filtered_outputs += 1
def get_block_rate(self, window_seconds: int = 300) -> float:
"""Calculate the block rate over a time window."""
now = time.time()
cutoff = now - window_seconds
recent_requests = sum(1 for t in self._request_times if t > cutoff)
recent_blocks = sum(1 for t in self._block_times if t > cutoff)
if recent_requests == 0:
return 0.0
return recent_blocks / recent_requests
def should_alert(self) -> bool:
"""Determine if current metrics warrant an alert."""
block_rate = self.get_block_rate()
# Alert if block rate exceeds threshold
if block_rate > 0.3: # >30% of requests blocked in last 5 min
return True
return FalseCI/CD 中的安全測試
將 AI 安全測試整合到開發流水線中,能在迴歸問題進入正式環境前及早發現:
- 單元層級測試:對照已知載荷測試個別安全元件 (分類器、過濾器)
- 整合測試:端到端測試完整的安全流水線
- 迴歸測試:維護一套先前發現的攻擊載荷,並驗證它們仍被封鎖
- 對抗性測試:定期將自動化紅隊工具 (Garak、Promptfoo) 作為部署流水線的一部分執行
新興趨勢
目前的研究方向
LLM 安全領域正在快速演進。可能形塑未來樣貌的關鍵研究方向包括:
-
LLM 行為的形式化驗證:研究人員正在探索數學框架,用以證明模型在對抗條件下的行為性質。儘管神經網路的完整形式化驗證仍屬難以處理,針對特定性質的有界驗證已展現潛力。
-
LLM 穩健性的對抗性訓練:除了標準的 RLHF,研究人員正在開發在安全訓練過程中明確讓模型接觸對抗性輸入的訓練流程,以提升對已知攻擊模式的抗性。
-
可解釋性導向的防禦:機制可解釋性研究讓防禦方能在神經元與電路層級理解特定攻擊為何能成功,進而推動更具針對性的防禦措施。
-
多代理安全:隨著 LLM 代理日漸普及,保護代理間通訊並在代理系統中維持信任邊界,已成為具有重大實務意義的活躍研究領域。
-
大規模自動化紅隊:NVIDIA 的 Garak、Microsoft 的 PyRIT,以及英國 AISI 的 Inspect 框架等工具,正讓前所未有規模的自動化安全測試成為可能,但自動化測試的品質與覆蓋率仍是尚未解決的挑戰。
將這些研究方向整合到正式環境系統中,將定義下一世代的 AI 安全實務。
實作考量
架構模式
在實作與 LLM 互動的系統時,有幾種架構模式會影響整體應用程式的安全態勢:
閘道器模式:在使用者與 LLM 之間設置專用的 API 閘道器,負責認證、速率限制、輸入驗證與輸出過濾。這種設計讓安全控制集中化,但也形成單一故障點。
from dataclasses import dataclass
from typing import Optional
import time
@dataclass
class SecurityGateway:
"""Gateway pattern for securing LLM application access."""
input_classifier: object # ML-based input classifier
output_filter: object # Output content filter
rate_limiter: object # Rate limiting service
audit_logger: object # Audit trail logger
def process_request(self, user_id: str, message: str, session_id: str) -> dict:
"""Process a request through all security layers."""
request_id = self._generate_request_id()
# Layer 1: Rate limiting
if not self.rate_limiter.allow(user_id):
self.audit_logger.log(request_id, "rate_limited", user_id)
return {"error": "Rate limit exceeded", "retry_after": 60}
# Layer 2: Input classification
classification = self.input_classifier.classify(message)
if classification.is_adversarial:
self.audit_logger.log(
request_id, "input_blocked",
user_id, classification.category
)
return {"error": "Request could not be processed"}
# Layer 3: LLM processing
response = self._call_llm(message, session_id)
# Layer 4: Output filtering
filtered = self.output_filter.filter(response)
if filtered.was_modified:
self.audit_logger.log(
request_id, "output_filtered",
user_id, filtered.reason
)
# Layer 5: Audit logging
self.audit_logger.log(
request_id, "completed",
user_id, len(message), len(filtered.content)
)
return {"response": filtered.content}
def _generate_request_id(self) -> str:
import uuid
return str(uuid.uuid4())
def _call_llm(self, message: str, session_id: str) -> str:
# LLM API call implementation
pass邊車 (Sidecar) 模式:安全元件以獨立服務的形式與 LLM 並行運作,各自負責特定的安全面向。這種方式提供更好的隔離與獨立擴展性,但會增加系統複雜度。
網格 (Mesh) 模式:對於多代理系統,每個代理都擁有自己的安全邊界,包含認證、授權與稽核。代理之間的通訊遵循零信任原則。
效能影響
安全措施不可避免地會增加延遲與運算開銷。理解這些取捨對正式環境部署至關重要:
| 安全層 | 典型延遲 | 運算成本 | 對使用者體驗的影響 |
|---|---|---|---|
| 關鍵字過濾 | <1ms | 可忽略 | 無 |
| 正規表達式過濾 | 1-5ms | 低 | 無 |
| ML 分類器 (小型) | 10-50ms | 中等 | 極小 |
| ML 分類器 (大型) | 50-200ms | 高 | 可察覺 |
| LLM 作為裁判 | 500-2000ms | 非常高 | 顯著 |
| 完整流水線 | 100-500ms | 高 | 中等 |
建議採用的方式是先使用快速、輕量的檢查 (關鍵字與正規表達式過濾) 攔截明顯的攻擊,再對通過初步過濾的輸入進行更昂貴的 ML 分析。這種級聯式做法能在可接受的效能下提供良好的安全性。
監控與可觀測性
對 LLM 應用程式進行有效的安全監控,需要追蹤能捕捉對抗性行為模式的指標:
from dataclasses import dataclass
from collections import defaultdict
import time
@dataclass
class SecurityMetrics:
"""Track security-relevant metrics for LLM applications."""
# Counters
total_requests: int = 0
blocked_requests: int = 0
filtered_outputs: int = 0
anomalous_sessions: int = 0
# Rate tracking
_request_times: list = None
_block_times: list = None
def __post_init__(self):
self._request_times = []
self._block_times = []
def record_request(self, was_blocked: bool = False, was_filtered: bool = False):
"""Record a request and its disposition."""
now = time.time()
self.total_requests += 1
self._request_times.append(now)
if was_blocked:
self.blocked_requests += 1
self._block_times.append(now)
if was_filtered:
self.filtered_outputs += 1
def get_block_rate(self, window_seconds: int = 300) -> float:
"""Calculate the block rate over a time window."""
now = time.time()
cutoff = now - window_seconds
recent_requests = sum(1 for t in self._request_times if t > cutoff)
recent_blocks = sum(1 for t in self._block_times if t > cutoff)
if recent_requests == 0:
return 0.0
return recent_blocks / recent_requests
def should_alert(self) -> bool:
"""Determine if current metrics warrant an alert."""
block_rate = self.get_block_rate()
# Alert if block rate exceeds threshold
if block_rate > 0.3: # >30% of requests blocked in last 5 min
return True
return FalseCI/CD 中的安全測試
將 AI 安全測試整合到開發流水線中,能在迴歸問題進入正式環境前及早發現:
- 單元層級測試:對照已知載荷測試個別安全元件 (分類器、過濾器)
- 整合測試:端到端測試完整的安全流水線
- 迴歸測試:維護一套先前發現的攻擊載荷,並驗證它們仍被封鎖
- 對抗性測試:定期將自動化紅隊工具 (Garak、Promptfoo) 作為部署流水線的一部分執行
新興趨勢
目前的研究方向
LLM 安全領域正在快速演進。可能形塑未來樣貌的關鍵研究方向包括:
-
LLM 行為的形式化驗證:研究人員正在探索數學框架,用以證明模型在對抗條件下的行為性質。儘管神經網路的完整形式化驗證仍屬難以處理,針對特定性質的有界驗證已展現潛力。
-
LLM 穩健性的對抗性訓練:除了標準的 RLHF,研究人員正在開發在安全訓練過程中明確讓模型接觸對抗性輸入的訓練流程,以提升對已知攻擊模式的抗性。
-
可解釋性導向的防禦:機制可解釋性研究讓防禦方能在神經元與電路層級理解特定攻擊為何能成功,進而推動更具針對性的防禦措施。
-
多代理安全:隨著 LLM 代理日漸普及,保護代理間通訊並在代理系統中維持信任邊界,已成為具有重大實務意義的活躍研究領域。
-
大規模自動化紅隊:NVIDIA 的 Garak、Microsoft 的 PyRIT,以及英國 AISI 的 Inspect 框架等工具,正讓前所未有規模的自動化安全測試成為可能,但自動化測試的品質與覆蓋率仍是尚未解決的挑戰。
將這些研究方向整合到正式環境系統中,將定義下一世代的 AI 安全實務。
參考文獻與延伸閱讀
- Mehrotra et al. 2023 — "Tree of Attacks: Jailbreaking Black-Box LLMs with Auto-Generated Subtrees" (TAP)
- Chao et al. 2023 — "Jailbreaking Black-Box Large Language Models in Twenty Queries" (PAIR)
- Shokri et al. 2017 — "Membership Inference Attacks Against Machine Learning Models"
針對本文所涵蓋的攻擊類型,最有效的防禦方式是什麼?
為何本文描述的技術能在不同模型版本與供應商之間仍然有效?