Agent安全工程实现

admin 2026-09-10 04:31:43 网络安全文章 来源:ZONE.CI 全球网 0 阅读模式

文章总结: 本文介绍agent安全工程实现,重点包括沙箱架构设计(工具执行沙箱、资源隔离与审计日志、权限模型及动态调整、权限组合检测)以及HITL工程实现(风险分级引擎、确认流程与批量确认)。核心思想是通过沙箱隔离、权限最小化、风险分级和人工审批来保障agent调用外部工具的安全性,防止提示注入和危险操作。 综合评分: 82 文章分类: 安全开发,安全建设,应用安全


Agent安全工程实现

原创

pandazhengzheng pandazhengzheng

安全分析与研究

2026年9月9日 22:00 广东

在小说阅读器读本章

去阅读

在公众号小说中沉浸阅读

一、沙箱架构设计

Agent调用外部工具时,工具执行必须在沙箱内进行,防止提示注入导致的危险操作。

1.1 工具执行沙箱

import subprocess
import resource
from dataclasses import dataclass

@dataclass
class SandboxConfig:
    timeout_seconds: int = 30
    max_memory_mb: int = 512
    max_cpu_percent: int = 50
    max_file_size_mb: int = 10
    allowed_paths: list = None
    network_allowed: bool = False

class ToolSandbox:
    def __init__(self, config: SandboxConfig):
        self.config = config

    def execute(self, tool, args):
        # 1. 参数校验
        if not self._validate_args(tool, args):
            return {"error": "invalid_args"}
        # 2. 路径白名单检查
        if not self._check_paths(args):
            return {"error": "path_not_allowed"}
        # 3. 在隔离环境中执行
        try:
            result = self._run_isolated(tool.command, args)
            return result
        except subprocess.TimeoutExpired:
            return {"error": "timeout"}
        except Exception as e:
            return {"error": str(e)}

    def _run_isolated(self, command, args):
        # 用容器/进程隔离执行
        proc = subprocess.run(
            [command] + args,
            timeout=self.config.timeout_seconds,
            capture_output=True,
            env=self._sandbox_env(),
            # 在Linux下可加unshare做命名空间隔离
        )
        return {"stdout": proc.stdout, "stderr": proc.stderr, "code": proc.returncode}

    def _sandbox_env(self):
        env = {"PATH": "/usr/bin:/bin"}
        if not self.config.network_allowed:
            env["NO_NETWORK"] = "1"
        return env

1.2 资源隔离与审计日志

class AuditedSandbox(ToolSandbox):
    def __init__(self, config, audit_logger):
        super().__init__(config)
        self.audit = audit_logger

    def execute(self, tool, args, context):
        self.audit.log(
            action="tool_call_start",
            tool=tool.name,
            args=self._redact(args),
            agent_id=context.agent_id,
            timestamp=time.now(),
        )
        result = super().execute(tool, args)
        self.audit.log(
            action="tool_call_end",
            tool=tool.name,
            result_status=result.get("error", "success"),
            duration_ms=result.get("duration"),
        )
        return result

    def _redact(self, args):
        """脱敏参数中的敏感字段"""
        redacted = {}
        for k, v in args.items():
            if k in self.sensitive_fields:
                redacted[k] = "[REDACTED]"
            else:
                redacted[k] = v
        return redacted

1.3 权限模型

from enum import Enum

class Permission(Enum):
    READ_FILE = "read_file"
    WRITE_FILE = "write_file"
    EXECUTE = "execute"
    NETWORK = "network"
    DELETE = "delete"

class PermissionModel:
    def __init__(self, agent_role, permissions):
        self.role = agent_role
        self.permissions = permissions  # 该角色允许的权限集

    def check(self, action, resource=None):
        if action not in self.permissions:
            return False
        # 资源级权限检查
        if resource and not self._resource_allowed(action, resource):
            return False
        return True

    def _resource_allowed(self, action, resource):
        # 文件路径白名单
        if action == Permission.READ_FILE:
            return any(
                resource.startswith(prefix)
                for prefix in self.allowed_read_paths
            )
        if action == Permission.WRITE_FILE:
            return any(
                resource.startswith(prefix)
                for prefix in self.allowed_write_paths
            )
        return False

1.4 动态权限调整

class DynamicPermissionManager:
    def __init__(self, base_permissions, risk_monitor):
        self.base = base_permissions
        self.risk = risk_monitor
        self.current = base_permissions.copy()

    def adjust(self, context):
        risk_score = self.risk.assess(context)
        if risk_score > 0.8:
            # 高风险时收紧权限
            self.current = self._restrict(self.base)
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;elif&nbsp;risk_score <&nbsp;0.3:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.current = self.base
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;self.current

&nbsp; &nbsp;&nbsp;def&nbsp;_restrict(self, permissions):
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 移除高风险权限
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;permissions - {Permission.WRITE_FILE, Permission.DELETE, Permission.EXECUTE}

1.5 权限组合检测

某些权限单独安全但组合危险(如读文件+网络=数据外泄):

class&nbsp;PermissionCombinationChecker:
&nbsp; &nbsp;&nbsp;def&nbsp;__init__(self):
&nbsp; &nbsp; &nbsp; &nbsp; self.dangerous_combos = [
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {Permission.READ_FILE, Permission.NETWORK}, &nbsp;# 数据外泄
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {Permission.WRITE_FILE, Permission.EXECUTE}, &nbsp;# 持久化
&nbsp; &nbsp; &nbsp; &nbsp; ]

&nbsp; &nbsp;&nbsp;def&nbsp;check(self, requested_permissions):
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;for&nbsp;combo&nbsp;in&nbsp;self.dangerous_combos:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;combo.issubset(requested_permissions):
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;False,&nbsp;f"dangerous_combination:&nbsp;{combo}"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;True,&nbsp;"ok"

二、HITL工程实现

2.1 风险分级引擎

class&nbsp;RiskAssessor:
&nbsp; &nbsp;&nbsp;def&nbsp;__init__(self, weights):
&nbsp; &nbsp; &nbsp; &nbsp; self.weights = weights

&nbsp; &nbsp;&nbsp;def&nbsp;assess(self, action, context):
&nbsp; &nbsp; &nbsp; &nbsp; score =&nbsp;0
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 影响面
&nbsp; &nbsp; &nbsp; &nbsp; score += self.weights["impact"] * self._impact(action, context)
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 可逆性
&nbsp; &nbsp; &nbsp; &nbsp; score += self.weights["irreversibility"] * (1&nbsp;- action.reversibility)
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 资产价值
&nbsp; &nbsp; &nbsp; &nbsp; score += self.weights["asset_value"] * context.asset_value
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 偏离常规
&nbsp; &nbsp; &nbsp; &nbsp; score += self.weights["novelty"] * self._novelty(action, context)
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;score

&nbsp; &nbsp;&nbsp;def&nbsp;_impact(self, action, context):
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;action.type ==&nbsp;"delete":
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;1.0
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;action.type ==&nbsp;"isolate_host":
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;0.8
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;action.type ==&nbsp;"block_ip":
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;0.3
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;0.1

2.2 确认界面与异步确认流程

class&nbsp;HITLConfirmFlow:
&nbsp; &nbsp;&nbsp;def&nbsp;__init__(self, threshold=0.7, timeout="4h"):
&nbsp; &nbsp; &nbsp; &nbsp; self.threshold = threshold
&nbsp; &nbsp; &nbsp; &nbsp; self.timeout = timeout

&nbsp; &nbsp;&nbsp;async&nbsp;def&nbsp;gate(self, action, context):
&nbsp; &nbsp; &nbsp; &nbsp; risk = self.risk_assessor.assess(action, context)
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;risk < self.threshold:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;{"approved":&nbsp;True,&nbsp;"auto":&nbsp;True}
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 创建确认工单
&nbsp; &nbsp; &nbsp; &nbsp; ticket = self._create_ticket(action, context, risk)
&nbsp; &nbsp; &nbsp; &nbsp; self._notify_analyst(ticket)
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;try:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; decision =&nbsp;await&nbsp;self._await_decision(ticket, self.timeout)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self._audit(decision)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;decision
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;except&nbsp;TimeoutError:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 超时降级:不执行,升级
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self._escalate(ticket)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;{"approved":&nbsp;False,&nbsp;"reason":&nbsp;"timeout"}

2.3 批量确认与审计

class&nbsp;BatchHITL:
&nbsp; &nbsp;&nbsp;"""对同类低风险动作批量确认,避免确认疲劳"""
&nbsp; &nbsp;&nbsp;def&nbsp;__init__(self, max_batch=10, similarity_threshold=0.9):
&nbsp; &nbsp; &nbsp; &nbsp; self.max_batch = max_batch
&nbsp; &nbsp; &nbsp; &nbsp; self.similarity = similarity_threshold
&nbsp; &nbsp; &nbsp; &nbsp; self.pending = []

&nbsp; &nbsp;&nbsp;def&nbsp;submit(self, action, context):
&nbsp; &nbsp; &nbsp; &nbsp; self.pending.append((action, context))
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;self._can_batch():
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;self._request_batch_confirmation()
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;self._request_single_confirmation(action, context)

&nbsp; &nbsp;&nbsp;def&nbsp;_can_batch(self):
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;len(self.pending) <&nbsp;2:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;False
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 检查待确认动作是否足够相似
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;for&nbsp;i&nbsp;in&nbsp;range(len(self.pending) -&nbsp;1):
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;self._similarity(self.pending[i], self.pending[-1]) < self.similarity:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;False
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;len(self.pending) >= self.max_batch&nbsp;or&nbsp;True

三、双LLM模式实现

双LLM模式(来自Anthropic的方案):外层不可信LLM做规划,内层特权LLM做执行,两者通信受严格协议约束。

3.1 特权分离架构

用户输入 ─► [外层LLM(不可信)] ─► 动作提案 ─► [协议校验] ─► [内层LLM(特权)] ─► 执行
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ▲ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;│
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; └───────────── 执行结果(受限) ◄─────────────────────┘
class&nbsp;DualLLMArchitecture:
&nbsp; &nbsp;&nbsp;def&nbsp;__init__(self, outer_llm, inner_llm, protocol, sandbox):
&nbsp; &nbsp; &nbsp; &nbsp; self.outer = outer_llm &nbsp; &nbsp; &nbsp;# 不可信,做规划
&nbsp; &nbsp; &nbsp; &nbsp; self.inner = inner_llm &nbsp; &nbsp; &nbsp;# 特权,做执行
&nbsp; &nbsp; &nbsp; &nbsp; self.protocol = protocol &nbsp; &nbsp;# 通信协议
&nbsp; &nbsp; &nbsp; &nbsp; self.sandbox = sandbox

&nbsp; &nbsp;&nbsp;def&nbsp;run(self, user_input, context):
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;for&nbsp;step&nbsp;in&nbsp;range(self.max_steps):
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 1. 外层LLM生成动作提案
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; proposal = self.outer.propose(user_input, context)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 2. 协议校验:提案是否符合允许的动作格式
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;not&nbsp;self.protocol.validate(proposal):
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context.add_warning("invalid_proposal")
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;continue
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 3. 内层LLM执行(在沙箱内)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = self.sandbox.execute(self.inner, proposal, context)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 4. 受限结果回传外层(不含敏感细节)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; filtered = self.protocol.filter_result(result)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context.update(filtered)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;self._is_complete(filtered):
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;break
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;context

3.2 通信协议

class&nbsp;DualLLMProtocol:
&nbsp; &nbsp;&nbsp;def&nbsp;__init__(self, allowed_actions, sensitive_fields):
&nbsp; &nbsp; &nbsp; &nbsp; self.allowed = allowed_actions
&nbsp; &nbsp; &nbsp; &nbsp; self.sensitive = sensitive_fields

&nbsp; &nbsp;&nbsp;def&nbsp;validate(self, proposal):
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;proposal.action&nbsp;not&nbsp;in&nbsp;self.allowed:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;False
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;not&nbsp;self._check_args_schema(proposal):
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;False
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;True

&nbsp; &nbsp;&nbsp;def&nbsp;filter_result(self, result):
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;"""内层→外层的返回结果过滤"""
&nbsp; &nbsp; &nbsp; &nbsp; filtered = {}
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;for&nbsp;k, v&nbsp;in&nbsp;result.items():
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;k&nbsp;in&nbsp;self.sensitive:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; filtered[k] =&nbsp;"[FILTERED]"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;else:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; filtered[k] = v
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;filtered

3.3 降级策略

当内层LLM不可用时:

class&nbsp;DualLLMWithFallback(DualLLMArchitecture):
&nbsp; &nbsp;&nbsp;def&nbsp;run(self, user_input, context):
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;try:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;super().run(user_input, context)
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;except&nbsp;InnerLLMUnavailable:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 降级为单LLM模式 + 严格HITL
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;self._fallback_single_llm(user_input, context)

&nbsp; &nbsp;&nbsp;def&nbsp;_fallback_single_llm(self, user_input, context):
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 每个动作都需HITL确认
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;for&nbsp;step&nbsp;in&nbsp;range(self.max_steps):
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; proposal = self.outer.propose(user_input, context)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;not&nbsp;self.hitl.gate(proposal, context).approved:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;continue
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = self.sandbox.execute_direct(proposal)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context.update(result)
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;context

四、提示注入防御工程

4.1 输入净化

class&nbsp;PromptInjectionGuard:
&nbsp; &nbsp;&nbsp;def&nbsp;__init__(self, patterns, llm_judge):
&nbsp; &nbsp; &nbsp; &nbsp; self.patterns = patterns &nbsp;# 已知注入模式
&nbsp; &nbsp; &nbsp; &nbsp; self.llm = llm_judge

&nbsp; &nbsp;&nbsp;def&nbsp;check(self, user_input, system_prompt):
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 1. 模式匹配
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;for&nbsp;pattern&nbsp;in&nbsp;self.patterns:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;pattern.match(user_input):
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;{"blocked":&nbsp;True,&nbsp;"reason":&nbsp;"pattern_match"}
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 2. LLM语义判定:输入是否试图覆盖系统指令
&nbsp; &nbsp; &nbsp; &nbsp; verdict = self.llm.check_override_attempt(user_input, system_prompt)
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;verdict.is_injection:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;{"blocked":&nbsp;True,&nbsp;"reason":&nbsp;"semantic_injection"}
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;{"blocked":&nbsp;False}

4.2 输出过滤

class&nbsp;OutputFilter:
&nbsp; &nbsp;&nbsp;def&nbsp;__init__(self, policy):
&nbsp; &nbsp; &nbsp; &nbsp; self.policy = policy

&nbsp; &nbsp;&nbsp;def&nbsp;filter(self, output, context):
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 1. 检查是否包含未授权的工具调用
&nbsp; &nbsp; &nbsp; &nbsp; tool_calls = self._extract_tool_calls(output)
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;for&nbsp;call&nbsp;in&nbsp;tool_calls:
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;not&nbsp;self.policy.allow(call):
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;self._redact_call(output, call)
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 2. 检查是否泄露系统提示
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;self._contains_system_prompt(output, context):
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;self._redact_system(output)
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;output

五、实战案例

5.1 企业Agent系统的安全架构

某企业部署内部运维Agent,可执行查询、配置修改、服务重启等操作。

架构

  • 双LLM模式:外层GPT-4做规划,内层专用小模型做执行。
  • 三级权限:只读(自动)、配置修改(HITL确认)、破坏性操作(双人确认)。
  • 全量审计:每个动作记录Agent推理链、工具调用、HITL决策。

经验教训

  • 早期外层LLM可直接调用工具,发生过”Agent误将生产配置当作测试配置修改”。改为双LLM后,内层LLM对”生产”关键词强制触发HITL。
  • HITL确认曾因通知渠道单一(仅邮件)导致响应慢,后增加IM推送,平均确认时间从2小时降至15分钟。
  • 权限组合检测发现过”Agent先读敏感文件再发起网络请求”的可疑序列,及时阻断潜在数据外泄。

5.2 MCP安全网关实现

某企业使用MCP(Model Context Protocol)连接多个工具服务器,需统一安全网关。

class&nbsp;MCPSecurityGateway:

`


免责声明:

本文所载程序、技术方法仅面向合法合规的安全研究与教学场景,旨在提升网络安全防护能力,具有明确的技术研究属性。

任何单位或个人未经授权,将本文内容用于攻击、破坏等非法用途的,由此引发的全部法律责任、民事赔偿及连带责任,均由行为人独立承担,本站不承担任何连带责任。

本站内容均为技术交流与知识分享目的发布,若存在版权侵权或其他异议,请通过邮件联系处理,具体联系方式可点击页面上方的联系我

本文转载自:安全分析与研究 pandazhengzheng pandazhengzheng《Agent安全工程实现》

Agent安全工程实现 网络安全文章

Agent安全工程实现

文章总结: 本文介绍agent安全工程实现,重点包括沙箱架构设计(工具执行沙箱、资源隔离与审计日志、权限模型及动态调整、权限组合检测)以及HITL工程实现(风险
评论:0   参与:  0