Files
pruefwerk/compliance-agent/rules/vendor/gitlab/pack.yaml
sharangandClaude Opus 5.5 d406741907
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m13s
CI / Deploy Agent (push) Successful in 6m21s
feat(sast): vendored MIT semgrep packs and a guard against registry rules (#492) (#504)
Our ~35 own rules left whole languages without SAST findings. Three
permissively licensed community packs now run next to them, on the same
semgrep invocation (--metrics=off, local files only):

- GitLab sast-rules v2.10.1 (53bf5cf6): 148 rules for C#, Java,
  JavaScript/TypeScript, Python and one Go rule; only files whose header says
  "License: MIT (c) GitLab Inc.". Not vendored: c/ (every file GPL-2.0,
  generated from flawfinder), go/ apart from one file (Apache-2.0 gosec
  ports), scala/, rules/lgpl, rules/lgpl-cc (Commons Clause), rules/gitlab (EE).
- 0xdea semgrep-rules (dae50da6, MIT): 35 C/C++ rules.
- elttam semgrep-rules (24426856, MIT; its LICENSE carries the Semgrep
  template's copyright line): 34 rules for Java, Go and Struts/Spring XML.

Each pack lives in compliance-agent/rules/vendor/<source>/ with LICENSE,
NOTICE (provenance, what was left out and why) and UPSTREAM (pinned commit):
upstream/ holds the selected files unchanged with their tests, pack.yaml the
rules the agent runs, ids prefixed per source (gitlab-, 0xdea-, elttam-),
rules.json an index for the tests. scripts/vendor-semgrep-rules.py
regenerates all of it deterministically.

Provenance: every candidate rule was compared with the Semgrep registry
(semgrep/semgrep-rules, read only for the comparison). Eight GitLab Python/JS
rules with the same message or the same patterns are not vendored, nor are
elttam's Kubernetes rules (registry-derived). Also left out: elttam's
entrypoint enumerators, its ORM-leak hints, three files whose upstream
tests fail on semgrep 1.177 and a join-mode rule.

Noise budget: run over the nightly fixtures, the public samples and
FreeRTOS-Kernel, lwIP, OpenRA, eShopOnWeb, requests, express and
spring-petclinic. 15 rules that flood real code (0xdea missing-return 1514
hits, typos 989, interesting-api-calls 718, signed-unsigned-conversion 221,
suspicious-assert 176, format-string-bugs 61 ...; GitLab assert-used) are
dropped from the pack, each listed with its reason in NOTICE. CPU time of
the semgrep run roughly doubles on C-heavy trees (FreeRTOS-Kernel 70 s ->
136 s, lwIP 18 s -> 68 s), well inside the 10-minute stage timeout.

Ids stay bare (#473 logic covers the vendored ids, fingerprint() unchanged).
The control map gets one vendored semgrep binding per control, by CWE (by
rule id for the few elttam rules without one), with exactly the languages of
the rules behind it; a test checks every vendored rule maps to a control
that claims its languages.

Guard: semgrep_args() builds the one invocation; a test fails if any
--config is not a staged local pack, or is auto, p/, r/ or a URL, and
another scans the agent source, scripts, docker/, CI and Dockerfile.agent for
a registry config.

Nightly baselines with C, Python, C# or JS code change and need a bless run
after the image is deployed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-06 12:22:50 +00:00

9454 lines
419 KiB
YAML

# GitLab SAST rules, vendored by scripts/vendor-semgrep-rules.py; do not edit.
# Upstream: https://gitlab.com/gitlab-org/security-products/sast-rules at 53bf5cf6df3c51b6c02110f5a638b5e6213666cd
# Licence: MIT (per-file header `License: MIT (c) GitLab Inc.`); see LICENSE and NOTICE next to this file.
# Changed from upstream: ids prefixed with 'gitlab-', rules
# left out as listed in NOTICE, rules re-serialised into one file.
rules:
- id: gitlab-csharp_cookies_rule-CookieWithoutHttpOnlyFlag
languages: [csharp]
mode: taint
pattern-sources:
- pattern: 'var $COOKIE = new HttpCookie(...);
'
pattern-sinks:
- pattern: $COOKIE
pattern-sanitizers:
- pattern: $COOKIE.HttpOnly = true;
message: 'The `HttpOnly` attribute when set to `true` protects the cookie value from being accessed by
client side JavaScript such
as reading the `document.cookie` values. By enabling this protection, a website that is
vulnerable to
Cross-Site Scripting (XSS) will be able to block malicious scripts from accessing the cookie
value from JavaScript.
Example of protecting an HttpCookie:
```
// Create an HttpOnly cookie.
HttpCookie someCookie = new HttpCookie("SomeCookieName", "SomeValue");
someCookie.HttpOnly = true;
```
For more information see:
https://learn.microsoft.com/en-us/dotnet/api/system.web.httpcookie.httponly
Session cookies should be configured with the following security directives:
- [HTTPOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies)
- [Secure](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies)
- [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite)
'
severity: WARNING
metadata:
shortDescription: Sensitive cookie without 'HttpOnly' flag
category: security
owasp:
- A5:2017-Broken Access Control
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
cwe: CWE-1004
security-severity: Low
- id: gitlab-csharp_cookies_rule-CookieWithoutSSLFlag
languages: [csharp]
mode: taint
pattern-sources:
- pattern: 'var $COOKIE = new HttpCookie(...);
'
pattern-sinks:
- pattern: $COOKIE
pattern-sanitizers:
- pattern: $COOKIE.Secure = true;
message: 'The `Secure` attribute when set to `true` protects the cookie value from being being
transmitted over clear text
communication paths such as HTTP. By enabling this protection, the cookie will only be sent
over HTTPS.
Example of protecting an HttpCookie:
```
// Create an HttpOnly cookie.
HttpCookie someCookie = new HttpCookie("SomeCookieName", "SomeValue");
someCookie.Secure = true;
```
For more information see:
https://learn.microsoft.com/en-us/dotnet/api/system.web.httpcookie.secure
Session cookies should be configured with the following security directives:
- [HTTPOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies)
- [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite)
- [Secure](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies)
'
severity: WARNING
metadata:
shortDescription: Sensitive cookie in HTTPS session without 'Secure' attribute
category: security
owasp:
- A3:2017-Sensitive Data Exposure
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
cwe: CWE-614
security-severity: Low
- id: gitlab-csharp_crypto_rule-CertificateValidationDisabled
languages: [csharp]
patterns:
- pattern-inside: 'using System.Net;
...
'
- pattern: ServicePointManager.ServerCertificateValidationCallback += $CALLBACK;
- metavariable-pattern:
metavariable: $CALLBACK
patterns:
- pattern-either:
- pattern: $RETURNTYPE $FUNC(...) { return true; }
- pattern: (...) => true;
message: 'The `ServicePointManager.ServerCertificateValidationCallback` event has been set
to always return `true`, which effectively disables the validation of server
certificates.
This allows for an adversary who is in between the application and the target host to intercept
potentially sensitive information or transmit malicious data.
Remove the callback function that is returning true to allow normal certificate validation to
proceed.
When no callback is provided, the client will validate that the certificate name matches the
hostname
that was used when creating the request.
For more information on the `ServerCertificateValidationCallback` property see:
https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.servercertificatevalidationcallback
'
severity: WARNING
metadata:
shortDescription: Certificate validation disabled
category: security
owasp:
- A3:2017-Sensitive Data Exposure
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
cwe: CWE-295
security-severity: Medium
- id: gitlab-csharp_crypto_rule-WeakCipherAlgorithm
languages: [csharp]
patterns:
- pattern-inside: 'using System.Security.Cryptography;
...
'
- pattern-either:
- pattern-regex: .*DES\.Create\(\);
- pattern: new DESCryptoServiceProvider();
- pattern-regex: .*TripleDES\.Create\(\);
- pattern: new TripleDESCryptoServiceProvider();
- pattern-regex: .*RC2\.Create\(\);
- pattern: new RC2CryptoServiceProvider();
message: "DES, TripleDES and RC2 are all considered broken or insecure cryptographic algorithms.\nIf using\
\ .NET Framework greater than version 6.0 consider using `ChaCha20Poly1305`\ninstead as it is easier\
\ and faster than the alternatives such as `AES-256-GCM`.\n\nFor older applications, `AES-256-GCM` is\
\ recommended, however it has many drawbacks:\n- Slower than `ChaCha20Poly1305`.\n- Catastrophic failure\
\ if nonce values are reused.\n\nExample using `ChaCha20Poly1305`:\n```\n// Generate a random key\n\
byte[] key = new byte[32];\nRandomNumberGenerator.Fill(key);\n\n// Note nonce values _must_ be regenerated\
\ every time they are used.\nbyte[] nonce = new byte[12];\nRandomNumberGenerator.Fill(nonce);\n\nbyte[]\
\ authTag = new byte[16];\nbyte[] cipherText;\n\nusing (ChaCha20Poly1305 encryptor = new ChaCha20Poly1305(key))\n\
{\n byte[] plainText = System.Text.Encoding.UTF8.GetBytes(\"Secret text to encrypt\");\n cipherText\
\ = new byte[plainText.Length];\n encryptor.Encrypt(nonce, plainText, cipherText, authTag);\n}\n\n\
using (ChaCha20Poly1305 decryptor = new ChaCha20Poly1305(key))\n{\n byte[] output = new byte[cipherText.Length];\n\
\ decryptor.Decrypt(nonce, cipherText, authTag, output);\n Console.WriteLine(\"Output: {0}\",\
\ System.Text.Encoding.UTF8.GetString(output));\n}\n```\n\nExample using `AES-256-GCM`:\n```\n// Generate\
\ a random key\nbyte[] key = new byte[32];\nRandomNumberGenerator.Fill(key);\n\n// Note nonce values\
\ _must_ be regenerated every time they are used.\nbyte[] nonce = new byte[AesGcm.NonceByteSizes.MaxSize];\n\
RandomNumberGenerator.Fill(nonce);\n\nbyte[] authTag = new byte[AesGcm.TagByteSizes.MaxSize];\nbyte[]\
\ cipherText;\n\nusing (AesGcm encryptor = new AesGcm(key))\n{\n byte[] plainText = Encoding.UTF8.GetBytes(\"\
Secret text to encrypt\");\n cipherText = new byte[plainText.Length];\n encryptor.Encrypt(nonce,\
\ plainText, cipherText, authTag);\n}\n\nusing (AesGcm decryptor = new AesGcm(key))\n{\n byte[] output\
\ = new byte[cipherText.Length];\n decryptor.Decrypt(nonce, cipherText, authTag, output);\n Console.WriteLine(\"\
Output: {0}\", Encoding.UTF8.GetString(output));\n}\n```\n"
severity: WARNING
metadata:
shortDescription: Use of a broken or risky cryptographic algorithm
category: security
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
cwe: CWE-327
security-severity: Medium
- id: gitlab-csharp_crypto_rule-WeakCipherMode
languages: [csharp]
patterns:
- pattern-inside: 'using System.Security.Cryptography;
...
'
- metavariable-regex:
metavariable: $CIPHER
regex: ^(ECB|CBC|OFB|CFB|CTS)$
- pattern: CipherMode.$CIPHER
message: "Cryptographic algorithms provide many different modes of operation, only some of which provide\n\
message integrity. Without message integrity it could be possible for an adversary to attempt\nto tamper\
\ with the ciphertext which could lead to compromising the encryption key. Newer\nalgorithms\napply\
\ message integrity to validate ciphertext has not been tampered with.\n\nInstead of using an algorithm\
\ that requires configuring a `CipherMode`, an algorithm\nthat has built-in message integrity should\
\ be used. If using .NET Framework greater\nthan version 6.0 consider using `ChaCha20Poly1305` or `AES-256-GCM`.\n\
\nFor older applications, `AES-256-GCM` is recommended, however it has many drawbacks:\n- Slower than\
\ `ChaCha20Poly1305`.\n- Catastrophic failure if nonce values are re-used.\n\nExample using `ChaCha20Poly1305`:\n\
```\n// Generate a random key\nbyte[] key = new byte[32];\nRandomNumberGenerator.Fill(key);\n\nChaCha20Poly1305\
\ encryptor = new ChaCha20Poly1305(key);\n\n// Note nonce values _must_ be regenerated every time they\
\ are used.\nvar nonce = new byte[12];\nRandomNumberGenerator.Fill(nonce);\n\nbyte[] plainText = System.Text.Encoding.UTF8.GetBytes(\"\
Secret text to encrypt\");\nbyte[] cipherText = new byte[plainText.Length];\nvar authTag = new byte[16];\n\
\nencryptor.Encrypt(nonce, plainText, cipherText, authTag);\nbyte[] output = new byte[cipherText.Length];\n\
encryptor.Decrypt(nonce, cipherText, authTag, output);\nConsole.WriteLine(\"Output: {0}\", System.Text.Encoding.UTF8.GetString(output));\n\
```\n\nExample using `AES-256-GCM`:\n```\nvar plaintextBytes = Encoding.UTF8.GetBytes(\"Secret text\
\ to encrypt\");\nvar key = new byte[32];\nRandomNumberGenerator.Fill(key);\n\nusing var aes = new AesGcm(key);\n\
var nonce = new byte[AesGcm.NonceByteSizes.MaxSize];\nRandomNumberGenerator.Fill(nonce);\n\nvar cipherText\
\ = new byte[plaintextBytes.Length];\nvar tag = new byte[AesGcm.TagByteSizes.MaxSize];\n\naes.Encrypt(nonce,\
\ plaintextBytes, cipherText, tag);\n\n// Decrypt\nusing (var decrypt = new AesGcm(key))\n{\n var\
\ decryptedBytes = new byte[cipherText.Length];\n\n decrypt.Decrypt(nonce, cipherText, tag, decryptedBytes);\n\
\n Console.WriteLine(\"Decrypted: {0}\", Encoding.UTF8.GetString(decryptedBytes));\n}\n```\n"
severity: WARNING
metadata:
shortDescription: Use of a broken or risky cryptographic algorithm
category: security
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
cwe: CWE-327
security-severity: Medium
- id: gitlab-csharp_crypto_rule-WeakHashingFunction
languages: [csharp]
patterns:
- pattern-either:
- patterns:
- metavariable-regex:
metavariable: $HASH_PROVIDER
regex: ^(SHA1CryptoServiceProvider|MD5CryptoServiceProvider)$
- pattern: new $HASH_PROVIDER
- patterns:
- metavariable-regex:
metavariable: $HASH_CLASS
regex: ^System.Security.Cryptography.(SHA1|MD5)$
- pattern: $HASH_CLASS.$METHOD();
message: "Both MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions.\n\
This means\nthat two different values, when hashed, can lead to the same hash value. If the application\
\ is\ntrying\nto use these hash methods for storing passwords, then it is recommended to switch to a\n\
password hashing\nalgorithm such as Argon2id or PBKDF2. Currently there is no vetted Argon2id implementation\
\ for\nC# so\nit is recommended that PBKDF2 be used until one is available.\n\nExample using PBKDF2\
\ to generate and compare passwords:\n```\nconst int SaltSize = 24;\nconst int HashSize = 24;\n// number\
\ of pbkdf2 iterations, Rfc2898DeriveBytes uses hmac-sha1\n// so set a high iteration count\nconst int\
\ Iterations = 1_300_000;\nbyte[] salt = new byte[SaltSize];\nRandomNumberGenerator.Fill(salt);\n\n\
Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(\"some password\", salt, Iterations);\nbyte[] hashBytes\
\ = pbkdf2.GetBytes(HashSize);\n// Store salt and hashedBytes in a data store such as database for authentication\n\
Console.WriteLine(\"Hash {0}\", BitConverter.ToString(hashBytes).Replace(\"-\", \"\"));\n// Do a constant\
\ time comparison as to not leak data based on timing\nif (CryptographicOperations.FixedTimeEquals(hashBytes,\
\ hashBytes)) {\n Console.WriteLine(\"hashes are equal\");\n}\n```\nFor more information on PBKDF2\
\ see:\nhttps://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rfc2898derivebytes\n\
\nFor more information on secure password storage see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html\n"
severity: WARNING
metadata:
shortDescription: Use of a broken or risky cryptographic algorithm (SHA1/MD5)
category: security
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
cwe: CWE-327
security-severity: Medium
- id: gitlab-csharp_crypto_rule-WeakRNG
languages: [csharp]
patterns:
- pattern: (Random $RNG).$METHOD(...);
- focus-metavariable: $RNG
message: 'Depending on the context, generating weak random numbers may expose cryptographic functions
which rely on these numbers to be exploitable. When generating numbers for sensitive values
such as tokens, nonces, and cryptographic keys, it is recommended that the
`RandomNumberGenerator` class be used.
Example `RandomNumberGenerator` usage:
```
Int32 randInt = RandomNumberGenerator.GetInt32(32000);
byte[] randomBytes = new byte[64];
RandomNumberGenerator.Fill(randomBytes);
Console.WriteLine("Random Int32: {0}", randInt);
Console.WriteLine("Random Bytes: {0}", BitConverter.ToString(randomBytes).Replace("-", ""));
```
For more information see:
https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator
'
severity: WARNING
metadata:
shortDescription: Use of cryptographically weak Pseudo-Random Number Generator (PRNG)
category: security
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
cwe: CWE-338
security-severity: Medium
- id: gitlab-csharp_csrf_rule-Csrf
languages: [csharp]
patterns:
- pattern: "[$HTTPMETHOD]\npublic $RET $FOO(...) {\n ...\n}\n"
- pattern-not: "[ValidateAntiForgeryToken]\npublic $RET $FOO(...) {\n ...\n}\n"
- pattern-not-inside: "[AutoValidateAntiforgeryToken]\nclass $CLASS{\n ...\n}\n"
- pattern-not-inside: "[ValidateAntiForgeryToken]\nclass $CLASS{\n ...\n}\n"
- metavariable-regex:
metavariable: $HTTPMETHOD
regex: Http(Post|Delete|Patch|Put)
message: 'The application failed to protect against Cross-Site Request Forgery (CSRF)
due to not including the `[ValidateAntiForgeryToken]` attribute on an
HTTP method handler that could change user state (usually in the form of POST or PUT
methods).
The vulnerability can be exploited by an adversary creating a link or form on a third
party site and tricking an authenticated victim to access them.
Add the `[ValidateAntiForgeryToken]` to all methods which take in user data and change
user state (such as updating a database with a new value). This is especially true for
functionality such as updating passwords or other security sensitive functions.
Alternatively, applications can enable a global
[AutoValidateAntiforgeryTokenAttribute](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.autovalidateantiforgerytokenattribute)
filter.
For more information on ValidateAntiForgeryToken and other CSRF protections in .NET
see the following URL:
https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery
Additionally, consider setting all session cookies to have the `SameSite=Strict` attribute.
It should be noted that this may impact usability when sharing links across other mediums.
It is recommended that a two cookie based approach is taken, as outlined in the
[Top level
navigations](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-08#section-8.8.2)
section
of the SameSite RFC.
For more information on CSRF see OWASP''s guide:
https://owasp.org/www-community/attacks/csrf
'
severity: WARNING
metadata:
shortDescription: Potential Cross-Site Request Forgery (CSRF)
category: security
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
cwe: CWE-352
security-severity: Medium
- id: gitlab-csharp_deserialization_rule-InsecureDeserialization
languages: [csharp]
mode: taint
pattern-sources:
- pattern: Request.Cookies[...]
- pattern: Request.Cookies.Get(...)
- pattern: Request.Form[...]
- pattern: Request.Form.Get(...)
- pattern: Request.Headers[...]
- pattern: Request.Headers.Get(...)
- pattern: Request.QueryString[...]
- pattern: Request.QueryString.Get(...)
- pattern: Request.Body
- pattern: $CTX.Request.Cookies[...]
- pattern: $CTX.Request.Cookies.Get(...)
- pattern: $CTX.Request.Form[...]
- pattern: $CTX.Request.Form.Get(...)
- pattern: $CTX.Request.Headers[...]
- pattern: $CTX.Request.Headers.Get(...)
- pattern: $CTX.Request.QueryString[...]
- pattern: $CTX.Request.QueryString.Get(...)
- pattern: $CTX.Request.Body
- pattern: System.IO.File.ReadAllText(...)
- pattern: System.IO.File.ReadAllTextAsync(...)
- pattern: System.IO.File.ReadAllLines(...)
- pattern: System.IO.File.ReadAllLinesAsync(...)
- pattern: System.IO.File.ReadAllBytes(...)
- pattern: System.IO.File.ReadAllBytesAsync(...)
- pattern: System.IO.File.ReadLines(...)
- pattern: System.IO.File.ReadLinesAsync(...)
- pattern: System.Environment.GetEnvironmentVariable(...)
pattern-sinks:
- pattern: (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter $OBJ).Deserialize(...)
- pattern: (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter $OBJ).UnsafeDeserialize(...)
- pattern: (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter $OBJ).UnsafeDeserializeMethod(...)
- pattern: (System.Runtime.Serialization.Formatters.Soap.SoapFormatter $OBJ).Deserialize(...)
- pattern: (System.Runtime.Serialization.NetDataContractSerializer $OBJ).Deserialize(...)
- pattern: (System.Web.UI.LosFormatter $OBJ).Deserialize(...)
message: "Deserialization attacks exploit the process of reading serialized data and turning it back into\
\ an\nobject. By constructing malicious objects and serializing them, an adversary may attempt to:\n\
\n- Inject code that is executed upon object construction, which occurs during the deserialization process.\n\
- Exploit mass assignment by including fields that are not normally a part of the serialized data but\
\ are\n read in during deserialization.\n\nMicrosoft recommends no longer using the following serialization\
\ formats:\n\n- BinaryFormatter\n- SoapFormatter\n- NetDataContractSerializer\n- LosFormatter\n- ObjectStateFormatter\n\
\nConsider safer alternatives such as serializing data in the JSON format. Ensure any format chosen\
\ allows\nthe application to specify exactly which object types are allowed to be deserialized. Additionally,\
\ when\ndeserializing, never deserialize to base object types like `Object` and only cast to the exact\
\ object\ntype that is expected.\n\nTo protect against mass assignment, only allow deserialization of\
\ the specific fields that are required.\nIf this is not easily done, consider creating an intermediary\
\ type that can be serialized with only the\nnecessary fields exposed.\n\nFor more information see Microsoft's\
\ deserialization security guide:\nhttps://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide\n\
\nFor more details on deserialization attacks in general, see OWASP's guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html\n\
\nIt should be noted that [tools exist](https://github.com/pwntester/ysoserial.net) to automatically\
\ create\nexploit code for these vulnerabilities.\n"
metadata:
shortDescription: Deserialization of potentially untrusted data
category: security
cwe: CWE-502
owasp:
- A8:2017-Insecure Deserialization
- A08:2021-Software and Data Integrity Failures
- A08:2025-Software or Data Integrity Failures
security-severity: High
severity: WARNING
- id: gitlab-csharp_endpoint_rule-UnvalidatedRedirect
languages: [csharp]
mode: taint
pattern-sources:
- patterns:
- pattern: $SRC
- pattern-inside: 'public $RET $FUNC(...,$SRC,...){...}
'
- patterns:
- pattern: $SRC
- pattern-inside: 'if (Uri.TryCreate(..., ..., $SRC)){
...
}
'
pattern-sanitizers:
- pattern: Url.Action(...)
- pattern: Url.HttpRouteUrl(...)
- pattern: Url.RouteUrl(...)
pattern-sinks:
- patterns:
- pattern-either:
- patterns:
- pattern-either:
- pattern: return $METHOD(...)
- pattern: return new $METHOD(...)
- pattern: "if (!Url.IsLocalUrl(...)) {\n ...\n return $METHOD(...)\n}\n"
- patterns:
- pattern-not-inside: "if (Url.IsLocalUrl(...)) {\n ...\n}\n"
- pattern-not-inside: "if (!Url.IsLocalUrl(...)) {\n return $X\n}\n...\n"
- pattern-either:
- pattern: $METHOD(...)
- pattern: new $METHOD(...)
- metavariable-pattern:
metavariable: $METHOD
pattern-either:
- pattern: Redirect
- pattern: RedirectPermanent
- pattern: RedirectToRoute
- pattern: RedirectToRoutePermanent
- pattern: RedirectResult
message: 'The application may allow open redirects if created using user supplied input. Open redirects
are
commonly
abused in phishing attacks where the original domain or URL looks like a legitimate link, but
then
redirects a user to a malicious site. An example would be
`https://example.com/redirect?url=https://%62%61%64%2e%63%6f%6d%2f%66%61%6b%65%6c%6f%67%69%6e`
which,
when decoded, turns into `bad.com/fakelogin`.
Never redirect a client based on user input. It is recommended that the list of target links
to
redirect a user to are contained server side, and retrieved using a numerical value
as an index to return the link to be redirected to. For example, `/redirect?id=1` would cause
the
application to look up the `1` index and return a URL such as `https://example.com`. This URL
would
then be used to redirect the user, using the 301 response code and `Location` header.
For more information on open redirects see OWASP''s guide:
https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html
'
metadata:
shortDescription: URL redirection to untrusted site 'open redirect'
category: security
owasp:
- A1:2017-Injection
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
cwe: CWE-601
security-severity: Info
severity: WARNING
- id: gitlab-csharp_injection_rule-CommandInjection
languages: [csharp]
patterns:
- pattern-either:
- patterns:
- pattern-inside: '...
(System.Diagnostics.Process $PROC).Start(...);
'
- pattern-either:
- patterns:
- pattern: (System.Diagnostics.Process $PROC).StartInfo.FileName = <...$ARG...>;
- pattern-not: (System.Diagnostics.Process $PROC).StartInfo.FileName = "...";
- patterns:
- pattern: (System.Diagnostics.Process $PROC).StartInfo.Arguments = <...$ARG...>;
- pattern-not: (System.Diagnostics.Process $PROC).StartInfo.Arguments = "...";
- patterns:
- pattern: System.Diagnostics.Process.Start($ARG);
- pattern-not: System.Diagnostics.Process.Start("...");
- patterns:
- pattern-not: $PSINFO.Arguments = "...";
- pattern-not: $PSINFO.FileName = "...";
- pattern-not: new System.Diagnostics.ProcessStartInfo("...");
- pattern-not: new System.Diagnostics.ProcessStartInfo();
- pattern-either:
- pattern: new System.Diagnostics.ProcessStartInfo(...);
- pattern: $PSINFO.Arguments = <...$ARG...>;
- pattern: $PSINFO.FileName = <...$ARG...>;
- patterns:
- pattern-inside: 'new System.Diagnostics.ProcessStartInfo{
...
}
'
- pattern-not: Arguments = "..."
- pattern-not: FileName = "..."
- pattern-either:
- pattern: Arguments = ...
- pattern: FileName = ...
message: "OS command injection is a critical vulnerability that can lead to a full system\ncompromise\
\ as it may allow an adversary to pass in arbitrary commands or arguments\nto be executed.\n\nUser input\
\ should never be used in constructing commands or command arguments\nto functions which execute OS\
\ commands. This includes filenames supplied by\nuser uploads or downloads.\n\nEnsure your application\
\ does not:\n\n- Use user-supplied information in the process name to execute.\n- Use user-supplied\
\ information in an OS command execution function which does\nnot escape shell meta-characters.\n- Use\
\ user-supplied information in arguments to OS commands.\n\nThe application should have a hardcoded\
\ set of arguments that are to be passed\nto OS commands. If filenames are being passed to these functions,\
\ it is\nrecommended that a hash of the filename be used instead, or some other unique\nidentifier.\
\ It is strongly recommended that a native library that implements\nthe same functionality be used instead\
\ of using OS system commands, due to the\nrisk of unknown attacks against third party commands.\n\n\
When specifying the OS command, ensure the application uses the full path\ninformation, otherwise the\
\ OS may attempt to look up which process to execute\nand could be vulnerable to untrusted search path\
\ vulnerabilities (CWE-426).\n\nExample of safely executing an OS command:\n```\npublic void ExecuteCommand(string\
\ userFileData) {\n // generate a random filename, do not using user input\n string fileName =\
\ \"C:\\\\Temp\\\\\" + Guid.NewGuid();\n File.WriteAllText(fileName, userFileData);\n\n using\
\ (Process process = new Process())\n {\n // hardcode the full process path\n ProcessStartInfo\
\ processInfo = new ProcessStartInfo(\"C:\\\\App\\\\FileReader.exe\");\n // only pass in trust\
\ arguments, and never direct user input.\n processInfo.Arguments = fileName;\n processInfo.UseShellExecute\
\ = false;\n process.StartInfo = processInfo;\n process.Start();\n }\n}\n```\n\nFor\
\ more information on OS command injection, see OWASP's guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html\n"
severity: ERROR
metadata:
shortDescription: Improper neutralization of special elements used in an OS command ('OS Command Injection')
category: security
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
cwe: CWE-78
security-severity: High
- id: gitlab-csharp_injection_rule-LdapInjection
languages: [csharp]
mode: taint
pattern-sources:
- patterns:
- pattern-inside: '$RET $METHOD(...,$VAR,...){...}
'
- pattern: $VAR
pattern-sinks:
- pattern: System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(...)
- pattern: new System.DirectoryServices.DirectoryEntry(...)
- pattern: new System.DirectoryServices.DirectorySearcher(...)
- pattern: new System.DirectoryServices.Protocols.SearchRequest(...)
- patterns:
- focus-metavariable: $TAINTED
- pattern-either:
- pattern: (System.DirectoryServices.DirectoryEntry $SOURCE).Path = $TAINTED
- pattern: (System.DirectoryServices.DirectorySearcher $SEARCHER).Filter = $TAINTED
- pattern: (System.DirectoryServices.Protocols.SearchRequest $SEARCHREQ).Filter = $TAINTED
- pattern: (System.DirectoryServices.Protocols.SearchRequest $SEARCHREQ).DistinguishedName = $TAINTED
- pattern: (System.DirectoryServices.AccountManagement.UserPrincipal $SEARCHREQ).$PROP = $TAINTED
message: "LDAP injection attacks exploit LDAP queries to influence how data is returned by\nthe LDAP,\
\ or in this case an Active Directory server.\n\nIt is recommended that newer applications use the `System.DirectoryServices.AccountManagement`\n\
API instead of `DirectorySearcher` API as it hides the complexity of querying LDAP directly.\nHowever,\n\
the `AccountManagement` API is still susceptible to LDAP injection if a user inputs LDAP\nqueries,\n\
including LDAP filter characters such as `*`.\n\nIt is recommended that all input passed to LDAP querying\
\ systems encode the following values:\n\n- Any occurrence of the null character must be escaped as\
\ “\\00”.\n- Any occurrence of the open parenthesis character must be escaped as “\\28”.\n- Any occurrence\
\ of the close parenthesis character must be escaped as “\\29”.\n- Any occurrence of the asterisk character\
\ must be escaped as “\\2a”.\n- Any occurrence of the backslash character must be escaped as “\\5c”.\n\
\nExample code that safely encodes input for use in an LDAP query using the `AccountManagement`\nAPI:\n\
```\nusing System.DirectoryServices.AccountManagement;\n\nstring EncodeLDAPString(string input) {\n\
\ // Note the \\ character is replaced first\n char[] chars = new char[] { '\\\\', '\\0', '(',\
\ ')', '*' };\n string[] encoded = new string[] { \"\\\\5c\", \"\\\\00\", \"\\\\28\", \"\\\\29\"\
, \"\\\\2a\" };\n\n for (int i = 0; i < chars.Length; i++)\n {\n input = input.Replace(chars[i].ToString(),\
\ encoded[i]);\n }\n\n return input;\n}\n\n// unsafe, do not use without encoding first\nstring\
\ userInput = \"Administrator\";\nPrincipalContext AD = new PrincipalContext(ContextType.Domain, \"\
ad.example.dev\");\n\nUserPrincipal u = new UserPrincipal(AD);\nstring encodedUserName = EncodeLDAPString(userInput);\n\
\n// The AD search term, encoded prior to calling search\nu.SamAccountName = encodedUserName;\n\n//\
\ Search for user\nPrincipalSearcher search = new PrincipalSearcher(u);\n\n// Use FindOne to only return\
\ a single result\nUserPrincipal result = (UserPrincipal)search.FindOne();\nsearch.Dispose();\n\n//\
\ show some details\nif (result != null) {\n Console.WriteLine(\"User: {0}\", result.DisplayName);\n\
} else {\n Console.WriteLine(\"user not found\");\n}\n```\n\nThe same encoding method shown in `EncodeLDAPString`\
\ can also be used when using the\nolder `DirectorySearcher` API.\n\nFor more information see OWASP's\
\ guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html\n"
severity: WARNING
metadata:
shortDescription: Improper neutralization of special elements used in an LDAP query ('LDAP Injection')
category: security
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
cwe: CWE-90
security-severity: Medium
- id: gitlab-csharp_injection_rule-SQLInjection
languages: [csharp]
patterns:
- pattern-either:
- patterns:
- metavariable-pattern:
metavariable: $FUNC
pattern-either:
- pattern: SqlQuery
- pattern: ExecuteSqlCommand
- pattern: ExecuteSqlCommandAsync
- pattern: ExecuteSqlRaw
- pattern: ExecuteSqlRawAsync
- pattern: FromSqlRaw
- pattern: FromSql
- pattern: GetSqlStringCommand
- pattern: ExecuteDataSet
- pattern: ExecuteReader
- pattern: ExecuteNonQuery
- pattern: ExecuteScalar
- pattern: CreateSQLQuery
- pattern-either:
- pattern: $DB.$FUNC($ARG, ...)
- pattern: $DB.$FUNC<$CC>($ARG, ...)
- pattern-not: $DB.$FUNC("...", ...)
- pattern-not: $DB.$FUNC<$CC>("...", ...)
- patterns:
- pattern-inside: 'using System.Data.Linq;
...
'
- pattern-either:
- patterns:
- pattern: (DataContext $CTX).ExecuteQuery<$TRESULT>($ARG, ...)
- pattern-not: (DataContext $CTX).ExecuteQuery<$TRESULT>("...", ...)
- patterns:
- pattern: (DataContext $CTX).ExecuteQuery($TYPE, $ARG, ...)
- pattern-not: (DataContext $CTX).ExecuteQuery($TYPE, "...", ...)
- patterns:
- pattern: (DataContext $CTX).ExecuteCommand($ARG, ...)
- pattern-not: (DataContext $CTX).ExecuteCommand("...", ...)
- patterns:
- metavariable-pattern:
metavariable: $IMPL
pattern-either:
- pattern: SqlCommand
- pattern: OracleCommand
- pattern: NpgsqlCommand
- pattern: MySqlCommand
- pattern: EntityCommand
- pattern: OdbcCommand
- pattern: OleDbCommand
- pattern: SqliteCommand
- pattern-either:
- patterns:
- pattern: new $IMPL($ARG, ...);
- pattern-not: new $IMPL("...", ...);
- patterns:
- pattern: ($IMPL $CMD).CommandText = <...$ARG...>;
- pattern-not: ($IMPL $CMD).CommandText = "...";
- patterns:
- metavariable-pattern:
metavariable: $FUNC
pattern-either:
- pattern: ExecuteDataRow
- pattern: ExecuteDataRowAsync
- pattern: ExecuteDataset
- pattern: ExecuteDatasetAsync
- pattern: ExecuteNonQuery
- pattern: ExecuteNonQueryAsync
- pattern: ExecuteReader
- pattern: ExecuteReaderAsync
- pattern: ExecuteScalar
- pattern: ExecuteScalarAsync
- pattern: UpdateDataSet
- pattern: UpdateDataSetAsync
- pattern-inside: 'using MySql.Data.MySqlClient;
...
'
- pattern: MySqlHelper.$FUNC($CONN, $ARG, ...)
- pattern-not: MySqlHelper.$FUNC($CONN, "...", ...)
- patterns:
- pattern-inside: 'using Cassandra;
...
'
- pattern-not: $SESS.Execute("...", ...)
- pattern-either:
- pattern: (Session $SESS).Execute($ARG, ...)
- patterns:
- pattern-inside: 'var $SESS = $CLUSTER.Connect(...);
...
'
- pattern: $SESS.Execute($ARG, ...)
message: "SQL Injection is a critical vulnerability that can lead to data or system compromise. By\ndynamically\
\ generating SQL query strings, user input may be able to influence the logic of\nthe SQL statement.\
\ This could lead to an adversary accessing information they should\nnot have access to, or in some\
\ circumstances, being able to execute OS functionality or code.\n\nReplace all dynamically generated\
\ SQL queries with parameterized queries. In situations where\ndynamic queries must be created, never\
\ use direct user input, but instead use a map or\ndictionary of valid values and resolve them using\
\ a user supplied key.\n\nFor example, some database drivers do not allow parameterized queries for\
\ `>` or `<` comparison\noperators. In these cases, do not use a user supplied `>` or `<` value, but\
\ rather have the\nuser\nsupply a `gt` or `lt` value. The alphabetical values are then used to look\
\ up the `>` and `<`\nvalues to be used in the construction of the dynamic query. The same goes for\
\ other queries\nwhere\ncolumn or table names are required but cannot be parameterized.\n\nExample using\
\ parameterized queries with `SqlCommand`:\n```\nstring userInput = \"someUserInput\";\nstring connectionString\
\ = ...;\nusing (SqlConnection connection = new SqlConnection(connectionString))\n{\n connection.Open();\n\
\ String sql = \"SELECT name, value FROM table where name=@Name\";\n\n using (SqlCommand command\
\ = new SqlCommand(sql, connection))\n {\n command.Parameters.Add(\"@Name\", System.Data.SqlDbType.NVarChar);\n\
\ command.Parameters[\"@Name\"].Value = userInput;\n using (SqlDataReader reader = command.ExecuteReader())\n\
\ {\n while (reader.Read())\n {\n Console.WriteLine(\"{0}\
\ {1}\", reader.GetString(0), reader.GetString(1));\n }\n }\n }\n}\n```\n\nFor\
\ more information on SQL Injection see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\n"
severity: WARNING
metadata:
shortDescription: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
category: security
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
cwe: CWE-89
security-severity: Medium
- id: gitlab-csharp_injection_rule-XPathInjection
languages: [csharp]
patterns:
- pattern-inside: 'using System.Xml;
...
'
- pattern-either:
- patterns:
- metavariable-regex:
metavariable: $FUNC
regex: ^(SelectNodes|SelectSingleNode|Compile|Evaluate|Matches|Select|SelectAncestors|SelectChildren|SelectDescendants)$
- metavariable-regex:
metavariable: $TY
regex: ^(XPathNavigator|XmlDocument|XmlNode|XmlDocumentXPathExtensions)$
- pattern: ($TY $VAR).$FUNC(<...$ARG...>, ...)
- pattern-not: ($TY $VAR).$FUNC("...", ...)
- patterns:
- pattern-inside: 'using System.Xml.Linq;
...
'
- metavariable-regex:
metavariable: $FUNC
regex: ^(XPathEvaluate|XPathSelectElement|XPathSelectElements)$
- pattern: $VAR.$FUNC(<...$ARG...>, ...)
- pattern-not: $VAR.$FUNC("...", ...)
- patterns:
- pattern-inside: 'using System.Xml.Schema;
...
'
- pattern-either:
- patterns:
- pattern: $VAR.XPath = <...$ARG...>;
- pattern-not: $VAR.XPath = "..."
- patterns:
- pattern: new XmlSchemaXPath { XPath = <...$ARG...> };
- focus-metavariable: $ARG
message: "XPath injection is a vulnerability that can allow an adversary to inject or modify how an XML\n\
query\nis structured. Depending on the logic of the original query, this could lead to adversaries\n\
extracting unauthorized information or in rare cases bypassing authorization checks.\n\nIt is recommended\
\ that LINQ to XML is used instead of XPath for querying XML documents. Care\nmust be taken to **not**\
\ call these LINQ functions with user input as they can still lead to\nXPath\ninjection:\n\n- `XPathEvaluate`\n\
- `XPathSelectElement`\n- `XPathSelectElements`\n\nExample using LINQ to XML to safely extract the first\
\ user from a list of users:\n```\n// XDocument is safe from XXE attacks as the resolver is disabled\
\ by default\nXDocument doc = XDocument.Load(\"users.xml\");\nXNamespace ns = \"urn:users-schema\";\n\
\nstring userInput = \"LastName\";\n\n// Get all the users.\nvar user = doc.Descendants(ns + \"user\"\
)\n .Select(u => new {\n FirstName = (string)u.Element(ns + \"first-name\"\
),\n LastName = (string)u.Element(ns + \"last-name\")\n }).Where(u =>\
\ u.LastName == userInput).FirstOrDefault();\n\nConsole.WriteLine(user.FirstName + \" \" + user.LastName);\n\
```\n\nFor more information on LINQ to XML security see:\nhttps://learn.microsoft.com/en-us/dotnet/standard/linq/linq-xml-security\n\
\nFor more information on XML security see OWASP's guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net\n"
severity: INFO
metadata:
shortDescription: Improper neutralization of data within XPath expressions ('XPath Injection')
category: security
cwe: CWE-643
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
security-severity: Medium
- id: gitlab-csharp_injection_rule-XmlDocumentXXEInjection
languages: [csharp]
mode: taint
pattern-sinks:
- patterns:
- pattern-not-inside: '(XmlDocument $DOC).XmlResolver = null;
...
'
- pattern-either:
- pattern: (XmlDocument $DOC).Load(...);
- pattern: (XmlDocument $DOC).LoadXml(...);
pattern-sources:
- pattern: var $DOC = new System.Xml.XmlDocument(...);
- patterns:
- pattern: var $DOC = new System.Xml.XmlDocument {...};
- pattern-not: var $DOC = new System.Xml.XmlDocument {...,XmlResolver = null,...};
message: 'External XML entities are a feature of XML parsers that allow documents to contain references
to
other documents or data. This feature can be abused to read files, communicate with external
hosts,
exfiltrate data, or cause a Denial of Service (DoS).
XML parsers and document loaders must be configured to not resolve entities. This can be done
by:
- Ensuring you are running a version of .NET Framework greater than 4.5.2 (released in 2014).
- Using `XDocument` which disables entity resolution and is generally safe from DoS.
- Setting `XmlDocument`''s `XmlResolver` to null.
Example of safely loading an XML file using `XmlDocument`:
```
XmlDocument document = new XmlDocument();
document.XmlResolver = null;
document.Load("users.xml");
```
For more information on XML security, see OWASP''s guide:
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net
'
severity: WARNING
metadata:
shortDescription: Improper restriction of XML external entity reference ('XXE')
category: security
cwe: CWE-611
owasp:
- A4:2017-XML External Entities (XXE)
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
security-severity: Medium
- id: gitlab-csharp_injection_rule-XmlReaderXXEInjection
languages: [csharp]
mode: taint
pattern-sinks:
- patterns:
- pattern-either:
- pattern-inside: '$SETTINGS.ProhibitDtd = false;
...
'
- pattern-inside: '$SETTINGS.DtdProcessing = DtdProcessing.Parse;
...
'
- pattern: System.Xml.XmlReader.Create(..., $SETTINGS);
pattern-sources:
- pattern: var $SETTINGS = new XmlReaderSettings();
message: 'External XML entities are a feature of XML parsers that allow documents to contain references
to
other documents or data. This feature can be abused to read files, communicate with external
hosts,
exfiltrate data, or cause a Denial of Service (DoS).
XML parsers and document loaders must be configured to not resolve entities. This can be done
by:
- Ensuring you are running a version of .NET Framework greater than 4.5.2 (released in 2014).
- Setting `XmlTextReader`''s `ProhibitDtd` to `true`
- Setting `XmlReaderSettings` `DtdProcessing` to `DtdProcessing.Prohibit`
Example of safely loading an XML file using `XmlDocument`:
```
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
XmlReader reader = XmlReader.Create(path, settings);
```
For more information on XML security, see OWASP''s guide:
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net
'
severity: WARNING
metadata:
shortDescription: Improper restriction of XML external entity reference ('XXE')
category: security
cwe: CWE-611
owasp:
- A4:2017-XML External Entities (XXE)
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
security-severity: MEDIUM
- id: gitlab-csharp_other_rule-UnsafeXSLTSettingUsed
languages: [csharp]
patterns:
- pattern-either:
- patterns:
- pattern: new XsltSettings() {...,$OPTIONS,...};
- metavariable-pattern:
metavariable: $OPTIONS
pattern-either:
- pattern: EnableDocumentFunction = true
- pattern: EnableScript = true
- patterns:
- pattern: $SETTINGS.$OPT = true;
- pattern: 'var $SETTINGS = new XsltSettings();
...
$SETTINGS.$OPT = true;
'
- metavariable-pattern:
metavariable: $OPT
pattern-either:
- pattern: EnableDocumentFunction
- pattern: EnableScript
message: 'By setting `XsltSettings.EnableScript` to true, an adversary who is able to influence the
loaded
XSL document could directly inject code to compromise the system. It is strongly
recommended that an alternative approach is used to work with XML data.
For increased security:
- Never process user-supplied XSL style sheets
- Ensure `XsltSettings.EnableScript` is set to false
- Ensure `XsltSettings.EnableDocumentFunction` is set to false
If the application must calculate values from XML input, instead of using XSL scripts to
execute functions, modify the XML document prior to running the
`XslCompiledTransform.Transform` method.
Example of modifying the XML prior to running `Transform`:
```
const String filename = "number.xml";
const String stylesheet = "calc.xsl";
// Compile the style sheet.
XsltSettings xslt_settings = new XsltSettings();
xslt_settings.EnableScript = false; // disable script
xslt_settings.EnableDocumentFunction = false; // disable document() function
XslCompiledTransform xslt = new XslCompiledTransform();
XmlResolver resolver = null; // set a null entity resolver
xslt.Load(stylesheet, xslt_settings, resolver);
// Load the XML source file, using XDocument for safety
XDocument doc = XDocument.Load(filename);
// do our modifications to the document before the transformation
// instead of inside of a script.
doc.Element("data").Add(new XElement("circle", new XElement("radius", 12)));
// Create an XmlWriter.
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
XmlWriter writer = XmlWriter.Create("output.xml", settings);
// Finally, execute the transformation.
xslt.Transform(doc.CreateReader(), writer);
writer.Close();
```
For more information on security considerations when using XSL see the following URLs:
- https://learn.microsoft.com/en-us/dotnet/standard/data/xml/xslt-security-considerations
- https://learn.microsoft.com/en-us/dotnet/api/system.xml.xsl.xslcompiledtransform?view=net-7.0#security-considerations
'
severity: WARNING
metadata:
shortDescription: XML injection (aka Blind XPath injection)
category: security
cwe: CWE-91
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
security-severity: High
- id: gitlab-csharp_password_rule-PasswordComplexity
languages: [csharp]
pattern-either:
- pattern: $OPT.Password.RequireDigit = false;
- pattern: $OPT.Password.RequireLowercase = false;
- pattern: $OPT.Password.RequireNonAlphanumeric = false;
- pattern: $OPT.Password.RequireUppercase = false;
- patterns:
- pattern: $OPT.Password.RequiredLength = $LEN;
- metavariable-comparison:
metavariable: $LEN
comparison: $LEN < 8
- patterns:
- pattern: $OPT.Password.RequiredUniqueChars = $LEN;
- metavariable-comparison:
metavariable: $LEN
comparison: $LEN < 1
message: "The application's `PasswordValidator.RequiredLength` property allows passwords\nto be less than\
\ 8 characters. Consider requiring a length of at least 8 or more\ncharacters to reduce the chance of\
\ passwords being brute forced.\n\nExample of setting the RequiredLength to 8 in ASP.NET Core Identity:\n\
```\nbuilder.Services.Configure<IdentityOptions>(options =>\n{\n // Default Password settings.\n\
\ options.Password.RequireDigit = true;\n options.Password.RequireLowercase = true;\n options.Password.RequireNonAlphanumeric\
\ = true;\n options.Password.RequireUppercase = true;\n options.Password.RequiredLength = 8;\n\
\ options.Password.RequiredUniqueChars = 1;\n});\n```\n\nFor more information on configuring ASP.NET\
\ Core Identity see:\nhttps://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration\n"
severity: WARNING
metadata:
shortDescription: Weak password requirements
category: security
cwe: CWE-521
owasp:
- A2:2017-Broken Authentication
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
security-severity: Info
- id: gitlab-csharp_path_rule-PathTraversal
languages: [csharp]
mode: taint
pattern-sources:
- patterns:
- pattern-inside: "public class $CLASS : Controller {\n ...\n}\n"
- pattern: $PARAM
- pattern-either:
- patterns:
- metavariable-regex:
metavariable: $HTTP_ANNO
regex: ^(Http)
- pattern-inside: '[$HTTP_ANNO]
public string $METHOD(...,$PARAM,...){...}
'
- pattern-inside: 'public IActionResult $METHOD(...,$PARAM,...){...}
'
pattern-sanitizers:
- pattern-either:
- pattern: (Microsoft.Extensions.FileProviders.PhysicalFileProvider $E).GetFileInfo(...)
- pattern: (System.Web.HttpServerUtility $E).MapPath(...)
- pattern: (System.Web.HttpServerUtilityBase $E).MapPath(...)
- pattern: (System.Web.HttpRequest $E).MapPath(...)
pattern-sinks:
- pattern-either:
- pattern: System.IO.Directory.Delete(...)
- pattern: System.IO.Directory.GetFiles(...)
- pattern: System.IO.Directory.Move(...)
- pattern: System.IO.File.AppendAllLines(...)
- pattern: System.IO.File.AppendAllLinesAsync(...)
- pattern: System.IO.File.AppendAllText(...)
- pattern: System.IO.File.AppendAllTextAsync(...)
- pattern: System.IO.File.AppendText(...)
- pattern: System.IO.File.Copy(...)
- pattern: System.IO.File.Create(...)
- pattern: System.IO.File.CreateText(...)
- pattern: System.IO.File.Delete(...)
- pattern: System.IO.File.Move(...)
- pattern: System.IO.File.Open(...)
- pattern: System.IO.File.OpenRead(...)
- pattern: System.IO.File.OpenText(...)
- pattern: System.IO.File.OpenWrite(...)
- pattern: System.IO.File.ReadAllBytes(...)
- pattern: System.IO.File.ReadAllBytesAsync(...)
- pattern: System.IO.File.ReadAllLines(...)
- pattern: System.IO.File.ReadAllLinesAsync(...)
- pattern: System.IO.File.ReadAllText(...)
- pattern: System.IO.File.ReadAllTextAsync(...)
- pattern: System.IO.File.ReadLines(...)
- pattern: System.IO.File.Replace(...)
- pattern: System.IO.File.SetAccessControl(...)
- pattern: System.IO.File.WriteAllBytes(...)
- pattern: System.IO.File.WriteAllBytesAsync(...)
- pattern: System.IO.File.WriteAllLines(...)
- pattern: System.IO.File.WriteAllLinesAsync(...)
- pattern: System.IO.File.WriteAllText(...)
- pattern: System.IO.File.WriteAllTextAsync(...)
- pattern: new System.IO.FileInfo(...)
- pattern: (System.IO.FileInfo $E).CopyTo(...)
- pattern: (System.IO.FileInfo $E).MoveTo(...)
- pattern: (System.IO.FileInfo $E).Replace(...)
- pattern: System.Reflection.Assembly.LoadFile(...)
- pattern: System.Reflection.Assembly.LoadFrom(...)
- pattern: System.Reflection.Assembly.ReflectionOnlyLoadFrom(...)
- pattern: System.Reflection.Assembly.UnsafeLoadFrom(...)
- pattern: System.AppDomain.AppendPrivatePath(...)
- pattern: System.Xml.XmlReader.Create(...)
- pattern: new System.IO.StreamReader.ctor(...)
- pattern: new System.IO.StreamWriter.ctor(...)
- pattern: new System.IO.FileStream.ctor(...)
- pattern: new System.Web.Mvc.FilePathResult(...)
- pattern: new Microsoft.AspNetCore.Mvc.PhysicalFileResult(...)
- pattern: (Microsoft.AspNetCore.Mvc.RazorPages.PageModel $E).PhysicalFile(...)
- pattern: (System.Web.UI.WebControls.FileUpload $E).SaveAs(...)
- pattern: (System.Web.HttpResponse $E).TransmitFile(...)
- pattern: (System.Web.HttpResponse $E).WriteFile(...)
- pattern: (System.Web.HttpResponseBase $E).TransmitFile(...)
- pattern: (System.Web.HttpResponseBase $E).WriteFile(...)
- pattern: (System.IO.Compression.ZipFileExtensions $E).CreateEntryFromFile(...)
- pattern: (System.IO.Compression.ZipFileExtensions $E).ExtractToFile(...)
- pattern: (System.IO.Compression.ZipFileExtensions $E).ExtractToDirectory(...)
- pattern: (System.Net.WebClient $E).DownloadFile(...)
- pattern: (System.Net.WebClient $E).DownloadFileAsync(...)
- pattern: (System.Net.WebClient $E).DownloadFileTaskAsync(...)
message: "The application dynamically constructs file or path information. If the path\ninformation comes\
\ from user input, it could be abused to read sensitive files,\naccess other users data, or aid in exploitation\
\ to gain further system access.\n\nUser input should never be used in constructing paths or files for\
\ interacting\nwith the filesystem. This includes filenames supplied by user uploads or downloads.\n\
If possible consider hashing user input or replacing it with unique values and\nuse `System.IO.Path.GetFullPath`\
\ to resolve and validate the path information\nprior to processing any file functionality.\n\nExample\
\ using `Path.GetFullPath` and not allowing direct user input:\n```\n// store user input alongside an\
\ ID we control\nstruct userData\n{\n public string userFilename;\n public Guid id;\n}\n\nclass\
\ Program\n{\n public static void Main()\n {\n userData data = new userData();\n \
\ // user input, saved only as a reference\n data.userFilename = \"..\\\\test.txt\";\n\n \
\ // random id as the filename\n data.id = Guid.NewGuid();\n\n // restrict all file\
\ processing to this directory only\n string basePath = \"C:\\\\Restricted\\\\\";\n\n \
\ // resolve the full path, but only use our random generated id\n string fullPath = Path.GetFullPath(basePath\
\ + data.id);\n\n // verify the path is contained within our basePath\n if (!fullPath.StartsWith(basePath))\
\ {\n Console.WriteLine(\"Invalid path specified!\");\n return;\n }\n \
\ // process / work with file\n }\n}\n```\n\nFor more information on path traversal issues\
\ see OWASP:\nhttps://owasp.org/www-community/attacks/Path_Traversal\n"
metadata:
shortDescription: Improper limitation of a pathname to a restricted directory ('Path Traversal')
category: security
cwe: CWE-22
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
security-severity: Medium
severity: WARNING
- id: gitlab-csharp_validation_rule-InputValidation
languages: [csharp]
patterns:
- pattern: "[ValidateInput(false)]\npublic $RET $FOO(...)\n{\n ...\n}\n"
message: "By using the `[ValidateInput(false)]` attribute in a controller\nclass, the application will\
\ disable request validation for that\nmethod. This disables ASP.NET from examining requests for injection\n\
attacks such as Cross-Site-Scripting (XSS).\n\nIf possible, re-enable validation by using `ValidateInput(true)`.\n\
In some cases this may not be possible, in which case ensure how the\nrequest data used is validated\
\ and this method does not\noutput user input directly into the view.\n\nFor more information on protecting\
\ ASP.NET Core applications from XSS see:\nhttps://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting\n\
\nExample of enabling `ValidateInput` attribute:\n```\nclass ControllerClass\n{\n [ValidateInput(true)]\n\
\ public void SomeActionMethod()\n {\n }\n}\n```\n\nFor more information on ASP.NET request\
\ validation see OWASP:\nhttps://owasp.org/www-community/ASP-NET_Request_Validation\n"
severity: WARNING
metadata:
shortDescription: ASP.NET input validation disabled
category: security
cwe: CWE-554
owasp:
- A6:2017-Security Misconfiguration
- A04:2021-Insecure Design
- A05:2025-Injection
security-severity: Info
- id: gitlab-csharp_xss_rule-HtmlElementXss
languages: [csharp]
mode: taint
pattern-sources:
- patterns:
- pattern: $PARAM
- pattern-inside: '$RET $METHOD(...,$PARAM,...){...}
'
- pattern: Request.Cookies[...]
- pattern: Request.Cookies.Get(...)
- pattern: Request.Form[...]
- pattern: Request.Form.Get(...)
- pattern: Request.Headers[...]
- pattern: Request.Headers.Get(...)
- pattern: Request.QueryString[...]
- pattern: Request.QueryString.Get(...)
- pattern: Request.Params[...]
- pattern: Request.RawUrl
- pattern: Request.Url
- pattern: Request.Path
- pattern: Request.Body
- pattern: $CTX.Request.Cookies[...]
- pattern: $CTX.Request.Cookies.Get(...)
- pattern: $CTX.Request.Form[...]
- pattern: $CTX.Request.Form.Get(...)
- pattern: $CTX.Request.Headers[...]
- pattern: $CTX.Request.Headers.Get(...)
- pattern: $CTX.Request.QueryString[...]
- pattern: $CTX.Request.QueryString.Get(...)
- pattern: $CTX.Request.Body
pattern-sanitizers:
- patterns:
- metavariable-regex:
metavariable: $FUNC
regex: (SerializeObject|HtmlAttributeEncode|HtmlEncode|HtmlFormUrlEncode|UrlEncode|UrlPathEncode|XmlAttributeEncode|XmlEncode|Encode)
- pattern: $CLASS.$FUNC(...)
pattern-sinks:
- pattern: (System.Web.Mvc.HtmlHelper $E).Raw(...)
- pattern: (Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper $E).Raw(...)
- pattern: Response.Write(...)
- pattern: (System.Web.UI.HtmlTextWriter $E).AddAttribute(...)
- pattern: (System.Web.UI.HtmlTextWriter $E).AddStyleAttribute(...)
- pattern: (System.Web.UI.HtmlTextWriter $E).RenderBeginTag(...)
- pattern: (System.Web.UI.HtmlTextWriter $E).Write(...)
- pattern: (System.Web.UI.HtmlTextWriter $E).WriteAttribute(...)
- pattern: (System.Web.UI.HtmlTextWriter $E).WriteBeginTag(...)
- pattern: (System.Web.UI.HtmlTextWriter $E).WriteEndTag(...)
- pattern: (System.Web.UI.HtmlTextWriter $E).WriteFullBeginTag(...)
- pattern: (System.Web.UI.HtmlTextWriter $E).WriteStyleAttribute(...)
message: 'Cross Site Scripting (XSS) is an attack which exploits a web application or system to treat
user input
as markup or script code. It is important to encode the data depending on the specific context
it
is used in. There are at least six context types:
- Inside HTML tags `<div>context 1</div>`
- Inside attributes: `<div class="context 2"></div>`
- Inside event attributes `<button onclick="context 3">button</button>`
- Inside script blocks: `<script>var x = "context 4"</script>`
- Unsafe element HTML assignment: `element.innerHTML = "context 5"`
- Inside URLs: `<iframe src="context 6"></iframe><a href="context 6">link</a>`
User input that is displayed within the application must be encoded, sanitized or validated
to ensure it cannot be treated as HTML or executed as Javascript code. Care must also be
taken
to not mix server-side templating with client-side templating, as the server-side templating
will
not encode things like {{ 7*7 }} which may execute client-side templating features.
It is _NOT_ advised to encode user input prior to inserting into a data store. The data will
need to be
encoded depending on context of where it is output. It is much safer to force the displaying
system to
handle the encoding and not attempt to guess how it should be encoded.
Consider using built-in framework capabilities for automatically encoding user input.
Depending
on output context, consider using the following `System.Text.Encodings.Web` encoders:
- [HtmlEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.htmlencoder)
- [JavaScriptEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.javascriptencoder)
- [UrlEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.urlencoder)
For more information on protecting ASP.NET Core applications from XSS see:
https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting#accessing-encoders-in-code
'
metadata:
shortDescription: Improper neutralization of input during web page generation ('Cross-site Scripting')
category: security
cwe: CWE-79
owasp:
- A7:2017-Cross-Site Scripting (XSS)
- A03:2021-Injection
- A05:2025-Injection
security-severity: Medium
severity: WARNING
- id: gitlab-csharp_xss_rule-ScriptXss
languages: [csharp]
mode: taint
pattern-sources:
- patterns:
- pattern: $PARAM
- pattern-inside: '$RET $METHOD(...,$PARAM,...){...}
'
- pattern: Request.Cookies[...]
- pattern: Request.Cookies.Get(...)
- pattern: Request.Form[...]
- pattern: Request.Form.Get(...)
- pattern: Request.Headers[...]
- pattern: Request.Headers.Get(...)
- pattern: Request.QueryString[...]
- pattern: Request.QueryString.Get(...)
- pattern: Request.Params[...]
- pattern: Request.RawUrl
- pattern: Request.Url
- pattern: Request.Path
- pattern: Request.Body
- pattern: $CTX.Request.Cookies[...]
- pattern: $CTX.Request.Cookies.Get(...)
- pattern: $CTX.Request.Form[...]
- pattern: $CTX.Request.Form.Get(...)
- pattern: $CTX.Request.Headers[...]
- pattern: $CTX.Request.Headers.Get(...)
- pattern: $CTX.Request.QueryString[...]
- pattern: $CTX.Request.QueryString.Get(...)
- pattern: $CTX.Request.Body
- pattern: $ELE.Text
pattern-sanitizers:
- patterns:
- metavariable-regex:
metavariable: $FUNC
regex: (SerializeObject|HtmlAttributeEncode|HtmlEncode|HtmlFormUrlEncode|UrlEncode|UrlPathEncode|XmlAttributeEncode|XmlEncode|Encode)
- pattern: $CLASS.$FUNC(...)
pattern-propagators:
- pattern: (StringBuilder $OUT).Append($IN)
from: $IN
to: $OUT
pattern-sinks:
- pattern: $SCRIPTMANAGER.RegisterStartupScript(...)
- pattern: $SCRIPTMANAGER.RegisterClientScriptBlock(...)
- pattern: System.Web.UI.RegisterStartupScript(...)
- pattern: System.Web.UI.RegisterClientScriptBlock(...)
message: 'Cross Site Scripting (XSS) is an attack which exploits a web application or system to treat
user input
as markup or script code. It is important to encode the data depending on the specific context
it
is used in.
User input that is used within the application scripts must be encoded, sanitized or validated
to ensure it cannot change the behavior of the Javascript code.
It is _NOT_ advised to encode user input prior to inserting into a data store. The data will
need to be
encoded depending on context of where it is output. It is much safer to force the displaying
system to
handle the encoding and not attempt to guess how it should be encoded.
Consider using built-in framework capabilities for automatically encoding user input.
Depending
on output context, consider using the following `System.Text.Encodings.Web` encoders:
- [HtmlEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.htmlencoder)
- [JavaScriptEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.javascriptencoder)
- [UrlEncoder](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.urlencoder)
For more information on protecting ASP.NET Core applications from XSS see:
https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting#accessing-encoders-in-code
'
metadata:
shortDescription: Improper neutralization of input during web page generation ('Cross-site Scripting')
category: security
cwe: CWE-79
owasp:
- A7:2017-Cross-Site Scripting (XSS)
- A03:2021-Injection
- A05:2025-Injection
security-severity: MEDIUM
severity: WARNING
- id: gitlab-go_crypto_rule-tlsversion
languages: [go]
pattern-either:
- patterns:
- pattern-either:
- patterns:
- pattern-inside: 'tls.Config{...}
'
- pattern: 'MinVersion: $VAL
'
- patterns:
- pattern-inside: '$VAR = uint16($VAL)
...
'
- pattern-inside: 'tls.Config{...}
'
- pattern: 'MinVersion: $VAR
'
- metavariable-pattern:
metavariable: $VAL
pattern-either:
- pattern: tls.VersionTLS11
- pattern: tls.VersionTLS10
- patterns:
- pattern-inside: 'tls.Config{...}
'
- pattern: 'MaxVersion: $ANYVAL
'
- pattern-not-inside: 'tls.Config{..., MinVersion: ..., ...}
'
message: "TLS versions 1.1 and 1.0 were deprecated by the IETF in June 2018 due to \na number of attacks\
\ against the vulnerable versions. Use of a deprecated \nTLS version may result in the unauthorized\
\ retrieval of sensitive \ninformation. It is strongly recommended that all TLS connections\nuse TLS\
\ 1.3 as Go will automatically choose the most secure cipher when \nnegotiating the TLS handshake with\
\ client or servers. TLS 1.3 cipher suites \nare configured to require Perfect Forward Secrecy (PFS).\
\ PFS is an important \nproperty as it will ensure that past encrypted transmissions could not be\n\
decrypted if the TLS certificate was compromised.\n\nExample using TLS 1.3 for a Go server:\n```\ncert,\
\ err := tls.LoadX509KeyPair(\"server.crt\", \"server.key\")\nif err != nil {\n log.Fatal(err)\n}\n\
\ncfg := &tls.Config{Certificates: []tls.Certificate{cert}, \n MinVersion: tls.VersionTLS13}\n\
\nsrv := &http.Server{\n Addr: \":8999\",\n TLSConfig: cfg,\n ReadTimeout: time.Minute,\n\
\ WriteTimeout: time.Minute,\n}\nlog.Fatal(srv.ListenAndServeTLS(\"cert.pem\", \"key.pem\"))\n```\n"
metadata:
shortDescription: Selection of less-secure algorithm during negotiation ('algorithm downgrade')
cwe: CWE-757
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
security-severity: Medium
category: security
severity: WARNING
- id: gitlab-java_cookie_rule-CookieInsecure
languages: [java]
patterns:
- pattern: '$X.servlet.http.Cookie $C = new $X.servlet.http.Cookie(..., ...);
...
($X.servlet.http.HttpServletResponse $RESP).addCookie($C);
'
- pattern-not-inside: '$X.servlet.http.Cookie $C = new $X.servlet.http.Cookie(..., ...);
...
$C.setSecure(true);
...
($X.servlet.http.HttpServletResponse $RESP).addCookie($C);
'
message: 'The `Secure` attribute when set to `true` protects the cookie value from being being
transmitted over clear text
communication paths such as HTTP. By enabling this protection, the cookie will only be sent
over HTTPS.
Example of protecting a `Cookie`:
```
// Create an Secure cookie.
Cookie someCookie = new Cookie("SomeCookieName", "SomeValue");
// Set Secure flag to true
someCookie.setSecure(true);
```
For more information see:
https://jakarta.ee/specifications/servlet/4.0/apidocs/javax/servlet/http/cookie#setSecure-boolean-
Session cookies should be configured with the following security directives:
- [HTTPOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies)
- [SameSite](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite)
- [Secure](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies)
'
severity: WARNING
metadata:
shortDescription: Sensitive cookie in HTTPS session without 'Secure' attribute
category: security
cwe: CWE-614
owasp:
- A3:2017-Sensitive Data Exposure
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
technology:
- java
security-severity: Low
- id: gitlab-java_cookie_rule-HttpResponseSplitting
languages: [java]
mode: taint
pattern-sanitizers:
- patterns:
- pattern-inside: '$STR.replaceAll($REPLACER, "...");
...
'
- pattern: $STR
- metavariable-regex:
metavariable: $REPLACER
regex: .*\[(?=.*\\r)(?=.*\\n).*\]\+
- pattern: org.apache.commons.text.StringEscapeUtils.escapeJava($STR);
pattern-sinks:
- pattern: new javax.servlet.http.Cookie("$KEY", ...);
- patterns:
- pattern-inside: '$C = new javax.servlet.http.Cookie("$KEY", ...);
...
'
- pattern: $C.setValue(...);
pattern-sources:
- pattern: (javax.servlet.http.HttpServletRequest $REQ).getParameter(...);
- pattern: (javax.servlet.http.HttpServletRequest $REQ).getParameterNames();
- pattern: (javax.servlet.http.HttpServletRequest $REQ).getParameterValues(...);
- pattern: (javax.servlet.http.HttpServletRequest $REQ).getParameterMap();
- pattern: (javax.servlet.http.HttpServletRequest $REQ).getHeader(...);
- pattern: (javax.servlet.http.HttpServletRequest $REQ).getPathInfo();
message: "HTTP Response Splitting is a vulnerability where Carriage Return (CR `\\r`) and Line Feed (LF\n\
`\\n`)\ncharacters are introduced into an HTTP header from user-supplied input. By injecting the\n`\\\
r\\n`\ncharacter sequence, an adversary could potentially modify how the response is interpreted by\n\
the\nclient or any downstream caching services. This could allow an adversary to poison the cache\n\
data or execute Cross-Site Scripting (XSS) attacks.\n\nSome Java application servers such as [Apache\
\ Tomcat](https://tomcat.apache.org/) as of version\n8.0, newer versions of Jetty and other servers\
\ that implement the [RFC 6265 Standard](https://datatracker.ietf.org/doc/html/rfc6265) will\ndisallow\
\ `\\r' and '\\n` characters characters from being set in cookies. If your application server does not\n\
automatically provide this functionality, user-supplied input that is used in cookie keys or\nvalues\
\ must be validated.\n\nExample of validating cookies to only allow valid characters:\n```\n// throws\
\ an IllegalArgumentException if the provided value contains invalid characters\npublic void validateRfc6265CookieValue(String\
\ value) throws IllegalArgumentException {\n char[] chars = value.toCharArray();\n\n // iterate\
\ over every character\n for (int i = 0; i < chars.length; i++) {\n char c = chars[i];\n\n\
\ // check for any characters below 0x21 as well as: '\"' ',' ';' '\\' and 0x7f.\n if\
\ (c < 0x21 || c == '\"' || c == ',' || c == ';' || c == '\\\\' || c == 0x7f) {\n throw new\
\ IllegalArgumentException(\"Invalid character in cookie detected:\n{0}\".format(Integer.toString(c)));\n\
\ }\n }\n}\n```\n\nAlternatively, you could use a string escape package such as\n[Apache Commons\
\ Text](https://commons.apache.org/proper/commons-text/) to escape the input:\n```\npublic String escapeValue(String\
\ value) {\n return StringEscapeUtils.escapeJava(value);\n}\n```\n\nFor more information on response\
\ splitting attacks see OWASP:\nhttps://owasp.org/www-community/attacks/HTTP_Response_Splitting\n"
severity: WARNING
metadata:
shortDescription: Improper neutralization of CRLF sequences in HTTP headers ('HTTP Response Splitting')
category: security
cwe: CWE-113
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
technology:
- java
security-severity: High
- id: gitlab-java_cookie_rule-RequestParamToHeader
languages: [java]
mode: taint
pattern-sanitizers:
- patterns:
- pattern-inside: '$STR.replaceAll("$INPUT", "...");
...
'
- pattern: $STR
- metavariable-regex:
metavariable: $INPUT
regex: .*\[(?=.*\\r)(?=.*\\n).*\]\+
- pattern: org.apache.commons.text.StringEscapeUtils.unescapeJava(...);
pattern-sinks:
- pattern: ($X.servlet.http.HttpServletResponse $RES).setHeader("$KEY", ...);
- pattern: ($X.servlet.http.HttpServletResponse $RES).addHeader("$KEY", ...);
- pattern: ($X.servlet.http.HttpServletResponseWrapper $WRP).setHeader("$KEY", ...);
- pattern: ($X.servlet.http.HttpServletResponseWrapper $WRP).addHeader("$KEY", ...);
pattern-sources:
- pattern: ($X.servlet.http.HttpServletRequest $REQ).getParameter(...);
- pattern: ($X.servlet.http.HttpServletRequest $REQ).getParameterNames();
- pattern: ($X.servlet.http.HttpServletRequest $REQ).getParameterValues(...);
- pattern: ($X.servlet.http.HttpServletRequest $REQ).getParameterMap();
- pattern: ($X.servlet.http.HttpServletRequest $REQ).getHeader(...);
- pattern: ($X.servlet.http.HttpServletRequest $REQ).getPathInfo();
message: "HTTP Response Splitting is a vulnerability where Carriage Return (CR `\\r`) and Line Feed (LF\n\
`\\n`)\ncharacters are introduced into an HTTP header from user-supplied input. By injecting the\n`\\\
r\\n`\ncharacter sequence, an adversary could potentially modify how the response is interpreted by\n\
the\nclient or any down stream caching services. This could allow an adversary to poison the cache\n\
data or execute Cross-Site Scripting (XSS) attacks.\n\nSome Java application servers such as [Apache\
\ Tomcat](https://tomcat.apache.org/) will\nautomatically encode\ncharacters from being set in response\
\ headers as a space `0x20` character. If your application\nserver does\nnot automatically provide this\
\ functionality, user-supplied input that is used in header keys\nor values must be\nvalidated.\n\n\
Example of validating headers to only allow valid characters:\n```\n// throws an IllegalArgumentException\
\ if the provided value contains invalid characters\npublic void validateHeader(String value) throws\
\ IllegalArgumentException {\n char[] chars = value.toCharArray();\n\n // iterate over every character\n\
\ for (int i = 0; i < chars.length; i++) {\n char c = chars[i];\n\n // check for any\
\ characters below 0x21 as well as: '\"' ',' ';' '\\' and 0x7f.\n if (c < 0x21 || c == '\"' ||\
\ c == ',' || c == ';' || c == '\\\\' || c == 0x7f) {\n throw new IllegalArgumentException(\"\
Invalid character in cookie detected:\n{0}\".format(Integer.toString(c)));\n }\n }\n}\n```\n\
\nAlternatively, you could use a string escape package such as\n[Apache Commons Text](https://commons.apache.org/proper/commons-text/)\
\ to escape the input:\n```\npublic String escapeValue(String value) {\n return StringEscapeUtils.escapeJava(value);\n\
}\n```\n\nFor more information on response splitting attacks see OWASP:\nhttps://owasp.org/www-community/attacks/HTTP_Response_Splitting\n"
severity: ERROR
metadata:
shortDescription: Improper neutralization of CRLF sequences in HTTP headers ('HTTP Response Splitting')
category: security
cwe: CWE-113
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
technology:
- java
security-severity: High
- id: gitlab-java_cors_rule-PermissiveCORSInjection
languages: [java]
mode: taint
pattern-sources:
- pattern: (HttpServletRequest $REQ).getParameter(...)
- pattern: (HttpServletRequest $REQ).getHeader(...)
- pattern: (HttpServletRequest $REQ).getPathInfo()
- pattern: (HttpServletRequest $REQ).getQueryString()
- pattern: (HttpServletRequest $REQ).getAttribute(...)
- pattern: (HttpServletRequest $REQ).getSession().getAttribute(...)
- pattern: (HttpServletRequest $REQ).getServletContext().getAttribute(...)
- pattern: (HttpServletRequest $REQ).getParameterValues(...)
- pattern: (HttpServletRequest $REQ).getParameterNames()
- pattern: (HttpServletRequest $REQ).getParameterMap()
pattern-sinks:
- patterns:
- pattern-either:
- pattern: (HttpServletResponse $RES).setHeader("$HEADER", ...)
- pattern: (HttpServletResponse $RES).addHeader("$HEADER", ...)
- metavariable-regex:
metavariable: $HEADER
regex: (?i)(Access-Control-Allow-Origin)
message: "This application potentially allows user-supplied input into the value of the\n`Access-Control-Allow-Origin`\
\ response header. This header is part of the\n[Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)\
\ CORS\nspecification. By allowing user input to specify which domains can communicate with this\nserver,\n\
an adversary could exploit a weakness in this server to force clients to send credentials (such\nas\
\ session\nidentifiers) to the adversary's server.\n\nFor the above attack to work, the application\
\ would need to suffer from an additional\nvulnerability,\nsuch as Cross-Site Scripting (XSS).\n\nTo\
\ remediate this issue, do not use user-supplied information when calling\n`HttpServletResponse.setHeader`\
\ or `HttpServletResponse.addHeader`\nfor the `Access-Control-Allow-Origin` header's value. Instead,\
\ hardcode the allowed domain(s)\nand reference them in a lookup\ntable:\nExample allowing dynamic but\
\ safe domains in `Access-Control-Allow-Origin`:\n\n```\n // this data should be in the class constructor\
\ or taken from a trusted datasource\n Map<String, String> allowedDomains = new HashMap();\n allowedDomains.put(\"\
sub1\", \"sub1.example.com\");\n allowedDomains.put(\"sub2\", \"sub2.example.com\");\n\n // extract\
\ the allowedDomain parameters value as a key to look up which domain to provide\nvia the allowedDomains\
\ map\n // if not found, sets sub1 as the default\n String headerValue = allowedDomains.getOrDefault(request.getParameter(\"\
allowedDomain\"),\nallowedDomains.get(\"sub1\"));\n\n // add the header with our trusted sub1.example.com\
\ or sub2.example.com domains.\n response.addHeader(\"Access-Control-Allow-Origin\", headerValue);\n\
}\n```\n\nFor more information on `Access-Control-Allow-Origin` see:\nhttps://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin\n"
severity: ERROR
metadata:
shortDescription: Permissive cross-domain policy with untrusted domains
cwe: CWE-942
category: security
owasp:
- A5:2017-Broken Access Control
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
technology:
- java
security-severity: Low
- id: gitlab-java_crypto_rule-BlowfishKeySize
languages: [java]
patterns:
- pattern-inside: '$KEYGEN = javax.crypto.KeyGenerator.getInstance("Blowfish", ...);
...
'
- pattern: $KEYGEN.init($KEY_SIZE)
- metavariable-comparison:
comparison: int($KEY_SIZE) < 128
metavariable: $KEY_SIZE
message: "The Blowfish encryption algorithm was meant as a drop-in replacement for DES and was created\
\ in\n1993. Smaller key sizes may make the ciphertext vulnerable to [birthday\nattacks](https://en.wikipedia.org/wiki/Birthday_attack).\
\ While no known attacks against\nBlowfish\nexist, it should never be used to encrypt files over 4GB\
\ in size. If possible consider\nusing AES as the instance of `KeyGenerator` instead of Blowfish.\n\n\
To remediate the small key size, pass a value such as 256 to the `KeyGenerator.init(keySize)`\nmethod.\n\
\nExample setting a larger key size and changing to `KeyGenerator` to AES:\n```\npublic static void\
\ aesKeyGenerator() throws java.security.NoSuchAlgorithmException {\n // Use the AES algorithm for\
\ key generation\n KeyGenerator keyGenerator = KeyGenerator.getInstance(\"AES\");\n\n // Set the\
\ key size here\n keyGenerator.init(256);\n\n // get the raw bytes of the key\n byte[] key\
\ = keyGenerator.generateKey().getEncoded();\n\n // pass the key bytes to create a SecretKeySpec\n\
\ SecretKeySpec secretKeySpec = new SecretKeySpec(key, \"AES\");\n}\n```\n\nExample setting a larger\
\ key size for Blowfish:\n```\npublic static void blowFishKeyGenerator() throws java.security.NoSuchAlgorithmException\
\ {\n // Use the Blowfish algorithm for key generation\n KeyGenerator keyGenerator = KeyGenerator.getInstance(\"\
Blowfish\");\n\n // Set the key size here\n keyGenerator.init(256);\n\n // get the raw bytes\
\ of the key\n byte[] key = keyGenerator.generateKey().getEncoded();\n\n // pass the key bytes\
\ to create a SecretKeySpec\n SecretKeySpec secretKeySpec = new SecretKeySpec(key, \"Blowfish\");\n\
}\n```\n\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n"
severity: WARNING
metadata:
category: security
shortDescription: Inadequate encryption strength
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
cwe: CWE-326
technology:
- java
security-severity: Medium
- id: gitlab-java_crypto_rule-CipherDESInsecure
languages: [java]
patterns:
- pattern-either:
- pattern: javax.crypto.Cipher.getInstance("$ALG", ...)
- pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG");
...
javax.crypto.Cipher.getInstance($PROP, ...);
'
- metavariable-regex:
metavariable: $ALG
regex: ^DES(/|$)
message: "DES, TripleDES and RC2 are all considered broken or insecure cryptographic algorithms.\nNewer\
\ algorithms apply message integrity to validate ciphertext has not been tampered\nwith. Consider using\
\ `ChaCha20Poly1305` instead as it is easier and faster than the\nalternatives such as `AES-256-GCM`.\n\
\nFor older applications that don't have support for `ChaCha20Poly1305`,\n`AES-256-GCM` is recommended,\
\ however it has many drawbacks:\n- Slower than `ChaCha20Poly1305`.\n- Catastrophic failure if nonce\
\ values are reused.\n\nExample using `ChaCha20Poly1305`:\n```\npublic encrypt() throws Exception {\n\
\ chaChaEncryption(\"Secret text to encrypt\".getBytes(StandardCharsets.UTF_8));\n}\n\npublic SecureRandom\
\ getSecureRandomDRBG() throws NoSuchAlgorithmException {\n // Use DRBG according to\nhttp://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf\n\
\ return SecureRandom.getInstance(\"DRBG\",\n // Security strength in bits (default is\
\ 128)\n DrbgParameters.instantiation(256,\n // Set prediction resistance\
\ and re-seeding\n DrbgParameters.Capability.PR_AND_RESEED,\n // Set the\
\ personalization string (optional, not necessary)\n \"some_personalization_string\"\
.getBytes()\n )\n );\n}\n\npublic Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[]\
\ secretKey) throws\nNoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,\nInvalidAlgorithmParameterException\
\ {\n // Get a DRBG random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n\
\ // Create a ChaCha20-Poly1305 cipher instance\n Cipher chaChaCipher = Cipher.getInstance(\"\
ChaCha20-Poly1305/None/NoPadding\");\n // Create our parameterSpec using our ivKey\n AlgorithmParameterSpec\
\ parameterSpec = new IvParameterSpec(ivKey);\n // Create a SecretKeySpec using our secretKey\n \
\ SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, \"ChaCha20\");\n // Initialize and\
\ return the cipher for the provided mode\n chaChaCipher.init(mode, secretKeySpec, parameterSpec,\
\ random);\n return chaChaCipher;\n}\n\npublic void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException,\n\
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {\n // Get a DRBG\
\ random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n // Create\
\ secretKey\n byte[] secretKey = new byte[32];\n random.nextBytes(secretKey);\n // Create an\
\ IV Key\n byte[] ivKey = new byte[12];\n random.nextBytes(ivKey);\n\n // Create a chaCha encryption\
\ cipher instance\n Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey);\n\
\n // Encrypt the text using ChaCha20Poly1305\n byte[] cipherText = null;\n try {\n \
\ cipherText = chaChaEncryptor.doFinal(plainText);\n } catch (IllegalBlockSizeException | BadPaddingException\
\ e) {\n System.out.println(\"failed to encrypt text\");\n return;\n }\n System.out.println(\"\
encrypted: \" + Base64.getEncoder().encodeToString(cipherText));\n\n // Create a chaCha decryption\
\ cipher instance\n Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey);\n\
\n // Decrypt the text\n byte[] decryptedText = null;\n try {\n decryptedText = chaChaDecryptor.doFinal(cipherText);\n\
\ } catch (IllegalBlockSizeException | BadPaddingException e) {\n System.out.println(\"failed\
\ to decrypt text\");\n return;\n }\n System.out.println(\"decrypted: \" + new String(decryptedText,\
\ StandardCharsets.UTF_8));\n}\n```\n\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n"
severity: WARNING
metadata:
shortDescription: Inadequate encryption strength
category: security
cwe: CWE-326
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
technology:
- java
security-severity: Medium
- id: gitlab-java_crypto_rule-CipherDESedeInsecure
languages: [java]
patterns:
- pattern-either:
- pattern: javax.crypto.Cipher.getInstance("$ALG", ...)
- pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG");
...
javax.crypto.Cipher.getInstance($PROP, ...);
'
- metavariable-regex:
metavariable: $ALG
regex: DESede(/|$)
message: "DES, TripleDES and RC2 are all considered broken or insecure cryptographic algorithms.\nNewer\
\ algorithms apply message integrity to validate ciphertext has not been tampered\nwith. Consider using\
\ `ChaCha20Poly1305` instead as it is easier and faster than the\nalternatives such as `AES-256-GCM`.\n\
\nFor older applications that don't have support for `ChaCha20Poly1305`,\n`AES-256-GCM` is recommended,\
\ however it has many drawbacks:\n- Slower than `ChaCha20Poly1305`.\n- Catastrophic failure if nonce\
\ values are reused.\n\nExample using `ChaCha20Poly1305`:\n```\npublic encrypt() throws Exception {\n\
\ chaChaEncryption(\"Secret text to encrypt\".getBytes(StandardCharsets.UTF_8));\n}\n\npublic SecureRandom\
\ getSecureRandomDRBG() throws NoSuchAlgorithmException {\n // Use DRBG according to\nhttp://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf\n\
\ return SecureRandom.getInstance(\"DRBG\",\n // Security strength in bits (default is\
\ 128)\n DrbgParameters.instantiation(256,\n // Set prediction resistance\
\ and re-seeding\n DrbgParameters.Capability.PR_AND_RESEED,\n // Set the\
\ personalization string (optional, not necessary)\n \"some_personalization_string\"\
.getBytes()\n )\n );\n}\n\npublic Cipher getChaCha20Poly1305(int mode, byte[] nonceKey,\
\ byte[] secretKey) throws\nNoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,\n\
InvalidAlgorithmParameterException {\n // Get a DRBG random number generator instance\n SecureRandom\
\ random = getSecureRandomDRBG();\n // Create a ChaCha20-Poly1305 cipher instance\n Cipher chaChaCipher\
\ = Cipher.getInstance(\"ChaCha20-Poly1305/None/NoPadding\");\n // Create our parameterSpec using\
\ our nonceKey\n AlgorithmParameterSpec parameterSpec = new IvParameterSpec(nonceKey);\n // Create\
\ a SecretKeySpec using our secretKey\n SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey,\
\ \"ChaCha20\");\n // Initialize and return the cipher for the provided mode\n chaChaCipher.init(mode,\
\ secretKeySpec, parameterSpec, random);\n return chaChaCipher;\n}\n\npublic void chaChaEncryption(byte[]\
\ plainText) throws NoSuchAlgorithmException,\nNoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException\
\ {\n // Get a DRBG random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n\
\ // Create secretKey\n byte[] secretKey = new byte[32];\n random.nextBytes(secretKey);\n \
\ // Create an IV nonceKey\n byte[] nonceKey = new byte[12];\n random.nextBytes(nonceKey);\n\
\ // Create a chaCha encryption cipher instance\n Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE,\
\ nonceKey, secretKey);\n // Encrypt the text using ChaCha20Poly1305\n byte[] cipherText = null;\n\
\ try {\n cipherText = chaChaEncryptor.doFinal(plainText);\n } catch (IllegalBlockSizeException\
\ | BadPaddingException e) {\n System.out.println(\"failed to encrypt text\");\n return;\n\
\ }\n System.out.println(\"encrypted: \" + Base64.getEncoder().encodeToString(cipherText));\n\
\ // Create a chaCha decryption cipher instance\n Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE,\
\ nonceKey, secretKey);\n // Decrypt the text\n byte[] decryptedText = null;\n try {\n \
\ decryptedText = chaChaDecryptor.doFinal(cipherText);\n } catch (IllegalBlockSizeException |\
\ BadPaddingException e) {\n System.out.println(\"failed to decrypt text\");\n return;\n\
\ }\n System.out.println(\"decrypted: \" + new String(decryptedText, StandardCharsets.UTF_8));\n\
}\n```\n\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n"
severity: WARNING
metadata:
shortDescription: Use of a broken or risky cryptographic algorithm
category: security
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
technology:
- java
security-severity: Medium
- id: gitlab-java_crypto_rule-CipherECBMode
languages: [java]
patterns:
- pattern-either:
- pattern: javax.crypto.Cipher.getInstance("$ALG", ...)
- pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG");
...
javax.crypto.Cipher.getInstance($PROP, ...);
'
- metavariable-comparison:
metavariable: $ALG
comparison: "$ALG in (\n \"AES/ECB/NoPadding\" \"AES/ECB/PKCS5Padding\"\n \"DES/ECB/NoPadding\"\
\ \"DES/ECB/PKCS5Padding\"\n \"DESede/ECB/NoPadding\" \"DESede/ECB/PKCS5Padding\"\n \"AES/ECB/PKCS7Padding\"\
\n)\n"
message: "Cryptographic algorithms provide many different modes of operation, only some of which provide\n\
message integrity. Without message integrity it could be possible for an adversary to attempt\nto tamper\
\ with the ciphertext which could lead to compromising the encryption key. Newer\nalgorithms\napply\
\ message integrity to validate ciphertext has not been tampered with.\n\nInstead of using an algorithm\
\ that requires configuring a cipher mode, an algorithm\nthat has built-in message integrity should\
\ be used. Consider using `ChaCha20Poly1305` or\n`AES-256-GCM` instead.\n\nFor older applications that\
\ don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is\nrecommended, however it has many drawbacks:\n\
\ - Slower than `ChaCha20Poly1305`.\n - Catastrophic failure if nonce values are reused.\n\nExample\
\ using `ChaCha20Poly1305`:\n```\npublic encrypt() throws Exception {\n chaChaEncryption(\"Secret\
\ text to encrypt\".getBytes(StandardCharsets.UTF_8));\n}\n\npublic SecureRandom getSecureRandomDRBG()\
\ throws NoSuchAlgorithmException {\n // Use DRBG according to\nhttp://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf\n\
\ return SecureRandom.getInstance(\"DRBG\",\n // Security strength in bits (default is\
\ 128)\n DrbgParameters.instantiation(256,\n // Set prediction resistance\
\ and re-seeding\n DrbgParameters.Capability.PR_AND_RESEED,\n // Set the\
\ personalization string (optional, not necessary)\n \"some_personalization_string\"\
.getBytes()\n )\n );\n}\n\npublic Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[]\
\ secretKey) throws\nNoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,\nInvalidAlgorithmParameterException\
\ {\n // Get a DRBG random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n\
\ // Create a ChaCha20-Poly1305 cipher instance\n Cipher chaChaCipher = Cipher.getInstance(\"\
ChaCha20-Poly1305/None/NoPadding\");\n // Create our parameterSpec using our ivKey\n AlgorithmParameterSpec\
\ parameterSpec = new IvParameterSpec(ivKey);\n // Create a SecretKeySpec using our secretKey\n \
\ SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, \"ChaCha20\");\n // Initialize and\
\ return the cipher for the provided mode\n chaChaCipher.init(mode, secretKeySpec, parameterSpec,\
\ random);\n return chaChaCipher;\n}\n\npublic void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException,\n\
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {\n // Get a DRBG\
\ random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n // Create\
\ secretKey\n byte[] secretKey = new byte[32];\n random.nextBytes(secretKey);\n // Create an\
\ IV Key\n byte[] ivKey = new byte[12];\n random.nextBytes(ivKey);\n\n // Create a chaCha encryption\
\ cipher instance\n Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey);\n\
\n // Encrypt the text using ChaCha20Poly1305\n byte[] cipherText = null;\n try {\n \
\ cipherText = chaChaEncryptor.doFinal(plainText);\n } catch (IllegalBlockSizeException | BadPaddingException\
\ e) {\n System.out.println(\"failed to encrypt text\");\n return;\n }\n System.out.println(\"\
encrypted: \" + Base64.getEncoder().encodeToString(cipherText));\n\n // Create a chaCha decryption\
\ cipher instance\n Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey);\n\
\n // Decrypt the text\n byte[] decryptedText = null;\n try {\n decryptedText = chaChaDecryptor.doFinal(cipherText);\n\
\ } catch (IllegalBlockSizeException | BadPaddingException e) {\n System.out.println(\"failed\
\ to decrypt text\");\n return;\n }\n System.out.println(\"decrypted: \" + new String(decryptedText,\
\ StandardCharsets.UTF_8));\n}\n```\n\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n"
severity: ERROR
metadata:
shortDescription: Use of a broken or risky cryptographic algorithm
category: security
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
technology:
- java
security-severity: Medium
- id: gitlab-java_crypto_rule-CipherIntegrity
languages: [java]
patterns:
- pattern-either:
- pattern: javax.crypto.Cipher.getInstance("$ALG", ...)
- pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG");
...
javax.crypto.Cipher.getInstance($PROP, ...);
'
- metavariable-comparison:
metavariable: $ALG
comparison: "$ALG in (\n \"AES\"\n \"AES/CBC/NoPadding\" \"AES/CBC/PKCS5Padding\" \"AES/CBC/PKCS7Padding\"\
\n \"AES/CFB/NoPadding\" \"AES/CFB/PKCS5Padding\" \"AES/CFB/PKCS7Padding\"\n \"AES/CTR/NoPadding\"\
\n \"AES/ECB/NoPadding\" \"AES/ECB/PKCS5Padding\" \"AES/ECB/PKCS7Padding\"\n \"AES/OFB/NoPadding\"\
\ \"AES/OFB/PKCS5Padding\" \"AES/OFB/PKCS7Padding\"\n \"ARCFOUR\"\n \"DES\"\n \"DES/CBC/NoPadding\"\
\ \"DES/CBC/PKCS5Padding\"\n \"DES/ECB/NoPadding\" \"DES/ECB/PKCS5Padding\"\n \"DESede\"\n \"\
DESede/CBC/NoPadding\" \"DESede/CBC/PKCS5Padding\"\n \"DESede/ECB/NoPadding\" \"DESede/ECB/PKCS5Padding\"\
\n \"RC4\"\n)\n"
message: "Cryptographic algorithms provide many different modes of operation, only some of which provide\n\
message integrity. Without message integrity it could be possible for an adversary to attempt\nto tamper\
\ with the ciphertext which could lead to compromising the encryption key. Newer\nalgorithms\napply\
\ message integrity to validate ciphertext has not been tampered with.\n\nInstead of using an algorithm\
\ that requires configuring a cipher mode, an algorithm\nthat has built-in message integrity should\
\ be used. Consider using `ChaCha20Poly1305` or\n`AES-256-GCM` instead.\n\nFor older applications that\
\ don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is\nrecommended, however it has many drawbacks:\n\
\ - Slower than `ChaCha20Poly1305`.\n - Catastrophic failure if nonce values are reused.\n\nExample\
\ using `ChaCha20Poly1305`:\n```\npublic encrypt() throws Exception {\n chaChaEncryption(\"Secret\
\ text to encrypt\".getBytes(StandardCharsets.UTF_8));\n}\n\npublic SecureRandom getSecureRandomDRBG()\
\ throws NoSuchAlgorithmException {\n// Use DRBG according to\nhttp://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf\n\
\ return SecureRandom.getInstance(\"DRBG\",\n // Security strength in bits (default is\
\ 128)\n DrbgParameters.instantiation(256,\n // Set prediction resistance\
\ and re-seeding\n DrbgParameters.Capability.PR_AND_RESEED,\n // Set the\
\ personalization string (optional, not necessary)\n \"some_personalization_string\"\
.getBytes()\n )\n );\n}\n\npublic Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[]\
\ secretKey) throws\nNoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,\nInvalidAlgorithmParameterException\
\ {\n // Get a DRBG random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n\
\ // Create a ChaCha20-Poly1305 cipher instance\n Cipher chaChaCipher = Cipher.getInstance(\"\
ChaCha20-Poly1305/None/NoPadding\");\n // Create our parameterSpec using our ivKey\n AlgorithmParameterSpec\
\ parameterSpec = new IvParameterSpec(ivKey);\n // Create a SecretKeySpec using our secretKey\n \
\ SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, \"ChaCha20\");\n // Initialize and\
\ return the cipher for the provided mode\n chaChaCipher.init(mode, secretKeySpec, parameterSpec,\
\ random);\n return chaChaCipher;\n}\n\npublic void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException,\n\
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {\n // Get a DRBG\
\ random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n // Create\
\ secretKey\n byte[] secretKey = new byte[32];\n random.nextBytes(secretKey);\n // Create an\
\ IV Key\n byte[] ivKey = new byte[12];\n random.nextBytes(ivKey);\n\n // Create a chaCha encryption\
\ cipher instance\n Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey);\n\
\n // Encrypt the text using ChaCha20Poly1305\n byte[] cipherText = null;\n try {\n \
\ cipherText = chaChaEncryptor.doFinal(plainText);\n } catch (IllegalBlockSizeException | BadPaddingException\
\ e) {\n System.out.println(\"failed to encrypt text\");\n return;\n }\n System.out.println(\"\
encrypted: \" + Base64.getEncoder().encodeToString(cipherText));\n\n // Create a chaCha decryption\
\ cipher instance\n Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey);\n\
\n // Decrypt the text\n byte[] decryptedText = null;\n try {\n decryptedText = chaChaDecryptor.doFinal(cipherText);\n\
\ } catch (IllegalBlockSizeException | BadPaddingException e) {\n System.out.println(\"failed\
\ to decrypt text\");\n return;\n }\n System.out.println(\"decrypted: \" + new String(decryptedText,\
\ StandardCharsets.UTF_8));\n}\n```\n\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n"
severity: ERROR
metadata:
shortDescription: Use of a broken or risky cryptographic algorithm
category: security
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
technology:
- java
security-severity: Medium
- id: gitlab-java_crypto_rule-CipherPaddingOracle
languages: [java]
patterns:
- pattern-either:
- pattern: javax.crypto.Cipher.getInstance("$ALG", ...)
- pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG");
...
javax.crypto.Cipher.getInstance($PROP, ...);
'
- metavariable-comparison:
metavariable: $ALG
comparison: "$ALG in (\n \"AES/CBC/PKCS5Padding\" \"DES/CBC/PKCS5Padding\" \"DESede/CBC/PKCS5Padding\"\
\ \"AES/CBC/PKCS7Padding\"\n)\n"
message: "Cryptographic block ciphers can be configured to pad individual blocks if there is not enough\n\
input data to match the size of the block. This specific mode of CBC used in combination with\nPKCS5Padding\
\ is susceptible to padding oracle attacks. An adversary could potentially decrypt\nthe message if the\
\ system exposed the difference between plaintext with invalid padding or\nvalid padding. The distinction\
\ between valid and invalid padding is usually revealed through\ndistinct error messages being returned\
\ for each condition.\n\nConsider switching to a more secure cipher that doesn't require padding and\
\ builds in message\nauthentication integrity directly into the algorithm.\n\nConsider using `ChaCha20Poly1305`\
\ or\n`AES-256-GCM` instead.\n\nFor older applications that don't have support for `ChaCha20Poly1305`,\
\ `AES-256-GCM` is\nrecommended, however it has many drawbacks:\n - Slower than `ChaCha20Poly1305`.\n\
\ - Catastrophic failure if nonce values are reused.\n\nExample using `ChaCha20Poly1305`:\n```\npublic\
\ encrypt() throws Exception {\n chaChaEncryption(\"Secret text to encrypt\".getBytes(StandardCharsets.UTF_8));\n\
}\n\npublic SecureRandom getSecureRandomDRBG() throws NoSuchAlgorithmException {\n // Use DRBG according\
\ to\nhttp://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf\n return SecureRandom.getInstance(\"\
DRBG\",\n // Security strength in bits (default is 128)\n DrbgParameters.instantiation(256,\n\
\ // Set prediction resistance and re-seeding\n DrbgParameters.Capability.PR_AND_RESEED,\n\
\ // Set the personalization string (optional, not necessary)\n \"some_personalization_string\"\
.getBytes()\n )\n );\n}\n\npublic Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[]\
\ secretKey) throws\nNoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,\nInvalidAlgorithmParameterException\
\ {\n // Get a DRBG random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n\
\ // Create a ChaCha20-Poly1305 cipher instance\n Cipher chaChaCipher = Cipher.getInstance(\"\
ChaCha20-Poly1305/None/NoPadding\");\n // Create our parameterSpec using our ivKey\n AlgorithmParameterSpec\
\ parameterSpec = new IvParameterSpec(ivKey);\n // Create a SecretKeySpec using our secretKey\n \
\ SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, \"ChaCha20\");\n // Initialize and\
\ return the cipher for the provided mode\n chaChaCipher.init(mode, secretKeySpec, parameterSpec,\
\ random);\n return chaChaCipher;\n}\n\npublic void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException,\n\
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {\n // Get a DRBG\
\ random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n // Create\
\ secretKey\n byte[] secretKey = new byte[32];\n random.nextBytes(secretKey);\n // Create an\
\ IV Key\n byte[] ivKey = new byte[12];\n random.nextBytes(ivKey);\n\n // Create a chaCha encryption\
\ cipher instance\n Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey);\n\
\n // Encrypt the text using ChaCha20Poly1305\n byte[] cipherText = null;\n try {\n \
\ cipherText = chaChaEncryptor.doFinal(plainText);\n } catch (IllegalBlockSizeException | BadPaddingException\
\ e) {\n System.out.println(\"failed to encrypt text\");\n return;\n }\n System.out.println(\"\
encrypted: \" + Base64.getEncoder().encodeToString(cipherText));\n\n // Create a chaCha decryption\
\ cipher instance\n Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey);\n\
\n // Decrypt the text\n byte[] decryptedText = null;\n try {\n decryptedText = chaChaDecryptor.doFinal(cipherText);\n\
\ } catch (IllegalBlockSizeException | BadPaddingException e) {\n System.out.println(\"failed\
\ to decrypt text\");\n return;\n }\n System.out.println(\"decrypted: \" + new String(decryptedText,\
\ StandardCharsets.UTF_8));\n}\n```\n\nFor more information on padding oracle attacks see:\nhttps://en.wikipedia.org/wiki/Padding_oracle_attack\n\
\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n"
severity: ERROR
metadata:
shortDescription: Use of a broken or risky cryptographic algorithm
category: security
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
technology:
- java
security-severity: Medium
- id: gitlab-java_crypto_rule-CustomMessageDigest
languages: [java]
patterns:
- pattern: "class $CLAZZ extends java.security.MessageDigest {\n ...\n}\n"
message: 'The application was found implementing a custom `java.security.MessageDigest`. It is
strongly recommended that a standard Digest algorithm be chosen instead as implementing
a digest by hand is error-prone. The National Institute of Standards and
Technology (NIST) recommends the use of SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, or
SHA-512/256.
Example of creating a SHA-384 hash:
```
// Create a MessageDigest using the SHA-384 algorithm
MessageDigest sha384Digest = MessageDigest.getInstance("SHA-384");
// Call update with your data
sha384Digest.update(input);
// Only call digest once all data has been fed into the update sha384digest instance
byte[] output = sha384Digest.digest();
// output base64 encoded version of the hash
System.out.println("hash: " + Base64.getEncoder().encodeToString(output));
```
'
severity: WARNING
metadata:
shortDescription: Use of a broken or risky cryptographic algorithm
category: security
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
technology:
- java
security-severity: Medium
- id: gitlab-java_crypto_rule-HazelcastSymmetricEncryption
languages: [java]
patterns:
- pattern: new com.hazelcast.config.SymmetricEncryptionConfig()
message: 'The network communications for Hazelcast is configured to use a deprecated symmetric cipher.
Consider using TLS/SSL when establishing communications across the Hazelcast cluster.
For more information on configuring TLS/SSL for Hazelcast see:
https://docs.hazelcast.com/imdg/4.2/security/tls-ssl
'
severity: WARNING
metadata:
shortDescription: Inadequate encryption strength
category: security
cwe: CWE-326
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
technology:
- java
security-severity: Medium
- id: gitlab-java_crypto_rule-InsufficientKeySizeRsa
languages: [java]
patterns:
- pattern-either:
- patterns:
- pattern-inside: '$GEN = KeyPairGenerator.getInstance($ALG, ...);
...
'
- pattern-either:
- pattern: $VAR.initialize($SIZE, ...);
- pattern: new java.security.spec.RSAKeyGenParameterSpec($SIZE,...);
- metavariable-comparison:
comparison: $SIZE < 2048
metavariable: $SIZE
- metavariable-regex:
metavariable: $ALG
regex: '"(RSA|DSA)"'
message: "The application is generating an RSA key that is less than the recommended 2048 bits.\nThe National\
\ Institute of Standards and Technology (NIST) deprecated signing Digital\nCertificates that contained\
\ RSA Public Keys of 1024 bits in December 2010. While\n1024-bit RSA keys have not been factored yet,\
\ advances in compute may make it possible\nin the near future.\n\nConsider upgrading to the newer asymmetric\
\ algorithm such as `Ed25519` which handles\nthe complexities of generating key pairs and choosing correct\
\ key sizes for you:\n```\npublic static KeyPair generateEd25519() throws NoSuchAlgorithmException {\n\
\ // Choose Ed25519 for KeyPairGenerator Instance\n KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(\"\
Ed25519\");\n // Generate a KeyPair and return\n return keyPairGenerator.generateKeyPair();\n\
}\n```\n\nOtherwise use a key size greater than 2048 when generating RSA keys:\n```\npublic static KeyPair\
\ generateRSA() throws NoSuchAlgorithmException {\n // Choose RSA for KeyPairGenerator Instance\n\
\ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(\"RSA\");\n // Initialize with\
\ 2048 key size\n keyPairGenerator.initialize(2048);\n // Generate a KeyPair and return\n return\
\ keyPairGenerator.generateKeyPair();\n}\n```\n\nFor more information on Ed25519 see: http://ed25519.cr.yp.to/\n\
\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n"
metadata:
shortDescription: Inadequate encryption strength
category: security
cwe: CWE-326
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
security-severity: Medium
severity: WARNING
- id: gitlab-java_crypto_rule-NullCipher
languages: [java]
pattern: new javax.crypto.NullCipher()
message: "The application was found creating a `NullCipher` instance. `NullCipher` implements the\n`Cipher`\
\ interface by returning ciphertext identical to the supplied plaintext. This means\nany data passed\
\ to the `doFinal(...)` or `update(...)` methods will not actually encrypt\nthe input.\n\nRemove the\
\ NullCipher reference and replace with a legitimate `Cipher` instance such as\n`ChaCha20-Poly1305`\n\
\nExample using `ChaCha20Poly1305`:\n```\npublic encrypt() throws Exception {\n chaChaEncryption(\"\
Secret text to encrypt\".getBytes(StandardCharsets.UTF_8));\n}\n\npublic SecureRandom getSecureRandomDRBG()\
\ throws NoSuchAlgorithmException {\n // Use DRBG according to\nhttp://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf\n\
\ return SecureRandom.getInstance(\"DRBG\",\n // Security strength in bits (default is\
\ 128)\n DrbgParameters.instantiation(256,\n // Set prediction resistance\
\ and re-seeding\n DrbgParameters.Capability.PR_AND_RESEED,\n // Set the\
\ personalization string (optional, not necessary)\n \"some_personalization_string\"\
.getBytes()\n )\n );\n}\n\npublic Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[]\
\ secretKey) throws\nNoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,\nInvalidAlgorithmParameterException\
\ {\n // Get a DRBG random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n\
\ // Create a ChaCha20-Poly1305 cipher instance\n Cipher chaChaCipher = Cipher.getInstance(\"\
ChaCha20-Poly1305/None/NoPadding\");\n // Create our parameterSpec using our ivKey\n AlgorithmParameterSpec\
\ parameterSpec = new IvParameterSpec(ivKey);\n // Create a SecretKeySpec using our secretKey\n \
\ SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, \"ChaCha20\");\n // Initialize and\
\ return the cipher for the provided mode\n chaChaCipher.init(mode, secretKeySpec, parameterSpec,\
\ random);\n return chaChaCipher;\n}\n\npublic void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException,\n\
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {\n // Get a DRBG\
\ random number generator instance\n SecureRandom random = getSecureRandomDRBG();\n // Create\
\ secretKey\n byte[] secretKey = new byte[32];\n random.nextBytes(secretKey);\n // Create an\
\ IV Key\n byte[] ivKey = new byte[12];\n random.nextBytes(ivKey);\n\n // Create a chaCha encryption\
\ cipher instance\n Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey);\n\
\n // Encrypt the text using ChaCha20Poly1305\n byte[] cipherText = null;\n try {\n \
\ cipherText = chaChaEncryptor.doFinal(plainText);\n } catch (IllegalBlockSizeException | BadPaddingException\
\ e) {\n System.out.println(\"failed to encrypt text\");\n return;\n }\n System.out.println(\"\
encrypted: \" + Base64.getEncoder().encodeToString(cipherText));\n\n // Create a chaCha decryption\
\ cipher instance\n Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey);\n\
\n // Decrypt the text\n byte[] decryptedText = null;\n try {\n decryptedText = chaChaDecryptor.doFinal(cipherText);\n\
\ } catch (IllegalBlockSizeException | BadPaddingException e) {\n System.out.println(\"failed\
\ to decrypt text\");\n return;\n }\n System.out.println(\"decrypted: \" + new String(decryptedText,\
\ StandardCharsets.UTF_8));\n}\n```\n\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n"
severity: WARNING
metadata:
shortDescription: Use of a broken or risky cryptographic algorithm
category: security
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
technology:
- java
security-severity: Medium
- id: gitlab-java_crypto_rule-RsaNoPadding
languages: [java]
patterns:
- pattern-either:
- pattern: javax.crypto.Cipher.getInstance("$ALG", ...)
- pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG");
...
javax.crypto.Cipher.getInstance($PROP, ...);
'
- metavariable-regex:
metavariable: $ALG
regex: (?i)^RSA/.*NoPadding$
message: "The software uses the RSA algorithm but does not incorporate Optimal Asymmetric\nEncryption\
\ Padding (OAEP). By not enabling padding, the algorithm maybe vulnerable\nto [chosen plaintext attacks](https://en.wikipedia.org/wiki/Chosen-plaintext_attack).\n\
\nTo enable OAEP mode, pass `RSA/ECB/OAEPWithSHA-256AndMGF1Padding` to the `Cipher.getInstance`\nmethod.\n\
\nExample encrypting and decrypting a message using RSA with OAEP:\n```\npublic static void encryptWithRSA()\
\ throws InvalidKeyException, NoSuchAlgorithmException,\nNoSuchPaddingException, IllegalBlockSizeException,\
\ BadPaddingException {\n // Generate an RSA Public and Private Key Pair\n KeyPair keyPair = generateRSAKeys();\n\
\ // Create a Cipher instance using RSA, ECB with OAEP\n Cipher rsaEncryptor = Cipher.getInstance(\"\
RSA/ECB/OAEPWithSHA-256AndMGF1Padding\");\n // Initialize to ENCRYPT_MODE with the public key\n \
\ rsaEncryptor.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());\n // Encrypt our secret message\n\
\ byte[] cipherText = rsaEncryptor.doFinal(\"Some secret\nmessage\".getBytes(StandardCharsets.UTF_8));\n\
\n // Create a Cipher instance using RSA, ECB with OAEP\n Cipher rsaDecryptor = Cipher.getInstance(\"\
RSA/ECB/OAEPWithSHA-256AndMGF1Padding\");\n // Initialize to DECRYPT_MODE with the private key\n\
\ rsaDecryptor.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());\n // Decrypt the secret message\n\
\ byte[] plainText = rsaDecryptor.doFinal(cipherText);\n // Debug output\n System.out.println(new\
\ String(plainText));\n}\n```\nMore information on Optimal asymmetric encryption padding:\nhttps://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding\n\
\nFor more information on Java Cryptography see:\nhttps://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html\n"
metadata:
shortDescription: Use of RSA algorithm without OAEP
category: security
cwe: CWE-780
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
security-severity: Medium
severity: WARNING
- id: gitlab-java_crypto_rule-WeakMessageDigest
languages: [java]
patterns:
- pattern-either:
- pattern: java.security.MessageDigest.getInstance("$ALG", ...)
- pattern: java.security.Signature.getInstance("$ALG", ...)
- pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG");
...
java.security.MessageDigest.getInstance("$ALG", ...);
'
- pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$ALG");
...
java.security.Signature.getInstance("$ALG", ...);
'
- metavariable-comparison:
metavariable: $ALG
comparison: "$ALG in (\n \"MD2\" \"MD4\" \"MD5\" \"MD5withRSA\"\n \"SHA-1\" \"SHA1withRSA\" \"SHA1withDSA\"\
\n)\n"
message: 'The application was found using an insecure or risky digest or signature algorithm. Both MD5
and SHA1 hash algorithms have been found to be vulnerable to producing collisions.
This means
that two different values, when hashed, can lead to the same hash value. If the application is
trying
to use these hash methods for storing passwords, then it is recommended to switch to a
password hashing
algorithm such as Argon2id or PBKDF2.
strongly recommended that a standard Digest algorithm be chosen instead as implementing
a digest by hand is error-prone.
Example of creating a SHA-384 hash:
```
// Create a MessageDigest using the SHA-384 algorithm
MessageDigest sha384Digest = MessageDigest.getInstance("SHA-384");
// Call update with your data
sha384Digest.update(input);
// Only call digest once all data has been fed into the update sha384digest instance
byte[] output = sha384Digest.digest();
// output base64 encoded version of the hash
System.out.println("hash: " + Base64.getEncoder().encodeToString(output));
```
For more information on secure password storage see OWASP:
https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
'
severity: WARNING
metadata:
shortDescription: Use of a broken or risky cryptographic algorithm (SHA1/MD5)
category: security
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
technology:
- java
security-severity: Medium
- id: gitlab-java_crypto_rule-WeakTLSProtocol-DefaultHttpClient
languages: [java]
patterns:
- pattern: new org.apache.http.impl.client.DefaultHttpClient();
message: "The `org.apache.http.impl.client.DefaultHttpClient` does not verify the hostnames upon connection.\n\
\nThis allows for an adversary who is in between the application and the target host to intercept\n\
potentially sensitive information or transmit malicious data.\n\nDo not use the `org.apache.http.impl.client.DefaultHttpClient();`\
\ as it is deprecated. Instead\nuse the new `java.net.http.HttpClient` that was introduced in Java 9.\n\
\nExample connecting to a host that will automatically do TLS validation:\n```\n// Create a new java.net.http.HttpClient\n\
HttpClient httpClient = HttpClient.newHttpClient();\n// Create a HttpRequest builder\nHttpRequest request\
\ = HttpRequest.newBuilder()\n // Create a URI for a website which requires TLS\n .uri(URI.create(\"\
https://www.example.com/\"))\n // Build the request\n .build();\n\n// Use the httpClient\
\ to send the request and use an HttpResponse.BodyHandlers String type\nHttpResponse<String> response\
\ = httpClient.send(request, HttpResponse.BodyHandlers.ofString());\n// Debug print\nSystem.out.println(response);\n\
```\n"
metadata:
shortDescription: Improper certificate validation
category: security
cwe: CWE-295
owasp:
- A3:2017-Sensitive Data Exposure
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
security-severity: Medium
severity: WARNING
- id: gitlab-java_crypto_rule-WeakTLSProtocol-SSLContext
languages: [java]
patterns:
- pattern-either:
- pattern: javax.net.ssl.SSLContext.getInstance("$PROTO", ...)
- pattern: '$PROP = (java.util.Properties $P).getProperty(..., "$PROTO");
...
javax.net.ssl.SSLContext.getInstance($PROP, ...);
'
- metavariable-comparison:
metavariable: $PROTO
comparison: '$PROTO not in ("TLS" "TLSv1.2" "TLSv1.3" "DTLSv1.2" "DTLSv1.3")
'
message: "Avoid initializing SSLContext with insecure protocols like `SSL`, `SSLv2`, or `SSLv3`.\nThese\
\ protocols are outdated and do not validate certificates by default. Additionally,\nthese older `SSL`\
\ versions have many known security issues.\n\nInstead, use secure protocols like `TLSv1.2` or `TLSv1.3`.\n\
```\nSSLContext context = SSLContext.getInstance(\"TLSv1.3\");\n```\nFor more information on see OWASP:\n\
\ - https://owasp.org/www-project-web-security-testing-guide/v41/4-Web_Application_Security_Testing/09-Testing_for_Weak_Cryptography/01-Testing_for_Weak_SSL_TLS_Ciphers_Insufficient_Transport_Layer_Protection\n"
metadata:
shortDescription: Inadequate encryption strength
category: security
cwe: CWE-326
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
security-severity: MEDIUM
severity: WARNING
- id: gitlab-java_crypto_rule-WeakTLSProtocolVersion
languages: [java]
patterns:
- pattern-either:
- pattern-inside: 'import javax.net.ssl.*;
...
'
- pattern-inside: 'import javax.net.ssl.SSLContext;
...
'
- pattern-either:
- pattern-inside: 'SSLContext.getInstance("$UNSAFE_VERSION");
'
- pattern-inside: 'SSLContext.getInstance(...);
...
$ENGINE.setEnabledProtocols(new String[]{...,"$UNSAFE_VERSION",...});
'
- pattern-not-inside: '$C = SSLContext.getInstance(...);
...
$ENGINE.setEnabledProtocols(new String[]{...,"TLSv1.2",...});
'
- pattern-not-inside: '$C = SSLContext.getInstance(...);
...
$ENGINE.setEnabledProtocols(new String[]{...,"TLSv1.3",...});
'
- pattern-not-inside: '$C = SSLContext.getInstance(...);
...
$ENGINE.setEnabledProtocols(new String[]{...,"DTLSv1.2",...});
'
- pattern-not-inside: '$C = SSLContext.getInstance(...);
...
$ENGINE.setEnabledProtocols(new String[]{...,"DTLSv1.3",...});
'
- metavariable-regex:
metavariable: $UNSAFE_VERSION
regex: ^(TLS|(D)?TLSv1.(0|1))$
message: 'The application was found enabling insecure TLS protocol versions. When enabling protocol
versions for an `SSLContext`, only the following versions should be allowed:
- TLSv1.2
- TLSv1.3
- DTLSv1.2
- DTLSv1.3
To mitigate potential security risks, it is strongly advised to enforce TLS 1.2 as the minimum
protocol version and disallow older versions such as TLS 1.0. Do note that newer versions of
Java do not even support TLS 1.0 and will throw `NoSuchAlgorithmException`. Versions of TLS
prior to 1.2 could expose the connection to downgrade attacks, where an adversary intercepts
the
connection and alters the requested protocol version to be a less secure one.
In many scenarios, relying on the default system configuration does not meet compliance
standards. This is due to the application being deployed across diverse systems with varying
configurations and Java versions. While the default value may be secure on modern and
up-to-date systems, it may not hold true for older systems. Consequently, it is highly
recommended to explicitly define a secure configuration in all cases.
Example configuring an SSLContext with TLSv1.2:
```
// Create an SSLContext with TLSv1.2 explicitly
SSLContext tlsContext = SSLContext.getInstance("TLSv1.2"); // or TLSv1.3, DTLSv1.2, DTLSv1.3
// Alternatively, set the enabled protocols
SSLContext serverSslContext = SSLContext.getInstance("TLS");
SSLEngine serverEngine = serverSslContext.createSSLEngine();
// Calling setEnabledProtocols will override the original context''s configured protocol version
serverEngine.setEnabledProtocols(new String[]{ "TLSv1.2" });
```
For more information on `SSLContext` see:
- https://docs.oracle.com/en/java/javase/11/docs/api/java.base/javax/net/ssl/SSLContext.html
For more information on MiTM attacks see:
- https://owasp.org/www-community/attacks/Manipulator-in-the-middle_attack
'
metadata:
shortDescription: Inadequate encryption strength
category: security
cwe: CWE-326
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
security-severity: Medium
severity: WARNING
- id: gitlab-java_endpoint_rule-HostnameVerifier
languages: [java]
message: "The `HostnameVerifier` has been set to always return `true`. This effectively \ndisables the\
\ validation of server or client certificates. This could allow an \nadversary who is in between the\
\ application and the target host to launch a Man \nin the middle attack (MITM) i.e intercept potentially\
\ sensitive information or \ninject malicious content into the communication stream.\n\nTo mitigate\
\ this vulnerability and enhance the security of your application, it is \nstrongly advised to adhere\
\ to the default HostnameVerifier settings. This ensures \nthat the validation mechanism remains intact,\
\ providing a crucial layer of security \nagainst unauthorized interception and data manipulation.\n\
\nImplementing the default HostnameVerifier can be achieved with the following code \nsnippet:\n```\n\
// Use the default HostnameVerifier\nHttpsURLConnection connection = (HttpsURLConnection) url.openConnection();\n\
connection.setHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier());\n```\nFor more information\
\ on TLS security, refer the following OWASP documentation:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html\n"
metadata:
shortDescription: Improper certificate validation
category: security
cwe: CWE-295
owasp:
- A3:2017-Sensitive Data Exposure
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
security-severity: MEDIUM
patterns:
- pattern-inside: "class $V implements HostnameVerifier {\n ...\n}\n"
- pattern-either:
- pattern: "boolean verify(...) {\n ...\n return true;\n ...\n}\n"
- pattern-not:
patterns:
- pattern: "boolean verify(...) {\n ...\n return $VAR;\n ...\n }\n"
- metavariable-regex:
metavariable: $VAR
regex: ^((?!true).)*$
- pattern-not: "boolean verify(...) {\n $VAR = true;\n ...\n return $VAR;\n ...\n }\n"
severity: WARNING
- id: gitlab-java_endpoint_rule-UnvalidatedRedirect
languages: [java]
message: "Unvalidated redirects occur when an application redirects a user to a\ndestination URL specified\
\ by a user supplied parameter that is not validated.\nSuch vulnerabilities can be used to facilitate\
\ phishing attacks.\n\nTo avoid open redirect vulnerabilities in Java, one effective strategy is to\n\
only allow redirection to URLs that are pre-defined in a safe list. This safe\nlist can be implemented\
\ using a collection like a Map, List, or Dictionary,\nwhere you store all the valid URLs or URL patterns.\
\ When a redirect request is\nmade, you can check if the requested URL is in this safe list before proceeding\
\ \nwith the redirection. For example:\n\n```\n protected void doGet(HttpServletRequest request, HttpServletResponse\
\ response) throws ServletException, IOException {\n private List<String> safeUrls = new ArrayList<>();\n\
\ safeUrls.add(\"/home\");\n safeUrls.add(\"/user/profile\");\n safeUrls.add(\"/dashboard\"\
);\n \n String redirectUrl = request.getParameter(\"url\");\n\n if (safeUrls.contains(redirectUrl))\
\ {\n response.sendRedirect(redirectUrl);\n } else {\n response.sendRedirect(\"\
/errorPage\");\n }\n }\"\n``` \n"
mode: taint
pattern-sources:
- patterns:
- pattern: '$URL = ($X.servlet.http.HttpServletRequest $REQ).$M(...);
'
- metavariable-regex:
metavariable: $M
regex: (getParameter|getCookies|getHeader|getHeaders|getHeaderNames|getPathInfo|getPathTranslated|getContextPath|getQueryString|getRemoteUser|getRequestedSessionId|getRequestURI|getRequestURL|getServletPath|getParts|getPart|getReader)
pattern-sinks:
- pattern-either:
- pattern: '($X.servlet.http.HttpServletResponse $RES).sendRedirect($URL)
'
- pattern: '($X.servlet.http.HttpServletResponse $RES).addHeader("Location", $URL)
'
pattern-sanitizers:
- patterns:
- pattern-inside: "if ($SAFE.contains($URL)){\n ...\n}\n"
- pattern-either:
- pattern: '($X.servlet.http.HttpServletResponse $RES).sendRedirect($URL)
'
- pattern: '($X.servlet.http.HttpServletResponse $RES).addHeader("Location", $URL)
'
metadata:
category: security
cwe: CWE-601
owasp:
- A1:2017-Injection
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
shortDescription: URL redirection to untrusted site ('Open Redirect')
security-severity: Info
severity: ERROR
- id: gitlab-java_endpoint_rule-X509TrustManager
languages: [java]
message: "The `X509TrustManager` has been configured to return null. This effectively disables the\nvalidation\
\ of server or client certificates. This could allow an adversary who is in \nbetween the application\
\ and the target host to launch a Man in the middle attack (MITM) i.e \nintercept potentially sensitive\
\ information or inject malicious content into the \ncommunication stream.\n\nConsider using the \n\
default `TrustManager` instead of implementing a custom one. If you must override\nthe default verification\
\ process, implement proper TrustManager verification for\n`checkServerTrusted` and `checkClientTrusted`\
\ by throwing `CertificateException` if \nthe certificate is invalid.\n\nFor most applications, using\
\ the default TrustManager provided by the Java runtime is \nsufficient and recommended. Following is\
\ an example using the built in `TrustManagerFactory` \nto manage validating certificate chains:\n```\n\
// Use the default TrustManagerFactory\nTrustManagerFactory trustManagerFactory =\nTrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\n\
// Use default system KeyStore, alternatively pass in your own keystore.\ntrustManagerFactory.init((KeyStore)\
\ null);\n// Create SSLContext for TLS connections\nSSLContext tlsContext = SSLContext.getInstance(\"\
TLS\");\n// Initialize the tlsContext with our trust manager and a SecureRandom number generator.\n\
tlsContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());\n```\nFor more information\
\ on TLS security, refer the following OWASP documentation:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html\n"
metadata:
shortDescription: Improper certificate validation
category: security
cwe: CWE-295
owasp:
- A3:2017-Sensitive Data Exposure
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
security-severity: MEDIUM
patterns:
- pattern-inside: "class $V implements X509TrustManager {\n ...\n}\n"
- pattern-either:
- pattern: public void checkClientTrusted(...) {}
- pattern: public void checkServerTrusted(...) {}
- patterns:
- pattern-either:
- pattern: "X509Certificate[] getAcceptedIssuers() {\n ...\n return null;\n ...\n}\n"
- pattern-not:
patterns:
- pattern: "X509Certificate[] getAcceptedIssuers() {\n ...\n return $VAR;\n ...\n }\n"
- metavariable-regex:
metavariable: $VAR
regex: ^((?!null).)*$
- pattern-not: "X509Certificate[] getAcceptedIssuers() {\n $VAR = null;\n ...\n return\
\ $VAR;\n ...\n }\n"
severity: WARNING
- id: gitlab-java_file_rule-FileUploadFileName
languages: [java]
message: "The filename provided by the FileUpload API can be tampered with\nwhich could lead to unauthorized\
\ access or file inclusion vulnerabilities.\nTo mitigate this risk, it is essential to conduct rigorous\
\ validation of the\nfilenames provided by clients. This validation should ensure that the filename\n\
adheres to a predefined structure, is devoid of potentially dangerous characters\n(such as forward slashes\
\ / and backslashes \\), and corresponds to an authorized\nfile only.\n\nFor example, as a remediation\
\ strategy, the application could:\n1. Sanitize Filenames: Create a function to sanitize filenames by\
\ removing\n or replacing unauthorized characters, including path traversal sequences (../ or ..\\\
).\n2. Allowlist Validation: Implement a allowlist approach, allowing only filenames\n that match\
\ a specific pattern or are part of a predefined list.\n3. Use Server-Generated Filenames: Rather than\
\ relying on client-provided filenames,\n generate unique names server-side for storing files.\n4.\
\ Verify File Paths: Ensure files are being saved in the correct,\n intended directory, and prevent\
\ redirection to unauthorized directories.\n\nExample remediation:\n```\n public class FileUploadHandler\
\ {\n\n protected void doPost(HttpServletRequest request, HttpServletResponse response)\n \
\ throws ServletException, IOException {\n\n Part filePart = request.getPart(\"file\"\
);\n String fileName = filePart.getSubmittedFileName();\n\n // removes any path information\
\ from the filename\n String sanitizedFileName = sanitizeFileName(fileName);\n if\
\ (!isFileNameAllowed(sanitizedFileName)) {\n throw new SecurityException(\"Invalid file\
\ name\");\n }\n\n // Generate a unique file name for storage\n String storedFileName\
\ = UUID.randomUUID().toString() + \".txt\";\n\n Path targetPath = Paths.get(\"uploads\").resolve(storedFileName);\n\
\ Files.copy(fileContent, targetPath, StandardCopyOption.REPLACE_EXISTING);\n }\n\n \
\ private String sanitizeFileName(String fileName) {\n return Paths.get(fileName).getFileName().toString();\n\
\ }\n\n private boolean isFileNameAllowed(String fileName) {\n return fileName.matches(\"\
[a-zA-Z0-9._-]+\");\n }\n }\n```\n"
pattern-either:
- patterns:
- pattern-inside: "$FILES = (ServletFileUpload $SFU).parseRequest(($X.servlet.http.HttpServletRequest\
\ $REQ));\n...\nfor(FileItem $ITEM : $FILES) {\n ...\n}\n"
- pattern: $ITEM.getName()
- pattern: ($X.servlet.http.Part $PART).getSubmittedFileName()
metadata:
shortDescription: Improper limitation of a pathname to a restricted directory ('Path Traversal')
cwe: CWE-22
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
security-severity: Info
category: security
technology:
- java
severity: WARNING
- id: gitlab-java_file_rule-FilenameUtils
languages: [java]
message: "The filename provided by the FileUpload API can be tampered with by the client to reference\n\
unauthorized files. The provided filename should be properly validated to ensure it's properly\nstructured,\
\ contains no unauthorized path characters (e.g., / \\), and refers to an authorized\nfile.\n\nThe application\
\ was found to take a parameter from user input to construct a path name. If an\nunfiltered parameter\
\ is passed to this file API, files from an arbitrary filesystem location\ncould be read. When data\
\ from an unstrusted source is untrusted source is used to construct\na file path, an attacker could\
\ potentially gain access to restrcited files locations outside\nthe relevant context.\n\nFor example,\
\ if the application tries to access the users profile picture based on their user\nname by concatenating\
\ the username to the filepath:\n\n\"images/userprofiles/\" + username\n\nThe expected result of this\
\ would be \"images/userprofiles/alice\", however an attacker could\nuse a malicious input such as \"\
../../../etc/passwd\" to gain access to and/or manipulate\nsensitive information\n\nAssume all input\
\ is malicious. Use an \"accept known good\" input validation strategy.\n\nInputs can be sanitized by\
\ using the getName() method with concat() method to remove the \npotentially malicious path traversal\
\ and limit the scope to a restricted directory. Or \ninput can also be sanitized by using resolve()\
\ method alongwith startsWith() method to \nverify that the base path of the file is safe and expected.\n\
\nExample of limiting path traversal using getName:\n\n```\nprotected void doPut(HttpServletRequest\
\ req, HttpServletResponse resp) throws ServletException, IOException {\n\n String input = req.getHeader(\"\
input\");\n\n input = getName(input);\n \n String safePath = concat(basePath, input);\n\n \
\ // Read the contents of the file\n File file = new File(safePath);\n}\n```\n"
metadata:
category: security
cwe: CWE-22
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
shortDescription: Improper limitation of a pathname to a restricted directory ('Path Traversal')
security-severity: Info
technology:
- java
mode: taint
pattern-sanitizers:
- pattern: '$NAME = org.apache.commons.io.FilenameUtils.getName(...);
...
$SAFE = concat($BASE, $NAME);
'
- pattern: "$RET $FUN(...){\n ...\n $PATH = $BP.resolve(...);\n ...\n if(!$PATH.startsWith(...)) {\n\
\ throw new $EXC(...);\n }\n ...\n}\n"
pattern-sources:
- pattern: (HttpServletRequest $REQ)
pattern-sinks:
- pattern: org.apache.commons.io.FilenameUtils.concat(...)
- pattern: org.apache.commons.io.FilenameUtils.getFullPath(...)
- pattern: org.apache.commons.io.FilenameUtils.getFullPathNoEndSeparator(...)
- pattern: org.apache.commons.io.FilenameUtils.getPath(...)
- pattern: org.apache.commons.io.FilenameUtils.getPathNoEndSeparator(...)
- pattern: org.apache.commons.io.FilenameUtils.normalize(...)
- pattern: org.apache.commons.io.FilenameUtils.normalizeNoEndSeparator(...)
- pattern: org.apache.commons.io.FilenameUtils.normalizeNoEndSeparator(...)
- pattern: org.apache.commons.io.FilenameUtils.removeExtension(...)
- pattern: org.apache.commons.io.FilenameUtils.separatorsToSystem(...)
- pattern: org.apache.commons.io.FilenameUtils.separatorsToUnix(...)
- pattern: org.apache.commons.io.FilenameUtils.separatorsToWindows(...)
severity: WARNING
- id: gitlab-java_inject_rule-CommandInjection
languages: [java]
mode: taint
pattern-sources:
- pattern: (javax.servlet.http.HttpServletRequest $R).$METHOD(...)
- pattern: (java.util.Scanner $S).$METHOD(...)
- pattern: (java.util.stream.Stream).$METHOD(...)
- pattern: (java.util.StringJoiner $SJ).toString(...)
- pattern: (java.sql.ResultSet.getString $R).$METHOD(...)
- pattern: (java.lang.System $S).getProperty(...)
- pattern: (java.lang.System $S).getenv(...)
- pattern: (java.lang.StringBuilder $SB).toString(...)
- pattern: (java.io.FileInputStream $F).read(...)
- pattern: (java.io.FileReader $F).read(...)
- pattern: (java.net.Socket $S).getInputStream(...)
- pattern: (java.net.Socket $S).getOutputStream(...)
- pattern: (java.net.DatagramSocket $S).receive(...)
- pattern: (java.net.DatagramSocket $S).getInputStream(...)
- pattern: java.nio.file.Files.readAllBytes(...)
- pattern: java.nio.file.Files.readAllLines(...)
- pattern: java.nio.file.Files.lines(...)
- pattern: java.nio.file.Files.newBufferedReader(...)
- pattern: org.apache.commons.io.IOUtils.toString(...)
- pattern: org.apache.commons.io.IOUtils.readLines(...)
- pattern: org.apache.commons.io.IOUtils.toByteArray(...)
- pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).readValue(...)
- pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).treeToValue(...)
- pattern: $CLASS.$METHOD(..., (javax.servlet.http.HttpServletRequest $R), ...)
- pattern: $FUNC(..., (javax.servlet.http.HttpServletRequest $R), ...)
- patterns:
- pattern-inside: $FUNC(..., String $X, ...) { ... }
- focus-metavariable: $X
pattern-propagators:
- pattern: $LIST.add($X)
from: $X
to: $LIST
- pattern: $MAP.put(..., $X)
from: $X
to: $MAP
- pattern: $STR.concat($X)
from: $X
to: $STR
- pattern: $STR = String.format(..., $X, ...)
from: $X
to: $STR
- pattern: $STR = String.join(..., $X, ...)
from: $X
to: $STR
pattern-sinks:
- pattern: (ProcessBuilder $PB).command(...)
- pattern: new ProcessBuilder(...)
- pattern: (Runtime $R).exec(...)
message: "OS command injection is a critical vulnerability that can lead to a full system\ncompromise\
\ as it may allow an adversary to pass in arbitrary commands or arguments\nto be executed.\n\nUser input\
\ should never be used in constructing commands or command arguments\nto functions which execute OS\
\ commands. This includes filenames supplied by\nuser uploads or downloads.\n\nEnsure your application\
\ does not:\n\n- Use user-supplied information in the process name to execute.\n- Use user-supplied\
\ information in an OS command execution function which does\nnot escape shell meta-characters.\n- Use\
\ user-supplied information in arguments to OS commands.\n\nThe application should have a hardcoded\
\ set of arguments that are to be passed\nto OS commands. If filenames are being passed to these functions,\
\ it is\nrecommended that a hash of the filename be used instead, or some other unique\nidentifier.\
\ It is strongly recommended that a native library that implements\nthe same functionality be used instead\
\ of using OS system commands, due to the\nrisk of unknown attacks against third party commands.\n\n\
When specifying the OS command, ensure the application uses the full path\ninformation, otherwise the\
\ OS may attempt to look up which process to execute\nand could be vulnerable to untrusted search path\
\ vulnerabilities (CWE-426).\n\nExample of safely executing an OS command:\n```\npublic static void\
\ executeCommand(String userFileData) throws java.io.IOException {\n // Generate a random filename,\
\ do not use user input\n String fileName = UUID.randomUUID().toString();\n // Create a Buffered/FileWriter\n\
\ BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));\n // Write the user content\
\ to our random file\n writer.write(userFileData);\n // Close the file to flush contents\n \
\ writer.close();\n // Create the process builder with a hardcoded path to the binary, and our randomly\n\
generated filename\n ProcessBuilder processBuilder = new ProcessBuilder(\"/opt/app/path\", fileName);\n\
\ // Start the process\n Process process = processBuilder.start();\n // Handle/redirect output\
\ of process here\n // ...\n}\n```\n\nFor more information on OS command injection, see OWASP's guide:\n\
https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html\n"
severity: WARNING
metadata:
shortDescription: Improper neutralization of special elements used in an OS command ('OS Command Injection')
category: security
cwe: CWE-78
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
technology:
- java
security-severity: High
- id: gitlab-java_inject_rule-ELInjection
languages: [java]
message: "This rule identifies potential Expression Language (EL) injection vulnerabilities within Java\
\ applications. \nThe rule targets use of `createValueExpression`, `createMethodExpression`, `ELProcessor.eval`,\
\ `getValue`, \nand `setValue` methods, particularly when input to these methods is not a hardcoded\
\ string, indicating dynamic \nevaluation of potentially untrusted input. \n\n`createValueExpression`\
\ creates a `ValueExpression` object which gets evaluated upon calling methods like \n`getValue()` and\
\ `setValue()` or a Lambda `invoke()` i.e. it evaluates the expression passed to the \n`createValueExpression`\
\ method.\n\nSimilarly, `createMethodExpression` creates a `MethodExpression` object which gets evaluated\
\ upon calling \nmethods like `invoke()` and `getMethodInfo()`.\n`ELProcessor.eval`, `getValue()`, and\
\ `setValue()` methods all evaluate their expressions which are passed \nas parameters.\n\nCalling these\
\ method directly with user-supplied input may allow an adversary to execute arbitrary Java \ncode,\
\ including OS system commands. Never call these methods directly with user-supplied input. Consider\
\ \nalternate methods such as a lookup table to take user input and resolve hardcoded values.\n\nSecure\
\ example:\n\n```\nimport javax.el.ELProcessor;\nimport java.util.Set;\n\npublic class SafeELHandling\
\ {\n private static final Set<String> ALLOWED_VALUES = Set.of(\"value1\", \"value2\", \"value3\"\
);\n\n public void processInput(String userInput) {\n // Validate user input against the allowlist\n\
\ if (!ALLOWED_VALUES.contains(userInput)) {\n throw new IllegalArgumentException(\"\
Invalid input\");\n }\n \n ELProcessor elProcessor = new ELProcessor();\n \
\ elProcessor.defineBean(\"userInput\", userInput);\n \n // Example EL expression using\
\ the safe, predefined input\n String result = (String) elProcessor.eval(userInput);\n }\n\
}\n```\n"
metadata:
category: security
cwe: CWE-917
shortDescription: Improper neutralization of special elements used in an expression language statement
('Expression Language Injection')
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
technology:
- java
security-severity: Info
pattern-either:
- patterns:
- pattern: '(ExpressionFactory $EXP).createValueExpression((ELContext $CTX), $EXPR,
...)
'
- pattern-not: '(ExpressionFactory $EXP).createValueExpression((ELContext $CTX), "...",
...)
'
- patterns:
- pattern: '(ExpressionFactory $EXP).createMethodExpression((ELContext $CTX), $EXPR,
...)
'
- pattern-not: '(ExpressionFactory $EXP).createMethodExpression((ELContext $CTX), "...",
...)
'
- patterns:
- pattern: '($X.el.ELProcessor $P).eval(...)
'
- pattern-not: '($X.el.ELProcessor $P).eval("...", ...)
'
- patterns:
- pattern: '($X.el.ELProcessor $P).getValue(...)
'
- pattern-not: '($X.el.ELProcessor $P).getValue("...", ...)
'
- patterns:
- pattern: '($X.el.ELProcessor $P).setValue(...)
'
- pattern-not: "($X.el.ELProcessor $P).setValue(\"...\", \"...\") \n"
severity: WARNING
- id: gitlab-java_inject_rule-FileDisclosureRequestDispatcher
languages: [java]
mode: taint
pattern-sources:
- pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameter(...)
- pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameterNames();
- pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameterValues(...);
- pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameterMap();
- pattern: (javax.servlet.http.HttpServletRequest $VAR).getHeader(...);
- pattern: (javax.servlet.http.HttpServletRequest $VAR).getPathInfo();
pattern-sinks:
- patterns:
- pattern-not-inside: '$VAL = $MAP.getOrDefault(..., "...");
...
'
- pattern-inside: '$REQ = $HTTP.getRequestDispatcher(...);
...
'
- pattern-either:
- pattern: $REQ.include($FST, $SND)
- pattern: $REQ.forward($FST, $SND)
message: 'The `HttpRequest.getRequestDispatcher()`''s `include` and `forward` methods will return
any file that is resolvable within the web application context. This includes the `web.xml`
file, any compiled classes, `jsp` files, and additional JAR or WAR libraries that are
accessible.
Never pass user-supplied input directly to any of these methods. Use a lookup table or
hardcode
which views or paths the user should be directed to. Another option is to use a simple HTTP
redirect by returning an empty response body with a 301 status code and a `Location` redirect
header. In Java servlets, this can be done by using the `response.sendRedirect(...)` method.
Example using a redirect instead of a `RequestDispatcher`:
```
// Create a look up table or pull from a data source
HashMap<String, String> lookupTable = new HashMap<>();
lookupTable.put("key1", "/Resource1");
lookupTable.put("key2", "/Resource2");
// Get user input
String userInput = request.getParameter("key");
// Look up resource to redirect to from the user input
String redirectValue = lookupTable.getOrDefault(userInput, "/Resource1");
// Redirect the user
response.sendRedirect(redirectValue);
```
'
metadata:
shortDescription: Files or directories accessible to external parties
category: security
cwe: CWE-552
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
security-severity: HIGH
severity: ERROR
- id: gitlab-java_inject_rule-FileDisclosureSpringFramework
languages: [java]
mode: taint
pattern-sources:
- pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameter(...)
- pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameterNames();
- pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameterValues(...);
- pattern: (javax.servlet.http.HttpServletRequest $VAR).getParameterMap();
- pattern: (javax.servlet.http.HttpServletRequest $VAR).getHeader(...);
- pattern: (javax.servlet.http.HttpServletRequest $VAR).getPathInfo();
pattern-sinks:
- patterns:
- pattern-not-inside: "$FST = $MAP.getOrDefault(..., \"...\");\n ...\n"
- pattern: new org.springframework.web.servlet.ModelAndView($FST, ...);
- focus-metavariable: $FST
- patterns:
- pattern-not-inside: '$FST = $MAP.getOrDefault(..., "...");
...
'
- pattern-inside: '$MVC = new org.springframework.web.servlet.ModelAndView();
...
'
- pattern: $MVC.setViewName(...);
message: "The `org.springframework.web.servlet.ModelAndView` class may\npotentially allow access to restricted\
\ files if called with user-supplied input.\n\nThe ModelAndView class looks up a view by name to resolve\
\ a `.jsp`\nfile. If this view name comes from user-supplied input, it could be abused to attempt\n\
to return a JSP view that the user should not have access to.\n\nUse a lookup table or hardcode which\
\ views or paths the user should be directed to.\n\nExample using a lookup table to resolve a view from\
\ a Spring MVC application:\n```\n@RequestMapping(value=\"/mvc\", method=RequestMethod.GET)\npublic\
\ ModelAndView mvc(HttpServletRequest request, HttpServletResponse response, Model model)\n {\n //\
\ Create a look up table or pull from a data source\n HashMap<String, String> lookupTable = new HashMap<>();\n\
\ lookupTable.put(\"key1\", \"view1\");\n lookupTable.put(\"key2\", \"view2\");\n // Get user input\n\
\ String userInput = request.getParameter(\"key\");\n // Look up view from the user input\n String\
\ viewValue = lookupTable.getOrDefault(userInput, \"Resource1\");\n // return the new model and view\n\
\ return new ModelAndView(viewValue);\n}\n```\n\nExample using a redirect instead of a `RequestDispatcher`\
\ in Spring:\n```\n@RequestMapping(value=\"/mvc\", method=RequestMethod.GET)\npublic void mvc(HttpServletRequest\
\ request, HttpServletResponse response, Model model)\n {\n // Create a look up table or pull from\
\ a data source\n HashMap<String, String> lookupTable = new HashMap<>();\n lookupTable.put(\"key1\"\
, \"view1\");\n lookupTable.put(\"key2\", \"view2\");\n // Get user input\n String userInput = request.getParameter(\"\
key\");\n // Look up resource to redirect to from the user input\n String redirectValue = lookupTable.getOrDefault(userInput,\
\ \"/Resource1\");\n // return the new model and view\n response.sendRedirect(redirectValue);\n}\n\
```\n"
metadata:
shortDescription: Files or directories accessible to external parties
category: security
cwe: CWE-552
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
security-severity: HIGH
severity: ERROR
- id: gitlab-java_inject_rule-HttpParameterPollution
languages: [java]
mode: taint
pattern-sources:
- pattern: (HttpServletRequest $REQ).getParameter(...)
pattern-sanitizers:
- pattern: java.net.URLEncoder.encode(...)
- pattern: com.google.common.net.UrlEscapers.urlPathSegmentEscaper().escape(...)
pattern-sinks:
- pattern: new org.apache.http.client.methods.HttpGet(...)
- pattern: new org.apache.commons.httpclient.methods.GetMethod(...)
- pattern: (org.apache.commons.httpclient.methods.GetMethod $GM).setQueryString(...)
message: "The application was found including unvalidated user input into a URL, which could lead to\n\
HTTP Parameter Pollution (HPP) or worse, Server Side Request Forgery (SSRF). This could\nallow an adversary\
\ to override the value of a URL or a request parameter. HTTP Parameter\nPollution\n(HPP) attacks consist\
\ of injecting encoded query string delimiters into other existing\nparameters. If a web\napplication\
\ does not properly sanitize the user input, an adversary may modify the logic of\nthese\nrequests to\
\ other applications.\n\nTo remediate this issue, never allow user input directly into creation of a\
\ URL or URL\nparameter. Consider\nusing a map to look up user-supplied information and return exact\
\ values to be used in the\ngeneration of\nrequests.\n\nExample using a map to look up a key to be used\
\ in a HTTP request:\n```\nHashMap<String, String> lookupTable = new HashMap<>();\nlookupTable.put(\"\
key1\", \"value1\");\nlookupTable.put(\"key2\", \"value2\");\nString userInput = request.getParameter(\"\
key\");\n\n// Create a CloseableHttpClient, ideally any requests issued should be done\n// out-of-band\
\ from the servlet request itself (such as using a separate thread/scheduler\nsystem)\ntry (final CloseableHttpClient\
\ httpClient = HttpClients.createDefault()) {\n // Lookup the value from our user input from our\
\ lookupTable\n String value = lookupTable.getOrDefault(userInput, \"value1\");\n // Construct\
\ the url, with the hardcoded url and only pass in the value from the\nlookupTable,\n // not direct\
\ user input\n final HttpGet httpget = new HttpGet(\"https://example.com/getId?key=\"+value);\n \
\ // Execute the request\n CloseableHttpResponse clientResponse = httpClient.execute(httpget);\n\
\ // Read the response\n byte[] responseData = clientResponse.getEntity().getContent().readAllBytes();\n\
\ // Handle the response\n // ...\n}\n```\n\nIf using a map is not possible, the user-supplied\
\ input must be encoded prior to use, and\nnever allow full\nURLs:\n```\n// Get user input\nString userInput\
\ = request.getParameter(\"key\");\n// Encode the string using java.net.URLEncoder with the UTF-8 character\
\ set\nString encodedString = java.net.URLEncoder.encode(userInput, StandardCharsets.UTF_8);\n// Create\
\ a CloseableHttpClient, ideally any requests issued should be done\n// out-of-band from the servlet\
\ request itself (such as using a separate thread/scheduler\nsystem)\ntry (final CloseableHttpClient\
\ httpClient = HttpClients.createDefault()) {\n // Construct the url, with the hardcoded url and only\
\ pass in the encoded value, never a\nfull URL\n final HttpGet httpget = new HttpGet(\"https://example.com/getId?key=\"\
+encodedString);\n // Execute the request\n CloseableHttpResponse clientResponse = httpClient.execute(httpget);\n\
\ // Read the response\n byte[] responseData = clientResponse.getEntity().getContent().readAllBytes();\n\
\ // handle the response\n}\n```\n\nFor more information on SSRF see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html\n\
\nFor more information on HTTP Parameter Pollution see:\nhttps://en.wikipedia.org/wiki/HTTP_parameter_pollution\n"
severity: ERROR
metadata:
shortDescription: Improper neutralization of argument delimiters in a command ('Argument Injection')
category: security
cwe: CWE-88
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
technology:
- java
security-severity: Medium
- id: gitlab-java_inject_rule-LDAPInjection
languages: [java]
mode: taint
pattern-sinks:
- pattern: javax.naming.ldap.LdapName(...)
- pattern: (javax.naming.directory.Context $C).lookup(...)
- pattern: (javax.naming.Context $C).lookup(...)
- patterns:
- pattern-inside: (com.unboundid.ldap.sdk.LDAPConnection $C).search($QUERY, ...)
- pattern: $QUERY
- patterns:
- pattern-either:
- pattern: $CTX.lookup(...)
- patterns:
- pattern-inside: $CTX.search($QUERY, ...)
- pattern: $QUERY
- patterns:
- pattern-inside: $CTX.search($NAME, $FILTER, ...)
- pattern: $FILTER
- metavariable-pattern:
metavariable: $CTX
pattern-either:
- pattern: (DirContext $C)
- pattern: (InitialDirContext $IDC)
- pattern: (LdapContext $LC)
- pattern: (EventDirContext $EDC)
- pattern: (LdapCtx $LC)
- pattern: (javax.naming.directory.DirContext $C)
- pattern: (javax.naming.directory.InitialDirContext $IDC)
- pattern: (javax.naming.ldap.LdapContext $LC)
- pattern: (javax.naming.event.EventDirContext $EDC)
- pattern: (com.sun.jndi.ldap.LdapCtx $LC)
- patterns:
- pattern-either:
- patterns:
- pattern-inside: $CTX.list($QUERY, ...)
- pattern: $QUERY
- patterns:
- pattern-inside: $CTX.lookup($QUERY, ...)
- pattern: $QUERY
- patterns:
- pattern-inside: $CTX.search($QUERY, ...)
- pattern: $QUERY
- patterns:
- pattern-inside: $CTX.search($NAME, $FILTER, ...)
- pattern: $FILTER
- metavariable-pattern:
metavariable: $CTX
pattern-either:
- pattern: (LdapTemplate $LT)
- pattern: (LdapOperations $LO)
- pattern: (org.springframework.ldap.core.LdapTemplate $LT)
- pattern: (org.springframework.ldap.core.LdapOperations $LO)
pattern-sources:
- patterns:
- pattern-inside: "$FUNC(..., $T $VAR, ...) {\n ...\n}\n"
- pattern: $VAR
- patterns:
- pattern-inside: "$FUNC(..., $T $X, ...) {\n ...\n $VAR = ... + $X;\n ...\n}\n"
- pattern: $VAR
message: "LDAP injection attacks exploit LDAP queries to influence how data is returned by\nthe LDAP server.\n\
\nLater versions of Java's `InitialDirContext.search` introduced a four argument method, one of\nwhich\
\ is the `filterArg` parameter. The `filterArg` will be automatically encoded when\nquerying\nthe LDAP\
\ server. If this method signature is not available, the application must encode the\nLDAP strings manually.\n\
\nMore details on the four argument `search` method can be found here:\nhttps://docs.oracle.com/en/java/javase/20/docs/api/java.naming/javax/naming/directory/InitialDirContext.html#search(javax.naming.Name,java.lang.String,java.lang.Object[],javax.naming.directory.SearchControls)\n\
\nTo encode the string manually, it is recommended that all input passed to LDAP querying\nsystems\n\
encode the following values:\n\n- Any occurrence of the null character must be escaped as “\\00”.\n\
- Any occurrence of the open parenthesis character must be escaped as “\\28”.\n- Any occurrence of the\
\ close parenthesis character must be escaped as “\\29”.\n- Any occurrence of the asterisk character\
\ must be escaped as “\\2a”.\n- Any occurrence of the backslash character must be escaped as “\\5c”.\n\
\nExample function that safely encodes user-supplied input to be used in an LDAP query.\n```\npublic\
\ static String encodeLDAPString(String input) {\n // Note the \\ character is replaced first\n CharSequence[]\
\ chars = new CharSequence[] { \"\\\\\", \"\\0\", \"(\", \")\", \"*\" };\n CharSequence[] encoded =\
\ new CharSequence[] { \"\\\\5c\", \"\\\\00\", \"\\\\28\", \"\\\\29\", \"\\\\2a\" };\n // Iterate over\
\ each character sequence, replacing the raw value with an encoded version of\nit\n for (int i = 0;\
\ i < chars.length; i++)\n {\n // re-assign to input\n input = input.replace(chars[i], encoded[i]);\n\
\ }\n // return our modified input string\n return input;\n}\n```\n\nExample code that using the\
\ `filterArgs` parameter which automatically encodes for us:\n```\n// Create a properties to hold the\
\ ldap connection details\nProperties props = new Properties();\n// Use the com.sun.jndi.ldap.LdapCtxFactory\
\ factory provider\nprops.put(Context.INITIAL_CONTEXT_FACTORY, \"com.sun.jndi.ldap.LdapCtxFactory\"\
);\n// The LDAP server URL\nprops.put(Context.PROVIDER_URL, \"ldap://ldap.example.org:3889\");\n// User\
\ details for the connection\nprops.put(Context.SECURITY_PRINCIPAL, \"cn=admin,dc=example,dc=org\");\n\
// LDAP account password\nString ldapAccountPassword = getAccountPasswordFromSecureStoreOrKMS();\n//\
\ Pass in the LDAP password\nprops.put(Context.SECURITY_CREDENTIALS, ldapAccountPassword);\n\n// Create\
\ the LDAPContext\nInitialDirContext ldapContext = new InitialDirContext(props);\n// Example using SUBTREE_SCOPE\
\ SearchControls\nSearchControls searchControls = new SearchControls();\nsearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);\n\
\n// Get user input for query\nString userQuery = someUserInput;\n// Use searchArguments to hold the\
\ user-supplied input\nObject[] searchArguments = new Object[]{userQuery};\n// Hardcode the BaseDN,\
\ use the {0} format specifier to use the searchArguments array value,\nand pass in the search controls.\n\
// searchArguments automatically encode\nNamingEnumeration answer = ldapContext.search(\"dc=example,dc=org\"\
, \"(cn={0})\",\nsearchArguments, searchControls);\n// Process the response answer\nwhile (answer.hasMoreElements())\
\ {\n ...\n}\n```\n\nFor more information on LDAP Injection see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html\n"
severity: WARNING
metadata:
shortDescription: Improper neutralization of special elements used in an LDAP query ('LDAP Injection')
category: security
cwe: CWE-90
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
technology:
- java
security-severity: Medium
- id: gitlab-java_inject_rule-OgnlInjection
languages: [java]
mode: taint
pattern-sources:
- patterns:
- pattern-inside: "$FUNC(..., $T $VAR, ...) {\n ...\n}\n"
- metavariable-pattern:
metavariable: $VAR
pattern-either:
- pattern: (String $S)
- pattern: (Map<String, ?> $M)
- pattern: (Map<String, String> $M)
- pattern: (Map<String, Object> $M)
- pattern: $VAR
pattern-sinks:
- patterns:
- pattern-inside: com.opensymphony.xwork2.util.TextParseUtil.translateVariables($VAL, ...)
- pattern: $VAL
- patterns:
- pattern-inside: com.opensymphony.xwork2.util.TextParseUtil.translateVariablesCollection($VAL, ...)
- pattern: $VAL
- pattern: com.opensymphony.xwork2.util.TextParseUtil.shallBeIncluded(...)
- pattern: com.opensymphony.xwork2.util.TextParseUtil.commaDelimitedStringToSet(...)
- patterns:
- pattern-inside: (com.opensymphony.xwork2.util.TextParser $P).evaluate($VAR, $VAL, ...)
- pattern: $VAL
- patterns:
- pattern-inside: (com.opensymphony.xwork2.util.OgnlTextParser $P).evaluate($VAR, $VAL, ...)
- pattern: $VAL
- pattern: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).getGetMethod($CLZ, ...)
- pattern: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).getSetMethod($CLZ, ...)
- pattern: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).getField($CLZ, ...)
- patterns:
- pattern-inside: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).setProperties($MAP, ...)
- pattern: $MAP
- patterns:
- pattern-inside: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).setProperty($VAL, ...)
- pattern: $VAL
- patterns:
- pattern-inside: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).getValue($VAL, ...)
- pattern: $VAL
- patterns:
- pattern-inside: (com.opensymphony.xwork2.ognl.OgnlReflectionProvider $P).setValue($VAL, ...)
- pattern: $VAL
- pattern: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).getGetMethod($CLZ, ...)
- pattern: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).getSetMethod($CLZ, ...)
- pattern: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).getField($CLZ, ...)
- patterns:
- pattern-inside: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).setProperties($MAP,
...)
- pattern: $MAP
- patterns:
- pattern-inside: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).setProperty($VAR,
...)
- pattern: $VAR
- patterns:
- pattern-inside: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).getValue($VAR, ...)
- pattern: $VAR
- patterns:
- pattern-inside: (com.opensymphony.xwork2.util.reflection.ReflectionProvider $P).setValue($VAR, ...)
- pattern: $VAR
- patterns:
- pattern-inside: (com.opensymphony.xwork2.ognl.OgnlUtil $P).setProperties($MAP, ...)
- pattern: $MAP
- patterns:
- pattern-inside: (com.opensymphony.xwork2.ognl.OgnlUtil $P).setProperty($VAR, ...)
- pattern: $VAR
- patterns:
- pattern-inside: (com.opensymphony.xwork2.ognl.OgnlUtil $P).getValue($VAR, ...)
- pattern: $VAR
- patterns:
- pattern-inside: (com.opensymphony.xwork2.ognl.OgnlUtil $P).setValue($VAR, ...)
- pattern: $VAR
- patterns:
- pattern-inside: (com.opensymphony.xwork2.ognl.OgnlUtil $P).callMethod($VAR, ...)
- pattern: $VAR
- patterns:
- pattern-inside: (com.opensymphony.xwork2.ognl.OgnlUtil $P).compile($VAR, ...)
- pattern: $VAR
- pattern: (org.apache.struts2.util.VelocityStrutsUtil $P).evaluate(...)
- pattern: org.apache.struts2.util.StrutsUtil.findString(...)
- pattern: org.apache.struts2.util.StrutsUtil.findValue(..., $VAL)
- pattern: org.apache.struts2.util.StrutsUtil.getText(...)
- pattern: org.apache.struts2.util.StrutsUtil.translateVariables(...)
- patterns:
- pattern-inside: org.apache.struts2.util.StrutsUtil.makeSelectList($VAR, ...)
- pattern: $VAR
- patterns:
- pattern-inside: (org.apache.struts2.views.jsp.ui.OgnlTool $T).findValue($VAR, ...)
- pattern: $VAR
- pattern: (com.opensymphony.xwork2.util.ValueStack $V).findString(...)
- patterns:
- pattern-inside: (com.opensymphony.xwork2.util.ValueStack $V).findValue($VAR, ...)
- pattern: $VAR
- patterns:
- pattern-inside: (com.opensymphony.xwork2.util.ValueStack $V).setValue($VAR, ...)
- pattern: $VAR
- patterns:
- pattern-inside: (com.opensymphony.xwork2.util.ValueStack $V).setParameter($VAR, ...)
- pattern: $VAR
message: 'The Object Graph Navigation Language (OGNL) is an expression language that allows access to
Java objects and properties stored in an ActionContext. Usage of these low-level
functions is discouraged because they can effectively execute strings as code, leading to
remote code execution vulnerabilities. Consider using struts tags when processing
user-supplied input and templates.
Much like the Struts security guide recommending to not use raw `${}` EL expressions,
do not call or use the following OGNL packages with user-supplied input:
- `com.opensymphony.xwork2.ognl`
- `com.opensymphony.xwork2.util`
- `com.opensymphony.xwork2.util.reflection`
- `org.apache.struts2.util.StrutsUtil`
For more information on Struts2 security see:
https://struts.apache.org/security/#do-not-use-incoming-untrusted-user-input-in-forced-expression-evaluation
'
severity: WARNING
metadata:
shortDescription: Expression injection (OGNL)
category: security
cwe: CWE-917
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
technology:
- java
security-severity: High
- id: gitlab-java_inject_rule-SpotbugsPathTraversalAbsolute
languages: [java]
mode: taint
pattern-sources:
- pattern: (javax.servlet.http.HttpServletRequest $R).$METHOD(...)
- pattern: (java.util.Scanner $S).$METHOD(...)
- pattern: (java.util.stream.Stream).$METHOD(...)
- pattern: (java.util.StringJoiner $SJ).toString(...)
- pattern: (java.sql.ResultSet.getString $R).$METHOD(...)
- pattern: (java.lang.System $S).getProperty(...)
- pattern: (java.lang.System $S).getenv(...)
- pattern: (java.lang.StringBuilder $SB).toString(...)
- pattern: (java.io.FileInputStream $F).read(...)
- pattern: (java.io.FileReader $F).read(...)
- pattern: (java.net.Socket $S).getInputStream(...)
- pattern: (java.net.Socket $S).getOutputStream(...)
- pattern: (java.net.DatagramSocket $S).receive(...)
- pattern: (java.net.DatagramSocket $S).getInputStream(...)
- pattern: java.nio.file.Files.readAllBytes(...)
- pattern: java.nio.file.Files.readAllLines(...)
- pattern: java.nio.file.Files.lines(...)
- pattern: java.nio.file.Files.newBufferedReader(...)
- pattern: org.apache.commons.io.IOUtils.toString(...)
- pattern: org.apache.commons.io.IOUtils.readLines(...)
- pattern: org.apache.commons.io.IOUtils.toByteArray(...)
- pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).readValue(...)
- pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).treeToValue(...)
- pattern: $CLASS.$METHOD(..., (javax.servlet.http.HttpServletRequest $R), ...)
- pattern: $FUNC(..., (javax.servlet.http.HttpServletRequest $R), ...)
- patterns:
- pattern-inside: $FUNC(..., @RequestParam String $X, ...) { ... }
- focus-metavariable: $X
pattern-propagators:
- pattern: $LIST.add($X)
from: $X
to: $LIST
- pattern: $MAP.put(..., $X)
from: $X
to: $MAP
- pattern: $STR.concat($X)
from: $X
to: $STR
- pattern: $STR = String.format(..., $X, ...)
from: $X
to: $STR
- pattern: $STR = String.join(..., $X, ...)
from: $X
to: $STR
pattern-sanitizers:
- pattern: org.apache.commons.io.FilenameUtils.getName(...)
pattern-sinks:
- patterns:
- pattern-inside: '$U = new java.net.URI($VAR)
'
- pattern-either:
- pattern-inside: new java.io.File($U)
- pattern-inside: java.nio.file.Paths.get($U)
- pattern: $VAR
- patterns:
- pattern-inside: new java.io.RandomAccessFile($INPUT,...)
- pattern: $INPUT
- pattern: new java.io.FileReader(...)
- pattern: new javax.activation.FileDataSource(...)
- pattern: new java.io.FileInputStream(...)
- pattern: new java.io.FileOutputStream(...)
- pattern: new java.io.File(...)
- pattern: java.nio.file.Paths.get(...)
- pattern: java.io.File.createTempFile(...)
- pattern: java.io.File.createTempDirectory(...)
- pattern: java.nio.file.Files.createTempFile(...)
- pattern: java.nio.file.Files.createTempDirectory(...)
- patterns:
- pattern: $SRC.$METHOD(...)
- metavariable-pattern:
metavariable: $SRC
pattern-either:
- pattern: getClass()
- pattern: getClass().getClassLoader()
- pattern: (ClassLoader $C)
- pattern: (Class $C)
- pattern: $CLZ.getClassLoader()
- metavariable-pattern:
metavariable: $METHOD
pattern-either:
- pattern: getResourceAsStream
- pattern: getResource
- patterns:
- pattern-inside: new java.io.FileWriter($PATH, ...)
- pattern: $PATH
- patterns:
- pattern-inside: new java.io.FileOutputStream($PATH, ...)
- pattern: $PATH
message: "The application dynamically constructs file or path information. If the path\ninformation comes\
\ from user input, it could be abused to read sensitive files,\naccess other users' data, or aid in\
\ exploitation to gain further system access.\n\nUser input should never be used in constructing paths\
\ or files for interacting\nwith the filesystem. This includes filenames supplied by user uploads or\
\ downloads.\nIf possible, consider hashing user input or replacing it with unique values and\nuse `Path.resolve`\
\ to resolve and validate the path information\nprior to processing any file functionality.\n\nExample\
\ using `Path.resolve` and not allowing direct user input:\n```\n// Class to store our user data along\
\ with a randomly generated file name\npublic static class UserData {\n private String userFileNameUnsafe;\n\
\ private String fileName;\n public UserData(String userFileName) {\n this.userFileNameUnsafe\
\ = userFileName;\n // Generate a random ID for the filename\n this.fileName = UUID.randomUUID().toString();\n\
\ }\n public String getUserFileNameUnsafe() { return userFileNameUnsafe; };\n public String\
\ getFileName() { return fileName; };\n}\n\npublic static void main(String[] args) throws Exception\
\ {\n // User input, saved only as a reference\n UserData userData = new UserData(\"..\\\\test.txt\"\
);\n // Restrict all file processing to this directory only\n String base = \"/var/app/restricted\"\
;\n Path basePath = Paths.get(base);\n // Resolve the full path, but only use our random generated\
\ filename\n Path fullPath = basePath.resolve(userData.getFileName());\n // verify the path is\
\ contained within our basePath\n if (!fullPath.startsWith(base)) {\n throw new Exception(\"\
Invalid path specified!\");\n }\n // process / work with file\n}\n```\n\nFor more information\
\ on path traversal issues see OWASP:\nhttps://owasp.org/www-community/attacks/Path_Traversal\n"
metadata:
shortDescription: Improper limitation of a pathname to a restricted directory ('Path Traversal')
cwe: CWE-22
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
security-severity: Medium
technology:
- java
category: security
severity: WARNING
- id: gitlab-java_ldap_rule-AnonymousLDAP
languages: [java]
patterns:
- pattern-inside: 'import javax.naming.Context;
...
'
- pattern: $ENV.put(Context.SECURITY_AUTHENTICATION, "none");
message: "The application does not provide authentication when communicating an LDAP\nserver. It is strongly\
\ recommended that the LDAP server be configured with\nauthentication and restrict what queries users\
\ can execute.\n\nExample code that authenticates with a remote LDAP server and encodes any\nuser-supplied\
\ input:\n```\n// Create a properties to hold the ldap connection details\nProperties props = new Properties();\n\
// Use the com.sun.jndi.ldap.LdapCtxFactory factory provider\nprops.put(Context.INITIAL_CONTEXT_FACTORY,\
\ \"com.sun.jndi.ldap.LdapCtxFactory\");\n// The LDAP server URL\nprops.put(Context.PROVIDER_URL, \"\
ldap://ldap.example.org:3889\");\n// User details for the connection\nprops.put(Context.SECURITY_PRINCIPAL,\
\ \"cn=admin,dc=example,dc=org\");\n// LDAP account password\nString ldapAccountPassword = getAccountPasswordFromSecureStoreOrKMS();\n\
// Pass in the LDAP password\nprops.put(Context.SECURITY_CREDENTIALS, ldapAccountPassword);\n\n// Create\
\ the LDAPContext\nInitialDirContext ldapContext = new InitialDirContext(props);\n// Example using SUBTREE_SCOPE\
\ SearchControls\nSearchControls searchControls = new SearchControls();\nsearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);\n\
\n// Get user input for query\nString userQuery = someUserInput;\n// Use searchArguments to hold the\
\ user-supplied input\nObject[] searchArguments = new Object[]{userQuery};\n// Hardcode the BaseDN,\
\ use the {0} format specifier to use the searchArguments array value,\nand pass in the search controls.\n\
// searchArguments automatically encode\nNamingEnumeration answer = ldapContext.search(\"dc=example,dc=org\"\
, \"(cn={0})\",\nsearchArguments, searchControls);\n// Process the response answer\nwhile (answer.hasMoreElements())\
\ {\n ...\n}\n```\n\nFor information on enabling authentication, please see your LDAP server's\ndocumentation.\n\
\nFor more information on LDAP Injection see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html\n"
metadata:
shortDescription: Missing authentication for critical function (LDAP)
category: security
cwe: CWE-306
owasp:
- A2:2017-Broken Authentication
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
security-severity: High
severity: WARNING
- id: gitlab-java_password_rule-ConstantDBPassword
languages: [java]
patterns:
- pattern: java.sql.DriverManager.getConnection($URI, $USR, "...");
- pattern-not: java.sql.DriverManager.getConnection($URI, $USR, "");
message: 'A potential hard-coded password was identified in a database connection string.
Passwords should not be stored directly in code
but loaded from secure locations such as a Key Management System (KMS).
The purpose of using a Key Management System is so access can be audited and keys easily
rotated
in the event of a breach. By hardcoding passwords, it will be extremely difficult to determine
when or if, a key is compromised.
The recommendation on which KMS to use depends on the environment the application is running
in:
- For Google Cloud Platform consider [Cloud Key Management](https://cloud.google.com/kms/docs)
- For Amazon Web Services consider [AWS Key Management](https://aws.amazon.com/kms/)
- For on premise or other alternatives to cloud providers, consider [Hashicorp''s
Vault](https://www.vaultproject.io/)
- For other cloud providers, please see their documentation
'
severity: ERROR
metadata:
shortDescription: Use of hard-coded password
category: security
cwe: CWE-259
owasp:
- A2:2017-Broken Authentication
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
technology:
- java
security-severity: Critical
- id: gitlab-java_password_rule-EmptyDBPassword
languages: [java]
patterns:
- pattern: java.sql.DriverManager.getConnection($URI, $USR, "");
message: 'The application does not provide authentication when communicating a database
server. It is strongly recommended that the database server be configured with
authentication and restrict what queries users can execute.
Please see your database server''s documentation on how to configure a password.
Additionally, passwords should not be stored directly in code
but loaded from secure locations such as a Key Management System (KMS).
The purpose of using a Key Management System is so access can be audited and keys easily
rotated
in the event of a breach. By hardcoding passwords, it will be extremely difficult to determine
when or if, a key is compromised.
The recommendation on which KMS to use depends on the environment the application is running
in:
- For Google Cloud Platform consider [Cloud Key Management](https://cloud.google.com/kms/docs)
- For Amazon Web Services consider [AWS Key Management](https://aws.amazon.com/kms/)
- For on premise or other alternatives to cloud providers, consider [Hashicorp''s
Vault](https://www.vaultproject.io/)
- For other cloud providers, please see their documentation
'
severity: ERROR
metadata:
shortDescription: Missing authentication for critical function (database)
category: security
cwe: CWE-306
owasp:
- A2:2017-Broken Authentication
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
technology:
- java
security-severity: Critical
- id: gitlab-java_password_rule-HardcodePassword
languages: [java]
pattern-either:
- pattern: new java.security.KeyStore.PasswordProtection("...".toCharArray())
- pattern: java.security.KeyStore.getInstance(...).load(..., "...".toCharArray())
- pattern: (java.security.KeyStore $KS).load(..., "...".toCharArray())
- pattern: KeyManagerFactory.getInstance(...).init(..., "...".toCharArray())
- pattern: (KeyManagerFactory $KMF).init(..., "...".toCharArray())
- pattern: PBEKeySpec("...", ...)
- pattern: PasswordAuthentication("...", "...")
- pattern: (PasswordCallback $CB).setPassword("...")
- pattern: KerberosKey(...,"...",...)
- pattern: java.sql.DriverManager.getConnection(..., "...")
- pattern: io.vertx.ext.web.handler.CSRFHandler.create(..., "...")
- pattern: $S.setPassword("...")
message: 'A potential hard-coded password was identified in a hard-coded string.
Passwords should not be stored directly in code
but loaded from secure locations such as a Key Management System (KMS).
The purpose of using a Key Management System is so access can be audited and keys easily
rotated
in the event of a breach. By hardcoding passwords, it will be extremely difficult to determine
when or if, a key is compromised.
The recommendation on which KMS to use depends on the environment the application is running
in:
- For Google Cloud Platform consider [Cloud Key Management](https://cloud.google.com/kms/docs)
- For Amazon Web Services consider [AWS Key Management](https://aws.amazon.com/kms/)
- For on premise or other alternatives to cloud providers, consider [Hashicorp''s
Vault](https://www.vaultproject.io/)
- For other cloud providers, please see their documentation
'
severity: ERROR
metadata:
shortDescription: Use of hard-coded password
category: security
cwe: CWE-259
owasp:
- A2:2017-Broken Authentication
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
technology:
- java
security-severity: High
- id: gitlab-java_perm_rule-DangerousPermissions
languages: [java]
pattern-either:
- pattern: '$RUNVAR = new RuntimePermission("createClassLoader");
...
(PermissionCollection $PC).add($RUNVAR);
'
- pattern: '$REFVAR = new ReflectPermission("suppressAccessChecks");
...
(PermissionCollection $PC).add($REFVAR);
'
- pattern: (PermissionCollection $PC).add(new ReflectPermission("suppressAccessChecks"))
- pattern: (PermissionCollection $PC).add(new RuntimePermission("createClassLoader"))
message: 'The application was found to permit the `RuntimePermission` of `createClassLoader`,
`ReflectPermission` of `suppressAccessChecks`, or both.
By granting the `RuntimePermission` of `createClassLoader`, a compromised application
could instantiate their own class loaders and load arbitrary classes.
By granting the `ReflectPermission` of `suppressAccessChecks` an application will no longer
check Java language access checks on fields and methods of a class. This will effectively
grant access to protected and private members.
For more information on `RuntimePermission` see:
https://docs.oracle.com/javase/8/docs/api/java/lang/RuntimePermission.html
For more information on `ReflectPermission` see:
https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/ReflectPermission.html
'
metadata:
shortDescription: Incorrect permission assignment for critical resource
category: security
cwe: CWE-732
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
confidence: HIGH
security-severity: Medium
severity: WARNING
- id: gitlab-java_perm_rule-OverlyPermissiveFilePermissionInline
languages: [java]
patterns:
- pattern-either:
- pattern: java.nio.file.Files.setPosixFilePermissions(..., java.nio.file.attribute.PosixFilePermissions.fromString("$PERM_STRING"));
- pattern: '$PERMISSIONS = java.nio.file.attribute.PosixFilePermissions.fromString("$PERM_STRING");
...
java.nio.file.Files.setPosixFilePermissions(..., $PERMISSIONS);
'
- metavariable-regex:
metavariable: $PERM_STRING
regex: '[rwx-]{6}[rwx]{1,}'
message: 'The application was found setting file permissions to overly permissive values. Consider
using the following values if the application user is the only process to access
the file:
- `r--` - read only access to the file
- `w--` - write only access to the file
- `rw-` - read/write access to the file
Example setting read/write permissions for only the owner of a `Path`:
```
// Get a reference to the path
Path path = Paths.get("/tmp/somefile");
// Create a PosixFilePermission set from java.nio.file.attribute
Set<PosixFilePermission> permissions =
java.nio.file.attribute.PosixFilePermissions.fromString("rw-------");
// Set the permissions
java.nio.file.Files.setPosixFilePermissions(path, permissions);
```
For all other values please see:
https://en.wikipedia.org/wiki/File-system_permissions#Symbolic_notation
'
metadata:
shortDescription: Incorrect permission assignment for critical resource
cwe: CWE-732
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
category: security
confidence: HIGH
security-severity: Medium
severity: WARNING
- id: gitlab-java_script_rule-ScriptInjection
languages: [java]
mode: taint
pattern-sinks:
- patterns:
- pattern: (javax.script.ScriptEngine $ENGINE).eval($ARG, ...);
- pattern-not: (javax.script.ScriptEngine $ENGINE).eval("...");
- pattern-not: (javax.script.ScriptEngine $ENGINE).eval("...", (javax.script.Bindings $BINDING));
- patterns:
- pattern-either:
- pattern: (javax.script.Invocable $INVC).invokeFunction(..., $ARG)
- pattern: (javax.script.Invocable $INVC).invokeMethod(..., $ARG)
pattern-sources:
- patterns:
- pattern-inside: $FUNC(..., $T $VAR, ...) { ... }
- pattern: $VAR
message: "The application executes an argument using a `ScriptEngine`'s `eval` method. This\nmay allow\
\ for direct OS commands to be executed as it's possible to pass in strings\nsuch as `java.lang.Runtime.getRuntime().exec('/bin/sh\
\ ...');`.\n\nNever pass user-supplied input directly to the `eval` function. If possible hardcode all\n\
JavasScript code or use a lookup table to resolve user input to known values. If none of these\ntechniques\
\ are possible, use `javax.script.Bindings` to pass input to the script engine.\n\nExample using `Binding`\
\ to safely pass in string values:\n```\n// Get ECMAScript engine\nScriptEngine engine = new ScriptEngineManager().getEngineByName(\"\
ECMAScript\");\n\n// User input, consisting of first and last name\nString userFirstName = \"John\"\
;\nString userLastName = \"Snow\";\n\n// Create bindings to pass into our script, forcing the values\
\ to be String.\nBindings bindings = engine.createBindings();\nbindings.put(\"fname\", new String(userFirstName));\n\
bindings.put(\"lname\", new String(userLastName));\n\n// Example script that concatenates a greeting\
\ with the user-supplied input first/last name\nString script = \"var greeting='Hello ';\" +\n// fname\
\ and lname variables will be resolved by our bindings defined above\n\"greeting += fname + ' ' + lname;\"\
\ +\n// prints greeting\n\"greeting\";\n\ntry {\n // Execute the script, passing in the bindings\n\
\ Object bindingsResult = engine.eval(script, bindings);\n // Work with result\n // ...\n} catch\
\ (ScriptException e) {\n // Handle exception\n e.printStackTrace();\n}\n```\n"
severity: ERROR
metadata:
shortDescription: Improper control of generation of code ('Code Injection')
category: security
cwe: CWE-94
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
security-severity: High
- id: gitlab-java_script_rule-SpringSpelExpressionParser
languages: [java]
patterns:
- pattern: ($PARSER $P).$METHOD($ARG);
- pattern-not: ($PARSER $P).$METHOD("...");
- metavariable-pattern:
metavariable: $PARSER
pattern-either:
- pattern: org.springframework.expression.spel.standard.SpelExpressionParser
- pattern: org.springframework.expression.ExpressionParser
- metavariable-regex:
metavariable: $METHOD
regex: (parseExpression|parseRaw)
message: "The application was found calling SpringFramework's `SpelExpressionParser.parseExpression`.\n\
Calling this method directly with user-supplied input may allow an adversary to\nexecute arbitrary Java\
\ code including OS system commands.\n\nNever call `parseExpression` or `parseRaw` directly with user-supplied\
\ input. Consider\nalternate\nmethods such as a lookup table to take user input and resolve hardcoded\
\ values.\n\nLater versions of SpringFramework introduced a `SimpleEvaluationContext` which can be\n\
used to access bound data when calling the `getValue` result of `parseExpression`. This\n`SimpleEvaluationContext`\
\ has a reduced set of functionality and can restrict data binding\nto read-only or read-write contexts.\
\ An adversary could still access public properties\nor fields on custom types that have been provided\
\ to the evaluation context. Use with caution.\n\nExample using `SimpleEvaluationContext` with a read-write\
\ data binding context:\n```\n@RequestMapping(value=\"/spel\", method=RequestMethod.POST)\npublic String\
\ spel(@Validated User user, Model model) {\n // Create the Expression Parser\n SpelExpressionParser\
\ parser = new SpelExpressionParser();\n // Parse the expression\n Expression parsedExpression = parser.parseExpression(model.getPossiblyUnsafeData());\n\
\ // Create the read-write data binding context\n SimpleEvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();\n\
\ // Execute the expression, passing in the read-write context\n Object result = parsedExpression.getValue(context);\n\
\ // work with the result\n // ...\n return \"user\";\n}\n```\n\nFor more information on SimpleEvaluationContext\
\ see:\nhttps://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/expression/spel/support/SimpleEvaluationContext.html\n"
severity: ERROR
metadata:
shortDescription: Improper neutralization of special elements used in an expression language statement
('Expression Language Injection')
category: security
cwe: CWE-917
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
security-severity: High
- id: gitlab-java_smtp_rule-InsecureSmtp
languages: [java]
patterns:
- pattern-either:
- pattern-inside: '$E = new org.apache.commons.mail.SimpleEmail(...);
...
'
- pattern-inside: '$E = new org.apache.commons.mail.Email(...);
...
'
- pattern-inside: '$E = new org.apache.commons.mail.MultiPartEmail(...);
...
'
- pattern-inside: '$E = new org.apache.commons.mail.HtmlEmail(...);
...
'
- pattern-inside: '$E = new org.apache.commons.mail.ImageHtmlEmail(...);
...
'
- pattern-not-inside: '...
$E.setSSLOnConnect(true);
...
$E.setSSLCheckServerIdentity(true);
'
- pattern-not-inside: '...
$E.setSSLCheckServerIdentity(true);
...
$E.setSSLOnConnect(true);
'
message: 'The Apache commons mail client by default does not enable TLS server identity.
This allows for an adversary who is in between the application and the target host to intercept
potentially sensitive information or transmit malicious data.
Enable checking server identity by calling `Email.setSSLCheckServerIdentity(true)`
Example email client that enables TLS and server identity:
```
// Create an email client
Email email = new SimpleEmail();
// Configure the email hostname
email.setHostName("smtp.mail.example.com");
// Set the port
email.setSmtpPort(465);
// Securely retrieve username and password values
String username = getUserNameFromKMSorSecretStore();
String password = getPasswordFromKMSorSecretStore();
// Configure the Authenticator
DefaultAuthenticator auth = new DefaultAuthenticator(username, password);
// Set the authenticator
email.setAuthenticator(auth);
// Ensure we use SSL on connect
email.setSSLOnConnect(true);
// Ensure we validate server identity
email.setSSLCheckServerIdentity(true);
// configure the rest of the email
email.setFrom("x@example.com");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("y@example.com");
email.send();
```
'
metadata:
shortDescription: Improper validation of certificate with host mismatch
category: security
cwe: CWE-297
owasp:
- A3:2017-Sensitive Data Exposure
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
security-severity: Medium
severity: ERROR
- id: gitlab-java_smtp_rule-SmtpClient
languages: [java]
message: 'The application was found calling `MimeMessage` methods without encoding
new line characters. Much like HTTP, Simple Mail Transfer Protocol (SMTP) is a
text based protocol that uses headers to convey additional directives for how
email messages should be treated. An adversary could potentially cause email
messages to be sent to unintended recipients by abusing the CC or BCC headers
if they were able to inject them.
To mitigate this issue, `\r\n` (CRLF) character sequences must be escaped
or encoded prior to being used in any of the `MimeMessage` methods.
Example that escapes values that come from user input with
[Apache Commons Text](https://commons.apache.org/proper/commons-text/):
```
// Create a MimeMessage with a javax.mail.Session
Message message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress("source@example.com"));
// Set the to address
message.setRecipients(Message.RecipientType.TO,new InternetAddress[] {new
InternetAddress("destination@example.com")});
// Example user input
String subject = "potentially malicious data";
String headerValue = "potentially malicious data";
// Use Apache Commons Text StringEscapeUtils.escapeJava to encode \r\n to \\r\\n.
message.setSubject(StringEscapeUtils.escapeJava(subject));
// Use Apache Commons Text StringEscapeUtils.escapeJava to encode \r\n to \\r\\n.
message.addHeader("HeaderName", StringEscapeUtils.escapeJava(header));
// Use Apache Commons Text StringEscapeUtils.escapeJava to encode \r\n to \\r\\n.
message.setDescription(StringEscapeUtils.escapeJava("some description"));
// Use Apache Commons Text StringEscapeUtils.escapeJava to encode \r\n to \\r\\n.
message.setDisposition(StringEscapeUtils.escapeJava("some disposition"));
// Set the mail body text
message.setText("Some email content.");
// Send the message
```
'
patterns:
- pattern-inside: '$M = new MimeMessage(...);
...
'
- pattern-either:
- patterns:
- pattern-either:
- pattern: $M.setSubject($VAR)
- pattern: $M.addHeader($ARG, $VAR)
- pattern: $M.addHeader($VAR, $ARG)
- pattern: $M.setDescription($VAR)
- pattern: $M.setDisposition($VAR)
- metavariable-regex:
metavariable: $VAR
regex: ^[a-zA-Z_$][a-zA-Z0-9_$]*$
- patterns:
- pattern-either:
- pattern: $M.setSubject($OBJ.$GETTER(...))
- pattern: $M.setSubject($OBJ.$GETTER(...) + ...)
- pattern: $M.setSubject(... + $OBJ.$GETTER(...))
- pattern: $M.setSubject(... + $OBJ.$GETTER(...) + ...)
- pattern: $M.addHeader($ARG, $OBJ.$GETTER(...))
- pattern: $M.addHeader($ARG, $OBJ.$GETTER(...) + ...)
- pattern: $M.addHeader($ARG, ... + $OBJ.$GETTER(...))
- pattern: $M.addHeader($ARG, ... + $OBJ.$GETTER(...) + ...)
- pattern: $M.addHeader($OBJ.$GETTER(...), $ARG)
- pattern: $M.addHeader($OBJ.$GETTER(...) + ..., $ARG)
- pattern: $M.addHeader(... + $OBJ.$GETTER(...), $ARG)
- pattern: $M.addHeader(... + $OBJ.$GETTER(...) + ..., $ARG)
- pattern: $M.setDescription($OBJ.$GETTER(...))
- pattern: $M.setDisposition($OBJ.$GETTER(...) + ...)
- pattern: $M.setDisposition(... + $OBJ.$GETTER(...))
- pattern: $M.setDisposition(... + $OBJ.$GETTER(...) + ...)
- metavariable-regex:
metavariable: $GETTER
regex: ^get
metadata:
shortDescription: Improper neutralization of special elements used in a command
category: security
cwe: CWE-77
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
security-severity: Low
severity: ERROR
- id: gitlab-java_ssrf_rule-SSRF
languages: [java]
message: "Server-Side-Request-Forgery (SSRF) exploits backend systems that initiate requests to third\n\
parties.\nIf user input is used in constructing or sending these requests, an attacker could supply\n\
malicious\ndata to force the request to other systems or modify request data to cause unwanted actions.\n\
\nEnsure user input is not used directly in constructing URLs or URIs when initiating requests\nto third\
\ party\nsystems from back end systems. Care must also be taken when constructing payloads using user\n\
input. Where\npossible restrict to known URIs or payloads. Consider using a server-side map where keys\
\ are\nused to return\nURLs such as `https://site/goto?key=1` where `{key: 1, url: 'http://some.url/',\
\ key: 2, url:\n'http://...'}`.\n\nIf you must use user-supplied input for requesting URLs, it is strongly\
\ recommended that the\nHTTP client\nchosen allows you to customize and block certain IP ranges at the\
\ network level. By blocking\nRFC 1918\naddresses or other network address ranges, you can limit the\
\ severity of a successful SSRF\nattack. Care must\nalso be taken to block certain protocol or address\
\ formatting such as IPv6.\n\nIf you cannot block address ranges at the client level, you may want to\
\ run the HTTP client\nas a protected\nuser, or in a protected network where you can apply IP Table\
\ or firewall rules to block access\nto dangerous\naddresses. Finally, if none of the above protections\
\ are available, you could also run a\ncustom HTTP proxy\nand force all requests through it to handle\
\ blocking dangerous addresses.\n\nExample using a map to look up a key to be used in a HTTP request:\n\
```\nHashMap<String, String> lookupTable = new HashMap<>();\nlookupTable.put(\"key1\", \"https://example.com/\"\
);\nlookupTable.put(\"key2\", \"https://safeurl.com/\");\nString userInput = request.getParameter(\"\
key\");\n\n// Create a CloseableHttpClient, ideally any requests issued should be done\n// out-of-band\
\ from the servlet request itself (such as using a separate thread/scheduler\nsystem)\ntry (final CloseableHttpClient\
\ httpClient = HttpClients.createDefault()) {\n // Lookup the value from our user input from our\
\ lookupTable\n String value = lookupTable.getOrDefault(userInput, \"https://example.com/\");\n \
\ // Construct the url, with the hardcoded url and only pass in the value from the\nlookupTable,\n\
\ // not direct user input\n final HttpGet httpget = new HttpGet(value);\n // Execute the request\n\
\ CloseableHttpResponse clientResponse = httpClient.execute(httpget);\n // Read the response\n\
\ byte[] responseData = clientResponse.getEntity().getContent().readAllBytes();\n // Handle the\
\ response\n // ...\n}\n```\n\nIf using a map is not possible, the user-supplied input must be encoded\
\ prior to use, and\nnever allow full\nURLs:\n```\n// Get user input\nString userInput = request.getParameter(\"\
key\");\n// Encode the string using java.net.URLEncoder with the UTF-8 character set\nString encodedString\
\ = java.net.URLEncoder.encode(userInput, StandardCharsets.UTF_8);\n// Create a CloseableHttpClient,\
\ ideally any requests issued should be done\n// out-of-band from the servlet request itself (such as\
\ using a separate thread/scheduler\nsystem)\ntry (final CloseableHttpClient httpClient = HttpClients.createDefault())\
\ {\n // Construct the url, with the hardcoded url and only pass in the encoded value, never a\nfull\
\ URL\n final HttpGet httpget = new HttpGet(\"https://example.com/getId?key=\"+encodedString);\n //\
\ Execute the request\n CloseableHttpResponse clientResponse = httpClient.execute(httpget);\n // Read\
\ the response\n byte[] responseData = clientResponse.getEntity().getContent().readAllBytes();\n //\
\ handle the response\n}\n```\n\nFor more information on SSRF see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html\n"
pattern-either:
- patterns:
- pattern-either:
- pattern-inside: 'import java.net.*;
...
'
- pattern-inside: 'import java.net.URL;
...
'
- pattern-inside: 'import java.net.URI;
...
'
- pattern: new $TYPE(...). ... .$FUNC
- pattern-not: new $TYPE("..."). ... .$FUNC
- metavariable-pattern:
metavariable: $FUNC
pattern-either:
- pattern: connect
- pattern: GetContent
- pattern: openConnection
- pattern: openStream
- pattern: getContent
- metavariable-pattern:
metavariable: $TYPE
pattern-either:
- pattern: URL
- pattern: java.net.URL
- pattern: URI
- pattern: java.net.URI
- patterns:
- pattern-either:
- pattern-inside: 'import java.net.*;
...
'
- pattern-inside: 'import java.net.InetSocketAddress;
...
'
- pattern: 'new InetSocketAddress(..., $PORT)
'
- pattern-not: 'new InetSocketAddress("...", $PORT)
'
metadata:
shortDescription: Server-Side Request Forgery (SSRF)
category: security
cwe: CWE-918
owasp:
- A1:2017-Injection
- A10:2021-Server-Side Request Forgery
- A01:2025-Broken Access Control
security-severity: Medium
severity: ERROR
- id: gitlab-java_strings_rule-BadHexConversion
languages: [java]
message: 'The application is using `Integer.toHexString` on a digest array buffer which
may lead to an incorrect version of values.
Consider using the `java.util.HexFormat` object introduced in Java 17. For older Java applications
consider using the `javax.xml.bind.DatatypeConverter`.
Example using `HexFormat` to create a human-readable string:
```
// Create a MessageDigest using the SHA-384 algorithm
MessageDigest sha384Digest = MessageDigest.getInstance("SHA-384");
// Call update with your data
sha384Digest.update("some input".getBytes(StandardCharsets.UTF_8));
// Only call digest once all data has been fed into the update sha384digest instance
byte[] output = sha384Digest.digest();
// Create a JDK 17 HexFormat object
HexFormat hex = HexFormat.of();
// Use formatHex on the byte array to create a string (note that alphabet characters are
lowercase)
String hexString = hex.formatHex(output);
```
For more information on DatatypeConverter see:
https://docs.oracle.com/javase/9/docs/api/javax/xml/bind/DatatypeConverter.html#printHexBinary-byte:A-
'
patterns:
- pattern-inside: '$B_ARR = (java.security.MessageDigest $MD).digest(...);
...
'
- pattern-either:
- pattern: "for(...) {\n ...\n $B = $B_ARR[...];\n ...\n Integer.toHexString($B);\n}\n"
- pattern: "for(...) {\n ...\n Integer.toHexString($B_ARR[...]);\n}\n"
- pattern: "for(byte $B :$B_ARR) {\n ...\n Integer.toHexString($B);\n}\n"
- pattern: "while(...) {\n ...\n Integer.toHexString($B_ARR[...])\n}\n"
- pattern: "do {\n ...\n Integer.toHexString($B_ARR[...])\n} while(...)\n"
- pattern: "while(...) {\n ...\n $B = $B_ARR[...];\n ...\n Integer.toHexString($B);\n}\n"
- pattern: "do {\n ...\n $B = $B_ARR[...];\n ...\n Integer.toHexString($B);\n} while(...)\n"
metadata:
shortDescription: Incorrect type conversion or cast
cwe: CWE-704
category: security
confidence: HIGH
owasp:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration
security-severity: Info
severity: WARNING
- id: gitlab-java_strings_rule-FormatStringManipulation
languages: [java]
patterns:
- pattern-either:
- patterns:
- pattern-inside: 'String $INPUT = (HttpServletRequest $REQ).getParameter(...);
...
'
- pattern-inside: 'String $FORMAT_STR = ... + $INPUT;
...
'
- patterns:
- pattern-inside: 'String $INPUT = (HttpServletRequest $REQ).getParameter(...);
...
'
- pattern-inside: 'String $FORMAT_STR = ... + $INPUT + ...;
...
'
- pattern-inside: 'String $FORMAT_STR = ... + (HttpServletRequest $REQ).getParameter(...) + ...;
...
'
- pattern-inside: 'String $FORMAT_STR = ... + (HttpServletRequest $REQ).getParameter(...);
...
'
- pattern-either:
- pattern: String.format($FORMAT_STR, ...);
- pattern: String.format(java.util.Locale.$LOCALE, $FORMAT_STR, ...);
- pattern: (java.util.Formatter $F).format($FORMAT_STR, ...);
- pattern: (java.util.Formatter $F).format(java.util.Locale.$LOCALE, $FORMAT_STR, ...);
- pattern: (java.io.PrintStream $F).printf($FORMAT_STR, ...);
- pattern: (java.io.PrintStream $F).printf(java.util.Locale.$LOCALE, $FORMAT_STR, ...);
- pattern: (java.io.PrintStream $F).format($FORMAT_STR, ...);
- pattern: (java.io.PrintStream $F).format(java.util.Locale.$LOCALE, $FORMAT_STR, ...);
- pattern: System.out.printf($FORMAT_STR, ...);
- pattern: System.out.printf(java.util.Locale.$LOCALE, $FORMAT_STR, ...);
- pattern: System.out.format($FORMAT_STR, ...);
- pattern: System.out.format(java.util.Locale.$LOCALE, $FORMAT_STR, ...);
message: 'The application allows user input to control format string parameters. By passing invalid
format
string specifiers an adversary could cause the application to throw exceptions or possibly
leak
internal information depending on application logic.
Never allow user-supplied input to be used to create a format string. Replace all format
string
arguments with hardcoded format strings containing the necessary specifiers.
Example of using `String.format` safely:
```
// Get untrusted user input
String userInput = request.getParameter("someInput");
// Ensure that user input is not included in the first argument to String.format
String.format("Hardcoded string expecting a string: %s", userInput);
// ...
```
'
metadata:
shortDescription: Use of externally-controlled format string
cwe: CWE-134
category: security
confidence: HIGH
owasp:
- A1:2017-Injection
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
security-severity: Medium
severity: ERROR
- id: gitlab-java_strings_rule-ModifyAfterValidation
languages: [java]
patterns:
- pattern: '(java.util.regex.Pattern $Y).matcher($VAR);
...
$VAR.$METHOD(...);
'
- metavariable-regex:
metavariable: $METHOD
regex: (replace|replaceAll|replaceFirst|concat)
message: "The application was found matching a variable during a regular expression\npattern match, and\
\ then calling string modification functions after validation has occurred.\nThis is usually indicative\
\ of a poor input validation strategy as an adversary may attempt to\nexploit the removal of characters.\n\
\nFor example a common mistake in attempting to remove path characters to protect against path\ntraversal\
\ is to match '../' and then remove any matches. However, if an adversary were to\ninclude in their\
\ input: '....//' then the `replace` method would replace the first `../` but\ncause the leading `..`\
\ and trailing `/` to join into the final string of `../`, effectively\nbypassing the check.\n\nTo remediate\
\ this issue always perform string modifications before any validation of a string.\nIt is strongly\
\ recommended that strings be encoded instead of replaced or removed prior to\nvalidation.\n\n\nExample\
\ replaces `..` before validation. Do note this is still not a recommended method for\nprotecting against\
\ directory traversal, always use randomly generated IDs or filenames instead:\n```\n// This is ONLY\
\ for demonstration purpose, never use untrusted input\n// in paths, always use randomly generated filenames\
\ or IDs.\nString input = \"test../....//dir\";\n// Use replaceAll _not_ replace\ninput = input.replaceAll(\"\
\\\\.\\\\.\", \"\");\n// Input would be test///dir at this point\n// Create a pattern to match on\n\
Pattern pattern = Pattern.compile(\"\\\\.\\\\.\");\n// Create a matcher\nMatcher match = pattern.matcher(input);\n\
// Call find to see if .. is still in our string\nif (match.find()) {\n throw new Exception(\"..\
\ detected\");\n}\n// Use the input (but do not modify the string)\nSystem.out.println(input + \" safe\"\
);\n```\n\nFor more information see Carnegie Mellon University's Secure Coding Guide:\nhttps://wiki.sei.cmu.edu/confluence/display/java/IDS11-J.+Perform+any+string+modifications+before+validation\n\
\n"
metadata:
shortDescription: Collapse of data into unsafe value
category: security
cwe: CWE-182
confidence: HIGH
owasp:
- A1:2017-Injection
- A03:2021-Injection
security-severity: Info
severity: WARNING
- id: gitlab-java_strings_rule-NormalizeAfterValidation
languages: [java]
patterns:
- pattern: '$Y = java.util.regex.Pattern.compile("[<>]");
...
$Y.matcher($VAR);
...
java.text.Normalizer.normalize($VAR, ...);
'
message: "The application was found matching a variable during a regular expression\npattern match, and\
\ then calling a Unicode normalize function after validation has occurred.\nThis is usually indicative\
\ of a poor input validation strategy as an adversary may attempt to\nexploit the normalization process.\n\
\nTo remediate this issue, always perform Unicode normalization before any validation of a\nstring.\n\
\nExample of normalizing a string before validation:\n```\n// User input possibly containing malicious\
\ unicode\nString userInput = \"\\uFE64\" + \"tag\" + \"\\uFE65\";\n// Normalize the input\nuserInput\
\ = Normalizer.normalize(userInput, Normalizer.Form.NFKC);\n// Compile our regex pattern looking for\
\ < or > characters\nPattern pattern = Pattern.compile(\"[<>]\");\n// Create a matcher from the userInput\n\
Matcher matcher = pattern.matcher(userInput);\n// See if the matcher matches\nif (matcher.find()) {\n\
\ // It did so throw an error\n throw new Exception(\"found banned characters in input\");\n}\n\
```\n\nFor more information see Carnegie Mellon University's Secure Coding Guide:\nhttps://wiki.sei.cmu.edu/confluence/display/java/IDS01-J.+Normalize+strings+before+validating+them\n"
metadata:
shortDescription: 'Incorrect behavior order: validate before canonicalize'
category: security
cwe: CWE-180
confidence: HIGH
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
security-severity: Info
severity: WARNING
- id: gitlab-java_templateinjection_rule-TemplateInjection
languages: [java]
message: 'The application may allow control over a template string. Providing user input directly in the
template by
dynamically creating template strings may allow an adversary to execute arbitrary Java code,
including
OS system commands.
For Velocity, never call `evaluate` with user-supplied input in the template string. Use a
`VelocityContext`
object instead to data-bind user-supplied information as it will be treated as an underlying
data type and not
template code.
Example using Apache Velocity''s `VelocityContext` and escape tools to pass in user-supplied
data to a template:
```
// Create a tool manager
ToolManager manager = new ToolManager(true);
// Create a context from the tool manager
Context context = manager.createContext();
// For demonstration purposes, alternatively configure from a properties file
context.put("esc", new EscapeTool());
// For demonstration purposes, create an output buffer
StringWriter stringWriter = new StringWriter();
// Get userInput
String userInput = "potentially malicious data";
// Use the context to pass in the userInput value
context.put("userInput", userInput);
// Pass in the context, the output buffer, a logtag (demo), and the template with userInput
// making sure to escape it if in the context of HTML.
Velocity.evaluate(context, stringWriter, "demo", "Hello $esc.html($userInput)");
// Work with the output buffer
// ...
```
For other templating engines, please see your framework''s documentation.
'
pattern-either:
- patterns:
- pattern: org.apache.velocity.app.Velocity.evaluate(..., $VAR)
- pattern-not: org.apache.velocity.app.Velocity.evaluate(..., "...")
- patterns:
- pattern-not-inside: '$C = (freemarker.template.Configuration $CFG).getTemplate("...");
...
'
- pattern-inside: '$C = (freemarker.template.Configuration $CFG).getTemplate($IN);
...
'
- pattern: $C.process(...)
- patterns:
- pattern-inside: 'import com.mitchellbosecke.pebble.PebbleEngine;
...
'
- pattern-inside: '$C = $T.getTemplate($IN);
...
'
- pattern-not-inside: '$C = $T.getTemplate("...");
...
'
- pattern: $C.evaluate(...)
metadata:
shortDescription: Improper control of generation of code ('Code Injection')
category: security
cwe: CWE-94
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
security-severity: High
severity: ERROR
- id: gitlab-java_unsafe_rule-ExternalConfigControl
languages: [java]
patterns:
- pattern: '$TAINTED = (HttpServletRequest $REQ).getParameter(...);
...
(java.sql.Connection $CONN).setCatalog($TAINTED);
'
message: 'The application was found using user-supplied input in a `java.sql.Connection`''s
`setCatalog` call. This could allow an adversary to supply a different database for the
lifetime of the connection. Allowing external control of system settings can disrupt service
or cause an application to behave in unexpected, and potentially malicious ways. Most likely
this would only cause an error by providing a nonexistent catalog name.
It is recommended to not use user-supplied input when selecting the database for an
applications
database connection.
'
severity: WARNING
metadata:
shortDescription: External control of system or configuration setting
category: security
cwe: CWE-15
owasp:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
technology:
- java
security-severity: Low
- id: gitlab-java_xml_rule-SAMLIgnoreComments
languages: [java]
message: "SAML parses attestations as an XML document. By processing XML comments, comment\nfields can\
\ end up modifying the interpretation of input fields. This could allow\nan adversary to insert an XML\
\ comment to break up the attestation's username\nor other fields, allowing an attacker to bypass authorization\
\ or authentication checks.\n\nTo remediate this issue, when using `org.opensaml.xml.parse.BasicParserPool`\
\ ensure\n`setIgnoreComments(false)` is not called.\n\nThe default value of `ignoreComments` is true,\
\ which is safe. \n\nRef:\n- https://javadoc.io/doc/org.opensaml/xmltooling/latest/org/opensaml/xml/parse/BasicParserPool.html#ignoreComments\n\
\nFor more information on how this issue can be exploited see:\nhttps://developer.okta.com/blog/2018/02/27/a-breakdown-of-the-new-saml-authentication-bypass-vulnerability\n\
\nFor more information on SAML security see OWASP:\nhttps://cheatsheetseries.owasp.org/cheatsheets/SAML_Security_Cheat_Sheet.html\n"
metadata:
shortDescription: Weak authentication
cwe: CWE-1390
category: security
owasp:
- A2:2017-Broken Authentication
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
security-severity: Medium
pattern: (org.opensaml.xml.parse.BasicParserPool $POOL).setIgnoreComments(false);
severity: WARNING
- id: gitlab-java_xml_rule-XmlDecoder
languages: [java]
message: "Deserialization attacks exploit the process of reading serialized data and turning it back\n\
into an object. By constructing malicious objects and serializing them, an adversary may\nattempt to:\n\
\n- Inject code that is executed upon object construction, which occurs during the\ndeserialization\
\ process.\n- Exploit mass assignment by including fields that are not normally a part of the serialized\n\
data but are read in during deserialization.\n\nConsider safer alternatives such as serializing data\
\ in the JSON format. Ensure any format\nchosen allows\nthe application to specify exactly which object\
\ types are allowed to be deserialized.\nAdditionally, when\ndeserializing, never deserialize to base\
\ object types like `Object` and only cast to the exact\nobject\ntype that is expected.\n\nTo protect\
\ against mass assignment, only allow deserialization of the specific fields that are\nrequired. If\
\ this is not easily done, consider creating an intermediary type that\ncan be serialized with only\
\ the necessary fields exposed.\n\nDo note that `XMLEncoder` and `XMLDecoder` are not recommended. If\
\ the application must\nuse this serialization method, use a custom ClassLoader to prevent loading of\
\ arbitrary\nclasses:\n```\nXMLDecoder decoder = new XMLDecoder(inputStream, null, null, new ClassLoader()\
\ {\n @Override\n protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException\
\ {\n if (!name.equals(NameOfBeanHere.class.getName()) &&\n!name.equals(XMLDecoder.class.getName()))\
\ {\n throw new RuntimeException(\"Unauthorized deserialization attempt: \" + name);\n \
\ }\n\n return super.loadClass(name, resolve);\n }\n});\n```\n\nFor more information\
\ on XML security see OWASP's guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java\n\
\nFor more details on deserialization attacks in general, see OWASP's guide:\nhttps://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html\n\
\nIt should be noted that [tools exist](https://github.com/frohoff/ysoserial) to\nautomatically create\n\
exploit code for these vulnerabilities.\n"
metadata:
shortDescription: Deserialization of untrusted data
category: security
cwe: CWE-502
owasp:
- A8:2017-Insecure Deserialization
- A08:2021-Software and Data Integrity Failures
- A08:2025-Software or Data Integrity Failures
security-severity: High
patterns:
- pattern: '(java.beans.XMLDecoder $D).readObject();
'
- pattern-not:
pattern-either:
- patterns:
- pattern-inside: 'java.beans.XMLDecoder $DEC = new java.beans.XMLDecoder(..., $CL);
...
'
- pattern: $DEC.readObject();
- metavariable-pattern:
metavariable: $CL
patterns:
- pattern: "new ClassLoader(){\n ...\n $RET loadClass(String name, boolean resolve){\n \
\ if($X){\n throw ...\n }\n ...\n }\n ...\n}\n"
- metavariable-pattern:
metavariable: $X
pattern-either:
- pattern: '!name.equals(...)
'
- pattern: '!$LIST.contains(name)
'
- patterns:
- pattern-inside: 'ClassLoader $CLASS_LOADER = $CL;
...
java.beans.XMLDecoder $DEC = new java.beans.XMLDecoder(..., $CLASS_LOADER);
...
'
- pattern: $DEC.readObject();
- metavariable-pattern:
metavariable: $CL
patterns:
- pattern: "new ClassLoader(){\n ...\n $RET loadClass(String name, boolean resolve){\n \
\ if($X){\n throw ...\n }\n ...\n }\n ...\n}\n"
- metavariable-pattern:
metavariable: $X
pattern-either:
- pattern: '!name.equals(...)
'
- pattern: '!$LIST.contains(name)
'
severity: WARNING
- id: gitlab-java_xml_rule-XsltTransform
languages: [java]
mode: taint
pattern-sources:
- patterns:
- pattern-either:
- patterns:
- pattern-inside: "$FUNC(...,String $VAR, ...) {\n ...\n}\n"
- pattern-either:
- pattern: new FileInputStream(<... $VAR ...>);
- pattern: getClass().getResourceAsStream(<... $VAR ...>)
- patterns:
- pattern-inside: "class $CLZ {\n String $X = \"...\";\n ...\n}\n"
- pattern-inside: "$FUNC(...,String $Y, ...) {\n ...\n}\n"
- pattern-either:
- pattern: new FileInputStream($X + $Y);
- pattern: getClass().getResourceAsStream($X + $Y)
pattern-sinks:
- patterns:
- pattern-either:
- pattern-inside: (javax.xml.transform.TransformerFactory $T).newTransformer($SRC, ...)
- pattern-inside: (javax.xml.transform.Transformer $T).transform($SRC, ...)
- pattern: $SRC
message: 'The application performs XSLT translation with potentially malicious input. An adversary who
is able to influence the
loaded
XSL document could call XSL functions or exploit External XML Entity (XXE) attacks that allow
file
retrieval or force the parser to connect to arbitrary servers to exfiltrate files. It is
strongly
recommended that an alternative approach is used to work with XML data.
For increased security, never process user-supplied XSL style sheets. If XSLT processing is
absolutely
necessary, ensure that `FEATURE_SECURE_PROCESSING` is enabled prior to processing the XSLT
file:
```
// Create a new TransformerFactory instance
TransformerFactory transformerFactory = TransformerFactory.newInstance();
// Enable the FEATURE_SECURE_PROCESSING feature
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// Read in the XML Source
Source xmlSource = new StreamSource(new FileInputStream("hardcoded.xml"));
// Read in the XSL template file
Source xslSource = new StreamSource(new FileInputStream("hardcoded.xsl"));
/// Create the transformer object to do the transformation
Transformer transformer = transformerFactory.newTransformer(xslSource);
// Create a Result object for output
Result result = new StreamResult(System.out);
// Execute the transformation process
transformer.transform(xmlSource, result);
```
For more information on XML security see OWASP''s guide:
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java
For more information on the secure processing feature see:
- https://xml.apache.org/xalan-j/features.html#secureprocessing
'
metadata:
shortDescription: XML injection (aka Blind XPath injection)
category: security
cwe: CWE-91
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
security-severity: Medium
severity: WARNING
- id: gitlab-java_xss_rule-WicketXSS
languages: [java]
patterns:
- pattern-inside: 'import org.apache.wicket.$A;
...
'
- pattern: '$OBJ.setEscapeModelStrings(false);
'
message: "The application is disabling Wicket's string escaping functionality by calling\n`setEscapeModelStrings(false)`.\n\
This could lead to Cross Site Scripting (XSS) if used with user-supplied input. XSS is an\nattack which\
\ exploits\n a web application or system to treat user input\nas markup or script code. It is important\
\ to encode the data depending on the specific context\nit\nis used in. There are at least six context\
\ types:\n\n- Inside HTML tags `<div>context 1</div>`\n- Inside attributes: `<div class=\"context 2\"\
></div>`\n- Inside event attributes `<button onclick=\"context 3\">button</button>`\n- Inside script\
\ blocks: `<script>var x = \"context 4\"</script>`\n- Unsafe element HTML assignment: `element.innerHTML\
\ = \"context 5\"`\n- Inside URLs: `<iframe src=\"context 6\"></iframe><a href=\"context 6\">link</a>`\n\
\nScript blocks alone have multiple ways they need to be encoded. Extra care must be taken if\nuser\
\ input\nis ever output inside of script tags.\n\nUser input that is displayed within the application\
\ must be encoded, sanitized or validated\nto ensure it cannot be treated as HTML or executed as JavaScript\
\ code. Care must also be\ntaken\nto not mix server-side templating with client-side templating, as\
\ the server-side templating\nwill\nnot encode things like {{ 7*7 }} which may execute client-side templating\
\ features.\n\nIt is _NOT_ advised to encode user input prior to inserting into a data store. The data\
\ will\nneed to be\nencoded depending on context of where it is output. It is much safer to force the\
\ displaying\nsystem to\nhandle the encoding and not attempt to guess how it should be encoded.\n\n\
Use Wicket's built in escaping feature by calling `Component.setEscapeModelStrings(true);`\n\nFor more\
\ information on Wicket components see:\n- https://nightlies.apache.org/wicket/apidocs/9.x/org/apache/wicket/Component.html\n\
\nFor more information on XSS see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html\n"
metadata:
shortDescription: Improper neutralization of input during web page generation ('Cross-site Scripting')
category: security
cwe: CWE-79
owasp:
- A7:2017-Cross-Site Scripting (XSS)
- A03:2021-Injection
- A05:2025-Injection
security-severity: Medium
severity: WARNING
- id: gitlab-java_xss_rule-XSSReqParamToServletWriter
languages: [java]
mode: taint
pattern-sources:
- pattern: (javax.servlet.http.HttpServletRequest $R).$METHOD(...)
- pattern: (java.util.Scanner $S).$METHOD(...)
- pattern: (java.util.stream.Stream).$METHOD(...)
- pattern: (java.util.StringJoiner $SJ).toString(...)
- pattern: (java.sql.ResultSet.getString $R).$METHOD(...)
- pattern: (java.lang.System $S).getProperty(...)
- pattern: (java.lang.System $S).getenv(...)
- pattern: (java.lang.StringBuilder $SB).toString(...)
- pattern: (java.io.FileInputStream $F).read(...)
- pattern: (java.io.FileReader $F).read(...)
- pattern: (java.net.Socket $S).getInputStream(...)
- pattern: (java.net.Socket $S).getOutputStream(...)
- pattern: (java.net.DatagramSocket $S).receive(...)
- pattern: (java.net.DatagramSocket $S).getInputStream(...)
- pattern: java.nio.file.Files.readAllBytes(...)
- pattern: java.nio.file.Files.readAllLines(...)
- pattern: java.nio.file.Files.lines(...)
- pattern: java.nio.file.Files.newBufferedReader(...)
- pattern: org.apache.commons.io.IOUtils.toString(...)
- pattern: org.apache.commons.io.IOUtils.readLines(...)
- pattern: org.apache.commons.io.IOUtils.toByteArray(...)
- pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).readValue(...)
- pattern: (com.fasterxml.jackson.databind.ObjectMapper $OM).treeToValue(...)
- pattern: $CLASS.$METHOD(..., (javax.servlet.http.HttpServletRequest $R), ...)
- pattern: $FUNC(..., (javax.servlet.http.HttpServletRequest $R), ...)
- patterns:
- pattern-inside: $FUNC(..., String $X, ...) { ... }
- focus-metavariable: $X
pattern-propagators:
- pattern: $LIST.add($X)
from: $X
to: $LIST
- pattern: $MAP.put(..., $X)
from: $X
to: $MAP
- pattern: $STR.concat($X)
from: $X
to: $STR
- pattern: $STR = String.format(..., $X, ...)
from: $X
to: $STR
- pattern: $STR = String.join(..., $X, ...)
from: $X
to: $STR
pattern-sanitizers:
- pattern: org.owasp.encoder.Encode.forHtml(...)
- pattern: org.owasp.esapi.ESAPI.encoder().encodeForHTML(...)
- pattern: org.apache.commons.text.StringEscapeUtils.escapeHtml3(...)
- pattern: org.apache.commons.text.StringEscapeUtils.escapeHtml4(...)
- pattern: org.owasp.benchmark.helpers.Utils.encodeForHTML(...)
pattern-sinks:
- pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().print(...)
- patterns:
- pattern-inside: '$W = (javax.servlet.http.HttpServletResponse $R).getWriter();
...
'
- pattern: $W.print(...);
- pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().println(...)
- patterns:
- pattern-inside: '$W = (javax.servlet.http.HttpServletResponse $R).getWriter();
...
'
- pattern: $W.println(...);
- pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().format(...)
- patterns:
- pattern-inside: '$W = (javax.servlet.http.HttpServletResponse $R).getWriter();
...
'
- pattern: $W.format(...);
- pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().append(...)
- patterns:
- pattern-inside: '$W = (javax.servlet.http.HttpServletResponse $R).getWriter();
...
'
- pattern: $W.append(...);
- pattern: (javax.servlet.http.HttpServletResponse $R).getWriter().write(...)
- patterns:
- pattern-inside: '$W = (javax.servlet.http.HttpServletResponse $R).getWriter();
...
'
- pattern: $W.write(...);
message: 'The application is returning user-supplied data from an HTTP request directly into an HTTP
response output
writer. This could lead to Cross Site Scripting (XSS) if the input were malicious
script code and the application server is not properly validating the output.
XSS is an attack which exploits a web application or system to treat user input
as markup or script code. It is important to encode the data depending on the specific context
it is used in. There are at least six context types:
- Inside HTML tags `<div>context 1</div>`
- Inside attributes: `<div class="context 2"></div>`
- Inside event attributes `<button onclick="context 3">button</button>`
- Inside script blocks: `<script>var x = "context 4"</script>`
- Unsafe element HTML assignment: `element.innerHTML = "context 5"`
- Inside URLs: `<iframe src="context 6"></iframe><a href="context 6">link</a>`
Script blocks alone have multiple ways they need to be encoded. Extra care must be taken if
user input
is ever output inside of script tags.
User input that is displayed within the application must be encoded, sanitized or validated
to ensure it cannot be treated as HTML or executed as Javascript code. Care must also be
taken
to not mix server-side templating with client-side templating, as the server-side templating
will
not encode things like {{ 7*7 }} which may execute client-side templating features.
It is _NOT_ advised to encode user input prior to inserting into a data store. The data will
need to be
encoded depending on context of where it is output. It is much safer to force the displaying
system to
handle the encoding and not attempt to guess how it should be encoded.
If possible do not use user input directly in the output to the response writer.
If the application must output user-supplied input, it will need to encode the data depending
on
the output context.
Consider using [Apache Commons Text](https://commons.apache.org/proper/commons-text/)
`StringEscapeUtils` methods for various context. Please note there is no way to safely
output script code in most circumstances, regardless of encoding. If calling the HTTP
response writer directly, ensure that the `Content-Type` is set to `text/plain` so it will
not be accidentally interpreted by HTML by modern browsers.
```
// Get user input
String htmlInput = request.getParameter("userInput");
// Encode the input using the Html4 encoder
String htmlEncoded = StringEscapeUtils.escapeHtml4(htmlInput);
// Force the HTTP response to be content type of text/plain so it is not interpreted as HTML
response.setContentType("text/plain");
// Ensure UTF-8
response.setCharacterEncoding("UTF-8");
// Write response
response.getWriter().write(htmlEncoded);
```
For more information on XSS see OWASP:
- https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
'
severity: WARNING
metadata:
shortDescription: Improper neutralization of input during web page generation ('Cross-site Scripting')
category: security
cwe: CWE-79
owasp:
- A7:2017-Cross-Site Scripting (XSS)
- A03:2021-Injection
- A05:2025-Injection
technology:
- java
security-severity: Medium
- id: gitlab-java_xxe_rule-XMLRdr
languages: [java]
message: 'External XML entities are a feature of XML parsers that allow documents to contain references
to
other documents or data. This feature can be abused to read files, communicate with external
hosts,
exfiltrate data, or cause a Denial of Service (DoS).
The XMLReaderFactory has been deprecated. It is recommended that
[SAXParserFactory](https://docs.oracle.com/javase/9/docs/api/javax/xml/parsers/SAXParserFactory.html)
be used
instead. Additionally when using the SAXParser it must be configured to disallow doctypes,
which will
protect against the majority of XXE attacks.
Example creating a SAXParser with disallowing the doctypes feature enabled:
```
// Create a SAXParserFactory
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
// Enable the feature which disallows <!DOCTYPE declarations which includes referencing
external entities.
saxParserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
// Create a new parser from this factory
SAXParser parser = saxParserFactory.newSAXParser();
// Parse the XML file, passing in a DefaultHandler (which also includes an empty entityResolve
method)
parser.parse(new FileInputStream(new File("bad.xml")), new DefaultHandler());
```
For more information on XML security see OWASP''s guide:
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java
'
patterns:
- pattern-inside: '$R = XMLReaderFactory.createXMLReader();
...
'
- pattern-not-inside: '$R.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
...
'
- pattern: $R.parse(...);
metadata:
shortDescription: Improper restriction of XML external entity reference ('XXE')
category: security
cwe: CWE-611
owasp:
- A4:2017-XML External Entities (XXE)
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
security-severity: Medium
severity: ERROR
- id: gitlab-javascript_buf_rule-buffer-noassert-read
languages: [javascript]
patterns:
- pattern: $OBJ.$METHOD(..., true)
- metavariable-regex:
metavariable: $METHOD
regex: ^(readUInt8|readUInt16LE|readUInt16BE|readUInt32LE|readUInt32BE|readUInt32BE|readInt8|readInt16LE|readInt16BE|readInt32LE|readInt32BE|readFloatLE|readFloatBE|readDoubleLE|readDoubleBE)$
severity: WARNING
metadata:
owasp:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration
cwe: CWE-125
shortDescription: Out-of-bounds read
security-severity: MEDIUM
category: security
source-rule-url: https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-buffer-noassert.js
message: "The application is using Buffer API methods with the `noAssert` \nparameter set to `true` for\
\ the read buffer methods. This disables \nthe bounds checking and could result in reading beyond the\
\ end of \nthe buffer, leading to potential memory corruption and security \nvulnerabilities. When `noAssert`\
\ is set to `true`, the methods \ndo not perform bounds checking, allowing the offset to be beyond \n\
the end of the buffer. This can lead to out-of-bounds memory access, \ncausing undefined behavior, crashes,\
\ or potential security exploits.\n\nTo mitigate the issue, ensure that the `noAssert` parameter is\
\ not \nset to `true`. Always use bounds checking to prevent out-of-bounds \nmemory access. Validate\
\ the offset before performing read operations \non the buffer.\n\nSecure Code Example:\n```\n const\
\ buffer = Buffer.alloc(10); // Allocate a buffer of 10 bytes\n\n function safeBufferMethods(buf) {\n\
\ const safeOffset = 5; // An offset within the bounds of the buffer\n\n // Secure read methods\n\
\ if (safeOffset < buf.length) {\n buf.readUInt8(safeOffset);\n buf.readUInt16LE(safeOffset);\n\
\ buf.readUInt16BE(safeOffset);\n buf.readUInt32LE(safeOffset);\n buf.readUInt32BE(safeOffset);\n\
\ buf.readInt8(safeOffset);\n buf.readInt16LE(safeOffset);\n buf.readInt16BE(safeOffset);\n\
\ buf.readInt32LE(safeOffset);\n buf.readInt32BE(safeOffset);\n buf.readFloatLE(safeOffset);\n\
\ buf.readFloatBE(safeOffset);\n buf.readDoubleLE(safeOffset);\n buf.readDoubleBE(safeOffset);\n\
\ }\n }\n try {\n safeBufferMethods(buffer);\n } catch (error) {\n console.error('Caught\
\ an error:', error);\n }\n```\n"
- id: gitlab-javascript_buf_rule-buffer-noassert-write
languages: [javascript]
patterns:
- pattern: $OBJ.$METHOD(..., true)
- metavariable-regex:
metavariable: $METHOD
regex: ^(writeUInt8|writeUInt16LE|writeUInt16BE|writeUInt32LE|writeUInt32BE|writeInt8|writeInt16LE|writeInt16BE|writeInt32LE|writeInt32BE|writeFloatLE|writeFloatBE|writeDoubleLE|writeDoubleBE)$
severity: WARNING
metadata:
owasp:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration
cwe: CWE-787
shortDescription: Out-of-bounds write
security-severity: MEDIUM
category: security
source-rule-url: https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-buffer-noassert.js
message: "The application is using Buffer API methods with the `noAssert` \nparameter set to `true` for\
\ the write buffer methods. This disables \nthe bounds checking and could result in writing beyond the\
\ end of \nthe buffer, leading to potential memory corruption and security \nvulnerabilities. When `noAssert`\
\ is set to `true`, the methods \ndo not perform bounds checking, allowing the offset to be beyond \n\
the end of the buffer. This can lead to out-of-bounds memory access, \ncausing undefined behavior, crashes,\
\ or potential security exploits.\n\nTo mitigate the issue, ensure that the `noAssert` parameter is\
\ not \nset to `true`. Always use bounds checking to prevent out-of-bounds \nmemory access. Validate\
\ the offset before performing write operations \non the buffer.\n\nSecure Code Example:\n```\n const\
\ buffer = Buffer.alloc(10); // Allocate a buffer of 10 bytes\n\n function safeBufferMethods(buf) {\n\
\ const safeOffset = 5; // An offset within the bounds of the buffer\n\n // Secure write methods\n\
\ if (safeOffset < buf.length) {\n buf.writeUInt8(0, safeOffset);\n buf.writeUInt16LE(0,\
\ safeOffset);\n buf.writeUInt16BE(0, safeOffset);\n buf.writeUInt32LE(0, safeOffset);\n \
\ buf.writeUInt32BE(0, safeOffset);\n buf.writeInt8(0, safeOffset);\n buf.writeInt16LE(0,\
\ safeOffset);\n buf.writeInt16BE(0, safeOffset);\n buf.writeInt32LE(0, safeOffset);\n \
\ buf.writeInt32BE(0, safeOffset);\n buf.writeFloatLE(0, safeOffset);\n buf.writeFloatBE(0,\
\ safeOffset);\n buf.writeDoubleLE(0, safeOffset);\n buf.writeDoubleBE(0, safeOffset);\n \
\ }\n }\n\n try {\n safeBufferMethods(buffer);\n } catch (error) {\n console.error('Caught\
\ an error:', error);\n }\n```\n"
- id: gitlab-javascript_buf_rule-detect-new-buffer
languages: [javascript, typescript]
patterns:
- patterns:
- pattern-not-inside: 'require("safe-buffer")
...'
- pattern-not-inside: 'import { Buffer } from "safe-buffer"
...'
- pattern-inside: function $FUNC(..., $X, ...) { ... }
- pattern: new Buffer($X,...)
- pattern-not: 'new Buffer("...",...)
'
- pattern-not: 'new Buffer([...] , ...)
'
message: 'The application was found calling the `new Buffer` constructor which has been deprecated
since Node 8.
By passing in a non-literal value, an adversary could allocate large amounts of memory.
Other issues also exist with the `Buffer` constructor:
- Older versions would return uninitialized memory, which could contain sensitive information
- Unable to easily determine what a Buffer contained if passed a non-literal value
To remediate this issue, use `Buffer.alloc` or `Buffer.from` instead to allocate a new
`Buffer`.
Example using `Buffer.alloc` instead of `new Buffer(...)`:
```
// Create a new buffer using Buffer.from
const buf = Buffer.from([1, 2, 3, 4]);
// Work with buf
```
For more information on migrating to `Buffer.from()`/`Buffer.alloc()` see:
- https://nodejs.org/en/docs/guides/buffer-constructor-deprecation
'
metadata:
shortDescription: Allocation of resources without limits or throttling
cwe: CWE-770
category: security
owasp:
- A9:2017-Using Components with Known Vulnerabilities
- A06:2021-Vulnerable and Outdated Components
source-rule-url: https://github.com/eslint-community/eslint-plugin-security/blob/main/rules/detect-new-buffer.js
security-severity: Medium
severity: WARNING
- id: gitlab-javascript_dos_rule-non-literal-regexp
languages: [javascript, typescript]
pattern-either:
- patterns:
- pattern: 'new RegExp(...)
'
- pattern-not: 'new RegExp("...", ...)
'
- pattern-not: 'new RegExp(/.../, ...)
'
- patterns:
- pattern: 'RegExp(...)
'
- pattern-not: 'RegExp("...", ...)
'
- pattern-not: 'RegExp(/.../, ...)
'
- patterns:
- pattern: '"...".$METHOD(...)
'
- pattern-not: '"...".$METHOD("...")
'
- pattern-not: '"...".$METHOD(/.../)
'
- metavariable-regex:
metavariable: $METHOD
regex: ^(match|search)$
message: "The `RegExp` constructor was called with a non-literal value. If an adversary were able to\n\
supply a malicious regex, they could cause a Regular Expression Denial of Service (ReDoS)\nagainst the\
\ application. In Node applications, this could cause the entire application to no\nlonger be responsive\
\ to other users' requests.\n\nTo remediate this issue, never allow user-supplied regular expressions.\
\ Instead, the regular \nexpression should be hardcoded. If this is not possible, consider using an\
\ alternative regular\nexpression engine such as [node-re2](https://www.npmjs.com/package/re2). RE2\
\ is a safe alternative \nthat does not support backtracking, which is what leads to ReDoS.\n\nExample\
\ using re2 which does not support backtracking (Note: it is still recommended to\nnever use user-supplied\
\ input):\n```\n// Import the re2 module\nconst RE2 = require('re2');\n\nfunction match(userSuppliedRegex,\
\ userInput) {\n // Create a RE2 object with the user supplied regex, this is relatively safe\n \
\ // due to RE2 not supporting backtracking which can be abused to cause long running\n // queries\n\
\ var re = new RE2(userSuppliedRegex);\n // Execute the regular expression against some userInput\n\
\ var result = re.exec(userInput);\n // Work with the result\n}\n```\n\nFor more information on\
\ Regular Expression DoS see:\n- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS\n"
metadata:
cwe: CWE-185
shortDescription: Regular expression with non-literal value
category: security
owasp:
- A1:2017-Injection
- A03:2021-Injection
security-severity: Medium
severity: WARNING
- id: gitlab-javascript_eval_rule-eval-with-expression
languages: [javascript, typescript]
patterns:
- pattern-either:
- patterns:
- pattern: 'eval($OBJ)
'
- pattern-not: 'eval("...")
'
- patterns:
- pattern: '$A.eval($OBJ)
'
- pattern-not: '$A.eval("...")
'
- patterns:
- pattern: '(..., eval)($OBJ)
'
- pattern-not: '(..., eval)("...")
'
- patterns:
- pattern: '$ALIAS = eval;
...
$ALIAS($OBJ)
'
- pattern-not: '$ALIAS = eval;
...
$ALIAS("...")
'
- pattern: 'new Function(..., "..." + $OBJ + "...")
'
- pattern: '$BODY = "..." + $OBJ + "..."
...
new Function(..., $BODY)
'
- pattern: 'new Function(..., `...${...}...`)
'
- pattern: '$BODY = `...${...}...`
...
new Function(..., $BODY)
'
- pattern: 'Function(..., "..." + $OBJ + "...")
'
- pattern: '$BODY = "..." + $OBJ + "..."
...
Function(..., $BODY)
'
- pattern: '$BODY = `...${...}...`
...
Function(..., $BODY)
'
- pattern: 'Function(..., `...${...}...`)
'
- pattern: 'setTimeout("..." + $OBJ + "...", ...)
'
- pattern: 'setTimeout(`...${...}...`, ...)
'
- pattern: 'setInterval("..." + $OBJ + "...", ...)
'
- pattern: 'setInterval(`...${...}...`, ...)
'
- pattern-not: 'setTimeout("...", ...)
'
- pattern-not: 'setInterval("...", ...)
'
severity: WARNING
message: "The application was found calling the `eval` function OR Function()\n constructor OR setTimeout()\
\ OR setInterval() methods. If the\n\n variables or strings or functions passed to these methods contains\
\ user-supplied input, an adversary could attempt to execute arbitrary\n\n JavaScript\n\n code. This\
\ could lead to a full system compromise in Node applications or Cross-site Scripting\n\n (XSS) in\
\ web applications.\n\n\n To remediate this issue, remove all calls to above methods and consider alternative\
\ methods for\n\n executing\n\n the necessary business logic. There is almost no safe method of calling\
\ `eval` or other above stated sinks with\n\n user-supplied input.\n\n Instead, consider alternative\
\ methods such as using property accessors to dynamically access\n\n values.\n\n\n Example using property\
\ accessors to dynamically access an object's property:\n\n ```\n\n // Define an object\n\n const\
\ obj = {key1: 'value1', key2: 'value2'};\n\n // Get key dynamically from user input\n\n const key\
\ = getUserInput();\n\n // Check if the key exists in our object and return it, or a default empty\
\ string\n\n const value = (obj.hasOwnProperty(key)) ? obj[key] : '';\n\n // Work with the value\n\
\n ```\n\n\n For more information on why not to use `eval`, and alternatives see:\n\n - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval!\n\
\n Other References:\n\n - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function\n\
\n - https://developer.mozilla.org/en-US/docs/Web/API/setTimeout\n\n - https://developer.mozilla.org/en-US/docs/Web/API/setInterval\n"
metadata:
cwe: CWE-95
shortDescription: Improper neutralization of directives in dynamically evaluated code ('Eval Injection')
category: security
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
source-rule-url: https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-eval-with-expression.js
security-severity: High
- id: gitlab-javascript_pathtraversal_rule-non-literal-fs-filename
languages: [typescript, javascript]
patterns:
- pattern-either:
- pattern-inside: 'import $MOD from $IMP
...
'
- pattern-inside: '$MOD = require($IMP)
...
'
- metavariable-comparison:
metavariable: $IMP
comparison: $IMP in ['fs', 'node:fs', 'fs/promises', 'node:fs/promises', 'fs-extra']
- pattern-not: $MOD.appendFile("...", ...)
- pattern-not: $MOD.appendFileSync("...", ...)
- pattern-not: $MOD.chmod("...", ...)
- pattern-not: $MOD.chmodSync("...", ...)
- pattern-not: $MOD.chown("...", ...)
- pattern-not: $MOD.chownSync("...", ...)
- pattern-not: $MOD.createReadStream("...", ...)
- pattern-not: $MOD.createWriteStream("...", ...)
- pattern-not: $MOD.exists("...", ...)
- pattern-not: $MOD.existsSync("...", ...)
- pattern-not: $MOD.lchmod("...", ...)
- pattern-not: $MOD.lchmodSync("...", ...)
- pattern-not: $MOD.lchown("...", ...)
- pattern-not: $MOD.lchownSync("...", ...)
- pattern-not: $MOD.link("...", "...", ...)
- pattern-not: $MOD.linkSync("...", "...", ...)
- pattern-not: $MOD.lstat("...", ...)
- pattern-not: $MOD.lstatSync("...", ...)
- pattern-not: $MOD.mkdir("...", ...)
- pattern-not: $MOD.mkdirSync("...", ...)
- pattern-not: $MOD.open("...", ...)
- pattern-not: $MOD.openSync("...", ...)
- pattern-not: $MOD.readdir("...", ...)
- pattern-not: $MOD.readdirSync("...", ...)
- pattern-not: $MOD.readFile("...", ...)
- pattern-not: $MOD.readFileSync("...", ...)
- pattern-not: $MOD.readlink("...", ...)
- pattern-not: $MOD.readlinkSync("...", ...)
- pattern-not: $MOD.realpath("...", ...)
- pattern-not: $MOD.realpathSync("...", ...)
- pattern-not: $MOD.rename("...", "...", ...)
- pattern-not: $MOD.renameSync("...", "...", ...)
- pattern-not: $MOD.rmdir("...", ...)
- pattern-not: $MOD.rmdirSync("...", ...)
- pattern-not: $MOD.stat("...", ...)
- pattern-not: $MOD.statSync("...", ...)
- pattern-not: $MOD.symlink("...", "...", ...)
- pattern-not: $MOD.symlinkSync("...", "...", ...)
- pattern-not: $MOD.truncate("...", ...)
- pattern-not: $MOD.truncateSync("...", ...)
- pattern-not: $MOD.unlink("...", ...)
- pattern-not: $MOD.unlinkSync("...", ...)
- pattern-not: $MOD.unwatchFile("...", ...)
- pattern-not: $MOD.utimes("...", ...)
- pattern-not: $MOD.utimesSync("...", ...)
- pattern-not: $MOD.watch("...", ...)
- pattern-not: $MOD.watchFile("...", ...)
- pattern-not: $MOD.writeFile("...", ...)
- pattern-not: $MOD.writeFileSync("...", ...)
- pattern-either:
- pattern: $MOD.appendFile(...)
- pattern: $MOD.appendFileSync(...)
- pattern: $MOD.chmod(...)
- pattern: $MOD.chmodSync(...)
- pattern: $MOD.chown(...)
- pattern: $MOD.chownSync(...)
- pattern: $MOD.createReadStream(...)
- pattern: $MOD.createWriteStream(...)
- pattern: $MOD.exists(...)
- pattern: $MOD.existsSync(...)
- pattern: $MOD.lchmod(...)
- pattern: $MOD.lchmodSync(...)
- pattern: $MOD.lchown(...)
- pattern: $MOD.lchownSync(...)
- pattern: $MOD.link(...)
- pattern: $MOD.linkSync(...)
- pattern: $MOD.lstat(...)
- pattern: $MOD.lstatSync(...)
- pattern: $MOD.mkdir(...)
- pattern: $MOD.mkdirSync(...)
- pattern: $MOD.open(...)
- pattern: $MOD.openSync(...)
- pattern: $MOD.readdir(...)
- pattern: $MOD.readdirSync(...)
- pattern: $MOD.readFile(...)
- pattern: $MOD.readFileSync(...)
- pattern: $MOD.readlink(...)
- pattern: $MOD.readlinkSync(...)
- pattern: $MOD.realpath(...)
- pattern: $MOD.realpathSync(...)
- pattern: $MOD.rename(...)
- pattern: $MOD.renameSync(...)
- pattern: $MOD.rmdir(...)
- pattern: $MOD.rmdirSync(...)
- pattern: $MOD.stat(...)
- pattern: $MOD.statSync(...)
- pattern: $MOD.symlink(...)
- pattern: $MOD.symlinkSync(...)
- pattern: $MOD.truncate(...)
- pattern: $MOD.truncateSync(...)
- pattern: $MOD.unlink(...)
- pattern: $MOD.unlinkSync(...)
- pattern: $MOD.unwatchFile(...)
- pattern: $MOD.utimes(...)
- pattern: $MOD.utimesSync(...)
- pattern: $MOD.watch(...)
- pattern: $MOD.watchFile(...)
- pattern: $MOD.writeFile(...)
- pattern: $MOD.writeFileSync(...)
message: "The application dynamically constructs file or path information. If the path\ninformation comes\
\ from user-supplied input, it could be abused to read sensitive files,\naccess other users' data, or\
\ aid in exploitation to gain further system access.\n\nUser input should never be used in constructing\
\ paths or files for interacting\nwith the filesystem. This includes filenames supplied by user uploads\
\ or downloads.\nIf possible, consider hashing user input or using unique values and\nuse `path.normalize`\
\ to resolve and validate the path information\nprior to processing any file functionality.\n\nExample\
\ using `path.normalize` and not allowing direct user input:\n```\n// User input, saved only as a reference\n\
// id is a randomly generated UUID to be used as the filename\nconst userData = {userFilename: userSuppliedFilename,\
\ id: crypto.randomUUID()};\n// Restrict all file processing to this directory only\nconst basePath\
\ = '/app/restricted/';\n\n// Create the full path, but only use our random generated id as the filename\n\
const joinedPath = path.join(basePath, userData.id);\n// Normalize path, removing any '..'\nconst fullPath\
\ = path.normalize(joinedPath);\n// Verify the fullPath is contained within our basePath\nif (!fullPath.startsWith(basePath))\
\ {\n console.log(\"Invalid path specified!\");\n}\n// Process / work with file\n// ...\n```\n\n\
For more information on path traversal issues see OWASP:\nhttps://owasp.org/www-community/attacks/Path_Traversal\n"
metadata:
shortDescription: Improper limitation of a pathname to a restricted directory ('Path Traversal')
cwe: CWE-22
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
security-severity: Medium
category: security
severity: WARNING
- id: gitlab-javascript_random_rule-pseudo-random-bytes
languages: [javascript, typescript]
pattern: crypto.pseudoRandomBytes
severity: WARNING
message: 'Depending on the context, generating weak random numbers may expose cryptographic functions,
which rely on these numbers, to be exploitable. When generating numbers for sensitive values
such as tokens, nonces, and cryptographic keys, it is recommended that the `randomBytes` method
of the `crypto` module be used instead of `pseudoRandomBytes`.
Example using `randomBytes`:
```
// Generate 256 bytes of random data
const randomBytes = crypto.randomBytes(256);
```
For more information on JavaScript Cryptography see:
https://nodejs.org/api/crypto.html#cryptorandombytessize-callback
'
metadata:
cwe: CWE-338
shortDescription: Use of cryptographically weak pseudo-random number generator (PRNG)
category: security
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
source-rule-url: https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-pseudoRandomBytes.js
security-severity: Medium
- id: gitlab-javascript_react_rule-dangerouslysetinnerhtml
languages: [typescript, javascript]
pattern-either:
- pattern: '<$X dangerouslySetInnerHTML=... />
'
- pattern: '{dangerouslySetInnerHTML: ...}
'
severity: WARNING
message: 'The application was found calling `dangerouslySetInnerHTML` which may lead to Cross Site
Scripting (XSS). By default, React components will encode the data properly before rendering.
Calling `dangerouslySetInnerHTML` disables this encoding and allows raw markup
and JavaScript to be executed.
XSS is an attack which exploits a web application or system to treat
user input as markup or script code. It is important to encode the data, depending on the
specific context it is used in. There are at least six context types:
- Inside HTML tags `<div>context 1</div>`
- Inside attributes: `<div class="context 2"></div>`
- Inside event attributes `<button onclick="context 3">button</button>`
- Inside script blocks: `<script>var x = "context 4"</script>`
- Unsafe element HTML assignment: `element.innerHTML = "context 5"`
- Inside URLs: `<iframe src="context 6"></iframe><a href="context 6">link</a>`
Script blocks alone have multiple ways they need to be encoded. Extra care must be taken if
user input
is ever output inside of script tags.
User input that is displayed within the application must be encoded, sanitized or validated
to ensure it cannot be treated as HTML or executed as Javascript code. Care must also be
taken
to not mix server-side templating with client-side templating, as the server-side templating
will
not encode things like {{ 7*7 }} which may execute client-side templating features.
It is _NOT_ advised to encode user input prior to inserting into a data store. The data will
need to be
encoded depending on context of where it is output. It is much safer to force the displaying
system to
handle the encoding and not attempt to guess how it should be encoded.
Remove the call to `dangerouslySetInnerHTML` or ensure that the data used in this call does
not come from user-supplied input.
For more information on dangerously setting inner HTML see:
- https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-html
'
metadata:
cwe: CWE-79
owasp:
- A7:2017-Cross-Site Scripting (XSS)
- A03:2021-Injection
- A05:2025-Injection
shortDescription: Improper neutralization of input during web page generation ('Cross-site Scripting')
category: security
security-severity: Medium
- id: gitlab-javascript_require_rule-non-literal-require
languages: [javascript, typescript]
patterns:
- pattern: require($OBJ)
- pattern-not: require('...')
severity: WARNING
message: 'The application was found to dynamically import a module by calling `require` using a
non-literal string. An adversary might be able to read the first line of
arbitrary files. If they had write access to the file system, they may also be able to
execute arbitrary code.
To remediate this issue, use a hardcoded string literal when calling `require`. Never call it
it with dynamically created variables or user-supplied data.
'
metadata:
cwe: CWE-95
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
shortDescription: Improper neutralization of directives in dynamically evaluated code ('Eval Injection')
category: security
source-rule-url: https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-non-literal-require.js
security-severity: Low
- id: gitlab-javascript_timing_rule-possible-timing-attacks
languages: [javascript]
patterns:
- pattern-not: if ($Z == null) { ... };
- pattern-not: if ($Z === null) { ... };
- pattern-not: if ($Z != null) { ... };
- pattern-not: if ($Z !== null) { ... };
- pattern-not: if ($Q != undefined) { ... };
- pattern-not: if ($Q !== undefined) { ... };
- pattern-not: if ($Q == undefined) { ... };
- pattern-not: if ($Q === undefined) { ... };
- pattern-not: return $Y == null;
- pattern-not: return $Y === null;
- pattern-not: return $Y != null;
- pattern-not: return $Y !== null;
- pattern-not: return $Y == undefined;
- pattern-not: return $Y === undefined;
- pattern-not: return $Y != undefined;
- pattern-not: return $Y !== undefined;
- pattern-either:
- pattern: "if (password == $X) {\n ...\n}\n"
- pattern: "if ($X == password) {\n ...\n}\n"
- pattern: "if (password === $X) {\n ...\n}\n"
- pattern: "if ($X === password) {\n ...\n}\n"
- pattern: "if (pass == $X) {\n ...\n}\n"
- pattern: "if ($X == pass) {\n ...\n}\n"
- pattern: "if (pass === $X) {\n ...\n}\n"
- pattern: "if ($X === pass) {\n ...\n}\n"
- pattern: "if (secret == $X) {\n ...\n}\n"
- pattern: "if ($X == secret) {\n ...\n}\n"
- pattern: "if (secret === $X) {\n ...\n}\n"
- pattern: "if ($X === secret) {\n ...\n}\n"
- pattern: "if (api == $X) {\n ...\n}\n"
- pattern: "if ($X == api) {\n ...\n}\n"
- pattern: "if (api === $X) {\n ...\n}\n"
- pattern: "if ($X === api) {\n ...\n}\n"
- pattern: "if (apiKey == $X) {\n ...\n}\n"
- pattern: "if ($X == apiKey) {\n ...\n}\n"
- pattern: "if (apiKey === $X) {\n ...\n}\n"
- pattern: "if ($X === apiKey) {\n ...\n}\n"
- pattern: "if (apiSecret == $X) {\n ...\n}\n"
- pattern: "if ($X == apiSecret) {\n ...\n}\n"
- pattern: "if (apiSecret === $X) {\n ...\n}\n"
- pattern: "if ($X === apiSecret) {\n ...\n}\n"
- pattern: "if (token == $X) {\n ...\n}\n"
- pattern: "if ($X == token) {\n ...\n}\n"
- pattern: "if (token === $X) {\n ...\n}\n"
- pattern: "if ($X === token) {\n ...\n}\n"
- pattern: "if (hash == $X) {\n ...\n}\n"
- pattern: "if ($X == hash) {\n ...\n}\n"
- pattern: "if (hash === $X) {\n ...\n}\n"
- pattern: "if ($X === hash) {\n ...\n}\n"
- pattern: "if (auth_token == $X) {\n ...\n}\n"
- pattern: "if ($X == auth_token) {\n ...\n}\n"
- pattern: "if (auth_token === $X) {\n ...\n}\n"
- pattern: "if ($X === auth_token) {\n ...\n}\n"
- pattern: "if (password != $X) {\n ...\n}\n"
- pattern: "if ($X != password) {\n ...\n}\n"
- pattern: "if (password !== $X) {\n ...\n}\n"
- pattern: "if ($X !== password) {\n ...\n}\n"
- pattern: "if (pass != $X) {\n ...\n}\n"
- pattern: "if ($X != pass) {\n ...\n}\n"
- pattern: "if (pass !== $X) {\n ...\n}\n"
- pattern: "if ($X !== pass) {\n ...\n}\n"
- pattern: "if (secret != $X) {\n ...\n}\n"
- pattern: "if ($X != secret) {\n ...\n}\n"
- pattern: "if (secret !== $X) {\n ...\n}\n"
- pattern: "if ($X !== secret) {\n ...\n}\n"
- pattern: "if (api != $X) {\n ...\n}\n"
- pattern: "if ($X != api) {\n ...\n}\n"
- pattern: "if (api !== $X) {\n ...\n}\n"
- pattern: "if ($X !== api) {\n ...\n}\n"
- pattern: "if (apiKey != $X) {\n ...\n}\n"
- pattern: "if ($X != apiKey) {\n ...\n}\n"
- pattern: "if (apiKey !== $X) {\n ...\n}\n"
- pattern: "if ($X !== apiKey) {\n ...\n}\n"
- pattern: "if (apiSecret != $X) {\n ...\n}\n"
- pattern: "if ($X != apiSecret) {\n ...\n}\n"
- pattern: "if (apiSecret !== $X) {\n ...\n}\n"
- pattern: "if ($X !== apiSecret) {\n ...\n}\n"
- pattern: "if (token != $X) {\n ...\n}\n"
- pattern: "if ($X != token) {\n ...\n}\n"
- pattern: "if (token !== $X) {\n ...\n}\n"
- pattern: "if ($X !== token) {\n ...\n}\n"
- pattern: "if (hash != $X) {\n ...\n}\n"
- pattern: "if ($X != hash) {\n ...\n}\n"
- pattern: "if (hash !== $X) {\n ...\n}\n"
- pattern: "if ($X !== hash) {\n ...\n}\n"
- pattern: "if (auth_token != $X) {\n ...\n}\n"
- pattern: "if ($X != auth_token) {\n ...\n}\n"
- pattern: "if (auth_token !== $X) {\n ...\n}\n"
- pattern: "if ($X !== auth_token) {\n ...\n}\n"
- pattern: 'return $X === auth_token;
'
- pattern: 'return auth_token === $X;
'
- pattern: 'return $X === token;
'
- pattern: 'return token === $X;
'
- pattern: 'return $X === hash;
'
- pattern: 'return hash === $X;
'
- pattern: 'return $X === password;
'
- pattern: 'return password === $X;
'
- pattern: 'return $X === pass;
'
- pattern: 'return pass === $X;
'
- pattern: 'return $X === apiKey;
'
- pattern: 'return apiKey === $X;
'
- pattern: 'return $X === apiSecret;
'
- pattern: 'return apiSecret === $X;
'
- pattern: 'return $X === api_key;
'
- pattern: 'return api_key === $X;
'
- pattern: 'return $X === api_secret;
'
- pattern: 'return api_secret === $X;
'
- pattern: 'return $X === secret;
'
- pattern: 'return secret === $X;
'
- pattern: 'return $X === api;
'
- pattern: 'return api === $X;
'
- pattern: 'return $X == auth_token;
'
- pattern: 'return auth_token == $X;
'
- pattern: 'return $X == token;
'
- pattern: 'return token == $X;
'
- pattern: 'return $X == hash;
'
- pattern: 'return hash == $X;
'
- pattern: 'return $X == password;
'
- pattern: 'return password == $X;
'
- pattern: 'return $X == pass;
'
- pattern: 'return pass == $X;
'
- pattern: 'return $X == apiKey;
'
- pattern: 'return apiKey == $X;
'
- pattern: 'return $X == apiSecret;
'
- pattern: 'return apiSecret == $X;
'
- pattern: 'return $X == api_key;
'
- pattern: 'return api_key == $X;
'
- pattern: 'return $X == api_secret;
'
- pattern: 'return api_secret == $X;
'
- pattern: 'return $X == secret;
'
- pattern: 'return secret == $X;
'
- pattern: 'return $X == api;
'
- pattern: 'return api == $X;
'
- pattern: 'return $X !== auth_token;
'
- pattern: 'return auth_token !== $X;
'
- pattern: 'return $X !== token;
'
- pattern: 'return token !== $X;
'
- pattern: 'return $X !== hash;
'
- pattern: 'return hash !== $X;
'
- pattern: 'return $X !== password;
'
- pattern: 'return password !== $X;
'
- pattern: 'return $X !== pass;
'
- pattern: 'return pass !== $X;
'
- pattern: 'return $X !== apiKey;
'
- pattern: 'return apiKey !== $X;
'
- pattern: 'return $X !== apiSecret;
'
- pattern: 'return apiSecret !== $X;
'
- pattern: 'return $X !== api_key;
'
- pattern: 'return api_key !== $X;
'
- pattern: 'return $X !== api_secret;
'
- pattern: 'return api_secret !== $X;
'
- pattern: 'return $X !== secret;
'
- pattern: 'return secret !== $X;
'
- pattern: 'return $X !== api;
'
- pattern: 'return api !== $X;
'
- pattern: 'return $X != auth_token;
'
- pattern: 'return auth_token != $X;
'
- pattern: 'return $X != token;
'
- pattern: 'return token != $X;
'
- pattern: 'return $X != hash;
'
- pattern: 'return hash != $X;
'
- pattern: 'return $X != password;
'
- pattern: 'return password != $X;
'
- pattern: 'return $X != pass;
'
- pattern: 'return pass != $X;
'
- pattern: 'return $X != apiKey;
'
- pattern: 'return apiKey != $X;
'
- pattern: 'return $X != apiSecret;
'
- pattern: 'return apiSecret != $X;
'
- pattern: 'return $X != api_key;
'
- pattern: 'return api_key != $X;
'
- pattern: 'return $X != api_secret;
'
- pattern: 'return api_secret != $X;
'
- pattern: 'return $X != secret;
'
- pattern: 'return secret != $X;
'
- pattern: 'return $X != api;
'
- pattern: 'return api != $X;
'
severity: WARNING
message: "The application was found executing string comparisons using one of `===`, `!==`, `==` or `!=`\n\
against security sensitive values. String comparisons like this are not constant time, meaning\nthe\n\
first character found not to match in the two strings will immediately exit the conditional\nstatement.\n\
This allows an adversary to calculate or observe small timing differences depending on the\nstrings\n\
passed to this comparison. This potentially allows an adversary the ability to brute force a\nstring\n\
that will match the expected value by monitoring different character values.\n\nTo remediate this issue,\
\ use the `crypto.timingSafeEqual` method when comparing strings.\n\nExample using `crypto.timingSafeEqual`\
\ to safely compare strings:\n```\nfunction constantTimeIsPasswordEqual(userInput) {\n // Retrieve\
\ the password from a secure data store such as a KMS or Hashicorp's vault.\n const password = getPasswordFromSecureDataStore();\n\
\ // Use crypto timingSafeEqual to ensure the comparison is done in constant time.\n return crypto.timingSafeEqual(Buffer.from(userInput,\
\ 'utf-8'), Buffer.from(password,\n'utf-8'));\n}\n```\n\nFor more information on constant time comparison\
\ see:\n- https://nodejs.org/api/crypto.html#crypto_crypto_timingsafeequal_a_b\n"
metadata:
cwe: CWE-208
shortDescription: Observable timing discrepancy
category: security
owasp:
- A3:2017-Sensitive Data Exposure
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
security-severity: Medium
- id: gitlab-python_bind-all-interfaces_rule-general-bindall-interfaces
languages: [python]
message: 'Binding to all network interfaces can potentially open up a service to
traffic on unintended interfaces, that may not be properly documented or
secured. By passing "0.0.0.0", "::" or an empty string as the address to the `socket.bind`
function,
the application will bind to all interfaces.
Consider passing in the interface ip address through an environment variable,
configuration file, or by determining the primary interface(s) IP address.
Example getting the IP address from an environment variable `IP_ADDRESS`:
```
# Get the IP_ADDRESS env variable, or bind to
# 127.0.0.1 if it is not set
address = os.getenv("IP_ADDRESS", "127.0.0.1")
# Create an internet socket
sock = socket.socket(socket.AF_INET)
# Set the port to listen on
port = 9777
# Bind to the address and port combination
sock.bind((address, port))
# Listen for connections
sock.listen()
# Handle the connection
```
'
patterns:
- pattern-either:
- pattern: '$S = socket.socket(...)
...
$S.bind(("0.0.0.0", ...))
'
- pattern: '$S = socket.socket(...)
...
$S.bind(("::", ...))
'
- pattern: '$S = socket.socket(...)
...
$S.bind(("", ...))
'
metadata:
category: security
owasp:
- A6:2017-Security Misconfiguration
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
shortDescription: Binding to an unrestricted IP address
cwe: CWE-1327
security-severity: Low
severity: INFO
- id: gitlab-python_crypto_rule-cipher-modes
languages: [python]
message: "Cryptographic algorithms provide many different modes of operation, only some of which provide\n\
message integrity. Without message integrity it could be possible for an adversary to attempt\nto tamper\
\ with the ciphertext which could lead to compromising the encryption key. Newer\nalgorithms\napply\
\ message integrity to validate ciphertext has not been tampered with.\n\nInstead of using an algorithm\
\ that requires configuring a cipher mode, an algorithm\nthat has built-in message integrity should\
\ be used. Consider using `ChaCha20Poly1305` or\n`AES-256-GCM` instead.\n\nFor older applications that\
\ don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is\nrecommended, however it has many drawbacks:\n\
\ - Slower than `ChaCha20Poly1305`.\n - Catastrophic failure if nonce values are reused.\n\nExample\
\ using `ChaCha20Poly1305`:\n```\nimport os\n# Import ChaCha20Poly1305 from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead\
\ import ChaCha20Poly1305\n# Our plaintext to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We\
\ do not require authenticated but unencrypted data, so set to None\naad = None\n# Generate a secure\
\ key\nkey = ChaCha20Poly1305.generate_key()\n# Create a new ChaCha20Poly1305 instance with our secure\
\ key\nchacha = ChaCha20Poly1305(key)\n# Note: nonce values _must_ be regenerated every time they are\
\ used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text = chacha.encrypt(nonce, plain_text,\
\ aad)\n# Decrypt the plain text using the nonce and cipher_text\nchacha.decrypt(nonce, cipher_text,\
\ aad)\n```\n\nExample using `AESGCM`:\n```\nimport os\n# Import AESGCM from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead\
\ import AESGCM\n# Our plaintext to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We do not require\
\ authenticated but unencrypted data, so set to None\naad = None\n# Generate a secure key\nkey = AESGCM.generate_key(bit_length=128)\n\
# Create a new AESGCM instance with our secure key\naesgcm = AESGCM(key)\n# Note: nonce values _must_\
\ be regenerated every time they are used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text\
\ = aesgcm.encrypt(nonce, plain_text, aad)\n# Decrypt the plain text using the nonce and cipher_text\n\
aesgcm.decrypt(nonce, cipher_text, aad)\n```\n\nFor more information on the cryptography module see:\n\
- https://cryptography.io/en/latest/\n"
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
pattern: cryptography.hazmat.primitives.ciphers.modes.ECB(...)
severity: WARNING
- id: gitlab-python_crypto_rule-crypto-cipher-blowfish
languages: [python]
message: "The Blowfish encryption algorithm was meant as a drop-in replacement for DES and was created\
\ in\n1993. Smaller key sizes may make the ciphertext vulnerable to [birthday\nattacks](https://en.wikipedia.org/wiki/Birthday_attack).\
\ While no known attacks against\nBlowfish\nexist, it should never be used to encrypt files over 4GB\
\ in size. If possible consider\nusing ChaCha20Poly1305 or AES-GCM instead of Blowfish.\n\nFor older\
\ applications that don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is\nrecommended, however\
\ it has many drawbacks:\n - Slower than `ChaCha20Poly1305`.\n - Catastrophic failure if nonce values\
\ are reused.\n\nNote that the `Crypto` and `Cryptodome` Python packages are no longer recommended for\n\
new applications, instead consider using the [cryptography](https://cryptography.io/) package.\n\nExample\
\ using `ChaCha20Poly1305`:\n```\nimport os\n# Import ChaCha20Poly1305 from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead\
\ import ChaCha20Poly1305\n# Our plaintext to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We\
\ do not require authenticated but unencrypted data, so set to None\naad = None\n# Generate a secure\
\ key\nkey = ChaCha20Poly1305.generate_key()\n# Create a new ChaCha20Poly1305 instance with our secure\
\ key\nchacha = ChaCha20Poly1305(key)\n# Note: nonce values _must_ be regenerated every time they are\
\ used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text = chacha.encrypt(nonce, plain_text,\
\ aad)\n# Decrypt the plain text using the nonce and cipher_text\nchacha.decrypt(nonce, cipher_text,\
\ aad)\n```\n\nExample using `AESGCM`:\n```\nimport os\n# Import AESGCM from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead\
\ import AESGCM\n# Our plaintext to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We do not require\
\ authenticated but unencrypted data, so set to None\naad = None\n# Generate a secure key\nkey = AESGCM.generate_key(bit_length=128)\n\
# Create a new AESGCM instance with our secure key\naesgcm = AESGCM(key)\n# Note: nonce values _must_\
\ be regenerated every time they are used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text\
\ = aesgcm.encrypt(nonce, plain_text, aad)\n# Decrypt the plain text using the nonce and cipher_text\n\
aesgcm.decrypt(nonce, cipher_text, aad)\n```\n\nFor more information on the cryptography module see:\n\
- https://cryptography.io/en/latest/\n"
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
patterns:
- pattern-either:
- pattern: Cryptodome.Cipher.Blowfish.new(...)
- pattern: Crypto.Cipher.Blowfish.new(...)
severity: WARNING
- id: gitlab-python_crypto_rule-crypto-cipher-des
languages: [python]
message: 'DES, TripleDES, RC2 and RC4 are all considered broken or insecure cryptographic algorithms.
Newer algorithms apply message integrity to validate ciphertext has not been tampered
with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the
alternatives such as `AES-256-GCM`.
For older applications that don''t have support for `ChaCha20Poly1305`,
`AES-256-GCM` is recommended, however it has many drawbacks:
- Slower than `ChaCha20Poly1305`.
- Catastrophic failure if nonce values are reused.
Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for
new applications, instead consider using the [cryptography](https://cryptography.io/) package.
Example using `ChaCha20Poly1305`:
```
import os
# Import ChaCha20Poly1305 from cryptography
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
# Our plaintext to encrypt
plain_text = b"Secret text to encrypt"
# We do not require authenticated but unencrypted data, so set to None
aad = None
# Generate a secure key
key = ChaCha20Poly1305.generate_key()
# Create a new ChaCha20Poly1305 instance with our secure key
chacha = ChaCha20Poly1305(key)
# Note: nonce values _must_ be regenerated every time they are used.
nonce = os.urandom(12)
# Encrypt our plaintext
cipher_text = chacha.encrypt(nonce, plain_text, aad)
# Decrypt the plain text using the nonce and cipher_text
chacha.decrypt(nonce, cipher_text, aad)
```
Example using `AESGCM`:
```
import os
# Import AESGCM from cryptography
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
# Our plaintext to encrypt
plain_text = b"Secret text to encrypt"
# We do not require authenticated but unencrypted data, so set to None
aad = None
# Generate a secure key
key = AESGCM.generate_key(bit_length=128)
# Create a new AESGCM instance with our secure key
aesgcm = AESGCM(key)
# Note: nonce values _must_ be regenerated every time they are used.
nonce = os.urandom(12)
# Encrypt our plaintext
cipher_text = aesgcm.encrypt(nonce, plain_text, aad)
# Decrypt the plain text using the nonce and cipher_text
aesgcm.decrypt(nonce, cipher_text, aad)
```
For more information on the cryptography module see:
- https://cryptography.io/en/latest/
'
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
patterns:
- pattern-either:
- pattern: Cryptodome.Cipher.DES.new(...)
- pattern: Crypto.Cipher.DES.new(...)
severity: WARNING
- id: gitlab-python_crypto_rule-crypto-cipher-rc2
languages: [python]
message: 'DES, TripleDES, RC2 and RC4 are all considered broken or insecure cryptographic algorithms.
Newer algorithms apply message integrity to validate ciphertext has not been tampered
with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the
alternatives such as `AES-256-GCM`.
For older applications that don''t have support for `ChaCha20Poly1305`,
`AES-256-GCM` is recommended, however it has many drawbacks:
- Slower than `ChaCha20Poly1305`.
- Catastrophic failure if nonce values are reused.
Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for
new applications, instead consider using the [cryptography](https://cryptography.io/) package.
Example using `ChaCha20Poly1305`:
```
import os
# Import ChaCha20Poly1305 from cryptography
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
# Our plaintext to encrypt
plain_text = b"Secret text to encrypt"
# We do not require authenticated but unencrypted data, so set to None
aad = None
# Generate a secure key
key = ChaCha20Poly1305.generate_key()
# Create a new ChaCha20Poly1305 instance with our secure key
chacha = ChaCha20Poly1305(key)
# Note: nonce values _must_ be regenerated every time they are used.
nonce = os.urandom(12)
# Encrypt our plaintext
cipher_text = chacha.encrypt(nonce, plain_text, aad)
# Decrypt the plain text using the nonce and cipher_text
chacha.decrypt(nonce, cipher_text, aad)
```
Example using `AESGCM`:
```
import os
# Import AESGCM from cryptography
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
# Our plaintext to encrypt
plain_text = b"Secret text to encrypt"
# We do not require authenticated but unencrypted data, so set to None
aad = None
# Generate a secure key
key = AESGCM.generate_key(bit_length=128)
# Create a new AESGCM instance with our secure key
aesgcm = AESGCM(key)
# Note: nonce values _must_ be regenerated every time they are used.
nonce = os.urandom(12)
# Encrypt our plaintext
cipher_text = aesgcm.encrypt(nonce, plain_text, aad)
# Decrypt the plain text using the nonce and cipher_text
aesgcm.decrypt(nonce, cipher_text, aad)
```
For more information on the cryptography module see:
- https://cryptography.io/en/latest/
'
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
patterns:
- pattern-either:
- pattern: Cryptodome.Cipher.ARC2.new(...)
- pattern: Crypto.Cipher.ARC2.new
severity: WARNING
- id: gitlab-python_crypto_rule-crypto-cipher-rc4
languages: [python]
message: 'DES, TripleDES, RC2 and RC4 are all considered broken or insecure cryptographic algorithms.
Newer algorithms apply message integrity to validate ciphertext has not been tampered
with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the
alternatives such as `AES-256-GCM`.
For older applications that don''t have support for `ChaCha20Poly1305`,
`AES-256-GCM` is recommended, however it has many drawbacks:
- Slower than `ChaCha20Poly1305`.
- Catastrophic failure if nonce values are reused.
Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for
new applications, instead consider using the [cryptography](https://cryptography.io/) package.
Example using `ChaCha20Poly1305`:
```
import os
# Import ChaCha20Poly1305 from cryptography
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
# Our plaintext to encrypt
plain_text = b"Secret text to encrypt"
# We do not require authenticated but unencrypted data, so set to None
aad = None
# Generate a secure key
key = ChaCha20Poly1305.generate_key()
# Create a new ChaCha20Poly1305 instance with our secure key
chacha = ChaCha20Poly1305(key)
# Note: nonce values _must_ be regenerated every time they are used.
nonce = os.urandom(12)
# Encrypt our plaintext
cipher_text = chacha.encrypt(nonce, plain_text, aad)
# Decrypt the plain text using the nonce and cipher_text
chacha.decrypt(nonce, cipher_text, aad)
```
Example using `AESGCM`:
```
import os
# Import AESGCM from cryptography
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
# Our plaintext to encrypt
plain_text = b"Secret text to encrypt"
# We do not require authenticated but unencrypted data, so set to None
aad = None
# Generate a secure key
key = AESGCM.generate_key(bit_length=128)
# Create a new AESGCM instance with our secure key
aesgcm = AESGCM(key)
# Note: nonce values _must_ be regenerated every time they are used.
nonce = os.urandom(12)
# Encrypt our plaintext
cipher_text = aesgcm.encrypt(nonce, plain_text, aad)
# Decrypt the plain text using the nonce and cipher_text
aesgcm.decrypt(nonce, cipher_text, aad)
```
For more information on the cryptography module see:
- https://cryptography.io/en/latest/
'
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
patterns:
- pattern-either:
- pattern: Cryptodome.Cipher.ARC4.new(...)
- pattern: Crypto.Cipher.ARC4.new(...)
severity: WARNING
- id: gitlab-python_crypto_rule-crypto-cipher-xor
languages: [python]
message: 'The application was found using the `xor` algorithm, which can be trivially decoded.
Newer algorithms apply message integrity to validate ciphertext has not been tampered
with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the
alternatives such as `AES-256-GCM`.
For older applications that don''t have support for `ChaCha20Poly1305`,
`AES-256-GCM` is recommended, however it has many drawbacks:
- Slower than `ChaCha20Poly1305`.
- Catastrophic failure if nonce values are reused.
Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for
new applications, instead consider using the [cryptography](https://cryptography.io/) package.
Example using `ChaCha20Poly1305`:
```
import os
# Import ChaCha20Poly1305 from cryptography
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
# Our plaintext to encrypt
plain_text = b"Secret text to encrypt"
# We do not require authenticated but unencrypted data, so set to None
aad = None
# Generate a secure key
key = ChaCha20Poly1305.generate_key()
# Create a new ChaCha20Poly1305 instance with our secure key
chacha = ChaCha20Poly1305(key)
# Note: nonce values _must_ be regenerated every time they are used.
nonce = os.urandom(12)
# Encrypt our plaintext
cipher_text = chacha.encrypt(nonce, plain_text, aad)
# Decrypt the plain text using the nonce and cipher_text
chacha.decrypt(nonce, cipher_text, aad)
```
Example using `AESGCM`:
```
import os
# Import AESGCM from cryptography
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
# Our plaintext to encrypt
plain_text = b"Secret text to encrypt"
# We do not require authenticated but unencrypted data, so set to None
aad = None
# Generate a secure key
key = AESGCM.generate_key(bit_length=128)
# Create a new AESGCM instance with our secure key
aesgcm = AESGCM(key)
# Note: nonce values _must_ be regenerated every time they are used.
nonce = os.urandom(12)
# Encrypt our plaintext
cipher_text = aesgcm.encrypt(nonce, plain_text, aad)
# Decrypt the plain text using the nonce and cipher_text
aesgcm.decrypt(nonce, cipher_text, aad)
```
For more information on the cryptography module see:
- https://cryptography.io/en/latest/
'
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
patterns:
- pattern-either:
- pattern: Cryptodome.Cipher.XOR.new(...)
- pattern: Crypto.Cipher.XOR.new(...)
severity: WARNING
- id: gitlab-python_crypto_rule-crypto-encrypt-dsa-rsa
languages: [python]
message: "The application is generating an RSA key that is less than the recommended 2048 bits.\nThe National\
\ Institute of Standards and Technology (NIST) deprecated signing Digital\nCertificates that contained\
\ RSA Public Keys of 1024 bits in December 2010. While\n1024-bit RSA keys have not been factored yet,\
\ advances in compute may make it possible\nin the near future.\n\nConsider upgrading to the newer asymmetric\
\ algorithm such as `X25519` which handles\nthe complexities of generating key pairs and choosing correct\
\ key sizes for you:\n```\nfrom cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey\n\
\n# Generate a private key for use in the exchange.\nprivate_key = X25519PrivateKey.generate()\n# Work\
\ with private key/exchange with a peer's\n# public key to created a shared and derived key\n# ...\n\
```\n\nOtherwise use a key size greater than 2048 when generating RSA keys:\n```\nfrom cryptography.hazmat.primitives.asymmetric\
\ import rsa\n# Generate a private key of 4096 bits\nprivate_key = rsa.generate_private_key(\n #\
\ do not change the exponent value from 65537\n public_exponent=65537,\n key_size=4096,\n)\n#\
\ Work with the private key to sign/encrypt data\n# ...\n```\n\nFor more information on using the cryptography\
\ module see:\n- https://cryptography.io/en/latest\n"
metadata:
cwe: CWE-326
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Inadequate encryption strength
security-severity: Medium
patterns:
- pattern-either:
- pattern: 'cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(...,key_size=$SIZE,...)
'
- pattern: 'cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key($EXP, $SIZE,...)
'
- pattern: 'cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key($SIZE, ...)
'
- pattern: 'cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key(...,key_size=$SIZE,...)
'
- pattern: 'cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key($EXP, $SIZE, ...)
'
- pattern: cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key($SIZE,...)
- pattern: Crypto.PublicKey.RSA.generate($SIZE, ...)
- pattern: Crypto.PublicKey.DSA.generate($SIZE, ...)
- pattern: Cryptodome.PublicKey.DSA.generate($SIZE, ...)
- pattern: Cryptodome.PublicKey.RSA.generate($SIZE, ...)
- pattern: Crypto.PublicKey.DSA.generate(bits=$SIZE, ...)
- pattern: Cryptodome.PublicKey.DSA.generate(bits=$SIZE, ...)
- pattern: pycrypto_rsa.generate(bits=$SIZE, ...)
- pattern: pycrypto_dsa.generate(bits=$SIZE, ...)
- pattern: pycryptodomex_rsa.generate(bits=$SIZE, ...)
- pattern: pycryptodomex_rsa.generate($SIZE, ...)
- pattern: pycryptodomex_dsa.generate(bits=$SIZE, ...)
- pattern: pycryptodomex_dsa.generate($SIZE, ...)
- metavariable-comparison:
comparison: $SIZE < 2048
metavariable: $SIZE
severity: ERROR
- id: gitlab-python_crypto_rule-crypto-hash-md5
languages: [python]
message: 'The application was found using an insecure or risky digest or signature algorithm. MD5
and SHA1 hash algorithms have been found to be vulnerable to producing collisions.
This means
that two different values, when hashed, can lead to the same hash value. If the application is
trying
to use these hash methods for storing passwords, then it is recommended to switch to a
password hashing
algorithm such as Argon2id or PBKDF2.
It is strongly recommended that a standard digest algorithm be chosen instead as implementing
a custom algorithm is prone to errors.
Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for
new applications, instead consider using the [cryptography](https://cryptography.io/) package.
Example of creating a SHA-384 hash using the `cryptography` package:
```
from cryptography.hazmat.primitives import hashes
# Create a SHA384 digest
digest = hashes.Hash(hashes.SHA384())
# Update the digest with some initial data
digest.update(b"some data to hash")
# Add more data to the digest
digest.update(b"some more data")
# Finalize the digest as bytes
result = digest.finalize()
```
For more information on secure password storage see OWASP:
- https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
For more information on the cryptography module see:
- https://cryptography.io/en/latest/
'
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
patterns:
- pattern-either:
- pattern: Crypto.Hash.MD5.new(...)
- pattern: Cryptodome.Hash.MD5.new (...)
severity: WARNING
- id: gitlab-python_crypto_rule-crypto-hash-sha1
languages: [python]
message: 'The application was found using an insecure or risky digest or signature algorithm. MD5
and SHA1 hash algorithms have been found to be vulnerable to producing collisions.
This means
that two different values, when hashed, can lead to the same hash value. If the application is
trying
to use these hash methods for storing passwords, then it is recommended to switch to a
password hashing
algorithm such as Argon2id or PBKDF2.
It is strongly recommended that a standard digest algorithm be chosen instead as implementing
a custom algorithm is prone to errors.
Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for
new applications, instead consider using the [cryptography](https://cryptography.io/) package.
Example of creating a SHA-384 hash using the `cryptography` package:
```
from cryptography.hazmat.primitives import hashes
# Create a SHA384 digest
digest = hashes.Hash(hashes.SHA384())
# Update the digest with some initial data
digest.update(b"some data to hash")
# Add more data to the digest
digest.update(b"some more data")
# Finalize the digest as bytes
result = digest.finalize()
```
For more information on secure password storage see OWASP:
- https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
For more information on the cryptography module see:
- https://cryptography.io/en/latest/
'
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
patterns:
- pattern-either:
- pattern: Crypto.Hash.SHA.new(...)
- pattern: Cryptodome.Hash.SHA.new (...)
severity: WARNING
- id: gitlab-python_crypto_rule-crypto-hazmat-cipher-arc4
languages: [python]
message: 'DES, TripleDES, RC2 and RC4 are all considered broken or insecure cryptographic algorithms.
Newer algorithms apply message integrity to validate ciphertext has not been tampered
with. Consider using `ChaCha20Poly1305` instead as it is easier and faster than the
alternatives such as `AES-256-GCM`.
For older applications that don''t have support for `ChaCha20Poly1305`,
`AES-256-GCM` is recommended, however it has many drawbacks:
- Slower than `ChaCha20Poly1305`.
- Catastrophic failure if nonce values are reused.
Example using `ChaCha20Poly1305`:
```
import os
# Import ChaCha20Poly1305 from cryptography
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
# Our plaintext to encrypt
plain_text = b"Secret text to encrypt"
# We do not require authenticated but unencrypted data, so set to None
aad = None
# Generate a secure key
key = ChaCha20Poly1305.generate_key()
# Create a new ChaCha20Poly1305 instance with our secure key
chacha = ChaCha20Poly1305(key)
# Note: nonce values _must_ be regenerated every time they are used.
nonce = os.urandom(12)
# Encrypt our plaintext
cipher_text = chacha.encrypt(nonce, plain_text, aad)
# Decrypt the plain text using the nonce and cipher_text
chacha.decrypt(nonce, cipher_text, aad)
```
Example using `AESGCM`:
```
import os
# Import AESGCM from cryptography
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
# Our plaintext to encrypt
plain_text = b"Secret text to encrypt"
# We do not require authenticated but unencrypted data, so set to None
aad = None
# Generate a secure key
key = AESGCM.generate_key(bit_length=128)
# Create a new AESGCM instance with our secure key
aesgcm = AESGCM(key)
# Note: nonce values _must_ be regenerated every time they are used.
nonce = os.urandom(12)
# Encrypt our plaintext
cipher_text = aesgcm.encrypt(nonce, plain_text, aad)
# Decrypt the plain text using the nonce and cipher_text
aesgcm.decrypt(nonce, cipher_text, aad)
```
For more information on the cryptography module see:
- https://cryptography.io/en/latest/
'
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
pattern: cryptography.hazmat.primitives.ciphers.algorithms.ARC4(...)
severity: WARNING
- id: gitlab-python_crypto_rule-crypto-hazmat-cipher-blowfish
languages: [python]
message: "The Blowfish encryption algorithm was meant as a drop-in replacement for DES and was created\
\ in\n1993. Smaller key sizes may make the ciphertext vulnerable to [birthday\nattacks](https://en.wikipedia.org/wiki/Birthday_attack).\
\ While no known attacks against\nBlowfish\nexist, it should never be used to encrypt files over 4GB\
\ in size. If possible consider\nusing ChaCha20Poly1305 or AES-GCM instead of Blowfish.\n\nFor older\
\ applications that don't have support for `ChaCha20Poly1305`, `AES-256-GCM` is\nrecommended, however\
\ it has many drawbacks:\n - Slower than `ChaCha20Poly1305`.\n - Catastrophic failure if nonce values\
\ are reused.\n\nExample using `ChaCha20Poly1305`:\n```\nimport os\n# Import ChaCha20Poly1305 from cryptography\n\
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305\n# Our plaintext to encrypt\n\
plain_text = b\"Secret text to encrypt\"\n# We do not require authenticated but unencrypted data, so\
\ set to None\naad = None\n# Generate a secure key\nkey = ChaCha20Poly1305.generate_key()\n# Create\
\ a new ChaCha20Poly1305 instance with our secure key\nchacha = ChaCha20Poly1305(key)\n# Note: nonce\
\ values _must_ be regenerated every time they are used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\n\
cipher_text = chacha.encrypt(nonce, plain_text, aad)\n# Decrypt the plain text using the nonce and cipher_text\n\
chacha.decrypt(nonce, cipher_text, aad)\n```\n\nExample using `AESGCM`:\n```\nimport os\n# Import AESGCM\
\ from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead import AESGCM\n# Our plaintext\
\ to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We do not require authenticated but unencrypted\
\ data, so set to None\naad = None\n# Generate a secure key\nkey = AESGCM.generate_key(bit_length=128)\n\
# Create a new AESGCM instance with our secure key\naesgcm = AESGCM(key)\n# Note: nonce values _must_\
\ be regenerated every time they are used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text\
\ = aesgcm.encrypt(nonce, plain_text, aad)\n# Decrypt the plain text using the nonce and cipher_text\n\
aesgcm.decrypt(nonce, cipher_text, aad)\n```\n\nFor more information on the cryptography module see:\n\
- https://cryptography.io/en/latest/\n"
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
pattern: cryptography.hazmat.primitives.ciphers.algorithms.Blowfish(...)
severity: WARNING
- id: gitlab-python_crypto_rule-crypto-hazmat-cipher-idea
languages: [python]
message: "The IDEA encryption algorithm was meant as a drop-in replacement for DES and was created in\n\
1991. A number of [vulnerabilities and\nexploits](https://en.wikipedia.org/wiki/International_Data_Encryption_Algorithm#Security)\
\ have\nbeen identified to work against IDEA and\nit is no longer recommended. If possible consider\n\
using ChaCha20Poly1305 or AES-GCM instead of Blowfish.\n\nFor older applications that don't have support\
\ for `ChaCha20Poly1305`, `AES-256-GCM` is\nrecommended, however it has many drawbacks:\n - Slower\
\ than `ChaCha20Poly1305`.\n - Catastrophic failure if nonce values are reused.\n\nExample using `ChaCha20Poly1305`:\n\
```\nimport os\n# Import ChaCha20Poly1305 from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead\
\ import ChaCha20Poly1305\n# Our plaintext to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We\
\ do not require authenticated but unencrypted data, so set to None\naad = None\n# Generate a secure\
\ key\nkey = ChaCha20Poly1305.generate_key()\n# Create a new ChaCha20Poly1305 instance with our secure\
\ key\nchacha = ChaCha20Poly1305(key)\n# Note: nonce values _must_ be regenerated every time they are\
\ used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text = chacha.encrypt(nonce, plain_text,\
\ aad)\n# Decrypt the plain text using the nonce and cipher_text\nchacha.decrypt(nonce, cipher_text,\
\ aad)\n```\n\nExample using `AESGCM`:\n```\nimport os\n# Import AESGCM from cryptography\nfrom cryptography.hazmat.primitives.ciphers.aead\
\ import AESGCM\n# Our plaintext to encrypt\nplain_text = b\"Secret text to encrypt\"\n# We do not require\
\ authenticated but unencrypted data, so set to None\naad = None\n# Generate a secure key\nkey = AESGCM.generate_key(bit_length=128)\n\
# Create a new AESGCM instance with our secure key\naesgcm = AESGCM(key)\n# Note: nonce values _must_\
\ be regenerated every time they are used.\nnonce = os.urandom(12)\n# Encrypt our plaintext\ncipher_text\
\ = aesgcm.encrypt(nonce, plain_text, aad)\n# Decrypt the plain text using the nonce and cipher_text\n\
aesgcm.decrypt(nonce, cipher_text, aad)\n```\n\nFor more information on the cryptography module see:\n\
- https://cryptography.io/en/latest/\n"
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
shortDescription: Use of a Broken or Risky Cryptographic Algorithm
security-severity: Medium
category: security
pattern: cryptography.hazmat.primitives.ciphers.algorithms.IDEA(...)
severity: WARNING
- id: gitlab-python_crypto_rule-crypto-hazmat-hash-md5
languages: [python]
message: 'The application was found using an insecure or risky digest or signature algorithm. MD2, MD5
and SHA1 hash algorithms have been found to be vulnerable to producing collisions.
This means
that two different values, when hashed, can lead to the same hash value. If the application is
trying
to use these hash methods for storing passwords, then it is recommended to switch to a
password hashing
algorithm such as Argon2id or PBKDF2.
It is strongly recommended that a standard digest algorithm be chosen instead as implementing
a custom algorithm is prone to errors.
Example of creating a SHA-384 hash using the `cryptography` package:
```
from cryptography.hazmat.primitives import hashes
# Create a SHA384 digest
digest = hashes.Hash(hashes.SHA384())
# Update the digest with some initial data
digest.update(b"some data to hash")
# Add more data to the digest
digest.update(b"some more data")
# Finalize the digest as bytes
result = digest.finalize()
```
For more information on secure password storage see OWASP:
- https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
For more information on the cryptography module see:
- https://cryptography.io/en/latest/
'
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
category: security
pattern: cryptography.hazmat.primitives.hashes.MD5(...)
severity: WARNING
- id: gitlab-python_crypto_rule-crypto-hazmat-hash-sha1
languages: [python]
message: 'The application was found using an insecure or risky digest or signature algorithm. MD2, MD5
and SHA1 hash algorithms have been found to be vulnerable to producing collisions.
This means
that two different values, when hashed, can lead to the same hash value. If the application is
trying
to use these hash methods for storing passwords, then it is recommended to switch to a
password hashing
algorithm such as Argon2id or PBKDF2.
It is strongly recommended that a standard digest algorithm be chosen instead as implementing
a custom algorithm is prone to error.
Example of creating a SHA-384 hash using the `cryptography` package:
```
from cryptography.hazmat.primitives import hashes
# Create a SHA384 digest
digest = hashes.Hash(hashes.SHA384())
# Update the digest with some initial data
digest.update(b"some data to hash")
# Add more data to the digest
digest.update(b"some more data")
# Finalize the digest as bytes
result = digest.finalize()
```
For more information on secure password storage see OWASP:
- https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
For more information on the cryptography module see:
- https://cryptography.io/en/latest/
'
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
pattern: cryptography.hazmat.primitives.hashes.SHA1(...)
severity: WARNING
- id: gitlab-python_crypto_rule-hash-md2
languages: [python]
message: 'The application was found using an insecure or risky digest or signature algorithm. MD2, MD5
and SHA1 hash algorithms have been found to be vulnerable to producing collisions.
This means
that two different values, when hashed, can lead to the same hash value. If the application is
trying
to use these hash methods for storing passwords, then it is recommended to switch to a
password hashing
algorithm such as Argon2id or PBKDF2.
Note that the `Crypto` and `Cryptodome` Python packages are no longer recommended for
new applications, instead consider using the [cryptography](https://cryptography.io/) package.
Example of creating a SHA-384 hash using the `cryptography` package:
```
from cryptography.hazmat.primitives import hashes
# Create a SHA384 digest
digest = hashes.Hash(hashes.SHA384())
# Update the digest with some initial data
digest.update(b"some data to hash")
# Add more data to the digest
digest.update(b"some more data")
# Finalize the digest as bytes
result = digest.finalize()
```
For more information on secure password storage see OWASP:
- https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
For more information on the cryptography module see:
- https://cryptography.io/en/latest/
'
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
patterns:
- pattern-either:
- pattern: Crypto.Hash.MD2.new(...)
- pattern: Cryptodome.Hash.MD2.new (...)
severity: WARNING
- id: gitlab-python_crypto_rule-hash-md4
languages: [python]
message: "The application was found using an insecure or risky digest or signature algorithm. MD2, MD4,\n\
\ MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions.\n\nThis means\n\
that two different values, when hashed, can lead to the same hash value. If the application is\ntrying\n\
to use these hash methods for storing passwords, then it is recommended to switch to a\npassword hashing\n\
algorithm such as Argon2id or PBKDF2.\n\nNote that the `Crypto` and `Cryptodome` Python packages are\
\ no longer recommended for\nnew applications, instead consider using the [cryptography](https://cryptography.io/)\
\ package.\n\nExample of creating a SHA-384 hash using the `cryptography` package:\n```\nfrom cryptography.hazmat.primitives\
\ import hashes\n# Create a SHA384 digest\ndigest = hashes.Hash(hashes.SHA384())\n# Update the digest\
\ with some initial data\ndigest.update(b\"some data to hash\")\n# Add more data to the digest\ndigest.update(b\"\
some more data\")\n# Finalize the digest as bytes\nresult = digest.finalize()\n```\n\nFor more information\
\ on secure password storage see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html\n\
\nFor more information on the cryptography module see:\n- https://cryptography.io/en/latest/\n"
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
patterns:
- pattern-either:
- pattern: Crypto.Hash.MD4.new(...)
- pattern: Cryptodome.Hash.MD4.new (...)
severity: WARNING
- id: gitlab-python_crypto_rule-hash-md5
languages: [python]
message: "The application was found using an insecure or risky digest or signature algorithm. MD2, MD4,\n\
\ MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions.\n\nThis means\n\
that two different values, when hashed, can lead to the same hash value. If the application is\ntrying\n\
to use these hash methods for storing passwords, then it is recommended to switch to a\npassword hashing\n\
algorithm such as Argon2id or PBKDF2.\n\nNote that the `Crypto` and `Cryptodome` Python packages are\
\ no longer recommended for\nnew applications, instead consider using the [cryptography](https://cryptography.io/)\
\ package.\n\nExample of creating a SHA-384 hash using the `cryptography` package:\n```\nfrom cryptography.hazmat.primitives\
\ import hashes\n# Create a SHA384 digest\ndigest = hashes.Hash(hashes.SHA384())\n# Update the digest\
\ with some initial data\ndigest.update(b\"some data to hash\")\n# Add more data to the digest\ndigest.update(b\"\
some more data\")\n# Finalize the digest as bytes\nresult = digest.finalize()\n```\n\nFor more information\
\ on secure password storage see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html\n\
\nFor more information on the cryptography module see:\n- https://cryptography.io/en/latest/\n"
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
pattern: hashlib.md5(...)
severity: WARNING
- id: gitlab-python_crypto_rule-hash-sha1
languages: [python]
message: "The application was found using an insecure or risky digest or signature algorithm. MD2, MD4,\n\
\ MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions.\n\nThis means\n\
that two different values, when hashed, can lead to the same hash value. If the application is\ntrying\n\
to use these hash methods for storing passwords, then it is recommended to switch to a\npassword hashing\n\
algorithm such as Argon2id or PBKDF2.\n\nNote that the `Crypto` and `Cryptodome` Python packages are\
\ no longer recommended for\nnew applications, instead consider using the [cryptography](https://cryptography.io/)\
\ package.\n\nExample of creating a SHA-384 hash using the `cryptography` package:\n```\nfrom cryptography.hazmat.primitives\
\ import hashes\n# Create a SHA384 digest\ndigest = hashes.Hash(hashes.SHA384())\n# Update the digest\
\ with some initial data\ndigest.update(b\"some data to hash\")\n# Add more data to the digest\ndigest.update(b\"\
some more data\")\n# Finalize the digest as bytes\nresult = digest.finalize()\n```\n\nFor more information\
\ on secure password storage see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html\n\
\nFor more information on the cryptography module see:\n- https://cryptography.io/en/latest/\n"
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
pattern: hashlib.sha1(...)
severity: WARNING
- id: gitlab-python_crypto_rule-hashlib-new-insecure-functions
languages: [python]
message: 'The application was found using an insecure or risky digest or signature algorithm. MD2, MD4,
MD5 and SHA1 hash algorithms have been found to be vulnerable to producing collisions.
This means
that two different values, when hashed, can lead to the same hash value. If the application is
trying
to use these hash methods for storing passwords, then it is recommended to switch to a
password hashing
algorithm such as Argon2id or PBKDF2.
It is strongly recommended that a standard digest algorithm be chosen instead as implementing
a custom algorithm is prone to errors.
Example using `hashlib.sha384()` to create a SHA384 hash:
```
import hashlib
# Create a SHA384 digest
digest = hashlib.sha384()
# Update the digest with some initial data
digest.update(b"some data to hash")
# Add more data to the digest
digest.update(b"some more data")
# Finalize the digest as bytes
digest.digest()
```
'
metadata:
cwe: CWE-327
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of a broken or risky cryptographic algorithm
security-severity: Medium
patterns:
- pattern-either:
- pattern: hashlib.new("=~/[M|m][D|d][4|5]/", ...)
- pattern: hashlib.new(..., name="=~/[M|m][D|d][4|5]/", ...)
- pattern: hashlib.new('sha1')
- pattern: hashlib.new(..., name='SHA1')
- pattern: hashlib.new('sha', string='test')
- pattern: hashlib.new(name='SHA', string='test')
severity: WARNING
- id: gitlab-python_crypto_rule-import-pycrypto
languages: [python]
message: 'The application was detected importing `pycrypto`. This package has been deprecated as it
contains
security vulnerabilities.
To remediate this issue, consider using the [cryptography](https://cryptography.io/)
package instead.
'
metadata:
cwe: CWE-1104
owasp:
- A9:2017-Using Components with Known Vulnerabilities
- A06:2021-Vulnerable and Outdated Components
- A03:2025-Software Supply Chain Failures
category: security
shortDescription: Use of unmaintained third party components
security-severity: Medium
pattern-either:
- pattern: import pycryto
- pattern: import Crypto.Cipher
- pattern: import Crypto.Hash
- pattern: import Crypto.IO
- pattern: import Crypto.Protocol
- pattern: import Crypto.PublicKey
- pattern: import Crypto.Random
- pattern: import Crypto.Signature
- pattern: import Crypto.Util
severity: ERROR
- id: gitlab-python_deserialization_rule-cpickle
languages: [python]
message: "The application was found using `cPickle` which is vulnerable to deserialization attacks.\n\
Deserialization attacks exploit the process of reading serialized data and turning it back\ninto an\
\ object. By constructing malicious objects and serializing them, an adversary may\nattempt to:\n\n\
- Inject code that is executed upon object construction, which occurs during the\ndeserialization process.\n\
- Exploit mass assignment by including fields that are not normally a part of the serialized\ndata but\
\ are read in during deserialization.\n\nConsider safer alternatives such as serializing data in the\
\ JSON format. Ensure any format\nchosen allows\nthe application to specify exactly which object types\
\ are allowed to be deserialized.\n\nTo protect against mass assignment, only allow deserialization\
\ of the specific fields that are\nrequired. If this is not easily done, consider creating an intermediary\
\ type that\ncan be serialized with only the necessary fields exposed.\n\nExample JSON deserializer\
\ using an intermediary type that is validated against a schema to\nensure\nit is safe from mass assignment:\n\
```\nimport jsonschema\n\n# Create a schema to validate our user-supplied input against\n# an intermediary\
\ object\nintermediary_schema = {\n \"type\" : \"object\",\n \"properties\" : {\n \"name\"\
: {\"type\" : \"string\"}\n },\n \"required\": [\"name\"],\n # Protect against random properties\
\ being added to the object\n \"additionalProperties\": False,\n}\n# If a user attempted to add \"\
'is_admin': True\" it would cause a validation error\nintermediary_object = {'name': 'test user'}\n\n\
try:\n # Validate the user supplied intermediary object against our schema\n jsonschema.validate(instance=intermediary_object,\
\ schema=intermediary_schema)\n user_object = {'user':\n {\n # Assign the deserialized\
\ data from intermediary object\n 'name': intermediary_object['name'],\n # Add\
\ in protected data in object definition (or set it from a class constructor)\n 'is_admin':\
\ False,\n }\n }\n # Work with the user_object\nexcept jsonschema.exceptions.ValidationError\
\ as ex:\n # Gracefully handle validation errors\n # ...\n```\n\nFor more details on deserialization\
\ attacks in general, see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html\n"
metadata:
cwe: CWE-502
owasp:
- A8:2017-Insecure Deserialization
- A08:2021-Software and Data Integrity Failures
- A08:2025-Software or Data Integrity Failures
category: security
shortDescription: Deserialization of untrusted data
security-severity: High
pattern: cPickle.$FUNC(...)
severity: WARNING
- id: gitlab-python_deserialization_rule-pickle
languages: [python]
message: "The application was found using `pickle` which is vulnerable to deserialization attacks.\nDeserialization\
\ attacks exploit the process of reading serialized data and turning it back\ninto an object. By constructing\
\ malicious objects and serializing them, an adversary may\nattempt to:\n\n- Inject code that is executed\
\ upon object construction, which occurs during the\ndeserialization process.\n- Exploit mass assignment\
\ by including fields that are not normally a part of the serialized\ndata but are read in during deserialization.\n\
\nConsider safer alternatives such as serializing data in the JSON format. Ensure any format\nchosen\
\ allows the application to specify exactly which object types are allowed to be deserialized.\n\nTo\
\ protect against mass assignment, only allow deserialization of the specific fields that are\nrequired.\
\ If this is not easily done, consider creating an intermediary type that\ncan be serialized with only\
\ the necessary fields exposed.\n\nExample JSON deserializer using an intermediary type that is validated\
\ against a schema to ensure\nit is safe from mass assignment:\n```\nimport jsonschema\n\n# Create a\
\ schema to validate our user-supplied input against\n# an intermediary object\nintermediary_schema\
\ = {\n \"type\" : \"object\",\n \"properties\" : {\n \"name\": {\"type\" : \"string\"\
}\n },\n \"required\": [\"name\"],\n # Protect against random properties being added to the\
\ object\n \"additionalProperties\": False,\n}\n# If a user attempted to add \"'is_admin': True\"\
\ it would cause a validation error\nintermediary_object = {'name': 'test user'}\n\ntry:\n # Validate\
\ the user supplied intermediary object against our schema\n jsonschema.validate(instance=intermediary_object,\
\ schema=intermediary_schema)\n user_object = {'user':\n {\n # Assign the deserialized\
\ data from intermediary object\n 'name': intermediary_object['name'],\n # Add\
\ in protected data in object definition (or set it from a class constructor)\n 'is_admin':\
\ False,\n }\n }\n # Work with the user_object\nexcept jsonschema.exceptions.ValidationError\
\ as ex:\n # Gracefully handle validation errors\n # ...\n```\n\nFor more details on deserialization\
\ attacks in general, see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html\n"
metadata:
cwe: CWE-502
owasp:
- A8:2017-Insecure Deserialization
- A08:2021-Software and Data Integrity Failures
- A08:2025-Software or Data Integrity Failures
category: security
shortDescription: Deserialization of untrusted data
security-severity: High
patterns:
- pattern-either:
- patterns:
- pattern: pickle.$METHOD(...)
- pattern-not: pickle.$METHOD("...")
- patterns:
- pattern: _pickle.$METHOD(...)
- pattern-not: _pickle.$METHOD("...")
- metavariable-regex:
metavariable: $METHOD
regex: (load|loads|Unpickler)
severity: WARNING
- id: gitlab-python_deserialization_rule-shelve
languages: [python]
message: "The application was found using `shelve` which is vulnerable to deserialization attacks as\n\
it calls `pickle` internally.\nDeserialization attacks exploit the process of reading serialized data\
\ and turning it back\ninto an object. By constructing malicious objects and serializing them, an adversary\
\ may\nattempt to:\n\n- Inject code that is executed upon object construction, which occurs during the\n\
deserialization process.\n- Exploit mass assignment by including fields that are not normally a part\
\ of the serialized\ndata but are read in during deserialization.\n\nConsider safer alternatives such\
\ as serializing data in the JSON format. Ensure any format\nchosen allows\nthe application to specify\
\ exactly which object types are allowed to be deserialized.\n\nTo protect against mass assignment,\
\ only allow deserialization of the specific fields that are\nrequired. If this is not easily done,\
\ consider creating an intermediary type that\ncan be serialized with only the necessary fields exposed.\n\
\nExample JSON deserializer using an intermediary type that is validated against a schema to\nensure\n\
it is safe from mass assignment:\n```\nimport jsonschema\n\n# Create a schema to validate our user-supplied\
\ input against\n# an intermediary object\nintermediary_schema = {\n \"type\" : \"object\",\n \
\ \"properties\" : {\n \"name\": {\"type\" : \"string\"}\n },\n \"required\": [\"name\"\
],\n # Protect against random properties being added to the object\n \"additionalProperties\"\
: False,\n}\n# If a user attempted to add \"'is_admin': True\" it would cause a validation error\nintermediary_object\
\ = {'name': 'test user'}\n\ntry:\n # Validate the user supplied intermediary object against our\
\ schema\n jsonschema.validate(instance=intermediary_object, schema=intermediary_schema)\n user_object\
\ = {'user':\n {\n # Assign the deserialized data from intermediary object\n \
\ 'name': intermediary_object['name'],\n # Add in protected data in object definition\
\ (or set it from a class constructor)\n 'is_admin': False,\n }\n }\n # Work\
\ with the user_object\nexcept jsonschema.exceptions.ValidationError as ex:\n # Gracefully handle\
\ validation errors\n # ...\n```\n\nFor more details on deserialization attacks in general, see OWASP's\
\ guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html\n"
metadata:
cwe: CWE-502
owasp:
- A8:2017-Insecure Deserialization
- A08:2021-Software and Data Integrity Failures
- A08:2025-Software or Data Integrity Failures
category: security
shortDescription: Deserialization of untrusted data
security-severity: High
pattern-either:
- pattern: shelve.$FUNC(...)
severity: WARNING
- id: gitlab-python_deserialization_rule-yaml-load
languages: [python]
message: "The application was found using an unsafe version of `yaml` load which is vulnerable to\ndeserialization\
\ attacks. Deserialization attacks exploit the process of reading serialized\ndata and turning it back\n\
into an object. By constructing malicious objects and serializing them, an adversary may\nattempt to:\n\
\n- Inject code that is executed upon object construction, which occurs during the\ndeserialization\
\ process.\n- Exploit mass assignment by including fields that are not normally a part of the serialized\n\
data but are read in during deserialization.\n\nTo remediate this issue, use `safe_load()` or call `yaml.load()`\
\ with the `Loader` argument\nset to\n`yaml.SafeLoader`.\n\nExample loading YAML using `safe_load`:\n\
```\nimport yaml\n\n# Use safe_load to load data into an intermediary object\nintermediary_object =\
\ yaml.safe_load(\"\"\"user:\n name: 'test user'\"\"\"\n)\n# Create our real object, copying over\
\ only the necessary fields\nuser_object = {'user': {\n # Assign the deserialized data from intermediary\
\ object\n 'name': intermediary_object['user']['name'],\n # Add in protected data in object\
\ definition (or set it from a class constructor)\n 'is_admin': False,\n }\n}\n# Work with\
\ user_object\n# ...\n```\n\nFor more details on deserialization attacks in general, see OWASP's guide:\n\
- https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html\n"
patterns:
- pattern-inside: 'import yaml
...
'
- pattern-not-inside: 'from ruamel.yaml import YAML
...
'
- pattern-either:
- pattern: yaml.unsafe_load(...)
- pattern: yaml.$LD(..., Loader=yaml.$LOADER, ...)
- pattern: yaml.$LD($DATA)
- metavariable-regex:
metavariable: $LOADER
regex: (Loader|UnsafeLoader|CLoader|FullLoader)
- metavariable-regex:
metavariable: $LD
regex: (load|load_all)
metadata:
cwe: CWE-502
owasp:
- A8:2017-Insecure Deserialization
- A08:2021-Software and Data Integrity Failures
- A08:2025-Software or Data Integrity Failures
category: security
shortDescription: Deserialization of untrusted data
security-severity: High
severity: ERROR
- id: gitlab-python_django_rule-django-extra-used
languages: [python]
message: "SQL Injection is a critical vulnerability that can lead to data or system compromise. By\ndynamically\
\ generating SQL query strings, user input may be able to influence the logic of\nthe SQL statement.\
\ This could lead to an adversary accessing information they should\nnot have access to, or in some\
\ circumstances, being able to execute OS functionality or code.\n\nReplace all dynamically generated\
\ SQL queries with parameterized queries. In situations where\ndynamic queries must be created, never\
\ use direct user input, but instead use a map or\ndictionary of valid values and resolve them using\
\ a user supplied key.\n\nFor example, some database drivers do not allow parameterized queries for\
\ `>` or `<` comparison\noperators. In these cases, do not use a user supplied `>` or `<` value, but\
\ rather have the\nuser\nsupply a `gt` or `lt` value. The alphabetical values are then used to look\
\ up the `>` and `<`\nvalues to be used in the construction of the dynamic query. The same goes for\
\ other queries\nwhere\ncolumn or table names are required but cannot be parameterized.\n\nThe `QuerySet.extra`\
\ API method will be deprecated as it a source of SQL Injection\nvulnerabilities and other problems.\
\ This method is especially risky as callers\nwill need to do their own escaping of any parameters that\
\ come from user-supplied\ninformation.\n\nTo remediate this issue, do not use `extra` but use other\
\ `QuerySet` methods to achieve\nthe same goals. If for some reason this is not feasible, consider using\
\ the `RawSQL` method\nand making sure that all arguments, including user-supplied ones, are only used\
\ in\n`params`\n\n\nWhile not recommended due to [potential SQL\nInjection](https://docs.djangoproject.com/en/4.2/ref/models/expressions/#raw-sql-expressions),\n\
below is an example using `RawSQL`,\npassing in user-supplied data as a `param` which will escape the\
\ input:\n```\n# If dealing with integer based user input, restrict the values to integers only using\
\ the\n# path configuration: path('<int:user_supplied_id>/someview/', views.some_view,\nname='someview'),\n\
\n# views.py\ndef some_view(request, user_supplied_id):\n # Never use string interpolation in the `sql`\
\ parameter.\n # Never quote the `%s` string format such as `... where id='%s'` as this could lead\
\ to SQL\nInjection.\n # Pass the user supplied data only in the `params` parameter.\n for obj in\
\ DBObject.objects.all().annotate(\n val=RawSQL(sql=\"select id from some_secondary_table where\
\ id=%s\",\nparams=[user_supplied_id])):\n # Work with the results from the query\n # ...\n```\n\
\nFor more information on QuerySet see:\n- https://docs.djangoproject.com/en/4.2/ref/models/querysets/#queryset-api\n\
\nFor more information on SQL Injection see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\n"
patterns:
- pattern: $X.objects. ... .extra(..., $K = $V, ...)
- pattern-not-inside: '$V = [''...'']
...
'
- metavariable-pattern:
metavariable: $V
patterns:
- pattern: $V
- pattern-not: '[..., ''...'', ...]'
- pattern-not: '{..., ''...'': ''...'', ...}'
- pattern-not: '"..."'
- pattern-not: '[..., "..." % "...", ...]'
- pattern-not: '{..., $L: "..." % "...", ...}'
- pattern-not: '{..., $L: "...".format("..."), ...}'
- pattern-not: '[..., "...".format("..."), ...]'
metadata:
cwe: CWE-89
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
category: security
shortDescription: Improper neutralization of special elements used in an SQL Command ('SQL Injection')
security-severity: High
severity: WARNING
- id: gitlab-python_escaping_rule-jinja2-autoescape-false
languages: [python]
message: "The application was found using Jinja2 `Environment` without autoescaping enabled. If using\
\ in\nthe context of HTML this could lead to Cross-Site Scripting (XSS) attacks when rendering with\n\
user-supplied input.\n\nUnfortunately, Jinja2 does not support context-aware escaping, meaning it is\
\ insufficient to\nprotect against\nXSS for the various web contexts. It is important to encode the\
\ data depending on the specific\ncontext\nit\nis used in. There are at least six context types:\n\n\
- Inside HTML tags `<div>context 1</div>`\n- Inside attributes: `<div class=\"context 2\"></div>`\n\
- Inside event attributes `<button onclick=\"context 3\">button</button>`\n- Inside script blocks: `<script>var\
\ x = \"context 4\"</script>`\n- Unsafe element HTML assignment: `element.innerHTML = \"context 5\"\
`\n- Inside URLs: `<iframe src=\"context 6\"></iframe><a href=\"context 6\">link</a>`\n\nScript blocks\
\ alone have multiple ways they need to be encoded. Extra care must be taken if\nuser input\nis ever\
\ output inside of script tags.\n\nUser input that is displayed within the application must be encoded,\
\ sanitized or validated\nto ensure it cannot be treated as HTML or executed as Javascript code. Care\
\ must also be\ntaken\nto not mix server-side templating with client-side templating, as the server-side\
\ templating\nwill\nnot encode things like {{ 7*7 }} which may execute client-side templating features.\n\
\nIt is _NOT_ advised to encode user input prior to inserting into a data store. The data will\nneed\
\ to be\nencoded depending on context of where it is output. It is much safer to force the displaying\n\
system to\nhandle the encoding and not attempt to guess how it should be encoded.\n\nTo handle different\
\ contexts, one approach would be to write custom Jinja2 filters. Below is\nan example\nthat escapes\
\ or encodes links and potentially malicious script, note this does not include\nother contexts\nsuch\
\ as CSS or attributes:\n```\nfrom jinja2 import Environment, select_autoescape, FileSystemLoader\n\
from jinja2 import pass_eval_context\nfrom markupsafe import Markup, escape\n\n@pass_eval_context\n\
def escape_link(eval_ctx, value):\n bad_link = \"#JinjatmplZ\"\n # Block any values that start\
\ with // as that could be used to inject\n # links to third party pages see:\nhttps://en.wikipedia.org/wiki/Wikipedia:Protocol-relative_URL\n\
\ if value.startswith('//'):\n return bad_link\n\n # Only allow relative links\n # if\
\ you want to allow links that start with http or ws replace with below:\n # if not value.startswith('/'):\
\ and not value.startswith('http') and not\nvalue.startswith('ws')\n if not value.startswith('/'):\n\
\ return bad_link\n\n # Alternatively, you could only call escape if autoescape is true\n\
\ # if eval_ctx.autoescape:\n # return escape(value)\n # else\n # return value\n\n\
\ return escape(value)\n\n# Create a replacement table\njs_replacement = str.maketrans({\n \
\ '\"': \"\\\\u0022\",\n '`': \"\\\\u0060\",\n '&': \"\\\\u0026\",\n '\\'':\
\ \"\\\\u0027\",\n '+': \"\\\\u002b\",\n '/': \"\\\\/\",\n '<': \"\\\\u003c\"\
,\n '>': \"\\\\u003e\",\n '\\\\': \"\\\\\\\\\",\n '(': \"\\\\u0028\",\n \
\ ')': \"\\\\u0029\",\n })\n\n@pass_eval_context\ndef escape_js(eval_ctx, value):\n \"\"\"\n\
\ Escape the input for use in <script> context, USE WITH CAUTION\n It is strongly recommended\
\ to _never_ pass user-supplied input to\n the JavaScript context. This may still be unsafe depending\
\ where\n used, it does not consider characters used in regular expressions\n for example.\n\
\ \"\"\"\n\n #if eval_ctx.autoescape:\n # value = escape(value)\n # Escape by default\n\
\ value = escape(value)\n # Translate any potential characters using our translation table\n \
\ return value.translate(js_replacement)\n\n# Create our environment, setting autoescape to use the\
\ default\n# select_autoescape function\nenv = Environment(\n loader=FileSystemLoader(os.getcwd()+\"\
/template\"),\n autoescape=select_autoescape,\n)\n# Add an escape link filter to be used in our template\n\
env.filters[\"escape_link\"] = escape_link\nenv.filters[\"escape_js\"] = escape_js\n# Load our template\
\ file\ntemplate = env.get_template(\"mytemplate.html\")\n# Render with different variables which call\
\ our filters\nprint(template.render(\n html_context=\"<img src=x onerror=alert(1)>\",\n link_context=\"\
/# onclick=alert(1)<script>alert(1)</script>\",\n script_context=\"alert(1);alert`1`\",)\n)\n\n#\
\ Sample template:\n\"\"\"\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <title>My Webpage</title>\n\
</head>\n<body>\n <h1>My Webpage</h1>\n {{ html_context }}\n <a href=\"{{ link_context | escape_link\
\ }}\">link</a>\n <script>{{ script_context | escape_js }}</script>\n</body>\n</html>\n\"\"\"\n```\n\
\nFor more information on autoescape see:\n- https://jinja.palletsprojects.com/en/3.1.x/api/#autoescaping\n\
\nFor more information on XSS see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html\n"
metadata:
cwe: CWE-116
owasp:
- A7:2017-Cross-Site Scripting (XSS)
- A03:2021-Injection
- A05:2025-Injection
category: security
shortDescription: Improper encoding or escaping of output
security-severity: Medium
patterns:
- pattern-inside: 'import jinja2
...
'
- pattern-not: jinja2.Environment(..., autoescape=True, ...)
- pattern-not: jinja2.Environment(..., autoescape=jinja2.select_autoescape(...),...)
- pattern-not: jinja2.Environment(..., autoescape=select_autoescape(...), ...)
- pattern: jinja2.Environment(...)
severity: WARNING
- id: gitlab-python_escaping_rule-use-of-mako-templates
languages: [python]
message: "The application was found using mako templates without `default_filters`\nbeing passed to the\
\ `Template` or `TemplateLookup` constructors. If using \nin the context of HTML, this could lead to\
\ Cross-Site Scripting (XSS) attacks \nwhen rendering with user-supplied input.\n\nUnfortunately, Jinja2\
\ does not support context-aware escaping, meaning it\nis insufficient to protect against XSS for the\
\ various web contexts. It is \nimportant to encode the data depending on the specific context it is\
\ used in. \nThere are at least six context types:\n\n- Inside HTML tags `<div>context 1</div>`\n- Inside\
\ attributes: `<div class=\"context 2\"></div>`\n- Inside event attributes `<button onclick=\"context\
\ 3\">button</button>`\n- Inside script blocks: `<script>var x = \"context 4\"</script>`\n- Unsafe element\
\ HTML assignment: `element.innerHTML = \"context 5\"`\n- Inside URLs: \n`<iframe src=\"context 6\"\
></iframe><a href=\"context 6\">link</a>`\n\nScript blocks alone have multiple ways they need to be\
\ encoded. Extra care\nmust be taken if user input is ever output inside of script tags.\n\nUser input\
\ that is displayed within the application must be encoded,\nsanitized or validated to ensure it cannot\
\ be treated as HTML or executed \nas Javascript code. Care must also be taken to not mix server-side\
\ templating \nwith client-side templating, as the server-side templating will not encode things \n\
like {{ 7*7 }} which may execute client-side templating features.\n\nIt is _NOT_ advised to encode user\
\ input prior to inserting into a data\nstore. The data will need to be encoded depending on context\
\ of where it is output. \nIt is much safer to force the displaying system to handle the encoding and\
\ \nnot attempt to guess how it should be encoded.\n\nTo handle different contexts, one approach would\
\ be to write custom mako\nfilters. Below is an example that escapes or encodes links and \npotentially\
\ malicious script, note this does not include other contexts \nsuch as CSS or attributes:\n```\n# filters.py\
\ module:\n\ndef escape_link(value):\n bad_link = \"#JinjatmplZ\"\n # Block any values that start\
\ with // as that could be used to inject\n # links to third party pages see:\nhttps://en.wikipedia.org/wiki/Wikipedia:Protocol-relative_URL\n\
\ if value.startswith('//'):\n return bad_link\n\n # Only allow relative links\n # if\
\ you want to allow links that start with http or ws replace with below:\n # if not value.startswith('/'):\
\ and not value.startswith('http') and not\nvalue.startswith('ws')\n if not value.startswith('/'):\n\
\ return bad_link\n\n return value\n\n# Create a replacement table\njs_replacement = str.maketrans({\n\
\ '\\0': \"\\\\u0000\",\n '\\t': \"\\\\t\",\n '\\n': \"\\\\n\",\n '\\v': \"\\\\u000b\",\n\
\ '\\f': \"\\\\f`\",\n '\\r': \"\\\\r\",\n '\"': \"\\\\u0022\",\n '`': \"\\\\u0060\",\n\
\ '&': \"\\\\u0026\",\n '\\'': \"\\\\u0027\",\n '+': \"\\\\u002b\",\n '/': \"\\\\/\"\
,\n '<': \"\\\\u003c\",\n '>': \"\\\\u003e\",\n '\\\\': \"\\\\\\\\\",\n '(': \"\\\\u0028\"\
,\n ')': \"\\\\u0029\",\n})\n\ndef escape_js(value):\n # Escape the input for use in <script>\
\ context, USE WITH CAUTION\n # It is strongly recommended to never pass user-supplied input to\n\
\ # the JavaScript context.\n\n # Translate any potential characters using our translation table\n\
\ return value.translate(js_replacement)\n\n#####################################################################\n\
# main module: #\n#####################################################################\n\
from mako.template import Template\n\n# Define our template, note the calls to our custom filters depending\n\
# on context\ntemplate_text = \"\"\"\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <title>My Webpage</title>\n\
</head>\n<body>\n <h1>My Webpage</h1>\n ${html_context}\n <a href=\"${link_context | escape_link}\"\
>link</a>\n <script>${script_context | escape_js}</script>\n</body>\n</html>\n\"\"\"\n\n# Load our\
\ template with default filters and our imported filters for\n# usage in template files\nt = Template(template_text,\n\
\ # By default enable the html filter with 'h'\n default_filters=['h'],\n \
\ # Import our custom filters\n imports=[\"from filters import escape_link, escape_js\"\
])\n\n# Render our template\nprint(t.render(html_context=\"<img src=x onerror=alert(1)>\",\n link_context=\"\
/# onclick=alert(1)<script>alert(1)</script>\",\n script_context=\"alert(1)<img src=x onerror=alert(1)>\"\
,)\n)\n```\n"
metadata:
cwe: CWE-79
category: security
owasp:
- A7:2017-Cross-Site Scripting (XSS)
- A03:2021-Injection
- A05:2025-Injection
shortDescription: Improper neutralization of input during web page generation ('Cross-site Scripting')
security-severity: Medium
patterns:
- pattern-either:
- pattern: mako.template.Template(...)
- pattern: mako.lookup.TemplateLookup(...)
- pattern-not: mako.lookup.TemplateLookup(..., default_filters=["..."])
- pattern-not: mako.template.Template(..., default_filters=["..."])
severity: WARNING
- id: gitlab-python_eval_rule-eval
languages: [python]
message: "The application was found calling the `eval` function with non-literal data. If the variable\
\ contains \nuser-controlled data, either partially or fully, an adversary could compromise the entire\
\ system by \nexecuting arbitrary Python code.\n\nTo remediate this issue, remove all calls to `eval`\
\ and consider alternative methods for executing \nthe necessary business logic. There is almost no\
\ safe method of calling `eval` with user-supplied input.\n\nIf the application only needs to convert\
\ strings into objects, consider using `json.loads`. In \nsome cases `ast.literal_eval` is recommended,\
\ but this should be avoided as it can still suffer \nfrom other issues such as the ability for malicious\
\ code to crash the python interpreter or application.\n\nExample using `json.loads`` to load in arbitrary\
\ data to create data structures:\n```\n# User supplied data as a blob of JSON\nuser_supplied_data =\
\ \"\"\"{\"user\": \"test\", \"metadata\": [1,2,3]}\"\"\"\n# Load the JSON\nuser_object = json.loads(user_supplied_data)\n\
# Manually add protected properties _after_ loading, never before\nuser_object[\"is_admin\"] = False\n\
# Work with the object\n```\n"
patterns:
- pattern: eval($X,...)
- pattern-not: 'eval("...")
'
- pattern-not: 'eval("..." % <... "..." ...>)
'
- pattern-not: 'eval(<... "...".format( "..." ) ...>)
'
- pattern-not-inside: "def eval(...):\n ...\n...\n"
metadata:
cwe: CWE-95
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
category: security
shortDescription: Improper neutralization of directives in dynamically evaluated code ('Eval Injection')
security-severity: High
severity: WARNING
- id: gitlab-python_exec_rule-exec-used
languages: [python]
message: "The application was found calling the `exec` function with a non-literal variable. If the\n\
variable comes from user-supplied input, an adversary could compromise the entire system by\nexecuting\
\ arbitrary python code.\n\nTo remediate this issue, remove all calls to `exec` and consider alternative\
\ methods for\nexecuting the necessary business logic. There is almost no safe method of calling `eval`\
\ \nwith user-supplied input.\n\nIf the application only needs to convert strings into objects, consider\
\ using `json.loads`.\nIn some cases `ast.literal_eval` is recommended, but this should be avoided as\
\ it can still\nsuffer from other issues such as the ability for malicious code to crash the python\n\
interpreter or application.\n\nExample using `json.loads`` to load in arbitrary data to create data\
\ structures:\n```\n# User supplied data as a blob of JSON\nuser_supplied_data = \"\"\"{\"user\": \"\
test\", \"metadata\": [1,2,3]}\"\"\"\n# Load the JSON\nuser_object = json.loads(user_supplied_data)\n\
# Manually add protected properties _after_ loading, never before\nuser_object[\"is_admin\"] = False\n\
# Work with the object\n```\n"
metadata:
cwe: CWE-95
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
category: security
shortDescription: Improper neutralization of directives in dynamically evaluated code ('Eval Injection')
security-severity: High
patterns:
- pattern: exec(...)
- pattern-not: exec("...")
severity: WARNING
- id: gitlab-python_exec_rule-linux-command-wildcard-injection
languages: [python]
message: "Detected use of the wildcard character in a system call that spawns a shell. This subjects the\n\
wildcard to normal shell expansion, which can have unintended consequences if there exist any\nnon-standard\
\ file names. For instance, a file named `-e sh script.sh` could cause issues when \nexpanded by the\
\ shell and executed as a command. Consider using a different method to achieve \nthe same result, such\
\ as using the `glob` module to expand the wildcard before passing it to the\nsystem call. Or if the\
\ command is static, consider hardcoding the command instead of using a\nwildcard.\n\nFor example, the\
\ below code uses the glob module to expand the wildcard and get a list of all \nCSV files in the current\
\ directory. This list is then used in the subprocess.run call, instead of a \nwildcard. This avoids\
\ the potential issues that can arise from using a wildcard in a system call.\n```\nimport glob\nimport\
\ subprocess\n\n# Secure way to process all CSV files\nfiles = glob.glob('*.csv')\nfor file in files:\n\
\ subprocess.run(['process_data', file])\n```\n"
metadata:
category: security
cwe: CWE-155
owasp:
- A1:2017-Injection
- A03:2021-Injection
shortDescription: Improper neutralization of wildcards or matching symbols
security-severity: High
patterns:
- pattern-either:
- pattern: os.$X("$CMD", ...)
- pattern: subprocess.Popen("$CMD", shell=True, ...)
- metavariable-regex:
metavariable: $CMD
regex: (.*?)(\*|\?)
- pattern-not-inside: os.spawnvp(...)
metavariable-regex:
X: (system|popen|popen2|popen3|popen4)
severity: WARNING
- id: gitlab-python_exec_rule-os-path
languages: [python]
message: 'Starting a process with a shell; seems safe, but may be changed in the future, consider
rewriting without shell
'
pattern-either:
- pattern: os.system("...", ...)
- pattern: $OS.popen("...", ...)
- pattern: $OS.popen2("...", ...)
- pattern: $OS.popen3("...", ...)
- pattern: $OS.popen4("...", ...)
- pattern: commands.getoutput("...", ...)
- pattern: commands.getstatusoutput("...", ...)
metadata:
cwe: CWE-78
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
shortDescription: Improper neutralization of special elements used in an OS Command ('OS Command Injection')
security-severity: High
category: security
severity: INFO
- id: gitlab-python_exec_rule-os-popen2
languages: [python]
message: 'Starting a process with a shell; seems safe, but may be changed in the future, consider
rewriting without shell
'
patterns:
- pattern-either:
- pattern: os.system(...)
- pattern: os.popen(...)
- pattern: os.popen2(...)
- pattern: os.popen3(...)
- pattern: os.popen4(...)
- pattern: popen2.popen2(...)
- pattern: popen2.popen3(...)
- pattern: popen2.popen4(...)
- pattern: popen2.Popen3(...)
- pattern: popen2.Popen4(...)
- pattern: commands.getoutput(...)
- pattern: commands.getstatusoutput("")
metadata:
cwe: CWE-78
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
shortDescription: Improper neutralization of special elements used in an OS Command ('OS Command Injection')
security-severity: High
category: security
severity: INFO
- id: gitlab-python_exec_rule-subprocess-call
languages: [python]
message: 'Python possesses many mechanisms to invoke an external executable. However,
doing so may present a security issue if appropriate care is not taken to
sanitize any user provided or variable input. This plugin test is part of a
family of tests built to check for process spawning and warn appropriately.
Specifically, this test looks for the spawning of a subprocess without the
use of a command shell. This type of subprocess invocation is not
vulnerable to shell injection attacks, but care should still be taken to
ensure validity of input.
'
patterns:
- pattern-not: subprocess.$FUNC($ARG, shell=<... True ...>)
- pattern-not: subprocess.$FUNC($ARG, shell=<... 'True' ...>)
- pattern-not: subprocess.$FUNC($ARG, shell=<... "True" ...>)
- pattern-either:
- pattern: 'subprocess.$FUNC($ARG, shell=False)
'
- pattern: 'subprocess.$FUNC($ARG, shell=0)
'
- pattern: 'subprocess.$FUNC($ARG, shell={...})
'
- pattern: 'subprocess.$FUNC($ARG, shell=[...])
'
- pattern: 'subprocess.$FUNC($ARG)
'
metadata:
cwe: CWE-78
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
shortDescription: Improper neutralization of special elements used in an OS Command ('OS Command Injection')
security-severity: High
category: security
severity: WARNING
- id: gitlab-python_exec_rule-subprocess-shell-TRUE
languages: [python]
message: 'subprocess call - check for execution of untrusted input
'
patterns:
- pattern-not: subprocess.$FUNC(..., shell=True, ...)
- pattern: $FOO(..., shell=True, ...)
metadata:
cwe: CWE-78
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
shortDescription: Improper neutralization of special elements used in an OS Command ('OS Command Injection')
security-severity: High
category: security
severity: WARNING
- id: gitlab-python_file-permissions_rule-general-bad-permission
languages: [python]
message: 'The application was found setting file permissions to overly permissive values. Consider
using the following values if the application user is the only process to access
the file:
- 0400 - read only access to the file
- 0200 - write only access to the file
- 0600 - read/write access to the file
Example creating a file with read/write permissions for the application user:
```
# Use octal values to set 0o600 (read/write access to the file) for the current
# user
os.chmod(''somefile.txt'', 0o600)
```
For all other values please see:
https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation
'
metadata:
shortDescription: Incorrect permission assignment for critical resource
cwe: CWE-732
category: security
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
security-severity: Medium
patterns:
- pattern: os.chmod(...,$MASK)
- metavariable-regex:
metavariable: $MASK
regex: (0x..f|0o..[2,3,7]|stat.S_IXGRP|stat.S_IWOTH)
severity: WARNING
- id: gitlab-python_files_rule-tarfile-unsafe-members
languages: [python]
message: "The application may be vulnerable to a path traversal if it extracts untrusted archive files.\n\
This vulnerability is colloquially known as 'Zip Slip'. Archive files may contain folders\nwhich,\n\
when extracted, may write outside of the intended directory. This is exploited by including\npath traversal\
\ characters such as `../../other/directory` to overwrite or place files in system\nor application directories.\n\
\nExtra care must be taken when extracting archive files as there are numerous concerns:\n\n- If possible,\
\ generate unique filenames instead of using the archives file names, as it may be\npossible for users\
\ to overwrite files if the filenames are the same.\n- Validate file paths are written with a prefixed,\
\ known trusted directory.\n- Only process regular files and not symbolic links, as some applications\
\ may attempt to\nread/follow\nthe symbolic link, leading to arbitrary file read / write vulnerabilities.\n\
\nExample of securely processing an archive file:\n```\nimport tarfile\nimport uuid\n# import os\n\n\
tar = tarfile.open('some.tar')\n\n# Max number of allowed files in our archive\nmax_files = 10\n# Max\
\ size for all files in archive\nmax_size = 1024 * 1024 * 10 # 10MB\n# Max size per file in archive\n\
max_file_size = 1024 * 1024 # 1MB\n\n# Validate number of files in archive\nif len(tar.getmembers())\
\ > max_files:\n raise Exception(\"Too many files in archive\")\n\ntotal_size = 0\n# Loop over all\
\ files to see if we exceed max size\n# if so, do not process any of them.\nfor f in tar.getmembers():\n\
\ total_size += f.size\n if total_size >= max_size:\n raise Exception(\"Archive files exceeded\
\ max file size\")\n\n# Iterate over files now that we know the total size is within limits\nfor f in\
\ tar.getmembers():\n # Internally this calls TarInfo.isreg() which ensures\n # the file is a\
\ regular file and not a sym link or directory\n if not f.isfile():\n continue\n\n # Optional,\
\ set a limit on each file size\n if f.size > max_file_size:\n raise Exception(f\"File {f.name}\
\ too large: {f.size}\")\n\n # If original names are required, ensure that only the\n # filename\
\ is used:\n # filename = os.path.basename(f.name)\n\n # More secure, generate a UUID4 value instead\n\
\ filename = uuid.uuid4().hex\n\n # Reset the archive filename to the basename\n # Newer versions\
\ of python (3.11.4+) should use:\n # new_tar = old_tar.replace(name=...new name...)\n f.name\
\ = filename\n\n # Extract the file into a restricted directory, with our\n # own user's attributes,\
\ not the file from the archive\n tar.extract(f, '/opt/app/restricted/', set_attrs=False)\n```\n\n\
For more information on tarfile see:\n- https://docs.python.org/3/library/tarfile.html\n"
metadata:
cwe: CWE-22
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
shortDescription: Improper limitation of a pathname to a restricted directory ('Path Traversal')
security-severity: Medium
category: security
patterns:
- pattern-inside: 'import tarfile
...
'
- pattern-either:
- patterns:
- pattern-inside: '$TAR = tarfile.open(...)
...
'
- pattern-either:
- pattern: $TAR.extractall(...)
- pattern: tarfile.extractall(..., members=$TAR)
- pattern: $TAR.extractall(..., members=[])
- patterns:
- pattern: tarfile.extractall(...)
- pattern: tarfile.extractall(..., members=[])
severity: WARNING
- id: gitlab-python_ftp_rule-ftplib
languages: [python]
message: "The application was found using an FTP library. As FTP does not provide encryption, it is\n\
strongly recommended that any file transfers be done over a more secure transport such as\nSSH.\n\n\
The [paramiko](https://www.paramiko.org/) library can be used with an SCP module to allow\nsecure file\
\ transfers.\n\nExample using `paramiko` SSH client and the `scp` module:\n```\nimport paramiko\nimport\
\ scp\n\n# Create an SSH client\nwith paramiko.SSHClient() as ssh:\n # Load the system host keys\
\ so we can confirm the\n # host we are connecting to is legitimate\n ssh.load_system_host_keys('/home/appuser/.ssh/known_hosts')\n\
\n # Connect to the remote host using our SSH private key\n ssh.connect(hostname='example.org',\n\
\ port=22,\n username='appuser',\n key_filename='/home/appuser/.ssh/private_key')\n\
\n # Create an SCP client with the ssh transport and copy files\n with scp.SCPClient(ssh.get_transport())\
\ as secure_copy:\n secure_copy.get('remote/test.file', 'local/test.file')\n secure_copy.put('local/some.file',\
\ 'remote/some.file')\n```\n\nFor more information on the paramiko module see:\n- https://www.paramiko.org/\n\
\nFor more information on the scp module see:\n- https://github.com/jbardin/scp.py\n"
metadata:
cwe: CWE-319
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Cleartext transmission of sensitive information
security-severity: Medium
pattern: ftplib.$ANYTHING(...)
severity: WARNING
- id: gitlab-python_log_rule-logging-config-insecure-listen
languages: [python]
message: 'The application was found calling the `logging.config.listen`` function, which provides the
ability to listen for
external configuration files over a socket server. This listen socket parses part of the
configuration and calls
`eval` on the supplied configuration file. A local user, or an adversary who is able to
exploit
a Server Side Request Forgery (SSRF) attack to communicate over localhost, would be able to
execute arbitrary
code by passing in a logging config that contains python code.
To remediate the issue, remove the call to `logging.config.listen` method.
For more information on the listen functionality see:
- https://docs.python.org/3/library/logging.config.html#logging.config.listen
'
metadata:
cwe: CWE-94
shortDescription: Improper control of generation of code ('Code Injection')
category: security
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
security-severity: High
patterns:
- pattern: logging.config.listen(...)
severity: WARNING
- id: gitlab-python_random_rule-random
languages: [python]
message: 'Depending on the context, generating weak random numbers may expose cryptographic functions,
which rely on these numbers, to be exploitable. When generating numbers for sensitive values
such as tokens, nonces, and cryptographic keys, it is recommended that the `secrets` module
be used instead.
Example using the secrets module:
```
import secrets
# Generate a secure random 64 byte array
random_bytes = secrets.token_bytes(64)
print(random_bytes)
# Generate a secure random 64 byte array as a hex string
random_bytes_hex = secrets.token_hex(64)
# Generate a secure random 64 byte array base64 encoded for use in URLs
random_string = secrets.token_urlsafe(64)
```
For more information on the `secrets` module see:
- https://docs.python.org/3/library/secrets.html
'
metadata:
cwe: CWE-338
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
category: security
shortDescription: Use of cryptographically weak pseudo-random number generator (PRNG)
security-severity: Low
pattern-either:
- pattern: random.random(...)
- pattern: random.randrange(...)
- pattern: random.randint(...)
- pattern: random.choice(...)
- pattern: random.uniform(...)
- pattern: random.triangular(...)
severity: WARNING
- id: gitlab-python_requests_rule-request-without-timeout
languages: [python]
message: 'The application was found using the `requests` module without configuring a timeout value for
connections. This could lead to uncontrolled resource consumption where the application could
run out of
socket descriptors, effectively causing a Denial of Service (DoS).
To remediate this issue, pass in a `timeout=` argument to each `requests` call.
Example using a timeout for an HTTP GET request:
```
# Issue a GET request to https://example.com with a timeout of 10 seconds
response = requests.get(''https://example.com'', timeout=10)
# Work with the response object
# ...
```
For more information on using the requests module see:
- https://requests.readthedocs.io/en/latest/api/
'
patterns:
- pattern-either:
- patterns:
- pattern: requests.$METHOD(..., timeout=$VAL, ...)
- metavariable-comparison:
comparison: $VAL <= 0
metavariable: $VAL
- patterns:
- pattern: requests.$METHOD(..., timeout=$VAL, ...)
- metavariable-regex:
metavariable: $VAL
regex: (^None)
- patterns:
- pattern-not: requests.$METHOD(..., timeout=$VAL, ...)
- pattern-either:
- pattern: requests.$METHOD(..., ...)
- pattern: requests.$METHOD(...)
- metavariable-regex:
metavariable: $METHOD
regex: (get|put|delete|post|options|head|patch)
metadata:
cwe: CWE-770
category: security
shortDescription: Allocation of resources without limits or throttling
owasp:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration
security-severity: Medium
severity: WARNING
- id: gitlab-python_snmp_rule-insecure-snmp-version
languages: [python]
message: "Pysnmp was detected using versions SNMPv1 or SNMPv2. SNPMv1 and SNMPv2 are insecure\nand should\
\ no longer be used as they do not offer encryption.\n\nIf possible, query SNMP devices using SNMPv3\
\ instead.\n\nExample querying a device using SNMPv3 with SHA-AES:\n```\nfrom pysnmp.hlapi import *\n\
# Create the snpm iterator\niterator = getCmd(\n SnmpEngine(),\n # Configure using SHA AES\n \
\ UsmUserData('usr-sha-aes', 'authkey1', 'privkey1',\n authProtocol=USM_AUTH_HMAC96_SHA,\n\
\ privProtocol=USM_PRIV_CFB128_AES),\n UdpTransportTarget(('demo.snmplabs.com', 161)),\n\
\ ContextData(),\n ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))\n)\n```\n\nFor more\
\ information on using SNMPv3 with `Pysnmp` see:\n- https://pysnmp.readthedocs.io/en/latest/examples/hlapi/v3arch/asyncore/sync/manager/cmdgen/snmp-versions.html#snmpv3-auth-sha-privacy-aes128\n"
metadata:
cwe: CWE-319
category: security
shortDescription: Cleartext transmission of sensitive information
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
security-severity: Medium
pattern-either:
- pattern: pysnmp.hlapi.CommunityData(..., mpModel=0, ...)
- pattern: pysnmp.hlapi.CommunityData(..., mpModel=1, ...)
severity: WARNING
- id: gitlab-python_snmp_rule-snmp-weak-cryptography
languages: [python]
message: "Pysnmp was detected using SNMPv3 without authentication or encryption\nprotections enabled.\n\
\n- Use of `usmNoAuthProtocol` or `usmNoPrivProtocol` indicates that\neither authentication or privacy,\
\ respectively, is not being used. \n- The absence of `authKey` (or `authKey=None`) implies no authentication,\
\ \nwhich is equivalent to using `usmNoAuthProtocol`. \n- The absence of `privKey` (or `privKey=None`)\
\ implies no privacy (encryption), \nwhich is equivalent to using `usmNoPrivProtocol`.\n\nTo enhance\
\ the security of your SNMP communications, it is recommended to use both\nauthentication and privacy\
\ features in SNMPv3:\n\n- Use SHA for Authentication: SHA (Secure Hash Algorithm) is a more secure\
\ option \nfor SNMP message authentication. To use SHA, set the `authProtocol` to \n`usmHMACSHAAuthProtocol`\
\ and provide a strong `authKey`.\n- Use AES for Privacy: AES (Advanced Encryption Standard) is recommended\
\ for \nencrypting SNMP messages. Set the `privProtocol` to `usmAesCfb128Protocol`\nor a similar AES-based\
\ protocol and specify a strong `privKey`.\n\nExample of secure `UsmUserData` configuration:\n``` \n\
\ from pysnmp.hlapi import UsmUserData, usmHMACSHAAuthProtocol, usmAesCfb128Protocol\n \n user_data\
\ = UsmUserData('username','authKey', 'privKey', \n authProtocol=usmHMACSHAAuthProtocol,\n\
\ privProtocol=usmAesCfb128Protocol)\n```\n"
metadata:
cwe: CWE-319
category: security
shortDescription: Cleartext transmission of sensitive information
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
security-severity: Medium
pattern-either:
- pattern-regex: UsmUserData(.*usmNoAuthProtocol.*)
- pattern-regex: UsmUserData(.*usmNoPrivProtocol.*)
- pattern: 'UsmUserData(..., authKey=None, ...)
'
- pattern: 'UsmUserData(..., privKey=None, ...)
'
- pattern: 'UsmUserData(..., authProtocol=(1,3,6,1,6,3,10,1,1,1), ...)
'
- pattern: 'UsmUserData(..., privProtocol=(1,3,6,1,6,3,10,1,2,1), ...)
'
- patterns:
- pattern-not: 'UsmUserData($NAME,$AUTHKEY,"...", ...)
'
- pattern-not: 'UsmUserData(..., privKey=$PRIVKEY, ...)
'
- pattern-not: 'UsmUserData(..., privProtocol=$PRIVPROT, ...)
'
- pattern: 'UsmUserData(...)
'
severity: WARNING
- id: gitlab-python_sql_rule-hardcoded-sql-expression
languages: [python]
message: 'SQL Injection is a critical vulnerability that can lead to data or system compromise. By
dynamically generating SQL query strings, user input may be able to influence the logic of
the SQL statement. This could lead to an adversary accessing information they should
not have access to, or in some circumstances, being able to execute OS functionality or code.
Replace all dynamically generated SQL queries with parameterized queries. In situations where
dynamic queries must be created, never use direct user input, but instead use a map or
dictionary of valid values and resolve them using a user supplied key.
For example, some database drivers do not allow parameterized queries for `>` or `<` comparison
operators. In these cases, do not use a user supplied `>` or `<` value, but rather have the
user
supply a `gt` or `lt` value. The alphabetical values are then used to look up the `>` and `<`
values to be used in the construction of the dynamic query. The same goes for other queries
where
column or table names are required but cannot be parameterized.
Example using `PreparedStatement` queries:
```
import sqlite3
# Create a new database (in memory)
con = sqlite3.connect(":memory:")
# Get a cursor from the connection
cur = con.cursor()
# Create a tuple of the value to be used in the parameterized query
params = (''user-input'',)
# execute the statement, passing in the params for the value
cur.execute("select name from sqlite_master where name = ?", params)
# work with the result
result = cur.fetchall()
```
For more information on SQL Injection see OWASP:
https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
'
metadata:
cwe: CWE-89
owasp:
- A1:2017-Injection
- A03:2021-Injection
- A05:2025-Injection
category: security
shortDescription: Improper neutralization of special elements used in an SQL Command ('SQL Injection')
security-severity: High
mode: taint
pattern-sources:
- patterns:
- pattern-either:
- pattern: '"$QUERY" % ...
'
- pattern: '"$QUERY".format(...)
'
- pattern: 'f"$QUERY{...}..."
'
- pattern: '"$QUERY" + ...
'
- pattern: '$TMP = "$QUERY"
...
$SQL = $TMP + "..." % ...
'
- pattern: "$SQL = \"$QUERY\"\n...\n$SQL += ... \n"
- metavariable-regex:
metavariable: $QUERY
regex: (?i)^(SELECT|INSERT|UPDATE|DELETE)\s
pattern-sinks:
- patterns:
- pattern: $DB.execute(...)
- pattern-not:
pattern-either:
- pattern: $DB.execute("...")
- pattern: $DB.execute("$QUERY" % "...")
- pattern: $DB.execute("$QUERY" + "...")
severity: WARNING
- id: gitlab-python_ssl_rule-req-no-certvalid
languages: [python]
message: 'The application was found using the `requests` module without configuring a timeout value for
connections. The `verify=False` argument has been set, which effectively disables the
validation
of server certificates.
This allows for an adversary who is in between the application and the target host to intercept
potentially sensitive information or transmit malicious data.
To remediate this issue either remove the `verify=False` argument, or set `verify=True`to each
`requests` call.
Example verifying server certificates for an HTTP GET request:
```
# Issue a GET request to https://example.com with a timeout of 10 seconds and verify the
# server certificate explicitly.
response = requests.get(''https://example.com'', timeout=10, verify=True)
# Work with the response object
# ...
```
For more information on using the requests module see:
- https://requests.readthedocs.io/en/latest/api/
'
metadata:
cwe: CWE-295
owasp:
- A3:2017-Sensitive Data Exposure
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
category: security
shortDescription: Improper certificate validation
security-severity: Medium
patterns:
- pattern-either:
- pattern: requests.put(..., verify=False, ...)
- pattern: requests.patch(..., verify=False, ...)
- pattern: requests.delete(..., verify=False, ...)
- pattern: requests.head(..., verify=False, ...)
- pattern: requests.options(..., verify=False, ...)
- pattern: requests.request(..., verify=False, ...)
- pattern: requests.get(..., verify=False, ...)
- pattern: requests.post(..., verify=False, ...)
severity: ERROR
- id: gitlab-python_ssl_rule-ssl-no-version
languages: [python]
message: "The application was found calling `ssl.wrap_socket` without a TLS protocol version specified.\n\
Additionally, `ssl.wrap_socket` has been deprecated since Python 3.7. It is strongly\nrecommended\n\
that newer applications use TLS 1.2 or 1.3 and `SSLContext.wrap_socket`.\n\nTo remediate this issue,\
\ create a new TLS context and pass in `ssl.PROTOCOL_TLS_CLIENT`\nfor clients or `ssl.PROTOCOL_TLS_SERVER`\
\ for servers to the `ssl.SSLContext(...)` `protocol=`\nargument. When converting the socket to a TLS\
\ socket, use the new `SSLContext.wrap_socket`\nmethod instead.\n\n\nExample creating a TLS 1.3 client\
\ socket connection by using a newer version of Python\n(3.11.4) and\nthe SSL module:\n```\nimport ssl\n\
import socket\n\n# Create our initial socket\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM)\
\ as sock:\n # Connect the socket\n sock.connect(('www.example.org', 443))\n\n # Create a new\
\ SSLContext with protocol set to ssl.PROTOCOL_TLS_CLIENT\n # This will auto-select the highest grade\
\ TLS protocol version (1.3)\n context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)\n #\
\ Load our a certificates for server certificate authentication\n context.load_verify_locations('cert.pem')\n\
\ # Create our TLS socket, and validate the server hostname matches\n with context.wrap_socket(sock,\
\ server_hostname=\"www.example.org\") as tls_sock:\n # Send some bytes over the socket (HTTP\
\ request in this case)\\\n data = bytes('GET / HTTP/1.1\\r\\nHost: example.org\\r\\n\\r\\n',\
\ 'utf-8')\n sent_bytes = tls_sock.send(data)\n # Validate number of sent bytes\n \
\ # ...\n # Read the response\n resp = tls_sock.recv()\n # Work with the response\n\
\ # ...\n```\n\nFor more information on the ssl module see:\n- https://docs.python.org/3/library/ssl.html\n"
metadata:
cwe: CWE-326
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
shortDescription: Inadequate encryption strength
security-severity: Medium
category: security
patterns:
- pattern: ssl.wrap_socket()
severity: WARNING
- id: gitlab-python_ssl_rule-ssl-with-bad-version
languages: [python]
message: "The application was found calling an SSL module with SSL or TLS protocols that have known\n\
deficiencies.\nIt is strongly recommended that newer applications use TLS 1.2 or 1.3 and\n`SSLContext.wrap_socket`.\n\
\nIf using the `pyOpenSSL` module, please note that it has been deprecated and the Python\nCryptographic\
\ Authority\nstrongly suggests moving to use the [pyca/cryptography](https://github.com/pyca/cryptography)\n\
module instead.\n\nTo remediate this issue for the `ssl` module, create a new TLS context and pass in\n\
`ssl.PROTOCOL_TLS_CLIENT` for clients or `ssl.PROTOCOL_TLS_SERVER` for servers to the\n`ssl.SSLContext(...)`\
\ `protocol=`\nargument. When converting the socket to a TLS socket, use the new `SSLContext.wrap_socket`\n\
method instead.\n\nExample creating a TLS 1.3 client socket connection by using a newer version of Python\n\
(3.11.4) and\nthe SSL module:\n```\nimport ssl\nimport socket\n\n# Create our initial socket\nwith socket.socket(socket.AF_INET,\
\ socket.SOCK_STREAM) as sock:\n # Connect the socket\n sock.connect(('www.example.org', 443))\n\
\n # Create a new SSLContext with protocol set to ssl.PROTOCOL_TLS_CLIENT\n # This will auto-select\
\ the highest grade TLS protocol version (1.3)\n context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)\n\
\ # Load our a certificates for server certificate authentication\n context.load_verify_locations('cert.pem')\n\
\ # Create our TLS socket, and validate the server hostname matches\n with context.wrap_socket(sock,\
\ server_hostname=\"www.example.org\") as tls_sock:\n # Send some bytes over the socket (HTTP\
\ request in this case)\\\n data = bytes('GET / HTTP/1.1\\r\\nHost: example.org\\r\\n\\r\\n',\
\ 'utf-8')\n sent_bytes = tls_sock.send(data)\n # Validate number of sent bytes\n \
\ # ...\n # Read the response\n resp = tls_sock.recv()\n # Work with the response\n\
\ # ...\n```\n\nFor more information on the ssl module see:\n- https://docs.python.org/3/library/ssl.html\n\
\nFor more information on pyca/cryptography and openssl see:\n- https://cryptography.io/en/latest/openssl/\n"
metadata:
cwe: CWE-326
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
shortDescription: Inadequate Encryption Strength
security-severity: Medium
category: security
patterns:
- pattern-either:
- pattern: ssl.PROTOCOL_SSLv2
- pattern: ssl.PROTOCOL_SSLv3
- pattern: ssl.PROTOCOL_TLSv1
- pattern: ssl.PROTOCOL_TLSv1_1
- pattern: pyOpenSSL.SSL.SSLv2_METHOD
- pattern: pyOpenSSL.SSL.SSLv23_METHOD
- pattern: pyOpenSSL.SSL.SSLv3_METHOD
- pattern: pyOpenSSL.SSL.TLSv1_METHOD
- pattern: pyOpenSSL.SSL.TLSv1_1_METHOD
severity: ERROR
- id: gitlab-python_ssl_rule-unverified-context
languages: [python]
message: "The application was found creating a SSL context using the `_create_unverified_context`.\nThis\
\ effectively disables the validation of server certificates.\n\nThis allows for an adversary who is\
\ in between the application and the target host to intercept\npotentially sensitive information or\
\ transmit malicious data.\n\nTo remediate this issue remove the call to `_create_unverified_context`\
\ and either create a\ndefault\ncontext using `ssl.create_default_context` or create a context with\
\ TLS 1.3.\n\nExample creating a TLS 1.3 client socket connection by using a newer version of Python\n\
(3.11.4) and\nthe SSL module:\n```\nimport ssl\nimport socket\n\n# Create our initial socket\nwith socket.socket(socket.AF_INET,\
\ socket.SOCK_STREAM) as sock:\n # Connect the socket\n sock.connect(('www.example.org', 443))\n\
\n # Create a new SSLContext with protocol set to ssl.PROTOCOL_TLS_CLIENT\n # This will auto-select\
\ the highest grade TLS protocol version (1.3)\n context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)\n\
\ # Load our a certificates for server certificate authentication\n context.load_verify_locations('cert.pem')\n\
\ # Create our TLS socket, and validate the server hostname matches\n with context.wrap_socket(sock,\
\ server_hostname=\"www.example.org\") as tls_sock:\n # Send some bytes over the socket (HTTP\
\ request in this case)\\\n data = bytes('GET / HTTP/1.1\\r\\nHost: example.org\\r\\n\\r\\n',\
\ 'utf-8')\n sent_bytes = tls_sock.send(data)\n # Validate number of sent bytes\n \
\ # ...\n # Read the response\n resp = tls_sock.recv()\n # Work with the response\n\
\ # ...\n```\n\nUnverified SSL context detected. This will permit insecure connections without\
\ `verifyingSSL`\ncertificates. Use `ssl.create_default_context()` instead.\n"
metadata:
cwe: CWE-295
owasp:
- A3:2017-Sensitive Data Exposure
- A07:2021-Identification and Authentication Failures
- A07:2025-Authentication Failures
category: security
shortDescription: Improper certificate validation
security-severity: Medium
pattern: ssl._create_unverified_context(...)
severity: ERROR
- id: gitlab-python_telnet_rule-import-telnib
languages: [python]
message: "The application was found using a telnet library. As telnet does not provide encryption, it\
\ is\nstrongly recommended that communications use a more secure transport such as\nSSH.\n\nThe [paramiko](https://www.paramiko.org/)\
\ library can be used to initiate SSH connections.\n\nExample using `paramiko` SSH client:\n```\nimport\
\ paramiko\nimport scp\n\n# Create an SSH client\nwith paramiko.SSHClient() as ssh:\n # Load the\
\ system host keys so we can confirm the\n # host we are connecting to is legitimate\n ssh.load_system_host_keys('/home/appuser/.ssh/known_hosts')\n\
\n # Connect to the remote host using our SSH private key\n ssh.connect(hostname='example.org',\n\
\ port=22,\n username='appuser',\n key_filename='/home/appuser/.ssh/private_key')\n\
\ # Work with the connection\n```\n\nFor more information on the paramiko module see:\n- https://www.paramiko.org/\n"
metadata:
cwe: CWE-319
category: security
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
- A04:2025-Cryptographic Failures
shortDescription: Cleartext transmission of sensitive information
security-severity: Medium
patterns:
- pattern: import telnetlib
severity: ERROR
- id: gitlab-python_tmpdir_rule-hardcodedtmp
languages: [python]
message: "The application was found creating files in shared system temporary directories\n(`/tmp` or\
\ `/var/tmp`) without using the `tempfile.TemporaryFile` function. Depending\non how the application\
\ uses this temporary file, an attacker may be able to create\nsymlinks that point to other files prior\
\ to the application creating or writing\nto the target file, leading to unintended files being created\
\ or overwritten.\n\nExample using `tempfile.TemporaryFile` to write a file:\n```\nimport tempfile\n\
\n# Open a new temporary file using a context manager\nwith tempfile.TemporaryFile() as fp:\n # Write\
\ some data to the temporary file\n fp.write(b'Some data')\n # Seek back to beginning of file\n\
\ fp.seek(0)\n # Read it\n data = fp.read()\n# File is automatically closed/removed once we\
\ exit the with context\n```\n\nFor more information on alternative tempfile functions see:\n- https://docs.python.org/3/library/tempfile.html\n"
metadata:
cwe: CWE-377
category: security
shortDescription: Insecure temporary file
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
security-severity: Medium
pattern: $CALL("=~/^\/tmp.*/", ...)
severity: WARNING
- id: gitlab-python_tmpdir_rule-mktemp-q
languages: [python]
message: "The application was found creating temporary files with the insecure `mktemp` method.\nDepending\
\ on how the application uses this temporary file, an attacker may be able to create\nsymlinks that\
\ point to other files prior to the application creating or writing\nto the target file, leading to\
\ unintended files being created or overwritten.\n\nTo remediate this issue consider using `tempfile.TemporaryFile`\
\ instead.\n\nExample using `tempfile.TemporaryFile` to write a file:\n```\nimport tempfile\n\n# Open\
\ a new temporary file using a context manager\nwith tempfile.TemporaryFile() as fp:\n # Write some\
\ data to the temporary file\n fp.write(b'Some data')\n # Seek back to beginning of file\n \
\ fp.seek(0)\n # Read it\n data = fp.read()\n# File is automatically closed/removed once we exit\
\ the with context\n```\n\nFor more information on alternative tempfile functions see:\n- https://docs.python.org/3/library/tempfile.html\n"
metadata:
cwe: CWE-377
category: security
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
- A01:2025-Broken Access Control
shortDescription: Insecure temporary file
security-severity: Medium
pattern: tempfile.mktemp(...)
severity: ERROR
- id: gitlab-python_urlopen_rule-urllib-urlopen
languages: [python]
message: 'The application was found passing in a non-literal value to the `urllib` methods which issue
requests. `urllib` supports the `file://` scheme, which may allow an adversary who can control
the URL value to read arbitrary files on the file system.
To remediate this issue either hardcode the URLs being used in urllib or use the `requests`
module instead.
Example using the `requests` module to issue an HTTPS request:
```
import requests
# Issue a GET request to https://example.com with a timeout of 10 seconds
response = requests.get(''https://example.com'', timeout=10)
# Work with the response object
# ...
```
'
patterns:
- pattern-either:
- patterns:
- pattern-either:
- pattern: urllib.$METHOD(...)
- pattern: urllib.request.$METHOD(...)
- pattern-not: urllib.$METHOD("...")
- pattern-not: urllib.request.$METHOD("...")
- pattern-not: urllib.$METHOD("...", ...)
- pattern-not: urllib.request.$METHOD("...", ...)
- metavariable-regex:
metavariable: $METHOD
regex: (urlopen|urlretrieve)
- patterns:
- pattern-either:
- pattern-inside: '$OPENER = urllib.URLopener(...)
...
'
- pattern-inside: '$OPENER = urllib.request.URLopener(...)
...
'
- pattern-inside: '$OPENER = urllib.FancyURLopener(...)
...
'
- pattern-inside: '$OPENER = urllib.request.FancyURLopener(...)
...
'
- pattern-either:
- pattern: $OPENER.open(...)
- pattern: $OPENER.retrieve(...)
- pattern-not: $OPENER.open("...")
- pattern-not: $OPENER.retrieve("...")
metadata:
cwe: CWE-918
owasp:
- A1:2017-Injection
- A10:2021-Server-Side Request Forgery
- A01:2025-Broken Access Control
shortDescription: Server-side request forgery (SSRF)
security-severity: Medium
category: security
severity: WARNING
- id: gitlab-python_xml_rule-celement
languages: [python]
message: "The application was found using the `xml.etree` package for processing XML.\nPythons default\
\ xml processors suffer from various XML parsing vulnerabilities\nand care must be taken when handling\
\ XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities such as\
\ eXternal XML Entity\ninjection maybe exploitable.\n\nThe `etree` package suffers from the following\
\ security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion - May allow an\
\ adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary XML.\n*\
\ Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause the\
\ Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\
library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\
\ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\
# Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\
\ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\
\nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n"
metadata:
cwe: CWE-611
owasp:
- A4:2017-XML External Entities (XXE)
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
category: security
shortDescription: Improper restriction of XML external entity reference
security-severity: Medium
pattern-either:
- patterns:
- pattern: xml.etree.cElementTree.fromstring(...)
- pattern-not: xml.etree.cElementTree.fromstring("...")
- pattern: xml.etree.cElementTree.parse(...)
- pattern: xml.etree.cElementTree.iterparse(...)
- pattern: xml.etree.cElementTree.XMLParser(...)
severity: WARNING
- id: gitlab-python_xml_rule-element
languages: [python]
message: "The application was found using the `xml.etree` package for processing XML.\nPythons default\
\ xml processors suffer from various XML parsing vulnerabilities\nand care must be taken when handling\
\ XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities such as\
\ eXternal XML Entity\ninjection maybe exploitable.\n\nThe `etree` package suffers from the following\
\ security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion - May allow an\
\ adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary XML.\n*\
\ Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause the\
\ Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\
library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\
\ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\
# Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\
\ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\
\nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n"
metadata:
cwe: CWE-611
owasp:
- A4:2017-XML External Entities (XXE)
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
category: security
shortDescription: Improper restriction of XML external entity reference
security-severity: Medium
pattern-either:
- patterns:
- pattern: xml.etree.ElementTree.fromstring(...)
- pattern-not: xml.etree.ElementTree.fromstring("...")
- pattern: xml.etree.ElementTree.parse(...)
- pattern: xml.etree.ElementTree.iterparse(...)
- pattern: xml.etree.ElementTree.XMLParser(...)
severity: WARNING
- id: gitlab-python_xml_rule-etree
languages: [python]
message: "The application was found using the `lxml.etree` package for processing XML.\nPython's default\
\ XML processors suffer from various XML parsing vulnerabilities\nand care must be taken when handling\
\ XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities such as\
\ eXternal XML Entity\ninjection maybe exploitable.\n\nThe `etree` package suffers from the following\
\ security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion - May allow an\
\ adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary XML.\n*\
\ Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause the\
\ Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\
library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\
\ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\
# Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\
\ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\
\nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n"
metadata:
cwe: CWE-611
owasp:
- A4:2017-XML External Entities (XXE)
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
category: security
shortDescription: Improper restriction of XML external entity reference
security-severity: Medium
pattern-either:
- pattern: lxml.etree.parse(...)
- patterns:
- pattern: lxml.etree.fromstring(...)
- pattern-not: lxml.etree.fromstring("...")
- pattern: lxml.etree.RestrictedElement(...)
- pattern: lxml.etree.GlobalParserTLS(...)
- pattern: lxml.etree.getDefaultParser(...)
- pattern: lxml.etree.check_docinfo(...)
severity: WARNING
- id: gitlab-python_xml_rule-expatbuilder
languages: [python]
message: "The application was found using the `xml.dom.expatbuilder` which calls the `xml.dom.minidom`\n\
package for processing XML. Python's default XML processors suffer from various XML parsing\nvulnerabilities\n\
and care must be taken when handling XML data. Additionally, depending on the\nversion of Python, more\
\ critical vulnerabilities such as eXternal XML Entity\ninjection maybe exploitable.\n\nThe `xml.dom.minidom`\
\ package suffers from the following security risks as of Python 3.7.1:\n* Billion laughs / exponential\
\ entity expansion - May allow an adversary to cause\n a Denial of Service (DoS) against the application\
\ parsing arbitrary XML.\n* Quadratic blowup entity expansion - Similar to above, but requires a larger\
\ input\n to cause the Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\
library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\
\ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\
# Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\
\ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\
\nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n"
metadata:
cwe: CWE-611
owasp:
- A4:2017-XML External Entities (XXE)
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
category: security
shortDescription: Improper restriction of XML external entity reference
security-severity: Medium
pattern-either:
- patterns:
- pattern: xml.dom.expatbuilder.parse(...)
- pattern-not: xml.dom.expatbuilder.parse("...")
- pattern: xml.dom.expatbuilder.parseString(...)
severity: WARNING
- id: gitlab-python_xml_rule-expatreader
languages: [python]
message: "The application was found using the `xml.sax.expatreader` package for processing XML. Python's\n\
default XML processors suffer from various XML parsing vulnerabilities\nand care must be taken when\
\ handling XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities\
\ such as eXternal XML Entity\ninjection maybe exploitable.\n\nThe `xml.sax` package suffers from the\
\ following security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion - May\
\ allow an adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary\
\ XML.\n* Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause\
\ the Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\
library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\
\ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\
# Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\
\ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\
\nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n"
metadata:
cwe: CWE-611
owasp:
- A4:2017-XML External Entities (XXE)
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
category: security
shortDescription: Improper restriction of XML external entity reference
security-severity: Medium
pattern-either:
- pattern: xml.dom.expatreader.parse(...)
- patterns:
- pattern: xml.dom.expatreader.parseString(...)
- pattern-not: xml.dom.expatreader.parseString("...")
- pattern: xml.dom.expatreader.parseString(...)
- pattern: xml.dom.expatreader.create_parser(...)
severity: WARNING
- id: gitlab-python_xml_rule-minidom
languages: [python]
message: "The application was found using the `xml.dom.minidom` package for processing XML. Python's\n\
default XML processors suffer from various XML parsing vulnerabilities\nand care must be taken when\
\ handling XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities\
\ such as eXternal XML Entity\ninjection maybe exploitable.\n\nThe `xml.dom.minidom` package suffers\
\ from the following security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion\
\ - May allow an adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary\
\ XML.\n* Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause\
\ the Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\
library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\
\ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\
# Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\
\ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\
\nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n"
metadata:
cwe: CWE-611
owasp:
- A4:2017-XML External Entities (XXE)
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
category: security
shortDescription: Improper restriction of XML external entity reference
security-severity: Medium
pattern-either:
- patterns:
- pattern: xml.dom.minidom.parseString(...)
- pattern-not: xml.dom.minidom.parseString("...")
- pattern: xml.dom.minidom.parse(...)
severity: WARNING
- id: gitlab-python_xml_rule-pulldom
languages: [python]
message: "The application was found using the `xml.dom.pulldom` package for processing XML. Python's\n\
default XML processors suffer from various XML parsing vulnerabilities\nand care must be taken when\
\ handling XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities\
\ such as eXternal XML Entity\ninjection maybe exploitable.\n\nThe `xml.dom.pulldom` package suffers\
\ from the following security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion\
\ - May allow an adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary\
\ XML.\n* Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause\
\ the Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\
library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\
\ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\
# Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\
\ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\
\nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n"
metadata:
cwe: CWE-611
owasp:
- A4:2017-XML External Entities (XXE)
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
category: security
shortDescription: Improper restriction of XML external entity reference
security-severity: Medium
pattern-either:
- patterns:
- pattern: xml.dom.pulldom.parseString(...)
- pattern-not: xml.dom.pulldom.parseString("...")
- pattern: xml.dom.pulldom.parse(...)
severity: WARNING
- id: gitlab-python_xml_rule-sax
languages: [python]
message: "The application was found using the `xml.sax` package for processing XML.\nPython's default\
\ XML processors suffer from various XML parsing vulnerabilities\nand care must be taken when handling\
\ XML data. Additionally, depending on the\nversion of Python, more critical vulnerabilities such as\
\ eXternal XML Entity\ninjection maybe exploitable.\n\nThe `xml.sax` package suffers from the following\
\ security risks as of Python 3.7.1:\n* Billion laughs / exponential entity expansion - May allow an\
\ adversary to cause\n a Denial of Service (DoS) against the application parsing arbitrary XML.\n*\
\ Quadratic blowup entity expansion - Similar to above, but requires a larger input\n to cause the\
\ Denial of Service.\n\nTo remediate the above issues, consider using the\n[defusedxml](https://pypi.org/project/defusedxml/)\n\
library when processing untrusted XML.\n\nExample parsing an XML document using defusedxml:\n```\nfrom\
\ defusedxml.ElementTree import parse\n\n# Parse the inventory.xml file\net = parse('inventory.xml')\n\
# Get the root element\nroot = et.getroot()\n# Work with the root element\n# ...\n```\n\nFor more information\
\ on the various XML parsers and their vulnerabilities please see:\n- https://docs.python.org/3/library/xml.html#xml-vulnerabilities\n\
\nFor more information on XML security see OWASP's guide:\n- https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python\n"
metadata:
cwe: CWE-611
owasp:
- A4:2017-XML External Entities (XXE)
- A05:2021-Security Misconfiguration
- A02:2025-Security Misconfiguration
category: security
shortDescription: Improper restriction of XML external entity reference
security-severity: Medium
pattern-either:
- pattern: xml.sax.parse(...)
- patterns:
- pattern: xml.sax.parseString(...)
- pattern-not: xml.sax.parseString("...")
- pattern: xml.sax.make_parser(...)
severity: WARNING