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 Weak Cryptographic Algorithms and Insecure SSL #115

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

Summary by CodeRabbit

  • New Features

    • Introduced rules to detect the use of insecure hashing algorithms (MD5, SHA-1) and weak SSL contexts in Java applications.
    • Added guidance for secure alternatives and references to security standards.
  • Tests

    • Added test configurations to validate the usage of MD5 and SHA-1 algorithms, along with SSL context configurations.
    • Included valid and invalid examples to ensure adherence to secure practices.
  • Snapshots

    • Created snapshot entries for MD5, SHA-1, and weak SSL context usages to track instantiation patterns.

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

Walkthrough

This pull request introduces three new security rules for Java applications focusing on detecting and preventing the use of weak cryptographic algorithms and insecure SSL contexts. The rules target MD5 and SHA1 hashing algorithms, which are considered cryptographically weak, and deprecated SSL/TLS versions. Each rule includes detailed configuration for identifying insecure code patterns, provides warnings about potential security risks, and references relevant security standards like CWE and OWASP guidelines.

Changes

File Change Summary
rules/java/security/use-of-md5-java.yml New rule to detect MD5 hash algorithm usage
rules/java/security/use-of-sha1-java.yml New rule to detect SHA1 hash algorithm usage
rules/java/security/weak-ssl-context-java.yml New rule to identify insecure SSL contexts
tests/__snapshots__/*-snapshot.yml Added snapshot files for each new rule
tests/java/*-test.yml Added test configurations for each new rule

Sequence Diagram

sequenceDiagram
    participant Code
    participant SecurityRule
    participant Analyzer
    
    Code->>SecurityRule: Invoke method with algorithm
    SecurityRule->>Analyzer: Check algorithm type
    alt Insecure Algorithm
        Analyzer-->>Code: Generate Warning
        Analyzer->>Code: Suggest Secure Alternative
    else Secure Algorithm
        Analyzer-->>Code: No Action
    end
Loading

Possibly related PRs

Suggested reviewers

  • rohit121

Poem

🐰 Hop, hop, through the code we go,
Weak algorithms must not grow!
MD5 and SHA1, beware,
Security rules now declare,
A rabbit's wisdom, crystal clear! 🔒


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Beta)
  • @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 Weak Cryptographic Algorithms and Insecure SSL Dec 16, 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: 6

🧹 Nitpick comments (6)
rules/java/security/weak-ssl-context-java.yml (2)

4-13: Enhance security guidance in the message

While the message correctly identifies the issue, consider enhancing it with:

  1. Explicit mention of TLSv1.3 as the preferred version
  2. Link to NIST guidelines for TLS
  3. Impact of using weak encryption
  message: >-
    'An insecure SSL context was detected. TLS versions 1.0, 1.1, and all
        SSL versions are considered weak encryption and are deprecated. Use
-       SSLContext.getInstance("TLSv1.2") for the best security.'
+       SSLContext.getInstance("TLSv1.3") (preferred) or SSLContext.getInstance("TLSv1.2").
+       Using weak encryption may expose sensitive data to security vulnerabilities.'
  note: >-
    [CWE-326] Inadequate Encryption Strength
    [REFERENCES]
        - https://tools.ietf.org/html/rfc7568
        - https://tools.ietf.org/id/draft-ietf-tls-oldversions-deprecate-02.html
+       - https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-52r2.pdf

21-75: Consider additional constraints for dynamic context generation

The constraints effectively handle:

  1. String literals with regex validation
  2. Identifiers with proper type checking
  3. Variable declarations and field access

However, consider adding constraints for:

  1. Method return values
  2. Configuration property lookups
  3. Environment variable access

This would help catch cases where the SSL context version is determined dynamically at runtime.

Would you like me to provide example constraints for these scenarios?

tests/java/use-of-md5-java-test.yml (1)

1-7: Consider adding more test cases for comprehensive coverage.

While the basic valid/invalid cases are good, consider adding:

  • Multiple provider variants (e.g., "MD5", "SUN")
  • Case sensitivity tests ("md5", "MD5")
  • Different method overloads

Example additions:

valid:
  - |
    MessageDigest md5Digest = MessageDigest.getInstance("SHA-512");
+ - |
+   MessageDigest md5Digest = MessageDigest.getInstance("SHA-256");
invalid:
  - |
    MessageDigest md5Digest = MessageDigest.getInstance("MD5");
+ - |
+   MessageDigest md5Digest = MessageDigest.getInstance("md5", "SUN");
+ - |
+   MessageDigest md5Digest = MessageDigest.getInstance("MD5", provider);
rules/java/security/use-of-md5-java.yml (1)

13-17: Consider adding patterns for other common MD5 implementations.

The current patterns focus on MessageDigest but miss other common MD5 usages.

Consider adding:

  any:
    - pattern: java.security.MessageDigest.getInstance($ALGO)
    - pattern: java.security.MessageDigest.getInstance($ALGO, $$$)
    - pattern: MessageDigest.getInstance($ALGO)
    - pattern: MessageDigest.getInstance($ALGO, $$$)
+   - pattern: org.apache.commons.codec.digest.DigestUtils.md5($$$)
+   - pattern: org.apache.commons.codec.digest.DigestUtils.md5Hex($$$)
+   - pattern: com.google.common.hash.Hashing.md5()
tests/java/use-of-sha1-java-test.yml (1)

8-18: Consider adding more comprehensive test cases.

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

invalid:
  - |
    java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA1", "SUN");
    DigestUtils.getSha1Digest().digest(password.getBytes());
  - |
    MessageDigest sha1Digest = MessageDigest.getInstance("SHA1", "SUN");
  - |
    byte[] hashValue = DigestUtils.getSha1Digest().digest(password.getBytes());
  - |
    MessageDigest sha1Digest = MessageDigest.getInstance("SHA1");
+ - |
+   MessageDigest sha1Digest = MessageDigest.getInstance("sha1");  // Case variation
+ - |
+   com.google.common.hash.HashFunction hf = Hashing.sha1();  // Guava implementation
+ - |
+   org.apache.commons.codec.digest.DigestUtils.sha1Hex(password);  // Commons Codec
rules/java/security/use-of-sha1-java.yml (1)

4-12: Enhance security context in documentation

Consider adding more specific details to strengthen the security guidance:

  • Include the year SHA1 was officially broken (2017 with the SHAttered attack)
  • Add NIST recommendations and references
  • Specify minimum key lengths for SHA256/SHA512
 message: >-
   Detected SHA1 hash algorithm which is considered insecure. SHA1 is not
   collision resistant and is therefore not suitable as a cryptographic
   signature. Instead, use PBKDF2 for password hashing or SHA256 or SHA512
-  for other hash function applications.
+  for other hash function applications. SHA1 was officially broken in 2017
+  through the SHAttered attack, and NIST recommends using SHA256 or stronger.
 note: >-
   [CWE-328] Use of Weak Hash.
   [REFERENCES]
       - https://owasp.org/Top10/A02_2021-Cryptographic_Failures
+      - https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar2.pdf
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3b6d6f3 and 67064b6.

📒 Files selected for processing (9)
  • rules/java/security/use-of-md5-java.yml (1 hunks)
  • rules/java/security/use-of-sha1-java.yml (1 hunks)
  • rules/java/security/weak-ssl-context-java.yml (1 hunks)
  • tests/__snapshots__/use-of-md5-java-snapshot.yml (1 hunks)
  • tests/__snapshots__/use-of-sha1-java-snapshot.yml (1 hunks)
  • tests/__snapshots__/weak-ssl-context-java-snapshot.yml (1 hunks)
  • tests/java/use-of-md5-java-test.yml (1 hunks)
  • tests/java/use-of-sha1-java-test.yml (1 hunks)
  • tests/java/weak-ssl-context-java-test.yml (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • tests/snapshots/use-of-md5-java-snapshot.yml
  • tests/snapshots/use-of-sha1-java-snapshot.yml
🔇 Additional comments (5)
tests/java/weak-ssl-context-java-test.yml (2)

2-8: Consider adding validation for dynamic context retrieval

The valid patterns correctly include TLSv1.2 and TLSv1.3. However, the dynamic context retrieval via getSslContext() might need additional validation to ensure it doesn't return insecure versions at runtime.

Consider adding constraints or documentation for the getSslContext() method to ensure it only returns secure TLS versions.


9-19: LGTM! Comprehensive coverage of insecure SSL/TLS versions

The invalid patterns correctly identify all deprecated and insecure SSL/TLS versions:

  • SSL (generic)
  • TLS (generic)
  • TLSv1
  • SSLv3
  • TLSv1.1

This aligns with security best practices and NIST recommendations.

tests/__snapshots__/weak-ssl-context-java-snapshot.yml (1)

1-37: LGTM! Well-structured snapshots with complete coverage

The snapshots:

  1. Cover all insecure SSL/TLS versions defined in the test file
  2. Include precise source location information for each case
  3. Maintain consistent styling across all cases

This provides good test coverage for the security rule.

rules/java/security/weak-ssl-context-java.yml (1)

14-20: LGTM! Effective pattern matching for SSL context detection

The rule correctly:

  1. Identifies calls to SSLContext.getInstance()
  2. Excludes secure versions (TLSv1.2 and TLSv1.3)
  3. Uses negative patterns to prevent false positives
rules/java/security/use-of-sha1-java.yml (1)

1-22: Verify rule coverage and false positives

Let's ensure the rule effectively catches all SHA1 usage patterns while avoiding false positives.

✅ Verification successful

Let me gather more information about the test coverage to ensure the rule's effectiveness.


Rule implementation and test coverage verified successfully

The rule effectively covers all common SHA1 usage patterns in Java:

  • Direct MessageDigest.getInstance calls with "SHA1" or "SHA-1"
  • Qualified MessageDigest.getInstance calls
  • DigestUtils.getSha1Digest() usage
  • Provider-specific instantiation

The test file comprehensively covers all patterns defined in the rule with appropriate valid and invalid test cases, ensuring the rule's reliability in detecting insecure SHA1 usage while avoiding false positives.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify rule coverage and potential false positives

# Check if there are corresponding test files
echo "Checking for test files..."
fd "use-of-sha1.*test" tests/

# Check for potential SHA1 usages that might be missed
echo "Checking for potential missed SHA1 patterns..."
rg -i "sha-?1" --type java

# Check for similar security rules to ensure consistency
echo "Checking for similar security rules..."
fd "." rules/java/security/ -e yml | xargs cat | grep -i "MessageDigest"

Length of output: 960


Script:

#!/bin/bash
# Check the test file content to verify coverage of all patterns
echo "Checking test content..."
cat tests/java/use-of-sha1-java-test.yml

# Check for any other potential SHA1-related patterns in the codebase
echo "Checking for additional SHA1 patterns..."
rg -i "sha-?1|messagedigest" --type-list
rg -i "sha-?1|messagedigest" -g "*.java" || echo "No .java files found"

Length of output: 1538

rules/java/security/use-of-md5-java.yml Show resolved Hide resolved
- |
MessageDigest sha1Digest = MessageDigest.getInstance("SHA1", "SUN");
- |
byte[] hashValue = DigestUtils.getSha1Digest().digest(password.getBytes());
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove duplicate test case.

The test case for DigestUtils.getSha1Digest() appears twice (lines 14 and 18).

  - |
    byte[] hashValue = DigestUtils.getSha1Digest().digest(password.getBytes());
  - |
    MessageDigest sha1Digest = MessageDigest.getInstance("SHA1");
- - |
-   byte[] hashValue = DigestUtils.getSha1Digest().digest(password.getBytes());

Also applies to: 18-18

tests/java/use-of-sha1-java-test.yml Show resolved Hide resolved
rules/java/security/use-of-sha1-java.yml Show resolved Hide resolved
rules/java/security/use-of-sha1-java.yml Show resolved Hide resolved
rules/java/security/use-of-sha1-java.yml Show resolved Hide resolved
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