@sun-asterisk/sunlint 1.1.7 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/.sunlint.json +1 -1
  2. package/CHANGELOG.md +83 -0
  3. package/README.md +66 -4
  4. package/config/presets/all.json +125 -0
  5. package/config/presets/beginner.json +16 -8
  6. package/config/presets/ci.json +12 -4
  7. package/config/presets/maintainability.json +38 -0
  8. package/config/presets/performance.json +32 -0
  9. package/config/presets/quality.json +103 -0
  10. package/config/presets/recommended.json +36 -12
  11. package/config/presets/security.json +88 -0
  12. package/config/presets/strict.json +15 -5
  13. package/config/rules/rules-registry-generated.json +6312 -0
  14. package/config/rules-summary.json +1941 -0
  15. package/core/adapters/sunlint-rule-adapter.js +452 -0
  16. package/core/analysis-orchestrator.js +4 -4
  17. package/core/config-manager.js +28 -5
  18. package/core/rule-selection-service.js +52 -55
  19. package/docs/CONFIGURATION.md +111 -3
  20. package/docs/LANGUAGE-SPECIFIC-RULES.md +308 -0
  21. package/docs/README.md +3 -0
  22. package/docs/STANDARDIZED-CATEGORY-FILTERING.md +156 -0
  23. package/engines/eslint-engine.js +92 -2
  24. package/engines/heuristic-engine.js +8 -31
  25. package/origin-rules/common-en.md +1320 -0
  26. package/origin-rules/dart-en.md +289 -0
  27. package/origin-rules/java-en.md +60 -0
  28. package/origin-rules/kotlin-mobile-en.md +453 -0
  29. package/origin-rules/reactjs-en.md +102 -0
  30. package/origin-rules/security-en.md +1055 -0
  31. package/origin-rules/swift-en.md +449 -0
  32. package/origin-rules/typescript-en.md +136 -0
  33. package/package.json +6 -5
  34. package/scripts/copy-rules.js +86 -0
  35. package/rules/README.md +0 -252
  36. package/rules/common/C002_no_duplicate_code/analyzer.js +0 -65
  37. package/rules/common/C002_no_duplicate_code/config.json +0 -23
  38. package/rules/common/C003_no_vague_abbreviations/analyzer.js +0 -418
  39. package/rules/common/C003_no_vague_abbreviations/config.json +0 -35
  40. package/rules/common/C006_function_naming/analyzer.js +0 -349
  41. package/rules/common/C006_function_naming/config.json +0 -86
  42. package/rules/common/C010_limit_block_nesting/analyzer.js +0 -389
  43. package/rules/common/C013_no_dead_code/analyzer.js +0 -206
  44. package/rules/common/C014_dependency_injection/analyzer.js +0 -338
  45. package/rules/common/C017_constructor_logic/analyzer.js +0 -314
  46. package/rules/common/C019_log_level_usage/analyzer.js +0 -362
  47. package/rules/common/C019_log_level_usage/config.json +0 -121
  48. package/rules/common/C029_catch_block_logging/analyzer.js +0 -373
  49. package/rules/common/C029_catch_block_logging/config.json +0 -59
  50. package/rules/common/C031_validation_separation/analyzer.js +0 -186
  51. package/rules/common/C041_no_sensitive_hardcode/analyzer.js +0 -292
  52. package/rules/common/C042_boolean_name_prefix/analyzer.js +0 -300
  53. package/rules/common/C043_no_console_or_print/analyzer.js +0 -304
  54. package/rules/common/C047_no_duplicate_retry_logic/analyzer.js +0 -351
  55. package/rules/common/C075_explicit_return_types/analyzer.js +0 -103
  56. package/rules/common/C076_single_test_behavior/analyzer.js +0 -121
  57. package/rules/docs/C002_no_duplicate_code.md +0 -57
  58. package/rules/docs/C031_validation_separation.md +0 -72
  59. package/rules/index.js +0 -149
  60. package/rules/migration/converter.js +0 -385
  61. package/rules/migration/mapping.json +0 -164
  62. package/rules/security/S026_json_schema_validation/analyzer.js +0 -251
  63. package/rules/security/S026_json_schema_validation/config.json +0 -27
  64. package/rules/security/S027_no_hardcoded_secrets/analyzer.js +0 -263
  65. package/rules/security/S027_no_hardcoded_secrets/config.json +0 -29
  66. package/rules/security/S029_csrf_protection/analyzer.js +0 -264
  67. package/rules/tests/C002_no_duplicate_code.test.js +0 -50
  68. package/rules/universal/C010/generic.js +0 -0
  69. package/rules/universal/C010/tree-sitter-analyzer.js +0 -0
  70. package/rules/utils/ast-utils.js +0 -191
  71. package/rules/utils/base-analyzer.js +0 -98
  72. package/rules/utils/pattern-matchers.js +0 -239
  73. package/rules/utils/rule-helpers.js +0 -264
  74. package/rules/utils/severity-constants.js +0 -93
@@ -0,0 +1,1055 @@
1
+ # 📘 Security Specific Coding Rules
2
+
3
+ > This is a comprehensive list of security rules designed to enhance the security posture of applications.
4
+ > Each rule includes a title, detailed description, applicable programming languages, and priority level.
5
+
6
+ ### 📘 Rule S001 – Fail securely when access control errors occur
7
+
8
+ - **Objective**: Ensure the system does not accidentally grant access when errors occur, helping to reduce the risk of unauthorized access and protect sensitive resources.
9
+ - **Details**:
10
+ - When errors occur in access control checks (e.g., query errors, runtime exceptions), the system must deny access instead of granting default permissions.
11
+ - Must not fall back to "allow" state if permission data is missing or logic errors occur.
12
+ - Access control mechanisms must fail in a "deny by default" manner.
13
+ - **Applies to**: All languages
14
+ - **Tools**: SonarQube (S4524), PMD (SecurityCodeGuidelines), Manual Review, Unit Test
15
+ - **Principles**: CODE_QUALITY, SECURITY
16
+ - **Version**: 1.0
17
+ - **Status**: activated
18
+ - **Severity**: critical
19
+
20
+ ### 📘 Rule S002 – Avoid IDOR vulnerabilities in CRUD operations
21
+
22
+ - **Objective**: Prevent unauthorized access to sensitive data by verifying users' actual access rights, avoiding reliance solely on IDs in URLs.
23
+ - **Details**:
24
+ - Must not control permissions based solely on `id` sent from the client.
25
+ - Always verify resource ownership at the backend (authorization logic).
26
+ - Prefer using UUID or encrypted IDs to avoid predictable sequential IDs.
27
+ - Check APIs like: `GET/PUT/DELETE /api/resource/{id}` must ensure the id belongs to the current user.
28
+ - **Applies to**: All languages
29
+ - **Tools**: SonarQube (S6142, S2076), Semgrep (custom rule), Manual Review
30
+ - **Principles**: CODE_QUALITY, SECURITY
31
+ - **Version**: 1.0
32
+ - **Status**: activated
33
+ - **Severity**: critical
34
+
35
+ ### 📘 Rule S003 – URL redirects must be within an allow list
36
+
37
+ - **Objective**: Prevent Open Redirect vulnerabilities, protecting users from being redirected to malicious pages through spoofed input.
38
+ - **Details**:
39
+ - Must not redirect to URLs received from user input without validation.
40
+ - If dynamic redirects are needed, must check URLs against an allow list before execution.
41
+ - If the URL is outside the allow list, you can:
42
+ - Reject the redirect (HTTP 400)
43
+ - Or display a clear warning before continuing.
44
+ - **Applies to**: All languages
45
+ - **Tools**: Semgrep (custom rule), Manual Review, SonarQube (custom rule)
46
+ - **Principles**: SECURITY
47
+ - **Version**: 1.0
48
+ - **Status**: activated
49
+ - **Severity**: low
50
+
51
+ ### 📘 Rule S004 – Do not log login credentials, payment information, and unencrypted tokens
52
+
53
+ - **Objective**: Prevent leakage of sensitive information through log systems – a common attack vector if logs are shared, stored incorrectly, or exploited.
54
+ - **Details**:
55
+ - Must not log fields like: `password`, `access_token`, `credit_card`, `cvv`, `secret_key`, etc.
56
+ - Tokens (session tokens, JWT, etc.) if logging is mandatory for debugging, must be hashed or masked (`****`).
57
+ - Avoid logging entire `request.body`, `form-data`, or `headers` containing sensitive information.
58
+ - Ensure logs are configured to exclude sensitive fields.
59
+ - **Applies to**: All languages
60
+ - **Tools**: SonarQube (S2068, S5334), Semgrep (custom rule), Manual Review
61
+ - **Principles**: CODE_QUALITY, SECURITY
62
+ - **Version**: 1.0
63
+ - **Status**: activated
64
+ - **Severity**: medium
65
+
66
+ ### 📘 Rule S005 – Do not use Origin header for authentication or access control
67
+
68
+ - **Objective**: Prevent authentication or authorization decisions based on `Origin` header – which can be easily spoofed from the client side and is unreliable for security purposes.
69
+ - **Details**:
70
+ - `Origin` header can be modified from the client side (via curl, script, proxy), so it must not be used as a basis for:
71
+ - User identification
72
+ - Access permission checks
73
+ - Security business logic routing
74
+ - `Origin` should only be used for source authentication in CSRF checks or CORS policies, **not for authorization decisions**.
75
+ - If behavior needs to be limited by domain, must check against tokens, user sessions, or actually verified scopes.
76
+ - **Applies to**: All languages
77
+ - **Tools**: Manual Review, Semgrep (custom rule), SonarQube (custom rule)
78
+ - **Principles**: CODE_QUALITY, SECURITY
79
+ - **Version**: 1.0
80
+ - **Status**: activated
81
+ - **Severity**: low
82
+
83
+ ### 📘 Rule S006 – Do not send recovery or activation codes in plaintext
84
+
85
+ - **Objective**: Prevent leakage of verification codes, recovery codes, or activation tokens if email/SMS is intercepted or exposed – thereby minimizing the risk of account takeover attacks.
86
+ - **Details**:
87
+ - Should not send recovery or activation codes in predictable formats, sequential numbers, or containing user identifying information.
88
+ - Codes sent via email/SMS must be random codes with short time-to-live (TTL), verified one-way by the system (hashed) or verified by session.
89
+ - Should not store plaintext codes in database or log sent code content.
90
+ - Prefer verification via temporary encrypted one-time links.
91
+ - **Applies to**: All languages
92
+ - **Tools**: Manual Review, Semgrep (custom rule), Secret Detection (regex scanner), SonarQube (custom rule)
93
+ - **Principles**: CODE_QUALITY, SECURITY
94
+ - **Version**: 1.0
95
+ - **Status**: activated
96
+ - **Severity**: medium
97
+
98
+ ### 📘 Rule S007 – Do not store OTP codes in plaintext
99
+
100
+ - **Objective**: Protect the system from OTP reuse attacks if database/logs are accessed without authorization. OTP, magic-links, or reset codes must be treated like passwords – only stored in one-way hashed form, not recoverable.
101
+ - **Details**:
102
+ - Must not store OTP codes, reset tokens, or magic-link codes in original form (plaintext) in database or log files.
103
+ - OTP should have short TTL (e.g., 5 minutes) and be stored using hash functions like SHA-256.
104
+ - During verification, should only compare hashed versions.
105
+ - Never resend original OTP to user if already stored – generate new code if needed.
106
+ - **Applies to**: All languages
107
+ - **Tools**: Manual Review, Semgrep (custom rule), Secret Detection, SonarQube (custom rule)
108
+ - **Principles**: CODE_QUALITY, SECURITY
109
+ - **Version**: 1.0
110
+ - **Status**: activated
111
+ - **Severity**: medium
112
+
113
+ ### 📘 Rule S008 – Encryption algorithms and parameters must support flexible configuration and upgrades (crypto agility)
114
+
115
+ - **Objective**: Avoid binding the system to outdated cryptographic algorithms or parameters (like MD5, SHA-1, DES...), ensuring easy upgrades when standards change or new vulnerabilities emerge.
116
+ - **Details**:
117
+ - Do not hardcode algorithms or encryption modes in source code.
118
+ - Components like encryption algorithms, key size, hash rounds, cipher modes... should be configured via files or environment variables.
119
+ - Prefer using modern algorithms like AES-GCM, SHA-256, Argon2, ChaCha20.
120
+ - Algorithm changes should not require modifying core logic in code.
121
+ - **Applies to**: All languages
122
+ - **Tools**: Manual Review, Semgrep (custom rule), Secret Scanners, SonarQube (custom rule)
123
+ - **Principles**: CODE_QUALITY, MAINTAINABILITY, SECURITY
124
+ - **Version**: 1.0
125
+ - **Status**: activated
126
+ - **Severity**: low
127
+
128
+ ### 📘 Rule S009 – Do not use insecure encryption modes, padding, or cryptographic algorithms
129
+
130
+ - **Objective**: Prevent security vulnerabilities from using outdated encryption or hash algorithms, insecure padding/encryption modes leading to data exposure, pattern leakage, or padding oracle attacks.
131
+ - **Details**:
132
+ - Do not use ECB mode in symmetric encryption (AES/3DES/Blowfish), as it reveals identical data patterns.
133
+ - Avoid insecure padding like `PKCS#1 v1.5` in RSA, vulnerable to padding oracle attacks.
134
+ - Do not use encryption algorithms with block size < 128-bit like `Triple-DES`, `Blowfish`, vulnerable to brute-force and collision attacks.
135
+ - Do not use weak hash functions that have been broken like `MD5`, `SHA-1`.
136
+ - In cases requiring backward compatibility (legacy), must isolate and clearly warn.
137
+ - **Applies to**: All languages
138
+ - **Tools**: SonarQube (S2070, S4790, S5547), Semgrep (crypto rules), Manual Review
139
+ - **Principles**: CODE_QUALITY, SECURITY
140
+ - **Version**: 1.0
141
+ - **Status**: activated
142
+ - **Severity**: medium
143
+
144
+ ### 📘 Rule S010 – Must use cryptographically secure random number generators (CSPRNG) for security purposes
145
+
146
+ - **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.
147
+ - **Details**:
148
+ - Absolutely do not use `Math.random()` or similar functions for security values.
149
+ - Always use functions designed for cryptographic purposes, e.g.: `crypto.randomBytes()`, `SecureRandom`, `secrets`, `crypto/rand`, etc.
150
+ - Applies to: OTP codes, password reset tokens, session IDs, magic links, temporary file names, security GUIDs...
151
+ - Ensure generated values are sufficiently long (entropy ≥ 128 bits) and non-repeating.
152
+ - **Applies to**: All languages
153
+ - **Tools**: SonarQube (S2245), Semgrep (random-insecure), Manual Review
154
+ - **Principles**: CODE_QUALITY, SECURITY
155
+ - **Version**: 1.0
156
+ - **Status**: activated
157
+ - **Severity**: high
158
+
159
+ ### 📘 Rule S011 – GUIDs used for security purposes must be generated according to UUID v4 standard with CSPRNG
160
+
161
+ - **Objective**: Prevent guessing, recreation, or exploitation of GUIDs when used as identifiers for sensitive resources, by ensuring GUIDs are generated according to UUID v4 standard with cryptographically secure random number generators (CSPRNG).
162
+ - **Details**:
163
+ - Avoid using UUID v1 as it may leak MAC address and timestamp.
164
+ - Do not use UUID v3/v5 as they are based on hash from input → can be recreated if input is known.
165
+ - UUID v4 must be randomly generated (random-based), using CSPRNG.
166
+ - Mandatory when GUID is used as: password reset ID, session ID, magic link, API key, authentication token...
167
+ - **Applies to**: All languages
168
+ - **Tools**: Manual Review, Semgrep (uuid version rules), Static Analyzer, SonarQube (custom rule)
169
+ - **Principles**: CODE_QUALITY, SECURITY
170
+ - **Version**: 1.0
171
+ - **Status**: activated
172
+ - **Severity**: high
173
+
174
+ ### 📘 Rule S012 – Protect secrets and encrypt sensitive data
175
+
176
+ - **Objective**: Protect encryption keys, passwords, access tokens, API keys... from exposure through source code, `.env` files, or logs. Ensure sensitive data is always encrypted and keys are managed securely through Key Vault or HSM.
177
+ - **Details**:
178
+ - Do not store private keys, JWT secrets, passwords in `.env` files, config JSON, YAML without encryption or strict access management.
179
+ - Absolutely do not hardcode secrets in source code (even test keys).
180
+ - Must use secure secret management systems like AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, GCP Secret Manager, or HSM.
181
+ - Sensitive data like payment information, passwords, PII must be encrypted before storing in database or storage.
182
+ - Logs must exclude or obfuscate secret information.
183
+ - **Applies to**: All languages
184
+ - **Tools**: SonarQube (S2068, S5547), GitLeaks, TruffleHog, Semgrep (hardcoded-secrets), Secret Scanner CI/CD
185
+ - **Principles**: SECURITY
186
+ - **Version**: 1.0
187
+ - **Status**: activated
188
+ - **Severity**: medium
189
+
190
+ ### 📘 Rule S013 – Always use TLS for all connections
191
+
192
+ - **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.
193
+ - **Details**:
194
+ - Absolutely do not allow HTTP communication for any API, login forms, or personal data (PII).
195
+ - TLS mandatory for all:
196
+ - Frontend → backend communication (browser, mobile)
197
+ - Backend → third-party API communication
198
+ - Service-to-service communication
199
+ - Disable debug/localhost unencrypted modes in production.
200
+ - Enable HSTS (HTTP Strict Transport Security) on frontend to enforce HTTPS.
201
+ - **Applies to**: All languages
202
+ - **Tools**: OWASP ZAP, SSLyze, Lighthouse, Static Analyzer (Semgrep/ESLint), Manual Review, SonarQube (custom rule)
203
+ - **Principles**: CODE_QUALITY, SECURITY
204
+ - **Version**: 1.0
205
+ - **Status**: activated
206
+ - **Severity**: high
207
+
208
+ ### 📘 Rule S014 – Only use TLS 1.2 or 1.3
209
+
210
+ - **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.
211
+ - **Details**:
212
+ - TLS 1.0 and 1.1 are no longer supported by modern browsers and systems.
213
+ - Older versions are vulnerable to downgrade attacks or encryption vulnerability exploitation.
214
+ - Need explicit configuration on backend applications, reverse proxy (NGINX, Apache), and any SSL clients.
215
+ - Prefer default configuration as TLS 1.3 if supported.
216
+ - **Applies to**: All languages
217
+ - **Tools**: SSLyze, testssl.sh, OWASP ZAP, Manual Review, Configuration Scanner
218
+ - **Principles**: CODE_QUALITY, SECURITY
219
+ - **Version**: 1.0
220
+ - **Status**: activated
221
+ - **Severity**: medium
222
+
223
+ ### 📘 Rule S015 – Only accept trusted TLS certificates and eliminate weak ciphers
224
+
225
+ - **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.
226
+ - **Details**:
227
+ - 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).
228
+ - Absolutely do not accept any certificate automatically (e.g., `rejectUnauthorized: false`, `InsecureSkipVerify: true`).
229
+ - Disable outdated cipher suites like RC4, 3DES, NULL cipher, or those using MD5, SHA1.
230
+ - Prefer modern ciphers like AES-GCM, ChaCha20-Poly1305, TLS_ECDHE.
231
+ - Use tools like [SSL Labs](https://www.ssllabs.com/ssltest/), `testssl.sh`, or `nmap --script ssl-enum-ciphers` to scan TLS configuration.
232
+ - **Applies to**: All languages
233
+ - **Tools**: SSL Labs, testssl.sh, nmap ssl-enum-ciphers, Manual Review
234
+ - **Principles**: SECURITY
235
+ - **Version**: 1.0
236
+ - **Status**: activated
237
+ - **Severity**: medium
238
+
239
+ ### 📘 Rule S016 – Do not pass sensitive data via query string
240
+
241
+ - **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.
242
+ - **Details**:
243
+ - Do not put authentication tokens, passwords, OTP codes, personal information (PII) in query strings like `GET /api/reset?token=...`
244
+ - Data in query strings is easily:
245
+ - Logged by server/proxy/load balancer
246
+ - Cached in browser, proxy
247
+ - Saved in history, bookmarks
248
+ - Only pass sensitive data through:
249
+ - HTTP body (POST/PUT)
250
+ - Custom headers (Authorization, X-Token, ...)
251
+ - **Applies to**: All languages
252
+ - **Tools**: Semgrep (hardcoded query pattern), Manual Review, Proxy log scanner, SonarQube (custom rule)
253
+ - **Principles**: SECURITY
254
+ - **Version**: 1.0
255
+ - **Status**: activated
256
+ - **Severity**: high
257
+
258
+ ### 📘 Rule S017 – Always use parameterized queries
259
+
260
+ - **Objective**: Prevent various forms of injection (SQL Injection, HQL Injection, NoSQL Injection) by always using parameterized queries or ORM when accessing data.
261
+ - **Details**:
262
+ - Must not directly concatenate user input values into queries.
263
+ - Use secure query mechanisms such as:
264
+ - `?`, `$1`, `:param`, or binding in ORM
265
+ - Entity Framework, JPA, Sequelize, GORM, etc.
266
+ - For NoSQL (MongoDB, Firebase...), should not use raw JS queries based on string input.
267
+ - If absolutely unavoidable to use parameters, must properly escape input according to the engine being used (not recommended).
268
+ - **Applies to**: All languages
269
+ - **Tools**: SonarQube (S2077, S3649), Semgrep (injection rules), CodeQL, Manual Review
270
+ - **Principles**: CODE_QUALITY, SECURITY
271
+ - **Version**: 1.0
272
+ - **Status**: activated
273
+ - **Severity**: critical
274
+
275
+ ### 📘 Rule S018 – Prefer Allow List for Input Validation
276
+
277
+ - **Objective**: Ensure all user inputs or external data sources are strictly validated by accepting only known good values. This reduces the risk of attacks like XSS, SQL Injection, and other security issues caused by malformed or unexpected input.
278
+ - **Details**:
279
+ - Always use an **Allow List** to validate input values – only allow explicitly defined values or types (e.g., positive integers, valid emails, safe strings).
280
+ - Avoid using **Deny Lists** because:
281
+ - They are prone to bypass due to incomplete coverage.
282
+ - They fail to catch new or unknown attack patterns.
283
+ - Apply to all input sources, including:
284
+ - HTML form fields
285
+ - URL parameters, HTTP headers, cookies
286
+ - REST API payloads or batch file inputs
287
+ - RSS feeds, webhook payloads, etc.
288
+ - Validation should be based on:
289
+ - Data types (number, string, boolean)
290
+ - Specific patterns (regex, enums)
291
+ - Range or length restrictions
292
+ - Use standard validation libraries where available:
293
+ - `class-validator`, `joi`, `yup`, `express-validator` (JavaScript)
294
+ - `javax.validation` (Java), `FluentValidation` (C#), `Cerberus` (Python), etc.
295
+ - **Applies to**: All languages
296
+ - **Tools**: Static Analysis (Semgrep, SonarQube), Manual Review, Input Validation Libraries
297
+ - **Principles**: SECURITY
298
+ - **Version**: 1.0
299
+ - **Status**: activated
300
+ - **Severity**: medium
301
+
302
+ ### 📘 Rule S019 – Sanitize input before sending emails to prevent SMTP Injection
303
+ - **Objective**: Prevent SMTP/IMAP injection by removing control characters and ensuring proper formatting of user input used in email sending.
304
+ - **Details**:
305
+ - SMTP Injection occurs when input contains `\r`, `\n` which can inject new lines or alter email content.
306
+ - Risks: hidden email sending, modified content, header spoofing, or spam.
307
+ - Prevention:
308
+ - Strip or reject control characters (`\n`, `\r`) in `to`, `subject`, `cc`, `bcc`, `reply-to`.
309
+ - Validate email format strictly before use.
310
+ - Prefer using secure email APIs like SendGrid, Amazon SES, Mailgun instead of direct SMTP protocol.
311
+ - **Applies to**: All languages
312
+ - **Tools**: Semgrep (regex match), Manual Review, Static Analysis, SonarQube (custom rule)
313
+ - **Principles**: SECURITY
314
+ - **Version**: 1.0
315
+ - **Status**: activated
316
+ - **Severity**: medium
317
+
318
+ ### 📘 Rule S020 – Avoid using `eval()` or executing dynamic code
319
+ - **Objective**: Prevent Remote Code Execution (RCE) by disallowing use of dynamic code execution functions like `eval()`, `Function()`, `exec()`, `Runtime.exec()` with user-controlled input.
320
+ - **Details**:
321
+ - Functions like `eval()`, `exec()`, `new Function()`, or `setTimeout(..., string)` allow arbitrary code execution, dangerous with untrusted input.
322
+ - Attackers can execute system commands, read files, or manipulate databases remotely.
323
+ - Alternatives to `eval`:
324
+ - Object mapping or switch-case for dynamic logic
325
+ - JSON parsing for data structures
326
+ - `safe-eval` library (only within a sandboxed scope)
327
+ - **Applies to**: All languages
328
+ - **Tools**: Semgrep (eval-detection rules), ESLint (`no-eval`), SonarQube (S1523), Static Analyzer
329
+ - **Principles**: SECURITY
330
+ - **Version**: 1.0
331
+ - **Status**: activated
332
+ - **Severity**: high
333
+
334
+ ### 📘 Rule S021 – Sanitize user-generated Markdown, CSS, and XSL content
335
+ - **Objective**: Prevent script injection via user-generated content in Markdown, CSS, or XSL.
336
+ - **Details**:
337
+ - Attackers may abuse Markdown parser or render engine to inject JS, malicious links, or dangerous attributes (`onload`, `style=...`).
338
+ - For XSL, non-sandboxed processing or external entity access can lead to XXE or XSLT injection.
339
+ - Prevention:
340
+ - Use libraries like `marked.js`, `markdown-it` with `sanitize: true` or XSS filter plugins.
341
+ - Avoid rendering tags like `style`, `script`, `iframe`, or `javascript:` URLs.
342
+ - For CSS/XSL, use sandboxed rendering engines and escape output before rendering.
343
+ - **Applies to**: All languages
344
+ - **Tools**: DOMPurify, sanitize-html, markdown-it, Bandit (Python), Manual Review, SonarQube (custom rule)
345
+ - **Principles**: CODE_QUALITY, SECURITY
346
+ - **Version**: 1.0
347
+ - **Status**: activated
348
+ - **Severity**: medium
349
+
350
+ ### 📘 Rule S022 – Escape data properly based on output context
351
+ - **Objective**: Prevent XSS, Header Injection, Email Injection by escaping output data according to context (HTML, JS, URL, Header, Email, etc).
352
+ - **Details**:
353
+ - Use the correct escaping strategy for each context:
354
+ - **HTML content**: escape `&`, `<`, `>`, `"`, `'`
355
+ - **HTML attributes**: escape `"` and `'` values
356
+ - **JavaScript inline**: escape strings to avoid arbitrary execution
357
+ - **URL params**: use `encodeURIComponent()`
358
+ - **HTTP headers**: strip `\r`, `\n` to prevent injection
359
+ - **SMTP email**: filter control characters like `\r`, `\n`, `bcc:` from content
360
+ - Avoid using a single escape function for all cases.
361
+ - **Applies to**: All languages
362
+ - **Tools**: ESLint (`no-script-url`, `react/no-danger`), Bandit, SonarQube (S2076), DOMPurify, Manual Review
363
+ - **Principles**: CODE_QUALITY, SECURITY
364
+ - **Version**: 1.0
365
+ - **Status**: activated
366
+ - **Severity**: medium
367
+
368
+ ### 📘 Rule S023 – Prevent JSON Injection and JSON eval attacks
369
+ - **Objective**: Prevent JavaScript execution via unsafe JSON handling or injection attacks.
370
+ - **Details**:
371
+ - Never use `eval()` to process JSON from users.
372
+ - Use proper JSON parsers:
373
+ - JavaScript: `JSON.parse()`
374
+ - Python: `json.loads()`
375
+ - Java: `Gson`, `Jackson`, `ObjectMapper`
376
+ - When rendering raw JSON into HTML, escape dangerous sequences like `</script>` or `</`.
377
+ - Validate data before embedding JSON into `<script>` tags.
378
+ - **Applies to**: All languages
379
+ - **Tools**: ESLint (`no-eval`), Semgrep (`eval-dynamic`, `json-injection`), Bandit, SonarQube (S1523), Manual Review
380
+ - **Principles**: CODE_QUALITY, SECURITY
381
+ - **Version**: 1.0
382
+ - **Status**: activated
383
+ - **Severity**: high
384
+
385
+ ### 📘 Rule S024 – Protect against XPath Injection and XML External Entity (XXE)
386
+ - **Objective**: Prevent XPath injection and XXE vulnerabilities that can expose files, trigger SSRF, or run malicious code.
387
+ - **Details**:
388
+ - **XPath Injection**:
389
+ - Never inject user data directly into XPath queries.
390
+ - Use parameterized APIs or safe XPath binding mechanisms.
391
+ - **XXE**:
392
+ - Disable external entity processing in XML parsers to prevent local file access or SSRF.
393
+ - Disable general and parameter entity processing in DOM/SAX/lxml parsers.
394
+ - **Applies to**: All languages
395
+ - **Tools**: Semgrep (xpath injection), Bandit (Python), SonarQube (S2755), Manual Config Review
396
+ - **Principles**: SECURITY
397
+ - **Version**:
398
+ - **Status**: draft
399
+ - **Severity**: medium
400
+
401
+ ### 📘 Rule S025 – Always validate client-side data on the server
402
+ - **Objective**: Ensure all data from clients is validated server-side to prevent attacks from forged or malicious input.
403
+ - **Details**:
404
+ - Client-side validation is only for UX – it can be bypassed.
405
+ - Server-side validation is the last defense before DB writes or API calls.
406
+ - Benefits:
407
+ - Blocks SQLi, XSS, Buffer Overflow, SSRF
408
+ - Preserves data integrity (valid enums, length limits, etc.)
409
+ - Testable via unit tests
410
+ - Recommended libraries:
411
+ - Java: Hibernate Validator, Spring `@Valid`
412
+ - Node.js: Joi, express-validator
413
+ - Python: pydantic, marshmallow
414
+ - **Applies to**: All languages
415
+ - **Tools**: SonarQube (S5334), ESLint (`require-validate`), Bandit (Python), Static Analysis
416
+ - **Principles**: CODE_QUALITY, SECURITY
417
+ - **Version**: 1.0
418
+ - **Status**: activated
419
+ - **Severity**: medium
420
+
421
+ ### 📘 Rule S026 – Apply JSON Schema Validation to input data
422
+ - **Objective**: Ensure all incoming JSON is fully validated by schema (structure, types, constraints) before processing.
423
+ - **Details**:
424
+ - JSON schema can enforce:
425
+ - Required fields, type enforcement
426
+ - Constraints like length, min/max values, format checks
427
+ - Reduce injection risk or logic bugs from malformed JSON
428
+ - Language-specific tools:
429
+ - Java: use Jackson + Hibernate Validator (`@Valid`, `@Email`, `@Min`)
430
+ - JavaScript: use `ajv`, `joi`
431
+ - Python: use `jsonschema`, `pydantic`
432
+ - Go: use `gojsonschema`
433
+ - C#: use `NJsonSchema`
434
+ - **Applies to**: All languages
435
+ - **Tools**: AJV, jsonschema, Joi, Pydantic, Hibernate Validator, SonarQube (custom rule), Manual Review
436
+ - **Principles**: CODE_QUALITY, SECURITY
437
+ - **Version**: 1.0
438
+ - **Status**: activated
439
+ - **Severity**: medium
440
+
441
+ ### 📘 Rule S027 – Never expose secrets in source code or Git
442
+ - **Objective**: Prevent leakage of credentials, API keys, tokens, or sensitive config via source code or version control.
443
+ - **Details**:
444
+ - Common leak sources:
445
+ - `.env`, `config.yaml`, `secrets.json`, or hardcoded values like `API_KEY`, `JWT_SECRET`
446
+ - Mitigation:
447
+ - Use `.gitignore` to exclude secret files
448
+ - Scan commits with GitLeaks, TruffleHog, detect-secrets
449
+ - Add pre-commit hooks to block secret-containing files
450
+ - If leaked, rotate keys, revoke tokens, and clean Git history
451
+ - Additional notes:
452
+ - Avoid plaintext secrets in CI/CD pipelines
453
+ - Store secrets in a secure vault (e.g., AWS Secrets Manager, HashiCorp Vault)
454
+ - **Applies to**: All languages
455
+ - **Tools**: GitLeaks, TruffleHog, detect-secrets, git-secrets, SonarQube (custom rule)
456
+ - **Principles**: CODE_QUALITY, SECURITY
457
+ - **Version**: 1.0
458
+ - **Status**: activated
459
+ - **Severity**: medium
460
+
461
+ ### 📘 Rule S028 – Limit upload file size and number of files per user
462
+ - **Objective**: Prevent resource abuse and protect against DoS attacks by limiting file size, number of files, and user storage usage.
463
+ - **Details**:
464
+ - Must enforce limits on:
465
+ - **Maximum file size** (e.g., ≤ 10MB)
466
+ - **Total number of files** per user or per upload
467
+ - **Total storage quota per user** (if applicable)
468
+ - Limits should be:
469
+ - Enforced on both client-side and server-side (server is mandatory)
470
+ - Handled via HTTP layer or upload middleware
471
+ - Logged when violations occur for abuse tracking
472
+ - Technology examples:
473
+ - Node.js: `multer` (`limits.fileSize`, `fileFilter`)
474
+ - Python: `Flask-Limiter`, request body size limit
475
+ - Java: Spring's `multipart.maxFileSize`, `maxRequestSize`
476
+ - Nginx/nginx-ingress: `client_max_body_size`
477
+ - **Applies to**: All languages
478
+ - **Tools**: Manual Review, Static Analysis, API Gateway Limit, Nginx Config, WAF, SonarQube (custom rule)
479
+ - **Principles**: CODE_QUALITY, SECURITY
480
+ - **Version**: 1.0
481
+ - **Status**: activated
482
+ - **Severity**: medium
483
+
484
+ ### 📘 Rule S029 – Apply CSRF protection for authentication-related features
485
+ - **Objective**: Prevent Cross-Site Request Forgery (CSRF) attacks where an attacker triggers unauthorized actions using the victim's authenticated session.
486
+ - **Details**:
487
+ - CSRF occurs when:
488
+ - Victim is logged in (cookies exist)
489
+ - Browser automatically sends cookies with attacker-forged requests
490
+ - **Protection mechanisms**:
491
+ - **CSRF Token**: Generate a unique token (per session/request), attach it in form or header, and validate server-side
492
+ - **SameSite Cookie**:
493
+ - `SameSite=Lax`: suitable for most form-based POST requests
494
+ - `SameSite=Strict`: most secure, may affect UX
495
+ - `SameSite=None; Secure`: required for cross-domain cookies (must use HTTPS)
496
+ - **2FA or re-authentication** for critical actions like changing email/password or performing transactions
497
+ - For API or SPA:
498
+ - Avoid storing access tokens in cookies
499
+ - Prefer using `Authorization: Bearer <token>` to eliminate CSRF risk
500
+ - **Applies to**: All languages
501
+ - **Tools**: Spring Security CSRF, Express `csurf`, Django CSRF middleware, Helmet.js, Manual Review, SonarQube (custom rule)
502
+ - **Principles**: CODE_QUALITY, SECURITY
503
+ - **Version**: 1.0
504
+ - **Status**: activated
505
+ - **Severity**: high
506
+
507
+ ### 📘 Rule S030 – Disable directory browsing and protect sensitive metadata files
508
+ - **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.
509
+ - **Details**:
510
+ - Directory browsing occurs if no `index.html` exists or misconfigured server
511
+ - Sensitive files may be exposed if not explicitly blocked, e.g.:
512
+ - `.git/config` → contains repo URL or credentials
513
+ - `.env` → secrets
514
+ - `.DS_Store`, `Thumbs.db`, `.svn` → folder structure leaks
515
+ - **Mitigation**:
516
+ - Disable `autoindex` or `Indexes` on the web server (Apache/Nginx)
517
+ - Deny access to metadata or dotfiles (`.git`, `.env`, etc.)
518
+ - Review default config of frameworks (Express, Spring, Django, etc.)
519
+ - Use `.gitignore` to exclude sensitive files from version control
520
+ - **Applies to**: All languages
521
+ - **Tools**: Static Analysis, Manual Review, Burp Suite, Nikto, SonarQube (custom rule)
522
+ - **Principles**: CODE_QUALITY, SECURITY
523
+ - **Version**: 1.0
524
+ - **Status**: activated
525
+ - **Severity**: medium
526
+
527
+ ### 📘 Rule S031 – Set the Secure flag on session cookies for HTTPS protection
528
+ - **Objective**: Prevent attackers from stealing session cookies via unencrypted HTTP, especially on public or monitored networks (MITM).
529
+ - **Details**:
530
+ - If a **cookie lacks the `Secure` flag**, it may be sent over plain HTTP
531
+ - Attackers on public Wi-Fi or LAN may intercept session tokens
532
+ - Sensitive cookies should always include:
533
+ - `Secure`: only send via HTTPS
534
+ - `HttpOnly`: prevent JS access
535
+ - `SameSite`: control CSRF exposure
536
+ - **Best practices**:
537
+ - Use HTTPS in all environments (dev, staging, prod)
538
+ - Ensure web server enforces HTTP → HTTPS redirects
539
+ - **Applies to**: All languages
540
+ - **Tools**: OWASP ZAP, Burp Suite, Static Analysis, Manual Review, SonarQube (custom rule)
541
+ - **Principles**: SECURITY
542
+ - **Version**: 1.0
543
+ - **Status**: activated
544
+ - **Severity**: high
545
+
546
+ ### 📘 Rule S032 – Enable HttpOnly attribute for Session Cookies to prevent JavaScript access
547
+
548
+ - **Objective**: Prevent JavaScript (including malicious code during XSS attacks) from accessing session cookies, thereby limiting the risk of theft and session hijacking.
549
+ - **Details**:
550
+ - **Without `HttpOnly`** → JavaScript can call `document.cookie` and read all session data.
551
+ - XSS attacks exploit this vulnerability to steal tokens or cookies.
552
+ - `HttpOnly` is one of the most important security flags along with:
553
+ - `Secure`: only send cookies over HTTPS.
554
+ - `SameSite`: limit CSRF attacks.
555
+ - Combine with:
556
+ - Comprehensive XSS protection (escaping, CSP).
557
+ - Cookie validation in all environments (QA, prod, staging).
558
+ - **Applies to**: All languages
559
+ - **Tools**: Static Analysis, OWASP ZAP, Burp Suite, Manual Review, SonarQube (custom rule)
560
+ - **Principles**: SECURITY
561
+ - **Version**: 1.0
562
+ - **Status**: activated
563
+ - **Severity**: medium
564
+
565
+ ### 📘 Rule S033 – Set SameSite attribute for Session Cookies to reduce CSRF risk
566
+
567
+ - **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.
568
+ - **Details**:
569
+ - **Without `SameSite`**, cookies will be sent in all requests – even when coming from malicious sites → easily exploited in CSRF attacks.
570
+ - `SameSite` values:
571
+ - `Strict`: highest security, does not send cookies when redirected from other sites (best CSRF prevention).
572
+ - `Lax`: common default, allows cookies to be sent with GET navigation requests (form submissions...).
573
+ - `None`: **must be used with `Secure`** if the application needs to work cross-domain (e.g., SPA frontend calling API from different domain).
574
+ - `SameSite` needs to work together with:
575
+ - `HttpOnly` to prevent JS access.
576
+ - `Secure` to only send over HTTPS.
577
+ - Always check that the backend application has set `SameSite` correctly, and cookies are not reset incorrectly due to duplicate headers.
578
+ - **Applies to**: All languages
579
+ - **Tools**: OWASP ZAP, Postman, Static Analysis, Manual Review, SonarQube (custom rule)
580
+ - **Principles**: CODE_QUALITY, SECURITY
581
+ - **Version**: 1.0
582
+ - **Status**: activated
583
+ - **Severity**: medium
584
+
585
+ ### 📘 Rule S034 – Use `__Host-` prefix for Session Cookies to prevent subdomain sharing
586
+
587
+ - **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.
588
+ - **Details**:
589
+ - The `__Host-` prefix enforces:
590
+ - Must include `Secure`
591
+ - Must not specify `Domain` (defaults to root domain)
592
+ - `Path` must be `/`
593
+ - Advantages:
594
+ - Cookie exists only on the root domain (e.g., `example.com`), cannot be overridden by subdomains.
595
+ - Prevents scenarios like:
596
+ - A malicious app on `sub1.example.com` sets a fake `sessionId`, which is then reused on `example.com`.
597
+ - Commonly used for:
598
+ - Session cookies
599
+ - CSRF tokens
600
+ - Auth tokens
601
+ - Limitation:
602
+ - Only applicable over **HTTPS** and must be set from the root domain.
603
+ - **Applies to**: All languages
604
+ - **Tools**: Manual Review, Static Analysis, Chrome DevTools Audit, SonarQube (custom rule)
605
+ - **Principles**: CODE_QUALITY, SECURITY
606
+ - **Version**: 1.0
607
+ - **Status**: activated
608
+ - **Severity**: medium
609
+
610
+ ### 📘 Rule S035 – Set the `Path` attribute for Session Cookies to limit access scope
611
+
612
+ - **Objective**: Reduce the risk of session cookie leaks or abuse across multiple apps under the same domain (e.g., `/app1` and `/app2`) by limiting cookie scope via the `Path` attribute.
613
+ - **Details**:
614
+ - Cookies with `Path=/` are sent with **all requests under the same domain**, including unrelated applications.
615
+ - Risk in shared domain environments:
616
+ - Example: `example.com/app1`, `example.com/app2`
617
+ - Cookie from `app1` will also be sent to `app2` unless `Path` is restricted.
618
+ - Best practices:
619
+ - Set specific `Path` (e.g., `/app1/`) so cookies only work within that path.
620
+ - Avoid empty `Path` (`""`) – which defaults to `/`.
621
+ - **Applies to**: All languages
622
+ - **Tools**: Static Analysis, Manual Review, Chrome DevTools, Postman, SonarQube (custom rule)
623
+ - **Principles**: CODE_QUALITY, SECURITY
624
+ - **Version**: 1.0
625
+ - **Status**: activated
626
+ - **Severity**: medium
627
+
628
+ ### 📘 Rule S036 – Prevent LFI and RFI using path validation and allow-lists
629
+
630
+ - **Objective**: Block Local File Inclusion (LFI) and Remote File Inclusion (RFI) attacks where attackers access sensitive files (e.g., `/etc/passwd`, `C:\Windows\system32`) or execute code from external URLs.
631
+ - **Details**:
632
+ - **LFI**: The app accepts unchecked file paths → attacker reads internal files.
633
+ - **RFI**: The app includes external files from user input → leads to Remote Code Execution.
634
+ - Preventive measures:
635
+ - Use **Allow List** of valid filenames/paths.
636
+ - Never include/load user input directly.
637
+ - Disallow URL usage in include/require/load/open.
638
+ - Disable remote includes (e.g., `allow_url_include=Off` in PHP).
639
+ - Normalize paths to remove `../` (path traversal).
640
+ - Restrict permissions via sandboxing.
641
+ - **Applies to**: All languages
642
+ - **Tools**: Static Analysis, OWASP ZAP, Burp Suite, Manual Review, SonarQube (custom rule)
643
+ - **Principles**: CODE_QUALITY, SECURITY
644
+ - **Version**: 1.0
645
+ - **Status**: activated
646
+ - **Severity**: high
647
+
648
+ ### 📘 Rule S037 – Set anti-cache headers to prevent sensitive data leakage
649
+
650
+ - **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.
651
+ - **Details**:
652
+ - Modern browsers may cache:
653
+ - Filled-in forms
654
+ - Login results
655
+ - Rendered tokens or confidential data
656
+ - Recommended headers:
657
+ - `Cache-Control: no-store, no-cache, must-revalidate`
658
+ - `Pragma: no-cache`
659
+ - `Expires: 0`
660
+ - Use for:
661
+ - Profile lookups, dashboard pages
662
+ - Tokens, session content
663
+ - Check using DevTools → Network → Headers.
664
+ - **Applies to**: All languages
665
+ - **Tools**: Static Analysis, Postman, Chrome DevTools, Manual Review, SonarQube (custom rule)
666
+ - **Principles**: SECURITY
667
+ - **Version**: 1.0
668
+ - **Status**: activated
669
+ - **Severity**: medium
670
+
671
+ ### 📘 Rule S038 – Hide system version information in HTTP Headers
672
+
673
+ - **Objective**: Prevent attackers from discovering backend technologies (e.g., server, framework, OS) via HTTP response headers that can be used to target known vulnerabilities.
674
+ - **Details**:
675
+ - Common leak examples:
676
+ - `Server: nginx/1.23.0`
677
+ - `X-Powered-By: Express`
678
+ - `X-AspNet-Version`, `X-Runtime`, etc.
679
+ - Preventive steps:
680
+ - Disable or override these headers.
681
+ - Use middleware or reverse proxy to strip response headers.
682
+ - Verify using DevTools, curl, or Postman.
683
+ - **Applies to**: All languages
684
+ - **Tools**: Static Analysis, curl, Postman, Chrome DevTools, Burp Suite, SonarQube (custom rule)
685
+ - **Principles**: SECURITY
686
+ - **Version**:
687
+ - **Status**: draft
688
+ - **Severity**: medium
689
+
690
+ ### 📘 Rule S039 – Never transmit Session Tokens via URL parameters
691
+
692
+ - **Objective**: Prevent session hijacking by ensuring session tokens are not stored in browser history, server logs, proxy logs, or leaked via Referrer headers.
693
+ - **Details**:
694
+ - Risks of token in URL (e.g., `https://example.com/dashboard?sessionId=abc123`):
695
+ - Saved in browser history
696
+ - Logged on server/load balancer
697
+ - Leaked via `Referer` to third parties
698
+ - Best practices:
699
+ - Use `Secure`, `HttpOnly` cookies for token storage
700
+ - Use headers or body for API auth – never query string
701
+ - **Applies to**: All languages
702
+ - **Tools**: Static Analysis, Manual Review, Burp Suite, Postman, SonarQube (custom rule)
703
+ - **Principles**: SECURITY
704
+ - **Version**: 1.0
705
+ - **Status**: activated
706
+ - **Severity**: high
707
+
708
+ ### 📘 Rule S040 – Regenerate Session Token after login to prevent Session Fixation
709
+
710
+ - **Objective**: Prevent attackers from setting a session ID before login and taking over the session post-login if the ID remains unchanged.
711
+ - **Details**:
712
+ - Attack scenario:
713
+ - Attacker sets known session ID before login
714
+ - Victim logs in without regenerating session
715
+ - Attacker reuses the same ID for access
716
+ - Preventive actions:
717
+ - Invalidate old session after login and create a new one
718
+ - For JWT: issue new token on login
719
+ - For cookies: delete old session and set a new cookie
720
+ - **Applies to**: All languages
721
+ - **Tools**: Static Analysis, Manual Review, OWASP ZAP, Burp Suite, SonarQube (custom rule)
722
+ - **Principles**: SECURITY
723
+ - **Version**: 1.0
724
+ - **Status**: activated
725
+ - **Severity**: high
726
+
727
+ ### 📘 Rule S041 – Session Tokens must be invalidated after logout or expiration
728
+
729
+ - **Objective**: Prevent users from reusing old session tokens after logout or timeout, which could lead to session hijacking.
730
+ - **Details**:
731
+ - Actions required:
732
+ - **Backend**:
733
+ - Remove session from memory (e.g., Redis)
734
+ - Revoke token or blacklist old JWT
735
+ - **Frontend**:
736
+ - Delete cookie (`document.cookie = ...`, `res.clearCookie(...)`)
737
+ - Remove tokens from localStorage
738
+ - Redirect/reload after logout
739
+ - Add `Cache-Control: no-store` to prevent old content reuse
740
+ - **Applies to**: All languages
741
+ - **Tools**: Static Analysis, Manual Review, Postman, DevTools, SonarQube (custom rule)
742
+ - **Principles**: CODE_QUALITY, SECURITY
743
+ - **Version**: 1.0
744
+ - **Status**: activated
745
+ - **Severity**: medium
746
+
747
+ ### 📘 Rule S042 – Require re-authentication for long-lived sessions or sensitive actions
748
+
749
+ - **Objective**: Reduce the risk of session hijacking or privilege misuse by forcing re-authentication after long idle periods or before critical actions.
750
+ - **Details**:
751
+ - When using persistent login or "Remember Me":
752
+ - Require re-login after X hours (e.g., 12h, 24h)
753
+ - Re-authenticate after inactivity (e.g., 30 mins)
754
+ - Require password or 2FA for sensitive actions (password change, payments)
755
+ - For JWT:
756
+ - Use short-lived tokens with secure refresh logic
757
+ - **Applies to**: All languages
758
+ - **Tools**: Manual Review, Static Analysis (JWT expiry, session policy), Security Test, SonarQube (custom rule)
759
+ - **Principles**: CODE_QUALITY, SECURITY
760
+ - **Version**: 1.0
761
+ - **Status**: activated
762
+ - **Severity**: medium
763
+
764
+ ### 📘 Rule S043 – Password changes must invalidate all other login sessions
765
+
766
+ - **Objective**: Ensure attackers cannot continue using old session tokens after a password change. Enforce correct access control after sensitive updates.
767
+ - **Details**:
768
+ - On password change:
769
+ - Invalidate all other active sessions (except current if necessary)
770
+ - Clear all session tokens from DB, Redis, or memory
771
+ - For JWT: use token versioning or timestamp to revoke old tokens
772
+ - Require re-login across all devices
773
+ - **Applies to**: All languages
774
+ - **Tools**: Manual Review, Static Analysis (Token Revocation Logic), SonarQube (custom rule)
775
+ - **Principles**: CODE_QUALITY, SECURITY
776
+ - **Version**: 1.0
777
+ - **Status**: activated
778
+ - **Severity**: medium
779
+
780
+ ### 📘 Rule S044 – Require re-authentication before modifying critical information
781
+
782
+ - **Objective**: Prevent unauthorized changes to critical information when the session is not fully authenticated. Protect users in half-open session states.
783
+ - **Details**:
784
+ - When updating sensitive information (password, email, payment method, access permissions, etc.):
785
+ - Require password re-entry or two-factor authentication (2FA)
786
+ - Do not store any information in session unless fully authenticated
787
+ - If the session is in a temporary state (e.g., OTP not completed or social login not finished), **block access to sensitive resources**
788
+ - On the frontend: redirect the user to the re-authentication screen
789
+ - **Applies to**: All languages
790
+ - **Tools**: Manual Review, Static Analysis (flow check), Security Test, SonarQube (custom rule)
791
+ - **Principles**: CODE_QUALITY, SECURITY
792
+ - **Version**: 1.0
793
+ - **Status**: activated
794
+ - **Severity**: medium
795
+
796
+ ### 📘 Rule S045 – Implement brute-force protection for login
797
+
798
+ - **Objective**: Prevent brute-force and credential stuffing attacks by limiting failed login attempts and introducing friction for suspicious behavior.
799
+ - **Details**:
800
+ - Implement one or more of the following:
801
+ - Limit failed login attempts by IP or account (Rate Limiting)
802
+ - Soft lockout: temporarily lock account (e.g., 15 minutes after 5 failed attempts)
803
+ - Trigger CAPTCHA or 2FA after multiple failed attempts
804
+ - Check passwords against breached password lists (e.g., HaveIBeenPwned, zxcvbn)
805
+ - Log all failed login attempts for monitoring and alerting
806
+ - **Applies to**: All languages
807
+ - **Tools**: Manual Review, Static Analysis, OWASP ZAP, Custom Logging, SonarQube (custom rule)
808
+ - **Principles**: CODE_QUALITY, SECURITY
809
+ - **Version**: 1.0
810
+ - **Status**: activated
811
+ - **Severity**: medium
812
+
813
+ ### 📘 Rule S046 – Notify users of critical account changes
814
+
815
+ - **Objective**: Alert users to sensitive actions to detect potential compromise and allow timely intervention.
816
+ - **Details**:
817
+ - Notify users when performing actions such as:
818
+ - Password reset
819
+ - Changing email or phone number
820
+ - Login from new devices or suspicious IPs
821
+ - Notification channels: Email, Push Notification, or SMS
822
+ - **Do not include sensitive info** (e.g., password, token, unencrypted links)
823
+ - Log these events for security audit purposes
824
+ - **Applies to**: All languages
825
+ - **Tools**: Manual Review, Security Test, Notification Audit, SonarQube (custom rule)
826
+ - **Principles**: CODE_QUALITY, SECURITY
827
+ - **Version**: 1.0
828
+ - **Status**: activated
829
+ - **Severity**: medium
830
+
831
+ ### 📘 Rule S047 – Secure temporary passwords and activation codes
832
+
833
+ - **Objective**: Ensure that temporary passwords and activation codes are secure, unpredictable, single-use, and time-limited.
834
+ - **Details**:
835
+ - Temporary credentials must:
836
+ - Be randomly generated using CSPRNG
837
+ - Be at least **6 characters long**, and contain **letters and numbers**
838
+ - Have short validity: **15 minutes to 24 hours**
839
+ - Be **one-time use only**
840
+ - **Must not** be used as permanent passwords
841
+ - Additional protection:
842
+ - Store only hashed values if persisted
843
+ - Invalidate after use
844
+ - Disallow regeneration until expired
845
+ - **Applies to**: All languages
846
+ - **Tools**: Manual Review, Static Analysis, Audit Flow, SonarQube (custom rule)
847
+ - **Principles**: CODE_QUALITY, SECURITY
848
+ - **Version**: 1.0
849
+ - **Status**: activated
850
+ - **Severity**: high
851
+
852
+ ### 📘 Rule S048 – Do not expose current password during reset flow
853
+
854
+ - **Objective**: Ensure the current user password is never revealed or sent in any step of the password reset process.
855
+ - **Details**:
856
+ - **Never display or send the current password** to the user
857
+ - Do not email or SMS old passwords
858
+ - During password reset:
859
+ - Only ask for new password (with confirmation)
860
+ - Use OTP/email/token for verification, not current password
861
+ - If changing password while logged in, require **manual entry of current password**, never show it
862
+ - **Applies to**: All languages
863
+ - **Tools**: Manual Review, Penetration Test, SonarQube (custom rule)
864
+ - **Principles**: SECURITY
865
+ - **Version**: 1.0
866
+ - **Status**: activated
867
+ - **Severity**: medium
868
+
869
+ ### 📘 Rule S049 – Authentication codes must expire quickly
870
+
871
+ - **Objective**: Ensure that OTPs, reset tokens, and activation links expire quickly to reduce risk of interception or reuse.
872
+ - **Details**:
873
+ - Authentication codes must:
874
+ - Expire quickly (⏱ recommended: **5–10 minutes**)
875
+ - Be **automatically invalidated** after expiration
876
+ - Be **one-time use only**
877
+ - Do not accept expired or reused codes
878
+ - For critical actions (reset password, email verification), require re-authentication after code validation
879
+ - **Applies to**: All languages
880
+ - **Tools**: Manual Review, Static Analysis, SonarQube (custom rule)
881
+ - **Principles**: CODE_QUALITY, SECURITY
882
+ - **Version**: 1.0
883
+ - **Status**: activated
884
+ - **Severity**: medium
885
+
886
+ ### 📘 Rule S050 – Session tokens must have minimum 64-bit entropy and use secure algorithms
887
+
888
+ - **Objective**: Prevent attackers from predicting or forging session tokens by ensuring sufficient length, entropy, and cryptographic safety.
889
+ - **Details**:
890
+ - Session tokens must have at least **64-bit entropy**, recommended: **128-bit or 256-bit**
891
+ - Use approved cryptographic algorithms:
892
+ - HMAC-SHA-256
893
+ - AES-256
894
+ - ChaCha20
895
+ - Avoid weak algorithms:
896
+ - MD5
897
+ - SHA-1
898
+ - Do not generate tokens using `Math.random()` or short guessable strings
899
+ - Always use CSPRNG for token generation
900
+ - **Applies to**: All languages
901
+ - **Tools**: Manual Review, Static Analysis, SonarQube (custom rule)
902
+ - **Principles**: CODE_QUALITY, SECURITY
903
+ - **Version**: 1.0
904
+ - **Status**: activated
905
+ - **Severity**: medium
906
+
907
+ ### 📘 Rule S051 – Support 12–64 character passwords; reject >128 characters
908
+
909
+ - **Objective**: Allow users to use strong passphrases while preventing resource abuse from excessively long inputs.
910
+ - **Details**:
911
+ - Accept passwords with **12–64 characters**
912
+ - Support strong passphrases (e.g. `correct horse battery staple`)
913
+ - **Reject passwords >128 characters** to:
914
+ - Prevent DoS from large inputs
915
+ - Avoid poor hash performance on long strings
916
+ - Optionally warn users if password <12 characters
917
+ - **Applies to**: All languages
918
+ - **Tools**: Manual Review, Static Analysis, Unit Test, SonarQube (custom rule)
919
+ - **Principles**: CODE_QUALITY, SECURITY
920
+ - **Version**: 1.0
921
+ - **Status**: activated
922
+ - **Severity**: medium
923
+
924
+ ### 📘 Rule S052 – OTPs must have at least 20-bit entropy
925
+
926
+ - **Objective**: Ensure OTPs are strong enough to resist brute-force or statistical guessing attacks.
927
+ - **Details**:
928
+ - OTP must have minimum **20-bit entropy**, equivalent to **6-digit random numbers** (`000000–999999`)
929
+ - Generate OTPs using **CSPRNG**
930
+ - Avoid using `Math.random()` or insecure generators
931
+ - Alphanumeric or longer OTPs increase entropy and are preferred
932
+ - **Applies to**: All languages
933
+ - **Tools**: Manual Review, Unit Test, Static Analysis, SonarQube (custom rule)
934
+ - **Principles**: CODE_QUALITY, SECURITY
935
+ - **Version**: 1.0
936
+ - **Status**: activated
937
+ - **Severity**: medium
938
+
939
+ ### 📘 Rule S053 – Only use secure OTP algorithms like HOTP/TOTP
940
+
941
+ - **Objective**: Ensure OTPs are secure against spoofing and replay attacks by using safe, standard algorithms.
942
+ - **Details**:
943
+ - **Do not use**:
944
+ - Weak algorithms like `MD5`, `SHA-1` (deprecated)
945
+ - OTPs without expiration or usage limits
946
+ - **Use standards**:
947
+ - `HOTP` (HMAC-based OTP – [RFC 4226](https://datatracker.ietf.org/doc/html/rfc4226))
948
+ - `TOTP` (Time-based OTP – [RFC 6238](https://datatracker.ietf.org/doc/html/rfc6238))
949
+ - Recommended libraries:
950
+ - `PyOTP` (Python), `otplib` (Node.js), `Google Authenticator` SDK (Java)
951
+ - Always enforce time-based expiration (typically 30–300 seconds)
952
+ - **Applies to**: All languages
953
+ - **Tools**: Manual Review, Unit Test, Static Analysis, SonarQube (custom rule)
954
+ - **Principles**: CODE_QUALITY, SECURITY
955
+ - **Version**: 1.0
956
+ - **Status**: activated
957
+ - **Severity**: medium
958
+
959
+ ### 📘 Rule S054 – Avoid using default accounts like "admin", "root", "sa"
960
+
961
+ - **Objective**: Prevent brute-force attacks and ensure traceability and accountability in auditing. Avoid predictable, shared accounts lacking identity association.
962
+ - **Details**:
963
+ - Do not use default or common account names (e.g., admin, root, sa, test, guest, etc.).
964
+ - Each user must have a separate account with role-based access control.
965
+ - Force password change on first use or system initialization.
966
+ - The system must log all login attempts and resource access per specific user.
967
+ - **Applies to**: All languages
968
+ - **Tools**: Manual Review, CI Security Audit, IAM Policy Scan, SonarQube (custom rule)
969
+ - **Principles**: CODE_QUALITY, SECURITY
970
+ - **Version**: 1.0
971
+ - **Status**: activated
972
+ - **Severity**: high
973
+
974
+ ### 📘 Rule S055 – Validate input Content-Type in REST services
975
+
976
+ - **Objective**: Prevent attacks via malformed or improperly handled data by validating incoming data format (e.g., JSON, XML).
977
+ - **Details**:
978
+ - REST services must check the Content-Type HTTP header to ensure data format matches expectations (e.g., `application/json`, `application/xml`).
979
+ - Reject requests with incorrect or unsupported Content-Type.
980
+ - Avoid processing `text/plain`, `multipart/form-data` unless explicitly required.
981
+ - Log rejected requests due to invalid Content-Type to detect attacks or client issues early.
982
+ - **Applies to**: All languages
983
+ - **Tools**: Manual Review, API Gateway Config, Static Code Analysis (Semgrep), SonarQube (custom rule)
984
+ - **Principles**: SECURITY
985
+ - **Version**: 1.0
986
+ - **Status**: activated
987
+ - **Severity**: medium
988
+
989
+ ### 📘 Rule S056 – Protect against Log Injection attacks
990
+
991
+ - **Objective**: Prevent attackers from injecting fake log entries that distort tracking or exploit log analysis systems.
992
+ - **Details**:
993
+ - Do not log user input directly without sanitization.
994
+ - Escape special characters like: `\n`, `\r`, `%`, `\t`, `"`, `'`, `[`, `]`, etc.
995
+ - Use structured logging (e.g., JSON) to detect anomalies more easily.
996
+ - Avoid `string concatenation` when writing log entries with user input.
997
+ - **Applies to**: All languages
998
+ - **Tools**: SonarQube, Semgrep, Manual Review
999
+ - **Principles**: CODE_QUALITY, SECURITY
1000
+ - **Version**: 1.0
1001
+ - **Status**: activated
1002
+ - **Severity**: high
1003
+
1004
+ ### 📘 Rule S057 – Use synchronized time and UTC in logs
1005
+
1006
+ - **Objective**: Ensure consistent, accurate log timestamps to support auditing, investigation, and cross-system comparison.
1007
+ - **Details**:
1008
+ - Always use UTC timezone for logging to avoid issues with local offsets or daylight saving.
1009
+ - Configure system time sync via NTP (Network Time Protocol).
1010
+ - Verify all backends, logging middleware, and log collectors use standard formats (`ISO 8601`, `UTC`, `RFC3339`, etc.).
1011
+ - Helps unify log data across services and regions.
1012
+ - **Applies to**: All languages
1013
+ - **Tools**: Manual Review, Audit Logging Middleware, Centralized Logging Tools (ELK, Fluentd, Datadog), SonarQube (custom rule)
1014
+ - **Principles**: CODE_QUALITY, SECURITY
1015
+ - **Version**: 1.0
1016
+ - **Status**: activated
1017
+ - **Severity**: medium
1018
+
1019
+ ### 📘 Rule S058 – Protect applications from SSRF attacks
1020
+
1021
+ - **Objective**: Prevent Server-Side Request Forgery (SSRF) and protect internal networks or cloud metadata services from unauthorized access via untrusted input.
1022
+ - **Details**:
1023
+ - Always validate URLs or network addresses from client input or HTTP metadata.
1024
+ - Apply allow lists for:
1025
+ - Valid protocols: only allow `https`, `http`
1026
+ - Specific domains or trusted internal IP ranges
1027
+ - Allowed ports (avoid sensitive ones like 22, 3306, 6379, etc.)
1028
+ - Block access to:
1029
+ - `127.0.0.1`, `::1` (localhost)
1030
+ - `169.254.169.254` (AWS metadata)
1031
+ - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16` if not needed
1032
+ - Limit timeouts and disallow redirects unless required.
1033
+ - **Applies to**: All languages
1034
+ - **Tools**: SonarQube, Manual Review, Burp Suite Test
1035
+ - **Principles**: SECURITY
1036
+ - **Version**: 1.0
1037
+ - **Status**: activated
1038
+ - **Severity**: medium
1039
+
1040
+ ### 📘 Rule S059 – Configure Allow List for server-side outbound requests
1041
+
1042
+ - **Objective**: Reduce risks from the server making outbound requests to untrusted systems (SSRF, malicious downloads, data leaks).
1043
+ - **Details**:
1044
+ - All outbound connections (HTTP, FTP, DNS, etc.) must be restricted via allow lists.
1045
+ - Do not let the server freely access the internet or unknown domains by default.
1046
+ - Example restrictions:
1047
+ - Only allow sending files to trusted storage or domains like `https://trusted.example.com`.
1048
+ - Containers may only use DNS for allowed addresses.
1049
+ - In cloud/serverless environments, restrict outbound traffic using IAM policies, security groups, or network ACLs.
1050
+ - **Applies to**: All languages
1051
+ - **Tools**: Manual Config Review, Firewall/Proxy Logs, CloudTrail, Burp Suite Test, SonarQube (custom rule)
1052
+ - **Principles**: SECURITY
1053
+ - **Version**: 1.0
1054
+ - **Status**: activated
1055
+ - **Severity**: low