check-deserialization

分析 PHP 代码中的不安全反序列化问题。检测使用用户输入的 unserialize 调用、缺失 allowed_classes 参数、PHP 对象注入风险以及 gadget 链。

仓库最近推送
GitHub Stars
109
Forks
26
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "check-deserialization":https://skillpi.com/zh/skills/deepskill-a093c1d48844ad60c3d06221aece506dcde61309756e504859bbdcd7c15f77ec。安装前核对上游来源和版本:https://github.com/dykyi-roman/awesome-claude-code。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

分析 PHP 代码中的不安全反序列化问题。检测使用用户输入的 unserialize 调用、缺失 allowed_classes 参数、PHP 对象注入风险以及 gadget 链。

0 下载

介绍来源: third_party · dykyi-roman · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: check-deserialization
description: Analyzes PHP code for insecure deserialization. Detects unserialize with user input, missing allowed_classes, PHP object injection risks, gadget chains.

Insecure Deserialization Security Check

Analyze PHP code for insecure deserialization vulnerabilities (OWASP A08:2021).

Detection Patterns

1. Unserialize with User Input

// CRITICAL: Direct user input
$data = unserialize($_GET['data']);
$object = unserialize($_POST['payload']);
$config = unserialize($_COOKIE['session']);

// CRITICAL: Request object
$data = unserialize($request->input('data'));

// CRITICAL: From file upload
$content = file_get_contents($_FILES['import']['tmp_name']);
$data = unserialize($content);

2. Missing allowed_classes Option

// CRITICAL: No allowed_classes restriction (PHP 7+)
$data = unserialize($serialized);
// Can instantiate ANY class

// CRITICAL: allowed_classes = true (default behavior)
$data = unserialize($serialized, ['allowed_classes' => true]);

// SECURE: No objects allowed
$data = unserialize($serialized, ['allowed_classes' => false]);

// SECURE: Whitelist specific classes
$data = unserialize($serialized, [
    'allowed_classes' => [User::class, Config::class],
]);

3. Gadget Chain Triggers

// VULNERABLE: Classes with dangerous magic methods
class FileHandler
{
    private string $path;

    // Called on unserialize - could delete arbitrary files
    public function __wakeup(): void
    {
        unlink($this->path);
    }
}

class Logger
{
    private string $logFile;
    private string $data;

    // Called when object destroyed - could write arbitrary files
    public function __destruct()
    {
        file_put_contents($this->logFile, $this->data);
    }
}

class DataLoader
{
    private string $source;

    // Called on property access - SSRF/file read
    public function __get($name)
    {
        return file_get_contents($this->source);
    }
}

class CommandRunner
{
    private string $command;

    // Called when object used as string - RCE
    public function __toString(): string
    {
        return shell_exec($this->command);
    }
}

4. Database-Stored Serialized Data

// CRITICAL: Trusting database content
$row = $db->query("SELECT settings FROM users WHERE id = ?", [$id]);
$settings = unserialize($row['settings']);
// If attacker can modify DB (SQL injection), they control serialized data

// CRITICAL: Session storage
$sessionData = unserialize($redis->get('session:' . $sessionId));

5. Phar Deserialization

// CRITICAL: Phar metadata triggers unserialize
$phar = new Phar($userUploadedFile);
// Reading phar file deserializes metadata

// CRITICAL: File operations on phar://
file_exists('phar://' . $uploadedFile);
file_get_contents('phar://' . $userFile);
is_dir('phar://' . $path);
fopen('phar://' . $filename, 'r');

// CRITICAL: include/require phar
include 'phar://' . $plugin . '/bootstrap.php';

6. Base64-Encoded Serialized Data

// CRITICAL: Common pattern to hide serialized data
$payload = base64_decode($_GET['token']);
$data = unserialize($payload);

// CRITICAL: In cookies
$sessionData = unserialize(base64_decode($_COOKIE['session']));

// CRITICAL: In headers
$auth = unserialize(base64_decode($request->header('X-Auth-Data')));

7. JSON with Object Mapping

// POTENTIALLY VULNERABLE: JSON to object without validation
$json = file_get_contents('php://input');
$data = json_decode($json);

// CRITICAL: Mapping to class with dangerous methods
$object = (new UserDTO())->fromArray(json_decode($json, true));
// If class has __set or __call that executes code

// CRITICAL: Doctrine/JMS Serializer without type whitelist
$user = $this->serializer->deserialize($json, 'object', 'json');

8. Cache Deserialization

// CRITICAL: Cache poisoning leads to object injection
$cacheKey = 'user_' . $userId;
$user = unserialize($cache->get($cacheKey));
// If cache can be poisoned, attacker controls object

// CRITICAL: File-based cache
$cached = file_get_contents("/tmp/cache/{$key}.cache");
$data = unserialize($cached);

9. Framework-Specific Patterns

// CRITICAL: Laravel signed URLs without validation
$data = unserialize($request->input('signed_data'));

// CRITICAL: Symfony serialized tokens
$token = unserialize($session->get('_security_main'));

// CRITICAL: Custom session handlers
class MySessionHandler implements SessionHandlerInterface
{
    public function read($id): string|false
    {
        $data = $this->storage->get($id);
        return unserialize($data); // Dangerous
    }
}

10. RPC/IPC Serialization

// CRITICAL: Inter-process communication
$message = unserialize(file_get_contents('php://stdin'));

// CRITICAL: Queue messages
$job = unserialize($queue->pop());

// CRITICAL: Socket data
$data = unserialize(socket_read($socket, 1024));

Grep Patterns

# unserialize calls
Grep: "unserialize\s*\(" --glob "**/*.php"

# unserialize with user input
Grep: "unserialize\s*\([^)]*(\\\$_GET|\\\$_POST|\\\$_COOKIE|\\\$_REQUEST)" --glob "**/*.php"

# phar:// usage
Grep: "phar://" --glob "**/*.php"

# Magic methods that could be exploited
Grep: "__wakeup|__destruct|__toString|__call\s*\(" --glob "**/*.php"

# Missing allowed_classes
Grep: "unserialize\s*\([^)]+\)\s*;" --glob "**/*.php"

Secure Patterns

Use JSON Instead

// SECURE: JSON for data interchange
$data = json_decode($input, true, 512, JSON_THROW_ON_ERROR);

// SECURE: Validate JSON structure
$data = json_decode($input, true);
if (!isset($data['expected_field'])) {
    throw new InvalidInputException();
}

Restrict allowed_classes

// SECURE: Only allow specific classes
$allowed = [
    UserDTO::class,
    ConfigDTO::class,
];

$data = unserialize($serialized, ['allowed_classes' => $allowed]);

// SECURE: No objects at all (for arrays/primitives)
$data = unserialize($serialized, ['allowed_classes' => false]);

Signature Verification

// SECURE: Sign serialized data
final class SecureSerializer
{
    public function __construct(
        private readonly string $secretKey,
    ) {}

    public function serialize(mixed $data): string
    {
        $serialized = serialize($data);
        $signature = hash_hmac('sha256', $serialized, $this->secretKey);
        return base64_encode($signature . $serialized);
    }

    public function unserialize(string $input, array $allowedClasses = []): mixed
    {
        $decoded = base64_decode($input, true);
        if ($decoded === false || strlen($decoded) < 64) {
            throw new SecurityException('Invalid data format');
        }

        $signature = substr($decoded, 0, 64);
        $serialized = substr($decoded, 64);

        $expected = hash_hmac('sha256', $serialized, $this->secretKey);
        if (!hash_equals($expected, $signature)) {
            throw new SecurityException('Invalid signature');
        }

        return unserialize($serialized, ['allowed_classes' => $allowedClasses]);
    }
}

Use Typed DTOs

// SECURE: Manual mapping to DTO
final readonly class CreateUserRequest
{
    public function __construct(
        public string $name,
        public string $email,
        public int $age,
    ) {}

    public static function fromArray(array $data): self
    {
        return new self(
            name: $data['name'] ?? throw new ValidationException('Name required'),
            email: $data['email'] ?? throw new ValidationException('Email required'),
            age: (int) ($data['age'] ?? throw new ValidationException('Age required')),
        );
    }
}

// Usage
$data = json_decode($input, true);
$request = CreateUserRequest::fromArray($data);

Disable Phar Wrapper

// In php.ini
; phar.readonly = 1  (prevents phar creation)

// At runtime - remove phar wrapper
stream_wrapper_unregister('phar');

// Validate file type before operations
if (pathinfo($file, PATHINFO_EXTENSION) === 'phar') {
    throw new SecurityException('Phar files not allowed');
}

Severity Classification

Pattern Severity CWE
unserialize($_GET/$_POST) 🔴 Critical CWE-502
unserialize without allowed_classes 🔴 Critical CWE-502
Phar with user-controlled path 🔴 Critical CWE-502
Classes with dangerous __destruct 🟠 Major CWE-502
Cache/DB deserialization 🟠 Major CWE-502
Missing signature verification 🟡 Minor CWE-502

Output Format

### Insecure Deserialization: [Description]

**Severity:** 🔴 Critical
**Location:** `file.php:line`
**CWE:** CWE-502 (Deserialization of Untrusted Data)

**Issue:**
User-controlled data is deserialized without restrictions, allowing object injection.

**Attack Vector:**
1. Attacker crafts serialized payload with gadget chain
2. Payload triggers __destruct() that writes to file
3. Attacker achieves remote code execution

**Code:**
```php
// Vulnerable
$data = unserialize($_POST['data']);

Fix:

// Secure: Use JSON or restrict classes
$data = json_decode($_POST['data'], true);

// Or with signature and whitelist
$data = unserialize($payload, [
    'allowed_classes' => [SafeDTO::class],
]);

References:

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值75/100

亮点

  • 提供全面的 PHP 不安全反序列化漏洞检测能力,覆盖用户输入、数据库、缓存、Phar 等多种高危场景
  • 内容详实,包含具体代码示例、grep 命令和修复建议,实用性强
触发精准92/100

亮点

  • 触发描述清晰准确,明确列出检测目标(unserialize 用户输入、allowed_classes 缺失、gadget 链等)
  • 边界定义清晰,不易与其他安全检测 Skill 混淆
结构规范95/100

待提升项

  • 缺少 When to Use 章节 原报告严重程度:轻微

    文档结构完整但未明确说明适用场景和使用时机

    改进建议:建议补充 When to Use 章节,说明在代码审计、CI/CD 安全检查等场景下的使用方法

亮点

  • 结构清晰,分检测模式、grep 模式、安全模式、严重性分类、输出格式五大模块
  • 每类漏洞均配有具体代码示例和修复方案,便于理解与实施
执行可靠80/100

亮点

  • 提供可执行的 grep 命令用于实际扫描
  • 安全建议包含签名验证、allowed_classes 白名单等可靠防护措施
  • 覆盖 Phar 反序列化、缓存投毒等高级攻击向量
证据可验 (前四项均值)86/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • owasp.org

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。