初始化

This commit is contained in:
2026-03-05 21:27:11 +08:00
commit 130de0fd5d
140 changed files with 21972 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
# Security Audit — 检查命令与代码示例
> 主流程见 SKILL.md本文档为 PHP/前端/密钥/CodeGuard 的完整检查命令和最佳实践。
## 依赖扫描
```bash
npm audit --audit-level=high
composer audit
```
## PHP 检查命令
```bash
vendor/bin/phpstan analyse --level=max
rg -n "eval\(|exec\(|system\(|passthru\(|shell_exec\(|popen\(" --type php --glob '!vendor/**'
rg -n "unserialize\(" --type php --glob '!vendor/**'
rg -n "include\s*\\\$|require\s*\\\$" --type php --glob '!vendor/**'
rg -n "Db::raw\(|DB::select\(.*\\\$" --type php --glob '!vendor/**'
```
## 前端检查命令
```bash
rg -n "v-html" --glob '*.vue' --glob '*.ts'
rg -n "eval\(|new Function\(" --glob '*.ts' --glob '!node_modules/**'
rg -n "\.innerHTML\s*=|\.outerHTML\s*=" --glob '*.vue' --glob '!node_modules/**'
rg -n "localStorage\.(set|get)Item.*[Tt]oken" --glob '*.ts' --glob '!node_modules/**'
rg -n "target=\"_blank\"" --glob '*.vue' | rg -v "noopener"
```
## 密钥扫描命令
```bash
# 通用、AWS、GitHub、Stripe、Google、JWT、私钥、数据库连接串
rg -rn "(?i)(api.?key|secret|password|token)\s*[=:]\s*['\"][a-zA-Z0-9]{8,}" --glob '!vendor/**' --glob '!node_modules/**'
rg -rn "A(KIA|GPA|IDA|ROA)[0-9A-Z]{16}" ...
rg -rn "gh[pousr]_[a-zA-Z0-9]{36}" ...
rg -rn "sk_live_|pk_live_|sk_test_[a-zA-Z0-9]{24}" ...
rg -rn "AIza[a-zA-Z0-9_\-]{35}" ...
rg -rn "eyJ[a-zA-Z0-9_\-]+\.[a-zA-Z0-9_\-]+\.[a-zA-Z0-9_\-]+" ...
rg -rn "BEGIN\s+(RSA\s+)?PRIVATE\s+KEY" ...
rg -rn "(mysql|mongodb|redis|postgres)://[^:]+:[^@]+" ...
```
## CORS 集中配置
❌ Controller 内单独设置 Allow-Origin: *。✅ CorsMiddleware 集中配置env('CORS_ORIGIN')Allow-Credentials 与 Allow-Origin: * 不共存。
## 密码哈希
❌ md5/sha1、PASSWORD_BCRYPT 无 cost。✅ PASSWORD_ARGON2IDmemory_cost 65536, time_cost 4或 PASSWORD_BCRYPT cost=12。验证用 password_verify升级用 password_needs_rehash。
## CodeGuard 增强
IDORfind/findOrFail($request/$id) 未附加所有权 → 应 $user->orders()->findOrFail($id)。Mass Assignmentfill($request->all())、create/update($request->all())。Sessionsetcookie 需 Secure+HttpOnly+SameSite。禁用算法md5/sha1、AES-ECB。文件上传不用 getClientFilename() 原始名,用 UUIDMIME 用 finfo magic bytes。SSRFGuzzle/curl 对用户 URL 需域名白名单。

View File

@@ -0,0 +1,82 @@
---
description: API & Web services security (REST/GraphQL/SOAP), schema validation, authn/z, SSRF
languages:
- c
- go
- java
- typescript
- php
- python
- ruby
- xml
- yaml
alwaysApply: false
---
rule_id: codeguard-0-api-web-services
## API & Web Services Security
Secure REST, GraphQL, and SOAP/WS services endtoend: transport, authn/z, schema validation, SSRF controls, DoS limits, and microservicesafe patterns.
### Transport and TLS
- HTTPS only; consider mTLS for highvalue/internal services. Validate certs (CN/SAN, revocation) and prevent mixed content.
### Authentication and Tokens
- Use standard flows (OAuth2/OIDC) for clients; avoid custom schemes. For services, use mTLS or signed service tokens.
- JWTs: pin algorithms; validate iss/aud/exp/nbf; short lifetimes; rotation; denylist on logout/revoke. Prefer opaque tokens when revocation is required and central store is available.
- API keys: scope narrowly; rate limit; monitor usage; do not use alone for sensitive operations.
### Authorization
- Enforce perendpoint, perresource checks serverside; deny by default.
- For microservices, authorize at gateway (coarse) and service (fine) layers; propagate signed internal identity, not external tokens.
### Input and Content Handling
- Validate inputs via contracts: OpenAPI/JSON Schema, GraphQL SDL, XSD. Reject unknown fields and oversize payloads; set limits.
- Content types: enforce explicit ContentType/Accept; reject unsupported combinations. Harden XML parsers against XXE/expansion.
### SQL/Injection Safety in Resolvers and Handlers
- Use parameterized queries/ORM bind parameters; never concatenate user input into queries or commands.
### GraphQLSpecific Controls
- Limit query depth and overall complexity; enforce pagination; timeouts on execution; disable introspection and IDEs in production.
- Implement field/objectlevel authorization to prevent IDOR/BOLA; validate batching and rate limit per object type.
### SSRF Prevention for Outbound Calls
- Do not accept raw URLs. Validate domains/IPs using libraries; restrict to HTTP/HTTPS only (block file://, gopher://, ftp://, etc.).
- Case 1 (fixed partners): strict allowlists; disable redirects; network egress allowlists.
- Case 2 (arbitrary): block private/linklocal/localhost ranges; resolve and verify all IPs are public; require signed tokens from the target where feasible.
### SOAP/WS and XML Safety
- Validate SOAP payloads with XSD; limit message sizes; enable XML signatures/encryption where required.
- Configure parsers against XXE, entity expansion, and recursive payloads; scan attachments.
### Rate Limiting and DoS
- Apply perIP/user/client limits, circuit breakers, and timeouts. Use serverside batching and caching to reduce load.
### Management Endpoints
- Do not expose over the Internet. Require strong auth (MFA), network restrictions, and separate ports/hosts.
### Testing and Assessment
- Maintain formal API definitions; drive contract tests and fuzzing from specs.
- Assess endpoints for authn/z bypass, SSRF, injection, and information leakage; log token validation failures.
### Microservices Practices
- Policyascode with embedded decision points; sidecar or library PDPs.
- Service identity via mTLS or signed tokens; never reuse external tokens internally.
- Centralized structured logging with correlation IDs; sanitize sensitive data.
### Implementation Checklist
- HTTPS/mTLS configured; certs managed; no mixed content.
- Contract validation at the edge and service; unknown fields rejected; size/time limits enforced.
- Strong authn/z per endpoint; GraphQL limits applied; introspection disabled in prod.
- SSRF protections at app and network layers; redirects disabled; allowlists where possible.
- Rate limiting, circuit breakers, and resilient patterns in place.
- Management endpoints isolated and strongly authenticated.
- Logs structured and privacysafe with correlation IDs.
### Test Plan
- Contract tests for schema adherence; fuzzing with schemaaware tools.
- Pen tests for SSRF, IDOR/BOLA, and authz bypass; performance tests for DoS limits.
- Test all HTTP methods per endpoint; discover parameters in URL paths, headers, and structured data beyond obvious query strings.
- Automated checks for token validation and revocation behavior.

View File

@@ -0,0 +1,103 @@
---
description: Authentication and MFA best practices (passwords, MFA, OAuth/OIDC, SAML, recovery, tokens)
languages:
- c
- go
- java
- typescript
- kotlin
- matlab
- php
- python
- ruby
- swift
alwaysApply: false
---
rule_id: codeguard-0-authentication-mfa
## Authentication & MFA
Build a resilient, user-friendly authentication system that resists credential attacks, protects secrets, and supports strong, phishing-resistant MFA and secure recovery.
### Account Identifiers and UX
- Use non-public, random, and unique internal user identifiers. Allow login via verified email or username.
- Always return generic error messages (e.g., "Invalid username or password"). Keep timing consistent to prevent account enumeration.
- Support password managers: `<input type="password">`, allow paste, no JS blocks.
### Password Policy
- Accept passphrases and full Unicode; minimum 8 characters; avoid composition rules. Set only a reasonable maximum length (64+).
- Check new passwords against breach corpora (e.g., kanonymity APIs); reject breached/common passwords.
### Password Storage (Hashing)
- Hash, do not encrypt. Use slow, memoryhard algorithms with unique peruser salts and constanttime comparison.
- Preferred order and parameters (tune to your hardware; target <1s on server):
- Argon2id: m=1946 MiB, t=21, p=1 (or equivalent security tradeoffs)
- scrypt: N=2^17, r=8, p=1 (or equivalent)
- bcrypt (legacy only): cost ≥10, be aware of 72byte input limit
- PBKDF2 (FIPS): PBKDF2HMACSHA256 ≥600k, or SHA1 ≥1.3M
- Optional pepper: store outside DB (KMS/HSM); if used, apply via HMAC or prehashing. Plan for user resets if pepper rotates.
- Unicode and null bytes must be supported endtoend by the library.
### Authentication Flow Hardening
- Enforce TLS for all auth endpoints and token transport; enable HSTS.
- Implement rate limits per IP, account, and globally; add proofofwork or CAPTCHA only as last resort.
- Lockouts/throttling: progressive backoff; avoid permanent lockout via resets/alerts.
- Uniform responses and code paths to reduce oracle/timing signals.
### MultiFactor Authentication (MFA)
- Adopt phishingresistant factors by default for sensitive accounts: passkeys/WebAuthn (FIDO2) or hardware U2F.
- Acceptable: TOTP (appbased), smart cards with PIN. Avoid for sensitive use: SMS/voice, email codes; never rely on security questions.
- Require MFA for: login, password/email changes, disabling MFA, privilege elevation, highvalue transactions, new devices/locations.
- Riskbased MFA signals: new device, geovelocity, IP reputation, unusual time, breached credentials.
- MFA recovery: provide singleuse backup codes, encourage multiple factors, and require strong identity verification for resets.
- Handle failed MFA: offer alternative enrolled methods, notify users of failures, and log context (no secrets).
### Federation and Protocols (OAuth 2.0 / OIDC / SAML)
- Use standard protocols only; do not build your own.
- OAuth 2.0/OIDC:
- Prefer Authorization Code with PKCE for public/native apps; avoid Implicit and ROPC.
- Validate state and nonce; use exact redirect URI matching; prevent open redirects.
- Constrain tokens to audience/scope; use DPoP or mTLS for senderconstraining when possible.
- Rotate refresh tokens; revoke on logout or risk signals.
- SAML:
- TLS 1.2+; sign responses/assertions; encrypt sensitive assertions.
- Validate issuers, InResponseTo, timestamps (NotBefore/NotOnOrAfter), Recipient; verify against trusted keys.
- Prevent XML signature wrapping with strict schema validation and hardened XPath selection.
- Keep response lifetimes short; prefer SPinitiated flows; validate RelayState; implement replay detection.
### Tokens (JWT and Opaque)
- Prefer opaque servermanaged tokens for simplicity and revocation. If using JWTs:
- Explicitly pin algorithms; reject "none"; validate iss/aud/exp/iat/nbf; use short lifetimes and rotation.
- Store secrets/keys securely (KMS/HSM). Use strong HMAC secrets or asymmetric keys; never hardcode.
- Consider binding tokens to a client context (e.g., fingerprint hash in cookie) to reduce replay.
- Implement denylist/allowlist for revocation on logout and critical events.
### Recovery and Reset
- Return the same response for existing and nonexisting accounts (no enumeration). Normalize timing.
- Generate 32+ byte, CSPRNG tokens; singleuse; store as hashes; short expiry.
- Use HTTPS reset links to pinned, trusted domains; add referrer policy (noreferrer) on UI.
- After reset: require reauthentication, rotate sessions, and do not autologin.
- Never lock accounts due to reset attempts; ratelimit and monitor instead.
### Administrative and Internal Accounts
- Separate admin login from public forms; enforce stronger MFA, device posture checks, IP allowlists, and stepup auth.
- Use distinct session contexts and stricter timeouts for admin operations.
### Monitoring and Signals
- Log auth events (failures/successes, MFA enroll/verify, resets, lockouts) with stable fields and correlation IDs; never log secrets or raw tokens.
- Detect credential stuffing: high failure rates, many IPs/agents, impossible travel. Notify users of new device logins.
### Implementation Checklist
- Passwords: Argon2id (preferred) with peruser salt, constanttime verify; breached password checks on change/set.
- MFA: WebAuthn/passkeys or hardware tokens for highrisk; TOTP as fallback; secure recovery with backup codes.
- Federation: Authorization Code + PKCE; strict redirect URI validation; audience/scope enforced; token rotation.
- Tokens: shortlived, senderconstrained where possible; revocation implemented; secrets in KMS/HSM.
- Recovery: singleuse, hashed, timeboxed tokens; consistent responses; reauth required after reset; sessions rotated.
- Abuse: rate limits, throttling, and anomaly detection on auth endpoints; uniform error handling.
- Admin: isolated flows with stricter policies and device checks.
### Test Plan
- Unit/integration tests for login, MFA enroll/verify, resets, and lockouts with uniform errors.
- Protocol tests: PKCE, state/nonce, redirect URI validation, token audience/scope.
- Dynamic tests for credential stuffing resistance and token replay; validate revocation after logout and role change.

View File

@@ -0,0 +1,59 @@
---
description: Authorization and access control (RBAC/ABAC/ReBAC, IDOR, mass assignment, transaction auth)
languages:
- c
- go
- java
- typescript
- php
- python
- ruby
- yaml
alwaysApply: false
---
rule_id: codeguard-0-authorization-access-control
## Authorization & Access Control
Enforce least privilege and precise access decisions for every request and resource, prevent IDOR and mass assignment, and provide strong transaction authorization where necessary.
### Core Principles
1. Deny by Default: The default for any access request should be 'deny'. Explicitly grant permissions to roles or users rather than explicitly denying them. When no allow rule matches, return HTTP 403 Forbidden.
2. Principle of Least Privilege: Grant users the minimum level of access required to perform their job functions. Regularly audit permissions to ensure they are not excessive.
3. Validate Permissions on Every Request: Check authorization for every single request, regardless of source (AJAX, API, direct). Use middleware/filters to ensure consistent enforcement.
4. Prefer ABAC/ReBAC over RBAC: Use Attribute-Based Access Control (ABAC) or Relationship-Based Access Control (ReBAC) for fine-grained permissions instead of simple role-based access control.
### Systemic Controls
- Centralize authorization at service boundaries via middleware/policies/filters.
- Model permissions at the resource level (ownership/tenancy) and enforce scoping in data queries.
- Return generic 403/404 responses to avoid leaking resource existence.
- Log all denials with user, action, resource identifier (non-PII), and rationale code.
### Preventing IDOR
- Never trust user-supplied identifiers alone. Always verify access to each object instance.
- Resolve resources through user-scoped queries or server-side lookups. Example: `currentUser.projects.find(id)` instead of `Project.find(id)`.
- Use non-enumerable identifiers (UUIDs/random) as defense-in-depth. Do not rely on obscurity alone.
### Preventing Mass Assignment
- Do not bind request bodies directly to domain objects containing sensitive fields.
- Expose only safe, editable fields via DTOs. Maintain explicit allow-lists for patch/update.
- Use framework features to block-list sensitive fields if allow-listing is infeasible.
### Transaction Authorization (Step-Up)
- Require a second factor for sensitive actions (wire transfers, privilege elevation, data export). Apply WhatYouSeeIsWhatYouSign: show critical fields for user confirmation.
- Use unique, timelimited authorization credentials per transaction; reject on data changes midflow.
- Enforce the chosen authorization method server-side; prevent clientside downgrades.
- Protect against brute-force with throttling and complete flow restarts after failures.
### Testing and Automation
- Maintain an authorization matrix (YAML/JSON) listing endpoints/resources, roles/attributes, and expected outcomes.
- Automate integration tests that iterate the matrix, mint role tokens, and assert allow/deny results—including token expiry/revocation cases.
- Exercise negative tests: swapped IDs, downgraded roles, missing scopes, and bypass attempts.
### Implementation Checklist
- Middleware/policies enforce deny-by-default and resource checks on every endpoint.
- Query scoping ensures users only access permitted rows/objects.
- DTOs and allow-lists prevent mass assignment; sensitive fields never bindable.
- Step-up authorization in place for sensitive operations with unique, short-lived credentials.
- Authorization matrix drives CI tests; failures block merges.

View File

@@ -0,0 +1,111 @@
---
description: Client-side web security (XSS/DOM XSS, CSP, CSRF, clickjacking, XS-Leaks, third-party JS)
languages:
- c
- html
- typescript
- php
- vlang
alwaysApply: false
---
rule_id: codeguard-0-client-side-web-security
## Clientside Web Security
Protect browser clients against code injection, request forgery, UI redress, crosssite leaks, and unsafe thirdparty scripts with layered, contextaware controls.
### XSS Prevention (ContextAware)
- HTML context: prefer `textContent`. If HTML is required, sanitize with a vetted library (e.g., DOMPurify) and strict allowlists.
- Attribute context: always quote attributes and encode values.
- TypeScript context: do not build JS from untrusted strings; avoid inline event handlers; use `addEventListener`.
- URL context: validate protocol/domain and encode; block `typescript:` and data URLs where inappropriate.
- Redirects/forwards: never use user input directly for destinations; use server-side mapping (ID→URL) or validate against trusted domain allowlists.
- CSS context: allowlist values; never inject raw style text from users.
Example sanitization:
```typescript
const clean = DOMPurify.sanitize(userHtml, {
ALLOWED_TAGS: ['b','i','p','a','ul','li'],
ALLOWED_ATTR: ['href','target','rel'],
ALLOW_DATA_ATTR: false
});
```
### DOMbased XSS and Dangerous Sinks
- Prohibit `innerHTML`, `outerHTML`, `document.write` with untrusted data.
- Prohibit `eval`, `new Function`, stringbased `setTimeout/Interval`.
- Validate and encode data before assigning to `location` or event handler properties.
- Use strict mode and explicit variable declarations to prevent global namespace pollution from DOM clobbering.
- Adopt Trusted Types and enforce strict CSP to prevent DOM sinks exploitation.
Trusted Types + CSP:
```http
Content-Security-Policy: script-src 'self' 'nonce-{random}'; object-src 'none'; base-uri 'self'; require-trusted-types-for 'script'
```
### Content Security Policy (CSP)
- Prefer noncebased or hashbased CSP over domain allowlists.
- Start with ReportOnly mode; collect violations; then enforce.
- Baseline to aim for: `default-src 'self'; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'; form-action 'self'; object-src 'none'; base-uri 'none'; upgrade-insecure-requests`.
### CSRF Defense
- Fix XSS first; then layer CSRF defenses.
- Use frameworknative CSRF protections and synchronizer tokens on all statechanging requests.
- Cookie settings: `SameSite=Lax` or `Strict`; sessions `Secure` and `HttpOnly`; use `__Host-` prefix when possible.
- Validate Origin/Referer; require custom headers for API mutations in SPA token models.
- Never use GET for state changes; validate tokens on POST/PUT/DELETE/PATCH only. Enforce HTTPS for all token transmission.
### Clickjacking Defense
- Primary: `Content-Security-Policy: frame-ancestors 'none'` or a specific allowlist.
- Fallback for legacy browsers: `X-Frame-Options: DENY` or `SAMEORIGIN`.
- Consider UX confirmations for sensitive actions when framing is required.
### CrossSite Leaks (XSLeaks) Controls
- Use `SameSite` cookies appropriately; prefer `Strict` for sensitive actions.
- Adopt Fetch Metadata protections to block suspicious crosssite requests.
- Isolate browsing contexts: COOP/COEP and CORP where applicable.
- Disable caching and add userunique tokens for sensitive responses to prevent cache probing.
### ThirdParty TypeScript
- Minimize and isolate: prefer sandboxed iframes with `sandbox` and postMessage origin checks.
- Use Subresource Integrity (SRI) for external scripts and monitor for changes.
- Provide a firstparty, sanitized data layer; deny direct DOM access from tags where possible.
- Govern via tag manager controls and vendor contracts; keep libraries updated.
SRI example:
```html
<script src="https://cdn.vendor.com/app.ts"
integrity="sha384-..." crossorigin="anonymous"></script>
```
### HTML5, CORS, WebSockets, Storage
- postMessage: always specify exact target origin; verify `event.origin` on receive.
- CORS: avoid `*`; allowlist origins; validate preflights; do not rely on CORS for authz.
- WebSockets: require `wss://`, origin checks, auth, message size limits, and safe JSON parsing.
- Client storage: never store secrets in `localStorage`/`sessionStorage`; prefer HttpOnly cookies; if unavoidable, isolate via Web Workers.
- Links: add `rel="noopener noreferrer"` to external `target=_blank` links.
### HTTP Security Headers (Client Impact)
- HSTS: enforce HTTPS everywhere.
- XContentTypeOptions: `nosniff`.
- ReferrerPolicy and PermissionsPolicy: restrict sensitive signals and capabilities.
### AJAX and Safe DOM APIs
- Avoid dynamic code execution; use function callbacks, not strings.
- Build JSON with `JSON.stringify`; never via string concatenation.
- Prefer creating elements and setting `textContent`/safe attributes over raw HTML insertion.
### Implementation Checklist
- Contextual encoding/sanitization for every sink; no dangerous APIs without guards.
- Strict CSP with nonces and Trusted Types; violations monitored.
- CSRF tokens on all statechanging requests; secure cookie attributes.
- Frame protections set; XSLeak mitigations enabled (Fetch Metadata, COOP/COEP/CORP).
- Thirdparty JS isolated with SRI and sandbox; vetted data layer only.
- HTML5/CORS/WebSocket usage hardened; no secrets in web storage.
- Security headers enabled and validated.
### Test Plan
- Automated checks for dangerous DOM/API patterns.
- E2E tests for CSRF and clickjacking; CSP report monitoring.
- Manual probes for XSLeaks (frame count, timing, cache) and open redirect behavior.

View File

@@ -0,0 +1,74 @@
---
description: Secure file handling & uploads (validation, storage isolation, scanning, safe delivery)
languages:
- c
- go
- java
- typescript
- php
- python
- ruby
alwaysApply: false
---
rule_id: codeguard-0-file-handling-and-uploads
## File Upload Security Guidelines
This rule advises on secure file upload practices to prevent malicious file attacks and protect system integrity:
- Extension Validation
- List allowed extensions only for business-critical functionality.
- Ensure input validation is applied before validating extensions.
- Avoid double extensions (e.g., `.jpg.php`) and null byte injection (e.g., `.php%00.jpg`).
- Use allowlist approach rather than denylist for file extensions.
- Validate extensions after decoding filename to prevent bypass attempts.
- Content Type and File Signature Validation
- Never trust client-supplied Content-Type headers as they can be spoofed.
- Validate file signatures (magic numbers) in conjunction with Content-Type checking.
- Implement allowlist approach for MIME types as a quick protection layer.
- Use file signature validation but not as a standalone security measure.
- Filename Security
- Generate random filenames (UUID/GUID) instead of using user-supplied names.
- If user filenames required, implement maximum length limits.
- Restrict characters to alphanumeric, hyphens, spaces, and periods only.
- Prevent leading periods (hidden files) and sequential periods (directory traversal).
- Avoid leading hyphens or spaces for safer shell script processing.
- File Content Validation
- For images, apply image rewriting techniques to destroy malicious content.
- For Microsoft documents, use Apache POI for validation.
- Avoid ZIP files due to numerous attack vectors.
- Implement manual file review in sandboxed environments when resources allow.
- Integrate antivirus scanning and Content Disarm & Reconstruct (CDR) for applicable file types.
- Storage Security
- Store files on different servers for complete segregation when possible.
- Store files outside webroot with administrative access only.
- If storing in webroot, set write-only permissions with proper access controls.
- Use application handlers that map IDs to filenames for public access.
- Consider database storage for specific use cases with DBA expertise.
- Access Control and Authentication
- Require user authentication before allowing file uploads.
- Implement proper authorization levels for file access and modification.
- Set filesystem permissions on principle of least privilege.
- Scan files before execution if execution permission is required.
- Upload and Download Limits
- Set proper file size limits for upload protection.
- Consider post-decompression size limits for compressed files.
- Implement request limits for download services to prevent DoS attacks.
- Use secure methods to calculate ZIP file sizes safely.
- Additional Security Measures
- Protect file upload endpoints from CSRF attacks.
- Keep all file processing libraries securely configured and updated.
- Implement logging and monitoring for upload activities.
- Provide user reporting mechanisms for illegal content.
- Use secure extraction methods for compressed files.
Summary:
Implement defense-in-depth for file uploads through multi-layered validation, secure storage practices, proper access controls, and comprehensive monitoring. Never rely on single validation methods and always generate safe filenames to prevent attacks.

View File

@@ -0,0 +1,107 @@
---
description: Input validation and injection defense (SQL/SOQL/LDAP/OS), parameterization, prototype pollution
languages:
- apex
- c
- go
- html
- java
- typescript
- php
- powershell
- python
- ruby
- shell
- sql
alwaysApply: false
---
rule_id: codeguard-0-input-validation-injection
## Input Validation & Injection Defense
Ensure untrusted input is validated and never interpreted as code. Prevent injection across SQL, LDAP, OS commands, templating, and TypeScript runtime object graphs.
### Core Strategy
- Validate early at trust boundaries with positive (allowlist) validation and canonicalization.
- Treat all untrusted input as data, never as code. Use safe APIs that separate code from data.
- Parameterize queries/commands; escape only as last resort and contextspecific.
### Validation Playbook
- Syntactic validation: enforce format, type, ranges, and lengths for each field.
- Semantic validation: enforce business rules (e.g., start ≤ end date, enum allowlists).
- Normalization: canonicalize encodings before validation; validate complete strings (regex anchors ^$); beware ReDoS.
- Freeform text: define character class allowlists; normalize Unicode; set length bounds.
- Files: validate by content type (magic), size caps, and safe extensions; servergenerate filenames; scan; store outside web root.
### SQL Injection Prevention
- Use prepared statements and parameterized queries for 100% of data access.
- Use bind variables for any dynamic SQL construction within stored procedures and never concatenate user input into SQL.
- Prefer leastprivilege DB users and views; never grant admin to app accounts.
- Escaping is fragile and discouraged; parameterization is the primary defense.
Example (Java PreparedStatement):
```java
String custname = request.getParameter("customerName");
String query = "SELECT account_balance FROM user_data WHERE user_name = ? ";
PreparedStatement pstmt = connection.prepareStatement( query );
pstmt.setString( 1, custname);
ResultSet results = pstmt.executeQuery( );
```
### SOQL/SOSL Injection (Salesforce)
SOQL and SOSL are query/search languages (no SQL-style DDL/DML). Data changes are performed via Apex DML or Database methods. Note: SOQL can lock rows via `FOR UPDATE`.
- Primary risk: data exfiltration by bypassing intended query filters/business logic; impact is amplified when Apex runs with elevated access (system mode) or when CRUD/FLS aren't enforced.
- Second-order risk (conditional): if queried records are passed to DML, injection can broaden the record set and cause unintended mass updates/deletes.
- Prefer static SOQL/SOSL with bind variables: `[SELECT Id FROM Account WHERE Name = :userInput]` or `FIND :term`.
- For dynamic SOQL, use `Database.queryWithBinds()`; for dynamic SOSL, use `Search.query()`. Allowlist any dynamic identifiers. If concatenation is unavoidable, escape string values with `String.escapeSingleQuotes()`.
- Enforce CRUD/FLS with `WITH USER_MODE` or `WITH SECURITY_ENFORCED` (don't combine both). Enforce record sharing with `with sharing` or user-mode operations. Use `Security.stripInaccessible()` before DML.
### LDAP Injection Prevention
- Always apply contextappropriate escaping:
- DN escaping for `\ # + < > , ; " =` and leading/trailing spaces
- Filter escaping for `* ( ) \ NUL`
- Validate inputs with allowlists before constructing queries; use libraries that provide DN/filter encoders.
- Use leastprivilege LDAP connections with bind authentication; avoid anonymous binds for application queries.
### OS Command Injection Defense
- Prefer builtin APIs instead of shelling out (e.g., library calls over `exec`).
- If unavoidable, use structured execution that separates command and arguments (e.g., ProcessBuilder). Do not invoke shells.
- Strictly allowlist commands and validate arguments with allowlist regex; exclude metacharacters (& | ; $ > < ` \ ! ' " ( ) and whitespace as needed).
- Use `--` to delimit arguments where supported to prevent option injection.
Example (Java ProcessBuilder):
```java
ProcessBuilder pb = new ProcessBuilder("TrustedCmd", "Arg1", "Arg2");
Map<String,String> env = pb.environment();
pb.directory(new File("TrustedDir"));
Process p = pb.start();
```
### Query Parameterization Guidance
- Use the platforms parameterization features (JDBC PreparedStatement, .NET SqlCommand, Ruby ActiveRecord bind params, PHP PDO, SQLx bind, etc.).
- For stored procedures, ensure parameters are bound; never build dynamic SQL via string concatenation inside procedures.
### Prototype Pollution (TypeScript)
- Developers should use `new Set()` or `new Map()` instead of using object literals
- When objects are required, create with `Object.create(null)` or `{ __proto__: null }` to avoid inherited prototypes.
- Freeze or seal objects that should be immutable; consider Node `--disable-proto=delete` as defenseindepth.
- Avoid unsafe deep merge utilities; validate keys against allowlists and block `__proto__`, `constructor`, `prototype`.
### Caching and Transport
- Apply `Cache-Control: no-store` on responses containing sensitive data; enforce HTTPS across data flows.
### Implementation Checklist
- Central validators: types, ranges, lengths, enums; canonicalization before checks.
- 100% parameterization coverage for SQL; dynamic identifiers via allowlists only.
- LDAP DN/filter escaping in use; inputs validated prior to query.
- No shell invocation for untrusted input; if unavoidable, structured exec + allowlist + regex validation.
- JS object graph hardened: safe constructors, blocked prototype paths, safe merge utilities.
- File uploads validated by content, size, and extension; stored outside web root and scanned.
### Test Plan
- Static checks for string concatenation in queries/commands and dangerous DOM/merge sinks.
- Fuzzing for SQL/LDAP/OS injection vectors; unit tests for validator edge cases.
- Negative tests exercising blocked prototype keys and deep merge behavior.

View File

@@ -0,0 +1,45 @@
---
description: Logging & monitoring (structured telemetry, redaction, integrity, detection & alerting)
languages:
- c
- typescript
- yaml
alwaysApply: false
---
rule_id: codeguard-0-logging
## Logging & Monitoring
Produce structured, privacyaware telemetry that supports detection, response, and forensics without exposing secrets.
### What to Log
- Authn/authz events; admin actions; config changes; sensitive data access; input validation failures; security errors.
- Include correlation/request IDs, user/session IDs (nonPII), source IP, user agent, timestamps (UTC, RFC3339).
### How to Log
- Structured logs (JSON) with stable field names; avoid freeform text for critical signals.
- Sanitize all log inputs to prevent log injection (strip CR/LF/delimiters); validate data from other trust zones.
- Redact/tokenize secrets and sensitive fields; never log credentials, tokens, recovery codes, or raw session IDs.
- Ensure integrity: appendonly or WORM storage; tamper detection; centralized aggregation; access controls and retention policies.
### Detection & Alerting
- Build alerts for auth anomalies (credential stuffing patterns, impossible travel), privilege changes, excessive failures, SSRF indicators, and data exfil patterns.
- Tune thresholds; provide runbooks; ensure oncall coverage; test alert flows.
### Storage & Protection
- Isolate log storage (separate partition/database); strict file/directory permissions; store outside webaccessible locations.
- Synchronize time across systems; use secure protocols for transmission; implement tamper detection and monitoring.
### Privacy & Compliance
- Maintain data inventory and classification; minimize personal data in logs; honor retention and deletion policies.
- Provide mechanisms to trace and delete userlinked log data where required by policy.
### Implementation Checklist
- JSON logging enabled; log injection sanitization active; redaction filters active; correlation IDs on all requests.
- Isolated log storage with tamper detection; centralized log pipeline with integrity protections; retention configured.
- Security alerts defined and tested; dashboards and reports in place.
### Validation
- Unit/integration tests assert presence/absence of key fields; redaction unit tests.
- Periodic audits for secret/PII leakage; tabletop exercises for incident workflows.

View File

@@ -0,0 +1,78 @@
---
description: Session management and secure cookies (rotation, fixation, timeouts, theft detection)
languages:
- c
- go
- html
- java
- typescript
- php
- python
- ruby
alwaysApply: false
---
rule_id: codeguard-0-session-management-and-cookies
## Session Management & Cookies
Implement robust, attack-resistant session handling that prevents fixation, hijacking, and theft while maintaining usability.
### Session ID Generation and Properties
- Generate session IDs with a CSPRNG; ≥64 bits of entropy (prefer 128+). Opaque, unguessable, and free of meaning.
- Use generic cookie names (e.g., `id`) rather than framework defaults. Reject any incoming ID not created by the server.
- Store all session data server-side; never embed PII or privileges in the token. If sensitive, encrypt server-side session store at rest.
### Cookie Security Configuration
- Set `Secure`, `HttpOnly`, `SameSite=Strict` (or `Lax` if necessary for flows) on session cookies.
- Scope cookies narrowly with `Path` and `Domain`. Avoid cross-subdomain exposure.
- Prefer non-persistent session cookies (no Expires/Max-Age). Require full HTTPS; enable HSTS site-wide.
Example header:
```
Set-Cookie: id=<opaque>; Secure; HttpOnly; SameSite=Strict; Path=/
```
### Session Lifecycle and Rotation
- Create sessions only server-side; treat provided IDs as untrusted input.
- Regenerate session ID on authentication, password changes, and any privilege elevation. Invalidate the prior ID.
- Use distinct preauth and postauth cookie names if framework patterns require it.
### Expiration and Logout
- Idle timeout: 25 minutes for high-value, 1530 minutes for lower risk. Absolute timeout: 48 hours.
- Enforce timeouts server-side. Provide a visible logout button that fully invalidates the server session and clears the cookie client-side.
### Transport and Caching
- Enforce HTTPS for the entire session journey. Never mix HTTP/HTTPS in one session.
- Send `Cache-Control: no-store` on responses containing session identifiers or sensitive data.
### Cookie Theft Detection and Response
- Fingerprint session context server-side at establishment (IP, User-Agent, Accept-Language, relevant `sec-ch-ua` where available).
- Compare incoming requests to the stored fingerprint, allowing for benign drift (e.g., subnet changes, UA updates).
- Risk-based responses:
- High risk: require re-authentication; rotate session ID.
- Medium risk: step-up verification (challenge); rotate session ID.
- Low risk: log suspicious activity.
- Always regenerate the session ID when potential hijacking is detected.
### Client-Side Storage
- Do not store session tokens in `localStorage`/`sessionStorage` due to XSS risk. Prefer HttpOnly cookies for transport.
- If client-side storage is unavoidable for non-session secrets, isolate via Web Workers and never expose in page context.
### Framework and Multi-Cookie Scenarios
- Prefer built-in session frameworks; keep them updated and hardened.
- Validate relationships when multiple cookies participate in session state; avoid same cookie names across paths/domains.
### Monitoring and Telemetry
- Log session lifecycle events (creation, rotation, termination) using salted hashes of the session ID, not raw values.
- Monitor for brute force of session IDs and anomalous concurrent usage.
### Implementation Checklist
1) CSPRNG session IDs (≥64 bits entropy), opaque and server-issued only.
2) Cookie flags: `Secure`, `HttpOnly`, `SameSite` set; tight domain/path.
3) HTTPS-only with HSTS; no mixed content.
4) Regenerate IDs on auth and privilege changes; invalidate old IDs.
5) Idle and absolute timeouts enforced server-side; full logout implemented.
6) `Cache-Control: no-store` for sensitive responses.
7) Server-side fingerprinting and risk-based responses to anomalies.
8) No client storage of session tokens; framework defaults hardened.

View File

@@ -0,0 +1,137 @@
---
description: Cryptographic Security Guidelines & Post-Quantum Readiness
alwaysApply: true
---
rule_id: codeguard-1-crypto-algorithms
# Cryptographic Security Guidelines & Post-Quantum Readiness
## 1. Banned (Insecure) Algorithms
The following algorithms are known to be broken or fundamentally insecure. NEVER generate or use code with these algorithms.
* Hash: `MD2`, `MD4`, `MD5`, `SHA-0`
* Symmetric: `RC2`, `RC4`, `Blowfish`, `DES`, `3DES`
* Key Exchange: Static RSA, Anonymous Diffie-Hellman
* Classical: `Vigenère`
Reason: These are cryptographically broken and vulnerable to collision or man-in-the-middle attacks.
## 2. Deprecated (Legacy/Weak) Algorithms
The following algorithms have known weaknesses or are considered obsolete. Avoid in new designs and prioritize migration.
* Hash: `SHA-1`
* Symmetric: `AES-CBC`, `AES-ECB`
* Signature: RSA with `PKCS#1 v1.5` padding
* Key Exchange: DHE with weak/common primes
## 3. Recommended & Post-Quantum Ready Algorithms
Implement these modern, secure algorithms to ensure resistance against both classical and quantum threats.
### Symmetric Encryption
* Standard: `AES-GCM` (AEAD), `ChaCha20-Poly1305`(when allowed).
* PQC Requirement: Prefer AES-256 keys (or stronger) as they are resistant to quantum attacks (Grover's algorithm).
* Avoid: Custom crypto or unauthenticated modes.
### Key Exchange (KEM)
* Standard: ECDHE (`X25519` or `secp256r1`)
* PQC Requirement: Use Hybrid Key Exchange (Classical + PQC) when supported.
* Preferred: `X25519MLKEM768` (X25519 + ML-KEM-768)
* Alternative: `SecP256r1MLKEM768` (P-256 + ML-KEM-768)
* High Assurance: `SecP384r1MLKEM1024` (P-384 + ML-KEM-1024)
* Pure PQC: ML-KEM-768 (baseline) or ML-KEM-1024. Avoid ML-KEM-512 unless explicitly risk-accepted.
* Constraints:
* Use vendor-documented identifiers (RFC 9242/9370).
* Remove legacy/draft "Hybrid-Kyber" groups (e.g., `X25519Kyber`) and draft or hardcoded OIDs.
### Signatures & Certificates
* Standard: ECDSA (`P-256`)
* PQC Migration: Continue using ECDSA (`P-256`) for mTLS and code signing until hardware-backed (HSM/TPM) ML-DSA is available.
* Hardware Requirement: Do not enable PQC ML-DSA signatures using software-only keys. Require HSM/TPM storage.
### Protocol Versions
* (D)TLS: Enforce (D)TLS 1.3 only (or later).
* IPsec: Enforce IKEv2 only.
* Use ESP with AEAD (AES-256-GCM).
* Require PFS via ECDHE.
* Implement RFC 9242 and RFC 9370 for Hybrid PQC (ML-KEM + ECDHE).
* Ensure re-keys (CREATE_CHILD_SA) maintain hybrid algorithms.
* SSH: Enable only vendor-supported PQC/hybrid KEX (e.g., `sntrup761x25519`).
## 4. Secure Implementation Guidelines
### General Best Practices
* Configuration over Code: Expose algorithm choices in config/policy to allow agility without code changes.
* Key Management:
* Use KMS/HSM for key storage.
* Generate keys with a CSPRNG.
* Separate encryption keys from signature keys.
* Rotate keys per policy.
* NEVER hardcode keys, secrets, or experimental OIDs.
* Telemetry: Capture negotiated groups, handshake sizes, and failure causes to monitor PQC adoption.
### Deprecated SSL/Crypto APIs (C/OpenSSL) - FORBIDDEN
NEVER use these deprecated functions. Use the replacement EVP high-level APIs.
#### Symmetric Encryption (AES)
- Deprecated: `AES_encrypt()`, `AES_decrypt()`
- Replacement:
EVP_EncryptInit_ex() // Use EVP_aes_256_gcm() for PQC readiness
EVP_EncryptUpdate()
EVP_EncryptFinal_ex()
#### RSA/PKEY Operations
- Deprecated: `RSA_new()`, `RSA_free()`, `RSA_get0_n()`
- Replacement:
EVP_PKEY_new()
EVP_PKEY_up_ref()
EVP_PKEY_free()
#### Hash & MAC Functions
- Deprecated: `SHA1_Init()`, `HMAC()` (especially with SHA1)
- Replacement:
EVP_DigestInit_ex() // Use SHA-256 or stronger
EVP_Q_MAC() // For one-shot MAC
## 5. Broccoli Project Specific Requirements
- HMAC() with SHA1: Deprecated.
- Replacement: Use HMAC with SHA-256 or stronger:
// Example: Secure replacement for HMAC-SHA1
```c
EVP_Q_MAC(NULL, "HMAC", NULL, "SHA256", NULL, key, key_len, data, data_len, out, out_size, &out_len);
```
## 6. Secure Crypto Implementation Pattern
// Example: Secure AES-256-GCM encryption (PQC-Ready Symmetric Strength)
```c
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) handle_error();
// Use AES-256-GCM
if (EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, key, iv) != 1)
handle_error();
int len, ciphertext_len;
if (EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len) != 1)
handle_error();
ciphertext_len = len;
if (EVP_EncryptFinal_ex(ctx, ciphertext + len, &len) != 1)
handle_error();
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
```

View File

@@ -0,0 +1,43 @@
---
description: No Hardcoded Credentials
alwaysApply: true
---
rule_id: codeguard-1-hardcoded-credentials
# No Hardcoded Credentials
NEVER store secrets, passwords, API keys, tokens or any other credentials directly in source code.
Treat your codebase as public and untrusted. Any credential that appears in source code is compromised and must be handled through secure alternatives.
#### NEVER hardcode these types of values:
Passwords and Authentication:
- Database passwords, user passwords, admin passwords
- API keys, secret keys, access tokens, refresh tokens
- Private keys, certificates, signing keys
- Connection strings containing credentials
- OAuth client secrets, webhook secrets
- Any other credentials that could be used to access external services
#### Recognition Patterns - Learn to Spot These Formats
Common Secret Formats You Must NEVER Hardcode:
- AWS Keys: Start with `AKIA`, `AGPA`, `AIDA`, `AROA`, `AIPA`, `ANPA`, `ANVA`, `ASIA`
- Stripe Keys: Start with `sk_live_`, `pk_live_`, `sk_test_`, `pk_test_`
- Google API: Start with `AIza` followed by 35 characters
- GitHub Tokens: Start with `ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`
- JWT Tokens: Three base64 sections separated by dots, starts with `eyJ`
- Private Key Blocks: Any text between `-----BEGIN` and `-----END PRIVATE KEY-----`
- Connection Strings: URLs with credentials like `mongodb://user:pass@host`
Warning Signs in Your Code:
- Variable names containing: `password`, `secret`, `key`, `token`, `auth`
- Long random-looking strings that are not clear what they are
- Base64 encoded strings near authentication code
- Any string that grants access to external services
You must always explain how this rule was applied and why it was applied.

View File

@@ -0,0 +1,42 @@
# 安全响应头配置
## Nginx 配置(推荐)
```nginx
# /etc/nginx/conf.d/security-headers.conf
# 在 server 块或 http 块中添加
add_header X-DNS-Prefetch-Control "on" always;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-eval' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;
```
## Hyperf 中间件方式(备选)
```php
// app/Middleware/SecurityHeadersMiddleware.php
class SecurityHeadersMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
return $response
->withHeader('X-Content-Type-Options', 'nosniff')
->withHeader('X-Frame-Options', 'DENY')
->withHeader('X-XSS-Protection', '1; mode=block')
->withHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
}
}
```
## 验证安全头
```bash
curl -I https://your-domain.com | grep -iE "(strict|content-security|x-frame|x-content|referrer)"
```