Scope: This is a comprehensive security standard that MUST be followed when developing, reviewing, or modifying any code. It applies to all languages, frameworks, and platforms. Compliance is mandatory — not optional.
Golden Rule: Never execute the code (
dotnet build,npm run dev, etc.). Only write code; the owner runs it on the appropriate server.
| Category | Approved | Banned |
|---|---|---|
| Symmetric | AES-GCM, ChaCha20-Poly1305 | ECB, DES, 3DES, RC2, RC4, Blowfish |
| Asymmetric | RSA ≥2048, ECC (Curve25519, Ed25519, P-256+) | RSA <2048, static RSA key exchange |
| Hashing | SHA-256, SHA-384, SHA-512 | MD2, MD4, MD5, SHA-0, SHA-1 |
| Password Hashing | Argon2id, scrypt, bcrypt (cost≥10), PBKDF2-HMAC-SHA-256 | MD5, SHA-1, plain SHA-256 (unsalted) |
| RNG | CSPRNG only (SecureRandom, crypto.randomBytes, secrets) | Math.random, System.Random, rand() |
| Key Exchange | ECDHE, DHE with validated groups | Anonymous DH, static RSA |
- Generate keys in validated modules (HSM/KMS). Never from passwords or predictable inputs.
- Separate keys by purpose (encryption vs. signing vs. wrapping).
- Store in KMS/HSM/vault. NEVER hardcode. Avoid plain environment variables.
- Use KEK to wrap DEKs. Store separately. Rotate on compromise or policy.
- Audit all key access and operations.
- Encrypt sensitive data; minimize stored secrets; tokenize where possible.
- Use authenticated encryption (AEAD). Manage nonces/IVs properly; keep salts unique per item.
- Protect backups: encrypt, restrict access, test restores, manage retention.
- TLS 1.3 preferred. Allow TLS 1.2 only for legacy. Disable TLS 1.0/1.1 and SSL.
- Prefer AEAD cipher suites. Disable NULL/EXPORT/anon.
- Certificates: 2048-bit+ keys, SHA-256, correct CN/SAN.
- HTTPS site-wide. Redirect HTTP→HTTPS. Prevent mixed content. Set cookies
Secure.
- Send
Strict-Transport-Securityonly over HTTPS. - Test:
max-age=86400withincludeSubDomains. - Production:
max-age=31536000(≥1 year) withincludeSubDomains. - Consider
preloadonce stable.
- Accept passphrases and full Unicode. Minimum 8 characters. Reasonable maximum (64+).
- Check against breach corpora (k-anonymity APIs). Reject common/breached passwords.
- Hash with Argon2id (preferred), scrypt, bcrypt, or PBKDF2. NEVER encrypt passwords.
- Use unique per-user salts. Constant-time comparison.
- Enforce TLS for all auth endpoints.
- Generic error messages: "Invalid username or password" (prevent enumeration).
- Implement rate limits per IP, account, and globally.
- Progressive backoff for lockouts; avoid permanent lockout.
- Phishing-resistant factors preferred: WebAuthn/Passkeys (FIDO2), hardware U2F.
- Acceptable: TOTP (app-based). Avoid: SMS/voice, email codes, security questions.
- Require MFA for: login, password changes, privilege elevation, high-value transactions.
- Provide single-use backup codes for recovery.
- Use standard protocols only — never build custom auth schemes.
- Prefer Authorization Code with PKCE for public/native apps.
- Validate
stateandnonce. Exact redirect URI matching. - Short-lived tokens. Rotate refresh tokens. Revoke on logout.
- Pin algorithms. Reject
"none". Validateiss/aud/exp/iat/nbf. - Short lifetimes. Implement revocation (denylist/allowlist).
- Store keys in KMS/HSM. NEVER hardcode JWT secrets.
- Deny by default: Return 403 when no allow rule matches.
- Least privilege: Grant minimum required access.
- Validate every request: Check authorization for every request (AJAX, API, direct).
- Prefer ABAC/ReBAC over RBAC for fine-grained permissions.
- Never trust user-supplied identifiers alone. Verify access per object instance.
- Resolve via user-scoped queries:
currentUser.projects.find(id)NOTProject.find(id). - Use non-enumerable identifiers (UUIDs) as defense-in-depth.
- NEVER bind request bodies directly to domain objects.
- Expose only safe fields via DTOs with explicit allow-lists.
- Use framework features to block sensitive fields.
- Require step-up authentication for sensitive operations.
- Use unique, time-limited credentials per transaction.
- Enforce server-side; prevent client-side downgrades.
- Validate early at trust boundaries with positive (allow-list) validation.
- Treat all untrusted input as data, never as code.
- Parameterize queries/commands. Escape only as last resort.
- 100% parameterized queries. Use prepared statements / ORM bind parameters.
- NEVER concatenate user input into SQL strings.
- Use least-privilege database accounts.
- Prefer built-in APIs over shell execution.
- If unavoidable, use structured execution (ProcessBuilder, etc.) — not shell invocation.
- Allow-list commands and arguments.
- Apply context-appropriate escaping (DN escaping, filter escaping).
- Validate inputs with allow-lists before constructing queries.
- Use
new Map()/new Set()instead of object literals. - Create objects with
Object.create(null)or{ __proto__: null }. - Block
__proto__,constructor,prototypein deep merge utilities.
- HTML context: prefer
textContent. Use DOMPurify with strict allow-lists. - Attribute context: always quote and encode.
- JavaScript context: NEVER build JS from untrusted strings. No
eval(), noinnerHTML. - URL context: validate protocol/domain. Block
javascript:. - Redirects: validate against trusted domain allow-lists.
- Prefer nonce-based or hash-based CSP.
- Start with Report-Only mode, then enforce.
- Baseline:
default-src 'self'; script-src 'self' 'nonce-{random}'; object-src 'none'; base-uri 'self'.
- Use framework-native CSRF tokens on all state-changing requests.
- Cookie settings:
SameSite=LaxorStrict;Secure;HttpOnly. - NEVER use GET for state changes.
Content-Security-Policy: frame-ancestors 'none'or specific allow-list.- Fallback:
X-Frame-Options: DENYorSAMEORIGIN.
| Header | Value | Purpose |
|---|---|---|
Strict-Transport-Security |
max-age=31536000; includeSubDomains |
Force HTTPS |
X-Content-Type-Options |
nosniff |
Prevent MIME sniffing |
X-Frame-Options |
SAMEORIGIN or DENY |
Clickjacking protection |
Referrer-Policy |
origin-when-cross-origin |
Limit referrer info |
Permissions-Policy |
Restrict all unused APIs | Limit browser features |
Content-Security-Policy |
Strict policy | XSS mitigation |
- NEVER store secrets in
localStorage/sessionStorage. - Prefer HttpOnly cookies for token transport.
- Add
rel="noopener noreferrer"to externaltarget="_blank"links.
- HTTPS only. Consider mTLS for high-value/internal services.
- Use OAuth 2.0/OIDC for client auth. For services: mTLS or signed tokens.
- API keys: scope narrowly, rate limit, monitor. NEVER use alone for sensitive operations.
- Validate via contracts (OpenAPI/JSON Schema). Reject unknown fields.
- Enforce explicit
Content-Type/Accept. Set payload size limits. - Harden XML parsers against XXE/entity expansion.
- Per-IP/user/client limits. Circuit breakers. Timeouts.
- Server-side batching and caching to reduce load.
- Do NOT accept raw URLs from users.
- Validate domains/IPs. Block private/link-local/localhost ranges.
- Restrict to HTTP/HTTPS only (block
file://,gopher://,ftp://).
- Generate with CSPRNG (≥128 bits entropy). Opaque, unguessable.
- Store all session data server-side. Never embed PII in tokens.
Set-Cookie: id=<opaque>; Secure; HttpOnly; SameSite=Strict; Path=/
Secure: HTTPS only.HttpOnly: No JavaScript access.SameSite=Strict(orLax).- Scope narrowly with
PathandDomain.
- Regenerate session ID on authentication and privilege changes.
- Idle timeout: 2–5 min (high-value) / 15–30 min (lower risk).
- Absolute timeout: 4–8 hours.
- Full logout must invalidate server session and clear cookie.
- Isolate database servers. Disable network access when possible.
- NEVER allow direct connections from clients to backend database.
- TLS for all database connections. Verify certificates.
- Always require authentication (including local connections).
- Dedicated accounts per application/service. Minimum required permissions.
- NEVER use admin/root/sa accounts for applications.
- NEVER store credentials in source code.
- Store in configuration outside web root, or use secrets management.
- NEVER check credential files into source control.
- Apply least privilege to all database accounts.
- Separate accounts for Dev, UAT, and Production.
- Implement row-level and column-level security when needed.
- Allow-list file extensions (not deny-list).
- Validate file signatures (magic numbers). NEVER trust
Content-Typealone. - Generate random filenames (UUID/GUID). Restrict characters.
- Store outside web root. Use application handlers for access.
- Require authentication before upload/download.
- Set file size limits. Consider post-decompression size limits.
- Scan for malware. Consider CDR (Content Disarm & Reconstruct).
- Rewrite images to destroy malicious content.
- Log and monitor upload activities.
- Authentication/authorization events. Admin actions. Config changes.
- Sensitive data access. Input validation failures. Security errors.
- Include: correlation IDs, user IDs (non-PII), source IP, timestamps (UTC).
- Structured logs (JSON). Stable field names.
- Sanitize inputs to prevent log injection (strip CR/LF/delimiters).
- NEVER log: credentials, tokens, recovery codes, raw session IDs, PII.
- Append-only or WORM storage. Tamper detection.
- Centralized aggregation. Access controls. Retention policies.
- Store outside web-accessible locations.
- Protected branches. Mandatory reviews. Signed commits.
- Secrets: NEVER hardcode. Fetch at runtime from vault/KMS. Mask in logs.
- Security gates: SAST, SCA, DAST, IaC scanning. Block on critical findings.
- Pin dependencies via lockfiles. Verify integrity.
- Run as non-root. Set
USERin Dockerfile. --cap-drop all. NEVER use--privileged.- NEVER mount Docker socket (
/var/run/docker.sock). - Read-only root filesystem. Resource limits (CPU/memory).
- Minimal base images (distroless/alpine). Pin tags and digests.
- Scan images on build. Block high-severity vulnerabilities.
npm ci --omit=devfor deterministic builds.ENV NODE_ENV=production.- Non-root user. Proper init system (
dumb-init). Graceful shutdown. - Multi-stage builds. Use
.dockerignore.
- Maintain lockfiles. Pin versions. Verify integrity.
- Regular audits (
npm audit, NuGet audit). Patch within SLA by severity. - Minimize dependency footprint. Remove unused packages.
- Use private registries. Enable 2FA for publishing.
- Generate Software Bill of Materials for apps/images.
- Attest provenance (SLSA, Sigstore).
- Sign artifacts. Verify signatures at deploy.
| Category | Examples |
|---|---|
| AWS Keys | AKIA..., AGPA..., ASIA... |
| Stripe Keys | sk_live_..., pk_live_... |
| Google API | AIza + 35 chars |
| GitHub Tokens | ghp_..., gho_..., ghs_... |
| JWTs | eyJ... (three base64 sections) |
| Private Keys | -----BEGIN ... PRIVATE KEY----- |
| Connection Strings | mongodb://user:pass@host, Server=...;Password=... |
- Variable names containing:
password,secret,key,token,auth. - Long random-looking strings near authentication code.
- Base64-encoded strings near auth logic.
- Store in secrets manager, Key Vault, or environment-specific configuration.
- Use
dotnet user-secretsfor .NET local development. - Use
.env.local(git-ignored) for Node.js local development.
- Disable DTDs and external entities by default.
- Validate against local, trusted schemas.
- Set limits (size, depth, element counts).
- NEVER deserialize untrusted native objects.
- Prefer JSON with schema validation.
- Avoid:
BinaryFormatter(.NET),pickle(Python),unserialize()(PHP). - Use:
System.Text.Json(.NET),json_decode()(PHP),yaml.safe_load(Python).
- Keep runtime and NuGet packages updated.
- Use
[Authorize]attributes. Perform server-side authorization checks. - Anti-forgery tokens on state-changing actions.
- Enforce HTTPS redirects. Remove version headers. Set CSP/HSTS.
- Use parameterized SQL. Validate with allow-lists.
- Limit request sizes. Validate and sanitize input.
- Avoid
eval,child_process.execwith user input. - Use
helmetfor headers. Rate limit auth endpoints. - Cookies:
secure,httpOnly,sameSite.NODE_ENV=production. - Keep packages updated. Run
npm audit. Use security linters.
- Protect all internal API endpoints (shared secret / mTLS).
- SQL injection: use parameter binding with SQLAlchemy
text(). - Secrets: load from environment (Pydantic
BaseSettings). NEVER hardcode. - Use
HTTPExceptionfor API errors.
When encountering X.509 certificate data:
- Expiration: Flag expired or not-yet-valid certificates as CRITICAL.
- Key Strength: Flag RSA < 2048-bit or ECC < P-256 as HIGH.
- Signature Algorithm: Flag MD5 or SHA-1 signatures as HIGH.
- Self-Signed: Flag as INFORMATIONAL — acceptable only for dev/testing.
- AEAD encryption everywhere. Vetted libraries only. No custom crypto.
- Keys in KMS/HSM. Purpose-scoped. Rotation documented.
- TLS 1.3/1.2 with strong ciphers. Compression off.
- HSTS deployed. Mixed content eliminated.
- Argon2id for password hashing. Per-user salt. Constant-time verify.
- MFA implemented for high-risk operations.
- OAuth 2.0 + PKCE for auth flows. Token rotation implemented.
- Rate limits on auth endpoints. Uniform error responses.
- Deny-by-default enforced on every endpoint.
- Query scoping prevents cross-tenant data access.
- DTOs prevent mass assignment.
- Authorization matrix drives CI tests.
- Contextual XSS encoding/sanitization for every sink.
- CSP with nonces. Violations monitored.
- CSRF tokens on all state-changing requests.
- Security headers configured and validated.
- HTTPS/mTLS configured. Certs managed.
- Contract validation at edge. Unknown fields rejected.
- Rate limiting and circuit breakers in place.
- SSRF protections at app and network layers.
- Pipeline secrets in vault. Ephemeral runners. Security scans in CI.
- Containers: non-root, least privilege, read-only FS, scanned images.
- Lockfiles present. SBOM generated. Dependencies audited.
- No hardcoded credentials in source code. Verified by automated scans.