Skip to content

Rules - dont-call-system c/cpp #17

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

Merged
merged 2 commits into from
Oct 14, 2024
Merged

Rules - dont-call-system c/cpp #17

merged 2 commits into from
Oct 14, 2024

Conversation

ESS-ENN
Copy link
Collaborator

@ESS-ENN ESS-ENN commented Oct 11, 2024

Summary by CodeRabbit

  • New Features

    • Introduced new static analysis rules for C and C++ to warn against the use of the system function, promoting safer coding practices.
    • Added test cases that validate the new rules and demonstrate the avoidance of system calls.
  • Bug Fixes

    • Updated existing test cases to reflect the prohibition of system function usage, ensuring better adherence to security guidelines.

Copy link

coderabbitai bot commented Oct 11, 2024

Walkthrough

This pull request introduces new static analysis rules for both C and C++ programming languages, specifically warning against the use of the system function due to its potential security vulnerabilities. The rules, dont-call-system-c and dont-call-system-cpp, are accompanied by patterns to identify calls to system and suggest safer alternatives. Additionally, new test cases are added to validate these rules, including snapshots that demonstrate both valid and invalid usages of the system function.

Changes

File Path Change Summary
rules/c/security/dont-call-system-c.yml New rule dont-call-system-c added; defines pattern PATTERN_SYSTEM to match system function calls.
rules/cpp/security/dont-call-system-cpp.yml New rule dont-call-system-cpp added; defines pattern PATTERN_SYSTEM to match system function calls.
tests/snapshots/dont-call-system-c-snapshot.yml New snapshot dont-call-system-c-snapshot.yml added with test functions for system function usage.
tests/snapshots/dont-call-system-cpp-snapshot.yml New snapshot dont-call-system-cpp-snapshot.yml added with test functions for system function usage.
tests/c/dont-call-system-c-test.yml New valid test case test_003 added; modified invalid test cases test_001 and test_002.
tests/cpp/dont-call-system-cpp-test.yml New valid test case test_003 added; removed invalid test cases test_001 and test_002.

Possibly related PRs

  • More Rules #8: The new rule std-return-data-c in rules/c/security/std-return-data-c.yml addresses potential vulnerabilities in C programming, which is related to the main PR's focus on security rules for C, specifically the dont-call-system-c rule.
  • New Rules #2 #9: The introduction of rules for JavaScript and TypeScript regarding security practices, while not directly related to C, reflects a broader initiative to enhance security across multiple languages, which aligns with the main PR's objective of improving code safety through static analysis rules.

Suggested reviewers

  • petrisorcoderabbit
  • harjotgill

🐇 "In code we hop, with rules so bright,
Avoid the system, keep coding light.
With patterns in place, we’ll guide the way,
To safer practices, come what may!" 🐇


🪧 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

@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

🧹 Outside diff range and nitpick comments (4)
rules/c/security/dont-call-system-c.yml (2)

4-12: Approve message and note with minor formatting suggestion.

The message and note provide clear, actionable advice and valuable context. However, the formatting of the note could be improved for better readability.

Consider reformatting the note section for better readability:

note: >-
  [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').
  
  [REFERENCES]
  - https://owasp.org/Top10/A03_2021-Injection

1-26: Excellent rule implementation with a minor suggestion.

This rule is well-structured and comprehensive. It effectively identifies calls to the system function, provides clear guidance on alternatives, and includes relevant security context. Great job!

To further enhance this rule, consider adding examples of both valid and invalid code snippets in a comment section. This would help developers quickly understand what the rule is checking for and how to comply with it.

Here's an example of how you might add code snippets:

# Add this section at the end of the file
examples:
  - name: Invalid use of system
    language: c
    code: |
      #include <stdlib.h>
      int main() {
          system("ls -l"); // Invalid: Using system function
          return 0;
      }
  - name: Valid alternative using execve
    language: c
    code: |
      #include <unistd.h>
      int main() {
          char *args[] = {"ls", "-l", NULL};
          execve("/bin/ls", args, NULL); // Valid: Using execve
          return 0;
      }
rules/cpp/security/dont-call-system-cpp.yml (1)

4-12: Consider enhancing the warning message with explicit security risks.

The current message and note provide good information about why system should be avoided and suggest alternatives. To make the warning more impactful, consider explicitly mentioning the security risks associated with using system.

Here's a suggested improvement for the message:

  message: >-
    Don't call `system`. It's a high-level wrapper that allows for stacking
    multiple commands. Always prefer a more restrictive API such as calling
-   `execve` from the `exec` family.
+   `execve` from the `exec` family. Using `system` can lead to command
+   injection vulnerabilities if user input is not properly sanitized.
tests/__snapshots__/dont-call-system-c-snapshot.yml (1)

1-41: LGTM! Consider adding inline comments for clarity.

The overall structure and purpose of this snapshot file are appropriate for testing the dont-call-system-c rule. It includes both a "bad" example (test_002) and a "better but still problematic" example (test_001), which should effectively test the rule's implementation.

Consider adding inline comments within the code snippets to explicitly state the purpose of each function (e.g., "Unsafe usage" for test_002 and "More careful but still problematic usage" for test_001). This would enhance the clarity and educational value of the snapshot.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 55859ed and 764307a.

📒 Files selected for processing (6)
  • rules/c/security/dont-call-system-c.yml (1 hunks)
  • rules/cpp/security/dont-call-system-cpp.yml (1 hunks)
  • tests/snapshots/dont-call-system-c-snapshot.yml (1 hunks)
  • tests/snapshots/dont-call-system-cpp-snapshot.yml (1 hunks)
  • tests/c/dont-call-system-c-test.yml (1 hunks)
  • tests/cpp/dont-call-system-cpp-test.yml (1 hunks)
🧰 Additional context used
🔇 Additional comments (21)
rules/c/security/dont-call-system-c.yml (3)

1-3: LGTM: Rule metadata is well-defined.

The rule id is descriptive, the language is correctly specified, and the severity level is appropriate for this type of security warning.


13-23: LGTM: PATTERN_SYSTEM is well-defined.

The pattern correctly identifies call expressions to the system function. The use of stopBy: neighbor and checking for both the identifier and argument list ensures accurate matching.


24-26: LGTM: Rule section is concise and effective.

The rule correctly uses the PATTERN_SYSTEM to identify calls to the system function. The structure is simple and effective for this type of static analysis rule.

rules/cpp/security/dont-call-system-cpp.yml (3)

1-3: LGTM: Rule metadata is well-defined.

The rule id is descriptive, the language is correctly set to C++, and the warning severity is appropriate for this security-related issue.


24-26: LGTM: Rule definition is concise and correct.

The rule section effectively utilizes the PATTERN_SYSTEM defined in the utils section to identify calls to the system function.


1-26: Overall, this is a well-implemented and valuable static analysis rule.

The dont-call-system-cpp rule effectively targets the use of the potentially dangerous system function in C++ code. It provides clear guidance to developers and includes relevant references to security standards. With the suggested improvements, this rule will be even more robust and informative.

Great job on addressing this important security concern!

tests/c/dont-call-system-c-test.yml (4)

4-7: LGTM: Valid test case demonstrates safe alternative to system()

This test case correctly illustrates how to handle system-related functionality without using the system() function. It uses a storer object to store binary data from a system clock, which is a safe alternative.


10-16: Security vulnerability: Unsafe use of system() function

This test case correctly demonstrates an invalid usage of the system() function:

  1. It uses system() with a command string that includes user input, which is a severe security risk (command injection vulnerability).
  2. There's no input validation or sanitization before using the input in the command.
  3. No error checking is performed on the snprintf() or system() calls.

To address these issues in real code:

  1. Avoid system() altogether. Use safer alternatives like execve() family of functions.
  2. If system() must be used, ensure thorough input validation and sanitization.
  3. Always check return values of functions like snprintf() and system() for errors.

17-34: Improved but still unsafe use of system() function

This test case correctly demonstrates an invalid usage of the system() function, albeit with improved error handling:

  1. It still uses system() with a command string that includes user input, which remains a severe security risk (command injection vulnerability).
  2. The error handling for snprintf() and system() calls is a good practice, but it doesn't mitigate the core security issue.

While the error handling is an improvement over test_002, to address the security concerns in real code:

  1. Avoid system() altogether. Use safer alternatives like execve() family of functions.
  2. If system() must be used (strongly discouraged), ensure thorough input validation and sanitization in addition to error handling.
  3. Consider using a whitelist of allowed commands instead of directly incorporating user input into the command string.

1-34: Effective test cases for "dont-call-system-c" rule

These test cases effectively demonstrate the intent of the "dont-call-system-c" rule:

  1. The valid case (test_003) shows a safe alternative to using system().
  2. The invalid cases (test_001 and test_002) illustrate unsafe uses of system(), both with and without error handling.

This comprehensive approach helps developers understand:

  • How to correctly handle system-related functionality without system().
  • Why system() is dangerous even with proper error handling.
  • The importance of avoiding system() altogether in security-sensitive contexts.

Consider adding more valid cases to showcase other safe alternatives to system(), providing developers with a broader range of secure options.

tests/cpp/dont-call-system-cpp-test.yml (4)

3-7: Appropriate valid test case for the rule.

This test case correctly demonstrates a valid usage that doesn't involve the system() function. Instead, it uses Clocks->system(), which likely refers to a system clock, and storer->store_binary() for data storage. This aligns well with the rule's objective of avoiding system() calls.


9-16: Appropriate invalid test case demonstrating unsafe system() usage.

This test case correctly illustrates an invalid usage of the system() function. It constructs a command string using user input and executes it without any error checking, which is precisely the kind of unsafe practice the rule aims to prevent. This example effectively demonstrates why using system() can lead to security vulnerabilities.


17-34: Appropriate invalid test case demonstrating system() usage with error handling.

This test case effectively illustrates why using system() is discouraged, even when implemented with error handling. Despite the careful approach with error checking for both snprintf and system calls, the fundamental security risk of executing system commands with user input remains. This example reinforces the rule's importance by showing that even seemingly careful uses of system() are considered invalid.


1-34: Comprehensive test cases effectively illustrate the rule.

The test cases in this file provide a well-rounded set of examples for the dont-call-system-cpp rule:

  1. The valid case demonstrates a safe alternative to using system().
  2. The first invalid case shows a basic misuse of system() without error handling.
  3. The second invalid case illustrates that even with proper error handling, using system() is still considered unsafe.

This combination effectively communicates the rule's intent and covers different scenarios developers might encounter. It reinforces the importance of avoiding system() calls in all situations, contributing to better code security.

tests/__snapshots__/dont-call-system-c-snapshot.yml (2)

4-10: Confirm if test_002 is intended as a negative example.

The test_002 function demonstrates several unsafe practices:

  1. No error checking for the snprintf call.
  2. No input validation or sanitization, potentially allowing command injection.
  3. No error checking for the system call.

These issues align with the purpose of the dont-call-system-c rule. Please confirm if this function is intentionally written as a negative example to trigger the rule.


11-28: Confirm if test_001 is intended as a more careful but still problematic example.

The test_001 function demonstrates more careful coding practices:

  1. It checks for buffer overflow and negative return values from snprintf.
  2. It includes error handling for both snprintf and system calls.

However, it still uses the system function, which is the subject of the dont-call-system-c rule. This seems to be intentionally written as a more careful but still problematic example. Please confirm if this interpretation is correct.

tests/__snapshots__/dont-call-system-cpp-snapshot.yml (5)

1-41: LGTM: Overall structure of the snapshot file is correct.

The file structure follows the expected format for a snapshot test file. The id dont-call-system-cpp correctly matches the rule being tested, and the inclusion of labels for highlighting specific code parts is beneficial for visualization.


4-10: LGTM: test_002 function serves its purpose as a test case.

This function demonstrates a straightforward use of system without error checking, which is appropriate for testing the dont-call-system-cpp rule. It provides a clear example of code that should trigger the rule.


11-28: LGTM: test_001 function provides a more robust test case.

This function demonstrates a more careful use of system with proper error checking for both snprintf and system. The error handling placeholders are appropriate for a test case. This example is valuable as it shows that the rule should still trigger even with added safety measures.


29-41: LGTM: Labels are well-defined and useful.

The labels are correctly structured and provide useful highlighting for the system call and its components. The use of primary and secondary styles allows for differentiated highlighting, which is helpful for visualizing the critical parts of the code that the rule is meant to catch.


1-41: Overall, excellent snapshot test file for the dont-call-system-cpp rule.

This snapshot file is well-structured and includes appropriate test cases for the dont-call-system-cpp rule. It covers both a simple case (test_002) and a more robust case (test_001) of system usage, which will help ensure the rule catches various scenarios. The inclusion of labels for highlighting is a nice touch for improved visualization of the critical code parts.

Great job on creating a comprehensive test file that will help maintain the quality of the static analysis rule.

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