laravel-owasp-security
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLaravel OWASP Security
Laravel OWASP安全
Dual-purpose security skill for Laravel 13 + React/Inertia.js applications. Run a full OWASP Top 10 audit against a codebase, or use as a secure coding reference when building features.
适用于Laravel 13 + React/Inertia.js应用的双用途安全技能。可针对代码库执行完整的OWASP Top 10审计,或作为构建功能时的安全编码参考。
How to Audit
审计步骤
Step 1: Detect Stack
步骤1:检测技术栈
Check if the project uses React + Inertia.js by looking for:
- exists
app/Http/Middleware/HandleInertiaRequests.php - contains
resources/js/or.tsxfiles.jsx - in
inertiajs/inertia-laravelcomposer.json - in
@inertiajs/reactpackage.json
If detected, state at the top of the report:
"React + Inertia.js detected — Laravel OWASP checklist AND React/Inertia security checks will both be applied."
If not detected, state:
"No React/Inertia.js detected — applying Laravel OWASP checklist only."
通过以下特征检查项目是否使用React + Inertia.js:
- 存在文件
app/Http/Middleware/HandleInertiaRequests.php - 目录包含
resources/js/或.tsx文件.jsx - 中存在
composer.json依赖inertiajs/inertia-laravel - 中存在
package.json依赖@inertiajs/react
若检测到,在报告顶部声明:
"已检测到React + Inertia.js — 将同时应用Laravel OWASP检查清单和React/Inertia安全检查。"
若未检测到,声明:
"未检测到React/Inertia.js — 仅应用Laravel OWASP检查清单。"
Step 2: Determine Scope
步骤2:确定审计范围
- If arguments provided (): review only those files or features
$ARGUMENTS - If no arguments: review the entire codebase
- 若提供参数():仅审查指定文件或功能
$ARGUMENTS - 若无参数:审查整个代码库
Step 3: Run Checklist
步骤3:执行检查清单
Work through every item below. For each, output:
- PASS — brief confirmation of what was verified
- FAIL — exact , a description of the vulnerability (do NOT reproduce any code, values, API keys, tokens, or .env contents from the file), and a fix recommendation
file:line - N/A — if the check does not apply to this project
逐项检查以下内容。针对每项输出:
- 通过 — 简要说明已验证的内容
- 失败 — 精确的,漏洞描述(请勿复制文件中的任何代码、值、API密钥、令牌或.env内容),以及修复建议
文件:行号 - 不适用 — 若该检查不适用于此项目
OWASP Top 10 Checklist
OWASP Top 10检查清单
1. Broken Access Control (A01:2021)
1. 访问控制失效(A01:2021)
- Middleware protects all route groups by role (,
auth, etc.)role:admin - Resource queries scoped to authenticated user —
->where('user_id', auth()->id()) - No direct object reference without ownership check
- Gates and Policies used to authorize resource access
- Frontend role checks are mirrored server-side — never rely on React UI checks alone
- 所有路由组通过角色中间件(、
auth等)保护role:admin - 资源查询限定在已认证用户范围内 — 使用
->where('user_id', auth()->id()) - 无未进行所有权检查的直接对象引用
- 使用Gates和Policies授权资源访问
- 前端角色检查需在服务器端镜像实现 — 切勿仅依赖React UI检查
2. Cryptographic Failures (A02:2021)
2. 加密失败(A02:2021)
- Passwords hashed with or
Hash::make()Eloquent cast — never stored as plaintext'hashed' - No MD5 or SHA1 used for password hashing
- Sensitive fields (API keys, secrets) encrypted with or
Crypt::encryptString()Eloquent cast'encrypted' - is long, random, and unique per environment
APP_KEY - Signed URLs () used for sensitive one-time actions (password reset, email verify)
URL::signedRoute()
- 密码使用或
Hash::make()Eloquent类型转换进行哈希 — 绝不以明文存储'hashed' - 密码哈希未使用MD5或SHA1算法
- 敏感字段(API密钥、机密信息)使用或
Crypt::encryptString()Eloquent类型转换加密'encrypted' - 为长随机值,且每个环境唯一
APP_KEY - 敏感一次性操作(密码重置、邮箱验证)使用签名URL()
URL::signedRoute()
3. Injection (A03:2021)
3. 注入攻击(A03:2021)
SQL & Mass Assignment:
- No string concatenation in ,
whereRaw(),selectRaw()— useorderByRaw()bindings? - Column names never derived from user input without a whitelist
- No passed directly to
$request->all(),create(), orfill()update() - No or
forceFill()with unvalidated user inputforceCreate() - Models define explicitly — not
$fillable$guarded = [] - Controllers use for mass operations
$request->validated()
XSS — Blade & React:
- No in Blade templates with untrusted data
{!! $userInput !!} - used for all user-supplied Blade output
{{ }} - No in React without
dangerouslySetInnerHTMLfirstDOMPurify.sanitize() - and
hrefattributes not set from unvalidated user inputsrc - No ,
eval(), ornew Function()with user-controlled stringssetTimeout(string) - External CDN scripts use Subresource Integrity ()
integrity="sha384-..."
SQL与批量赋值:
- 、
whereRaw()、selectRaw()中无字符串拼接 — 使用orderByRaw()绑定? - 列名从不直接来自用户输入,除非经过白名单验证
- 不直接将传入
$request->all()、create()或fill()update() - 不使用或
forceFill()处理未验证的用户输入forceCreate() - 模型明确定义— 不使用
$fillable$guarded = [] - 控制器使用进行批量操作
$request->validated()
XSS — Blade与React:
- Blade模板中未信任数据不使用语法
{!! $userInput !!} - 所有用户提供的Blade输出使用语法
{{ }} - React中使用前需先通过
dangerouslySetInnerHTML处理DOMPurify.sanitize() - 和
href属性不使用未验证的用户输入设置src - 不使用、
eval()或new Function()处理用户可控字符串setTimeout(string) - 外部CDN脚本使用子资源完整性()
integrity="sha384-..."
4. Insecure Design (A04:2021)
4. 不安全设计(A04:2021)
- Business logic enforced server-side — prices, totals, and discounts never trusted from client input
- Sensitive operations require secondary confirmation (e.g. password re-entry for account deletion)
- No mass action endpoints without per-item authorization check
- Admin-only features isolated behind separate middleware — not just hidden in the UI
- Payment amounts and enrollment states calculated server-side, not passed as form inputs
- 业务逻辑在服务器端强制执行 — 价格、总计和折扣绝不信任客户端输入
- 敏感操作需二次确认(如删除账户需重新输入密码)
- 批量操作端点需进行逐项授权检查
- 仅管理员可用的功能需隔离在独立中间件后 — 不只是在UI中隐藏
- 支付金额和注册状态由服务器端计算,不通过表单输入传递
5. Security Misconfiguration (A05:2021)
5. 安全配置错误(A05:2021)
- in production
APP_DEBUG=false - is in
.envand never committed.gitignore - Database uses a restricted user — not root/admin — in production
- and
storage/have correct permissions (not world-writable)bootstrap/cache/ - is set and unique per environment
APP_KEY - CORS is not
allowed_originsfor authenticated API routes['*']
- 生产环境中
APP_DEBUG=false - 文件已加入
.env,从未提交到版本库.gitignore - 生产环境数据库使用受限用户 — 不使用root/admin账户
- 和
storage/目录权限正确(不可全局写入)bootstrap/cache/ - 已设置且每个环境唯一
APP_KEY - 已认证API路由的CORS 不设置为
allowed_origins['*']
6. Vulnerable & Outdated Components (A06:2021)
6. 易受攻击且过时的组件(A06:2021)
- passes with no known CVEs
composer audit - passes with no known CVEs
npm audit - Laravel framework is on a supported version
- 执行通过,无已知CVE漏洞
composer audit - 执行通过,无已知CVE漏洞
npm audit - Laravel框架处于支持版本
7. Identification & Authentication Failures (A07:2021)
7. 身份识别与认证失败(A07:2021)
Auth:
- Using Laravel Breeze, Fortify, or Jetstream — not custom-rolled auth
- Passwords hashed with bcrypt or argon2 (Laravel default)
- Login route rate limited — middleware or
throttleinRateLimiterLoginRequest - Password reset and email verification routes rate limited
- Payment and sensitive action routes have appropriate rate limits
- called after successful login
session()->regenerate()
Cookie & Session:
- in
http_only = trueconfig/session.php - or
same_site = laxinstrictconfig/session.php - or
secure = true(auto for HTTPS) innullconfig/session.php - is a reasonable value (15–30 min recommended for most apps)
lifetime - unless subdomains are needed
domain = null - middleware is in the web group
EncryptCookies
认证:
- 使用Laravel Breeze、Fortify或Jetstream — 不使用自定义认证实现
- 密码使用bcrypt或argon2(Laravel默认算法)哈希
- 登录路由设置速率限制 — 使用中间件或
throttle中的LoginRequestRateLimiter - 密码重置和邮箱验证路由设置速率限制
- 支付和敏感操作路由设置适当的速率限制
- 登录成功后调用
session()->regenerate()
Cookie与会话:
- 中
config/session.phphttp_only = true - 中
config/session.php或same_site = laxstrict - 中
config/session.php或secure = true(HTTPS自动启用)null - 为合理值(大多数应用建议15–30分钟)
lifetime - ,除非需要子域名支持
domain = null - 中间件已加入web组
EncryptCookies
8. Software & Data Integrity Failures (A08:2021)
8. 软件与数据完整性失败(A08:2021)
CSRF:
- middleware active in the web group
VerifyCsrfToken - Only stateless routes (webhooks, external callbacks) are excluded from CSRF
- directive used in all non-Inertia POST forms
@csrf - Excluded routes in are justified
validateCsrfTokens(except: [...])
Deserialization:
- No
unserialize($request->input(...)) - No
eval($request->input(...)) - No
extract($request->all())
CSRF:
- 中间件在web组中激活
VerifyCsrfToken - 仅无状态路由(webhook、外部回调)排除CSRF验证
- 所有非Inertia POST表单使用指令
@csrf - 中排除的路由需有合理理由
validateCsrfTokens(except: [...])
反序列化:
- 不使用
unserialize($request->input(...)) - 不使用
eval($request->input(...)) - 不使用
extract($request->all())
9. Security Logging & Monitoring Failures (A09:2021)
9. 安全日志与监控失败(A09:2021)
- Failed login attempts logged with IP and identifier
- Payment failures and exceptions logged
- Log entries do not contain raw passwords or secrets
- Monitoring in place (Laravel Telescope, Sentry, or similar)
- 失败的登录尝试记录IP和标识符
- 支付失败和异常已记录
- 日志条目不包含明文密码或机密信息
- 已配置监控(Laravel Telescope、Sentry或类似工具)
10. Server-Side Request Forgery — SSRF (A10:2021)
10. 服务器端请求伪造 — SSRF(A10:2021)
- No with unvalidated URLs
Http::get($request->input('url')) - User-supplied URLs validated against an allowlist or scheme check
- Internal network addresses blocked from user-supplied URLs
- 不使用处理未验证的URL
Http::get($request->input('url')) - 用户提供的URL需通过白名单或协议检查验证
- 用户提供的URL需阻止内部网络地址
Additional Checks
额外检查
Not part of the OWASP Top 10 but critical for Laravel applications.
不属于OWASP Top 10,但对Laravel应用至关重要。
Command Injection & Dangerous Functions
命令注入与危险函数
- No ,
exec(),shell_exec(),system()with user inputpassthru() - No open redirects — no with unvalidated URLs
redirect($request->input('url')) - File uploads validate ,
mimes:— filenames never derived from raw user inputmax:
- 不使用、
exec()、shell_exec()、system()处理用户输入passthru() - 无开放重定向 — 不使用处理未验证的URL
redirect($request->input('url')) - 文件上传验证、
mimes:— 文件名绝不直接来自用户原始输入max:
Security Headers
安全头
- set — with nonces (
Content-Security-Policy) if possibleVite::useCspNonce() - set
X-Frame-Options - set
X-Content-Type-Options - set for HTTPS
Strict-Transport-Security - set
Referrer-Policy - set
Permissions-Policy
- 设置— 尽可能使用随机数(
Content-Security-Policy)Vite::useCspNonce() - 设置
X-Frame-Options - 设置
X-Content-Type-Options - 针对HTTPS设置
Strict-Transport-Security - 设置
Referrer-Policy - 设置
Permissions-Policy
React + Inertia.js Checks
React + Inertia.js检查
Only run if React + Inertia.js detected in Step 1.
仅当步骤1中检测到React + Inertia.js时执行。
R1. XSS in React Components
R1. React组件中的XSS
- No without
dangerouslySetInnerHTML={{ __html: userInput }}firstDOMPurify.sanitize() - and
hrefattributes not set from unvalidated user input —srcURLs execute scriptsjavascript: - No ,
eval(), ornew Function()with user-controlled stringssetTimeout(string) - Links from user input validate scheme (or
https://only)http://
- 不使用,除非先通过
dangerouslySetInnerHTML={{ __html: userInput }}处理DOMPurify.sanitize() - 和
href属性不使用未验证的用户输入设置 —srcURL会执行脚本javascript: - 不使用、
eval()或new Function()处理用户可控字符串setTimeout(string) - 用户输入的链接需验证协议(仅允许或
https://)http://
R2. Inertia.js Data Exposure (Critical)
R2. Inertia.js数据暴露(严重)
- does NOT expose passwords, tokens, or internal-only flags
HandleInertiaRequests::share() - Controllers use or API Resources — not raw model
->only([...])toArray() - All Inertia props are treated as public — visible in HTML attribute on initial load
data-page - Payment secret keys and admin-only credentials are never passed as Inertia props
- Inertia v2 History Encryption enabled for pages with sensitive data
- 绝不暴露密码、令牌或内部专用标志
HandleInertiaRequests::share() - 控制器使用或API资源 — 不使用原始模型
->only([...])toArray() - 所有Inertia属性均视为公开 — 初始加载时会显示在HTML属性中
data-page - 支付密钥和管理员专用凭证绝不作为Inertia属性传递
- 包含敏感数据的页面启用Inertia v2历史加密
R3. CSRF in Inertia.js
R3. Inertia.js中的CSRF
- Inertia header not disabled
X-XSRF-TOKEN - Custom or
fetchcalls include CSRF token manually if bypassing Inertia's routeraxios - Webhook/callback routes are the ONLY CSRF-excluded routes
- 未禁用Inertia 头
X-XSRF-TOKEN - 若绕过Inertia路由,自定义或
fetch调用需手动包含CSRF令牌axios - 仅Webhook/回调路由排除CSRF验证
R4. Authentication State in React
R4. React中的认证状态
- Inertia prop excludes password hash, remember tokens, and 2FA secrets
auth.user - Role/permission checks enforced server-side — React checks are UI-only
- contains only fields the UI actually needs
auth.user
- Inertia属性排除密码哈希、记住令牌和双因素认证密钥
auth.user - 角色/权限检查在服务器端强制执行 — React检查仅用于UI展示
- 仅包含UI实际需要的字段
auth.user
R5. Sensitive Data in Browser
R5. 浏览器中的敏感数据
- No API keys or secrets hardcoded in React components or TypeScript files
- No sensitive data in or
localStorage— use HttpOnly cookiessessionStorage - env vars contain no secrets — they are public by design
VITE_*
- React组件或TypeScript文件中未硬编码API密钥或机密信息
- 敏感数据不存储在或
localStorage中 — 使用HttpOnly CookiesessionStorage - 环境变量不包含机密信息 — 它们默认是公开的
VITE_*
R6. Dependency Security
R6. 依赖安全
- passes with no high/critical CVEs in React or Inertia packages
npm audit - React is on a supported version
- Third-party component libraries reviewed for known CVEs
- 执行通过,React或Inertia包中无高/严重级CVE漏洞
npm audit - React处于支持版本
- 第三方组件库已审查是否存在已知CVE漏洞
Output Format
输出格式
Structure the audit report as:
undefined审计报告结构如下:
undefinedLaravel OWASP Security Audit Report
Laravel OWASP安全审计报告
React + Inertia.js detected — Laravel OWASP checklist AND React/Inertia security checks will both be applied.
已检测到React + Inertia.js — 将同时应用Laravel OWASP检查清单和React/Inertia安全检查。
1. Broken Access Control (A01:2021)
1. 访问控制失效(A01:2021)
- PASS — role middleware applied to all route groups
app/Http/Middleware/RoleMiddleware.php - FAIL — Payment model fetched without ownership check (direct object reference exposure). Fix: scope the query to the authenticated user.
app/Http/Controllers/PaymentController.php:42
[Continue for all 10 OWASP checks + Additional Checks + R1–R6 React/Inertia checks]
- 通过 — 所有路由组已应用角色中间件
app/Http/Middleware/RoleMiddleware.php - 失败 — 未进行所有权检查就获取Payment模型(直接对象引用暴露)。修复建议:将查询限定在已认证用户范围内。
app/Http/Controllers/PaymentController.php:42
[继续完成所有10项OWASP检查 + 额外检查 + R1–R6 React/Inertia检查]
Summary
总结
Critical Issues (fix immediately)
严重问题(立即修复)
- ...
- ...
Warnings (fix soon)
警告(尽快修复)
- ...
- ...
Passed
通过项
X checks passed.
共X项检查通过。
Recommended Commands
推荐执行命令
composer audit
npm audit
---composer audit
npm audit
---When to Apply for Guidance
何时寻求指导
Reference the rule files when:
- Implementing authentication or password handling
- Building payment or webhook integrations
- Writing file upload or download logic
- Designing admin or role-based access control
- Building API endpoints with user-supplied input
- Using in React components
dangerouslySetInnerHTML - Passing data from Laravel controllers to Inertia props
在以下场景参考规则文件:
- 实现认证或密码处理功能
- 构建支付或Webhook集成
- 编写文件上传或下载逻辑
- 设计管理员或基于角色的访问控制
- 构建接收用户输入的API端点
- 在React组件中使用
dangerouslySetInnerHTML - 从Laravel控制器向Inertia属性传递数据
Rule Categories by Priority
按优先级划分的规则类别
| Priority | Category | Impact | Rule File |
|---|---|---|---|
| 1 | Broken Access Control | CRITICAL | |
| 2 | Cryptographic Failures | CRITICAL | |
| 3 | Injection Prevention | CRITICAL | |
| 4 | XSS & React/Inertia | HIGH | |
| 5 | CSRF Protection | HIGH | |
| 6 | Security Misconfiguration | HIGH | |
| 7 | Authentication & Rate Limiting | HIGH | |
| 8 | Inertia Data Exposure | HIGH | |
| 优先级 | 类别 | 影响 | 规则文件 |
|---|---|---|---|
| 1 | 访问控制失效 | 严重 | |
| 2 | 加密失败 | 严重 | |
| 3 | 注入防护 | 严重 | |
| 4 | XSS与React/Inertia | 高 | |
| 5 | CSRF防护 | 高 | |
| 6 | 安全配置错误 | 高 | |
| 7 | 认证与速率限制 | 高 | |
| 8 | Inertia数据暴露 | 高 | |
Quick Reference
快速参考
1. Broken Access Control (CRITICAL)
1. 访问控制失效(严重)
- — Middleware, ownership checks, policies, scoped queries
sec-broken-access-control
- — 中间件、所有权检查、策略、限定范围的查询
sec-broken-access-control
2. Cryptographic Failures (CRITICAL)
2. 加密失败(严重)
- — Password hashing, encrypted casts, signed URLs
sec-cryptographic-failures
- — 密码哈希、加密类型转换、签名URL
sec-cryptographic-failures
3. Injection Prevention (CRITICAL)
3. 注入防护(严重)
- — SQL injection, mass assignment, raw query bindings
sec-injection-prevention
- — SQL注入、批量赋值、原始查询绑定
sec-injection-prevention
4. XSS & React/Inertia (HIGH)
4. XSS与React/Inertia(高)
- — dangerouslySetInnerHTML, DOMPurify, href/src validation
sec-xss-react-inertia
- — dangerouslySetInnerHTML、DOMPurify、href/src验证
sec-xss-react-inertia
5. CSRF Protection (HIGH)
5. CSRF防护(高)
- — VerifyCsrfToken, webhook exclusions, Inertia CSRF
sec-csrf-protection
- — VerifyCsrfToken、Webhook排除、Inertia CSRF
sec-csrf-protection
6. Security Misconfiguration (HIGH)
6. 安全配置错误(高)
- — APP_DEBUG, APP_KEY, security headers, CORS
sec-security-misconfiguration
- — APP_DEBUG、APP_KEY、安全头、CORS
sec-security-misconfiguration
7. Authentication & Rate Limiting (HIGH)
7. 认证与速率限制(高)
- — Throttle, session regeneration, brute force prevention
sec-authentication-rate-limiting
- — 速率限制、会话再生、暴力破解防护
sec-authentication-rate-limiting
8. Inertia Data Exposure (HIGH)
8. Inertia数据暴露(高)
- — data-page attribute exposure, secret props, API Resources
sec-inertia-data-exposure
- — data-page属性暴露、机密属性、API资源
sec-inertia-data-exposure
How to Use
使用方法
Read individual rule files for detailed explanations and code examples:
rules/sec-broken-access-control.md
rules/sec-cryptographic-failures.md
rules/sec-injection-prevention.md
rules/sec-xss-react-inertia.md
rules/sec-csrf-protection.md
rules/sec-security-misconfiguration.md
rules/sec-authentication-rate-limiting.md
rules/sec-inertia-data-exposure.mdEach rule file contains:
- YAML frontmatter with metadata (title, impact, tags)
- Why it matters in Laravel/React context
- Incorrect code example with explanation
- Correct code example with fix
- Laravel 13 and PHP 8.3+ specific context
阅读单个规则文件获取详细说明和代码示例:
rules/sec-broken-access-control.md
rules/sec-cryptographic-failures.md
rules/sec-injection-prevention.md
rules/sec-xss-react-inertia.md
rules/sec-csrf-protection.md
rules/sec-security-misconfiguration.md
rules/sec-authentication-rate-limiting.md
rules/sec-inertia-data-exposure.md每个规则文件包含:
- 带元数据的YAML前置内容(标题、影响、标签)
- 在Laravel/React场景中的重要性说明
- 错误代码示例及解释
- 正确代码示例及修复方案
- Laravel 13和PHP 8.3+特定上下文
Full Compiled Document
完整编译文档
For the complete guide with all rules expanded:
AGENTS.md如需包含所有扩展规则的完整指南:
AGENTS.md