security-audit

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Security Audit Skill

安全审计技能

Security audits, vulnerability assessment, and secure coding patterns aligned with OWASP.
符合OWASP标准的安全审计、漏洞评估和安全编码模式。

Expertise Areas

专业领域

  • Vulnerabilities: XXE, SQL injection, XSS, CSRF, auth flaws, insecure deserialization
  • Risk Scoring: CVSS v3.1 methodology
  • Secure Coding: Input validation, output encoding, cryptography, session management
  • 漏洞类型: XXE、SQL注入、XSS、CSRF、认证缺陷、不安全反序列化
  • 风险评分: CVSS v3.1 方法论
  • 安全编码: 输入校验、输出编码、密码学、会话管理

OWASP Top 10 (2021)

OWASP Top 10 (2021)

RankCategoryDescription
A01Broken Access ControlUnauthorized access to resources
A02Cryptographic FailuresWeak encryption, exposed secrets
A03InjectionSQL, NoSQL, OS, LDAP injection
A04Insecure DesignMissing security controls by design
A05Security MisconfigurationDefault configs, verbose errors
A06Vulnerable ComponentsOutdated libraries with CVEs
A07Auth FailuresBroken authentication/session
A08Data Integrity FailuresInsecure deserialization, CI/CD
A09Logging FailuresMissing audit logs, monitoring
A10SSRFServer-side request forgery
排名类别描述
A01失效的访问控制资源未授权访问
A02加密失效弱加密、密钥泄露
A03注入SQL、NoSQL、操作系统、LDAP注入
A04不安全设计设计层面缺失安全控制
A05安全配置错误默认配置、冗余错误信息
A06存在漏洞的组件带有CVE的过期依赖库
A07认证失效认证/会话机制损坏
A08数据完整性失效不安全反序列化、CI/CD流程风险
A09日志与监控失效缺失审计日志、监控不足
A10SSRF服务器端请求伪造

XXE Prevention

XXE防护

XML External Entity injection allows attackers to read files, perform SSRF, or DoS.
XML外部实体注入可让攻击者读取文件、发起SSRF或DoS攻击。

Vulnerable Code

存在漏洞的代码

php
// ❌ VULNERABLE - External entities enabled
$doc = new DOMDocument();
$doc->loadXML($userInput);
php
// ❌ 存在漏洞 - 外部实体已启用
$doc = new DOMDocument();
$doc->loadXML($userInput);

Secure Code

安全代码

php
// ✅ SECURE - Disable external entities
$doc = new DOMDocument();
$doc->loadXML(
    $userInput,
    LIBXML_NONET | LIBXML_NOENT | LIBXML_DTDLOAD
);

// Or use libxml_disable_entity_loader for older PHP
libxml_disable_entity_loader(true); // Deprecated in PHP 8.0
php
// ✅ 安全 - 禁用外部实体
$doc = new DOMDocument();
$doc->loadXML(
    $userInput,
    LIBXML_NONET | LIBXML_NOENT | LIBXML_DTDLOAD
);

// 旧版本PHP可使用libxml_disable_entity_loader
libxml_disable_entity_loader(true); // PHP 8.0已废弃

SimpleXML Secure Usage

SimpleXML安全用法

php
// ✅ SECURE
$xml = simplexml_load_string(
    $userInput,
    'SimpleXMLElement',
    LIBXML_NONET | LIBXML_NOENT
);
php
// ✅ 安全
$xml = simplexml_load_string(
    $userInput,
    'SimpleXMLElement',
    LIBXML_NONET | LIBXML_NOENT
);

SQL Injection Prevention

SQL注入防护

Vulnerable Code

存在漏洞的代码

php
// ❌ VULNERABLE - Direct string interpolation
$query = "SELECT * FROM users WHERE id = " . $_GET['id'];
$result = $pdo->query($query);
php
// ❌ 存在漏洞 - 直接字符串拼接
$query = "SELECT * FROM users WHERE id = " . $_GET['id'];
$result = $pdo->query($query);

Secure Code - PDO

安全代码 - PDO

php
// ✅ SECURE - Prepared statements
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);
$result = $stmt->fetchAll();
php
// ✅ 安全 - 预处理语句
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);
$result = $stmt->fetchAll();

Secure Code - TYPO3 QueryBuilder

安全代码 - TYPO3 QueryBuilder

php
// ✅ SECURE - TYPO3 QueryBuilder with named parameters
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('users');
$result = $queryBuilder
    ->select('*')
    ->from('users')
    ->where(
        $queryBuilder->expr()->eq(
            'uid',
            $queryBuilder->createNamedParameter($id, Connection::PARAM_INT)
        )
    )
    ->executeQuery()
    ->fetchAllAssociative();
php
// ✅ 安全 - 带命名参数的TYPO3 QueryBuilder
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('users');
$result = $queryBuilder
    ->select('*')
    ->from('users')
    ->where(
        $queryBuilder->expr()->eq(
            'uid',
            $queryBuilder->createNamedParameter($id, Connection::PARAM_INT)
        )
    )
    ->executeQuery()
    ->fetchAllAssociative();

XSS Prevention

XSS防护

Output Encoding

输出编码

php
// ✅ SECURE - Escape all output
echo htmlspecialchars($userInput, ENT_QUOTES | ENT_HTML5, 'UTF-8');
php
// ✅ 安全 - 转义所有输出
echo htmlspecialchars($userInput, ENT_QUOTES | ENT_HTML5, 'UTF-8');

Fluid Templates

Fluid模板

html
<!-- ✅ SAFE - Auto-escaped -->
{variable}

<!-- ❌ DANGEROUS - Raw output, use only for trusted HTML -->
{variable -> f:format.raw()}

<!-- ✅ SAFE - Explicit escaping -->
{variable -> f:format.htmlspecialchars()}
html
<!-- ✅ 安全 - 自动转义 -->
{variable}

<!-- ❌ 危险 - 原始输出,仅可用于受信任的HTML -->
{variable -> f:format.raw()}

<!-- ✅ 安全 - 显式转义 -->
{variable -> f:format.htmlspecialchars()}

Content Security Policy

内容安全策略

php
// Set CSP header
header("Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';");
php
// 设置CSP头
header("Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';");

CSRF Protection

CSRF防护

Form Tokens

表单令牌

php
// Generate token
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;

// Validate token
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    throw new SecurityException('CSRF token mismatch');
}
php
// 生成令牌
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;

// 校验令牌
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    throw new SecurityException('CSRF令牌不匹配');
}

TYPO3 CSRF Protection

TYPO3 CSRF防护

php
use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;

// Generate
$formProtection = $this->formProtectionFactory->createFromRequest($request);
$token = $formProtection->generateToken('myForm');

// Validate
$isValid = $formProtection->validateToken($token, 'myForm');
php
use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;

// 生成令牌
$formProtection = $this->formProtectionFactory->createFromRequest($request);
$token = $formProtection->generateToken('myForm');

// 校验令牌
$isValid = $formProtection->validateToken($token, 'myForm');

API Key Encryption at Rest

静态API密钥加密

Never store API keys in plain text. Use sodium for encryption:
php
<?php
declare(strict_types=1);

final class ApiKeyEncryption
{
    public function encrypt(string $apiKey, string $key): string
    {
        $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $encrypted = sodium_crypto_secretbox($apiKey, $nonce, $key);
        return 'enc:' . base64_encode($nonce . $encrypted);
    }

    public function decrypt(string $encrypted, string $key): string
    {
        if (!str_starts_with($encrypted, 'enc:')) {
            throw new \InvalidArgumentException('Invalid encrypted format');
        }

        $decoded = base64_decode(substr($encrypted, 4));
        $nonce = substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $ciphertext = substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);

        $decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
        if ($decrypted === false) {
            throw new \RuntimeException('Decryption failed');
        }

        return $decrypted;
    }
}
永远不要明文存储API密钥,使用sodium进行加密:
php
<?php
declare(strict_types=1);

final class ApiKeyEncryption
{
    public function encrypt(string $apiKey, string $key): string
    {
        $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $encrypted = sodium_crypto_secretbox($apiKey, $nonce, $key);
        return 'enc:' . base64_encode($nonce . $encrypted);
    }

    public function decrypt(string $encrypted, string $key): string
    {
        if (!str_starts_with($encrypted, 'enc:')) {
            throw new \InvalidArgumentException('无效的加密格式');
        }

        $decoded = base64_decode(substr($encrypted, 4));
        $nonce = substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $ciphertext = substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);

        $decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
        if ($decrypted === false) {
            throw new \RuntimeException('解密失败');
        }

        return $decrypted;
    }
}

Password Hashing

密码哈希

Modern Password Hashing

现代密码哈希方案

php
// ✅ SECURE - Use password_hash with Argon2id
$hash = password_hash($password, PASSWORD_ARGON2ID);

// Verify
if (password_verify($inputPassword, $storedHash)) {
    // Valid password
}

// Check if rehash needed (algorithm upgrade)
if (password_needs_rehash($storedHash, PASSWORD_ARGON2ID)) {
    $newHash = password_hash($password, PASSWORD_ARGON2ID);
    // Update stored hash
}
php
// ✅ 安全 - 使用带Argon2id的password_hash
$hash = password_hash($password, PASSWORD_ARGON2ID);

// 校验密码
if (password_verify($inputPassword, $storedHash)) {
    // 密码有效
}

// 检查是否需要重新哈希(算法升级)
if (password_needs_rehash($storedHash, PASSWORD_ARGON2ID)) {
    $newHash = password_hash($password, PASSWORD_ARGON2ID);
    // 更新存储的哈希值
}

TYPO3 Password Hashing

TYPO3密码哈希

php
use TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory;

$hashInstance = GeneralUtility::makeInstance(PasswordHashFactory::class)
    ->getDefaultHashInstance('BE');

$hash = $hashInstance->getHashedPassword($password);
$isValid = $hashInstance->checkPassword($password, $hash);
php
use TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory;

$hashInstance = GeneralUtility::makeInstance(PasswordHashFactory::class)
    ->getDefaultHashInstance('BE');

$hash = $hashInstance->getHashedPassword($password);
$isValid = $hashInstance->checkPassword($password, $hash);

CVSS v3.1 Scoring

CVSS v3.1 评分

Base Metrics

基础指标

MetricValues
Attack Vector (AV)Network (N), Adjacent (A), Local (L), Physical (P)
Attack Complexity (AC)Low (L), High (H)
Privileges Required (PR)None (N), Low (L), High (H)
User Interaction (UI)None (N), Required (R)
Scope (S)Unchanged (U), Changed (C)
Confidentiality (C)None (N), Low (L), High (H)
Integrity (I)None (N), Low (L), High (H)
Availability (A)None (N), Low (L), High (H)
指标可选值
攻击向量 (AV)网络 (N)、邻接 (A)、本地 (L)、物理 (P)
攻击复杂度 (AC)低 (L)、高 (H)
所需权限 (PR)无 (N)、低 (L)、高 (H)
用户交互 (UI)无 (N)、需要 (R)
影响范围 (S)未改变 (U)、已改变 (C)
机密性 (C)无 (N)、低 (L)、高 (H)
完整性 (I)无 (N)、低 (L)、高 (H)
可用性 (A)无 (N)、低 (L)、高 (H)

Severity Ratings

严重程度评级

ScoreSeverity
0.0None
0.1 - 3.9Low
4.0 - 6.9Medium
7.0 - 8.9High
9.0 - 10.0Critical
分数严重程度
0.0无风险
0.1 - 3.9低危
4.0 - 6.9中危
7.0 - 8.9高危
9.0 - 10.0严重

Example CVSS Vector

CVSS向量示例

CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
Score: 9.8 (Critical)

Translation:
- Network accessible
- Low complexity
- No privileges required
- No user interaction
- Unchanged scope
- High impact on C/I/A
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
分数: 9.8 (严重)

说明:
- 可通过网络访问
- 低复杂度
- 无需权限
- 无需用户交互
- 影响范围未改变
- 对机密性/完整性/可用性影响高

Security Audit Checklist

安全审计检查清单

Authentication & Authorization

认证与授权

  • Passwords hashed with Argon2id or bcrypt
  • MFA enabled for privileged accounts
  • Session tokens regenerated on login
  • Proper logout (session destruction)
  • Role-based access control (RBAC)
  • 密码使用Argon2id或bcrypt哈希
  • 特权账户启用MFA
  • 登录时重新生成会话令牌
  • 正常注销(销毁会话)
  • 基于角色的访问控制(RBAC)

Input Validation

输入校验

  • All input validated server-side
  • Parameterized SQL queries (no interpolation)
  • XML external entities disabled
  • File uploads restricted (type, size, location)
  • 所有输入在服务端校验
  • 使用参数化SQL查询(无字符串拼接)
  • XML外部实体已禁用
  • 文件上传受限制(类型、大小、存储位置)

Output Encoding

输出编码

  • Context-appropriate encoding (HTML, JS, URL)
  • Content Security Policy configured
  • X-Content-Type-Options: nosniff
  • X-Frame-Options: DENY or SAMEORIGIN
  • 上下文适配的编码(HTML、JS、URL)
  • 已配置内容安全策略
  • X-Content-Type-Options: nosniff
  • X-Frame-Options: DENY或SAMEORIGIN

Secrets Management

密钥管理

  • API keys encrypted at rest
  • Secrets not in version control
  • Environment variables for config
  • Key rotation policy
  • API密钥静态加密
  • 密钥不存入版本控制
  • 配置使用环境变量
  • 密钥轮换策略

Transport Security

传输安全

  • TLS 1.2+ enforced
  • HSTS header set
  • Certificate validity monitored
  • 强制使用TLS 1.2+
  • 已设置HSTS头
  • 证书有效期已监控

Logging & Monitoring

日志与监控

  • Authentication events logged
  • Failed login attempts tracked
  • Sensitive data not logged
  • Audit trail for privileged actions
  • 认证事件已记录
  • 登录失败尝试已跟踪
  • 敏感数据不记入日志
  • 特权操作有审计追踪

Secure Configuration (TYPO3)

安全配置(TYPO3)

php
// config/system/settings.php
return [
    'BE' => [
        'debug' => false,
        'lockIP' => 4,
        'lockSSL' => true,
    ],
    'FE' => [
        'debug' => false,
        'lockSSL' => true,
    ],
    'SYS' => [
        'displayErrors' => 0,
        'devIPmask' => '',
        'trustedHostsPattern' => 'example\\.com|www\\.example\\.com',
        'features' => [
            'security.backend.enforceReferrer' => true,
            'security.frontend.enforceContentSecurityPolicy' => true,
        ],
    ],
];

php
// config/system/settings.php
return [
    'BE' => [
        'debug' => false,
        'lockIP' => 4,
        'lockSSL' => true,
    ],
    'FE' => [
        'debug' => false,
        'lockSSL' => true,
    ],
    'SYS' => [
        'displayErrors' => 0,
        'devIPmask' => '',
        'trustedHostsPattern' => 'example\\.com|www\\.example\\.com',
        'features' => [
            'security.backend.enforceReferrer' => true,
            'security.frontend.enforceContentSecurityPolicy' => true,
        ],
    ],
];

Related Skills

相关技能

  • security-incident-reporting - Post-incident documentation, NIST/SANS frameworks, DDoS post-mortem, CVE correlation
  • typo3-security - TYPO3-specific hardening and configuration

  • security-incident-reporting - 事后文档、NIST/SANS框架、DDoS事后复盘、CVE关联
  • typo3-security - TYPO3专属加固与配置

Credits & Attribution

致谢与归属

Thanks to Netresearch DTT GmbH for their contributions to the TYPO3 community.
感谢Netresearch DTT GmbH对TYPO3社区的贡献。