人工智能黑客
AI 安全资源

安全人工智能开发

构建安全人工智能应用程序的完整开发人员指南 - 从输入验证到部署

Updated: November 2026

安全原则

1。深度防御

实施多层安全控制。不应完全依赖任何单一控制。

2.最低权限

向用户、API 和 AI 组件授予最低必要权限。

3.安全失败

发生错误时,默认为安全状态而不是许可状态。

4。零信任

永远不要相信,永远要验证。在每个边界进行验证,包括内部系统。

输入验证

所有用户输入在处理之前都必须经过验证和清理。这是抵御即时注入和其他攻击的第一道防线。

输入验证类

```python
import re
from typing import Optional, List

class InputValidator:
    # Known injection patterns
    INJECTION_PATTERNS = [
        r"ignore\s+(previous|prior|all)\s+(instructions|rules)",
        r"(forget|disregard)\s+(your|all)\s+(instructions|rules)",
        r"you\s+are\s+(now|still)\s+(dan|do\s+anything)",
        r"system\s+prompt:",
        r"{{.*}}",
        r"\[INST\]|\[/INST\]|<\|end\|>",
    ]
    
    # Encoding patterns
    ENCODING_PATTERNS = [
        r"base64:",  # Base64 prefix
        r"\\x[0-9a-fA-F]{2}",  # Hex encoding
        r"%[0-9a-fA-F]{2}",  # URL encoding
    ]
    
    def validate(self, user_input: str) -> dict:
        """Validate user input for potential attacks."""
        issues = []
        
        # Length check
        if len(user_input) > 10000:
            issues.append("Input exceeds maximum length")
        
        # Check for injection patterns
        for pattern in self.INJECTION_PATTERNS:
            if re.search(pattern, user_input, re.IGNORECASE):
                issues.append(f"Suspicious pattern detected: {pattern}")
        
        # Check for encoding attempts
        for pattern in self.ENCODED_PATTERNS:
            if re.search(pattern, user_input):
                issues.append(f"Encoded content detected")
        
        # Check for high entropy (possible encoding)
        unique_chars = len(set(user_input))
        if len(user_input) > 50 and unique_chars / len(user_input) < 0.3:
            issues.append("High entropy detected - possible encoding")
        
        return {
            "valid": len(issues) == 0,
            "issues": issues,
            "sanitized": self._sanitize(user_input)
        }
    
    def _sanitize(self, user_input: str) -> str:
        """Basic sanitization."""
        # Remove control characters
        sanitized = re.sub(r'[\x00-\x1F\x7F]', '', user_input)
        return sanitized.strip()
```

验证清单

  • 在应用程序边界进行验证
  • 检查输入长度
  • 注入模式匹配
  • 检测编码尝试
  • 类型验证
  • 处理前进行消毒
  • 日志验证失败
  • 速率限制

输出处理

LLM 输出在呈现给用户或传递给其他系统之前必须经过验证和清理。

内容过滤

  • 检查敏感数据暴露
  • 验证没有系统提示泄露
  • 验证输出格式
  • 检查注入的内容

PII 检测

  • 扫描个人信息
  • 掩盖或编辑敏感数据
  • 记录 PII 暴露尝试
  • 检测到时的用户通知

格式验证

  • 验证 JSON 输出
  • 检查预期结构
  • 验证允许的值
  • 清理HTML(如果适用)

输出处理程序示例

```python
import re
import json

class OutputHandler:
    PII_PATTERNS = {
        "ssn": r"\b\d{3}-\d{2}-\d{4}\b",
        "email": r"\b[\w.-]+@[\w.-]+\.\w+\b",
        "phone": r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b",
    }
    
    def process_output(self, raw_output: str) -> dict:
        """Process and validate LLM output."""
        result = {
            "original": raw_output,
            "cleaned": raw_output,
            "warnings": [],
            "blocked": False
        }
        
        # Check for system prompt leakage
        if "system prompt" in raw_output.lower():
            result["warnings"].append("System prompt reference detected")
        
        # Scan for PII
        for pii_type, pattern in self.PII_PATTERNS.items():
            matches = re.findall(pattern, raw_output)
            if matches:
                result["warnings"].append(f"{pii_type} detected in output")
                # Optionally mask
                result["cleaned"] = re.sub(pattern, "[REDACTED]", result["cleaned"])
        
        return result
```

API 安全

身份验证

  • 使用强大的 API 密钥管理
  • 尽可能实施 OAuth 2.0
  • JWT 令牌验证
  • API 密钥轮换

授权

  • 基于角色的访问控制 (RBAC)
  • API密钥范围
  • 每用户速率限制
  • 租户隔离

速率限制

  • 基于令牌的限制
  • 基于请求的限制
  • 成本控制
  • 分层限制

API 安全清单

  • 仅使用 HTTPS
  • 实施速率限制
  • 验证所有输入
  • 清理所有输出
  • 使用API​​密钥,而不是嵌入式
  • 实施请求签名
  • 记录 API 访问
  • 正确实施 CORS

身份验证和授权

用户身份验证

  • 强密码策略
  • MFA 支持
  • 会话管理
  • 令牌过期

API 身份验证

  • API 密钥管理
  • OAuth 范围
  • JWT 验证
  • 密钥轮换

授权

  • RBAC 实施
  • 权限检查
  • 资源级访问
  • 审计日志记录

数据安全

数据分类

  • 识别敏感数据
  • 按敏感度分类
  • 按类别应用控制
  • 定期审核

加密

  • 传输中的TLS
  • 静态 AES
  • 密钥管理
  • 密钥轮换

PII 处理

  • 检测
  • 最小化
  • 同意管理
  • 删除权

日志记录和监控

记录内容

安全事件

  • 身份验证尝试
  • 授权失败
  • 超出速率限制
  • 可疑模式

AI 特定事件

  • 提示注入尝试
  • 系统提示接入
  • 工具调用
  • 通过 AI 进行数据访问

操作事件

  • API调用
  • 错误和异常
  • 性能指标
  • 成本跟踪

监控最佳实践

  • 安全事件实时警报
  • 安全指标仪表板
  • 自动异常检测
  • 与 SIEM 集成
  • 定期日志审查
  • 保留策略

常见漏洞

1. AI功能中的IDOR

AI 访问资源时不安全的直接对象引用

示例

用户要求 AI“读取文件 X”,并且 AI 无需进行适当的授权检查即可访问。

2。通过LLM的SSRF

通过 AI 工具调用进行服务器端请求伪造

示例

提示欺骗 AI 向内部服务发出请求。

3.身份验证绕过

AI 端点身份验证薄弱或缺失

示例

未经适当身份验证检查的 AI API 端点。

4。 Vector DB Exposure

具有敏感嵌入的未受保护的矢量数据库

示例

带有嵌入式敏感数据的可公开访问的矢量数据库。

合规性

GDPR (EU)

  • 处理的合法基础
  • 数据最小化
  • 访问/删除权
  • 数据可移植性

CCPA (California)

  • 知情权
  • 删除权
  • 选择退出的权利
  • 非歧视

AI 特定

  • 欧盟人工智能法案要求
  • AI风险评估
  • 透明度义务
  • 人为监督

See the full framework breakdown in our AI security standards reference, including NIST AI RMF and ISO/IEC 42001.

AH
AI Hacking Team

The AI Hacking team researches and documents AI/LLM security vulnerabilities, red teaming techniques, and defensive strategies. Our guides are based on real-world pentesting experience and continuous monitoring of the AI security landscape.

Frequently Asked Questions

What are the key principles of secure AI development?
Key principles include: defense in depth, least privilege, fail secure, input validation, output sanitization, proper authentication/authorization, and comprehensive Logging. Treat all user input as untrusted and validate at every boundary.
How do I validate input in AI applications?
Input validation for AI includes: pattern matching for injection attempts, encoding detection (Base64, URL encoding), length limits, content type validation, and sanitization before processing. Always validate at the application boundary and before any AI processing.
What are common AI application vulnerabilities?
Common vulnerabilities include: prompt injection, IDOR in AI features, SSRF via LLM requests, authentication bypass, vector database exposure, excessive agency, and improper output handling. OWASP LLM Top 10 provides a comprehensive list.
How should I handle AI API keys securely?
Never hardcode API keys. Use environment variables, secrets management services (AWS Secrets Manager, HashiCorp Vault), rotate keys regularly, scope permissions minimally, implement rate limiting, and never expose keys in client-side code.

Stay Ahead of AI Security

Get the latest AI/LLM security research, OWASP updates, and new vulnerabilities delivered straight to your inbox.