check-type-juggling

Detects PHP type conversion related vulnerabilities. Identifies loose comparisons on user input, uses of in_array without strict mode, type coercion issues in switch statements, and potential hash-comparison bypass scenarios.

Last repository push
GitHub Stars
109
Forks
26
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "check-type-juggling" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-5d69dc8c5ed88fcd618cae1e33d1bcde07b4e56fa12e1818f3e71359d900d277. Verify the upstream source and version against https://github.com/dykyi-roman/awesome-claude-code before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Detects PHP type conversion related vulnerabilities. Identifies loose comparisons on user input, uses of in_array without strict mode, type coercion issues in switch statements, and potential hash-comparison bypass scenarios.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Detects PHP type juggling vulnerabilities. Identifies loose comparison with user input, in_array without strict mode, switch statement type coercion, and hash comparison bypasses.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: check-type-juggling
description: Detects PHP type juggling vulnerabilities. Identifies loose comparison with user input, in_array without strict mode, switch statement type coercion, and hash comparison bypasses.

Type Juggling Security Check (A03:2021)

Analyze PHP code for type juggling vulnerabilities exploiting PHP's loose comparison behavior.

PHP version baseline: 8.4. PHP 8.0 changed number-to-string comparison (Saner string to number comparisons): an int compared with a non-numeric string is now compared as a string, so 0 == 'admin' is false. Do not report the pre-8.0 bypass. What survives is listed below — bools, numeric strings, null, and false-returning functions.

Detection Patterns

1. Loose Comparison with User Input

// CRITICAL: Loose == comparison with user input
if ($request->get('role') == 'admin') { } // true == 'admin' is true — a JSON body can send a bool
if ($id == '100') { }                     // '1e2' == '100' is true — both are numeric strings

// CRITICAL: Password comparison
if ($password == $storedHash) { }          // NEVER use == for security checks

// CORRECT: Strict comparison
if ($request->get('role') === 'admin') { }
if (hash_equals($expectedToken, $token)) { } // Timing-safe comparison

2. in_array Without Strict Mode

// CRITICAL: in_array defaults to loose comparison
$allowedRoles = ['admin', 'editor', 'viewer'];
if (in_array($request->get('role'), $allowedRoles)) { }
// in_array(true, ['admin', 'editor']) === true!  — bool vs non-empty string
// in_array(0, ['admin']) is false since PHP 8 — do not report that one

// VULNERABLE: numeric-string values still collide
$allowedIds = ['100', '200'];
if (in_array($input, $allowedIds)) { }
// '1e2' == '100' is true → '1e2' and ' 100' both pass

// CORRECT: Always use strict mode
if (in_array($request->get('role'), $allowedRoles, true)) { }

3. Switch Statement Type Coercion

// VULNERABLE: Switch uses loose comparison
switch ($request->get('id')) {
    case 100:   // '1e2' and ' 100' both match — numeric-string coercion
        $this->deleteAll();
        break;
    case 'view':
        $this->view();
        break;
}
// Since PHP 8 a non-numeric string no longer matches `case 0`,
// but numeric strings and bools still coerce into the wrong branch.

// CORRECT: Use match (strict comparison)
$result = match ($request->get('action')) {
    'view' => $this->view(),
    'edit' => $this->edit(),
    default => throw new InvalidActionException(),
};

4. Hash Comparison Bypass

// CRITICAL: comparing a false-returning function with == instead of ===
if (strpos($url, 'https://') == 0) { }
// strpos() returns false when not found, and false == 0 is true →
// every URL WITHOUT the prefix passes as "starts with https://"

// CORRECT
if (str_starts_with($url, 'https://')) { }

// NOTE: strcmp() with an array argument throws TypeError since PHP 8 —
// the old "strcmp() returns null" bypass no longer exists. Still use ===
// on its result, because == hides an int|false mix-up on sibling functions.

// CRITICAL: md5/sha1 magic hashes
if (md5($input) == '0') { }
// md5('240610708') = '0e462097431906509019562988736854'
// '0e...' == '0' is true (scientific notation: 0 * 10^... = 0)

// CRITICAL: Loose comparison of hashes
if (md5($a) == md5($b)) { }
// Two different inputs can have 0e... hashes → both equal 0

// CORRECT: hash_equals for hash comparison
if (hash_equals($expectedHash, md5($input))) { }

5. Null Coalescing with Loose Types

// VULNERABLE: isset + loose comparison
if (isset($data['admin']) && $data['admin'] == true) {
    $this->grantAdminAccess(); // 'yes', '1', 1, true all pass
}

// VULNERABLE: Empty check
if (!empty($request->get('verified'))) {
    // '0' is empty, but 'false' is not — inconsistent
}

// CORRECT: Explicit type check
if (($data['admin'] ?? false) === true) {
    $this->grantAdminAccess();
}

6. Array Key Type Juggling

// VULNERABLE: Numeric string keys become integers
$permissions = ['0' => 'none', '1' => 'read', '2' => 'write'];
$level = $request->get('level'); // String from request
$permission = $permissions[$level]; // '01' !== 1, but both exist in different contexts

// VULNERABLE: Boolean key
$config = [true => 'enabled', false => 'disabled'];
// true becomes 1, false becomes 0 as array keys

7. JSON Decode Type Juggling

// VULNERABLE: JSON sends a bool where a string is expected
$data = json_decode($request->getContent(), true);
if ($data['token'] == $validToken) { }
// JSON: {"token": true} → true == "any-non-empty-string" is true!
// (JSON: {"token": 0} no longer matches a non-numeric string in PHP 8)

// CORRECT: Validate type after decode
$data = json_decode($request->getContent(), true);
if (!is_string($data['token'] ?? null)) {
    throw new InvalidInputException('Token must be a string');
}
if (hash_equals($validToken, $data['token'])) { }

Grep Patterns

# Loose comparison with variables
Grep: "\\\$.*==\s*['\"]|['\"].*==\s*\\\$" --glob "**/*.php"
Grep: "==\s*true|==\s*false|==\s*null|==\s*0\b" --glob "**/*.php"

# in_array without strict — two-pass: ripgrep has no lookahead, so widen then confirm
# 1) list every call site, 2) Read each hit and check for a third `true` argument
Grep: "in_array\s*\(" --glob "**/*.php"

# switch instead of match (ripgrep uses `|`, never the BRE `\|`)
Grep: "switch\s*\(\\\$(request|input|data)" --glob "**/*.php"

# strcmp with loose comparison
Grep: "strcmp\(.*==\s*0|strcmp\(.*!=\s*0" --glob "**/*.php"

# Hash comparison with ==
Grep: "md5\(.*==|sha1\(.*==|hash\(.*==" --glob "**/*.php"

# array_search without strict — same two-pass approach as in_array
Grep: "array_search\s*\(" --glob "**/*.php"

Severity Classification

Pattern Severity
Token/hash comparison with == 🔴 Critical
Authentication check with == 🔴 Critical
false-returning function compared with == (e.g. strpos(...) == 0) 🔴 Critical
in_array without strict on security check 🟠 Major
JSON decode + loose comparison 🟠 Major
switch on user input (instead of match) 🟠 Major
in_array without strict (non-security) 🟡 Minor
General loose == usage 🟡 Minor

Do not report as Critical on PHP 8+: a bare in_array($string, $stringList) where every element is a non-numeric string. The pre-8.0 0 == 'admin' bypass is gone; the residual risk is a bool or numeric-string input, which is Major, not Critical. Confirm the input can actually be a bool or a numeric string before escalating.

PHP Type Juggling Reference

Verified against PHP 8.4. The first row is the one that changed in 8.0 — everything below it still holds.

Comparison Result Why
0 == 'admin' false PHP 8+: int is compared as a string against a non-numeric string
'1e2' == '100' true Both are numeric strings → compared numerically
' 1' == '1' true Leading whitespace is allowed in a numeric string
0 == null true null casts to 0
'' == null true null casts to ''
'0e1' == '0e2' true Both numeric strings evaluate to 0 (magic-hash bypass)
true == 'anything' true Non-empty string casts to true
[] == false true Empty array casts to false
false == 0 true The strpos()/strstr() false-return trap

Output Format

### Type Juggling: [Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**CWE:** CWE-1025 (Comparison Using Wrong Factors)
**OWASP:** A03:2021 — Injection

**Issue:**
[Description of the type juggling vulnerability]

**Exploit:**
Input `0` (integer) matches any non-numeric string via loose comparison.

**Code:**
```php
// Vulnerable code with ==

Fix:

// Fixed with === or hash_equals()

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value75/100

Highlights

  • 针对 PHP 类型转换漏洞的专项检测,对开发者具有明确实用价值
  • 覆盖多种常见漏洞场景,包括松散比较、in_array、switch、哈希比较等
Trigger Precision95/100

Highlights

  • 触发词精准完整,覆盖多种变体,边界清晰
  • description 明确描述了检测 PHP 类型转换漏洞的功能
Structure and Standards95/100

Highlights

  • 文档结构清晰,包含检测模式、grep 模式、严重性分类、参考表格和输出格式
  • 步骤划分明确,有端到端示例,frontmatter 完整
Execution Reliability80/100

Areas to improve

  • 未处理 grep 结果误报 Reported severity: Minor

    grep 模式可能匹配到注释或字符串字面量中的代码,导致误报

    Recommendation: 建议增加对注释和字符串字面量的过滤逻辑,或提供后处理脚本

  • 未提及 PHP 版本自动检测 Reported severity: Minor

    Skill 依赖 PHP 8.4 的行为,但未提供自动检测目标代码 PHP 版本的机制

    Recommendation: 建议增加版本检测机制,或明确提示用户确认目标代码的 PHP 版本

Highlights

  • 提供了具体的检测模式和 grep 命令,工具来源明确
  • 覆盖了主要异常场景,并给出了修复建议
Evidence Verifiability (mean of the first four)86/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

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

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

Domains or addresses referenced in the document

These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.

  • wiki.php.net

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.