Updated skills

This commit is contained in:
Anon 2026-06-25 23:02:43 +02:00
parent c23a71c489
commit 3c452dfcc5
29 changed files with 3208 additions and 1550 deletions

View file

@ -0,0 +1,145 @@
---
name: dotnet-security-review
description: >-
Performs a systematic C#/ASP.NET Core security code review on .NET 8 (C# 12)
and .NET 10 (C# 14) codebases. Covers OWASP Top 10, authentication/authorization
audit, input validation, cryptography, dependency vulnerabilities, security
headers, middleware pipeline, and CI/CD security posture.
metadata:
platform: ".NET 8 and .NET 10 (no .NET 9 projects in scope)"
---
# Security Code Review for C# / ASP.NET Core (.NET 8 + .NET 10)
You are a security auditor performing a thorough, evidence-based code review. Every finding MUST include file path, line number, severity, impact, and a concrete fix.
## Step 0 — Detect the target framework
Before scoring findings, follow `../../references/detect-target-framework.md`. The security guidance below applies to **both** .NET 8 and .NET 10 unless explicitly marked. A few items are .NET 10-only — when reviewing a .NET 8 project, don't recommend them as "fixes":
- **ASP.NET Core Identity passkeys** (`AddPasskeys()`) — .NET 10 only. On .NET 8, recommend external IdP / `Fido2NetLib` or password+TOTP.
- **Minimal-API built-in validation** (`AddValidation()`) — .NET 10 only. On .NET 8, FluentValidation + `IEndpointFilter` is the safe equivalent.
- **First-party `Microsoft.AspNetCore.OpenApi`** — .NET 9+ only. On .NET 8 the project should use `Swashbuckle.AspNetCore`; flag missing OpenAPI security schemes accordingly.
- **`HybridCache`** — .NET 9+ only. On .NET 8 verify `IDistributedCache` configurations (encryption-at-rest, key prefixing, TLS to Redis) directly.
- The C# 14 `field` keyword, `extension(...)` blocks, null-conditional assignment, and partial constructors **do not compile on net8.0** — never propose security fixes that introduce them on a .NET 8 project.
All cryptography, JWT, authorization-policy, header, and middleware guidance applies identically on both targets.
## Target Selection
The user's arguments are in `$ARGUMENTS`.
- If `$ARGUMENTS` contains a file path or directory, review that target.
- If `$ARGUMENTS` is "all", review the entire codebase starting from the solution root.
- If `$ARGUMENTS` is empty, run `git diff --name-only HEAD~5` to find recently changed `.cs` files. If none, ask the user what to review.
When reviewing a directory or "all", use Glob to find `**/*.cs` files, then prioritize:
1. Controllers, filters, middleware (`*Controller.cs`, `*Filter.cs`, `Program.cs`)
2. Auth handlers and delegating handlers (`*Handler.cs`, `*DelegatingHandler.cs`)
3. Service implementations handling external input or secrets
4. Repository and data access code
5. Configuration and DI registration (`*Extensions.cs`, `*Options.cs`)
6. Validators
## Review Process
Execute each phase sequentially. Use the Read tool for files and the Grep tool for pattern searches. NEVER use bash `grep` or `rg` -- always use the Grep tool.
### Phase 1: Automated Pattern Scanning
Read `references/scanning-patterns.md` for the full pattern catalog. Run all Grep searches in parallel across `.cs` files in the target scope. Each pattern targets a specific vulnerability class: injection, deserialization, cryptography, async anti-patterns, data exposure, SSRF, missing controls, ReDoS, log injection, open redirect, cookie security, file upload, claims safety, and thread safety.
### Phase 2: File-by-File Deep Review
Read `references/deep-review-categories.md` for the complete checklist (Categories A through L). For each file in scope (or top ~20 most security-relevant files when reviewing "all"), check all applicable categories:
- **A**: Authentication & Authorization (JWT validation, auth schemes, IDOR)
- **B**: Input Validation
- **C**: Error Handling & Information Leakage
- **D**: Cryptography & Secrets
- **E**: Data Protection & PII
- **F**: Concurrency & State Safety
- **G**: CancellationToken Propagation
- **H**: HTTP Client Security (resilience handlers, DNS refresh)
- **I**: Configuration Security
- **J**: Logging & Monitoring Security
- **K**: Output Encoding & Response Security
- **L**: Supply Chain & Build Security
### Phase 3: Architecture & Project-Specific Checks
Read `references/architecture-checks.md` for checks tailored to common ASP.NET Core project patterns. These cover endpoint authorization verification, anonymous endpoint abuse potential, OTP/MFA security, exception handling coverage, optimistic concurrency, state expiry, blob storage SAS security, message queue security, JSON serialization settings, background task queue safety, rate limiting, security headers, middleware ordering, and NuGet audit configuration.
Read the project's CLAUDE.md or AGENTS.md for project-specific architecture details to inform these checks.
### Phase 4: Dependency Vulnerability Check
Read `references/dependencies-and-headers.md` (Phase 4 section) for dependency scanning patterns. Check `.csproj` files for known-vulnerable versions and NuGet audit configuration.
### Phase 5: Security Headers & Middleware Pipeline
Read `references/dependencies-and-headers.md` (Phase 5 section) for the 14-item headers checklist and middleware ordering verification.
## Output Format
### Security Review Report
**Scope:** [files/directories reviewed]
**Date:** [current date]
**Risk Summary:** [X CRITICAL, Y HIGH, Z MEDIUM, W LOW, V INFO]
#### Findings
For each finding:
**[SEVERITY] [SHORT-TITLE]**
- **Location:** `file/path.cs:LINE`
- **Category:** [OWASP category or security domain]
- **Description:** [What the vulnerability is and why it matters]
- **Impact:** [What an attacker could achieve]
- **Recommendation:** [Specific fix with code example]
#### Summary Table
| # | Severity | Category | File | Description |
|---|----------|----------|------|-------------|
| 1 | CRITICAL | ... | ... | ... |
#### Recommendations
1. Immediate fixes (CRITICAL/HIGH)
2. Short-term improvements (MEDIUM)
3. Long-term hardening (LOW/INFO)
4. Tooling recommendations (NuGet audit, SAST integration, etc.)
## Severity
Use standard severity: CRITICAL > HIGH > MEDIUM > LOW > INFO. CRITICAL = actively exploitable, HIGH = significant with effort, MEDIUM = increased attack surface, LOW = minor improvement, INFO = hardening suggestion.
## Anti-Rationalization Table
| Rationalization | Reality |
|---|---|
| "This is just a test file" | Test code handling secrets or auth IS production-relevant. Report as INFO. |
| "Probably a false positive" | ALWAYS read surrounding code before dismissing. If you cannot prove it safe, report it. |
| "The framework handles this" | Verify the protection is actually enabled and configured. Defaults can be overridden. |
| "Internal API, not public-facing" | Internal APIs are attacked via SSRF, supply chain, lateral movement. |
| "No one would exploit this" | Threat models change. Report it; let the team decide risk acceptance. |
## Red Flags
STOP and investigate deeper if you encounter any of these:
- Any endpoint without an explicit auth attribute (`[Authorize]` or `[AllowAnonymous]`)
- Any `catch` block returning raw exception data to the client
- Any hardcoded key, token, password, or connection string literal
- Any `new HttpClient()` (should use `IHttpClientFactory`)
- Any `TypeNameHandling` value other than `None`
## Important Guidelines
1. Only report real findings with evidence (file path and line number). Do not speculate.
2. If a pattern search returns no results, note "No issues found" and move on.
3. For false positives (e.g., `System.Random` in tests, not production), note as INFO with explanation.
4. Prioritize production code over test code.
5. When reviewing "all", cap the report at the 30 most significant findings.
6. ALWAYS verify context before reporting -- a pattern match alone is not a finding. Read the surrounding code.

View file

@ -0,0 +1,134 @@
# Architecture & Project-Specific Checks Reference
# Phase 3 checks for common ASP.NET Core project patterns. Read the project's CLAUDE.md
# or AGENTS.md for project-specific details (endpoint list, service names, DI registrations)
# to inform these checks.
## Check 1: Endpoint Auth Matrix Verification
Cross-reference the controller's actual `[Authorize]`/`[AllowAnonymous]` attributes against the project's documented auth requirements. Read CLAUDE.md or AGENTS.md for the expected auth matrix. Any mismatch is CRITICAL.
For projects with multiple auth schemes (e.g., Azure AD + custom JWT), verify each endpoint uses the correct scheme/policy.
## Check 2: Anonymous Endpoint Abuse Potential
For each `[AllowAnonymous]` endpoint, verify:
- Rate limiting or throttling exists for sensitive operations (e.g., code generation, login attempts)
- Enumeration attacks are mitigated (IDs are GUIDs or non-sequential, not auto-increment)
- No state modification without prior authentication or verification (e.g., OTP first)
## Check 3: OTP / MFA Security Review
If the project implements OTP or MFA, read the service implementation and verify:
- Code length is sufficient (6+ characters)
- Codes are generated with `RandomNumberGenerator`
- Hash is SHA-256 or stronger (not MD5/SHA1)
- Expiry is enforced (typically 5-10 minutes)
- Wrong attempt counter increments correctly and triggers lockout after a threshold
- No timing side-channel in hash comparison
## Check 4: Exception Handling Coverage
Grep for `throw new` statements. Verify that all thrown exceptions are either:
- The project's structured error type (e.g., `ApiException`, `DomainException`, or the project's custom base exception), OR
- Known typed exceptions for external service failures
Any unstructured exception thrown from handler/service code may bypass error filters and leak internal details.
## Check 5: Optimistic Concurrency on State Writes
If using a database with optimistic concurrency (ETags, row versions):
- Verify every write/update operation passes the concurrency token
- Verify the concurrency token store/tracking mechanism is consulted on every read/write cycle
## Check 6: Expired State Handling
If the project uses application-level state expiry (not DB TTL):
- Verify expired records are deleted or excluded on read (not returned to callers)
- Verify callers cannot act on expired data
## Check 7: Blob Storage SAS URL Security
If the project generates SAS URLs for blob storage:
- SAS token expiry is short-lived (minutes, not days)
- Permission is read-only (not write/delete)
- Scoped to the specific blob (not container-level)
## Check 8: Message Queue Security
If the project uses message queues (Service Bus, RabbitMQ, etc.):
- Messages do not contain secrets or unnecessary PII
- Queue connections use managed identity or connection strings from secret stores
## Check 9: JSON Serialization Settings
Check that `TypeNameHandling` is set to `None` (default) and not `Auto`/`All` anywhere. This applies to both Newtonsoft.Json and any custom serializer configuration.
## Check 10: Background Task Queue Safety
If the project uses a background task queue:
- Bounded capacity prevents unbounded memory growth
- Backpressure is handled correctly (not silently dropping critical events like audit logs)
- Task failures are observed and logged/metered
## Check 11: Custom Token / JWT Security
If the project issues its own JWTs (not just validating external tokens):
- **Algorithm**: HMAC-SHA256 or stronger (RSA for distributed validation)
- **Signing key source**: Key loaded from configuration/secret store, NOT hardcoded
- **Signing key length**: Minimum 256 bits (32 bytes) for HMAC-SHA256
- **Token expiry**: Appropriately capped (tokens should not outlive the session/resource they protect)
- **Claims validation**: Custom claims (e.g., resource IDs) are validated against route parameters by an authorization handler
- **TokenValidationParameters**: `ValidateIssuer`, `ValidateAudience`, `ValidateLifetime`, `ValidateIssuerSigningKey` all `true`
- **ClockSkew**: Tightened from default 5 minutes to 2 minutes or less
## Check 12: Response Data Sanitization
If the project sanitizes response data (e.g., stripping internal paths or fields):
- Sanitization handles malformed input gracefully (does not throw/crash)
- Only known sensitive fields are stripped (no over-stripping that breaks functionality)
- Sanitization is applied on every code path returning the data (not just the happy path)
## Check 13: Rate Limiting
Verify rate limiting posture:
- Grep for `AddRateLimiter` and `UseRateLimiter` -- if absent, note as finding
- Application-level throttling exists for sensitive operations (e.g., SMS/code generation resend limits)
- Brute force protection exists for verification endpoints (wrong attempt lockout)
- **Recommendation**: Add ASP.NET Core `System.Threading.RateLimiting` middleware for IP-based throttling on public endpoints
## Check 14: Security Headers Completeness
Check Program.cs / middleware for these headers (report missing ones):
- `X-Content-Type-Options: nosniff`
- `X-Frame-Options: DENY`
- `Referrer-Policy: strict-origin-when-cross-origin`
- `Permissions-Policy: camera=(), microphone=(), geolocation=()`
- `X-XSS-Protection: 0` (disable legacy XSS filter; CSP is the modern replacement)
- `Content-Security-Policy` (at minimum for APIs: `default-src 'none'`)
- `Server` header removed
- `X-Powered-By` header removed
## Check 15: Middleware Pipeline Ordering
Read Program.cs and verify correct middleware order:
1. `UseExceptionHandler` (outermost -- catches everything)
2. `UseHsts` (non-development only)
3. `UseHttpsRedirection`
4. Security headers middleware
5. `UseRateLimiter` (if present)
6. `UseRouting` (if explicit)
7. `UseCors`
8. `UseAuthentication`
9. `UseAuthorization`
10. `MapControllers` / endpoints
Authentication MUST come before Authorization. CORS MUST come before Authentication. ExceptionHandler MUST be first.
## Check 16: NuGet Audit & Build Security
Check for build-level security configuration:
- Does `Directory.Build.props` exist? If so, verify `NuGetAudit`, `NuGetAuditMode`, `NuGetAuditLevel` settings.
- Are Roslyn security analyzer packages referenced? (`SecurityCodeScan.VS2019`, `SonarAnalyzer.CSharp`, `Meziantou.Analyzer`)
- Are `AnalysisLevel` / `AnalysisMode` set in `.csproj` or `Directory.Build.props`?
- Run Grep for floating versions: `Version="[^"]*\*"` in `.csproj` files
- Recommend `dotnet list package --vulnerable --include-transitive` as a CI step

View file

@ -0,0 +1,107 @@
# Deep Review Categories Reference
# File-by-file review checklist for Phase 2. For each file in scope (or top ~20 most
# security-relevant files when reviewing "all"), read the file and check each applicable category.
## Category A: Authentication & Authorization
1. Every controller action has either `[Authorize]` (class or method level) or `[AllowAnonymous]` explicitly.
2. No IDOR: when accessing resources by ID, verify the handler checks that the caller owns or is authorized to access that resource.
3. JWT validation settings are strict: issuer, audience, lifetime, algorithm all validated.
4. Token acquisition uses correct flow: app tokens for backend-to-backend, OBO only where user context is needed.
5. No `[AllowAnonymous]` on endpoints that modify sensitive state without alternative authentication (e.g., OTP verification first).
6. **Multiple auth scheme verification**: If the project uses multiple auth schemes (e.g., Azure AD + custom JWT), verify correct scheme is applied per endpoint. No scheme confusion between internal and client-facing endpoints.
7. **JWT `alg:none` rejection**: Verify `TokenValidationParameters` does NOT allow `alg:none`. All schemes must validate the signing algorithm (`ValidateIssuerSigningKey = true`).
8. **HMAC signing key minimum length**: If using HMAC-SHA256 for JWT signing, the key must be at least 256 bits (32 bytes). Check options validation.
9. **Structured error responses on auth failure**: `OnChallenge` (401) and `OnForbidden` (403) events should return structured JSON error responses, not default HTML/empty responses.
## Category B: Input Validation
1. All DTOs accepted by handlers have corresponding FluentValidation validators registered.
2. Route parameters are validated for format before use (e.g., GUID format, positive integers).
3. File uploads are validated for content type, size, and extension (not just extension).
4. No unvalidated user input flows into file paths, URLs, SQL, commands, or log messages.
5. Phone numbers, emails, and other PII are validated and normalized before processing.
## Category C: Error Handling & Information Leakage
1. All expected errors use a structured error type -- never return raw exception details to clients.
2. Exception filters catch known exception types and return only safe error payloads.
3. Unknown exceptions are wrapped as generic 500 errors without stack traces or internal details.
4. Error messages returned to clients do not reveal internal architecture, database schema, or file paths.
5. Catch blocks never silently swallow exceptions -- they must log or rethrow.
## Category D: Cryptography & Secrets
1. OTP/MFA codes use `RandomNumberGenerator` (not `System.Random`).
2. Hash comparison uses constant-time comparison to prevent timing attacks.
3. Hash storage uses a secure algorithm (SHA-256 minimum; bcrypt/Argon2 for passwords).
4. No secrets, connection strings, or API keys appear in source code or `appsettings.json` committed to git.
5. Options validation (`ValidateOnStart()`) is configured to reject placeholder secrets in production.
## Category E: Data Protection & PII
1. Sensitive fields (phone numbers, etc.) are masked before returning to unauthenticated callers.
2. PII (names, addresses, phone numbers, emails) is not logged in full -- use masking.
3. Sensitive internal fields (hash values, internal IDs) are excluded from API responses.
4. Blob/file storage SAS URLs have appropriate expiry times and permissions (read-only, short-lived).
5. Audit logs do not contain raw PII that violates data protection requirements.
## Category F: Concurrency & State Safety
1. Database state mutations use optimistic concurrency (ETags, row versions, or equivalent).
2. Concurrency exceptions are caught and retried appropriately in handlers.
3. Multi-step validation flows (OTP, MFA) handle concurrent attempts correctly.
4. Counter increments (e.g., wrong attempt counts) are atomic or protected against race conditions.
5. Scheduled/delayed operations do not race with in-progress workflows.
## Category G: CancellationToken Propagation
1. Every `async` method in the call chain accepts `CancellationToken cancellationToken = default`.
2. The token is passed to every awaited call: HTTP calls, DB queries, blob operations, queue sends.
3. The controller passes `HttpContext.RequestAborted` to handlers.
4. Missing propagation is a DoS vector (abandoned requests hold resources).
## Category H: HTTP Client Security
1. HttpClient instances have timeouts configured (not infinite).
2. Delegating handlers do not log tokens or authorization headers.
3. SSL/TLS validation is not disabled (`ServerCertificateCustomValidationCallback` returning true).
4. Retry policies do not retry on authentication failures (401/403).
5. External API clients have adequate timeout and error handling even without resilience middleware.
6. **Standard resilience handler**: Verify `AddStandardResilienceHandler()` or equivalent resilience pipeline is configured on named HttpClients.
7. **Retry-After header respect**: Retry policies should honor `Retry-After` headers from downstream APIs to avoid cascading failures.
8. **DNS refresh**: Verify `SocketsHttpHandler.PooledConnectionLifetime` is set (recommended 2-5 min) to handle DNS changes.
## Category I: Configuration Security
1. CORS policy does not use `AllowAnyOrigin()` in production.
2. Swagger UI is disabled in production (or restricted to authorized users).
3. Health check endpoints do not expose sensitive information.
4. `X-Powered-By` and `Server` headers are removed.
5. HTTPS redirection and HSTS are configured for production.
## Category J: Logging & Monitoring Security
1. Authentication events are logged (both success and failure) for audit trail.
2. Authorization failures are logged with sufficient context (user, endpoint, reason).
3. Input validation failures are logged (not just returned as 400 responses).
4. Structured logging used throughout -- no string interpolation in log method calls (use message templates).
5. Sensitive data (passwords, tokens, PII, hash values) is NEVER logged at any log level.
6. Correlation IDs are included in all error log entries for traceability.
7. Log output is not accessible to API clients (no endpoint returns log data).
## Category K: Output Encoding & Response Security
1. No internal file paths, class names, or assembly names leak in API responses (check error messages, headers).
2. Razor templates are verified for `@Html.Raw()` usage -- must be justified and input-sanitized.
3. `TypeNameHandling.None` verified for Newtonsoft.Json serialization (prevents type injection).
4. `Content-Type` headers are explicitly set on all responses (no browser MIME-sniffing).
5. Response sanitization logic handles malformed input gracefully (no crashes on invalid JSON/data).
## Category L: Supply Chain & Build Security
1. `Directory.Build.props` exists with NuGet audit settings (`NuGetAudit`, `NuGetAuditMode`, `NuGetAuditLevel`).
2. Package versions are pinned (no floating versions like `Version="1.*"`).
3. `AnalysisLevel` and `AnalysisMode` are set to `latest-Recommended` / `Recommended` in build configuration.
4. Security analyzers included in packages (SecurityCodeScan, SonarAnalyzer.CSharp, or Meziantou.Analyzer).
5. No known-vulnerable version ranges in `.csproj` files (check Newtonsoft.Json >= 13.0.1, Microsoft.Identity.Web >= 2.x, System.Text.Json >= 8.0.5).

View file

@ -0,0 +1,92 @@
# Dependencies & Headers Reference
# Combined Phase 4 (dependency vulnerability checks) and Phase 5 (headers/middleware) content.
## Phase 4: Dependency Vulnerability Check
### Automated Grep Checks
Run these Grep patterns against `.csproj` files to detect known-vulnerable version ranges:
| Pattern | Risk |
|---------|------|
| `Newtonsoft\.Json.*Version="([0-9]+)` where major < 13 | CVEs in Newtonsoft.Json < 13.0.1 |
| `Newtonsoft\.Json.*Version="13\.0\.0"` | Pre-patch 13.x |
| `Microsoft\.Identity\.Web.*Version="1\."` | CVEs in Microsoft.Identity.Web < 2.x |
| `System\.Text\.Json.*Version="[0-7]\.\|Version="8\.0\.[0-4]"` | CVEs in System.Text.Json < 8.0.5 |
| `Version="[^"]*\*"` | Floating versions (unpinned, supply chain risk) |
### NuGet Audit Configuration Check
Grep `Directory.Build.props` and `.csproj` files for:
- `<NuGetAudit>true</NuGetAudit>` -- should be present
- `<NuGetAuditMode>all</NuGetAuditMode>` -- audits transitive dependencies
- `<NuGetAuditLevel>low</NuGetAuditLevel>` -- catches all severity levels
- `<WarningsAsErrors>` containing `NU1903;NU1904` -- fails build on high/critical vulnerabilities
### ReDoS in Validators
Check all `Regex` and `.Matches()` calls in validators:
- Pattern: `new Regex\((?!.*RegexOptions\.NonBacktracking)` -- missing NonBacktracking flag (.NET 7+)
- Check for nested quantifiers: `(a+)+`, `(a*)*`, `(a|a)*` patterns
### Command Recommendation
Include in report output (do NOT run automatically):
```bash
dotnet list package --vulnerable --include-transitive
```
## Phase 5: Security Headers & Middleware Pipeline
### Headers Checklist (14 items)
Read `Program.cs` and any middleware configuration files. Check for each header:
| # | Header / Control | Expected Value | Severity if Missing |
|---|-----------------|----------------|---------------------|
| 1 | `X-Content-Type-Options` | `nosniff` | MEDIUM |
| 2 | `X-Frame-Options` | `DENY` | MEDIUM |
| 3 | `Referrer-Policy` | `strict-origin-when-cross-origin` | LOW |
| 4 | `Permissions-Policy` | `camera=(), microphone=(), geolocation=()` | LOW |
| 5 | `X-XSS-Protection` | `0` (disable legacy filter; CSP replaces it) | LOW |
| 6 | `Content-Security-Policy` | At minimum `default-src 'none'` for APIs | MEDIUM |
| 7 | `Server` header | REMOVED | LOW |
| 8 | `X-Powered-By` header | REMOVED | LOW |
| 9 | `Strict-Transport-Security` | `max-age=31536000; includeSubDomains; preload` | HIGH |
| 10 | `Cache-Control` | `no-store` on sensitive data endpoints | MEDIUM |
| 11 | HTTPS Redirection | `app.UseHttpsRedirection()` present | HIGH |
| 12 | HSTS | `app.UseHsts()` in non-development | HIGH |
| 13 | Rate Limiting | `app.UseRateLimiter()` present | MEDIUM |
| 14 | Swagger restricted | Conditionally enabled (dev/staging only) | MEDIUM |
### Middleware Pipeline Ordering
The correct order for ASP.NET Core middleware is critical. Misordering can bypass security controls.
**Expected order:**
```
1. app.UseExceptionHandler(...) // Outermost: catches all unhandled exceptions
2. app.UseHsts() // HSTS (non-development only)
3. app.UseHttpsRedirection() // Force HTTPS
4. Security headers middleware // Custom: X-Content-Type-Options, etc.
5. app.UseRateLimiter() // Throttle before routing (if present)
6. app.UseRouting() // (implicit in .NET 8+ with MapControllers)
7. app.UseCors(...) // CORS before auth (preflight must not require auth)
8. app.UseAuthentication() // Identify the caller
9. app.UseAuthorization() // Enforce access rules
10. app.MapControllers() // Endpoint dispatch
```
**Critical ordering rules:**
- `UseExceptionHandler` MUST be first -- otherwise exceptions in early middleware are unhandled
- `UseAuthentication` MUST come before `UseAuthorization` -- otherwise auth policies have no identity to check
- `UseCors` MUST come before `UseAuthentication` -- otherwise CORS preflight (OPTIONS) requests fail with 401
- `UseRateLimiter` SHOULD come before `UseRouting` -- otherwise rate limits apply after route matching overhead
- `UseHsts` and `UseHttpsRedirection` SHOULD come early -- before any response body is written
### Middleware Verification Procedure
1. Read `Program.cs` from the `var app = builder.Build()` line to `app.Run()`
2. List every `app.Use*` and `app.Map*` call in order
3. Compare against expected order above
4. Report any misordering as MEDIUM severity

View file

@ -0,0 +1,116 @@
# Scanning Patterns Reference
# Automated Grep patterns organized by vulnerability class for Phase 1 scanning.
# Run all searches in parallel across .cs files in the target scope.
## Injection Vulnerabilities
| ID | Pattern | Target |
|----|---------|--------|
| INJ-1 | `\$".*SELECT\|INSERT\|UPDATE\|DELETE\|DROP\|EXEC` | SQL injection via string interpolation |
| INJ-2 | `string\.Format.*SELECT\|INSERT\|UPDATE\|DELETE` | SQL injection via string.Format |
| INJ-3 | `\.FromSqlRaw\(.*\$"\|\.FromSqlRaw\(.*string\.Format` | EF Core raw SQL injection |
| INJ-4 | `ExecuteSqlRaw\(.*\$"\|ExecuteSqlRaw\(.*string\.Format` | EF Core command injection |
| INJ-5 | `Process\.Start\|ProcessStartInfo` | Command injection |
| INJ-6 | `DirectorySearcher\|LdapConnection` | LDAP injection (check for string concat) |
| INJ-7 | `XmlDocument\|XmlReader\|XDocument` | XXE (verify secure settings) |
| INJ-8 | `Path\.Combine.*Request\|Path\.Combine.*user\|\.\.\/\|\.\.\\` | Path traversal |
## Insecure Deserialization
| ID | Pattern | Target |
|----|---------|--------|
| DES-1 | `BinaryFormatter\|SoapFormatter\|ObjectStateFormatter\|LosFormatter\|NetDataContractSerializer` | Banned deserializers |
| DES-2 | `JsonConvert\.DeserializeObject.*TypeNameHandling` | Newtonsoft type handling |
| DES-3 | `TypeNameHandling\s*=\s*TypeNameHandling\.(All\|Auto\|Objects\|Arrays)` | Unsafe type handling |
## Cryptography Weaknesses
| ID | Pattern | Target |
|----|---------|--------|
| CRY-1 | `new Random\(\)\|System\.Random` | Insecure randomness (should be RandomNumberGenerator) |
| CRY-2 | `MD5\.Create\|SHA1\.Create\|DESCryptoServiceProvider\|RC2CryptoServiceProvider\|TripleDES` | Weak algorithms |
| CRY-3 | `ECB` | Insecure cipher mode |
| CRY-4 | `password\|secret\|key\|token\|credential\|apikey\|connectionstring` in string literals | Hardcoded secrets |
## Async Anti-Patterns
| ID | Pattern | Target |
|----|---------|--------|
| ASY-1 | `\.Result[^s]\|\.Result$` | Sync-over-async deadlock risk |
| ASY-2 | `\.Wait\(\)` | Sync-over-async deadlock risk |
| ASY-3 | `\.GetAwaiter\(\)\.GetResult\(\)` | Sync-over-async |
| ASY-4 | `Task\.Run\(` | Thread pool abuse in ASP.NET context |
## Sensitive Data Exposure
| ID | Pattern | Target |
|----|---------|--------|
| EXP-1 | `_logger\.Log.*password\|_logger\.Log.*secret\|_logger\.Log.*token\|_logger\.Log.*apiKey` (case insensitive) | Logging secrets |
| EXP-2 | `Console\.Write.*password\|Console\.Write.*secret\|Console\.Write.*token` | Console output of secrets |
| EXP-3 | `Html\.Raw\(` | XSS via unencoded HTML |
| EXP-4 | `Exception\.ToString\(\)\|Exception\.StackTrace\|Exception\.Message` returned in HTTP responses | Stack trace leakage |
## SSRF Risks
| ID | Pattern | Target |
|----|---------|--------|
| SSRF-1 | `new HttpClient\(\).*\+\|HttpClient.*GetAsync\(.*\+\|HttpClient.*PostAsync\(.*\+` | User-controlled URLs |
| SSRF-2 | `new Uri\(.*Request\|new Uri\(.*user\|new Uri\(.*input` | Unvalidated URI construction |
| SSRF-3 | `HttpClient.*GetAsync\(.*[^"]\)\|HttpClient.*PostAsync\(.*[^"]\)` | Non-literal URLs in HTTP calls |
| SSRF-4 | `new Uri\([^"]*\)` | Dynamic URI construction |
| SSRF-5 | `IPAddress\.Parse\("\|Uri\("http` | Hardcoded IPs/URLs |
## Missing Security Controls
| ID | Pattern | Target |
|----|---------|--------|
| CTL-1 | `\[HttpPost\]\|\[HttpPut\]\|\[HttpDelete\]\|\[HttpPatch\]` | Unannotated endpoints (check for nearby [Authorize]/[AllowAnonymous]) |
| CTL-2 | `AllowAnyOrigin` | CORS misconfiguration |
| CTL-3 | `app\.UseDeveloperExceptionPage` | Dev error page in production |
| CTL-4 | `#pragma warning disable` | Disabled security warnings |
## ReDoS
| ID | Pattern | Target |
|----|---------|--------|
| REG-1 | `new Regex\((?!.*RegexOptions\.NonBacktracking)` | Regex without NonBacktracking (ReDoS risk in .NET 7+) |
## Log Injection
| ID | Pattern | Target |
|----|---------|--------|
| LOG-1 | `_logger\.Log.*(Request\.Query\|Request\.Form\|Request\.Headers\|Request\.Body)` | Unsanitized request data in logs |
| LOG-2 | `_logger\.Log.*\\n\|_logger\.Log.*\\r` | Newline chars in log messages (log forging) |
## Open Redirect
| ID | Pattern | Target |
|----|---------|--------|
| RED-1 | `Redirect\(\|RedirectToAction\(.*\+` | Open redirect via concatenation |
| RED-2 | `Response\.Redirect\(` | Direct response redirect |
## Cookie Security
| ID | Pattern | Target |
|----|---------|--------|
| COK-1 | `CookieOptions\|\.Cookies\.Append` | Cookie usage (verify HttpOnly, Secure, SameSite) |
| COK-2 | `SameSite\s*=\s*SameSiteMode\.None` | SameSite=None (requires Secure flag) |
## File Upload
| ID | Pattern | Target |
|----|---------|--------|
| UPL-1 | `IFormFile` | File upload handling (verify validation) |
| UPL-2 | `ContentType.*application/octet-stream\|ContentType.*\*\/\*` | Permissive content type acceptance |
## Claims Safety
| ID | Pattern | Target |
|----|---------|--------|
| CLM-1 | `User\.Claims\.First\(\|User\.FindFirst\(.*\.Value(?!\?)` | Null-unsafe claims access (missing ?.) |
## Thread Safety
| ID | Pattern | Target |
|----|---------|--------|
| THR-1 | `static\s+.*HttpClient\s+\w+\s*=\s*new\s+HttpClient` | Static HttpClient instantiation (use IHttpClientFactory) |