Skip to content

Add AST rules for detecting world-writable file creation in C/C++ #191

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 45 commits into from
Mar 31, 2025

Conversation

ESS-ENN
Copy link
Collaborator

@ESS-ENN ESS-ENN commented Mar 31, 2025

Summary by CodeRabbit

  • New Features

    • Introduced new security rules for both C and C++ that help detect insecure practices in file permission settings, improving protection against unauthorized file modifications.
  • Tests

    • Added comprehensive test cases and snapshots to validate the correct handling of file permissions for C and C++ code, ensuring robust detection of potential vulnerabilities.

Sakshis and others added 30 commits December 16, 2024 13:09
@CLAassistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ ESS-ENN
❌ Sakshis


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 Mar 31, 2025

Walkthrough

This pull request introduces new security rules for detecting instances of world-writable file creation in C and C++ code. The rules, defined in YAML files, use AST analysis to check for unsafe file permission settings and reference CWE-732. Additionally, corresponding snapshot and test files have been added to validate both correct and incorrect permission configurations through functions testing octal and symbolic modes.

Changes

File(s) Change Summary
rules/.../world-writable-file-c.yml
rules/.../world-writable-file-cpp.yml
Added new security rules for C and C++ that detect creation of world-writable files. Rules use AST analysis, flag unsafe modes, include CWE-732 reference, and report warnings.
tests/.../world-writable-file-c(-cpp)-snapshot.yml Introduced snapshot tests containing test_octal_bad and test_symbol_direct_bad functions to validate rule behavior regarding file permission settings.
tests/c/...-file-c-test.yml
tests/cpp/...-file-cpp-test.yml
Added test cases for C and C++ that validate proper (valid) and improper (invalid) file permission setups using both octal and symbolic notation.

Sequence Diagram(s)

sequenceDiagram
    participant Dev as Developer Code
    participant AST as AST Parser
    participant Rule as Security Rule Checker
    participant Test as Test Runner

    Dev->>AST: Submit C/C++ source code
    AST->>Rule: Analyze file creation calls (chmod, open, etc.)
    Rule-->>AST: Return warning if world-writable permission detected
    AST->>Test: Log results for snapshot validation
Loading

Suggested reviewers

  • ganeshpatro321

Poem

In my burrow of code so deep,
I hop with caution, no secrets to keep.
Files now guarded with rules so tight,
World-writable risks are out of sight.
A secure spring dance, under moonlight!
🐰💻 Hop to a safer code delight!


🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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 AST rules for detecting world-writable file creation in C/C++ Mar 31, 2025
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: 2

🧹 Nitpick comments (9)
tests/__snapshots__/world-writable-file-c-snapshot.yml (1)

15-51: Label Metadata Validation.
The labels accurately capture different segments (such as the mode literal, variable assignment, and function calls) and their character ranges. Please verify that these numeric ranges (e.g., start and end positions) match the expected AST output from your parser.

tests/__snapshots__/world-writable-file-cpp-snapshot.yml (2)

15-51: Label Metadata Consistency for Octal Block.
The labels for the test_octal_bad() snapshot are well defined, with proper identification of the mode variable and function call positions. Double-check that these positions remain accurate with any future AST refinements.


64-79: Label Definitions for Symbolic Mode Block.
The label definitions for the symbolic mode test consistently mark the key expressions and their ranges. Ensure that the AST matching produces similar ranges during test execution for reliable detections.

rules/c/security/world-writable-file-c.yml (5)

13-32: Utility Definitions and AST Helpers.
The utils section defines helper mappings—follows_umask and AND_2_EQUALS_2_&_S_IXXXX—to assist with the AST matching. The regex in the latter is complex; please verify it covers all intended insecure mode patterns.


43-116: Rule Block for chmod/fchmod/creat Calls.
This section meticulously matches calls to chmod, fchmod, and creat, ensuring the mode argument meets insecure specifications and is not corrected by a preceding umask operation.
Consider adding inline comments to break down the nested matching logic for better readability and maintainability.


118-182: Rule Block for fchmodat Calls.
The rules captured here correctly address fchmodat by ensuring that the mode argument is flagged if it matches the insecure pattern. Additional inline documentation within this complex nested structure might help future maintainers.


184-255: Rule Block for open Calls.
This section checks calls to open with insecure mode settings. The nested AST conditions are consistent with the previous blocks; however, consider adding clarifying comments to explain the overall logic.


257-328: Rule Block for openat Calls.
The matching conditions for openat mimic those for open and ensure that insecure mode values are accurately detected. Due to the heavy nesting, a few inline comments summarizing each step would improve clarity and future maintenance.

rules/cpp/security/world-writable-file-cpp.yml (1)

32-43: Utility: AND_2_EQUALS_2_&_S_IXXXX Complexity
This utility uses a complex regex pattern to match mode values either as a number literal or as part of a binary expression. The name isn’t very self-explanatory. It would be beneficial to add inline comments or documentation explaining the intent and structure of the regex alternatives for future maintainability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 289aa26 and ce381a6.

📒 Files selected for processing (6)
  • rules/c/security/world-writable-file-c.yml (1 hunks)
  • rules/cpp/security/world-writable-file-cpp.yml (1 hunks)
  • tests/__snapshots__/world-writable-file-c-snapshot.yml (1 hunks)
  • tests/__snapshots__/world-writable-file-cpp-snapshot.yml (1 hunks)
  • tests/c/world-writable-file-c-test.yml (1 hunks)
  • tests/cpp/world-writable-file-cpp-test.yml (1 hunks)
🔇 Additional comments (15)
tests/__snapshots__/world-writable-file-c-snapshot.yml (1)

1-14: Comprehensive Snapshot for C World-Writable Detection.
The snapshot for test_octal_bad() clearly demonstrates the insecure use of mode 0666 through various file operations (e.g., chmod, fchmod, fchmodat, open, and openat). This provides a robust test case for the security rule.

tests/__snapshots__/world-writable-file-cpp-snapshot.yml (2)

1-14: Snapshot for Insecure Octal Mode in C++ Test.
The first snapshot block representing test_octal_bad() correctly reproduces an insecure scenario by using octal mode 0666 across the file operations in C++ code.


52-63: Snapshot for Insecure Symbolic Mode in C++ Test.
The snapshot for test_symbol_direct_bad() effectively captures a scenario using symbolic constants that include insecure permission flags (e.g., S_IWOTH).

tests/cpp/world-writable-file-cpp-test.yml (2)

14-26: Validation of Insecure Octal Usage in Invalid Section.
The test_octal_bad() function in the invalid section is correctly implemented by explicitly declaring mode_t mode = 0666 and reusing it across various file operations to simulate an insecure condition.


27-37: Validation of Insecure Symbolic Mode in Invalid Section.
The test_symbol_direct_bad() function properly demonstrates the risky behavior by combining file permission constants that include S_IWOTH.

tests/c/world-writable-file-c-test.yml (2)

14-26: Validation of Insecure Octal Mode in Invalid Test.
The test_octal_bad() function is correctly defined to simulate a misconfiguration using mode_t mode = 0666, making it a suitable test case for triggering the rule.


27-37: Validation of Insecure Symbolic Mode in Invalid Test.
The test_symbol_direct_bad() function clearly demonstrates insecure symbolic permission settings by including S_IWOTH, which is useful for rule verification.

rules/c/security/world-writable-file-c.yml (1)

1-12: Metadata and General Configuration.
The file metadata (ID, language, severity, message, and note) is well articulated. The message explains the risk of world-writable file creation and includes a reference (CWE-732 with a link) for further context.

rules/cpp/security/world-writable-file-cpp.yml (7)

1-10: Metadata and Documentation Consistency
The metadata fields (id, language, severity, message, and note) are clearly defined. The description in the message accurately describes the potential security issue, and the note provides a CWE reference with a helpful link.


11-11: Flag for Essential Rule Identification
Setting ast-grep-essentials: true properly tags this rule for integration with the ast-grep essential ruleset.


13-31: Utility: follows_umask Structure
The follows_umask utility is well-structured to detect an expression statement that calls umask. The use of nthChild and the regex (^umask$) ensures accurate matching of the intended identifier.


44-118: Rule Branch for chmod, fchmod, and creat
This branch meticulously checks calls to chmod, fchmod, or creat by scrutinizing the $MODE argument through nested AST patterns. The conditions such as checking declarations, assignment expressions, and comma expressions are comprehensive.
It is recommended to validate these patterns against a suite of test cases to ensure all edge cases are covered.


119-184: Rule Branch for fchmodat
The fchmodat branch mirrors the logical structure of the previous rule branch while targeting fchmodat calls. It carefully encapsulates the conditions to verify the mode argument, ensuring consistency in approach.
Ensure this branch is validated with diverse code scenarios to confirm accurate AST pattern matching.


185-257: Rule Branch for open
This segment targets the open function and employs nested checks consistent with the other branches. The approach to match the $MODE argument—including handling for declarations, assignment expressions, and comma expressions—is thorough.
Testing with various call signatures is advised to guarantee the rule’s robustness.


258-329: Rule Branch for openat
The implementation for detecting openat calls with inappropriate $MODE settings aligns with the established patterns in the rule. The attentive use of AST nodes and nested conditions should effectively capture world-writable file creation issues.
As with the other branches, comprehensive testing is recommended to ensure this branch behaves as intended across different code patterns.

@ganeshpatro321 ganeshpatro321 merged commit ee25e84 into coderabbitai:main Mar 31, 2025
1 of 2 checks passed
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.

3 participants