diff --git a/assets/semgrep_rules/generated/nonfree/audit.yaml b/assets/semgrep_rules/generated/nonfree/audit.yaml index 0088c2de..02362781 100644 --- a/assets/semgrep_rules/generated/nonfree/audit.yaml +++ b/assets/semgrep_rules/generated/nonfree/audit.yaml @@ -2981,6 +2981,406 @@ rules: version_id: 6xTDg3J url: https://semgrep.dev/playground/r/6xTDg3J/generic.secrets.security.detected-generic-secret.detected-generic-secret origin: community +- id: generic.secrets.security.detected-github-token.detected-github-token + patterns: + - pattern-either: + - pattern: "$VAR = $SECRET\n" + - pattern: "$VAR: $SECRET\n" + - pattern: "$VAR = '$SECRET'\n" + - pattern: "$VAR: '$SECRET'\n" + - pattern: "'$VAR' = '$SECRET'\n" + - pattern: "'$VAR': '$SECRET'\n" + - pattern: '"[hH][tT][tT][pP][sS]?://.*$SECRET.*" + + ' + - metavariable-regex: + metavariable: "$SECRET" + regex: gh[pousr]_[A-Za-z0-9_]{36,251} + - metavariable-analysis: + analyzer: entropy + metavariable: "$SECRET" + languages: + - generic + message: GitHub Token detected + severity: ERROR + metadata: + cwe: + - 'CWE-798: Use of Hard-coded Credentials' + source-rule-url: https://github.blog/changelog/2021-03-04-authentication-token-format-updates/ + category: security + technology: + - secrets + - github + confidence: LOW + owasp: + - A07:2021 - Identification and Authentication Failures + references: + - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures + cwe2022-top25: true + cwe2021-top25: true + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Hard-coded Secrets + source: https://semgrep.dev/r/generic.secrets.security.detected-github-token.detected-github-token + shortlink: https://sg.run/PpOv + semgrep.dev: + rule: + r_id: 11589 + rv_id: 833769 + rule_id: eqUv7b + version_id: o5TBEv9 + url: https://semgrep.dev/playground/r/o5TBEv9/generic.secrets.security.detected-github-token.detected-github-token + origin: community +- id: generic.secrets.security.detected-google-gcm-service-account.detected-google-gcm-service-account + pattern-regex: (("|'|`)?type("|'|`)?\s{0,50}(:|=>|=)\s{0,50}("|'|`)?service_account("|'|`)?,?) + languages: + - regex + message: Google (GCM) Service account detected + severity: ERROR + metadata: + cwe: + - 'CWE-798: Use of Hard-coded Credentials' + source-rule-url: https://github.com/grab/secret-scanner/blob/master/scanner/signatures/pattern.go + category: security + technology: + - secrets + - google-cloud + confidence: LOW + owasp: + - A07:2021 - Identification and Authentication Failures + references: + - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures + cwe2022-top25: true + cwe2021-top25: true + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Hard-coded Secrets + source: https://semgrep.dev/r/generic.secrets.security.detected-google-gcm-service-account.detected-google-gcm-service-account + shortlink: https://sg.run/6nXj + semgrep.dev: + rule: + r_id: 9059 + rv_id: 833772 + rule_id: NbUkL8 + version_id: 2KT7xeR + url: https://semgrep.dev/playground/r/2KT7xeR/generic.secrets.security.detected-google-gcm-service-account.detected-google-gcm-service-account + origin: community +- id: generic.secrets.security.detected-google-oauth-access-token.detected-google-oauth-access-token + pattern-regex: ya29\.[0-9A-Za-z\-_]+ + languages: + - regex + message: Google OAuth Access Token detected + severity: ERROR + metadata: + cwe: + - 'CWE-798: Use of Hard-coded Credentials' + source-rule-url: https://github.com/dxa4481/truffleHogRegexes/blob/master/truffleHogRegexes/regexes.json + category: security + technology: + - secrets + - google + confidence: LOW + owasp: + - A07:2021 - Identification and Authentication Failures + references: + - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures + cwe2022-top25: true + cwe2021-top25: true + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Hard-coded Secrets + source: https://semgrep.dev/r/generic.secrets.security.detected-google-oauth-access-token.detected-google-oauth-access-token + shortlink: https://sg.run/ox2n + semgrep.dev: + rule: + r_id: 9060 + rv_id: 833773 + rule_id: kxUkpo + version_id: X0T5NEk + url: https://semgrep.dev/playground/r/X0T5NEk/generic.secrets.security.detected-google-oauth-access-token.detected-google-oauth-access-token + origin: community +- id: generic.secrets.security.detected-heroku-api-key.detected-heroku-api-key + pattern-regex: "[hH][eE][rR][oO][kK][uU].*[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}" + languages: + - regex + message: Heroku API Key detected + severity: ERROR + metadata: + cwe: + - 'CWE-798: Use of Hard-coded Credentials' + source-rule-url: https://github.com/dxa4481/truffleHogRegexes/blob/master/truffleHogRegexes/regexes.json + category: security + technology: + - secrets + - heroku + confidence: LOW + owasp: + - A07:2021 - Identification and Authentication Failures + references: + - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures + cwe2022-top25: true + cwe2021-top25: true + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Hard-coded Secrets + source: https://semgrep.dev/r/generic.secrets.security.detected-heroku-api-key.detected-heroku-api-key + shortlink: https://sg.run/pxXR + semgrep.dev: + rule: + r_id: 9062 + rv_id: 833775 + rule_id: x8UnOB + version_id: 1QTPLBk + url: https://semgrep.dev/playground/r/1QTPLBk/generic.secrets.security.detected-heroku-api-key.detected-heroku-api-key + origin: community +- id: generic.secrets.security.detected-hockeyapp.detected-hockeyapp + pattern-regex: (?i)hockey.{0,50}(\\\"|'|`)?[0-9a-f]{32}(\\\"|'|`)? + languages: + - regex + message: HockeyApp detected + severity: ERROR + metadata: + cwe: + - 'CWE-798: Use of Hard-coded Credentials' + source-rule-url: https://github.com/grab/secret-scanner/blob/master/scanner/signatures/pattern.go + category: security + technology: + - secrets + - hockeyapp + confidence: LOW + owasp: + - A07:2021 - Identification and Authentication Failures + references: + - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures + cwe2022-top25: true + cwe2021-top25: true + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Hard-coded Secrets + source: https://semgrep.dev/r/generic.secrets.security.detected-hockeyapp.detected-hockeyapp + shortlink: https://sg.run/2xoY + semgrep.dev: + rule: + r_id: 9063 + rv_id: 833776 + rule_id: OrU3zo + version_id: 9lTJ02n + url: https://semgrep.dev/playground/r/9lTJ02n/generic.secrets.security.detected-hockeyapp.detected-hockeyapp + origin: community +- id: generic.secrets.security.detected-jwt-token.detected-jwt-token + pattern-regex: eyJ[A-Za-z0-9-_=]{14,}\.[A-Za-z0-9-_=]{13,}\.?[A-Za-z0-9-_.+/=]*? + languages: + - regex + message: JWT token detected + severity: ERROR + metadata: + source-rule-url: https://github.com/Yelp/detect-secrets/blob/master/detect_secrets/plugins/jwt.py + category: security + technology: + - secrets + - jwt + confidence: LOW + references: + - https://semgrep.dev/blog/2020/hardcoded-secrets-unverified-tokens-and-other-common-jwt-mistakes/ + cwe: + - 'CWE-321: Use of Hard-coded Cryptographic Key' + owasp: + - A02:2021 - Cryptographic Failures + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Cryptographic Issues + source: https://semgrep.dev/r/generic.secrets.security.detected-jwt-token.detected-jwt-token + shortlink: https://sg.run/05N5 + semgrep.dev: + rule: + r_id: 12854 + rv_id: 833777 + rule_id: kxU8E8 + version_id: yeTN18Q + url: https://semgrep.dev/playground/r/yeTN18Q/generic.secrets.security.detected-jwt-token.detected-jwt-token + origin: community +- id: generic.secrets.security.detected-kolide-api-key.detected-kolide-api-key + pattern-regex: k2sk_v[0-9]_[0-9a-zA-Z]{24} + languages: + - regex + message: Kolide API Key detected + severity: ERROR + metadata: + cwe: + - 'CWE-798: Use of Hard-coded Credentials' + category: security + technology: + - secrets + - kolide + confidence: LOW + owasp: + - A07:2021 - Identification and Authentication Failures + references: + - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures + cwe2022-top25: true + cwe2021-top25: true + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Hard-coded Secrets + source: https://semgrep.dev/r/generic.secrets.security.detected-kolide-api-key.detected-kolide-api-key + shortlink: https://sg.run/d2YQ + semgrep.dev: + rule: + r_id: 14734 + rv_id: 833778 + rule_id: JDULYW + version_id: rxTDzqX + url: https://semgrep.dev/playground/r/rxTDzqX/generic.secrets.security.detected-kolide-api-key.detected-kolide-api-key + origin: community +- id: generic.secrets.security.detected-mailchimp-api-key.detected-mailchimp-api-key + pattern-regex: "[0-9a-f]{32}-us[0-9]{1,2}" + languages: + - regex + message: MailChimp API Key detected + severity: ERROR + metadata: + source-rule-url: https://github.com/dxa4481/truffleHogRegexes/blob/master/truffleHogRegexes/regexes.json + category: security + cwe: + - 'CWE-798: Use of Hard-coded Credentials' + technology: + - secrets + - mailchimp + confidence: LOW + owasp: + - A07:2021 - Identification and Authentication Failures + references: + - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures + cwe2022-top25: true + cwe2021-top25: true + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Hard-coded Secrets + source: https://semgrep.dev/r/generic.secrets.security.detected-mailchimp-api-key.detected-mailchimp-api-key + shortlink: https://sg.run/XBde + semgrep.dev: + rule: + r_id: 9064 + rv_id: 833779 + rule_id: eqU8QR + version_id: bZTBerP + url: https://semgrep.dev/playground/r/bZTBerP/generic.secrets.security.detected-mailchimp-api-key.detected-mailchimp-api-key + origin: community +- id: generic.secrets.security.detected-mailgun-api-key.detected-mailgun-api-key + pattern-regex: key-[0-9a-zA-Z]{32} + languages: + - regex + message: Mailgun API Key detected + severity: ERROR + metadata: + cwe: + - 'CWE-798: Use of Hard-coded Credentials' + source-rule-url: https://github.com/dxa4481/truffleHogRegexes/blob/master/truffleHogRegexes/regexes.json + category: security + technology: + - secrets + - mailgun + confidence: LOW + owasp: + - A07:2021 - Identification and Authentication Failures + references: + - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures + cwe2022-top25: true + cwe2021-top25: true + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Hard-coded Secrets + source: https://semgrep.dev/r/generic.secrets.security.detected-mailgun-api-key.detected-mailgun-api-key + shortlink: https://sg.run/jRL2 + semgrep.dev: + rule: + r_id: 9065 + rv_id: 833780 + rule_id: v8UneY + version_id: NdTB2LW + url: https://semgrep.dev/playground/r/NdTB2LW/generic.secrets.security.detected-mailgun-api-key.detected-mailgun-api-key + origin: community +- id: generic.secrets.security.detected-npm-registry-auth-token.detected-npm-registry-auth-token + patterns: + - pattern: "$AUTHTOKEN = $VALUE" + - metavariable-regex: + metavariable: "$AUTHTOKEN" + regex: _(authToken|auth|password) + - pattern-not: "$AUTHTOKEN = ${...}" + languages: + - generic + message: NPM registry authentication token detected + paths: + include: + - "*npmrc*" + severity: ERROR + metadata: + cwe: + - 'CWE-798: Use of Hard-coded Credentials' + category: security + technology: + - secrets + - npm + confidence: LOW + owasp: + - A07:2021 - Identification and Authentication Failures + references: + - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures + cwe2022-top25: true + cwe2021-top25: true + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Hard-coded Secrets + source: https://semgrep.dev/r/generic.secrets.security.detected-npm-registry-auth-token.detected-npm-registry-auth-token + shortlink: https://sg.run/Ppg3 + semgrep.dev: + rule: + r_id: 10045 + rv_id: 833781 + rule_id: 5rU4pe + version_id: kbT2lp0 + url: https://semgrep.dev/playground/r/kbT2lp0/generic.secrets.security.detected-npm-registry-auth-token.detected-npm-registry-auth-token + origin: community - id: generic.secrets.security.detected-onfido-live-api-token.detected-onfido-live-api-token pattern-regex: "(?:api_live(?:_[a-zA-Z]{2})?\\.[a-zA-Z0-9-_]{11}\\.[-_a-zA-Z0-9]{32})" languages: @@ -3014,6 +3414,122 @@ rules: version_id: 2KTdZdb url: https://semgrep.dev/playground/r/2KTdZdb/generic.secrets.security.detected-onfido-live-api-token.detected-onfido-live-api-token origin: community +- id: generic.secrets.security.detected-outlook-team.detected-outlook-team + pattern-regex: https://outlook\.office\.com/webhook/[0-9a-f-]{36} + languages: + - regex + message: Outlook Team detected + severity: ERROR + metadata: + cwe: + - 'CWE-798: Use of Hard-coded Credentials' + source-rule-url: https://github.com/grab/secret-scanner/blob/master/scanner/signatures/pattern.go + category: security + technology: + - secrets + - outlook + confidence: LOW + owasp: + - A07:2021 - Identification and Authentication Failures + references: + - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures + cwe2022-top25: true + cwe2021-top25: true + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Hard-coded Secrets + source: https://semgrep.dev/r/generic.secrets.security.detected-outlook-team.detected-outlook-team + shortlink: https://sg.run/1ZwQ + semgrep.dev: + rule: + r_id: 9066 + rv_id: 833782 + rule_id: d8UjXq + version_id: w8TAxrB + url: https://semgrep.dev/playground/r/w8TAxrB/generic.secrets.security.detected-outlook-team.detected-outlook-team + origin: community +- id: generic.secrets.security.detected-paypal-braintree-access-token.detected-paypal-braintree-access-token + pattern-regex: access_token\$production\$[0-9a-z]{16}\$[0-9a-z]{32} + languages: + - regex + message: PayPal Braintree Access Token detected + severity: ERROR + metadata: + cwe: + - 'CWE-798: Use of Hard-coded Credentials' + source-rule-url: https://github.com/dxa4481/truffleHogRegexes/blob/master/truffleHogRegexes/regexes.json + category: security + technology: + - secrets + - paypal + - braintree + confidence: LOW + owasp: + - A07:2021 - Identification and Authentication Failures + references: + - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures + cwe2022-top25: true + cwe2021-top25: true + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Hard-coded Secrets + source: https://semgrep.dev/r/generic.secrets.security.detected-paypal-braintree-access-token.detected-paypal-braintree-access-token + shortlink: https://sg.run/9oBR + semgrep.dev: + rule: + r_id: 9067 + rv_id: 833783 + rule_id: ZqU507 + version_id: xyTNeOg + url: https://semgrep.dev/playground/r/xyTNeOg/generic.secrets.security.detected-paypal-braintree-access-token.detected-paypal-braintree-access-token + origin: community +- id: generic.secrets.security.detected-pgp-private-key-block.detected-pgp-private-key-block + pattern-regex: "-----BEGIN PGP PRIVATE KEY BLOCK-----" + languages: + - regex + message: Something that looks like a PGP private key block is detected. This is + a potential hardcoded secret that could be leaked if this code is committed. Instead, + remove this code block from the commit. + severity: ERROR + metadata: + cwe: + - 'CWE-798: Use of Hard-coded Credentials' + source-rule-url: https://github.com/dxa4481/truffleHogRegexes/blob/master/truffleHogRegexes/regexes.json + category: security + technology: + - secrets + confidence: LOW + owasp: + - A07:2021 - Identification and Authentication Failures + references: + - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures + cwe2022-top25: true + cwe2021-top25: true + subcategory: + - audit + likelihood: LOW + impact: MEDIUM + license: Commons Clause License Condition v1.0[LGPL-2.1-only] + vulnerability_class: + - Hard-coded Secrets + source: https://semgrep.dev/r/generic.secrets.security.detected-pgp-private-key-block.detected-pgp-private-key-block + shortlink: https://sg.run/ydKd + semgrep.dev: + rule: + r_id: 9068 + rv_id: 833784 + rule_id: nJUzXz + version_id: O9TJWz9 + url: https://semgrep.dev/playground/r/O9TJWz9/generic.secrets.security.detected-pgp-private-key-block.detected-pgp-private-key-block + origin: community - id: generic.secrets.security.detected-picatic-api-key.detected-picatic-api-key pattern-regex: sk_live_[0-9a-z]{32} languages: @@ -11028,53 +11544,6 @@ rules: fix-regex: regex: "<%-(.*?)%>" replacement: "<%=\\1%>" -- id: javascript.express.security.audit.xss.ejs.var-in-href.var-in-href - message: 'Detected a template variable used in an anchor tag with the ''href'' attribute. - This allows a malicious actor to input the ''javascript:'' URI and is subject - to cross- site scripting (XSS) attacks. If using a relative URL, start with a - literal forward slash and concatenate the URL, like this: href=''/<%= link %>''. - You may also consider setting the Content Security Policy (CSP) header.' - metadata: - cwe: - - 'CWE-79: Improper Neutralization of Input During Web Page Generation (''Cross-site - Scripting'')' - owasp: - - A07:2017 - Cross-Site Scripting (XSS) - - A03:2021 - Injection - references: - - https://flask.palletsprojects.com/en/1.1.x/security/#cross-site-scripting-xss#:~:text=javascript:%20URI - - https://github.com/pugjs/pug/issues/2952 - category: security - technology: - - express - cwe2022-top25: true - cwe2021-top25: true - subcategory: - - audit - likelihood: LOW - impact: MEDIUM - confidence: LOW - license: Commons Clause License Condition v1.0[LGPL-2.1-only] - vulnerability_class: - - Cross-Site-Scripting (XSS) - source: https://semgrep.dev/r/javascript.express.security.audit.xss.ejs.var-in-href.var-in-href - shortlink: https://sg.run/Zv0p - semgrep.dev: - rule: - r_id: 9279 - rv_id: 834083 - rule_id: PeUZrg - version_id: NdTB2yr - url: https://semgrep.dev/playground/r/NdTB2yr/javascript.express.security.audit.xss.ejs.var-in-href.var-in-href - origin: community - languages: - - regex - severity: WARNING - paths: - include: - - "*.ejs" - - "*.html" - pattern-regex: "]*?[^\\/&=]<%.*?%>.*?>" - id: javascript.express.security.audit.xss.ejs.var-in-script-src.var-in-script-src message: Detected a template variable used as the 'src' in a script tag. Although template variables are HTML escaped, HTML escaping does not always prevent malicious diff --git a/assets/semgrep_rules/generated/oss/audit.yaml b/assets/semgrep_rules/generated/oss/audit.yaml index 92cb9f78..2fa26920 100644 --- a/assets/semgrep_rules/generated/oss/audit.yaml +++ b/assets/semgrep_rules/generated/oss/audit.yaml @@ -1,5 +1,29392 @@ --- rules: +- id: gitlab.bandit.B101 + languages: + - python + message: | + The application was found using `assert` in non-test code. Usually reserved for debug and test + code, the `assert` + function is commonly used to test conditions before continuing execution. However, enclosed + code will be removed + when compiling Python code to optimized byte code. Depending on the assertion and subsequent + logic, this could + lead to undefined behavior of the application or application crashes. + + To remediate this issue, remove the `assert` calls. If necessary, replace them with either `if` + conditions or + `try/except` blocks. + + Example using `try/except` instead of `assert`: + ``` + # Below try/except is equal to the assert statement of: + # assert user.is_authenticated(), "user must be authenticated" + try: + if not user.is_authenticated(): + raise AuthError("user must be authenticated") + except AuthError as e: + # Handle error + # ... + # Return, do not continue processing + return + ``` + metadata: + cwe: CWE-754 + category: security + shortDescription: Improper check for unusual or exceptional conditions + owasp: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + security-severity: Info + primary_identifier: bandit.B101 + secondary_identifiers: + - name: Bandit Test ID B101 + type: bandit_test_id + value: B101 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B101 + shortlink: https://sg.run/yzWA + semgrep.dev: + rule: + r_id: 11524 + rv_id: 920076 + rule_id: KxU4lp + version_id: rxTjvjK + url: https://semgrep.dev/playground/r/rxTjvjK/gitlab.bandit.B101 + origin: community + subcategory: + - audit + patterns: + - pattern: assert(...) + - pattern-not-inside: | + import pytest + ... + - pattern-not-inside: | + import unittest + ... + severity: INFO +- id: gitlab.bandit.B102 + languages: + - python + message: "The application was found calling the `exec` function with a non-literal + variable. If the\nvariable 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\ninterpreter 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-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + category: security + shortDescription: Improper neutralization of special elements used in an OS command + ('OS Command Injection') + security-severity: High + primary_identifier: bandit.B102 + secondary_identifiers: + - name: Bandit Test ID B102 + type: bandit_test_id + value: B102 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B102 + shortlink: https://sg.run/rAJJ + semgrep.dev: + rule: + r_id: 11525 + rv_id: 920109 + rule_id: qNUoNN + version_id: YDTYbvj + url: https://semgrep.dev/playground/r/YDTYbvj/gitlab.bandit.B102 + origin: community + subcategory: + - audit + patterns: + - pattern: exec(...) + - pattern-not: exec("...") + severity: WARNING +- id: gitlab.bandit.B103 + 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 + security-severity: Medium + primary_identifier: bandit.B103 + secondary_identifiers: + - name: Bandit Test ID B103 + type: bandit_test_id + value: B103 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B103 + shortlink: https://sg.run/bDNv + semgrep.dev: + rule: + r_id: 11526 + rv_id: 920118 + rule_id: lBUd5P + version_id: 0bTp31b + url: https://semgrep.dev/playground/r/0bTp31b/gitlab.bandit.B103 + origin: community + subcategory: + - audit + 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.bandit.B104 + 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: + cwe: CWE-200 + category: security + owasp: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + shortDescription: Exposure of sensitive information to an unauthorized actor + security-severity: Low + primary_identifier: bandit.B104 + secondary_identifiers: + - name: Bandit Test ID B104 + type: bandit_test_id + value: B104 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B104 + shortlink: https://sg.run/NrBN + semgrep.dev: + rule: + r_id: 11527 + rv_id: 920077 + rule_id: YGUroX + version_id: bZTLoLd + url: https://semgrep.dev/playground/r/bZTLoLd/gitlab.bandit.B104 + origin: community + subcategory: + - audit + severity: INFO +- id: gitlab.bandit.B108 + languages: + - python + message: | + The application was found creating files in shared system temporary directories + (`/tmp` or `/var/tmp`) without using the `tempfile.TemporaryFile` function. Depending + on how the application uses this temporary file, an attacker may be able to create + symlinks that point to other files prior to the application creating or writing + to the target file, leading to unintended files being created or overwritten. + + Example using `tempfile.TemporaryFile` to write a file: + ``` + import tempfile + + # Open a new temporary file using a context manager + with tempfile.TemporaryFile() as fp: + # Write some data to the temporary file + fp.write(b'Some data') + # Seek back to beginning of file + fp.seek(0) + # Read it + data = fp.read() + # File is automatically closed/removed once we exit the with context + ``` + + For more information on alternative tempfile functions see: + - https://docs.python.org/3/library/tempfile.html + metadata: + cwe: CWE-377 + category: security + shortDescription: Insecure temporary file + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + primary_identifier: bandit.B108 + secondary_identifiers: + - name: Bandit Test ID B108 + type: bandit_test_id + value: B108 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B108 + shortlink: https://sg.run/QRL4 + semgrep.dev: + rule: + r_id: 39386 + rv_id: 920134 + rule_id: 0oU6oJ + version_id: bZTLo1N + url: https://semgrep.dev/playground/r/bZTLo1N/gitlab.bandit.B108 + origin: community + subcategory: + - audit + pattern: $CALL("=~/^\/tmp.*/", ...) + severity: WARNING +- id: gitlab.bandit.B108-1 + pattern: open("=~/^\/tmp.*/", ...) + message: 'Detected hardcoded temp directory. Consider using ''tempfile.TemporaryFile'' + instead. + + ' + metadata: + cwe: 'CWE-377: Insecure Temporary File' + license: MIT + source: https://semgrep.dev/r/gitlab.bandit.B108-1 + shortlink: https://sg.run/O81B + semgrep.dev: + rule: + r_id: 11875 + rv_id: 13242 + rule_id: 6JU6qd + version_id: l4TzRP + url: https://semgrep.dev/playground/r/l4TzRP/gitlab.bandit.B108-1 + origin: community + category: security + subcategory: + - audit + severity: WARNING + languages: + - python +- id: gitlab.bandit.B113 + 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-400 + category: security + shortDescription: Uncontrolled resource consumption + owasp: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + security-severity: Medium + primary_identifier: bandit.B113 + secondary_identifiers: + - name: Bandit Test ID B113 + type: bandit_test_id + value: B113 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B113 + shortlink: https://sg.run/PoEq + semgrep.dev: + rule: + r_id: 47601 + rv_id: 920124 + rule_id: OrULKb + version_id: o5TK1Z7 + url: https://semgrep.dev/playground/r/o5TK1Z7/gitlab.bandit.B113 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.bandit.B201 + languages: + - python + message: | + The Flask application is running with `debug=True` configured. By enabling this option, certain + exceptions or errors could cause sensitive information to be leaked in HTTP responses. + + Additionally, it is not recommended to run a Flask application using `Flask.run(...)` in + production. Instead, a WSGI server such as + [gunicorn](https://flask.palletsprojects.com/en/2.3.x/deploying/gunicorn/) + or [waitress](https://flask.palletsprojects.com/en/2.3.x/deploying/waitress/) be used instead. + + For more information on deployment options for Flask applications see: + - https://flask.palletsprojects.com/en/2.3.x/deploying/ + metadata: + cwe: CWE-489 + category: security + owasp: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + shortDescription: Active debug code + security-severity: Medium + primary_identifier: bandit.B201 + secondary_identifiers: + - name: Bandit Test ID B201 + type: bandit_test_id + value: B201 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B201 + shortlink: https://sg.run/eK4b + semgrep.dev: + rule: + r_id: 11876 + rv_id: 920120 + rule_id: oqUrz7 + version_id: qkTpw47 + url: https://semgrep.dev/playground/r/qkTpw47/gitlab.bandit.B201 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + import flask + ... + - pattern: "$APP.run(..., debug=True, ...)" + severity: WARNING +- id: gitlab.bandit.B202 + languages: + - python + message: | + The application may be vulnerable to a path traversal if it extracts untrusted archive files. + This vulnerability is colloquially known as 'Zip Slip'. Archive files may contain folders + which, + when extracted, may write outside of the intended directory. This is exploited by including + path traversal characters such as `../../other/directory` to overwrite or place files in system + or application directories. + + Extra care must be taken when extracting archive files as there are numerous concerns: + + - If possible, generate unique filenames instead of using the archives file names, as it may be + possible for users to overwrite files if the filenames are the same. + - Validate file paths are written with a prefixed, known trusted directory. + - Only process regular files and not symbolic links, as some applications may attempt to + read/follow + the symbolic link, leading to arbitrary file read / write vulnerabilities. + + Example of securely processing an archive file: + ``` + import tarfile + import uuid + # import os + + tar = tarfile.open('some.tar') + + # Max number of allowed files in our archive + max_files = 10 + # Max size for all files in archive + max_size = 1024 * 1024 * 10 # 10MB + # Max size per file in archive + max_file_size = 1024 * 1024 # 1MB + + # Validate number of files in archive + if len(tar.getmembers()) > max_files: + raise Exception("Too many files in archive") + + total_size = 0 + # Loop over all files to see if we exceed max size + # if so, do not process any of them. + for f in tar.getmembers(): + total_size += f.size + if total_size >= max_size: + raise Exception("Archive files exceeded max file size") + + # Iterate over files now that we know the total size is within limits + for f in tar.getmembers(): + # Internally this calls TarInfo.isreg() which ensures + # the file is a regular file and not a sym link or directory + if not f.isfile(): + continue + + # Optional, set a limit on each file size + if f.size > max_file_size: + raise Exception(f"File {f.name} too large: {f.size}") + + # If original names are required, ensure that only the + # filename is used: + # filename = os.path.basename(f.name) + + # More secure, generate a UUID4 value instead + filename = uuid.uuid4().hex + + # Reset the archive filename to the basename + # Newer versions of python (3.11.4+) should use: + # new_tar = old_tar.replace(name=...new name...) + f.name = filename + + # Extract the file into a restricted directory, with our + # own user's attributes, not the file from the archive + tar.extract(f, '/opt/app/restricted/', set_attrs=False) + ``` + + For more information on tarfile see: + - https://docs.python.org/3/library/tarfile.html + metadata: + cwe: CWE-22 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + shortDescription: Improper limitation of a pathname to a restricted directory + ('Path Traversal') + security-severity: Medium + category: security + primary_identifier: bandit.B202 + secondary_identifiers: + - name: Bandit Test ID B202 + type: bandit_test_id + value: B202 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B202 + shortlink: https://sg.run/J0EQ + semgrep.dev: + rule: + r_id: 47602 + rv_id: 920119 + rule_id: eqUPXn + version_id: K3TwLJL + url: https://semgrep.dev/playground/r/K3TwLJL/gitlab.bandit.B202 + origin: community + subcategory: + - audit + 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.bandit.B301-1 + languages: + - python + message: | + The application was found using `pickle` which is vulnerable to deserialization attacks. + Deserialization attacks exploit the process of reading serialized data and turning it back + into an object. By constructing malicious objects and serializing them, an adversary may + attempt to: + + - Inject code that is executed upon object construction, which occurs during the + deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized + data but are read in during deserialization. + + Consider safer alternatives such as serializing data in the JSON format. Ensure any format + chosen allows the application to specify exactly which object types are allowed to be deserialized. + + To protect against mass assignment, only allow deserialization of the specific fields that are + required. If this is not easily done, consider creating an intermediary type that + can be serialized with only the necessary fields exposed. + + Example JSON deserializer using an intermediary type that is validated against a schema to ensure + it is safe from mass assignment: + ``` + import jsonschema + + # Create a schema to validate our user-supplied input against + # an intermediary object + intermediary_schema = { + "type" : "object", + "properties" : { + "name": {"type" : "string"} + }, + "required": ["name"], + # Protect against random properties being added to the object + "additionalProperties": False, + } + # If a user attempted to add "'is_admin': True" it would cause a validation error + intermediary_object = {'name': 'test user'} + + try: + # Validate the user supplied intermediary object against our schema + jsonschema.validate(instance=intermediary_object, schema=intermediary_schema) + user_object = {'user': + { + # Assign the deserialized data from intermediary object + 'name': intermediary_object['name'], + # Add in protected data in object definition (or set it from a class constructor) + 'is_admin': False, + } + } + # Work with the user_object + except jsonschema.exceptions.ValidationError as ex: + # Gracefully handle validation errors + # ... + ``` + + For more details on deserialization attacks in general, see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + metadata: + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + category: security + shortDescription: Deserialization of untrusted data + security-severity: High + primary_identifier: bandit.B301-1 + secondary_identifiers: + - name: Bandit Test ID B301 + type: bandit_test_id + value: B301 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B301-1 + shortlink: https://sg.run/v20A + semgrep.dev: + rule: + r_id: 11877 + rv_id: 920102 + rule_id: zdU1y5 + version_id: BjTKL1v + url: https://semgrep.dev/playground/r/BjTKL1v/gitlab.bandit.B301-1 + origin: community + subcategory: + - audit + 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.bandit.B301-2 + languages: + - python + message: | + The application was found using `cPickle` which is vulnerable to deserialization attacks. + Deserialization attacks exploit the process of reading serialized data and turning it back + into an object. By constructing malicious objects and serializing them, an adversary may + attempt to: + + - Inject code that is executed upon object construction, which occurs during the + deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized + data but are read in during deserialization. + + Consider safer alternatives such as serializing data in the JSON format. Ensure any format + chosen allows + the application to specify exactly which object types are allowed to be deserialized. + + To protect against mass assignment, only allow deserialization of the specific fields that are + required. If this is not easily done, consider creating an intermediary type that + can be serialized with only the necessary fields exposed. + + Example JSON deserializer using an intermediary type that is validated against a schema to + ensure + it is safe from mass assignment: + ``` + import jsonschema + + # Create a schema to validate our user-supplied input against + # an intermediary object + intermediary_schema = { + "type" : "object", + "properties" : { + "name": {"type" : "string"} + }, + "required": ["name"], + # Protect against random properties being added to the object + "additionalProperties": False, + } + # If a user attempted to add "'is_admin': True" it would cause a validation error + intermediary_object = {'name': 'test user'} + + try: + # Validate the user supplied intermediary object against our schema + jsonschema.validate(instance=intermediary_object, schema=intermediary_schema) + user_object = {'user': + { + # Assign the deserialized data from intermediary object + 'name': intermediary_object['name'], + # Add in protected data in object definition (or set it from a class constructor) + 'is_admin': False, + } + } + # Work with the user_object + except jsonschema.exceptions.ValidationError as ex: + # Gracefully handle validation errors + # ... + ``` + + For more details on deserialization attacks in general, see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + metadata: + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + category: security + shortDescription: Deserialization of untrusted data + security-severity: High + primary_identifier: bandit.B301-2 + secondary_identifiers: + - name: Bandit Test ID B301 + type: bandit_test_id + value: B301 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B301-2 + shortlink: https://sg.run/d0gZ + semgrep.dev: + rule: + r_id: 11878 + rv_id: 920099 + rule_id: pKUwGl + version_id: GxToXPq + url: https://semgrep.dev/playground/r/GxToXPq/gitlab.bandit.B301-2 + origin: community + subcategory: + - audit + pattern: cPickle.$FUNC(...) + severity: WARNING +- id: gitlab.bandit.B301-3 + languages: + - python + message: | + The application was found using `dill` which is vulnerable to deserialization attacks. + Deserialization attacks exploit the process of reading serialized data and turning it back + into an object. By constructing malicious objects and serializing them, an adversary may + attempt to: + + - Inject code that is executed upon object construction, which occurs during the + deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized + data but are read in during deserialization. + + Consider safer alternatives such as serializing data in the JSON format. Ensure any format + chosen allows + the application to specify exactly which object types are allowed to be deserialized. + + To protect against mass assignment, only allow deserialization of the specific fields that are + required. If this is not easily done, consider creating an intermediary type that + can be serialized with only the necessary fields exposed. + + Example JSON deserializer using an intermediary type that is validated against a schema to + ensure + it is safe from mass assignment: + ``` + import jsonschema + + # Create a schema to validate our user-supplied input against + # an intermediary object + intermediary_schema = { + "type" : "object", + "properties" : { + "name": {"type" : "string"} + }, + "required": ["name"], + # Protect against random properties being added to the object + "additionalProperties": False, + } + # If a user attempted to add "'is_admin': True" it would cause a validation error + intermediary_object = {'name': 'test user'} + + try: + # Validate the user supplied intermediary object against our schema + jsonschema.validate(instance=intermediary_object, schema=intermediary_schema) + user_object = {'user': + { + # Assign the deserialized data from intermediary object + 'name': intermediary_object['name'], + # Add in protected data in object definition (or set it from a class constructor) + 'is_admin': False, + } + } + # Work with the user_object + except jsonschema.exceptions.ValidationError as ex: + # Gracefully handle validation errors + # ... + ``` + + For more details on deserialization attacks in general, see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + metadata: + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + category: security + shortDescription: Deserialization of untrusted data + security-severity: High + primary_identifier: bandit.B301-3 + secondary_identifiers: + - name: Bandit Test ID B301 + type: bandit_test_id + value: B301 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B301-3 + shortlink: https://sg.run/dgZ0 + semgrep.dev: + rule: + r_id: 11534 + rv_id: 920100 + rule_id: j2UqZR + version_id: RGT2xAE + url: https://semgrep.dev/playground/r/RGT2xAE/gitlab.bandit.B301-3 + origin: community + subcategory: + - audit + pattern-either: + - pattern: dill.$FUNC(...) + severity: WARNING +- id: gitlab.bandit.B301-4 + languages: + - python + message: | + The application was found using `shelve` which is vulnerable to deserialization attacks as + it calls `pickle` internally. + Deserialization attacks exploit the process of reading serialized data and turning it back + into an object. By constructing malicious objects and serializing them, an adversary may + attempt to: + + - Inject code that is executed upon object construction, which occurs during the + deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized + data but are read in during deserialization. + + Consider safer alternatives such as serializing data in the JSON format. Ensure any format + chosen allows + the application to specify exactly which object types are allowed to be deserialized. + + To protect against mass assignment, only allow deserialization of the specific fields that are + required. If this is not easily done, consider creating an intermediary type that + can be serialized with only the necessary fields exposed. + + Example JSON deserializer using an intermediary type that is validated against a schema to + ensure + it is safe from mass assignment: + ``` + import jsonschema + + # Create a schema to validate our user-supplied input against + # an intermediary object + intermediary_schema = { + "type" : "object", + "properties" : { + "name": {"type" : "string"} + }, + "required": ["name"], + # Protect against random properties being added to the object + "additionalProperties": False, + } + # If a user attempted to add "'is_admin': True" it would cause a validation error + intermediary_object = {'name': 'test user'} + + try: + # Validate the user supplied intermediary object against our schema + jsonschema.validate(instance=intermediary_object, schema=intermediary_schema) + user_object = {'user': + { + # Assign the deserialized data from intermediary object + 'name': intermediary_object['name'], + # Add in protected data in object definition (or set it from a class constructor) + 'is_admin': False, + } + } + # Work with the user_object + except jsonschema.exceptions.ValidationError as ex: + # Gracefully handle validation errors + # ... + ``` + + For more details on deserialization attacks in general, see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + metadata: + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + category: security + shortDescription: Deserialization of untrusted data + security-severity: High + primary_identifier: bandit.B301-4 + secondary_identifiers: + - name: Bandit Test ID B301 + type: bandit_test_id + value: B301 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B301-4 + shortlink: https://sg.run/Zer4 + semgrep.dev: + rule: + r_id: 11535 + rv_id: 920103 + rule_id: 10UZxd + version_id: DkT2yNv + url: https://semgrep.dev/playground/r/DkT2yNv/gitlab.bandit.B301-4 + origin: community + subcategory: + - audit + pattern-either: + - pattern: shelve.$FUNC(...) + severity: WARNING +- id: gitlab.bandit.B302 + languages: + - python + message: | + The application was found using `dill` which is vulnerable to deserialization attacks. + Deserialization attacks exploit the process of reading serialized data and turning it back + into an object. By constructing malicious objects and serializing them, an adversary may + attempt to: + + - Inject code that is executed upon object construction, which occurs during the + deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized + data but are read in during deserialization. + + Consider safer alternatives such as serializing data in the JSON format. Ensure any format + chosen allows + the application to specify exactly which object types are allowed to be deserialized. + + To protect against mass assignment, only allow deserialization of the specific fields that are + required. If this is not easily done, consider creating an intermediary type that + can be serialized with only the necessary fields exposed. + + Example JSON deserializer using an intermediary type that is validated against a schema to + ensure + it is safe from mass assignment: + ``` + import jsonschema + + # Create a schema to validate our user-supplied input against + # an intermediary object + intermediary_schema = { + "type" : "object", + "properties" : { + "name": {"type" : "string"} + }, + "required": ["name"], + # Protect against random properties being added to the object + "additionalProperties": False, + } + # If a user attempted to add "'is_admin': True" it would cause a validation error + intermediary_object = {'name': 'test user'} + + try: + # Validate the user supplied intermediary object against our schema + jsonschema.validate(instance=intermediary_object, schema=intermediary_schema) + user_object = {'user': + { + # Assign the deserialized data from intermediary object + 'name': intermediary_object['name'], + # Add in protected data in object definition (or set it from a class constructor) + 'is_admin': False, + } + } + # Work with the user_object + except jsonschema.exceptions.ValidationError as ex: + # Gracefully handle validation errors + # ... + ``` + + For more details on deserialization attacks in general, see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + metadata: + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + category: security + shortDescription: Deserialization of untrusted data + security-severity: High + primary_identifier: bandit.B302 + secondary_identifiers: + - name: Bandit Test ID B302 + type: bandit_test_id + value: B302 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B302 + shortlink: https://sg.run/ZkeD + semgrep.dev: + rule: + r_id: 11879 + rv_id: 920101 + rule_id: 2ZUK4W + version_id: A8TNlJ0 + url: https://semgrep.dev/playground/r/A8TNlJ0/gitlab.bandit.B302 + origin: community + subcategory: + - audit + pattern-either: + - pattern: marshal.dump(...) + - pattern: marshal.dumps(...) + - pattern: marshal.load(...) + - pattern: marshal.loads(...) + severity: WARNING +- id: gitlab.bandit.B303-1 + 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. + + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B303-1 + secondary_identifiers: + - name: Bandit Test ID B303 + type: bandit_test_id + value: B303 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B303-1 + shortlink: https://sg.run/nkkX + semgrep.dev: + rule: + r_id: 11880 + rv_id: 920095 + rule_id: X5U77W + version_id: 44TeqZZ + url: https://semgrep.dev/playground/r/44TeqZZ/gitlab.bandit.B303-1 + origin: community + subcategory: + - audit + pattern: hashlib.md5(...) + severity: WARNING +- id: gitlab.bandit.B303-2 + 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. + + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B303-2 + secondary_identifiers: + - name: Bandit Test ID B303 + type: bandit_test_id + value: B303 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B303-2 + shortlink: https://sg.run/EOOw + semgrep.dev: + rule: + r_id: 11881 + rv_id: 920096 + rule_id: j2URRg + version_id: PkTjGQ1 + url: https://semgrep.dev/playground/r/PkTjGQ1/gitlab.bandit.B303-2 + origin: community + subcategory: + - audit + pattern: hashlib.sha1(...) + severity: WARNING +- id: gitlab.bandit.B303-3 + patterns: + - pattern-either: + - pattern: Crypto.Hash.MD2.new(...) + - pattern: Cryptodome.Hash.MD2.new (...) + message: | + Detected MD2 hash algorithm which is considered insecure. This algorithm + has many known vulnerabilities and has been deprecated. Use SHA256 or SHA3 instead. + metadata: + cwe: CWE-327 + shortDescription: Use of a Broken or Risky Cryptographic Algorithm + owasp: A3:2017-Sensitive Data Exposure + primary_identifier: bandit.B303-3 + secondary_identifiers: + - name: Bandit Test ID B303 + type: bandit_test_id + value: B303 + license: MIT + source: https://semgrep.dev/r/gitlab.bandit.B303-3 + shortlink: https://sg.run/nq5r + semgrep.dev: + rule: + r_id: 11536 + rv_id: 73118 + rule_id: 9AUOKZ + version_id: WrTw4p + url: https://semgrep.dev/playground/r/WrTw4p/gitlab.bandit.B303-3 + origin: community + category: security + subcategory: + - audit + severity: WARNING + languages: + - python +- id: gitlab.bandit.B303-4 + patterns: + - pattern-either: + - pattern: Crypto.Hash.MD4.new(...) + - pattern: Cryptodome.Hash.MD4.new (...) + message: | + Detected MD4 hash algorithm which is considered insecure. This algorithm + has many known vulnerabilities and has been deprecated. Use SHA256 or SHA3 instead. + metadata: + cwe: CWE-327 + shortDescription: Use of a Broken or Risky Cryptographic Algorithm + owasp: A3:2017-Sensitive Data Exposure + primary_identifier: bandit.B303-4 + secondary_identifiers: + - name: Bandit Test ID B303 + type: bandit_test_id + value: B303 + license: MIT + source: https://semgrep.dev/r/gitlab.bandit.B303-4 + shortlink: https://sg.run/E5GB + semgrep.dev: + rule: + r_id: 11537 + rv_id: 73119 + rule_id: yyUvLN + version_id: 0bTXP3 + url: https://semgrep.dev/playground/r/0bTXP3/gitlab.bandit.B303-4 + origin: community + category: security + subcategory: + - audit + severity: WARNING + languages: + - python +- id: gitlab.bandit.B303-5 + patterns: + - pattern-either: + - pattern: Crypto.Hash.MD5.new(...) + - pattern: Cryptodome.Hash.MD5.new (...) + message: | + Detected MD5 hash algorithm which is considered insecure. MD5 is not + collision resistant and is therefore not suitable as a cryptographic + signature. Use SHA256 or SHA3 instead. + metadata: + cwe: CWE-327 + shortDescription: Use of a Broken or Risky Cryptographic Algorithm + owasp: A3:2017-Sensitive Data Exposure + primary_identifier: bandit.B303-5 + secondary_identifiers: + - name: Bandit Test ID B303 + type: bandit_test_id + value: B303 + license: MIT + source: https://semgrep.dev/r/gitlab.bandit.B303-5 + shortlink: https://sg.run/70eQ + semgrep.dev: + rule: + r_id: 11538 + rv_id: 73120 + rule_id: r6UkYj + version_id: K3TXWk + url: https://semgrep.dev/playground/r/K3TXWk/gitlab.bandit.B303-5 + origin: community + category: security + subcategory: + - audit + severity: WARNING + languages: + - python +- id: gitlab.bandit.B303-6 + patterns: + - pattern-either: + - pattern: Crypto.Hash.SHA.new(...) + - pattern: Cryptodome.Hash.SHA.new (...) + message: | + Detected SHA1 hash algorithm which is considered insecure. SHA1 is not + collision resistant and is therefore not suitable as a cryptographic + signature. Use SHA256 or SHA3 instead. + metadata: + cwe: CWE-327 + shortDescription: Use of a Broken or Risky Cryptographic Algorithm + owasp: A3:2017-Sensitive Data Exposure + primary_identifier: bandit.B303-6 + secondary_identifiers: + - name: Bandit Test ID B303 + type: bandit_test_id + value: B303 + license: MIT + source: https://semgrep.dev/r/gitlab.bandit.B303-6 + shortlink: https://sg.run/L0KY + semgrep.dev: + rule: + r_id: 11539 + rv_id: 73121 + rule_id: bwUOkX + version_id: qkTy8y + url: https://semgrep.dev/playground/r/qkTy8y/gitlab.bandit.B303-6 + origin: community + category: security + subcategory: + - audit + severity: WARNING + languages: + - python +- id: gitlab.bandit.B303-7 + 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 + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + category: security + primary_identifier: bandit.B303-7 + secondary_identifiers: + - name: Bandit Test ID B303 + type: bandit_test_id + value: B303 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B303-7 + shortlink: https://sg.run/7GGZ + semgrep.dev: + rule: + r_id: 11882 + rv_id: 920091 + rule_id: 10Ueez + version_id: 8KTvlKz + url: https://semgrep.dev/playground/r/8KTvlKz/gitlab.bandit.B303-7 + origin: community + subcategory: + - audit + pattern: cryptography.hazmat.primitives.hashes.MD5(...) + severity: WARNING +- id: gitlab.bandit.B303-8 + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B303-8 + secondary_identifiers: + - name: Bandit Test ID B303 + type: bandit_test_id + value: B303 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B303-8 + shortlink: https://sg.run/L88r + semgrep.dev: + rule: + r_id: 11883 + rv_id: 920092 + rule_id: 9AUkko + version_id: gETkXeJ + url: https://semgrep.dev/playground/r/gETkXeJ/gitlab.bandit.B303-8 + origin: community + subcategory: + - audit + pattern: cryptography.hazmat.primitives.hashes.SHA1(...) + severity: WARNING +- id: gitlab.bandit.B304-1 + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B304-1 + secondary_identifiers: + - name: Bandit Test ID B304 + type: bandit_test_id + value: B304 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B304-1 + shortlink: https://sg.run/8RRy + semgrep.dev: + rule: + r_id: 11884 + rv_id: 920093 + rule_id: yyUyyn + version_id: QkT1NZk + url: https://semgrep.dev/playground/r/QkT1NZk/gitlab.bandit.B304-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: Crypto.Hash.MD2.new(...) + - pattern: Cryptodome.Hash.MD2.new (...) + severity: WARNING +- id: gitlab.bandit.B304-10 + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B304-10 + secondary_identifiers: + - name: Bandit Test ID B304 + type: bandit_test_id + value: B304 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B304-10 + shortlink: https://sg.run/4PPl + semgrep.dev: + rule: + r_id: 11888 + rv_id: 920088 + rule_id: kxU886 + version_id: ExT1Wg2 + url: https://semgrep.dev/playground/r/ExT1Wg2/gitlab.bandit.B304-10 + origin: community + subcategory: + - audit + pattern: cryptography.hazmat.primitives.ciphers.algorithms.ARC4(...) + severity: WARNING +- id: gitlab.bandit.B304-11 + languages: + - python + message: | + The Blowfish encryption algorithm was meant as a drop-in replacement for DES and was created in + 1993. Smaller key sizes may make the ciphertext vulnerable to [birthday + attacks](https://en.wikipedia.org/wiki/Birthday_attack). While no known attacks against + Blowfish + exist, it should never be used to encrypt files over 4GB in size. If possible consider + using ChaCha20Poly1305 or AES-GCM instead of Blowfish. + + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B304-11 + secondary_identifiers: + - name: Bandit Test ID B304 + type: bandit_test_id + value: B304 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B304-11 + shortlink: https://sg.run/P88Y + semgrep.dev: + rule: + r_id: 11889 + rv_id: 920089 + rule_id: wdUGGA + version_id: 7ZTbRre + url: https://semgrep.dev/playground/r/7ZTbRre/gitlab.bandit.B304-11 + origin: community + subcategory: + - audit + pattern: cryptography.hazmat.primitives.ciphers.algorithms.Blowfish(...) + severity: WARNING +- id: gitlab.bandit.B304-12 + languages: + - python + message: | + The IDEA encryption algorithm was meant as a drop-in replacement for DES and was created in + 1991. A number of [vulnerabilities and + exploits](https://en.wikipedia.org/wiki/International_Data_Encryption_Algorithm#Security) have + been identified to work against IDEA and + it is no longer recommended. If possible consider + using ChaCha20Poly1305 or AES-GCM instead of Blowfish. + + 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 + shortDescription: Use of a Broken or Risky Cryptographic Algorithm + security-severity: Medium + category: security + primary_identifier: bandit.B304-12 + secondary_identifiers: + - name: Bandit Test ID B304 + type: bandit_test_id + value: B304 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B304-12 + shortlink: https://sg.run/Jjjw + semgrep.dev: + rule: + r_id: 11890 + rv_id: 920090 + rule_id: x8U22d + version_id: LjTzeXr + url: https://semgrep.dev/playground/r/LjTzeXr/gitlab.bandit.B304-12 + origin: community + subcategory: + - audit + pattern: cryptography.hazmat.primitives.ciphers.algorithms.IDEA(...) + severity: WARNING +- id: gitlab.bandit.B304-2 + 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. + + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B304-2 + secondary_identifiers: + - name: Bandit Test ID B304 + type: bandit_test_id + value: B304 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B304-2 + shortlink: https://sg.run/grrJ + semgrep.dev: + rule: + r_id: 11885 + rv_id: 920094 + rule_id: r6U99k + version_id: 3ZTLwOL + url: https://semgrep.dev/playground/r/3ZTLwOL/gitlab.bandit.B304-2 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: Crypto.Hash.MD4.new(...) + - pattern: Cryptodome.Hash.MD4.new (...) + severity: WARNING +- id: gitlab.bandit.B304-3 + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B304-3 + secondary_identifiers: + - name: Bandit Test ID B304 + type: bandit_test_id + value: B304 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B304-3 + shortlink: https://sg.run/Q444 + semgrep.dev: + rule: + r_id: 11886 + rv_id: 920086 + rule_id: bwUNNN + version_id: ZRTed36 + url: https://semgrep.dev/playground/r/ZRTed36/gitlab.bandit.B304-3 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: Crypto.Hash.MD5.new(...) + - pattern: Cryptodome.Hash.MD5.new (...) + severity: WARNING +- id: gitlab.bandit.B304-4 + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B304-4 + secondary_identifiers: + - name: Bandit Test ID B304 + type: bandit_test_id + value: B304 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B304-4 + shortlink: https://sg.run/344r + semgrep.dev: + rule: + r_id: 11887 + rv_id: 920087 + rule_id: NbUYYN + version_id: nWTnNp8 + url: https://semgrep.dev/playground/r/nWTnNp8/gitlab.bandit.B304-4 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: Crypto.Hash.SHA.new(...) + - pattern: Cryptodome.Hash.SHA.new (...) + severity: WARNING +- id: gitlab.bandit.B304-5 + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B304-5 + secondary_identifiers: + - name: Bandit Test ID B304 + type: bandit_test_id + value: B304 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B304-5 + shortlink: https://sg.run/8nvQ + semgrep.dev: + rule: + r_id: 11540 + rv_id: 920081 + rule_id: NbUAOd + version_id: xyTdrd4 + url: https://semgrep.dev/playground/r/xyTdrd4/gitlab.bandit.B304-5 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: Cryptodome.Cipher.ARC2.new(...) + - pattern: Crypto.Cipher.ARC2.new + severity: WARNING +- id: gitlab.bandit.B304-6 + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B304-6 + secondary_identifiers: + - name: Bandit Test ID B304 + type: bandit_test_id + value: B304 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B304-6 + shortlink: https://sg.run/gJ75 + semgrep.dev: + rule: + r_id: 11541 + rv_id: 920082 + rule_id: kxURAL + version_id: O9Tv7v0 + url: https://semgrep.dev/playground/r/O9Tv7v0/gitlab.bandit.B304-6 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: Cryptodome.Cipher.ARC4.new(...) + - pattern: Crypto.Cipher.ARC4.new(...) + severity: WARNING +- id: gitlab.bandit.B304-7 + languages: + - python + message: | + The Blowfish encryption algorithm was meant as a drop-in replacement for DES and was created in + 1993. Smaller key sizes may make the ciphertext vulnerable to [birthday + attacks](https://en.wikipedia.org/wiki/Birthday_attack). While no known attacks against + Blowfish + exist, it should never be used to encrypt files over 4GB in size. If possible consider + using ChaCha20Poly1305 or AES-GCM instead of Blowfish. + + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B304-7 + secondary_identifiers: + - name: Bandit Test ID B304 + type: bandit_test_id + value: B304 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B304-7 + shortlink: https://sg.run/Q8oq + semgrep.dev: + rule: + r_id: 11542 + rv_id: 920079 + rule_id: wdU82R + version_id: kbTOPOq + url: https://semgrep.dev/playground/r/kbTOPOq/gitlab.bandit.B304-7 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: Cryptodome.Cipher.Blowfish.new(...) + - pattern: Crypto.Cipher.Blowfish.new(...) + severity: WARNING +- id: gitlab.bandit.B304-8 + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B304-8 + secondary_identifiers: + - name: Bandit Test ID B304 + type: bandit_test_id + value: B304 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B304-8 + shortlink: https://sg.run/3AkW + semgrep.dev: + rule: + r_id: 11543 + rv_id: 920080 + rule_id: x8UWB8 + version_id: w8Tkbke + url: https://semgrep.dev/playground/r/w8Tkbke/gitlab.bandit.B304-8 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: Cryptodome.Cipher.DES.new(...) + - pattern: Crypto.Cipher.DES.new(...) + severity: WARNING +- id: gitlab.bandit.B304-9 + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B304-9 + secondary_identifiers: + - name: Bandit Test ID B304 + type: bandit_test_id + value: B304 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B304-9 + shortlink: https://sg.run/4yw9 + semgrep.dev: + rule: + r_id: 11544 + rv_id: 920083 + rule_id: OrUG0Q + version_id: e1TZKZ7 + url: https://semgrep.dev/playground/r/e1TZKZ7/gitlab.bandit.B304-9 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: Cryptodome.Cipher.XOR.new(...) + - pattern: Crypto.Cipher.XOR.new(...) + severity: WARNING +- id: gitlab.bandit.B305 + languages: + - python + message: | + Cryptographic algorithms provide many different modes of operation, only some of which provide + message integrity. Without message integrity it could be possible for an adversary to attempt + to tamper with the ciphertext which could lead to compromising the encryption key. Newer + algorithms + apply message integrity to validate ciphertext has not been tampered with. + + Instead of using an algorithm that requires configuring a cipher mode, an algorithm + that has built-in message integrity should be used. Consider using `ChaCha20Poly1305` or + `AES-256-GCM` instead. + + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B305 + secondary_identifiers: + - name: Bandit Test ID B305 + type: bandit_test_id + value: B305 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B305 + shortlink: https://sg.run/5JJA + semgrep.dev: + rule: + r_id: 11891 + rv_id: 920078 + rule_id: OrUDDX + version_id: NdTeRel + url: https://semgrep.dev/playground/r/NdTeRel/gitlab.bandit.B305 + origin: community + subcategory: + - audit + pattern: cryptography.hazmat.primitives.ciphers.modes.ECB(...) + severity: WARNING +- id: gitlab.bandit.B306 + languages: + - python + message: | + The application was found creating temporary files with the insecure `mktemp` method. + Depending on how the application uses this temporary file, an attacker may be able to create + symlinks that point to other files prior to the application creating or writing + to the target file, leading to unintended files being created or overwritten. + + To remediate this issue consider using `tempfile.TemporaryFile` instead. + + Example using `tempfile.TemporaryFile` to write a file: + ``` + import tempfile + + # Open a new temporary file using a context manager + with tempfile.TemporaryFile() as fp: + # Write some data to the temporary file + fp.write(b'Some data') + # Seek back to beginning of file + fp.seek(0) + # Read it + data = fp.read() + # File is automatically closed/removed once we exit the with context + ``` + + For more information on alternative tempfile functions see: + - https://docs.python.org/3/library/tempfile.html + metadata: + cwe: CWE-377 + category: security + owasp: + - A3:2017-Sensitive Data Exposure + - A01:2021-Broken Access Control + shortDescription: Insecure temporary file + security-severity: Medium + primary_identifier: bandit.B306 + secondary_identifiers: + - name: Bandit Test ID B306 + type: bandit_test_id + value: B306 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B306 + shortlink: https://sg.run/Pp6v + semgrep.dev: + rule: + r_id: 11545 + rv_id: 920135 + rule_id: eqUvdb + version_id: NdTeRdN + url: https://semgrep.dev/playground/r/NdTeRdN/gitlab.bandit.B306 + origin: community + subcategory: + - audit + pattern: tempfile.mktemp(...) + severity: ERROR +- id: gitlab.bandit.B307 + 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(...): + ... + ... + metadata: + cwe: CWE-95 + owasp: + - A1:2017-Injection + - A03:2021-Injection + category: security + shortDescription: Improper neutralization of directives in dynamically evaluated + code ('Eval Injection') + security-severity: High + primary_identifier: bandit.B307 + secondary_identifiers: + - name: Bandit Test ID B307 + type: bandit_test_id + value: B307 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B307 + shortlink: https://sg.run/J3WP + semgrep.dev: + rule: + r_id: 11546 + rv_id: 920108 + rule_id: v8U5kd + version_id: l4TXDxq + url: https://semgrep.dev/playground/r/l4TXDxq/gitlab.bandit.B307 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.bandit.B308.B703 + patterns: + - pattern-not-inside: django.utils.html.format_html(...) + - pattern: django.utils.safestring.mark_safe(...) + message: | + 'mark_safe()' is used to mark a string as "safe" for HTML output. + This disables escaping and could therefore subject the content to + XSS attacks. Use 'django.utils.html.format_html()' to build HTML + for rendering instead. + metadata: + cwe: 'CWE-79: Improper Neutralization of Input During Web Page Generation (''Cross-site + Scripting'')' + owasp: 'A7: Cross-Site Scripting (XSS)' + license: MIT + source: https://semgrep.dev/r/gitlab.bandit.B308.B703 + shortlink: https://sg.run/58xj + semgrep.dev: + rule: + r_id: 11547 + rv_id: 13275 + rule_id: d8UzRp + version_id: JdTQjX + url: https://semgrep.dev/playground/r/JdTQjX/gitlab.bandit.B308.B703 + origin: community + category: security + subcategory: + - audit + severity: WARNING + languages: + - python +- id: gitlab.bandit.B310-1 + 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-939 + owasp: + - A1:2017-Injection + - A03:2021-Injection + shortDescription: Improper authorization in handler for custom URL scheme + security-severity: Medium + category: security + primary_identifier: bandit.B310-1 + secondary_identifiers: + - name: Bandit Test ID B310 + type: bandit_test_id + value: B310 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B310-1 + shortlink: https://sg.run/R8zN + semgrep.dev: + rule: + r_id: 11549 + rv_id: 920136 + rule_id: nJUYed + version_id: kbTOPx6 + url: https://semgrep.dev/playground/r/kbTOPx6/gitlab.bandit.B310-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.bandit.B311 + 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-330 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + category: security + shortDescription: Use of insufficiently random values + security-severity: Medium + primary_identifier: bandit.B311 + secondary_identifiers: + - name: Bandit Test ID B311 + type: bandit_test_id + value: B311 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B311 + shortlink: https://sg.run/B4PR + semgrep.dev: + rule: + r_id: 11551 + rv_id: 920123 + rule_id: 7KUe7J + version_id: 6xTyXxd + url: https://semgrep.dev/playground/r/6xTyXxd/gitlab.bandit.B311 + origin: community + subcategory: + - audit + pattern-either: + - pattern: random.random(...) + - pattern: random.randrange(...) + - pattern: random.randint(...) + - pattern: random.choice(...) + - pattern: random.uniform(...) + - pattern: random.triangular(...) + severity: INFO +- id: gitlab.bandit.B313 + languages: + - python + message: | + The application was found using the `xml.etree` package for processing XML. + Pythons default xml processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `etree` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A03:2021-Injection + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + primary_identifier: bandit.B313 + secondary_identifiers: + - name: Bandit Test ID B313 + type: bandit_test_id + value: B313 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B313 + shortlink: https://sg.run/31Wr + semgrep.dev: + rule: + r_id: 39387 + rv_id: 920137 + rule_id: KxUOo7 + version_id: w8TkbnA + url: https://semgrep.dev/playground/r/w8TkbnA/gitlab.bandit.B313 + origin: community + subcategory: + - audit + 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.bandit.B313.B314.B315.B316.B318.B319.B320.B405.B406.B407.B408.B409.B410 + pattern-either: + - pattern: import xml + - pattern: import lxml + - pattern: xml.etree.cElementTree.fromstring(...) + - pattern: xml.etree.cElementTree.parse(...) + - pattern: xml.etree.cElementTree.iterparse(...) + - pattern: xml.etree.cElementTree.XMLParser(...) + - pattern: xml.etree.ElementTree.fromstring(...) + - pattern: xml.etree.ElementTree.parse(...) + - pattern: xml.etree.ElementTree.iterparse(...) + - pattern: xml.etree.ElementTree.XMLParser(...) + - pattern: xml.sax.expatreader.create_parser(...) + - pattern: xml.dom.expatbuilder.parse(...) + - pattern: xml.dom.expatbuilder.parseString(...) + - pattern: xml.dom.minidom.parseString(...) + - pattern: xml.dom.minidom.parse(...) + - pattern: xml.dom.pulldom.parseString(...) + - pattern: xml.dom.pulldom.parse(...) + - pattern: lxml.etree.fromstring(...) + - pattern: lxml.etree.RestrictedElement(...) + - pattern: lxml.etree.GlobalParserTLS(...) + - pattern: lxml.etree.getDefaultParser(...) + - pattern: lxml.etree.check_docinfo(...) + metadata: + cwe: 'CWE-611: Improper Restriction of XML External Entity Reference' + owasp: 'A4: XML External Entities (XXE)' + license: MIT + source: https://semgrep.dev/r/gitlab.bandit.B313.B314.B315.B316.B318.B319.B320.B405.B406.B407.B408.B409.B410 + shortlink: https://sg.run/DJ5G + semgrep.dev: + rule: + r_id: 11552 + rv_id: 13281 + rule_id: L1U4Yd + version_id: DkTKjj + url: https://semgrep.dev/playground/r/DkTKjj/gitlab.bandit.B313.B314.B315.B316.B318.B319.B320.B405.B406.B407.B408.B409.B410 + origin: community + category: security + subcategory: + - audit + message: | + Found use of the native Python XML libraries, which is vulnerable to XML external entity (XXE) + attacks. The Python documentation recommends the 'defusedxml' library instead. Use 'defusedxml'. + See https://github.com/tiran/defusedxml for more information. + severity: ERROR + languages: + - python +- id: gitlab.bandit.B314 + languages: + - python + message: | + The application was found using the `xml.etree` package for processing XML. + Pythons default xml processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `etree` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A03:2021-Injection + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + primary_identifier: bandit.B314 + secondary_identifiers: + - name: Bandit Test ID B314 + type: bandit_test_id + value: B314 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B314 + shortlink: https://sg.run/4g0l + semgrep.dev: + rule: + r_id: 39388 + rv_id: 920138 + rule_id: qNUKOW + version_id: xyTdrZd + url: https://semgrep.dev/playground/r/xyTdrZd/gitlab.bandit.B314 + origin: community + subcategory: + - audit + 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.bandit.B315 + languages: + - python + message: | + The application was found using the `xml.sax.expatreader` package for processing XML. Python's + default XML processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `xml.sax` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A03:2021-Injection + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + primary_identifier: bandit.B315 + secondary_identifiers: + - name: Bandit Test ID B315 + type: bandit_test_id + value: B315 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B315 + shortlink: https://sg.run/5nKA + semgrep.dev: + rule: + r_id: 39391 + rv_id: 920140 + rule_id: JDUZkD + version_id: e1TZK11 + url: https://semgrep.dev/playground/r/e1TZK11/gitlab.bandit.B315 + origin: community + subcategory: + - audit + 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.bandit.B316 + languages: + - python + message: | + The application was found using the `xml.dom.expatbuilder` which calls the `xml.dom.minidom` + package for processing XML. Python's default XML processors suffer from various XML parsing + vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `xml.dom.minidom` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A03:2021-Injection + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + primary_identifier: bandit.B316 + secondary_identifiers: + - name: Bandit Test ID B316 + type: bandit_test_id + value: B316 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B316 + shortlink: https://sg.run/Jp8w + semgrep.dev: + rule: + r_id: 39390 + rv_id: 920139 + rule_id: PeUnzj + version_id: O9Tv7OX + url: https://semgrep.dev/playground/r/O9Tv7OX/gitlab.bandit.B316 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern: xml.dom.expatbuilder.parse(...) + - pattern-not: xml.dom.expatbuilder.parse("...") + - pattern: xml.dom.expatbuilder.parseString(...) + severity: WARNING +- id: gitlab.bandit.B317 + languages: + - python + message: | + The application was found using the `xml.sax` package for processing XML. + Python's default XML processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `xml.sax` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A03:2021-Injection + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + primary_identifier: bandit.B317 + secondary_identifiers: + - name: Bandit Test ID B317 + type: bandit_test_id + value: B317 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B317 + shortlink: https://sg.run/RPPO + semgrep.dev: + rule: + r_id: 11893 + rv_id: 920143 + rule_id: v8Ujj8 + version_id: ZRTedN2 + url: https://semgrep.dev/playground/r/ZRTedN2/gitlab.bandit.B317 + origin: community + subcategory: + - audit + pattern-either: + - pattern: xml.sax.parse(...) + - patterns: + - pattern: xml.sax.parseString(...) + - pattern-not: xml.sax.parseString("...") + - pattern: xml.sax.make_parser(...) + severity: WARNING +- id: gitlab.bandit.B318 + languages: + - python + message: | + The application was found using the `xml.dom.minidom` package for processing XML. Python's + default XML processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `xml.dom.minidom` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A03:2021-Injection + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + primary_identifier: bandit.B318 + secondary_identifiers: + - name: Bandit Test ID B318 + type: bandit_test_id + value: B318 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B318 + shortlink: https://sg.run/01Av + semgrep.dev: + rule: + r_id: 39398 + rv_id: 920141 + rule_id: WAU68J + version_id: vdTvQN8 + url: https://semgrep.dev/playground/r/vdTvQN8/gitlab.bandit.B318 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern: xml.dom.minidom.parseString(...) + - pattern-not: xml.dom.minidom.parseString("...") + - pattern: xml.dom.minidom.parse(...) + severity: WARNING +- id: gitlab.bandit.B319 + languages: + - python + message: | + The application was found using the `xml.dom.pulldom` package for processing XML. Python's + default XML processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `xml.dom.pulldom` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A03:2021-Injection + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + primary_identifier: bandit.B319 + secondary_identifiers: + - name: Bandit Test ID B319 + type: bandit_test_id + value: B319 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B319 + shortlink: https://sg.run/K2L7 + semgrep.dev: + rule: + r_id: 39399 + rv_id: 920142 + rule_id: 0oU6o9 + version_id: d6T6gAy + url: https://semgrep.dev/playground/r/d6T6gAy/gitlab.bandit.B319 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern: xml.dom.pulldom.parseString(...) + - pattern-not: xml.dom.pulldom.parseString("...") + - pattern: xml.dom.pulldom.parse(...) + severity: WARNING +- id: gitlab.bandit.B320 + languages: + - python + message: | + The application was found using the `lxml.etree` package for processing XML. + Python's default XML processors suffer from various XML parsing vulnerabilities + and care must be taken when handling XML data. Additionally, depending on the + version of Python, more critical vulnerabilities such as eXternal XML Entity + injection maybe exploitable. + + The `etree` package suffers from the following security risks as of Python 3.7.1: + * Billion laughs / exponential entity expansion - May allow an adversary to cause + a Denial of Service (DoS) against the application parsing arbitrary XML. + * Quadratic blowup entity expansion - Similar to above, but requires a larger input + to cause the Denial of Service. + + To remediate the above issues, consider using the + [defusedxml](https://pypi.org/project/defusedxml/) + library when processing untrusted XML. + + Example parsing an XML document using defusedxml: + ``` + from defusedxml.ElementTree import parse + + # Parse the inventory.xml file + et = parse('inventory.xml') + # Get the root element + root = et.getroot() + # Work with the root element + # ... + ``` + + For more information on the various XML parsers and their vulnerabilities please see: + - https://docs.python.org/3/library/xml.html#xml-vulnerabilities + + For more information on XML security see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#python + metadata: + cwe: CWE-611 + owasp: + - A4:2017-XML External Entities (XXE) + - A03:2021-Injection + category: security + shortDescription: Improper restriction of XML external entity reference + security-severity: Medium + primary_identifier: bandit.B320 + secondary_identifiers: + - name: Bandit Test ID B320 + type: bandit_test_id + value: B320 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B320 + shortlink: https://sg.run/PGLY + semgrep.dev: + rule: + r_id: 39389 + rv_id: 920121 + rule_id: lBUNZy + version_id: l4TXDx0 + url: https://semgrep.dev/playground/r/l4TXDx0/gitlab.bandit.B320 + origin: community + subcategory: + - audit + 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.bandit.B323 + languages: + - python + message: | + The application was found creating a SSL context using the `_create_unverified_context`. + This 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 remove the call to `_create_unverified_context` and either create a + default + context using `ssl.create_default_context` or create a context with TLS 1.3. + + Example creating a TLS 1.3 client socket connection by using a newer version of Python + (3.11.4) and + the SSL module: + ``` + import ssl + import socket + + # Create our initial socket + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + # Connect the socket + sock.connect(('www.example.org', 443)) + + # Create a new SSLContext with protocol set to ssl.PROTOCOL_TLS_CLIENT + # This will auto-select the highest grade TLS protocol version (1.3) + context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) + # Load our a certificates for server certificate authentication + context.load_verify_locations('cert.pem') + # Create our TLS socket, and validate the server hostname matches + with context.wrap_socket(sock, server_hostname="www.example.org") as tls_sock: + # Send some bytes over the socket (HTTP request in this case)\ + data = bytes('GET / HTTP/1.1\r\nHost: example.org\r\n\r\n', 'utf-8') + sent_bytes = tls_sock.send(data) + # Validate number of sent bytes + # ... + # Read the response + resp = tls_sock.recv() + # Work with the response + # ... + ``` + + Unverified SSL context detected. This will permit insecure connections without `verifyingSSL` + certificates. Use `ssl.create_default_context()` instead. + metadata: + cwe: CWE-295 + owasp: + - A2:2017-Broken Authentication + - A07:2021-Identification and Authentication Failures + category: security + shortDescription: Improper certificate validation + security-severity: Medium + primary_identifier: bandit.B323 + secondary_identifiers: + - name: Bandit Test ID B323 + type: bandit_test_id + value: B323 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B323 + shortlink: https://sg.run/BLLW + semgrep.dev: + rule: + r_id: 11895 + rv_id: 920132 + rule_id: ZqUgg2 + version_id: yeTDg2n + url: https://semgrep.dev/playground/r/yeTDg2n/gitlab.bandit.B323 + origin: community + subcategory: + - audit + pattern: ssl._create_unverified_context(...) + severity: ERROR +- id: gitlab.bandit.B324 + 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 + category: security + shortDescription: Use of a broken or risky cryptographic algorithm + security-severity: Medium + primary_identifier: bandit.B324 + secondary_identifiers: + - name: Bandit Test ID B324 + type: bandit_test_id + value: B324 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B324 + shortlink: https://sg.run/Wg1E + semgrep.dev: + rule: + r_id: 11553 + rv_id: 920097 + rule_id: 8GUE2O + version_id: JdToRDv + url: https://semgrep.dev/playground/r/JdToRDv/gitlab.bandit.B324 + origin: community + subcategory: + - audit + 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.bandit.B401 + languages: + - python + message: | + The application was found using a telnet library. As telnet does not provide encryption, it is + strongly recommended that communications use a more secure transport such as + SSH. + + The [paramiko](https://www.paramiko.org/) library can be used to initiate SSH connections. + + Example using `paramiko` SSH client: + ``` + import paramiko + import scp + + # Create an SSH client + with paramiko.SSHClient() as ssh: + # Load the system host keys so we can confirm the + # host we are connecting to is legitimate + ssh.load_system_host_keys('/home/appuser/.ssh/known_hosts') + + # Connect to the remote host using our SSH private key + ssh.connect(hostname='example.org', + port=22, + username='appuser', + key_filename='/home/appuser/.ssh/private_key') + # Work with the connection + ``` + + For more information on the paramiko module see: + - https://www.paramiko.org/ + metadata: + cwe: CWE-319 + category: security + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + shortDescription: Cleartext transmission of sensitive information + security-severity: Medium + primary_identifier: bandit.B401 + secondary_identifiers: + - name: Bandit Test ID B401 + type: bandit_test_id + value: B401 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B401 + shortlink: https://sg.run/0nrw + semgrep.dev: + rule: + r_id: 11554 + rv_id: 920133 + rule_id: gxUW4o + version_id: rxTjvLk + url: https://semgrep.dev/playground/r/rxTjvLk/gitlab.bandit.B401 + origin: community + subcategory: + - audit + patterns: + - pattern: import telnetlib + severity: ERROR +- id: gitlab.bandit.B404 + languages: + - python + message: 'Consider possible security implications associated with subprocess module. + + ' + metadata: + cwe: CWE-78 + owasp: A8:2017-Insecure Deserialization + shortDescription: Improper Neutralization of Special Elements used in an OS Command + ('OS Command Injection') + primary_identifier: bandit.B404 + secondary_identifiers: + - name: Bandit Test ID B404 + type: bandit_test_id + value: B404 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B404 + shortlink: https://sg.run/lj3o + semgrep.dev: + rule: + r_id: 11557 + rv_id: 835419 + rule_id: 4bUz3p + version_id: A8T3lxl + url: https://semgrep.dev/playground/r/A8T3lxl/gitlab.bandit.B404 + origin: community + category: security + subcategory: + - audit + patterns: + - pattern: import subprocess + severity: WARNING +- id: gitlab.bandit.B413 + 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 + - A02:2021-Cryptographic Failures + category: security + shortDescription: Use of unmaintained third party components + security-severity: Medium + primary_identifier: bandit.B413 + secondary_identifiers: + - name: Bandit Test ID B413 + type: bandit_test_id + value: B413 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B413 + shortlink: https://sg.run/okGX + semgrep.dev: + rule: + r_id: 11560 + rv_id: 920098 + rule_id: 5rU45b + version_id: 5PTNG9o + url: https://semgrep.dev/playground/r/5PTNG9o/gitlab.bandit.B413 + origin: community + subcategory: + - audit + 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.bandit.B501 + 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: + - A2:2017-Broken Authentication + - A07:2021-Identification and Authentication Failures + category: security + shortDescription: Improper certificate validation + security-severity: Medium + primary_identifier: bandit.B501 + secondary_identifiers: + - name: Bandit Test ID B501 + type: bandit_test_id + value: B501 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B501 + shortlink: https://sg.run/zk6n + semgrep.dev: + rule: + r_id: 11561 + rv_id: 920129 + rule_id: GdU0wd + version_id: jQTwjYg + url: https://semgrep.dev/playground/r/jQTwjYg/gitlab.bandit.B501 + origin: community + subcategory: + - audit + 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.bandit.B502 + languages: + - python + message: | + The application was found calling an SSL module with SSL or TLS protocols that have known + deficiencies. + It is strongly recommended that newer applications use TLS 1.2 or 1.3 and + `SSLContext.wrap_socket`. + + If using the `pyOpenSSL` module, please note that it has been deprecated and the Python + Cryptographic Authority + strongly suggests moving to use the [pyca/cryptography](https://github.com/pyca/cryptography) + module instead. + + To remediate this issue for the `ssl` module, create a new TLS context and pass in + `ssl.PROTOCOL_TLS_CLIENT` for clients or `ssl.PROTOCOL_TLS_SERVER` for servers to the + `ssl.SSLContext(...)` `protocol=` + argument. When converting the socket to a TLS socket, use the new `SSLContext.wrap_socket` + method instead. + + Example creating a TLS 1.3 client socket connection by using a newer version of Python + (3.11.4) and + the SSL module: + ``` + import ssl + import socket + + # Create our initial socket + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + # Connect the socket + sock.connect(('www.example.org', 443)) + + # Create a new SSLContext with protocol set to ssl.PROTOCOL_TLS_CLIENT + # This will auto-select the highest grade TLS protocol version (1.3) + context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) + # Load our a certificates for server certificate authentication + context.load_verify_locations('cert.pem') + # Create our TLS socket, and validate the server hostname matches + with context.wrap_socket(sock, server_hostname="www.example.org") as tls_sock: + # Send some bytes over the socket (HTTP request in this case)\ + data = bytes('GET / HTTP/1.1\r\nHost: example.org\r\n\r\n', 'utf-8') + sent_bytes = tls_sock.send(data) + # Validate number of sent bytes + # ... + # Read the response + resp = tls_sock.recv() + # Work with the response + # ... + ``` + + For more information on the ssl module see: + - https://docs.python.org/3/library/ssl.html + + For more information on pyca/cryptography and openssl see: + - https://cryptography.io/en/latest/openssl/ + metadata: + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + shortDescription: Inadequate Encryption Strength + security-severity: Medium + category: security + primary_identifier: bandit.B502 + secondary_identifiers: + - name: Bandit Test ID B502 + type: bandit_test_id + value: B502 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B502 + shortlink: https://sg.run/4g0g + semgrep.dev: + rule: + r_id: 39400 + rv_id: 920131 + rule_id: KxUOoO + version_id: 9lTA7Wo + url: https://semgrep.dev/playground/r/9lTA7Wo/gitlab.bandit.B502 + origin: community + subcategory: + - audit + 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.bandit.B502.B503 + 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 + message: | + An insecure SSL version was detected. TLS versions 1.0, 1.1, and all SSL versions + are considered weak encryption and are deprecated. + Use 'ssl.PROTOCOL_TLSv1_2' or higher. + metadata: + cwe: 'CWE-326: Inadequate Encryption Strength' + owasp: 'A3: Sensitive Data Exposure' + license: MIT + source: https://semgrep.dev/r/gitlab.bandit.B502.B503 + shortlink: https://sg.run/plRe + semgrep.dev: + rule: + r_id: 11562 + rv_id: 13295 + rule_id: ReUPvG + version_id: 1QTeld + url: https://semgrep.dev/playground/r/1QTeld/gitlab.bandit.B502.B503 + origin: community + category: security + subcategory: + - audit + severity: WARNING + languages: + - python +- id: gitlab.bandit.B504 + languages: + - python + message: | + The application was found calling `ssl.wrap_socket` without a TLS protocol version specified. + Additionally, `ssl.wrap_socket` has been deprecated since Python 3.7. It is strongly + recommended + that newer applications use TLS 1.2 or 1.3 and `SSLContext.wrap_socket`. + + To remediate this issue, create a new TLS context and pass in `ssl.PROTOCOL_TLS_CLIENT` + for clients or `ssl.PROTOCOL_TLS_SERVER` for servers to the `ssl.SSLContext(...)` `protocol=` + argument. When converting the socket to a TLS socket, use the new `SSLContext.wrap_socket` + method instead. + + + Example creating a TLS 1.3 client socket connection by using a newer version of Python + (3.11.4) and + the SSL module: + ``` + import ssl + import socket + + # Create our initial socket + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + # Connect the socket + sock.connect(('www.example.org', 443)) + + # Create a new SSLContext with protocol set to ssl.PROTOCOL_TLS_CLIENT + # This will auto-select the highest grade TLS protocol version (1.3) + context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) + # Load our a certificates for server certificate authentication + context.load_verify_locations('cert.pem') + # Create our TLS socket, and validate the server hostname matches + with context.wrap_socket(sock, server_hostname="www.example.org") as tls_sock: + # Send some bytes over the socket (HTTP request in this case)\ + data = bytes('GET / HTTP/1.1\r\nHost: example.org\r\n\r\n', 'utf-8') + sent_bytes = tls_sock.send(data) + # Validate number of sent bytes + # ... + # Read the response + resp = tls_sock.recv() + # Work with the response + # ... + ``` + + For more information on the ssl module see: + - https://docs.python.org/3/library/ssl.html + metadata: + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + shortDescription: Inadequate encryption strength + security-severity: Medium + category: security + primary_identifier: bandit.B504 + secondary_identifiers: + - name: Bandit Test ID B504 + type: bandit_test_id + value: B504 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B504 + shortlink: https://sg.run/2bNr + semgrep.dev: + rule: + r_id: 11563 + rv_id: 920130 + rule_id: AbUWYl + version_id: 1QT4NYz + url: https://semgrep.dev/playground/r/1QT4NYz/gitlab.bandit.B504 + origin: community + subcategory: + - audit + patterns: + - pattern: ssl.wrap_socket() + severity: WARNING +- id: gitlab.bandit.B505-1 + languages: + - python + message: | + The application is generating an RSA key that is less than the recommended 2048 bits. + The National Institute of Standards and Technology (NIST) deprecated signing Digital + Certificates that contained RSA Public Keys of 1024 bits in December 2010. While + 1024-bit RSA keys have not been factored yet, advances in compute may make it possible + in the near future. + + Consider upgrading to the newer asymmetric algorithm such as `X25519` which handles + the complexities of generating key pairs and choosing correct key sizes for you: + ``` + from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey + + # Generate a private key for use in the exchange. + private_key = X25519PrivateKey.generate() + # Work with private key/exchange with a peer's + # public key to created a shared and derived key + # ... + ``` + + Otherwise use a key size greater than 2048 when generating RSA keys: + ``` + from cryptography.hazmat.primitives.asymmetric import rsa + # Generate a private key of 4096 bits + private_key = rsa.generate_private_key( + # do not change the exponent value from 65537 + public_exponent=65537, + key_size=4096, + ) + # Work with the private key to sign/encrypt data + # ... + ``` + + For more information on using the cryptography module see: + - https://cryptography.io/en/latest + metadata: + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + category: security + shortDescription: Inadequate encryption strength + security-severity: Medium + primary_identifier: bandit.B505-1 + secondary_identifiers: + - name: Bandit Test ID B505 + type: bandit_test_id + value: B505 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B505-1 + shortlink: https://sg.run/XL9j + semgrep.dev: + rule: + r_id: 11564 + rv_id: 920084 + rule_id: BYUBYZ + version_id: vdTvQGr + url: https://semgrep.dev/playground/r/vdTvQGr/gitlab.bandit.B505-1 + origin: community + subcategory: + - audit + 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.bandit.B505-2 + languages: + - python + message: | + The application was found using an insufficient curve size for the Elliptical + Cryptography (EC) asymmetric algorithm. NIST recommends using a key size of + 224 or greater. + + To remediate this issue, replace the current key size with `ec.SECP384R1`, + + Example using `ec.SECP384R1`: + ``` + from cryptography.hazmat.primitives.asymmetric import ec + # Generate an EC private key using SECP384R1 + private_key = ec.generate_private_key( + ec.SECP384R1() + ) + # Work with/sign data using the key + # ... + ``` + + For more information on the cryptography module's EC section see: + - https://cryptography.io/en/latest/hazmat/primitives/asymmetric/ec/ + metadata: + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + category: security + shortDescription: Inadequate encryption strength + security-severity: Medium + primary_identifier: bandit.B505-2 + secondary_identifiers: + - name: Bandit Test ID B505 + type: bandit_test_id + value: B505 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B505-2 + shortlink: https://sg.run/jNgP + semgrep.dev: + rule: + r_id: 11565 + rv_id: 920085 + rule_id: DbUW8j + version_id: d6T6gPr + url: https://semgrep.dev/playground/r/d6T6gPr/gitlab.bandit.B505-2 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: cryptography.hazmat.primitives.asymmetric.ec.generate_private_key(...) + - pattern: cryptography.hazmat.primitives.asymmetric.ec.$SIZE + - metavariable-pattern: + metavariable: "$SIZE" + pattern-either: + - pattern: SECP192R1 + - pattern: SECT163K1 + - pattern: SECT163R2 + - focus-metavariable: "$SIZE" + severity: ERROR +- id: gitlab.bandit.B506 + languages: + - python + message: | + The application was found using an unsafe version of `yaml` load which is vulnerable to + deserialization attacks. Deserialization attacks exploit the process of reading serialized + data and turning it back + into an object. By constructing malicious objects and serializing them, an adversary may + attempt to: + + - Inject code that is executed upon object construction, which occurs during the + deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized + data but are read in during deserialization. + + To remediate this issue, use `safe_load()` or call `yaml.load()` with the `Loader` argument + set to + `yaml.SafeLoader`. + + Example loading YAML using `safe_load`: + ``` + import yaml + + # Use safe_load to load data into an intermediary object + intermediary_object = yaml.safe_load("""user: + name: 'test user'""" + ) + # Create our real object, copying over only the necessary fields + user_object = {'user': { + # Assign the deserialized data from intermediary object + 'name': intermediary_object['user']['name'], + # Add in protected data in object definition (or set it from a class constructor) + 'is_admin': False, + } + } + # Work with user_object + # ... + ``` + + For more details on deserialization attacks in general, see OWASP's guide: + - https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + 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 + category: security + shortDescription: Deserialization of untrusted data + security-severity: High + primary_identifier: bandit.B506 + secondary_identifiers: + - name: Bandit Test ID B506 + type: bandit_test_id + value: B506 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B506 + shortlink: https://sg.run/1nb1 + semgrep.dev: + rule: + r_id: 11566 + rv_id: 920104 + rule_id: WAUZx1 + version_id: WrTYnE6 + url: https://semgrep.dev/playground/r/WrTYnE6/gitlab.bandit.B506 + origin: community + subcategory: + - audit + severity: ERROR +- id: gitlab.bandit.B507 + languages: + - python + message: | + The application was found to ignore host keys. Host keys are important as + they provide assurance that the client can prove that the host is trusted. + By ignoring these host keys, it is impossible for the client to validate the + connection is to a trusted host. + + To remediate this issue, remove the call to `set_missing_host_key_policy(...)` which + sets the host key policy. Instead, load key files using either `load_system_host_keys` + or `load_host_keys` to only allow known good hosts. By not setting a host key policy + for unknown hosts, `paramiko`'s default policy is to use `RejectPolicy`. + + Example configuration connecting to a known, trusted host, and not allowing connections + to unknown hosts: + ``` + import paramiko + + # Create an SSH client + with paramiko.SSHClient() as ssh: + # Load the system host keys so we can confirm the + # host we are connecting to is legitimate + ssh.load_system_host_keys('/home/appuser/.ssh/known_hosts') + + # Connect to the remote host using our SSH private key + ssh.connect(hostname='example.org', + port=22, + username='appuser', + key_filename='/home/appuser/.ssh/private_key') + ``` + + For more information on `set_missing_host_key_policy` see: + - https://docs.paramiko.org/en/stable/api/client.html#paramiko.client.SSHClient.set_missing_host_key_policy + metadata: + cwe: CWE-322 + category: security + owasp: + - A5:2017-Broken Access Control + - A07:2021-Identification and Authentication Failures + shortDescription: Key exchange without entity authentication + security-severity: Medium + primary_identifier: bandit.B507 + secondary_identifiers: + - name: Bandit Test ID B507 + type: bandit_test_id + value: B507 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B507 + shortlink: https://sg.run/WOO4 + semgrep.dev: + rule: + r_id: 11897 + rv_id: 920128 + rule_id: EwUQQv + version_id: X0TAKxW + url: https://semgrep.dev/playground/r/X0TAKxW/gitlab.bandit.B507 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + $CLIENT = paramiko.client.SSHClient(...) + ... + $CLIENT.set_missing_host_key_policy(...) + - pattern-either: + - pattern: paramiko.client.AutoAddPolicy + - pattern: paramiko.client.WarningPolicy + severity: ERROR +- id: gitlab.bandit.B508 + languages: + - python + message: | + Pysnmp was detected using versions SNMPv1 or SNMPv2. SNPMv1 and SNMPv2 are insecure + and should no longer be used as they do not offer encryption. + + If possible, query SNMP devices using SNMPv3 instead. + + Example querying a device using SNMPv3 with SHA-AES: + ``` + from pysnmp.hlapi import * + # Create the snpm iterator + iterator = getCmd( + SnmpEngine(), + # Configure using SHA AES + UsmUserData('usr-sha-aes', 'authkey1', 'privkey1', + authProtocol=USM_AUTH_HMAC96_SHA, + privProtocol=USM_PRIV_CFB128_AES), + UdpTransportTarget(('demo.snmplabs.com', 161)), + ContextData(), + ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)) + ) + ``` + + For more information on using SNMPv3 with `Pysnmp` see: + - https://pysnmp.readthedocs.io/en/latest/examples/hlapi/v3arch/asyncore/sync/manager/cmdgen/snmp-versions.html#snmpv3-auth-sha-privacy-aes128 + metadata: + cwe: CWE-319 + category: security + shortDescription: Cleartext transmission of sensitive information + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: Medium + primary_identifier: bandit.B508 + secondary_identifiers: + - name: Bandit Test ID B508 + type: bandit_test_id + value: B508 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B508 + shortlink: https://sg.run/RpEK + semgrep.dev: + rule: + r_id: 47605 + rv_id: 920125 + rule_id: ZqUR1w + version_id: zyTG3l5 + url: https://semgrep.dev/playground/r/zyTG3l5/gitlab.bandit.B508 + origin: community + subcategory: + - audit + pattern-either: + - pattern: pysnmp.hlapi.CommunityData(..., mpModel=0, ...) + - pattern: pysnmp.hlapi.CommunityData(..., mpModel=1, ...) + severity: WARNING +- id: gitlab.bandit.B509 + 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 + security-severity: Medium + primary_identifier: bandit.B509 + secondary_identifiers: + - name: Bandit Test ID B509 + type: bandit_test_id + value: B509 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B509 + shortlink: https://sg.run/A3O4 + semgrep.dev: + rule: + r_id: 47606 + rv_id: 920126 + rule_id: nJUDAe + version_id: pZTbDNl + url: https://semgrep.dev/playground/r/pZTbDNl/gitlab.bandit.B509 + origin: community + subcategory: + - audit + 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.bandit.B601 + languages: + - python + message: | + Unverified SSL context detected. This will permit insecure connections without `verifyingSSL` + certificates. Use `ssl.create_default_context()` instead. + patterns: + - pattern-inside: | + import paramiko + ... + - pattern: "$CLIENT.exec_command(...)" + metadata: + cwe: CWE-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + shortDescription: Improper neutralization of special elements used in an OS Command + ('OS Command Injection') + security-severity: High + category: security + primary_identifier: bandit.B601 + secondary_identifiers: + - name: Bandit Test ID B601 + type: bandit_test_id + value: B601 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B601 + shortlink: https://sg.run/9qdy + semgrep.dev: + rule: + r_id: 11567 + rv_id: 920113 + rule_id: 0oUEOA + version_id: RGT2xA7 + url: https://semgrep.dev/playground/r/RGT2xA7/gitlab.bandit.B601 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.bandit.B602 + languages: + - python + patterns: + - patterns: + - pattern-not-inside: | + ... + $ARG = '...'.format('...') + ... + - pattern: subprocess.$FUNC($ARG, ...) + - pattern-not: subprocess.$FUNC('...', ...) + - pattern-not: subprocess.$FUNC('...' % '...', ...) + - pattern-not: subprocess.$FUNC('...'.format('...'), ...) + - pattern-either: + - pattern: subprocess.$FUNC(..., shell=True, ...) + - pattern: subprocess.$FUNC(..., shell=[$V, ...], ...) + - pattern: 'subprocess.$FUNC(..., shell={$K: $V, ...}, ...)' + - patterns: + - pattern: subprocess.$FUNC(..., shell=$INTVAL, ...) + - pattern-not: subprocess.$FUNC(..., shell=0, ...) + - metavariable-regex: + metavariable: "$INTVAL" + regex: "^[0-9]+$" + - patterns: + - pattern: subprocess.$FUNC(..., shell='$STRVAL', ...) + - pattern-not: subprocess.$FUNC(..., shell='', ...) + message: | + Found `subprocess` function `$FUNC` with `shell=True`. This is dangerous because this call will + spawn the command using a shell process. Doing so propagates current shell settings and + variables, + which makes it much easier for a malicious actor to execute commands. Use `shell=False` + instead. + metadata: + cwe: CWE-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + shortDescription: Improper neutralization of special elements used in an OS Command + ('OS Command Injection') + security-severity: High + category: security + primary_identifier: bandit.B602 + secondary_identifiers: + - name: Bandit Test ID B602 + type: bandit_test_id + value: B602 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B602 + shortlink: https://sg.run/yzYA + semgrep.dev: + rule: + r_id: 11568 + rv_id: 920116 + rule_id: KxU4yp + version_id: DkT2yNA + url: https://semgrep.dev/playground/r/DkT2yNA/gitlab.bandit.B602 + origin: community + subcategory: + - audit + severity: ERROR +- id: gitlab.bandit.B603 + 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 + shortDescription: Improper neutralization of special elements used in an OS Command + ('OS Command Injection') + security-severity: High + category: security + primary_identifier: bandit.B603 + secondary_identifiers: + - name: Bandit Test ID B603 + type: bandit_test_id + value: B603 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B603 + shortlink: https://sg.run/rABJ + semgrep.dev: + rule: + r_id: 11569 + rv_id: 920115 + rule_id: qNUoqN + version_id: BjTKL1R + url: https://semgrep.dev/playground/r/BjTKL1R/gitlab.bandit.B603 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.bandit.B604 + 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 + shortDescription: Improper neutralization of special elements used in an OS Command + ('OS Command Injection') + security-severity: High + category: security + primary_identifier: bandit.B604 + secondary_identifiers: + - name: Bandit Test ID B604 + type: bandit_test_id + value: B604 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B604 + shortlink: https://sg.run/bDvv + semgrep.dev: + rule: + r_id: 11570 + rv_id: 920117 + rule_id: lBUdPP + version_id: WrTYnE4 + url: https://semgrep.dev/playground/r/WrTYnE4/gitlab.bandit.B604 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.bandit.B605 + 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 + shortDescription: Improper neutralization of special elements used in an OS Command + ('OS Command Injection') + security-severity: High + category: security + primary_identifier: bandit.B605 + secondary_identifiers: + - name: Bandit Test ID B605 + type: bandit_test_id + value: B605 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B605 + shortlink: https://sg.run/NrlN + semgrep.dev: + rule: + r_id: 11571 + rv_id: 920112 + rule_id: YGUrPX + version_id: GxToXP3 + url: https://semgrep.dev/playground/r/GxToXP3/gitlab.bandit.B605 + origin: community + subcategory: + - audit + severity: INFO +- id: gitlab.bandit.B606 + languages: + - python + message: | + Found dynamic content when spawning a process. This is dangerous if externaldata can reach this + function call because it allows a malicious actor toexecute commands. Ensure no external data + reaches here. + patterns: + - pattern-either: + - patterns: + - pattern-not: os.$W("...", ...) + - pattern-either: + - pattern: os.execl(...) + - pattern: os.execle(...) + - pattern: os.execlp(...) + - pattern: os.execlpe(...) + - pattern: os.execv(...) + - pattern: os.execve(...) + - pattern: os.execvp(...) + - pattern: os.execvpe(...) + - pattern: os.startfile(...) + - patterns: + - pattern-either: + - pattern: os.spawnl(...) + - pattern: os.spawnle(...) + - pattern: os.spawnlp(...) + - pattern: os.spawnlpe(...) + - pattern: os.spawnv(...) + - pattern: os.spawnve(...) + - pattern: os.spawnvp(...) + - pattern: os.spawnvpe(...) + metadata: + cwe: CWE-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + shortDescription: Improper neutralization of special elements used in an OS Command + ('OS Command Injection') + security-severity: High + category: security + primary_identifier: bandit.B606 + secondary_identifiers: + - name: Bandit Test ID B606 + type: bandit_test_id + value: B606 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B606 + shortlink: https://sg.run/kLQA + semgrep.dev: + rule: + r_id: 11572 + rv_id: 920114 + rule_id: 6JUqpb + version_id: A8TNlJD + url: https://semgrep.dev/playground/r/A8TNlJD/gitlab.bandit.B606 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.bandit.B607 + 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 + shortDescription: Improper neutralization of special elements used in an OS Command + ('OS Command Injection') + security-severity: High + category: security + primary_identifier: bandit.B607 + secondary_identifiers: + - name: Bandit Test ID B607 + type: bandit_test_id + value: B607 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B607 + shortlink: https://sg.run/wx9d + semgrep.dev: + rule: + r_id: 11573 + rv_id: 920111 + rule_id: oqUzYg + version_id: 5PTNG9R + url: https://semgrep.dev/playground/r/5PTNG9R/gitlab.bandit.B607 + origin: community + subcategory: + - audit + severity: INFO +- id: gitlab.bandit.B608 + 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 + category: security + shortDescription: Improper neutralization of special elements used in an SQL Command + ('SQL Injection') + security-severity: High + primary_identifier: bandit.B608 + secondary_identifiers: + - name: Bandit Test ID B608 + type: bandit_test_id + value: B608 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B608 + shortlink: https://sg.run/xYry + semgrep.dev: + rule: + r_id: 11574 + rv_id: 920127 + rule_id: zdUyPj + version_id: 2KTdOYW + url: https://semgrep.dev/playground/r/2KTdOYW/gitlab.bandit.B608 + origin: community + subcategory: + - audit + patterns: + - metavariable-regex: + metavariable: "$QUERY" + regex: "(?i)^(SELECT|INSERT|UPDATE|DELETE)\\s" + - pattern-not: + pattern-either: + - pattern: $DB.execute("...") + - pattern: $DB.execute("$QUERY" % "...") + - pattern: $DB.execute("$QUERY" + "...") + - pattern-either: + - pattern: $DB.execute("$QUERY" % ...) + - pattern: $DB.execute("$QUERY".format(...)) + - pattern: $DB.execute(f"$QUERY") + - pattern: $DB.execute("$QUERY" + ...) + - patterns: + - pattern-either: + - pattern-inside: | + ... + $SQL = "$QUERY" % ... + ... + - pattern-inside: | + ... + $SQL = "$QUERY" + ... + ... + - pattern-inside: | + ... + $TMP = "$QUERY" + ... + $SQL = $TMP + "..." % ... + ... + - pattern-inside: | + ... + $SQL = "$QUERY" + ... + $SQL += ... + ... + - pattern-inside: | + ... + $SQL = "$QUERY".format(...) + ... + - pattern-inside: | + ... + $SQL = f"$QUERY" + ... + - pattern: "$DB.execute($SQL)" + severity: WARNING +- id: gitlab.bandit.B609 + languages: + - python + message: "Detected use of the wildcard character in a system call that spawns a + shell. This subjects the\nwildcard 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 + primary_identifier: bandit.B609 + secondary_identifiers: + - name: Bandit Test ID B609 + type: bandit_test_id + value: B609 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B609 + shortlink: https://sg.run/055v + semgrep.dev: + rule: + r_id: 11898 + rv_id: 920110 + rule_id: 7KUppP + version_id: JdToRDY + url: https://semgrep.dev/playground/r/JdToRDY/gitlab.bandit.B609 + origin: community + subcategory: + - audit + 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.bandit.B610 + 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. + + The `QuerySet.extra` API method will be deprecated as it a source of SQL Injection + vulnerabilities and other problems. This method is especially risky as callers + will need to do their own escaping of any parameters that come from user-supplied + information. + + To remediate this issue, do not use `extra` but use other `QuerySet` methods to achieve + the same goals. If for some reason this is not feasible, consider using the `RawSQL` method + and making sure that all arguments, including user-supplied ones, are only used in + `params` + + + While not recommended due to [potential SQL + Injection](https://docs.djangoproject.com/en/4.2/ref/models/expressions/#raw-sql-expressions), + below is an example using `RawSQL`, + passing in user-supplied data as a `param` which will escape the input: + ``` + # If dealing with integer based user input, restrict the values to integers only using the + # path configuration: path('/someview/', views.some_view, + name='someview'), + + # views.py + def some_view(request, user_supplied_id): + # Never use string interpolation in the `sql` parameter. + # Never quote the `%s` string format such as `... where id='%s'` as this could lead to SQL + Injection. + # Pass the user supplied data only in the `params` parameter. + for obj in DBObject.objects.all().annotate( + val=RawSQL(sql="select id from some_secondary_table where id=%s", + params=[user_supplied_id])): + # Work with the results from the query + # ... + ``` + + For more information on QuerySet see: + - https://docs.djangoproject.com/en/4.2/ref/models/querysets/#queryset-api + + For more information on SQL Injection see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html + 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 + category: security + shortDescription: Improper neutralization of special elements used in an SQL Command + ('SQL Injection') + security-severity: High + primary_identifier: bandit.B610 + secondary_identifiers: + - name: Bandit Test ID B610 + type: bandit_test_id + value: B610 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B610 + shortlink: https://sg.run/O1wk + semgrep.dev: + rule: + r_id: 11575 + rv_id: 920105 + rule_id: pKUG96 + version_id: 0bTp31Q + url: https://semgrep.dev/playground/r/0bTp31Q/gitlab.bandit.B610 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.bandit.B611 + 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. + + To remediate this issue, do not use `raw` or `RawSQL` but use other `QuerySet` methods to + achieve + the same goals. If for some reason this is not feasible, ensure calls including user-supplied + data + pass it in to the `params` parameter of the `RawSQL` method. + + While not recommended due to [potential SQL + Injection](https://docs.djangoproject.com/en/4.2/ref/models/expressions/#raw-sql-expressions), + below is an example using `RawSQL`, + passing in user-supplied data as a `param` which will escape the input: + ``` + # If dealing with integer based user input, restrict the values to integers only using the + # path configuration: path('/someview/', views.some_view, + name='someview'), + + # views.py + def some_view(request, user_supplied_id): + # Never use string interpolation in the `sql` parameter. + # Never quote the `%s` string format such as `... where id='%s'` as this could lead to SQL + Injection. + # Pass the user supplied data only in the `params` parameter. + for obj in DBObject.objects.all().annotate( + val=RawSQL(sql="select id from some_secondary_table where id=%s", + params=[user_supplied_id])): + # Work with the results from the query + # ... + ``` + + For more information on QuerySet see: + - https://docs.djangoproject.com/en/4.2/ref/models/querysets/#queryset-api + + 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 + category: security + shortDescription: Improper neutralization of special elements used in an SQL Command + ('SQL Injection') + primary_identifier: bandit.B611 + secondary_identifiers: + - name: Bandit Test ID B611 + type: bandit_test_id + value: B611 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B611 + shortlink: https://sg.run/e4xL + semgrep.dev: + rule: + r_id: 11576 + rv_id: 835414 + rule_id: 2ZU4Wb + version_id: PkTxGK4 + url: https://semgrep.dev/playground/r/PkTxGK4/gitlab.bandit.B611 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: "$MODEL.objects.raw($QUERY, ...)" + - pattern: django.db.models.expressions.RawSQL(...) + severity: ERROR +- id: gitlab.bandit.B611-1 + message: "SQL Injections are a critical type of vulnerability that can lead to data + \nor system compromise. By dynamically generating SQL query strings, user \ninput + may be able to influence the logic of the SQL statement. \nThis could lead to + an adversary accessing information they should not \nhave access to, or in some + circumstances, being able to execute OS functionality\nor code.\n\nReplace all + dynamically generated SQL queries with parameterized queries. \nIn situations + where dynamic queries must be created, never use direct user input,\nbut instead + use a map or dictionary of valid values and resolve them using a user \nsupplied + key.\n\nFor example, some database drivers do not allow parameterized queries + for \n`>` or `<` comparison operators. In these cases, do not use a user supplied + \n`>` or `<` value, but rather have the user supply a `gt` or `lt` value. \nThe + alphabetical values are then used to look up the `>` and `<` values to be used + \nin the construction of the dynamic query. The same goes for other queries where + \ncolumn or table names are required but cannot be parameterized.\n\nData that + is possible user-controlled from a python request is passed\nto `raw()` function. + To remediate this issue, use django's QuerySets, \nwhich are built with query + parameterization and therefore not vulnerable \nto sql injection. For example, + you could use `Entry.objects.filter(date=2006)`\n\nIf for some reason this is + not feasible, ensure calls including user-supplied \ndata pass it in to the `params` + parameter of the `raw()` method.\nBelow is an example using `raw()`, passing in + user-supplied data as `params`. \nThis will treat the query as a parameterized + query and `params` as strictly data, \npreventing any possibility of SQL Injection.\n\n```\ndef + test(request):\n uname = request.GET[\"username\"] \n res = User.objects.raw('SELECT + * FROM myapp_user WHERE username = %s', (uname,))\n```\n\nFor more information + on QuerySet see:\n- https://docs.djangoproject.com/en/5.0/ref/models/querysets/\n\nFor + more information on SQL Injection see OWASP:\n- https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html\n" + metadata: + cwe: CWE-89 + owasp: + - A1:2017-Injection + - A03:2021-Injection + category: security + shortDescription: Improper neutralization of special elements used in an SQL Command + ('SQL Injection') + security-severity: High + primary_identifier: bandit.B611 + secondary_identifiers: + - name: Bandit Test ID B611 + type: bandit_test_id + value: B611 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B611-1 + shortlink: https://sg.run/Gdj0z + semgrep.dev: + rule: + r_id: 144292 + rv_id: 920144 + rule_id: j2UgdG1 + version_id: nWTnNPQ + url: https://semgrep.dev/playground/r/nWTnNPQ/gitlab.bandit.B611-1 + origin: community + subcategory: + - audit + languages: + - python + severity: ERROR + mode: taint + pattern-sources: + - patterns: + - pattern: "$PARAM" + - pattern-inside: "def $VIEW(...,$PARAM,...):\n ...\n return ... \n" + pattern-sinks: + - patterns: + - pattern: "$QUERY" + - pattern-inside: "$MODEL.objects.raw($QUERY, ... )" +- id: gitlab.bandit.B611-2 + languages: + - python + message: "SQL Injections are a critical type of 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 the SQL \nstatement. This could lead to + an adversary accessing information they should not have access to, or in\nsome + circumstances, being able to execute OS functionality or code.\n\nReplace all + dynamically generated SQL queries with parameterized queries. In situations where + dynamic \nqueries must be created, never use direct user input, but instead use + a map or dictionary of valid values \nand resolve them using a user supplied key.\n\nFor + example, some database drivers do not allow parameterized queries for `>` or `<` + comparison operators. \nIn these cases, do not use a user supplied `>` or `<` + value, but rather have the user supply a `gt` or `lt` \nvalue. The alphabetical + values are then used to look up the `>` and `<` values to be used in the \nconstruction + of the dynamic query. The same goes for other queries where column or table names + are required \nbut cannot be parameterized.\n\nTo remediate this issue, do not + use `raw` or `RawSQL` but use other `QuerySet` methods to achieve the same\ngoals. + If for some reason this is not feasible, ensure calls including user-supplied + data pass it in to \nthe `params` parameter of the `RawSQL` method.\n\nWhile not + recommended due to [potential SQL Injection](https://docs.djangoproject.com/en/5.0/ref/models/expressions/#raw-sql-expressions), + below is an example using `RawSQL`.\nPassing in user-supplied data as a `param` + which will escape the input:\n\n```\n# If dealing with integer based user input, + restrict the values to integers only using the\n# path configuration: path('/someview/', + views.some_view, name='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 Injection.\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\", params=[user_supplied_id])):\n # Work with the results from + the query\n # ...\n```\n\nFor more information on QuerySets 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" + metadata: + cwe: CWE-89 + owasp: + - A1:2017-Injection + - A03:2021-Injection + category: security + shortDescription: Improper neutralization of special elements used in an SQL Command + ('SQL Injection') + security-severity: CRITICAL + primary_identifier: bandit.B611 + secondary_identifiers: + - name: Bandit Test ID B611 + type: bandit_test_id + value: B611 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B611-2 + shortlink: https://sg.run/Redjv + semgrep.dev: + rule: + r_id: 144293 + rv_id: 920145 + rule_id: 10UO6J3 + version_id: ExT1WNv + url: https://semgrep.dev/playground/r/ExT1WNv/gitlab.bandit.B611-2 + origin: community + subcategory: + - audit + mode: taint + pattern-sources: + - patterns: + - pattern: "$PARAM" + - pattern-inside: | + def $VIEW(...,$PARAM,...): + ... + return ... + pattern-sinks: + - patterns: + - pattern: "$QUERY" + - pattern-inside: django.db.models.expressions.RawSQL($QUERY, ... ) + severity: ERROR +- id: gitlab.bandit.B612 + 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 + security-severity: High + primary_identifier: bandit.B612 + secondary_identifiers: + - name: Bandit Test ID B612 + type: bandit_test_id + value: B612 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B612 + shortlink: https://sg.run/GBEn + semgrep.dev: + rule: + r_id: 47604 + rv_id: 920122 + rule_id: d8UN2B + version_id: YDTYbvy + url: https://semgrep.dev/playground/r/YDTYbvy/gitlab.bandit.B612 + origin: community + subcategory: + - audit + patterns: + - pattern: logging.config.listen(...) + severity: WARNING +- id: gitlab.bandit.B701 + languages: + - python + message: | + The application was found using Jinja2 `Environment` without autoescaping enabled. If using in + the context of HTML this could lead to Cross-Site Scripting (XSS) attacks when rendering with + user-supplied input. + + Unfortunately, Jinja2 does not support context-aware escaping, meaning it is insufficient to + protect against + XSS for the various web contexts. 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 `
context 1
` + - Inside attributes: `
` + - Inside event attributes `` + - Inside script blocks: `` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: `link` + + 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. + + To handle different contexts, one approach would be to write custom Jinja2 filters. Below is + an example + that escapes or encodes links and potentially malicious script, note this does not include + other contexts + such as CSS or attributes: + ``` + from jinja2 import Environment, select_autoescape, FileSystemLoader + from jinja2 import pass_eval_context + from markupsafe import Markup, escape + + @pass_eval_context + def escape_link(eval_ctx, value): + bad_link = "#JinjatmplZ" + # Block any values that start with // as that could be used to inject + # links to third party pages see: + https://en.wikipedia.org/wiki/Wikipedia:Protocol-relative_URL + if value.startswith('//'): + return bad_link + + # Only allow relative links + # if you want to allow links that start with http or ws replace with below: + # if not value.startswith('/'): and not value.startswith('http') and not + value.startswith('ws') + if not value.startswith('/'): + return bad_link + + # Alternatively, you could only call escape if autoescape is true + # if eval_ctx.autoescape: + # return escape(value) + # else + # return value + + return escape(value) + + # Create a replacement table + js_replacement = str.maketrans({ + '"': "\\u0022", + '`': "\\u0060", + '&': "\\u0026", + '\'': "\\u0027", + '+': "\\u002b", + '/': "\\/", + '<': "\\u003c", + '>': "\\u003e", + '\\': "\\\\", + '(': "\\u0028", + ')': "\\u0029", + }) + + @pass_eval_context + def escape_js(eval_ctx, value): + """ + Escape the input for use in ", + script_context="alert(1);alert`1`",) + ) + + # Sample template: + """ + + + + My Webpage + + +

My Webpage

+ {{ html_context }} + link + + + + """ + ``` + + For more information on autoescape see: + - https://jinja.palletsprojects.com/en/3.1.x/api/#autoescaping + + For more information on XSS see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html + metadata: + cwe: CWE-116 + owasp: + - A7:2017-Cross-Site Scripting (XSS) + - A03:2021-Injection + category: security + shortDescription: Improper encoding or escaping of output + security-severity: Medium + primary_identifier: bandit.B701 + secondary_identifiers: + - name: Bandit Test ID B701 + type: bandit_test_id + value: B701 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B701 + shortlink: https://sg.run/v0j0 + semgrep.dev: + rule: + r_id: 11577 + rv_id: 920106 + rule_id: X5UZBZ + version_id: K3TwLJR + url: https://semgrep.dev/playground/r/K3TwLJR/gitlab.bandit.B701 + origin: community + subcategory: + - audit + patterns: + - pattern-not: jinja2.Environment(..., autoescape=True, ...) + - pattern-not: jinja2.Environment(..., autoescape=jinja2.select_autoescape(...), + ...) + - pattern: jinja2.Environment(...) + severity: WARNING +- id: gitlab.bandit.B702 + 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 `
context + 1
`\n- Inside attributes: `
`\n- Inside event + attributes ``\n- Inside script blocks: + ``\n- Unsafe element HTML assignment: `element.innerHTML + = \"context 5\"`\n- Inside URLs: \n`link`\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 \nlike {{ 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 \n\n\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=\"\",\n + \ link_context=\"/# onclick=alert(1)\",\n script_context=\"alert(1)\",)\n)\n```\n" + metadata: + cwe: CWE-79 + category: security + owasp: + - A7:2017-Cross-Site Scripting (XSS) + - A03:2021-Injection + shortDescription: Improper neutralization of input during web page generation + ('Cross-site Scripting') + security-severity: Medium + primary_identifier: bandit.B702 + secondary_identifiers: + - name: Bandit Test ID B702 + type: bandit_test_id + value: B702 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B702 + shortlink: https://sg.run/K887 + semgrep.dev: + rule: + r_id: 11899 + rv_id: 920107 + rule_id: L1Urrl + version_id: qkTpw4A + url: https://semgrep.dev/playground/r/qkTpw4A/gitlab.bandit.B702 + origin: community + subcategory: + - audit + 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.bandit.B703 + languages: + - python + 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 `
context 1
` + - Inside attributes: `
` + - Inside event attributes `` + - Inside script blocks: `` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: `link` + + 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. + + Consider using + [format_html](https://docs.djangoproject.com/en/4.2/ref/utils/#django.utils.html.format_html) + instead of + the `django.utils.safestring` methods. + + Example using `format_html`: + ``` + # Use format_html to create an HTML link, using href as the parameter + # which will be encoded automatically + format_html("
  • Some Link
  • ", href) + ``` + + For more information on XSS see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html + metadata: + cwe: CWE-79 + owasp: + - A7:2017-Cross-Site Scripting (XSS) + - A03:2021-Injection + category: security + shortDescription: Improper neutralization of input during web page generation + ('Cross-site Scripting') + security-severity: Medium + primary_identifier: bandit.B703 + secondary_identifiers: + - name: Bandit Test ID B703 + type: bandit_test_id + value: B703 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.bandit.B703 + shortlink: https://sg.run/dgk0 + semgrep.dev: + rule: + r_id: 11578 + rv_id: 920146 + rule_id: j2UqOR + version_id: 7ZTbRoP + url: https://semgrep.dev/playground/r/7ZTbRoP/gitlab.bandit.B703 + origin: community + subcategory: + - audit + patterns: + - pattern-not-inside: django.utils.html.format_html(...) + - pattern-either: + - patterns: + - pattern: django.utils.safestring.SafeText(...) + - pattern-not: django.utils.safestring.SafeText("...") + - patterns: + - pattern: django.utils.safestring.SafeUnicode(...) + - pattern-not: django.utils.safestring.SafeUnicode("...") + - patterns: + - pattern: django.utils.safestring.SafeString(...) + - pattern-not: django.utils.safestring.SafeString("...") + - patterns: + - pattern: django.utils.safestring.SafeBytes(...) + - pattern-not: django.utils.safestring.SafeBytes("...") + - patterns: + - pattern: django.utils.safestring.mark_safe(...) + - pattern-not: django.utils.safestring.mark_safe("...") + severity: WARNING +- id: gitlab.eslint.detect-buffer-noassert + languages: + - javascript + - typescript + pattern-either: + - pattern: "$OBJ.readUInt8(..., true)" + - pattern: "$OBJ.readUInt16LE(..., true)" + - pattern: "$OBJ.readUInt16BE(..., true)" + - pattern: "$OBJ.readUInt32LE(..., true)" + - pattern: "$OBJ.readUInt32BE(..., true)" + - pattern: "$OBJ.readInt8(..., true)" + - pattern: "$OBJ.readInt16LE(..., true)" + - pattern: "$OBJ.readInt16BE(..., true)" + - pattern: "$OBJ.readInt32LE(..., true)" + - pattern: "$OBJ.readInt32BE(..., true)" + - pattern: "$OBJ.readFloatLE(..., true)" + - pattern: "$OBJ.readFloatBE(..., true)" + - pattern: "$OBJ.readDoubleLE(..., true)" + - pattern: "$OBJ.readDoubleBE(..., true)" + - pattern: "$OBJ.writeUInt8(..., true)" + - pattern: "$OBJ.writeUInt16LE(..., true)" + - pattern: "$OBJ.writeUInt16BE(..., true)" + - pattern: "$OBJ.writeUInt32LE(..., true)" + - pattern: "$OBJ.writeUInt32BE(..., true)" + - pattern: "$OBJ.writeInt8(..., true)" + - pattern: "$OBJ.writeInt16LE(..., true)" + - pattern: "$OBJ.writeInt16BE(..., true)" + - pattern: "$OBJ.writeInt32LE(..., true)" + - pattern: "$OBJ.writeInt32BE(..., true)" + - pattern: "$OBJ.writeFloatLE(..., true)" + - pattern: "$OBJ.writeFloatBE(..., true)" + - pattern: "$OBJ.writeDoubleLE(..., true)" + - pattern: "$OBJ.writeDoubleBE(..., true)" + severity: WARNING + message: | + The application was found using `noAssert` when calling the Buffer API. The `noAssert` + argument has + been deprecated since Node 10. Calling the Buffer API with this argument allows the offset + specified to + be beyond the end of the buffer. This could result in writing or reading beyond the end of the + buffer and + cause a segmentation fault, leading to the application crashing. + + To remediate this issue, remove the `true` argument when calling any of the Buffer read or + write methods. + The application should still handle `RangeError` exception cases where the offset is beyond + the end of the + buffer. + + Example reading from a Buffer without the `noAssert` argument and gracefully handling errors: + ``` + // Create a new buffer + const buf = Buffer.from([1, 2, 3, 4]); + try { + // Read a single byte from it, starting at offset 1 + const b = buf.readInt8(1); + // Work with b + } catch (e) { + if (e instanceof RangeError) { + console.log('Invalid offset: %s', e.message); + } + // handle other errors + } + ``` + metadata: + shortDescription: Improper restriction of operations within the bounds of a memory + buffer + cwe: CWE-119 + category: security + owasp: + - A9:2017-Using Components with Known Vulnerabilities + - A06:2021-Vulnerable and Outdated Components + source-rule-url: https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-buffer-noassert.js + security-severity: Medium + primary_identifier: eslint.detect-buffer-noassert + secondary_identifiers: + - name: ESLint rule ID/detect-buffer-noassert + type: eslint_rule_id + value: detect-buffer-noassert + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.eslint.detect-buffer-noassert + shortlink: https://sg.run/E5WB + semgrep.dev: + rule: + r_id: 11581 + rv_id: 920147 + rule_id: yyUvwN + version_id: LjTzeQl + url: https://semgrep.dev/playground/r/LjTzeQl/gitlab.eslint.detect-buffer-noassert + origin: community + subcategory: + - audit +- id: gitlab.eslint.detect-child-process + languages: + - javascript + - typescript + patterns: + - pattern: child_process.exec(...) + - pattern-not: child_process.exec('...') + severity: WARNING + message: | + OS command injection is a critical vulnerability that can lead to a full system + compromise as it may allow an adversary to pass in arbitrary commands or arguments + to be executed. + + User input should never be used in constructing commands or command arguments + to functions which execute OS commands. This includes filenames supplied by + user uploads or downloads. + + Ensure your application does not: + + - Use user-supplied information in the process name to execute. + - Use user-supplied information in an OS command execution function which does + not escape shell meta-characters. + - Use user-supplied information in arguments to OS commands. + + The application should have a hardcoded set of arguments that are to be passed + to OS commands. If filenames are being passed to these functions, it is + recommended that a hash of the filename be used instead, or some other unique + identifier. It is strongly recommended that a native library that implements + the same functionality be used instead of using OS system commands, due to the + risk of unknown attacks against third-party commands. + + When specifying the OS command, ensure the application uses the full path + information, otherwise the OS may attempt to look up which process to execute + and could be vulnerable to untrusted search path vulnerabilities (CWE-426). + + Example of safely executing an OS command: + ``` + const child_process = require('child_process'); + const fs = require('fs'); + const crypto = require('node:crypto'); + const { mkdtempSync } = require('node:fs'); + + function executeCommand(userFileData) { + // Create a temporary directory, preferably in an application directory + // that only the application has access to. + const fileDir = mkdtempSync('/tmp/tmpdir-'); + // Generate a random filename, do not use user input + const filePath = fileDir + path.sep + crypto.randomUUID(); + // Write the user-supplied data to the temporary file. + fs.writeFileSync(filePath, userFileData); + // Execute a program with a hardcoded path to the binary + child_process.exec(`/bin/cat ${filePath}`, (error, stdout, stderr) => { + // Delete the temporary directory and file if no longer needed + fs.rmSync(fileDir, { recursive: true, force: true }); + if (error) { + console.error(`exec error: ${error}`); + return; + } + console.log(`stdout: ${stdout}`); + console.error(`stderr: ${stderr}`); + }); + } + ``` + + For more information on OS command injection, see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html + + Detected non-literal calls to child_process.exec(). This could lead to a command + injection vulnerability. + metadata: + cwe: CWE-95 + owasp: A1:2017-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-child-process.js + primary_identifier: eslint.detect-child-process + secondary_identifiers: + - name: ESLint rule ID/detect-child-process + type: eslint_rule_id + value: detect-child-process + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.eslint.detect-child-process + shortlink: https://sg.run/nqRr + semgrep.dev: + rule: + r_id: 11580 + rv_id: 835458 + rule_id: 9AUODZ + version_id: PkTxG74 + url: https://semgrep.dev/playground/r/PkTxG74/gitlab.eslint.detect-child-process + origin: community + subcategory: + - audit +- id: gitlab.eslint.detect-disable-mustache-escape + languages: + - javascript + - typescript + patterns: + - pattern-inside: | + $OBJ = require('mustache') + ... + - pattern-either: + - pattern: | + $OBJ.escape = function($TEXT) { + ... + return $TEXT; + } + - patterns: + - metavariable-regex: + metavariable: "$X" + regex: '"\{\{\{(.+?)\}\}\}"' + - pattern: "$OBJ.render($X, ... )" + - patterns: + - metavariable-regex: + metavariable: "$Y" + regex: '"\{\{\&(.+?)\}\}"' + - pattern: "$OBJ.render($Y, ... )" + severity: WARNING + message: | + Markup escaping disabled. This can be used with some template engines to escape + disabling of HTML entities, which can lead to XSS attacks. + metadata: + cwe: CWE-79 + owasp: + - A7:2017-Cross-Site Scripting (XSS) + - A03:2021-Injection + category: security + shortDescription: Improper neutralization of input during web page generation + (XSS) + security-severity: Medium + primary_identifier: eslint.detect-disable-mustache-escape + secondary_identifiers: + - name: ESLint rule ID/detect-disable-mustache-escape + type: eslint_rule_id + value: detect-disable-mustache-escape + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.eslint.detect-disable-mustache-escape + shortlink: https://sg.run/Jjjo + semgrep.dev: + rule: + r_id: 11902 + rv_id: 920156 + rule_id: QrUppL + version_id: GxToX63 + url: https://semgrep.dev/playground/r/GxToX63/gitlab.eslint.detect-disable-mustache-escape + origin: community + subcategory: + - audit +- id: gitlab.eslint.detect-eval-with-expression + languages: + - javascript + - typescript + patterns: + - pattern-either: + - patterns: + - pattern: 'eval($OBJ) + + ' + - pattern-not: 'eval("...") + + ' + - patterns: + - pattern: "$A.eval($OBJ)\n" + - pattern-not: '$A.eval("...") + + ' + - patterns: + - pattern: "(..., eval)($OBJ)\n" + - 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() + constructor OR setTimeout() OR setInterval() methods. If the + + variables or strings or functions passed to these methods contains user-supplied input, an adversary could attempt to execute arbitrary + + JavaScript + + code. This could lead to a full system compromise in Node applications or Cross-site Scripting + + (XSS) in web applications. + + + To remediate this issue, remove all calls to above methods and consider alternative methods for + + executing + + the necessary business logic. There is almost no safe method of calling `eval` or other above stated sinks with + + user-supplied input. + + Instead, consider alternative methods such as using property accessors to dynamically access + + values. + + + Example using property accessors to dynamically access an object's property: + + ``` + + // Define an object + + const obj = {key1: 'value1', key2: 'value2'}; + + // Get key dynamically from user input + + const key = getUserInput(); + + // Check if the key exists in our object and return it, or a default empty string + + const value = (obj.hasOwnProperty(key)) ? obj[key] : ''; + + // Work with the value + + ``` + + + For more information on why not to use `eval`, and alternatives see: + + - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval! + + Other References: + + - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function + + - https://developer.mozilla.org/en-US/docs/Web/API/setTimeout + + - https://developer.mozilla.org/en-US/docs/Web/API/setInterval + metadata: + cwe: CWE-95 + shortDescription: Improper neutralization of directives in dynamically evaluated + code ('Eval Injection') + category: security + owasp: + - A1:2017-Injection + - A03:2021-Injection + source-rule-url: https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-eval-with-expression.js + security-severity: High + primary_identifier: eslint.detect-eval-with-expression + secondary_identifiers: + - name: ESLint rule ID/detect-eval-with-expression + type: eslint_rule_id + value: detect-eval-with-expression + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.eslint.detect-eval-with-expression + shortlink: https://sg.run/ZeD4 + semgrep.dev: + rule: + r_id: 11579 + rv_id: 920150 + rule_id: 10UZgd + version_id: QkT1N0L + url: https://semgrep.dev/playground/r/QkT1N0L/gitlab.eslint.detect-eval-with-expression + origin: community + subcategory: + - audit +- id: gitlab.eslint.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 + primary_identifier: eslint.detect-new-buffer + secondary_identifiers: + - name: ESLint rule ID/detect-new-buffer + type: eslint_rule_id + value: detect-new-buffer + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.eslint.detect-new-buffer + shortlink: https://sg.run/BJ85 + semgrep.dev: + rule: + r_id: 47607 + rv_id: 920148 + rule_id: EwU5PB + version_id: 8KTvl9L + url: https://semgrep.dev/playground/r/8KTvl9L/gitlab.eslint.detect-new-buffer + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.eslint.detect-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 + information comes from user-supplied input, it could be abused to read sensitive files, + access other users' data, or aid in exploitation to gain further system access. + + User input should never be used in constructing paths or files for interacting + with the filesystem. This includes filenames supplied by user uploads or downloads. + If possible, consider hashing user input or using unique values and + use `path.normalize` to resolve and validate the path information + prior to processing any file functionality. + + Example using `path.normalize` and not allowing direct user input: + ``` + // User input, saved only as a reference + // id is a randomly generated UUID to be used as the filename + const userData = {userFilename: userSuppliedFilename, id: crypto.randomUUID()}; + // Restrict all file processing to this directory only + const basePath = '/app/restricted/'; + + // Create the full path, but only use our random generated id as the filename + const joinedPath = path.join(basePath, userData.id); + // Normalize path, removing any '..' + const fullPath = path.normalize(joinedPath); + // Verify the fullPath is contained within our basePath + if (!fullPath.startsWith(basePath)) { + console.log("Invalid path specified!"); + } + // Process / work with file + // ... + ``` + + For more information on path traversal issues see OWASP: + https://owasp.org/www-community/attacks/Path_Traversal + 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 + security-severity: Medium + category: security + primary_identifier: eslint.detect-non-literal-fs-filename + secondary_identifiers: + - name: ESLint rule ID/detect-non-literal-fs-filename + type: eslint_rule_id + value: detect-non-literal-fs-filename + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.eslint.detect-non-literal-fs-filename + shortlink: https://sg.run/L09Y + semgrep.dev: + rule: + r_id: 11583 + rv_id: 920151 + rule_id: bwUO0X + version_id: 3ZTLwQ5 + url: https://semgrep.dev/playground/r/3ZTLwQ5/gitlab.eslint.detect-non-literal-fs-filename + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.eslint.detect-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\nsupply 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 + primary_identifier: eslint.detect-non-literal-regexp + secondary_identifiers: + - name: ESLint rule ID/detect-non-literal-regexp + type: eslint_rule_id + value: detect-non-literal-regexp + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.eslint.detect-non-literal-regexp + shortlink: https://sg.run/70yQ + semgrep.dev: + rule: + r_id: 11582 + rv_id: 920149 + rule_id: r6UkPj + version_id: gETkXxL + url: https://semgrep.dev/playground/r/gETkXxL/gitlab.eslint.detect-non-literal-regexp + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.eslint.detect-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 + 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 + primary_identifier: eslint.detect-non-literal-require + secondary_identifiers: + - name: ESLint rule ID/detect-non-literal-require + type: eslint_rule_id + value: detect-non-literal-require + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.eslint.detect-non-literal-require + shortlink: https://sg.run/5JJ6 + semgrep.dev: + rule: + r_id: 11903 + rv_id: 920154 + rule_id: 3qUEE5 + version_id: JdToRpY + url: https://semgrep.dev/playground/r/JdToRpY/gitlab.eslint.detect-non-literal-require + origin: community + subcategory: + - audit +- id: gitlab.eslint.detect-object-injection + patterns: + - pattern: "$O[$ARG]" + - pattern-not: $O["..."] + - pattern-not: "$O[($ARG : float)]" + - pattern-not-inside: | + $ARG = [$V]; + ... + <... $O[$ARG] ...>; + - pattern-not-inside: | + $ARG = $V; + ... + <... $O[$ARG] ...>; + - metavariable-regex: + metavariable: "$ARG" + regex: "(?![0-9]+)" + message: Bracket object notation with user input is present, this might allow an + attacker to access all properties of the object and even it's prototype, leading + to possible code execution. + languages: + - javascript + - typescript + severity: WARNING + metadata: + cwe: 'CWE-94: Improper Control of Generation of Code (''Code Injection'')' + primary_identifier: eslint.detect-object-injection + secondary_identifiers: + - name: ESLint rule ID security/detect-object-injection + type: eslint_rule_id + value: security/detect-object-injection + license: MIT + source: https://semgrep.dev/r/gitlab.eslint.detect-object-injection + shortlink: https://sg.run/8nbQ + semgrep.dev: + rule: + r_id: 11584 + rv_id: 56280 + rule_id: NbUAnd + version_id: rxTqor + url: https://semgrep.dev/playground/r/rxTqor/gitlab.eslint.detect-object-injection + origin: community + category: security + subcategory: + - audit +- id: gitlab.eslint.detect-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) { + ... + } + - pattern: | + if ($X == password) { + ... + } + - pattern: | + if (password === $X) { + ... + } + - pattern: | + if ($X === password) { + ... + } + - pattern: | + if (pass == $X) { + ... + } + - pattern: | + if ($X == pass) { + ... + } + - pattern: | + if (pass === $X) { + ... + } + - pattern: | + if ($X === pass) { + ... + } + - pattern: | + if (secret == $X) { + ... + } + - pattern: | + if ($X == secret) { + ... + } + - pattern: | + if (secret === $X) { + ... + } + - pattern: | + if ($X === secret) { + ... + } + - pattern: | + if (api == $X) { + ... + } + - pattern: | + if ($X == api) { + ... + } + - pattern: | + if (api === $X) { + ... + } + - pattern: | + if ($X === api) { + ... + } + - pattern: | + if (apiKey == $X) { + ... + } + - pattern: | + if ($X == apiKey) { + ... + } + - pattern: | + if (apiKey === $X) { + ... + } + - pattern: | + if ($X === apiKey) { + ... + } + - pattern: | + if (apiSecret == $X) { + ... + } + - pattern: | + if ($X == apiSecret) { + ... + } + - pattern: | + if (apiSecret === $X) { + ... + } + - pattern: | + if ($X === apiSecret) { + ... + } + - pattern: | + if (token == $X) { + ... + } + - pattern: | + if ($X == token) { + ... + } + - pattern: | + if (token === $X) { + ... + } + - pattern: | + if ($X === token) { + ... + } + - pattern: | + if (hash == $X) { + ... + } + - pattern: | + if ($X == hash) { + ... + } + - pattern: | + if (hash === $X) { + ... + } + - pattern: | + if ($X === hash) { + ... + } + - pattern: | + if (auth_token == $X) { + ... + } + - pattern: | + if ($X == auth_token) { + ... + } + - pattern: | + if (auth_token === $X) { + ... + } + - pattern: | + if ($X === auth_token) { + ... + } + - pattern: | + if (password != $X) { + ... + } + - pattern: | + if ($X != password) { + ... + } + - pattern: | + if (password !== $X) { + ... + } + - pattern: | + if ($X !== password) { + ... + } + - pattern: | + if (pass != $X) { + ... + } + - pattern: | + if ($X != pass) { + ... + } + - pattern: | + if (pass !== $X) { + ... + } + - pattern: | + if ($X !== pass) { + ... + } + - pattern: | + if (secret != $X) { + ... + } + - pattern: | + if ($X != secret) { + ... + } + - pattern: | + if (secret !== $X) { + ... + } + - pattern: | + if ($X !== secret) { + ... + } + - pattern: | + if (api != $X) { + ... + } + - pattern: | + if ($X != api) { + ... + } + - pattern: | + if (api !== $X) { + ... + } + - pattern: | + if ($X !== api) { + ... + } + - pattern: | + if (apiKey != $X) { + ... + } + - pattern: | + if ($X != apiKey) { + ... + } + - pattern: | + if (apiKey !== $X) { + ... + } + - pattern: | + if ($X !== apiKey) { + ... + } + - pattern: | + if (apiSecret != $X) { + ... + } + - pattern: | + if ($X != apiSecret) { + ... + } + - pattern: | + if (apiSecret !== $X) { + ... + } + - pattern: | + if ($X !== apiSecret) { + ... + } + - pattern: | + if (token != $X) { + ... + } + - pattern: | + if ($X != token) { + ... + } + - pattern: | + if (token !== $X) { + ... + } + - pattern: | + if ($X !== token) { + ... + } + - pattern: | + if (hash != $X) { + ... + } + - pattern: | + if ($X != hash) { + ... + } + - pattern: | + if (hash !== $X) { + ... + } + - pattern: | + if ($X !== hash) { + ... + } + - pattern: | + if (auth_token != $X) { + ... + } + - pattern: | + if ($X != auth_token) { + ... + } + - pattern: | + if (auth_token !== $X) { + ... + } + - pattern: | + if ($X !== auth_token) { + ... + } + - 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 `!=` + against security sensitive values. String comparisons like this are not constant time, meaning + the + first character found not to match in the two strings will immediately exit the conditional + statement. + This allows an adversary to calculate or observe small timing differences depending on the + strings + passed to this comparison. This potentially allows an adversary the ability to brute force a + string + that will match the expected value by monitoring different character values. + + To remediate this issue, use the `crypto.timingSafeEqual` method when comparing strings. + + Example using `crypto.timingSafeEqual` to safely compare strings: + ``` + function constantTimeIsPasswordEqual(userInput) { + // Retrieve the password from a secure data store such as a KMS or Hashicorp's vault. + const password = getPasswordFromSecureDataStore(); + // Use crypto timingSafeEqual to ensure the comparison is done in constant time. + return crypto.timingSafeEqual(Buffer.from(userInput, 'utf-8'), Buffer.from(password, + 'utf-8')); + } + ``` + + For more information on constant time comparison see: + - https://nodejs.org/api/crypto.html#crypto_crypto_timingsafeequal_a_b + metadata: + cwe: CWE-208 + shortDescription: Observable timing discrepancy + category: security + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: Medium + primary_identifier: eslint.detect-possible-timing-attacks + secondary_identifiers: + - name: ESLint rule ID/detect-possible-timing-attacks + type: eslint_rule_id + value: detect-possible-timing-attacks + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.eslint.detect-possible-timing-attacks + shortlink: https://sg.run/GwwB + semgrep.dev: + rule: + r_id: 11904 + rv_id: 920155 + rule_id: 4bU22N + version_id: 5PTNGAR + url: https://semgrep.dev/playground/r/5PTNGAR/gitlab.eslint.detect-possible-timing-attacks + origin: community + subcategory: + - audit +- id: gitlab.eslint.detect-pseudoRandomBytes + 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 + source-rule-url: https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-pseudoRandomBytes.js + security-severity: Medium + primary_identifier: eslint.detect-pseudoRandomBytes + secondary_identifiers: + - name: ESLint rule ID/detect-pseudoRandomBytes + type: eslint_rule_id + value: detect-pseudoRandomBytes + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.eslint.detect-pseudoRandomBytes + shortlink: https://sg.run/P88N + semgrep.dev: + rule: + r_id: 11901 + rv_id: 920152 + rule_id: gxUYYL + version_id: 44TeqlN + url: https://semgrep.dev/playground/r/44TeqlN/gitlab.eslint.detect-pseudoRandomBytes + origin: community + subcategory: + - audit +- id: gitlab.eslint.react-dangerouslysetinnerhtml + languages: + - typescript + - javascript + pattern-either: + - pattern: "<$X dangerouslySetInnerHTML=... />\n" + - pattern: "{dangerouslySetInnerHTML: ...}\n" + 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 `
    context 1
    ` + - Inside attributes: `
    ` + - Inside event attributes `` + - Inside script blocks: `` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: `link` + + 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 + shortDescription: Improper neutralization of input during web page generation + ('Cross-site Scripting') + category: security + security-severity: Medium + primary_identifier: eslint.react-dangerouslysetinnerhtml + secondary_identifiers: + - name: ESLint rule ID/react-dangerouslysetinnerhtml + type: eslint_rule_id + value: react-dangerouslysetinnerhtml + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.eslint.react-dangerouslysetinnerhtml + shortlink: https://sg.run/Awwg + semgrep.dev: + rule: + r_id: 11906 + rv_id: 920153 + rule_id: JDUQQY + version_id: PkTjG1q + url: https://semgrep.dev/playground/r/PkTjG1q/gitlab.eslint.react-dangerouslysetinnerhtml + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.AWS_QUERY_INJECTION-1 + languages: + - java + message: | + Constructing SimpleDB queries containing user input can allow an attacker to view unauthorized + records. + metadata: + category: security + cwe: CWE-943 + shortDescription: Improper Neutralization of Special Elements in Data Query Logic + technology: + - java + primary_identifier: find_sec_bugs.AWS_QUERY_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-AWS_QUERY_INJECTION + type: find_sec_bugs_type + value: AWS_QUERY_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.AWS_QUERY_INJECTION-1 + shortlink: https://sg.run/ALZ6 + semgrep.dev: + rule: + r_id: 21194 + rv_id: 835500 + rule_id: QrU1JP + version_id: xyTNrbE + url: https://semgrep.dev/playground/r/xyTNrbE/gitlab.find_sec_bugs.AWS_QUERY_INJECTION-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sinks: + - patterns: + - pattern-either: + - pattern-inside: | + $REQ = new SelectRequest($QUERY, ...); + ... + $DB.select($REQ); + - pattern-inside: "$DB.select(new SelectRequest($QUERY,...));\n" + - pattern-inside: "$DB.select((SelectRequest $SR).withSelectExpression($QUERY,...));\n" + - pattern: "$QUERY" + - metavariable-pattern: + metavariable: "$DB" + pattern-either: + - pattern: "(AmazonSimpleDB $DB)" + - pattern: "(AmazonSimpleDBClient $DB)" + pattern-sources: + - patterns: + - pattern-inside: | + $FUNC(..., $VAR, ...) { + ... + } + - pattern: "$VAR" + - patterns: + - pattern-inside: | + $FUNC(...) { + ... + $VAR = ... + $X; + ... + } + - pattern: "$VAR" + severity: ERROR +- id: gitlab.find_sec_bugs.BAD_HEXA_CONVERSION-1 + 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(...) { + ... + $B = $B_ARR[...]; + ... + Integer.toHexString($B); + } + - pattern: | + for(...) { + ... + Integer.toHexString($B_ARR[...]); + } + - pattern: | + for(byte $B :$B_ARR) { + ... + Integer.toHexString($B); + } + - pattern: | + while(...) { + ... + Integer.toHexString($B_ARR[...]) + } + - pattern: | + do { + ... + Integer.toHexString($B_ARR[...]) + } while(...) + - pattern: | + while(...) { + ... + $B = $B_ARR[...]; + ... + Integer.toHexString($B); + } + - pattern: | + do { + ... + $B = $B_ARR[...]; + ... + Integer.toHexString($B); + } while(...) + 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 + primary_identifier: find_sec_bugs.BAD_HEXA_CONVERSION-1 + secondary_identifiers: + - name: Find Security Bugs-BAD_HEXA_CONVERSION + type: find_sec_bugs_type + value: BAD_HEXA_CONVERSION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.BAD_HEXA_CONVERSION-1 + shortlink: https://sg.run/kD4K + semgrep.dev: + rule: + r_id: 21228 + rv_id: 920200 + rule_id: 2ZUd06 + version_id: GxToX83 + url: https://semgrep.dev/playground/r/GxToX83/gitlab.find_sec_bugs.BAD_HEXA_CONVERSION-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.BEAN_PROPERTY_INJECTION-1 + languages: + - java + message: | + An attacker can set arbitrary bean properties that can compromise system integrity. An + attacker can leverage this functionality to access special bean properties like + class.classLoader that will allow them to override system properties and potentially execute + arbitrary code. + metadata: + category: security + cwe: CWE-15 + shortDescription: External Control of System or Configuration Setting + technology: + - java + primary_identifier: find_sec_bugs.BEAN_PROPERTY_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-BEAN_PROPERTY_INJECTION + type: find_sec_bugs_type + value: BEAN_PROPERTY_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.BEAN_PROPERTY_INJECTION-1 + shortlink: https://sg.run/Ben9 + semgrep.dev: + rule: + r_id: 21195 + rv_id: 835501 + rule_id: 3qULd8 + version_id: O9TJ7Lz + url: https://semgrep.dev/playground/r/O9TJ7Lz/gitlab.find_sec_bugs.BEAN_PROPERTY_INJECTION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: "$TYPE $FUNC(..., HttpServletRequest $REQ, ...) { ... }" + - pattern-either: + - pattern: | + $MAP.put(..., $REQ.getParameter(...)); + ... + $BEAN_UTIL.populate(..., $MAP); + - pattern: | + while (...) { + ... + $MAP.put(..., $REQ.getParameterValues(...)); + } + ... + $BEAN_UTIL.populate(..., $MAP); + - metavariable-pattern: + metavariable: "$BEAN_UTIL" + pattern-either: + - pattern: "(BeanUtilsBean $B)" + - pattern: new BeanUtilsBean() + - pattern: org.apache.commons.beanutils.BeanUtils + severity: ERROR +- id: gitlab.find_sec_bugs.BLOWFISH_KEY_SIZE-1 + 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 + 1993. Smaller key sizes may make the ciphertext vulnerable to [birthday + attacks](https://en.wikipedia.org/wiki/Birthday_attack). While no known attacks against + Blowfish + exist, it should never be used to encrypt files over 4GB in size. If possible consider + using AES as the instance of `KeyGenerator` instead of Blowfish. + + To remediate the small key size, pass a value such as 256 to the `KeyGenerator.init(keySize)` + method. + + Example setting a larger key size and changing to `KeyGenerator` to AES: + ``` + public static void aesKeyGenerator() throws java.security.NoSuchAlgorithmException { + // Use the AES algorithm for key generation + KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); + + // Set the key size here + keyGenerator.init(256); + + // get the raw bytes of the key + byte[] key = keyGenerator.generateKey().getEncoded(); + + // pass the key bytes to create a SecretKeySpec + SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); + } + ``` + + Example setting a larger key size for Blowfish: + ``` + public static void blowFishKeyGenerator() throws java.security.NoSuchAlgorithmException { + // Use the Blowfish algorithm for key generation + KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish"); + + // Set the key size here + keyGenerator.init(256); + + // get the raw bytes of the key + byte[] key = keyGenerator.generateKey().getEncoded(); + + // pass the key bytes to create a SecretKeySpec + SecretKeySpec secretKeySpec = new SecretKeySpec(key, "Blowfish"); + } + ``` + + For more information on Java Cryptography see: + https://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html + severity: WARNING + metadata: + category: security + shortDescription: Inadequate encryption strength + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + cwe: CWE-326 + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.BLOWFISH_KEY_SIZE-1 + secondary_identifiers: + - name: Find Security Bugs-BLOWFISH_KEY_SIZE + type: find_sec_bugs_type + value: BLOWFISH_KEY_SIZE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.BLOWFISH_KEY_SIZE-1 + shortlink: https://sg.run/NjB1 + semgrep.dev: + rule: + r_id: 21171 + rv_id: 920161 + rule_id: 2ZUd1P + version_id: WrTYnQ4 + url: https://semgrep.dev/playground/r/WrTYnQ4/gitlab.find_sec_bugs.BLOWFISH_KEY_SIZE-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.CIPHER_INTEGRITY-1 + 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 ( + "AES" + "AES/CBC/NoPadding" "AES/CBC/PKCS5Padding" "AES/CBC/PKCS7Padding" + "AES/CFB/NoPadding" "AES/CFB/PKCS5Padding" "AES/CFB/PKCS7Padding" + "AES/CTR/NoPadding" + "AES/ECB/NoPadding" "AES/ECB/PKCS5Padding" "AES/ECB/PKCS7Padding" + "AES/OFB/NoPadding" "AES/OFB/PKCS5Padding" "AES/OFB/PKCS7Padding" + "ARCFOUR" + "DES" + "DES/CBC/NoPadding" "DES/CBC/PKCS5Padding" + "DES/ECB/NoPadding" "DES/ECB/PKCS5Padding" + "DESede" + "DESede/CBC/NoPadding" "DESede/CBC/PKCS5Padding" + "DESede/ECB/NoPadding" "DESede/ECB/PKCS5Padding" + "RC4" + ) + message: | + Cryptographic algorithms provide many different modes of operation, only some of which provide + message integrity. Without message integrity it could be possible for an adversary to attempt + to tamper with the ciphertext which could lead to compromising the encryption key. Newer + algorithms + apply message integrity to validate ciphertext has not been tampered with. + + Instead of using an algorithm that requires configuring a cipher mode, an algorithm + that has built-in message integrity should be used. Consider using `ChaCha20Poly1305` or + `AES-256-GCM` instead. + + 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`: + ``` + public encrypt() throws Exception { + chaChaEncryption("Secret text to encrypt".getBytes(StandardCharsets.UTF_8)); + } + + public SecureRandom getSecureRandomDRBG() throws NoSuchAlgorithmException { + // Use DRBG according to + http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf + return SecureRandom.getInstance("DRBG", + // Security strength in bits (default is 128) + DrbgParameters.instantiation(256, + // Set prediction resistance and re-seeding + DrbgParameters.Capability.PR_AND_RESEED, + // Set the personalization string (optional, not necessary) + "some_personalization_string".getBytes() + ) + ); + } + + public Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[] secretKey) throws + NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, + InvalidAlgorithmParameterException { + // Get a DRBG random number generator instance + SecureRandom random = getSecureRandomDRBG(); + // Create a ChaCha20-Poly1305 cipher instance + Cipher chaChaCipher = Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding"); + // Create our parameterSpec using our ivKey + AlgorithmParameterSpec parameterSpec = new IvParameterSpec(ivKey); + // Create a SecretKeySpec using our secretKey + SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "ChaCha20"); + // Initialize and return the cipher for the provided mode + chaChaCipher.init(mode, secretKeySpec, parameterSpec, random); + return chaChaCipher; + } + + public void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException, + NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + // Get a DRBG random number generator instance + SecureRandom random = getSecureRandomDRBG(); + // Create secretKey + byte[] secretKey = new byte[32]; + random.nextBytes(secretKey); + // Create an IV Key + byte[] ivKey = new byte[12]; + random.nextBytes(ivKey); + + // Create a chaCha encryption cipher instance + Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey); + + // Encrypt the text using ChaCha20Poly1305 + byte[] cipherText = null; + try { + cipherText = chaChaEncryptor.doFinal(plainText); + } catch (IllegalBlockSizeException | BadPaddingException e) { + System.out.println("failed to encrypt text"); + return; + } + System.out.println("encrypted: " + Base64.getEncoder().encodeToString(cipherText)); + + // Create a chaCha decryption cipher instance + Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey); + + // Decrypt the text + byte[] decryptedText = null; + try { + decryptedText = chaChaDecryptor.doFinal(cipherText); + } catch (IllegalBlockSizeException | BadPaddingException e) { + System.out.println("failed to decrypt text"); + return; + } + System.out.println("decrypted: " + new String(decryptedText, StandardCharsets.UTF_8)); + } + ``` + + For more information on Java Cryptography see: + https://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html + 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 + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.CIPHER_INTEGRITY-1 + secondary_identifiers: + - name: Find Security Bugs-CIPHER_INTEGRITY + type: find_sec_bugs_type + value: CIPHER_INTEGRITY + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.CIPHER_INTEGRITY-1 + shortlink: https://sg.run/O4Db + semgrep.dev: + rule: + r_id: 21175 + rv_id: 920165 + rule_id: 9AUAzy + version_id: l4TXDv0 + url: https://semgrep.dev/playground/r/l4TXDv0/gitlab.find_sec_bugs.CIPHER_INTEGRITY-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.COMMAND_INJECTION-1 + 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 + compromise as it may allow an adversary to pass in arbitrary commands or arguments + to be executed. + + User input should never be used in constructing commands or command arguments + to functions which execute OS commands. This includes filenames supplied by + user uploads or downloads. + + Ensure your application does not: + + - Use user-supplied information in the process name to execute. + - Use user-supplied information in an OS command execution function which does + not escape shell meta-characters. + - Use user-supplied information in arguments to OS commands. + + The application should have a hardcoded set of arguments that are to be passed + to OS commands. If filenames are being passed to these functions, it is + recommended that a hash of the filename be used instead, or some other unique + identifier. It is strongly recommended that a native library that implements + the same functionality be used instead of using OS system commands, due to the + risk of unknown attacks against third party commands. + + When specifying the OS command, ensure the application uses the full path + information, otherwise the OS may attempt to look up which process to execute + and could be vulnerable to untrusted search path vulnerabilities (CWE-426). + + Example of safely executing an OS command: + ``` + public static void executeCommand(String userFileData) throws java.io.IOException { + // Generate a random filename, do not use user input + String fileName = UUID.randomUUID().toString(); + // Create a Buffered/FileWriter + BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); + // Write the user content to our random file + writer.write(userFileData); + // Close the file to flush contents + writer.close(); + // Create the process builder with a hardcoded path to the binary, and our randomly + generated filename + ProcessBuilder processBuilder = new ProcessBuilder("/opt/app/path", fileName); + // Start the process + Process process = processBuilder.start(); + // Handle/redirect output of process here + // ... + } + ``` + + For more information on OS command injection, see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html + 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 + technology: + - java + security-severity: High + primary_identifier: find_sec_bugs.COMMAND_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-COMMAND_INJECTION + type: find_sec_bugs_type + value: COMMAND_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.COMMAND_INJECTION-1 + shortlink: https://sg.run/WDoz + semgrep.dev: + rule: + r_id: 21197 + rv_id: 920181 + rule_id: PeUjYP + version_id: w8TkbDA + url: https://semgrep.dev/playground/r/w8TkbDA/gitlab.find_sec_bugs.COMMAND_INJECTION-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.COOKIE_PERSISTENT-1 + languages: + - java + message: | + Storing sensitive data in a persistent cookie for an extended period can lead to a breach of + confidentiality or account compromise. + metadata: + category: security + cwe: CWE-614 + shortDescription: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute + technology: + - java + primary_identifier: find_sec_bugs.COOKIE_PERSISTENT-1 + secondary_identifiers: + - name: Find Security Bugs-COOKIE_PERSISTENT + type: find_sec_bugs_type + value: COOKIE_PERSISTENT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.COOKIE_PERSISTENT-1 + shortlink: https://sg.run/2k6Y + semgrep.dev: + rule: + r_id: 21163 + rv_id: 835467 + rule_id: KxUwpN + version_id: 0bTw30A + url: https://semgrep.dev/playground/r/0bTw30A/gitlab.find_sec_bugs.COOKIE_PERSISTENT-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: "(javax.servlet.http.Cookie $C).setMaxAge($AGE);\n" + - metavariable-comparison: + comparison: "$AGE >= 31536000" + metavariable: "$AGE" + severity: WARNING +- id: gitlab.find_sec_bugs.COOKIE_USAGE-1 + languages: + - java + message: | + The information stored in a custom cookie should not be sensitive or related to the session. + In most cases, sensitive data should only be stored in session and referenced by the user's + session cookie. + metadata: + category: security + cwe: CWE-614 + shortDescription: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute + technology: + - java + primary_identifier: find_sec_bugs.COOKIE_USAGE-1 + secondary_identifiers: + - name: Find Security Bugs-COOKIE_USAGE + type: find_sec_bugs_type + value: COOKIE_USAGE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.COOKIE_USAGE-1 + shortlink: https://sg.run/XWze + semgrep.dev: + rule: + r_id: 21164 + rv_id: 835468 + rule_id: qNUpNY + version_id: K3TrLAp + url: https://semgrep.dev/playground/r/K3TrLAp/gitlab.find_sec_bugs.COOKIE_USAGE-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + $FUNC(..., HttpServletRequest $REQ, ...) { + ... + } + - pattern-either: + - patterns: + - pattern-inside: | + for (Cookie $C : $REQ.getCookies()) { + ... + } + - pattern-either: + - pattern: "$C.getName();" + - pattern: "$C.getValue();" + - pattern: "$C.getPath();" + - pattern: "(Cookie $COOKIE).getName();" + - pattern: "(Cookie $COOKIE).getValue();" + - pattern: "(Cookie $COOKIE).getPath();" + severity: WARNING +- id: gitlab.find_sec_bugs.CRLF_INJECTION_LOGS-1 + languages: + - java + patterns: + - pattern-either: + - pattern: | + $TAINTED = (HttpServletRequest $REQ).getParameter(...); + ... + $LOGGER.$METHOD(...,$TAINTED,...); + - pattern: | + $TAINTED = (HttpServletRequest $REQ).getParameter(...); + ... + $VAR = String.Format(..., $TAINTED,...); + ... + $LOGGER.$METHOD(...,$VAR,...); + - pattern: | + $TAINTED = (HttpServletRequest $REQ).getParameter(...); + ... + $LOGGER.$METHOD(...,String.Format(..., $TAINTED,...),...); + - pattern: | + $TAINTED = (HttpServletRequest $REQ).getParameter(...); + ... + $VAR = ... + $TAINTED + ...; + ... + $LOGGER.$METHOD(...,$VAR,...); + - pattern: | + $TAINTED = (HttpServletRequest $REQ).getParameter(...); + ... + $LOGGER.$METHOD(...,... + $TAINTED + ...,...); + - metavariable-regex: + metavariable: "$METHOD" + regex: "(log|logp|logrb|entering|exiting|fine|finer|finest|info|debug|trace|warn|warning|config|error|severe)" + - metavariable-pattern: + metavariable: "$LOGGER" + pattern-either: + - pattern: "(Logger $LOG)" + - pattern: org.pmw.tinylog.Logger + - pattern: org.apache.log4j.Logger + - pattern: org.apache.logging.log4j.Logger + - pattern: org.slf4j.Logger + - pattern: org.apache.commons.logging.Log + - pattern: java.util.logging.Logger + message: | + The application was found to take data from user input and output it into a logger method. + When data from + an untrusted source is sent to a logger without validation, an attacker could forge log + entries + or include malicious content. If the log file is processed automatically, the attacker can + render the file unusable by corrupting the format of the file or injecting unexpected + characters. An attacker may also inject code or other commands into the log file and take + advantage of a vulnerability in the log processing utility (e.g. command injection or XSS). + + To mitigate this issue, encode values that come from user input with a package such as + [Apache Commons Text](https://commons.apache.org/proper/commons-text/) to escape the input: + ``` + public String escapeValue(String value) { + return StringEscapeUtils.escapeJava(value); + } + ``` + + For more information on log injection see OWASP: + https://owasp.org/www-community/attacks/Log_Injection + severity: ERROR + metadata: + shortDescription: Improper neutralization of CRLF sequences ('CRLF Injection') + category: security + cwe: CWE-93 + technology: + - java + primary_identifier: find_sec_bugs.CRLF_INJECTION_LOGS-1 + secondary_identifiers: + - name: Find Security Bugs-CRLF_INJECTION_LOGS + type: find_sec_bugs_type + value: CRLF_INJECTION_LOGS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.CRLF_INJECTION_LOGS-1 + shortlink: https://sg.run/De7W + semgrep.dev: + rule: + r_id: 21196 + rv_id: 835502 + rule_id: 4bUeor + version_id: e1TDKPQ + url: https://semgrep.dev/playground/r/e1TDKPQ/gitlab.find_sec_bugs.CRLF_INJECTION_LOGS-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.CUSTOM_INJECTION-1 + languages: + - java + patterns: + - pattern-either: + - pattern: | + $QUERY = ... + $VAR + ...; + ... + $ST.executeQuery($QUERY); + - pattern: | + $QUERY = ... + $VAR ; + ... + $ST.executeQuery($QUERY); + - pattern: | + $QUERY = String.format("...",...,$VAR,...); + ... + $ST.executeQuery($QUERY); + - pattern: "$ST.executeQuery((StringBuilder $SB).toString());" + - pattern: "$ST.executeQuery(... + $VAR + ...);" + - pattern: "$ST.executeQuery(... + $VAR);" + - pattern: $ST.executeQuery(...,String.format("...",...,$VAR,...), ...); + - metavariable-pattern: + metavariable: "$ST" + pattern-either: + - pattern: "(java.sql.Statement $ST)" + - pattern: "(org.apache.turbine.om.peer.BasePeer $ST)" + 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: + ``` + // Some userInput + String userInput = "someUserInput"; + // Your connection string + String url = "..."; + // Get a connection from the DB via the DriverManager + Connection conn = DriverManager.getConnection(url); + // Create a prepared statement + PreparedStatement st = conn.prepareStatement("SELECT name FROM table where name=?"); + // Set each parameters value by the index (starting from 1) + st.setString(1, userInput); + // Execute query and get the result set + ResultSet rs = st.executeQuery(); + // Iterate over results + while (rs.next()) { + // Get result for this row at the provided column number (starting from 1) + String result = rs.getString(1); + // ... + } + // Close the ResultSet + rs.close(); + // Close the PreparedStatement + st.close(); + ``` + + For more information on SQL Injection see OWASP: + https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html + severity: WARNING + metadata: + shortDescription: Improper neutralization of special elements used in an SQL command + ('SQL Injection') + category: security + cwe: CWE-89 + technology: + - java + primary_identifier: find_sec_bugs.CUSTOM_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-CUSTOM_INJECTION + type: find_sec_bugs_type + value: CUSTOM_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.CUSTOM_INJECTION-1 + shortlink: https://sg.run/0WpJ + semgrep.dev: + rule: + r_id: 21198 + rv_id: 835504 + rule_id: JDUoqr + version_id: d6TKgNJ + url: https://semgrep.dev/playground/r/d6TKgNJ/gitlab.find_sec_bugs.CUSTOM_INJECTION-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.CUSTOM_INJECTION-2 + languages: + - java + message: | + The method identified is susceptible to injection. The input should be validated and properly + escaped. + metadata: + category: security + cwe: CWE-89 + shortDescription: Improper Neutralization of Special Elements used in an SQL Command + ('SQL Injection') + technology: + - java + primary_identifier: find_sec_bugs.CUSTOM_INJECTION-2 + secondary_identifiers: + - name: Find Security Bugs-CUSTOM_INJECTION + type: find_sec_bugs_type + value: CUSTOM_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.CUSTOM_INJECTION-2 + shortlink: https://sg.run/KyG6 + semgrep.dev: + rule: + r_id: 21199 + rv_id: 835505 + rule_id: 5rUN6G + version_id: ZRTldRY + url: https://semgrep.dev/playground/r/ZRTldRY/gitlab.find_sec_bugs.CUSTOM_INJECTION-2 + origin: community + subcategory: + - audit + patterns: + - pattern-not-inside: 'final String $VAR = ...; + + ' + - pattern-either: + - pattern: '"$SQL_STR" + ... + + ' + - pattern: String.format("$SQL_STR", ...) + - pattern: '"$SQL_STR".concat(...) + + ' + - pattern: (StringBuilder $BUILDER). ... .append("$SQL_STR") + - patterns: + - pattern-inside: | + StringBuilder $BUILDER = new StringBuilder("$SQL_STR"); + ... + - pattern: "$BUILDER.append(...)" + - patterns: + - pattern-inside: | + $QUERY = "$SQL_STR"; + ... + - pattern: "$QUERY += ..." + - metavariable-regex: + metavariable: "$SQL_STR" + regex: "(?i)(select|insert|create|update|alter|delete|drop)\\b" + severity: WARNING +- id: gitlab.find_sec_bugs.CUSTOM_MESSAGE_DIGEST-1 + languages: + - java + patterns: + - pattern: | + class $CLAZZ extends java.security.MessageDigest { + ... + } + 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: + - A6:2017-Security Misconfiguration + - A04:2021-Insecure Design + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.CUSTOM_MESSAGE_DIGEST-1 + secondary_identifiers: + - name: Find Security Bugs-CUSTOM_MESSAGE_DIGEST + type: find_sec_bugs_type + value: CUSTOM_MESSAGE_DIGEST + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.CUSTOM_MESSAGE_DIGEST-1 + shortlink: https://sg.run/vpAR + semgrep.dev: + rule: + r_id: 21177 + rv_id: 920167 + rule_id: r6Ujx4 + version_id: 6xTyXJd + url: https://semgrep.dev/playground/r/6xTyXJd/gitlab.find_sec_bugs.CUSTOM_MESSAGE_DIGEST-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.DANGEROUS_PERMISSION_COMBINATION-1 + 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")) + languages: + - java + 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: Improper privilege management + category: security + cwe: CWE-269 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + confidence: HIGH + security-severity: Medium + primary_identifier: find_sec_bugs.DANGEROUS_PERMISSION_COMBINATION-1 + secondary_identifiers: + - name: Find Security Bugs-DANGEROUS_PERMISSION_COMBINATION + type: find_sec_bugs_type + value: DANGEROUS_PERMISSION_COMBINATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.DANGEROUS_PERMISSION_COMBINATION-1 + shortlink: https://sg.run/2kN5 + semgrep.dev: + rule: + r_id: 21219 + rv_id: 920193 + rule_id: 0oUpO1 + version_id: gETkXOL + url: https://semgrep.dev/playground/r/gETkXOL/gitlab.find_sec_bugs.DANGEROUS_PERMISSION_COMBINATION-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.DEFAULT_HTTP_CLIENT-1 + 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. + + This allows for an adversary who is in between the application and the target host to intercept + potentially sensitive information or transmit malicious data. + + Do not use the `org.apache.http.impl.client.DefaultHttpClient();` as it is deprecated. Instead + use the new `java.net.http.HttpClient` that was introduced in Java 9. + + Example connecting to a host that will automatically do TLS validation: + ``` + // Create a new java.net.http.HttpClient + HttpClient httpClient = HttpClient.newHttpClient(); + // Create a HttpRequest builder + HttpRequest request = HttpRequest.newBuilder() + // Create a URI for a website which requires TLS + .uri(URI.create("https://www.example.com/")) + // Build the request + .build(); + + // Use the httpClient to send the request and use an HttpResponse.BodyHandlers String type + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + // Debug print + System.out.println(response); + ``` + metadata: + shortDescription: Improper certificate validation + category: security + cwe: CWE-295 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: Medium + primary_identifier: find_sec_bugs.DEFAULT_HTTP_CLIENT-1 + secondary_identifiers: + - name: Find Security Bugs-DEFAULT_HTTP_CLIENT + type: find_sec_bugs_type + value: DEFAULT_HTTP_CLIENT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.DEFAULT_HTTP_CLIENT-1 + shortlink: https://sg.run/dPw5 + semgrep.dev: + rule: + r_id: 21178 + rv_id: 920173 + rule_id: bwULG5 + version_id: jQTwjyg + url: https://semgrep.dev/playground/r/jQTwjyg/gitlab.find_sec_bugs.DEFAULT_HTTP_CLIENT-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.DES_USAGE-1 + 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. + 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`: + ``` + public encrypt() throws Exception { + chaChaEncryption("Secret text to encrypt".getBytes(StandardCharsets.UTF_8)); + } + + public SecureRandom getSecureRandomDRBG() throws NoSuchAlgorithmException { + // Use DRBG according to + http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf + return SecureRandom.getInstance("DRBG", + // Security strength in bits (default is 128) + DrbgParameters.instantiation(256, + // Set prediction resistance and re-seeding + DrbgParameters.Capability.PR_AND_RESEED, + // Set the personalization string (optional, not necessary) + "some_personalization_string".getBytes() + ) + ); + } + + public Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[] secretKey) throws + NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, + InvalidAlgorithmParameterException { + // Get a DRBG random number generator instance + SecureRandom random = getSecureRandomDRBG(); + // Create a ChaCha20-Poly1305 cipher instance + Cipher chaChaCipher = Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding"); + // Create our parameterSpec using our ivKey + AlgorithmParameterSpec parameterSpec = new IvParameterSpec(ivKey); + // Create a SecretKeySpec using our secretKey + SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "ChaCha20"); + // Initialize and return the cipher for the provided mode + chaChaCipher.init(mode, secretKeySpec, parameterSpec, random); + return chaChaCipher; + } + + public void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException, + NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + // Get a DRBG random number generator instance + SecureRandom random = getSecureRandomDRBG(); + // Create secretKey + byte[] secretKey = new byte[32]; + random.nextBytes(secretKey); + // Create an IV Key + byte[] ivKey = new byte[12]; + random.nextBytes(ivKey); + + // Create a chaCha encryption cipher instance + Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey); + + // Encrypt the text using ChaCha20Poly1305 + byte[] cipherText = null; + try { + cipherText = chaChaEncryptor.doFinal(plainText); + } catch (IllegalBlockSizeException | BadPaddingException e) { + System.out.println("failed to encrypt text"); + return; + } + System.out.println("encrypted: " + Base64.getEncoder().encodeToString(cipherText)); + + // Create a chaCha decryption cipher instance + Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey); + + // Decrypt the text + byte[] decryptedText = null; + try { + decryptedText = chaChaDecryptor.doFinal(cipherText); + } catch (IllegalBlockSizeException | BadPaddingException e) { + System.out.println("failed to decrypt text"); + return; + } + System.out.println("decrypted: " + new String(decryptedText, StandardCharsets.UTF_8)); + } + ``` + + For more information on Java Cryptography see: + https://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html + severity: WARNING + metadata: + shortDescription: Inadequate encryption strength + category: security + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.DES_USAGE-1 + secondary_identifiers: + - name: Find Security Bugs-DES_USAGE + type: find_sec_bugs_type + value: DES_USAGE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.DES_USAGE-1 + shortlink: https://sg.run/kDnz + semgrep.dev: + rule: + r_id: 21172 + rv_id: 920162 + rule_id: X5UAPg + version_id: 0bTp3lb + url: https://semgrep.dev/playground/r/0bTp3lb/gitlab.find_sec_bugs.DES_USAGE-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.DMI_CONSTANT_DB_PASSWORD-1.HARD_CODE_PASSWORD-3 + languages: + - java + patterns: + - pattern: 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 + technology: + - java + security-severity: Critical + primary_identifier: find_sec_bugs.DMI_CONSTANT_DB_PASSWORD-1.HARD_CODE_PASSWORD-3 + secondary_identifiers: + - name: Find Security Bugs-DMI_CONSTANT_DB_PASSWORD + type: find_sec_bugs_type + value: DMI_CONSTANT_DB_PASSWORD + - name: Find Security Bugs-HARD_CODE_PASSWORD + type: find_sec_bugs_type + value: HARD_CODE_PASSWORD + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.DMI_CONSTANT_DB_PASSWORD-1.HARD_CODE_PASSWORD-3 + shortlink: https://sg.run/qZAx + semgrep.dev: + rule: + r_id: 21212 + rv_id: 920190 + rule_id: 5rUN5O + version_id: 7ZTbRnP + url: https://semgrep.dev/playground/r/7ZTbRnP/gitlab.find_sec_bugs.DMI_CONSTANT_DB_PASSWORD-1.HARD_CODE_PASSWORD-3 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.DMI_EMPTY_DB_PASSWORD-1.HARD_CODE_PASSWORD-2 + 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 + technology: + - java + security-severity: Critical + primary_identifier: find_sec_bugs.DMI_EMPTY_DB_PASSWORD-1.HARD_CODE_PASSWORD-2 + secondary_identifiers: + - name: Find Security Bugs-DMI_EMPTY_DB_PASSWORD + type: find_sec_bugs_type + value: DMI_EMPTY_DB_PASSWORD + - name: Find Security Bugs-HARD_CODE_PASSWORD + type: find_sec_bugs_type + value: HARD_CODE_PASSWORD + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.DMI_EMPTY_DB_PASSWORD-1.HARD_CODE_PASSWORD-2 + shortlink: https://sg.run/lW3j + semgrep.dev: + rule: + r_id: 21213 + rv_id: 920191 + rule_id: GdUow0 + version_id: LjTzeAl + url: https://semgrep.dev/playground/r/LjTzeAl/gitlab.find_sec_bugs.DMI_EMPTY_DB_PASSWORD-1.HARD_CODE_PASSWORD-2 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.ECB_MODE-1 + 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 ( + "AES/ECB/NoPadding" "AES/ECB/PKCS5Padding" + "DES/ECB/NoPadding" "DES/ECB/PKCS5Padding" + "DESede/ECB/NoPadding" "DESede/ECB/PKCS5Padding" + "AES/ECB/PKCS7Padding" + ) + message: | + Cryptographic algorithms provide many different modes of operation, only some of which provide + message integrity. Without message integrity it could be possible for an adversary to attempt + to tamper with the ciphertext which could lead to compromising the encryption key. Newer + algorithms + apply message integrity to validate ciphertext has not been tampered with. + + Instead of using an algorithm that requires configuring a cipher mode, an algorithm + that has built-in message integrity should be used. Consider using `ChaCha20Poly1305` or + `AES-256-GCM` instead. + + 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`: + ``` + public encrypt() throws Exception { + chaChaEncryption("Secret text to encrypt".getBytes(StandardCharsets.UTF_8)); + } + + public SecureRandom getSecureRandomDRBG() throws NoSuchAlgorithmException { + // Use DRBG according to + http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf + return SecureRandom.getInstance("DRBG", + // Security strength in bits (default is 128) + DrbgParameters.instantiation(256, + // Set prediction resistance and re-seeding + DrbgParameters.Capability.PR_AND_RESEED, + // Set the personalization string (optional, not necessary) + "some_personalization_string".getBytes() + ) + ); + } + + public Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[] secretKey) throws + NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, + InvalidAlgorithmParameterException { + // Get a DRBG random number generator instance + SecureRandom random = getSecureRandomDRBG(); + // Create a ChaCha20-Poly1305 cipher instance + Cipher chaChaCipher = Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding"); + // Create our parameterSpec using our ivKey + AlgorithmParameterSpec parameterSpec = new IvParameterSpec(ivKey); + // Create a SecretKeySpec using our secretKey + SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "ChaCha20"); + // Initialize and return the cipher for the provided mode + chaChaCipher.init(mode, secretKeySpec, parameterSpec, random); + return chaChaCipher; + } + + public void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException, + NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + // Get a DRBG random number generator instance + SecureRandom random = getSecureRandomDRBG(); + // Create secretKey + byte[] secretKey = new byte[32]; + random.nextBytes(secretKey); + // Create an IV Key + byte[] ivKey = new byte[12]; + random.nextBytes(ivKey); + + // Create a chaCha encryption cipher instance + Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey); + + // Encrypt the text using ChaCha20Poly1305 + byte[] cipherText = null; + try { + cipherText = chaChaEncryptor.doFinal(plainText); + } catch (IllegalBlockSizeException | BadPaddingException e) { + System.out.println("failed to encrypt text"); + return; + } + System.out.println("encrypted: " + Base64.getEncoder().encodeToString(cipherText)); + + // Create a chaCha decryption cipher instance + Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey); + + // Decrypt the text + byte[] decryptedText = null; + try { + decryptedText = chaChaDecryptor.doFinal(cipherText); + } catch (IllegalBlockSizeException | BadPaddingException e) { + System.out.println("failed to decrypt text"); + return; + } + System.out.println("decrypted: " + new String(decryptedText, StandardCharsets.UTF_8)); + } + ``` + + For more information on Java Cryptography see: + https://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html + 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 + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.ECB_MODE-1 + secondary_identifiers: + - name: Find Security Bugs-ECB_MODE + type: find_sec_bugs_type + value: ECB_MODE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.ECB_MODE-1 + shortlink: https://sg.run/xPDP + semgrep.dev: + rule: + r_id: 21174 + rv_id: 920164 + rule_id: 10U4j4 + version_id: qkTpwx7 + url: https://semgrep.dev/playground/r/qkTpwx7/gitlab.find_sec_bugs.ECB_MODE-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.EL_INJECTION-1 + 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 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 + technology: + - java + security-severity: Info + primary_identifier: find_sec_bugs.EL_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-EL_INJECTION + type: find_sec_bugs_type + value: EL_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.EL_INJECTION-1 + shortlink: https://sg.run/4k1E + semgrep.dev: + rule: + r_id: 21200 + rv_id: 920182 + rule_id: GdUo2e + version_id: xyTdrpd + url: https://semgrep.dev/playground/r/xyTdrpd/gitlab.find_sec_bugs.EL_INJECTION-1 + origin: community + subcategory: + - audit + 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(...)\n" + - pattern-not: '($X.el.ELProcessor $P).eval("...", ...) + + ' + - patterns: + - pattern: "($X.el.ELProcessor $P).getValue(...)\n" + - pattern-not: '($X.el.ELProcessor $P).getValue("...", ...) + + ' + - patterns: + - pattern: "($X.el.ELProcessor $P).setValue(...)\n" + - pattern-not: "($X.el.ELProcessor $P).setValue(\"...\", \"...\") \n" + severity: WARNING +- id: gitlab.find_sec_bugs.EXTERNAL_CONFIG_CONTROL-1 + 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: + - A1:2017-Injection + - A03:2021-Injection + technology: + - java + security-severity: Low + primary_identifier: find_sec_bugs.EXTERNAL_CONFIG_CONTROL-1 + secondary_identifiers: + - name: Find Security Bugs-EXTERNAL_CONFIG_CONTROL + type: find_sec_bugs_type + value: EXTERNAL_CONFIG_CONTROL + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.EXTERNAL_CONFIG_CONTROL-1 + shortlink: https://sg.run/dPZY + semgrep.dev: + rule: + r_id: 21234 + rv_id: 920205 + rule_id: r6UjYJ + version_id: WrTYn34 + url: https://semgrep.dev/playground/r/WrTYn34/gitlab.find_sec_bugs.EXTERNAL_CONFIG_CONTROL-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.FILE_UPLOAD_FILENAME-1 + languages: + - java + message: | + The filename provided by the FileUpload API can be tampered with + which could lead to unauthorized access or file inclusion vulnerabilities. + To mitigate this risk, it is essential to conduct rigorous validation of the + filenames provided by clients. This validation should ensure that the filename + adheres to a predefined structure, is devoid of potentially dangerous characters + (such as forward slashes / and backslashes \), and corresponds to an authorized + file only. + + For example, as a remediation strategy, the application could: + 1. Sanitize Filenames: Create a function to sanitize filenames by removing + or replacing unauthorized characters, including path traversal sequences (../ or ..\). + 2. Allowlist Validation: Implement a allowlist approach, allowing only filenames + that match a specific pattern or are part of a predefined list. + 3. Use Server-Generated Filenames: Rather than relying on client-provided filenames, + generate unique names server-side for storing files. + 4. Verify File Paths: Ensure files are being saved in the correct, + intended directory, and prevent redirection to unauthorized directories. + + Example remediation: + ``` + public class FileUploadHandler { + + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + Part filePart = request.getPart("file"); + String fileName = filePart.getSubmittedFileName(); + + // removes any path information from the filename + String sanitizedFileName = sanitizeFileName(fileName); + if (!isFileNameAllowed(sanitizedFileName)) { + throw new SecurityException("Invalid file name"); + } + + // Generate a unique file name for storage + String storedFileName = UUID.randomUUID().toString() + ".txt"; + + Path targetPath = Paths.get("uploads").resolve(storedFileName); + Files.copy(fileContent, targetPath, StandardCopyOption.REPLACE_EXISTING); + } + + private String sanitizeFileName(String fileName) { + return Paths.get(fileName).getFileName().toString(); + } + + private boolean isFileNameAllowed(String fileName) { + return fileName.matches("[a-zA-Z0-9._-]+"); + } + } + ``` + pattern-either: + - patterns: + - pattern-inside: | + $FILES = (ServletFileUpload $SFU).parseRequest(($X.servlet.http.HttpServletRequest $REQ)); + ... + for(FileItem $ITEM : $FILES) { + ... + } + - 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 + security-severity: Info + category: security + technology: + - java + primary_identifier: find_sec_bugs.FILE_UPLOAD_FILENAME-1 + secondary_identifiers: + - name: Find Security Bugs-FILE_UPLOAD_FILENAME + type: find_sec_bugs_type + value: FILE_UPLOAD_FILENAME + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.FILE_UPLOAD_FILENAME-1 + shortlink: https://sg.run/5Z9l + semgrep.dev: + rule: + r_id: 21191 + rv_id: 920179 + rule_id: L1Uz0W + version_id: NdTeRoN + url: https://semgrep.dev/playground/r/NdTeRoN/gitlab.find_sec_bugs.FILE_UPLOAD_FILENAME-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.FORMAT_STRING_MANIPULATION-1 + 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 + - A03:2021-Injection + security-severity: Medium + primary_identifier: find_sec_bugs.FORMAT_STRING_MANIPULATION-1 + secondary_identifiers: + - name: Find Security Bugs-FORMAT_STRING_MANIPULATION + type: find_sec_bugs_type + value: FORMAT_STRING_MANIPULATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.FORMAT_STRING_MANIPULATION-1 + shortlink: https://sg.run/w4q0 + semgrep.dev: + rule: + r_id: 21229 + rv_id: 920201 + rule_id: X5UA3o + version_id: RGT2xR7 + url: https://semgrep.dev/playground/r/RGT2xR7/gitlab.find_sec_bugs.FORMAT_STRING_MANIPULATION-1 + origin: community + subcategory: + - audit + severity: ERROR +- id: gitlab.find_sec_bugs.HARD_CODE_KEY-1 + pattern-either: + - patterns: + - pattern-not-inside: | + $FUNC(...,byte[] $KEY_BYTES, ...) { + ... + } + - pattern-either: + - pattern: new DESKeySpec((byte[] $KEY_BYTES)); + - pattern: new DESedeKeySpec((byte[] $KEY_BYTES)); + - pattern: new KerberosKey(..., (byte[] $KEY_BYTES), ..., ...); + - pattern: new SecretKeySpec((byte[] $KEY_BYTES), ...); + - pattern: new X509EncodedKeySpec((byte[] $KEY_BYTES)); + - pattern: new PKCS8EncodedKeySpec((byte[] $KEY_BYTES)); + - pattern: new KeyRep(...,(byte[] $KEY_BYTES)); + - pattern: new KerberosTicket(...,(byte[] $KEY_BYTES),...); + - metavariable-pattern: + metavariable: "$KEY_BYTES" + patterns: + - pattern-not-regex: "(null)" + - patterns: + - pattern-not-inside: | + $FUNC(..., BigInteger $PRIVATE_KEY, ...) { + ... + } + - pattern-either: + - pattern: new DSAPrivateKeySpec((BigInteger $PRIVATE_KEY), ...); + - pattern: new DSAPublicKeySpec((BigInteger $PRIVATE_KEY), ...); + - pattern: new DHPrivateKeySpec((BigInteger $PRIVATE_KEY), ...); + - pattern: new DHPublicKeySpec((BigInteger $PRIVATE_KEY), ...); + - pattern: new ECPrivateKeySpec((BigInteger $PRIVATE_KEY), ...); + - pattern: new RSAPrivateKeySpec((BigInteger $PRIVATE_KEY), ...); + - pattern: new RSAMultiPrimePrivateCrtKeySpec((BigInteger $PRIVATE_KEY), ...); + - pattern: new RSAPrivateCrtKeySpec((BigInteger $PRIVATE_KEY), ...); + - pattern: new RSAPublicKeySpec((BigInteger $PRIVATE_KEY), ...); + - metavariable-pattern: + metavariable: "$PRIVATE_KEY" + patterns: + - pattern-not-regex: "(null)" + message: | + Cryptographic keys should not be kept in the source code. The source code can be widely shared + in an enterprise environment, and is certainly shared in open source. To be managed safely, + passwords and secret keys should be stored in separate configuration files or keystores. + languages: + - java + severity: ERROR + metadata: + category: security + cwe: 'CWE-321: Use of Hard-coded Cryptographic Key' + technology: + - java + license: MIT + source: https://semgrep.dev/r/gitlab.find_sec_bugs.HARD_CODE_KEY-1 + shortlink: https://sg.run/Y4yX + semgrep.dev: + rule: + r_id: 21214 + rv_id: 26889 + rule_id: ReU2vo + version_id: rxT4Zk + url: https://semgrep.dev/playground/r/rxT4Zk/gitlab.find_sec_bugs.HARD_CODE_KEY-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.HARD_CODE_KEY-2 + patterns: + - pattern-either: + - pattern: String $VAR = "..."; + - pattern: byte[] $VAR = {...}; + - pattern: byte[] $VAR = new byte[]{...}; + - pattern: char[] $VAR = {...}; + - pattern: char[] $VAR = new char[]{...}; + - metavariable-regex: + metavariable: "$VAR" + regex: "(?i).*(pass|pwd|psw|secret|key|cipher|crypt|des|aes|mac|private|sign|cert).*" + message: | + Cryptographic keys should not be kept in the source code. The source code can be widely shared + in an enterprise environment, and is certainly shared in open source. To be managed safely, + passwords and secret keys should be stored in separate configuration files or keystores. + languages: + - java + severity: WARNING + metadata: + category: security + cwe: 'CWE-321: Use of Hard-coded Cryptographic Key' + technology: + - java + license: MIT + source: https://semgrep.dev/r/gitlab.find_sec_bugs.HARD_CODE_KEY-2 + shortlink: https://sg.run/obGN + semgrep.dev: + rule: + r_id: 21216 + rv_id: 26891 + rule_id: BYUKYz + version_id: NdTo8N + url: https://semgrep.dev/playground/r/NdTo8N/gitlab.find_sec_bugs.HARD_CODE_KEY-2 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.HARD_CODE_KEY-3 + patterns: + - pattern: String $VAR = "$VAL"; + - metavariable-regex: + metavariable: "$VAL" + regex: "(?i).*(password|motdepasse|heslo|adgangskode|wachtwoord|salasana|passwort|passord|senha|geslo|clave|losenord|clave|parola|secret|pwd).*" + message: | + Cryptographic keys should not be kept in the source code. The source code can be widely shared + in an enterprise environment, and is certainly shared in open source. To be managed safely, + passwords and secret keys should be stored in separate configuration files or keystores. + languages: + - java + severity: WARNING + metadata: + category: security + cwe: 'CWE-321: Use of Hard-coded Cryptographic Key' + technology: + - java + license: MIT + source: https://semgrep.dev/r/gitlab.find_sec_bugs.HARD_CODE_KEY-3 + shortlink: https://sg.run/z561 + semgrep.dev: + rule: + r_id: 21217 + rv_id: 26892 + rule_id: DbU28G + version_id: kbTLq6 + url: https://semgrep.dev/playground/r/kbTLq6/gitlab.find_sec_bugs.HARD_CODE_KEY-3 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.HARD_CODE_KEY-4 + patterns: + - pattern-not-inside: | + $FUNC(..., $VAR_NAME, ...) { + ... + } + - pattern-either: + - pattern: "(String $VAR_NAME).equals(...)" + - pattern: "(String $OTHER).equals((String $VAR_NAME))" + - pattern: java.util.Arrays.equals(...,(String $VAR_NAME),...) + - pattern: "(byte[] $VAR_NAME).equals(...)" + - pattern: "(byte[] $OTHER).equals((byte[] $VAR_NAME))" + - pattern: java.util.Arrays.equals(...,(byte[] $VAR_NAME),...) + - pattern: java.lang.Byte.comapre(...,(byte[] $VAR_NAME),...) + - pattern: "(char[] $VAR_NAME).equals(...)" + - pattern: "(char[] $OTHER).equals((char[] $VAR_NAME))" + - pattern: java.util.Arrays.equals(...,(char[] $VAR_NAME),...) + - metavariable-regex: + metavariable: "$VAR_NAME" + regex: "(?i).*(pass|pwd|psw|secret|key|cipher|crypt|des|aes|mac|private|sign|cert).*" + message: | + Cryptographic keys should not be kept in the source code. The source code can be widely shared + in an enterprise environment, and is certainly shared in open source. To be managed safely, + passwords and secret keys should be stored in separate configuration files or keystores. + languages: + - java + severity: WARNING + metadata: + category: security + cwe: 'CWE-321: Use of Hard-coded Cryptographic Key' + technology: + - java + license: MIT + source: https://semgrep.dev/r/gitlab.find_sec_bugs.HARD_CODE_KEY-4 + shortlink: https://sg.run/6kO6 + semgrep.dev: + rule: + r_id: 21215 + rv_id: 26890 + rule_id: AbUNYQ + version_id: bZT9qN + url: https://semgrep.dev/playground/r/bZT9qN/gitlab.find_sec_bugs.HARD_CODE_KEY-4 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.HARD_CODE_PASSWORD-1 + 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 + technology: + - java + security-severity: High + primary_identifier: find_sec_bugs.HARD_CODE_PASSWORD-1 + secondary_identifiers: + - name: Find Security Bugs-HARD_CODE_PASSWORD + type: find_sec_bugs_type + value: HARD_CODE_PASSWORD + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.HARD_CODE_PASSWORD-1 + shortlink: https://sg.run/pNRN + semgrep.dev: + rule: + r_id: 21218 + rv_id: 920192 + rule_id: WAUYxY + version_id: 8KTvlyL + url: https://semgrep.dev/playground/r/8KTvlyL/gitlab.find_sec_bugs.HARD_CODE_PASSWORD-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.HAZELCAST_SYMMETRIC_ENCRYPTION-1 + 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 + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.HAZELCAST_SYMMETRIC_ENCRYPTION-1 + secondary_identifiers: + - name: Find Security Bugs-HAZELCAST_SYMMETRIC_ENCRYPTION + type: find_sec_bugs_type + value: HAZELCAST_SYMMETRIC_ENCRYPTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.HAZELCAST_SYMMETRIC_ENCRYPTION-1 + shortlink: https://sg.run/ZP2L + semgrep.dev: + rule: + r_id: 21179 + rv_id: 920168 + rule_id: NbUe1Z + version_id: o5TK1l7 + url: https://semgrep.dev/playground/r/o5TK1l7/gitlab.find_sec_bugs.HAZELCAST_SYMMETRIC_ENCRYPTION-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.HRS_REQUEST_PARAMETER_TO_COOKIE-1 + languages: + - java + message: | + This code constructs an HTTP Cookie using an untrusted HTTP parameter. If this cookie is added + to an HTTP response, it will allow a HTTP response splitting vulnerability. See + http://en.wikipedia.org/wiki/HTTP_response_splitting for more information. + metadata: + category: security + cwe: CWE-113 + shortDescription: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP + Response Splitting') + technology: + - java + primary_identifier: find_sec_bugs.HRS_REQUEST_PARAMETER_TO_COOKIE-1 + secondary_identifiers: + - name: Find Security Bugs-HRS_REQUEST_PARAMETER_TO_COOKIE + type: find_sec_bugs_type + value: HRS_REQUEST_PARAMETER_TO_COOKIE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.HRS_REQUEST_PARAMETER_TO_COOKIE-1 + shortlink: https://sg.run/1k2Q + semgrep.dev: + rule: + r_id: 21166 + rv_id: 835470 + rule_id: YGUYoN + version_id: l4TyD3P + url: https://semgrep.dev/playground/r/l4TyD3P/gitlab.find_sec_bugs.HRS_REQUEST_PARAMETER_TO_COOKIE-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: | + $STR.replaceAll("$REPLACE_CHAR", "$REPLACER"); + ... + - pattern: "$STR" + - metavariable-regex: + metavariable: "$REPLACER" + regex: ".*^(CRLF).*" + - metavariable-regex: + metavariable: "$REPLACE_CHAR" + regex: "(*CRLF)" + - pattern: org.apache.commons.text.StringEscapeUtils.unescapeJava(...); + 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(...);" + severity: ERROR +- id: gitlab.find_sec_bugs.HRS_REQUEST_PARAMETER_TO_HTTP_HEADER-1 + 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`) + characters are introduced into an HTTP header from user-supplied input. By injecting the + `\r\n` + character sequence, an adversary could potentially modify how the response is interpreted by + the + client or any down stream caching services. This could allow an adversary to poison the cache + data or execute Cross-Site Scripting (XSS) attacks. + + Some Java application servers such as [Apache Tomcat](https://tomcat.apache.org/) will + automatically encode + characters from being set in response headers as a space `0x20` character. If your application + server does + not automatically provide this functionality, user-supplied input that is used in header keys + or values must be + validated. + + Example of validating headers to only allow valid characters: + ``` + // throws an IllegalArgumentException if the provided value contains invalid characters + public void validateHeader(String value) throws IllegalArgumentException { + char[] chars = value.toCharArray(); + + // iterate over every character + for (int i = 0; i < chars.length; i++) { + char c = chars[i]; + + // check for any characters below 0x21 as well as: '"' ',' ';' '\' and 0x7f. + if (c < 0x21 || c == '"' || c == ',' || c == ';' || c == '\\' || c == 0x7f) { + throw new IllegalArgumentException("Invalid character in cookie detected: + {0}".format(Integer.toString(c))); + } + } + } + ``` + + Alternatively, you could use a string escape package such as + [Apache Commons Text](https://commons.apache.org/proper/commons-text/) to escape the input: + ``` + public String escapeValue(String value) { + return StringEscapeUtils.escapeJava(value); + } + ``` + + For more information on response splitting attacks see OWASP: + https://owasp.org/www-community/attacks/HTTP_Response_Splitting + 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 + technology: + - java + security-severity: High + primary_identifier: find_sec_bugs.HRS_REQUEST_PARAMETER_TO_HTTP_HEADER-1 + secondary_identifiers: + - name: Find Security Bugs-HRS_REQUEST_PARAMETER_TO_HTTP_HEADER + type: find_sec_bugs_type + value: HRS_REQUEST_PARAMETER_TO_HTTP_HEADER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.HRS_REQUEST_PARAMETER_TO_HTTP_HEADER-1 + shortlink: https://sg.run/93NR + semgrep.dev: + rule: + r_id: 21167 + rv_id: 920159 + rule_id: 6JUye5 + version_id: BjTKLrR + url: https://semgrep.dev/playground/r/BjTKLrR/gitlab.find_sec_bugs.HRS_REQUEST_PARAMETER_TO_HTTP_HEADER-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.HTTPONLY_COOKIE-1 + languages: + - java + pattern-either: + - patterns: + - pattern: | + javax.servlet.http.Cookie $C = new Cookie(..., ...); + ... + (HttpServletResponse $RESP).addCookie($C); + - pattern-not-inside: | + javax.servlet.http.Cookie $C = new Cookie(..., ...); + ... + $C.setHttpOnly(true); + ... + (HttpServletResponse $RESP).addCookie($C); + - pattern: "(javax.servlet.http.Cookie $C).setHttpOnly(false);" + 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 a `Cookie`: + ``` + // Create an HttpOnly cookie. + Cookie someCookie = new Cookie("SomeCookieName", "SomeValue"); + // Set HttpOnly flag to true + someCookie.setHttpOnly(true); + ``` + + For more information see: + https://jakarta.ee/specifications/servlet/4.0/apidocs/javax/servlet/http/cookie#setHttpOnly-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) + - [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 + cwe: CWE-1004 + technology: + - java + primary_identifier: find_sec_bugs.HTTPONLY_COOKIE-1 + secondary_identifiers: + - name: Find Security Bugs-HTTPONLY_COOKIE + type: find_sec_bugs_type + value: HTTPONLY_COOKIE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.HTTPONLY_COOKIE-1 + shortlink: https://sg.run/z5B0 + semgrep.dev: + rule: + r_id: 21161 + rv_id: 835465 + rule_id: WAUYRb + version_id: DkTGyBj + url: https://semgrep.dev/playground/r/DkTGyBj/gitlab.find_sec_bugs.HTTPONLY_COOKIE-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.HTTP_PARAMETER_POLLUTION-1 + 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 + HTTP Parameter Pollution (HPP) or worse, Server Side Request Forgery (SSRF). This could + allow an adversary to override the value of a URL or a request parameter. HTTP Parameter + Pollution + (HPP) attacks consist of injecting encoded query string delimiters into other existing + parameters. If a web + application does not properly sanitize the user input, an adversary may modify the logic of + these + requests to other applications. + + To remediate this issue, never allow user input directly into creation of a URL or URL + parameter. Consider + using a map to look up user-supplied information and return exact values to be used in the + generation of + requests. + + Example using a map to look up a key to be used in a HTTP request: + ``` + HashMap lookupTable = new HashMap<>(); + lookupTable.put("key1", "value1"); + lookupTable.put("key2", "value2"); + String userInput = request.getParameter("key"); + + // Create a CloseableHttpClient, ideally any requests issued should be done + // out-of-band from the servlet request itself (such as using a separate thread/scheduler + system) + try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { + // Lookup the value from our user input from our lookupTable + String value = lookupTable.getOrDefault(userInput, "value1"); + // Construct the url, with the hardcoded url and only pass in the value from the + lookupTable, + // not direct user input + final HttpGet httpget = new HttpGet("https://example.com/getId?key="+value); + // Execute the request + CloseableHttpResponse clientResponse = httpClient.execute(httpget); + // Read the response + byte[] responseData = clientResponse.getEntity().getContent().readAllBytes(); + // Handle the response + // ... + } + ``` + + If using a map is not possible, the user-supplied input must be encoded prior to use, and + never allow full + URLs: + ``` + // Get user input + String userInput = request.getParameter("key"); + // Encode the string using java.net.URLEncoder with the UTF-8 character set + String encodedString = java.net.URLEncoder.encode(userInput, StandardCharsets.UTF_8); + // Create a CloseableHttpClient, ideally any requests issued should be done + // out-of-band from the servlet request itself (such as using a separate thread/scheduler + system) + try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { + // Construct the url, with the hardcoded url and only pass in the encoded value, never a + full URL + final HttpGet httpget = new HttpGet("https://example.com/getId?key="+encodedString); + // Execute the request + CloseableHttpResponse clientResponse = httpClient.execute(httpget); + // Read the response + byte[] responseData = clientResponse.getEntity().getContent().readAllBytes(); + // handle the response + } + ``` + + For more information on SSRF see OWASP: + https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html + + For more information on HTTP Parameter Pollution see: + https://en.wikipedia.org/wiki/HTTP_parameter_pollution + 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 + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.HTTP_PARAMETER_POLLUTION-1 + secondary_identifiers: + - name: Find Security Bugs-HTTP_PARAMETER_POLLUTION + type: find_sec_bugs_type + value: HTTP_PARAMETER_POLLUTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.HTTP_PARAMETER_POLLUTION-1 + shortlink: https://sg.run/Jw5Q + semgrep.dev: + rule: + r_id: 21202 + rv_id: 920185 + rule_id: AbUNR4 + version_id: vdTvQ88 + url: https://semgrep.dev/playground/r/vdTvQ88/gitlab.find_sec_bugs.HTTP_PARAMETER_POLLUTION-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.HTTP_RESPONSE_SPLITTING-1 + 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`) + characters are introduced into an HTTP header from user-supplied input. By injecting the + `\r\n` + character sequence, an adversary could potentially modify how the response is interpreted by + the + client or any downstream caching services. This could allow an adversary to poison the cache + data or execute Cross-Site Scripting (XSS) attacks. + + Some Java application servers such as [Apache Tomcat](https://tomcat.apache.org/) as of version + 8.0, newer versions of Jetty and other servers that implement the [RFC 6265 Standard](https://datatracker.ietf.org/doc/html/rfc6265) will + disallow `\r' and '\n` characters characters from being set in cookies. If your application server does not + automatically provide this functionality, user-supplied input that is used in cookie keys or + values must be validated. + + Example of validating cookies to only allow valid characters: + ``` + // throws an IllegalArgumentException if the provided value contains invalid characters + public void validateRfc6265CookieValue(String value) throws IllegalArgumentException { + char[] chars = value.toCharArray(); + + // iterate over every character + for (int i = 0; i < chars.length; i++) { + char c = chars[i]; + + // check for any characters below 0x21 as well as: '"' ',' ';' '\' and 0x7f. + if (c < 0x21 || c == '"' || c == ',' || c == ';' || c == '\\' || c == 0x7f) { + throw new IllegalArgumentException("Invalid character in cookie detected: + {0}".format(Integer.toString(c))); + } + } + } + ``` + + Alternatively, you could use a string escape package such as + [Apache Commons Text](https://commons.apache.org/proper/commons-text/) to escape the input: + ``` + public String escapeValue(String value) { + return StringEscapeUtils.escapeJava(value); + } + ``` + + For more information on response splitting attacks see OWASP: + https://owasp.org/www-community/attacks/HTTP_Response_Splitting + 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 + technology: + - java + security-severity: High + primary_identifier: find_sec_bugs.HTTP_RESPONSE_SPLITTING-1 + secondary_identifiers: + - name: Find Security Bugs-HTTP_RESPONSE_SPLITTING + type: find_sec_bugs_type + value: HTTP_RESPONSE_SPLITTING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.HTTP_RESPONSE_SPLITTING-1 + shortlink: https://sg.run/jBZ2 + semgrep.dev: + rule: + r_id: 21165 + rv_id: 920158 + rule_id: lBUX54 + version_id: A8TNl5D + url: https://semgrep.dev/playground/r/A8TNl5D/gitlab.find_sec_bugs.HTTP_RESPONSE_SPLITTING-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.IMPROPER_UNICODE-1 + languages: + - java + message: 'Improper Handling of Unicode Encoding + + ' + metadata: + category: security + confidence: HIGH + cwe: CWE-176 + shortDescription: Improper Handling of Unicode Encoding + primary_identifier: find_sec_bugs.IMPROPER_UNICODE-1 + secondary_identifiers: + - name: Find Security Bugs-IMPROPER_UNICODE + type: find_sec_bugs_type + value: IMPROPER_UNICODE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.IMPROPER_UNICODE-1 + shortlink: https://sg.run/xPlp + semgrep.dev: + rule: + r_id: 21230 + rv_id: 835532 + rule_id: j2UwZp + version_id: pZTXDv2 + url: https://semgrep.dev/playground/r/pZTXDv2/gitlab.find_sec_bugs.IMPROPER_UNICODE-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern-either: + - pattern: | + $S = (String $INPUT).$TRANSFORM(...); + ... + $S.$METHOD(...); + - pattern: "(String $INPUT).$TRANSFORM().$METHOD(...);" + - metavariable-regex: + metavariable: "$METHOD" + regex: "(equals|equalsIgnoreCase|indexOf)" + - metavariable-regex: + metavariable: "$TRANSFORM" + regex: "(toLowerCase|toUpperCase)" + - pattern: java.text.Normalizer.normalize(...); + - pattern: java.net.IDN.toASCII(...); + - pattern: "(URI $U).toASCIIString();" + severity: ERROR +- id: gitlab.find_sec_bugs.INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE-1 + languages: + - java + pattern-either: + - pattern: | + catch(Throwable $E) { + ... + $E.printStackTrace(); + ... + } + - pattern: | + catch(Exception $E) { + ... + $E.printStackTrace(); + ... + } + - pattern: | + catch(Error $E) { + ... + $E.printStackTrace(); + ... + } + - pattern: | + catch(java.io.FileNotFoundException $E) { + ... + $E.printStackTrace(); + ... + } + - pattern: | + catch(java.sql.SQLException $E) { + ... + $E.printStackTrace(); + ... + } + - pattern: | + catch(java.net.BindException $E) { + ... + $E.printStackTrace(); + ... + } + - pattern: | + catch(java.util.ConcurrentModificationException $E) { + ... + $E.printStackTrace(); + ... + } + - pattern: | + catch(javax.naming.InsufficientResourcesException $E) { + ... + $E.printStackTrace(); + ... + } + - pattern: | + catch(java.util.MissingResourceException $E) { + ... + $E.printStackTrace(); + ... + } + - pattern: | + catch(java.util.jar.JarException $E) { + ... + $E.printStackTrace(); + ... + } + - pattern: | + catch(java.security.acl.NotOwnerException $E) { + ... + $E.printStackTrace(); + ... + } + - pattern: | + catch(OutOfMemoryError $E) { + ... + $E.printStackTrace(); + ... + } + - pattern: | + catch(StackOverflowError $E) { + ... + $E.printStackTrace(); + ... + } + message: | + The application was found printing stack information to the default system output. + As stack trace data may contain sensitive information, it is recommended that the + output be logged using a secure logging framework. Log files should also be protected + with proper operating system permission levels. + severity: WARNING + metadata: + shortDescription: Information exposure through an error message + category: security + cwe: CWE-209 + technology: + - java + primary_identifier: find_sec_bugs.INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE-1 + secondary_identifiers: + - name: Find Security Bugs-INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE + type: find_sec_bugs_type + value: INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE-1 + shortlink: https://sg.run/ZPrn + semgrep.dev: + rule: + r_id: 21235 + rv_id: 835537 + rule_id: bwULk7 + version_id: 9lTJ7YE + url: https://semgrep.dev/playground/r/9lTJ7YE/gitlab.find_sec_bugs.INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.INSECURE_COOKIE-1 + 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: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + technology: + - java + security-severity: Low + primary_identifier: find_sec_bugs.INSECURE_COOKIE-1 + secondary_identifiers: + - name: Find Security Bugs-INSECURE_COOKIE + type: find_sec_bugs_type + value: INSECURE_COOKIE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.INSECURE_COOKIE-1 + shortlink: https://sg.run/pNER + semgrep.dev: + rule: + r_id: 21162 + rv_id: 920157 + rule_id: 0oUp4O + version_id: RGT2xk7 + url: https://semgrep.dev/playground/r/RGT2xk7/gitlab.find_sec_bugs.INSECURE_COOKIE-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.INSECURE_SMTP_SSL-1 + 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: | + $E.setSSLOnConnect(true); + ... + $E.setSSLCheckServerIdentity(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 + - A02:2021-Cryptographic Failures + security-severity: Medium + primary_identifier: find_sec_bugs.INSECURE_SMTP_SSL-1 + secondary_identifiers: + - name: Find Security Bugs-INSECURE_SMTP_SSL + type: find_sec_bugs_type + value: INSECURE_SMTP_SSL + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.INSECURE_SMTP_SSL-1 + shortlink: https://sg.run/rNB0 + semgrep.dev: + rule: + r_id: 21225 + rv_id: 920197 + rule_id: oqUKxo + version_id: PkTjGdq + url: https://semgrep.dev/playground/r/PkTjGdq/gitlab.find_sec_bugs.INSECURE_SMTP_SSL-1 + origin: community + subcategory: + - audit + severity: ERROR +- id: gitlab.find_sec_bugs.JAXRS_ENDPOINT-1 + languages: + - java + message: | + This method is part of a REST Web Service (JSR311). The security of this web service should be + analyzed; Authentication, if enforced, should be tested. Access control, if enforced, should be + tested. The inputs should be tracked for potential vulnerabilities. The communication should + ideally be over SSL. + metadata: + category: security + cwe: CWE-20 + shortDescription: Improper Input Validation + technology: + - java + primary_identifier: find_sec_bugs.JAXRS_ENDPOINT-1 + secondary_identifiers: + - name: Find Security Bugs-JAXRS_ENDPOINT + type: find_sec_bugs_type + value: JAXRS_ENDPOINT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.JAXRS_ENDPOINT-1 + shortlink: https://sg.run/QJ0x + semgrep.dev: + rule: + r_id: 21186 + rv_id: 835492 + rule_id: d8U6DE + version_id: 1QTPNWX + url: https://semgrep.dev/playground/r/1QTPNWX/gitlab.find_sec_bugs.JAXRS_ENDPOINT-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: | + $STR.replaceAll("$REPLACE_CHAR", "$REPLACER"); + ... + - pattern: "$STR" + - metavariable-regex: + metavariable: "$REPLACER" + regex: ".*^(CRLF).*" + - metavariable-regex: + metavariable: "$REPLACE_CHAR" + regex: "(*CRLF)" + - pattern: org.apache.commons.text.StringEscapeUtils.unescapeJava(...); + pattern-sinks: + - pattern: return ...; + pattern-sources: + - patterns: + - pattern-inside: | + @javax.ws.rs.Path("...") + $TYPE $FUNC(..., $VAR, ...) { + ... + } + - pattern: "$VAR" + severity: WARNING +- id: gitlab.find_sec_bugs.JAXWS_ENDPOINT-1 + languages: + - java + message: | + This method is part of a SOAP Web Service (JSR224). The security of this web service should be + analyzed; Authentication, if enforced, should be tested. Access control, if enforced, should be + tested. The inputs should be tracked for potential vulnerabilities. The communication should + ideally be over SSL. + metadata: + category: security + cwe: CWE-20 + owasp: A7:2017-Cross-Site Scripting (XSS) + shortDescription: Improper Input Validation + technology: + - java + primary_identifier: find_sec_bugs.JAXWS_ENDPOINT-1 + secondary_identifiers: + - name: Find Security Bugs-JAXWS_ENDPOINT + type: find_sec_bugs_type + value: JAXWS_ENDPOINT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.JAXWS_ENDPOINT-1 + shortlink: https://sg.run/3Qjl + semgrep.dev: + rule: + r_id: 21187 + rv_id: 835493 + rule_id: ZqUewk + version_id: 9lTJ7NE + url: https://semgrep.dev/playground/r/9lTJ7NE/gitlab.find_sec_bugs.JAXWS_ENDPOINT-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: | + $STR.replaceAll("$REPLACE_CHAR", "$REPLACER"); + ... + - pattern: "$STR" + - metavariable-regex: + metavariable: "$REPLACER" + regex: ".*^(CRLF).*" + - metavariable-regex: + metavariable: "$REPLACE_CHAR" + regex: "(*CRLF)" + - pattern: org.apache.commons.text.StringEscapeUtils.unescapeJava(...); + pattern-sinks: + - pattern: return ...; + pattern-sources: + - patterns: + - pattern-inside: | + @javax.jws.WebMethod(...) + $TYPE $FUNC(..., $VAR, ...) { + ... + } + - pattern: "$VAR" + severity: INFO +- id: gitlab.find_sec_bugs.LDAP_ANONYMOUS-1 + 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 + server. It is strongly recommended that the LDAP server be configured with + authentication and restrict what queries users can execute. + + Example code that authenticates with a remote LDAP server and encodes any + user-supplied input: + ``` + // Create a properties to hold the ldap connection details + Properties props = new Properties(); + // Use the com.sun.jndi.ldap.LdapCtxFactory factory provider + props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + // The LDAP server URL + props.put(Context.PROVIDER_URL, "ldap://ldap.example.org:3889"); + // User details for the connection + props.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=example,dc=org"); + // LDAP account password + String ldapAccountPassword = getAccountPasswordFromSecureStoreOrKMS(); + // Pass in the LDAP password + props.put(Context.SECURITY_CREDENTIALS, ldapAccountPassword); + + // Create the LDAPContext + InitialDirContext ldapContext = new InitialDirContext(props); + // Example using SUBTREE_SCOPE SearchControls + SearchControls searchControls = new SearchControls(); + searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); + + // Get user input for query + String userQuery = someUserInput; + // Use searchArguments to hold the user-supplied input + Object[] searchArguments = new Object[]{userQuery}; + // Hardcode the BaseDN, use the {0} format specifier to use the searchArguments array value, + and pass in the search controls. + // searchArguments automatically encode + NamingEnumeration answer = ldapContext.search("dc=example,dc=org", "(cn={0})", + searchArguments, searchControls); + // Process the response answer + while (answer.hasMoreElements()) { + ... + } + ``` + + For information on enabling authentication, please see your LDAP server's + documentation. + + For more information on LDAP Injection see OWASP: + https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html + metadata: + shortDescription: Missing authentication for critical function (LDAP) + category: security + cwe: CWE-306 + owasp: + - A2:2017-Broken Authentication + - A07:2021-Identification and Authentication Failures + security-severity: High + primary_identifier: find_sec_bugs.LDAP_ANONYMOUS-1 + secondary_identifiers: + - name: Find Security Bugs-LDAP_ANONYMOUS + type: find_sec_bugs_type + value: LDAP_ANONYMOUS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.LDAP_ANONYMOUS-1 + shortlink: https://sg.run/0Wrb + semgrep.dev: + rule: + r_id: 21210 + rv_id: 920189 + rule_id: PeUjLD + version_id: ExT1WAv + url: https://semgrep.dev/playground/r/ExT1WAv/gitlab.find_sec_bugs.LDAP_ANONYMOUS-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.LDAP_ENTRY_POISONING-1 + languages: + - java + message: | + Without proper access control, executing an LDAP statement that contains a + user-controlled value can allow an attacker to abuse poorly configured LDAP + context + metadata: + category: security + cwe: CWE-20 + shortDescription: Improper Input Validation + primary_identifier: find_sec_bugs.LDAP_ENTRY_POISONING-1 + secondary_identifiers: + - name: Find Security Bugs-LDAP_ENTRY_POISONING + type: find_sec_bugs_type + value: LDAP_ENTRY_POISONING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.LDAP_ENTRY_POISONING-1 + shortlink: https://sg.run/Ky0d + semgrep.dev: + rule: + r_id: 21211 + rv_id: 835517 + rule_id: JDUog3 + version_id: 5PTyG0d + url: https://semgrep.dev/playground/r/5PTyG0d/gitlab.find_sec_bugs.LDAP_ENTRY_POISONING-1 + origin: community + subcategory: + - audit + patterns: + - pattern: new javax.naming.directory.SearchControls($SCOPE, $CLIMIT, $TLIMIT, $ATTR, + true, $DEREF) + severity: ERROR +- id: gitlab.find_sec_bugs.LDAP_INJECTION-1 + 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(..., $VAR, ...) { + ... + } + - pattern: "$VAR" + - patterns: + - pattern-inside: | + $FUNC(..., $X, ...) { + ... + $VAR = ... + $X; + ... + } + - pattern: "$VAR" + message: | + LDAP injection attacks exploit LDAP queries to influence how data is returned by + the LDAP server. + + Later versions of Java's `InitialDirContext.search` introduced a four argument method, one of + which is the `filterArg` parameter. The `filterArg` will be automatically encoded when + querying + the LDAP server. If this method signature is not available, the application must encode the + LDAP strings manually. + + More details on the four argument `search` method can be found here: + https://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) + + To encode the string manually, it is recommended that all input passed to LDAP querying + systems + encode the following values: + + - Any occurrence of the null character must be escaped as “\00”. + - Any occurrence of the open parenthesis character must be escaped as “\28”. + - Any occurrence of the close parenthesis character must be escaped as “\29”. + - Any occurrence of the asterisk character must be escaped as “\2a”. + - Any occurrence of the backslash character must be escaped as “\5c”. + + Example function that safely encodes user-supplied input to be used in an LDAP query. + ``` + public static String encodeLDAPString(String input) { + // Note the \ character is replaced first + CharSequence[] chars = new CharSequence[] { "\\", "\0", "(", ")", "*" }; + CharSequence[] encoded = new CharSequence[] { "\\5c", "\\00", "\\28", "\\29", "\\2a" }; + // Iterate over each character sequence, replacing the raw value with an encoded version of + it + for (int i = 0; i < chars.length; i++) + { + // re-assign to input + input = input.replace(chars[i], encoded[i]); + } + // return our modified input string + return input; + } + ``` + + Example code that using the `filterArgs` parameter which automatically encodes for us: + ``` + // Create a properties to hold the ldap connection details + Properties props = new Properties(); + // Use the com.sun.jndi.ldap.LdapCtxFactory factory provider + props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + // The LDAP server URL + props.put(Context.PROVIDER_URL, "ldap://ldap.example.org:3889"); + // User details for the connection + props.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=example,dc=org"); + // LDAP account password + String ldapAccountPassword = getAccountPasswordFromSecureStoreOrKMS(); + // Pass in the LDAP password + props.put(Context.SECURITY_CREDENTIALS, ldapAccountPassword); + + // Create the LDAPContext + InitialDirContext ldapContext = new InitialDirContext(props); + // Example using SUBTREE_SCOPE SearchControls + SearchControls searchControls = new SearchControls(); + searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); + + // Get user input for query + String userQuery = someUserInput; + // Use searchArguments to hold the user-supplied input + Object[] searchArguments = new Object[]{userQuery}; + // Hardcode the BaseDN, use the {0} format specifier to use the searchArguments array value, + and pass in the search controls. + // searchArguments automatically encode + NamingEnumeration answer = ldapContext.search("dc=example,dc=org", "(cn={0})", + searchArguments, searchControls); + // Process the response answer + while (answer.hasMoreElements()) { + ... + } + ``` + + For more information on LDAP Injection see OWASP: + https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html + 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 + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.LDAP_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-LDAP_INJECTION + type: find_sec_bugs_type + value: LDAP_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.LDAP_INJECTION-1 + shortlink: https://sg.run/5Z93 + semgrep.dev: + rule: + r_id: 21203 + rv_id: 920186 + rule_id: BYUKEw + version_id: d6T6gvy + url: https://semgrep.dev/playground/r/d6T6gvy/gitlab.find_sec_bugs.LDAP_INJECTION-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.MALICIOUS_XSLT-1 + languages: + - java + mode: taint + pattern-sources: + - patterns: + - pattern-either: + - patterns: + - pattern-inside: | + $FUNC(...,String $VAR, ...) { + ... + } + - pattern-either: + - pattern: new FileInputStream(<... $VAR ...>); + - pattern: getClass().getResourceAsStream(<... $VAR ...>) + - patterns: + - pattern-inside: | + class $CLZ { + String $X = "..."; + ... + } + - pattern-inside: | + $FUNC(...,String $Y, ...) { + ... + } + - 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: Improper neutralization of special elements in output used by + a downstream component ('Injection') + category: security + cwe: CWE-74 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: Medium + primary_identifier: find_sec_bugs.MALICIOUS_XSLT-1 + secondary_identifiers: + - name: Find Security Bugs-MALICIOUS_XSLT + type: find_sec_bugs_type + value: MALICIOUS_XSLT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.MALICIOUS_XSLT-1 + shortlink: https://sg.run/L2KJ + semgrep.dev: + rule: + r_id: 21239 + rv_id: 920208 + rule_id: x8UdB6 + version_id: qkTpwB7 + url: https://semgrep.dev/playground/r/qkTpwB7/gitlab.find_sec_bugs.MALICIOUS_XSLT-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.MODIFICATION_AFTER_VALIDATION-1 + 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 + pattern match, and then calling string modification functions after validation has occurred. + This is usually indicative of a poor input validation strategy as an adversary may attempt to + exploit the removal of characters. + + For example a common mistake in attempting to remove path characters to protect against path + traversal is to match '../' and then remove any matches. However, if an adversary were to + include in their input: '....//' then the `replace` method would replace the first `../` but + cause the leading `..` and trailing `/` to join into the final string of `../`, effectively + bypassing the check. + + To remediate this issue always perform string modifications before any validation of a string. + It is strongly recommended that strings be encoded instead of replaced or removed prior to + validation. + + + Example replaces `..` before validation. Do note this is still not a recommended method for + protecting against directory traversal, always use randomly generated IDs or filenames instead: + ``` + // This is ONLY for demonstration purpose, never use untrusted input + // in paths, always use randomly generated filenames or IDs. + String input = "test../....//dir"; + // Use replaceAll _not_ replace + input = input.replaceAll("\\.\\.", ""); + // Input would be test///dir at this point + // Create a pattern to match on + Pattern pattern = Pattern.compile("\\.\\."); + // Create a matcher + Matcher match = pattern.matcher(input); + // Call find to see if .. is still in our string + if (match.find()) { + throw new Exception(".. detected"); + } + // Use the input (but do not modify the string) + System.out.println(input + " safe"); + ``` + + For more information see Carnegie Mellon University's Secure Coding Guide: + https://wiki.sei.cmu.edu/confluence/display/java/IDS11-J.+Perform+any+string+modifications+before+validation + + 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 + primary_identifier: find_sec_bugs.MODIFICATION_AFTER_VALIDATION-1 + secondary_identifiers: + - name: Find Security Bugs-MODIFICATION_AFTER_VALIDATION + type: find_sec_bugs_type + value: MODIFICATION_AFTER_VALIDATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.MODIFICATION_AFTER_VALIDATION-1 + shortlink: https://sg.run/O4Yp + semgrep.dev: + rule: + r_id: 21231 + rv_id: 920202 + rule_id: 10U4xJ + version_id: A8TNlXD + url: https://semgrep.dev/playground/r/A8TNlXD/gitlab.find_sec_bugs.MODIFICATION_AFTER_VALIDATION-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.NORMALIZATION_AFTER_VALIDATION-1 + patterns: + - pattern: | + $Y = java.util.regex.Pattern.compile("[<>]"); + ... + $Y.matcher($VAR); + ... + java.text.Normalizer.normalize($VAR, ...); + languages: + - java + message: | + The application was found matching a variable during a regular expression + pattern match, and then calling a Unicode normalize function after validation has occurred. + This is usually indicative of a poor input validation strategy as an adversary may attempt to + exploit the normalization process. + + To remediate this issue, always perform Unicode normalization before any validation of a + string. + + Example of normalizing a string before validation: + ``` + // User input possibly containing malicious unicode + String userInput = "\uFE64" + "tag" + "\uFE65"; + // Normalize the input + userInput = Normalizer.normalize(userInput, Normalizer.Form.NFKC); + // Compile our regex pattern looking for < or > characters + Pattern pattern = Pattern.compile("[<>]"); + // Create a matcher from the userInput + Matcher matcher = pattern.matcher(userInput); + // See if the matcher matches + if (matcher.find()) { + // It did so throw an error + throw new Exception("found banned characters in input"); + } + ``` + + For more information see Carnegie Mellon University's Secure Coding Guide: + https://wiki.sei.cmu.edu/confluence/display/java/IDS01-J.+Normalize+strings+before+validating+them + metadata: + shortDescription: 'Incorrect behavior order: validate before canonicalize' + category: security + cwe: CWE-180 + confidence: HIGH + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: Info + primary_identifier: find_sec_bugs.NORMALIZATION_AFTER_VALIDATION-1 + secondary_identifiers: + - name: Find Security Bugs-NORMALIZATION_AFTER_VALIDATION + type: find_sec_bugs_type + value: NORMALIZATION_AFTER_VALIDATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.NORMALIZATION_AFTER_VALIDATION-1 + shortlink: https://sg.run/eJnl + semgrep.dev: + rule: + r_id: 21232 + rv_id: 920203 + rule_id: 9AUAKN + version_id: BjTKLpR + url: https://semgrep.dev/playground/r/BjTKLpR/gitlab.find_sec_bugs.NORMALIZATION_AFTER_VALIDATION-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.NULL_CIPHER-1 + languages: + - java + pattern: new javax.crypto.NullCipher() + message: | + The application was found creating a `NullCipher` instance. `NullCipher` implements the + `Cipher` interface by returning ciphertext identical to the supplied plaintext. This means + any data passed to the `doFinal(...)` or `update(...)` methods will not actually encrypt + the input. + + Remove the NullCipher reference and replace with a legitimate `Cipher` instance such as + `ChaCha20-Poly1305` + + Example using `ChaCha20Poly1305`: + ``` + public encrypt() throws Exception { + chaChaEncryption("Secret text to encrypt".getBytes(StandardCharsets.UTF_8)); + } + + public SecureRandom getSecureRandomDRBG() throws NoSuchAlgorithmException { + // Use DRBG according to + http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf + return SecureRandom.getInstance("DRBG", + // Security strength in bits (default is 128) + DrbgParameters.instantiation(256, + // Set prediction resistance and re-seeding + DrbgParameters.Capability.PR_AND_RESEED, + // Set the personalization string (optional, not necessary) + "some_personalization_string".getBytes() + ) + ); + } + + public Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[] secretKey) throws + NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, + InvalidAlgorithmParameterException { + // Get a DRBG random number generator instance + SecureRandom random = getSecureRandomDRBG(); + // Create a ChaCha20-Poly1305 cipher instance + Cipher chaChaCipher = Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding"); + // Create our parameterSpec using our ivKey + AlgorithmParameterSpec parameterSpec = new IvParameterSpec(ivKey); + // Create a SecretKeySpec using our secretKey + SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "ChaCha20"); + // Initialize and return the cipher for the provided mode + chaChaCipher.init(mode, secretKeySpec, parameterSpec, random); + return chaChaCipher; + } + + public void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException, + NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + // Get a DRBG random number generator instance + SecureRandom random = getSecureRandomDRBG(); + // Create secretKey + byte[] secretKey = new byte[32]; + random.nextBytes(secretKey); + // Create an IV Key + byte[] ivKey = new byte[12]; + random.nextBytes(ivKey); + + // Create a chaCha encryption cipher instance + Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey); + + // Encrypt the text using ChaCha20Poly1305 + byte[] cipherText = null; + try { + cipherText = chaChaEncryptor.doFinal(plainText); + } catch (IllegalBlockSizeException | BadPaddingException e) { + System.out.println("failed to encrypt text"); + return; + } + System.out.println("encrypted: " + Base64.getEncoder().encodeToString(cipherText)); + + // Create a chaCha decryption cipher instance + Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey); + + // Decrypt the text + byte[] decryptedText = null; + try { + decryptedText = chaChaDecryptor.doFinal(cipherText); + } catch (IllegalBlockSizeException | BadPaddingException e) { + System.out.println("failed to decrypt text"); + return; + } + System.out.println("decrypted: " + new String(decryptedText, StandardCharsets.UTF_8)); + } + ``` + + For more information on Java Cryptography see: + https://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html + 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 + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.NULL_CIPHER-1 + secondary_identifiers: + - name: Find Security Bugs-NULL_CIPHER + type: find_sec_bugs_type + value: NULL_CIPHER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.NULL_CIPHER-1 + shortlink: https://sg.run/EzLo + semgrep.dev: + rule: + r_id: 21181 + rv_id: 920170 + rule_id: wdUk3N + version_id: pZTbDyl + url: https://semgrep.dev/playground/r/pZTbDyl/gitlab.find_sec_bugs.NULL_CIPHER-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.OGNL_INJECTION-1 + languages: + - java + mode: taint + pattern-sources: + - patterns: + - pattern-inside: | + $FUNC(..., $VAR, ...) { + ... + } + - metavariable-pattern: + metavariable: "$VAR" + pattern-either: + - pattern: "(String $S)" + - pattern: "(Map $M)" + - pattern: "(Map $M)" + - pattern: "(Map $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 + technology: + - java + security-severity: High + primary_identifier: find_sec_bugs.OGNL_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-OGNL_INJECTION + type: find_sec_bugs_type + value: OGNL_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.OGNL_INJECTION-1 + shortlink: https://sg.run/Gb4n + semgrep.dev: + rule: + r_id: 21204 + rv_id: 920187 + rule_id: DbU2QO + version_id: ZRTedp2 + url: https://semgrep.dev/playground/r/ZRTedp2/gitlab.find_sec_bugs.OGNL_INJECTION-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.OVERLY_PERMISSIVE_FILE_PERMISSION-1 + 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 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 + category: security + confidence: HIGH + security-severity: Medium + primary_identifier: find_sec_bugs.OVERLY_PERMISSIVE_FILE_PERMISSION-1 + secondary_identifiers: + - name: Find Security Bugs-OVERLY_PERMISSIVE_FILE_PERMISSION + type: find_sec_bugs_type + value: OVERLY_PERMISSIVE_FILE_PERMISSION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.OVERLY_PERMISSIVE_FILE_PERMISSION-1 + shortlink: https://sg.run/XW9A + semgrep.dev: + rule: + r_id: 21220 + rv_id: 920194 + rule_id: KxUwyj + version_id: QkT1NwL + url: https://semgrep.dev/playground/r/QkT1NwL/gitlab.find_sec_bugs.OVERLY_PERMISSIVE_FILE_PERMISSION-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.OVERLY_PERMISSIVE_FILE_PERMISSION-2 + languages: + - java + message: 'Overly permissive file permission + + ' + metadata: + category: security + confidence: HIGH + cwe: CWE-732 + shortDescription: Incorrect Permission Assignment for Critical Resource + primary_identifier: find_sec_bugs.OVERLY_PERMISSIVE_FILE_PERMISSION-2 + secondary_identifiers: + - name: Find Security Bugs-OVERLY_PERMISSIVE_FILE_PERMISSION + type: find_sec_bugs_type + value: OVERLY_PERMISSIVE_FILE_PERMISSION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.OVERLY_PERMISSIVE_FILE_PERMISSION-2 + shortlink: https://sg.run/jBgA + semgrep.dev: + rule: + r_id: 21221 + rv_id: 835523 + rule_id: qNUpqB + version_id: WrTdn2y + url: https://semgrep.dev/playground/r/WrTdn2y/gitlab.find_sec_bugs.OVERLY_PERMISSIVE_FILE_PERMISSION-2 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + $PERMS.add($P); + ... + java.nio.file.Files.setPosixFilePermissions(..., $PERMS); + - metavariable-regex: + metavariable: "$P" + regex: "(PosixFilePermission.){0,1}(OTHERS_)" + severity: WARNING +- id: gitlab.find_sec_bugs.PADDING_ORACLE-1 + 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 ( + "AES/CBC/PKCS5Padding" "DES/CBC/PKCS5Padding" "DESede/CBC/PKCS5Padding" "AES/CBC/PKCS7Padding" + ) + message: | + Cryptographic block ciphers can be configured to pad individual blocks if there is not enough + input data to match the size of the block. This specific mode of CBC used in combination with + PKCS5Padding is susceptible to padding oracle attacks. An adversary could potentially decrypt + the message if the system exposed the difference between plaintext with invalid padding or + valid padding. The distinction between valid and invalid padding is usually revealed through + distinct error messages being returned for each condition. + + Consider switching to a more secure cipher that doesn't require padding and builds in message + authentication integrity directly into the algorithm. + + Consider using `ChaCha20Poly1305` or + `AES-256-GCM` instead. + + 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`: + ``` + public encrypt() throws Exception { + chaChaEncryption("Secret text to encrypt".getBytes(StandardCharsets.UTF_8)); + } + + public SecureRandom getSecureRandomDRBG() throws NoSuchAlgorithmException { + // Use DRBG according to + http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf + return SecureRandom.getInstance("DRBG", + // Security strength in bits (default is 128) + DrbgParameters.instantiation(256, + // Set prediction resistance and re-seeding + DrbgParameters.Capability.PR_AND_RESEED, + // Set the personalization string (optional, not necessary) + "some_personalization_string".getBytes() + ) + ); + } + + public Cipher getChaCha20Poly1305(int mode, byte[] ivKey, byte[] secretKey) throws + NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, + InvalidAlgorithmParameterException { + // Get a DRBG random number generator instance + SecureRandom random = getSecureRandomDRBG(); + // Create a ChaCha20-Poly1305 cipher instance + Cipher chaChaCipher = Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding"); + // Create our parameterSpec using our ivKey + AlgorithmParameterSpec parameterSpec = new IvParameterSpec(ivKey); + // Create a SecretKeySpec using our secretKey + SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "ChaCha20"); + // Initialize and return the cipher for the provided mode + chaChaCipher.init(mode, secretKeySpec, parameterSpec, random); + return chaChaCipher; + } + + public void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException, + NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + // Get a DRBG random number generator instance + SecureRandom random = getSecureRandomDRBG(); + // Create secretKey + byte[] secretKey = new byte[32]; + random.nextBytes(secretKey); + // Create an IV Key + byte[] ivKey = new byte[12]; + random.nextBytes(ivKey); + + // Create a chaCha encryption cipher instance + Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, ivKey, secretKey); + + // Encrypt the text using ChaCha20Poly1305 + byte[] cipherText = null; + try { + cipherText = chaChaEncryptor.doFinal(plainText); + } catch (IllegalBlockSizeException | BadPaddingException e) { + System.out.println("failed to encrypt text"); + return; + } + System.out.println("encrypted: " + Base64.getEncoder().encodeToString(cipherText)); + + // Create a chaCha decryption cipher instance + Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, ivKey, secretKey); + + // Decrypt the text + byte[] decryptedText = null; + try { + decryptedText = chaChaDecryptor.doFinal(cipherText); + } catch (IllegalBlockSizeException | BadPaddingException e) { + System.out.println("failed to decrypt text"); + return; + } + System.out.println("decrypted: " + new String(decryptedText, StandardCharsets.UTF_8)); + } + ``` + + For more information on padding oracle attacks see: + https://en.wikipedia.org/wiki/Padding_oracle_attack + + For more information on Java Cryptography see: + https://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html + 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 + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.PADDING_ORACLE-1 + secondary_identifiers: + - name: Find Security Bugs-PADDING_ORACLE + type: find_sec_bugs_type + value: PADDING_ORACLE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.PADDING_ORACLE-1 + shortlink: https://sg.run/eJ3E + semgrep.dev: + rule: + r_id: 21176 + rv_id: 920166 + rule_id: yyUDX2 + version_id: YDTYb2y + url: https://semgrep.dev/playground/r/YDTYb2y/gitlab.find_sec_bugs.PADDING_ORACLE-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.PATH_TRAVERSAL_IN-1 + languages: + - java + message: | + A file is opened to read its content. The filename comes from an input parameter. If an + unfiltered parameter is passed to this file API, files from an arbitrary filesystem location + could be read. This rule identifies potential path traversal vulnerabilities. In many cases, + the constructed file path cannot be controlled by the user. + metadata: + category: security + cwe: CWE-22 + shortDescription: Improper Limitation of a Pathname to a Restricted Directory + ('Path Traversal') + technology: + - java + primary_identifier: find_sec_bugs.PATH_TRAVERSAL_IN-1 + secondary_identifiers: + - name: Find Security Bugs-PATH_TRAVERSAL_IN + type: find_sec_bugs_type + value: PATH_TRAVERSAL_IN + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.PATH_TRAVERSAL_IN-1 + shortlink: https://sg.run/R5KK + semgrep.dev: + rule: + r_id: 21205 + rv_id: 835511 + rule_id: WAUYbb + version_id: gETyX8w + url: https://semgrep.dev/playground/r/gETyX8w/gitlab.find_sec_bugs.PATH_TRAVERSAL_IN-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - pattern: org.apache.commons.io.FilenameUtils.getName(...) + pattern-sinks: + - patterns: + - pattern-inside: "$U = new java.net.URI($VAR)\n" + - 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(...) + - patterns: + - pattern-either: + - pattern-inside: new java.io.File(...,(String $VAR), ...) + - pattern-inside: java.nio.file.Paths.get(...,(String $VAR),...) + - pattern-inside: java.io.File.createTempFile(...,(String $VAR), ...) + - pattern-inside: java.io.File.createTempDirectory(...,(String $VAR),...) + - pattern-inside: java.nio.file.Files.createTempFile(..., (String $VAR), ...) + - pattern-inside: java.nio.file.Files.createTempDirectory(..., (String $VAR), + ...) + - pattern: "$VAR" + pattern-sources: + - patterns: + - pattern-inside: | + $FUNC(String[] $ARGS) { + ... + } + - pattern: "$ARGS[$IDX]" + - patterns: + - pattern-inside: | + $FUNC(..., String $VAR, ...) { + ... + } + - pattern: "$VAR" + severity: ERROR +- id: gitlab.find_sec_bugs.PATH_TRAVERSAL_OUT-1.PATH_TRAVERSAL_OUT-1 + languages: + - java + message: | + A file is opened to write to its contents. The filename comes from an input parameter. If an + unfiltered parameter is passed to this file API, files at an arbitrary filesystem location + could be modified. This rule identifies potential path traversal vulnerabilities. In many + cases, the constructed file path cannot be controlled by the user. + metadata: + category: security + cwe: CWE-22 + shortDescription: Improper Limitation of a Pathname to a Restricted Directory + ('Path Traversal') + technology: + - java + primary_identifier: find_sec_bugs.PATH_TRAVERSAL_OUT-1.PATH_TRAVERSAL_OUT-1 + secondary_identifiers: + - name: Find Security Bugs-PATH_TRAVERSAL_OUT + type: find_sec_bugs_type + value: PATH_TRAVERSAL_OUT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.PATH_TRAVERSAL_OUT-1.PATH_TRAVERSAL_OUT-1 + shortlink: https://sg.run/ALZ4 + semgrep.dev: + rule: + r_id: 21206 + rv_id: 835512 + rule_id: 0oUpvO + version_id: QkTkN34 + url: https://semgrep.dev/playground/r/QkTkN34/gitlab.find_sec_bugs.PATH_TRAVERSAL_OUT-1.PATH_TRAVERSAL_OUT-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - pattern: org.apache.commons.io.FilenameUtils.getName(...) + pattern-sinks: + - patterns: + - pattern-inside: new java.io.FileWriter($PATH, ...) + - pattern: "$PATH" + - patterns: + - pattern-inside: new java.io.FileOutputStream($PATH, ...) + - pattern: "$PATH" + pattern-sources: + - patterns: + - pattern-inside: | + $FUNC(String[] $ARGS) { + ... + } + - pattern: "$ARGS[$IDX]" + - patterns: + - pattern-inside: | + $FUNC(..., String $VAR, ...) { + ... + } + - pattern: "$VAR" + severity: ERROR +- id: gitlab.find_sec_bugs.PERMISSIVE_CORS-1 + languages: + - java + message: | + Prior to HTML5, Web browsers enforced the Same Origin Policy which ensures that in order for + JavaScript to access the contents of a Web page, both the JavaScript and the Web page must + originate from the same domain. Without the Same Origin Policy, a malicious website could serve + up JavaScript that loads sensitive information from other websites using a client's + credentials, cull through it, and communicate it back to the attacker. HTML5 makes it possible + for JavaScript to access data across domains if a new HTTP header called + Access-Control-Allow-Origin is defined. With this header, a Web server defines which other + domains are allowed to access its domain using cross-origin requests. However, caution should + be taken when defining the header because an overly permissive CORS policy will allow a + malicious application to communicate with the victim application in an inappropriate way, + leading to spoofing, data theft, relay and other attacks. + metadata: + category: security + cwe: CWE-942 + shortDescription: Permissive Cross-domain Policy with Untrusted Domains + technology: + - java + primary_identifier: find_sec_bugs.PERMISSIVE_CORS-1 + secondary_identifiers: + - name: Find Security Bugs-PERMISSIVE_CORS + type: find_sec_bugs_type + value: PERMISSIVE_CORS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.PERMISSIVE_CORS-1 + shortlink: https://sg.run/rNJA + semgrep.dev: + rule: + r_id: 21169 + rv_id: 835473 + rule_id: zdUG5y + version_id: 5PTyGld + url: https://semgrep.dev/playground/r/5PTyGld/gitlab.find_sec_bugs.PERMISSIVE_CORS-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: (HttpServletResponse $RES).setHeader("$HEADER", "$VAL") + - pattern: (HttpServletResponse $RES).addHeader("$HEADER", "$VAL") + - metavariable-regex: + metavariable: "$HEADER" + regex: "(?i)(Access-Control-Allow-Origin)" + - metavariable-regex: + metavariable: "$VAL" + regex: "(\\*|null)" + severity: ERROR +- id: gitlab.find_sec_bugs.PERMISSIVE_CORS-2 + 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 + `Access-Control-Allow-Origin` response header. This header is part of the + [Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) CORS + specification. By allowing user input to specify which domains can communicate with this + server, + an adversary could exploit a weakness in this server to force clients to send credentials (such + as session + identifiers) to the adversary's server. + + For the above attack to work, the application would need to suffer from an additional + vulnerability, + such as Cross-Site Scripting (XSS). + + To remediate this issue, do not use user-supplied information when calling + `HttpServletResponse.setHeader` or `HttpServletResponse.addHeader` + for the `Access-Control-Allow-Origin` header's value. Instead, hardcode the allowed domain(s) + and reference them in a lookup + table: + Example allowing dynamic but safe domains in `Access-Control-Allow-Origin`: + + ``` + // this data should be in the class constructor or taken from a trusted datasource + Map allowedDomains = new HashMap(); + allowedDomains.put("sub1", "sub1.example.com"); + allowedDomains.put("sub2", "sub2.example.com"); + + // extract the allowedDomain parameters value as a key to look up which domain to provide + via the allowedDomains map + // if not found, sets sub1 as the default + String headerValue = allowedDomains.getOrDefault(request.getParameter("allowedDomain"), + allowedDomains.get("sub1")); + + // add the header with our trusted sub1.example.com or sub2.example.com domains. + response.addHeader("Access-Control-Allow-Origin", headerValue); + } + ``` + + For more information on `Access-Control-Allow-Origin` see: + https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin + severity: ERROR + metadata: + shortDescription: Permissive cross-domain policy with untrusted domains + cwe: CWE-942 + category: security + owasp: + - A1:2017-Injection + - A03:2021-Injection + technology: + - java + security-severity: Low + primary_identifier: find_sec_bugs.PERMISSIVE_CORS-2 + secondary_identifiers: + - name: Find Security Bugs-PERMISSIVE_CORS + type: find_sec_bugs_type + value: PERMISSIVE_CORS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.PERMISSIVE_CORS-2 + shortlink: https://sg.run/bWNr + semgrep.dev: + rule: + r_id: 21170 + rv_id: 920160 + rule_id: pKUbrw + version_id: DkT2ynA + url: https://semgrep.dev/playground/r/DkT2ynA/gitlab.find_sec_bugs.PERMISSIVE_CORS-2 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.PREDICTABLE_RANDOM-1 + languages: + - java + patterns: + - pattern-either: + - pattern: | + java.util.Random $R = new java.util.Random(); + ... + $R.$METHOD(); + - pattern: "(java.util.Random $R).$METHOD()" + - pattern: new java.util.Random().$METHOD() + - pattern: org.apache.commons.lang.math.RandomUtils.$METHOD() + - pattern: org.apache.commons.lang.RandomStringUtils.$METHOD(...) + - metavariable-regex: + metavariable: "$METHOD" + regex: "^(next|random)" + 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 `DRBG` instance + of `SecureRandom` be used. + + Example using `DRBG` with `SecureRandom`: + ``` + public SecureRandom getSecureRandomDRBG() throws NoSuchAlgorithmException { + // Use DRBG according to + http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf + return SecureRandom.getInstance("DRBG", + // Security strength in bits (default is 128) + DrbgParameters.instantiation(256, + // Set prediction resistance and re-seeding + DrbgParameters.Capability.PR_AND_RESEED, + // Set the personalization string (optional, not necessary) + "some_personalization_string".getBytes() + ) + ); + } + ``` + + For more information on Java Cryptography see: + https://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html + severity: WARNING + metadata: + shortDescription: Use of insufficiently random values + category: security + cwe: CWE-330 + technology: + - java + primary_identifier: find_sec_bugs.PREDICTABLE_RANDOM-1 + secondary_identifiers: + - name: Find Security Bugs-PREDICTABLE_RANDOM + type: find_sec_bugs_type + value: PREDICTABLE_RANDOM + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.PREDICTABLE_RANDOM-1 + shortlink: https://sg.run/1kbD + semgrep.dev: + rule: + r_id: 21222 + rv_id: 835524 + rule_id: lBUXPJ + version_id: 0bTw3Rr + url: https://semgrep.dev/playground/r/0bTw3Rr/gitlab.find_sec_bugs.PREDICTABLE_RANDOM-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.PT_ABSOLUTE_PATH_TRAVERSAL-1 + 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)\n" + - 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 + information comes from user input, it could be abused to read sensitive files, + access other users' data, or aid in exploitation to gain further system access. + + User input should never be used in constructing paths or files for interacting + with the filesystem. This includes filenames supplied by user uploads or downloads. + If possible, consider hashing user input or replacing it with unique values and + use `Path.resolve` to resolve and validate the path information + prior to processing any file functionality. + + Example using `Path.resolve` and not allowing direct user input: + ``` + // Class to store our user data along with a randomly generated file name + public static class UserData { + private String userFileNameUnsafe; + private String fileName; + public UserData(String userFileName) { + this.userFileNameUnsafe = userFileName; + // Generate a random ID for the filename + this.fileName = UUID.randomUUID().toString(); + } + public String getUserFileNameUnsafe() { return userFileNameUnsafe; }; + public String getFileName() { return fileName; }; + } + + public static void main(String[] args) throws Exception { + // User input, saved only as a reference + UserData userData = new UserData("..\\test.txt"); + // Restrict all file processing to this directory only + String base = "/var/app/restricted"; + Path basePath = Paths.get(base); + // Resolve the full path, but only use our random generated filename + Path fullPath = basePath.resolve(userData.getFileName()); + // verify the path is contained within our basePath + if (!fullPath.startsWith(base)) { + throw new Exception("Invalid path specified!"); + } + // process / work with file + } + ``` + + For more information on path traversal issues see OWASP: + https://owasp.org/www-community/attacks/Path_Traversal + 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 + security-severity: Medium + technology: + - java + category: security + primary_identifier: find_sec_bugs.PT_ABSOLUTE_PATH_TRAVERSAL-1 + secondary_identifiers: + - name: Find Security Bugs-PT_ABSOLUTE_PATH_TRAVERSAL + type: find_sec_bugs_type + value: PT_ABSOLUTE_PATH_TRAVERSAL + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.PT_ABSOLUTE_PATH_TRAVERSAL-1 + shortlink: https://sg.run/Ben5 + semgrep.dev: + rule: + r_id: 21207 + rv_id: 920188 + rule_id: KxUwlN + version_id: nWTnNoQ + url: https://semgrep.dev/playground/r/nWTnNoQ/gitlab.find_sec_bugs.PT_ABSOLUTE_PATH_TRAVERSAL-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.PT_RELATIVE_PATH_TRAVERSAL-1 + languages: + - java + message: | + "The software uses an HTTP request parameter to construct a pathname that should be within a + restricted directory, but it does not properly neutralize sequences such as ".." that can + resolve to a location that is outside of that directory. See + http://cwe.mitre.org/data/definitions/23.html for more information." + metadata: + category: security + cwe: CWE-22 + shortDescription: Improper Limitation of a Pathname to a Restricted Directory + ('Path Traversal') + technology: + - java + primary_identifier: find_sec_bugs.PT_RELATIVE_PATH_TRAVERSAL-1 + secondary_identifiers: + - name: Find Security Bugs-PT_RELATIVE_PATH_TRAVERSAL + type: find_sec_bugs_type + value: PT_RELATIVE_PATH_TRAVERSAL + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.PT_RELATIVE_PATH_TRAVERSAL-1 + shortlink: https://sg.run/De5j + semgrep.dev: + rule: + r_id: 21208 + rv_id: 835514 + rule_id: qNUpqY + version_id: 44TQqN3 + url: https://semgrep.dev/playground/r/44TQqN3/gitlab.find_sec_bugs.PT_RELATIVE_PATH_TRAVERSAL-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - pattern: org.apache.commons.io.FilenameUtils.getName(...) + pattern-sinks: + - patterns: + - pattern-inside: "$U = new java.net.URI($VAR)\n" + - 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.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-inside: new java.io.FileWriter($PATH, ...) + - pattern: "$PATH" + - patterns: + - pattern-inside: new java.io.FileOutputStream($PATH, ...) + - pattern: "$PATH" + pattern-sources: + - patterns: + - pattern-inside: | + $P = (HttpServletRequest $REQ).getParameter(...); + ... + - pattern-either: + - pattern: "$P + ..." + - pattern: "... + $P" + severity: WARNING +- id: gitlab.find_sec_bugs.REQUESTDISPATCHER_FILE_DISCLOSURE-1 + 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 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 + security-severity: HIGH + primary_identifier: find_sec_bugs.REQUESTDISPATCHER_FILE_DISCLOSURE-1 + secondary_identifiers: + - name: Find Security Bugs-REQUESTDISPATCHER_FILE_DISCLOSURE + type: find_sec_bugs_type + value: REQUESTDISPATCHER_FILE_DISCLOSURE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.REQUESTDISPATCHER_FILE_DISCLOSURE-1 + shortlink: https://sg.run/Dbp3q + semgrep.dev: + rule: + r_id: 144296 + rv_id: 920183 + rule_id: r6UydB8 + version_id: O9Tv7dX + url: https://semgrep.dev/playground/r/O9Tv7dX/gitlab.find_sec_bugs.REQUESTDISPATCHER_FILE_DISCLOSURE-1 + origin: community + subcategory: + - audit + severity: ERROR +- id: gitlab.find_sec_bugs.REQUESTDISPATCHER_FILE_DISCLOSURE-1.STRUTS_FILE_DISCLOSURE-1.SPRING_FILE_DISCLOSURE-1 + languages: + - java + mode: taint + pattern-sinks: + - patterns: + - pattern: new org.springframework.web.servlet.ModelAndView($FST); + - pattern: "$FST" + - patterns: + - pattern: new org.springframework.web.servlet.ModelAndView($FST, $SND); + - pattern: "$FST" + - patterns: + - pattern: new org.springframework.web.servlet.ModelAndView($FST, $SND, $TRD); + - pattern: "$FST" + - patterns: + - pattern: new org.apache.struts.action.ActionForward($FST) + - pattern: "$FST" + - patterns: + - pattern: new org.apache.struts.action.ActionForward($FST, $SND) + - pattern: "$FST" + - patterns: + - pattern: new org.apache.struts.action.ActionForward($FST, $SND, $TRD) + - pattern: "$SND" + - patterns: + - pattern: new org.apache.struts.action.ActionForward($FST, $SND, $TRD) + - pattern: "$TRD" + - patterns: + - pattern-inside: | + $ACTION = new org.apache.struts.action.ActionForward(); + ... + - pattern: "$ACTION.setPath(...)" + - patterns: + - pattern-inside: | + $MVC = new org.springframework.web.servlet.ModelAndView(); + ... + - pattern: "$MVC.setViewName(...);" + - patterns: + - pattern-inside: | + $REQ = $HTTP.getRequestDispatcher(...); + ... + - pattern-either: + - pattern: "$REQ.include($FST, $SND)" + - pattern: "$REQ.forward($FST, $SND)" + pattern-sources: + - pattern: "(javax.servlet.http.HttpServletRequest $VAR).getParameter(...)" + message: | + The `org.springframework.web.servlet.ModelAndView` class and + `HttpRequest.getRequestDispatcher()`'s `include` and `forward` methods may + potentially allow access to restricted files if called with user-supplied input. + + For Spring MVC, the ModelAndView class looks up a view by name to resolve a `.jsp` + file. If this view name comes from user-supplied input, it could be abused to attempt + to return a JSP view that the user should not have access to. + + 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 lookup table to resolve a view from a Spring MVC application: + ``` + @RequestMapping(value="/mvc", method=RequestMethod.GET) + public ModelAndView mvc(HttpServletRequest request, HttpServletResponse response, Model model) + { + // Create a look up table or pull from a data source + HashMap lookupTable = new HashMap<>(); + lookupTable.put("key1", "view1"); + lookupTable.put("key2", "view2"); + // Get user input + String userInput = request.getParameter("key"); + // Look up view from the user input + String viewValue = lookupTable.getOrDefault(userInput, userInput); + // return the new model and view + return new ModelAndView(viewValue); + } + ``` + + Example using a redirect instead of a `RequestDispatcher`: + ``` + // Create a look up table or pull from a data source + HashMap 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 + primary_identifier: find_sec_bugs.REQUESTDISPATCHER_FILE_DISCLOSURE-1.STRUTS_FILE_DISCLOSURE-1.SPRING_FILE_DISCLOSURE-1 + secondary_identifiers: + - name: Find Security Bugs-REQUESTDISPATCHER_FILE_DISCLOSURE + type: find_sec_bugs_type + value: REQUESTDISPATCHER_FILE_DISCLOSURE + - name: Find Security Bugs-STRUTS_FILE_DISCLOSURE + type: find_sec_bugs_type + value: STRUTS_FILE_DISCLOSURE + - name: Find Security Bugs-SPRING_FILE_DISCLOSURE + type: find_sec_bugs_type + value: SPRING_FILE_DISCLOSURE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.REQUESTDISPATCHER_FILE_DISCLOSURE-1.STRUTS_FILE_DISCLOSURE-1.SPRING_FILE_DISCLOSURE-1 + shortlink: https://sg.run/PPWq + semgrep.dev: + rule: + r_id: 21201 + rv_id: 835507 + rule_id: ReU2bl + version_id: ExTrW5W + url: https://semgrep.dev/playground/r/ExTrW5W/gitlab.find_sec_bugs.REQUESTDISPATCHER_FILE_DISCLOSURE-1.STRUTS_FILE_DISCLOSURE-1.SPRING_FILE_DISCLOSURE-1 + origin: community + subcategory: + - audit + severity: ERROR +- id: gitlab.find_sec_bugs.RPC_ENABLED_EXTENSIONS-1 + languages: + - java + message: | + Enabling extensions in Apache XML RPC server or client can lead to deserialization + vulnerability which would allow an attacker to execute arbitrary code. + metadata: + category: security + cwe: CWE-502 + shortDescription: Deserialization of Untrusted Data + primary_identifier: find_sec_bugs.RPC_ENABLED_EXTENSIONS-1 + secondary_identifiers: + - name: Find Security Bugs-RPC_ENABLED_EXTENSIONS + type: find_sec_bugs_type + value: RPC_ENABLED_EXTENSIONS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.RPC_ENABLED_EXTENSIONS-1 + shortlink: https://sg.run/nw5O + semgrep.dev: + rule: + r_id: 21236 + rv_id: 835538 + rule_id: NbUeOb + version_id: yeTNg9z + url: https://semgrep.dev/playground/r/yeTNg9z/gitlab.find_sec_bugs.RPC_ENABLED_EXTENSIONS-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - patterns: + - pattern-inside: | + XmlRpcServerConfigImpl $VAR = new org.apache.xmlrpc.server.XmlRpcServerConfigImpl(); + ... + - pattern: "$VAR.setEnabledForExtensions(true);" + - patterns: + - pattern-inside: | + XmlRpcClientConfigImpl $VAR = new org.apache.xmlrpc.client.XmlRpcClientConfigImpl(); + ... + - pattern: "$VAR.setEnabledForExtensions(true);" + severity: WARNING +- id: gitlab.find_sec_bugs.RSA_KEY_SIZE-1 + 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. + The National Institute of Standards and Technology (NIST) deprecated signing Digital + Certificates that contained RSA Public Keys of 1024 bits in December 2010. While + 1024-bit RSA keys have not been factored yet, advances in compute may make it possible + in the near future. + + Consider upgrading to the newer asymmetric algorithm such as `Ed25519` which handles + the complexities of generating key pairs and choosing correct key sizes for you: + ``` + public static KeyPair generateEd25519() throws NoSuchAlgorithmException { + // Choose Ed25519 for KeyPairGenerator Instance + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("Ed25519"); + // Generate a KeyPair and return + return keyPairGenerator.generateKeyPair(); + } + ``` + + Otherwise use a key size greater than 2048 when generating RSA keys: + ``` + public static KeyPair generateRSA() throws NoSuchAlgorithmException { + // Choose RSA for KeyPairGenerator Instance + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + // Initialize with 2048 key size + keyPairGenerator.initialize(2048); + // Generate a KeyPair and return + return keyPairGenerator.generateKeyPair(); + } + ``` + + For more information on Ed25519 see: http://ed25519.cr.yp.to/ + + For more information on Java Cryptography see: + https://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html + metadata: + shortDescription: Inadequate encryption strength + category: security + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: Medium + primary_identifier: find_sec_bugs.RSA_KEY_SIZE-1 + secondary_identifiers: + - name: Find Security Bugs-RSA_KEY_SIZE + type: find_sec_bugs_type + value: RSA_KEY_SIZE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.RSA_KEY_SIZE-1 + shortlink: https://sg.run/nwLb + semgrep.dev: + rule: + r_id: 21180 + rv_id: 920169 + rule_id: kxUO7W + version_id: zyTG385 + url: https://semgrep.dev/playground/r/zyTG385/gitlab.find_sec_bugs.RSA_KEY_SIZE-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.RSA_NO_PADDING-1 + 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 + Encryption Padding (OAEP). By not enabling padding, the algorithm maybe vulnerable + to [chosen plaintext attacks](https://en.wikipedia.org/wiki/Chosen-plaintext_attack). + + To enable OAEP mode, pass `RSA/ECB/OAEPWithSHA-256AndMGF1Padding` to the `Cipher.getInstance` + method. + + Example encrypting and decrypting a message using RSA with OAEP: + ``` + public static void encryptWithRSA() throws InvalidKeyException, NoSuchAlgorithmException, + NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { + // Generate an RSA Public and Private Key Pair + KeyPair keyPair = generateRSAKeys(); + // Create a Cipher instance using RSA, ECB with OAEP + Cipher rsaEncryptor = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); + // Initialize to ENCRYPT_MODE with the public key + rsaEncryptor.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); + // Encrypt our secret message + byte[] cipherText = rsaEncryptor.doFinal("Some secret + message".getBytes(StandardCharsets.UTF_8)); + + // Create a Cipher instance using RSA, ECB with OAEP + Cipher rsaDecryptor = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); + // Initialize to DECRYPT_MODE with the private key + rsaDecryptor.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); + // Decrypt the secret message + byte[] plainText = rsaDecryptor.doFinal(cipherText); + // Debug output + System.out.println(new String(plainText)); + } + ``` + More information on Optimal asymmetric encryption padding: + https://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding + + For more information on Java Cryptography see: + https://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html + metadata: + shortDescription: Use of RSA algorithm without OAEP + category: security + cwe: CWE-780 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: Medium + primary_identifier: find_sec_bugs.RSA_NO_PADDING-1 + secondary_identifiers: + - name: Find Security Bugs-RSA_NO_PADDING + type: find_sec_bugs_type + value: RSA_NO_PADDING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.RSA_NO_PADDING-1 + shortlink: https://sg.run/7Qr4 + semgrep.dev: + rule: + r_id: 21182 + rv_id: 920171 + rule_id: x8Ud4w + version_id: 2KTdOrW + url: https://semgrep.dev/playground/r/2KTdOrW/gitlab.find_sec_bugs.RSA_NO_PADDING-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.SAML_IGNORE_COMMENTS-1 + 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: Improper authentication + cwe: CWE-287 + category: security + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + primary_identifier: find_sec_bugs.SAML_IGNORE_COMMENTS-1 + secondary_identifiers: + - name: Find Security Bugs-SAML_IGNORE_COMMENTS + type: find_sec_bugs_type + value: SAML_IGNORE_COMMENTS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.SAML_IGNORE_COMMENTS-1 + shortlink: https://sg.run/EzGA + semgrep.dev: + rule: + r_id: 21237 + rv_id: 920206 + rule_id: kxUOAp + version_id: 0bTp3eb + url: https://semgrep.dev/playground/r/0bTp3eb/gitlab.find_sec_bugs.SAML_IGNORE_COMMENTS-1 + origin: community + subcategory: + - audit + pattern: "(org.opensaml.xml.parse.BasicParserPool $POOL).setIgnoreComments(false);" + severity: WARNING +- id: gitlab.find_sec_bugs.SCRIPT_ENGINE_INJECTION-1.SPEL_INJECTION-1.EL_INJECTION-2.SEAM_LOG_INJECTION-1 + 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(..., $VAR, ...) { ... }" + - pattern: "$VAR" + message: | + The application executes an argument using a `ScriptEngine`'s `eval` method. This + may allow for direct OS commands to be executed as it's possible to pass in strings + such as `java.lang.Runtime.getRuntime().exec('/bin/sh ...');`. + + Never pass user-supplied input directly to the `eval` function. If possible hardcode all + JavasScript code or use a lookup table to resolve user input to known values. If none of these + techniques are possible, use `javax.script.Bindings` to pass input to the script engine. + + Example using `Binding` to safely pass in string values: + ``` + // Get ECMAScript engine + ScriptEngine engine = new ScriptEngineManager().getEngineByName("ECMAScript"); + + // User input, consisting of first and last name + String userFirstName = "John"; + String userLastName = "Snow"; + + // Create bindings to pass into our script, forcing the values to be String. + Bindings bindings = engine.createBindings(); + bindings.put("fname", new String(userFirstName)); + bindings.put("lname", new String(userLastName)); + + // Example script that concatenates a greeting with the user-supplied input first/last name + String script = "var greeting='Hello ';" + + // fname and lname variables will be resolved by our bindings defined above + "greeting += fname + ' ' + lname;" + + // prints greeting + "greeting"; + + try { + // Execute the script, passing in the bindings + Object bindingsResult = engine.eval(script, bindings); + // Work with result + // ... + } catch (ScriptException e) { + // Handle exception + e.printStackTrace(); + } + ``` + severity: ERROR + metadata: + shortDescription: Improper control of generation of code ('Code Injection') + category: security + cwe: CWE-94 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + primary_identifier: find_sec_bugs.SCRIPT_ENGINE_INJECTION-1.SPEL_INJECTION-1.EL_INJECTION-2.SEAM_LOG_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-SCRIPT_ENGINE_INJECTION + type: find_sec_bugs_type + value: SCRIPT_ENGINE_INJECTION + - name: Find Security Bugs-SPEL_INJECTION + type: find_sec_bugs_type + value: SPEL_INJECTION + - name: Find Security Bugs-EL_INJECTION + type: find_sec_bugs_type + value: EL_INJECTION + - name: Find Security Bugs-SEAM_LOG_INJECTION + type: find_sec_bugs_type + value: SEAM_LOG_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.SCRIPT_ENGINE_INJECTION-1.SPEL_INJECTION-1.EL_INJECTION-2.SEAM_LOG_INJECTION-1 + shortlink: https://sg.run/93d4 + semgrep.dev: + rule: + r_id: 21223 + rv_id: 920195 + rule_id: YGUYPE + version_id: 3ZTLwr5 + url: https://semgrep.dev/playground/r/3ZTLwr5/gitlab.find_sec_bugs.SCRIPT_ENGINE_INJECTION-1.SPEL_INJECTION-1.EL_INJECTION-2.SEAM_LOG_INJECTION-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.SCRIPT_ENGINE_INJECTION-2 + 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`. + Calling this method directly with user-supplied input may allow an adversary to + execute arbitrary Java code including OS system commands. + + Never call `parseExpression` or `parseRaw` directly with user-supplied input. Consider + alternate + methods such as a lookup table to take user input and resolve hardcoded values. + + Later versions of SpringFramework introduced a `SimpleEvaluationContext` which can be + used to access bound data when calling the `getValue` result of `parseExpression`. This + `SimpleEvaluationContext` has a reduced set of functionality and can restrict data binding + to read-only or read-write contexts. An adversary could still access public properties + or fields on custom types that have been provided to the evaluation context. Use with caution. + + Example using `SimpleEvaluationContext` with a read-write data binding context: + ``` + @RequestMapping(value="/spel", method=RequestMethod.POST) + public String spel(@Validated User user, Model model) { + // Create the Expression Parser + SpelExpressionParser parser = new SpelExpressionParser(); + // Parse the expression + Expression parsedExpression = parser.parseExpression(model.getPossiblyUnsafeData()); + // Create the read-write data binding context + SimpleEvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build(); + // Execute the expression, passing in the read-write context + Object result = parsedExpression.getValue(context); + // work with the result + // ... + return "user"; + } + ``` + + For more information on SimpleEvaluationContext see: + https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/expression/spel/support/SimpleEvaluationContext.html + 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 + security-severity: High + primary_identifier: find_sec_bugs.SCRIPT_ENGINE_INJECTION-2 + secondary_identifiers: + - name: Find Security Bugs-SCRIPT_ENGINE_INJECTION + type: find_sec_bugs_type + value: SCRIPT_ENGINE_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.SCRIPT_ENGINE_INJECTION-2 + shortlink: https://sg.run/yJYr + semgrep.dev: + rule: + r_id: 21224 + rv_id: 920196 + rule_id: 6JUyKR + version_id: 44Teq6N + url: https://semgrep.dev/playground/r/44Teq6N/gitlab.find_sec_bugs.SCRIPT_ENGINE_INJECTION-2 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.SERVLET_PARAMETER-1.SERVLET_CONTENT_TYPE-1.SERVLET_SERVER_NAME-1.SERVLET_SESSION_ID-1.SERVLET_QUERY_STRING-1.SERVLET_HEADER-1.SERVLET_HEADER_REFERER-1.SERVLET_HEADER_USER_AGENT-1 + languages: + - java + message: | + The Servlet can read GET and POST parameters from various methods. The + value obtained should be considered unsafe." + metadata: + category: security + cwe: CWE-20 + shortDescription: Improper Input Validation + primary_identifier: find_sec_bugs.SERVLET_PARAMETER-1.SERVLET_CONTENT_TYPE-1.SERVLET_SERVER_NAME-1.SERVLET_SESSION_ID-1.SERVLET_QUERY_STRING-1.SERVLET_HEADER-1.SERVLET_HEADER_REFERER-1.SERVLET_HEADER_USER_AGENT-1 + secondary_identifiers: + - name: Find Security Bugs-SERVLET_PARAMETER + type: find_sec_bugs_type + value: SERVLET_PARAMETER + - name: Find Security Bugs-SERVLET_CONTENT_TYPE + type: find_sec_bugs_type + value: SERVLET_CONTENT_TYPE + - name: Find Security Bugs-SERVLET_SERVER_NAME + type: find_sec_bugs_type + value: SERVLET_SERVER_NAME + - name: Find Security Bugs-SERVLET_SESSION_ID + type: find_sec_bugs_type + value: SERVLET_SESSION_ID + - name: Find Security Bugs-SERVLET_QUERY_STRING + type: find_sec_bugs_type + value: SERVLET_QUERY_STRING + - name: Find Security Bugs-SERVLET_HEADER + type: find_sec_bugs_type + value: SERVLET_HEADER + - name: Find Security Bugs-SERVLET_HEADER_REFERER + type: find_sec_bugs_type + value: SERVLET_HEADER_REFERER + - name: Find Security Bugs-SERVLET_HEADER_USER_AGENT + type: find_sec_bugs_type + value: SERVLET_HEADER_USER_AGENT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.SERVLET_PARAMETER-1.SERVLET_CONTENT_TYPE-1.SERVLET_SERVER_NAME-1.SERVLET_SESSION_ID-1.SERVLET_QUERY_STRING-1.SERVLET_HEADER-1.SERVLET_HEADER_REFERER-1.SERVLET_HEADER_USER_AGENT-1 + shortlink: https://sg.run/gGey + semgrep.dev: + rule: + r_id: 21185 + rv_id: 835491 + rule_id: v8Uv2D + version_id: jQTrjeN + url: https://semgrep.dev/playground/r/jQTrjeN/gitlab.find_sec_bugs.SERVLET_PARAMETER-1.SERVLET_CONTENT_TYPE-1.SERVLET_SERVER_NAME-1.SERVLET_SESSION_ID-1.SERVLET_QUERY_STRING-1.SERVLET_HEADER-1.SERVLET_HEADER_REFERER-1.SERVLET_HEADER_USER_AGENT-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sinks: + - pattern-either: + - pattern: '"..." + $PAR' + - pattern: $PAR + "..." + pattern-sources: + - pattern-either: + - pattern: "(javax.servlet.http.HttpServletRequest $REQ).getContentType(...)" + - pattern: "(javax.servlet.http.HttpServletRequest $REQ).getServerName(...)" + - pattern: "(javax.servlet.http.HttpServletRequest $REQ).getRequestedSessionId(...)" + - pattern: "(javax.servlet.http.HttpServletRequest $REQ).getParameterValues(...)" + - pattern: "(javax.servlet.http.HttpServletRequest $REQ).getParameterMap(...)" + - pattern: "(javax.servlet.http.HttpServletRequest $REQ).getParameterNames(...)" + - pattern: "(javax.servlet.http.HttpServletRequest $REQ).getParameter(...)" + severity: WARNING +- id: gitlab.find_sec_bugs.SMTP_HEADER_INJECTION-1 + 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 + security-severity: Low + primary_identifier: find_sec_bugs.SMTP_HEADER_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-SMTP_HEADER_INJECTION + type: find_sec_bugs_type + value: SMTP_HEADER_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.SMTP_HEADER_INJECTION-1 + shortlink: https://sg.run/bWve + semgrep.dev: + rule: + r_id: 21226 + rv_id: 920198 + rule_id: zdUGRr + version_id: JdToRvY + url: https://semgrep.dev/playground/r/JdToRvY/gitlab.find_sec_bugs.SMTP_HEADER_INJECTION-1 + origin: community + subcategory: + - audit + severity: ERROR +- id: gitlab.find_sec_bugs.SPRING_CSRF_PROTECTION_DISABLED-1 + languages: + - java + pattern-either: + - pattern: "(org.springframework.security.config.annotation.web.builders.HttpSecurity + $H). ... .csrf().disable();" + - pattern: "(org.springframework.security.config.annotation.web.configurers.CsrfConfigurer + $C).disable();" + message: | + The application fails to protect against Cross-Site Request Forgery (CSRF) + due to disabling Spring's CSRF protection features. + + 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. + + To remediate this issue, remove the call to `HttpSecurity.csrf().disable()` or remove + the custom `CsrfConfigurer`. + + For more information on CSRF protection in Spring see: + https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#servlet-csrf + + 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 + metadata: + shortDescription: Cross-Site Request Forgery (CSRF) + category: security + cwe: CWE-352 + primary_identifier: find_sec_bugs.SPRING_CSRF_PROTECTION_DISABLED-1 + secondary_identifiers: + - name: Find Security Bugs-SPRING_CSRF_PROTECTION_DISABLED + type: find_sec_bugs_type + value: SPRING_CSRF_PROTECTION_DISABLED + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.SPRING_CSRF_PROTECTION_DISABLED-1 + shortlink: https://sg.run/DGLj + semgrep.dev: + rule: + r_id: 47608 + rv_id: 835490 + rule_id: 7KU6jz + version_id: X0T5Ken + url: https://semgrep.dev/playground/r/X0T5Ken/gitlab.find_sec_bugs.SPRING_CSRF_PROTECTION_DISABLED-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.SPRING_FILE_DISCLOSURE-1 + 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(..., "..."); + ... + - 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 + potentially allow access to restricted files if called with user-supplied input. + + The ModelAndView class looks up a view by name to resolve a `.jsp` + file. If this view name comes from user-supplied input, it could be abused to attempt + to return a JSP view that the user should not have access to. + + Use a lookup table or hardcode which views or paths the user should be directed to. + + Example using a lookup table to resolve a view from a Spring MVC application: + ``` + @RequestMapping(value="/mvc", method=RequestMethod.GET) + public ModelAndView mvc(HttpServletRequest request, HttpServletResponse response, Model model) + { + // Create a look up table or pull from a data source + HashMap lookupTable = new HashMap<>(); + lookupTable.put("key1", "view1"); + lookupTable.put("key2", "view2"); + // Get user input + String userInput = request.getParameter("key"); + // Look up view from the user input + String viewValue = lookupTable.getOrDefault(userInput, "Resource1"); + // return the new model and view + return new ModelAndView(viewValue); + } + ``` + + Example using a redirect instead of a `RequestDispatcher` in Spring: + ``` + @RequestMapping(value="/mvc", method=RequestMethod.GET) + public void mvc(HttpServletRequest request, HttpServletResponse response, Model model) + { + // Create a look up table or pull from a data source + HashMap lookupTable = new HashMap<>(); + lookupTable.put("key1", "view1"); + lookupTable.put("key2", "view2"); + // Get user input + String userInput = request.getParameter("key"); + // Look up resource to redirect to from the user input + String redirectValue = lookupTable.getOrDefault(userInput, "/Resource1"); + // return the new model and view + 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 + security-severity: HIGH + primary_identifier: find_sec_bugs.SPRING_FILE_DISCLOSURE-1 + secondary_identifiers: + - name: Find Security Bugs-SPRING_FILE_DISCLOSURE + type: find_sec_bugs_type + value: SPRING_FILE_DISCLOSURE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.SPRING_FILE_DISCLOSURE-1 + shortlink: https://sg.run/WAd5Z + semgrep.dev: + rule: + r_id: 144297 + rv_id: 920184 + rule_id: bwUbpPx + version_id: e1TZK31 + url: https://semgrep.dev/playground/r/e1TZK31/gitlab.find_sec_bugs.SPRING_FILE_DISCLOSURE-1 + origin: community + subcategory: + - audit + severity: ERROR +- id: gitlab.find_sec_bugs.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1 + patterns: + - pattern-not-inside: | + final String $ARG = ...; + ... + - pattern-not-inside: | + class $CLAZZ { + ... + final String $ARG = ...; + ... + } + - pattern-either: + - patterns: + - pattern: "(javax.jdo.PersistenceManager $PM).newQuery($ARG)" + - pattern-not: (javax.jdo.PersistenceManager $PM).newQuery("...") + - patterns: + - pattern: "(javax.jdo.PersistenceManager $PM).newQuery(..., $ARG)" + - pattern-not: (javax.jdo.PersistenceManager $PM).newQuery(..., "...") + - patterns: + - pattern: "(javax.jdo.Query $Q).setFilter($ARG)" + - pattern-not: (javax.jdo.Query $Q).setFilter("...") + - patterns: + - pattern: "(javax.jdo.Query $Q).setGrouping($ARG)" + - pattern-not: (javax.jdo.Query $Q).setGrouping("...") + - patterns: + - pattern: "(javax.jdo.Query $Q).setGrouping($ARG)" + - pattern-not: (javax.jdo.Query $Q).setGrouping("...") + - patterns: + - pattern: "(org.hibernate.criterion.Restrictions $H).sqlRestriction($ARG, ...)" + - pattern-not: (org.hibernate.criterion.Restrictions $H).sqlRestriction("...", + ...) + - patterns: + - pattern: "(org.hibernate.Session $S).createQuery((String $ARG), ...)" + - pattern-not: (org.hibernate.Session $S).createQuery("...", ...) + - patterns: + - pattern: "(org.hibernate.Session $S).createSQLQuery($ARG, ...)" + - pattern-not: (org.hibernate.Session $S).createSQLQuery("...", ...) + - patterns: + - pattern: "(java.sql.Statement $S).executeQuery($ARG, ...)" + - pattern-not: (java.sql.Statement $S).createSQLQuery("...", ...) + - patterns: + - pattern: "(java.sql.Statement $S).execute($ARG, ...)" + - pattern-not: (java.sql.Statement $S).execute("...", ...) + - patterns: + - pattern: "(java.sql.Statement $S).executeUpdate($ARG, ...)" + - pattern-not: (java.sql.Statement $S).executeUpdate("...", ...) + - patterns: + - pattern: "(java.sql.Statement $S).executeLargeUpdate($ARG, ...)" + - pattern-not: (java.sql.Statement $S).executeLargeUpdate("...", ...) + - patterns: + - pattern: "(java.sql.Statement $S).addBatch($ARG, ...)" + - pattern-not: (java.sql.Statement $S).addBatch("...", ...) + - patterns: + - pattern: "(java.sql.PreparedStatement $S).executeQuery($ARG, ...)" + - pattern-not: (java.sql.PreparedStatement $S).executeQuery("...", ...) + - patterns: + - pattern: "(java.sql.PreparedStatement $S).execute($ARG, ...)" + - pattern-not: (java.sql.PreparedStatement $S).execute("...", ...) + - patterns: + - pattern: "(java.sql.PreparedStatement $S).executeUpdate($ARG, ...)" + - pattern-not: (java.sql.PreparedStatement $S).executeUpdate("...", ...) + - patterns: + - pattern: "(java.sql.PreparedStatement $S).executeLargeUpdate($ARG, ...)" + - pattern-not: (java.sql.PreparedStatement $S).executeLargeUpdate("...", ...) + - patterns: + - pattern: "(java.sql.PreparedStatement $S).addBatch($ARG, ...)" + - pattern-not: (java.sql.PreparedStatement $S).addBatch("...", ...) + - patterns: + - pattern: "(java.sql.Connection $S).prepareCall($ARG, ...)" + - pattern-not: (java.sql.Connection $S).prepareCall("...", ...) + - patterns: + - pattern: "(java.sql.Connection $S).prepareStatement($ARG, ...)" + - pattern-not: (java.sql.Connection $S).prepareStatement("...", ...) + - patterns: + - pattern: "(java.sql.Connection $S).nativeSQL($ARG, ...)" + - pattern-not: (java.sql.Connection $S).nativeSQL("...", ...) + - patterns: + - pattern: new org.springframework.jdbc.core.PreparedStatementCreatorFactory($ARG, + ...) + - pattern-not: new org.springframework.jdbc.core.PreparedStatementCreatorFactory("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.PreparedStatementCreatorFactory $F).newPreparedStatementCreator($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.PreparedStatementCreatorFactory + $F).newPreparedStatementCreator("...", ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).batchUpdate($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).batchUpdate("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).execute($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).execute("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).query($ARG, ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).query("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForList($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForList("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForMap($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForMap("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForObject($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForObject("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForObject($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForObject("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForRowSet($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForRowSet("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForInt($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForInt("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForLong($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForLong("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).udpate($ARG, ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).udpate("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).batchUpdate($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).batchUpdate("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).execute($ARG, ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).execute("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).query($ARG, ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).query("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).queryForList($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).queryForList("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).queryForMap($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).queryForMap("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).queryForObject($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).queryForObject("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).queryForRowSet($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).queryForRowSet("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).queryForInt($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).queryForInt("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).queryForLong($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).queryForLong("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).update($ARG, ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).update("...", + ...) + - patterns: + - pattern: "(io.vertx.sqlclient.SqlClient $O).query($ARG, ...)" + - pattern-not: (io.vertx.sqlclient.SqlClient $O).query("...", ...) + - patterns: + - pattern: "(io.vertx.sqlclient.SqlClient $O).preparedQuery($ARG, ...)" + - pattern-not: (io.vertx.sqlclient.SqlClient $O).preparedQuery("...", ...) + - patterns: + - pattern: "(io.vertx.sqlclient.SqlConnection $O).prepare($ARG, ...)" + - pattern-not: (io.vertx.sqlclient.SqlConnection $O).prepare("...", ...) + - patterns: + - pattern: "(org.apache.turbine.om.peer.BasePeer $O).executeQuery($ARG, ...)" + - pattern-not: (org.apache.turbine.om.peer.BasePeer $O).executeQuery("...", + ...) + - patterns: + - pattern: "(org.apache.torque.util.BasePeer $O).executeQuery($ARG, ...)" + - pattern-not: (org.apache.torque.util.BasePeer $O).executeQuery("...", ...) + - patterns: + - pattern: "(javax.persistence.EntityManager $O).createQuery($ARG, ...)" + - pattern-not: (javax.persistence.EntityManager $O).createQuery("...", ...) + - patterns: + - pattern: "(javax.persistence.EntityManager $O).createNativeQuery($ARG, ...)" + - pattern-not: (javax.persistence.EntityManager $O).createNativeQuery("...", + ...) + languages: + - java + message: | + The input values included in SQL queries need to be passed in safely. Bind + variables in prepared statements can be used to easily mitigate the risk of + SQL injection. + metadata: + category: security + cwe: 'CWE-89: Improper Neutralization of Special Elements used in an SQL Command + (''SQL Injection'')' + primary_identifier: find_sec_bugs.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1 + secondary_identifiers: + - name: Find Security Bugs-SQL_INJECTION_SPRING_JDBC + type: find_sec_bugs_type + value: SQL_INJECTION_SPRING_JDBC + - name: Find Security Bugs-SQL_INJECTION_JPA + type: find_sec_bugs_type + value: SQL_INJECTION_JPA + - name: Find Security Bugs-SQL_INJECTION_JDO + type: find_sec_bugs_type + value: SQL_INJECTION_JDO + - name: Find Security Bugs-SQL_INJECTION_JDBC + type: find_sec_bugs_type + value: SQL_INJECTION_JDBC + - name: Find Security Bugs-SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE + type: find_sec_bugs_type + value: SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE + license: MIT + source: https://semgrep.dev/r/gitlab.find_sec_bugs.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1 + shortlink: https://sg.run/WD1A + semgrep.dev: + rule: + r_id: 21209 + rv_id: 57077 + rule_id: lBUXP4 + version_id: YDT5zl + url: https://semgrep.dev/playground/r/YDT5zl/gitlab.find_sec_bugs.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1 + origin: community + subcategory: + - audit + severity: ERROR +- id: gitlab.find_sec_bugs.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1.SQL_INJECTION-1.SQL_INJECTION_HIBERNATE-1.SQL_INJECTION_VERTX-1.SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING-1 + languages: + - java + 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: + ``` + // Some userInput + String userInput = "someUserInput"; + // Your connection string + String url = "..."; + // Get a connection from the DB via the DriverManager + Connection conn = DriverManager.getConnection(url); + // Create a prepared statement + PreparedStatement st = conn.prepareStatement("SELECT name FROM table where name=?"); + // Set each parameters value by the index (starting from 1) + st.setString(1, userInput); + // Execute query and get the result set + ResultSet rs = st.executeQuery(); + // Iterate over results + while (rs.next()) { + // Get result for this row at the provided column number (starting from 1) + String result = rs.getString(1); + // ... + } + // Close the ResultSet + rs.close(); + // Close the PreparedStatement + st.close(); + ``` + + For more information on SQL Injection see OWASP: + https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html + metadata: + shortDescription: Improper Neutralization of Special Elements used in an SQL Command + ('SQL Injection') + category: security + cwe: CWE-89 + primary_identifier: find_sec_bugs.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1.SQL_INJECTION-1.SQL_INJECTION_HIBERNATE-1.SQL_INJECTION_VERTX-1.SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING-1 + secondary_identifiers: + - name: Find Security Bugs-SQL_INJECTION_SPRING_JDBC + type: find_sec_bugs_type + value: SQL_INJECTION_SPRING_JDBC + - name: Find Security Bugs-SQL_INJECTION_JPA + type: find_sec_bugs_type + value: SQL_INJECTION_JPA + - name: Find Security Bugs-SQL_INJECTION_JDO + type: find_sec_bugs_type + value: SQL_INJECTION_JDO + - name: Find Security Bugs-SQL_INJECTION_JDBC + type: find_sec_bugs_type + value: SQL_INJECTION_JDBC + - name: Find Security Bugs-SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE + type: find_sec_bugs_type + value: SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE + - name: Find Security Bugs-SQL_INJECTION + type: find_sec_bugs_type + value: SQL_INJECTION + - name: Find Security Bugs-SQL_INJECTION_HIBERNATE + type: find_sec_bugs_type + value: SQL_INJECTION_HIBERNATE + - name: Find Security Bugs-SQL_INJECTION_VERTX + type: find_sec_bugs_type + value: SQL_INJECTION_VERTX + - name: Find Security Bugs-SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING + type: find_sec_bugs_type + value: SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1.SQL_INJECTION-1.SQL_INJECTION_HIBERNATE-1.SQL_INJECTION_VERTX-1.SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING-1 + shortlink: https://sg.run/W9PA + semgrep.dev: + rule: + r_id: 47609 + rv_id: 835515 + rule_id: L1Udoq + version_id: PkTxGwA + url: https://semgrep.dev/playground/r/PkTxGwA/gitlab.find_sec_bugs.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1.SQL_INJECTION-1.SQL_INJECTION_HIBERNATE-1.SQL_INJECTION_VERTX-1.SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING-1 + origin: community + subcategory: + - audit + patterns: + - pattern-not-inside: | + final String $ARG = ...; + ... + - pattern-not-inside: | + class $CLAZZ { + ... + final String $ARG = ...; + ... + } + - pattern-either: + - patterns: + - pattern: "(javax.jdo.PersistenceManager $PM).newQuery($ARG)" + - pattern-not: (javax.jdo.PersistenceManager $PM).newQuery("...") + - patterns: + - pattern: "(javax.jdo.PersistenceManager $PM).newQuery(..., $ARG)" + - pattern-not: (javax.jdo.PersistenceManager $PM).newQuery(..., "...") + - patterns: + - pattern: "(javax.jdo.Query $Q).setFilter($ARG)" + - pattern-not: (javax.jdo.Query $Q).setFilter("...") + - patterns: + - pattern: "(javax.jdo.Query $Q).setGrouping($ARG)" + - pattern-not: (javax.jdo.Query $Q).setGrouping("...") + - patterns: + - pattern: "(javax.jdo.Query $Q).setGrouping($ARG)" + - pattern-not: (javax.jdo.Query $Q).setGrouping("...") + - patterns: + - pattern: org.hibernate.criterion.Restrictions.sqlRestriction($ARG, ...) + - pattern-not: org.hibernate.criterion.Restrictions.sqlRestriction("...", ...) + - patterns: + - pattern: "(org.hibernate.Session $S).createQuery((String $ARG), ...)" + - pattern-not: (org.hibernate.Session $S).createQuery("...", ...) + - patterns: + - pattern: "(org.hibernate.Session $S).createSQLQuery($ARG, ...)" + - pattern-not: (org.hibernate.Session $S).createSQLQuery("...", ...) + - patterns: + - pattern: "(java.sql.Statement $S).executeQuery($ARG, ...)" + - pattern-not: (java.sql.Statement $S).createSQLQuery("...", ...) + - patterns: + - pattern: "(java.sql.Statement $S).execute($ARG, ...)" + - pattern-not: (java.sql.Statement $S).execute("...", ...) + - patterns: + - pattern: "(java.sql.Statement $S).executeUpdate($ARG, ...)" + - pattern-not: (java.sql.Statement $S).executeUpdate("...", ...) + - patterns: + - pattern: "(java.sql.Statement $S).executeLargeUpdate($ARG, ...)" + - pattern-not: (java.sql.Statement $S).executeLargeUpdate("...", ...) + - patterns: + - pattern: "(java.sql.Statement $S).addBatch($ARG, ...)" + - pattern-not: (java.sql.Statement $S).addBatch("...", ...) + - patterns: + - pattern: "(java.sql.PreparedStatement $S).executeQuery($ARG, ...)" + - pattern-not: (java.sql.PreparedStatement $S).executeQuery("...", ...) + - patterns: + - pattern: "(java.sql.PreparedStatement $S).execute($ARG, ...)" + - pattern-not: (java.sql.PreparedStatement $S).execute("...", ...) + - patterns: + - pattern: "(java.sql.PreparedStatement $S).executeUpdate($ARG, ...)" + - pattern-not: (java.sql.PreparedStatement $S).executeUpdate("...", ...) + - patterns: + - pattern: "(java.sql.PreparedStatement $S).executeLargeUpdate($ARG, ...)" + - pattern-not: (java.sql.PreparedStatement $S).executeLargeUpdate("...", ...) + - patterns: + - pattern: "(java.sql.PreparedStatement $S).addBatch($ARG, ...)" + - pattern-not: (java.sql.PreparedStatement $S).addBatch("...", ...) + - patterns: + - pattern: "(java.sql.Connection $S).prepareCall($ARG, ...)" + - pattern-not: (java.sql.Connection $S).prepareCall("...", ...) + - patterns: + - pattern: "(java.sql.Connection $S).prepareStatement($ARG, ...)" + - pattern-not: (java.sql.Connection $S).prepareStatement("...", ...) + - patterns: + - pattern: "(java.sql.Connection $S).nativeSQL($ARG, ...)" + - pattern-not: (java.sql.Connection $S).nativeSQL("...", ...) + - patterns: + - pattern: new org.springframework.jdbc.core.PreparedStatementCreatorFactory($ARG, + ...) + - pattern-not: new org.springframework.jdbc.core.PreparedStatementCreatorFactory("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.PreparedStatementCreatorFactory $F).newPreparedStatementCreator($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.PreparedStatementCreatorFactory + $F).newPreparedStatementCreator("...", ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).batchUpdate($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).batchUpdate("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).execute($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).execute("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).query($ARG, ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).query("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForList($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForList("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForMap($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForMap("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForObject($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForObject("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForObject($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForObject("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForRowSet($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForRowSet("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForInt($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForInt("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).queryForLong($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).queryForLong("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcOperations $O).udpate($ARG, ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcOperations $O).udpate("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).batchUpdate($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).batchUpdate("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).execute($ARG, ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).execute("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).query($ARG, ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).query("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).queryForList($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).queryForList("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).queryForMap($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).queryForMap("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).queryForObject($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).queryForObject("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).queryForRowSet($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).queryForRowSet("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).queryForInt($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).queryForInt("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).queryForLong($ARG, + ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).queryForLong("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.JdbcTemplate $O).update($ARG, ...)" + - pattern-not: (org.springframework.jdbc.core.JdbcTemplate $O).update("...", + ...) + - patterns: + - pattern: "(io.vertx.sqlclient.SqlClient $O).query($ARG, ...)" + - pattern-not: (io.vertx.sqlclient.SqlClient $O).query("...", ...) + - patterns: + - pattern: "(io.vertx.sqlclient.SqlClient $O).preparedQuery($ARG, ...)" + - pattern-not: (io.vertx.sqlclient.SqlClient $O).preparedQuery("...", ...) + - patterns: + - pattern: "(io.vertx.sqlclient.SqlConnection $O).prepare($ARG, ...)" + - pattern-not: (io.vertx.sqlclient.SqlConnection $O).prepare("...", ...) + - patterns: + - pattern: "(org.apache.turbine.om.peer.BasePeer $O).executeQuery($ARG, ...)" + - pattern-not: (org.apache.turbine.om.peer.BasePeer $O).executeQuery("...", + ...) + - patterns: + - pattern: "(org.apache.torque.util.BasePeer $O).executeQuery($ARG, ...)" + - pattern-not: (org.apache.torque.util.BasePeer $O).executeQuery("...", ...) + - patterns: + - pattern: "(javax.persistence.EntityManager $O).createQuery($ARG, ...)" + - pattern-not: (javax.persistence.EntityManager $O).createQuery("...", ...) + - patterns: + - pattern: "(javax.persistence.EntityManager $O).createNativeQuery($ARG, ...)" + - pattern-not: (javax.persistence.EntityManager $O).createNativeQuery("...", + ...) + severity: ERROR +- id: gitlab.find_sec_bugs.SSL_CONTEXT-1 + 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`. + These protocols are outdated and do not validate certificates by default. Additionally, + these older `SSL` versions have many known security issues. + + Instead, use secure protocols like `TLSv1.2` or `TLSv1.3`. + ``` + SSLContext context = SSLContext.getInstance("TLSv1.3"); + ``` + For more information on see OWASP: + - 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 + metadata: + shortDescription: Improper certificate validation + category: security + cwe: CWE-295 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: MEDIUM + primary_identifier: find_sec_bugs.SSL_CONTEXT-1 + secondary_identifiers: + - name: Find Security Bugs-SSL_CONTEXT + type: find_sec_bugs_type + value: SSL_CONTEXT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.SSL_CONTEXT-1 + shortlink: https://sg.run/8k34 + semgrep.dev: + rule: + r_id: 21184 + rv_id: 920174 + rule_id: eqUZxA + version_id: 1QT4N7z + url: https://semgrep.dev/playground/r/1QT4N7z/gitlab.find_sec_bugs.SSL_CONTEXT-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.SSL_CONTEXT-2 + 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 + security-severity: Medium + primary_identifier: find_sec_bugs.SSL_CONTEXT-2 + secondary_identifiers: + - name: Find Security Bugs-SSL_CONTEXT + type: find_sec_bugs_type + value: SSL_CONTEXT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.SSL_CONTEXT-2 + shortlink: https://sg.run/0JlB + semgrep.dev: + rule: + r_id: 67598 + rv_id: 920175 + rule_id: x8UeYj + version_id: 9lTA75o + url: https://semgrep.dev/playground/r/9lTA75o/gitlab.find_sec_bugs.SSL_CONTEXT-2 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.STRUTS_FORM_VALIDATION-1 + languages: + - java + message: | + Form inputs should have minimal input validation. Preventive validation helps + provide defense in depth against a variety of risks. + metadata: + category: security + cwe: CWE-20 + shortDescription: Improper Input Validation + primary_identifier: find_sec_bugs.STRUTS_FORM_VALIDATION-1 + secondary_identifiers: + - name: Find Security Bugs-STRUTS_FORM_VALIDATION + type: find_sec_bugs_type + value: STRUTS_FORM_VALIDATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.STRUTS_FORM_VALIDATION-1 + shortlink: https://sg.run/R5K2 + semgrep.dev: + rule: + r_id: 21193 + rv_id: 835499 + rule_id: gxUkqj + version_id: w8TAbgP + url: https://semgrep.dev/playground/r/w8TAbgP/gitlab.find_sec_bugs.STRUTS_FORM_VALIDATION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + class $CLASS extends $SC { + ... + } + - metavariable-regex: + metavariable: "$SC" + regex: "(ActionForm|ValidatorForm)" + - pattern-not: public void validate() { ... } + severity: WARNING +- id: gitlab.find_sec_bugs.TDES_USAGE-1 + 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. + 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`: + ``` + public encrypt() throws Exception { + chaChaEncryption("Secret text to encrypt".getBytes(StandardCharsets.UTF_8)); + } + + public SecureRandom getSecureRandomDRBG() throws NoSuchAlgorithmException { + // Use DRBG according to + http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf + return SecureRandom.getInstance("DRBG", + // Security strength in bits (default is 128) + DrbgParameters.instantiation(256, + // Set prediction resistance and re-seeding + DrbgParameters.Capability.PR_AND_RESEED, + // Set the personalization string (optional, not necessary) + "some_personalization_string".getBytes() + ) + ); + } + + public Cipher getChaCha20Poly1305(int mode, byte[] nonceKey, byte[] secretKey) throws + NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, + InvalidAlgorithmParameterException { + // Get a DRBG random number generator instance + SecureRandom random = getSecureRandomDRBG(); + // Create a ChaCha20-Poly1305 cipher instance + Cipher chaChaCipher = Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding"); + // Create our parameterSpec using our nonceKey + AlgorithmParameterSpec parameterSpec = new IvParameterSpec(nonceKey); + // Create a SecretKeySpec using our secretKey + SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "ChaCha20"); + // Initialize and return the cipher for the provided mode + chaChaCipher.init(mode, secretKeySpec, parameterSpec, random); + return chaChaCipher; + } + + public void chaChaEncryption(byte[] plainText) throws NoSuchAlgorithmException, + NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { + // Get a DRBG random number generator instance + SecureRandom random = getSecureRandomDRBG(); + // Create secretKey + byte[] secretKey = new byte[32]; + random.nextBytes(secretKey); + // Create an IV nonceKey + byte[] nonceKey = new byte[12]; + random.nextBytes(nonceKey); + // Create a chaCha encryption cipher instance + Cipher chaChaEncryptor = getChaCha20Poly1305(Cipher.ENCRYPT_MODE, nonceKey, secretKey); + // Encrypt the text using ChaCha20Poly1305 + byte[] cipherText = null; + try { + cipherText = chaChaEncryptor.doFinal(plainText); + } catch (IllegalBlockSizeException | BadPaddingException e) { + System.out.println("failed to encrypt text"); + return; + } + System.out.println("encrypted: " + Base64.getEncoder().encodeToString(cipherText)); + // Create a chaCha decryption cipher instance + Cipher chaChaDecryptor = getChaCha20Poly1305(Cipher.DECRYPT_MODE, nonceKey, secretKey); + // Decrypt the text + byte[] decryptedText = null; + try { + decryptedText = chaChaDecryptor.doFinal(cipherText); + } catch (IllegalBlockSizeException | BadPaddingException e) { + System.out.println("failed to decrypt text"); + return; + } + System.out.println("decrypted: " + new String(decryptedText, StandardCharsets.UTF_8)); + } + ``` + + For more information on Java Cryptography see: + https://docs.oracle.com/en/java/javase/15/security/java-cryptography-architecture-jca-reference-guide.html + 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 + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.TDES_USAGE-1 + secondary_identifiers: + - name: Find Security Bugs-TDES_USAGE + type: find_sec_bugs_type + value: TDES_USAGE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.TDES_USAGE-1 + shortlink: https://sg.run/w4BX + semgrep.dev: + rule: + r_id: 21173 + rv_id: 920163 + rule_id: j2UwKr + version_id: K3TwLjL + url: https://semgrep.dev/playground/r/K3TwLjL/gitlab.find_sec_bugs.TDES_USAGE-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.TEMPLATE_INJECTION_PEBBLE-1.TEMPLATE_INJECTION_FREEMARKER-1.TEMPLATE_INJECTION_VELOCITY-1 + 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 + security-severity: High + primary_identifier: find_sec_bugs.TEMPLATE_INJECTION_PEBBLE-1.TEMPLATE_INJECTION_FREEMARKER-1.TEMPLATE_INJECTION_VELOCITY-1 + secondary_identifiers: + - name: Find Security Bugs-TEMPLATE_INJECTION_PEBBLE + type: find_sec_bugs_type + value: TEMPLATE_INJECTION_PEBBLE + - name: Find Security Bugs-TEMPLATE_INJECTION_FREEMARKER + type: find_sec_bugs_type + value: TEMPLATE_INJECTION_FREEMARKER + - name: Find Security Bugs-TEMPLATE_INJECTION_VELOCITY + type: find_sec_bugs_type + value: TEMPLATE_INJECTION_VELOCITY + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.TEMPLATE_INJECTION_PEBBLE-1.TEMPLATE_INJECTION_FREEMARKER-1.TEMPLATE_INJECTION_VELOCITY-1 + shortlink: https://sg.run/vpK4 + semgrep.dev: + rule: + r_id: 21233 + rv_id: 920204 + rule_id: yyUDL9 + version_id: DkT2yYA + url: https://semgrep.dev/playground/r/DkT2yYA/gitlab.find_sec_bugs.TEMPLATE_INJECTION_PEBBLE-1.TEMPLATE_INJECTION_FREEMARKER-1.TEMPLATE_INJECTION_VELOCITY-1 + origin: community + subcategory: + - audit + severity: ERROR +- id: gitlab.find_sec_bugs.TRUST_BOUNDARY_VIOLATION-1 + languages: + - java + message: | + A trust boundary can be thought of as line drawn through a program. On one side + of the line, data is untrusted. On the other side of the line, data is assumed + to be trustworthy. The purpose of validation logic is to allow data to safely + cross the trust boundary - to move from untrusted to trusted. A trust boundary + violation occurs when a program blurs the line between what is trusted and what + is untrusted. By combining trusted and untrusted data in the same data + structure, it becomes easier for programmers to mistakenly trust unvalidated + data. + metadata: + category: security + cwe: CWE-501 + shortDescription: Trust Boundary Violation + primary_identifier: find_sec_bugs.TRUST_BOUNDARY_VIOLATION-1 + secondary_identifiers: + - name: Find Security Bugs-TRUST_BOUNDARY_VIOLATION + type: find_sec_bugs_type + value: TRUST_BOUNDARY_VIOLATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.TRUST_BOUNDARY_VIOLATION-1 + shortlink: https://sg.run/yJWd + semgrep.dev: + rule: + r_id: 21168 + rv_id: 835472 + rule_id: oqUKne + version_id: JdTlRw1 + url: https://semgrep.dev/playground/r/JdTlRw1/gitlab.find_sec_bugs.TRUST_BOUNDARY_VIOLATION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - patterns: + - pattern: "(HttpServletRequest $H). ... .setAttribute($ARG1, $ARG2);" + - pattern-not: (HttpServletRequest $H). ... .setAttribute("...", "..."); + - patterns: + - pattern: "(HttpServletRequest $H). ... .putValue($ARG1, $ARG2);" + - pattern-not: (HttpServletRequest $H). ... .putValue("...", "..."); + severity: WARNING +- id: gitlab.find_sec_bugs.UNENCRYPTED_SOCKET-1.UNENCRYPTED_SERVER_SOCKET-1 + languages: + - java + message: | + Beyond using an SSL socket, you need to make sure your use of SSLSocketFactory + does all the appropriate certificate validation checks to make sure you are not + subject to man-in-the-middle attacks. Please read the OWASP Transport Layer + Protection Cheat Sheet for details on how to do this correctly. + metadata: + cwe: CWE-319 + shortDescription: Cleartext Transmission of Sensitive Information + primary_identifier: find_sec_bugs.UNENCRYPTED_SOCKET-1.UNENCRYPTED_SERVER_SOCKET-1 + secondary_identifiers: + - name: Find Security Bugs-UNENCRYPTED_SOCKET + type: find_sec_bugs_type + value: UNENCRYPTED_SOCKET + - name: Find Security Bugs-UNENCRYPTED_SERVER_SOCKET + type: find_sec_bugs_type + value: UNENCRYPTED_SERVER_SOCKET + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.UNENCRYPTED_SOCKET-1.UNENCRYPTED_SERVER_SOCKET-1 + shortlink: https://sg.run/4k1Z + semgrep.dev: + rule: + r_id: 21188 + rv_id: 835494 + rule_id: nJUn7D + version_id: yeTNgbz + url: https://semgrep.dev/playground/r/yeTNgbz/gitlab.find_sec_bugs.UNENCRYPTED_SOCKET-1.UNENCRYPTED_SERVER_SOCKET-1 + origin: community + category: security + subcategory: + - audit + patterns: + - pattern: new java.net.Socket(...) + severity: WARNING +- id: gitlab.find_sec_bugs.UNVALIDATED_REDIRECT-1.URL_REWRITING-1 + 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\nonly 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 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(...);\n" + - 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)\n" + - pattern: '($X.servlet.http.HttpServletResponse $RES).addHeader("Location", $URL) + + ' + pattern-sanitizers: + - patterns: + - pattern-inside: | + if ($SAFE.contains($URL)){ + ... + } + - pattern-either: + - pattern: "($X.servlet.http.HttpServletResponse $RES).sendRedirect($URL)\n" + - pattern: '($X.servlet.http.HttpServletResponse $RES).addHeader("Location", + $URL) + + ' + metadata: + category: security + cwe: CWE-601 + owasp: + - A1:2017-Injection + - A03:2021-Injection + shortDescription: URL redirection to untrusted site ('Open Redirect') + security-severity: Info + primary_identifier: find_sec_bugs.UNVALIDATED_REDIRECT-1.URL_REWRITING-1 + secondary_identifiers: + - name: Find Security Bugs-UNVALIDATED_REDIRECT + type: find_sec_bugs_type + value: UNVALIDATED_REDIRECT + - name: Find Security Bugs-URL_REWRITING + type: find_sec_bugs_type + value: URL_REWRITING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.UNVALIDATED_REDIRECT-1.URL_REWRITING-1 + shortlink: https://sg.run/PPWE + semgrep.dev: + rule: + r_id: 21189 + rv_id: 920177 + rule_id: EwU1nP + version_id: rxTjv4k + url: https://semgrep.dev/playground/r/rxTjv4k/gitlab.find_sec_bugs.UNVALIDATED_REDIRECT-1.URL_REWRITING-1 + origin: community + subcategory: + - audit + severity: ERROR +- id: gitlab.find_sec_bugs.URLCONNECTION_SSRF_FD-1 + languages: + - java + message: | + Server-Side-Request-Forgery (SSRF) exploits backend systems that initiate requests to third + parties. + If user input is used in constructing or sending these requests, an attacker could supply + malicious + data to force the request to other systems or modify request data to cause unwanted actions. + + Ensure user input is not used directly in constructing URLs or URIs when initiating requests + to third party + systems from back end systems. Care must also be taken when constructing payloads using user + input. Where + possible restrict to known URIs or payloads. Consider using a server-side map where keys are + used to return + URLs such as `https://site/goto?key=1` where `{key: 1, url: 'http://some.url/', key: 2, url: + 'http://...'}`. + + If you must use user-supplied input for requesting URLs, it is strongly recommended that the + HTTP client + chosen allows you to customize and block certain IP ranges at the network level. By blocking + RFC 1918 + addresses or other network address ranges, you can limit the severity of a successful SSRF + attack. Care must + also be taken to block certain protocol or address formatting such as IPv6. + + If you cannot block address ranges at the client level, you may want to run the HTTP client + as a protected + user, or in a protected network where you can apply IP Table or firewall rules to block access + to dangerous + addresses. Finally, if none of the above protections are available, you could also run a + custom HTTP proxy + and force all requests through it to handle blocking dangerous addresses. + + Example using a map to look up a key to be used in a HTTP request: + ``` + HashMap lookupTable = new HashMap<>(); + lookupTable.put("key1", "https://example.com/"); + lookupTable.put("key2", "https://safeurl.com/"); + String userInput = request.getParameter("key"); + + // Create a CloseableHttpClient, ideally any requests issued should be done + // out-of-band from the servlet request itself (such as using a separate thread/scheduler + system) + try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { + // Lookup the value from our user input from our lookupTable + String value = lookupTable.getOrDefault(userInput, "https://example.com/"); + // Construct the url, with the hardcoded url and only pass in the value from the + lookupTable, + // not direct user input + final HttpGet httpget = new HttpGet(value); + // Execute the request + CloseableHttpResponse clientResponse = httpClient.execute(httpget); + // Read the response + byte[] responseData = clientResponse.getEntity().getContent().readAllBytes(); + // Handle the response + // ... + } + ``` + + If using a map is not possible, the user-supplied input must be encoded prior to use, and + never allow full + URLs: + ``` + // Get user input + String userInput = request.getParameter("key"); + // Encode the string using java.net.URLEncoder with the UTF-8 character set + String encodedString = java.net.URLEncoder.encode(userInput, StandardCharsets.UTF_8); + // Create a CloseableHttpClient, ideally any requests issued should be done + // out-of-band from the servlet request itself (such as using a separate thread/scheduler + system) + try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { + // Construct the url, with the hardcoded url and only pass in the encoded value, never a + full URL + final HttpGet httpget = new HttpGet("https://example.com/getId?key="+encodedString); + // Execute the request + CloseableHttpResponse clientResponse = httpClient.execute(httpget); + // Read the response + byte[] responseData = clientResponse.getEntity().getContent().readAllBytes(); + // handle the response + } + ``` + + For more information on SSRF see OWASP: + https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html + 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 + security-severity: Medium + primary_identifier: find_sec_bugs.URLCONNECTION_SSRF_FD-1 + secondary_identifiers: + - name: Find Security Bugs-URLCONNECTION_SSRF_FD + type: find_sec_bugs_type + value: URLCONNECTION_SSRF_FD + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.URLCONNECTION_SSRF_FD-1 + shortlink: https://sg.run/Njl7 + semgrep.dev: + rule: + r_id: 21227 + rv_id: 920199 + rule_id: pKUblx + version_id: 5PTNGeR + url: https://semgrep.dev/playground/r/5PTNGeR/gitlab.find_sec_bugs.URLCONNECTION_SSRF_FD-1 + origin: community + subcategory: + - audit + severity: ERROR +- id: gitlab.find_sec_bugs.WEAK_FILENAMEUTILS-1 + languages: + - java + message: "The filename provided by the FileUpload API can be tampered with by the + client to reference\nunauthorized 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 + shortDescription: Improper limitation of a pathname to a restricted directory + ('Path Traversal') + security-severity: Info + technology: + - java + primary_identifier: find_sec_bugs.WEAK_FILENAMEUTILS-1 + secondary_identifiers: + - name: Find Security Bugs-WEAK_FILENAMEUTILS + type: find_sec_bugs_type + value: WEAK_FILENAMEUTILS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.WEAK_FILENAMEUTILS-1 + shortlink: https://sg.run/Gb41 + semgrep.dev: + rule: + r_id: 21192 + rv_id: 920180 + rule_id: 8GUvb6 + version_id: kbTOPL6 + url: https://semgrep.dev/playground/r/kbTOPL6/gitlab.find_sec_bugs.WEAK_FILENAMEUTILS-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - pattern: | + $NAME = org.apache.commons.io.FilenameUtils.getName(...); + ... + $SAFE = concat($BASE, $NAME); + - pattern: | + $RET $FUN(...){ + ... + $PATH = $BP.resolve(...); + ... + if(!$PATH.startsWith(...)) { + throw new $EXC(...); + } + ... + } + 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.find_sec_bugs.WEAK_HOSTNAME_VERIFIER + 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();\nconnection.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: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + security-severity: MEDIUM + primary_identifier: find_sec_bugs.WEAK_HOSTNAME_VERIFIER + secondary_identifiers: + - name: Find Security Bugs-WEAK_HOSTNAME_VERIFIER + type: find_sec_bugs_type + value: WEAK_HOSTNAME_VERIFIER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.WEAK_HOSTNAME_VERIFIER + shortlink: https://sg.run/Ab6G0 + semgrep.dev: + rule: + r_id: 144294 + rv_id: 920176 + rule_id: 9AUdr86 + version_id: yeTDgZn + url: https://semgrep.dev/playground/r/yeTDgZn/gitlab.find_sec_bugs.WEAK_HOSTNAME_VERIFIER + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + class $V implements HostnameVerifier { + ... + } + - pattern-either: + - pattern: | + boolean verify(...) { + ... + return true; + ... + } + - pattern-not: + patterns: + - pattern: | + boolean verify(...) { + ... + return $VAR; + ... + } + - metavariable-regex: + metavariable: "$VAR" + regex: "^((?!true).)*$" + - pattern-not: | + boolean verify(...) { + $VAR = true; + ... + return $VAR; + ... + } + severity: WARNING +- id: gitlab.find_sec_bugs.WEAK_HOSTNAME_VERIFIER-1.WEAK_TRUST_MANAGER-1 + languages: + - java + message: | + Either the `HostnameVerifier` has been set to always return `true` or the `X509TrustManager` + has + been configured to return null, or both. This effectively disables the validation of server or + client 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. + + It is recommended to not override the default `HostnameVerifiers`. + + Consider using the default `TrustManager` instead of implementing a custom one. If you must + override + the default verification process, implement proper TrustManager verification for + `checkServerTrusted` and + `checkClientTrusted` by throwing `CertificateException` if the certificate is invalid. + + Example using the built in `TrustManagerFactory` to manage validating certificate chains: + ``` + // Use the default TrustManagerFactory + TrustManagerFactory trustManagerFactory = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + // Use default system KeyStore, alternatively pass in your own keystore. + trustManagerFactory.init((KeyStore) null); + // Create SSLContext for TLS connections + SSLContext tlsContext = SSLContext.getInstance("TLS"); + // Initialize the tlsContext with our trust manager and a SecureRandom number generator. + tlsContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom()); + ``` + + For more information on TLS security see OWASP: + https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html + metadata: + shortDescription: Improper certificate validation + category: security + cwe: CWE-295 + primary_identifier: find_sec_bugs.WEAK_HOSTNAME_VERIFIER-1.WEAK_TRUST_MANAGER-1 + secondary_identifiers: + - name: Find Security Bugs-WEAK_HOSTNAME_VERIFIER + type: find_sec_bugs_type + value: WEAK_HOSTNAME_VERIFIER + - name: Find Security Bugs-WEAK_TRUST_MANAGER + type: find_sec_bugs_type + value: WEAK_TRUST_MANAGER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.WEAK_HOSTNAME_VERIFIER-1.WEAK_TRUST_MANAGER-1 + shortlink: https://sg.run/Jw5Z + semgrep.dev: + rule: + r_id: 21190 + rv_id: 835496 + rule_id: 7KUbOj + version_id: bZTBoWW + url: https://semgrep.dev/playground/r/bZTBoWW/gitlab.find_sec_bugs.WEAK_HOSTNAME_VERIFIER-1.WEAK_TRUST_MANAGER-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - patterns: + - pattern-inside: | + class $V implements HostnameVerifier { + ... + } + - pattern-inside: | + public boolean verify(...) { + ... + } + - pattern: return true; + - patterns: + - pattern-inside: | + class $V implements X509TrustManager { + ... + } + - pattern-either: + - pattern: public void checkClientTrusted(...) {} + - pattern: public void checkServerTrusted(...) {} + - pattern: | + public X509Certificate[] getAcceptedIssuers() { + ... + return null; + } + severity: WARNING +- id: gitlab.find_sec_bugs.WEAK_MESSAGE_DIGEST_MD5-1.WEAK_MESSAGE_DIGEST_SHA1-1 + 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 ( + "MD2" "MD4" "MD5" "MD5withRSA" + "SHA-1" "SHA1withRSA" "SHA1withDSA" + ) + 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: + - A6:2017-Security Misconfiguration + - A04:2021-Insecure Design + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.WEAK_MESSAGE_DIGEST_MD5-1.WEAK_MESSAGE_DIGEST_SHA1-1 + secondary_identifiers: + - name: Find Security Bugs-WEAK_MESSAGE_DIGEST_MD5 + type: find_sec_bugs_type + value: WEAK_MESSAGE_DIGEST_MD5 + - name: Find Security Bugs-WEAK_MESSAGE_DIGEST_SHA1 + type: find_sec_bugs_type + value: WEAK_MESSAGE_DIGEST_SHA1 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.WEAK_MESSAGE_DIGEST_MD5-1.WEAK_MESSAGE_DIGEST_SHA1-1 + shortlink: https://sg.run/L2R7 + semgrep.dev: + rule: + r_id: 21183 + rv_id: 920172 + rule_id: OrUvyR + version_id: X0TAK2W + url: https://semgrep.dev/playground/r/X0TAK2W/gitlab.find_sec_bugs.WEAK_MESSAGE_DIGEST_MD5-1.WEAK_MESSAGE_DIGEST_SHA1-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.WEAK_TRUST_MANAGER + 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 \ndefault `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.\ntlsContext.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: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + security-severity: MEDIUM + primary_identifier: find_sec_bugs.WEAK_TRUST_MANAGER + secondary_identifiers: + - name: Find Security Bugs-WEAK_TRUST_MANAGER + type: find_sec_bugs_type + value: WEAK_TRUST_MANAGER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.WEAK_TRUST_MANAGER + shortlink: https://sg.run/BYoR7 + semgrep.dev: + rule: + r_id: 144295 + rv_id: 920178 + rule_id: yyURlY5 + version_id: bZTLo9N + url: https://semgrep.dev/playground/r/bZTLo9N/gitlab.find_sec_bugs.WEAK_TRUST_MANAGER + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + class $V implements X509TrustManager { + ... + } + - pattern-either: + - pattern: public void checkClientTrusted(...) {} + - pattern: public void checkServerTrusted(...) {} + - patterns: + - pattern-either: + - pattern: | + X509Certificate[] getAcceptedIssuers() { + ... + return null; + ... + } + - pattern-not: + patterns: + - pattern: | + X509Certificate[] getAcceptedIssuers() { + ... + return $VAR; + ... + } + - metavariable-regex: + metavariable: "$VAR" + regex: "^((?!null).)*$" + - pattern-not: | + X509Certificate[] getAcceptedIssuers() { + $VAR = null; + ... + return $VAR; + ... + } + severity: WARNING +- id: gitlab.find_sec_bugs.WICKET_XSS1-1 + languages: + - java + patterns: + - pattern-inside: | + import org.apache.wicket.$A; + ... + - pattern: "$OBJ.setEscapeModelStrings(false);\n" + message: | + The application is disabling Wicket's string escaping functionality by calling + `setEscapeModelStrings(false)`. + This could lead to Cross Site Scripting (XSS) if used with user-supplied input. 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 `
    context 1
    ` + - Inside attributes: `
    ` + - Inside event attributes `` + - Inside script blocks: `` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: `link` + + 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. + + Use Wicket's built in escaping feature by calling `Component.setEscapeModelStrings(true);` + + For more information on Wicket components see: + - https://nightlies.apache.org/wicket/apidocs/9.x/org/apache/wicket/Component.html + + For more information on XSS see OWASP: + - https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html + metadata: + shortDescription: Improper neutralization of input during web page generation + ('Cross-site Scripting') + category: security + cwe: CWE-79 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: Medium + primary_identifier: find_sec_bugs.WICKET_XSS1-1 + secondary_identifiers: + - name: Find Security Bugs-WICKET_XSS1 + type: find_sec_bugs_type + value: WICKET_XSS1 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.WICKET_XSS1-1 + shortlink: https://sg.run/QJoP + semgrep.dev: + rule: + r_id: 21242 + rv_id: 920209 + rule_id: v8Uvkz + version_id: l4TXD60 + url: https://semgrep.dev/playground/r/l4TXD60/gitlab.find_sec_bugs.WICKET_XSS1-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs.XML_DECODER-1 + languages: + - java + message: | + Deserialization attacks exploit the process of reading serialized data and turning it back + into an object. By constructing malicious objects and serializing them, an adversary may + attempt to: + + - Inject code that is executed upon object construction, which occurs during the + deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized + data but are read in during deserialization. + + Consider safer alternatives such as serializing data in the JSON format. Ensure any format + chosen allows + the application to specify exactly which object types are allowed to be deserialized. + Additionally, when + deserializing, never deserialize to base object types like `Object` and only cast to the exact + object + type that is expected. + + To protect against mass assignment, only allow deserialization of the specific fields that are + required. If this is not easily done, consider creating an intermediary type that + can be serialized with only the necessary fields exposed. + + Do note that `XMLEncoder` and `XMLDecoder` are not recommended. If the application must + use this serialization method, use a custom ClassLoader to prevent loading of arbitrary + classes: + ``` + XMLDecoder decoder = new XMLDecoder(inputStream, null, null, new ClassLoader() { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (!name.equals(NameOfBeanHere.class.getName()) && + !name.equals(XMLDecoder.class.getName())) { + throw new RuntimeException("Unauthorized deserialization attempt: " + name); + } + + return super.loadClass(name, resolve); + } + }); + ``` + + 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 details on deserialization attacks in general, see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + + It should be noted that [tools exist](https://github.com/frohoff/ysoserial) to + automatically create + exploit code for these vulnerabilities. + metadata: + shortDescription: Deserialization of untrusted data + category: security + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + security-severity: High + primary_identifier: find_sec_bugs.XML_DECODER-1 + secondary_identifiers: + - name: Find Security Bugs-XML_DECODER + type: find_sec_bugs_type + value: XML_DECODER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.XML_DECODER-1 + shortlink: https://sg.run/7QeR + semgrep.dev: + rule: + r_id: 21238 + rv_id: 920207 + rule_id: wdUk2X + version_id: K3TwLGL + url: https://semgrep.dev/playground/r/K3TwLGL/gitlab.find_sec_bugs.XML_DECODER-1 + origin: community + subcategory: + - audit + patterns: + - pattern: "(java.beans.XMLDecoder $D).readObject();\n" + - 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(){ + ... + $RET loadClass(String name, boolean resolve){ + if($X){ + throw ... + } + ... + } + ... + } + - metavariable-pattern: + metavariable: "$X" + pattern-either: + - pattern: "!name.equals(...)\n" + - pattern: "!$LIST.contains(name)\n" + - 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(){ + ... + $RET loadClass(String name, boolean resolve){ + if($X){ + throw ... + } + ... + } + ... + } + - metavariable-pattern: + metavariable: "$X" + pattern-either: + - pattern: "!name.equals(...)\n" + - pattern: "!$LIST.contains(name)\n" + severity: WARNING +- id: gitlab.find_sec_bugs.XPATH_INJECTION-1 + languages: + - java + message: | + The application processes `XPath` queries with potentially malicious input. + An adversary who is able to control the XPath query could potentially influence the logic + of how data is retrieved, processed or even bypass protections. + + To protect against XPath injection, user input should be parameterized using a variable + resolver. + By creating a class that implements the `XPathVariableResolver` the application can ensure + that + the xpath query and user-supplied input are treated separately. + + Example implementation of an XPathVariableResolver: + ``` + // Create a class which implements the XPathVariableResolver interface + public static class SimpleXPathVariableResolver implements XPathVariableResolver { + // Use a map or lookup table to store variables for resolution + private HashMap variables = new HashMap<>(); + // Allow caller to set variables + public void setVariable(QName name, String value) { + variables.put(name, value); + } + // Implement the resolveVariable to return the value + @Override + public Object resolveVariable(QName name) { + return variables.getOrDefault(name, ""); + } + } + + public static void xpathQuery(String userInput) throws ParseException, + ParserConfigurationException, + SAXException, IOException, XPathExpressionException { + + // Create our DocumentFactory + DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); + // Enable namespace awareness + domFactory.setNamespaceAware(true); + // Enable secure processing + domFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + // Create our DocumentBuilder + DocumentBuilder builder = domFactory.newDocumentBuilder(); + // Parse our XML document + Document doc = builder.parse("inventory.xml"); + + // Create a new instance of an XPath object + XPath xpathProcessor = XPathFactory.newInstance().newXPath(); + // Create our XPathVariableResolver + SimpleXPathVariableResolver resolver = new SimpleXPathVariableResolver(); + // Add user input as a variable value + resolver.setVariable(new QName("author"), userInput); + // Configure the processor to use our variable resolver + xpathProcessor.setXPathVariableResolver(resolver); + // Evaluate the XPath query + String result = xpathProcessor.compile("//author[contains(., $author)]").evaluate(doc); + // Work with the result + // ... + } + ``` + + For more information on XPath Injection see: + - https://owasp.org/www-community/attacks/XPATH_Injection + metadata: + shortDescription: Improper neutralization of data within XPath expressions ('XPath + Injection') + category: security + cwe: CWE-643 + primary_identifier: find_sec_bugs.XPATH_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-XPATH_INJECTION + type: find_sec_bugs_type + value: XPATH_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.XPATH_INJECTION-1 + shortlink: https://sg.run/8kv7 + semgrep.dev: + rule: + r_id: 21240 + rv_id: 835542 + rule_id: OrUv05 + version_id: kbT2P0y + url: https://semgrep.dev/playground/r/kbT2P0y/gitlab.find_sec_bugs.XPATH_INJECTION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern-inside: import javax.xml.xpath.*; ... + - pattern-inside: import javax.xml.xpath.XPath; ... + - pattern-either: + - patterns: + - pattern: "(XPath $X).compile($ARG)" + - pattern-not: (XPath $X).compile("...") + - patterns: + - pattern: "(XPath $X).evaluate($ARG)" + - pattern-not: (XPath $X).evaluate("...") + severity: ERROR +- id: gitlab.find_sec_bugs.XSS_REQUEST_PARAMETER_TO_SEND_ERROR-1 + languages: + - java + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: org.owasp.encoder.Encode.forHtml($TAINTED); + - pattern: "$TAINTED" + pattern-sinks: + - patterns: + - pattern-inside: "$FUNC(..., HttpServletResponse $RES, ...) {...}" + - pattern: "$RES.sendError(..., $DATA);" + - pattern: "$DATA" + pattern-sources: + - patterns: + - pattern-inside: "$FUNC(..., HttpServletRequest $REQ, ...) {...}" + - pattern-either: + - pattern: "$REQ.getParameter(...);" + - pattern: "$REQ.getHeader(...);" + - pattern: "$REQ.getRequestedSessionId();" + - pattern: "$REQ.getQueryString();" + message: | + The application is returning user-supplied data from an HTTP request to an HTTP response's + `sendError` method. 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. Note that Apache + Tomcat 9 and above automatically encode the output and are not vulnerable. + + 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 `
    context 1
    ` + - Inside attributes: `
    ` + - Inside event attributes `` + - Inside script blocks: `` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: `link` + + 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 `sendError` message parameter. + + Regardless if the application server handles output encoding, consider encoding any + user-supplied + input + that is used in the sendError method: + + Example using [Apache Commons Text](https://commons.apache.org/proper/commons-text/) + `StringEscapeUtils.escapeHtml4`: + ``` + // Get user input + String userInput = request.getParameter("key"); + // Encode the input using the Html4 encoder + String encoded = StringEscapeUtils.escapeHtml4(userInput); + // Respond with the error code and value + response.sendError(401, encoded); + ``` + + 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 + technology: + - java + primary_identifier: find_sec_bugs.XSS_REQUEST_PARAMETER_TO_SEND_ERROR-1 + secondary_identifiers: + - name: Find Security Bugs-XSS_REQUEST_PARAMETER_TO_SEND_ERROR + type: find_sec_bugs_type + value: XSS_REQUEST_PARAMETER_TO_SEND_ERROR + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.XSS_REQUEST_PARAMETER_TO_SEND_ERROR-1 + shortlink: https://sg.run/0xwb + semgrep.dev: + rule: + r_id: 47610 + rv_id: 835545 + rule_id: 8GUo74 + version_id: O9TJ7Kz + url: https://semgrep.dev/playground/r/O9TJ7Kz/gitlab.find_sec_bugs.XSS_REQUEST_PARAMETER_TO_SEND_ERROR-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER-1 + 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 `
    context 1
    ` + - Inside attributes: `
    ` + - Inside event attributes `` + - Inside script blocks: `` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: `link` + + 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: + - A1:2017-Injection + - A03:2021-Injection + technology: + - java + security-severity: Medium + primary_identifier: find_sec_bugs.XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER-1 + secondary_identifiers: + - name: Find Security Bugs-XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER + type: find_sec_bugs_type + value: XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER-1 + shortlink: https://sg.run/3Qkb + semgrep.dev: + rule: + r_id: 21243 + rv_id: 920210 + rule_id: d8U6Rg + version_id: YDTYbny + url: https://semgrep.dev/playground/r/YDTYbny/gitlab.find_sec_bugs.XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs.XSS_REQUEST_WRAPPER-1 + languages: + - java + message: 'Avoid using custom XSS filtering. Please use standard sanitization functions. + + ' + metadata: + category: security + cwe: CWE-79 + shortDescription: Improper Neutralization of Input During Web Page Generation + ('Cross-site Scripting') + primary_identifier: find_sec_bugs.XSS_REQUEST_WRAPPER-1 + secondary_identifiers: + - name: Find Security Bugs-XSS_REQUEST_WRAPPER + type: find_sec_bugs_type + value: XSS_REQUEST_WRAPPER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.XSS_REQUEST_WRAPPER-1 + shortlink: https://sg.run/gG7n + semgrep.dev: + rule: + r_id: 21241 + rv_id: 835543 + rule_id: eqUZdN + version_id: w8TAbdP + url: https://semgrep.dev/playground/r/w8TAbdP/gitlab.find_sec_bugs.XSS_REQUEST_WRAPPER-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + class $CLASS extends HttpServletRequestWrapper { + ... + } + - pattern: stripXSS(...) { ... } + severity: INFO +- id: gitlab.find_sec_bugs.XSS_SERVLET-1 + languages: + - java + message: | + A potential XSS was found. It could be used to execute unwanted JavaScript in a + client's browser. + metadata: + category: security + cwe: CWE-79 + shortDescription: Improper Neutralization of Input During Web Page Generation + ('Cross-site Scripting') + primary_identifier: find_sec_bugs.XSS_SERVLET-1 + secondary_identifiers: + - name: Find Security Bugs-XSS_SERVLET + type: find_sec_bugs_type + value: XSS_SERVLET + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.XSS_SERVLET-1 + shortlink: https://sg.run/4kwE + semgrep.dev: + rule: + r_id: 21244 + rv_id: 835547 + rule_id: ZqUeEA + version_id: vdTOQxl + url: https://semgrep.dev/playground/r/vdTOQxl/gitlab.find_sec_bugs.XSS_SERVLET-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: org.owasp.encoder.Encode.forHtml($TAINTED); + - pattern: "$TAINTED" + pattern-sinks: + - patterns: + - pattern-inside: "$FUNC(..., HttpServletResponse $RES, ...) {...}" + - pattern-inside: | + $WRITER = $RES.getWriter(); + ... + - pattern: "$WRITER.write($DATA,...);" + - pattern: "$DATA" + - patterns: + - pattern-inside: "$FUNC(..., HttpServletResponse $RES, ...) {...}" + - pattern: "$RES.getWriter().write($DATA,...);" + - pattern: "$DATA" + pattern-sources: + - patterns: + - pattern-inside: "$FUNC(..., HttpServletRequest $REQ, ...) {...}" + - pattern: "$REQ.getParameter(...);" + severity: WARNING +- id: gitlab.find_sec_bugs.XSS_SERVLET-2.XSS_SERVLET_PARAMETER-1 + languages: + - java + message: | + The Servlet can read GET and POST parameters from various methods. The value obtained should be + considered unsafe. You may need to validate or sanitize those values before passing them to + sensitive APIs + metadata: + category: security + cwe: CWE-20 + shortDescription: Improper Input Validation + technology: + - java + primary_identifier: find_sec_bugs.XSS_SERVLET-2.XSS_SERVLET_PARAMETER-1 + secondary_identifiers: + - name: Find Security Bugs-XSS_SERVLET + type: find_sec_bugs_type + value: XSS_SERVLET + - name: Find Security Bugs-XSS_SERVLET_PARAMETER + type: find_sec_bugs_type + value: XSS_SERVLET_PARAMETER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.XSS_SERVLET-2.XSS_SERVLET_PARAMETER-1 + shortlink: https://sg.run/PP6q + semgrep.dev: + rule: + r_id: 21245 + rv_id: 835548 + rule_id: nJUneR + version_id: d6TKg2J + url: https://semgrep.dev/playground/r/d6TKg2J/gitlab.find_sec_bugs.XSS_SERVLET-2.XSS_SERVLET_PARAMETER-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern-inside: "$TYPE $FUNC(..., ServletRequest $REQ, ...) { ... }" + - pattern-either: + - pattern: "$REQ.getParameter(...);" + - pattern: "$REQ.getParameterValues();" + - pattern: "$REQ.getParameterMap(...);" + - pattern: "$REQ.getParameterNames();" + - patterns: + - pattern-inside: "$TYPE $FUNC(..., HttpServletRequest $SREQ, ...) { ... }" + - pattern-either: + - pattern: "$SREQ.getRequestedSessionId();" + - pattern: "$SREQ.getQueryString();" + - pattern: "$SREQ.getParameter(...);" + - pattern: "$SREQ.getParameterValues();" + - pattern: "$SREQ.getParameterMap(...);" + - pattern: "$SREQ.getParameterNames();" + - patterns: + - pattern: "$SREQ.getHeader($HEADER);" + - metavariable-regex: + metavariable: "$HEADER" + regex: "(?i)(Host|Referer|User-Agent)" + severity: WARNING +- id: gitlab.find_sec_bugs.XXE_DTD_TRANSFORM_FACTORY-1.XXE_XSLT_TRANSFORM_FACTORY-1 + languages: + - java + message: | + XML External Entity (XXE) attacks can occur when an XML parser supports XML + entities while processing XML received from an untrusted source. + metadata: + category: security + cwe: CWE-611 + shortDescription: Improper Restriction of XML External Entity Reference ('XXE') + primary_identifier: find_sec_bugs.XXE_DTD_TRANSFORM_FACTORY-1.XXE_XSLT_TRANSFORM_FACTORY-1 + secondary_identifiers: + - name: Find Security Bugs-XXE_DTD_TRANSFORM_FACTORY + type: find_sec_bugs_type + value: XXE_DTD_TRANSFORM_FACTORY + - name: Find Security Bugs-XXE_XSLT_TRANSFORM_FACTORY + type: find_sec_bugs_type + value: XXE_XSLT_TRANSFORM_FACTORY + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs.XXE_DTD_TRANSFORM_FACTORY-1.XXE_XSLT_TRANSFORM_FACTORY-1 + shortlink: https://sg.run/5Zx3 + semgrep.dev: + rule: + r_id: 21247 + rv_id: 835550 + rule_id: 7KUb72 + version_id: nWTyNA4 + url: https://semgrep.dev/playground/r/nWTyNA4/gitlab.find_sec_bugs.XXE_DTD_TRANSFORM_FACTORY-1.XXE_XSLT_TRANSFORM_FACTORY-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: import javax.xml.transform.*; ... + - pattern-inside: | + $T = $FACT.newTransformer(); + ... + - pattern-not-inside: | + $T.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + ... + - pattern-not-inside: | + $T.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + ... + - pattern-not-inside: | + $T.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + ... + - pattern: "$T.transform(...)" + severity: ERROR +- id: gitlab.find_sec_bugs.XXE_SAXPARSER-1 + 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). + + It is recommended that the `SAXParser` is configured to disable DTD doctypes as this protects + 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 ,...)" + - patterns: + - pattern-either: + - pattern: | + $CMDARR = arrayOf("$SHELL",...,<...$PARAM...>,...) + ... + $R.exec($CMDARR,...) + - pattern: $R.exec(arrayOf("$SHELL",...,<...$PARAM...>,...), ...) + - pattern: $R.exec(java.util.String.format("...", ...,<...$PARAM...>,...)) + - pattern: "$R.exec(($A: String) + ($B: String))" + - metavariable-regex: + metavariable: "$SHELL" + regex: "(/.../)?(sh|bash|ksh|csh|tcsh|zsh)$" + - pattern-not: $R.exec("...","...","...",...) + - pattern-not: '$R.exec(arrayOf("...","...","...",...),...) + + ' + - patterns: + - pattern-inside: | + fun $FUNC(..., $PARAM: String, ...) { + ... + } + - pattern-inside: | + $PB = ProcessBuilder() + ... + - pattern-either: + - pattern: "$PB.command(<...$PARAM...>,...)" + - patterns: + - pattern-inside: "$VAL = <...$PARAM...>; ..." + - pattern: "$PB.command(<...$VAL...>,...)" + - patterns: + - pattern-either: + - pattern: $PB.command("$SHELL",...,<...$PARAM...>,...) + - pattern: | + $CMDARR = java.util.Arrays.asList("$SHELL",...,<...$PARAM...>,...) + ... + $PB.command($CMDARR,...) + - pattern: $PB.command(java.util.Arrays.asList("$SHELL",...,<...$PARAM...>,...),...) + - pattern: $PB.command(java.util.String.format("...", ...,<...$PARAM...>,...)) + - pattern: "$PB.command(($A: String) + ($B: String))" + - metavariable-regex: + metavariable: "$SHELL" + regex: "(/.../)?(sh|bash|ksh|csh|tcsh|zsh)$" + - pattern-not: $PB.command("...","...","...",...) + - pattern-not: '$PB.command(java.util.Arrays.asList("...","...","...",...)) + + ' +- id: gitlab.find_sec_bugs_kotlin.CUSTOM_MESSAGE_DIGEST-1 + languages: + - kotlin + message: | + Implementing a custom MessageDigest is error-prone. 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. + severity: WARNING + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm + category: security + cwe: CWE-327 + owasp: + - A6:2017-Security Misconfiguration + - A04:2021-Insecure Design + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.CUSTOM_MESSAGE_DIGEST-1 + secondary_identifiers: + - name: Find Security Bugs-CUSTOM_MESSAGE_DIGEST + type: find_sec_bugs_type + value: CUSTOM_MESSAGE_DIGEST + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.CUSTOM_MESSAGE_DIGEST-1 + shortlink: https://sg.run/oqPQn + semgrep.dev: + rule: + r_id: 144316 + rv_id: 920407 + rule_id: PeUJ47p + version_id: WrTYnJ8 + url: https://semgrep.dev/playground/r/WrTYnJ8/gitlab.find_sec_bugs_kotlin.CUSTOM_MESSAGE_DIGEST-1 + origin: community + subcategory: + - audit + pattern: | + class $CLAZZ : java.security.MessageDigest(...) { + ... + } +- id: gitlab.find_sec_bugs_kotlin.DANGEROUS_PERMISSION_COMBINATION-1 + languages: + - kotlin + message: 'Do not grant dangerous combinations of permissions. + + ' + metadata: + shortDescription: Improper privilege management + category: security + cwe: CWE-269 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + confidence: HIGH + security-severity: MEDIUM + primary_identifier: find_sec_bugs.DANGEROUS_PERMISSION_COMBINATION-1 + secondary_identifiers: + - name: Find Security Bugs-DANGEROUS_PERMISSION_COMBINATION + type: find_sec_bugs_type + value: DANGEROUS_PERMISSION_COMBINATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.DANGEROUS_PERMISSION_COMBINATION-1 + shortlink: https://sg.run/gx36y + semgrep.dev: + rule: + r_id: 144341 + rv_id: 920432 + rule_id: lBU4kqe + version_id: jQTwjJE + url: https://semgrep.dev/playground/r/jQTwjJE/gitlab.find_sec_bugs_kotlin.DANGEROUS_PERMISSION_COMBINATION-1 + origin: community + subcategory: + - audit + severity: WARNING + patterns: + - pattern-either: + - patterns: + - pattern-inside: | + $PC = $X.getPermissions(...) + ... + - pattern: "$PC.add($PERMISSION)" + - pattern: | + $REFVAR = $PERMISSION + ...; + ($PC: PermissionCollection).add($REFVAR) + - pattern: "($PC: PermissionCollection).add($PERMISSION)" + - metavariable-pattern: + metavariable: "$PERMISSION" + pattern-either: + - pattern: ReflectPermission("suppressAccessChecks") + - pattern: RuntimePermission("createClassLoader") +- id: gitlab.find_sec_bugs_kotlin.DES_USAGE-1 + languages: + - kotlin + message: | + DES is considered strong ciphers for modern applications. Currently, NIST recommends the usage + of AES block ciphers instead of DES. + severity: WARNING + metadata: + shortDescription: Inadequate encryption strength + category: security + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.DES_USAGE-1 + secondary_identifiers: + - name: Find Security Bugs-DES_USAGE + type: find_sec_bugs_type + value: DES_USAGE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.DES_USAGE-1 + shortlink: https://sg.run/KxrY6 + semgrep.dev: + rule: + r_id: 144311 + rv_id: 920402 + rule_id: 8GUQRPl + version_id: GxToXBo + url: https://semgrep.dev/playground/r/GxToXBo/gitlab.find_sec_bugs_kotlin.DES_USAGE-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: javax.crypto.Cipher.getInstance($TRANSFORMATION, ...) + - metavariable-regex: + metavariable: "$TRANSFORMATION" + regex: ^"DES(/|"$) +- id: gitlab.find_sec_bugs_kotlin.DMI_CONSTANT_DB_PASSWORD-1.HARD_CODE_PASSWORD-3 + pattern: 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 + technology: + - kotlin + security-severity: Critical + primary_identifier: find_sec_bugs.DMI_CONSTANT_DB_PASSWORD-1.HARD_CODE_PASSWORD-3 + secondary_identifiers: + - name: Find Security Bugs-DMI_CONSTANT_DB_PASSWORD + type: find_sec_bugs_type + value: DMI_CONSTANT_DB_PASSWORD + - name: Find Security Bugs-HARD_CODE_PASSWORD + type: find_sec_bugs_type + value: HARD_CODE_PASSWORD + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.DMI_CONSTANT_DB_PASSWORD-1.HARD_CODE_PASSWORD-3 + shortlink: https://sg.run/7KRN4 + semgrep.dev: + rule: + r_id: 144338 + rv_id: 920429 + rule_id: 0oULNkq + version_id: pZTbDAY + url: https://semgrep.dev/playground/r/pZTbDAY/gitlab.find_sec_bugs_kotlin.DMI_CONSTANT_DB_PASSWORD-1.HARD_CODE_PASSWORD-3 + origin: community + subcategory: + - audit + languages: + - kotlin +- id: gitlab.find_sec_bugs_kotlin.DMI_EMPTY_DB_PASSWORD-1.HARD_CODE_PASSWORD-2 + 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 + technology: + - kotlin + security-severity: Critical + primary_identifier: find_sec_bugs.DMI_EMPTY_DB_PASSWORD-1.HARD_CODE_PASSWORD-2 + secondary_identifiers: + - name: Find Security Bugs-DMI_EMPTY_DB_PASSWORD + type: find_sec_bugs_type + value: DMI_EMPTY_DB_PASSWORD + - name: Find Security Bugs-HARD_CODE_PASSWORD + type: find_sec_bugs_type + value: HARD_CODE_PASSWORD + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.DMI_EMPTY_DB_PASSWORD-1.HARD_CODE_PASSWORD-2 + shortlink: https://sg.run/L1bq7 + semgrep.dev: + rule: + r_id: 144339 + rv_id: 920430 + rule_id: KxUvE9Q + version_id: 2KTdOEq + url: https://semgrep.dev/playground/r/2KTdOEq/gitlab.find_sec_bugs_kotlin.DMI_EMPTY_DB_PASSWORD-1.HARD_CODE_PASSWORD-2 + origin: community + subcategory: + - audit + languages: + - kotlin +- id: gitlab.find_sec_bugs_kotlin.ECB_MODE-1 + languages: + - kotlin + message: | + An authentication cipher mode which provides better confidentiality of the encrypted data + should be used instead of Electronic Code Book (ECB) mode, which does not provide good + confidentiality. Specifically, ECB mode produces the same output for the same input each time. + This allows an attacker to intercept and replay the data. + metadata: + category: security + cwe: CWE-326 + shortDescription: Inadequate Encryption Strength + technology: + - kotlin + security-severity: CRITICAL + primary_identifier: find_sec_bugs.ECB_MODE-1 + secondary_identifiers: + - name: Find Security Bugs-ECB_MODE + type: find_sec_bugs_type + value: ECB_MODE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.ECB_MODE-1 + shortlink: https://sg.run/lBdQ5 + semgrep.dev: + rule: + r_id: 144313 + rv_id: 920404 + rule_id: QrUWPRO + version_id: A8TNlp5 + url: https://semgrep.dev/playground/r/A8TNlp5/gitlab.find_sec_bugs_kotlin.ECB_MODE-1 + origin: community + subcategory: + - audit + severity: ERROR + patterns: + - pattern: javax.crypto.Cipher.getInstance($TRANSFORMATION, ...) + - metavariable-regex: + metavariable: "$TRANSFORMATION" + regex: ^"[^/]*/ECB(/.*)?"$ +- id: gitlab.find_sec_bugs_kotlin.EL_INJECTION-1 + languages: + - kotlin + message: | + An expression is built with a dynamic value. The source of the value(s) should be verified to + avoid that unfiltered values fall into this risky code evaluation. + 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 + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.EL_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-EL_INJECTION + type: find_sec_bugs_type + value: EL_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.EL_INJECTION-1 + shortlink: https://sg.run/x80NP + semgrep.dev: + rule: + r_id: 144330 + rv_id: 920421 + rule_id: JDUN0wo + version_id: 0bTp3qB + url: https://semgrep.dev/playground/r/0bTp3qB/gitlab.find_sec_bugs_kotlin.EL_INJECTION-1 + origin: community + subcategory: + - audit + severity: WARNING + pattern-either: + - patterns: + - metavariable-regex: + metavariable: "$METHOD" + regex: "^create(Method|Value)Expression$" + - metavariable-pattern: + metavariable: "$EXPR" + patterns: + - pattern-not: '"..."' + - pattern: "($EXP: ExpressionFactory ).$METHOD(($CTX: $X.el.ELContext), $EXPR, + ...)\n" + - patterns: + - pattern: "($P: $X.el.ELProcessor).$METHOD(...)\n" + - pattern-not: '($P: $X.el.ELProcessor).$METHOD("...", ...) + + ' + - metavariable-regex: + metavariable: "$METHOD" + regex: "^(eval|(get|set)Value)$" +- id: gitlab.find_sec_bugs_kotlin.EXTERNAL_CONFIG_CONTROL-1 + languages: + - kotlin + message: | + Allowing external control of system settings can disrupt service or cause an application to + behave in unexpected, and potentially malicious ways. An attacker could cause an error by + providing a nonexistent catalog name or connect to an unauthorized portion of the database. + severity: WARNING + metadata: + shortDescription: External control of system or configuration setting + category: security + cwe: CWE-15 + owasp: + - A1:2017-Injection + - A03:2021-Injection + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.EXTERNAL_CONFIG_CONTROL-1 + secondary_identifiers: + - name: Find Security Bugs-EXTERNAL_CONFIG_CONTROL + type: find_sec_bugs_type + value: EXTERNAL_CONFIG_CONTROL + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.EXTERNAL_CONFIG_CONTROL-1 + shortlink: https://sg.run/DbpGW + semgrep.dev: + rule: + r_id: 144352 + rv_id: 920443 + rule_id: yyURlbK + version_id: e1TZKGz + url: https://semgrep.dev/playground/r/e1TZKGz/gitlab.find_sec_bugs_kotlin.EXTERNAL_CONFIG_CONTROL-1 + origin: community + subcategory: + - audit + patterns: + - metavariable-pattern: + metavariable: "$GET_PARAMETER" + pattern-either: + - pattern: "($REQ: HttpServletRequest).getParameter" + - pattern: "($REQ: HttpServletRequest?)?.getParameter" + - metavariable-pattern: + metavariable: "$SET_CATALOG" + pattern-either: + - pattern: "($CONN: java.sql.Connection).setCatalog" + - pattern: "($CONN: java.sql.Connection?)?.setCatalog" + - pattern: |- + $TAINTED = $GET_PARAMETER(...) + ... + $SET_CATALOG($TAINTED) +- id: gitlab.find_sec_bugs_kotlin.FILE_UPLOAD_FILENAME-1 + languages: + - kotlin + message: | + The filename provided by the FileUpload API can be tampered with by the client to reference + unauthorized files. The provided filename should be properly validated to ensure it's properly + structured, contains no unauthorized path characters (e.g., / \), and refers to an authorized + file. + metadata: + category: security + cwe: CWE-22 + shortDescription: Improper limitation of a pathname to a restricted directory + ('Path Traversal') + owasp: + - A1:2017-Injection + - A03:2021-Injection + technology: + - kotlin + security-severity: CRITICAL + primary_identifier: find_sec_bugs.FILE_UPLOAD_FILENAME-1 + secondary_identifiers: + - name: Find Security Bugs-FILE_UPLOAD_FILENAME + type: find_sec_bugs_type + value: FILE_UPLOAD_FILENAME + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.FILE_UPLOAD_FILENAME-1 + shortlink: https://sg.run/NbkY1 + semgrep.dev: + rule: + r_id: 144327 + rv_id: 920418 + rule_id: qNU26gX + version_id: BjTKLvn + url: https://semgrep.dev/playground/r/BjTKLvn/gitlab.find_sec_bugs_kotlin.FILE_UPLOAD_FILENAME-1 + origin: community + subcategory: + - audit + severity: ERROR + pattern-either: + - patterns: + - pattern-inside: | + $FILES = ($SFU: ServletFileUpload).parseRequest(($REQ: $X.servlet.http.HttpServletRequest?)) + ... + for($ITEM in $FILES) { + ... + } + - pattern: "$ITEM.getName()" + - pattern: "($PART: $X.servlet.http.Part).getSubmittedFileName()" +- id: gitlab.find_sec_bugs_kotlin.FORMAT_STRING_MANIPULATION-1 + languages: + - kotlin + message: | + Allowing user input to control format parameters could enable an attacker to cause exceptions + to be thrown or leak information.Attackers may be able to modify the format string argument, + such that an exception is thrown. If this exception is left uncaught, it may crash the + application. Alternatively, if sensitive information is used within the unused arguments, + attackers may change the format string to reveal this information. + metadata: + shortDescription: Use of externally-controlled format string + cwe: CWE-134 + category: security + confidence: HIGH + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: CRITICAL + primary_identifier: find_sec_bugs.FORMAT_STRING_MANIPULATION-1 + secondary_identifiers: + - name: Find Security Bugs-FORMAT_STRING_MANIPULATION + type: find_sec_bugs_type + value: FORMAT_STRING_MANIPULATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.FORMAT_STRING_MANIPULATION-1 + shortlink: https://sg.run/GdjB1 + semgrep.dev: + rule: + r_id: 144348 + rv_id: 920439 + rule_id: X5UQDe1 + version_id: kbTOPej + url: https://semgrep.dev/playground/r/kbTOPej/gitlab.find_sec_bugs_kotlin.FORMAT_STRING_MANIPULATION-1 + origin: community + subcategory: + - audit + severity: ERROR + patterns: + - pattern-either: + - patterns: + - pattern-inside: | + $INPUT = ($REQ: HttpServletRequest).getParameter(...) + ... + - pattern-inside: | + $FORMAT_STR = ... + $INPUT + ... + - patterns: + - pattern-inside: | + $INPUT = ($REQ: HttpServletRequest).getParameter(...) + ... + - pattern-inside: | + $FORMAT_STR = ... + $INPUT + ... + ... + - pattern-inside: | + $FORMAT_STR = ... + ($REQ: HttpServletRequest).getParameter(...) + ... + ... + - pattern-inside: | + $FORMAT_STR = ... + ($REQ: HttpServletRequest).getParameter(...) + ... + - pattern-either: + - pattern: String.format($FORMAT_STR, ...) + - pattern: String.format(java.util.Locale.$LOCALE, $FORMAT_STR, ...) + - patterns: + - pattern-inside: | + $F = java.util.Formatter(...) + ... + - pattern-either: + - pattern: "$F.format($FORMAT_STR, ...)" + - pattern: "$F.format(java.util.Locale.$LOCALE, $FORMAT_STR, ...)" + - pattern: "($F: java.io.PrintStream).printf($FORMAT_STR, ...)" + - pattern: "($F: java.io.PrintStream).printf(java.util.Locale.$LOCALE, $FORMAT_STR, + ...)" + - pattern: "($F: java.io.PrintStream).format($FORMAT_STR, ...)" + - pattern: "($F: java.io.PrintStream).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, ...) +- id: gitlab.find_sec_bugs_kotlin.HARD_CODE_PASSWORD-1 + languages: + - kotlin + message: | + A potential hard-coded password was identified in the source code. + 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 + technology: + - kotlin + security-severity: High + primary_identifier: find_sec_bugs.HARD_CODE_PASSWORD-1 + secondary_identifiers: + - name: Find Security Bugs-HARD_CODE_PASSWORD + type: find_sec_bugs_type + value: HARD_CODE_PASSWORD + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.HARD_CODE_PASSWORD-1 + shortlink: https://sg.run/8GAN4 + semgrep.dev: + rule: + r_id: 144340 + rv_id: 920431 + rule_id: qNU26gK + version_id: X0TAKnb + url: https://semgrep.dev/playground/r/X0TAKnb/gitlab.find_sec_bugs_kotlin.HARD_CODE_PASSWORD-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: java.security.KeyStore.PasswordProtection("...".toCharArray()) + - pattern: java.security.KeyStore.getInstance(...).load(..., "...".toCharArray()) + - pattern: '($KS: java.security.KeyStore).load(..., "...".toCharArray())' + - pattern: KeyManagerFactory.getInstance(...).init(..., "...".toCharArray()) + - pattern: '($KMF: KeyManagerFactory).init(..., "...".toCharArray())' + - pattern: PBEKeySpec("...", ...) + - pattern: PasswordAuthentication("...", "...") + - pattern: '($CB: PasswordCallback).setPassword("...")' + - pattern: KerberosKey(...,"...",...) + - pattern: java.sql.DriverManager.getConnection(..., "...") + - pattern: io.vertx.ext.web.handler.CSRFHandler.create(..., "...") + - pattern: $S.setPassword("...") +- id: gitlab.find_sec_bugs_kotlin.HAZELCAST_SYMMETRIC_ENCRYPTION-1 + languages: + - kotlin + message: | + The network communications for Hazelcast is configured to use a symmetric cipher (probably DES + or Blowfish). Those ciphers alone do not provide integrity or secure authentication. The use of + asymmetric encryption is preferred. + severity: WARNING + metadata: + shortDescription: Inadequate encryption strength + category: security + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.HAZELCAST_SYMMETRIC_ENCRYPTION-1 + secondary_identifiers: + - name: Find Security Bugs-HAZELCAST_SYMMETRIC_ENCRYPTION + type: find_sec_bugs_type + value: HAZELCAST_SYMMETRIC_ENCRYPTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.HAZELCAST_SYMMETRIC_ENCRYPTION-1 + shortlink: https://sg.run/zdqQ0 + semgrep.dev: + rule: + r_id: 144317 + rv_id: 920408 + rule_id: JDUN0Oq + version_id: 0bTp3qG + url: https://semgrep.dev/playground/r/0bTp3qG/gitlab.find_sec_bugs_kotlin.HAZELCAST_SYMMETRIC_ENCRYPTION-1 + origin: community + subcategory: + - audit + pattern: com.hazelcast.config.SymmetricEncryptionConfig() +- id: gitlab.find_sec_bugs_kotlin.HRS_REQUEST_PARAMETER_TO_HTTP_HEADER-1 + languages: + - kotlin + message: | + This code directly writes an HTTP parameter to an HTTP header, which allows for a HTTP + response splitting vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting for + more information. + 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 + technology: + - kotlin + security-severity: CRITICAL + primary_identifier: find_sec_bugs.HRS_REQUEST_PARAMETER_TO_HTTP_HEADER-1 + secondary_identifiers: + - name: Find Security Bugs-HRS_REQUEST_PARAMETER_TO_HTTP_HEADER + type: find_sec_bugs_type + value: HRS_REQUEST_PARAMETER_TO_HTTP_HEADER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.HRS_REQUEST_PARAMETER_TO_HTTP_HEADER-1 + shortlink: https://sg.run/Dbp3W + semgrep.dev: + rule: + r_id: 144308 + rv_id: 920399 + rule_id: EwUj7yz + version_id: PkTjGbo + url: https://semgrep.dev/playground/r/PkTjGbo/gitlab.find_sec_bugs_kotlin.HRS_REQUEST_PARAMETER_TO_HTTP_HEADER-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - patterns: + - metavariable-pattern: + metavariable: "$S0" + pattern-either: + - pattern: "..." + - pattern: '""' + - metavariable-pattern: + metavariable: "$PATTERN" + patterns: + - pattern: "..." + - pattern-regex: ".*\\[\\]?(?=[^]]*\\\\r)(?=[^]]*\\\\n)[^]]*\\]\\+" + - pattern-inside: | + $STR.replace($PATTERN, $S0); + ... + - pattern: org.apache.commons.text.StringEscapeUtils.unescapeJava(...); + pattern-sinks: + - pattern: '($RES: $X.servlet.http.HttpServletResponse).setHeader("$KEY", ...);' + - pattern: '($RES: $X.servlet.http.HttpServletResponse).addHeader("$KEY", ...);' + - pattern: '($WRP: $X.servlet.http.HttpServletResponseWrapper).setHeader("$KEY", + ...);' + - pattern: '($WRP: $X.servlet.http.HttpServletResponseWrapper).addHeader("$KEY", + ...);' + pattern-sources: + - pattern: "($REQ: $X.servlet.http.HttpServletRequest).getParameter(...);" + - pattern: "($REQ: $X.servlet.http.HttpServletRequest).getParameterNames();" + - pattern: "($REQ: $X.servlet.http.HttpServletRequest).getParameterValues(...);" + - pattern: "($REQ: $X.servlet.http.HttpServletRequest).getParameterMap();" + - pattern: "($REQ: $X.servlet.http.HttpServletRequest).getHeader(...);" + - pattern: "($REQ: $X.servlet.http.HttpServletRequest).getPathInfo();" +- id: gitlab.find_sec_bugs_kotlin.HTTPONLY_COOKIE-1 + languages: + - kotlin + message: | + A new cookie is created without the HttpOnly flag set. The HttpOnly flag is a directive to the + browser to make sure that the cookie can not be red by malicious script. When a user is the + target of a "Cross-Site Scripting", the attacker would benefit greatly from getting the session + id for example. + severity: WARNING + metadata: + shortDescription: Sensitive cookie without 'HttpOnly' flag + category: security + owasp: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + cwe: CWE-1004 + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.HTTPONLY_COOKIE-1 + secondary_identifiers: + - name: Find Security Bugs-HTTPONLY_COOKIE + type: find_sec_bugs_type + value: HTTPONLY_COOKIE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.HTTPONLY_COOKIE-1 + shortlink: https://sg.run/Redj2 + semgrep.dev: + rule: + r_id: 144305 + rv_id: 920396 + rule_id: d8UrXO1 + version_id: QkT1N2z + url: https://semgrep.dev/playground/r/QkT1N2z/gitlab.find_sec_bugs_kotlin.HTTPONLY_COOKIE-1 + origin: community + subcategory: + - audit + patterns: + - pattern: | + $C = $X.servlet.http.Cookie(..., ...) + ...; + ($RESP: $X.servlet.http.HttpServletResponse).addCookie($C) + - pattern-not-inside: | + $C = $X.servlet.http.Cookie(..., ...) + ... + $C.setHttpOnly(true) + ...; + ($RESP: $X.servlet.http.HttpServletResponse).addCookie($C) +- id: gitlab.find_sec_bugs_kotlin.HTTP_PARAMETER_POLLUTION-1 + languages: + - kotlin + message: | + Concatenating unvalidated user input into a URL can allow an attacker to override the value of + a request parameter. Attacker may be able to override existing parameter values, inject a new + parameter or exploit variables out of a direct reach. HTTP Parameter Pollution (HPP) attacks + consist of injecting encoded query string delimiters into other existing parameters. If a web + application does not properly sanitize the user input, a malicious user may compromise the + logic of the application to perform either client-side or server-side attacks. + 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 + technology: + - kotlin + security-severity: CRITICAL + primary_identifier: find_sec_bugs.HTTP_PARAMETER_POLLUTION-1 + secondary_identifiers: + - name: Find Security Bugs-HTTP_PARAMETER_POLLUTION + type: find_sec_bugs_type + value: HTTP_PARAMETER_POLLUTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.HTTP_PARAMETER_POLLUTION-1 + shortlink: https://sg.run/eq7lE + semgrep.dev: + rule: + r_id: 144332 + rv_id: 920423 + rule_id: GdUvNO6 + version_id: qkTpwJD + url: https://semgrep.dev/playground/r/qkTpwJD/gitlab.find_sec_bugs_kotlin.HTTP_PARAMETER_POLLUTION-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sources: + - pattern: "($REQ: HttpServletRequest).getParameter(...)" + pattern-sanitizers: + - pattern: java.net.URLEncoder.encode(...) + - pattern: com.google.common.net.UrlEscapers.urlPathSegmentEscaper().escape(...) + pattern-sinks: + - pattern: org.apache.http.client.methods.HttpGet(...) + - pattern: org.apache.commons.httpclient.methods.GetMethod(...) + - pattern: "($GM: org.apache.commons.httpclient.methods.GetMethod).setQueryString(...)" +- id: gitlab.find_sec_bugs_kotlin.HTTP_RESPONSE_SPLITTING-1 + languages: + - kotlin + message: | + When an HTTP request contains unexpected CR and LF characters, the server may respond with an + output stream that is interpreted as two different HTTP responses (instead of one). An attacker + can control the second response and mount attacks such as cross-site scripting and cache + poisoning attacks. + 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 + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.HTTP_RESPONSE_SPLITTING-1 + secondary_identifiers: + - name: Find Security Bugs-HTTP_RESPONSE_SPLITTING + type: find_sec_bugs_type + value: HTTP_RESPONSE_SPLITTING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.HTTP_RESPONSE_SPLITTING-1 + shortlink: https://sg.run/BYoR9 + semgrep.dev: + rule: + r_id: 144307 + rv_id: 920398 + rule_id: nJUxX53 + version_id: 44Teq82 + url: https://semgrep.dev/playground/r/44Teq82/gitlab.find_sec_bugs_kotlin.HTTP_RESPONSE_SPLITTING-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - patterns: + - metavariable-pattern: + metavariable: "$S0" + pattern-either: + - pattern: "..." + - pattern: '""' + - metavariable-pattern: + metavariable: "$PATTERN" + patterns: + - pattern: "..." + - pattern-regex: ".*\\[\\]?(?=[^]]*\\\\r)(?=[^]]*\\\\n)[^]]*\\]\\+" + - pattern-inside: | + $STR.replace($PATTERN, $S0) + ... + - pattern: org.apache.commons.text.StringEscapeUtils.escapeJava(...) + pattern-sinks: + - pattern: javax.servlet.http.Cookie("$KEY", ...) + - patterns: + - pattern-inside: | + $C = javax.servlet.http.Cookie("$KEY", ...) + ... + - pattern: "$C.setValue(...)" + pattern-sources: + - pattern: "($REQ: javax.servlet.http.HttpServletRequest).getParameter(...)" + - pattern: "($REQ: javax.servlet.http.HttpServletRequest).getParameterNames()" + - pattern: "($REQ: javax.servlet.http.HttpServletRequest).getParameterValues(...)" + - pattern: "($REQ: javax.servlet.http.HttpServletRequest).getParameterMap()" + - pattern: "($REQ: javax.servlet.http.HttpServletRequest).getHeader(...)" + - pattern: "($REQ: javax.servlet.http.HttpServletRequest).getPathInfo()" +- id: gitlab.find_sec_bugs_kotlin.INSECURE_COOKIE-1 + languages: + - kotlin + message: | + "A new cookie is created without the Secure flag set. The Secure flag is a + directive to the browser to make sure that the cookie is not sent for insecure communication + (http://)" + severity: WARNING + metadata: + shortDescription: Sensitive cookie in HTTPS session without 'Secure' attribute + category: security + cwe: CWE-614 + owasp: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.INSECURE_COOKIE-1 + secondary_identifiers: + - name: Find Security Bugs-INSECURE_COOKIE + type: find_sec_bugs_type + value: INSECURE_COOKIE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.INSECURE_COOKIE-1 + shortlink: https://sg.run/Ab6G6 + semgrep.dev: + rule: + r_id: 144306 + rv_id: 920397 + rule_id: ZqUQ0k0 + version_id: 3ZTLwbB + url: https://semgrep.dev/playground/r/3ZTLwbB/gitlab.find_sec_bugs_kotlin.INSECURE_COOKIE-1 + origin: community + subcategory: + - audit + patterns: + - pattern: | + $C = $X.servlet.http.Cookie(..., ...) + ...; + ($RESP: $X.servlet.http.HttpServletResponse).addCookie($C) + - pattern-not-inside: | + $C = $X.servlet.http.Cookie(..., ...) + ... + $C.setSecure(true) + ...; + ($RESP: $X.servlet.http.HttpServletResponse).addCookie($C) +- id: gitlab.find_sec_bugs_kotlin.INSECURE_SMTP_SSL-1 + languages: + - kotlin + message: 'Server identity verification is disabled when making SSL connections. + + ' + metadata: + shortDescription: Improper validation of certificate with host mismatch + category: security + cwe: CWE-297 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: CRITICAL + primary_identifier: find_sec_bugs.INSECURE_SMTP_SSL-1 + secondary_identifiers: + - name: Find Security Bugs-INSECURE_SMTP_SSL + type: find_sec_bugs_type + value: INSECURE_SMTP_SSL + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.INSECURE_SMTP_SSL-1 + shortlink: https://sg.run/4bJZZ + semgrep.dev: + rule: + r_id: 144344 + rv_id: 920435 + rule_id: oqUgqQQ + version_id: yeTDgew + url: https://semgrep.dev/playground/r/yeTDgew/gitlab.find_sec_bugs_kotlin.INSECURE_SMTP_SSL-1 + origin: community + subcategory: + - audit + severity: ERROR + patterns: + - pattern-either: + - pattern-inside: | + $E = org.apache.commons.mail.SimpleEmail(...) + ... + - pattern-inside: | + $E = org.apache.commons.mail.Email(...) + ... + - pattern-inside: | + $E = org.apache.commons.mail.MultiPartEmail(...) + ... + - pattern-inside: | + $E = org.apache.commons.mail.HtmlEmail(...) + ... + - pattern-inside: | + $E = org.apache.commons.mail.ImageHtmlEmail(...) + ... + - pattern-not: | + $E.setSSLOnConnect(true) + ... + $E.setSSLCheckServerIdentity(true) +- id: gitlab.find_sec_bugs_kotlin.LDAP_ANONYMOUS-1 + languages: + - kotlin + message: | + Without proper access control, executing an LDAP statement that contains a + user-controlled value can allow an attacker to abuse poorly configured LDAP + context + metadata: + shortDescription: Missing authentication for critical function (LDAP) + category: security + cwe: CWE-306 + owasp: + - A2:2017-Broken Authentication + - A07:2021-Identification and Authentication Failures + security-severity: MEDIUM + primary_identifier: find_sec_bugs.LDAP_ANONYMOUS-1 + secondary_identifiers: + - name: Find Security Bugs-LDAP_ANONYMOUS + type: find_sec_bugs_type + value: LDAP_ANONYMOUS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.LDAP_ANONYMOUS-1 + shortlink: https://sg.run/Ew2Ro + semgrep.dev: + rule: + r_id: 144337 + rv_id: 920428 + rule_id: WAUWB5G + version_id: zyTG3r2 + url: https://semgrep.dev/playground/r/zyTG3r2/gitlab.find_sec_bugs_kotlin.LDAP_ANONYMOUS-1 + origin: community + subcategory: + - audit + severity: WARNING + patterns: + - pattern-inside: | + import javax.naming.Context + ... + - pattern: $ENV[Context.SECURITY_AUTHENTICATION] = "none" +- id: gitlab.find_sec_bugs_kotlin.LDAP_INJECTION-1 + languages: + - kotlin + message: | + Just like SQL, all inputs passed to an LDAP query need to be passed in safely. Unfortunately, + LDAP doesn't have prepared statement interfaces like SQL. Therefore, the primary defense + against LDAP injection is strong input validation of any untrusted data before including it in + an LDAP query. + 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 + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.LDAP_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-LDAP_INJECTION + type: find_sec_bugs_type + value: LDAP_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.LDAP_INJECTION-1 + shortlink: https://sg.run/v8DwR + semgrep.dev: + rule: + r_id: 144333 + rv_id: 920424 + rule_id: ReUDJWR + version_id: l4TXD1G + url: https://semgrep.dev/playground/r/l4TXD1G/gitlab.find_sec_bugs_kotlin.LDAP_INJECTION-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sinks: + - pattern: javax.naming.ldap.LdapName(...) + - pattern: "($C: javax.naming.directory.Context).lookup(...)" + - pattern: "($C: javax.naming.Context).lookup(...)" + - patterns: + - pattern-inside: "($C: com.unboundid.ldap.sdk.LDAPConnection).search($QUERY, + ...)" + - pattern: "$QUERY" + - patterns: + - pattern-either: + - 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: "($C: DirContext)" + - pattern: "($IDC: InitialDirContext)" + - pattern: "($LC: LdapContext)" + - pattern: "($EDC: EventDirContext)" + - pattern: "($LC: LdapCtx)" + - pattern: "($C: javax.naming.directory.DirContext)" + - pattern: "($IDC: javax.naming.directory.InitialDirContext)" + - pattern: "($LC: javax.naming.ldap.LdapContext)" + - pattern: "($EDC: javax.naming.event.EventDirContext)" + - pattern: "($LC: com.sun.jndi.ldap.LdapCtx)" + - patterns: + - pattern-either: + - pattern: "$CTX.lookup(...)" + - patterns: + - pattern-inside: "$CTX.search($QUERY, ...)" + - pattern: "$QUERY" + - patterns: + - pattern-inside: "$CTX.search($NAME, $FILTER, ...)" + - pattern: "$FILTER" + - pattern-inside: + pattern-either: + - pattern: "$CTX = DirContext(...);..." + - pattern: "$CTX = InitialDirContext(...);..." + - pattern: "$CTX = LdapContext(...);..." + - pattern: "$CTX = EventDirContext(...);..." + - pattern: "$CTX = LdapCtx(...);..." + - pattern: "$CTX = javax.naming.directory.DirContext(...);..." + - pattern: "$CTX = javax.naming.directory.InitialDirContext(...);..." + - pattern: "$CTX = javax.naming.ldap.LdapContext(...);..." + - pattern: "$CTX = javax.naming.event.EventDirContext(...);..." + - pattern: "$CTX = com.sun.jndi.ldap.LdapCtx(...);..." + - pattern-either: + - 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: "($LT: LdapTemplate)" + - pattern: "($LO: LdapOperations)" + - pattern: "($LT: org.springframework.ldap.core.LdapTemplate)" + - pattern: "($LO: org.springframework.ldap.core.LdapOperations)" + - 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" + - pattern-inside: + pattern-either: + - pattern: "$CTX = LdapTemplate(...);..." + - pattern: "$CTX = LdapOperations(...);..." + - pattern: "$CTX = org.springframework.ldap.core.LdapTemplate(...);..." + - pattern: "$CTX = org.springframework.ldap.core.LdapOperations(...);..." + pattern-sources: + - patterns: + - pattern-inside: | + fun $FUNC(..., $VAR: String, ...) { + ... + } + - pattern: "$VAR" + - patterns: + - pattern-inside: | + fun $FUNC(..., $X: String, ...) { + ... + $VAR = ... + $X + ... + } + - pattern: "$VAR" +- id: gitlab.find_sec_bugs_kotlin.MALICIOUS_XSLT-1 + languages: + - kotlin + message: | + It is possible to attach malicious behavior to those style sheets. Therefore, if an attacker + can control the content or the source of the style sheet, he might be able to trigger remote + code execution. + metadata: + shortDescription: Improper neutralization of special elements in output used by + a downstream component ('Injection') + category: security + cwe: CWE-74 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: MEDIUM + primary_identifier: find_sec_bugs.MALICIOUS_XSLT-1 + secondary_identifiers: + - name: Find Security Bugs-MALICIOUS_XSLT + type: find_sec_bugs_type + value: MALICIOUS_XSLT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.MALICIOUS_XSLT-1 + shortlink: https://sg.run/KxrK6 + semgrep.dev: + rule: + r_id: 144355 + rv_id: 920446 + rule_id: NbU3PWR + version_id: ZRTedXe + url: https://semgrep.dev/playground/r/ZRTedXe/gitlab.find_sec_bugs_kotlin.MALICIOUS_XSLT-1 + origin: community + subcategory: + - audit + severity: WARNING + mode: taint + pattern-sources: + - patterns: + - pattern-either: + - patterns: + - pattern-inside: | + fun $FUNC(...,$VAR: String, ...) { + ... + } + - pattern-either: + - pattern: FileInputStream(<... $VAR ...>); + - pattern: javaClass.getResourceAsStream(<... $VAR ...>) + - patterns: + - pattern-inside: | + class $CLZ { + var $X = "..."; + ... + } + - pattern-inside: | + fun $FUNC(...,$Y: String, ...) { + ... + } + - pattern-either: + - pattern: FileInputStream($X + $Y); + - pattern: javaClass.getResourceAsStream($X + $Y) + pattern-sinks: + - patterns: + - pattern-either: + - pattern-inside: "($T: javax.xml.transform.TransformerFactory).newTransformer($SRC, + ...)" + - pattern-inside: "($T: javax.xml.transform.Transformer).transform($SRC, ...)" + - patterns: + - pattern-inside: |- + $FACTORY = javax.xml.transform.TransformerFactory.newInstance(...) + ... + - pattern-inside: "$FACTORY.newTransformer($SRC, ...)" + - patterns: + - pattern-inside: |- + $FACTORY = javax.xml.transform.TransformerFactory(...) + ... + - pattern-inside: |- + $T = $FACTORY.newTransformer(...) + ... + - pattern-inside: "$T.transform($SRC, ...)" + - pattern: "$SRC" +- id: gitlab.find_sec_bugs_kotlin.MODIFICATION_AFTER_VALIDATION-1 + languages: + - kotlin + message: 'CERT: IDS11-J. Perform any string modifications before validation + + ' + metadata: + shortDescription: Collapse of data into unsafe value + category: security + cwe: CWE-182 + confidence: HIGH + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: MEDIUM + primary_identifier: find_sec_bugs.MODIFICATION_AFTER_VALIDATION-1 + secondary_identifiers: + - name: Find Security Bugs-MODIFICATION_AFTER_VALIDATION + type: find_sec_bugs_type + value: MODIFICATION_AFTER_VALIDATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.MODIFICATION_AFTER_VALIDATION-1 + shortlink: https://sg.run/Redp2 + semgrep.dev: + rule: + r_id: 144349 + rv_id: 920440 + rule_id: j2UgdeW + version_id: w8TkbyJ + url: https://semgrep.dev/playground/r/w8TkbyJ/gitlab.find_sec_bugs_kotlin.MODIFICATION_AFTER_VALIDATION-1 + origin: community + subcategory: + - audit + severity: WARNING + patterns: + - pattern-inside: | + $PATTERN = Pattern.compile(...) + ... + - pattern-inside: | + $PATTERN.matcher($VAR) + ... + - pattern-either: + - pattern: "$VAR + $OTHER\n" + - patterns: + - pattern: "$VAR.$METHOD(...)\n" + - metavariable-regex: + metavariable: "$METHOD" + regex: "(replace|replaceAll|replaceFirst|concat)" +- id: gitlab.find_sec_bugs_kotlin.NORMALIZATION_AFTER_VALIDATION-1 + languages: + - kotlin + message: 'IDS01-J. Normalize strings before validating them + + ' + metadata: + shortDescription: 'Incorrect behavior order: validate before canonicalize' + category: security + cwe: CWE-180 + confidence: HIGH + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: MEDIUM + primary_identifier: find_sec_bugs.NORMALIZATION_AFTER_VALIDATION-1 + secondary_identifiers: + - name: Find Security Bugs-NORMALIZATION_AFTER_VALIDATION + type: find_sec_bugs_type + value: NORMALIZATION_AFTER_VALIDATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.NORMALIZATION_AFTER_VALIDATION-1 + shortlink: https://sg.run/Ab636 + semgrep.dev: + rule: + r_id: 144350 + rv_id: 920441 + rule_id: 10UO6W6 + version_id: xyTdrQW + url: https://semgrep.dev/playground/r/xyTdrQW/gitlab.find_sec_bugs_kotlin.NORMALIZATION_AFTER_VALIDATION-1 + origin: community + subcategory: + - audit + severity: WARNING + patterns: + - pattern: |- + $Y = java.util.regex.Pattern.compile("[<>]"); + ... + $Y.matcher($VAR); + ... + java.text.Normalizer.normalize($VAR, ...); +- id: gitlab.find_sec_bugs_kotlin.NULL_CIPHER-1 + languages: + - kotlin + message: | + The NullCipher implements the Cipher interface by returning ciphertext identical to the + supplied plaintext. In a few contexts, such as testing, a NullCipher may be appropriate. Avoid + using the NullCipher. Its accidental use can introduce a significant confidentiality risk. + 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 + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.NULL_CIPHER-1 + secondary_identifiers: + - name: Find Security Bugs-NULL_CIPHER + type: find_sec_bugs_type + value: NULL_CIPHER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.NULL_CIPHER-1 + shortlink: https://sg.run/2Z4qY + semgrep.dev: + rule: + r_id: 144319 + rv_id: 920410 + rule_id: GdUvNb9 + version_id: qkTpwJJ + url: https://semgrep.dev/playground/r/qkTpwJJ/gitlab.find_sec_bugs_kotlin.NULL_CIPHER-1 + origin: community + subcategory: + - audit + pattern: javax.crypto.NullCipher() +- id: gitlab.find_sec_bugs_kotlin.OGNL_INJECTION-1 + message: | + "A expression is built with a dynamic value. The source of the value(s) should be verified to + avoid that unfiltered values fall into this risky code evaluation." + languages: + - kotlin + severity: WARNING + metadata: + shortDescription: Expression injection (OGNL) + category: security + cwe: CWE-917 + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.OGNL_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-OGNL_INJECTION + type: find_sec_bugs_type + value: OGNL_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.OGNL_INJECTION-1 + shortlink: https://sg.run/d8dq5 + semgrep.dev: + rule: + r_id: 144334 + rv_id: 920425 + rule_id: AbU9DPg + version_id: YDTYb49 + url: https://semgrep.dev/playground/r/YDTYb49/gitlab.find_sec_bugs_kotlin.OGNL_INJECTION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern-inside: | + fun $FUNC(..., $VAR: String, ...) { + ... + } + - pattern-inside: | + fun $FUNC(..., $VAR: Map<$K,$V>, ...) { + ... + } + - pattern-inside: | + fun $FUNC(..., $VAR: Map<$K,*>, ...) { + ... + } + - pattern-inside: | + fun $FUNC(..., $VAR: java.util.HashMap<$K,$V>, ...) { + ... + } + - pattern-either: + - pattern: com.opensymphony.xwork2.util.TextParseUtil.translateVariables(...,$VAR, + ...) + - pattern: com.opensymphony.xwork2.util.TextParseUtil.translateVariablesCollection(..., + $VAR, ...) + - pattern: com.opensymphony.xwork2.util.TextParseUtil.shallBeIncluded(..., $VAR, + ...) + - pattern: com.opensymphony.xwork2.util.TextParseUtil.commaDelimitedStringToSet(..., + $VAR, ...) + - pattern: "($P:com.opensymphony.xwork2.util.TextParser).evaluate(..., $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.OgnlTextParser).evaluate(..., $VAR, + ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).getGetMethod(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).getSetMethod(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).getField(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).setProperties(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).setProperty(...,$VAR, + ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).getValue(...,$VAR, + ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).setValue(...,$VAR, + ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).getGetMethod(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).getSetMethod(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).getField(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).setProperties(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).setProperty(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).getValue(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).setValue(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlUtil).setProperties(..., $VAR, + ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlUtil).setProperty(..., $VAR, + ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlUtil).getValue(..., $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlUtil).setValue(..., $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlUtil).callMethod(..., $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlUtil).compile(..., $VAR, ...)" + - pattern: "($P:org.apache.struts2.util.VelocityStrutsUtil).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(...) + - pattern: org.apache.struts2.util.StrutsUtil.makeSelectList(..., $VAR, ...) + - pattern: "($T:org.apache.struts2.views.jsp.ui.OgnlTool).findValue(..., $VAR, + ...)" + - pattern: "($V:com.opensymphony.xwork2.util.ValueStack).findString(...)" + - pattern: "($V:com.opensymphony.xwork2.util.ValueStack).findValue(..., $VAR, + ...)" + - pattern: "($V:com.opensymphony.xwork2.util.ValueStack).setValue(..., $VAR, ...)" + - pattern: "($V:com.opensymphony.xwork2.util.ValueStack).setParameter(..., $VAR, + ...)" +- id: gitlab.find_sec_bugs_kotlin.OVERLY_PERMISSIVE_FILE_PERMISSION-1 + languages: + - kotlin + message: 'Overly permissive file permission + + ' + metadata: + shortDescription: Incorrect permission assignment for critical resource + cwe: CWE-732 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + category: security + confidence: HIGH + security-severity: MEDIUM + primary_identifier: find_sec_bugs.OVERLY_PERMISSIVE_FILE_PERMISSION-1 + secondary_identifiers: + - name: Find Security Bugs-OVERLY_PERMISSIVE_FILE_PERMISSION + type: find_sec_bugs_type + value: OVERLY_PERMISSIVE_FILE_PERMISSION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.OVERLY_PERMISSIVE_FILE_PERMISSION-1 + shortlink: https://sg.run/Qrdzx + semgrep.dev: + rule: + r_id: 144342 + rv_id: 920433 + rule_id: YGUpWGx + version_id: 1QT4NQj + url: https://semgrep.dev/playground/r/1QT4NQj/gitlab.find_sec_bugs_kotlin.OVERLY_PERMISSIVE_FILE_PERMISSION-1 + origin: community + subcategory: + - audit + severity: WARNING + 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,}" +- id: gitlab.find_sec_bugs_kotlin.PADDING_ORACLE-1 + languages: + - kotlin + message: | + This specific mode of CBC with PKCS5Padding is susceptible to padding oracle attacks. An + adversary could potentially decrypt the message if the system exposed the difference between + plaintext with invalid padding or valid padding. The distinction between valid and invalid + padding is usually revealed through distinct error messages being returned for each condition. + 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 + technology: + - java + security-severity: CRITICAL + primary_identifier: find_sec_bugs.PADDING_ORACLE-1 + secondary_identifiers: + - name: Find Security Bugs-PADDING_ORACLE + type: find_sec_bugs_type + value: PADDING_ORACLE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.PADDING_ORACLE-1 + shortlink: https://sg.run/6JGoj + semgrep.dev: + rule: + r_id: 144315 + rv_id: 920406 + rule_id: 4bUR4Kn + version_id: DkT2y7R + url: https://semgrep.dev/playground/r/DkT2y7R/gitlab.find_sec_bugs_kotlin.PADDING_ORACLE-1 + origin: community + subcategory: + - audit + patterns: + - pattern: javax.crypto.Cipher.getInstance($TRANSFORMATION) + - metavariable-regex: + metavariable: "$TRANSFORMATION" + regex: ^"[^/]*/CBC/PKCS5Padding + - metavariable-pattern: + metavariable: "$TRANSFORMATION" + patterns: + - pattern-not-regex: ^"(RSA|ECIES)/ +- id: gitlab.find_sec_bugs_kotlin.PERMISSIVE_CORS-2 + languages: + - kotlin + message: | + Prior to HTML5, Web browsers enforced the Same Origin Policy which ensures that in order for + JavaScript to access the contents of a Web page, both the JavaScript and the Web page must + originate from the same domain. Without the Same Origin Policy, a malicious website could serve + up JavaScript that loads sensitive information from other websites using a client's + credentials, cull through it, and communicate it back to the attacker. HTML5 makes it possible + for JavaScript to access data across domains if a new HTTP header called + Access-Control-Allow-Origin is defined. With this header, a Web server defines which other + domains are allowed to access its domain using cross-origin requests. However, caution should + be taken when defining the header because an overly permissive CORS policy will allow a + malicious application to communicate with the victim application in an inappropriate way, + leading to spoofing, data theft, relay and other attacks. + severity: ERROR + metadata: + shortDescription: Permissive cross-domain policy with untrusted domains + cwe: CWE-942 + category: security + owasp: + - A1:2017-Injection + - A03:2021-Injection + technology: + - kotlin + security-severity: CRITICAL + primary_identifier: find_sec_bugs.PERMISSIVE_CORS-2 + secondary_identifiers: + - name: Find Security Bugs-PERMISSIVE_CORS + type: find_sec_bugs_type + value: PERMISSIVE_CORS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.PERMISSIVE_CORS-2 + shortlink: https://sg.run/WAd5z + semgrep.dev: + rule: + r_id: 144309 + rv_id: 920400 + rule_id: 7KUg0J4 + version_id: JdToRK6 + url: https://semgrep.dev/playground/r/JdToRK6/gitlab.find_sec_bugs_kotlin.PERMISSIVE_CORS-2 + origin: community + subcategory: + - audit + mode: taint + pattern-sources: + - pattern: "($REQ: HttpServletRequest).getParameter(...)" + - pattern: "($REQ: HttpServletRequest).getHeader(...)" + - pattern: "($REQ: HttpServletRequest).getPathInfo()" + - pattern: "($REQ: HttpServletRequest).getQueryString()" + - pattern: "($REQ: HttpServletRequest).getAttribute(...)" + - pattern: "($REQ: HttpServletRequest).getSession().getAttribute(...)" + - pattern: "($REQ: HttpServletRequest).getServletContext().getAttribute(...)" + - pattern: "($REQ: HttpServletRequest).getParameterValues(...)" + - pattern: "($REQ: HttpServletRequest).getParameterNames()" + - pattern: "($REQ: HttpServletRequest).getParameterMap()" + pattern-sinks: + - patterns: + - pattern-either: + - pattern: '($RES: HttpServletResponse).setHeader("$HEADER", ...)' + - pattern: '($RES: HttpServletResponse).addHeader("$HEADER", ...)' + - metavariable-regex: + metavariable: "$HEADER" + regex: "(?i)(Access-Control-Allow-Origin)" +- id: gitlab.find_sec_bugs_kotlin.PT_ABSOLUTE_PATH_TRAVERSAL-1 + languages: + - kotlin + message: | + The software uses an HTTP request parameter to construct a pathname that should be within a + restricted directory, but it does not properly neutralize absolute path sequences such as + "/abs/path" that can resolve to a location that is outside of that directory. See + http://cwe.mitre.org/data/definitions/36.html for more information. + severity: WARNING + metadata: + shortDescription: Improper limitation of a pathname to a restricted directory + ('Path Traversal') + category: security + cwe: CWE-22 + owasp: + - A1:2017-Injection + - A03:2021-Injection + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.PT_ABSOLUTE_PATH_TRAVERSAL-1 + secondary_identifiers: + - name: Find Security Bugs-PT_ABSOLUTE_PATH_TRAVERSAL + type: find_sec_bugs_type + value: PT_ABSOLUTE_PATH_TRAVERSAL + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.PT_ABSOLUTE_PATH_TRAVERSAL-1 + shortlink: https://sg.run/ZqdJL + semgrep.dev: + rule: + r_id: 144335 + rv_id: 920426 + rule_id: BYUXqjb + version_id: 6xTyXWg + url: https://semgrep.dev/playground/r/6xTyXWg/gitlab.find_sec_bugs_kotlin.PT_ABSOLUTE_PATH_TRAVERSAL-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - pattern: org.apache.commons.io.FilenameUtils.getName(...) + pattern-sinks: + - patterns: + - pattern-inside: "$U = java.net.URI($VAR)\n" + - pattern-either: + - pattern-inside: java.io.File($U) + - pattern-inside: java.nio.file.Paths.get($U) + - pattern: "$VAR" + - patterns: + - pattern-inside: java.io.RandomAccessFile($INPUT,...) + - pattern: "$INPUT" + - pattern: java.io.FileReader(...) + - pattern: javax.activation.FileDataSource(...) + - pattern: java.io.FileInputStream(...) + - pattern: 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: "($C: ClassLoader)" + - pattern: "($C: Class)" + - pattern: "$CLZ.getClassLoader()" + - metavariable-pattern: + metavariable: "$METHOD" + pattern-either: + - pattern: getResourceAsStream + - pattern: getResource + - patterns: + - pattern-inside: java.io.FileWriter($PATH, ...) + - pattern: "$PATH" + - patterns: + - pattern-inside: java.io.FileOutputStream($PATH, ...) + - pattern: "$PATH" + pattern-sources: + - pattern: "($REQ: HttpServletRequest).getParameter(...)" + - patterns: + - pattern-inside: fun $FUNC(..., @RequestParam $REQ:$TYPE, ...) {...} + - focus-metavariable: "$REQ" +- id: gitlab.find_sec_bugs_kotlin.REQUESTDISPATCHER_FILE_DISCLOSURE-1.STRUTS_FILE_DISCLOSURE-1.SPRING_FILE_DISCLOSURE-1 + languages: + - kotlin + message: | + Constructing a server-side redirect path with user input could allow an + attacker to download application binaries (including application classes or + jar files) or view arbitrary files within protected directories. + metadata: + shortDescription: Files or directories accessible to external parties + category: security + cwe: CWE-552 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: CRITICAL + primary_identifier: find_sec_bugs.REQUESTDISPATCHER_FILE_DISCLOSURE-1.STRUTS_FILE_DISCLOSURE-1.SPRING_FILE_DISCLOSURE-1 + secondary_identifiers: + - name: Find Security Bugs-REQUESTDISPATCHER_FILE_DISCLOSURE + type: find_sec_bugs_type + value: REQUESTDISPATCHER_FILE_DISCLOSURE + - name: Find Security Bugs-STRUTS_FILE_DISCLOSURE + type: find_sec_bugs_type + value: STRUTS_FILE_DISCLOSURE + - name: Find Security Bugs-SPRING_FILE_DISCLOSURE + type: find_sec_bugs_type + value: SPRING_FILE_DISCLOSURE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.REQUESTDISPATCHER_FILE_DISCLOSURE-1.STRUTS_FILE_DISCLOSURE-1.SPRING_FILE_DISCLOSURE-1 + shortlink: https://sg.run/Or36b + semgrep.dev: + rule: + r_id: 144331 + rv_id: 920422 + rule_id: 5rUdWl9 + version_id: K3TwL3E + url: https://semgrep.dev/playground/r/K3TwL3E/gitlab.find_sec_bugs_kotlin.REQUESTDISPATCHER_FILE_DISCLOSURE-1.STRUTS_FILE_DISCLOSURE-1.SPRING_FILE_DISCLOSURE-1 + origin: community + subcategory: + - audit + severity: ERROR + mode: taint + pattern-sinks: + - patterns: + - pattern: org.springframework.web.servlet.ModelAndView($FST); + - pattern: "$FST" + - patterns: + - pattern: org.springframework.web.servlet.ModelAndView($FST, $SND); + - pattern: "$FST" + - patterns: + - pattern: org.springframework.web.servlet.ModelAndView($FST, $SND, $TRD); + - pattern: "$FST" + - patterns: + - pattern: org.apache.struts.action.ActionForward($FST) + - pattern: "$FST" + - patterns: + - pattern: org.apache.struts.action.ActionForward($FST, $SND) + - pattern: "$FST" + - patterns: + - pattern: org.apache.struts.action.ActionForward($FST, $SND, $TRD) + - pattern: "$SND" + - patterns: + - pattern: org.apache.struts.action.ActionForward($FST, $SND, $TRD) + - pattern: "$TRD" + - patterns: + - pattern-inside: | + $ACTION = org.apache.struts.action.ActionForward(); + ... + - pattern: "$ACTION.setPath(...)" + - patterns: + - pattern-inside: | + $MVC = org.springframework.web.servlet.ModelAndView(); + ... + - pattern: "$MVC.setViewName(...);" + - patterns: + - pattern-inside: | + $REQ = $HTTP.getRequestDispatcher(...); + ... + - pattern-either: + - pattern: "$REQ.include($FST, $SND)" + - pattern: "$REQ.forward($FST, $SND)" + pattern-sources: + - pattern: "($VAR: javax.servlet.http.HttpServletRequest).getParameter(...)" +- id: gitlab.find_sec_bugs_kotlin.RSA_KEY_SIZE-1 + languages: + - kotlin + message: | + Detected an insufficient key size for DSA. NIST recommends a key size + of 2048 or higher. + metadata: + shortDescription: Inadequate encryption strength + category: security + cwe: CWE-326 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: MEDIUM + primary_identifier: find_sec_bugs.RSA_KEY_SIZE-1 + secondary_identifiers: + - name: Find Security Bugs-RSA_KEY_SIZE + type: find_sec_bugs_type + value: RSA_KEY_SIZE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.RSA_KEY_SIZE-1 + shortlink: https://sg.run/pKJQR + semgrep.dev: + rule: + r_id: 144318 + rv_id: 920409 + rule_id: 5rUdWK5 + version_id: K3TwL38 + url: https://semgrep.dev/playground/r/K3TwL38/gitlab.find_sec_bugs_kotlin.RSA_KEY_SIZE-1 + origin: community + subcategory: + - audit + severity: WARNING + patterns: + - pattern-either: + - patterns: + - pattern-inside: | + $GEN = KeyPairGenerator.getInstance($ALG, ...); + ... + - pattern-either: + - pattern: "$VAR.initialize($SIZE, ...);" + - pattern: java.security.spec.RSAKeyGenParameterSpec($SIZE,...); + - metavariable-comparison: + comparison: "$SIZE < 2048" + metavariable: "$SIZE" + - metavariable-regex: + metavariable: "$ALG" + regex: '"(RSA|DSA)"' +- id: gitlab.find_sec_bugs_kotlin.RSA_NO_PADDING-1 + languages: + - kotlin + message: | + The software uses the RSA algorithm but does not incorporate Optimal Asymmetric + Encryption Padding (OAEP), which might weaken the encryption. + metadata: + shortDescription: Use of RSA algorithm without OAEP + category: security + cwe: CWE-780 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: MEDIUM + primary_identifier: find_sec_bugs.RSA_NO_PADDING-1 + secondary_identifiers: + - name: Find Security Bugs-RSA_NO_PADDING + type: find_sec_bugs_type + value: RSA_NO_PADDING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.RSA_NO_PADDING-1 + shortlink: https://sg.run/X5d4e + semgrep.dev: + rule: + r_id: 144320 + rv_id: 920411 + rule_id: ReUDJWO + version_id: l4TXD12 + url: https://semgrep.dev/playground/r/l4TXD12/gitlab.find_sec_bugs_kotlin.RSA_NO_PADDING-1 + origin: community + subcategory: + - audit + severity: WARNING + pattern-either: + - patterns: + - pattern: | + $VAR = "$ALG"; + ... + javax.crypto.Cipher.getInstance($VAR); + - metavariable-regex: + metavariable: "$ALG" + regex: ".*RSA.*NoPadding.*" + - patterns: + - pattern: javax.crypto.Cipher.getInstance($ALG,...); + - metavariable-regex: + metavariable: "$ALG" + regex: ".*RSA.*NoPadding.*" +- id: gitlab.find_sec_bugs_kotlin.SAML_IGNORE_COMMENTS-1 + languages: + - kotlin + message: 'Ignoring XML comments in SAML may lead to authentication bypass + + ' + metadata: + shortDescription: Improper authentication + cwe: CWE-287 + category: security + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: MEDIUM + primary_identifier: find_sec_bugs.SAML_IGNORE_COMMENTS-1 + secondary_identifiers: + - name: Find Security Bugs-SAML_IGNORE_COMMENTS + type: find_sec_bugs_type + value: SAML_IGNORE_COMMENTS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.SAML_IGNORE_COMMENTS-1 + shortlink: https://sg.run/WAd9z + semgrep.dev: + rule: + r_id: 144353 + rv_id: 920444 + rule_id: r6Uydg7 + version_id: vdTvQB4 + url: https://semgrep.dev/playground/r/vdTvQB4/gitlab.find_sec_bugs_kotlin.SAML_IGNORE_COMMENTS-1 + origin: community + subcategory: + - audit + severity: WARNING + pattern: "($POOL: org.opensaml.xml.parse.BasicParserPool).setIgnoreComments(false);" +- id: gitlab.find_sec_bugs_kotlin.SCRIPT_ENGINE_INJECTION-1.SPEL_INJECTION-1.EL_INJECTION-2.SEAM_LOG_INJECTION-1 + languages: + - kotlin + message: | + The software constructs all or part of a code segment using externally-influenced + input from an upstream component, but it does not neutralize or incorrectly + neutralizes special elements that could modify the syntax or behavior of the + intended code segment. + severity: ERROR + metadata: + shortDescription: Improper control of generation of code ('Code Injection') + category: security + cwe: CWE-94 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: CRITICAL + primary_identifier: find_sec_bugs.SCRIPT_ENGINE_INJECTION-1.SPEL_INJECTION-1.EL_INJECTION-2.SEAM_LOG_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-SCRIPT_ENGINE_INJECTION + type: find_sec_bugs_type + value: SCRIPT_ENGINE_INJECTION + - name: Find Security Bugs-SPEL_INJECTION + type: find_sec_bugs_type + value: SPEL_INJECTION + - name: Find Security Bugs-EL_INJECTION + type: find_sec_bugs_type + value: EL_INJECTION + - name: Find Security Bugs-SEAM_LOG_INJECTION + type: find_sec_bugs_type + value: SEAM_LOG_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.SCRIPT_ENGINE_INJECTION-1.SPEL_INJECTION-1.EL_INJECTION-2.SEAM_LOG_INJECTION-1 + shortlink: https://sg.run/3qPNl + semgrep.dev: + rule: + r_id: 144343 + rv_id: 920434 + rule_id: 6JUvn74 + version_id: 9lTA76K + url: https://semgrep.dev/playground/r/9lTA76K/gitlab.find_sec_bugs_kotlin.SCRIPT_ENGINE_INJECTION-1.SPEL_INJECTION-1.EL_INJECTION-2.SEAM_LOG_INJECTION-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sinks: + - patterns: + - patterns: + - pattern-inside: | + $ENGINE = $F.getEngineByExtension(...) + ... + - pattern: "$ENGINE.eval($ARG, ...);" + - pattern-not: $ENGINE.eval("..."); + - pattern-not: '$ENGINE.eval("...", ($BINDING: javax.script.Bindings));' + - patterns: + - pattern: "($ENGINE: javax.script.ScriptEngine).eval($ARG, ...);" + - pattern-not: '($ENGINE: javax.script.ScriptEngine).eval("...");' + - pattern-not: '($ENGINE: javax.script.ScriptEngine).eval("...", ($BINDING: javax.script.Bindings));' + - pattern: "($INVC: javax.script.Invocable).invokeFunction(..., $ARG)" + - pattern: "($INVC: javax.script.Invocable).invokeMethod(..., $ARG)" + pattern-sources: + - patterns: + - pattern-inside: 'fun $FUNC(..., $VAR: String, ...) { ... }' + - pattern: "$VAR" +- id: gitlab.find_sec_bugs_kotlin.SMTP_HEADER_INJECTION-1 + languages: + - kotlin + message: | + Simple Mail Transfer Protocol (SMTP) is a the text based protocol used for + email delivery. Like with HTTP, headers are separate by new line separator. If + kuser input is place in a header line, the application should remove or replace + new line characters (CR / LF). You should use a safe wrapper such as Apache + Common Email and Simple Java Mail which filter special characters that can lead + to header injection. + metadata: + shortDescription: Improper neutralization of special elements used in a command + category: security + cwe: CWE-77 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: CRITICAL + primary_identifier: find_sec_bugs.SMTP_HEADER_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-SMTP_HEADER_INJECTION + type: find_sec_bugs_type + value: SMTP_HEADER_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.SMTP_HEADER_INJECTION-1 + shortlink: https://sg.run/PedoE + semgrep.dev: + rule: + r_id: 144345 + rv_id: 920436 + rule_id: zdUKogv + version_id: rxTjvGO + url: https://semgrep.dev/playground/r/rxTjvGO/gitlab.find_sec_bugs_kotlin.SMTP_HEADER_INJECTION-1 + origin: community + subcategory: + - audit + severity: ERROR + patterns: + - pattern-inside: | + $M = 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" +- id: gitlab.find_sec_bugs_kotlin.SPRING_CSRF_PROTECTION_DISABLED-1 + languages: + - kotlin + message: | + The application fails to protect against Cross-Site Request Forgery (CSRF) + due to disabling Spring's CSRF protection features. + metadata: + shortDescription: Cross-Site Request Forgery (CSRF) + category: security + cwe: CWE-352 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: MEDIUM + primary_identifier: find_sec_bugs.SPRING_CSRF_PROTECTION_DISABLED-1 + secondary_identifiers: + - name: Find Security Bugs-SPRING_CSRF_PROTECTION_DISABLED + type: find_sec_bugs_type + value: SPRING_CSRF_PROTECTION_DISABLED + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.SPRING_CSRF_PROTECTION_DISABLED-1 + shortlink: https://sg.run/yyKZd + semgrep.dev: + rule: + r_id: 144324 + rv_id: 920415 + rule_id: WAUWB5o + version_id: GxToXBb + url: https://semgrep.dev/playground/r/GxToXBb/gitlab.find_sec_bugs_kotlin.SPRING_CSRF_PROTECTION_DISABLED-1 + origin: community + subcategory: + - audit + severity: WARNING + pattern-either: + - pattern: "($H: org.springframework.security.config.annotation.web.builders.HttpSecurity). + ... .csrf().disable()" + - pattern: "($C: CsrfConfigurer).disable()" +- id: gitlab.find_sec_bugs_kotlin.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1.SQL_INJECTION-1.SQL_INJECTION_HIBERNATE-1.SQL_INJECTION_VERTX-1.SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING-1 + languages: + - kotlin + message: | + The input values included in SQL queries need to be passed in safely. Bind + variables in prepared statements can be used to easily mitigate the risk of + SQL injection. + options: + taint_assume_safe_functions: true + metadata: + shortDescription: Improper Neutralization of Special Elements used in an SQL Command + ('SQL Injection') + category: security + cwe: CWE-89 + technology: + - java + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: CRITICAL + primary_identifier: find_sec_bugs.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1.SQL_INJECTION-1.SQL_INJECTION_HIBERNATE-1.SQL_INJECTION_VERTX-1.SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING-1 + secondary_identifiers: + - name: Find Security Bugs-SQL_INJECTION_SPRING_JDBC + type: find_sec_bugs_type + value: SQL_INJECTION_SPRING_JDBC + - name: Find Security Bugs-SQL_INJECTION_JPA + type: find_sec_bugs_type + value: SQL_INJECTION_JPA + - name: Find Security Bugs-SQL_INJECTION_JDO + type: find_sec_bugs_type + value: SQL_INJECTION_JDO + - name: Find Security Bugs-SQL_INJECTION_JDBC + type: find_sec_bugs_type + value: SQL_INJECTION_JDBC + - name: Find Security Bugs-SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE + type: find_sec_bugs_type + value: SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE + - name: Find Security Bugs-SQL_INJECTION + type: find_sec_bugs_type + value: SQL_INJECTION + - name: Find Security Bugs-SQL_INJECTION_HIBERNATE + type: find_sec_bugs_type + value: SQL_INJECTION_HIBERNATE + - name: Find Security Bugs-SQL_INJECTION_VERTX + type: find_sec_bugs_type + value: SQL_INJECTION_VERTX + - name: Find Security Bugs-SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING + type: find_sec_bugs_type + value: SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1.SQL_INJECTION-1.SQL_INJECTION_HIBERNATE-1.SQL_INJECTION_VERTX-1.SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING-1 + shortlink: https://sg.run/nJ41b + semgrep.dev: + rule: + r_id: 144336 + rv_id: 920427 + rule_id: DbU6low + version_id: o5TK1J1 + url: https://semgrep.dev/playground/r/o5TK1J1/gitlab.find_sec_bugs_kotlin.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1.SQL_INJECTION-1.SQL_INJECTION_HIBERNATE-1.SQL_INJECTION_VERTX-1.SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING-1 + origin: community + subcategory: + - audit + severity: ERROR + mode: taint + pattern-sources: + - patterns: + - pattern-inside: 'fun $FUNC(..., $SRC: String, ...) { ... }' + - pattern: "$SRC" + pattern-propagators: + - pattern: "$SB.append($SRC)" + from: "$SRC" + to: "$SB" + - patterns: + - pattern: "$F(..., $SRC, ...)" + - focus-metavariable: "$F" + - pattern-either: + - pattern: String.format + - pattern: StringBuilder + from: "$SRC" + to: "$F" + pattern-sinks: + - patterns: + - pattern-either: + - pattern: "($PM: javax.jdo.PersistenceManager).newQuery($ARG)" + - pattern: "($PM: javax.jdo.PersistenceManager).newQuery(..., $ARG)" + - pattern: "($Q: javax.jdo.Query).setFilter($ARG)" + - pattern: "($Q: javax.jdo.Query).setGrouping($ARG)" + - pattern: org.hibernate.criterion.Restrictions.sqlRestriction($ARG, ...) + - pattern: "($S: org.hibernate.Session).createQuery($ARG, ...)" + - pattern: "($S: org.hibernate.Session).createSQLQuery($ARG, ...)" + - pattern: "($S: java.sql.Statement).executeQuery($ARG, ...)" + - pattern: "($S: java.sql.Statement).execute($ARG, ...)" + - pattern: "($S: java.sql.Statement).executeUpdate($ARG, ...)" + - pattern: "($S: java.sql.Statement).executeLargeUpdate($ARG, ...)" + - pattern: "($S: java.sql.Statement).addBatch($ARG, ...)" + - pattern: "($S: java.sql.PreparedStatement).executeQuery($ARG, ...)" + - pattern: "($S: java.sql.PreparedStatement).execute($ARG, ...)" + - pattern: "($S: java.sql.PreparedStatement).executeUpdate($ARG, ...)" + - pattern: "($S: java.sql.PreparedStatement).executeLargeUpdate($ARG, ...)" + - pattern: "($S: java.sql.PreparedStatement).addBatch($ARG, ...)" + - pattern: "($S: java.sql.Connection).prepareCall($ARG, ...)" + - pattern: "($S: java.sql.Connection).prepareStatement($ARG, ...)" + - pattern: "($S: java.sql.Connection).nativeSQL($ARG, ...)" + - pattern: org.springframework.jdbc.core.PreparedStatementCreatorFactory($ARG, + ...) + - pattern: "($F: org.springframework.jdbc.core.PreparedStatementCreatorFactory).newPreparedStatementCreator($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).batchUpdate($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).execute($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).query($ARG, ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForList($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForMap($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForObject($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForObject($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForRowSet($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForInt($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForLong($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).update($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).batchUpdate($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).execute($ARG, ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).query($ARG, ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).queryForList($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).queryForMap($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).queryForObject($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).queryForRowSet($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).queryForInt($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).queryForLong($ARG, + ...)" + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).update($ARG, ...)" + - pattern: "($O: io.vertx.sqlclient.SqlClient).query($ARG, ...)" + - pattern: "($O: io.vertx.sqlclient.SqlClient).preparedQuery($ARG, ...)" + - pattern: "($O: io.vertx.sqlclient.SqlConnection).prepare($ARG, ...)" + - pattern: "($O: org.apache.turbine.om.peer.BasePeer).executeQuery($ARG, ...)" + - pattern: "($O: org.apache.torque.util.BasePeer).executeQuery($ARG, ...)" + - pattern: "($O: javax.persistence.EntityManager).createQuery($ARG, ...)" + - pattern: "($O: javax.persistence.EntityManager).createNativeQuery($ARG, ...)" + - pattern: "($H: org.jdbi.v3.core.Handle).createQuery($ARG, ...)" + - pattern: "($H: org.jdbi.v3.core.Handle).createScript($ARG, ...)" + - pattern: "($H: org.jdbi.v3.core.Handle).createUpdate($ARG, ...)" + - pattern: "($H: org.jdbi.v3.core.Handle).execute($ARG, ...)" + - pattern: "($H: org.jdbi.v3.core.Handle).prepareBatch($ARG, ...)" + - pattern: "($H: org.jdbi.v3.core.Handle).select($ARG, ...)" + - pattern: org.jdbi.v3.core.statement.Script($H, $ARG) + - pattern: org.jdbi.v3.core.statement.Update($H, $ARG) + - pattern: org.jdbi.v3.core.statement.PreparedBatch($H, $ARG) + - focus-metavariable: "$ARG" +- id: gitlab.find_sec_bugs_kotlin.SSL_CONTEXT-1 + languages: + - kotlin + message: | + A HostnameVerifier that accept any host are often use because of certificate + reuse on many hosts. As a consequence, this is vulnerable to Man-in-the-middleattacks + attacks since the client will trust any certificate. + metadata: + shortDescription: Improper certificate validation + category: security + cwe: CWE-295 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: MEDIUM + primary_identifier: find_sec_bugs.SSL_CONTEXT-1 + secondary_identifiers: + - name: Find Security Bugs-SSL_CONTEXT + type: find_sec_bugs_type + value: SSL_CONTEXT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.SSL_CONTEXT-1 + shortlink: https://sg.run/10wNQ + semgrep.dev: + rule: + r_id: 144322 + rv_id: 920413 + rule_id: BYUXqjx + version_id: JdToRK2 + url: https://semgrep.dev/playground/r/JdToRK2/gitlab.find_sec_bugs_kotlin.SSL_CONTEXT-1 + origin: community + subcategory: + - audit + severity: WARNING + patterns: + - pattern-either: + - pattern: org.apache.http.impl.client.DefaultHttpClient() + - pattern: javax.net.ssl.SSLContext.getInstance("SSL") +- id: gitlab.find_sec_bugs_kotlin.SSL_CONTEXT-2 + languages: + - kotlin + 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 + security-severity: MEDIUM + primary_identifier: find_sec_bugs.SSL_CONTEXT-2 + secondary_identifiers: + - name: Find Security Bugs-SSL_CONTEXT + type: find_sec_bugs_type + value: SSL_CONTEXT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.SSL_CONTEXT-2 + shortlink: https://sg.run/9ABgR + semgrep.dev: + rule: + r_id: 144323 + rv_id: 920414 + rule_id: DbU6lo9 + version_id: 5PTNGEx + url: https://semgrep.dev/playground/r/5PTNGEx/gitlab.find_sec_bugs_kotlin.SSL_CONTEXT-2 + origin: community + subcategory: + - audit + severity: WARNING + 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(arrayOf(...,"$UNSAFE_VERSION",...)); + - pattern-not: + patterns: + - pattern-inside: | + $C = SSLContext.getInstance(...); + ... + $ENGINE.setEnabledProtocols(arrayOf(...,"$DT_GOODNESS",...)); + - metavariable-regex: + metavariable: "$DT_GOODNESS" + regex: "^D?TLSv1\\.[23]$" + - pattern-not: + patterns: + - pattern-inside: | + $C = SSLContext.getInstance(...); + ... + $E = $C.createSSLEngine() + ... + $E.enabledProtocols = arrayOf(...,"$DT_GOODNESS",...) + - metavariable-regex: + metavariable: "$DT_GOODNESS" + regex: "^DTLSv1\\.[23]$" + - metavariable-regex: + metavariable: "$UNSAFE_VERSION" + regex: "^(TLS|(D)?TLSv1.(0|1))$" +- id: gitlab.find_sec_bugs_kotlin.TDES_USAGE-1 + languages: + - kotlin + message: | + Triple DES (also known as 3DES or DESede) is considered strong ciphers for modern + applications. NIST recommends the usage of AES block ciphers instead of 3DES. + 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 + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.TDES_USAGE-1 + secondary_identifiers: + - name: Find Security Bugs-TDES_USAGE + type: find_sec_bugs_type + value: TDES_USAGE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.TDES_USAGE-1 + shortlink: https://sg.run/qN5Q8 + semgrep.dev: + rule: + r_id: 144312 + rv_id: 920403 + rule_id: gxU3dv7 + version_id: RGT2x9A + url: https://semgrep.dev/playground/r/RGT2x9A/gitlab.find_sec_bugs_kotlin.TDES_USAGE-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: javax.crypto.Cipher.getInstance($ALG, ...) + - metavariable-regex: + metavariable: "$ALG" + regex: (?i)^"DESede(/|"$) +- id: gitlab.find_sec_bugs_kotlin.TEMPLATE_INJECTION_PEBBLE-1.TEMPLATE_INJECTION_FREEMARKER-1.TEMPLATE_INJECTION_VELOCITY-1 + languages: + - kotlin + message: | + A malicious user in control of a template can run malicious code on the + server-side. Velocity templates should be seen as scripts. + metadata: + shortDescription: Improper control of generation of code ('Code Injection') + category: security + cwe: CWE-94 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: CRITICAL + primary_identifier: find_sec_bugs.TEMPLATE_INJECTION_PEBBLE-1.TEMPLATE_INJECTION_FREEMARKER-1.TEMPLATE_INJECTION_VELOCITY-1 + secondary_identifiers: + - name: Find Security Bugs-TEMPLATE_INJECTION_PEBBLE + type: find_sec_bugs_type + value: TEMPLATE_INJECTION_PEBBLE + - name: Find Security Bugs-TEMPLATE_INJECTION_FREEMARKER + type: find_sec_bugs_type + value: TEMPLATE_INJECTION_FREEMARKER + - name: Find Security Bugs-TEMPLATE_INJECTION_VELOCITY + type: find_sec_bugs_type + value: TEMPLATE_INJECTION_VELOCITY + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.TEMPLATE_INJECTION_PEBBLE-1.TEMPLATE_INJECTION_FREEMARKER-1.TEMPLATE_INJECTION_VELOCITY-1 + shortlink: https://sg.run/BYoJ9 + semgrep.dev: + rule: + r_id: 144351 + rv_id: 920442 + rule_id: 9AUdrNp + version_id: O9Tv7RD + url: https://semgrep.dev/playground/r/O9Tv7RD/gitlab.find_sec_bugs_kotlin.TEMPLATE_INJECTION_PEBBLE-1.TEMPLATE_INJECTION_FREEMARKER-1.TEMPLATE_INJECTION_VELOCITY-1 + origin: community + subcategory: + - audit + severity: ERROR + pattern-either: + - patterns: + - pattern: org.apache.velocity.app.Velocity.evaluate(..., $VAR) + - pattern-not: org.apache.velocity.app.Velocity.evaluate(..., "...") + - patterns: + - pattern-not-inside: | + $C = ($CFG: freemarker.template.Configuration).getTemplate("..."); + ... + - pattern-inside: | + $C = ($CFG: freemarker.template.Configuration).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(...)" +- id: gitlab.find_sec_bugs_kotlin.UNVALIDATED_REDIRECT-1.URL_REWRITING-1 + languages: + - kotlin + message: | + Unvalidated redirects occur when an application redirects a user to a + destination URL specified by a user supplied parameter that is not validated. + Such vulnerabilities can be used to facilitate phishing attacks. + metadata: + category: security + cwe: CWE-601 + owasp: + - A1:2017-Injection + - A03:2021-Injection + shortDescription: URL redirection to untrusted site ('Open Redirect') + security-severity: CRITICAL + primary_identifier: find_sec_bugs.UNVALIDATED_REDIRECT-1.URL_REWRITING-1 + secondary_identifiers: + - name: Find Security Bugs-UNVALIDATED_REDIRECT + type: find_sec_bugs_type + value: UNVALIDATED_REDIRECT + - name: Find Security Bugs-URL_REWRITING + type: find_sec_bugs_type + value: URL_REWRITING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.UNVALIDATED_REDIRECT-1.URL_REWRITING-1 + shortlink: https://sg.run/r6GbA + semgrep.dev: + rule: + r_id: 144325 + rv_id: 920416 + rule_id: 0oULNkE + version_id: RGT2x9W + url: https://semgrep.dev/playground/r/RGT2x9W/gitlab.find_sec_bugs_kotlin.UNVALIDATED_REDIRECT-1.URL_REWRITING-1 + origin: community + subcategory: + - audit + severity: ERROR + mode: taint + pattern-sources: + - patterns: + - pattern: "$URL = ($REQ: $X.servlet.http.HttpServletRequest).$M(...);\n" + - 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: "($RES: $X.servlet.http.HttpServletResponse).sendRedirect($URL)\n" + - pattern: '($RES: $X.servlet.http.HttpServletResponse).addHeader("Location", + $URL) + + ' + pattern-sanitizers: + - patterns: + - pattern-inside: | + if ($SAFE.contains($URL)){ + ... + } + - pattern-either: + - pattern: "($RES: $X.servlet.http.HttpServletResponse).sendRedirect($URL)\n" + - pattern: '($RES: $X.servlet.http.HttpServletResponse).addHeader("Location", + $URL) + + ' +- id: gitlab.find_sec_bugs_kotlin.URLCONNECTION_SSRF_FD-1 + languages: + - kotlin + message: | + Server-Side Request Forgery occur when a web server executes a request to a user supplied + destination parameter that is not validated. Such vulnerabilities could allow an attacker to + access internal services or to launch attacks from your web server. + metadata: + shortDescription: Server-Side Request Forgery (SSRF) + category: security + cwe: CWE-918 + owasp: + - A1:2017-Injection + - A10:2021-Server-Side Request Forgery + security-severity: CRITICAL + primary_identifier: find_sec_bugs.URLCONNECTION_SSRF_FD-1 + secondary_identifiers: + - name: Find Security Bugs-URLCONNECTION_SSRF_FD + type: find_sec_bugs_type + value: URLCONNECTION_SSRF_FD + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.URLCONNECTION_SSRF_FD-1 + shortlink: https://sg.run/JDy0Z + semgrep.dev: + rule: + r_id: 144346 + rv_id: 920437 + rule_id: pKU1Zg4 + version_id: bZTLo6b + url: https://semgrep.dev/playground/r/bZTLo6b/gitlab.find_sec_bugs_kotlin.URLCONNECTION_SSRF_FD-1 + origin: community + subcategory: + - audit + severity: ERROR + pattern-either: + - patterns: + - pattern-either: + - pattern-inside: | + import java.net.*; + ... + - pattern-inside: | + import java.net.URL; + ... + - pattern-inside: | + import java.net.URI; + ... + - pattern: "$TYPE(...). ... .$FUNC" + - pattern-not: $TYPE("..."). ... .$FUNC + - metavariable-pattern: + metavariable: "$FUNC" + pattern-either: + - pattern: connect + - pattern: GetContent + - pattern: openConnection + - pattern: openStream + - pattern: getContent + - pattern: content + - 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: 'InetSocketAddress(..., $PORT) + + ' + - pattern-not: 'InetSocketAddress("...", $PORT) + + ' +- id: gitlab.find_sec_bugs_kotlin.WEAK_FILENAMEUTILS-1 + languages: + - kotlin + message: | + A file is opened to read its content. The filename comes from an input + parameter. If an unfiltered parameter is passed to this file API, files from an + arbitrary filesystem location could be read. + 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 + security-severity: MEDIUM + technology: + - kotlin + category: security + primary_identifier: find_sec_bugs.WEAK_FILENAMEUTILS-1 + secondary_identifiers: + - name: Find Security Bugs-WEAK_FILENAMEUTILS + type: find_sec_bugs_type + value: WEAK_FILENAMEUTILS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.WEAK_FILENAMEUTILS-1 + shortlink: https://sg.run/kxd2z + semgrep.dev: + rule: + r_id: 144328 + rv_id: 920419 + rule_id: lBU4kqW + version_id: DkT2y7P + url: https://semgrep.dev/playground/r/DkT2y7P/gitlab.find_sec_bugs_kotlin.WEAK_FILENAMEUTILS-1 + origin: community + subcategory: + - audit + severity: WARNING + patterns: + - pattern-inside: | + import org.apache.commons.io.FilenameUtils + ... + - pattern-either: + - pattern: normalize(...) + - pattern: getExtension(...) + - pattern: isExtensions(...) + - pattern: getName(...) + - pattern: getBaseName(...) + - pattern: org.apache.commons.io.FilenameUtils.normalize(...) + - pattern: org.apache.commons.io.FilenameUtils.getExtension(...) + - pattern: org.apache.commons.io.FilenameUtils.isExtensions(...) + - pattern: org.apache.commons.io.FilenameUtils.getName(...) + - pattern: org.apache.commons.io.FilenameUtils.getBaseName(...) +- id: gitlab.find_sec_bugs_kotlin.WEAK_HOSTNAME_VERIFIER-1.WEAK_TRUST_MANAGER-1 + languages: + - kotlin + message: | + A HostnameVerifier that accept any host are often use because of certificate + reuse on many hosts. As a consequence, this is vulnerable to Man-in-the-middle + attacks since the client will trust any certificate. + metadata: + category: security + cwe: CWE-295 + shortDescription: Improper Certificate Validation + security-severity: MEDIUM + primary_identifier: find_sec_bugs.WEAK_HOSTNAME_VERIFIER-1.WEAK_TRUST_MANAGER-1 + secondary_identifiers: + - name: Find Security Bugs-WEAK_HOSTNAME_VERIFIER + type: find_sec_bugs_type + value: WEAK_HOSTNAME_VERIFIER + - name: Find Security Bugs-WEAK_TRUST_MANAGER + type: find_sec_bugs_type + value: WEAK_TRUST_MANAGER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.WEAK_HOSTNAME_VERIFIER-1.WEAK_TRUST_MANAGER-1 + shortlink: https://sg.run/bwd0r + semgrep.dev: + rule: + r_id: 144326 + rv_id: 920417 + rule_id: KxUvE9Y + version_id: A8TNlp1 + url: https://semgrep.dev/playground/r/A8TNlp1/gitlab.find_sec_bugs_kotlin.WEAK_HOSTNAME_VERIFIER-1.WEAK_TRUST_MANAGER-1 + origin: community + subcategory: + - audit + severity: WARNING + patterns: + - pattern-either: + - patterns: + - pattern-inside: | + class $V : HostnameVerifier { + ... + } + - pattern: | + fun verify(...): Boolean { + return true + } + - patterns: + - pattern-inside: | + class $V : X509TrustManager { + ... + } + - pattern-either: + - pattern: fun checkClientTrusted(...) {} + - pattern: fun checkServerTrusted(...) {} + - pattern: 'fun getAcceptedIssuers(): Array? {return null}' +- id: gitlab.find_sec_bugs_kotlin.WEAK_MESSAGE_DIGEST_MD5-1.WEAK_MESSAGE_DIGEST_SHA1-1 + languages: + - kotlin + message: | + DES is considered strong ciphers for modern applications. Currently, NIST recommends the usage + of AES block ciphers instead of DES. + severity: WARNING + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm (SHA1/MD5) + category: security + cwe: CWE-327 + owasp: + - A6:2017-Security Misconfiguration + - A04:2021-Insecure Design + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.WEAK_MESSAGE_DIGEST_MD5-1.WEAK_MESSAGE_DIGEST_SHA1-1 + secondary_identifiers: + - name: Find Security Bugs-WEAK_MESSAGE_DIGEST_MD5 + type: find_sec_bugs_type + value: WEAK_MESSAGE_DIGEST_MD5 + - name: Find Security Bugs-WEAK_MESSAGE_DIGEST_SHA1 + type: find_sec_bugs_type + value: WEAK_MESSAGE_DIGEST_SHA1 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.WEAK_MESSAGE_DIGEST_MD5-1.WEAK_MESSAGE_DIGEST_SHA1-1 + shortlink: https://sg.run/j2Lp2 + semgrep.dev: + rule: + r_id: 144321 + rv_id: 920412 + rule_id: AbU9DP9 + version_id: YDTYb48 + url: https://semgrep.dev/playground/r/YDTYb48/gitlab.find_sec_bugs_kotlin.WEAK_MESSAGE_DIGEST_MD5-1.WEAK_MESSAGE_DIGEST_SHA1-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: MessageDigest.getInstance($ALG, ...) + - pattern: Signature.getInstance($ALG, ...) + - metavariable-regex: + metavariable: "$ALG" + regex: ".*(MD5|MD4|MD2|SHA1|SHA-1).*" +- id: gitlab.find_sec_bugs_kotlin.WICKET_XSS1-1 + languages: + - kotlin + message: 'Disabling HTML escaping put the application at risk for Cross-Site Scripting + (XSS). + + ' + metadata: + shortDescription: Improper neutralization of input during web page generation + ('Cross-site Scripting') + category: security + cwe: CWE-79 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: MEDIUM + primary_identifier: find_sec_bugs.WICKET_XSS1-1 + secondary_identifiers: + - name: Find Security Bugs-WICKET_XSS1 + type: find_sec_bugs_type + value: WICKET_XSS1 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.WICKET_XSS1-1 + shortlink: https://sg.run/lBdX5 + semgrep.dev: + rule: + r_id: 144357 + rv_id: 920448 + rule_id: wdU9XgL + version_id: ExT1WXN + url: https://semgrep.dev/playground/r/ExT1WXN/gitlab.find_sec_bugs_kotlin.WICKET_XSS1-1 + origin: community + subcategory: + - audit + severity: WARNING + patterns: + - pattern-inside: | + import org.apache.wicket.$A + ... + - pattern: "$OBJ.setEscapeModelStrings(false);\n" +- id: gitlab.find_sec_bugs_kotlin.XML_DECODER-1 + languages: + - kotlin + message: 'Avoid using XMLDecoder to parse content from an untrusted source. + + ' + metadata: + shortDescription: Deserialization of untrusted data + category: security + cwe: CWE-502 + owasp: + - A8:2017-Insecure Deserialization + - A08:2021-Software and Data Integrity Failures + security-severity: MEDIUM + primary_identifier: find_sec_bugs.XML_DECODER-1 + secondary_identifiers: + - name: Find Security Bugs-XML_DECODER + type: find_sec_bugs_type + value: XML_DECODER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.XML_DECODER-1 + shortlink: https://sg.run/0okxJ + semgrep.dev: + rule: + r_id: 144354 + rv_id: 920445 + rule_id: bwUbpWe + version_id: d6T6gpK + url: https://semgrep.dev/playground/r/d6T6gpK/gitlab.find_sec_bugs_kotlin.XML_DECODER-1 + origin: community + subcategory: + - audit + severity: WARNING + patterns: + - pattern-either: + - pattern: "($D: java.beans.XMLDecoder).readObject()" + - patterns: + - pattern: "$D.readObject()" + - pattern-inside: | + $D = XMLDecoder(...) + ... + - pattern-not: + pattern-either: + - patterns: + - pattern-inside: | + $DEC = java.beans.XMLDecoder(..., $CL) + ... + - pattern: "$DEC.readObject()" + - metavariable-pattern: + metavariable: "$CL" + patterns: + - pattern: | + object : ClassLoader() { + ... + fun loadClass(name: String, resolve: Boolean): $RET { + if($X){ + throw ... + } + ... + } + ... + } + - metavariable-pattern: + metavariable: "$X" + pattern-either: + - pattern: 'name != ... + + ' + - pattern: "!$LIST.contains(name)\n" + - patterns: + - pattern-inside: | + $CLASS_LOADER = $CL + ... + - pattern-inside: | + $DEC = java.beans.XMLDecoder(..., $CLASS_LOADER) + ... + - pattern: "$DEC.readObject()" + - metavariable-pattern: + metavariable: "$CL" + patterns: + - pattern: | + object : ClassLoader(){ + ... + fun loadClass(name: String, resolve: Boolean): $RET{ + if($X){ + throw ... + } + ... + } + ... + } + - metavariable-pattern: + metavariable: "$X" + pattern-either: + - pattern: 'name != ... + + ' + - pattern: "!$LIST.contains(name)\n" +- id: gitlab.find_sec_bugs_kotlin.XPATH_INJECTION-1 + languages: + - kotlin + message: | + The input values included in SQL queries need to be passed in safely. Bind + variables in prepared statements can be used to easily mitigate the risk of + SQL injection. + metadata: + shortDescription: Improper neutralization of data within XPath expressions ('XPath + Injection') + category: security + cwe: CWE-643 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: CRITICAL + primary_identifier: find_sec_bugs.XPATH_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-XPATH_INJECTION + type: find_sec_bugs_type + value: XPATH_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.XPATH_INJECTION-1 + shortlink: https://sg.run/qN5b8 + semgrep.dev: + rule: + r_id: 144356 + rv_id: 920447 + rule_id: kxUdNvG + version_id: nWTnN0p + url: https://semgrep.dev/playground/r/nWTnN0p/gitlab.find_sec_bugs_kotlin.XPATH_INJECTION-1 + origin: community + subcategory: + - audit + severity: ERROR + mode: taint + pattern-sources: + - patterns: + - pattern-inside: | + fun $FUNC(..., $VAR: $T, ...) { + ... + } + - pattern: "$VAR" + pattern-sinks: + - patterns: + - pattern-either: + - pattern-inside: "import javax.xml.xpath.*; \n...\n" + - pattern-inside: "import javax.xml.xpath.XPath; \n...\n" + - patterns: + - pattern-either: + - patterns: + - pattern: "$X.compile($VAR)" + - pattern-not: $X.compile("...") + - patterns: + - pattern: "$X.evaluate($VAR, ...)" + - pattern-not: $X.evaluate("...", ...) + pattern-sanitizers: + - pattern-either: + - pattern-inside: | + $X.xPathVariableResolver = ...; + ...; + $X.compile("..."); + - pattern-inside: | + $X.setXPathVariableResolver(...); + ...; + $X.compile("..."); +- id: gitlab.find_sec_bugs_kotlin.XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER-1 + languages: + - kotlin + message: 'Servlet reflected cross site scripting vulnerability + + ' + severity: WARNING + metadata: + shortDescription: Improper neutralization of input during web page generation + ('Cross-site Scripting') + category: security + cwe: CWE-79 + owasp: + - A1:2017-Injection + - A03:2021-Injection + technology: + - kotlin + security-severity: MEDIUM + primary_identifier: find_sec_bugs.XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER-1 + secondary_identifiers: + - name: Find Security Bugs-XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER + type: find_sec_bugs_type + value: XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER-1 + shortlink: https://sg.run/YGdPQ + semgrep.dev: + rule: + r_id: 144358 + rv_id: 920449 + rule_id: x8UKPbo + version_id: 7ZTbRXn + url: https://semgrep.dev/playground/r/7ZTbRXn/gitlab.find_sec_bugs_kotlin.XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: org.owasp.encoder.Encode.forHtml($TAINTED); + - pattern: "$TAINTED" + pattern-sinks: + - patterns: + - pattern-inside: 'fun $FUNC(..., $RES: HttpServletResponse , ...) {...}' + - pattern-inside: | + $WRITER = $RES.getWriter(); + ... + - pattern: "$WRITER.write($DATA,...);" + - pattern: "$DATA" + - patterns: + - pattern-inside: 'fun $FUNC(..., $RES: HttpServletResponse , ...) {...}' + - pattern: "$RES.getWriter().write($DATA,...);" + - pattern: "$DATA" + pattern-sources: + - patterns: + - pattern-inside: 'fun $FUNC(..., $REQ: HttpServletRequest , ...) {...}' + - pattern: "$REQ.getParameter(...);" +- id: gitlab.find_sec_bugs_kotlin.XXE_SAXPARSER-1 + languages: + - kotlin + message: | + XML External Entity (XXE) attacks can occur when an XML parser supports XML + entities while processing XML received from an untrusted source. + metadata: + shortDescription: Improper restriction of XML external entity reference ('XXE') + category: security + cwe: CWE-611 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: CRITICAL + primary_identifier: find_sec_bugs.XXE_SAXPARSER-1 + secondary_identifiers: + - name: Find Security Bugs-XXE_SAXPARSER + type: find_sec_bugs_type + value: XXE_SAXPARSER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.XXE_SAXPARSER-1 + shortlink: https://sg.run/6JGej + semgrep.dev: + rule: + r_id: 144359 + rv_id: 920450 + rule_id: OrUNwLe + version_id: LjTzelk + url: https://semgrep.dev/playground/r/LjTzelk/gitlab.find_sec_bugs_kotlin.XXE_SAXPARSER-1 + origin: community + subcategory: + - audit + severity: ERROR + patterns: + - pattern-inside: | + $SF = SAXParserFactory.newInstance() + ... + - pattern-not-inside: | + $SF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + ... + - pattern-not-inside: | + $SF.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + ... + - pattern-inside: | + $P = $SFP.newSAXParser(); + ... + - pattern: "$P.parse(...);" +- id: gitlab.find_sec_bugs_kotlin.XXE_XMLREADER-1 + languages: + - kotlin + message: | + XML External Entity (XXE) attacks can occur when an XML parser supports XML + entities while processing XML received from an untrusted source. + metadata: + shortDescription: Improper restriction of XML external entity reference ('XXE') + category: security + cwe: CWE-611 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: CRITICAL + primary_identifier: find_sec_bugs.XXE_XMLREADER-1 + secondary_identifiers: + - name: Find Security Bugs-XXE_XMLREADER + type: find_sec_bugs_type + value: XXE_XMLREADER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.XXE_XMLREADER-1 + shortlink: https://sg.run/oqP9n + semgrep.dev: + rule: + r_id: 144360 + rv_id: 920451 + rule_id: eqU0QP6 + version_id: 8KTvlBN + url: https://semgrep.dev/playground/r/8KTvlBN/gitlab.find_sec_bugs_kotlin.XXE_XMLREADER-1 + origin: community + subcategory: + - audit + severity: ERROR + patterns: + - pattern-inside: | + $R = XMLReaderFactory.createXMLReader() + ... + - pattern-not-inside: | + $R.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) + ... + - pattern: "$R.parse(...)" +- id: gitlab.find_sec_bugs_kotlin.XXE_XMLSTREAMREADER-1 + languages: + - kotlin + message: | + XML External Entity (XXE) attacks can occur when an XML parser supports XML + entities while processing XML received from an untrusted source. + metadata: + shortDescription: Improper restriction of XML external entity reference ('XXE') + category: security + cwe: CWE-611 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: CRITICAL + primary_identifier: find_sec_bugs.XXE_XMLSTREAMREADER-1 + secondary_identifiers: + - name: Find Security Bugs-XXE_XMLSTREAMREADER + type: find_sec_bugs_type + value: XXE_XMLSTREAMREADER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_kotlin.XXE_XMLSTREAMREADER-1 + shortlink: https://sg.run/zdqb0 + semgrep.dev: + rule: + r_id: 144361 + rv_id: 920452 + rule_id: v8UYeb2 + version_id: gETkXnr + url: https://semgrep.dev/playground/r/gETkXnr/gitlab.find_sec_bugs_kotlin.XXE_XMLSTREAMREADER-1 + origin: community + subcategory: + - audit + severity: ERROR + patterns: + - pattern-inside: | + $SF = XMLInputFactory.newFactory(); + ... + - pattern-not-inside: | + $SF.setProperty(XMLInputFactory.SUPPORT_DTD, false); + ... + - pattern-not-inside: | + $SF.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); + ... + - pattern-not-inside: | + $SF.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); + ... + - pattern-not-inside: | + $SF.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); + ... + - pattern: "$SF.createXMLStreamReader(...)" +- id: gitlab.find_sec_bugs_scala.AWS_QUERY_INJECTION-1 + languages: + - scala + message: | + Constructing SimpleDB queries containing user input can allow an attacker to view unauthorized + records. + metadata: + category: security + cwe: CWE-943 + shortDescription: Improper Neutralization of Special Elements in Data Query Logic + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.AWS_QUERY_INJECTION + secondary_identifiers: + - name: Find Security Bugs-AWS_QUERY_INJECTION + type: find_sec_bugs_type + value: AWS_QUERY_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.AWS_QUERY_INJECTION-1 + shortlink: https://sg.run/wyeY + semgrep.dev: + rule: + r_id: 67973 + rv_id: 920245 + rule_id: PeUGZy + version_id: nWTnN2j + url: https://semgrep.dev/playground/r/nWTnN2j/gitlab.find_sec_bugs_scala.AWS_QUERY_INJECTION-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sinks: + - pattern: new com.amazonaws.services.simpledb.model.SelectRequest($QUERY, ...); + - patterns: + - pattern-inside: "$DB.select(($SR: com.amazonaws.services.simpledb.model.SelectRequest).withSelectExpression($QUERY,...));\n" + - pattern: "$QUERY" + - metavariable-pattern: + metavariable: "$DB" + pattern-either: + - pattern: "($DB: com.amazonaws.services.simpledb.AmazonSimpleDB)" + - pattern: "($DB: com.amazonaws.services.simpledb.AmazonSimpleDBClient)" + pattern-sources: + - patterns: + - pattern-inside: | + def $FUNC(..., $REQ: HttpServletRequest, ...): $TYPE = { + ... + } + - pattern: "$REQ" + - patterns: + - pattern-inside: | + def $FUNC(..., $X: $TYPE, ...): $RET_TYPE = { + ... + $QUERY = <...$X...> + ... + } + - pattern: "$QUERY" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.BAD_HEXA_CONVERSION-1 + languages: + - scala + message: | + When converting a byte array containing a hash signature to a human readable string, a + conversion mistake can be made if the array is read byte by byte. + metadata: + category: security + confidence: HIGH + cwe: CWE-704 + shortDescription: Incorrect Type Conversion or Cast + security-severity: Medium + primary_identifier: find_sec_bugs.BAD_HEXA_CONVERSION + secondary_identifiers: + - name: Find Security Bugs-BAD_HEXA_CONVERSION + type: find_sec_bugs_type + value: BAD_HEXA_CONVERSION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.BAD_HEXA_CONVERSION-1 + shortlink: https://sg.run/GKWB + semgrep.dev: + rule: + r_id: 68004 + rv_id: 920275 + rule_id: eqUKvP + version_id: 1QT4N22 + url: https://semgrep.dev/playground/r/1QT4N22/gitlab.find_sec_bugs_scala.BAD_HEXA_CONVERSION-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: | + $B_ARR = ($MD: java.security.MessageDigest).digest(...); + ... + for(...) { + ... + Integer.toHexString(...); + } + - pattern: | + $B_ARR = ($MD: java.security.MessageDigest).digest(...); + ... + while(...) { + ... + Integer.toHexString(...); + } + severity: WARNING +- id: gitlab.find_sec_bugs_scala.BEAN_PROPERTY_INJECTION-1 + languages: + - scala + message: | + An attacker can set arbitrary bean properties that can compromise system integrity. An + attacker can leverage this functionality to access special bean properties like + class.classLoader that will allow them to override system properties and potentially execute + arbitrary code. + metadata: + category: security + cwe: CWE-15 + shortDescription: External Control of System or Configuration Setting + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.BEAN_PROPERTY_INJECTION + secondary_identifiers: + - name: Find Security Bugs-BEAN_PROPERTY_INJECTION + type: find_sec_bugs_type + value: BEAN_PROPERTY_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.BEAN_PROPERTY_INJECTION-1 + shortlink: https://sg.run/x31z + semgrep.dev: + rule: + r_id: 67974 + rv_id: 920246 + rule_id: JDURyW + version_id: ExT1WE7 + url: https://semgrep.dev/playground/r/ExT1WE7/gitlab.find_sec_bugs_scala.BEAN_PROPERTY_INJECTION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: 'def $FUNC(..., $REQ: HttpServletRequest, ...): $TYPE = { ... + }' + - pattern-either: + - pattern: | + $MAP.put(..., $REQ.getParameter(...)) + ... + $BEAN_UTIL.populate(..., $MAP) + - pattern: | + while (...) { + ... + $MAP.put(..., $REQ.getParameterValues(...). ...) + } + ... + $BEAN_UTIL.populate(..., $MAP) + - metavariable-pattern: + metavariable: "$BEAN_UTIL" + pattern-either: + - pattern: "(BeanUtilsBean $B)" + - pattern: new BeanUtilsBean() + - pattern: org.apache.commons.beanutils.BeanUtils + severity: ERROR +- id: gitlab.find_sec_bugs_scala.BLOWFISH_KEY_SIZE-1 + languages: + - scala + message: | + A small key size makes the ciphertext vulnerable to brute force attacks. At least 128 bits of + entropy should be used when generating the key if use of Blowfish is required. + metadata: + category: security + cwe: CWE-326 + shortDescription: Inadequate Encryption Strength + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.BLOWFISH_KEY_SIZE + secondary_identifiers: + - name: Find Security Bugs-BLOWFISH_KEY_SIZE + type: find_sec_bugs_type + value: BLOWFISH_KEY_SIZE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.BLOWFISH_KEY_SIZE-1 + shortlink: https://sg.run/ARvp + semgrep.dev: + rule: + r_id: 67950 + rv_id: 920222 + rule_id: ZqUd5K + version_id: l4TXDJz + url: https://semgrep.dev/playground/r/l4TXDJz/gitlab.find_sec_bugs_scala.BLOWFISH_KEY_SIZE-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + $KEYGEN = javax.crypto.KeyGenerator.getInstance("Blowfish", ...); + ... + $KEYGEN.init($KEY_SIZE); + - metavariable-comparison: + comparison: "$KEY_SIZE < 128" + metavariable: "$KEY_SIZE" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.CIPHER_INTEGRITY-1 + languages: + - scala + message: | + The ciphertext produced is susceptible to alteration by an adversary. This mean that the + cipher provides no way to detect that the data has been tampered with. If the ciphertext can be + controlled by an attacker, it could be altered without detection. + metadata: + category: security + cwe: CWE-353 + shortDescription: Missing Support for Integrity Check + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.CIPHER_INTEGRITY + secondary_identifiers: + - name: Find Security Bugs-CIPHER_INTEGRITY + type: find_sec_bugs_type + value: CIPHER_INTEGRITY + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.CIPHER_INTEGRITY-1 + shortlink: https://sg.run/09Qv + semgrep.dev: + rule: + r_id: 67954 + rv_id: 920226 + rule_id: L1UeyB + version_id: zyTG3bG + url: https://semgrep.dev/playground/r/zyTG3bG/gitlab.find_sec_bugs_scala.CIPHER_INTEGRITY-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: javax.crypto.Cipher.getInstance("...") + - pattern-either: + - pattern-regex: "(/CBC/PKCS5Padding)" + - pattern-regex: "(AES|DES(ede)?)(/ECB/*)" + - pattern-regex: "(AES|DES(ede)?)(/CBC/*)" + - pattern-regex: "(AES|DES(ede)?)(/OFB/*)" + - pattern-regex: "(AES|DES(ede)?)(/CTR/*)" + - pattern-not-regex: ".*/(CCM|CWC|OCB|EAX|GCM)/.*" + - pattern-not-regex: "^(RSA)/.*" + - pattern-not-regex: "^(ECIES)$" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.COMMAND_INJECTION-1.SCALA_COMMAND_INJECTION-1 + languages: + - scala + message: | + The highlighted API is used to execute a system command. If unfiltered input is passed to this + API, it can lead to arbitrary command execution. + metadata: + category: security + cwe: CWE-78 + shortDescription: Improper Neutralization of Special Elements used in an OS Command + ('OS Command Injection') + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.COMMAND_INJECTION-1.SCALA_COMMAND_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-COMMAND_INJECTION + type: find_sec_bugs_type + value: COMMAND_INJECTION + - name: Find Security Bugs-SCALA_COMMAND_INJECTION + type: find_sec_bugs_type + value: SCALA_COMMAND_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.COMMAND_INJECTION-1.SCALA_COMMAND_INJECTION-1 + shortlink: https://sg.run/eALb + semgrep.dev: + rule: + r_id: 67976 + rv_id: 920248 + rule_id: GdUX7G + version_id: LjTzekv + url: https://semgrep.dev/playground/r/LjTzekv/gitlab.find_sec_bugs_scala.COMMAND_INJECTION-1.SCALA_COMMAND_INJECTION-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern-inside: | + def $FUNC(..., $PARAM: String, ...): $TYPE = { + ... + } + - pattern-inside: | + val $RT = Runtime.getRuntime + ... + - pattern-either: + - pattern: "$RT.exec($PARAM)" + - pattern: | + var $CMDARR = new Array[String]("$SHELL",...,$PARAM,...) + ... + $RT.exec($CMDARR,...) + - pattern: $RT.exec(Array[String]("$SHELL",...,$PARAM,...), ...) + - pattern: $RT.exec(java.util.String.format("...", ...,$PARAM,...)) + - pattern: "$RT.exec(($A: String) + ($B: String))" + - metavariable-regex: + metavariable: "$SHELL" + regex: "(/.../)?(sh|bash|ksh|csh|tcsh|zsh)$" + - pattern-not: $RT.exec("...","...","...",...) + - pattern-not: $RT.exec(new Array[String]("...","...","...",...),...) + - patterns: + - pattern-inside: | + def $FUNC(...,$PARAM: String, ...): $TYPE = { + ... + } + - pattern-inside: | + val $PB = new ProcessBuilder() + ... + - pattern-either: + - pattern: "$PB.command($PARAM,...)" + - patterns: + - pattern-either: + - pattern: $PB.command("$SHELL",...,$PARAM,...) + - pattern: | + var $CMDARR = java.util.Arrays.asList("$SHELL",...,$PARAM,...) + ... + $PB.command($CMDARR,...) + - pattern: $PB.command(java.util.Arrays.asList("$SHELL",...,$PARAM,...),...) + - pattern: $PB.command(java.util.String.format("...", ...,$PARAM,...)) + - pattern: "$PB.command(($A: String) + ($B: String))" + - metavariable-regex: + metavariable: "$SHELL" + regex: "(/.../)?(sh|bash|ksh|csh|tcsh|zsh)$" + - pattern-not: $PB.command("...","...","...",...) + - pattern-not: '$PB.command(java.util.Arrays.asList("...","...","...",...)) + + ' + severity: WARNING +- id: gitlab.find_sec_bugs_scala.COOKIE_PERSISTENT-1 + languages: + - scala + message: | + "Storing sensitive data in a persistent cookie for an extended period can lead to a breach of + confidentiality or account compromise." + metadata: + category: security + cwe: CWE-614 + shortDescription: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.COOKIE_PERSISTENT + secondary_identifiers: + - name: Find Security Bugs-COOKIE_PERSISTENT + type: find_sec_bugs_type + value: COOKIE_PERSISTENT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.COOKIE_PERSISTENT-1 + shortlink: https://sg.run/Qj54 + semgrep.dev: + rule: + r_id: 67942 + rv_id: 920214 + rule_id: NbURkY + version_id: RGT2xRv + url: https://semgrep.dev/playground/r/RGT2xRv/gitlab.find_sec_bugs_scala.COOKIE_PERSISTENT-1 + origin: community + subcategory: + - audit + patterns: + - pattern: "($C: Cookie).setMaxAge($AGE)\n" + - metavariable-comparison: + comparison: "$AGE >= 31536000" + metavariable: "$AGE" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.COOKIE_USAGE-1 + languages: + - scala + message: | + The information stored in a custom cookie should not be sensitive or related to the session. + In most cases, sensitive data should only be stored in session and referenced by the user's + session cookie. + metadata: + category: security + cwe: CWE-614 + shortDescription: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.COOKIE_USAGE + secondary_identifiers: + - name: Find Security Bugs-COOKIE_USAGE + type: find_sec_bugs_type + value: COOKIE_USAGE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.COOKIE_USAGE-1 + shortlink: https://sg.run/3bxr + semgrep.dev: + rule: + r_id: 67943 + rv_id: 920215 + rule_id: kxUPkw + version_id: A8TNlXb + url: https://semgrep.dev/playground/r/A8TNlXb/gitlab.find_sec_bugs_scala.COOKIE_USAGE-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + def $FUNC(..., $REQ: HttpServletRequest, ...): $TYPE = { + ... + } + - pattern-either: + - patterns: + - pattern-inside: | + for ($C <- $REQ.getCookies) { + ... + } + - pattern-either: + - pattern: "$C.getName" + - pattern: "$C.getValue" + - pattern: "$C.getPath" + - pattern: "($C: Cookie).getName()" + - pattern: "($C: Cookie).getValue" + - pattern: "($C: Cookie).getPath" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.CRLF_INJECTION_LOGS-1 + languages: + - scala + message: | + When data from an untrusted source is put into a logger and not neutralized correctly, an + attacker could forge log entries or include malicious content. Inserted false entries could be + used to skew statistics, distract the administrator or even to implicate another party in the + commission of a malicious act. If the log file is processed automatically, the attacker can + render the file unusable by corrupting the format of the file or injecting unexpected + characters. An attacker may also inject code or other commands into the log file and take + advantage of a vulnerability in the log processing utility (e.g. command injection or XSS). + metadata: + category: security + cwe: CWE-93 + shortDescription: Improper Neutralization of CRLF Sequences ('CRLF Injection') + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.CRLF_INJECTION_LOGS + secondary_identifiers: + - name: Find Security Bugs-CRLF_INJECTION_LOGS + type: find_sec_bugs_type + value: CRLF_INJECTION_LOGS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.CRLF_INJECTION_LOGS-1 + shortlink: https://sg.run/O2PB + semgrep.dev: + rule: + r_id: 67975 + rv_id: 920247 + rule_id: 5rUGOX + version_id: 7ZTbRE8 + url: https://semgrep.dev/playground/r/7ZTbRE8/gitlab.find_sec_bugs_scala.CRLF_INJECTION_LOGS-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: $STR.replaceAll("$REPLACE_CHAR", "$REPLACE"); + - pattern: "$STR" + - metavariable-regex: + metavariable: "$REPLACE_CHAR" + regex: "(.*\\\\r\\\\n.*)" + - metavariable-regex: + metavariable: "$REPLACE" + regex: "(?!(\\\\r\\\\n))" + - pattern: org.owasp.encoder.Encode.forUriComponent(...) + - pattern: org.owasp.encoder.Encode.forUri(...) + - pattern: java.net.URLEncoder.encode(..., $CHARSET) + pattern-sinks: + - patterns: + - patterns: + - pattern: "$LOGGER.$METHOD(...,<...$TAINTED...>,...)" + - focus-metavariable: "$TAINTED" + - metavariable-regex: + metavariable: "$METHOD" + regex: "(log|logp|logrb|entering|exiting|fine|finer|finest|info|debug|trace|warn|warning|config|error|severe)" + - metavariable-pattern: + metavariable: "$LOGGER" + pattern-either: + - pattern: Logger + - pattern: log + - pattern: logger + - pattern: org.pmw.tinylog.Logger + - pattern: org.apache.log4j.Logger + - pattern: org.apache.logging.log4j.Logger + - pattern: org.slf4j.Logger + - pattern: org.apache.commons.logging.Log + - pattern: java.util.logging.Logger + pattern-sources: + - patterns: + - pattern-inside: | + def $FUNC(..., $REQ: HttpServletRequest, ...) : $TYPE = { + ... + } + - pattern: "$REQ.getParameter(...)" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.CUSTOM_INJECTION-1 + languages: + - scala + message: | + The method identified is susceptible to injection. The input should be validated and properly + escaped. + metadata: + category: security + cwe: CWE-89 + shortDescription: Improper Neutralization of Special Elements used in an SQL Command + ('SQL Injection') + technology: + - scala + security-severity: Low + primary_identifier: find_sec_bugs.CUSTOM_INJECTION + secondary_identifiers: + - name: Find Security Bugs-CUSTOM_INJECTION + type: find_sec_bugs_type + value: CUSTOM_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.CUSTOM_INJECTION-1 + shortlink: https://sg.run/v9zA + semgrep.dev: + rule: + r_id: 67977 + rv_id: 920249 + rule_id: ReUxgb + version_id: 8KTvl58 + url: https://semgrep.dev/playground/r/8KTvl58/gitlab.find_sec_bugs_scala.CUSTOM_INJECTION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern-inside: | + val $ST = connection.createStatement + ... + - pattern-either: + - pattern: | + val $QUERY = ... + $VAR + ... + ... + $ST.executeQuery($QUERY) + - pattern: | + val $QUERY = ... + $VAR + ... + $ST.executeQuery($QUERY) + - pattern: | + val $QUERY = String.format("...",...,$VAR,...) + ... + $ST.executeQuery($QUERY) + - pattern: "$ST.executeQuery(($SB: StringBuilder).toString())" + - pattern: "$ST.executeQuery(... + $VAR + ...)" + - pattern: "$ST.executeQuery(... + $VAR)" + - pattern: $ST.executeQuery(...,String.format("...",...,$VAR,...), ...) + severity: WARNING +- id: gitlab.find_sec_bugs_scala.CUSTOM_INJECTION-2 + languages: + - scala + message: | + The method identified is susceptible to injection. The input should be validated and properly + escaped. + metadata: + category: security + cwe: CWE-89 + shortDescription: Improper Neutralization of Special Elements used in an SQL Command + ('SQL Injection') + technology: + - scala + security-severity: High + primary_identifier: find_sec_bugs.CUSTOM_INJECTION-2 + secondary_identifiers: + - name: Find Security Bugs-CUSTOM_INJECTION + type: find_sec_bugs_type + value: CUSTOM_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.CUSTOM_INJECTION-2 + shortlink: https://sg.run/dRKZ + semgrep.dev: + rule: + r_id: 67978 + rv_id: 920250 + rule_id: AbUlzY + version_id: gETkXB2 + url: https://semgrep.dev/playground/r/gETkXB2/gitlab.find_sec_bugs_scala.CUSTOM_INJECTION-2 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + def $FOO(..., $SQLIN: String, ...): $TYPE = { + ... + } + - pattern-either: + - pattern: '"$SQL_STR" + $SQLIN + + ' + - pattern: String.format("$SQL_STR", ... + $SQLIN + ...) + - pattern: '"$SQL_STR".concat(...) + + ' + - pattern: (StringBuilder $BUILDER). ... .append("$SQL_STR") + - patterns: + - pattern-inside: | + StringBuilder $BUILDER = new StringBuilder(... + "$SQL_STR" + ...); + ... + - pattern: "$BUILDER.append(...)" + - pattern-not: $BUILDER.append("...") + - patterns: + - pattern-inside: | + $QUERY = "$SQL_STR"; + ... + - pattern: "$QUERY += ..." + - metavariable-regex: + metavariable: "$SQL_STR" + regex: "(?i)(select|insert|create|update|alter|delete|drop)\\b" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.CUSTOM_MESSAGE_DIGEST-1 + languages: + - scala + message: | + Implementing a custom MessageDigest is error-prone. 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. + metadata: + category: security + cwe: CWE-327 + shortDescription: Use of a Broken or Risky Cryptographic Algorithm + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.CUSTOM_MESSAGE_DIGEST + secondary_identifiers: + - name: Find Security Bugs-CUSTOM_MESSAGE_DIGEST + type: find_sec_bugs_type + value: CUSTOM_MESSAGE_DIGEST + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.CUSTOM_MESSAGE_DIGEST-1 + shortlink: https://sg.run/qpxz + semgrep.dev: + rule: + r_id: 67956 + rv_id: 920228 + rule_id: gxUX15 + version_id: 2KTdOvr + url: https://semgrep.dev/playground/r/2KTdOvr/gitlab.find_sec_bugs_scala.CUSTOM_MESSAGE_DIGEST-1 + origin: community + subcategory: + - audit + patterns: + - pattern: | + class $CLAZZ extends java.security.MessageDigest(...) { + ... + } + severity: WARNING +- id: gitlab.find_sec_bugs_scala.DANGEROUS_PERMISSION_COMBINATION-1 + pattern-either: + - pattern: | + $RUNVAR = new RuntimePermission("createClassLoader"); + ... + ($PC: PermissionCollection).add($RUNVAR); + - pattern: | + $REFVAR = new ReflectPermission("suppressAccessChecks"); + ... + ($PC: PermissionCollection).add($REFVAR); + - pattern: '($PC: PermissionCollection).add(new ReflectPermission ("suppressAccessChecks"))' + - pattern: '($PC: PermissionCollection).add(new RuntimePermission("createClassLoader"))' + languages: + - scala + message: 'Do not grant dangerous combinations of permissions. + + ' + metadata: + shortDescription: Improper privilege management + category: security + cwe: CWE-269 + confidence: HIGH + security-severity: Info + primary_identifier: find_sec_bugs.DANGEROUS_PERMISSION_COMBINATION + secondary_identifiers: + - name: Find Security Bugs-DANGEROUS_PERMISSION_COMBINATION + type: find_sec_bugs_type + value: DANGEROUS_PERMISSION_COMBINATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.DANGEROUS_PERMISSION_COMBINATION-1 + shortlink: https://sg.run/ARlp + semgrep.dev: + rule: + r_id: 67994 + rv_id: 920266 + rule_id: 10UNZy + version_id: l4TXDZz + url: https://semgrep.dev/playground/r/l4TXDZz/gitlab.find_sec_bugs_scala.DANGEROUS_PERMISSION_COMBINATION-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs_scala.DEFAULT_HTTP_CLIENT-1 + patterns: + - pattern: new org.apache.http.impl.client.DefaultHttpClient(...) + message: 'DefaultHttpClient with default constructor is not compatible with TLS + 1.2 + + ' + languages: + - scala + severity: WARNING + metadata: + shortDescription: Inadequate encryption strength + category: security + cwe: CWE-326 + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.DEFAULT_HTTP_CLIENT + secondary_identifiers: + - name: Find Security Bugs-DEFAULT_HTTP_CLIENT + type: find_sec_bugs_type + value: DEFAULT_HTTP_CLIENT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.DEFAULT_HTTP_CLIENT-1 + shortlink: https://sg.run/ll2y + semgrep.dev: + rule: + r_id: 67957 + rv_id: 920229 + rule_id: QrUNzB + version_id: X0TAKz2 + url: https://semgrep.dev/playground/r/X0TAKz2/gitlab.find_sec_bugs_scala.DEFAULT_HTTP_CLIENT-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs_scala.DES_USAGE-1 + languages: + - scala + message: | + DES is considered strong ciphers for modern applications. Currently, NIST recommends the usage + of AES block ciphers instead of DES. + metadata: + category: security + cwe: CWE-326 + shortDescription: Inadequate Encryption Strength + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.DES_USAGE + secondary_identifiers: + - name: Find Security Bugs-DES_USAGE + type: find_sec_bugs_type + value: DES_USAGE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.DES_USAGE-1 + shortlink: https://sg.run/BAkW + semgrep.dev: + rule: + r_id: 67951 + rv_id: 920223 + rule_id: nJUNz9 + version_id: YDTYbZD + url: https://semgrep.dev/playground/r/YDTYbZD/gitlab.find_sec_bugs_scala.DES_USAGE-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: javax.crypto.Cipher.getInstance("$ALG") + - metavariable-regex: + metavariable: "$ALG" + regex: "^(DES)/.*" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.DMI_CONSTANT_DB_PASSWORD-1.HARD_CODE_PASSWORD-3 + patterns: + - pattern: 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 + metadata: + category: security + cwe: CWE-259 + shortDescription: Use of Hard-coded Password + technology: + - scala + security-severity: Critical + primary_identifier: find_sec_bugs.DMI_CONSTANT_DB_PASSWORD-1.HARD_CODE_PASSWORD-3 + secondary_identifiers: + - name: Find Security Bugs-DMI_CONSTANT_DB_PASSWORD + type: find_sec_bugs_type + value: DMI_CONSTANT_DB_PASSWORD + - name: Find Security Bugs-HARD_CODE_PASSWORD + type: find_sec_bugs_type + value: HARD_CODE_PASSWORD + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.DMI_CONSTANT_DB_PASSWORD-1.HARD_CODE_PASSWORD-3 + shortlink: https://sg.run/5k8A + semgrep.dev: + rule: + r_id: 67991 + rv_id: 920263 + rule_id: 2ZUO4Y + version_id: 0bTp3o7 + url: https://semgrep.dev/playground/r/0bTp3o7/gitlab.find_sec_bugs_scala.DMI_CONSTANT_DB_PASSWORD-1.HARD_CODE_PASSWORD-3 + origin: community + subcategory: + - audit + severity: ERROR + languages: + - scala +- id: gitlab.find_sec_bugs_scala.DMI_EMPTY_DB_PASSWORD-1.HARD_CODE_PASSWORD-2 + 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 + metadata: + category: security + cwe: CWE-259 + shortDescription: Use of Hard-coded Password + technology: + - scala + security-severity: Critical + primary_identifier: find_sec_bugs.DMI_EMPTY_DB_PASSWORD-1.HARD_CODE_PASSWORD-2 + secondary_identifiers: + - name: Find Security Bugs-DMI_EMPTY_DB_PASSWORD + type: find_sec_bugs_type + value: DMI_EMPTY_DB_PASSWORD + - name: Find Security Bugs-HARD_CODE_PASSWORD + type: find_sec_bugs_type + value: HARD_CODE_PASSWORD + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.DMI_EMPTY_DB_PASSWORD-1.HARD_CODE_PASSWORD-2 + shortlink: https://sg.run/GKWp + semgrep.dev: + rule: + r_id: 67992 + rv_id: 920264 + rule_id: X5UKZx + version_id: K3TwLob + url: https://semgrep.dev/playground/r/K3TwLob/gitlab.find_sec_bugs_scala.DMI_EMPTY_DB_PASSWORD-1.HARD_CODE_PASSWORD-2 + origin: community + subcategory: + - audit + languages: + - scala + severity: ERROR +- id: gitlab.find_sec_bugs_scala.ECB_MODE-1 + languages: + - scala + message: | + An authentication cipher mode which provides better confidentiality of the encrypted data + should be used instead of Electronic Code Book (ECB) mode, which does not provide good + confidentiality. Specifically, ECB mode produces the same output for the same input each time. + This allows an attacker to intercept and replay the data. + metadata: + category: security + cwe: CWE-326 + shortDescription: Inadequate Encryption Strength + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.ECB_MODE + secondary_identifiers: + - name: Find Security Bugs-ECB_MODE + type: find_sec_bugs_type + value: ECB_MODE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.ECB_MODE-1 + shortlink: https://sg.run/WN84 + semgrep.dev: + rule: + r_id: 67953 + rv_id: 920225 + rule_id: 7KURQZ + version_id: o5TK1bB + url: https://semgrep.dev/playground/r/o5TK1bB/gitlab.find_sec_bugs_scala.ECB_MODE-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: javax.crypto.Cipher.getInstance("...") + - pattern-regex: "(AES|DES(ede)?)(/ECB/*)" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.EL_INJECTION-1 + languages: + - scala + message: | + An expression is built with a dynamic value. The source of the value(s) should be verified to + avoid that unfiltered values fall into this risky code evaluation. + metadata: + category: security + cwe: CWE-94 + shortDescription: Improper Control of Generation of Code ('Code Injection') + technology: + - scala + security-severity: High + primary_identifier: find_sec_bugs.EL_INJECTION + secondary_identifiers: + - name: Find Security Bugs-EL_INJECTION + type: find_sec_bugs_type + value: EL_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.EL_INJECTION-1 + shortlink: https://sg.run/ZxvD + semgrep.dev: + rule: + r_id: 67979 + rv_id: 920251 + rule_id: BYULN2 + version_id: QkT1NGN + url: https://semgrep.dev/playground/r/QkT1NGN/gitlab.find_sec_bugs_scala.EL_INJECTION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + import javax.el._ + ... + - pattern-either: + - pattern-inside: | + def $FUNC(..., $EXPR: String, ...) : $TYPE = { + ... + } + - pattern-inside: | + def $FUNC(..., $EXPR: String, ...) = { + ... + } + - pattern-either: + - pattern: "$X.createValueExpression(..., $EXPR, ...)" + - pattern: "$X.createMethodExpression(..., $EXPR, ...)" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.EXTERNAL_CONFIG_CONTROL-1 + languages: + - scala + message: | + Allowing external control of system settings can disrupt service or cause an application to + behave in unexpected, and potentially malicious ways. An attacker could cause an error by + providing a nonexistent catalog name or connect to an unauthorized portion of the database. + metadata: + category: security + cwe: CWE-15 + shortDescription: External Control of System or Configuration Setting + technology: + - scala + security-severity: High + primary_identifier: find_sec_bugs.EXTERNAL_CONFIG_CONTROL + secondary_identifiers: + - name: Find Security Bugs-EXTERNAL_CONFIG_CONTROL + type: find_sec_bugs_type + value: EXTERNAL_CONFIG_CONTROL + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.EXTERNAL_CONFIG_CONTROL-1 + shortlink: https://sg.run/09nk + semgrep.dev: + rule: + r_id: 68010 + rv_id: 920281 + rule_id: 7KURe0 + version_id: kbTOPDr + url: https://semgrep.dev/playground/r/kbTOPDr/gitlab.find_sec_bugs_scala.EXTERNAL_CONFIG_CONTROL-1 + origin: community + subcategory: + - audit + patterns: + - pattern: | + $TAINTED = ($REQ: HttpServletRequest).getParameter(...); + ... + ($CONN: java.sql.Connection).setCatalog($TAINTED); + severity: WARNING +- id: gitlab.find_sec_bugs_scala.FILE_UPLOAD_FILENAME-1 + languages: + - scala + message: | + The filename provided by the FileUpload API can be tampered with by the client to reference + unauthorized files. The provided filename should be properly validated to ensure it's properly + structured, contains no unauthorized path characters (e.g., / \), and refers to an authorized + file. + metadata: + category: security + cwe: CWE-22 + shortDescription: Improper limitation of a pathname to a restricted directory + ('Path Traversal') + technology: + - scala + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Info + primary_identifier: find_sec_bugs.FILE_UPLOAD_FILENAME + secondary_identifiers: + - name: Find Security Bugs-FILE_UPLOAD_FILENAME + type: find_sec_bugs_type + value: FILE_UPLOAD_FILENAME + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.FILE_UPLOAD_FILENAME-1 + shortlink: https://sg.run/b57p + semgrep.dev: + rule: + r_id: 67970 + rv_id: 920242 + rule_id: KxULbq + version_id: vdTvQ0A + url: https://semgrep.dev/playground/r/vdTvQ0A/gitlab.find_sec_bugs_scala.FILE_UPLOAD_FILENAME-1 + origin: community + subcategory: + - audit + patterns: + - pattern: | + def $FUNC (..., $REQ: HttpServletRequest, ... ) = { + ... + val $FILES = ($SFU: ServletFileUpload).parseRequest($REQ) + ... + for ($FILE <- $FILES.asScala) { + ... + } + } + - pattern: "$ITEM.getName()" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.FORMAT_STRING_MANIPULATION-1 + languages: + - scala + message: | + Allowing user input to control format parameters could enable an attacker to cause exceptions + to be thrown or leak information.Attackers may be able to modify the format string argument, + such that an exception is thrown. If this exception is left uncaught, it may crash the + application. Alternatively, if sensitive information is used within the unused arguments, + attackers may change the format string to reveal this information. + metadata: + category: security + confidence: HIGH + cwe: CWE-134 + shortDescription: Use of Externally-Controlled Format String + security-severity: Info + primary_identifier: find_sec_bugs.FORMAT_STRING_MANIPULATION + secondary_identifiers: + - name: Find Security Bugs-FORMAT_STRING_MANIPULATION + type: find_sec_bugs_type + value: FORMAT_STRING_MANIPULATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.FORMAT_STRING_MANIPULATION-1 + shortlink: https://sg.run/R18E + semgrep.dev: + rule: + r_id: 68005 + rv_id: 920276 + rule_id: v8UQ5x + version_id: 9lTA7l3 + url: https://semgrep.dev/playground/r/9lTA7l3/gitlab.find_sec_bugs_scala.FORMAT_STRING_MANIPULATION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - patterns: + - pattern-inside: | + $INPUT = ($REQ: javax.servlet.http.HttpServletRequest).getParameter(...); + ... + - pattern-inside: "$FORMAT_STR = <... $INPUT ...>;\n" + - patterns: + - pattern-inside: | + val $INPUT = ($REQ: javax.servlet.http.HttpServletRequest).getParameter(...); + ... + - pattern-inside: | + val $FORMAT_STR = <... $INPUT ...>; + ... + - pattern-inside: 'val $FORMAT_STR = ... + ($REQ: javax.servlet.http.HttpServletRequest).getParameter(...) + + ...; ... + + ' + - pattern-inside: 'val $FORMAT_STR = ... + ($REQ: javax.servlet.http.HttpServletRequest).getParameter(...); + ... + + ' + - pattern-either: + - pattern: "$VAL = <... $INPUT ...>" + - pattern: String.format($FORMAT_STR, ...); + - pattern: String.format(java.util.Locale.$LOCALE, $FORMAT_STR, ...); + - pattern: "($F: java.util.Formatter).format($FORMAT_STR, ...);" + - pattern: "($F: java.util.Formatter).format(java.util.Locale.$LOCALE, $FORMAT_STR, + ...);" + - pattern: "($F: java.io.PrintStream).printf($FORMAT_STR, ...);" + - pattern: "($F: java.io.PrintStream).printf(java.util.Locale.$LOCALE, $FORMAT_STR, + ...);" + - pattern: "($F: java.io.PrintStream).format($FORMAT_STR, ...);" + - pattern: "($F: java.io.PrintStream).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, ...); + severity: ERROR +- id: gitlab.find_sec_bugs_scala.HARD_CODE_PASSWORD-1 + languages: + - scala + message: | + A potential hard-coded password was identified in the source code. + 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 + metadata: + category: security + cwe: CWE-259 + shortDescription: Use of Hard-coded Password + technology: + - scala + security-severity: High + primary_identifier: find_sec_bugs.HARD_CODE_PASSWORD + secondary_identifiers: + - name: Find Security Bugs-HARD_CODE_PASSWORD + type: find_sec_bugs_type + value: HARD_CODE_PASSWORD + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.HARD_CODE_PASSWORD-1 + shortlink: https://sg.run/R18O + semgrep.dev: + rule: + r_id: 67993 + rv_id: 920265 + rule_id: j2Ujqy + version_id: qkTpwOo + url: https://semgrep.dev/playground/r/qkTpwOo/gitlab.find_sec_bugs_scala.HARD_CODE_PASSWORD-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: java.security.KeyStore.PasswordProtection("...".toCharArray()) + - pattern: java.security.KeyStore.getInstance(...).load(..., "...".toCharArray()) + - pattern: '($KS: java.security.KeyStore).load(..., "...".toCharArray())' + - pattern: KeyManagerFactory.getInstance(...).init(..., "...".toCharArray()) + - pattern: '($KMF: KeyManagerFactory).init(..., "...".toCharArray())' + - pattern: PBEKeySpec("...", ...) + - pattern: PasswordAuthentication("...", "...") + - pattern: '($CB: PasswordCallback).setPassword("...")' + - pattern: KerberosKey(...,"...",...) + - pattern: java.sql.DriverManager.getConnection(..., "...") + - pattern: io.vertx.ext.web.handler.CSRFHandler.create(..., "...") + - pattern: $S.setPassword("...") + severity: ERROR +- id: gitlab.find_sec_bugs_scala.HAZELCAST_SYMMETRIC_ENCRYPTION-1 + languages: + - scala + message: | + The network communications for Hazelcast is configured to use a symmetric cipher (probably DES + or Blowfish). Those ciphers alone do not provide integrity or secure authentication. The use of + asymmetric encryption is preferred. + metadata: + category: security + cwe: CWE-326 + shortDescription: Inadequate Encryption Strength + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.HAZELCAST_SYMMETRIC_ENCRYPTION + secondary_identifiers: + - name: Find Security Bugs-HAZELCAST_SYMMETRIC_ENCRYPTION + type: find_sec_bugs_type + value: HAZELCAST_SYMMETRIC_ENCRYPTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.HAZELCAST_SYMMETRIC_ENCRYPTION-1 + shortlink: https://sg.run/Ywve + semgrep.dev: + rule: + r_id: 67958 + rv_id: 920230 + rule_id: 3qUwPg + version_id: jQTwjnn + url: https://semgrep.dev/playground/r/jQTwjnn/gitlab.find_sec_bugs_scala.HAZELCAST_SYMMETRIC_ENCRYPTION-1 + origin: community + subcategory: + - audit + patterns: + - pattern: new com.hazelcast.config.SymmetricEncryptionConfig() + severity: WARNING +- id: gitlab.find_sec_bugs_scala.HRS_REQUEST_PARAMETER_TO_COOKIE-1 + languages: + - scala + message: | + This code constructs an HTTP Cookie using an untrusted HTTP parameter. If this cookie is added + to an HTTP response, it will allow a HTTP response splitting vulnerability. See + http://en.wikipedia.org/wiki/HTTP_response_splitting for more information. + metadata: + category: security + cwe: CWE-113 + shortDescription: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP + Response Splitting') + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.HRS_REQUEST_PARAMETER_TO_COOKIE + secondary_identifiers: + - name: Find Security Bugs-HRS_REQUEST_PARAMETER_TO_COOKIE + type: find_sec_bugs_type + value: HRS_REQUEST_PARAMETER_TO_COOKIE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.HRS_REQUEST_PARAMETER_TO_COOKIE-1 + shortlink: https://sg.run/PXJY + semgrep.dev: + rule: + r_id: 67945 + rv_id: 920217 + rule_id: x8UrnN + version_id: DkT2yR6 + url: https://semgrep.dev/playground/r/DkT2yR6/gitlab.find_sec_bugs_scala.HRS_REQUEST_PARAMETER_TO_COOKIE-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: $STR.replaceAll("$REPLACE_CHAR", "$REPLACE"); + - pattern: "$STR" + - metavariable-regex: + metavariable: "$REPLACE_CHAR" + regex: "(.*\\\\r\\\\n.*)" + - metavariable-regex: + metavariable: "$REPLACE" + regex: "(?!(\\\\r\\\\n))" + - pattern: org.owasp.encoder.Encode.forUriComponent(...) + - pattern: org.owasp.encoder.Encode.forUri(...) + - pattern: java.net.URLEncoder.encode(..., $CHARSET) + 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: "($REQ: HttpServletRequest).getParameter(...);" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.HRS_REQUEST_PARAMETER_TO_HTTP_HEADER-1 + languages: + - scala + message: | + This code directly writes an HTTP parameter to an HTTP header, which allows for a HTTP + response splitting vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting for + more information. + metadata: + category: security + cwe: CWE-113 + shortDescription: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP + Response Splitting') + technology: + - scala + security-severity: High + primary_identifier: find_sec_bugs.HRS_REQUEST_PARAMETER_TO_HTTP_HEADER + secondary_identifiers: + - name: Find Security Bugs-HRS_REQUEST_PARAMETER_TO_HTTP_HEADER + type: find_sec_bugs_type + value: HRS_REQUEST_PARAMETER_TO_HTTP_HEADER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.HRS_REQUEST_PARAMETER_TO_HTTP_HEADER-1 + shortlink: https://sg.run/JY9w + semgrep.dev: + rule: + r_id: 67946 + rv_id: 920218 + rule_id: OrU73v + version_id: WrTYnqO + url: https://semgrep.dev/playground/r/WrTYnqO/gitlab.find_sec_bugs_scala.HRS_REQUEST_PARAMETER_TO_HTTP_HEADER-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: $STR.replaceAll("$REPLACE_CHAR", "$REPLACE"); + - pattern: "$STR" + - metavariable-regex: + metavariable: "$REPLACE_CHAR" + regex: "(.*\\\\r\\\\n.*)" + - metavariable-regex: + metavariable: "$REPLACE" + regex: "(?!(\\\\r\\\\n))" + - pattern: org.owasp.encoder.Encode.forUriComponent(...) + - pattern: org.owasp.encoder.Encode.forUri(...) + - pattern: java.net.URLEncoder.encode(..., $CHARSET) + pattern-sinks: + - pattern: '($RES: HttpServletResponse).setHeader("$KEY", ...);' + - pattern: '($RES: HttpServletResponse).addHeader("$KEY", ...);' + - pattern: '($WRP: HttpServletResponseWrapper).setHeader("$KEY", ...);' + - pattern: '($WRP: HttpServletResponseWrapper).addHeader("$KEY", ...);' + pattern-sources: + - pattern: "($REQ: HttpServletRequest).getParameter(...);" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.HTTPONLY_COOKIE-1 + languages: + - scala + message: | + A new cookie is created without the HttpOnly flag set. The HttpOnly flag is a directive to the + browser to make sure that the cookie can not be red by malicious script. When a user is the + target of a "Cross-Site Scripting", the attacker would benefit greatly from getting the session + id for example. + metadata: + category: security + cwe: CWE-1004 + shortDescription: Sensitive Cookie Without 'HttpOnly' Flag + technology: + - scala + security-severity: Low + primary_identifier: find_sec_bugs.HTTPONLY_COOKIE + secondary_identifiers: + - name: Find Security Bugs-HTTPONLY_COOKIE + type: find_sec_bugs_type + value: HTTPONLY_COOKIE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.HTTPONLY_COOKIE-1 + shortlink: https://sg.run/8Oyy + semgrep.dev: + rule: + r_id: 67940 + rv_id: 920212 + rule_id: r6Uvrr + version_id: 5PTNGev + url: https://semgrep.dev/playground/r/5PTNGev/gitlab.find_sec_bugs_scala.HTTPONLY_COOKIE-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern: | + val $C = new javax.servlet.http.Cookie(..., ...); + ... + $RESP.addCookie($C); + - pattern-not-inside: | + val $C = new javax.servlet.http.Cookie(..., ...); + ... + $C.setHttpOnly(true); + ... + $RESP.addCookie($C); + - pattern: "(javax.servlet.http.Cookie $C).setHttpOnly(false);" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.HTTP_PARAMETER_POLLUTION-1 + languages: + - scala + message: | + Concatenating unvalidated user input into a URL can allow an attacker to override the value of + a request parameter. Attacker may be able to override existing parameter values, inject a new + parameter or exploit variables out of a direct reach. HTTP Parameter Pollution (HPP) attacks + consist of injecting encoded query string delimiters into other existing parameters. If a web + application does not properly sanitize the user input, a malicious user may compromise the + logic of the application to perform either client-side or server-side attacks. + metadata: + category: security + cwe: CWE-88 + shortDescription: Improper Neutralization of Argument Delimiters in a Command + ('Argument Injection') + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.HTTP_PARAMETER_POLLUTION + secondary_identifiers: + - name: Find Security Bugs-HTTP_PARAMETER_POLLUTION + type: find_sec_bugs_type + value: HTTP_PARAMETER_POLLUTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.HTTP_PARAMETER_POLLUTION-1 + shortlink: https://sg.run/E35w + semgrep.dev: + rule: + r_id: 67981 + rv_id: 920253 + rule_id: WAUnZW + version_id: 44TeqEd + url: https://semgrep.dev/playground/r/44TeqEd/gitlab.find_sec_bugs_scala.HTTP_PARAMETER_POLLUTION-1 + origin: community + subcategory: + - audit + mode: taint + 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: "($GM: org.apache.commons.httpclient.methods.GetMethod).setQueryString(...)" + pattern-sources: + - pattern: "($REQ: HttpServletRequest ).getParameter(...)" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.HTTP_RESPONSE_SPLITTING-1 + languages: + - scala + message: | + When an HTTP request contains unexpected CR and LF characters, the server may respond with an + output stream that is interpreted as two different HTTP responses (instead of one). An attacker + can control the second response and mount attacks such as cross-site scripting and cache + poisoning attacks. + metadata: + category: security + cwe: CWE-113 + shortDescription: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP + Response Splitting') + technology: + - scala + security-severity: High + primary_identifier: find_sec_bugs.HTTP_RESPONSE_SPLITTING + secondary_identifiers: + - name: Find Security Bugs-HTTP_RESPONSE_SPLITTING + type: find_sec_bugs_type + value: HTTP_RESPONSE_SPLITTING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.HTTP_RESPONSE_SPLITTING-1 + shortlink: https://sg.run/4Nxl + semgrep.dev: + rule: + r_id: 67944 + rv_id: 920216 + rule_id: wdUbJl + version_id: BjTKLkW + url: https://semgrep.dev/playground/r/BjTKLkW/gitlab.find_sec_bugs_scala.HTTP_RESPONSE_SPLITTING-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: $STR.replaceAll("$REPLACE_CHAR", "$REPLACE"); + - pattern: "$STR" + - metavariable-regex: + metavariable: "$REPLACE_CHAR" + regex: "(.*\\\\r\\\\n.*)" + - metavariable-regex: + metavariable: "$REPLACE" + regex: "(?!(\\\\r\\\\n))" + - pattern: org.owasp.encoder.Encode.forUriComponent(...) + - pattern: org.owasp.encoder.Encode.forUri(...) + - pattern: java.net.URLEncoder.encode(..., $CHARSET) + pattern-sinks: + - pattern: new javax.servlet.http.Cookie("$KEY", ...) + - pattern: "($C:javax.servlet.http.Cookie).setValue(...)" + pattern-sources: + - pattern: "($REQ: javax.servlet.http.HttpServletRequest).getParameter(...)" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.IMPROPER_UNICODE-1 + languages: + - scala + message: 'Improper Handling of Unicode Encoding + + ' + metadata: + category: security + confidence: HIGH + cwe: CWE-176 + shortDescription: Improper Handling of Unicode Encoding + security-severity: Medium + primary_identifier: find_sec_bugs.IMPROPER_UNICODE + secondary_identifiers: + - name: Find Security Bugs-IMPROPER_UNICODE + type: find_sec_bugs_type + value: IMPROPER_UNICODE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.IMPROPER_UNICODE-1 + shortlink: https://sg.run/ARlg + semgrep.dev: + rule: + r_id: 68006 + rv_id: 920277 + rule_id: d8Ugz5 + version_id: yeTDgOG + url: https://semgrep.dev/playground/r/yeTDgOG/gitlab.find_sec_bugs_scala.IMPROPER_UNICODE-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern-either: + - pattern: | + $S = ($INPUT: String).$TRANSFORM(...); + ... + $S.$METHOD(...); + - pattern: "($INPUT: String).$TRANSFORM().$METHOD(...);" + - metavariable-regex: + metavariable: "$METHOD" + regex: "(equals|equalsIgnoreCase|indexOf)" + - metavariable-regex: + metavariable: "$TRANSFORM" + regex: "(toLowerCase|toUpperCase)" + - pattern: java.text.Normalizer.normalize(...); + - pattern: java.net.IDN.toASCII(...); + - pattern: "($U: URI).toASCIIString()" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE-1 + languages: + - scala + message: | + The sensitive information may be valuable information on its own (such as a password), or it + may be useful for launching other, more deadly attacks. If an attack fails, an attacker may use + error information provided by the server to launch another more focused attack. For example, an + attempt to exploit a path traversal weakness (CWE-22) might yield the full pathname of the + installed application. + metadata: + category: security + cwe: CWE-209 + shortDescription: Information Exposure Through an Error Message + technology: + - scala + security-severity: Low + primary_identifier: find_sec_bugs.INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE + secondary_identifiers: + - name: Find Security Bugs-INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE + type: find_sec_bugs_type + value: INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE-1 + shortlink: https://sg.run/K6WP + semgrep.dev: + rule: + r_id: 68011 + rv_id: 920282 + rule_id: L1Ue4j + version_id: w8Tkbpv + url: https://semgrep.dev/playground/r/w8Tkbpv/gitlab.find_sec_bugs_scala.INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE-1 + origin: community + subcategory: + - audit + patterns: + - pattern: "$E.printStackTrace(...)" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.INSECURE_COOKIE-1 + languages: + - scala + message: | + "A new cookie is created without the Secure flag set. The Secure flag is a + directive to the browser to make sure that the cookie is not sent for insecure communication + (http://)" + metadata: + category: security + cwe: CWE-539 + shortDescription: Information Exposure Through Persistent Cookies + technology: + - scala + security-severity: Low + primary_identifier: find_sec_bugs.INSECURE_COOKIE + secondary_identifiers: + - name: Find Security Bugs-INSECURE_COOKIE + type: find_sec_bugs_type + value: INSECURE_COOKIE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.INSECURE_COOKIE-1 + shortlink: https://sg.run/gDLJ + semgrep.dev: + rule: + r_id: 67941 + rv_id: 920213 + rule_id: bwUowO + version_id: GxToX82 + url: https://semgrep.dev/playground/r/GxToX82/gitlab.find_sec_bugs_scala.INSECURE_COOKIE-1 + origin: community + subcategory: + - audit + patterns: + - pattern-not-inside: | + val $C = new javax.servlet.http.Cookie(..., ...); + ... + $C.setSecure(true); + ... + $RESP.addCookie($C); + - pattern-either: + - pattern: | + val $C = new javax.servlet.http.Cookie(..., ...); + ... + $RESP.addCookie($C); + - pattern: "($C:javax.servlet.http.Cookie).setSecure(false);" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.INSECURE_SMTP_SSL-1 + languages: + - scala + message: 'Server identity verification is disabled when making SSL connections. + + ' + metadata: + cwe: CWE-297 + shortDescription: Improper Validation of Certificate with Host Mismatch + security-severity: High + category: security + owasp: + - A2:2017-Broken Authentication + - A07:2021-Identification and Authentication Failures + primary_identifier: find_sec_bugs.INSECURE_SMTP_SSL + secondary_identifiers: + - name: Find Security Bugs-INSECURE_SMTP_SSL + type: find_sec_bugs_type + value: INSECURE_SMTP_SSL + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.INSECURE_SMTP_SSL-1 + shortlink: https://sg.run/4Nyg + semgrep.dev: + rule: + r_id: 68000 + rv_id: 920271 + rule_id: kxUPRZ + version_id: pZTbDnN + url: https://semgrep.dev/playground/r/pZTbDnN/gitlab.find_sec_bugs_scala.INSECURE_SMTP_SSL-1 + origin: community + subcategory: + - audit + 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: | + $E.setSSLOnConnect(true); + ... + $E.setSSLCheckServerIdentity(true); + severity: ERROR +- id: gitlab.find_sec_bugs_scala.JAXRS_ENDPOINT-1 + languages: + - scala + message: | + This method is part of a REST Web Service (JSR311). The security of this web service should be + analyzed. For example: + - Authentication, if enforced, should be tested. + - Access control, if enforced, should be tested. + - The inputs should be tracked for potential vulnerabilities. + - The communication should ideally be over SSL. + - If the service supports writes (e.g., via POST), its vulnerability to CSRF should be + investigated. + metadata: + category: security + cwe: CWE-20 + shortDescription: Improper Input Validation + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.JAXRS_ENDPOINT + secondary_identifiers: + - name: Find Security Bugs-JAXRS_ENDPOINT + type: find_sec_bugs_type + value: JAXRS_ENDPOINT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.JAXRS_ENDPOINT-1 + shortlink: https://sg.run/jKRY + semgrep.dev: + rule: + r_id: 67965 + rv_id: 920237 + rule_id: AbUlz8 + version_id: kbTOPzr + url: https://semgrep.dev/playground/r/kbTOPzr/gitlab.find_sec_bugs_scala.JAXRS_ENDPOINT-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sinks: + - pattern: "<...$VAR...>" + pattern-sources: + - patterns: + - pattern-inside: | + @javax.ws.rs.Path("...") + def $FUNC(..., $VAR: $TYPE, ...) = ... + - pattern: "$VAR" + severity: INFO +- id: gitlab.find_sec_bugs_scala.JAXWS_ENDPOINT-1 + languages: + - scala + message: | + This method is part of a SOAP Web Service (JSR224). The security of this web service should be + analyzed. For example: + - Authentication, if enforced, should be tested. + - Access control, if enforced, should be tested. + - The inputs should be tracked for potential vulnerabilities. + - The communication should ideally be over SSL. + metadata: + category: security + cwe: CWE-20 + owasp: + - A7:2017-Cross-Site Scripting (XSS) + - A03:2021-Injection + shortDescription: Improper Input Validation + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.JAXWS_ENDPOINT + secondary_identifiers: + - name: Find Security Bugs-JAXWS_ENDPOINT + type: find_sec_bugs_type + value: JAXWS_ENDPOINT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.JAXWS_ENDPOINT-1 + shortlink: https://sg.run/1yZw + semgrep.dev: + rule: + r_id: 67966 + rv_id: 920238 + rule_id: BYULNq + version_id: w8TkbRv + url: https://semgrep.dev/playground/r/w8TkbRv/gitlab.find_sec_bugs_scala.JAXWS_ENDPOINT-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sinks: + - pattern: "<...$VAR...>" + pattern-sources: + - patterns: + - pattern-inside: | + @javax.jws.WebMethod(...) + def $FUNC(..., $VAR: $TYPE, ...) = ... + - pattern: "$VAR" + severity: INFO +- id: gitlab.find_sec_bugs_scala.LDAP_ANONYMOUS-1 + languages: + - scala + message: | + Without proper access control, executing an LDAP statement that contains a + user-controlled value can allow an attacker to abuse poorly configured LDAP + context + metadata: + category: security + cwe: CWE-20 + shortDescription: Improper Input Validation + security-severity: Info + primary_identifier: find_sec_bugs.LDAP_ANONYMOUS + secondary_identifiers: + - name: Find Security Bugs-LDAP_ANONYMOUS + type: find_sec_bugs_type + value: LDAP_ANONYMOUS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.LDAP_ANONYMOUS-1 + shortlink: https://sg.run/PXpY + semgrep.dev: + rule: + r_id: 67989 + rv_id: 920261 + rule_id: zdU3yW + version_id: DkT2yk6 + url: https://semgrep.dev/playground/r/DkT2yk6/gitlab.find_sec_bugs_scala.LDAP_ANONYMOUS-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + import javax.naming.Context; + ... + - pattern: $ENV.put(Context.SECURITY_AUTHENTICATION, "none"); + severity: WARNING +- id: gitlab.find_sec_bugs_scala.LDAP_ENTRY_POISONING-1 + languages: + - scala + message: | + Without proper access control, executing an LDAP statement that contains a + user-controlled value can allow an attacker to abuse poorly configured LDAP + context + metadata: + category: security + cwe: CWE-20 + shortDescription: Improper Input Validation + security-severity: High + primary_identifier: find_sec_bugs.LDAP_ENTRY_POISONING + secondary_identifiers: + - name: Find Security Bugs-LDAP_ENTRY_POISONING + type: find_sec_bugs_type + value: LDAP_ENTRY_POISONING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.LDAP_ENTRY_POISONING-1 + shortlink: https://sg.run/JY3w + semgrep.dev: + rule: + r_id: 67990 + rv_id: 920262 + rule_id: pKUDGb + version_id: WrTYn8O + url: https://semgrep.dev/playground/r/WrTYn8O/gitlab.find_sec_bugs_scala.LDAP_ENTRY_POISONING-1 + origin: community + subcategory: + - audit + patterns: + - pattern: new javax.naming.directory.SearchControls($SCOPE, $CLIMIT, $TLIMIT, $ATTR, + true, $DEREF) + severity: ERROR +- id: gitlab.find_sec_bugs_scala.LDAP_INJECTION-1 + languages: + - scala + message: | + Just like SQL, all inputs passed to an LDAP query need to be passed in safely. Unfortunately, + LDAP doesn't have prepared statement interfaces like SQL. Therefore, the primary defense + against LDAP injection is strong input validation of any untrusted data before including it in + an LDAP query. + metadata: + category: security + cwe: CWE-90 + shortDescription: Improper Neutralization of Special Elements used in an LDAP + Query ('LDAP Injection') + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.LDAP_INJECTION + secondary_identifiers: + - name: Find Security Bugs-LDAP_INJECTION + type: find_sec_bugs_type + value: LDAP_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.LDAP_INJECTION-1 + shortlink: https://sg.run/7x0Z + semgrep.dev: + rule: + r_id: 67982 + rv_id: 920254 + rule_id: 0oU3Ey + version_id: PkTjGR6 + url: https://semgrep.dev/playground/r/PkTjGR6/gitlab.find_sec_bugs_scala.LDAP_INJECTION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern-inside: | + def $FUNC(..., $VAR: String, ...): $TYPE = { + ... + } + - pattern-inside: | + def $FUNC(..., $X: String, ...): $TYPE = { + ... + $VAR = ... + $X; + ... + } + - pattern-either: + - pattern: "($P: java.util.Properties).put($KEY, $VAR)" + - pattern: "$CTX.lookup(..., $VAR, ...)" + - pattern: "$CTX.search(..., $VAR, ...)" + - pattern: "$CTX.list(..., $VAR, ...)" + - metavariable-pattern: + metavariable: "$CTX" + pattern-either: + - pattern: "($CTX: javax.naming.directory.DirContext)" + - pattern: "($CTX: javax.naming.directory.Context)" + - pattern: "($CTX: javax.naming.Context)" + - pattern: "($CTX: javax.naming.directory.InitialDirContext)" + - pattern: "($CTX: javax.naming.ldap.LdapContext)" + - pattern: "($CTX: com.unboundid.ldap.sdk.LDAPConnection)" + - pattern: "($CTX: javax.naming.event.EventDirContext)" + - pattern: "($CTX: com.sun.jndi.ldap.LdapCtx)" + - pattern: "($CTX: org.springframework.ldap.core.LdapTemplate)" + - pattern: "($CTX: org.springframework.ldap.core.LdapOperations)" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.MALICIOUS_XSLT-1 + mode: taint + pattern-sources: + - patterns: + - pattern-either: + - patterns: + - pattern-inside: | + $FUNC(...,String $VAR, ...) { + ... + } + - pattern-either: + - pattern: new FileInputStream(<... $VAR ...>); + - pattern: getClass.getResourceAsStream(<... $VAR ...>) + - patterns: + - pattern-inside: | + class $CLZ { + String $X = "..."; + ... + } + - pattern-inside: | + $FUNC(...,String $Y, ...) { + ... + } + - 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" + languages: + - java + message: | + It is possible to attach malicious behavior to those style sheets. Therefore, if an attacker + can control the content or the source of the style sheet, he might be able to trigger remote + code execution. + metadata: + shortDescription: Improper neutralization of special elements in output used by + a downstream component ('Injection') + category: security + cwe: CWE-74 + security-severity: Medium + primary_identifier: find_sec_bugs.MALICIOUS_XSLT + secondary_identifiers: + - name: Find Security Bugs-MALICIOUS_XSLT + type: find_sec_bugs_type + value: MALICIOUS_XSLT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.MALICIOUS_XSLT-1 + shortlink: https://sg.run/ook7 + semgrep.dev: + rule: + r_id: 68016 + rv_id: 920287 + rule_id: 4bUqzj + version_id: d6T6g30 + url: https://semgrep.dev/playground/r/d6T6g30/gitlab.find_sec_bugs_scala.MALICIOUS_XSLT-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs_scala.MODIFICATION_AFTER_VALIDATION-1 + patterns: + - pattern: | + $Y.matcher($VAR); + ... + $VAR.$METHOD(...); + - metavariable-regex: + metavariable: "$METHOD" + regex: "(replace)" + languages: + - scala + message: 'CERT: IDS11-J. Perform any string modifications before validation + + ' + metadata: + shortDescription: Collapse of data into unsafe value + category: security + cwe: CWE-182 + confidence: HIGH + security-severity: Info + primary_identifier: find_sec_bugs.MODIFICATION_AFTER_VALIDATION + secondary_identifiers: + - name: Find Security Bugs-MODIFICATION_AFTER_VALIDATION + type: find_sec_bugs_type + value: MODIFICATION_AFTER_VALIDATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.MODIFICATION_AFTER_VALIDATION-1 + shortlink: https://sg.run/BA4b + semgrep.dev: + rule: + r_id: 68007 + rv_id: 920278 + rule_id: ZqUdq9 + version_id: rxTjv1N + url: https://semgrep.dev/playground/r/rxTjv1N/gitlab.find_sec_bugs_scala.MODIFICATION_AFTER_VALIDATION-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs_scala.NORMALIZATION_AFTER_VALIDATION-1 + patterns: + - pattern: | + $Y = java.util.regex.Pattern.compile("[<>]"); + ... + $Y.matcher($VAR); + ... + java.text.Normalizer.normalize($VAR, ...); + languages: + - scala + message: 'IDS01-J. Normalize strings before validating them + + ' + metadata: + shortDescription: Collapse of data into unsafe value + category: security + cwe: CWE-182 + confidence: HIGH + security-severity: Info + primary_identifier: find_sec_bugs.NORMALIZATION_AFTER_VALIDATION + secondary_identifiers: + - name: Find Security Bugs-NORMALIZATION_AFTER_VALIDATION + type: find_sec_bugs_type + value: NORMALIZATION_AFTER_VALIDATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.NORMALIZATION_AFTER_VALIDATION-1 + shortlink: https://sg.run/DDJ2 + semgrep.dev: + rule: + r_id: 68008 + rv_id: 920279 + rule_id: nJUNYE + version_id: bZTLoZ6 + url: https://semgrep.dev/playground/r/bZTLoZ6/gitlab.find_sec_bugs_scala.NORMALIZATION_AFTER_VALIDATION-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.find_sec_bugs_scala.NULL_CIPHER-1 + languages: + - scala + message: | + The NullCipher implements the Cipher interface by returning ciphertext identical to the + supplied plaintext. In a few contexts, such as testing, a NullCipher may be appropriate. Avoid + using the NullCipher. Its accidental use can introduce a significant confidentiality risk. + metadata: + category: security + cwe: CWE-327 + shortDescription: Use of a Broken or Risky Cryptographic Algorithm + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.NULL_CIPHER + secondary_identifiers: + - name: Find Security Bugs-NULL_CIPHER + type: find_sec_bugs_type + value: NULL_CIPHER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.NULL_CIPHER-1 + shortlink: https://sg.run/oox9 + semgrep.dev: + rule: + r_id: 67960 + rv_id: 920232 + rule_id: PeUGZw + version_id: 9lTA743 + url: https://semgrep.dev/playground/r/9lTA743/gitlab.find_sec_bugs_scala.NULL_CIPHER-1 + origin: community + subcategory: + - audit + pattern: new javax.crypto.NullCipher() + severity: WARNING +- id: gitlab.find_sec_bugs_scala.OGNL_INJECTION-1 + patterns: + - pattern-either: + - pattern-inside: | + def $FUNC(..., $VAR: String, ...): $TYPE = { + ... + } + - pattern-inside: | + def $FUNC(..., $VAR: Map[$K,$V], ...): $TYPE = { + ... + } + - pattern-inside: | + def $FUNC(..., $VAR: java.util.HashMap[$K,$V], ...): $TYPE = { + ... + } + - pattern-either: + - pattern: com.opensymphony.xwork2.util.TextParseUtil.translateVariables(..., + $VAR, ...) + - pattern: com.opensymphony.xwork2.util.TextParseUtil.translateVariablesCollection(..., + $VAR, ...) + - pattern: com.opensymphony.xwork2.util.TextParseUtil.shallBeIncluded(..., $VAR, + ...) + - pattern: com.opensymphony.xwork2.util.TextParseUtil.commaDelimitedStringToSet(..., + $VAR, ...) + - pattern: "($P:com.opensymphony.xwork2.util.TextParser).evaluate(..., $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.OgnlTextParser).evaluate(..., $VAR, + ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).getGetMethod(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).getSetMethod(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).getField(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).setProperties(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).setProperty(...,$VAR, + ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).getValue(...,$VAR, + ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlReflectionProvider).setValue(...,$VAR, + ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).getGetMethod(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).getSetMethod(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).getField(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).setProperties(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).setProperty(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).getValue(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.util.reflection.ReflectionProvider).setValue(..., + $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlUtil).setProperties(..., $VAR, + ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlUtil).setProperty(..., $VAR, + ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlUtil).getValue(..., $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlUtil).setValue(..., $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlUtil).callMethod(..., $VAR, ...)" + - pattern: "($P:com.opensymphony.xwork2.ognl.OgnlUtil).compile(..., $VAR, ...)" + - pattern: "($P:org.apache.struts2.util.VelocityStrutsUtil).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(...) + - pattern: org.apache.struts2.util.StrutsUtil.makeSelectList(..., $VAR, ...) + - pattern: "($T:org.apache.struts2.views.jsp.ui.OgnlTool).findValue(..., $VAR, + ...)" + - pattern: "($V:com.opensymphony.xwork2.util.ValueStack).findString(...)" + - pattern: "($V:com.opensymphony.xwork2.util.ValueStack).findValue(..., $VAR, + ...)" + - pattern: "($V:com.opensymphony.xwork2.util.ValueStack).setValue(..., $VAR, ...)" + - pattern: "($V:com.opensymphony.xwork2.util.ValueStack).setParameter(..., $VAR, + ...)" + message: | + "A expression is built with a dynamic value. The source of the value(s) should be verified to + avoid that unfiltered values fall into this risky code evaluation." + languages: + - scala + severity: WARNING + metadata: + shortDescription: Expression injection (OGNL) + category: security + cwe: CWE-917 + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.OGNL_INJECTION + secondary_identifiers: + - name: Find Security Bugs-OGNL_INJECTION + type: find_sec_bugs_type + value: OGNL_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.OGNL_INJECTION-1 + shortlink: https://sg.run/Lo0r + semgrep.dev: + rule: + r_id: 67983 + rv_id: 920255 + rule_id: KxUL4z + version_id: JdToRzd + url: https://semgrep.dev/playground/r/JdToRzd/gitlab.find_sec_bugs_scala.OGNL_INJECTION-1 + origin: community + subcategory: + - audit +- id: gitlab.find_sec_bugs_scala.OVERLY_PERMISSIVE_FILE_PERMISSION-1 + languages: + - scala + message: 'Overly permissive file permission + + ' + metadata: + category: security + confidence: HIGH + cwe: CWE-732 + shortDescription: Incorrect Permission Assignment for Critical Resource + security-severity: High + primary_identifier: find_sec_bugs.OVERLY_PERMISSIVE_FILE_PERMISSION + secondary_identifiers: + - name: Find Security Bugs-OVERLY_PERMISSIVE_FILE_PERMISSION + type: find_sec_bugs_type + value: OVERLY_PERMISSIVE_FILE_PERMISSION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.OVERLY_PERMISSIVE_FILE_PERMISSION-1 + shortlink: https://sg.run/BA4W + semgrep.dev: + rule: + r_id: 67995 + rv_id: 920267 + rule_id: 9AU7Ol + version_id: YDTYbED + url: https://semgrep.dev/playground/r/YDTYbED/gitlab.find_sec_bugs_scala.OVERLY_PERMISSIVE_FILE_PERMISSION-1 + origin: community + subcategory: + - audit + 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,}" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.OVERLY_PERMISSIVE_FILE_PERMISSION-2 + languages: + - scala + message: 'Overly permissive file permission + + ' + metadata: + category: security + confidence: HIGH + cwe: CWE-732 + shortDescription: Incorrect Permission Assignment for Critical Resource + security-severity: Medium + primary_identifier: find_sec_bugs.OVERLY_PERMISSIVE_FILE_PERMISSION-2 + secondary_identifiers: + - name: Find Security Bugs-OVERLY_PERMISSIVE_FILE_PERMISSION + type: find_sec_bugs_type + value: OVERLY_PERMISSIVE_FILE_PERMISSION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.OVERLY_PERMISSIVE_FILE_PERMISSION-2 + shortlink: https://sg.run/DDJY + semgrep.dev: + rule: + r_id: 67996 + rv_id: 920268 + rule_id: yyUgvq + version_id: 6xTyX8E + url: https://semgrep.dev/playground/r/6xTyX8E/gitlab.find_sec_bugs_scala.OVERLY_PERMISSIVE_FILE_PERMISSION-2 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + ... + java.nio.file.Files.setPosixFilePermissions(..., $PERMS); + - pattern-either: + - pattern: "$PERMS.add($P);" + - pattern: "$A = $B + $P;" + - metavariable-regex: + metavariable: "$P" + regex: "(PosixFilePermission.){0,1}(OTHERS_)" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.PADDING_ORACLE-1 + languages: + - scala + message: | + This specific mode of CBC with PKCS5Padding is susceptible to padding oracle attacks. An + adversary could potentially decrypt the message if the system exposed the difference between + plaintext with invalid padding or valid padding. The distinction between valid and invalid + padding is usually revealed through distinct error messages being returned for each condition. + metadata: + category: security + cwe: CWE-696 + shortDescription: Incorrect Behavior Order + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.PADDING_ORACLE + secondary_identifiers: + - name: Find Security Bugs-PADDING_ORACLE + type: find_sec_bugs_type + value: PADDING_ORACLE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.PADDING_ORACLE-1 + shortlink: https://sg.run/K6l7 + semgrep.dev: + rule: + r_id: 67955 + rv_id: 920227 + rule_id: 8GUljB + version_id: pZTbD0N + url: https://semgrep.dev/playground/r/pZTbD0N/gitlab.find_sec_bugs_scala.PADDING_ORACLE-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: javax.crypto.Cipher.getInstance("...") + - pattern-regex: "(/CBC/PKCS5Padding)" + - pattern-not-regex: "^(RSA)/.*" + - pattern-not-regex: "^(ECIES)$" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.PATH_TRAVERSAL_IN-1.SCALA_PATH_TRAVERSAL_IN-1 + languages: + - scala + message: | + A file is opened to read its content. The filename comes from an input parameter. If an + unfiltered parameter is passed to this file API, files from an arbitrary filesystem location + could be read. This rule identifies potential path traversal vulnerabilities. In many cases, + the constructed file path cannot be controlled by the user. + metadata: + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + category: security + cwe: CWE-22 + shortDescription: Improper limitation of a pathname to a restricted directory + ('Path Traversal') + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.PATH_TRAVERSAL_IN-1.SCALA_PATH_TRAVERSAL_IN-1 + secondary_identifiers: + - name: Find Security Bugs-PATH_TRAVERSAL_IN + type: find_sec_bugs_type + value: PATH_TRAVERSAL_IN + - name: Find Security Bugs-SCALA_PATH_TRAVERSAL_IN + type: find_sec_bugs_type + value: SCALA_PATH_TRAVERSAL_IN + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.PATH_TRAVERSAL_IN-1.SCALA_PATH_TRAVERSAL_IN-1 + shortlink: https://sg.run/8Ony + semgrep.dev: + rule: + r_id: 67984 + rv_id: 920256 + rule_id: qNUwoj + version_id: 5PTNGov + url: https://semgrep.dev/playground/r/5PTNGov/gitlab.find_sec_bugs_scala.PATH_TRAVERSAL_IN-1.SCALA_PATH_TRAVERSAL_IN-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - patterns: + - pattern-inside: | + def $FUNC(...,$ARGS: Array[String], ...): $TYPE = { + ... + } + - pattern-inside: | + $VAR = $ARGS($IDX) + ... + - pattern-inside: | + def $FUNC(...,$VAR: String, ...): $TYPE = { + ... + } + - pattern-not-inside: | + ... + org.apache.commons.io.FilenameUtils.getName($VAR) + ... + - pattern-either: + - patterns: + - pattern-inside: | + $U = new java.net.URI($VAR) + ... + - pattern-either: + - pattern: new java.io.File($U) + - pattern: java.nio.file.Paths.get($U) + - pattern: new java.io.RandomAccessFile(..., $VAR,...) + - pattern: new java.io.FileReader(<...$VAR...>, ...) + - pattern: new javax.activation.FileDataSource(..., $VAR, ...) + - pattern: new java.io.FileInputStream(..., $VAR, ...) + - pattern: new java.io.File(<...$VAR...>, ...) + - pattern: java.nio.file.Paths.get(...,$VAR,...) + - pattern: java.io.File.createTempFile(...,$VAR, ...) + - pattern: java.io.File.createTempDirectory(...,$VAR,...) + - pattern: java.nio.file.Files.createTempFile(..., $VAR, ...) + - pattern: java.nio.file.Files.createTempDirectory(..., $VAR, ...) + - pattern: scala.io.Source.from(<...$VAR...>) + - pattern: scala.io.Source.fromFile(<...$VAR...>) + - pattern: scala.io.Source.fromString(<...$VAR...>) + severity: ERROR +- id: gitlab.find_sec_bugs_scala.PATH_TRAVERSAL_OUT-1 + languages: + - scala + message: | + A file is opened to write to its contents. The filename comes from an input parameter. If an + unfiltered parameter is passed to this file API, files at an arbitrary filesystem location + could be modified. This rule identifies potential path traversal vulnerabilities. In many + cases, the constructed file path cannot be controlled by the user. + metadata: + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + category: security + cwe: CWE-22 + shortDescription: Improper limitation of a pathname to a restricted directory + ('Path Traversal') + technology: + - scala + security-severity: High + primary_identifier: find_sec_bugs.PATH_TRAVERSAL_OUT + secondary_identifiers: + - name: Find Security Bugs-PATH_TRAVERSAL_OUT + type: find_sec_bugs_type + value: PATH_TRAVERSAL_OUT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.PATH_TRAVERSAL_OUT-1 + shortlink: https://sg.run/gDJJ + semgrep.dev: + rule: + r_id: 67985 + rv_id: 920257 + rule_id: lBUDdd + version_id: GxToXk2 + url: https://semgrep.dev/playground/r/GxToXk2/gitlab.find_sec_bugs_scala.PATH_TRAVERSAL_OUT-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - pattern: org.apache.commons.io.FilenameUtils.getName(...) + pattern-sinks: + - patterns: + - pattern-inside: new java.io.FileWriter($PATH, ...) + - pattern: "$PATH" + - patterns: + - pattern-inside: new java.io.FileOutputStream($PATH, ...) + - pattern: "$PATH" + pattern-sources: + - patterns: + - pattern-inside: | + def $FUNC(..., $ARGS: Array[String], ...): $TYPE = { + ... + } + - pattern: "$ARGS[$IDX]" + - patterns: + - pattern-inside: | + def $FUNC(..., $VAR: String, ...): $TYPE = { + ... + } + - pattern: "$VAR" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.PERMISSIVE_CORS-1 + languages: + - scala + message: | + Prior to HTML5, Web browsers enforced the Same Origin Policy which ensures that in order for + JavaScript to access the contents of a Web page, both the JavaScript and the Web page must + originate from the same domain. Without the Same Origin Policy, a malicious website could serve + up JavaScript that loads sensitive information from other websites using a client's + credentials, cull through it, and communicate it back to the attacker. HTML5 makes it possible + for JavaScript to access data across domains if a new HTTP header called + Access-Control-Allow-Origin is defined. With this header, a Web server defines which other + domains are allowed to access its domain using cross-origin requests. However, caution should + be taken when defining the header because an overly permissive CORS policy will allow a + malicious application to communicate with the victim application in an inappropriate way, + leading to spoofing, data theft, relay and other attacks. + metadata: + category: security + cwe: CWE-942 + shortDescription: Permissive Cross-domain Policy with Untrusted Domains + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.PERMISSIVE_CORS + secondary_identifiers: + - name: Find Security Bugs-PERMISSIVE_CORS + type: find_sec_bugs_type + value: PERMISSIVE_CORS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.PERMISSIVE_CORS-1 + shortlink: https://sg.run/GKep + semgrep.dev: + rule: + r_id: 67948 + rv_id: 920220 + rule_id: v8UQnN + version_id: K3TwLKb + url: https://semgrep.dev/playground/r/K3TwLKb/gitlab.find_sec_bugs_scala.PERMISSIVE_CORS-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern-either: + - pattern: ($RESP:javax.servlet.http.HttpServletResponse).setHeader("$HEADER", + "$VAL") + - pattern: ($RESP:javax.servlet.http.HttpServletResponse).addHeader("$HEADER", + "$VAL") + - metavariable-regex: + metavariable: "$HEADER" + regex: "(?i)(Access-Control-Allow-Origin)" + - metavariable-regex: + metavariable: "$VAL" + regex: "(\\*|null)" + - patterns: + - pattern-inside: | + $REQVAL = ($REQ: javax.servlet.http.HttpServletRequest).getParameter(...) + ... + - pattern-either: + - pattern-inside: ($RESP:javax.servlet.http.HttpServletResponse).setHeader("$HEADER", + $REQVAL) + - pattern-inside: ($RESP:javax.servlet.http.HttpServletResponse).addHeader("$HEADER", + $REQVAL) + - patterns: + - pattern-either: + - pattern-inside: '($RESP:javax.servlet.http.HttpServletResponse).setHeader("$HEADER",($REQ: + javax.servlet.http.HttpServletRequest).getParameter(...))' + - pattern-inside: '($RESP:javax.servlet.http.HttpServletResponse).addHeader("$HEADER",($REQ: + javax.servlet.http.HttpServletRequest).getParameter(...))' + severity: ERROR +- id: gitlab.find_sec_bugs_scala.PERMISSIVE_CORS-2 + languages: + - java + message: | + Prior to HTML5, Web browsers enforced the Same Origin Policy which ensures that in order for + JavaScript to access the contents of a Web page, both the JavaScript and the Web page must + originate from the same domain. Without the Same Origin Policy, a malicious website could serve + up JavaScript that loads sensitive information from other websites using a client's + credentials, cull through it, and communicate it back to the attacker. HTML5 makes it possible + for JavaScript to access data across domains if a new HTTP header called + Access-Control-Allow-Origin is defined. With this header, a Web server defines which other + domains are allowed to access its domain using cross-origin requests. However, caution should + be taken when defining the header because an overly permissive CORS policy will allow a + malicious application to communicate with the victim application in an inappropriate way, + leading to spoofing, data theft, relay and other attacks. + metadata: + category: security + cwe: CWE-942 + shortDescription: Permissive Cross-domain Policy with Untrusted Domains + technology: + - java + security-severity: Low + primary_identifier: find_sec_bugs.PERMISSIVE_CORS-2 + secondary_identifiers: + - name: Find Security Bugs-PERMISSIVE_CORS + type: find_sec_bugs_type + value: PERMISSIVE_CORS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.PERMISSIVE_CORS-2 + shortlink: https://sg.run/R1oO + semgrep.dev: + rule: + r_id: 67949 + rv_id: 920221 + rule_id: d8Ugjv + version_id: qkTpwRo + url: https://semgrep.dev/playground/r/qkTpwRo/gitlab.find_sec_bugs_scala.PERMISSIVE_CORS-2 + origin: community + subcategory: + - audit + mode: taint + 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)" + pattern-sources: + - pattern: "(HttpServletRequest $REQ).getParameter(...)" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.PREDICTABLE_RANDOM-1.PREDICTABLE_RANDOM_SCALA-1 + languages: + - scala + message: | + The use of a predictable random value can lead to vulnerabilities when used in certain security + critical contexts. A quick fix could be to replace the use of scala.util.Random with something + stronger, such as java.security.SecureRandom + metadata: + category: security + cwe: CWE-330 + shortDescription: Use of Insufficiently Random Values + technology: + - scala + primary_identifier: find_sec_bugs.PREDICTABLE_RANDOM-1.PREDICTABLE_RANDOM_SCALA-1 + secondary_identifiers: + - name: Find Security Bugs-PREDICTABLE_RANDOM + type: find_sec_bugs_type + value: PREDICTABLE_RANDOM + - name: Find Security Bugs-PREDICTABLE_RANDOM_SCALA + type: find_sec_bugs_type + value: PREDICTABLE_RANDOM_SCALA + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.PREDICTABLE_RANDOM-1.PREDICTABLE_RANDOM_SCALA-1 + shortlink: https://sg.run/WNg4 + semgrep.dev: + rule: + r_id: 67997 + rv_id: 835611 + rule_id: r6Uvkl + version_id: 8KTGlJz + url: https://semgrep.dev/playground/r/8KTGlJz/gitlab.find_sec_bugs_scala.PREDICTABLE_RANDOM-1.PREDICTABLE_RANDOM_SCALA-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern: "$LANG.util.Random.$METHOD" + - metavariable-regex: + metavariable: "$METHOD" + regex: "^(next)" + - pattern: Math.random + severity: WARNING +- id: gitlab.find_sec_bugs_scala.PT_ABSOLUTE_PATH_TRAVERSAL-1 + languages: + - scala + message: | + "The software uses an HTTP request parameter to construct a pathname that should be within a + restricted directory, but it does not properly neutralize absolute path sequences such as + "/abs/path" that can resolve to a location that is outside of that directory. See + http://cwe.mitre.org/data/definitions/36.html for more information." + metadata: + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + category: security + cwe: CWE-22 + shortDescription: Improper limitation of a pathname to a restricted directory + ('Path Traversal') + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.PT_ABSOLUTE_PATH_TRAVERSAL + secondary_identifiers: + - name: Find Security Bugs-PT_ABSOLUTE_PATH_TRAVERSAL + type: find_sec_bugs_type + value: PT_ABSOLUTE_PATH_TRAVERSAL + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.PT_ABSOLUTE_PATH_TRAVERSAL-1 + shortlink: https://sg.run/Qj84 + semgrep.dev: + rule: + r_id: 67986 + rv_id: 920258 + rule_id: YGUbrQ + version_id: RGT2x0v + url: https://semgrep.dev/playground/r/RGT2x0v/gitlab.find_sec_bugs_scala.PT_ABSOLUTE_PATH_TRAVERSAL-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - pattern: org.apache.commons.io.FilenameUtils.getName(...) + pattern-sinks: + - patterns: + - pattern-inside: "$U = new java.net.URI($VAR)\n" + - 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.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-inside: new java.io.FileWriter($PATH, ...) + - pattern: "$PATH" + - patterns: + - pattern-inside: new java.io.FileOutputStream($PATH, ...) + - pattern: "$PATH" + pattern-sources: + - pattern: "($REQ: HttpServletRequest ).getParameter(...)" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.PT_RELATIVE_PATH_TRAVERSAL-1 + languages: + - scala + message: | + "The software uses an HTTP request parameter to construct a pathname that should be within a + restricted directory, but it does not properly neutralize sequences such as ".." that can + resolve to a location that is outside of that directory. See + http://cwe.mitre.org/data/definitions/23.html for more information." + metadata: + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + category: security + cwe: CWE-22 + shortDescription: Improper limitation of a pathname to a restricted directory + ('Path Traversal') + technology: + - scala + security-severity: Info + primary_identifier: find_sec_bugs.PT_RELATIVE_PATH_TRAVERSAL + secondary_identifiers: + - name: Find Security Bugs-PT_RELATIVE_PATH_TRAVERSAL + type: find_sec_bugs_type + value: PT_RELATIVE_PATH_TRAVERSAL + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.PT_RELATIVE_PATH_TRAVERSAL-1 + shortlink: https://sg.run/3bAr + semgrep.dev: + rule: + r_id: 67987 + rv_id: 920259 + rule_id: 6JUXq1 + version_id: A8TNlgb + url: https://semgrep.dev/playground/r/A8TNlgb/gitlab.find_sec_bugs_scala.PT_RELATIVE_PATH_TRAVERSAL-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - pattern: org.apache.commons.io.FilenameUtils.getName(...) + pattern-sinks: + - patterns: + - pattern-inside: "$U = new java.net.URI($VAR)\n" + - 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.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-inside: new java.io.FileWriter($PATH, ...) + - pattern: "$PATH" + - patterns: + - pattern-inside: new java.io.FileOutputStream($PATH, ...) + - pattern: "$PATH" + pattern-sources: + - patterns: + - pattern-inside: | + $P = ($REQ: HttpServletRequest ).getParameter(...); + ... + - pattern-either: + - pattern: "$P + ..." + - pattern: "... + $P" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.REQUESTDISPATCHER_FILE_DISCLOSURE-1.STRUTS_FILE_DISCLOSURE-1.SPRING_FILE_DISCLOSURE-1 + languages: + - scala + message: | + Constructing a server-side redirect path with user input could allow an + attacker to download application binaries (including application classes or + jar files) or view arbitrary files within protected directories. + metadata: + category: security + cwe: CWE-552 + shortDescription: Files or Directories Accessible to External Parties + security-severity: Info + primary_identifier: find_sec_bugs.REQUESTDISPATCHER_FILE_DISCLOSURE-1.STRUTS_FILE_DISCLOSURE-1.SPRING_FILE_DISCLOSURE-1 + secondary_identifiers: + - name: Find Security Bugs-REQUESTDISPATCHER_FILE_DISCLOSURE + type: find_sec_bugs_type + value: REQUESTDISPATCHER_FILE_DISCLOSURE + - name: Find Security Bugs-STRUTS_FILE_DISCLOSURE + type: find_sec_bugs_type + value: STRUTS_FILE_DISCLOSURE + - name: Find Security Bugs-SPRING_FILE_DISCLOSURE + type: find_sec_bugs_type + value: SPRING_FILE_DISCLOSURE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.REQUESTDISPATCHER_FILE_DISCLOSURE-1.STRUTS_FILE_DISCLOSURE-1.SPRING_FILE_DISCLOSURE-1 + shortlink: https://sg.run/n6qX + semgrep.dev: + rule: + r_id: 67980 + rv_id: 920252 + rule_id: DbUyWd + version_id: 3ZTLw4X + url: https://semgrep.dev/playground/r/3ZTLw4X/gitlab.find_sec_bugs_scala.REQUESTDISPATCHER_FILE_DISCLOSURE-1.STRUTS_FILE_DISCLOSURE-1.SPRING_FILE_DISCLOSURE-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sinks: + - patterns: + - pattern: new org.springframework.web.servlet.ModelAndView($FST) + - pattern: "$FST" + - patterns: + - pattern: new org.springframework.web.servlet.ModelAndView($FST, $SND) + - pattern: "$FST" + - patterns: + - pattern: new org.springframework.web.servlet.ModelAndView($FST, $SND, $TRD) + - pattern: "$FST" + - patterns: + - pattern: new org.apache.struts.action.ActionForward($FST) + - pattern: "$FST" + - patterns: + - pattern: new org.apache.struts.action.ActionForward($FST, $SND) + - pattern: "$FST" + - patterns: + - pattern: new org.apache.struts.action.ActionForward($FST, $SND, $TRD) + - pattern: "$SND" + - patterns: + - pattern: new org.apache.struts.action.ActionForward($FST, $SND, $TRD) + - pattern: "$TRD" + - patterns: + - pattern-inside: | + $ACTION = new org.apache.struts.action.ActionForward() + ... + - pattern: "$ACTION.setPath(...)" + - patterns: + - pattern-inside: | + $MVC = new org.springframework.web.servlet.ModelAndView() + ... + - pattern: "$MVC.setViewName(...);" + - patterns: + - pattern-inside: | + $REQ = $HTTP.getRequestDispatcher(...) + ... + - pattern-either: + - pattern: "$REQ.include($FST, $SND)" + - pattern: "$REQ.forward($FST, $SND)" + pattern-sources: + - pattern: "($VAR: javax.servlet.http.HttpServletRequest).getParameter(...)" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.RPC_ENABLED_EXTENSIONS-1 + languages: + - scala + message: | + Enabling extensions in Apache XML RPC server or client can lead to deserialization + vulnerability which would allow an attacker to execute arbitrary code. + metadata: + category: security + cwe: CWE-502 + shortDescription: Deserialization of Untrusted Data + security-severity: Info + primary_identifier: find_sec_bugs.RPC_ENABLED_EXTENSIONS + secondary_identifiers: + - name: Find Security Bugs-RPC_ENABLED_EXTENSIONS + type: find_sec_bugs_type + value: RPC_ENABLED_EXTENSIONS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.RPC_ENABLED_EXTENSIONS-1 + shortlink: https://sg.run/lljL + semgrep.dev: + rule: + r_id: 68013 + rv_id: 920284 + rule_id: gxUXWQ + version_id: O9Tv78L + url: https://semgrep.dev/playground/r/O9Tv78L/gitlab.find_sec_bugs_scala.RPC_ENABLED_EXTENSIONS-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - patterns: + - pattern-inside: | + val $VAR = new XmlRpcServerConfigImpl(); + ... + - pattern: "$VAR.setEnabledForExtensions(true);" + - patterns: + - pattern-inside: | + val $VAR = new org.apache.xmlrpc.client.XmlRpcClientConfigImpl(); + ... + - pattern: "$VAR.setEnabledForExtensions(true);" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.RSA_KEY_SIZE-1 + languages: + - scala + message: | + Detected an insufficient key size for DSA. NIST recommends a key size + of 2048 or higher. + metadata: + category: security + cwe: CWE-326 + shortDescription: Inadequate Encryption Strength + security-severity: Medium + primary_identifier: find_sec_bugs.RSA_KEY_SIZE + secondary_identifiers: + - name: Find Security Bugs-RSA_KEY_SIZE + type: find_sec_bugs_type + value: RSA_KEY_SIZE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.RSA_KEY_SIZE-1 + shortlink: https://sg.run/6wno + semgrep.dev: + rule: + r_id: 67959 + rv_id: 920231 + rule_id: 4bUqkK + version_id: 1QT4Ny2 + url: https://semgrep.dev/playground/r/1QT4Ny2/gitlab.find_sec_bugs_scala.RSA_KEY_SIZE-1 + origin: community + subcategory: + - audit + 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)"' + severity: WARNING +- id: gitlab.find_sec_bugs_scala.RSA_NO_PADDING-1 + languages: + - scala + message: | + The software uses the RSA algorithm but does not incorporate Optimal Asymmetric + Encryption Padding (OAEP), which might weaken the encryption. + metadata: + cwe: CWE-780 + shortDescription: Use of RSA Algorithm without OAEP + security-severity: Medium + category: security + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + primary_identifier: find_sec_bugs.RSA_NO_PADDING + secondary_identifiers: + - name: Find Security Bugs-RSA_NO_PADDING + type: find_sec_bugs_type + value: RSA_NO_PADDING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.RSA_NO_PADDING-1 + shortlink: https://sg.run/zNvG + semgrep.dev: + rule: + r_id: 67961 + rv_id: 920233 + rule_id: JDURyA + version_id: yeTDgxG + url: https://semgrep.dev/playground/r/yeTDgxG/gitlab.find_sec_bugs_scala.RSA_NO_PADDING-1 + origin: community + subcategory: + - audit + patterns: + - pattern: javax.crypto.Cipher.getInstance("$ALG",...) + - metavariable-regex: + metavariable: "$ALG" + regex: ".*NoPadding.*" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.SAML_IGNORE_COMMENTS-1 + languages: + - scala + message: 'Ignoring XML comments in SAML may lead to authentication bypass + + ' + metadata: + category: security + cwe: CWE-287 + shortDescription: Improper Authentication + security-severity: Medium + primary_identifier: find_sec_bugs.SAML_IGNORE_COMMENTS + secondary_identifiers: + - name: Find Security Bugs-SAML_IGNORE_COMMENTS + type: find_sec_bugs_type + value: SAML_IGNORE_COMMENTS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.SAML_IGNORE_COMMENTS-1 + shortlink: https://sg.run/YwgW + semgrep.dev: + rule: + r_id: 68014 + rv_id: 920285 + rule_id: QrUN6r + version_id: e1TZKeX + url: https://semgrep.dev/playground/r/e1TZKeX/gitlab.find_sec_bugs_scala.SAML_IGNORE_COMMENTS-1 + origin: community + subcategory: + - audit + pattern: "($POOL: BasicParserPool).setIgnoreComments(false);" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.SCALA_PLAY_SSRF-1 + languages: + - scala + message: | + Server-Side Request Forgery occur when a web server executes a request to a user supplied + destination parameter that is not validated. Such vulnerabilities could allow an attacker to + access internal services or to launch attacks from your web server. + metadata: + category: security + cwe: CWE-918 + shortDescription: Server-Side Request Forgery (SSRF) + security-severity: Medium + primary_identifier: find_sec_bugs.SCALA_PLAY_SSRF + secondary_identifiers: + - name: Find Security Bugs-SCALA_PLAY_SSRF + type: find_sec_bugs_type + value: SCALA_PLAY_SSRF + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.SCALA_PLAY_SSRF-1 + shortlink: https://sg.run/JY3o + semgrep.dev: + rule: + r_id: 68002 + rv_id: 920273 + rule_id: x8UrW1 + version_id: X0TAK42 + url: https://semgrep.dev/playground/r/X0TAK42/gitlab.find_sec_bugs_scala.SCALA_PLAY_SSRF-1 + origin: community + subcategory: + - audit + patterns: + - pattern-not-inside: | + object $CLAZZ { + ... + $ARG = ... + ... + } + - pattern-not-inside: | + class $CLAZZ { + ... + $ARG = ... + ... + } + - pattern-either: + - patterns: + - pattern-inside: | + import play.api.libs.ws._ + ... + - pattern-not: ($W:WSClient).url("...") + - pattern-not: ($W:WSClient).url("..." + "...") + - pattern: "($W:WSClient).url(<...$ARG...>)" + - patterns: + - pattern: "($W:play.api.libs.ws.WSClient).url(<...$ARG...>)" + - pattern-not: ($W:play.api.libs.ws.WSClient).url("...") + - pattern-not: ($W:play.api.libs.ws.WSClient).url("..." + "...") + severity: ERROR +- id: gitlab.find_sec_bugs_scala.SCALA_SENSITIVE_DATA_EXPOSURE-1 + languages: + - scala + message: | + Applications can unintentionally leak information about their configuration, internal + workings, or violate privacy through a variety of application problems. Pages that provide + different responses based on the validity of the data can lead to Information Leakage; + specifically when data deemed confidential is being revealed as a result of the web + application's design. + metadata: + category: security + cwe: CWE-200 + shortDescription: Information Exposure + technology: + - scala + - play + security-severity: Info + primary_identifier: find_sec_bugs.SCALA_SENSITIVE_DATA_EXPOSURE + secondary_identifiers: + - name: Find Security Bugs-SCALA_SENSITIVE_DATA_EXPOSURE + type: find_sec_bugs_type + value: SCALA_SENSITIVE_DATA_EXPOSURE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.SCALA_SENSITIVE_DATA_EXPOSURE-1 + shortlink: https://sg.run/qpr1 + semgrep.dev: + rule: + r_id: 68012 + rv_id: 920283 + rule_id: 8GUlEw + version_id: xyTdr8l + url: https://semgrep.dev/playground/r/xyTdr8l/gitlab.find_sec_bugs_scala.SCALA_SENSITIVE_DATA_EXPOSURE-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + def $FUNC(..., $ARG: String, ...) = $TYPE { + ... + } + - pattern-inside: | + $VAL = ($C: play.api.Configuration).underlying.getString($ARG) + ... + - pattern: Ok(<...$VAL...>) + severity: WARNING +- id: gitlab.find_sec_bugs_scala.SCALA_XSS_MVC_API-1 + languages: + - scala + message: 'Disabling HTML escaping put the application at risk for Cross-Site Scripting + (XSS). + + ' + metadata: + category: security + cwe: CWE-79 + shortDescription: Improper Neutralization of Input During Web Page Generation + ('Cross-site Scripting') + security-severity: Info + primary_identifier: find_sec_bugs.SCALA_XSS_MVC_API + secondary_identifiers: + - name: Find Security Bugs-SCALA_XSS_MVC_API + type: find_sec_bugs_type + value: SCALA_XSS_MVC_API + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.SCALA_XSS_MVC_API-1 + shortlink: https://sg.run/pzl3 + semgrep.dev: + rule: + r_id: 68018 + rv_id: 920289 + rule_id: JDURPW + version_id: nWTnN9j + url: https://semgrep.dev/playground/r/nWTnN9j/gitlab.find_sec_bugs_scala.SCALA_XSS_MVC_API-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - pattern: org.owasp.encoder.Encode.forHtml(...) + pattern-sinks: + - pattern: Ok(...) + pattern-sources: + - patterns: + - pattern-inside: | + def $FUNC(..., $ARG: String, ...) = Action { + ... + } + - focus-metavariable: "$ARG" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.SCRIPT_ENGINE_INJECTION-1.SPEL_INJECTION-1.EL_INJECTION-2.SEAM_LOG_INJECTION-1 + languages: + - scala + message: | + The software constructs all or part of a code segment using externally-influenced + input from an upstream component, but it does not neutralize or incorrectly + neutralizes special elements that could modify the syntax or behavior of the + intended code segment. + metadata: + cwe: CWE-94 + shortDescription: Improper Control of Generation of Code ('Code Injection') + security-severity: Info + category: security + owasp: + - A1:2017-Injection + - A03:2021-Injection + primary_identifier: find_sec_bugs.SCRIPT_ENGINE_INJECTION-1.SPEL_INJECTION-1.EL_INJECTION-2.SEAM_LOG_INJECTION-1 + secondary_identifiers: + - name: Find Security Bugs-SCRIPT_ENGINE_INJECTION + type: find_sec_bugs_type + value: SCRIPT_ENGINE_INJECTION + - name: Find Security Bugs-SPEL_INJECTION + type: find_sec_bugs_type + value: SPEL_INJECTION + - name: Find Security Bugs-EL_INJECTION + type: find_sec_bugs_type + value: EL_INJECTION + - name: Find Security Bugs-SEAM_LOG_INJECTION + type: find_sec_bugs_type + value: SEAM_LOG_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.SCRIPT_ENGINE_INJECTION-1.SPEL_INJECTION-1.EL_INJECTION-2.SEAM_LOG_INJECTION-1 + shortlink: https://sg.run/09nv + semgrep.dev: + rule: + r_id: 67998 + rv_id: 920269 + rule_id: bwUoOl + version_id: o5TK1dB + url: https://semgrep.dev/playground/r/o5TK1dB/gitlab.find_sec_bugs_scala.SCRIPT_ENGINE_INJECTION-1.SPEL_INJECTION-1.EL_INJECTION-2.SEAM_LOG_INJECTION-1 + origin: community + subcategory: + - audit + patterns: + - pattern: "($ENGINE: javax.script.ScriptEngine).eval($ARG)" + - pattern-not: '($ENGINE: javax.script.ScriptEngine).eval("...")' + severity: ERROR +- id: gitlab.find_sec_bugs_scala.SCRIPT_ENGINE_INJECTION-2 + languages: + - scala + message: | + The software constructs all or part of a code segment using externally-influenced + input from an upstream component, but it does not neutralize or incorrectly + neutralizes special elements that could modify the syntax or behavior of the + intended code segment. + metadata: + cwe: CWE-94 + shortDescription: Improper Control of Generation of Code ('Code Injection') + security-severity: Medium + category: security + owasp: + - A1:2017-Injection + - A03:2021-Injection + primary_identifier: find_sec_bugs.SCRIPT_ENGINE_INJECTION-2 + secondary_identifiers: + - name: Find Security Bugs-SCRIPT_ENGINE_INJECTION + type: find_sec_bugs_type + value: SCRIPT_ENGINE_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.SCRIPT_ENGINE_INJECTION-2 + shortlink: https://sg.run/K6W7 + semgrep.dev: + rule: + r_id: 67999 + rv_id: 920270 + rule_id: NbURAr + version_id: zyTG3LG + url: https://semgrep.dev/playground/r/zyTG3LG/gitlab.find_sec_bugs_scala.SCRIPT_ENGINE_INJECTION-2 + origin: community + subcategory: + - audit + patterns: + - pattern: "($P: org.springframework.expression.spel.standard.SpelExpressionParser).parseExpression($ARG);" + - pattern-not: '($P: org.springframework.expression.spel.standard.SpelExpressionParser + ).parseExpression("...");' + severity: ERROR +- id: gitlab.find_sec_bugs_scala.SERVLET_PARAMETER-1.SERVLET_CONTENT_TYPE-1.SERVLET_SERVER_NAME-1.SERVLET_SESSION_ID-1.SERVLET_QUERY_STRING-1.SERVLET_HEADER-1.SERVLET_HEADER_REFERER-1.SERVLET_HEADER_USER_AGENT-1 + languages: + - scala + message: | + The Servlet can read GET and POST parameters from various methods. The + value obtained should be considered unsafe." + metadata: + category: security + cwe: CWE-20 + shortDescription: Improper Input Validation + security-severity: Medium + primary_identifier: find_sec_bugs.SERVLET_PARAMETER-1.SERVLET_CONTENT_TYPE-1.SERVLET_SERVER_NAME-1.SERVLET_SESSION_ID-1.SERVLET_QUERY_STRING-1.SERVLET_HEADER-1.SERVLET_HEADER_REFERER-1.SERVLET_HEADER_USER_AGENT-1 + secondary_identifiers: + - name: Find Security Bugs-SERVLET_PARAMETER + type: find_sec_bugs_type + value: SERVLET_PARAMETER + - name: Find Security Bugs-SERVLET_CONTENT_TYPE + type: find_sec_bugs_type + value: SERVLET_CONTENT_TYPE + - name: Find Security Bugs-SERVLET_SERVER_NAME + type: find_sec_bugs_type + value: SERVLET_SERVER_NAME + - name: Find Security Bugs-SERVLET_SESSION_ID + type: find_sec_bugs_type + value: SERVLET_SESSION_ID + - name: Find Security Bugs-SERVLET_QUERY_STRING + type: find_sec_bugs_type + value: SERVLET_QUERY_STRING + - name: Find Security Bugs-SERVLET_HEADER + type: find_sec_bugs_type + value: SERVLET_HEADER + - name: Find Security Bugs-SERVLET_HEADER_REFERER + type: find_sec_bugs_type + value: SERVLET_HEADER_REFERER + - name: Find Security Bugs-SERVLET_HEADER_USER_AGENT + type: find_sec_bugs_type + value: SERVLET_HEADER_USER_AGENT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.SERVLET_PARAMETER-1.SERVLET_CONTENT_TYPE-1.SERVLET_SERVER_NAME-1.SERVLET_SESSION_ID-1.SERVLET_QUERY_STRING-1.SERVLET_HEADER-1.SERVLET_HEADER_REFERER-1.SERVLET_HEADER_USER_AGENT-1 + shortlink: https://sg.run/XkBK + semgrep.dev: + rule: + r_id: 67964 + rv_id: 920236 + rule_id: ReUxg8 + version_id: NdTeRzQ + url: https://semgrep.dev/playground/r/NdTeRzQ/gitlab.find_sec_bugs_scala.SERVLET_PARAMETER-1.SERVLET_CONTENT_TYPE-1.SERVLET_SERVER_NAME-1.SERVLET_SESSION_ID-1.SERVLET_QUERY_STRING-1.SERVLET_HEADER-1.SERVLET_HEADER_REFERER-1.SERVLET_HEADER_USER_AGENT-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - pattern: Encode.forHtml(...) + - pattern: org.owasp.esapi.Encoder.encodeForSQL(...) + pattern-sinks: + - patterns: + - pattern-either: + - pattern: "... + $PAR\n" + - pattern: "... + $PAR + ...\n" + - pattern: "$PAR + ...\n" + - pattern: "$PAR" + pattern-sources: + - pattern-either: + - pattern: "($REQ: HttpServletRequest).getContentType" + - pattern: "($REQ: HttpServletRequest).getServerName" + - pattern: "($REQ: HttpServletRequest).getRequestedSessionId" + - pattern: "($REQ: HttpServletRequest).getParameterValues(...)" + - pattern: "($REQ: HttpServletRequest).getParameterMap" + - pattern: "($REQ: HttpServletRequest).getParameterNames" + - pattern: "($REQ: HttpServletRequest).getParameter(...)" + - patterns: + - pattern-inside: "($REQ: HttpServletRequest).getSession\n" + - pattern: $SESS.getAttribute("...") + - pattern: '($REQ: HttpServletRequest).getSession.getAttribute("...") + + ' + severity: WARNING +- id: gitlab.find_sec_bugs_scala.SMTP_HEADER_INJECTION-1 + languages: + - scala + message: | + Simple Mail Transfer Protocol (SMTP) is a the text based protocol used for + email delivery. Like with HTTP, headers are separate by new line separator. If + kuser input is place in a header line, the application should remove or replace + new line characters (CR / LF). You should use a safe wrapper such as Apache + Common Email and Simple Java Mail which filter special characters that can lead + to header injection. + metadata: + category: security + cwe: CWE-77 + shortDescription: Improper Neutralization of Special Elements used in a Command + security-severity: High + primary_identifier: find_sec_bugs.SMTP_HEADER_INJECTION + secondary_identifiers: + - name: Find Security Bugs-SMTP_HEADER_INJECTION + type: find_sec_bugs_type + value: SMTP_HEADER_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.SMTP_HEADER_INJECTION-1 + shortlink: https://sg.run/PXpN + semgrep.dev: + rule: + r_id: 68001 + rv_id: 920272 + rule_id: wdUb84 + version_id: 2KTdOpr + url: https://semgrep.dev/playground/r/2KTdOpr/gitlab.find_sec_bugs_scala.SMTP_HEADER_INJECTION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - patterns: + - pattern-inside: | + $M = new MimeMessage(...); + ... + - pattern: "$M.setSubject($ARG);" + - pattern-not: $M.setSubject("...") + - patterns: + - pattern-inside: | + $M = new MimeMessage(...); + ... + - pattern: "$M.addHeader($ARG1, $ARG2)" + - pattern-not: $M.addHeader("...", "...") + - patterns: + - pattern-inside: | + $M = new MimeMessage(...); + ... + - pattern: "$M.setDescription($ARG)" + - pattern-not: $M.setDescription("...") + - patterns: + - pattern-inside: | + $M = new MimeMessage(...); + ... + - pattern: "$M.setDisposition($ARG)" + - pattern-not: $M.setDisposition("...") + severity: ERROR +- id: gitlab.find_sec_bugs_scala.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1.SCALA_SQL_INJECTION_SLICK-1 + languages: + - scala + message: | + The input values included in SQL queries need to be passed in safely. Bind + variables in prepared statements can be used to easily mitigate the risk of + SQL injection. + metadata: + category: security + cwe: CWE-89 + owasp: + - A1:2017-Injection + - A03:2021-Injection + shortDescription: Improper Neutralization of Special Elements used in an SQL Command + ('SQL Injection') + security-severity: Medium + primary_identifier: find_sec_bugs.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1.SCALA_SQL_INJECTION_SLICK-1 + secondary_identifiers: + - name: Find Security Bugs-SQL_INJECTION_SPRING_JDBC + type: find_sec_bugs_type + value: SQL_INJECTION_SPRING_JDBC + - name: Find Security Bugs-SQL_INJECTION_JPA + type: find_sec_bugs_type + value: SQL_INJECTION_JPA + - name: Find Security Bugs-SQL_INJECTION_JDO + type: find_sec_bugs_type + value: SQL_INJECTION_JDO + - name: Find Security Bugs-SQL_INJECTION_JDBC + type: find_sec_bugs_type + value: SQL_INJECTION_JDBC + - name: Find Security Bugs-SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE + type: find_sec_bugs_type + value: SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE + - name: Find Security Bugs-SCALA_SQL_INJECTION_SLICK + type: find_sec_bugs_type + value: SCALA_SQL_INJECTION_SLICK + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1.SCALA_SQL_INJECTION_SLICK-1 + shortlink: https://sg.run/4Nyl + semgrep.dev: + rule: + r_id: 67988 + rv_id: 920260 + rule_id: oqU1z2 + version_id: BjTKLbW + url: https://semgrep.dev/playground/r/BjTKLbW/gitlab.find_sec_bugs_scala.SQL_INJECTION_SPRING_JDBC-1.SQL_INJECTION_JPA-1.SQL_INJECTION_JDO-1.SQL_INJECTION_JDBC-1.SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE-1.SCALA_SQL_INJECTION_SLICK-1 + origin: community + subcategory: + - audit + patterns: + - pattern-not-inside: | + $ARG = ... + ... + - pattern-not-inside: | + object $CLAZZ { + ... + $ARG = ... + ... + } + - pattern-not-inside: | + class $CLAZZ { + ... + $ARG = ... + ... + } + - pattern-either: + - patterns: + - pattern: "($PM:javax.jdo.PersistenceManager).newQuery(<...$ARG...>)" + - pattern-not: ($PM:javax.jdo.PersistenceManager).newQuery("...") + - patterns: + - pattern: "($PM:javax.jdo.PersistenceManager).newQuery(..., <...$ARG...>)" + - pattern-not: ($PM:javax.jdo.PersistenceManager).newQuery(..., "...") + - patterns: + - pattern: "($Q: javax.jdo.Query).setFilter(<...$ARG...>)" + - pattern-not: '($Q: javax.jdo.Query).setFilter("...")' + - patterns: + - pattern: "($Q: javax.jdo.Query).setGrouping(<...$ARG...>)" + - pattern-not: '($Q: javax.jdo.Query).setGrouping("...")' + - patterns: + - pattern: "($Q: javax.jdo.Query).setGrouping(<...$ARG...>)" + - pattern-not: '($Q: javax.jdo.Query).setGrouping("...")' + - patterns: + - pattern: "($H: org.hibernate.criterion.Restrictions).sqlRestriction(<...$ARG...>, + ...)" + - pattern-not: '($H: org.hibernate.criterion.Restrictions).sqlRestriction("...", + ...)' + - patterns: + - pattern: "($S: org.hibernate.Session).createQuery(<...$ARG...>, ...)" + - pattern-not: '($S: org.hibernate.Session).createQuery("...", ...)' + - patterns: + - pattern: "($S: org.hibernate.Session).createSQLQuery(<...$ARG...>, ...)" + - pattern-not: '($S: org.hibernate.Session).createSQLQuery("...", ...)' + - patterns: + - pattern: "($S: java.sql.Statement).executeQuery(<...$ARG...>, ...)" + - pattern-not: '($S: java.sql.Statement).createSQLQuery("...", ...)' + - patterns: + - pattern: "($S: java.sql.Statement).execute(<...$ARG...>, ...)" + - pattern-not: '($S: java.sql.Statement).execute("...", ...)' + - patterns: + - pattern: "($S: java.sql.Statement).executeUpdate(<...$ARG...>, ...)" + - pattern-not: '($S: java.sql.Statement).executeUpdate("...", ...)' + - patterns: + - pattern: "($S: java.sql.Statement).executeLargeUpdate(<...$ARG...>, ...)" + - pattern-not: '($S: java.sql.Statement).executeLargeUpdate("...", ...)' + - patterns: + - pattern: "($S: java.sql.Statement).addBatch(<...$ARG...>, ...)" + - pattern-not: '($S: java.sql.Statement).addBatch("...", ...)' + - patterns: + - pattern: "($S: java.sql.PreparedStatement).executeQuery(<...$ARG...>, ...)" + - pattern-not: '($S: java.sql.PreparedStatement).executeQuery("...", ...)' + - patterns: + - pattern: "($S: java.sql.PreparedStatement).execute(<...$ARG...>, ...)" + - pattern-not: '($S: java.sql.PreparedStatement).execute("...", ...)' + - patterns: + - pattern: "($S: java.sql.PreparedStatement).executeUpdate(<...$ARG...>, ...)" + - pattern-not: '($S: java.sql.PreparedStatement).executeUpdate("...", ...)' + - patterns: + - pattern: "($S: java.sql.PreparedStatement).executeLargeUpdate(<...$ARG...>, + ...)" + - pattern-not: '($S: java.sql.PreparedStatement).executeLargeUpdate("...", ...)' + - patterns: + - pattern: "($S: java.sql.PreparedStatement).addBatch(<...$ARG...>, ...)" + - pattern-not: '($S: java.sql.PreparedStatement).addBatch("...", ...)' + - patterns: + - pattern: "($S: java.sql.Connection).prepareCall(<...$ARG...>, ...)" + - pattern-not: '($S: java.sql.Connection).prepareCall("...", ...)' + - patterns: + - pattern: "($S: java.sql.Connection).prepareStatement(<...$ARG...>, ...)" + - pattern-not: '($S: java.sql.Connection).prepareStatement("...", ...)' + - patterns: + - pattern: "($S: java.sql.Connection).nativeSQL(<...$ARG...>, ...)" + - pattern-not: '($S: java.sql.Connection).nativeSQL("...", ...)' + - patterns: + - pattern: new org.springframework.jdbc.core.PreparedStatementCreatorFactory(<...$ARG...>, + ...) + - pattern-not: new org.springframework.jdbc.core.PreparedStatementCreatorFactory("...", + ...) + - patterns: + - pattern: "(org.springframework.jdbc.core.PreparedStatementCreatorFactory $F).newPreparedStatementCreator(<...$ARG...>, + ...)" + - pattern-not: (org.springframework.jdbc.core.PreparedStatementCreatorFactory + $F).newPreparedStatementCreator("...", ...) + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).batchUpdate(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcOperations).batchUpdate("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).execute(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcOperations).execute("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).query(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcOperations).query("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForList(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcOperations).queryForList("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForMap(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcOperations).queryForMap("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForObject(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcOperations).queryForObject("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForObject(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcOperations).queryForObject("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForRowSet(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcOperations).queryForRowSet("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForInt(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcOperations).queryForInt("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).queryForLong(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcOperations).queryForLong("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcOperations).update(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcOperations).update("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).batchUpdate(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcTemplate).batchUpdate("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).execute(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcTemplate).execute("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).query(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcTemplate).query("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).queryForList(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcTemplate).queryForList("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).queryForMap(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcTemplate).queryForMap("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).queryForObject(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcTemplate).queryForObject("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).queryForRowSet(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcTemplate).queryForRowSet("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).queryForInt(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcTemplate).queryForInt("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).queryForLong(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcTemplate).queryForLong("...", + ...)' + - patterns: + - pattern: "($O: org.springframework.jdbc.core.JdbcTemplate).update(<...$ARG...>, + ...)" + - pattern-not: '($O: org.springframework.jdbc.core.JdbcTemplate).update("...", + ...)' + - patterns: + - pattern: "($O: io.vertx.sqlclient.SqlClient).query(<...$ARG...>, ...)" + - pattern-not: '($O: io.vertx.sqlclient.SqlClient).query("...", ...)' + - patterns: + - pattern: "($O: io.vertx.sqlclient.SqlClient).preparedQuery(<...$ARG...>, ...)" + - pattern-not: '($O: io.vertx.sqlclient.SqlClient).preparedQuery("...", ...)' + - patterns: + - pattern: "($O: io.vertx.sqlclient.SqlConnection).prepare(<...$ARG...>, ...)" + - pattern-not: '($O: io.vertx.sqlclient.SqlConnection).prepare("...", ...)' + - patterns: + - pattern: "($O: org.apache.turbine.om.peer.BasePeer).executeQuery(<...$ARG...>, + ...)" + - pattern-not: '($O: org.apache.turbine.om.peer.BasePeer).executeQuery("...", + ...)' + - patterns: + - pattern: "($O: org.apache.torque.util.BasePeer).executeQuery(<...$ARG...>, + ...)" + - pattern-not: '($O: org.apache.torque.util.BasePeer).executeQuery("...", ...)' + - patterns: + - pattern: "($O: javax.persistence.EntityManager).createQuery(<...$ARG...>, + ...)" + - pattern-not: '($O: javax.persistence.EntityManager).createQuery("...", ...)' + - patterns: + - pattern: "($O: javax.persistence.EntityManager).createNativeQuery(<...$ARG...>, + ...)" + - pattern-not: '($O: javax.persistence.EntityManager).createNativeQuery("...", + ...)' + - patterns: + - pattern: anorm.SQL(<...$ARG...>) + - pattern-not: anorm.SQL("...") + - patterns: + - pattern-inside: | + import anorm._ + ... + - pattern: SQL(<...$ARG...>) + - pattern-not: SQL("...") + severity: ERROR +- id: gitlab.find_sec_bugs_scala.SSL_CONTEXT-1 + languages: + - scala + message: | + A HostnameVerifier that accept any host are often use because of certificate + reuse on many hosts. As a consequence, this is vulnerable to Man-in-the-middleattacks + attacks since the client will trust any certificate. + metadata: + category: security + cwe: CWE-295 + shortDescription: Improper Certificate Validation + security-severity: Medium + primary_identifier: find_sec_bugs.SSL_CONTEXT + secondary_identifiers: + - name: Find Security Bugs-SSL_CONTEXT + type: find_sec_bugs_type + value: SSL_CONTEXT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.SSL_CONTEXT-1 + shortlink: https://sg.run/2rx0 + semgrep.dev: + rule: + r_id: 67963 + rv_id: 920235 + rule_id: GdUX7n + version_id: bZTLo56 + url: https://semgrep.dev/playground/r/bZTLo56/gitlab.find_sec_bugs_scala.SSL_CONTEXT-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: new org.apache.http.impl.client.DefaultHttpClient() + - pattern: javax.net.ssl.SSLContext.getInstance("SSL") + - patterns: + - pattern-inside: | + import javax.net.ssl._ + ... + - pattern: SSLContext.getInstance("SSL") + severity: WARNING +- id: gitlab.find_sec_bugs_scala.STRUTS_FORM_VALIDATION-1 + languages: + - scala + message: | + Form inputs should have minimal input validation. Preventive validation helps provide defense + in depth against a variety of risks. + metadata: + category: security + cwe: CWE-20 + shortDescription: Improper Input Validation + security-severity: Info + primary_identifier: find_sec_bugs.STRUTS_FORM_VALIDATION + secondary_identifiers: + - name: Find Security Bugs-STRUTS_FORM_VALIDATION + type: find_sec_bugs_type + value: STRUTS_FORM_VALIDATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.STRUTS_FORM_VALIDATION-1 + shortlink: https://sg.run/kqX7 + semgrep.dev: + rule: + r_id: 67972 + rv_id: 920244 + rule_id: lBUD9R + version_id: ZRTedK8 + url: https://semgrep.dev/playground/r/ZRTedK8/gitlab.find_sec_bugs_scala.STRUTS_FORM_VALIDATION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + class $CLASS extends $SC { + ... + } + - metavariable-regex: + metavariable: "$SC" + regex: "(ActionForm|ValidatorForm)" + - pattern-not: public void validate() { ... } + severity: WARNING +- id: gitlab.find_sec_bugs_scala.TDES_USAGE-1 + languages: + - scala + message: | + Triple DES (also known as 3DES or DESede) is considered strong ciphers for modern + applications. NIST recommends the usage of AES block ciphers instead of 3DES. + metadata: + category: security + cwe: CWE-326 + shortDescription: Inadequate Encryption Strength + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.TDES_USAGE + secondary_identifiers: + - name: Find Security Bugs-TDES_USAGE + type: find_sec_bugs_type + value: TDES_USAGE + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.TDES_USAGE-1 + shortlink: https://sg.run/DDoY + semgrep.dev: + rule: + r_id: 67952 + rv_id: 920224 + rule_id: EwUW2e + version_id: 6xTyX2E + url: https://semgrep.dev/playground/r/6xTyX2E/gitlab.find_sec_bugs_scala.TDES_USAGE-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: javax.crypto.Cipher.getInstance("$ALG") + - metavariable-regex: + metavariable: "$ALG" + regex: "^(DESede)/.*" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.TEMPLATE_INJECTION_PEBBLE-1.TEMPLATE_INJECTION_FREEMARKER-1.TEMPLATE_INJECTION_VELOCITY-1 + languages: + - scala + message: | + A malicious user in control of a template can run malicious code on the + server-side. Velocity templates should be seen as scripts. + metadata: + category: security + cwe: CWE-94 + shortDescription: Improper Control of Generation of Code ('Code Injection') + security-severity: Info + primary_identifier: find_sec_bugs.TEMPLATE_INJECTION_PEBBLE-1.TEMPLATE_INJECTION_FREEMARKER-1.TEMPLATE_INJECTION_VELOCITY-1 + secondary_identifiers: + - name: Find Security Bugs-TEMPLATE_INJECTION_PEBBLE + type: find_sec_bugs_type + value: TEMPLATE_INJECTION_PEBBLE + - name: Find Security Bugs-TEMPLATE_INJECTION_FREEMARKER + type: find_sec_bugs_type + value: TEMPLATE_INJECTION_FREEMARKER + - name: Find Security Bugs-TEMPLATE_INJECTION_VELOCITY + type: find_sec_bugs_type + value: TEMPLATE_INJECTION_VELOCITY + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.TEMPLATE_INJECTION_PEBBLE-1.TEMPLATE_INJECTION_FREEMARKER-1.TEMPLATE_INJECTION_VELOCITY-1 + shortlink: https://sg.run/WNgy + semgrep.dev: + rule: + r_id: 68009 + rv_id: 920280 + rule_id: EwUW4O + version_id: NdTeRZQ + url: https://semgrep.dev/playground/r/NdTeRZQ/gitlab.find_sec_bugs_scala.TEMPLATE_INJECTION_PEBBLE-1.TEMPLATE_INJECTION_FREEMARKER-1.TEMPLATE_INJECTION_VELOCITY-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern: org.apache.velocity.app.Velocity.evaluate(..., $VAR) + - pattern-not: org.apache.velocity.app.Velocity.evaluate(..., "...") + - patterns: + - pattern-not-inside: | + $C = ($CFG: freemarker.template.Configuration).getTemplate("..."); + ... + - pattern-inside: | + $C = ($CFG: freemarker.template.Configuration).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(...)" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.TRUST_BOUNDARY_VIOLATION-1 + languages: + - scala + message: | + A trust boundary can be thought of as line drawn through a program. On one side + of the line, data is untrusted. On the other side of the line, data is assumed + to be trustworthy. The purpose of validation logic is to allow data to safely + cross the trust boundary - to move from untrusted to trusted. A trust boundary + violation occurs when a program blurs the line between what is trusted and what + is untrusted. By combining trusted and untrusted data in the same data + structure, it becomes easier for programmers to mistakenly trust unvalidated + data. + metadata: + category: security + cwe: CWE-501 + shortDescription: Trust Boundary Violation + security-severity: Info + primary_identifier: find_sec_bugs.TRUST_BOUNDARY_VIOLATION + secondary_identifiers: + - name: Find Security Bugs-TRUST_BOUNDARY_VIOLATION + type: find_sec_bugs_type + value: TRUST_BOUNDARY_VIOLATION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.TRUST_BOUNDARY_VIOLATION-1 + shortlink: https://sg.run/5kQA + semgrep.dev: + rule: + r_id: 67947 + rv_id: 920219 + rule_id: eqUK89 + version_id: 0bTp3K7 + url: https://semgrep.dev/playground/r/0bTp3K7/gitlab.find_sec_bugs_scala.TRUST_BOUNDARY_VIOLATION-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - patterns: + - pattern: "($H: HttpServletRequest). ... .setAttribute($ARG1, $ARG2)" + - pattern-not: '($H: HttpServletRequest). ... .setAttribute("...", "...")' + - patterns: + - pattern: "($H: HttpServletRequest). ... .putValue($ARG1, $ARG2)" + - pattern-not: '($H: HttpServletRequest). ... .putValue("...", "...")' + severity: WARNING +- id: gitlab.find_sec_bugs_scala.UNENCRYPTED_SOCKET-1.UNENCRYPTED_SERVER_SOCKET-1 + languages: + - scala + message: | + Beyond using an SSL socket, you need to make sure your use of SSLSocketFactory + does all the appropriate certificate validation checks to make sure you are not + subject to man-in-the-middle attacks. Please read the OWASP Transport Layer + Protection Cheat Sheet for details on how to do this correctly. + metadata: + cwe: CWE-319 + shortDescription: Cleartext transmission of sensitive information + security-severity: Info + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + category: security + primary_identifier: find_sec_bugs.UNENCRYPTED_SOCKET-1.UNENCRYPTED_SERVER_SOCKET-1 + secondary_identifiers: + - name: Find Security Bugs-UNENCRYPTED_SOCKET + type: find_sec_bugs_type + value: UNENCRYPTED_SOCKET + - name: Find Security Bugs-UNENCRYPTED_SERVER_SOCKET + type: find_sec_bugs_type + value: UNENCRYPTED_SERVER_SOCKET + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.UNENCRYPTED_SOCKET-1.UNENCRYPTED_SERVER_SOCKET-1 + shortlink: https://sg.run/9eoY + semgrep.dev: + rule: + r_id: 67967 + rv_id: 920239 + rule_id: DbUypE + version_id: xyTdrjl + url: https://semgrep.dev/playground/r/xyTdrjl/gitlab.find_sec_bugs_scala.UNENCRYPTED_SOCKET-1.UNENCRYPTED_SERVER_SOCKET-1 + origin: community + subcategory: + - audit + patterns: + - pattern: new java.net.Socket(...) + severity: WARNING +- id: gitlab.find_sec_bugs_scala.UNVALIDATED_REDIRECT-1.URL_REWRITING-1 + languages: + - scala + message: | + Unvalidated redirects occur when an application redirects a user to a + destination URL specified by a user supplied parameter that is not validated. + Such vulnerabilities can be used to facilitate phishing attacks. + metadata: + category: security + cwe: CWE-601 + shortDescription: URL Redirection to Untrusted Site ('Open Redirect') + security-severity: Info + primary_identifier: find_sec_bugs.UNVALIDATED_REDIRECT-1.URL_REWRITING-1 + secondary_identifiers: + - name: Find Security Bugs-UNVALIDATED_REDIRECT + type: find_sec_bugs_type + value: UNVALIDATED_REDIRECT + - name: Find Security Bugs-URL_REWRITING + type: find_sec_bugs_type + value: URL_REWRITING + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.UNVALIDATED_REDIRECT-1.URL_REWRITING-1 + shortlink: https://sg.run/ybdx + semgrep.dev: + rule: + r_id: 67968 + rv_id: 920240 + rule_id: WAUno0 + version_id: O9Tv7pL + url: https://semgrep.dev/playground/r/O9Tv7pL/gitlab.find_sec_bugs_scala.UNVALIDATED_REDIRECT-1.URL_REWRITING-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - patterns: + - pattern: "($REQ: HttpServletResponse).sendRedirect(...)" + - pattern-not: '($REQ: HttpServletResponse).sendRedirect("...")' + - patterns: + - pattern: "($REQ: HttpServletResponse).addHeader(...)" + - pattern-not: '($REQ: HttpServletResponse).addHeader("...", "...")' + - patterns: + - pattern: "($REQ: HttpServletResponse).encodeURL(...)" + - pattern-not: '($REQ: HttpServletResponse).encodeURL("...")' + - patterns: + - pattern: "($REQ: HttpServletResponse).encodeRedirectUrl(...)" + - pattern-not: '($REQ: HttpServletResponse).encodeRedirectUrl("...")' + severity: ERROR +- id: gitlab.find_sec_bugs_scala.URLCONNECTION_SSRF_FD-1 + languages: + - scala + message: | + Server-Side Request Forgery occur when a web server executes a request to a user supplied + destination parameter that is not validated. Such vulnerabilities could allow an attacker to + access internal services or to launch attacks from your web server. + metadata: + category: security + cwe: CWE-918 + shortDescription: Server-Side Request Forgery (SSRF) + security-severity: Low + primary_identifier: find_sec_bugs.URLCONNECTION_SSRF_FD + secondary_identifiers: + - name: Find Security Bugs-URLCONNECTION_SSRF_FD + type: find_sec_bugs_type + value: URLCONNECTION_SSRF_FD + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.URLCONNECTION_SSRF_FD-1 + shortlink: https://sg.run/5k86 + semgrep.dev: + rule: + r_id: 68003 + rv_id: 920274 + rule_id: OrU7GA + version_id: jQTwjBn + url: https://semgrep.dev/playground/r/jQTwjBn/gitlab.find_sec_bugs_scala.URLCONNECTION_SSRF_FD-1 + origin: community + subcategory: + - audit + 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) + + ' + severity: ERROR +- id: gitlab.find_sec_bugs_scala.WEAK_FILENAMEUTILS-1 + languages: + - scala + message: | + A file is opened to read its content. The filename comes from an input + parameter. If an unfiltered parameter is passed to this file API, files from an + arbitrary filesystem location could be read. + metadata: + category: security + cwe: CWE-22 + shortDescription: Improper limitation of a pathname to a restricted directory + ('Path Traversal') + technology: + - scala + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + primary_identifier: find_sec_bugs.WEAK_FILENAMEUTILS + secondary_identifiers: + - name: Find Security Bugs-WEAK_FILENAMEUTILS + type: find_sec_bugs_type + value: WEAK_FILENAMEUTILS + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.WEAK_FILENAMEUTILS-1 + shortlink: https://sg.run/Np4p + semgrep.dev: + rule: + r_id: 67971 + rv_id: 920243 + rule_id: qNUwjw + version_id: d6T6gy0 + url: https://semgrep.dev/playground/r/d6T6gy0/gitlab.find_sec_bugs_scala.WEAK_FILENAMEUTILS-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern-inside: | + import org.apache.commons.io.FilenameUtils._ + ... + - pattern-either: + - pattern: normalize(...) + - pattern: getExtension(...) + - pattern: isExtensions(...) + - pattern: isExtension(...) + - pattern: getName(...) + - pattern: getBaseName(...) + - patterns: + - pattern-either: + - pattern: org.apache.commons.io.FilenameUtils.normalize(...) + - pattern: org.apache.commons.io.FilenameUtils.getExtension(...) + - pattern: org.apache.commons.io.FilenameUtils.isExtensions(...) + - pattern: org.apache.commons.io.FilenameUtils.isExtension(...) + - pattern: org.apache.commons.io.FilenameUtils.getName(...) + - pattern: org.apache.commons.io.FilenameUtils.getBaseName(...) + severity: WARNING +- id: gitlab.find_sec_bugs_scala.WEAK_HOSTNAME_VERIFIER-1.WEAK_TRUST_MANAGER-1 + languages: + - scala + message: | + A HostnameVerifier that accept any host are often use because of certificate + reuse on many hosts. As a consequence, this is vulnerable to Man-in-the-middle + attacks since the client will trust any certificate. + metadata: + category: security + cwe: CWE-295 + shortDescription: Improper Certificate Validation + security-severity: Info + primary_identifier: find_sec_bugs.WEAK_HOSTNAME_VERIFIER-1.WEAK_TRUST_MANAGER-1 + secondary_identifiers: + - name: Find Security Bugs-WEAK_HOSTNAME_VERIFIER + type: find_sec_bugs_type + value: WEAK_HOSTNAME_VERIFIER + - name: Find Security Bugs-WEAK_TRUST_MANAGER + type: find_sec_bugs_type + value: WEAK_TRUST_MANAGER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.WEAK_HOSTNAME_VERIFIER-1.WEAK_TRUST_MANAGER-1 + shortlink: https://sg.run/r2dn + semgrep.dev: + rule: + r_id: 67969 + rv_id: 920241 + rule_id: 0oU35P + version_id: e1TZKyX + url: https://semgrep.dev/playground/r/e1TZKyX/gitlab.find_sec_bugs_scala.WEAK_HOSTNAME_VERIFIER-1.WEAK_TRUST_MANAGER-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - patterns: + - pattern-inside: | + class $V extends HostnameVerifier { + ... + } + - pattern-either: + - pattern: def verify(...) = true + - pattern: | + def verify(...) = { + return true + } + - patterns: + - pattern-inside: | + class $V extends X509TrustManager { + ... + } + - pattern-either: + - pattern: 'def checkClientTrusted(...): Unit = {}' + - pattern: 'def checkServerTrusted(...): Unit = {}' + - pattern: def checkClientTrusted(...) = {} + - pattern: def checkServerTrusted(...) = {} + - pattern: 'def getAcceptedIssuers(): Array[X509Certificate] = null' + - pattern: 'def getAcceptedIssuers(): Array[X509Certificate] = {}' + severity: WARNING +- id: gitlab.find_sec_bugs_scala.WEAK_MESSAGE_DIGEST_MD5-1.WEAK_MESSAGE_DIGEST_SHA1-1 + languages: + - scala + message: | + DES is considered strong ciphers for modern applications. Currently, NIST recommends the usage + of AES block ciphers instead of DES. + metadata: + category: security + cwe: CWE-326 + shortDescription: Inadequate Encryption Strength + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.WEAK_MESSAGE_DIGEST_MD5-1.WEAK_MESSAGE_DIGEST_SHA1-1 + secondary_identifiers: + - name: Find Security Bugs-WEAK_MESSAGE_DIGEST_MD5 + type: find_sec_bugs_type + value: WEAK_MESSAGE_DIGEST_MD5 + - name: Find Security Bugs-WEAK_MESSAGE_DIGEST_SHA1 + type: find_sec_bugs_type + value: WEAK_MESSAGE_DIGEST_SHA1 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.WEAK_MESSAGE_DIGEST_MD5-1.WEAK_MESSAGE_DIGEST_SHA1-1 + shortlink: https://sg.run/pzxg + semgrep.dev: + rule: + r_id: 67962 + rv_id: 920234 + rule_id: 5rUGO2 + version_id: rxTjvAN + url: https://semgrep.dev/playground/r/rxTjvAN/gitlab.find_sec_bugs_scala.WEAK_MESSAGE_DIGEST_MD5-1.WEAK_MESSAGE_DIGEST_SHA1-1 + origin: community + subcategory: + - audit + patterns: + - pattern-either: + - pattern: MessageDigest.getInstance("$ALG", ...) + - pattern: Signature.getInstance("$ALG", ...) + - metavariable-regex: + metavariable: "$ALG" + regex: "(.*(MD5|MD4|MD2|SHA1|SHA-1).*)" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.WICKET_XSS1-1 + languages: + - scala + message: 'Disabling HTML escaping put the application at risk for Cross-Site Scripting + (XSS). + + ' + metadata: + category: security + cwe: CWE-79 + shortDescription: Improper Neutralization of Input During Web Page Generation + ('Cross-site Scripting') + security-severity: Medium + primary_identifier: find_sec_bugs.WICKET_XSS1 + secondary_identifiers: + - name: Find Security Bugs-WICKET_XSS1 + type: find_sec_bugs_type + value: WICKET_XSS1 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.WICKET_XSS1-1 + shortlink: https://sg.run/XkLl + semgrep.dev: + rule: + r_id: 68020 + rv_id: 920291 + rule_id: GdUX0G + version_id: 7ZTbRB8 + url: https://semgrep.dev/playground/r/7ZTbRB8/gitlab.find_sec_bugs_scala.WICKET_XSS1-1 + origin: community + subcategory: + - audit + patterns: + - pattern: "($X: Label).setEscapeModelStrings(false);" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.XML_DECODER-1 + languages: + - scala + message: 'Avoid using XMLDecoder to parse content from an untrusted source. + + ' + metadata: + category: security + cwe: CWE-502 + shortDescription: Deserialization of Untrusted Data + security-severity: High + primary_identifier: find_sec_bugs.XML_DECODER + secondary_identifiers: + - name: Find Security Bugs-XML_DECODER + type: find_sec_bugs_type + value: XML_DECODER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.XML_DECODER-1 + shortlink: https://sg.run/6wrw + semgrep.dev: + rule: + r_id: 68015 + rv_id: 920286 + rule_id: 3qUwBw + version_id: vdTvQXA + url: https://semgrep.dev/playground/r/vdTvQXA/gitlab.find_sec_bugs_scala.XML_DECODER-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + $D = new java.beans.XMLDecoder($IN); + ... + - pattern-not-inside: | + $DX = new java.beans.XMLDecoder("..."); + ... + - pattern: "$D.readObject" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.XPATH_INJECTION-1 + languages: + - scala + message: | + The input values included in SQL queries need to be passed in safely. Bind + variables in prepared statements can be used to easily mitigate the risk of + SQL injection. + metadata: + category: security + cwe: CWE-611 + shortDescription: Improper Restriction of XML External Entity Reference ('XXE') + security-severity: Medium + primary_identifier: find_sec_bugs.XPATH_INJECTION + secondary_identifiers: + - name: Find Security Bugs-XPATH_INJECTION + type: find_sec_bugs_type + value: XPATH_INJECTION + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.XPATH_INJECTION-1 + shortlink: https://sg.run/zNkz + semgrep.dev: + rule: + r_id: 68017 + rv_id: 920288 + rule_id: PeUGky + version_id: ZRTed28 + url: https://semgrep.dev/playground/r/ZRTed28/gitlab.find_sec_bugs_scala.XPATH_INJECTION-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sinks: + - patterns: + - pattern-either: + - pattern-inside: |- + import javax.xml.xpath._ + ... + - pattern-inside: |- + import javax.xml.xpath.XPath + ... + - pattern-either: + - pattern: "$Y.compile(...)" + - pattern: "$X.evaluate(..., $ARG2)" + pattern-sources: + - patterns: + - pattern-inside: | + def $FUNC(..., $ARG: $TYPE,...): $RET = { + ... + } + - pattern: "$ARG" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER-1 + languages: + - scala + message: 'Servlet reflected cross site scripting vulnerability + + ' + metadata: + category: security + cwe: CWE-79 + shortDescription: Improper Neutralization of Input During Web Page Generation + technology: + - scala + security-severity: Medium + primary_identifier: find_sec_bugs.XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER + secondary_identifiers: + - name: Find Security Bugs-XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER + type: find_sec_bugs_type + value: XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER-1 + shortlink: https://sg.run/jKNZ + semgrep.dev: + rule: + r_id: 68021 + rv_id: 920292 + rule_id: ReUxPb + version_id: LjTzeGv + url: https://semgrep.dev/playground/r/LjTzeGv/gitlab.find_sec_bugs_scala.XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - pattern: Encode.forHtml(...) + - pattern: org.owasp.esapi.Encoder.encodeForSQL(...) + pattern-sinks: + - patterns: + - pattern-inside: 'def $FUNC(..., $RES: HttpServletResponse, ...): $TYPE = {...}' + - pattern-inside: | + $WRITER = $RES.getWriter + ... + - pattern: "$WRITER.write(...)" + - patterns: + - pattern-inside: 'def $FUNC(..., $RES: HttpServletResponse, ...): $TYPE = {...}' + - pattern: "$RES.getWriter.write(...)" + - patterns: + - pattern-inside: 'def $FUNC(..., $RES: HttpServletResponse, ...): $TYPE = {...}' + - pattern: "$RES.getWriter.print(...)" + pattern-sources: + - patterns: + - pattern-inside: 'def $FUNC(..., $REQ: HttpServletRequest, ...): $TYPE = {...}' + - pattern-either: + - pattern: "$REQ.getParameter(...)" + - pattern: "$REQ.getQueryString" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.XSS_REQUEST_WRAPPER-1 + languages: + - scala + message: 'Avoid using custom XSS filtering. Please use standard sanitization functions. + + ' + metadata: + category: security + cwe: CWE-79 + shortDescription: Improper Neutralization of Input During Web Page Generation + ('Cross-site Scripting') + security-severity: Medium + primary_identifier: find_sec_bugs.XSS_REQUEST_WRAPPER + secondary_identifiers: + - name: Find Security Bugs-XSS_REQUEST_WRAPPER + type: find_sec_bugs_type + value: XSS_REQUEST_WRAPPER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.XSS_REQUEST_WRAPPER-1 + shortlink: https://sg.run/2rbz + semgrep.dev: + rule: + r_id: 68019 + rv_id: 920290 + rule_id: 5rUG4X + version_id: ExT1Wo7 + url: https://semgrep.dev/playground/r/ExT1Wo7/gitlab.find_sec_bugs_scala.XSS_REQUEST_WRAPPER-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + class $CLASS(...) extends HttpServletRequestWrapper(...) { + ... + } + - pattern: def stripXSS(...) = { ... } + severity: INFO +- id: gitlab.find_sec_bugs_scala.XSS_SERVLET-1 + languages: + - scala + message: | + A potential XSS was found. It could be used to execute unwanted JavaScript in a + client's browser. + metadata: + category: security + cwe: CWE-79 + shortDescription: Improper Neutralization of Input During Web Page Generation + ('Cross-site Scripting') + security-severity: Info + primary_identifier: find_sec_bugs.XSS_SERVLET + secondary_identifiers: + - name: Find Security Bugs-XSS_SERVLET + type: find_sec_bugs_type + value: XSS_SERVLET + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.XSS_SERVLET-1 + shortlink: https://sg.run/1ynb + semgrep.dev: + rule: + r_id: 68022 + rv_id: 920293 + rule_id: AbUlWY + version_id: 8KTvlN8 + url: https://semgrep.dev/playground/r/8KTvlN8/gitlab.find_sec_bugs_scala.XSS_SERVLET-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - patterns: + - pattern-inside: org.owasp.encoder.Encode.forHtml($TAINTED); + - pattern: "$TAINTED" + pattern-sinks: + - patterns: + - pattern-inside: 'def $FUNC(..., $RES: HttpServletResponse, ...): $TYPE = {...}' + - pattern-inside: | + $WRITER = $RES.getWriter; + ... + - pattern: "$WRITER.write($DATA,...);" + - pattern: "$DATA" + - patterns: + - pattern-inside: 'def $FUNC(..., $RES: HttpServletResponse, ...): $TYPE = {...}' + - pattern: "$RES.getWriter.write($DATA,...);" + - pattern: "$DATA" + pattern-sources: + - patterns: + - pattern-inside: 'def $FUNC(..., $REQ: HttpServletRequest, ...): $TYPE = {...}' + - pattern: "$REQ.getParameter(...);" + severity: WARNING +- id: gitlab.find_sec_bugs_scala.XXE_DOCUMENT-1 + languages: + - scala + message: | + XML External Entity (XXE) attacks can occur when an XML parser supports XML + entities while processing XML received from an untrusted source. + metadata: + category: security + cwe: CWE-611 + shortDescription: Improper Restriction of XML External Entity Reference ('XXE') + security-severity: Medium + primary_identifier: find_sec_bugs.XXE_DOCUMENT + secondary_identifiers: + - name: Find Security Bugs-XXE_DOCUMENT + type: find_sec_bugs_type + value: XXE_DOCUMENT + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.XXE_DOCUMENT-1 + shortlink: https://sg.run/9eqk + semgrep.dev: + rule: + r_id: 68023 + rv_id: 920294 + rule_id: BYULB2 + version_id: gETkXP2 + url: https://semgrep.dev/playground/r/gETkXP2/gitlab.find_sec_bugs_scala.XXE_DOCUMENT-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + $DF = DocumentBuilderFactory.newInstance + ... + - pattern-not-inside: | + $DF.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) + ... + - pattern-not-inside: | + $DF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) + ... + - pattern: "$DB.parse(...)" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.XXE_DTD_TRANSFORM_FACTORY-1.XXE_XSLT_TRANSFORM_FACTORY-1 + languages: + - scala + message: | + XML External Entity (XXE) attacks can occur when an XML parser supports XML + entities while processing XML received from an untrusted source. + metadata: + category: security + cwe: CWE-611 + shortDescription: Improper Restriction of XML External Entity Reference ('XXE') + security-severity: Medium + primary_identifier: find_sec_bugs.XXE_DTD_TRANSFORM_FACTORY-1.XXE_XSLT_TRANSFORM_FACTORY-1 + secondary_identifiers: + - name: Find Security Bugs-XXE_DTD_TRANSFORM_FACTORY + type: find_sec_bugs_type + value: XXE_DTD_TRANSFORM_FACTORY + - name: Find Security Bugs-XXE_XSLT_TRANSFORM_FACTORY + type: find_sec_bugs_type + value: XXE_XSLT_TRANSFORM_FACTORY + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.XXE_DTD_TRANSFORM_FACTORY-1.XXE_XSLT_TRANSFORM_FACTORY-1 + shortlink: https://sg.run/r2k6 + semgrep.dev: + rule: + r_id: 68025 + rv_id: 920296 + rule_id: WAUnPW + version_id: 3ZTLwRX + url: https://semgrep.dev/playground/r/3ZTLwRX/gitlab.find_sec_bugs_scala.XXE_DTD_TRANSFORM_FACTORY-1.XXE_XSLT_TRANSFORM_FACTORY-1 + origin: community + subcategory: + - audit + mode: taint + pattern-sanitizers: + - pattern: $T.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + - pattern: $T.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + - pattern: "$T.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);" + pattern-sinks: + - pattern: "$T.transform(...)" + pattern-sources: + - patterns: + - pattern-either: + - pattern-inside: |- + import javax.xml.transform._ + ... + - pattern-inside: |- + import javax.xml.transform.Transformer + ... + - pattern: "$FACT.newTransformer" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.XXE_SAXPARSER-1 + languages: + - scala + message: | + XML External Entity (XXE) attacks can occur when an XML parser supports XML + entities while processing XML received from an untrusted source. + metadata: + category: security + cwe: CWE-611 + shortDescription: Improper Restriction of XML External Entity Reference ('XXE') + security-severity: Info + primary_identifier: find_sec_bugs.XXE_SAXPARSER + secondary_identifiers: + - name: Find Security Bugs-XXE_SAXPARSER + type: find_sec_bugs_type + value: XXE_SAXPARSER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.XXE_SAXPARSER-1 + shortlink: https://sg.run/yb68 + semgrep.dev: + rule: + r_id: 68024 + rv_id: 920295 + rule_id: DbUyKd + version_id: QkT1NXN + url: https://semgrep.dev/playground/r/QkT1NXN/gitlab.find_sec_bugs_scala.XXE_SAXPARSER-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + val $SF = SAXParserFactory.newInstance + ... + - pattern-not-inside: | + $SF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) + ... + - pattern-not-inside: | + $SF.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) + ... + - pattern-inside: | + val $P = $SFP.newSAXParser + ... + - pattern: "$P.parse(...);" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.XXE_XMLREADER-1 + languages: + - scala + message: | + XML External Entity (XXE) attacks can occur when an XML parser supports XML + entities while processing XML received from an untrusted source. + metadata: + category: security + cwe: CWE-611 + shortDescription: Improper Restriction of XML External Entity Reference ('XXE') + security-severity: Medium + primary_identifier: find_sec_bugs.XXE_XMLREADER + secondary_identifiers: + - name: Find Security Bugs-XXE_XMLREADER + type: find_sec_bugs_type + value: XXE_XMLREADER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.XXE_XMLREADER-1 + shortlink: https://sg.run/b5rZ + semgrep.dev: + rule: + r_id: 68026 + rv_id: 920297 + rule_id: 0oU3Jy + version_id: 44Teq9d + url: https://semgrep.dev/playground/r/44Teq9d/gitlab.find_sec_bugs_scala.XXE_XMLREADER-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + val $R = XMLReaderFactory.createXMLReader + ... + - pattern-not-inside: | + $R.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) + ... + - pattern: "$R.parse(...)" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.XXE_XMLSTREAMREADER-1 + languages: + - scala + message: | + XML External Entity (XXE) attacks can occur when an XML parser supports XML + entities while processing XML received from an untrusted source. + metadata: + category: security + cwe: CWE-611 + shortDescription: Improper Restriction of XML External Entity Reference ('XXE') + security-severity: Medium + primary_identifier: find_sec_bugs.XXE_XMLSTREAMREADER + secondary_identifiers: + - name: Find Security Bugs-XXE_XMLSTREAMREADER + type: find_sec_bugs_type + value: XXE_XMLSTREAMREADER + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.XXE_XMLSTREAMREADER-1 + shortlink: https://sg.run/Np8x + semgrep.dev: + rule: + r_id: 68027 + rv_id: 920298 + rule_id: KxULYz + version_id: PkTjGz6 + url: https://semgrep.dev/playground/r/PkTjGz6/gitlab.find_sec_bugs_scala.XXE_XMLSTREAMREADER-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + $SF = XMLInputFactory.newFactory + ... + - pattern-not-inside: | + $SF.setProperty(XMLInputFactory.SUPPORT_DTD, false) + ... + - pattern-not-inside: | + $SF.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false) + ... + - pattern: "$SF.createXMLStreamReader(...)" + severity: ERROR +- id: gitlab.find_sec_bugs_scala.XXE_XPATH-1 + languages: + - scala + message: | + XML External Entity (XXE) attacks can occur when an XML parser supports XML + entities while processing XML received from an untrusted source. + metadata: + category: security + cwe: CWE-611 + shortDescription: Improper Restriction of XML External Entity Reference ('XXE') + security-severity: Medium + primary_identifier: find_sec_bugs.XXE_XPATH + secondary_identifiers: + - name: Find Security Bugs-XXE_XPATH + type: find_sec_bugs_type + value: XXE_XPATH + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.find_sec_bugs_scala.XXE_XPATH-1 + shortlink: https://sg.run/kqkX + semgrep.dev: + rule: + r_id: 68028 + rv_id: 920299 + rule_id: qNUwbj + version_id: JdToRkd + url: https://semgrep.dev/playground/r/JdToRkd/gitlab.find_sec_bugs_scala.XXE_XPATH-1 + origin: community + subcategory: + - audit + patterns: + - pattern-inside: | + val $DF = DocumentBuilderFactory.newInstance + ... + - pattern-not-inside: | + $DF.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "") + ... + - pattern-not-inside: | + $DF.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "") + ... + - pattern-not-inside: | + $DF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) + ... + - pattern-not-inside: | + $DF.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) + ... + - pattern-inside: | + $B = $DF.newDocumentBuilder + ... + - pattern: "$XPATH.evaluate(...)" + severity: ERROR +- id: gitlab.flawfinder.AddAccessAllowedAce-1 + languages: + - c + - cpp + message: 'Make sure that you set inheritance by hand if you wish it to inherit. + + ' + metadata: + cwe: CWE-732 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + shortDescription: This doesn't set the inheritance bits in the access control + entry (ACE) header (CWE-732) + security-severity: High + category: security + primary_identifier: flawfinder.AddAccessAllowedAce-1 + secondary_identifiers: + - name: Flawfinder - AddAccessAllowedAce + type: flawfinder_func_name + value: AddAccessAllowedAce + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.AddAccessAllowedAce-1 + shortlink: https://sg.run/1G7b + semgrep.dev: + rule: + r_id: 13066 + rv_id: 920336 + rule_id: 7KUpk7 + version_id: bZTLoE2 + url: https://semgrep.dev/playground/r/bZTLoE2/gitlab.flawfinder.AddAccessAllowedAce-1 + origin: community + subcategory: + - audit + pattern: AddAccessAllowedAce(...) + severity: WARNING +- id: gitlab.flawfinder.CreateProcess-1 + languages: + - c + - cpp + message: | + Due to how `CreateProcess` parses spaces, an attacker may be able to exploit this function + by creating a binary with the same name that is loaded first, depending on the search path + order. + + Ensure that quotation marks around the executable path are used, such as: + ``` + CreateProcessA(NULL, "\"C:\\Program Files\\MyApp.exe\"", ...) + ``` + For more information, please see MSDNs documentation at: + https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa#security-remarks + metadata: + shortDescription: Possible executable path hijacking (CreateProcess) + cwe: CWE-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.CreateProcess-1 + secondary_identifiers: + - name: Flawfinder - CreateProcess + type: flawfinder_func_name + value: CreateProcess + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.CreateProcess-1 + shortlink: https://sg.run/Q4KD + semgrep.dev: + rule: + r_id: 13086 + rv_id: 920353 + rule_id: YGUQ94 + version_id: 3ZTLwWB + url: https://semgrep.dev/playground/r/3ZTLwWB/gitlab.flawfinder.CreateProcess-1 + origin: community + subcategory: + - audit + pattern: CreateProcess(...) + severity: WARNING +- id: gitlab.flawfinder.CreateProcessAsUser-1.CreateProcessWithLogon-1 + languages: + - c + - cpp + message: | + Due to how `CreateProcess` parses spaces, an attacker may be able to exploit this function + by creating a binary with the same name that is loaded first, depending on the search path + order. + + Ensure that quotation marks around the executable path are used, such as: + ``` + CreateProcessAsUser(hToken, NULL, "\"C:\\Program Files\\MyApp.exe\"", ...) + ``` + For more information, please see MSDNs documentation at: + https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessasusera#security-remarks + metadata: + shortDescription: Possible executable path hijacking (CreateProcessAsUser/CreateProcessWithLogon) + cwe: CWE-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.CreateProcessAsUser-1.CreateProcessWithLogon-1 + secondary_identifiers: + - name: Flawfinder - CreateProcessAsUser + type: flawfinder_func_name + value: CreateProcessAsUser + - name: Flawfinder - CreateProcessWithLogon + type: flawfinder_func_name + value: CreateProcessWithLogon + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.CreateProcessAsUser-1.CreateProcessWithLogon-1 + shortlink: https://sg.run/34Yg + semgrep.dev: + rule: + r_id: 13087 + rv_id: 920354 + rule_id: 6JU6Pz + version_id: 44Teq52 + url: https://semgrep.dev/playground/r/44Teq52/gitlab.flawfinder.CreateProcessAsUser-1.CreateProcessWithLogon-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: CreateProcessAsUser(...) + - pattern: CreateProcessWithLogon(...) + severity: WARNING +- id: gitlab.flawfinder.EVP_des_ecb-1.EVP_des_cbc-1.EVP_des_cfb-1.EVP_des_ofb-1.EVP_desx_cbc-1 + languages: + - c + - cpp + message: | + The DES algorithm has not been recommended for over 15 years and was withdrawn from NIST (FIPS + 46-3) in 2005. + + Consider using libsodium's `crypto_secretbox_easy` authenticated encryption functions instead. + + For more information please see: + https://libsodium.gitbook.io/doc/secret-key_cryptography/secretbox. + + If you must be FIPS compliant, consider using OpenSSLs AES or 3DES ciphers. + metadata: + shortDescription: Insecure encryption algorithm (DES) + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: Medium + category: security + primary_identifier: flawfinder.EVP_des_ecb-1.EVP_des_cbc-1.EVP_des_cfb-1.EVP_des_ofb-1.EVP_desx_cbc-1 + secondary_identifiers: + - name: Flawfinder - EVP_des_ecb + type: flawfinder_func_name + value: EVP_des_ecb + - name: Flawfinder - EVP_des_cbc + type: flawfinder_func_name + value: EVP_des_cbc + - name: Flawfinder - EVP_des_cfb + type: flawfinder_func_name + value: EVP_des_cfb + - name: Flawfinder - EVP_des_ofb + type: flawfinder_func_name + value: EVP_des_ofb + - name: Flawfinder - EVP_desx_cbc + type: flawfinder_func_name + value: EVP_desx_cbc + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.EVP_des_ecb-1.EVP_des_cbc-1.EVP_des_cfb-1.EVP_des_ofb-1.EVP_desx_cbc-1 + shortlink: https://sg.run/lxzL + semgrep.dev: + rule: + r_id: 13057 + rv_id: 920327 + rule_id: wdUGO7 + version_id: zyTG3B6 + url: https://semgrep.dev/playground/r/zyTG3B6/gitlab.flawfinder.EVP_des_ecb-1.EVP_des_cbc-1.EVP_des_cfb-1.EVP_des_ofb-1.EVP_desx_cbc-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: EVP_des_ecb(...) + - pattern: EVP_des_cbc(...) + - pattern: EVP_des_cfb(...) + - pattern: EVP_des_ofb(...) + - pattern: EVP_desx_cbc(...) + severity: ERROR +- id: gitlab.flawfinder.EVP_rc4_40-1.EVP_rc2_40_cbc-1.EVP_rc2_64_cbc-1 + languages: + - c + - cpp + message: | + The RC4 algorithm is vulnerable to many attacks and should no longer be used for encrypting + data streams. + + Consider using libsodium's `crypto_secretstream_xchacha20poly1305` stream cipher encryption + functions instead. For more information please see: + https://libsodium.gitbook.io/doc/secret-key_cryptography/secretstream + + If you must be FIPS compliant, consider using OpenSSLs AES or 3DES ciphers. + metadata: + shortDescription: Insecure stream cipher (RC4) + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: Medium + category: security + primary_identifier: flawfinder.EVP_rc4_40-1.EVP_rc2_40_cbc-1.EVP_rc2_64_cbc-1 + secondary_identifiers: + - name: Flawfinder - EVP_rc4_40 + type: flawfinder_func_name + value: EVP_rc4_40 + - name: Flawfinder - EVP_rc2_40_cbc + type: flawfinder_func_name + value: EVP_rc2_40_cbc + - name: Flawfinder - EVP_rc2_64_cbc + type: flawfinder_func_name + value: EVP_rc2_64_cbc + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.EVP_rc4_40-1.EVP_rc2_40_cbc-1.EVP_rc2_64_cbc-1 + shortlink: https://sg.run/YXxW + semgrep.dev: + rule: + r_id: 13058 + rv_id: 920328 + rule_id: x8U2ke + version_id: pZTbD2g + url: https://semgrep.dev/playground/r/pZTbD2g/gitlab.flawfinder.EVP_rc4_40-1.EVP_rc2_40_cbc-1.EVP_rc2_64_cbc-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: EVP_rc4_40(...) + - pattern: EVP_rc2_40_cbc(...) + - pattern: EVP_rc2_64_cbc(...) + severity: ERROR +- id: gitlab.flawfinder.GetTempFileName-1 + languages: + - c + - cpp + message: | + The `GetTempFileName` function works by generating a randomly named file, creating the file + (if it does not exist) and then closing it. An application wishing to use this temporary file + will need to reopen this file to begin working with it. This leads to a potential + Time Of Check Time Of Use (TOCTOU) vulnerability, as an attacker could replace or modify + the contents of the file prior to it being used by the application. + + Consider generating a random filename and opening the file directly in a single `CreateFile` + or `OpenFile` call. + metadata: + shortDescription: Potential time of check time of use vulnerability (GetTempFileName) + cwe: CWE-377 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + category: security + primary_identifier: flawfinder.GetTempFileName-1 + secondary_identifiers: + - name: Flawfinder - GetTempFileName + type: flawfinder_func_name + value: GetTempFileName + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.GetTempFileName-1 + shortlink: https://sg.run/JjGo + semgrep.dev: + rule: + r_id: 13090 + rv_id: 920357 + rule_id: pKUw7J + version_id: 5PTNGry + url: https://semgrep.dev/playground/r/5PTNGry/gitlab.flawfinder.GetTempFileName-1 + origin: community + subcategory: + - audit + pattern: GetTempFileName(...) + severity: WARNING +- id: gitlab.flawfinder.LoadLibrary-1 + languages: + - c + - cpp + message: | + The `LoadLibrary` function is used to load DLLs dynamically. Depending on the filepath + parameter, + the OS version, and the modes set for the process prior to calling LoadLibrary, DLL hijacking + may + be possible. Attackers can exploit this by placing DLL files with the same name in directories + that + are searched before the legitimate DLL is. + + To assist in preventing against this class of vulnerability consider: + - Specifying a fully qualified path when using LoadLibraryEx. + - Use the `LOAD_LIBRARY_SEARCH` flags with LoadLibraryEx or with SetDefaultDllDirectories. + - If you use SetDefaultDllDirectories, be sure to use the AddDllDirectory or SetDllDirectory + functions to modify the list of directories. + - Only use `SearchPath` if the `SetSearchPathMode` function is called with + `BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE`. (Note: this only moves the current directory to + the end of the SearchPath search list.) + + For more information see the security remarks section of the MSDN documentation: + https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya#security-remarks + + For general information securely loading dynamic link libraries, see the MSDN documentation: + https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-security + metadata: + shortDescription: Potential for DLL hijacking (LoadLibrary) + cwe: CWE-20 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.LoadLibrary-1 + secondary_identifiers: + - name: Flawfinder - LoadLibrary + type: flawfinder_func_name + value: LoadLibrary + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.LoadLibrary-1 + shortlink: https://sg.run/y6n8 + semgrep.dev: + rule: + r_id: 13068 + rv_id: 920337 + rule_id: 8GUx8Y + version_id: NdTeR6w + url: https://semgrep.dev/playground/r/NdTeR6w/gitlab.flawfinder.LoadLibrary-1 + origin: community + subcategory: + - audit + pattern: LoadLibrary(...) + severity: WARNING +- id: gitlab.flawfinder.LoadLibraryEx-1 + languages: + - c + - cpp + message: | + The `LoadLibraryEx` function is used to load DLLs dynamically. Depending on the filepath + parameter, + the OS version, and the modes set for the process prior to calling LoadLibrary, DLL hijacking + may + be possible. Attackers can exploit this by placing DLL files with the same name in directories + that + are searched before the legitimate DLL is. + + To assist in preventing against this class of vulnerability consider: + - Specifying a fully qualified path when using LoadLibraryEx. + - Use the `LOAD_LIBRARY_SEARCH` flags with LoadLibraryEx or with SetDefaultDllDirectories. + - If you use SetDefaultDllDirectories, be sure to use the AddDllDirectory or SetDllDirectory + functions to modify the list of directories. + - Only use `SearchPath` if the `SetSearchPathMode` function is called with + `BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE`. (Note: this only moves the current directory to + the end of the SearchPath search list.) + + For more information see the security remarks section of the MSDN documentation: + https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya#security-remarks + + For general information securely loading dynamic link libraries, see the MSDN documentation: + https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-security + metadata: + shortDescription: Potential for DLL hijacking (LoadLibraryEx) + cwe: CWE-20 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.LoadLibraryEx-1 + secondary_identifiers: + - name: Flawfinder - LoadLibraryEx + type: flawfinder_func_name + value: LoadLibraryEx + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.LoadLibraryEx-1 + shortlink: https://sg.run/rkn6 + semgrep.dev: + rule: + r_id: 13069 + rv_id: 920338 + rule_id: gxUYQ3 + version_id: kbTOPWl + url: https://semgrep.dev/playground/r/kbTOPWl/gitlab.flawfinder.LoadLibraryEx-1 + origin: community + subcategory: + - audit + pattern: LoadLibraryEx(...) + severity: WARNING +- id: gitlab.flawfinder.MultiByteToWideChar-1 + languages: + - c + - cpp + message: | + The input buffer is the number of bytes in the string, but the size + of the output buffer is the number of characters. To avoid overflows, the + application must determine the correct buffer size which depends on the data type + the buffer receives. + + For more information see: + https://learn.microsoft.com/en-us/windows/win32/intl/security-considerations--international-features + metadata: + shortDescription: Easily misused function may lead to buffer overflows + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.MultiByteToWideChar-1 + secondary_identifiers: + - name: Flawfinder - MultiByteToWideChar + type: flawfinder_func_name + value: MultiByteToWideChar + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.MultiByteToWideChar-1 + shortlink: https://sg.run/N82x + semgrep.dev: + rule: + r_id: 13027 + rv_id: 920302 + rule_id: qNUb31 + version_id: RGT2xpv + url: https://semgrep.dev/playground/r/RGT2xpv/gitlab.flawfinder.MultiByteToWideChar-1 + origin: community + subcategory: + - audit + pattern: MultiByteToWideChar(...) + severity: INFO +- id: gitlab.flawfinder.RpcImpersonateClient-1.ImpersonateLoggedOnUser-1.CoImpersonateClient-1.ImpersonateNamedPipeClient-1.ImpersonateDdeClientWindow-1.ImpersonateSecurityContext-1.SetThreadToken-1 + languages: + - c + - cpp + message: | + These functions may be used to either drop or change account privileges. If the calls + fail, the process will continue to run with the privileges assigned to it on start. Depending + on + the logic of the application, this may allow attackers to abuse the system due to privileges + never + being changed to a different access level. + + Always ensure return values of this function are checked to determine if the application should + continue to operate. + metadata: + shortDescription: Ensure return values are checked when attempting to drop privileges + cwe: CWE-250 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: High + category: security + primary_identifier: flawfinder.RpcImpersonateClient-1.ImpersonateLoggedOnUser-1.CoImpersonateClient-1.ImpersonateNamedPipeClient-1.ImpersonateDdeClientWindow-1.ImpersonateSecurityContext-1.SetThreadToken-1 + secondary_identifiers: + - name: Flawfinder - RpcImpersonateClient + type: flawfinder_func_name + value: RpcImpersonateClient + - name: Flawfinder - ImpersonateLoggedOnUser + type: flawfinder_func_name + value: ImpersonateLoggedOnUser + - name: Flawfinder - CoImpersonateClient + type: flawfinder_func_name + value: CoImpersonateClient + - name: Flawfinder - ImpersonateNamedPipeClient + type: flawfinder_func_name + value: ImpersonateNamedPipeClient + - name: Flawfinder - ImpersonateDdeClientWindow + type: flawfinder_func_name + value: ImpersonateDdeClientWindow + - name: Flawfinder - ImpersonateSecurityContext + type: flawfinder_func_name + value: ImpersonateSecurityContext + - name: Flawfinder - SetThreadToken + type: flawfinder_func_name + value: SetThreadToken + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.RpcImpersonateClient-1.ImpersonateLoggedOnUser-1.CoImpersonateClient-1.ImpersonateNamedPipeClient-1.ImpersonateDdeClientWindow-1.ImpersonateSecurityContext-1.SetThreadToken-1 + shortlink: https://sg.run/rk96 + semgrep.dev: + rule: + r_id: 13025 + rv_id: 920300 + rule_id: 0oUJjL + version_id: 5PTNGqv + url: https://semgrep.dev/playground/r/5PTNGqv/gitlab.flawfinder.RpcImpersonateClient-1.ImpersonateLoggedOnUser-1.CoImpersonateClient-1.ImpersonateNamedPipeClient-1.ImpersonateDdeClientWindow-1.ImpersonateSecurityContext-1.SetThreadToken-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: RpcImpersonateClient(...) + - pattern: ImpersonateLoggedOnUser(...) + - pattern: CoImpersonateClient(...) + - pattern: ImpersonateNamedPipeClient(...) + - pattern: ImpersonateDdeClientWindow(...) + - pattern: ImpersonateSecurityContext(...) + - pattern: SetThreadToken(...) + severity: ERROR +- id: gitlab.flawfinder.SetSecurityDescriptorDacl-1 + languages: + - c + - cpp + message: | + When `SetSecurityDescriptorDacl` is called with a null `pDacl` parameter and the + `bDaclPresent` flag is `TRUE`, all access to the object is allowed. An attacker + could set the object to Deny all, which would include even the Administrator user(s). + + Either call `SetSecurityDescriptorDacl` with bDaclPresent as `FALSE`, or supply a valid + non-null `pDacl` parameter value. + + For more information please see: + https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-setsecuritydescriptordacl#remarks + metadata: + shortDescription: Null ACL when calling SetSecurityDescriptorDacl may allow all + access to objects + cwe: CWE-732 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + category: security + primary_identifier: flawfinder.SetSecurityDescriptorDacl-1 + secondary_identifiers: + - name: Flawfinder - SetSecurityDescriptorDacl + type: flawfinder_func_name + value: SetSecurityDescriptorDacl + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.SetSecurityDescriptorDacl-1 + shortlink: https://sg.run/brkZ + semgrep.dev: + rule: + r_id: 13070 + rv_id: 920339 + rule_id: QrUpe8 + version_id: w8TkbWb + url: https://semgrep.dev/playground/r/w8TkbWb/gitlab.flawfinder.SetSecurityDescriptorDacl-1 + origin: community + subcategory: + - audit + pattern: SetSecurityDescriptorDacl(...) + severity: ERROR +- id: gitlab.flawfinder.StrCat-1.StrCatA-1.StrcatW-1.lstrcatA-1.lstrcatW-1.strCatBuff-1.StrCatBuffA-1.StrCatBuffW-1.StrCatChainW-1._tccat-1._mbccat-1._ftcscat-1.StrCatN-1.StrCatNA-1.StrCatNW-1.StrNCat-1.StrNCatA-1.StrNCatW-1.lstrncat-1.lstrcatnA-1.lstrcatnW-1 + languages: + - c + - cpp + message: | + The `StrCat` family of functions do not guarantee the final string to be null terminated. + Consider using one of the following alternatives: `StringCbCat`, `StringCbCatEx`, + `StringCbCatN`, `StringCbCatNEx`, `StringCchCat`, `StringCchCatEx`, `StringCchCatN`, or + `StringCchCatNEx`. + + For more information please see: https://learn.microsoft.com/en-us/windows/win32/api/strsafe/ + metadata: + shortDescription: Insecure string processing function + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.StrCat-1.StrCatA-1.StrcatW-1.lstrcatA-1.lstrcatW-1.strCatBuff-1.StrCatBuffA-1.StrCatBuffW-1.StrCatChainW-1._tccat-1._mbccat-1._ftcscat-1.StrCatN-1.StrCatNA-1.StrCatNW-1.StrNCat-1.StrNCatA-1.StrNCatW-1.lstrncat-1.lstrcatnA-1.lstrcatnW-1 + secondary_identifiers: + - name: Flawfinder - StrCat + type: flawfinder_func_name + value: StrCat + - name: Flawfinder - StrCatA + type: flawfinder_func_name + value: StrCatA + - name: Flawfinder - StrcatW + type: flawfinder_func_name + value: StrcatW + - name: Flawfinder - lstrcatA + type: flawfinder_func_name + value: lstrcatA + - name: Flawfinder - lstrcatW + type: flawfinder_func_name + value: lstrcatW + - name: Flawfinder - strCatBuff + type: flawfinder_func_name + value: strCatBuff + - name: Flawfinder - StrCatBuffA + type: flawfinder_func_name + value: StrCatBuffA + - name: Flawfinder - StrCatBuffW + type: flawfinder_func_name + value: StrCatBuffW + - name: Flawfinder - StrCatChainW + type: flawfinder_func_name + value: StrCatChainW + - name: Flawfinder - _tccat + type: flawfinder_func_name + value: _tccat + - name: Flawfinder - _mbccat + type: flawfinder_func_name + value: _mbccat + - name: Flawfinder - _ftcscat + type: flawfinder_func_name + value: _ftcscat + - name: Flawfinder - StrCatN + type: flawfinder_func_name + value: StrCatN + - name: Flawfinder - StrCatNA + type: flawfinder_func_name + value: StrCatNA + - name: Flawfinder - StrCatNW + type: flawfinder_func_name + value: StrCatNW + - name: Flawfinder - StrNCat + type: flawfinder_func_name + value: StrNCat + - name: Flawfinder - StrNCatA + type: flawfinder_func_name + value: StrNCatA + - name: Flawfinder - StrNCatW + type: flawfinder_func_name + value: StrNCatW + - name: Flawfinder - lstrncat + type: flawfinder_func_name + value: lstrncat + - name: Flawfinder - lstrcatnA + type: flawfinder_func_name + value: lstrcatnA + - name: Flawfinder - lstrcatnW + type: flawfinder_func_name + value: lstrcatnW + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.StrCat-1.StrCatA-1.StrcatW-1.lstrcatA-1.lstrcatW-1.strCatBuff-1.StrCatBuffA-1.StrCatBuffW-1.StrCatChainW-1._tccat-1._mbccat-1._ftcscat-1.StrCatN-1.StrCatNA-1.StrCatNW-1.StrNCat-1.StrNCatA-1.StrNCatW-1.lstrncat-1.lstrcatnA-1.lstrcatnW-1 + shortlink: https://sg.run/kkoX + semgrep.dev: + rule: + r_id: 13028 + rv_id: 920303 + rule_id: lBUzG9 + version_id: A8TNlqb + url: https://semgrep.dev/playground/r/A8TNlqb/gitlab.flawfinder.StrCat-1.StrCatA-1.StrcatW-1.lstrcatA-1.lstrcatW-1.strCatBuff-1.StrCatBuffA-1.StrCatBuffW-1.StrCatChainW-1._tccat-1._mbccat-1._ftcscat-1.StrCatN-1.StrCatNA-1.StrCatNW-1.StrNCat-1.StrNCatA-1.StrNCatW-1.lstrncat-1.lstrcatnA-1.lstrcatnW-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: strcat(...) + - pattern: strcatA(...) + - pattern: StrcatW(...) + - pattern: lstrcatA(...) + - pattern: lstrcatW(...) + - pattern: strCatBuff(...) + - pattern: StrCatBuffA(...) + - pattern: StrCatBuffW(...) + - pattern: StrCatChainW(...) + - pattern: _tccat(...) + - pattern: _mbccat(...) + - pattern: _ftcscat(...) + - pattern: StrCatN(...) + - pattern: StrCatNA(...) + - pattern: StrCatNW(...) + - pattern: StrNCat(...) + - pattern: StrNCatA(...) + - pattern: StrNCatW(...) + - pattern: lstrncat(...) + - pattern: lstrcatnA(...) + - pattern: lstrcatnW(...) + severity: ERROR +- id: gitlab.flawfinder.access-1 + languages: + - c + - cpp + message: | + Usage of the `access` function call hints at a potential Time Of Check Time Of Use (TOCTOU) + vulnerability. Using the `access` function to check if a file exists and is readable before + opening it, an attacker can create a race condition between the `access` call and + opening the file. The attacker could replace the file with a different one or modify its + content between the time the `access` function is called and the file is opened, thus + bypassing the permission check. + + Call `setuid` to drop privileges on the process prior to opening any files. Instead of using + `access`, use `lstat` prior to opening the file and confirm the attributes are correct. Then + use `open` to get a file descriptor to this file. Call `fstat` on the `open` file descriptor + to confirm that `st_dev` and `st_ino` are equal between the two. If they are, it is safe to + read and operate on the file's contents. + + For more information please see: + https://wiki.sei.cmu.edu/confluence/display/c/FIO45-C.+Avoid+TOCTOU+race+conditions+while+accessing+files + metadata: + shortDescription: Potential time of check time of use vulnerability (access) + cwe: CWE-362 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + category: security + primary_identifier: flawfinder.access-1 + secondary_identifiers: + - name: Flawfinder - access + type: flawfinder_func_name + value: access + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.access-1 + shortlink: https://sg.run/ZkX7 + semgrep.dev: + rule: + r_id: 13079 + rv_id: 920347 + rule_id: BYU731 + version_id: ExT1WeB + url: https://semgrep.dev/playground/r/ExT1WeB/gitlab.flawfinder.access-1 + origin: community + subcategory: + - audit + pattern: access(...) + severity: ERROR +- id: gitlab.flawfinder.atoi-1.atol-1._wtoi-1._wtoi64-1 + languages: + - c + - cpp + message: | + The `atoi` family of functions can potentially overflow or underflow integer values. Consider + using `stroul` instead. + + For more information please see: + https://wiki.sei.cmu.edu/confluence/display/c/ERR34-C.+Detect+errors+when+converting+a+string+to+a+number + metadata: + shortDescription: Possible integer overflow or underflow + cwe: CWE-190 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: Medium + category: security + primary_identifier: flawfinder.atoi-1.atol-1._wtoi-1._wtoi64-1 + secondary_identifiers: + - name: Flawfinder - atoi + type: flawfinder_func_name + value: atoi + - name: Flawfinder - atol + type: flawfinder_func_name + value: atol + - name: Flawfinder - _wtoi + type: flawfinder_func_name + value: _wtoi + - name: Flawfinder - _wtoi64 + type: flawfinder_func_name + value: _wtoi64 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.atoi-1.atol-1._wtoi-1._wtoi64-1 + shortlink: https://sg.run/jk6Z + semgrep.dev: + rule: + r_id: 13065 + rv_id: 920335 + rule_id: EwUQzn + version_id: rxTjvnW + url: https://semgrep.dev/playground/r/rxTjvnW/gitlab.flawfinder.atoi-1.atol-1._wtoi-1._wtoi64-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: atoi(...) + - pattern: atol(...) + - pattern: _wtoi(...) + - pattern: _wtoi64(...) + severity: INFO +- id: gitlab.flawfinder.chmod-1 + languages: + - c + - cpp + message: | + Usage of the `chmod` function call hints at a potential Time Of Check Time Of Use (TOCTOU) + vulnerability. An attacker may be able to modify the file being specified by the `chmod` + function prior to the `chmod` function being called. Since `chmod` will resolve symbolic links, + an attacker may be able to exploit this fact to have files outside of their control modified. + + It is recommended that the `fchmod` function be used instead since this function takes + a file descriptor instead of a file. Ensure the opened file descriptor is pointing to + the correct file or directory prior to executing `fchmod` or any other file based operations. + + For more information please see: + https://wiki.sei.cmu.edu/confluence/display/c/FIO01-C.+Be+careful+using+functions+that+use+file+names+for+identification + metadata: + shortDescription: Potential time of check time of use vulnerability (chmod) + cwe: CWE-362 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + category: security + primary_identifier: flawfinder.chmod-1 + secondary_identifiers: + - name: Flawfinder - chmod + type: flawfinder_func_name + value: chmod + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.chmod-1 + shortlink: https://sg.run/EOe8 + semgrep.dev: + rule: + r_id: 13081 + rv_id: 920348 + rule_id: WAUP43 + version_id: 7ZTbRZz + url: https://semgrep.dev/playground/r/7ZTbRZz/gitlab.flawfinder.chmod-1 + origin: community + subcategory: + - audit + pattern: chmod(...) + severity: ERROR +- id: gitlab.flawfinder.chown-1 + languages: + - c + - cpp + message: | + Usage of the `chown` function call hints at a potential Time Of Check Time Of Use (TOCTOU) + vulnerability. An attacker may be able to modify the file being specified by the `chmod` + function prior to the `chown` function being called. Since `chown` will resolve symbolic links, + an attacker may be able to exploit this fact to have files outside of their control modified. + + It is recommended that the `fchown` or the `lchown` functions be used instead. The `fchown` + function takes a file descriptor instead of a file. The `lchown` function does not follow + symbolic links. Ensure the opened file descriptor is pointing to the correct file or + directory prior to executing `fchown` or any other file based operations. + + For more information please see: + https://wiki.sei.cmu.edu/confluence/display/c/FIO01-C.+Be+careful+using+functions+that+use+file+names+for+identification + metadata: + shortDescription: Potential time of check time of use vulnerability (chown) + cwe: CWE-362 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + category: security + primary_identifier: flawfinder.chown-1 + secondary_identifiers: + - name: Flawfinder - chown + type: flawfinder_func_name + value: chown + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.chown-1 + shortlink: https://sg.run/7Gpv + semgrep.dev: + rule: + r_id: 13082 + rv_id: 920349 + rule_id: 0oUJPK + version_id: LjTze9q + url: https://semgrep.dev/playground/r/LjTze9q/gitlab.flawfinder.chown-1 + origin: community + subcategory: + - audit + pattern: chown(...) + severity: ERROR +- id: gitlab.flawfinder.crypt-1.crypt_r-1 + languages: + - c + - cpp + message: | + The crypt functions are not recommended due to the significantly small + key space. Modern hardware can crack crypt produced passwords relatively quickly. + + Consider using the Argon2id password hashing algorithm provided by libsodium. + For more information please see: https://libsodium.gitbook.io/doc/password_hashing. + metadata: + shortDescription: Insecure hashing algorithm + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: Medium + category: security + primary_identifier: flawfinder.crypt-1.crypt_r-1 + secondary_identifiers: + - name: Flawfinder - crypt + type: flawfinder_func_name + value: crypt + - name: Flawfinder - crypt_r + type: flawfinder_func_name + value: crypt_r + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.crypt-1.crypt_r-1 + shortlink: https://sg.run/657w + semgrep.dev: + rule: + r_id: 13059 + rv_id: 920329 + rule_id: OrUD57 + version_id: 2KTdORB + url: https://semgrep.dev/playground/r/2KTdORB/gitlab.flawfinder.crypt-1.crypt_r-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: crypt(...) + - pattern: crypt_r(...) + severity: ERROR +- id: gitlab.flawfinder.cuserid-1 + languages: + - c + - cpp + message: | + `cuserid()` is poorly defined (e.g., some systems use the effective + UID, like Linux, while others like System V use the real UID). Therefore, you can't trust + what it does. The cuserid function was included in the 1988 version of POSIX, but removed + from the 1990 version. Also, if passed a non-null parameter, there's a risk of a buffer + overflow if the passed-in buffer is not at least `L_cuserid` characters long. + + Use `getpwuid(geteuid())` and extract the desired information instead. + + For more information please see: https://linux.die.net/man/3/getpwuid + metadata: + shortDescription: Usage of deprecated function (cuserid) + cwe: CWE-120 + owasp: + - A9:2017-Using Components with Known Vulnerabilities + - A06:2021-Vulnerable and Outdated Components + security-severity: Low + category: security + primary_identifier: flawfinder.cuserid-1 + secondary_identifiers: + - name: Flawfinder - cuserid + type: flawfinder_func_name + value: cuserid + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.cuserid-1 + shortlink: https://sg.run/kkgX + semgrep.dev: + rule: + r_id: 13072 + rv_id: 920340 + rule_id: 4bU20k + version_id: xyTdrRz + url: https://semgrep.dev/playground/r/xyTdrRz/gitlab.flawfinder.cuserid-1 + origin: community + subcategory: + - audit + pattern: cuserid(...) + severity: ERROR +- id: gitlab.flawfinder.drand48-1.erand48-1.jrand48-1.lcong48-1.lrand48-1.mrand48-1.nrand48-1.random-1.seed48-1.setstate-1.srand-1.strfry-1.srandom-1.g_rand_boolean-1.g_rand_int-1.g_rand_int_range-1.g_rand_double-1.g_rand_double_range-1.g_random_boolean-1.g_random_int-1.g_random_int_range-1.g_random_double-1.g_random_double_range-1 + languages: + - c + - cpp + message: | + The detected function is not sufficient at generating security-related random numbers, + such as those used in key and nonce creation. Consider using the libsodium library's + `randombytes_random` function instead. More information on libsodium's random number + generators can be found here: https://libsodium.gitbook.io/doc/generating_random_data. + + If FIPS validation is required, consider using OpenSSLs `RAND_bytes` family of functions after + enabling the `FIPS_mode_set`. + + For more information on OpenSSL random numbers please see: + https://wiki.openssl.org/index.php/Random_Numbers + metadata: + shortDescription: Usage of insufficient random number generators + cwe: CWE-327 + owasp: + - A3:2017-Sensitive Data Exposure + - A02:2021-Cryptographic Failures + security-severity: Medium + category: security + primary_identifier: flawfinder.drand48-1.erand48-1.jrand48-1.lcong48-1.lrand48-1.mrand48-1.nrand48-1.random-1.seed48-1.setstate-1.srand-1.strfry-1.srandom-1.g_rand_boolean-1.g_rand_int-1.g_rand_int_range-1.g_rand_double-1.g_rand_double_range-1.g_random_boolean-1.g_random_int-1.g_random_int_range-1.g_random_double-1.g_random_double_range-1 + secondary_identifiers: + - name: Flawfinder - drand48 + type: flawfinder_func_name + value: drand48 + - name: Flawfinder - erand48 + type: flawfinder_func_name + value: erand48 + - name: Flawfinder - jrand48 + type: flawfinder_func_name + value: jrand48 + - name: Flawfinder - lcong48 + type: flawfinder_func_name + value: lcong48 + - name: Flawfinder - lrand48 + type: flawfinder_func_name + value: lrand48 + - name: Flawfinder - mrand48 + type: flawfinder_func_name + value: mrand48 + - name: Flawfinder - nrand48 + type: flawfinder_func_name + value: nrand48 + - name: Flawfinder - random + type: flawfinder_func_name + value: random + - name: Flawfinder - seed48 + type: flawfinder_func_name + value: seed48 + - name: Flawfinder - setstate + type: flawfinder_func_name + value: setstate + - name: Flawfinder - srand + type: flawfinder_func_name + value: srand + - name: Flawfinder - strfry + type: flawfinder_func_name + value: strfry + - name: Flawfinder - srandom + type: flawfinder_func_name + value: srandom + - name: Flawfinder - g_rand_boolean + type: flawfinder_func_name + value: g_rand_boolean + - name: Flawfinder - g_rand_int + type: flawfinder_func_name + value: g_rand_int + - name: Flawfinder - g_rand_int_range + type: flawfinder_func_name + value: g_rand_int_range + - name: Flawfinder - g_rand_double + type: flawfinder_func_name + value: g_rand_double + - name: Flawfinder - g_rand_double_range + type: flawfinder_func_name + value: g_rand_double_range + - name: Flawfinder - g_random_boolean + type: flawfinder_func_name + value: g_random_boolean + - name: Flawfinder - g_random_int + type: flawfinder_func_name + value: g_random_int + - name: Flawfinder - g_random_int_range + type: flawfinder_func_name + value: g_random_int_range + - name: Flawfinder - g_random_double + type: flawfinder_func_name + value: g_random_double + - name: Flawfinder - g_random_double_range + type: flawfinder_func_name + value: g_random_double_range + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.drand48-1.erand48-1.jrand48-1.lcong48-1.lrand48-1.mrand48-1.nrand48-1.random-1.seed48-1.setstate-1.srand-1.strfry-1.srandom-1.g_rand_boolean-1.g_rand_int-1.g_rand_int_range-1.g_rand_double-1.g_rand_double_range-1.g_random_boolean-1.g_random_int-1.g_random_int_range-1.g_random_double-1.g_random_double_range-1 + shortlink: https://sg.run/grno + semgrep.dev: + rule: + r_id: 13085 + rv_id: 920352 + rule_id: lBUzno + version_id: QkT1NAz + url: https://semgrep.dev/playground/r/QkT1NAz/gitlab.flawfinder.drand48-1.erand48-1.jrand48-1.lcong48-1.lrand48-1.mrand48-1.nrand48-1.random-1.seed48-1.setstate-1.srand-1.strfry-1.srandom-1.g_rand_boolean-1.g_rand_int-1.g_rand_int_range-1.g_rand_double-1.g_rand_double_range-1.g_random_boolean-1.g_random_int-1.g_random_int_range-1.g_random_double-1.g_random_double_range-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: drand48(...) + - pattern: erand48(...) + - pattern: jrand48(...) + - pattern: lcong48(...) + - pattern: lrand48(...) + - pattern: mrand48(...) + - pattern: nrand48(...) + - pattern: random(...) + - pattern: seed48(...) + - pattern: setstate(...) + - pattern: srand(...) + - pattern: strfry(...) + - pattern: srandom(...) + - pattern: g_rand_boolean(...) + - pattern: g_rand_int(...) + - pattern: g_rand_int_range(...) + - pattern: g_rand_double(...) + - pattern: g_rand_double_range(...) + - pattern: g_random_boolean(...) + - pattern: g_random_int(...) + - pattern: g_random_int_range(...) + - pattern: g_random_double(...) + - pattern: g_random_double_range(...) + - pattern-regex: "(long|short|double|int|float|void)\\s(\\*|)(\\s|)(seed48|lcong48)(\\(.*\\))\\;" + severity: WARNING +- id: gitlab.flawfinder.equal-1.mismatch-1.is_permutation-1 + languages: + - c + message: | + This function is often discouraged by most C++ coding standards in favor of its safer + alternatives provided since C++14. Consider using a form of this function: + (std::equal, std::mismatch or std::is_permutation) that checks the second iterator + before potentially reading past its bounds. + + For more information please see: https://en.cppreference.com/w/cpp/algorithm + metadata: + shortDescription: Function does not check the second iterator for over-read conditions + cwe: CWE-126 + primary_identifier: flawfinder.equal-1.mismatch-1.is_permutation-1 + secondary_identifiers: + - name: Flawfinder - equal + type: flawfinder_func_name + value: equal + - name: Flawfinder - mismatch + type: flawfinder_func_name + value: mismatch + - name: Flawfinder - is_permutation + type: flawfinder_func_name + value: is_permutation + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.equal-1.mismatch-1.is_permutation-1 + shortlink: https://sg.run/xewe + semgrep.dev: + rule: + r_id: 13030 + rv_id: 835647 + rule_id: JDUQ8Q + version_id: e1TDKo7 + url: https://semgrep.dev/playground/r/e1TDKo7/gitlab.flawfinder.equal-1.mismatch-1.is_permutation-1 + origin: community + category: security + subcategory: + - audit + pattern-either: + - pattern: equal(...) + - pattern: mismatch(...) + - pattern: is_permutation(...) + severity: INFO +- id: gitlab.flawfinder.execl-1.execlp-1.execle-1.execv-1.execvp-1.popen-1.WinExec-1.ShellExecute-1 + languages: + - c + - cpp + message: | + It is generally not recommended to call out to the operating system to execute commands. + When the application is executing file system based commands, user input should never be used + in + constructing commands or command arguments. If possible, determine if a library can be used + instead to provide the same functionality. Otherwise, consider hard coding both the command + and arguments to be used, or at the very least restricting which arguments can be passed + to the command execution function. + + Please see the compliant solutions in the following page: + https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152177 + metadata: + shortDescription: Potential for OS command injection + cwe: CWE-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.execl-1.execlp-1.execle-1.execv-1.execvp-1.popen-1.WinExec-1.ShellExecute-1 + secondary_identifiers: + - name: Flawfinder - execl + type: flawfinder_func_name + value: execl + - name: Flawfinder - execlp + type: flawfinder_func_name + value: execlp + - name: Flawfinder - execle + type: flawfinder_func_name + value: execle + - name: Flawfinder - execv + type: flawfinder_func_name + value: execv + - name: Flawfinder - execvp + type: flawfinder_func_name + value: execvp + - name: Flawfinder - popen + type: flawfinder_func_name + value: popen + - name: Flawfinder - WinExec + type: flawfinder_func_name + value: WinExec + - name: Flawfinder - ShellExecute + type: flawfinder_func_name + value: ShellExecute + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.execl-1.execlp-1.execle-1.execv-1.execvp-1.popen-1.WinExec-1.ShellExecute-1 + shortlink: https://sg.run/4P6g + semgrep.dev: + rule: + r_id: 13088 + rv_id: 920355 + rule_id: oqUr85 + version_id: PkTjG2o + url: https://semgrep.dev/playground/r/PkTjG2o/gitlab.flawfinder.execl-1.execlp-1.execle-1.execv-1.execvp-1.popen-1.WinExec-1.ShellExecute-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: execl(...) + - pattern: execlp(...) + - pattern: execle(...) + - pattern: execv(...) + - pattern: execvp(...) + - pattern: popen(...) + - pattern: WinExec(...) + - pattern: ShellExecute(...) + severity: ERROR +- id: gitlab.flawfinder.fopen-1.open-1 + languages: + - c + - cpp + message: | + Usage of the `open` family of functions may hint at a potential Time Of Check Time Of Use + (TOCTOU) + vulnerability. An attacker may be able to modify the file being specified by the `open` + function prior to the `open` function being called. + + Prior to calling `open`, use `lstat` to open the file and confirm the attributes + are correct. Then use `open` to get a file descriptor to this file. Call `fstat` on the + `open` file descriptor to confirm that `st_dev` and `st_ino` are equal between the two. + If they are, it is safe to read and operate on the file's contents. + + For more information please see: + https://wiki.sei.cmu.edu/confluence/display/c/FIO45-C.+Avoid+TOCTOU+race+conditions+while+accessing+files + metadata: + shortDescription: Potential time of check time of use vulnerability (open/fopen) + cwe: CWE-362 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + category: security + primary_identifier: flawfinder.fopen-1.open-1 + secondary_identifiers: + - name: Flawfinder - fopen + type: flawfinder_func_name + value: fopen + - name: Flawfinder - open + type: flawfinder_func_name + value: open + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.fopen-1.open-1 + shortlink: https://sg.run/w1nx + semgrep.dev: + rule: + r_id: 13073 + rv_id: 920341 + rule_id: PeUBPk + version_id: O9Tv7Qb + url: https://semgrep.dev/playground/r/O9Tv7Qb/gitlab.flawfinder.fopen-1.open-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: fopen(...) + - pattern: open(...) + severity: INFO +- id: gitlab.flawfinder.fprintf-1.vfprintf-1._ftprintf-1._vftprintf-1.fwprintf-1.fvwprintf-1 + languages: + - c + - cpp + message: | + Format string vulnerabilities allow an attacker to read or in some cases, + potentially write data to + and from locations in the processes' memory. To prevent against format + string attacks, do not allow + users or un-validated input to provide the format specification. + Consider using a constant for the format specification, or only allow specific + characters to be provided to the format argument for the `fprintf` family of functions. + + For more information please see: https://linux.die.net/man/3/fprintf + + For more information on format string attacks please see OWASP's attack + guide: https://owasp.org/www-community/attacks/Format_string_attack + metadata: + shortDescription: Potential format string vulnerability + cwe: CWE-134 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.fprintf-1.vfprintf-1._ftprintf-1._vftprintf-1.fwprintf-1.fvwprintf-1 + secondary_identifiers: + - name: Flawfinder - fprintf + type: flawfinder_func_name + value: fprintf + - name: Flawfinder - vfprintf + type: flawfinder_func_name + value: vfprintf + - name: Flawfinder - _ftprintf + type: flawfinder_func_name + value: _ftprintf + - name: Flawfinder - _vftprintf + type: flawfinder_func_name + value: _vftprintf + - name: Flawfinder - fwprintf + type: flawfinder_func_name + value: fwprintf + - name: Flawfinder - fvwprintf + type: flawfinder_func_name + value: fvwprintf + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.fprintf-1.vfprintf-1._ftprintf-1._vftprintf-1.fwprintf-1.fvwprintf-1 + shortlink: https://sg.run/owX7 + semgrep.dev: + rule: + r_id: 13060 + rv_id: 920330 + rule_id: eqUpJj + version_id: X0TAKY0 + url: https://semgrep.dev/playground/r/X0TAKY0/gitlab.flawfinder.fprintf-1.vfprintf-1._ftprintf-1._vftprintf-1.fwprintf-1.fvwprintf-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern: fprintf($FD, $FMT, ...) + - pattern-not: fprintf($FD, "...", ...) + - patterns: + - pattern: vfprintf($FMT, $ARGS, ...) + - pattern-not: vfprintf("...", $ARGS, ...) + - patterns: + - pattern: _ftprintf($FD, $FMT, ...) + - pattern-not: _ftprintf($FD, "...", ...) + - patterns: + - pattern: fwprintf($FD, $FMT, ...) + - pattern-not: fwprintf($FD, "...", ...) + - patterns: + - pattern: fvwprintf($FD, $FMT, ...) + - pattern-not: fvwprintf($FD, "...", ...) + severity: ERROR +- id: gitlab.flawfinder.fscanf-1.sscanf-1.vsscanf-1.vfscanf-1._ftscanf-1.fwscanf-1.vfwscanf-1.vswscanf-1 + languages: + - c + - cpp + message: | + Format specifiers can take optional field widths, which should be + used to limit how many characters are copied into the target buffer. + + Example: + ``` + const char str[20] = "AAAAAAAAAAAAAAAAAAA"; + char buf[11] = {0}; + sscanf(str, "%10s", &buf); // buf = AAAAAAAAAA\0 + ``` + metadata: + shortDescription: sscanf() functions may allow format string based overflows + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.fscanf-1.sscanf-1.vsscanf-1.vfscanf-1._ftscanf-1.fwscanf-1.vfwscanf-1.vswscanf-1 + secondary_identifiers: + - name: Flawfinder - fscanf + type: flawfinder_func_name + value: fscanf + - name: Flawfinder - sscanf + type: flawfinder_func_name + value: sscanf + - name: Flawfinder - vsscanf + type: flawfinder_func_name + value: vsscanf + - name: Flawfinder - vfscanf + type: flawfinder_func_name + value: vfscanf + - name: Flawfinder - _ftscanf + type: flawfinder_func_name + value: _ftscanf + - name: Flawfinder - fwscanf + type: flawfinder_func_name + value: fwscanf + - name: Flawfinder - vfwscanf + type: flawfinder_func_name + value: vfwscanf + - name: Flawfinder - vswscanf + type: flawfinder_func_name + value: vswscanf + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.fscanf-1.sscanf-1.vsscanf-1.vfscanf-1._ftscanf-1.fwscanf-1.vfwscanf-1.vswscanf-1 + shortlink: https://sg.run/O8Xe + semgrep.dev: + rule: + r_id: 13031 + rv_id: 920304 + rule_id: 5rU8bL + version_id: BjTKLyW + url: https://semgrep.dev/playground/r/BjTKLyW/gitlab.flawfinder.fscanf-1.sscanf-1.vsscanf-1.vfscanf-1._ftscanf-1.fwscanf-1.vfwscanf-1.vswscanf-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: fscanf(...) + - pattern: sscanf(...) + - pattern: vsscanf(...) + - pattern: vfscanf(...) + - pattern: _ftscanf(...) + - pattern: fwscanf(...) + - pattern: vfwscanf(...) + - pattern: vswscanf(...) + severity: ERROR +- id: gitlab.flawfinder.g_get_home_dir-1 + languages: + - c + - cpp + message: | + This function is synonymous with `getenv("HOME")` and should be treated + as untrusted input as it could be modified by an attacker. Possible risks + include: + + - The value being too large and causing buffer overflows + - Files under the attacker's control being used maliciously + - Files outside of an attacker's control becoming accessible, depending on + access privileges. + metadata: + shortDescription: Possible use of untrusted environment variable + cwe: CWE-20 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.g_get_home_dir-1 + secondary_identifiers: + - name: Flawfinder - g_get_home_dir + type: flawfinder_func_name + value: g_get_home_dir + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.g_get_home_dir-1 + shortlink: https://sg.run/eK0X + semgrep.dev: + rule: + r_id: 13032 + rv_id: 920305 + rule_id: GdUZpz + version_id: DkT2yw6 + url: https://semgrep.dev/playground/r/DkT2yw6/gitlab.flawfinder.g_get_home_dir-1 + origin: community + subcategory: + - audit + pattern: g_get_home_dir(...) + severity: WARNING +- id: gitlab.flawfinder.g_get_tmp_dir-1 + languages: + - c + - cpp + message: | + This function is synonymous with `getenv("TMP")` and should be treated + as untrusted input as it could be modified by an attacker. Possible risks + include: + + - The value being too large and causing buffer overflows + - Files under the attacker's control being used maliciously + - Files outside of an attacker's control becoming accessible, depending on + access privileges. + metadata: + shortDescription: Possible use of untrusted environment variable + cwe: CWE-20 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.g_get_tmp_dir-1 + secondary_identifiers: + - name: Flawfinder - g_get_tmp_dir + type: flawfinder_func_name + value: g_get_tmp_dir + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.g_get_tmp_dir-1 + shortlink: https://sg.run/v2NX + semgrep.dev: + rule: + r_id: 13033 + rv_id: 920306 + rule_id: ReUojK + version_id: WrTYn7O + url: https://semgrep.dev/playground/r/WrTYn7O/gitlab.flawfinder.g_get_tmp_dir-1 + origin: community + subcategory: + - audit + pattern: g_get_tmp_dir(...) + severity: WARNING +- id: gitlab.flawfinder.getenv-1.curl_getenv-1 + languages: + - c + - cpp + message: | + This function's return value should be treated as untrusted input as it could be + modified by an attacker. Possible risks include: + + - The value being too large and causing buffer overflows + - Files under the attacker's control being used maliciously + - Files outside of an attacker's control becoming accessible, depending on + access privileges. + metadata: + shortDescription: Possible use of untrusted environment variable + cwe: CWE-20 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.getenv-1.curl_getenv-1 + secondary_identifiers: + - name: Flawfinder - getenv + type: flawfinder_func_name + value: getenv + - name: Flawfinder - curl_getenv + type: flawfinder_func_name + value: curl_getenv + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.getenv-1.curl_getenv-1 + shortlink: https://sg.run/ZkO7 + semgrep.dev: + rule: + r_id: 13035 + rv_id: 920307 + rule_id: BYU761 + version_id: 0bTp3G7 + url: https://semgrep.dev/playground/r/0bTp3G7/gitlab.flawfinder.getenv-1.curl_getenv-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: getenv(...) + - pattern: curl_getenv(...) + severity: WARNING +- id: gitlab.flawfinder.getlogin-1 + languages: + - c + - cpp + message: | + The `getlogin` function suffers from many bugs or unknown behaviors depending on the + system. Often, it gives only the first 8 characters of the login name. The user + currently logged in on the controlling TTY of our program does not necessarily mean + it is the user who started the process. + + Use getpwuid(geteuid()) and extract the desired information instead. + + For more information please see: https://linux.die.net/man/3/getpwuid + metadata: + shortDescription: Usage of deprecated function (getlogin) + cwe: CWE-807 + owasp: + - A9:2017-Using Components with Known Vulnerabilities + - A06:2021-Vulnerable and Outdated Components + security-severity: Low + category: security + primary_identifier: flawfinder.getlogin-1 + secondary_identifiers: + - name: Flawfinder - getlogin + type: flawfinder_func_name + value: getlogin + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.getlogin-1 + shortlink: https://sg.run/xene + semgrep.dev: + rule: + r_id: 13074 + rv_id: 920342 + rule_id: JDUQ9Q + version_id: e1TZK4n + url: https://semgrep.dev/playground/r/e1TZK4n/gitlab.flawfinder.getlogin-1 + origin: community + subcategory: + - audit + pattern: getlogin(...) + severity: ERROR +- id: gitlab.flawfinder.getpass-1 + languages: + - c + - cpp + message: | + This function is obsolete and not portable. It was in SUSv2 but removed by POSIX.2. What + it does exactly varies considerably between systems, particularly in where its prompt is + displayed and where it gets its data. Some systems will write to stderr instead of stdout. + Some will read from stdin if it can not be read from /dev/tty. In some systems the + buffer is static and limited to 127 characters, meaning the full password may not be returned + properly. + + If you want to read input without terminal echoing enabled, see the description of the ECHO + flag + in the termios manual pager. If you ever read passwords from a terminal, be sure to zero the + password as soon as possible, to avoid leaving the cleartext password visible in the + process' address space. + metadata: + shortDescription: Usage of deprecated function (getpass) + cwe: CWE-20 + owasp: + - A9:2017-Using Components with Known Vulnerabilities + - A06:2021-Vulnerable and Outdated Components + security-severity: Low + category: security + primary_identifier: flawfinder.getpass-1 + secondary_identifiers: + - name: Flawfinder - getpass + type: flawfinder_func_name + value: getpass + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.getpass-1 + shortlink: https://sg.run/O8We + semgrep.dev: + rule: + r_id: 13075 + rv_id: 920343 + rule_id: 5rU8gL + version_id: vdTvQLq + url: https://semgrep.dev/playground/r/vdTvQLq/gitlab.flawfinder.getpass-1 + origin: community + subcategory: + - audit + pattern: getpass(...) + severity: ERROR +- id: gitlab.flawfinder.getpw-1 + languages: + - c + message: | + The getpw() function is dangerous as it may overflow the provided + buffer when reading from the `/etc/passwd` file. While the passwd file + is not generally writeable, there are no protections offered by this function + to protect from reading past the bounds of the destination buffer. This function + is obsoleted by `getpwuid`. + + For more information please see: https://linux.die.net/man/3/getpwuid + metadata: + shortDescription: Use of deprecated function (getpwd) + cwe: CWE-120 + owasp: A1:2017-Injection + primary_identifier: flawfinder.getpw-1 + secondary_identifiers: + - name: Flawfinder - getpw + type: flawfinder_func_name + value: getpw + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.getpw-1 + shortlink: https://sg.run/EO08 + semgrep.dev: + rule: + r_id: 13037 + rv_id: 835652 + rule_id: WAUP03 + version_id: ExTrWl2 + url: https://semgrep.dev/playground/r/ExTrWl2/gitlab.flawfinder.getpw-1 + origin: community + category: security + subcategory: + - audit + pattern: getpw(...) + severity: ERROR +- id: gitlab.flawfinder.gets-1._getts-1 + languages: + - c + - cpp + message: | + The gets() function reads a line from stdin into the provided buffer + until either a terminating newline or EOF. This terminating newline or + EOF is replaced with a null byte `'\0'`. No check for buffer overruns are + performed so it is recommended to use `fgets()` instead. Do note + that some platforms will continue reading data after a `'\0'` is encountered. + + Usage of `fgets()` is not recommended for reading binary based files or inputs, + instead the `read` or `fread` functions should be used. + + For more information please see: https://linux.die.net/man/3/fgets + metadata: + shortDescription: Use of deprecated function (gets) + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.gets-1._getts-1 + secondary_identifiers: + - name: Flawfinder - gets + type: flawfinder_func_name + value: gets + - name: Flawfinder - _getts + type: flawfinder_func_name + value: _getts + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.gets-1._getts-1 + shortlink: https://sg.run/7G7v + semgrep.dev: + rule: + r_id: 13038 + rv_id: 920308 + rule_id: 0oUJjK + version_id: K3TwLgb + url: https://semgrep.dev/playground/r/K3TwLgb/gitlab.flawfinder.gets-1._getts-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: gets(...) + - pattern: _getts(...) + - pattern: _getws(...) + severity: ERROR +- id: gitlab.flawfinder.getwd-1 + languages: + - c + - cpp + message: | + `getwd` does not contain a parameter to limit how many characters can be copied into the + destination buffer. For portability and security reasons `getwd` has been deprecated in + favor of `getcwd`. + + For more information please see: https://linux.die.net/man/3/getcwd + metadata: + shortDescription: Insufficient protection against buffer overflow (getwd) + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.getwd-1 + secondary_identifiers: + - name: Flawfinder - getwd + type: flawfinder_func_name + value: getwd + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.getwd-1 + shortlink: https://sg.run/L8zL + semgrep.dev: + rule: + r_id: 13039 + rv_id: 920309 + rule_id: KxUY1o + version_id: qkTpwvo + url: https://semgrep.dev/playground/r/qkTpwvo/gitlab.flawfinder.getwd-1 + origin: community + subcategory: + - audit + pattern: getwd(...) + severity: WARNING +- id: gitlab.flawfinder.gsignal-1.ssignal-1 + languages: + - c + - cpp + message: | + The `gsignal` and `ssignal` functions are obsolete and no longer recommended. Consider + using the `raise` or `sigaction` functions instead for process signaling. + + For more information please see: https://linux.die.net/man/3/sigaction + metadata: + shortDescription: Deprecated function calls (ssignal/gsignal) + cwe: CWE-676 + owasp: + - A9:2017-Using Components with Known Vulnerabilities + - A06:2021-Vulnerable and Outdated Components + security-severity: Info + category: security + primary_identifier: flawfinder.gsignal-1.ssignal-1 + secondary_identifiers: + - name: Flawfinder - gsignal + type: flawfinder_func_name + value: gsignal + - name: Flawfinder - ssignal + type: flawfinder_func_name + value: ssignal + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.gsignal-1.ssignal-1 + shortlink: https://sg.run/eKOX + semgrep.dev: + rule: + r_id: 13076 + rv_id: 920344 + rule_id: GdUZdz + version_id: d6T6g8B + url: https://semgrep.dev/playground/r/d6T6g8B/gitlab.flawfinder.gsignal-1.ssignal-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: gsignal(...) + - pattern: ssignal(...) + severity: INFO +- id: gitlab.flawfinder.lstrcat-1.wcscat-1._tcscat-1._mbscat-1 + languages: + - c + - cpp + message: | + The `strcat` family of functions are unable to limit how many bytes are copied + to the destination buffer. It is recommended to use more secure alternatives such as + `snprintf`. + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strcat-s-wcscat-s-mbscat-s?view=msvc-170 + metadata: + shortDescription: Insecure functions unable to limit / check buffer sizes + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.lstrcat-1.wcscat-1._tcscat-1._mbscat-1 + secondary_identifiers: + - name: Flawfinder - lstrcat + type: flawfinder_func_name + value: lstrcat + - name: Flawfinder - wcscat + type: flawfinder_func_name + value: wcscat + - name: Flawfinder - _tcscat + type: flawfinder_func_name + value: _tcscat + - name: Flawfinder - _mbscat + type: flawfinder_func_name + value: _mbscat + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.lstrcat-1.wcscat-1._tcscat-1._mbscat-1 + shortlink: https://sg.run/8R7J + semgrep.dev: + rule: + r_id: 13040 + rv_id: 920310 + rule_id: qNUb3v + version_id: l4TXDpz + url: https://semgrep.dev/playground/r/l4TXDpz/gitlab.flawfinder.lstrcat-1.wcscat-1._tcscat-1._mbscat-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: lstrcat(...) + - pattern: wcscat(...) + - pattern: _tcscat(...) + - pattern: _mbscat(...) + severity: ERROR +- id: gitlab.flawfinder.lstrcatn-1.wcsncat-1._tcsncat-1._mbsnbcat-1 + languages: + - c + - cpp + message: | + Consider using more secure alternatives such as `snprintf`, instead of the + `wcsncat` family of functions. + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strncat-strncat-l-wcsncat-wcsncat-l-mbsncat-mbsncat-l?view=msvc-170 + metadata: + shortDescription: Easily misused string processing functions + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.lstrcatn-1.wcsncat-1._tcsncat-1._mbsnbcat-1 + secondary_identifiers: + - name: Flawfinder - lstrcatn + type: flawfinder_func_name + value: lstrcatn + - name: Flawfinder - wcsncat + type: flawfinder_func_name + value: wcsncat + - name: Flawfinder - _tcsncat + type: flawfinder_func_name + value: _tcsncat + - name: Flawfinder - _mbsnbcat + type: flawfinder_func_name + value: _mbsnbcat + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.lstrcatn-1.wcsncat-1._tcsncat-1._mbsnbcat-1 + shortlink: https://sg.run/grqo + semgrep.dev: + rule: + r_id: 13041 + rv_id: 920311 + rule_id: lBUzGo + version_id: YDTYbwD + url: https://semgrep.dev/playground/r/YDTYbwD/gitlab.flawfinder.lstrcatn-1.wcsncat-1._tcsncat-1._mbsnbcat-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: lstrcatn(...) + - pattern: wcsncat(...) + - pattern: _tcsncat(...) + - pattern: _mbsnbcat(...) + severity: INFO +- id: gitlab.flawfinder.lstrcpy-1.wcscpy-1._tcscpy-1._mbscpy-1 + languages: + - c + - cpp + message: | + The `lstrcpy` family of functions do not provide the ability to limit or check buffer + sizes before copying to a destination buffer. This can lead to buffer overflows. Consider + using more secure alternatives such as `strncpy_s`. + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strncpy-s-strncpy-s-l-wcsncpy-s-wcsncpy-s-l-mbsncpy-s-mbsncpy-s-l?view=msvc-170 + metadata: + shortDescription: Insecure functions unable to limit / check buffer sizes + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.lstrcpy-1.wcscpy-1._tcscpy-1._mbscpy-1 + secondary_identifiers: + - name: Flawfinder - lstrcpy + type: flawfinder_func_name + value: lstrcpy + - name: Flawfinder - wcscpy + type: flawfinder_func_name + value: wcscpy + - name: Flawfinder - _tcscpy + type: flawfinder_func_name + value: _tcscpy + - name: Flawfinder - _mbscpy + type: flawfinder_func_name + value: _mbscpy + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.lstrcpy-1.wcscpy-1._tcscpy-1._mbscpy-1 + shortlink: https://sg.run/Q41D + semgrep.dev: + rule: + r_id: 13042 + rv_id: 920312 + rule_id: YGUQd4 + version_id: JdToRn6 + url: https://semgrep.dev/playground/r/JdToRn6/gitlab.flawfinder.lstrcpy-1.wcscpy-1._tcscpy-1._mbscpy-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: lstrcpy(...) + - pattern: wcscpy(...) + - pattern: _tcscpy(...) + - pattern: _mbscpy(...) + severity: ERROR +- id: gitlab.flawfinder.lstrcpyn-1.wcsncpy-1._tcsncpy-1._mbsnbcpy-1 + languages: + - c + - cpp + message: | + The `lstrcpyn` family of functions do not always check for invalid pointers or check if there + is sufficient space prior to copying. The count argument limits the number of characters copied + but does validate if the count will fit within the size of the destination buffer, leading to + potential overflows. + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strncpy-s-strncpy-s-l-wcsncpy-s-wcsncpy-s-l-mbsncpy-s-mbsncpy-s-l?view=msvc-170 + metadata: + shortDescription: Insecure functions do not always null terminate or check invalid + pointers + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.lstrcpyn-1.wcsncpy-1._tcsncpy-1._mbsnbcpy-1 + secondary_identifiers: + - name: Flawfinder - lstrcpyn + type: flawfinder_func_name + value: lstrcpyn + - name: Flawfinder - wcsncpy + type: flawfinder_func_name + value: wcsncpy + - name: Flawfinder - _tcsncpy + type: flawfinder_func_name + value: _tcsncpy + - name: Flawfinder - _mbsnbcpy + type: flawfinder_func_name + value: _mbsnbcpy + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.lstrcpyn-1.wcsncpy-1._tcsncpy-1._mbsnbcpy-1 + shortlink: https://sg.run/347g + semgrep.dev: + rule: + r_id: 13043 + rv_id: 920313 + rule_id: 6JU6Nz + version_id: 5PTNG7y + url: https://semgrep.dev/playground/r/5PTNG7y/gitlab.flawfinder.lstrcpyn-1.wcsncpy-1._tcsncpy-1._mbsnbcpy-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: lstrcpyn(...) + - pattern: wcsncpy(...) + - pattern: _tcsncpy(...) + - pattern: _mbsnbcpy(...) + severity: INFO +- id: gitlab.flawfinder.memalign-1 + languages: + - c + - cpp + message: | + The `memalign` function may not check that the alignment argument is correct. Calling + free (on non Linux-based systems) may fail and in certain circumstances this failure + may be exploitable. This function has been deprecated in favor of `posix_memalign`. + + For more information please see: https://linux.die.net/man/3/memalign + metadata: + shortDescription: Use of deprecated function (memalign) + cwe: CWE-676 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.memalign-1 + secondary_identifiers: + - name: Flawfinder - memalign + type: flawfinder_func_name + value: memalign + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.memalign-1 + shortlink: https://sg.run/X8wl + semgrep.dev: + rule: + r_id: 13064 + rv_id: 920334 + rule_id: nJUrv6 + version_id: yeTDgql + url: https://semgrep.dev/playground/r/yeTDgql/gitlab.flawfinder.memalign-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: memalign(...) + - pattern-regex: "(void)\\s\\*(\\s|)(memalign)\\;" + severity: INFO +- id: gitlab.flawfinder.memcpy-1.CopyMemory-1.bcopy-1 + languages: + - c + - cpp + message: | + The `memcpy` family of functions require the developer to validate that the destination buffer + is the same size or larger than the source buffer. Buffer overflows could be introduced if care + is not taken to validate buffer sizes. + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/memcpy-s-wmemcpy-s?view=msvc-170 + metadata: + shortDescription: Function does not check for buffer overflows when copying + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.memcpy-1.CopyMemory-1.bcopy-1 + secondary_identifiers: + - name: Flawfinder - memcpy + type: flawfinder_func_name + value: memcpy + - name: Flawfinder - CopyMemory + type: flawfinder_func_name + value: CopyMemory + - name: Flawfinder - bcopy + type: flawfinder_func_name + value: bcopy + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.memcpy-1.CopyMemory-1.bcopy-1 + shortlink: https://sg.run/4P7g + semgrep.dev: + rule: + r_id: 13044 + rv_id: 920314 + rule_id: oqUr65 + version_id: GxToXlo + url: https://semgrep.dev/playground/r/GxToXlo/gitlab.flawfinder.memcpy-1.CopyMemory-1.bcopy-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: memcpy(...) + - pattern: CopyMemory(...) + - pattern: bcopy(...) + severity: INFO +- id: gitlab.flawfinder.mkstemp-1 + languages: + - c + - cpp + message: | + Some older Unix-like systems, `mkstemp` would create temp files with 0666 permissions, + meaning the file created would be read/write access for all users. + + Ensure the process has called the `umask` function with restricted permissions prior + to calling `mkstemp` and validate the permissions prior to using the file descriptor. + + For more information on temporary files please see: + https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152425 + metadata: + shortDescription: Potential file permissions issue (mkstemp) + cwe: CWE-377 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + category: security + primary_identifier: flawfinder.mkstemp-1 + secondary_identifiers: + - name: Flawfinder - mkstemp + type: flawfinder_func_name + value: mkstemp + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.mkstemp-1 + shortlink: https://sg.run/5Jo6 + semgrep.dev: + rule: + r_id: 13091 + rv_id: 920358 + rule_id: 2ZUKJn + version_id: GxToXYo + url: https://semgrep.dev/playground/r/GxToXYo/gitlab.flawfinder.mkstemp-1 + origin: community + subcategory: + - audit + pattern: mkstemp(...) + severity: INFO +- id: gitlab.flawfinder.mktemp-1 + languages: + - c + - cpp + message: | + The `mktemp` function should no longer be used due to multiple flaws. Some implementations + created random files by using known information like the process ID and a single letter. This + allows for possible race conditions where an attacker could guess or manipulate these files + prior to them being used. + + Consider using the `mkstemp` function instead, but be aware it also contains possible + risks. Ensure the process has called the `umask` function with restricted permissions prior + to calling `mkstemp` and validate the permissions prior to using the file descriptor. + + For more information on temporary files please see: + https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152425 + metadata: + shortDescription: Use of deprecated function (mktemp) + cwe: CWE-377 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + category: security + primary_identifier: flawfinder.mktemp-1 + secondary_identifiers: + - name: Flawfinder - mktemp + type: flawfinder_func_name + value: mktemp + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.mktemp-1 + shortlink: https://sg.run/GwPB + semgrep.dev: + rule: + r_id: 13092 + rv_id: 920359 + rule_id: X5U76e + version_id: RGT2xnA + url: https://semgrep.dev/playground/r/RGT2xnA/gitlab.flawfinder.mktemp-1 + origin: community + subcategory: + - audit + pattern: mktemp(...) + severity: ERROR +- id: gitlab.flawfinder.printf-1.vprintf-1.vwprintf-1.vfwprintf-1._vtprintf-1.wprintf-1 + languages: + - c + - cpp + message: | + Format string vulnerabilities allow an attacker to read or in some cases, potentially write + data to + and from locations in the processes' memory. To prevent against format string attacks, do not + allow + users or un-validated input to provide the format specification. + Consider using a constant for the format specification, or only allow specific + characters to be provided to the format argument for the `printf` family of functions. + + For more information please see: https://linux.die.net/man/3/fprintf + + For more information on format string attacks please see OWASP's attack guide: + https://owasp.org/www-community/attacks/Format_string_attack + metadata: + shortDescription: Potential format string vulnerability + cwe: CWE-134 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.printf-1.vprintf-1.vwprintf-1.vfwprintf-1._vtprintf-1.wprintf-1 + secondary_identifiers: + - name: Flawfinder - printf + type: flawfinder_func_name + value: printf + - name: Flawfinder - vprintf + type: flawfinder_func_name + value: vprintf + - name: Flawfinder - vwprintf + type: flawfinder_func_name + value: vwprintf + - name: Flawfinder - vfwprintf + type: flawfinder_func_name + value: vfwprintf + - name: Flawfinder - _vtprintf + type: flawfinder_func_name + value: _vtprintf + - name: Flawfinder - wprintf + type: flawfinder_func_name + value: wprintf + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.printf-1.vprintf-1.vwprintf-1.vfwprintf-1._vtprintf-1.wprintf-1 + shortlink: https://sg.run/z9Oz + semgrep.dev: + rule: + r_id: 13061 + rv_id: 920331 + rule_id: v8UjyR + version_id: jQTwj14 + url: https://semgrep.dev/playground/r/jQTwj14/gitlab.flawfinder.printf-1.vprintf-1.vwprintf-1.vfwprintf-1._vtprintf-1.wprintf-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern: printf(...) + - pattern-not: printf("...",...) + - patterns: + - pattern: vprintf($FMT, ...) + - pattern-not: vprintf("...", ...) + - patterns: + - pattern: vwprintf($FMT, ...) + - pattern-not: vwprintf("...", ...) + - patterns: + - pattern: vfwprintf($FILE, $FMT, ...) + - pattern-not: vfwprintf($FILE, "...", ...) + - patterns: + - pattern: _vtprintf($FILE, $FMT, ...) + - pattern-not: _vtprintf($FILE, "...", ...) + - patterns: + - pattern: wprintf($FMT, ...) + - pattern-not: wprintf("...", ...) + severity: ERROR +- id: gitlab.flawfinder.readlink-1 + languages: + - c + - cpp + message: | + Usage of the `readlink` function call hints at a potential Time Of Check Time Of Use (TOCTOU) + vulnerability. An attacker may be able to modify the file being specified by the `readlink` + function prior to the `readlink` function being called. Additionally, care must be taken + that the buffer provided is large enough to hold the contents of the file. + + Instead of using `readlink`, use `lstat` prior to opening the file and confirm the attributes + are correct. Then use `open` to get a file descriptor to this file. Call `fstat` on the + `open` file descriptor to confirm that `st_dev` and `st_ino` are equal between the two. + If they are, it is safe to read and operate on the file's contents. + + For more information please see: + https://wiki.sei.cmu.edu/confluence/display/c/FIO45-C.+Avoid+TOCTOU+race+conditions+while+accessing+files + metadata: + shortDescription: Potential time of check time of use vulnerability (readlink) + cwe: CWE-20 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + category: security + primary_identifier: flawfinder.readlink-1 + secondary_identifiers: + - name: Flawfinder - readlink + type: flawfinder_func_name + value: readlink + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.readlink-1 + shortlink: https://sg.run/L8AL + semgrep.dev: + rule: + r_id: 13083 + rv_id: 920350 + rule_id: KxUYWo + version_id: 8KTvlg4 + url: https://semgrep.dev/playground/r/8KTvlg4/gitlab.flawfinder.readlink-1 + origin: community + subcategory: + - audit + pattern: readlink(...) + severity: ERROR +- id: gitlab.flawfinder.realpath-1 + languages: + - c + - cpp + message: | + The `realpath` function should not be called with a destination buffer as it could + lead to overflowing if the path is greater than PATH_LEN. It is instead recommended + to call `realpath` with the destination buffer set to NULL and use the return value + as the resolved path. Be sure to free the returned pointer as realpath will allocate + the buffer internally using `malloc`. + + For more information see: https://linux.die.net/man/3/realpath + + Example: + + ``` + char const *symlink_path = "/tmp/symlink"; + char *resolved_path = NULL; + + resolved_path = realpath(symlink_path, NULL); + if (errno == 0) { + // ... use resolved_path... + free(resolved_path); + } + ``` + metadata: + shortDescription: Function does not ensure destination buffer length is sufficient + before copying + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.realpath-1 + secondary_identifiers: + - name: Flawfinder - realpath + type: flawfinder_func_name + value: realpath + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.realpath-1 + shortlink: https://sg.run/P8jN + semgrep.dev: + rule: + r_id: 13045 + rv_id: 920315 + rule_id: zdU1EX + version_id: RGT2xEA + url: https://semgrep.dev/playground/r/RGT2xEA/gitlab.flawfinder.realpath-1 + origin: community + subcategory: + - audit + pattern: realpath(...) + severity: WARNING +- id: gitlab.flawfinder.scanf-1.vscanf-1.wscanf-1._tscanf-1.vwscanf-1 + languages: + - c + - cpp + message: | + Format specifiers can take optional field widths, which should be + used to limit how many characters are copied into the target buffer. + + For more information please see: https://linux.die.net/man/3/scanf + + Example: + ``` + char buf[11] = {0}; + scanf("%10s", &buf); // buf = AAAAAAAAAA\0 + ``` + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/scanf-s-scanf-s-l-wscanf-s-wscanf-s-l?view=msvc-170 + metadata: + shortDescription: scanf() functions may allow format string based overflows + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.scanf-1.vscanf-1.wscanf-1._tscanf-1.vwscanf-1 + secondary_identifiers: + - name: Flawfinder - scanf + type: flawfinder_func_name + value: scanf + - name: Flawfinder - vscanf + type: flawfinder_func_name + value: vscanf + - name: Flawfinder - wscanf + type: flawfinder_func_name + value: wscanf + - name: Flawfinder - _tscanf + type: flawfinder_func_name + value: _tscanf + - name: Flawfinder - vwscanf + type: flawfinder_func_name + value: vwscanf + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.scanf-1.vscanf-1.wscanf-1._tscanf-1.vwscanf-1 + shortlink: https://sg.run/Jj6o + semgrep.dev: + rule: + r_id: 13046 + rv_id: 920316 + rule_id: pKUw5J + version_id: A8TNlE5 + url: https://semgrep.dev/playground/r/A8TNlE5/gitlab.flawfinder.scanf-1.vscanf-1.wscanf-1._tscanf-1.vwscanf-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern: scanf($FMT, ...) + - pattern-not: scanf("...", ...) + - patterns: + - pattern: vscanf($FMT, ...) + - pattern-not: vscanf("...", ...) + - patterns: + - pattern: wscanf($FMT, ...) + - pattern-not: wscanf("...", ...) + - patterns: + - pattern: _tscanf($FMT, ...) + - pattern-not: _tscanf(_T("..."), ...) + - patterns: + - pattern: vwscanf(FMT, ...) + - pattern-not: vwscanf("...", ...) + severity: ERROR +- id: gitlab.flawfinder.snprintf-1.vsnprintf-1._snprintf-1._sntprintf-1._vsntprintf-1 + languages: + - c + - cpp + message: | + Format string vulnerabilities allow an attacker to read or in some cases, potentially write + data to + and from locations in the processes' memory. To prevent against format string attacks, do not + allow + users or un-validated input to provide the format specification. + Consider using a constant for the format specification, or strip all format + specifiers from the input prior to calling the `snprintf` family of functions. + + Note that some variations of this function do not always null terminate the strings. + + For more information on using snprintf please see: https://linux.die.net/man/3/snprintf + + For more information on format string attacks please see OWASP's attack guide: + https://owasp.org/www-community/attacks/Format_string_attack + metadata: + shortDescription: Potential format string vulnerability + cwe: CWE-134 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.snprintf-1.vsnprintf-1._snprintf-1._sntprintf-1._vsntprintf-1 + secondary_identifiers: + - name: Flawfinder - snprintf + type: flawfinder_func_name + value: snprintf + - name: Flawfinder - vsnprintf + type: flawfinder_func_name + value: vsnprintf + - name: Flawfinder - _snprintf + type: flawfinder_func_name + value: _snprintf + - name: Flawfinder - _sntprintf + type: flawfinder_func_name + value: _sntprintf + - name: Flawfinder - _vsntprintf + type: flawfinder_func_name + value: _vsntprintf + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.snprintf-1.vsnprintf-1._snprintf-1._sntprintf-1._vsntprintf-1 + shortlink: https://sg.run/pkj3 + semgrep.dev: + rule: + r_id: 13062 + rv_id: 920332 + rule_id: d8UlJZ + version_id: 1QT4NEr + url: https://semgrep.dev/playground/r/1QT4NEr/gitlab.flawfinder.snprintf-1.vsnprintf-1._snprintf-1._sntprintf-1._vsntprintf-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern: snprintf($BUF,$SIZE,$FMT,...) + - pattern-not: snprintf($BUF,$SIZE,"...",...) + - patterns: + - pattern: vsnprintf($BUF,$SIZE,$FMT) + - pattern-not: vsnprintf($BUF,$SIZE,"...",...) + - patterns: + - pattern: _snprintf($BUF,$SIZE,$FMT,...) + - pattern-not: _snprintf($BUF,$SIZE,$FMT,"...",...) + - patterns: + - pattern: _sntprintf($VAR,$FMT,...) + - pattern-not: sntprintf($VAR,"...",...) + - patterns: + - pattern: _vsntprintf($VAR,$FMT,...) + - pattern-not: _vsntprintf($VAR,"...",...) + severity: ERROR +- id: gitlab.flawfinder.sprintf-1.vsprintf-1.swprintf-1.vswprintf-1._stprintf-1._vstprintf-1 + languages: + - c + - cpp + message: | + Use sprintf_s, snprintf, or vsnprintf instead. The `sprintf` family of functions do not allow + callers to set limits on how many bytes the destination buffer can hold. Consider using more + secure alternatives such as `snprintf`. + + For more information please see: https://linux.die.net/man/3/snprintf + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/sprintf-s-sprintf-s-l-swprintf-s-swprintf-s-l?view=msvc-170 + metadata: + shortDescription: Insecure function unable to limit / check buffer sizes + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.sprintf-1.vsprintf-1.swprintf-1.vswprintf-1._stprintf-1._vstprintf-1 + secondary_identifiers: + - name: Flawfinder - sprintf + type: flawfinder_func_name + value: sprintf + - name: Flawfinder - vsprintf + type: flawfinder_func_name + value: vsprintf + - name: Flawfinder - swprintf + type: flawfinder_func_name + value: swprintf + - name: Flawfinder - vswprintf + type: flawfinder_func_name + value: vswprintf + - name: Flawfinder - _stprintf + type: flawfinder_func_name + value: _stprintf + - name: Flawfinder - _vstprintf + type: flawfinder_func_name + value: _vstprintf + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.sprintf-1.vsprintf-1.swprintf-1.vswprintf-1._stprintf-1._vstprintf-1 + shortlink: https://sg.run/5J76 + semgrep.dev: + rule: + r_id: 13047 + rv_id: 920317 + rule_id: 2ZUK9n + version_id: BjTKLyp + url: https://semgrep.dev/playground/r/BjTKLyp/gitlab.flawfinder.sprintf-1.vsprintf-1.swprintf-1.vswprintf-1._stprintf-1._vstprintf-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: sprintf(...) + - pattern: vsprintf(...) + - pattern: swprintf(...) + - pattern: vswprintf(...) + - pattern: _stprintf(...) + - pattern: _vstprintf(...) + severity: ERROR +- id: gitlab.flawfinder.strcat-1 + languages: + - c + - cpp + message: | + The `strcat` family of functions are unable to limit how many bytes are copied + to the destination buffer. It is recommended to use more secure alternatives such as + `snprintf`. + + For more information please see: https://linux.die.net/man/3/snprintf + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strcat-s-wcscat-s-mbscat-s?view=msvc-170 + metadata: + shortDescription: Insecure string processing function + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.strcat-1 + secondary_identifiers: + - name: Flawfinder - strcat + type: flawfinder_func_name + value: strcat + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.strcat-1 + shortlink: https://sg.run/GwqB + semgrep.dev: + rule: + r_id: 13048 + rv_id: 920318 + rule_id: X5U7re + version_id: DkT2ywR + url: https://semgrep.dev/playground/r/DkT2ywR/gitlab.flawfinder.strcat-1 + origin: community + subcategory: + - audit + pattern: strcat(...) + severity: ERROR +- id: gitlab.flawfinder.strccpy-1.strcadd-1 + languages: + - c + - cpp + message: | + The `strccpy` and `strcadd` functions do not allow the caller to check that the destination + size + of the buffer will fit the input buffer prior to copying. + + For more information please see: + https://docs.oracle.com/cd/E18752_01/html/816-5172/streadd-3gen.html + metadata: + shortDescription: Insecure string processing functions + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.strccpy-1.strcadd-1 + secondary_identifiers: + - name: Flawfinder - strccpy + type: flawfinder_func_name + value: strccpy + - name: Flawfinder - strcadd + type: flawfinder_func_name + value: strcadd + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.strccpy-1.strcadd-1 + shortlink: https://sg.run/RP9E + semgrep.dev: + rule: + r_id: 13049 + rv_id: 920319 + rule_id: j2URoA + version_id: WrTYn78 + url: https://semgrep.dev/playground/r/WrTYn78/gitlab.flawfinder.strccpy-1.strcadd-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: strccpy(...) + - pattern: strcadd(...) + severity: INFO +- id: gitlab.flawfinder.strcpy-1 + languages: + - c + - cpp + message: | + The `strcpy` family of functions do not provide the ability to limit or check buffer + sizes before copying to a destination buffer. This can lead to buffer overflows. Consider + using more secure alternatives such as `strncpy` and provide the correct limit to the + destination buffer and ensure the string is null terminated. + + For more information please see: https://linux.die.net/man/3/strncpy + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strncpy-s-strncpy-s-l-wcsncpy-s-wcsncpy-s-l-mbsncpy-s-mbsncpy-s-l?view=msvc-170 + metadata: + shortDescription: Insecure string processing function (strcpy) + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.strcpy-1 + secondary_identifiers: + - name: Flawfinder - strcpy + type: flawfinder_func_name + value: strcpy + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.strcpy-1 + shortlink: https://sg.run/AwAg + semgrep.dev: + rule: + r_id: 13050 + rv_id: 920320 + rule_id: 10Ue1w + version_id: 0bTp3GG + url: https://semgrep.dev/playground/r/0bTp3GG/gitlab.flawfinder.strcpy-1 + origin: community + subcategory: + - audit + pattern: strcpy(...) + severity: ERROR +- id: gitlab.flawfinder.strcpyA-1.strcpyW-1.StrCpy-1.StrCpyA-1.lstrcpyA-1.lstrcpyW-1._tccpy-1._mbccpy-1._ftcscpy-1._mbsncpy-1.StrCpyN-1.StrCpyNA-1.StrCpyNW-1.StrNCpy-1.strcpynA-1.StrNCpyA-1.StrNCpyW-1.lstrcpynA-1.lstrcpynW-1 + languages: + - c + - cpp + message: | + The `StrCpy` family of functions do not guarantee the final string to be null terminated. + Consider + using one of the following alternatives `StringCbCopy`, `StringCbCopyEx`, `StringCbCopyN`, + `StringCbCopyNEx`, `StringCchCopy`, `StringCchCopyEx`, `StringCchCopyN`, or `StringCchCopyNEx`. + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strncpy-s-strncpy-s-l-wcsncpy-s-wcsncpy-s-l-mbsncpy-s-mbsncpy-s-l?view=msvc-170 + metadata: + shortDescription: Insecure string processing function + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.strcpyA-1.strcpyW-1.StrCpy-1.StrCpyA-1.lstrcpyA-1.lstrcpyW-1._tccpy-1._mbccpy-1._ftcscpy-1._mbsncpy-1.StrCpyN-1.StrCpyNA-1.StrCpyNW-1.StrNCpy-1.strcpynA-1.StrNCpyA-1.StrNCpyW-1.lstrcpynA-1.lstrcpynW-1 + secondary_identifiers: + - name: Flawfinder - strcpyA + type: flawfinder_func_name + value: strcpyA + - name: Flawfinder - strcpyW + type: flawfinder_func_name + value: strcpyW + - name: Flawfinder - StrCpy + type: flawfinder_func_name + value: StrCpy + - name: Flawfinder - StrCpyA + type: flawfinder_func_name + value: StrCpyA + - name: Flawfinder - lstrcpyA + type: flawfinder_func_name + value: lstrcpyA + - name: Flawfinder - lstrcpyW + type: flawfinder_func_name + value: lstrcpyW + - name: Flawfinder - _tccpy + type: flawfinder_func_name + value: _tccpy + - name: Flawfinder - _mbccpy + type: flawfinder_func_name + value: _mbccpy + - name: Flawfinder - _ftcscpy + type: flawfinder_func_name + value: _ftcscpy + - name: Flawfinder - _mbsncpy + type: flawfinder_func_name + value: _mbsncpy + - name: Flawfinder - StrCpyN + type: flawfinder_func_name + value: StrCpyN + - name: Flawfinder - StrCpyNA + type: flawfinder_func_name + value: StrCpyNA + - name: Flawfinder - StrCpyNW + type: flawfinder_func_name + value: StrCpyNW + - name: Flawfinder - StrNCpy + type: flawfinder_func_name + value: StrNCpy + - name: Flawfinder - strcpynA + type: flawfinder_func_name + value: strcpynA + - name: Flawfinder - StrNCpyA + type: flawfinder_func_name + value: StrNCpyA + - name: Flawfinder - StrNCpyW + type: flawfinder_func_name + value: StrNCpyW + - name: Flawfinder - lstrcpynA + type: flawfinder_func_name + value: lstrcpynA + - name: Flawfinder - lstrcpynW + type: flawfinder_func_name + value: lstrcpynW + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.strcpyA-1.strcpyW-1.StrCpy-1.StrCpyA-1.lstrcpyA-1.lstrcpyW-1._tccpy-1._mbccpy-1._ftcscpy-1._mbsncpy-1.StrCpyN-1.StrCpyNA-1.StrCpyNW-1.StrNCpy-1.strcpynA-1.StrNCpyA-1.StrNCpyW-1.lstrcpynA-1.lstrcpynW-1 + shortlink: https://sg.run/BLBb + semgrep.dev: + rule: + r_id: 13051 + rv_id: 920321 + rule_id: 9AUkxG + version_id: K3TwLg8 + url: https://semgrep.dev/playground/r/K3TwLg8/gitlab.flawfinder.strcpyA-1.strcpyW-1.StrCpy-1.StrCpyA-1.lstrcpyA-1.lstrcpyW-1._tccpy-1._mbccpy-1._ftcscpy-1._mbsncpy-1.StrCpyN-1.StrCpyNA-1.StrCpyNW-1.StrNCpy-1.strcpynA-1.StrNCpyA-1.StrNCpyW-1.lstrcpynA-1.lstrcpynW-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: strcpyA(...) + - pattern: strcpyW(...) + - pattern: StrCpy(...) + - pattern: StrCpyA(...) + - pattern: lstrcpyA(...) + - pattern: lstrcpyW(...) + - pattern: _tccpy(...) + - pattern: _mbccpy(...) + - pattern: _ftcscpy(...) + - pattern: _mbsncpy(...) + - pattern: StrCpyN(...) + - pattern: StrCpyNA(...) + - pattern: StrCpyNW(...) + - pattern: StrNCpy(...) + - pattern: strcpynA(...) + - pattern: StrNCpyA(...) + - pattern: StrNCpyW(...) + - pattern: lstrcpynA(...) + - pattern: lstrcpynW(...) + severity: ERROR +- id: gitlab.flawfinder.streadd-1.strecpy-1 + languages: + - c + - cpp + message: | + The `strecpy` and `streadd` functions require that the destination buffer size be at least + four + times the size of the source due to each character potentially becoming a `\` and 3 digits. + + For more information please see: + https://docs.oracle.com/cd/E18752_01/html/816-5172/streadd-3gen.html + metadata: + shortDescription: Insecure string processing functions + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.streadd-1.strecpy-1 + secondary_identifiers: + - name: Flawfinder - streadd + type: flawfinder_func_name + value: streadd + - name: Flawfinder - strecpy + type: flawfinder_func_name + value: strecpy + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.streadd-1.strecpy-1 + shortlink: https://sg.run/DwW2 + semgrep.dev: + rule: + r_id: 13052 + rv_id: 920322 + rule_id: yyUyKE + version_id: qkTpwvJ + url: https://semgrep.dev/playground/r/qkTpwvJ/gitlab.flawfinder.streadd-1.strecpy-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: streadd(...) + - pattern: strecpy(...) + severity: ERROR +- id: gitlab.flawfinder.strlen-1.wcslen-1._tcslen-1._mbslen-1 + languages: + - c + - cpp + message: | + The `strlen` family of functions does not handle strings that are not null + terminated. This can lead to buffer over reads and cause the application to + crash by accessing unintended memory locations. It is recommended that `strnlen` + be used instead as a `maxlen` value can be provided. + + For more information please see: https://linux.die.net/man/3/strnlen + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strnlen-strnlen-s?view=msvc-170 + metadata: + shortDescription: Function does not handle null terminated strings properly + cwe: CWE-126 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.strlen-1.wcslen-1._tcslen-1._mbslen-1 + secondary_identifiers: + - name: Flawfinder - strlen + type: flawfinder_func_name + value: strlen + - name: Flawfinder - wcslen + type: flawfinder_func_name + value: wcslen + - name: Flawfinder - _tcslen + type: flawfinder_func_name + value: _tcslen + - name: Flawfinder - _mbslen + type: flawfinder_func_name + value: _mbslen + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.strlen-1.wcslen-1._tcslen-1._mbslen-1 + shortlink: https://sg.run/WOky + semgrep.dev: + rule: + r_id: 13053 + rv_id: 920323 + rule_id: r6U9Qq + version_id: l4TXDp2 + url: https://semgrep.dev/playground/r/l4TXDp2/gitlab.flawfinder.strlen-1.wcslen-1._tcslen-1._mbslen-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: strlen(...) + - pattern: wcslen(...) + - pattern: _tcslen(...) + - pattern: _mbslen(...) + severity: INFO +- id: gitlab.flawfinder.strncat-1 + languages: + - c + - cpp + message: | + The `strncat` family of functions are easy to use incorrectly when calculating destination + buffer + sizes. It is recommended to use more secure alternatives such as `snprintf`. + + For more information please see: https://linux.die.net/man/3/snprintf + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strncat-s-strncat-s-l-wcsncat-s-wcsncat-s-l-mbsncat-s-mbsncat-s-l?view=msvc-170 + metadata: + shortDescription: Function does not handle null terminated strings or invalid + pointers properly + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.strncat-1 + secondary_identifiers: + - name: Flawfinder - strncat + type: flawfinder_func_name + value: strncat + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.strncat-1 + shortlink: https://sg.run/057k + semgrep.dev: + rule: + r_id: 13054 + rv_id: 920324 + rule_id: bwUN2p + version_id: YDTYbw8 + url: https://semgrep.dev/playground/r/YDTYbw8/gitlab.flawfinder.strncat-1 + origin: community + subcategory: + - audit + pattern: strncat(...) + severity: INFO +- id: gitlab.flawfinder.strncpy-1 + languages: + - c + - cpp + message: | + The `strncpy` family of functions do not properly handle strings that are not null terminated. + It is recommended to use more secure alternatives such as `snprintf`. + + For more information please see: https://linux.die.net/man/3/snprintf + + If developing for C Runtime Library (CRT), more secure versions of these functions should be + used, see: + https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strncpy-s-strncpy-s-l-wcsncpy-s-wcsncpy-s-l-mbsncpy-s-mbsncpy-s-l?view=msvc-170 + metadata: + shortDescription: Function does not handle null terminated strings or invalid + pointers properly + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.strncpy-1 + secondary_identifiers: + - name: Flawfinder - strncpy + type: flawfinder_func_name + value: strncpy + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.strncpy-1 + shortlink: https://sg.run/K8oP + semgrep.dev: + rule: + r_id: 13055 + rv_id: 920325 + rule_id: NbUY74 + version_id: 6xTyXRA + url: https://semgrep.dev/playground/r/6xTyXRA/gitlab.flawfinder.strncpy-1 + origin: community + subcategory: + - audit + pattern: strncpy(...) + severity: INFO +- id: gitlab.flawfinder.strtrns-1 + languages: + - c + - cpp + message: | + This function is easy to misuse by not accounting for the space necessary when transforming + strings. Ensure that the destination buffer is large enough to fit the transformed output. + + For more information please see: + https://docs.oracle.com/cd/E36784_01/html/E36877/strtrns-3gen.html + metadata: + shortDescription: Insecure string processing function + cwe: CWE-120 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.strtrns-1 + secondary_identifiers: + - name: Flawfinder - strtrns + type: flawfinder_func_name + value: strtrns + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.strtrns-1 + shortlink: https://sg.run/qq11 + semgrep.dev: + rule: + r_id: 13056 + rv_id: 920326 + rule_id: kxU811 + version_id: o5TK1LP + url: https://semgrep.dev/playground/r/o5TK1LP/gitlab.flawfinder.strtrns-1 + origin: community + subcategory: + - audit + pattern: strtrns(...) + severity: WARNING +- id: gitlab.flawfinder.syslog-1 + languages: + - c + - cpp + message: | + Format string vulnerabilities allow an attacker to read or in some cases, potentially write + data to + and from locations in the processes' memory. To prevent against format string attacks, do not + allow + users or un-validated input to provide the format specification. + Consider using a constant for the format specification, or strip all format + specifiers from the input prior to calling the `syslog` function. + + For more information please see: https://capec.mitre.org/data/definitions/67.html + metadata: + shortDescription: Potential format string vulnerability in syslog call + cwe: CWE-134 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.syslog-1 + secondary_identifiers: + - name: Flawfinder - syslog + type: flawfinder_func_name + value: syslog + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.syslog-1 + shortlink: https://sg.run/2R7z + semgrep.dev: + rule: + r_id: 13063 + rv_id: 920333 + rule_id: ZqUgoz + version_id: 9lTA732 + url: https://semgrep.dev/playground/r/9lTA732/gitlab.flawfinder.syslog-1 + origin: community + subcategory: + - audit + pattern-either: + - patterns: + - pattern: syslog($FUNC,...) + - pattern-not: syslog($FUNC,"...",...) + severity: ERROR +- id: gitlab.flawfinder.system-1 + languages: + - c + - cpp + message: | + It is generally not recommended to call out to the operating system to execute commands. + When the application is executing file system based commands, user input should never be used + in + constructing commands or command arguments. If possible, determine if a library can be used + instead to provide the same functionality. Otherwise, consider hard coding both the command + and arguments to be used, or at the very least restricting which arguments can be passed + to the command execution function. + + For more information please see: + https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152177 + metadata: + shortDescription: Potential for OS command injection + cwe: CWE-78 + owasp: + - A1:2017-Injection + - A03:2021-Injection + security-severity: High + category: security + primary_identifier: flawfinder.system-1 + secondary_identifiers: + - name: Flawfinder - system + type: flawfinder_func_name + value: system + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.system-1 + shortlink: https://sg.run/P80N + semgrep.dev: + rule: + r_id: 13089 + rv_id: 920356 + rule_id: zdU17X + version_id: JdToRG6 + url: https://semgrep.dev/playground/r/JdToRG6/gitlab.flawfinder.system-1 + origin: community + subcategory: + - audit + pattern: system(...) + severity: ERROR +- id: gitlab.flawfinder.tmpfile-1 + languages: + - c + - cpp + message: | + There exists a possible race condition in between the time that `tmpfile` returns + a pathname, and the time that the program opens it, another program might create + that pathname using `open`, or create it as a symbolic link. + + Consider using the `mkstemp` function instead, but be aware it also contains possible + risks. Ensure the process has called the `umask` function with restricted permissions prior + to calling `mkstemp` and validate the permissions prior to using the file descriptor. + + For more information on temporary files please see: + https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152425 + metadata: + shortDescription: Potential time of check time of use vulnerability (tmpfile) + cwe: CWE-377 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + category: security + primary_identifier: flawfinder.tmpfile-1 + secondary_identifiers: + - name: Flawfinder - tmpfile + type: flawfinder_func_name + value: tmpfile + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.tmpfile-1 + shortlink: https://sg.run/RPqE + semgrep.dev: + rule: + r_id: 13093 + rv_id: 920360 + rule_id: j2UR7A + version_id: A8TNl05 + url: https://semgrep.dev/playground/r/A8TNl05/gitlab.flawfinder.tmpfile-1 + origin: community + subcategory: + - audit + pattern: tmpfile(...) + severity: INFO +- id: gitlab.flawfinder.tmpnam-1.tempnam-1 + languages: + - c + - cpp + message: | + There exists a possible race condition in between the time that `tempnam` or `tmpnam` + returns a pathname, and the time that the program opens it, another program might create + that pathname using `open`, or create it as a symbolic link. + + Consider using the `mkstemp` function instead, but be aware it also contains possible + risks. Ensure the process has called the `umask` function with restricted permissions prior + to calling `mkstemp` and validate the permissions prior to using the file descriptor. + + For more information on temporary files please see: + https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152425 + metadata: + shortDescription: Potential time of check time of use vulnerability (tmpnam/tempnam) + cwe: CWE-377 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + category: security + primary_identifier: flawfinder.tmpnam-1.tempnam-1 + secondary_identifiers: + - name: Flawfinder - tmpnam + type: flawfinder_func_name + value: tmpnam + - name: Flawfinder - tempnam + type: flawfinder_func_name + value: tempnam + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.tmpnam-1.tempnam-1 + shortlink: https://sg.run/Awkg + semgrep.dev: + rule: + r_id: 13094 + rv_id: 920361 + rule_id: 10Ueqw + version_id: BjTKLJp + url: https://semgrep.dev/playground/r/BjTKLJp/gitlab.flawfinder.tmpnam-1.tempnam-1 + origin: community + subcategory: + - audit + pattern-either: + - pattern: tmpnam(...) + - pattern: tempnam(...) + severity: WARNING +- id: gitlab.flawfinder.ulimit-1 + languages: + - c + - cpp + message: | + The ulimit function is obsolete and no longer recommended. Use `getrlimit(2)`, + `setrlimit`, or `sysconf` instead. + + For more information please see: https://linux.die.net/man/3/setrlimit + metadata: + shortDescription: Usage of deprecated function (ulimit) + cwe: CWE-676 + owasp: + - A9:2017-Using Components with Known Vulnerabilities + - A06:2021-Vulnerable and Outdated Components + security-severity: Info + category: security + primary_identifier: flawfinder.ulimit-1 + secondary_identifiers: + - name: Flawfinder - ulimit + type: flawfinder_func_name + value: ulimit + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.ulimit-1 + shortlink: https://sg.run/v2nX + semgrep.dev: + rule: + r_id: 13077 + rv_id: 920345 + rule_id: ReUo4K + version_id: ZRTedDw + url: https://semgrep.dev/playground/r/ZRTedDw/gitlab.flawfinder.ulimit-1 + origin: community + subcategory: + - audit + pattern: ulimit(...) + severity: INFO +- id: gitlab.flawfinder.umask-1 + languages: + - c + - cpp + message: | + The umask function call sets the process's file mode creation mask. umask values determine + what permissions a file should be created with and who can read or write to these files. + Ensure that umask is given most restrictive possible setting depending on the context, + usually 066 or 077, for more information please see: + https://en.wikipedia.org/wiki/Umask#Mask_effect. + metadata: + shortDescription: Ensure restrictive umask values + cwe: CWE-732 + owasp: + - A6:2017-Security Misconfiguration + - A05:2021-Security Misconfiguration + security-severity: High + category: security + primary_identifier: flawfinder.umask-1 + secondary_identifiers: + - name: Flawfinder - umask + type: flawfinder_func_name + value: umask + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.umask-1 + shortlink: https://sg.run/brBZ + semgrep.dev: + rule: + r_id: 13026 + rv_id: 920301 + rule_id: KxUY1n + version_id: GxToXq2 + url: https://semgrep.dev/playground/r/GxToXq2/gitlab.flawfinder.umask-1 + origin: community + subcategory: + - audit + pattern: umask(...) + severity: INFO +- id: gitlab.flawfinder.usleep-1 + languages: + - c + - cpp + message: | + The `usleep` function has been deprecated, use `nanosleep` or `setitimer` instead. + + For more information please see: https://linux.die.net/man/3/setitimer + metadata: + shortDescription: Usage of deprecated function (usleep) + cwe: CWE-676 + owasp: + - A9:2017-Using Components with Known Vulnerabilities + - A06:2021-Vulnerable and Outdated Components + security-severity: Info + category: security + primary_identifier: flawfinder.usleep-1 + secondary_identifiers: + - name: Flawfinder - usleep + type: flawfinder_func_name + value: usleep + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.usleep-1 + shortlink: https://sg.run/d0xP + semgrep.dev: + rule: + r_id: 13078 + rv_id: 920346 + rule_id: AbUGoN + version_id: nWTnNQe + url: https://semgrep.dev/playground/r/nWTnNQe/gitlab.flawfinder.usleep-1 + origin: community + subcategory: + - audit + pattern: usleep(...) + severity: INFO +- id: gitlab.flawfinder.vfork-1 + languages: + - c + - cpp + message: | + The `vfork` function is suffers from portability issues and is not recommended. In + some Linux systems `vfork` is vulnerable to a race condition while the child process + is running as the user's UID but hasn't executed `execve`. The user may be able to send + signals to this process, which in `vfork` would not be sent to the parent process. As + a result a user may be able to cause a denial of service against the privileged process. + + Use `fork` instead and be aware of other potential Time Of Check Time Of Use (TOCTOU) + vulnerabilities. + + For more information please see: + https://wiki.sei.cmu.edu/confluence/display/c/POS38-C.+Beware+of+race+conditions+when+using+fork+and+file+descriptors + metadata: + shortDescription: Potential time of check time of use vulnerability (vfork) + cwe: CWE-362 + owasp: + - A5:2017-Broken Access Control + - A01:2021-Broken Access Control + security-severity: Medium + category: security + primary_identifier: flawfinder.vfork-1 + secondary_identifiers: + - name: Flawfinder - vfork + type: flawfinder_func_name + value: vfork + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.flawfinder.vfork-1 + shortlink: https://sg.run/8R2J + semgrep.dev: + rule: + r_id: 13084 + rv_id: 920351 + rule_id: qNUb8v + version_id: gETkXEA + url: https://semgrep.dev/playground/r/gETkXEA/gitlab.flawfinder.vfork-1 + origin: community + subcategory: + - audit + pattern: vfork(...) + severity: INFO +- id: gitlab.security_code_scan.SCS0001-1 + languages: + - csharp + patterns: + - pattern-inside: | + using System.Diagnostics; + ... + - pattern-either: + - patterns: + - pattern: Process.Start($ARG) + - pattern-not: Process.Start("...") + - pattern: "(Process $PROC).StartInfo.FileName = <...$ARG...>;" + - pattern: "(Process $PROC).StartInfo.Arguments = <...$ARG...>;" + - patterns: + - pattern-inside: | + $PSINFO = new ProcessStartInfo(...) + ... + Process.Start($PSINFO) + - pattern-either: + - pattern: "$PSINFO.Arguments = <...$ARG...>;" + - pattern: "$PSINFO.FileName = <...$ARG...>;" + message: | + OS command injection is a critical vulnerability that can lead to a full system + compromise as it may allow an adversary to pass in arbitrary commands or arguments + to be executed. + + User input should never be used in constructing commands or command arguments + to functions which execute OS commands. This includes filenames supplied by + user uploads or downloads. + + Ensure your application does not: + + - Use user-supplied information in the process name to execute. + - Use user-supplied information in an OS command execution function which does + not escape shell meta-characters. + - Use user-supplied information in arguments to OS commands. + + The application should have a hardcoded set of arguments that are to be passed + to OS commands. If filenames are being passed to these functions, it is + recommended that a hash of the filename be used instead, or some other unique + identifier. It is strongly recommended that a native library that implements + the same functionality be used instead of using OS system commands, due to the + risk of unknown attacks against third party commands. + + When specifying the OS command, ensure the application uses the full path + information, otherwise the OS may attempt to look up which process to execute + and could be vulnerable to untrusted search path vulnerabilities (CWE-426). + + Example of safely executing an OS command: + ``` + public void ExecuteCommand(string userFileData) { + // generate a random filename, do not using user input + string fileName = "C:\\Temp\\" + Guid.NewGuid(); + File.WriteAllText(fileName, userFileData); + + using (Process process = new Process()) + { + // hardcode the full process path + ProcessStartInfo processInfo = new ProcessStartInfo("C:\\App\\FileReader.exe"); + // only pass in trust arguments, and never direct user input. + processInfo.Arguments = fileName; + processInfo.UseShellExecute = false; + process.StartInfo = processInfo; + process.Start(); + } + } + ``` + + For more information on OS command injection, see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html + severity: ERROR + metadata: + shortDescription: Improper neutralization of special elements used in an OS command + ('OS Command Injection') + category: security + cwe: CWE-78 + primary_identifier: security_code_scan.SCS0001-1 + secondary_identifiers: + - name: SCS0001 + type: security_code_scan_rule_id + value: SCS0001 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0001-1 + shortlink: https://sg.run/WbD2 + semgrep.dev: + rule: + r_id: 31453 + rv_id: 835748 + rule_id: 3qU2L1 + version_id: e1TDKQ1 + url: https://semgrep.dev/playground/r/e1TDKQ1/gitlab.security_code_scan.SCS0001-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0002-1 + languages: + - csharp + patterns: + - pattern-either: + - patterns: + - metavariable-regex: + metavariable: "$FUNC" + regex: "^(SqlQuery|ExecuteSqlCommand|ExecuteSqlCommandAsync|ExecuteSqlRaw|ExecuteSqlRawAsync|FromSqlRaw|FromSql|GetSqlStringCommand|ExecuteDataSet|ExecuteReader|ExecuteNonQuery|ExecuteScalar|CreateSQLQuery)$" + - pattern: "$DB.$FUNC($ARG, ...);" + - pattern-not: $DB.$FUNC("...", ...); + - patterns: + - metavariable-regex: + metavariable: "$FUNC" + regex: "^(ExecuteQuery|ExecuteCommand)$" + - pattern-inside: | + using System.Data.Linq; + ... + - pattern: "(DataContext $CTX).$FUNC($ARG, ...)" + - patterns: + - metavariable-regex: + metavariable: "$IMPL" + regex: "^(SqlCommand|OracleCommand|NpgsqlCommand|MySqlCommand|EntityCommand|OdbcCommand|OleDbCommand|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-regex: + metavariable: "$FUNC" + regex: "^(ExecuteDataRow|ExecuteDataRowAsync|ExecuteDataset|ExecuteDatasetAsync|ExecuteNonQuery|ExecuteNonQueryAsync|ExecuteReader|ExecuteReaderAsync|ExecuteScalar|ExecuteScalarAsync|UpdateDataSet|UpdateDataSetAsync)$" + - pattern-inside: | + using MySql.Data.MySqlClient; + ... + - pattern: MySqlHelper.$FUNC("...", $ARG, ...); + - patterns: + - pattern-inside: | + using Cassandra; + ... + - pattern: "(Session $SESS).Execute($ARG, ...);" + - pattern-not: (Session $SESS).Execute("...", ...); + 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 parameterized queries with `SqlCommand`: + ``` + string userInput = "someUserInput"; + string connectionString = ...; + using (SqlConnection connection = new SqlConnection(connectionString)) + { + connection.Open(); + String sql = "SELECT name, value FROM table where name=@Name"; + + using (SqlCommand command = new SqlCommand(sql, connection)) + { + command.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar); + command.Parameters["@Name"].Value = userInput; + using (SqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1)); + } + } + } + } + ``` + + For more information on SQL Injection see OWASP: + https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html + severity: ERROR + metadata: + shortDescription: Improper Neutralization of Special Elements used in an SQL Command + ('SQL Injection') + category: security + cwe: CWE-89 + primary_identifier: security_code_scan.SCS0002-1 + secondary_identifiers: + - name: SCS0002 + type: security_code_scan_rule_id + value: SCS0002 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0002-1 + shortlink: https://sg.run/K1y5 + semgrep.dev: + rule: + r_id: 31455 + rv_id: 835750 + rule_id: PeUejg + version_id: d6TKgXy + url: https://semgrep.dev/playground/r/d6TKgXy/gitlab.security_code_scan.SCS0002-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0003-1 + 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 + query + is structured. Depending on the logic of the original query, this could lead to adversaries + extracting unauthorized information or in rare cases bypassing authorization checks. + + It is recommended that LINQ to XML is used instead of XPath for querying XML documents. Care + must be taken to **not** call these LINQ functions with user input as they can still lead to + XPath + injection: + + - `XPathEvaluate` + - `XPathSelectElement` + - `XPathSelectElements` + + Example using LINQ to XML to safely extract the first user from a list of users: + ``` + // XDocument is safe from XXE attacks as the resolver is disabled by default + XDocument doc = XDocument.Load("users.xml"); + XNamespace ns = "urn:users-schema"; + + string userInput = "LastName"; + + // Get all the users. + var user = doc.Descendants(ns + "user") + .Select(u => new { + FirstName = (string)u.Element(ns + "first-name"), + LastName = (string)u.Element(ns + "last-name") + }).Where(u => u.LastName == userInput).FirstOrDefault(); + + Console.WriteLine(user.FirstName + " " + user.LastName); + ``` + + For more information on LINQ to XML security see: + https://learn.microsoft.com/en-us/dotnet/standard/linq/linq-xml-security + + For more information on XML security see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net + severity: INFO + metadata: + shortDescription: Improper neutralization of data within XPath expressions ('XPath + Injection') + category: security + cwe: CWE-643 + primary_identifier: security_code_scan.SCS0003-1 + secondary_identifiers: + - name: SCS0003 + type: security_code_scan_rule_id + value: SCS0003 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0003-1 + shortlink: https://sg.run/qeZ7 + semgrep.dev: + rule: + r_id: 31456 + rv_id: 835751 + rule_id: JDUnoJ + version_id: ZRTld02 + url: https://semgrep.dev/playground/r/ZRTld02/gitlab.security_code_scan.SCS0003-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0004-1 + 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 + cwe: CWE-295 + primary_identifier: security_code_scan.SCS0004-1 + secondary_identifiers: + - name: SCS0004 + type: security_code_scan_rule_id + value: SCS0004 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0004-1 + shortlink: https://sg.run/PwPz + semgrep.dev: + rule: + r_id: 31445 + rv_id: 835740 + rule_id: ZqUDen + version_id: yeTNgln + url: https://semgrep.dev/playground/r/yeTNgln/gitlab.security_code_scan.SCS0004-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0005-1 + 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 + cwe: CWE-338 + primary_identifier: security_code_scan.SCS0005-1 + secondary_identifiers: + - name: SCS0005 + type: security_code_scan_rule_id + value: SCS0005 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0005-1 + shortlink: https://sg.run/Rw5q + semgrep.dev: + rule: + r_id: 31449 + rv_id: 835744 + rule_id: L1URz8 + version_id: kbT2PN6 + url: https://semgrep.dev/playground/r/kbT2PN6/gitlab.security_code_scan.SCS0005-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0006-1 + 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. + 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. Currently there is no vetted Argon2id implementation for + C# so + it is recommended that PBKDF2 be used until one is available. + + Example using PBKDF2 to generate and compare passwords: + ``` + const int SaltSize = 24; + const int HashSize = 24; + // number of pbkdf2 iterations, Rfc2898DeriveBytes uses hmac-sha1 + // so set a high iteration count + const int Iterations = 1_300_000; + byte[] salt = new byte[SaltSize]; + RandomNumberGenerator.Fill(salt); + + Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes("some password", salt, Iterations); + byte[] hashBytes = pbkdf2.GetBytes(HashSize); + // Store salt and hashedBytes in a data store such as database for authentication + Console.WriteLine("Hash {0}", BitConverter.ToString(hashBytes).Replace("-", "")); + // Do a constant time comparison as to not leak data based on timing + if (CryptographicOperations.FixedTimeEquals(hashBytes, hashBytes)) { + Console.WriteLine("hashes are equal"); + } + ``` + For more information on PBKDF2 see: + https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rfc2898derivebytes + + 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 + primary_identifier: security_code_scan.SCS0006-1 + secondary_identifiers: + - name: SCS0006 + type: security_code_scan_rule_id + value: SCS0006 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0006-1 + shortlink: https://sg.run/Gzbq + semgrep.dev: + rule: + r_id: 31448 + rv_id: 835743 + rule_id: 7KUKbk + version_id: NdTBRPN + url: https://semgrep.dev/playground/r/NdTBRPN/gitlab.security_code_scan.SCS0006-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0007-1 + languages: + - csharp + mode: taint + pattern-sanitizers: + - pattern: "(XmlReaderSettings $SETTINGS).ProhibitDtd = true;" + - pattern: "(XmlReaderSettings $SETTINGS).DtdProcessing = DtdProcessing.Prohibit;" + - pattern: "(XmlDocument $DOC).XmlResolver = null;" + - pattern: var $DOC = new XmlDocument { ..., XmlResolver = null, ... }; + pattern-sinks: + - pattern: XmlReader.Create(..., $SETTINGS); + - pattern: "(XmlDocument $DOC).Load(...);" + pattern-sources: + - pattern: var $SETTINGS = new XmlReaderSettings(); + - pattern: var $DOC = new XmlDocument(...); + - pattern: var $DOC = new XmlDocument {...}; + 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. + - Setting `XmlTextReader`'s `ProhibitDtd` to `true` + - Setting `XmlReaderSettings` `DtdProcessing` to `DtdProcessing.Prohibit` + + 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 + primary_identifier: security_code_scan.SCS0007-1 + secondary_identifiers: + - name: SCS0007 + type: security_code_scan_rule_id + value: SCS0007 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0007-1 + shortlink: https://sg.run/lbWE + semgrep.dev: + rule: + r_id: 31457 + rv_id: 835752 + rule_id: 5rU7N6 + version_id: nWTyNXQ + url: https://semgrep.dev/playground/r/nWTyNXQ/gitlab.security_code_scan.SCS0007-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0008-1 + 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 + cwe: CWE-614 + primary_identifier: security_code_scan.SCS0008-1 + secondary_identifiers: + - name: SCS0008 + type: security_code_scan_rule_id + value: SCS0008 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0008-1 + shortlink: https://sg.run/49k5 + semgrep.dev: + rule: + r_id: 31444 + rv_id: 835739 + rule_id: d8U86o + version_id: 9lTJ7ro + url: https://semgrep.dev/playground/r/9lTJ7ro/gitlab.security_code_scan.SCS0008-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0009-1 + 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 + cwe: CWE-1004 + primary_identifier: security_code_scan.SCS0009-1 + secondary_identifiers: + - name: SCS0009 + type: security_code_scan_rule_id + value: SCS0009 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0009-1 + shortlink: https://sg.run/39QK + semgrep.dev: + rule: + r_id: 31443 + rv_id: 835738 + rule_id: v8ULvw + version_id: 1QTPN6z + url: https://semgrep.dev/playground/r/1QTPN6z/gitlab.security_code_scan.SCS0009-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0010-1 + 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. + If using .NET Framework greater than version 6.0 consider using `ChaCha20Poly1305` + instead as it is easier and faster than the alternatives such as `AES-256-GCM`. + + For older applications, `AES-256-GCM` is recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are reused. + + Example using `ChaCha20Poly1305`: + ``` + // Generate a random key + byte[] key = new byte[32]; + RandomNumberGenerator.Fill(key); + + // Note nonce values _must_ be regenerated every time they are used. + byte[] nonce = new byte[12]; + RandomNumberGenerator.Fill(nonce); + + byte[] authTag = new byte[16]; + byte[] cipherText; + + using (ChaCha20Poly1305 encryptor = new ChaCha20Poly1305(key)) + { + byte[] plainText = System.Text.Encoding.UTF8.GetBytes("Secret text to encrypt"); + cipherText = new byte[plainText.Length]; + encryptor.Encrypt(nonce, plainText, cipherText, authTag); + } + + using (ChaCha20Poly1305 decryptor = new ChaCha20Poly1305(key)) + { + byte[] output = new byte[cipherText.Length]; + decryptor.Decrypt(nonce, cipherText, authTag, output); + Console.WriteLine("Output: {0}", System.Text.Encoding.UTF8.GetString(output)); + } + ``` + + Example using `AES-256-GCM`: + ``` + // Generate a random key + byte[] key = new byte[32]; + RandomNumberGenerator.Fill(key); + + // Note nonce values _must_ be regenerated every time they are used. + byte[] nonce = new byte[AesGcm.NonceByteSizes.MaxSize]; + RandomNumberGenerator.Fill(nonce); + + byte[] authTag = new byte[AesGcm.TagByteSizes.MaxSize]; + byte[] cipherText; + + using (AesGcm encryptor = new AesGcm(key)) + { + byte[] plainText = Encoding.UTF8.GetBytes("Secret text to encrypt"); + cipherText = new byte[plainText.Length]; + encryptor.Encrypt(nonce, plainText, cipherText, authTag); + } + + using (AesGcm decryptor = new AesGcm(key)) + { + byte[] output = new byte[cipherText.Length]; + decryptor.Decrypt(nonce, cipherText, authTag, output); + Console.WriteLine("Output: {0}", Encoding.UTF8.GetString(output)); + } + ``` + languages: + - csharp + severity: WARNING + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm + category: security + cwe: CWE-327 + primary_identifier: security_code_scan.SCS0010-1 + secondary_identifiers: + - name: SCS0010 + type: security_code_scan_rule_id + value: SCS0010 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0010-1 + shortlink: https://sg.run/Jzwy + semgrep.dev: + rule: + r_id: 31446 + rv_id: 835741 + rule_id: nJUQnX + version_id: rxTDvdk + url: https://semgrep.dev/playground/r/rxTDvdk/gitlab.security_code_scan.SCS0010-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0011-1 + patterns: + - pattern-either: + - pattern: new XsltSettings() {EnableScript = true}; + - pattern: | + var $SETTINGS = new XsltSettings(); + ... + $SETTINGS.EnableScript = true; + 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 + languages: + - csharp + severity: WARNING + metadata: + shortDescription: Improper restriction of XML external entity reference + category: security + cwe: CWE-611 + primary_identifier: security_code_scan.SCS0011-1 + secondary_identifiers: + - name: SCS0011 + type: security_code_scan_rule_id + value: SCS0011 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0011-1 + shortlink: https://sg.run/64k1 + semgrep.dev: + rule: + r_id: 31459 + rv_id: 835753 + rule_id: ReUE21 + version_id: ExTrW7v + url: https://semgrep.dev/playground/r/ExTrW7v/gitlab.security_code_scan.SCS0011-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0013-1 + 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 + message integrity. Without message integrity it could be possible for an adversary to attempt + to tamper with the ciphertext which could lead to compromising the encryption key. Newer + algorithms + apply message integrity to validate ciphertext has not been tampered with. + + Instead of using an algorithm that requires configuring a `CipherMode`, an algorithm + that has built-in message integrity should be used. If using .NET Framework greater + than version 6.0 consider using `ChaCha20Poly1305` or `AES-256-GCM`. + + For older applications, `AES-256-GCM` is recommended, however it has many drawbacks: + - Slower than `ChaCha20Poly1305`. + - Catastrophic failure if nonce values are re-used. + + Example using `ChaCha20Poly1305`: + ``` + // Generate a random key + byte[] key = new byte[32]; + RandomNumberGenerator.Fill(key); + + ChaCha20Poly1305 encryptor = new ChaCha20Poly1305(key); + + // Note nonce values _must_ be regenerated every time they are used. + var nonce = new byte[12]; + RandomNumberGenerator.Fill(nonce); + + byte[] plainText = System.Text.Encoding.UTF8.GetBytes("Secret text to encrypt"); + byte[] cipherText = new byte[plainText.Length]; + var authTag = new byte[16]; + + encryptor.Encrypt(nonce, plainText, cipherText, authTag); + byte[] output = new byte[cipherText.Length]; + encryptor.Decrypt(nonce, cipherText, authTag, output); + Console.WriteLine("Output: {0}", System.Text.Encoding.UTF8.GetString(output)); + ``` + + Example using `AES-256-GCM`: + ``` + var plaintextBytes = Encoding.UTF8.GetBytes("Secret text to encrypt"); + var key = new byte[32]; + RandomNumberGenerator.Fill(key); + + using var aes = new AesGcm(key); + var nonce = new byte[AesGcm.NonceByteSizes.MaxSize]; + RandomNumberGenerator.Fill(nonce); + + var cipherText = new byte[plaintextBytes.Length]; + var tag = new byte[AesGcm.TagByteSizes.MaxSize]; + + aes.Encrypt(nonce, plaintextBytes, cipherText, tag); + + // Decrypt + using (var decrypt = new AesGcm(key)) + { + var decryptedBytes = new byte[cipherText.Length]; + + decrypt.Decrypt(nonce, cipherText, tag, decryptedBytes); + + Console.WriteLine("Decrypted: {0}", Encoding.UTF8.GetString(decryptedBytes)); + } + ``` + severity: WARNING + metadata: + shortDescription: Use of a broken or risky cryptographic algorithm + category: security + cwe: CWE-327 + primary_identifier: security_code_scan.SCS0013-1 + secondary_identifiers: + - name: SCS0013 + type: security_code_scan_rule_id + value: SCS0013 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0013-1 + shortlink: https://sg.run/5gZ0 + semgrep.dev: + rule: + r_id: 31447 + rv_id: 835742 + rule_id: EwUe1Z + version_id: bZTBopN + url: https://semgrep.dev/playground/r/bZTBopN/gitlab.security_code_scan.SCS0013-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0016-1 + languages: + - csharp + patterns: + - pattern: | + [$HTTPMETHOD] + public $RET $FOO(...) { + ... + } + - pattern-not: | + [ValidateAntiForgeryToken] + public $RET $FOO(...) { + ... + } + - 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 + cwe: CWE-352 + primary_identifier: security_code_scan.SCS0016-1 + secondary_identifiers: + - name: SCS0016 + type: security_code_scan_rule_id + value: SCS0016 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0016-1 + shortlink: https://sg.run/AKL2 + semgrep.dev: + rule: + r_id: 31450 + rv_id: 835745 + rule_id: 8GU3vk + version_id: w8TAbXA + url: https://semgrep.dev/playground/r/w8TAbXA/gitlab.security_code_scan.SCS0016-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0017-1 + languages: + - csharp + patterns: + - pattern: | + [ValidateInput(false)] + public $RET $FOO(...) + { + ... + } + message: | + By using the `[ValidateInput(false)]` attribute in a controller + class, the application will disable request validation for that + method. This disables ASP.NET from examining requests for injection + attacks such as Cross-Site-Scripting (XSS). + + If possible, re-enable validation by using `ValidateInput(true)`. + In some cases this may not be possible, in which case ensure how the + request data used is validated and this method does not + output user input directly into the view. + + For more information on protecting ASP.NET Core applications from XSS see: + https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting + + Example of enabling `ValidateInput` attribute: + ``` + class ControllerClass + { + [ValidateInput(true)] + public void SomeActionMethod() + { + } + } + ``` + + For more information on ASP.NET request validation see OWASP: + https://owasp.org/www-community/ASP-NET_Request_Validation + severity: WARNING + metadata: + shortDescription: ASP.NET input validation disabled + category: security + cwe: CWE-554 + primary_identifier: security_code_scan.SCS0017-1 + secondary_identifiers: + - name: SCS0017 + type: security_code_scan_rule_id + value: SCS0017 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0017-1 + shortlink: https://sg.run/p16Z + semgrep.dev: + rule: + r_id: 31462 + rv_id: 835756 + rule_id: DbUwNq + version_id: 8KTGlRL + url: https://semgrep.dev/playground/r/8KTGlRL/gitlab.security_code_scan.SCS0017-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0018-1 + languages: + - csharp + mode: taint + pattern-sources: + - patterns: + - pattern-inside: | + public class $CLASS : Controller { + ... + } + - 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 + information comes from user input, it could be abused to read sensitive files, + access other users data, or aid in exploitation to gain further system access. + + User input should never be used in constructing paths or files for interacting + with the filesystem. This includes filenames supplied by user uploads or downloads. + If possible consider hashing user input or replacing it with unique values and + use `System.IO.Path.GetFullPath` to resolve and validate the path information + prior to processing any file functionality. + + Example using `Path.GetFullPath` and not allowing direct user input: + ``` + // store user input alongside an ID we control + struct userData + { + public string userFilename; + public Guid id; + } + + class Program + { + public static void Main() + { + userData data = new userData(); + // user input, saved only as a reference + data.userFilename = "..\\test.txt"; + + // random id as the filename + data.id = Guid.NewGuid(); + + // restrict all file processing to this directory only + string basePath = "C:\\Restricted\\"; + + // resolve the full path, but only use our random generated id + string fullPath = Path.GetFullPath(basePath + data.id); + + // verify the path is contained within our basePath + if (!fullPath.StartsWith(basePath)) { + Console.WriteLine("Invalid path specified!"); + return; + } + // process / work with file + } + } + ``` + + For more information on path traversal issues see OWASP: + https://owasp.org/www-community/attacks/Path_Traversal + metadata: + shortDescription: Improper limitation of a pathname to a restricted directory + ('Path Traversal') + cwe: CWE-22 + primary_identifier: security_code_scan.SCS0018-1 + secondary_identifiers: + - name: SCS0018 + type: security_code_scan_rule_id + value: SCS0018 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0018-1 + shortlink: https://sg.run/zrpd + semgrep.dev: + rule: + r_id: 31461 + rv_id: 835755 + rule_id: BYUy1X + version_id: LjTEeZl + url: https://semgrep.dev/playground/r/LjTEeZl/gitlab.security_code_scan.SCS0018-1 + origin: community + category: security + subcategory: + - audit + severity: WARNING +- id: gitlab.security_code_scan.SCS0026-1.SCS0031-1 + languages: + - csharp + patterns: + - pattern-either: + - patterns: + - pattern: "(DirectorySearcher $SOURCE).Filter = ..." + - pattern-not: (DirectorySearcher $SOURCE).Filter = "..." + - patterns: + - pattern: "(DirectorySearcher $SOURCE).Path = ..." + - pattern-not: (DirectorySearcher $SOURCE).Path = "..." + message: | + LDAP injection attacks exploit LDAP queries to influence how data is returned by + the LDAP, or in this case an Active Directory server. + + It is recommended that newer applications use the `System.DirectoryServices.AccountManagement` + API instead of `DirectorySearcher` API as it hides the complexity of querying LDAP directly. + However, + the `AccountManagement` API is still susceptible to LDAP injection if a user inputs LDAP + queries, + including LDAP filter characters such as `*`. + + It is recommended that all input passed to LDAP querying systems encode the following values: + + - Any occurrence of the null character must be escaped as “\00”. + - Any occurrence of the open parenthesis character must be escaped as “\28”. + - Any occurrence of the close parenthesis character must be escaped as “\29”. + - Any occurrence of the asterisk character must be escaped as “\2a”. + - Any occurrence of the backslash character must be escaped as “\5c”. + + Example code that safely encodes input for use in an LDAP query using the `AccountManagement` + API: + ``` + using System.DirectoryServices.AccountManagement; + + string EncodeLDAPString(string input) { + // Note the \ character is replaced first + char[] chars = new char[] { '\\', '\0', '(', ')', '*' }; + string[] encoded = new string[] { "\\5c", "\\00", "\\28", "\\29", "\\2a" }; + + for (int i = 0; i < chars.Length; i++) + { + input = input.Replace(chars[i].ToString(), encoded[i]); + } + + return input; + } + + // unsafe, do not use without encoding first + string userInput = "Administrator"; + PrincipalContext AD = new PrincipalContext(ContextType.Domain, "ad.example.dev"); + + UserPrincipal u = new UserPrincipal(AD); + string encodedUserName = EncodeLDAPString(userInput); + + // The AD search term, encoded prior to calling search + u.SamAccountName = encodedUserName; + + // Search for user + PrincipalSearcher search = new PrincipalSearcher(u); + + // Use FindOne to only return a single result + UserPrincipal result = (UserPrincipal)search.FindOne(); + search.Dispose(); + + // show some details + if (result != null) { + Console.WriteLine("User: {0}", result.DisplayName); + } else { + Console.WriteLine("user not found"); + } + ``` + + The same encoding method shown in `EncodeLDAPString` can also be used when using the + older `DirectorySearcher` API. + + For more information see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html + severity: WARNING + metadata: + shortDescription: Improper neutralization of special elements used in an LDAP + query ('LDAP Injection') + category: security + cwe: CWE-90 + primary_identifier: security_code_scan.SCS0026-1.SCS0031-1 + secondary_identifiers: + - name: SCS0026 + type: security_code_scan_rule_id + value: SCS0026 + - name: SCS0031 + type: security_code_scan_rule_id + value: SCS0031 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0026-1.SCS0031-1 + shortlink: https://sg.run/0ZWj + semgrep.dev: + rule: + r_id: 31454 + rv_id: 835749 + rule_id: 4bUbeO + version_id: vdTOQe8 + url: https://semgrep.dev/playground/r/vdTOQe8/gitlab.security_code_scan.SCS0026-1.SCS0031-1 + origin: community + subcategory: + - audit +- id: gitlab.security_code_scan.SCS0027-1 + languages: + - csharp + mode: taint + pattern-sources: + - patterns: + - pattern: "$SRC" + - pattern-inside: 'public $RET $FUNC(...,$SRC,...){...} + + ' + pattern-sanitizers: + - pattern-either: + - pattern: TryCreate(...) + - pattern: Action(...) + - pattern: HttpRouteUrl(...) + - pattern: RouteUrl(...) + pattern-sinks: + - patterns: + - pattern-not-inside: | + if (IsLocalUrl(...)) { + ... + Redirect(...); + ... + } + - pattern-not-inside: | + if ($URL.IsLocalUrl(...)) { + ... + Redirect(...); + ... + } + - pattern-either: + - pattern: Redirect(...) + - pattern: RedirectPermanent(...) + - pattern: RedirectToRoute(...) + - pattern: RedirectToRoutePermanent(...) + - pattern: new 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 + cwe: CWE-601 + primary_identifier: security_code_scan.SCS0027-1 + secondary_identifiers: + - name: SCS0027 + type: security_code_scan_rule_id + value: SCS0027 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0027-1 + shortlink: https://sg.run/DYeP + semgrep.dev: + rule: + r_id: 31452 + rv_id: 835747 + rule_id: QrUE1q + version_id: O9TJ7wX + url: https://semgrep.dev/playground/r/O9TJ7wX/gitlab.security_code_scan.SCS0027-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.security_code_scan.SCS0028-1 + 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(...)" + languages: + - csharp + message: | + Deserialization attacks exploit the process of reading serialized data and turning it back into an + object. By constructing malicious objects and serializing them, an adversary may attempt to: + + - Inject code that is executed upon object construction, which occurs during the deserialization process. + - Exploit mass assignment by including fields that are not normally a part of the serialized data but are + read in during deserialization. + + Microsoft recommends no longer using the following serialization formats: + + - BinaryFormatter + - SoapFormatter + - NetDataContractSerializer + - LosFormatter + - ObjectStateFormatter + + Consider safer alternatives such as serializing data in the JSON format. Ensure any format chosen allows + the application to specify exactly which object types are allowed to be deserialized. Additionally, when + deserializing, never deserialize to base object types like `Object` and only cast to the exact object + type that is expected. + + To protect against mass assignment, only allow deserialization of the specific fields that are required. + If this is not easily done, consider creating an intermediary type that can be serialized with only the + necessary fields exposed. + + For more information see Microsoft's deserialization security guide: + https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide + + For more details on deserialization attacks in general, see OWASP's guide: + https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html + + It should be noted that [tools exist](https://github.com/pwntester/ysoserial.net) to automatically create + exploit code for these vulnerabilities. + metadata: + shortDescription: Deserialization of potentially untrusted data + category: security + cwe: CWE-502 + primary_identifier: security_code_scan.SCS0028-1 + secondary_identifiers: + - name: SCS0028 + type: security_code_scan_rule_id + value: SCS0028 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0028-1 + shortlink: https://sg.run/BqeA + semgrep.dev: + rule: + r_id: 31451 + rv_id: 835746 + rule_id: gxUrkX + version_id: xyTNrPd + url: https://semgrep.dev/playground/r/xyTNrPd/gitlab.security_code_scan.SCS0028-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.security_code_scan.SCS0029-1 + mode: taint + pattern-sources: + - patterns: + - pattern: "$PARAM" + - metavariable-regex: + metavariable: "$HTTP_ANNO" + regex: "^(Http)" + - pattern-inside: | + public class $CLASS : Controller { + ... + } + - pattern-inside: | + [$HTTP_ANNO] + public string $METHOD(...,$PARAM,...){...} + 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: "(System.Web.HttpResponse $E).AddHeader(...)" + - pattern: "(System.Web.HttpResponse $E).AppendHeader(...)" + - pattern: "(System.Web.HttpResponse $E).Write(...)" + - pattern: "(System.Web.HttpResponse $E).BinaryWrite(...)" + - pattern: "(System.Web.HttpResponse $E).TransmitFile(...)" + - pattern: "(System.Web.HttpResponse $E).WriteFile(...)" + - pattern: "(System.Web.HttpResponseBase $E).AddHeader(...)" + - pattern: "(System.Web.HttpResponseBase $E).AppendHeader(...)" + - pattern: "(System.Web.HttpResponseBase $E).Write(...)" + - pattern: "(System.Web.HttpResponseBase $E).BinaryWrite(...)" + - pattern: "(System.Web.HttpResponseBase $E).WriteFile(...)" + - 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(...)" + - pattern: "(System.Web.UI.ClientScriptManager $E).RegisterStartupScript(...)" + - pattern: "(System.Web.UI.ClientScriptManager $E).RegisterClientScriptBlock(...)" + - pattern: "(System.Web.UI.Page $E).RegisterStartupScript(...)" + - pattern: "(System.Web.UI.Page $E).RegisterClientScriptBlock(...)" + - pattern: return ...; + languages: + - csharp + 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 `
    context 1
    ` + - Inside attributes: `
    ` + - Inside event attributes `` + - Inside script blocks: `` + - Unsafe element HTML assignment: `element.innerHTML = "context 5"` + - Inside URLs: `link` + + 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. + + 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 + primary_identifier: security_code_scan.SCS0029-1 + secondary_identifiers: + - name: SCS0029 + type: security_code_scan_rule_id + value: SCS0029 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0029-1 + shortlink: https://sg.run/2e5L + semgrep.dev: + rule: + r_id: 31463 + rv_id: 835757 + rule_id: WAU7El + version_id: gETyXdL + url: https://semgrep.dev/playground/r/gETyXdL/gitlab.security_code_scan.SCS0029-1 + origin: community + subcategory: + - audit + severity: WARNING +- id: gitlab.security_code_scan.SCS0032-1.SCS0033-1.SCS0034-1 + languages: + - csharp + patterns: + - pattern: | + new PasswordValidator + { + ..., + }; + - pattern: | + new PasswordValidator + { + ..., + RequiredLength = $LEN, + ..., + }; + - pattern-not: | + new PasswordValidator + { + ..., + RequireNonLetterOrDigit = true, + ..., + }; + - pattern-not: | + new PasswordValidator + { + ..., + RequireDigit = true, + ..., + }; + - pattern-not: | + new PasswordValidator + { + ..., + RequireLowercase = true, + ..., + }; + - pattern-not: | + new PasswordValidator + { + ..., + RequireUppercase = true, + ..., + }; + - metavariable-comparison: + metavariable: "$LEN" + comparison: "$LEN < 8" + message: | + The application's `PasswordValidator.RequiredLength` property allows passwords + to be less than 8 characters. Consider requiring a length of at least 8 or more + characters to reduce the chance of passwords being brute forced. + + Example of setting the RequiredLength to 8 in ASP.NET Core Identity: + ``` + builder.Services.Configure(options => + { + // Default Password settings. + options.Password.RequireDigit = true; + options.Password.RequireLowercase = true; + options.Password.RequireNonAlphanumeric = true; + options.Password.RequireUppercase = true; + options.Password.RequiredLength = 8; + options.Password.RequiredUniqueChars = 1; + }); + ``` + + For more information on configuring ASP.NET Core Identity see: + https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration + severity: WARNING + metadata: + shortDescription: Weak password requirements + category: security + cwe: CWE-521 + primary_identifier: security_code_scan.SCS0032-1.SCS0033-1.SCS0034-1 + secondary_identifiers: + - name: SCS0032 + type: security_code_scan_rule_id + value: SCS0032 + - name: SCS0033 + type: security_code_scan_rule_id + value: SCS0033 + - name: SCS0034 + type: security_code_scan_rule_id + value: SCS0034 + license: MIT + vulnerability_class: + - Other + source: https://semgrep.dev/r/gitlab.security_code_scan.SCS0032-1.SCS0033-1.SCS0034-1 + shortlink: https://sg.run/o1e0 + semgrep.dev: + rule: + r_id: 31460 + rv_id: 835754 + rule_id: AbUEJj + version_id: 7ZTxR0P + url: https://semgrep.dev/playground/r/7ZTxR0P/gitlab.security_code_scan.SCS0032-1.SCS0033-1.SCS0034-1 + origin: community + subcategory: + - audit - id: raptor-argv-envp-access metadata: author: Marco Ivaldi diff --git a/assets/semgrep_rules/generated/oss/others.yaml b/assets/semgrep_rules/generated/oss/others.yaml index 996c5ddb..50f78ed7 100644 --- a/assets/semgrep_rules/generated/oss/others.yaml +++ b/assets/semgrep_rules/generated/oss/others.yaml @@ -1,299 +1,5 @@ --- rules: -- id: gitlab.bandit.B108-1 - pattern: open("=~/^\/tmp.*/", ...) - message: 'Detected hardcoded temp directory. Consider using ''tempfile.TemporaryFile'' - instead. - - ' - metadata: - cwe: 'CWE-377: Insecure Temporary File' - license: MIT - source: https://semgrep.dev/r/gitlab.bandit.B108-1 - shortlink: https://sg.run/O81B - semgrep.dev: - rule: - r_id: 11875 - rv_id: 13242 - rule_id: 6JU6qd - version_id: l4TzRP - url: https://semgrep.dev/playground/r/l4TzRP/gitlab.bandit.B108-1 - origin: community - severity: WARNING - languages: - - python -- id: gitlab.bandit.B303-3 - patterns: - - pattern-either: - - pattern: Crypto.Hash.MD2.new(...) - - pattern: Cryptodome.Hash.MD2.new (...) - message: | - Detected MD2 hash algorithm which is considered insecure. This algorithm - has many known vulnerabilities and has been deprecated. Use SHA256 or SHA3 instead. - metadata: - cwe: CWE-327 - shortDescription: Use of a Broken or Risky Cryptographic Algorithm - owasp: A3:2017-Sensitive Data Exposure - primary_identifier: bandit.B303-3 - secondary_identifiers: - - name: Bandit Test ID B303 - type: bandit_test_id - value: B303 - license: MIT - source: https://semgrep.dev/r/gitlab.bandit.B303-3 - shortlink: https://sg.run/nq5r - semgrep.dev: - rule: - r_id: 11536 - rv_id: 73118 - rule_id: 9AUOKZ - version_id: WrTw4p - url: https://semgrep.dev/playground/r/WrTw4p/gitlab.bandit.B303-3 - origin: community - severity: WARNING - languages: - - python -- id: gitlab.bandit.B303-4 - patterns: - - pattern-either: - - pattern: Crypto.Hash.MD4.new(...) - - pattern: Cryptodome.Hash.MD4.new (...) - message: | - Detected MD4 hash algorithm which is considered insecure. This algorithm - has many known vulnerabilities and has been deprecated. Use SHA256 or SHA3 instead. - metadata: - cwe: CWE-327 - shortDescription: Use of a Broken or Risky Cryptographic Algorithm - owasp: A3:2017-Sensitive Data Exposure - primary_identifier: bandit.B303-4 - secondary_identifiers: - - name: Bandit Test ID B303 - type: bandit_test_id - value: B303 - license: MIT - source: https://semgrep.dev/r/gitlab.bandit.B303-4 - shortlink: https://sg.run/E5GB - semgrep.dev: - rule: - r_id: 11537 - rv_id: 73119 - rule_id: yyUvLN - version_id: 0bTXP3 - url: https://semgrep.dev/playground/r/0bTXP3/gitlab.bandit.B303-4 - origin: community - severity: WARNING - languages: - - python -- id: gitlab.bandit.B303-5 - patterns: - - pattern-either: - - pattern: Crypto.Hash.MD5.new(...) - - pattern: Cryptodome.Hash.MD5.new (...) - message: | - Detected MD5 hash algorithm which is considered insecure. MD5 is not - collision resistant and is therefore not suitable as a cryptographic - signature. Use SHA256 or SHA3 instead. - metadata: - cwe: CWE-327 - shortDescription: Use of a Broken or Risky Cryptographic Algorithm - owasp: A3:2017-Sensitive Data Exposure - primary_identifier: bandit.B303-5 - secondary_identifiers: - - name: Bandit Test ID B303 - type: bandit_test_id - value: B303 - license: MIT - source: https://semgrep.dev/r/gitlab.bandit.B303-5 - shortlink: https://sg.run/70eQ - semgrep.dev: - rule: - r_id: 11538 - rv_id: 73120 - rule_id: r6UkYj - version_id: K3TXWk - url: https://semgrep.dev/playground/r/K3TXWk/gitlab.bandit.B303-5 - origin: community - severity: WARNING - languages: - - python -- id: gitlab.bandit.B303-6 - patterns: - - pattern-either: - - pattern: Crypto.Hash.SHA.new(...) - - pattern: Cryptodome.Hash.SHA.new (...) - message: | - Detected SHA1 hash algorithm which is considered insecure. SHA1 is not - collision resistant and is therefore not suitable as a cryptographic - signature. Use SHA256 or SHA3 instead. - metadata: - cwe: CWE-327 - shortDescription: Use of a Broken or Risky Cryptographic Algorithm - owasp: A3:2017-Sensitive Data Exposure - primary_identifier: bandit.B303-6 - secondary_identifiers: - - name: Bandit Test ID B303 - type: bandit_test_id - value: B303 - license: MIT - source: https://semgrep.dev/r/gitlab.bandit.B303-6 - shortlink: https://sg.run/L0KY - semgrep.dev: - rule: - r_id: 11539 - rv_id: 73121 - rule_id: bwUOkX - version_id: qkTy8y - url: https://semgrep.dev/playground/r/qkTy8y/gitlab.bandit.B303-6 - origin: community - severity: WARNING - languages: - - python -- id: gitlab.bandit.B308.B703 - patterns: - - pattern-not-inside: django.utils.html.format_html(...) - - pattern: django.utils.safestring.mark_safe(...) - message: | - 'mark_safe()' is used to mark a string as "safe" for HTML output. - This disables escaping and could therefore subject the content to - XSS attacks. Use 'django.utils.html.format_html()' to build HTML - for rendering instead. - metadata: - cwe: 'CWE-79: Improper Neutralization of Input During Web Page Generation (''Cross-site - Scripting'')' - owasp: 'A7: Cross-Site Scripting (XSS)' - license: MIT - source: https://semgrep.dev/r/gitlab.bandit.B308.B703 - shortlink: https://sg.run/58xj - semgrep.dev: - rule: - r_id: 11547 - rv_id: 13275 - rule_id: d8UzRp - version_id: JdTQjX - url: https://semgrep.dev/playground/r/JdTQjX/gitlab.bandit.B308.B703 - origin: community - severity: WARNING - languages: - - python -- id: gitlab.bandit.B313.B314.B315.B316.B318.B319.B320.B405.B406.B407.B408.B409.B410 - pattern-either: - - pattern: import xml - - pattern: import lxml - - pattern: xml.etree.cElementTree.fromstring(...) - - pattern: xml.etree.cElementTree.parse(...) - - pattern: xml.etree.cElementTree.iterparse(...) - - pattern: xml.etree.cElementTree.XMLParser(...) - - pattern: xml.etree.ElementTree.fromstring(...) - - pattern: xml.etree.ElementTree.parse(...) - - pattern: xml.etree.ElementTree.iterparse(...) - - pattern: xml.etree.ElementTree.XMLParser(...) - - pattern: xml.sax.expatreader.create_parser(...) - - pattern: xml.dom.expatbuilder.parse(...) - - pattern: xml.dom.expatbuilder.parseString(...) - - pattern: xml.dom.minidom.parseString(...) - - pattern: xml.dom.minidom.parse(...) - - pattern: xml.dom.pulldom.parseString(...) - - pattern: xml.dom.pulldom.parse(...) - - pattern: lxml.etree.fromstring(...) - - pattern: lxml.etree.RestrictedElement(...) - - pattern: lxml.etree.GlobalParserTLS(...) - - pattern: lxml.etree.getDefaultParser(...) - - pattern: lxml.etree.check_docinfo(...) - metadata: - cwe: 'CWE-611: Improper Restriction of XML External Entity Reference' - owasp: 'A4: XML External Entities (XXE)' - license: MIT - source: https://semgrep.dev/r/gitlab.bandit.B313.B314.B315.B316.B318.B319.B320.B405.B406.B407.B408.B409.B410 - shortlink: https://sg.run/DJ5G - semgrep.dev: - rule: - r_id: 11552 - rv_id: 13281 - rule_id: L1U4Yd - version_id: DkTKjj - url: https://semgrep.dev/playground/r/DkTKjj/gitlab.bandit.B313.B314.B315.B316.B318.B319.B320.B405.B406.B407.B408.B409.B410 - origin: community - message: | - Found use of the native Python XML libraries, which is vulnerable to XML external entity (XXE) - attacks. The Python documentation recommends the 'defusedxml' library instead. Use 'defusedxml'. - See https://github.com/tiran/defusedxml for more information. - severity: ERROR - languages: - - python -- id: gitlab.bandit.B502.B503 - 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 - message: | - An insecure SSL version was detected. TLS versions 1.0, 1.1, and all SSL versions - are considered weak encryption and are deprecated. - Use 'ssl.PROTOCOL_TLSv1_2' or higher. - metadata: - cwe: 'CWE-326: Inadequate Encryption Strength' - owasp: 'A3: Sensitive Data Exposure' - license: MIT - source: https://semgrep.dev/r/gitlab.bandit.B502.B503 - shortlink: https://sg.run/plRe - semgrep.dev: - rule: - r_id: 11562 - rv_id: 13295 - rule_id: ReUPvG - version_id: 1QTeld - url: https://semgrep.dev/playground/r/1QTeld/gitlab.bandit.B502.B503 - origin: community - severity: WARNING - languages: - - python -- id: gitlab.eslint.detect-object-injection - patterns: - - pattern: "$O[$ARG]" - - pattern-not: $O["..."] - - pattern-not: "$O[($ARG : float)]" - - pattern-not-inside: | - $ARG = [$V]; - ... - <... $O[$ARG] ...>; - - pattern-not-inside: | - $ARG = $V; - ... - <... $O[$ARG] ...>; - - metavariable-regex: - metavariable: "$ARG" - regex: "(?![0-9]+)" - message: Bracket object notation with user input is present, this might allow an - attacker to access all properties of the object and even it's prototype, leading - to possible code execution. - languages: - - javascript - - typescript - severity: WARNING - metadata: - cwe: 'CWE-94: Improper Control of Generation of Code (''Code Injection'')' - primary_identifier: eslint.detect-object-injection - secondary_identifiers: - - name: ESLint rule ID security/detect-object-injection - type: eslint_rule_id - value: security/detect-object-injection - license: MIT - source: https://semgrep.dev/r/gitlab.eslint.detect-object-injection - shortlink: https://sg.run/8nbQ - semgrep.dev: - rule: - r_id: 11584 - rv_id: 56280 - rule_id: NbUAnd - version_id: rxTqor - url: https://semgrep.dev/playground/r/rxTqor/gitlab.eslint.detect-object-injection - origin: community - id: mobsf.mobsfscan.android.hidden_ui.android_hidden_ui patterns: - pattern-either: