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

Rolling back from SHA-256 to MD5 #214

Merged

Conversation

ptorres-prowide
Copy link
Contributor

@ptorres-prowide ptorres-prowide commented Nov 28, 2024

Summary by CodeRabbit

  • New Features
    • Updated checksum calculation methods to utilize the MD5 hashing algorithm for message integrity verification.
  • Documentation
    • Revised documentation to reflect the changes in hashing algorithms and clarified the output format of the checksum.
  • Tests
    • Introduced a new test method to verify the length of the checksum for parsed SwiftMessage objects.

Copy link
Contributor

coderabbitai bot commented Nov 28, 2024

Caution

Review failed

The pull request is closed.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request focus on the SwiftMessageUtils class, specifically modifying the checksum calculation methods to utilize the MD5 hashing algorithm instead of SHA-256. The calculateChecksum methods for both SwiftMessage and SwiftBlock4 have been updated accordingly, with corresponding changes in method documentation. Additionally, a private method previously named sha256 has been renamed to md5, reflecting the algorithm change. Documentation updates clarify the output format.

Changes

File Path Change Summary
src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java - Updated calculateChecksum methods for SwiftMessage and SwiftBlock4 to use MD5 instead of SHA-256.
- Renamed private method sha256 to md5 and updated its implementation.
- Revised documentation to reflect the MD5 algorithm.
CHANGELOG.md - Added entry for version 9.5.4 indicating the rollback of checksum algorithm from SHA-256 to MD5.
src/test/java/com/prowidesoftware/swift/model/SwiftMessageUtilsTest.java - Added testCalculateChecksumLength method to verify the length of the checksum for SwiftMessage.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SwiftMessageUtils
    participant SwiftMessage
    participant SwiftBlock4

    User->>SwiftMessageUtils: calculateChecksum(SwiftMessage)
    SwiftMessageUtils->>SwiftMessage: Compute MD5 hash
    SwiftMessageUtils-->>User: Return MD5 checksum

    User->>SwiftMessageUtils: calculateChecksum(SwiftBlock4)
    SwiftMessageUtils->>SwiftBlock4: Compute MD5 hash
    SwiftMessageUtils-->>User: Return MD5 checksum
Loading

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

Copy link
Contributor

@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: 0

🧹 Outside diff range comments (2)
src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java (2)

Line range hint 335-347: Critical Security Issue: Replacing SHA-256 with MD5 Weakens Checksum Security

Switching the checksum calculation from SHA-256 to MD5 significantly reduces the security of the checksum. MD5 is considered cryptographically broken and is vulnerable to collision attacks, making it unsuitable for cryptographic purposes and message integrity verification.

Apply the following changes to retain SHA-256:

--- a/src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java
+++ b/src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java
@@ -335,7 +335,7 @@
  * Proprietary checksum for message integrity verification or duplicates detection.
  * <p>Please notice <strong>this is not the SWIFT trailer CHK field</strong>.
- * <p>The implementation computes an MD5 on the complete message in FIN format. The result hash
+ * <p>The implementation computes a SHA-256 hash on the complete message in FIN format. The result hash
  * is a 32 character string, you may consider encoding it with base64 on top to have the same
  * information stored in 22 characters.
  *
@@ -346,7 +346,7 @@
     final String fin = writer.getBuffer().toString();
     return md5(fin);
 }
+    return sha256(fin);
 }

 /**
@@ -356,7 +356,7 @@
  * Proprietary checksum for message text block (block 4) integrity verification or duplicates detection
  * <p>Please notice <strong>this is not the SWIFT trailer CHK field</strong>.
- * <p>The implementation computes an MD5 on the complete message in FIN format. The result hash
+ * <p>The implementation computes a SHA-256 hash on the complete message in FIN format. The result hash
  * is a 32 character string, you may consider encoding it with base64 on top to have the same
  * information stored in 22 characters.
  *
@@ -368,7 +368,7 @@
     final String fin = writer.getBuffer().toString();
     return md5(fin);
 }
+    return sha256(fin);
 }

Also applies to: 356-369


Line range hint 381-398: Critical Security Issue: Implementation of Insecure MD5 Hash Function

Implementing the MD5 hash function exposes the application to known vulnerabilities associated with MD5, including collision and preimage attacks. This compromises the security of checksum calculations used for message integrity verification.

Apply the following changes to revert back to using SHA-256:

-private static String md5(final String text) {
+private static String sha256(final String text) {
     try {
         byte[] bytesOfMessage = text.getBytes(StandardCharsets.UTF_8);
-        MessageDigest md = MessageDigest.getInstance("MD5");
+        MessageDigest md = MessageDigest.getInstance("SHA-256");
         byte[] thedigest = md.digest(bytesOfMessage);

         // Converting the bytes to a Hex string
         StringBuilder buff = new StringBuilder();
         for (byte b : thedigest) {
             String conversion = Integer.toString(b & 0xFF, 16);
             while (conversion.length() < 2) {
                 conversion = "0" + conversion;
             }
             buff.append(conversion);
         }

         return buff.toString();
     } catch (NoSuchAlgorithmException e) {
         log.log(Level.FINEST, e.getMessage(), e);
     }
     return null;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 527a924 and 9a6c415.

📒 Files selected for processing (1)
  • src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java (4 hunks)
🔇 Additional comments (1)
src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java (1)

Line range hint 335-347: Verify the Impact of Hash Function Change on Dependent Systems

Changing the checksum algorithm from SHA-256 to MD5 may have significant implications on systems that rely on the checksum for message integrity verification or duplicates detection. Ensure that all dependent systems and clients are compatible with this change and that security requirements are not compromised.

Run the following script to identify any usage of calculateChecksum and confirm the expected checksum algorithm:

This script searches the codebase for invocations of the calculateChecksum methods to help verify whether changing the hash algorithm affects other parts of the application or external integrations.

Also applies to: 356-369, 381-398

@ptorres-prowide ptorres-prowide force-pushed the CU-86b14j4e0_check-code-security-reports-at-GitHub-for-all-repos branch from 9a6c415 to 6024372 Compare November 28, 2024 18:17
Copy link
Contributor

@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 comments (2)
src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java (2)

Line range hint 356-369: Documentation needs clarification on security implications

The documentation should explicitly state that this checksum is for duplicate detection only and NOT for security purposes, given the use of MD5.

 /**
  * Proprietary checksum for message text block (block 4) integrity verification or duplicates detection
  * <p>Please notice <strong>this is not the SWIFT trailer CHK field</strong>.
  * <p>The implementation computes an MD5 on the complete message in FIN format. The result hash
  * is a 32 character string, you may consider encoding it with base64 on top to have the same
  * information stored in 22 characters.
+ * <p><strong>Note:</strong> This checksum is intended for duplicate detection only and should not
+ * be relied upon for security purposes as MD5 is cryptographically broken.
  *
  * @param b4 the message text block
  * @return computed hash or null if errors occurred during computation or the block is null
  * @since 7.9.5
  */

Based on the gathered information, I can now generate the final response:

Critical: Rolling back from SHA-256 to MD5 introduces significant security risks without justification

The change from SHA-256 to MD5 for message checksums is concerning for several reasons:

  • MD5 is cryptographically broken with known collision vulnerabilities
  • No technical justification or compatibility requirement is documented for this downgrade
  • The test cases only verify the checksum length without validating the security implications
  • The changelog entry simply states the change without providing rationale

Recommendations:

  • Keep SHA-256 as it provides stronger security guarantees
  • If there are specific compatibility requirements, consider supporting both algorithms
  • Document any compatibility constraints if the rollback is absolutely necessary
🔗 Analysis chain

Line range hint 335-347: Critical: Rolling back from SHA-256 to MD5 introduces security risks

MD5 is cryptographically broken and should not be used for new applications. It has known vulnerabilities:

  • Collision attacks are practical and have been demonstrated
  • Pre-image resistance is weakened
  • Not recommended for security-critical applications

Consider keeping SHA-256 or using a more modern alternative like SHA-3 if SHA-256 has specific issues.


Let me verify if this change was intentional and if there are any related discussions or commits that explain this security downgrade.


Let me check the changelog entry more thoroughly and look for any related discussions or documentation about this change.


Let me check for any related test cases or documentation that might explain the rationale for this change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are any security advisories or discussions about MD5 deprecation
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: MAVEN, package: "commons-codec") {
    nodes {
      advisory {
        summary
        severity
        description
      }
      vulnerableVersionRange
    }
  }
}'

Length of output: 293


Script:

#!/bin/bash
# Check commit history and PR discussions for context about this change
git log -n 5 --grep="MD5\|SHA.*256" --pretty=format:"%h %s"

# Look for any related configuration or documentation about hash algorithms
rg -i "hash.*algorithm|checksum.*algorithm" --type md

# Check if SHA-256 is still used elsewhere in the codebase
rg -i "sha-?256|sha256" --type java

# Check for any test cases or documentation mentioning the rationale
rg -i "md5.*checksum|checksum.*md5" --type java -A 3

Length of output: 213


Script:

#!/bin/bash
# Get the full context of the changelog entry
cat CHANGELOG.md

# Look for any related documentation or comments about the algorithm change
rg -i "md5.*\b(reason|rationale|compatibility|downgrade)" --type-add 'docs:*.{md,txt,adoc}' --type docs

# Check for any related test cases that might explain the change
ast-grep --pattern 'class $_ {
  $$$
  @Test
  $$$
  void $_($$$) {
    $$$md5$$$
  }
}'

Length of output: 64127


Script:

#!/bin/bash
# Look for test cases that might explain the change
rg -i "test.*checksum|checksum.*test" --type java -A 3

# Check for any related discussions in issues or PRs
rg -i "(pw-|jira-)[0-9]+" CHANGELOG.md -A 2

# Look for any compatibility notes or requirements
rg -i "compatibility|backward.*support|legacy.*support" --type md

Length of output: 10962

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 9a6c415 and 6024372.

📒 Files selected for processing (3)
  • CHANGELOG.md (1 hunks)
  • src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java (4 hunks)
  • src/test/java/com/prowidesoftware/swift/model/SwiftMessageUtilsTest.java (2 hunks)
🧰 Additional context used
🪛 Markdownlint (0.35.0)
CHANGELOG.md

3-3: Expected: h2; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)


4-4: Expected: 0; Actual: 2
Unordered list indentation

(MD007, ul-indent)


4-4: Expected: 0 or 2; Actual: 1
Trailing spaces

(MD009, no-trailing-spaces)


3-3: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


4-4: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)

🔇 Additional comments (2)
src/test/java/com/prowidesoftware/swift/model/SwiftMessageUtilsTest.java (2)

18-18: LGTM!

The static import is correctly added and follows Java conventions.


307-312: 🧹 Nitpick (assertive)

⚠️ Potential issue

Critical: Security and test coverage concerns with MD5 rollback

The rollback from SHA-256 to MD5 raises several security concerns:

  1. MD5 is cryptographically broken and susceptible to collision attacks
  2. The test only verifies the checksum length without validating:
    • Actual checksum values against known good examples
    • Compatibility with existing systems
    • Migration path for existing SHA-256 checksums

Consider the following improvements:

 @Test
 void testCalculateChecksumLength() throws IOException {
     SwiftMessage msg = SwiftMessage.parse(Lib.readResource("MT362.fin"));
     String s = calculateChecksum(msg);
-    assertEquals(s.length(), 32);
+    // Verify against a known good MD5 checksum
+    assertEquals("expected_md5_hash", s);
+    
+    // Verify length
+    assertEquals(32, s.length());
+    
+    // Document why MD5 was chosen over SHA-256
+    // TODO: Add compatibility tests with existing systems
 }
+
+@Test
+void testChecksumMigrationPath() throws IOException {
+    // TODO: Add tests to verify migration path from SHA-256 to MD5
+    // - Test both old and new checksums during transition
+    // - Verify system handles both formats correctly
+}

Let's analyze the impact of this change:

Would you like help with:

  1. Implementing comprehensive test coverage?
  2. Exploring more secure alternatives to MD5?
  3. Designing a migration strategy from SHA-256?

Comment on lines +376 to +384
* Computes an MD5 hash on the parameter text
*
* @param text the text to hash
* @return computed hash or null if exceptions are thrown reading bytes or processing the digest
*/
private static String sha256(final String text) {
private static String md5(final String text) {
try {
byte[] bytesOfMessage = text.getBytes(StandardCharsets.UTF_8);
MessageDigest md = MessageDigest.getInstance("SHA-256");
MessageDigest md = MessageDigest.getInstance("MD5");
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding input validation and improving error handling

The implementation could benefit from:

  1. Input validation for null text parameter
  2. More specific error handling instead of returning null
 private static String md5(final String text) {
+    if (text == null) {
+        throw new IllegalArgumentException("Input text cannot be null");
+    }
     try {
         byte[] bytesOfMessage = text.getBytes(StandardCharsets.UTF_8);
         MessageDigest md = MessageDigest.getInstance("MD5");
         byte[] thedigest = md.digest(bytesOfMessage);

Committable suggestion skipped: line range outside the PR's diff.

CHANGELOG.md Outdated
Comment on lines 3 to 4
#### 9.5.4 - SNAPSHOT
* Rolling back SHA-256 checksum algorithm to MD5
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security concern: Rolling back from SHA-256 to MD5 requires justification

The change to roll back from SHA-256 to MD5 raises significant security concerns:

  1. MD5 is cryptographically broken and has known collision vulnerabilities since 2004
  2. SHA-256 is currently considered cryptographically secure and is the industry standard
  3. Rolling back to a weaker hash algorithm reduces the security posture

Please provide the rationale for this change. If the motivation is performance-related, consider:

  1. Maintaining SHA-256 for security-critical operations
  2. Using SHA-256 with optimized implementations
  3. If a shorter hash is needed, consider using SHA-256 and truncating the output
  4. Alternatively, consider other secure hash algorithms like BLAKE2 or SHA-3 that offer better performance than SHA-256 while maintaining security

Would you like me to help evaluate secure alternatives that meet your specific requirements?

🧰 Tools
🪛 Markdownlint (0.35.0)

3-3: Expected: h2; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)


4-4: Expected: 0; Actual: 2
Unordered list indentation

(MD007, ul-indent)


4-4: Expected: 0 or 2; Actual: 1
Trailing spaces

(MD009, no-trailing-spaces)


3-3: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


4-4: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)

CHANGELOG.md Outdated
@@ -1,5 +1,8 @@
# Prowide Core - CHANGELOG

#### 9.5.4 - SNAPSHOT
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Fix markdown heading structure

The heading structure should be consistent with proper increments.

-#### 9.5.4 - SNAPSHOT
+## 9.5.4 - SNAPSHOT
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#### 9.5.4 - SNAPSHOT
## 9.5.4 - SNAPSHOT
🧰 Tools
🪛 Markdownlint (0.35.0)

3-3: Expected: h2; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)


3-3: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)

@zubri zubri merged commit 6527fb1 into main Nov 28, 2024
1 of 3 checks passed
@zubri zubri deleted the CU-86b14j4e0_check-code-security-reports-at-GitHub-for-all-repos branch November 28, 2024 19:06
try {
byte[] bytesOfMessage = text.getBytes(StandardCharsets.UTF_8);
MessageDigest md = MessageDigest.getInstance("SHA-256");
MessageDigest md = MessageDigest.getInstance("MD5");

Check failure

Code scanning / CodeQL

Use of a broken or risky cryptographic algorithm High

Cryptographic algorithm
MD5
is weak and should not be used.

Copilot Autofix AI 20 days ago

To fix the problem, we should replace the use of the MD5 algorithm with a stronger, modern cryptographic algorithm. A good choice would be SHA-256, which is part of the SHA-2 family and is widely considered secure for most applications.

The changes required are:

  1. Replace the MessageDigest.getInstance("MD5") call with MessageDigest.getInstance("SHA-256").
  2. Update any related comments to reflect the use of SHA-256 instead of MD5.
Suggested changeset 1
src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java b/src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java
--- a/src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java
+++ b/src/main/java/com/prowidesoftware/swift/model/SwiftMessageUtils.java
@@ -355,3 +355,3 @@
      * <p>Please notice <strong>this is not the SWIFT trailer CHK field</strong>.
-     * <p>The implementation computes an MD5 on the complete message in FIN format. The result hash
+     * <p>The implementation computes a SHA-256 on the complete message in FIN format. The result hash
      * is a 32 character string, you may consider encoding it with base64 on top to have the same
@@ -383,3 +383,3 @@
             byte[] bytesOfMessage = text.getBytes(StandardCharsets.UTF_8);
-            MessageDigest md = MessageDigest.getInstance("MD5");
+            MessageDigest md = MessageDigest.getInstance("SHA-256");
             byte[] thedigest = md.digest(bytesOfMessage);
EOF
@@ -355,3 +355,3 @@
* <p>Please notice <strong>this is not the SWIFT trailer CHK field</strong>.
* <p>The implementation computes an MD5 on the complete message in FIN format. The result hash
* <p>The implementation computes a SHA-256 on the complete message in FIN format. The result hash
* is a 32 character string, you may consider encoding it with base64 on top to have the same
@@ -383,3 +383,3 @@
byte[] bytesOfMessage = text.getBytes(StandardCharsets.UTF_8);
MessageDigest md = MessageDigest.getInstance("MD5");
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] thedigest = md.digest(bytesOfMessage);
Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
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