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 detecting hard-coded secrets in C# and Python #99

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 9, 2024

Summary by CodeRabbit

  • New Features
    • Introduced security rules to detect hard-coded secrets in C# and Python applications, including:
      • Hard-coded secrets in OracleConnectionStringBuilder for C#.
      • Hard-coded bearer tokens in Elasticsearch for Python.
      • Empty passwords in Peewee ORM with MySQL for Python.
  • Tests
    • Added comprehensive test cases for the new security rules, including valid and invalid scenarios for each rule across C# and Python implementations.

@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.

Copy link

coderabbitai bot commented Dec 9, 2024

Walkthrough

This pull request introduces new security rules in YAML files for C# and Python applications to detect hard-coded secrets and empty passwords in database connections. Specifically, it adds rules for the OracleConnectionStringBuilder in C#, the Elasticsearch client in Python, and the Peewee ORM with MySQL. Accompanying test configurations are also created to validate these rules, ensuring that developers adhere to best practices regarding sensitive information management.

Changes

File Path Change Summary
rules/csharp/security/oracleconnectionstringbuilder-hardcoded-secret-csharp.yml Added rule oracleconnectionstringbuilder-hardcoded-secret-csharp to detect hard-coded secrets.
rules/python/security/python-elasticsearch-hardcoded-bearer-auth-python.yml Added rule python-elasticsearch-hardcoded-bearer-auth-python for detecting hard-coded bearer tokens.
rules/python/security/python-peewee-mysql-empty-password-python.yml Added rule python-peewee-mysql-empty-password-python to flag empty passwords in database connections.
tests/snapshots/oracleconnectionstringbuilder-hardcoded-secret-csharp-snapshot.yml Added snapshots for testing OracleConnectionStringBuilder password assignments.
tests/snapshots/python-elasticsearch-hardcoded-bearer-auth-python-snapshot.yml Added snapshots for testing Elasticsearch client with bearer authentication.
tests/snapshots/python-peewee-mysql-empty-password-python-snapshot.yml Added snapshots for testing Peewee ORM with MySQL database connections using empty passwords.
tests/csharp/oracleconnectionstringbuilder-hardcoded-secret-csharp-test.yml Added test case for validating OracleConnectionStringBuilder usage regarding hard-coded passwords.
tests/python/python-elasticsearch-hardcoded-bearer-auth-python-test.yml Added test cases for validating Elasticsearch client configurations with bearer tokens.
tests/python/python-peewee-mysql-empty-password-python-test.yml Added test cases for validating MySQLDatabase connections with empty passwords.

Possibly related PRs

Suggested reviewers

  • petrisorcoderabbit
  • harjotgill

🐰 In the code we hop and play,
To keep our secrets safe each day.
With rules to guard both night and morn,
From hard-coded strings, we are reborn!
So let’s write tests, both clear and bright,
To keep our code secure and right! 🌟


🪧 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 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.

@coderabbitai coderabbitai bot changed the title @coderabbitai Add security rules for detecting hard-coded secrets in C# and Python Dec 9, 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: 2

🧹 Outside diff range and nitpick comments (8)
tests/python/python-elasticsearch-hardcoded-bearer-auth-python-test.yml (2)

6-40: Consider adding more edge cases to the test suite.

While the current test cases cover basic scenarios, consider adding:

  • Bearer token with environment variables
  • Bearer token with secure vault integration
  • Bearer token with AWS Secrets Manager or similar services
🧰 Tools
🪛 yamllint (1.35.1)

[error] 40-40: trailing spaces

(trailing-spaces)


5-5: Fix formatting issues.

There are trailing spaces and extra blank lines at the end of the file.

-    
+
 invalid:
   - |
     from elasticsearch import Elasticsearch
@@ -40,3 +40,1 @@
-    ).indices.get(index="*") 
-
-
+    ).indices.get(index="*")

Also applies to: 40-42

🧰 Tools
🪛 yamllint (1.35.1)

[error] 5-5: trailing spaces

(trailing-spaces)

rules/python/security/python-elasticsearch-hardcoded-bearer-auth-python.yml (1)

14-435: Consider adding examples in the documentation.

The rule implementation is comprehensive and covers various patterns effectively. Consider adding code examples in the documentation to illustrate:

  • ✅ Correct ways to provide bearer tokens
  • ❌ Patterns that will trigger the rule
tests/python/python-peewee-mysql-empty-password-python-test.yml (1)

7-7: Remove trailing spaces

Remove trailing spaces at the end of lines 7 and 24.

Also applies to: 24-24

🧰 Tools
🪛 yamllint (1.35.1)

[error] 7-7: trailing spaces

(trailing-spaces)

rules/python/security/python-peewee-mysql-empty-password-python.yml (1)

31-31: Fix indentation inconsistencies

The file has multiple indentation issues. Please ensure consistent indentation throughout the file.

Also applies to: 40-40, 57-57, 69-69, 73-73, 76-76, 85-85, 95-95, 110-110, 119-119, 131-131, 146-146, 161-161, 180-180, 190-190, 194-194, 197-197, 206-206, 211-211

🧰 Tools
🪛 yamllint (1.35.1)

[warning] 31-31: wrong indentation: expected 10 but found 12

(indentation)

tests/csharp/oracleconnectionstringbuilder-hardcoded-secret-csharp-test.yml (2)

2-4: Consider adding more valid test cases.

The test configuration would benefit from additional valid examples demonstrating other secure patterns, such as:

  • Reading from environment variables
  • Using secure configuration providers
  • Using Azure Key Vault or other secret management services
 valid:
   - |
     builder.Password = args[1];
+  - |
+    builder.Password = Environment.GetEnvironmentVariable("DB_PASSWORD");
+  - |
+    builder.Password = configuration.GetValue<string>("ConnectionStrings:Password");
+  - |
+    builder.Password = await keyVaultClient.GetSecretAsync("DbPassword");

6-29: Add test cases for connection string parsing.

The test suite should also validate scenarios where passwords are extracted from connection strings, as this is another common pattern where secrets might be hard-coded.

 invalid:
+  - |
+    private OracleConnectionStringBuilder GetConnection(args)
+    {
+      return new OracleConnectionStringBuilder("Data Source=localhost;Password=hardcoded123;");
+    }
   // ... existing test cases ...
rules/csharp/security/oracleconnectionstringbuilder-hardcoded-secret-csharp.yml (1)

4-14: Enhance security message with concrete examples.

The warning message could be more actionable by including specific examples of secure alternatives.

 message: >-
   A secret is hard-coded in the application. Secrets stored in source
   code, such as credentials, identifiers, and other types of sensitive data,
   can be leaked and used by internal or external malicious actors. Use
   environment variables to securely provide credentials and other secrets or
-  retrieve them from a secure vault or Hardware Security Module (HSM).
+  retrieve them from a secure vault or Hardware Security Module (HSM).
+  
+  Examples of secure alternatives:
+  - Environment variables: builder.Password = Environment.GetEnvironmentVariable("DB_PASSWORD");
+  - Configuration providers: builder.Password = configuration.GetValue<string>("ConnectionStrings:Password");
+  - Azure Key Vault: builder.Password = await keyVaultClient.GetSecretAsync("DbPassword");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

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

📒 Files selected for processing (9)
  • rules/csharp/security/oracleconnectionstringbuilder-hardcoded-secret-csharp.yml (1 hunks)
  • rules/python/security/python-elasticsearch-hardcoded-bearer-auth-python.yml (1 hunks)
  • rules/python/security/python-peewee-mysql-empty-password-python.yml (1 hunks)
  • tests/__snapshots__/oracleconnectionstringbuilder-hardcoded-secret-csharp-snapshot.yml (1 hunks)
  • tests/__snapshots__/python-elasticsearch-hardcoded-bearer-auth-python-snapshot.yml (1 hunks)
  • tests/__snapshots__/python-peewee-mysql-empty-password-python-snapshot.yml (1 hunks)
  • tests/csharp/oracleconnectionstringbuilder-hardcoded-secret-csharp-test.yml (1 hunks)
  • tests/python/python-elasticsearch-hardcoded-bearer-auth-python-test.yml (1 hunks)
  • tests/python/python-peewee-mysql-empty-password-python-test.yml (1 hunks)
🧰 Additional context used
🪛 yamllint (1.35.1)
tests/python/python-elasticsearch-hardcoded-bearer-auth-python-test.yml

[error] 5-5: trailing spaces

(trailing-spaces)


[error] 40-40: trailing spaces

(trailing-spaces)


[warning] 42-42: too many blank lines

(2 > 0) (empty-lines)

rules/python/security/python-peewee-mysql-empty-password-python.yml

[warning] 31-31: wrong indentation: expected 10 but found 12

(indentation)


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

(indentation)


[warning] 57-57: wrong indentation: expected 10 but found 12

(indentation)


[error] 69-69: trailing spaces

(trailing-spaces)


[warning] 73-73: wrong indentation: expected 12 but found 14

(indentation)


[warning] 76-76: wrong indentation: expected 14 but found 16

(indentation)


[warning] 85-85: wrong indentation: expected 24 but found 23

(indentation)


[warning] 95-95: wrong indentation: expected 8 but found 10

(indentation)


[warning] 110-110: wrong indentation: expected 10 but found 12

(indentation)


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

(indentation)


[warning] 131-131: wrong indentation: expected 12 but found 14

(indentation)


[warning] 146-146: wrong indentation: expected 8 but found 10

(indentation)


[warning] 161-161: wrong indentation: expected 10 but found 12

(indentation)


[warning] 180-180: wrong indentation: expected 12 but found 14

(indentation)


[error] 190-190: trailing spaces

(trailing-spaces)


[warning] 194-194: wrong indentation: expected 12 but found 14

(indentation)


[warning] 197-197: wrong indentation: expected 14 but found 16

(indentation)


[warning] 206-206: wrong indentation: expected 24 but found 23

(indentation)


[warning] 211-211: wrong indentation: expected 2 but found 4

(indentation)

tests/python/python-peewee-mysql-empty-password-python-test.yml

[error] 7-7: trailing spaces

(trailing-spaces)


[error] 24-24: trailing spaces

(trailing-spaces)

🔇 Additional comments (8)
tests/python/python-elasticsearch-hardcoded-bearer-auth-python-test.yml (1)

2-4: LGTM! Well-structured test cases.

The valid test case correctly demonstrates proper instantiation of the Elasticsearch client without hardcoded secrets.

tests/__snapshots__/python-elasticsearch-hardcoded-bearer-auth-python-snapshot.yml (1)

1-298: LGTM! Well-structured test snapshots.

The snapshots provide comprehensive coverage of the test cases with proper style annotations for highlighting.

rules/python/security/python-elasticsearch-hardcoded-bearer-auth-python.yml (2)

1-13: LGTM! Well-documented security rule.

The rule provides clear guidance with appropriate references to CWE-798 and OWASP documentation.


436-445: LGTM! Comprehensive pattern matching.

The rule effectively matches all common patterns of hardcoded bearer token usage in Elasticsearch clients.

rules/python/security/python-peewee-mysql-empty-password-python.yml (1)

23-23: Verify database class patterns

The regex patterns for database classes look good, but let's verify they catch all possible variations.

Also applies to: 49-49, 102-102, 137-137, 153-153

✅ Verification successful

Database class patterns are comprehensive and accurate

Based on the search results from the test files and rule definitions, the regex pattern correctly covers all MySQL-related database classes used in the codebase:

  • MySQLDatabase (direct and peewee-prefixed)
  • MySQLConnectorDatabase (direct and playhouse.mysql_ext-prefixed)
  • MariaDBConnectorDatabase (direct and playhouse.mysql_ext-prefixed)
  • PooledMySQLDatabase (direct and playhouse.pool-prefixed)

The test files confirm these are the actual patterns used in real code scenarios, and no additional variations were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any MySQL-related database class definitions that might not be covered
rg -l "class.*MySQL.*Database" 

Length of output: 32


Script:

#!/bin/bash
# Let's try a broader search for MySQL database related patterns in the codebase
rg -i "mysql.*database|database.*mysql" -A 2

# Also search for peewee database imports or usage
rg -i "peewee.*database|from peewee import.*database" -A 2

# Search for playhouse database related imports
rg -i "playhouse.*database|from playhouse import.*database" -A 2

Length of output: 14775

tests/__snapshots__/python-peewee-mysql-empty-password-python-snapshot.yml (1)

1-284: LGTM! Snapshot implementation is comprehensive

The snapshot file correctly maps all test cases with accurate source segments and line numbers.

tests/__snapshots__/oracleconnectionstringbuilder-hardcoded-secret-csharp-snapshot.yml (1)

1-262: LGTM! Comprehensive snapshot coverage.

The snapshot file provides thorough coverage of different syntactic patterns and correctly maps source positions for accurate error reporting.

rules/csharp/security/oracleconnectionstringbuilder-hardcoded-secret-csharp.yml (1)

1-247: Verify rule effectiveness with real-world examples.

Let's verify the rule's effectiveness against common patterns in the codebase.

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