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 hard-coded secrets and error handling in C#, Java, and Kotlin #104

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 rules for detecting stack trace disclosures and hard-coded secrets in C#, Java, and Kotlin applications.
    • Added validation rules for exception handling and credential management to enhance security practices.
  • Tests

    • Created test configurations to validate proper handling of credentials and JWT creation in Java and Kotlin.
    • Added snapshots to facilitate testing of hard-coded secrets and stack trace disclosures.
  • Documentation

    • Included notes and resources for developers regarding security vulnerabilities related to sensitive information exposure.

@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 11, 2024

Walkthrough

This pull request introduces several new security rules across C#, Java, and Kotlin to enhance the detection of hard-coded secrets and improper error handling practices. Specifically, it adds rules to prevent stack trace disclosures in production environments and to identify hard-coded credentials in Java and Kotlin applications. Additionally, it includes corresponding test configurations to validate these rules, ensuring that developers adhere to best practices for security and sensitive data management.

Changes

File Path Change Summary
rules/csharp/security/stacktrace-disclosure-csharp.yml New rule stacktrace-disclosure-csharp added with severity warning; checks for UseDeveloperExceptionPage in non-development environments.
rules/java/security/hardcoded-secret-in-credentials-java.yml New rule hardcoded-secret-in-credentials-java added; includes utility functions to detect hard-coded secrets.
rules/kotlin/security/jwt-hardcode-kotlin.yml New file jwt-hardcode-kotlin.yml created with rules for detecting hard-coded secrets in JWT creation.
tests/snapshots/hardcoded-secret-in-credentials-java-snapshot.yml New snapshot for Java class OkhttpSecretBasicAuth capturing hard-coded credentials.
tests/snapshots/jwt-hardcode-kotlin-snapshot.yml New snapshot for Kotlin JWT creation with hard-coded secret.
tests/snapshots/stacktrace-disclosure-csharp-snapshot.yml New snapshot for C# stack trace disclosure handling based on environment conditions.
tests/csharp/stacktrace-disclosure-csharp-test.yml New validation rules for exception handling configurations in C# applications.
tests/java/hardcoded-secret-in-credentials-java-test.yml New test configuration for validating credential management in Java code.
tests/kotlin/jwt-hardcode-kotlin-test.yml New test configuration with valid and invalid JWT creation scenarios in Kotlin.

Possibly related PRs

Suggested reviewers

  • petrisorcoderabbit

Poem

In the code where secrets hide,
A rabbit hops with joy and pride.
No more traces in the night,
Hard-coded secrets out of sight!
With rules to guard and tests in place,
Our apps are safe, a secure space! 🐇✨


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

@coderabbitai coderabbitai bot changed the title @coderabbitai Add security rules for hard-coded secrets and error handling in C#, Java, and Kotlin 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: 8

🧹 Outside diff range and nitpick comments (6)
rules/csharp/security/stacktrace-disclosure-csharp.yml (1)

13-24: Enhance pattern matching to catch additional cases

The current pattern only checks for direct IsDevelopment() calls. Consider enhancing it to catch:

  1. Negated production checks (!IsProduction())
  2. Environment variable comparisons (ASPNETCORE_ENVIRONMENT == "Development")
 utils:
     $APP.UseDeveloperExceptionPage(...):
      kind: expression_statement
      pattern: $APP.UseDeveloperExceptionPage($$$);
      inside:
          stopBy: neighbor
          kind: block
          not:
           follows:
             stopBy: end
             kind: invocation_expression
-            pattern: $ENV.IsDevelopment()
+            patterns:
+              - $ENV.IsDevelopment()
+              - !$ENV.IsProduction()
+              - $ENV == "Development"
🧰 Tools
🪛 yamllint (1.35.1)

[warning] 15-15: wrong indentation: expected 8 but found 5

(indentation)


[warning] 21-21: wrong indentation: expected 13 but found 10

(indentation)


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

(indentation)

tests/csharp/stacktrace-disclosure-csharp-test.yml (1)

8-38: Add missing test cases

Consider adding these common scenarios to invalid test cases:

  1. Environment variable comparison
  2. Custom environment names
  3. Nested conditions
  - |
    if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
        {
            app.UseDeveloperExceptionPage();
        }
  - |
    if (env.EnvironmentName == "LocalDev")
        {
            app.UseDeveloperExceptionPage();
        }
  - |
    if (isDebugging)
        if (!isProd)
            {
                app.UseDeveloperExceptionPage();
            }
🧰 Tools
🪛 yamllint (1.35.1)

[error] 10-10: trailing spaces

(trailing-spaces)


[error] 12-12: trailing spaces

(trailing-spaces)


[error] 20-20: trailing spaces

(trailing-spaces)


[error] 22-22: trailing spaces

(trailing-spaces)


[error] 25-25: trailing spaces

(trailing-spaces)


[error] 30-30: trailing spaces

(trailing-spaces)


[error] 32-32: trailing spaces

(trailing-spaces)


[error] 35-35: trailing spaces

(trailing-spaces)


[error] 37-37: trailing spaces

(trailing-spaces)

tests/__snapshots__/stacktrace-disclosure-csharp-snapshot.yml (2)

1-72: Fix formatting inconsistencies

There are several formatting issues in the snapshots:

  1. Inconsistent indentation (e.g., lines 31, 68)
  2. Trailing spaces in code blocks
  3. Inconsistent newline usage

Consider running a formatter to ensure consistent style across all snapshots.


1-72: Security Implementation Review

Overall, this security rule implementation effectively addresses CWE-209 by preventing stack trace disclosure in production. However, consider these security-focused improvements:

  1. Elevate rule severity to ERROR to prevent accidental merges
  2. Add pattern matching for environment variable comparisons
  3. Fix the valid test case to properly demonstrate production error handling
  4. Add test cases for nested conditions and custom environment names

These changes will strengthen the security posture by catching more potential vulnerabilities.

rules/kotlin/security/jwt-hardcode-kotlin.yml (1)

34-34: Consider including HMAC512 in the primary pattern match.

The regex pattern ^(HMAC256$|HMAC384)$ excludes HMAC512, which is handled separately. Consider consolidating all HMAC algorithms into a single pattern for better maintainability.

-                  regex: ^(HMAC256$|HMAC384)$
+                  regex: ^(HMAC256$|HMAC384$|HMAC512$)$
rules/java/security/hardcoded-secret-in-credentials-java.yml (1)

16-84: Enhance credential pattern matching

The current pattern might miss some variations of credential creation. Consider:

  1. Adding patterns for common credential-related method names (e.g., createCredentials, getBasicAuth)
  2. Adding validation for obviously fake or test credentials (e.g., "test", "password123")
            - has:
                stopBy: end
                kind: identifier
                field: name
-               regex: "^basic$"
+               regex: "^(basic|createCredentials|getBasicAuth)$"
            - has:
                kind: string_literal
                pattern: $STRING
+               not:
+                 regex: "^(test|password|password123|admin|root)$"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

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

📒 Files selected for processing (9)
  • rules/csharp/security/stacktrace-disclosure-csharp.yml (1 hunks)
  • rules/java/security/hardcoded-secret-in-credentials-java.yml (1 hunks)
  • rules/kotlin/security/jwt-hardcode-kotlin.yml (1 hunks)
  • tests/__snapshots__/hardcoded-secret-in-credentials-java-snapshot.yml (1 hunks)
  • tests/__snapshots__/jwt-hardcode-kotlin-snapshot.yml (1 hunks)
  • tests/__snapshots__/stacktrace-disclosure-csharp-snapshot.yml (1 hunks)
  • tests/csharp/stacktrace-disclosure-csharp-test.yml (1 hunks)
  • tests/java/hardcoded-secret-in-credentials-java-test.yml (1 hunks)
  • tests/kotlin/jwt-hardcode-kotlin-test.yml (1 hunks)
🧰 Additional context used
🪛 yamllint (1.35.1)
tests/csharp/stacktrace-disclosure-csharp-test.yml

[error] 6-6: trailing spaces

(trailing-spaces)


[error] 10-10: trailing spaces

(trailing-spaces)


[error] 12-12: trailing spaces

(trailing-spaces)


[error] 20-20: trailing spaces

(trailing-spaces)


[error] 22-22: trailing spaces

(trailing-spaces)


[error] 25-25: trailing spaces

(trailing-spaces)


[error] 30-30: trailing spaces

(trailing-spaces)


[error] 32-32: trailing spaces

(trailing-spaces)


[error] 35-35: trailing spaces

(trailing-spaces)


[error] 37-37: trailing spaces

(trailing-spaces)


[warning] 39-39: too many blank lines

(1 > 0) (empty-lines)

rules/csharp/security/stacktrace-disclosure-csharp.yml

[warning] 15-15: wrong indentation: expected 8 but found 5

(indentation)


[warning] 21-21: wrong indentation: expected 13 but found 10

(indentation)


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

(indentation)


[error] 27-27: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (5)
rules/kotlin/security/jwt-hardcode-kotlin.yml (1)

1-15: LGTM! Well-structured rule definition with comprehensive documentation.

The rule configuration includes:

  • Clear severity level
  • Detailed explanation of the security risk
  • Appropriate references to CWE-798 and OWASP A03:2021
tests/kotlin/jwt-hardcode-kotlin-test.yml (1)

4-5: LGTM! Secure handling of system properties.

The valid test cases correctly demonstrate using configuration variables instead of hardcoded values for sensitive system properties.

tests/__snapshots__/jwt-hardcode-kotlin-snapshot.yml (1)

1-124: LGTM! Comprehensive snapshot with detailed labels.

The snapshot file correctly captures:

  • Code structure with imports and implementation
  • Detailed labels for pattern matching
  • Consistent with test cases
rules/java/security/hardcoded-secret-in-credentials-java.yml (1)

85-189: Simplify pattern matching logic

The current pattern matching is complex and might be fragile. Consider:

  1. Simplifying the nested structure to improve maintainability
  2. Adding patterns for additional credential creation patterns:
    • Builder pattern (CredentialsBuilder)
    • Factory methods (CredentialsFactory)
    • Static utility methods
tests/__snapshots__/hardcoded-secret-in-credentials-java-snapshot.yml (1)

1-83: LGTM: Snapshot structure is well-defined

The snapshot correctly captures:

  1. Source code segments
  2. Style information for syntax highlighting
  3. Position information for precise error reporting

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