# 📘 Security Specific Coding Rules

> This is a comprehensive list of security rules designed to enhance the security posture of applications.
> Each rule includes a title, detailed description, applicable programming languages, and priority level.

### 📘 Rule S001 – Authenticate backend component communications securely

- **Objective**: Ensure all communications between backend components (APIs, middleware, data layers) are authenticated using secure, short-lived credentials instead of static secrets.
- **Details**:
  - Backend-to-backend communications that bypass standard user session mechanisms must be authenticated.
  - **Required authentication methods**:
    - Individual service accounts (per-service identity)
    - Short-term tokens (JWT with short expiry, OAuth tokens)
    - Certificate-based authentication (mTLS)
  - **Prohibited credentials**:
    - Static passwords or API keys
    - Shared accounts with privileged access
    - Long-lived unchanging credentials
  - Apply to: service-to-service calls, internal APIs, message queues, database connections, cache layers.
- **Applies to**: All languages
- **Tools**: Manual Review, IAM Policy Audit, mTLS Scanner, Secret Rotation Checker
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: critical

### 📘 Rule S002 – Protect against OS command injection

- **Objective**: Prevent OS command injection attacks by ensuring all operating system calls use parameterized queries or proper output encoding.
- **Details**:
  - **Never** concatenate user input directly into OS commands or shell executions.
  - **Required protection methods**:
    - Use parameterized OS queries (subprocess with argument lists)
    - Apply contextual command line output encoding
    - Use language-specific safe APIs (e.g., `subprocess.run()` with `shell=False`)
  - **Avoid**:
    - `shell=True` with user input
    - String concatenation in `exec()`, `system()`, `Runtime.exec()`
    - Backtick operators or `$()` with untrusted data
  - Validate and sanitize all inputs before passing to system commands.
- **Applies to**: All languages
- **Tools**: SonarQube (S2076, S4721), Semgrep (command-injection), Bandit (B602, B603), Manual Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: critical

### 📘 Rule S003 – URL redirects must be within an allow list

- **Objective**: Prevent Open Redirect vulnerabilities, protecting users from being redirected to malicious pages through spoofed input.
- **Details**:
  - Must not redirect to URLs received from user input without validation.
  - If dynamic redirects are needed, must check URLs against an allow list before execution.
  - If the URL is outside the allow list, you can:
    - Reject the redirect (HTTP 400)
    - Or display a clear warning before continuing.
- **Applies to**: All languages
- **Tools**: Semgrep (custom rule), Manual Review, SonarQube (custom rule)
- **Principles**: SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: low

### 📘 Rule S004 – Do not log login credentials, payment information, and unencrypted tokens

- **Objective**: Prevent leakage of sensitive information through log systems – a common attack vector if logs are shared, stored incorrectly, or exploited.
- **Details**:
  - Must not log fields like: `password`, `access_token`, `credit_card`, `cvv`, `secret_key`, etc.
  - Tokens (session tokens, JWT, etc.) if logging is mandatory for debugging, must be hashed or masked (`****`).
  - Avoid logging entire `request.body`, `form-data`, or `headers` containing sensitive information.
  - Ensure logs are configured to exclude sensitive fields.
- **Applies to**: All languages
- **Tools**: SonarQube (S2068, S5334), Semgrep (custom rule), Manual Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S005 – Enforce authorization at trusted service layer

- **Objective**: Ensure authorization rules are enforced at a trusted server-side service layer, not relying on client-side controls that can be manipulated.
- **Details**:
  - **Never** rely on client-side JavaScript for authorization decisions.
  - **Required practices**:
    - Enforce all authorization checks on trusted backend services
    - Validate permissions server-side before processing requests
    - Use middleware or interceptors at the service layer
  - **Untrusted controls to avoid**:
    - Client-side JavaScript permission checks
    - Hidden form fields for authorization
    - URL parameters for access control
    - Browser-stored tokens without server validation
  - All sensitive operations must be re-validated at the backend regardless of client-side checks.
- **Applies to**: All languages
- **Tools**: Manual Review, Static Analysis, Penetration Testing, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: critical

### 📘 Rule S006 – Do not use default credentials for service authentication

- **Objective**: Ensure service authentication never uses default or well-known credentials that attackers can easily guess or find in documentation.
- **Details**:
  - **Never** use default credentials for any service authentication:
    - `root/root`, `admin/admin`, `test/test`
    - Default database passwords (e.g., `postgres/postgres`, `sa/sa`)
    - Factory-default API keys or tokens
  - **Required practices**:
    - Generate unique, strong credentials for each service instance
    - Rotate credentials regularly
    - Use secrets management tools (Vault, AWS Secrets Manager)
  - Scan configurations and deployment scripts for default credential patterns.
  - Block deployments containing default credentials in CI/CD pipelines.
- **Applies to**: All languages
- **Tools**: Manual Review, Secret Scanner, GitLeaks, TruffleHog, CI/CD Policy Checks
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: critical

### 📘 Rule S007 – Perform output encoding before interpreter use

- **Objective**: Ensure the application performs proper output encoding and escaping as a final step before data is used by the target interpreter, preventing injection attacks.
- **Details**:
  - Output encoding must occur either:
    - As a final step before being used by the interpreter
    - Or by the interpreter itself (using built-in encoding features)
  - **Context-specific encoding**:
    - HTML context: encode `<`, `>`, `&`, `"`, `'`
    - JavaScript context: escape strings properly
    - SQL context: use parameterized queries
    - URL context: use `encodeURIComponent()`
    - Shell context: escape shell metacharacters
  - **Never** trust that earlier encoding is sufficient – encode at the point of use.
  - Use framework-provided encoding functions where available.
- **Applies to**: All languages
- **Tools**: SonarQube (S5131, S2076), Semgrep (injection rules), ESLint, Manual Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S008 – Validate and sanitize SVG content

- **Objective**: Ensure user-supplied SVG (Scalable Vector Graphics) content is validated or sanitized to prevent script injection and other attacks.
- **Details**:
  - SVG files can contain embedded scripts and potentially dangerous elements.
  - **Allowed elements** (safe for graphics):
    - Drawing elements: `svg`, `path`, `rect`, `circle`, `ellipse`, `line`, `polyline`, `polygon`
    - Grouping: `g`, `defs`, `use`, `symbol`
    - Styling: `style` (with restrictions), `linearGradient`, `radialGradient`
  - **Prohibited elements** (must be removed/rejected):
    - `script` tags
    - `foreignObject` (can embed arbitrary HTML)
    - Event handlers (`onclick`, `onload`, `onerror`, etc.)
    - External references (`xlink:href` to external URLs)
  - Use SVG sanitization libraries (e.g., DOMPurify with SVG profile).
  - Consider converting SVGs to raster images for untrusted sources.
- **Applies to**: All languages
- **Tools**: DOMPurify, svg-sanitizer, Manual Review, CSP Headers
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S009 – Use only approved cryptographic algorithms, modes, and hash functions

- **Objective**: Prevent cryptographic vulnerabilities by ensuring only secure block modes, padding schemes, ciphers, and hash functions are used throughout the application.
- **Details**:
  - Do not use insecure block modes (e.g., ECB) as they reveal identical data patterns and are vulnerable to pattern analysis attacks.
  - Do not use weak padding schemes (e.g., `PKCS#1 v1.5`) which are vulnerable to padding oracle attacks.
  - Use only approved ciphers and modes such as `AES` with `GCM` (Galois/Counter Mode) for authenticated encryption.
  - Use only approved hash functions for general cryptographic use cases, including digital signatures, HMAC, KDF, and random bit generation.
  - Disallowed hash functions such as `MD5` must not be used for any cryptographic purpose, including checksums, integrity verification, or password hashing.
  - Do not use encryption algorithms with block size < 128-bit like `Triple-DES`, `Blowfish`.
  - For legacy compatibility requirements, isolate the implementation and add clear security warnings.
- **Applies to**: All languages
- **Tools**: SonarQube (S2070, S4790, S5547), Semgrep (crypto rules), Manual Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S010 – Must use cryptographically secure random number generators (CSPRNG) for security purposes

- **Objective**: Prevent attackers from guessing security random values like OTP, session ID, recovery tokens... by ensuring they are generated from Cryptographically Secure PRNG provided by cryptographic libraries/modules.
- **Details**:
  - Absolutely do not use `Math.random()` or similar functions for security values.
  - Always use functions designed for cryptographic purposes, e.g.: `crypto.randomBytes()`, `SecureRandom`, `secrets`, `crypto/rand`, etc.
  - Applies to: OTP codes, password reset tokens, session IDs, magic links, temporary file names, security GUIDs...
  - Ensure generated values are sufficiently long (entropy ≥ 128 bits) and non-repeating.
- **Applies to**: All languages
- **Tools**: SonarQube (S2245), Semgrep (random-insecure), Manual Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S011 – Enable Encrypted Client Hello (ECH) for TLS

- **Objective**: Prevent exposure of sensitive metadata during TLS handshake by enabling Encrypted Client Hello (ECH) to protect Server Name Indication (SNI) and other client hello fields.
- **Details**:
  - **Why ECH matters**:
    - Standard TLS exposes SNI in plaintext during handshake
    - Attackers can identify which sites users are visiting
    - Network monitors can filter/block based on SNI
  - **Required configuration**:
    - Enable ECH in TLS settings (TLS 1.3 required)
    - Configure ECH public keys properly
    - Support HTTPS DNS records for ECH key distribution
  - **Benefits**:
    - Encrypts SNI and other sensitive handshake data
    - Prevents traffic analysis based on destination
    - Enhances user privacy
  - Verify ECH is working using browser developer tools or TLS testing tools.
- **Applies to**: All languages
- **Tools**: SSL Labs, testssl.sh, Browser DevTools, Manual TLS Config Review
- **Principles**: SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S012 – Use secrets management solution for backend secrets

- **Objective**: Ensure all backend secrets are securely managed using a dedicated secrets management solution, never stored in source code or build artifacts.
- **Details**:
  - **Must use a secrets management solution** (key vault) to:
    - Create secrets securely
    - Store secrets with encryption at rest
    - Control access with fine-grained permissions
    - Rotate and destroy secrets safely
  - **Types of secrets to manage**:
    - Passwords and credentials
    - Cryptographic key material
    - Database connection strings
    - Third-party system integrations
    - TOTP seeds and internal secrets
    - API keys
  - **Prohibited practices**:
    - Secrets in application source code
    - Secrets in build artifacts or container images
    - Secrets in environment files committed to repos
  - **For L3 (high-security) applications**: Must use hardware-backed solution (HSM).
  - Recommended tools: HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, GCP Secret Manager.
- **Applies to**: All languages
- **Tools**: Vault, AWS Secrets Manager, Azure Key Vault, GitLeaks, TruffleHog, HSM
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: critical

### 📘 Rule S013 – Always use TLS for all connections

- **Objective**: Protect data in transit from leakage and Man-In-The-Middle (MITM) attacks by requiring all connections to use TLS (HTTPS), not allowing fallback to unencrypted protocols like HTTP.
- **Details**:
  - Absolutely do not allow HTTP communication for any API, login forms, or personal data (PII).
  - TLS mandatory for all:
    - Frontend → backend communication (browser, mobile)
    - Backend → third-party API communication
    - Service-to-service communication
  - Disable debug/localhost unencrypted modes in production.
  - Enable HSTS (HTTP Strict Transport Security) on frontend to enforce HTTPS.
- **Applies to**: All languages
- **Tools**: OWASP ZAP, SSLyze, Lighthouse, Static Analyzer (Semgrep/ESLint), Manual Review, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S014 – Only use TLS 1.2 or 1.3

- **Objective**: Protect network communication from attacks exploiting older TLS versions like BEAST, POODLE, Heartbleed, or downgrade attacks by only allowing TLS 1.2 or 1.3.
- **Details**:
  - TLS 1.0 and 1.1 are no longer supported by modern browsers and systems.
  - Older versions are vulnerable to downgrade attacks or encryption vulnerability exploitation.
  - Need explicit configuration on backend applications, reverse proxy (NGINX, Apache), and any SSL clients.
  - Prefer default configuration as TLS 1.3 if supported.
- **Applies to**: All languages
- **Tools**: SSLyze, testssl.sh, OWASP ZAP, Manual Review, Configuration Scanner
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S015 – Only accept trusted TLS certificates and eliminate weak ciphers

- **Objective**: Protect client-server connections from MITM attacks by only trusting valid TLS certificates signed by trusted CAs, and rejecting all unknown certificates or weak ciphers.
- **Details**:
  - Always use valid TLS certificates from trusted CAs. If using internal or self-signed certificates, only trust certificates that are explicitly configured (pinning, specific trust store).
  - Absolutely do not accept any certificate automatically (e.g., `rejectUnauthorized: false`, `InsecureSkipVerify: true`).
  - Disable outdated cipher suites like RC4, 3DES, NULL cipher, or those using MD5, SHA1.
  - Prefer modern ciphers like AES-GCM, ChaCha20-Poly1305, TLS_ECDHE.
  - Use tools like [SSL Labs](https://www.ssllabs.com/ssltest/), `testssl.sh`, or `nmap --script ssl-enum-ciphers` to scan TLS configuration.
- **Applies to**: All languages
- **Tools**: SSL Labs, testssl.sh, nmap ssl-enum-ciphers, Manual Review
- **Principles**: SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S016 – Do not pass sensitive data via query string

- **Objective**: Prevent leakage of sensitive data through URLs by not passing sensitive information via query string, instead using HTTP body or headers in authenticated requests or private operations.
- **Details**:
  - Do not put authentication tokens, passwords, OTP codes, personal information (PII) in query strings like `GET /api/reset?token=...`
  - Data in query strings is easily:
    - Logged by server/proxy/load balancer
    - Cached in browser, proxy
    - Saved in history, bookmarks
  - Only pass sensitive data through:
    - HTTP body (POST/PUT)
    - Custom headers (Authorization, X-Token, ...)
- **Applies to**: All languages
- **Tools**: Semgrep (hardcoded query pattern), Manual Review, Proxy log scanner, SonarQube (custom rule)
- **Principles**: SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S017 – Always use parameterized queries

- **Objective**: Prevent various forms of injection (SQL Injection, HQL Injection, NoSQL Injection) by always using parameterized queries or ORM when accessing data.
- **Details**:
  - Must not directly concatenate user input values into queries.
  - Use secure query mechanisms such as:
    - `?`, `$1`, `:param`, or binding in ORM
    - Entity Framework, JPA, Sequelize, GORM, etc.
  - For NoSQL (MongoDB, Firebase...), should not use raw JS queries based on string input.
  - If absolutely unavoidable to use parameters, must properly escape input according to the engine being used (not recommended).
- **Applies to**: All languages
- **Tools**: SonarQube (S2077, S3649), Semgrep (injection rules), CodeQL, Manual Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: critical

### 📘 Rule S018 – Do not store sensitive data in browser storage

- **Objective**: Prevent sensitive data exposure by ensuring browser storage mechanisms do not contain sensitive information, except for session tokens.
- **Details**:
  - **Browser storage types covered**:
    - `localStorage` (persistent, accessible by JavaScript)
    - `sessionStorage` (tab-scoped, accessible by JavaScript)
    - `IndexedDB` (client-side database)
    - Cookies (when not HttpOnly)
  - **Prohibited data in browser storage**:
    - Passwords or credentials
    - Personal Identifiable Information (PII)
    - Financial data (credit cards, bank accounts)
    - API keys or secrets
    - Encryption keys
  - **Exception**: Session tokens may be stored, but:
    - Use `HttpOnly` cookies when possible
    - Apply short expiration times
    - Implement proper token rotation
  - XSS attacks can access all JavaScript-readable storage.
  - Use server-side sessions for sensitive data instead.
- **Applies to**: All languages
- **Tools**: Browser DevTools, Static Analysis (Semgrep, ESLint), Manual Code Review, Security Audit
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S019 – Sanitize input before sending emails to prevent SMTP Injection

- **Objective**: Prevent SMTP/IMAP injection by removing control characters and ensuring proper formatting of user input used in email sending.
- **Details**:
  - SMTP Injection occurs when input contains `\r`, `\n` which can inject new lines or alter email content.
  - Risks: hidden email sending, modified content, header spoofing, or spam.
  - Prevention:
    - Strip or reject control characters (`\n`, `\r`) in `to`, `subject`, `cc`, `bcc`, `reply-to`.
    - Validate email format strictly before use.
    - Prefer using secure email APIs like SendGrid, Amazon SES, Mailgun instead of direct SMTP protocol.
- **Applies to**: All languages
- **Tools**: Semgrep (regex match), Manual Review, Static Analysis, SonarQube (custom rule)
- **Principles**: SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S020 – Avoid using `eval()` or executing dynamic code

- **Objective**: Prevent Remote Code Execution (RCE) by disallowing use of dynamic code execution functions like `eval()`, `Function()`, `exec()`, `Runtime.exec()` with user-controlled input.
- **Details**:
  - Functions like `eval()`, `exec()`, `new Function()`, or `setTimeout(..., string)` allow arbitrary code execution, dangerous with untrusted input.
  - Attackers can execute system commands, read files, or manipulate databases remotely.
  - Alternatives to `eval`:
    - Object mapping or switch-case for dynamic logic
    - JSON parsing for data structures
    - `safe-eval` library (only within a sandboxed scope)
- **Applies to**: All languages
- **Tools**: Semgrep (eval-detection rules), ESLint (`no-eval`), SonarQube (S1523), Static Analyzer
- **Principles**: SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S021 – Set Referrer-Policy to prevent sensitive data leakage

- **Objective**: Prevent leakage of sensitive URL data (path, query parameters, hostname) to third-party services via the `Referer` HTTP header.
- **Details**:
  - **Why it matters**:
    - `Referer` header can expose sensitive data in URLs to external sites
    - Internal application hostnames may reveal infrastructure details
    - Query parameters may contain tokens, IDs, or PII
  - **Implementation methods**:
    - HTTP response header: `Referrer-Policy: strict-origin-when-cross-origin`
    - HTML meta tag: `<meta name="referrer" content="strict-origin-when-cross-origin">`
    - HTML element attributes: `rel="noreferrer"` on links
  - **Recommended policies**:
    - `strict-origin-when-cross-origin` (default, balanced)
    - `same-origin` (stricter, only same-origin gets referrer)
    - `no-referrer` (strictest, never send referrer)
  - For internal non-public applications, use stricter policies to protect hostnames.
- **Applies to**: All languages
- **Tools**: Browser DevTools, Security Headers Scanner, OWASP ZAP, Manual Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S022 – Escape data properly based on output context

- **Objective**: Prevent XSS, Header Injection, Email Injection by escaping output data according to context (HTML, JS, URL, Header, Email, etc).
- **Details**:
  - Use the correct escaping strategy for each context:
    - **HTML content**: escape `&`, `<`, `>`, `"`, `'`
    - **HTML attributes**: escape `"` and `'` values
    - **JavaScript inline**: escape strings to avoid arbitrary execution
    - **URL params**: use `encodeURIComponent()`
    - **HTTP headers**: strip `\r`, `\n` to prevent injection
    - **SMTP email**: filter control characters like `\r`, `\n`, `bcc:` from content
  - Avoid using a single escape function for all cases.
- **Applies to**: All languages
- **Tools**: ESLint (`no-script-url`, `react/no-danger`), Bandit, SonarQube (S2076), DOMPurify, Manual Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S023 – Use output encoding when building dynamic JavaScript/JSON

- **Objective**: Prevent JavaScript and JSON injection by applying proper output encoding when dynamically building JavaScript content or JSON data.
- **Details**:
  - **When building dynamic JavaScript**:
    - Encode data before inserting into JS strings
    - Escape characters: `\`, `'`, `"`, `<`, `>`, `&`, newlines
    - Never use `eval()` or `new Function()` with user data
  - **When building JSON responses**:
    - Use native JSON serializers (`JSON.stringify()`, `json.dumps()`)
    - Escape `</script>` sequences when embedding in HTML
    - Validate JSON structure before parsing
  - **Dangerous patterns to avoid**:
    - String concatenation to build JS: `"var x = '" + userInput + "'"`
    - Inline event handlers with user data
    - Template literals with unescaped user input
  - Use Content Security Policy (CSP) as defense-in-depth.
- **Applies to**: All languages
- **Tools**: ESLint (`no-eval`), Semgrep (json-injection), SonarQube (S1523, S5334), Manual Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S024 – Protect against XPath Injection and XML External Entity (XXE)

- **Objective**: Prevent XPath injection and XXE vulnerabilities that can expose files, trigger SSRF, or run malicious code.
- **Details**:
  - **XPath Injection**:
    - Never inject user data directly into XPath queries.
    - Use parameterized APIs or safe XPath binding mechanisms.
  - **XXE**:
    - Disable external entity processing in XML parsers to prevent local file access or SSRF.
    - Disable general and parameter entity processing in DOM/SAX/lxml parsers.
- **Applies to**: All languages
- **Tools**: Semgrep (xpath injection), Bandit (Python), SonarQube (S2755), Manual Config Review
- **Principles**: SECURITY
- **Version**: 1.1
- **Status**: activated
- **Severity**: medium

### 📘 Rule S025 – Always validate client-side data on the server

- **Objective**: Ensure all data from clients is validated server-side to prevent attacks from forged or malicious input.
- **Details**:
  - Client-side validation is only for UX – it can be bypassed.
  - Server-side validation is the last defense before DB writes or API calls.
  - Benefits:
    - Blocks SQLi, XSS, Buffer Overflow, SSRF
    - Preserves data integrity (valid enums, length limits, etc.)
    - Testable via unit tests
  - Recommended libraries:
    - Java: Hibernate Validator, Spring `@Valid`
    - Node.js: Joi, express-validator
    - Python: pydantic, marshmallow
- **Applies to**: All languages
- **Tools**: SonarQube (S5334), ESLint (`require-validate`), Bandit (Python), Static Analysis
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S026 – Use TLS encryption for all inbound and outbound connections

- **Objective**: Ensure all application connections use encrypted TLS protocol, with no fallback to insecure or unencrypted protocols.
- **Details**:
  - **All connections must use TLS**:
    - Inbound: API endpoints, web interfaces, webhooks
    - Outbound: external APIs, databases, partner systems
  - **Connection types covered**:
    - Monitoring systems and health checks
    - Management tools and admin interfaces
    - Remote access and SSH connections
    - Middleware and message queues
    - Database connections (PostgreSQL, MySQL, MongoDB)
    - Mainframe and legacy system integrations
    - Partner and external API calls
  - **Requirements**:
    - TLS 1.2 minimum, prefer TLS 1.3
    - No fallback to HTTP, unencrypted protocols
    - Certificate validation enabled
    - Strong cipher suites only
  - Disable debug modes that bypass TLS in production.
- **Applies to**: All languages
- **Tools**: SSL Labs, testssl.sh, nmap, Network Traffic Analysis, Manual Config Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: critical

### 📘 Rule S027 – Validate mTLS client certificates before authentication

- **Objective**: Ensure mTLS client certificates are properly validated and trusted before using certificate identity for authentication or authorization decisions.
- **Details**:
  - **Before trusting certificate identity**:
    - Verify certificate is signed by trusted CA
    - Check certificate has not expired
    - Validate certificate is not revoked (CRL/OCSP)
    - Confirm certificate subject/SAN matches expected identity
  - **Certificate validation requirements**:
    - Full chain validation up to root CA
    - Check Extended Key Usage for client authentication
    - Verify certificate purpose and constraints
  - **Common mistakes to avoid**:
    - Accepting any valid certificate without identity check
    - Skipping revocation checks
    - Trusting self-signed certificates without explicit pinning
    - Using certificate CN without proper validation
  - Log all certificate validation failures for security monitoring.
- **Applies to**: All languages
- **Tools**: OpenSSL, mTLS Testing Tools, Certificate Validator, Manual Config Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: critical

### 📘 Rule S028 – Limit upload file size and number of files per user

- **Objective**: Prevent resource abuse and protect against DoS attacks by limiting file size, number of files, and user storage usage.
- **Details**:
  - Must enforce limits on:
    - **Maximum file size** (e.g., ≤ 10MB)
    - **Total number of files** per user or per upload
    - **Total storage quota per user** (if applicable)
  - Limits should be:
    - Enforced on both client-side and server-side (server is mandatory)
    - Handled via HTTP layer or upload middleware
    - Logged when violations occur for abuse tracking
  - Technology examples:
    - Node.js: `multer` (`limits.fileSize`, `fileFilter`)
    - Python: `Flask-Limiter`, request body size limit
    - Java: Spring's `multipart.maxFileSize`, `maxRequestSize`
    - Nginx/nginx-ingress: `client_max_body_size`
- **Applies to**: All languages
- **Tools**: Manual Review, Static Analysis, API Gateway Limit, Nginx Config, WAF, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S029 – Apply CSRF protection for authentication-related features

- **Objective**: Prevent Cross-Site Request Forgery (CSRF) attacks where an attacker triggers unauthorized actions using the victim's authenticated session.
- **Details**:
  - CSRF occurs when:
    - Victim is logged in (cookies exist)
    - Browser automatically sends cookies with attacker-forged requests
  - **Protection mechanisms**:
    - **CSRF Token**: Generate a unique token (per session/request), attach it in form or header, and validate server-side
    - **SameSite Cookie**:
      - `SameSite=Lax`: suitable for most form-based POST requests
      - `SameSite=Strict`: most secure, may affect UX
      - `SameSite=None; Secure`: required for cross-domain cookies (must use HTTPS)
    - **2FA or re-authentication** for critical actions like changing email/password or performing transactions
  - For API or SPA:
    - Avoid storing access tokens in cookies
    - Prefer using `Authorization: Bearer <token>` to eliminate CSRF risk
- **Applies to**: All languages
- **Tools**: Spring Security CSRF, Express `csurf`, Django CSRF middleware, Helmet.js, Manual Review, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S030 – Disable directory browsing and protect sensitive metadata files

- **Objective**: Prevent unauthorized access to file listings or metadata files such as `.git`, `.env`, `.DS_Store`, which can reveal sensitive system or source code information.
- **Details**:
  - Directory browsing occurs if no `index.html` exists or misconfigured server
  - Sensitive files may be exposed if not explicitly blocked, e.g.:
    - `.git/config` → contains repo URL or credentials
    - `.env` → secrets
    - `.DS_Store`, `Thumbs.db`, `.svn` → folder structure leaks
  - **Mitigation**:
    - Disable `autoindex` or `Indexes` on the web server (Apache/Nginx)
    - Deny access to metadata or dotfiles (`.git`, `.env`, etc.)
    - Review default config of frameworks (Express, Spring, Django, etc.)
    - Use `.gitignore` to exclude sensitive files from version control
- **Applies to**: All languages
- **Tools**: Static Analysis, Manual Review, Burp Suite, Nikto, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S031 – Set the Secure flag on session cookies for HTTPS protection

- **Objective**: Prevent attackers from stealing session cookies via unencrypted HTTP, especially on public or monitored networks (MITM).
- **Details**:
  - If a **cookie lacks the `Secure` flag**, it may be sent over plain HTTP
  - Attackers on public Wi-Fi or LAN may intercept session tokens
  - Sensitive cookies should always include:
    - `Secure`: only send via HTTPS
    - `HttpOnly`: prevent JS access
    - `SameSite`: control CSRF exposure
  - **Best practices**:
    - Use HTTPS in all environments (dev, staging, prod)
    - Ensure web server enforces HTTP → HTTPS redirects
- **Applies to**: All languages
- **Tools**: OWASP ZAP, Burp Suite, Static Analysis, Manual Review, SonarQube (custom rule)
- **Principles**: SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S032 – Enable HttpOnly attribute for Session Cookies to prevent JavaScript access

- **Objective**: Prevent JavaScript (including malicious code during XSS attacks) from accessing session cookies, thereby limiting the risk of theft and session hijacking.
- **Details**:
  - **Without `HttpOnly`** → JavaScript can call `document.cookie` and read all session data.
  - XSS attacks exploit this vulnerability to steal tokens or cookies.
  - `HttpOnly` is one of the most important security flags along with:
    - `Secure`: only send cookies over HTTPS.
    - `SameSite`: limit CSRF attacks.
  - Combine with:
    - Comprehensive XSS protection (escaping, CSP).
    - Cookie validation in all environments (QA, prod, staging).
- **Applies to**: All languages
- **Tools**: Static Analysis, OWASP ZAP, Burp Suite, Manual Review, SonarQube (custom rule)
- **Principles**: SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S033 – Set SameSite attribute for Session Cookies to reduce CSRF risk

- **Objective**: Limit the browser's ability to automatically send cookies in cross-origin requests, thereby minimizing the risk of Cross-Site Request Forgery (CSRF) attacks.
- **Details**:
  - **Without `SameSite`**, cookies will be sent in all requests – even when coming from malicious sites → easily exploited in CSRF attacks.
  - `SameSite` values:
    - `Strict`: highest security, does not send cookies when redirected from other sites (best CSRF prevention).
    - `Lax`: common default, allows cookies to be sent with GET navigation requests (form submissions...).
    - `None`: **must be used with `Secure`** if the application needs to work cross-domain (e.g., SPA frontend calling API from different domain).
  - `SameSite` needs to work together with:
    - `HttpOnly` to prevent JS access.
    - `Secure` to only send over HTTPS.
  - Always check that the backend application has set `SameSite` correctly, and cookies are not reset incorrectly due to duplicate headers.
- **Applies to**: All languages
- **Tools**: OWASP ZAP, Postman, Static Analysis, Manual Review, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S034 – Use `__Host-` prefix for Session Cookies to prevent subdomain sharing

- **Objective**: Prevent cookie theft between subdomains (e.g., `api.example.com` accessing cookies from `admin.example.com`) by using cookies prefixed with `__Host-`, which enforce strict security tied to the root domain.
- **Details**:
  - The `__Host-` prefix enforces:
    - Must include `Secure`
    - Must not specify `Domain` (defaults to root domain)
    - `Path` must be `/`
  - Advantages:
    - Cookie exists only on the root domain (e.g., `example.com`), cannot be overridden by subdomains.
    - Prevents scenarios like:
      - A malicious app on `sub1.example.com` sets a fake `sessionId`, which is then reused on `example.com`.
  - Commonly used for:
    - Session cookies
    - CSRF tokens
    - Auth tokens
  - Limitation:
    - Only applicable over **HTTPS** and must be set from the root domain.
- **Applies to**: All languages
- **Tools**: Manual Review, Static Analysis, Chrome DevTools Audit, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S035 – Host separate applications on different hostnames

- **Objective**: Leverage same-origin policy restrictions by hosting separate applications on different hostnames to isolate resources, cookies, and prevent cross-application attacks.
- **Details**:
  - **Same-origin policy benefits**:
    - Prevents scripts from one origin accessing resources from another
    - Isolates cookies and storage per hostname
    - Limits impact of XSS to single application
  - **Hosting requirements**:
    - Each application should have its own hostname/subdomain
    - Example: `app1.example.com`, `app2.example.com` (good)
    - Avoid: `example.com/app1`, `example.com/app2` (shared origin)
  - **Restrictions enforced**:
    - Document/script isolation between origins
    - Cookie isolation (with proper domain settings)
    - localStorage/sessionStorage separation
    - CORS enforcement for cross-origin requests
  - Use subdomains or separate domains for:
    - Admin panels vs public sites
    - API servers vs frontend apps
    - Multi-tenant applications
- **Applies to**: All languages
- **Tools**: Manual Architecture Review, DNS Configuration Audit, Browser DevTools
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S036 – Use internal data for file paths, validate user filenames strictly

- **Objective**: Prevent path traversal, LFI, RFI, and SSRF attacks by using internally generated file paths instead of user-submitted filenames, with strict validation when user input is unavoidable.
- **Details**:
  - **Preferred approach** - Use internal data:
    - Generate file paths from internal IDs or UUIDs
    - Map user selections to predefined safe paths
    - Store file metadata in database, not in filenames
  - **When user filenames are required**:
    - Strip path separators (`/`, `\`, `..`)
    - Validate against allow-list of characters
    - Limit filename length
    - Sanitize file extensions
    - Normalize paths before validation
  - **Attacks prevented**:
    - Path traversal (`../../etc/passwd`)
    - Local File Inclusion (LFI)
    - Remote File Inclusion (RFI)
    - Server-Side Request Forgery (SSRF)
  - Never use user input directly in: `include()`, `require()`, `open()`, `readFile()`, file download paths.
- **Applies to**: All languages
- **Tools**: Static Analysis, OWASP ZAP, Burp Suite, Semgrep (path-traversal), Manual Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: critical

### 📘 Rule S037 – Set anti-cache headers to prevent sensitive data leakage

- **Objective**: Prevent browsers from caching sensitive data such as tokens, personal information, or financial content which could leak when users share devices or use back/forward navigation.
- **Details**:
  - Modern browsers may cache:
    - Filled-in forms
    - Login results
    - Rendered tokens or confidential data
  - Recommended headers:
    - `Cache-Control: no-store, no-cache, must-revalidate`
    - `Pragma: no-cache`
    - `Expires: 0`
  - Use for:
    - Profile lookups, dashboard pages
    - Tokens, session content
  - Check using DevTools → Network → Headers.
- **Applies to**: All languages
- **Tools**: Static Analysis, Postman, Chrome DevTools, Manual Review, SonarQube (custom rule)
- **Principles**: SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S038 – Hide system version information in HTTP Headers

- **Objective**: Prevent attackers from discovering backend technologies (e.g., server, framework, OS) via HTTP response headers that can be used to target known vulnerabilities.
- **Details**:
  - Common leak examples:
    - `Server: nginx/1.23.0`
    - `X-Powered-By: Express`
    - `X-AspNet-Version`, `X-Runtime`, etc.
  - Preventive steps:
    - Disable or override these headers.
    - Use middleware or reverse proxy to strip response headers.
    - Verify using DevTools, curl, or Postman.
- **Applies to**: All languages
- **Tools**: Static Analysis, curl, Postman, Chrome DevTools, Burp Suite, SonarQube (custom rule)
- **Principles**: SECURITY
- **Version**: 1.1
- **Status**: activated
- **Severity**: medium

### 📘 Rule S039 – TLS clients must validate server certificates

- **Objective**: Ensure TLS clients validate certificates received from servers before establishing secure communication to prevent MITM attacks.
- **Details**:
  - **Required certificate validation**:
    - Verify certificate is signed by trusted CA
    - Check certificate chain up to root CA
    - Validate certificate has not expired
    - Confirm hostname matches certificate CN/SAN
  - **Do NOT disable validation**:
    - Never set `rejectUnauthorized: false` (Node.js)
    - Never set `verify=False` (Python requests)
    - Never set `InsecureSkipVerify: true` (Go)
    - Never ignore SSL errors in production
  - **Certificate revocation**:
    - Check CRL or OCSP when possible
    - Consider OCSP stapling for performance
  - For development/testing only: use self-signed certs with explicit trust, not disabled validation.
- **Applies to**: All languages
- **Tools**: SSL Labs, testssl.sh, Static Analysis, Manual Code Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: critical

### 📘 Rule S040 – Regenerate Session Token after login to prevent Session Fixation

- **Objective**: Prevent attackers from setting a session ID before login and taking over the session post-login if the ID remains unchanged.
- **Details**:
  - Attack scenario:
    - Attacker sets known session ID before login
    - Victim logs in without regenerating session
    - Attacker reuses the same ID for access
  - Preventive actions:
    - Invalidate old session after login and create a new one
    - For JWT: issue new token on login
    - For cookies: delete old session and set a new cookie
- **Applies to**: All languages
- **Tools**: Static Analysis, Manual Review, OWASP ZAP, Burp Suite, SonarQube (custom rule)
- **Principles**: SECURITY
- **Version**: 1.1
- **Status**: activated
- **Severity**: high

### 📘 Rule S041 – Session Tokens must be invalidated after logout or expiration

- **Objective**: Prevent users from reusing old session tokens after logout or timeout, which could lead to session hijacking.
- **Details**:
  - Actions required:
    - **Backend**:
      - Remove session from memory (e.g., Redis)
      - Revoke token or blacklist old JWT
    - **Frontend**:
      - Delete cookie (`document.cookie = ...`, `res.clearCookie(...)`)
      - Remove tokens from localStorage
      - Redirect/reload after logout
  - Add `Cache-Control: no-store` to prevent old content reuse
- **Applies to**: All languages
- **Tools**: Static Analysis, Manual Review, Postman, DevTools, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S042 – Require re-authentication for long-lived sessions or sensitive actions

- **Objective**: Reduce the risk of session hijacking or privilege misuse by forcing re-authentication after long idle periods or before critical actions.
- **Details**:
  - When using persistent login or "Remember Me":
    - Require re-login after X hours (e.g., 12h, 24h)
    - Re-authenticate after inactivity (e.g., 30 mins)
    - Require password or 2FA for sensitive actions (password change, payments)
  - For JWT:
    - Use short-lived tokens with secure refresh logic
- **Applies to**: All languages
- **Tools**: Manual Review, Static Analysis (JWT expiry, session policy), Security Test, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S043 – Password changes must invalidate all other login sessions

- **Objective**: Ensure attackers cannot continue using old session tokens after a password change. Enforce correct access control after sensitive updates.
- **Details**:
  - On password change:
    - Invalidate all other active sessions (except current if necessary)
    - Clear all session tokens from DB, Redis, or memory
    - For JWT: use token versioning or timestamp to revoke old tokens
    - Require re-login across all devices
- **Applies to**: All languages
- **Tools**: Manual Review, Static Analysis (Token Revocation Logic), SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.1
- **Status**: activated
- **Severity**: medium

### 📘 Rule S044 – Require re-authentication before modifying critical information

- **Objective**: Prevent unauthorized changes to critical information when the session is not fully authenticated. Protect users in half-open session states.
- **Details**:
  - When updating sensitive information (password, email, payment method, access permissions, etc.):
    - Require password re-entry or two-factor authentication (2FA)
    - Do not store any information in session unless fully authenticated
    - If the session is in a temporary state (e.g., OTP not completed or social login not finished), **block access to sensitive resources**
  - On the frontend: redirect the user to the re-authentication screen
- **Applies to**: All languages
- **Tools**: Manual Review, Static Analysis (flow check), Security Test, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S045 – Implement brute-force protection for login

- **Objective**: Prevent brute-force and credential stuffing attacks by limiting failed login attempts and introducing friction for suspicious behavior.
- **Details**:
  - Implement one or more of the following:
    - Limit failed login attempts by IP or account (Rate Limiting)
    - Soft lockout: temporarily lock account (e.g., 15 minutes after 5 failed attempts)
    - Trigger CAPTCHA or 2FA after multiple failed attempts
    - Check passwords against breached password lists (e.g., HaveIBeenPwned, zxcvbn)
  - Log all failed login attempts for monitoring and alerting
- **Applies to**: All languages
- **Tools**: Manual Review, Static Analysis, OWASP ZAP, Custom Logging, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S046 – Use algorithm allowlist for self-contained tokens

- **Objective**: Prevent algorithm confusion and downgrade attacks by restricting token signing/verification to an explicit allowlist of algorithms.
- **Details**:
  - **Must use algorithm allowlist**:
    - Define permitted algorithms explicitly for each context
    - Validate algorithm before processing token
    - Reject tokens using algorithms not in allowlist
  - **Critical requirement**:
    - **Never** allow the `none` algorithm
    - Prefer either symmetric OR asymmetric algorithms, not both
  - **If both symmetric and asymmetric needed**:
    - Implement key type validation
    - Prevent key confusion attacks (using symmetric key as asymmetric)
    - Use separate key stores for different algorithm types
  - **Recommended algorithms**:
    - Symmetric: HS256, HS384, HS512
    - Asymmetric: RS256, RS384, RS512, ES256, ES384, ES512
  - Validate algorithm in token header matches expected algorithm before verification.
- **Applies to**: All languages
- **Tools**: JWT Debugger, Static Analysis, Manual Code Review, Security Test
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: critical

### 📘 Rule S047 – Protect OAuth code flow against CSRF attacks

- **Objective**: Prevent browser-based CSRF attacks that could trigger unauthorized OAuth token requests by implementing PKCE or state parameter validation.
- **Details**:
  - **OAuth code flow CSRF protection methods**:
    - **PKCE (Proof Key for Code Exchange)** - Recommended:
      - Generate cryptographically random `code_verifier`
      - Send `code_challenge` (hash of verifier) in authorization request
      - Send `code_verifier` in token request
      - Server validates challenge matches verifier
    - **State parameter**:
      - Generate unique, unpredictable `state` value
      - Send `state` in authorization request
      - Validate `state` in callback matches sent value
      - Bind state to user session
  - **Requirements**:
    - Use PKCE for all public clients (SPAs, mobile apps)
    - Use state parameter as minimum for confidential clients
    - Never reuse state or PKCE values
  - Reject authorization responses without valid state/PKCE.
- **Applies to**: All languages
- **Tools**: OAuth Security Testing, Manual Code Review, OWASP ZAP
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S048 – Validate OAuth redirect URIs with exact string comparison

- **Objective**: Prevent OAuth redirect attacks by validating redirect URIs against a client-specific allowlist using exact string comparison, not pattern matching.
- **Details**:
  - **Redirect URI validation requirements**:
    - Use exact string comparison (no wildcards, no patterns)
    - Validate against pre-registered URIs only
    - Each OAuth client must have its own allowlist
  - **Do NOT allow**:
    - Wildcard redirects (`*.example.com`)
    - Partial matching (`example.com/callback*`)
    - Open redirects to any URL
    - Localhost in production (except for development clients)
  - **Pre-registration process**:
    - Register all valid redirect URIs during client creation
    - Require admin approval for URI changes
    - Audit redirect URI changes
  - **Common attack patterns blocked**:
    - Subdomain takeover (`attacker.example.com`)
    - Path traversal in redirect
    - Parameter injection in URI
- **Applies to**: All languages
- **Tools**: OAuth Security Testing, Manual Config Review, Penetration Testing
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: critical

### 📘 Rule S049 – Authentication codes must expire quickly

- **Objective**: Ensure that OTPs, reset tokens, and activation links expire quickly to reduce risk of interception or reuse.
- **Details**:
  - Authentication codes must:
    - Expire quickly (⏱ recommended: **5–10 minutes**)
    - Be **automatically invalidated** after expiration
    - Be **one-time use only**
  - Do not accept expired or reused codes
  - For critical actions (reset password, email verification), require re-authentication after code validation
- **Applies to**: All languages
- **Tools**: Manual Review, Static Analysis, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S050 – Reference tokens must be unique with 128-bit entropy using CSPRNG

- **Objective**: Ensure reference tokens (session tokens, opaque tokens) are unpredictable and resistant to brute-force attacks by using cryptographically secure generation.
- **Details**:
  - **Token requirements**:
    - Generated using CSPRNG (Cryptographically Secure Pseudo-Random Number Generator)
    - Minimum **128 bits of entropy** (recommended: 256 bits)
    - Must be unique across all active sessions
  - **Secure generation methods**:
    - Node.js: `crypto.randomBytes(32)`
    - Python: `secrets.token_hex(32)`
    - Java: `SecureRandom`
    - Go: `crypto/rand`
  - **Do NOT use**:
    - `Math.random()` or similar non-cryptographic RNG
    - Sequential or predictable patterns
    - User-derivable values (username, timestamp alone)
    - Short tokens (< 128 bits)
  - Store tokens securely (hashed if possible) and transmit only over TLS.
  - Implement token rotation and expiration policies.
- **Applies to**: All languages
- **Tools**: Static Analysis, Security Audit, CSPRNG Verification, Manual Code Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S051 – Support 12–64 character passwords; reject >128 characters

- **Objective**: Allow users to use strong passphrases while preventing resource abuse from excessively long inputs.
- **Details**:
  - Accept passwords with **12–64 characters**
    - Support strong passphrases (e.g. `correct horse battery staple`)
  - **Reject passwords >128 characters** to:
    - Prevent DoS from large inputs
    - Avoid poor hash performance on long strings
  - Optionally warn users if password <12 characters
- **Applies to**: All languages
- **Tools**: Manual Review, Static Analysis, Unit Test, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S052 – OTPs must have at least 20-bit entropy

- **Objective**: Ensure OTPs are strong enough to resist brute-force or statistical guessing attacks.
- **Details**:
  - OTP must have minimum **20-bit entropy**, equivalent to **6-digit random numbers** (`000000–999999`)
  - Generate OTPs using **CSPRNG**
  - Avoid using `Math.random()` or insecure generators
  - Alphanumeric or longer OTPs increase entropy and are preferred
- **Applies to**: All languages
- **Tools**: Manual Review, Unit Test, Static Analysis, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S053 – Return generic error messages, hide internal details

- **Objective**: Prevent exposure of sensitive internal system data by returning generic error messages to consumers when unexpected or security-sensitive errors occur.
- **Details**:
  - **Never expose to consumers**:
    - Stack traces or exception details
    - Database queries or SQL errors
    - Secret keys, tokens, or credentials
    - Internal file paths or system configuration
    - Server version or technology stack details
  - **Return generic messages**:
    - "An unexpected error occurred. Please try again later."
    - "Request could not be processed."
    - Use error codes for support reference (e.g., `ERR-12345`)
  - **Internal handling**:
    - Log full error details server-side for debugging
    - Include correlation IDs in logs for traceability
    - Use structured logging with proper log levels
  - Differentiate between client errors (4xx) and server errors (5xx) without leaking details.
- **Applies to**: All languages
- **Tools**: Static Analysis, Penetration Testing, Error Response Audit, Manual Code Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S054 – Avoid using default accounts like "admin", "root", "sa"

- **Objective**: Prevent brute-force attacks and ensure traceability and accountability in auditing. Avoid predictable, shared accounts lacking identity association.
- **Details**:
  - Do not use default or common account names (e.g., admin, root, sa, test, guest, etc.).
  - Each user must have a separate account with role-based access control.
  - Force password change on first use or system initialization.
  - The system must log all login attempts and resource access per specific user.
- **Applies to**: All languages
- **Tools**: Manual Review, CI Security Audit, IAM Policy Scan, SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S055 – Validate input Content-Type in REST services

- **Objective**: Prevent attacks via malformed or improperly handled data by validating incoming data format (e.g., JSON, XML).
- **Details**:
  - REST services must check the Content-Type HTTP header to ensure data format matches expectations (e.g., `application/json`, `application/xml`).
  - Reject requests with incorrect or unsupported Content-Type.
  - Avoid processing `text/plain`, `multipart/form-data` unless explicitly required.
  - Log rejected requests due to invalid Content-Type to detect attacks or client issues early.
- **Applies to**: All languages
- **Tools**: Manual Review, API Gateway Config, Static Code Analysis (Semgrep), SonarQube (custom rule)
- **Principles**: SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S056 – Protect against Log Injection attacks

- **Objective**: Prevent attackers from injecting fake log entries that distort tracking or exploit log analysis systems.
- **Details**:
  - Do not log user input directly without sanitization.
  - Escape special characters like: `\n`, `\r`, `%`, `\t`, `"`, `'`, `[`, `]`, etc.
  - Use structured logging (e.g., JSON) to detect anomalies more easily.
  - Avoid `string concatenation` when writing log entries with user input.
- **Applies to**: All languages
- **Tools**: SonarQube, Semgrep, Manual Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S057 – Use synchronized time and UTC in logs

- **Objective**: Ensure consistent, accurate log timestamps to support auditing, investigation, and cross-system comparison.
- **Details**:
  - Always use UTC timezone for logging to avoid issues with local offsets or daylight saving.
  - Configure system time sync via NTP (Network Time Protocol).
  - Verify all backends, logging middleware, and log collectors use standard formats (`ISO 8601`, `UTC`, `RFC3339`, etc.).
  - Helps unify log data across services and regions.
- **Applies to**: All languages
- **Tools**: Manual Review, Audit Logging Middleware, Centralized Logging Tools (ELK, Fluentd, Datadog), SonarQube (custom rule)
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S058 – Protect applications from SSRF attacks

- **Objective**: Prevent Server-Side Request Forgery (SSRF) and protect internal networks or cloud metadata services from unauthorized access via untrusted input.
- **Details**:
  - Always validate URLs or network addresses from client input or HTTP metadata.
  - Apply allow lists for:
    - Valid protocols: only allow `https`, `http`
    - Specific domains or trusted internal IP ranges
    - Allowed ports (avoid sensitive ones like 22, 3306, 6379, etc.)
  - Block access to:
    - `127.0.0.1`, `::1` (localhost)
    - `169.254.169.254` (AWS metadata)
    - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16` if not needed
  - Limit timeouts and disallow redirects unless required.
- **Applies to**: All languages
- **Tools**: SonarQube, Manual Review, Burp Suite Test
- **Principles**: SECURITY
- **Version**: 1.0
- **Status**: activated
- **Severity**: medium

### 📘 Rule S059 – Disable debug modes in production environments

- **Objective**: Prevent exposure of debugging features and information leakage by ensuring all debug modes are disabled in production environments.
- **Details**:
  - **Debug features to disable in production**:
    - Framework debug modes (Django `DEBUG=False`, Flask `debug=False`)
    - Detailed error pages with stack traces
    - Debug endpoints (`/debug`, `/trace`, `/actuator`)
    - SQL query logging to responses
    - Verbose logging that exposes sensitive data
  - **Common debug indicators to check**:
    - `DEBUG=true` in environment variables
    - Development server warnings in logs
    - Source maps exposed in frontend
    - Test/mock endpoints accessible
  - **Verification steps**:
    - Audit configuration files for debug settings
    - Test error responses for information leakage
    - Check HTTP headers for debug information
    - Review CI/CD pipelines for proper environment separation
  - Use environment-specific configurations, never deploy development configs to production.
- **Applies to**: All languages
- **Tools**: Configuration Audit, Penetration Testing, OWASP ZAP, Environment Checker
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: high

### 📘 Rule S060 – Enforce minimum password length of 8 characters, recommend 15+

- **Objective**: Ensure user-set passwords meet minimum length requirements to provide adequate security against brute-force and dictionary attacks.
- **Details**:
  - **Minimum requirements**:
    - Passwords must be at least **8 characters** in length
    - A minimum of **15 characters is strongly recommended** for better security
  - **Implementation guidelines**:
    - Enforce 8-character minimum at registration and password change
    - Display strength indicator encouraging longer passwords
    - Show recommendation for 15+ characters without blocking shorter valid passwords
  - **Rationale**:
    - 8 characters: baseline protection against common attacks
    - 15+ characters: significantly increases resistance to brute-force
    - Longer passwords (passphrases) are easier to remember and more secure
  - **User experience considerations**:
    - Provide real-time feedback on password strength
    - Suggest passphrase approach (e.g., "correct horse battery staple")
    - Do not impose complex character requirements that reduce usability
  - Combine with other password policies (breach detection, no common passwords).
- **Applies to**: All languages
- **Tools**: Static Analysis, Unit Test, Password Strength Libraries (zxcvbn), Manual Review
- **Principles**: CODE_QUALITY, SECURITY
- **Version**: 2.0
- **Status**: activated
- **Severity**: medium
