Check Deserializationのロゴ

Check Deserialization

コミュニティ
dykyi-roman
check-deserialization

Analyzes PHP code for insecure deserialization. Detects unserialize with user input, missing allowed_classes, PHP object injection risks, gadget chains.

Add to TypingMind

概要

公開者dykyi-roman
リポジトリawesome-claude-code
スキル名check-deserialization
スター
98
フォーク
25
同梱ファイル
指示のみ
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    dykyi-romanがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Check Deserialization」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/dykyi-roman/awesome-claude-code/tree/master/skills/check-deserialization
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/dykyi-roman/awesome-claude-code.git /tmp/awesome-claude-code
mkdir -p .claude/skills
cp -r /tmp/awesome-claude-code/skills/check-deserialization .claude/skills/check-deserialization
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでCheck Deserializationを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にCheck Deserializationを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Check Deserializationは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

Insecure Deserialization Security Check

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

Detection Patterns

1. Unserialize with User Input

php
// 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

php
// 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

php
// 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

php
// 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

php
// 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

php
// 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

php
// 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

php
// 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

php
// 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

php
// 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

bash
# 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

php
// 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

php
// 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

php
// 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

php
// 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

php
// 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

PatternSeverityCWE
unserialize($_GET/$_POST)🔴 CriticalCWE-502
unserialize without allowed_classes🔴 CriticalCWE-502
Phar with user-controlled path🔴 CriticalCWE-502
Classes with dangerous __destruct🟠 MajorCWE-502
Cache/DB deserialization🟠 MajorCWE-502
Missing signature verification🟡 MinorCWE-502

Output Format

markdown
### 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:

php
// 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:

よくある質問

AIスキル「Check Deserialization」では何ができますか?

Analyzes PHP code for insecure deserialization. Detects unserialize with user input, missing allowed_classes, PHP object injection risks, gadget chains.

TypingMindでCheck Deserializationを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Check Deserializationはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにCheck Deserializationをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/dykyi-roman/awesome-claude-code/tree/master/skills/check-deserializationを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Check Deserializationを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Check Deserializationで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもCheck Deserializationを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Check Deserialization」は無料ですか?

はい。dykyi-romanがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇