Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Security Rules for Flask, psycopg2, and urllib3 in Python Applications #103

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

ESS-ENN
Copy link
Collaborator

@ESS-ENN ESS-ENN commented Dec 11, 2024

Summary by CodeRabbit

  • New Features

    • Introduced new security rules for detecting insecure practices in Python applications:
      • hashids-with-flask-secret-python: Flags use of Flask secret key as salt in HashIDs.
      • python-psycopg2-empty-password-python: Warns against using empty passwords in database connections.
      • python-urllib3-hardcoded-secret-python: Identifies hard-coded secrets in HTTP headers.
  • Tests

    • Added test configurations and snapshots for validating the new security rules and their behaviors in various scenarios.

Copy link

coderabbitai bot commented Dec 11, 2024

Walkthrough

This pull request introduces three new security rules for Python applications: one for detecting the insecure use of Flask's secret key as salt in HashIDs, another for preventing database connections with empty passwords in psycopg2, and a third for identifying hard-coded secrets in urllib3. Each rule is accompanied by test snapshots and configurations to validate their implementations. The rules are categorized under relevant Common Weakness Enumeration (CWE) identifiers, emphasizing the importance of secure coding practices.

Changes

File Path Change Summary
rules/python/security/hashids-with-flask-secret-python.yml - New rule added: hashids-with-flask-secret-python to warn against using Flask's secret key as salt in HashIDs.
- Categorized under CWE-327.
rules/python/security/python-psycopg2-empty-password-python.yml - New rule added: python-psycopg2-empty-password-python to prevent database connections with empty passwords.
- Severity level set to warning, categorized under CWE-287.
rules/python/security/python-urllib3-hardcoded-secret-python.yml - New rule added: python-urllib3-hardcoded-secret-python to detect hard-coded secrets in urllib3.
- Severity level set to warning, categorized under CWE-798.
tests/__snapshots__/hashids-with-flask-secret-python-snapshot.yml - Snapshots added for testing variations of Hashids instantiation with Flask's secret key.
tests/__snapshots__/python-psycopg2-empty-password-python-snapshot.yml - Snapshots added for testing psycopg2 connection attempts with empty passwords.
tests/__snapshots__/python-urllib3-hardcoded-secret-python-snapshot.yml - Snapshots added for testing various configurations of urllib3's header generation with basic authentication.
tests/python/hashids-with-flask-secret-python-test.yml - New test cases added to validate correct and incorrect usages of Hashids with Flask's secret key.
tests/python/python-psycopg2-empty-password-python-test.yml - New test cases added to validate connection attempts with valid and invalid password inputs for psycopg2.
tests/python/python-urllib3-hardcoded-secret-python-test.yml - New test cases added to validate proper usage of basic authentication in urllib3's make_headers function.

Possibly related PRs

Suggested reviewers

  • harjotgill

Poem

In the land of code where bunnies hop,
New rules for safety, we’ll never stop!
With secrets secured and passwords tight,
Our Python apps will shine so bright!
So let’s code with care, and never fear,
For security’s here, let’s give a cheer! 🐇✨


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@CLAassistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.


Sakshis seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@coderabbitai coderabbitai bot changed the title @coderabbitai Add Security Rules for Flask, psycopg2, and urllib3 in Python Applications Dec 11, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (8)
tests/python/python-urllib3-hardcoded-secret-python-test.yml (1)

3-4: Consider clarifying the valid example syntax

The valid example urllib3.util.make_headers(basic_auth=user:123) might be confusing as it appears to use a literal without quotes. Consider adding more valid examples that demonstrate proper variable usage:

# Add these valid examples
username = os.getenv('USERNAME')
password = os.getenv('PASSWORD')
urllib3.util.make_headers(basic_auth=f"{username}:{password}")

# Or using a configuration object
auth_config = get_auth_config()  # from secure storage
urllib3.util.make_headers(basic_auth=f"{auth_config.user}:{auth_config.password}")
rules/python/security/python-urllib3-hardcoded-secret-python.yml (1)

14-101: Fix YAML indentation and consider adding references

While the rule patterns are comprehensive, there are some improvements needed:

  1. Fix the inconsistent YAML indentation throughout the file
  2. Consider adding more security references:
 note: >-
   [CWE-798] Use of Hard-coded Credentials.
   [REFERENCES]
       - https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html
+      - https://owasp.org/www-community/vulnerabilities/Use_of_hard-coded_password
+      - https://cwe.mitre.org/data/definitions/798.html
+      - https://docs.python.org/3/library/os.html#os.getenv
🧰 Tools
🪛 yamllint (1.35.1)

[error] 14-14: trailing spaces

(trailing-spaces)


[warning] 19-19: wrong indentation: expected 3 but found 4

(indentation)


[warning] 20-20: wrong indentation: expected 7 but found 8

(indentation)


[warning] 24-24: wrong indentation: expected 7 but found 8

(indentation)


[warning] 27-27: wrong indentation: expected 9 but found 10

(indentation)


[warning] 30-30: wrong indentation: expected 11 but found 12

(indentation)


[warning] 31-31: wrong indentation: expected 15 but found 16

(indentation)


[warning] 35-35: wrong indentation: expected 15 but found 16

(indentation)


[warning] 38-38: wrong indentation: expected 17 but found 18

(indentation)


[warning] 44-44: wrong indentation: expected 3 but found 4

(indentation)


[warning] 45-45: wrong indentation: expected 7 but found 8

(indentation)


[warning] 49-49: wrong indentation: expected 7 but found 8

(indentation)


[warning] 52-52: wrong indentation: expected 9 but found 10

(indentation)


[warning] 55-55: wrong indentation: expected 11 but found 12

(indentation)


[warning] 56-56: wrong indentation: expected 15 but found 16

(indentation)


[warning] 60-60: wrong indentation: expected 15 but found 16

(indentation)


[warning] 65-65: wrong indentation: expected 7 but found 8

(indentation)


[warning] 68-68: wrong indentation: expected 9 but found 10

(indentation)


[warning] 71-71: wrong indentation: expected 11 but found 12

(indentation)


[warning] 74-74: wrong indentation: expected 13 but found 14

(indentation)


[warning] 75-75: wrong indentation: expected 17 but found 18

(indentation)


[warning] 79-79: wrong indentation: expected 17 but found 18

(indentation)


[warning] 82-82: wrong indentation: expected 19 but found 20

(indentation)


[warning] 85-85: wrong indentation: expected 7 but found 8

(indentation)


[warning] 92-92: wrong indentation: expected 11 but found 12

(indentation)


[warning] 95-95: wrong indentation: expected 13 but found 14

(indentation)


[warning] 96-96: wrong indentation: expected 17 but found 18

(indentation)


[warning] 100-100: wrong indentation: expected 17 but found 18

(indentation)

rules/python/security/hashids-with-flask-secret-python.yml (2)

4-8: Fix typo in the warning message

There's an extra parenthesis in the message that affects readability.

Apply this diff:

      The Flask secret key is used as salt in HashIDs. The HashID mechanism
      is not secure. By observing sufficient HashIDs, the salt used to construct
      them can be recovered. This means the Flask secret key can be obtained by
-      attackers, through the HashIDs).
+      attackers through the HashIDs.

14-192: Consider adding pattern for direct secret key access

The patterns cover various ways of accessing Flask's secret key through config, but might miss direct access to secret_key attribute.

Consider adding patterns for:

# Pattern: Direct secret_key access
app.secret_key
current_app.secret_key
tests/python/hashids-with-flask-secret-python-test.yml (1)

1-25: Consider adding edge case test scenarios

While the current test coverage is good, consider adding these edge cases:

  1. Using a variable assigned from app.config['SECRET_KEY']
  2. Using string concatenation or formatting with the secret key
  3. Using dictionary unpacking with config values

Example test cases:

# Variable assignment
secret = app.config['SECRET_KEY']
hashids = Hashids(salt=secret)

# String formatting
hashids = Hashids(salt=f"{app.config['SECRET_KEY']}_suffix")

# Dict unpacking
config = {'salt': app.config['SECRET_KEY']}
hashids = Hashids(**config)
tests/__snapshots__/hashids-with-flask-secret-python-snapshot.yml (1)

1-230: Consider using relative positions for source mappings

The current absolute source positions (start/end) might be fragile to code changes. Consider using relative positions or pattern-based matching where possible.

Example approach:

# Instead of absolute positions:
start: 74
end: 126

# Consider relative positions from anchor points:
anchor: "Hashids("
offset_start: 0
offset_end: 52
tests/python/python-psycopg2-empty-password-python-test.yml (1)

5-10: Consider adding more test cases for comprehensive coverage.

While the current invalid cases cover empty string scenarios well, consider adding these additional cases for better coverage:

invalid:
  - |
    psycopg2.connect(password="")
  - |
    PASSWORD = ""
    psycopg2.connect(password=PASSWORD)
+ - |
+   psycopg2.connect(password=None)
+ - |
+   psycopg2.connect(password="   ")
+ - |
+   PASSWORD = None
+   psycopg2.connect(password=PASSWORD)
rules/python/security/python-psycopg2-empty-password-python.yml (1)

1-14: Enhance security message with specific mitigation steps.

The message and documentation are good, but could be more actionable by including specific code examples.

 message: >-
       The application creates a database connection with an empty password.
       This can lead to unauthorized access by either an internal or external
       malicious actor. To prevent this vulnerability, enforce authentication
       when connecting to a database by using environment variables to securely
       provide credentials or retrieving them from a secure vault or HSM
-      (Hardware Security Module).
+      (Hardware Security Module).
+      
+      Example of secure implementation:
+      ```python
+      import os
+      password = os.environ.get('DB_PASSWORD')
+      if not password:
+          raise ValueError("Database password must be configured")
+      psycopg2.connect(password=password)
+      ```
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2f95a8e and d7e7531.

📒 Files selected for processing (9)
  • rules/python/security/hashids-with-flask-secret-python.yml (1 hunks)
  • rules/python/security/python-psycopg2-empty-password-python.yml (1 hunks)
  • rules/python/security/python-urllib3-hardcoded-secret-python.yml (1 hunks)
  • tests/__snapshots__/hashids-with-flask-secret-python-snapshot.yml (1 hunks)
  • tests/__snapshots__/python-psycopg2-empty-password-python-snapshot.yml (1 hunks)
  • tests/__snapshots__/python-urllib3-hardcoded-secret-python-snapshot.yml (1 hunks)
  • tests/python/hashids-with-flask-secret-python-test.yml (1 hunks)
  • tests/python/python-psycopg2-empty-password-python-test.yml (1 hunks)
  • tests/python/python-urllib3-hardcoded-secret-python-test.yml (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/snapshots/python-psycopg2-empty-password-python-snapshot.yml
🧰 Additional context used
🪛 yamllint (1.35.1)
rules/python/security/python-urllib3-hardcoded-secret-python.yml

[error] 14-14: trailing spaces

(trailing-spaces)


[warning] 19-19: wrong indentation: expected 3 but found 4

(indentation)


[warning] 20-20: wrong indentation: expected 7 but found 8

(indentation)


[warning] 24-24: wrong indentation: expected 7 but found 8

(indentation)


[warning] 27-27: wrong indentation: expected 9 but found 10

(indentation)


[warning] 30-30: wrong indentation: expected 11 but found 12

(indentation)


[warning] 31-31: wrong indentation: expected 15 but found 16

(indentation)


[warning] 35-35: wrong indentation: expected 15 but found 16

(indentation)


[warning] 38-38: wrong indentation: expected 17 but found 18

(indentation)


[warning] 44-44: wrong indentation: expected 3 but found 4

(indentation)


[warning] 45-45: wrong indentation: expected 7 but found 8

(indentation)


[warning] 49-49: wrong indentation: expected 7 but found 8

(indentation)


[warning] 52-52: wrong indentation: expected 9 but found 10

(indentation)


[warning] 55-55: wrong indentation: expected 11 but found 12

(indentation)


[warning] 56-56: wrong indentation: expected 15 but found 16

(indentation)


[warning] 60-60: wrong indentation: expected 15 but found 16

(indentation)


[warning] 65-65: wrong indentation: expected 7 but found 8

(indentation)


[warning] 68-68: wrong indentation: expected 9 but found 10

(indentation)


[warning] 71-71: wrong indentation: expected 11 but found 12

(indentation)


[warning] 74-74: wrong indentation: expected 13 but found 14

(indentation)


[warning] 75-75: wrong indentation: expected 17 but found 18

(indentation)


[warning] 79-79: wrong indentation: expected 17 but found 18

(indentation)


[warning] 82-82: wrong indentation: expected 19 but found 20

(indentation)


[warning] 85-85: wrong indentation: expected 7 but found 8

(indentation)


[warning] 92-92: wrong indentation: expected 11 but found 12

(indentation)


[warning] 95-95: wrong indentation: expected 13 but found 14

(indentation)


[warning] 96-96: wrong indentation: expected 17 but found 18

(indentation)


[warning] 100-100: wrong indentation: expected 17 but found 18

(indentation)


[warning] 103-103: wrong indentation: expected 1 but found 2

(indentation)


[warning] 105-105: wrong indentation: expected 3 but found 4

(indentation)

tests/python/python-urllib3-hardcoded-secret-python-test.yml

[error] 14-14: trailing spaces

(trailing-spaces)


[error] 17-17: trailing spaces

(trailing-spaces)

🔇 Additional comments (5)
tests/python/python-urllib3-hardcoded-secret-python-test.yml (1)

6-19: LGTM! Comprehensive coverage of invalid patterns

The invalid test cases effectively cover various problematic patterns:

  • Direct string literals in basic_auth
  • Direct string literals in proxy_basic_auth
  • String concatenation with hard-coded values
  • Variable assignments with hard-coded values
  • Different package import paths
🧰 Tools
🪛 yamllint (1.35.1)

[error] 14-14: trailing spaces

(trailing-spaces)


[error] 17-17: trailing spaces

(trailing-spaces)

rules/python/security/python-urllib3-hardcoded-secret-python.yml (1)

4-13: LGTM! Clear and informative security message

The message effectively:

  • Explains the security risk
  • Provides mitigation strategies
  • References relevant security standards
tests/__snapshots__/python-urllib3-hardcoded-secret-python-snapshot.yml (1)

1-238: LGTM! Comprehensive and accurate test snapshots

The snapshots effectively:

  • Map all test cases with precise source locations
  • Include both full expressions and their components
  • Maintain consistent style categorization
rules/python/security/hashids-with-flask-secret-python.yml (1)

193-201: LGTM! Comprehensive pattern matching

The rule effectively combines all utility patterns to catch various ways of using Flask's secret key as salt in HashIDs.

tests/python/python-psycopg2-empty-password-python-test.yml (1)

1-4: LGTM! Valid test case looks good.

The valid test case correctly demonstrates proper password usage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants