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 Practices in Java and Go #116

Open
wants to merge 4 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

    • Added rules to detect the use of insecure cryptographic algorithms (RC2, RC4, weak RSA keys) in Java applications.
    • Introduced test configurations for validating secure cipher usage and RSA key sizes.
  • Bug Fixes

    • Invalid usages of RC2 and RC4 algorithms are now flagged to enhance security compliance.
  • Tests

    • Added test cases and snapshots for RC2, RC4, and weak RSA key scenarios to ensure proper detection and validation.

@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 cryptographic vulnerabilities. The rules detect the use of insecure cryptographic algorithms (RC2 and RC4) and weak RSA key sizes. Each rule is accompanied by corresponding test configurations and snapshot files to validate the detection mechanism. The changes aim to enhance security checks by flagging potentially vulnerable cryptographic implementations and providing guidance for using more secure alternatives.

Changes

File Change Summary
rules/java/security/use-of-rc2-java.yml New rule to detect RC2 cryptographic algorithm usage
rules/java/security/use-of-rc4-java.yml New rule to detect RC4 cryptographic algorithm usage
rules/java/security/use-of-weak-rsa-key-java.yml New rule to identify weak RSA key sizes
tests/java/use-of-rc2-java-test.yml Test configuration for RC2 algorithm detection
tests/java/use-of-rc4-java-test.yml Test configuration for RC4 algorithm detection
tests/java/use-of-weak-rsa-key-java-test.yml Test configuration for weak RSA key detection
tests/__snapshots__/use-of-rc2-java-snapshot.yml Snapshot tests for RC2 algorithm scenarios
tests/__snapshots__/use-of-rc4-java-snapshot.yml Snapshot tests for RC4 algorithm scenarios
tests/__snapshots__/use-of-weak-rsa-key-java-snapshot.yml Snapshot tests for weak RSA key scenarios

Sequence Diagram

sequenceDiagram
    participant Code
    participant SecurityRule
    participant CryptoAnalyzer
    
    Code->>SecurityRule: Invoke cryptographic method
    SecurityRule->>CryptoAnalyzer: Analyze algorithm/key size
    CryptoAnalyzer-->>SecurityRule: Detect vulnerability
    SecurityRule-->>Code: Warn about insecure implementation
Loading

Possibly related PRs

Suggested reviewers

  • petrisorcoderabbit

Poem

🐰 Cryptographic Rabbit's Warning 🔐

Beware the ciphers weak and old,
RC2 and RC4, their secrets told,
Weak RSA keys, a security fright,
Hop to stronger algorithms, do it right!

— CodeRabbit's Security Sentinel 🚨


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 Practices in Java and Go 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: 11

🧹 Nitpick comments (6)
tests/java/use-of-rc4-java-test.yml (1)

3-4: Consider adding IV initialization test case for AES/CBC.

While AES/CBC/PKCS7PADDING is a secure choice, it requires proper IV (Initialization Vector) handling. Consider adding a test case that demonstrates proper IV initialization to provide a complete example of secure usage.

valid:
  - |
    Cipher.getInstance("AES/CBC/PKCS7PADDING");
+  - |
+    SecureRandom random = new SecureRandom();
+    byte[] iv = new byte[16];
+    random.nextBytes(iv);
+    IvParameterSpec ivSpec = new IvParameterSpec(iv);
+    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");
+    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
rules/java/security/use-of-rc4-java.yml (1)

4-9: Enhance security guidance in the message.

The message provides good information but could be enhanced with more specific guidance:

message: >-
  'Use of RC4 was detected. RC4 is vulnerable to several attacks,
      including stream cipher attacks and bit flipping attacks. Instead, use a
-      strong, secure cipher: Cipher.getInstance("AES/CBC/PKCS7PADDING"). See
+      strong, secure cipher: Cipher.getInstance("AES/CBC/PKCS7PADDING") with a
+      secure random IV. Key size should be at least 256 bits. See
      https://owasp.org/www-community/Using_the_Java_Cryptographic_Extensions
      for more information.'
tests/java/use-of-rc2-java-test.yml (1)

1-39: Consider adding more test scenarios

While the current test cases cover basic RC2 usage patterns, consider adding tests for:

  1. RC2 with different modes (ECB, CBC, etc.)
  2. RC2 with different key sizes
  3. RC2 usage through reflection
  4. RC2 string concatenation cases

Would you like me to provide examples for these additional test cases?

tests/__snapshots__/use-of-rc2-java-snapshot.yml (1)

1-70: Consider adding negative test cases

The snapshot tests only verify positive matches. Consider adding negative test cases to ensure the rule doesn't produce false positives, such as:

  • Similar algorithm names (e.g., "RC2Padding")
  • Comments containing "RC2"
  • String variables containing "RC2" but used for other purposes

Would you like me to provide examples for these negative test cases?

rules/java/security/use-of-weak-rsa-key-go.yml (1)

4-5: Enhance the warning message with specific requirements

The current message could be more informative. Consider expanding it to include:

  • The minimum required key size (2048 bits)
  • The reason for this requirement
  • The impact of using weaker keys
- RSA keys should be at least 2048 bits.
+ RSA keys should be at least 2048 bits for adequate security. Keys smaller than 2048 bits are considered cryptographically weak and may be vulnerable to factoring attacks.
tests/java/use-of-weak-rsa-key-go-test.yml (1)

1-13: Add more test cases for comprehensive coverage

While the current test cases cover basic scenarios, consider adding these additional cases for better coverage:

 valid:
   - |
     rsa.GenerateKey(rand.Reader, 2048)
+  - |
+    rsa.GenerateKey(rand.Reader, 4096)
 invalid:
   - |
     pvk, err := rsa.GenerateKey(rand.Reader, 1025)
   - |
     pvk, err := rsa.GenerateKey(rand.Reader, -1929)
   - |
     pvk, err := rsa.GenerateKey(rand.Reader, 102.5)
   - |
     pvk, err := rsa.GenerateKey(rand.Reader, 192)
+  - |
+    pvk, err := rsa.GenerateKey(rand.Reader, 2047)
+  - |
+    pvk, err := rsa.GenerateKey(rand.Reader, 0)
📜 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 b6820c3.

📒 Files selected for processing (9)
  • rules/java/security/use-of-rc2-java.yml (1 hunks)
  • rules/java/security/use-of-rc4-java.yml (1 hunks)
  • rules/java/security/use-of-weak-rsa-key-go.yml (1 hunks)
  • tests/__snapshots__/use-of-rc2-java-snapshot.yml (1 hunks)
  • tests/__snapshots__/use-of-rc4-java-snapshot.yml (1 hunks)
  • tests/__snapshots__/use-of-weak-rsa-key-go-snapshot.yml (1 hunks)
  • tests/java/use-of-rc2-java-test.yml (1 hunks)
  • tests/java/use-of-rc4-java-test.yml (1 hunks)
  • tests/java/use-of-weak-rsa-key-go-test.yml (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/snapshots/use-of-rc4-java-snapshot.yml

tests/java/use-of-rc4-java-test.yml Show resolved Hide resolved
rules/java/security/use-of-rc4-java.yml Show resolved Hide resolved
rules/java/security/use-of-rc4-java.yml Show resolved Hide resolved
tests/java/use-of-rc2-java-test.yml Show resolved Hide resolved
rules/java/security/use-of-rc2-java.yml Show resolved Hide resolved
rules/java/security/use-of-rc2-java.yml Show resolved Hide resolved
rules/java/security/use-of-weak-rsa-key-go.yml Outdated Show resolved Hide resolved
tests/__snapshots__/use-of-weak-rsa-key-go-snapshot.yml Outdated Show resolved Hide resolved
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: 1

🧹 Nitpick comments (2)
tests/java/use-of-weak-rsa-key-java-test.yml (1)

6-15: Consider adding more edge cases for comprehensive testing.

While the current invalid cases cover important scenarios (weak key size, negative value, decimal value), consider adding these additional test cases:

  • Key size of 0
  • Very large key sizes (e.g., Integer.MAX_VALUE)
  • Common weak sizes (e.g., 1024 bits)
rules/java/security/use-of-weak-rsa-key-java.yml (1)

44-46: Fix indentation and trailing spaces.

The YAML indentation is incorrect and there are trailing spaces.

Apply this diff to fix the formatting:

-constraints: 
-      AST:
-        regex: '^(-?(0|[1-9][0-9]?|[1-9][0-9]{2}|1[0-9]{3}|20[0-3][0-9]|204[0-7])(\.[0-9]+)?|0|-[1-9][0-9]*|-[1-9][0-9]{2,}|-1[0-9]{3}|-20[0-3][0-9]|-204[0-7])$'
+constraints:
+  AST:
+    regex: '^(-?(0|[1-9][0-9]?|[1-9][0-9]{2}|1[0-9]{3}|20[0-3][0-9]|204[0-7])(\.[0-9]+)?|0|-[1-9][0-9]*|-[1-9][0-9]{2,}|-1[0-9]{3}|-20[0-3][0-9]|-204[0-7])$'
🧰 Tools
🪛 yamllint (1.35.1)

[error] 44-44: trailing spaces

(trailing-spaces)


[warning] 45-45: wrong indentation: expected 2 but found 6

(indentation)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b6820c3 and 9faf1ba.

📒 Files selected for processing (3)
  • rules/java/security/use-of-weak-rsa-key-java.yml (1 hunks)
  • tests/__snapshots__/use-of-weak-rsa-key-java-snapshot.yml (1 hunks)
  • tests/java/use-of-weak-rsa-key-java-test.yml (1 hunks)
🧰 Additional context used
🪛 yamllint (1.35.1)
rules/java/security/use-of-weak-rsa-key-java.yml

[error] 15-15: trailing spaces

(trailing-spaces)


[error] 44-44: trailing spaces

(trailing-spaces)


[warning] 45-45: wrong indentation: expected 2 but found 6

(indentation)

🔇 Additional comments (3)
tests/java/use-of-weak-rsa-key-java-test.yml (1)

2-5: LGTM! Valid test case correctly demonstrates secure key size.

The test case properly validates the use of 2048-bit RSA keys, which aligns with NIST recommendations for secure cryptographic practices.

rules/java/security/use-of-weak-rsa-key-java.yml (1)

1-7: LGTM! Well-documented security rule with proper references.

The rule is well-defined with:

  • Appropriate severity level
  • Clear message explaining the requirement
  • Proper reference to CWE-326
tests/__snapshots__/use-of-weak-rsa-key-java-snapshot.yml (1)

1-98: LGTM! Snapshots properly capture test scenarios.

The snapshots:

  • Accurately capture all test cases
  • Include proper source mapping
  • Have detailed labels for key components

Comment on lines +41 to +46
rule:
kind: expression_statement
matches: WeakRSA
constraints:
AST:
regex: '^(-?(0|[1-9][0-9]?|[1-9][0-9]{2}|1[0-9]{3}|20[0-3][0-9]|204[0-7])(\.[0-9]+)?|0|-[1-9][0-9]*|-[1-9][0-9]{2,}|-1[0-9]{3}|-20[0-3][0-9]|-204[0-7])$'
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

The regex pattern for RSA key size validation is incorrect and potentially dangerous

The test results reveal critical issues with the regex pattern:

  • It incorrectly accepts weak key sizes (512, 1024) that should be rejected
  • It incorrectly rejects secure key sizes (2048, 4096) that should be accepted
  • It dangerously accepts invalid values like negative numbers (-512), decimals (51.2), and zero (0)

For RSA keys, the pattern should:

  • Reject sizes below 2048 bits (current security standard)
  • Accept sizes 2048 bits and above
  • Only allow positive integers
🔗 Analysis chain

Verify the regex pattern coverage.

The regex pattern for key size validation is complex. Let's verify its coverage:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Test regex pattern against various key sizes
echo "Testing key sizes against the regex pattern..."

test_sizes=(
  "2048"  # Valid
  "512"   # Invalid - too small
  "-512"  # Invalid - negative
  "51.2"  # Invalid - decimal
  "0"     # Invalid - zero
  "4096"  # Valid
  "1024"  # Invalid - too small
)

for size in "${test_sizes[@]}"; do
  if echo "$size" | grep -P '^(-?(0|[1-9][0-9]?|[1-9][0-9]{2}|1[0-9]{3}|20[0-3][0-9]|204[0-7])(\.[0-9]+)?|0|-[1-9][0-9]*|-[1-9][0-9]{2,}|-1[0-9]{3}|-20[0-3][0-9]|-204[0-7])$' > /dev/null; then
    echo "$size matches the pattern"
  else
    echo "$size does not match the pattern"
  fi
done

Length of output: 2033

🧰 Tools
🪛 yamllint (1.35.1)

[error] 44-44: trailing spaces

(trailing-spaces)


[warning] 45-45: wrong indentation: expected 2 but found 6

(indentation)

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