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 Swift applications #45

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 Oct 24, 2024

Summary by CodeRabbit

  • New Features

    • Introduced security rules to detect hard-coded secrets for Blowfish and ChaCha20 encryption in Swift applications.
    • Added guidance for developers to manage sensitive data securely.
  • Tests

    • Added comprehensive test cases for both Blowfish and ChaCha20 functions, covering valid and invalid scenarios to ensure proper handling of encryption keys.

Copy link

coderabbitai bot commented Oct 24, 2024

Walkthrough

This pull request introduces two new security rules for Swift applications targeting hard-coded secrets related to the Blowfish and ChaCha20 encryption algorithms. Each rule is categorized with a severity level of "warning" and employs pattern matching to identify instances where sensitive data is directly embedded in the source code. Additionally, corresponding snapshot and test configuration files are created to validate the functionality of these rules, ensuring comprehensive coverage of potential vulnerabilities.

Changes

File Path Change Summary
rules/swift/security/blowfish-hardcoded-secret-swift.yml New rule added: blowfish-hardcoded-secret-swift to detect hard-coded secrets in Blowfish usage.
rules/swift/security/chacha20-hardcoded-secret-swift.yml New rule added: chacha20-hardcoded-secret-swift to identify hard-coded secrets in ChaCha20 usage.
tests/__snapshots__/blowfish-hardcoded-secret-swift-snapshot.yml New snapshot added for testing Blowfish with various key and IV combinations.
tests/__snapshots__/chacha20-hardcoded-secret-swift-snapshot.yml New snapshot added for testing ChaCha20 with various hardcoded secret keys.
tests/swift/blowfish-hardcoded-secret-swift-test.yml New test case added: blowfish-hardcoded-secret-swift with valid and invalid Blowfish usage cases.
tests/swift/chacha20-hardcoded-secret-swift-test.yml New test case added: chacha20-hardcoded-secret-swift with valid and invalid ChaCha20 usage cases.

Possibly related PRs

  • New Rules #2 #9: Introduces a security rule for detecting hard-coded secrets in JavaScript applications, similar to this PR's focus on Swift.
  • Rules - node-rsa-weak-key in Js/Ts #12: Relates to hard-coded secrets in JavaScript and TypeScript, emphasizing risks similar to those addressed in this PR.
  • Rules - One php and one java rule #20: Introduces a rule for detecting hard-coded secrets in Java applications, reinforcing the need for secure credential management.
  • Two openai go rules #29: Focuses on detecting hard-coded session keys in Go applications, conceptually similar to the main PR's objectives.
  • Two python rules 16Oct2024 #31: Introduces a rule for detecting hard-coded secrets in Python applications, aligning with the goals of this PR.
  • Two Rust rules 16Oct2024 #35: Rules for detecting empty passwords and hard-coded secrets in Rust applications relate to the main PR's focus.

Suggested reviewers

  • petrisorcoderabbit

Poem

🐇 In the land of code where secrets hide,
New rules emerge, a vigilant guide.
Blowfish and ChaCha, keep them secure,
With patterns and tests, we can be sure.
No hard-coded secrets, let’s be wise,
For safety in code, let’s all prioritize! 🛡️


🪧 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 Swift applications Oct 24, 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: 10

🧹 Outside diff range and nitpick comments (4)
tests/swift/blowfish-hardcoded-secret-swift-test.yml (1)

1-17: Add comments to document test cases and their purposes.

While the test cases are functional, adding comments to explain each case would improve maintainability and make it clearer why certain patterns are considered valid or invalid.

 id: blowfish-hardcoded-secret-swift
+# Tests for detecting hardcoded secrets in Blowfish encryption implementation
 valid:
+  # Demonstrates correct usage with a variable password and proper error handling
   - |
     try Blowfish(key: password, iv: "123")
 invalid:
+  # Case 1: Hardcoded string literal converted to bytes
   - |
     let password: Array<UInt8> = Array("s33krit".utf8)
     try Blowfish(key: password, iv: "123")
+  # Case 2: Direct string literal usage
   - |
     try Blowfish(key: "hello", iv: "123")
+  # Case 3: Missing try keyword for error handling
   - |
     let password = Array("s33krit".utf8)
     Blowfish(key: password, iv: "123")
tests/__snapshots__/chacha20-hardcoded-secret-swift-snapshot.yml (1)

1-215: Consider adding additional test cases for edge cases.

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

  1. Multi-line key assignments
  2. Keys derived from string interpolation
  3. Keys from concatenated strings
  4. Hex-encoded keys
  5. Base64-encoded keys

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

tests/__snapshots__/blowfish-hardcoded-secret-swift-snapshot.yml (1)

3-38: Security: Add labels for encryption parameters

To improve security analysis, consider adding specific labels for security-critical parameters like key length and encoding.

Example addition:

    - source: utf8
      style: parameter
      start: 27
      end: 31
    - source: Array
      style: parameter
      start: 14
      end: 19
rules/swift/security/chacha20-hardcoded-secret-swift.yml (1)

1-13: Consider adding Swift-specific security references.

The rule metadata is well-structured with appropriate severity and clear messaging. Consider enhancing the references section with Swift-specific security guidelines.

Add these additional references:

   [REFERENCES]
       - https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html
+      - https://developer.apple.com/documentation/security
+      - https://www.swift.org/security/
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3195f93 and 79348b0.

📒 Files selected for processing (6)
  • rules/swift/security/blowfish-hardcoded-secret-swift.yml (1 hunks)
  • rules/swift/security/chacha20-hardcoded-secret-swift.yml (1 hunks)
  • tests/snapshots/blowfish-hardcoded-secret-swift-snapshot.yml (1 hunks)
  • tests/snapshots/chacha20-hardcoded-secret-swift-snapshot.yml (1 hunks)
  • tests/swift/blowfish-hardcoded-secret-swift-test.yml (1 hunks)
  • tests/swift/chacha20-hardcoded-secret-swift-test.yml (1 hunks)
🔇 Additional comments (11)
tests/swift/blowfish-hardcoded-secret-swift-test.yml (1)

1-17: Verify test coverage with the security rule implementation.

The test cases should align with the patterns defined in the security rule file.

✅ Verification successful

Let me gather more information about the test cases and rule patterns to ensure proper alignment.


Test cases properly align with security rule patterns

After analyzing the rule file and test cases, I can confirm that the test coverage is comprehensive and correctly aligns with the security rule implementation. The test cases cover all the defined patterns:

  • Direct string literals in try expressions
  • Direct string literals in regular expressions
  • UTF-8 string conversions with Array constructor
  • Variable declarations with hardcoded strings
  • Both try and non-try expression variants

The invalid test cases appropriately match the rule's detection patterns for hardcoded secrets, while the valid case demonstrates proper usage without hardcoded values.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify alignment between test cases and rule patterns

# Test: Check if the security rule file exists and contains matching patterns
rg -l "blowfish.*hardcoded.*secret" rules/swift/security/
rg -A 5 "pattern:" rules/swift/security/blowfish-hardcoded-secret-swift.yml

Length of output: 1007


Script:

#!/bin/bash
# Get the complete rule file content to understand all patterns
cat rules/swift/security/blowfish-hardcoded-secret-swift.yml

# Also get any other similar security rules for Blowfish
fd blowfish rules/swift/security/ --exec cat {}

Length of output: 18262

tests/swift/chacha20-hardcoded-secret-swift-test.yml (2)

1-1: LGTM! Clear and descriptive test identifier.

The test ID follows good naming conventions and clearly indicates the target algorithm, issue type, and language.


1-17: Verify consistency with other encryption algorithm test configurations.

Let's ensure this test configuration follows similar patterns used for other encryption algorithms.

✅ Verification successful

Let me generate another verification script to look at the actual content of similar encryption test files, particularly focusing on Swift encryption tests since they would be most relevant.


Test configuration follows consistent patterns with other encryption tests

The chacha20 test configuration follows the same structure and patterns as other encryption-related tests in the codebase:

  • It maintains the standard valid/invalid sections like all other test files
  • The test cases for hardcoded secrets in Swift encryption (chacha20 and blowfish) follow identical patterns:
    • Valid cases use a password variable
    • Invalid cases check for hardcoded strings and array literals
  • The structure aligns with other encryption tests (like ECB cipher, RC4) that validate secure vs insecure usage patterns
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for similar test configurations and their structure

# Find all encryption-related test configurations
echo "Finding all encryption-related test configurations:"
fd -e yml -e yaml . tests/ | grep -i 'secret\|encrypt\|cipher'

# Compare structure with other test files
echo -e "\nChecking for consistent structure across test files:"
for f in $(fd -e yml -e yaml . tests/ | grep -i 'secret\|encrypt\|cipher'); do
  echo "=== $f ==="
  grep -A 1 "^valid:\|^invalid:" "$f" || true
done

Length of output: 18822


Script:

#!/bin/bash
# Get content of related Swift encryption test files
echo "=== Content of chacha20-hardcoded-secret-swift-test.yml ==="
cat tests/swift/chacha20-hardcoded-secret-swift-test.yml

echo -e "\n=== Content of blowfish-hardcoded-secret-swift-test.yml ==="
cat tests/swift/blowfish-hardcoded-secret-swift-test.yml

# Also check a few other encryption-related test files from different languages
echo -e "\n=== Content of ecb-cipher-java-test.yml ==="
cat tests/java/ecb-cipher-java-test.yml

echo -e "\n=== Content of insecure-cipher-algorithm-rc4-python-test.yml ==="
cat tests/python/insecure-cipher-algorithm-rc4-python-test.yml

Length of output: 2534

tests/__snapshots__/chacha20-hardcoded-secret-swift-snapshot.yml (2)

1-2: LGTM: Clear identification of the security rule.

The snapshot file is properly identified for the ChaCha20 hardcoded secret detection rule in Swift.


3-38: Comprehensive test coverage for various hardcoded secret patterns.

The snapshot includes a good variety of test cases covering:

  • Direct string literals ("hello", "s33krit")
  • UTF-8 array conversions
  • Variable assignments
  • Error handling with try
  • Different parameter combinations (key-only, key with IV)

However, there are some security considerations to note:

  1. The test values use predictable patterns ("hello", "s33krit", "123")
  2. The IV value "123" is particularly weak for cryptographic purposes

Let's verify if these test cases align with the rule definition:

Also applies to: 39-85, 86-138, 139-177, 178-215

✅ Verification successful

Let me gather more information about the rule definition and test cases to properly verify the alignment.


Test cases correctly align with the rule definition and security objectives

The test cases in the snapshot perfectly align with the rule definition which aims to detect hardcoded secrets in ChaCha20 encryption usage. The rule specifically looks for:

  1. Direct string literals in key parameters
  2. Array conversions of string literals to UTF-8
  3. Both try and non-try expressions
  4. Variable assignments of hardcoded strings

The test cases cover all these patterns comprehensively:

  • Direct usage: chacha20(key: Array("hello".utf8))
  • Variable assignments: let password = Array("s33krit".utf8)
  • Try expressions: try chacha20(key: Array("hello".utf8))

While the review comment raised concerns about predictable patterns and weak IV values, these are actually appropriate for test cases as they:

  • Demonstrate the rule's detection capabilities
  • Provide clear, readable examples
  • Focus on the pattern detection rather than cryptographic strength
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the rule file exists and contains matching patterns
rg -l "chacha20.*key" rules/swift/security/chacha20-hardcoded-secret-swift.yml

# Verify test configuration
rg -l "chacha20.*hardcoded.*secret" tests/swift/chacha20-hardcoded-secret-swift-test.yml

Length of output: 224


Script:

#!/bin/bash
# Check the rule definition
cat rules/swift/security/chacha20-hardcoded-secret-swift.yml

# Check the test configuration
cat tests/swift/chacha20-hardcoded-secret-swift-test.yml

# Look for any other related test files
fd chacha20.*swift.*test

Length of output: 9687

tests/__snapshots__/blowfish-hardcoded-secret-swift-snapshot.yml (1)

1-2: LGTM: File structure follows the snapshot test format.

The file is properly structured with an appropriate id and snapshots section.

rules/swift/security/chacha20-hardcoded-secret-swift.yml (3)

272-284: LGTM! Comprehensive pattern matching structure.

The rule definition effectively combines all utility patterns to catch various forms of hard-coded ChaCha20 secrets. The separation between try_expression and call_expression patterns ensures thorough coverage.


203-218: 🛠️ Refactor suggestion

Optimize pattern matching by using consistent stopBy directives.

The nested pattern uses redundant stopBy: neighbor directives which could be consolidated to improve readability and maintenance.

Consider simplifying the stopBy directives:

                            stopBy: neighbor
                            kind: navigation_expression
                            all:
                              - has:
-                                 stopBy: neighbor
+                                 stopBy: end
                                  kind: line_string_literal
                                  has:
-                                   stopBy: neighbor
+                                   stopBy: end
                                    kind: line_str_text
                              - has:
-                                 stopBy: neighbor
+                                 stopBy: end
                                  kind: navigation_suffix
                                  has:
-                                   stopBy: neighbor
+                                   stopBy: end
                                    kind: simple_identifier
                                    regex: "^utf8$"

Likely invalid or redundant comment.


1-284: Verify test coverage for security patterns.

Let's ensure comprehensive test coverage for this security rule.

✅ Verification successful

Based on the output, I can see that there are comprehensive test files for the chacha20-hardcoded-secret-swift rule, including both test cases and snapshots. Let me analyze the test coverage:

  1. Test file exists:
  • tests/swift/chacha20-hardcoded-secret-swift-test.yml
  • tests/__snapshots__/chacha20-hardcoded-secret-swift-snapshot.yml
  1. Test cases coverage:
tests/swift/chacha20-hardcoded-secret-swift-test.yml:valid:
  - |
    try chacha20(key: password, iv: "123")
tests/swift/chacha20-hardcoded-secret-swift-test.yml:invalid:
  - |
    let password: Array<UInt8> = Array("s33krit".utf8)
    try chacha20(key: password, iv: "123")
  - |
    try chacha20(key: "hello", iv: "123")

The test coverage appears complete with:

  1. Valid case: Using a non-hardcoded password variable
  2. Invalid cases:
    • Hardcoded string converted to bytes
    • Direct hardcoded string usage

Test coverage is adequate and properly validates the security rule.

The test cases appropriately cover:

  • Direct string literals
  • String-to-byte array conversions
  • Both valid and invalid patterns
  • Different parameter positions and contexts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for test files and their coverage

# Test: Look for corresponding test files
echo "Checking for test files..."
fd "chacha20.*test" --type f

# Test: Check test cases in snapshot files
echo -e "\nChecking snapshot coverage..."
fd "chacha20.*snapshot" --type f

# Test: Verify if we have both positive and negative test cases
echo -e "\nAnalyzing test cases..."
rg -A 5 "testCases:|valid:|invalid:" 

Length of output: 100157

rules/swift/security/blowfish-hardcoded-secret-swift.yml (2)

1-284: Verify consistency with other encryption-related rules.

Let's ensure this rule follows similar patterns and severity levels as other encryption-related rules in the codebase.

✅ Verification successful

Let me gather more specific information about these rules to ensure a thorough verification.

This will help us compare the structure, patterns, and messaging consistency across these security rules.


Based on the analysis of the related rules, I can now provide the final verification response:

The Blowfish hardcoded secret rule is consistent with other encryption rules

The rule is well-aligned with similar security rules in the codebase, particularly with the chacha20-hardcoded-secret-swift.yml rule. Key observations:

  • Both rules share the same severity level (warning)
  • Identical message and note sections, including CWE-798 reference
  • Similar pattern matching structure for detecting hardcoded secrets
  • Consistent pattern detection for both direct usage and UTF-8 encoded strings

The rule maintains the established pattern for detecting cryptographic misuse in the codebase and follows the same security standards as other encryption-related rules.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find other encryption-related rules and compare their patterns
echo "Searching for other encryption-related rules..."
fd -e yml -e yaml . rules/swift/security/ -x rg -l "severity|encryption|crypto|secret"

# Check their severity levels
echo "Checking severity levels of similar rules..."
fd -e yml -e yaml . rules/swift/security/ -x rg "^severity: "

Length of output: 572


Script:

#!/bin/bash
# Get detailed content of the related encryption rules
echo "=== Content of chacha20-hardcoded-secret-swift.yml ==="
cat rules/swift/security/chacha20-hardcoded-secret-swift.yml

echo -e "\n=== Content of insecure-biometrics-swift.yml ==="
cat rules/swift/security/insecure-biometrics-swift.yml

Length of output: 10263


78-123: Verify pattern matching for computed properties.

The pattern for instance matching might miss computed properties. Consider adding validation to ensure the rule catches cases where the key is computed at runtime but still contains hard-coded secrets.

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.

1 participant