check-csrf-protection

Analyze CSRF vulnerabilities in PHP code, detecting missing CSRF tokens, state-changing GET requests, and weak or incorrect token validation.

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-csrf-protection" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-0817e00d8e9d32776f9fdde01cc3a6ab1c0ec783bb3ed7601ecf66379b900df5. 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

Analyze CSRF vulnerabilities in PHP code, detecting missing CSRF tokens, state-changing GET requests, and weak or incorrect token validation.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Analyzes PHP code for CSRF vulnerabilities. Detects missing CSRF tokens, state-changing GET requests, token validation gaps.
Inputs and outputs
```markdown
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: check-csrf-protection
description: Analyzes PHP code for CSRF vulnerabilities. Detects missing CSRF tokens, state-changing GET requests, token validation gaps.

CSRF Protection Security Check

Analyze PHP code for Cross-Site Request Forgery vulnerabilities.

Detection Patterns

1. Missing CSRF Tokens

// CRITICAL: Form without CSRF token
<form method="POST" action="/transfer">
    <input name="amount" value="1000">
    <input name="to" value="attacker">
    <button>Transfer</button>
</form>

// CRITICAL: No token validation
public function transfer(Request $request): Response
{
    $amount = $request->get('amount');
    $to = $request->get('to');
    $this->bankService->transfer($amount, $to);
    // No CSRF check!
}

2. State-Changing GET Requests

// CRITICAL: Modification via GET
#[Route('/user/delete/{id}', methods: ['GET'])]
public function deleteUser(int $id): Response
{
    $this->userService->delete($id);
}

// CRITICAL: Toggle via GET
#[Route('/user/activate/{id}')]
public function activateUser(int $id): Response
{
    $user = $this->userRepository->find($id);
    $user->setActive(true);
}

// VULNERABLE: Logout via GET (session hijacking)
<a href="/logout">Logout</a>

3. Token Validation Gaps

// VULNERABLE: Token not validated server-side
public function handle(Request $request): Response
{
    // Frontend sends token but backend doesn't check
    $this->processPayment($request);
}

// VULNERABLE: Weak token validation
if ($request->get('_token')) { // Just checks existence
    $this->process();
}

// VULNERABLE: Token not regenerated after login
session_start();
$_SESSION['user'] = $user;
// CSRF token remains same from anonymous session

4. AJAX/API CSRF Issues

// VULNERABLE: No CSRF for AJAX
fetch('/api/update', {
    method: 'POST',
    body: JSON.stringify(data)
});

// VULNERABLE: Only Origin check, no token
if ($_SERVER['HTTP_ORIGIN'] === 'https://example.com') {
    $this->process(); // Origin can be spoofed in some scenarios
}

// VULNERABLE: CORS misconfiguration
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');

5. Cookie-Based Token Issues

// VULNERABLE: Token in cookie only
setcookie('csrf_token', $token);
// Attacker can't read but browser sends automatically

// CORRECT: Double Submit Cookie pattern
// Token in cookie AND in request header/body
// Server compares both values

6. Token Per-Session vs Per-Request

// LESS SECURE: Same token for entire session
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

// MORE SECURE: New token per form
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_tokens'][] = $token; // Store multiple

7. Subresource Integrity

// VULNERABLE: Third-party script without SRI
<script src="https://cdn.example.com/lib.js"></script>

// CORRECT: With subresource integrity
<script src="https://cdn.example.com/lib.js"
        integrity="sha384-abc123..."
        crossorigin="anonymous"></script>

8. SameSite Cookie Missing

// VULNERABLE: No SameSite attribute
setcookie('session_id', $sessionId);

// CORRECT: SameSite=Strict
setcookie('session_id', $sessionId, [
    'samesite' => 'Strict', // or 'Lax'
    'secure' => true,
    'httponly' => true
]);

Grep Patterns

# Forms without csrf token
Grep: '<form[^>]*method=["\']post["\'][^>]*>' -i --glob "**/*.php"
Grep: 'csrf|_token|token' --glob "**/*.php"

# GET routes that modify state
Grep: '#\[Route.*methods:.*GET.*\]' --glob "**/*.php"
Grep: 'public function delete|update|create' --glob "**/*.php"

# Cookie without samesite
Grep: "setcookie\([^)]+\)\s*;" --glob "**/*.php"

# CORS allow all
Grep: "Access-Control-Allow-Origin.*\*" --glob "**/*.php"

Severity Classification

Pattern Severity
State change via GET 🔴 Critical
No CSRF token on forms 🔴 Critical
Token not validated 🔴 Critical
Missing SameSite cookie 🟠 Major
Token per session only 🟡 Minor

Best Practices

Framework CSRF Protection

// Symfony
{{ csrf_token('authenticate') }}

// Laravel Blade
@csrf

// Validation
$request->validate([
    '_token' => 'required|string'
]);

Manual CSRF Token

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

// Include in form
<input type="hidden" name="_token" value="<?= $token ?>">

// Validate
if (!hash_equals($_SESSION['csrf_token'], $_POST['_token'])) {
    throw new CsrfException();
}

API CSRF Protection

// Use custom header (can't be set cross-origin)
fetch('/api/update', {
    method: 'POST',
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-Token': csrfToken
    },
    body: JSON.stringify(data)
});

// Server validates header
$token = $request->headers->get('X-CSRF-Token');
if (!$this->csrfManager->isValid($token)) {
    throw new CsrfException();
}

SameSite Cookies

session_start([
    'cookie_samesite' => 'Strict', // Prevents cross-site sending
    'cookie_secure' => true,
    'cookie_httponly' => true,
]);

Output Format

### CSRF Vulnerability: [Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**CWE:** CWE-352 (Cross-Site Request Forgery)

**Issue:**
[Description of the CSRF weakness]

**Attack Vector:**
Attacker creates malicious page that submits form to victim's browser.

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

Fix:

// With CSRF protection

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value95/100

Highlights

  • CSRF 安全检测是 PHP 开发中的核心安全需求,直接解决用户明确的核心任务痛点,显著提升日常高频场景的效率。
Trigger Precision90/100

Highlights

  • 触发词精准完整,覆盖多种变体,边界清晰。description 明确描述了检测 CSRF 漏洞、缺失令牌、状态变更 GET 请求等,覆盖全面。
Structure and Standards95/100

Highlights

  • Phase/步骤清晰,有出口条件,含端到端示例,frontmatter完整,单文件≤500行。结构清晰,包含检测模式、Grep 模式、严重性分类、最佳实践等,示例丰富。
Execution Reliability90/100

Highlights

  • 工具来源明确,参数正确,覆盖主要异常,不可逆操作有确认机制。提供了具体的 Grep 模式用于检测,代码示例和修复建议完整,可靠性高。
Evidence Verifiability (mean of the first four)93/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.

  • Accounts, secrets or authorization

    Use a dedicated least-privilege account. Keep secrets out of public content and command logs; verify the receiving service and tenant.

    Mentioned in main document · lines 91
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.

  • cdn.example.com
  • example.com

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.