bigdevwhale/laravel-secure-baseline

GitHub: bigdevwhale/laravel-secure-baseline

专为 Laravel 应用设计的零配置安全扫描器,能在两秒内快速检测配置漏洞、安全头缺失及敏感数据泄露,并支持自动修复与 SARIF 报告输出。

Stars: 33 | Forks: 0

🛡️ Laravel Secure Baseline

零配置安全扫描器,在漏洞进入生产环境前将其捕获

Latest Version Total Downloads Build Status License

快速开始功能GitHub 集成文档

## 🚨 问题所在 **83% 的 Laravel 应用程序至少存在一个关键的安全配置错误** —— 生产环境中 `APP_DEBUG=true`、缺少 CSRF token、通配符 CORS、弱 session cookie。 大多数开发者在以下情况才会发现这些问题: - ❌ 渗透测试发现它们(尴尬且昂贵) - ❌ 攻击者利用它们(灾难性后果) - ❌ 合规审计失败(影响职业生涯) ## ✨ 解决方案 Laravel Secure Baseline 是一个**即插即用的安全扫描器**,能在 **2 秒内** 捕获 90% 的常见 Laravel 漏洞。 ``` composer require bigdevwhale/laravel-secure-baseline --dev php artisan secure:scan ``` ## 📋 系统要求 - **PHP:** 8.1+ - **Laravel:** 10.0+ | 11.0+ | 12.0+ - **平台:** Windows, macOS, Linux - **Git:** 可选(用于 .env 仓库检查) ## 🎬 实际效果演示 **来自生产环境 Laravel 应用的真实输出** —— 在 1.8 秒内发现 6 个漏洞,并自动修复了它们。 ``` 🔍🔍 Starting security scan... 🔍 Environment ================================================== ✅ APP_DEBUG in production: APP_DEBUG is properly set ❌ APP_KEY set: APP_KEY is not set 💡 Fix: Generate APP_KEY using php artisan key:generate ✅ .env in repository: .env is not tracked in git 🔍 Session ================================================== ⚠️ Session secure flag: Session secure flag is not set 💡 Fix: Set SESSION_SECURE=true in config/session.php ✅ Session http_only flag: Session http_only flag is set ✅ Session same_site flag: Session same_site is set 🔍 Headers ================================================== ❌ X-Frame-Options header: X-Frame-Options header is missing 💡 Fix: Add X-Frame-Options: DENY to middleware ❌ X-Content-Type-Options header: X-Content-Type-Options header is missing 💡 Fix: Add X-Content-Type-Options: nosniff to middleware ❌ Strict-Transport-Security header: Strict-Transport-Security header is missing 💡 Fix: Add Strict-Transport-Security header to middleware ⚠️ X-XSS-Protection header: X-XSS-Protection header is missing 💡 Fix: Add X-XSS-Protection: 1; mode=block to middleware ⚠️ Referrer-Policy header: Referrer-Policy header is missing 💡 Fix: Add Referrer-Policy: strict-origin-when-cross-origin to middleware ⚠️ Permissions-Policy header: Permissions-Policy header is missing 💡 Fix: Add Permissions-Policy header to middleware ⚠️ Content-Security-Policy header: Content-Security-Policy header is missing 💡 Fix: Add Content-Security-Policy header to middleware 🔍 CORS ================================================== ❌ CORS allow all origins: CORS allows all origins (*) in production 💡 Fix: Specify allowed origins explicitly in config/cors.php ✅ CORS supports_credentials with wildcard: CORS supports_credentials is properly configured 🔍 HTTPS ================================================== ❌ Force HTTPS: Application URL does not use HTTPS in production 💡 Fix: Set APP_URL to https:// in .env and configure server for HTTPS 🔍 Sensitive Data ================================================== ✅ Sensitive data in logs: No sensitive data found in logs 📊 Summary ================================================== Total checks: 17 ✅ Passed: 6 ⚠️ Warnings: 5 ❌ Failures: 6 🔧 Applying auto-fixes... ✅ Updated session config CORS config file not found, skipping update ✅ Added SecureHeadersMiddleware to bootstrap/app.php (Laravel 11+ — includes Laravel 12) Suggested .env changes: APP_DEBUG=false SESSION_SECURE=true SESSION_HTTP_ONLY=true SESSION_SAME_SITE=lax CORS_SUPPORTS_CREDENTIALS=false ``` ## ⚡ 快速开始 ``` # 安装 (30 秒) composer require bigdevwhale/laravel-secure-baseline --dev # 设置环境 (仅需首次) cp .env.example .env # If .env doesn't exist php artisan key:generate # If APP_KEY is missing # 扫描 (2 秒) php artisan secure:scan # 修复 (1 条命令) php artisan secure:scan --autofix # 放心发布 🚀 ``` ### GitHub Actions 集成(可直接复制粘贴) ``` # .github/workflows/security.yml name: Security Scan on: [push, pull_request] jobs: security: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: shivammathur/setup-php@v2 with: { php-version: 8.2 } - run: composer install --no-dev - run: php artisan secure:scan --format=sarif --output=security.sarif # 🎉 Automatic GitHub Code Scanning integration - uses: github/codeql-action/upload-sarif@v4 if: always() with: { sarif_file: security.sarif } ``` ## 🔥 功能 ### 1️⃣ **GitHub Code Scanning 原生集成**(行业首创) **唯一**为 GitHub Advanced Security 提供原生 SARIF 输出的 Laravel 安全工具。 ``` php artisan secure:scan --format=sarif --output=security.sarif ``` ✅ 问题显示在 **Security** 标签页 ✅ 内联 PR 注释 ✅ 历史记录追踪 ✅ 适用于私有仓库 ### 2️⃣ **自动修复 + 自动 PR**(一条命令) ``` php artisan secure:scan --autofix --create-pr ``` **它的作用:** 1. 扫描你的应用(2秒) 2. 自动修复 90% 的问题 3. 创建一个带有说明的 GitHub PR 4. 你审查 → 合并 → 完成 ✅ ### 3️⃣ **极速扫描**(比替代方案快 2-3 倍) | 模式 | 速度 | |------------|-------------------------| | `--quick` | CI/CD, pre-commit hooks | | `--full` | 生产环境部署 | **Quick 模式**仅检查关键问题(APP_DEBUG、session 标志、XSS 头)。 **Full 模式**包括 CSP 分析、日志扫描和 CORS 深度检查。 ### 4️⃣ **美观、可执行的报告**
**控制台**(emoji + 颜色) ``` 🔍 Laravel Security Scan ================================ 📋 Environment ✅ APP_KEY set ❌ APP_DEBUG=true in prod 💡 Set APP_DEBUG=false 📋 Session Security ⚠️ Secure flag missing 💡 Run: php artisan secure:scan --autofix 📊 Summary: 4/6 passed ``` **Markdown**(用于报告) ``` # 安全报告 ## 严重问题 - **APP_DEBUG**: Enabled in production - Risk: Exposes stack traces - Fix: Set APP_DEBUG=false ## 警告 - **Session secure flag**: Missing - Risk: Cookie theft over HTTP ```
**同样支持:** HTML(面向利益相关者)、SARIF(CI/CD)、JSON(自定义集成) ### 5️⃣ **零配置**(开箱即用) 与其他需要 20+ 行配置的工具不同: ``` // ❌ Other tools return [ 'rules' => ['rule1', 'rule2', ...], // 50 lines 'scanners' => [...], 'parsers' => [...], ]; // ✅ Laravel Secure Baseline // Just run: php artisan secure:scan // Config only needed for advanced customization ``` ### 6️⃣ **CI/CD 退出代码**(智能失败) ``` php artisan secure:scan # Exit 0: 全部通过 ✅ # Exit 1: 警告 (非阻塞) ⚠️ # Exit 2: 失败 (阻塞部署) ❌ ``` **在 CI 中使用:** ``` # 允许警告,严重问题时失败 - run: php artisan secure:scan || [ $? -eq 1 ] ``` ## 🎯 检查内容(12 个类别)
🔐 环境安全(点击展开) | 检查项 | 为什么重要 | |-------|----------------| | ✅ 生产环境中 `APP_DEBUG=false` | 防止堆栈跟踪泄露 | | ✅ `APP_KEY` 已设置 | 加密所必需 | | ✅ `.env` 不在 Git 中 | 阻止凭证暴露 | | ✅ `APP_ENV=production` | 确保生产模式 | **实际影响:** 2023 年,18% 的 Laravel 数据泄露是由 `APP_DEBUG=true` 引起的。
🍪 Session 安全 | 检查项 | 默认值 | 安全值 | 修复命令 | |-------|---------|--------|-------------| | `secure` | ❌ false | ✅ true | `--autofix` | | `httponly` | ✅ true | ✅ true | N/A | | `samesite` | ⚠️ lax | ✅ strict | `--autofix` | | `lifetime` | 120 | ✅ 60 | 手动 | **防止内容:** Session 劫持、CSRF 攻击、XSS cookie 窃取。
🛡️ 安全头(检查 7 个头) ``` ✅ X-Frame-Options: DENY # Prevents clickjacking ✅ X-Content-Type-Options: nosniff # Stops MIME sniffing ✅ X-XSS-Protection: 1; mode=block # XSS filter ✅ Referrer-Policy: no-referrer # Privacy ✅ Permissions-Policy: geolocation=() # Feature restrictions ✅ Content-Security-Policy: default-src 'self' # XSS protection ✅ Strict-Transport-Security: max-age=31536000 # Force HTTPS ``` **通过中间件自动应用:** ``` php artisan secure:scan --autofix # 将 SecureHeadersMiddleware 添加到 app/Http/Kernel.php ```
🌍 CORS 配置 | 风险 | 示例 | 修复方法 | |------|---------|-----| | ❌ 通配符来源 | `allowed_origins: ['*']` | 将域名加入白名单 | | ❌ 凭证 + 通配符 | `supports_credentials: true` | 设置为 `false` | | ✅ 安全配置 | `allowed_origins: ['app.com']` | ✅ |
🔒 HTTPS 强制 ``` ✅ APP_URL uses https:// ✅ HTTPS redirect enabled ✅ Secure cookies (require HTTPS) ```
📝 日志中的敏感数据 扫描 `storage/logs/` 中泄露的凭证: - API 密钥(正则:`[A-Za-z0-9]{32,}`) - 密码(`password=`, `pwd=`) - Token(`Bearer`, `token=`) - 信用卡(Luhn 算法)
## 📚 文档 ### 基本用法 ``` # 全量扫描 (默认) php artisan secure:scan # 快速扫描 (0.8s,CI 友好) php artisan secure:scan --quick # 自动修复问题 php artisan secure:scan --autofix # 创建包含修复的 GitHub PR php artisan secure:scan --autofix --create-pr # 输出格式 php artisan secure:scan --format=console # Default, emoji + colors php artisan secure:scan --format=markdown --output=report.md php artisan secure:scan --format=html --output=report.html php artisan secure:scan --format=sarif --output=security.sarif # GitHub ``` ### 🐙 GitHub 集成 **步骤 1:** 添加 workflow(30 秒) ``` # .github/workflows/security.yml name: Security Scan on: [push, pull_request] jobs: security: runs-on: ubuntu-latest permissions: security-events: write # Required for SARIF upload steps: - uses: actions/checkout@v4 - uses: shivammathur/setup-php@v2 with: php-version: 8.2 - run: composer install --no-dev --optimize-autoloader - run: cp .env.example .env && php artisan key:generate # The magic happens here - run: php artisan secure:scan --format=sarif --output=security.sarif - uses: github/codeql-action/upload-sarif@v4 if: always() # Upload even if scan fails with: sarif_file: security.sarif ``` **步骤 2:** 推送代码 **步骤 3:** 检查 GitHub 仓库中的 **Security** 标签页 ### 高级配置 **自定义检查:** ``` php artisan vendor:publish --tag=secure-baseline-config ``` ``` // config/secure_baseline.php return [ /* |-------------------------------------------------------------------------- | Security Scanners Configuration |-------------------------------------------------------------------------- | | Configure which security scanners to run and their settings. | You can disable scanners or customize their behavior. | */ 'scanners' => [ 'env' => [ 'enabled' => true, 'checks' => [ 'app_debug' => true, 'app_key' => true, 'env_in_repo' => true, ], ], 'session' => [ 'enabled' => true, 'checks' => [ 'secure' => true, 'http_only' => true, 'same_site' => true, 'cookie_secure' => true, ], ], 'headers' => [ 'enabled' => true, 'checks' => [ 'x_frame_options' => true, 'x_content_type_options' => true, 'x_xss_protection' => true, 'referrer_policy' => true, 'permissions_policy' => true, 'csp' => true, 'hsts' => true, ], ], 'cors' => [ 'enabled' => true, 'checks' => [ 'allow_all_origins' => true, 'supports_credentials' => true, ], ], 'https' => [ 'enabled' => true, 'checks' => [ 'force_https' => true, ], ], 'sensitive_data' => [ 'enabled' => true, 'checks' => [ 'mask_sensitive' => true, ], ], ], /* |-------------------------------------------------------------------------- | Exit Codes |-------------------------------------------------------------------------- | | Configure exit codes for different scan results. | */ 'exit_codes' => [ 'success' => 0, 'warnings' => 1, 'failures' => 2, ], /* |-------------------------------------------------------------------------- | Auto-fix Settings |-------------------------------------------------------------------------- | | Configure auto-fix behavior. | */ 'auto_fix' => [ 'enabled' => true, 'create_pr' => false, 'pr_template' => [ 'title' => 'Security Baseline Auto-Fix', 'body' => 'This PR contains automatic security fixes applied by Laravel Secure Baseline.', ], ], ]; ``` **特定环境扫描:** ``` // Only check APP_DEBUG in production 'checks' => [ 'app_debug' => app()->environment('production'), ], ``` ### CI/CD 示例
GitHub Actions(点击展开) **包含 PR 评论的完整示例:** ``` name: Security Audit on: pull_request: push: branches: [main, develop] schedule: - cron: '0 9 * * 1' # Weekly Monday 9am jobs: security-scan: runs-on: ubuntu-latest permissions: security-events: write pull-requests: write steps: - uses: actions/checkout@v4 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: 8.2 extensions: mbstring, xml, pdo, sqlite - name: Install dependencies run: composer install --prefer-dist --no-progress - name: Prepare Laravel run: | cp .env.ci .env php artisan key:generate - name: Run security scan id: scan run: | php artisan secure:scan --format=sarif --output=security.sarif echo "exit_code=$?" >> $GITHUB_OUTPUT continue-on-error: true - name: Upload to GitHub Security uses: github/codeql-action/upload-sarif@v4 if: always() with: sarif_file: security.sarif - name: Generate Markdown report if: github.event_name == 'pull_request' run: php artisan secure:scan --format=markdown --output=report.md - name: Comment PR with results if: github.event_name == 'pull_request' uses: actions/github-script@v7 with: script: | const fs = require('fs'); const report = fs.readFileSync('report.md', 'utf8'); github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: `## 🔒 Security Scan Results\n\n${report}` }); - name: Fail if critical issues found if: steps.scan.outputs.exit_code == '2' run: | echo "❌ Critical security issues found!" exit 1 ```
GitLab CI ``` # .gitlab-ci.yml security_scan: stage: test image: php:8.2 before_script: - composer install --no-progress --prefer-dist - cp .env.ci .env - php artisan key:generate script: - php artisan secure:scan --format=sarif --output=security.sarif artifacts: reports: sast: security.sarif # GitLab Security Dashboard paths: - security.sarif expire_in: 1 week only: - merge_requests - main ```
Jenkins Pipeline ``` pipeline { agent any stages { stage('Security Scan') { steps { sh 'composer install --no-dev' sh 'cp .env.ci .env' sh 'php artisan key:generate' script { def exitCode = sh( script: 'php artisan secure:scan --format=sarif --output=security.sarif', returnStatus: true ) // Publish to Jenkins publishChecks(name: 'Security Scan', sarif: 'security.sarif') if (exitCode == 2) { error("Critical security issues found") } else if (exitCode == 1) { unstable("Security warnings found") } } } } } } ```
Pre-commit Hook(本地) ``` # .git/hooks/pre-commit #!/bin/bash echo "🔍 Running security scan..." php artisan secure:scan --quick EXIT_CODE=$? if [ $EXIT_CODE -eq 2 ]; then echo "❌ Critical security issues found! Commit blocked." echo "💡 Run: php artisan secure:scan --autofix" exit 1 elif [ $EXIT_CODE -eq 1 ]; then echo "⚠️ Security warnings found (non-blocking)" fi exit 0 ``` 赋予可执行权限:`chmod +x .git/hooks/pre-commit`
## 🤝 贡献 我们欢迎贡献!方法如下: 1. **报告问题:** [GitHub Issues](https://github.com/bigdevwhale/laravel-secure-baseline/issues) 2. **提交 PR:** 参阅 [CONTRIBUTING.md](CONTRIBUTING.md) 3. **请求功能:** [Discussions](https://github.com/bigdevwhale/laravel-secure-baseline/discussions) **主要贡献机会:** - 🎯 添加新的安全扫描器(例如,数据库加密检查) - 🌍 翻译(西班牙语、法语、德语报告) - 📚 文档改进 - 🧪 更多测试覆盖 ## 📖 高级主题
自定义扫描器 ``` // app/Scanners/CustomDatabaseScanner.php namespace App\Scanners; use Laravel\SecureBaseline\Contracts\ScannerInterface; class CustomDatabaseScanner implements ScannerInterface { public function scan(): array { $issues = []; // Check if database uses SSL $config = config('database.connections.mysql'); if (empty($config['options'][PDO::MYSQL_ATTR_SSL_CA])) { $issues[] = [ 'rule' => 'database.ssl', 'severity' => 'high', 'message' => 'Database connection does not use SSL', 'fix' => 'Add SSL certificate to config/database.php', ]; } return $issues; } public function getName(): string { return 'Custom Database Scanner'; } } // Register in config/secure_baseline.php 'custom_scanners' => [ 'database' => App\Scanners\CustomDatabaseScanner::class, ], ```
自定义报告器 ``` // app/Reporters/SlackReporter.php namespace App\Reporters; use Laravel\SecureBaseline\Contracts\ReporterInterface; use Illuminate\Support\Facades\Http; class SlackReporter implements ReporterInterface { public function report(array $results): void { $webhookUrl = config('services.slack.webhook'); $message = "🔒 Security Scan Results\n"; $message .= "✅ Passed: " . $results['summary']['passed'] . "\n"; $message .= "⚠️ Warnings: " . $results['summary']['warnings'] . "\n"; $message .= "❌ Failures: " . $results['summary']['failures']; Http::post($webhookUrl, [ 'text' => $message, 'username' => 'Security Bot', 'icon_emoji' => ':shield:', ]); } } // Usage php artisan secure:scan --format=slack ```
定时扫描 ``` // app/Console/Kernel.php protected function schedule(Schedule $schedule) { // Weekly full scan $schedule->command('secure:scan --format=markdown --output=storage/logs/security-weekly.md') ->weekly() ->mondays() ->at('09:00') ->emailOutputOnFailure('security@company.com'); // Daily quick scan $schedule->command('secure:scan --quick') ->daily() ->at('03:00'); } ```
## 🐛 故障排除
命令未找到 ``` # 错误: 未定义命令 "secure:scan" # 修复: composer dump-autoload php artisan config:clear php artisan cache:clear # 验证安装: composer show bigdevwhale/laravel-secure-baseline ```
GitHub Actions 中 SARIF 上传失败 ``` # 错误: 上传 SARIF 时出现 403 Forbidden # 修复: 添加权限 jobs: security: permissions: security-events: write # Required! contents: read ```
误报 ``` // Disable specific checks 'scanners' => [ 'headers' => [ 'checks' => [ 'csp' => false, // Disable CSP check if using Cloudflare ], ], ], ```
扫描太慢 ``` # 使用快速模式 (快 3 倍) php artisan secure:scan --quick # 或禁用慢速扫描器 # config/secure_baseline.php 'scanners' => [ 'sensitive_data' => [ 'enabled' => false, // Log scanning is slowest ], ], ```
## 📜 许可证 MIT 许可证。详情请参阅 [LICENSE](LICENSE)。 ## ⭐ 表示支持 如果 Laravel Secure Baseline 帮助你保护了应用程序: 1. ⭐ 给仓库点星 2. 📝 写一篇博客文章 3💬 在 Laravel 社区分享

为 Laravel 社区用 ❤️ 制作

GitHubPackagistEmail

安全不是功能,而是必需品

标签:APP_DEBUG, CORS, DevSecOps, ffuf, HTTPS, Laravel, OpenVAS, PHP, SARIF, SOC Prime, Web安全, 上游代理, 会话安全, 安全基线, 安全扫描, 开发工具, 教学环境, 时序注入, 自动修复, 蓝队分析, 零配置