Skip to content

Conversation

gojo-satorou-v7
Copy link
Contributor

@gojo-satorou-v7 gojo-satorou-v7 commented Mar 6, 2025

User description

Now the rebuild_safe_url checks for potential ssrf payload and returns None in case such url is provided, also I have made the path sanitization better since the previous one only removed the query and fragment part from the path but now it checks furtherfor carriage return and line feed and other misused paths and normalizes them.

fixes #3797
fixes #3923


PR Type

Bug fix, Tests


Description

  • Enhanced rebuild_safe_url to sanitize URLs against SSRF vulnerabilities.

  • Added is_dns_safe function to validate DNS safety of URLs.

  • Introduced comprehensive test cases for rebuild_safe_url function.

  • Removed deprecated is_safe_url function to streamline URL validation.


Changes walkthrough 📝

Relevant files
Tests
test_api.py
Add test cases for `rebuild_safe_url` function                     

website/test_api.py

  • Added a new test case class RebuildSafeUrlTestCase.
  • Included multiple test scenarios for rebuild_safe_url.
  • Validated URL sanitization against encoded characters, CRLF, and path
    traversal.
  • +28/-0   
    Bug fix
    utils.py
    Improve URL sanitization and add DNS safety checks             

    website/utils.py

  • Enhanced rebuild_safe_url to sanitize URLs against SSRF
    vulnerabilities.
  • Added is_dns_safe function to validate DNS safety of hostnames.
  • Improved path normalization and encoding in rebuild_safe_url.
  • Removed deprecated is_safe_url function.
  • +53/-17 

    Need help?
  • Type /help how to ... in the comments thread for any questions about PR-Agent usage.
  • Check out the documentation for more information.
  • Summary by CodeRabbit

    • Refactor
      • Streamlined the deletion confirmation flow and improved URL safety checks, ensuring a more secure and reliable user experience.
    • Tests
      • Added automated tests to validate robust URL handling.
    • Chores
      • Updated deletion actions to require secure POST submissions, further enhancing overall security.

    Copy link
    Contributor

    github-actions bot commented Mar 6, 2025

    PR Reviewer Guide 🔍

    (Review updated until commit 0ae056d)

    Here are some key observations to aid the review process:

    🎫 Ticket compliance analysis 🔶

    3797 - Partially compliant

    Compliant requirements:

    • Ensure rebuild_safe_url function sanitizes URLs to prevent SSRF vulnerabilities.
    • Validate DNS safety of URLs to block internal, loopback, and other unsafe addresses.
    • Normalize and sanitize paths to prevent misuse (e.g., CRLF injection, path traversal).
    • Remove deprecated or redundant functions related to URL validation.

    Non-compliant requirements:

    []

    Requires further human verification:

    []

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 PR contains tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Possible Issue

    The path.replace logic in rebuild_safe_url might not handle all edge cases of path traversal or CRLF injection. Ensure comprehensive testing and validation.

    path = parsed_url.path
    path = path.replace("\r", "").replace("\n", "")
    path = path.replace("/..", "").replace("/", "/")
    
    # Collapse multiple slashes into a single slash
    path = re.sub(r"/{2,}", "/", path)
    if path in ("", "."):
        path = "/"
    # Ensure the path starts with a slash
    elif not path.startswith("/"):
        path = "/" + path
    encoded_path = quote(path, safe="/")
    DNS Safety Validation

    The is_dns_safe function might not account for all edge cases of unsafe DNS resolution. Verify its robustness against potential bypass techniques.

    def is_dns_safe(hostname):
        try:
            resolved = socket.getaddrinfo(hostname, None)
        except socket.gaierror:
            return False  # Unable to resolve hostname; treat as unsafe.
        for result in resolved:
            ip_str = result[4][0]
            try:
                ip = ip_address(ip_str)
                if ip.is_private or ip.is_loopback or ip.is_reserved or ip.is_link_local:
                    return False
            except ValueError:
                continue
        return True

    Copy link
    Contributor

    github-actions bot commented Mar 6, 2025

    PR Code Suggestions ✨

    @gojo-satorou-v7 gojo-satorou-v7 marked this pull request as ready for review March 7, 2025 08:32
    Copy link
    Contributor

    github-actions bot commented Mar 7, 2025

    Persistent review updated to latest commit 0ae056d

    Copy link
    Contributor

    github-actions bot commented Mar 7, 2025

    PR Code Suggestions ✨

    @gojo-satorou-v7
    Copy link
    Contributor Author

    gojo-satorou-v7 commented Mar 7, 2025

    This fixes the issue for the rebuild_safe_url which was introducing SSRF vulnerabilities in the /website/views/issue.py at file issues.py and company.py by improperly sanitizing the url. My changes to the code bring enhanced protection from SSRF, CRLF and path traversal vulnerabilities by properly sanitizing and blocking requests to internal ip address.

    The dns_safe is another function added which first resolves the input url from the user and then resolves it's ip address before processing it any further [Protects from dns rebinding] . It is advisable to use this version of rebuild_safe_url wherever there;s a need to take user input.

    @gojo-satorou-v7
    Copy link
    Contributor Author

    @DonnieBLT I have added the test case, please check if any improvements are needed or edge case I might've missed.

    @gojo-satorou-v7
    Copy link
    Contributor Author

    gojo-satorou-v7 commented Mar 12, 2025

    Since the fix for #3923 was small I have included it in this PR.
    fixes #3923

    @gojo-satorou-v7
    Copy link
    Contributor Author

    Can this be merged? @DonnieBLT

    Copy link
    Contributor

    coderabbitai bot commented Mar 15, 2025

    Walkthrough

    The pull request improves security and reliability in multiple parts of the application. In the education template and view, deletion actions now enforce POST submissions with CSRF protection. In the URL utilities, a new DNS safety check is added to the URL rebuilding process while deprecating an older safety method. Additionally, comprehensive tests have been introduced to verify the updated URL safety functionality.

    Changes

    File(s) Change Summary
    website/templates/education/content_management.html
    website/views/education.py
    Updated deletion functionality by adding method="post" and a CSRF token in the HTML form, simplifying its layout, and enforcing POST-only requests in the view via the @require_POST decorator.
    website/test_api.py
    website/utils.py
    Added a new test case for rebuild_safe_url and enhanced its logic by introducing the is_dns_safe function to validate hostnames, while removing the deprecated is_safe_url function.

    Sequence Diagram(s)

    sequenceDiagram
        participant Client
        participant Form
        participant Server
        participant Database
    
        Client->>Form: Submit delete request (POST with CSRF)
        Form->>Server: Forward request to delete endpoint
        Server->>Database: Fetch and delete section
        Database-->>Server: Confirmation of deletion
        Server->>Client: Return response
    
    Loading
    sequenceDiagram
        participant Caller
        participant rebuild_safe_url
        participant is_dns_safe
    
        Caller->>rebuild_safe_url: Pass URL
        rebuild_safe_url->>is_dns_safe: Validate hostname safety
        is_dns_safe-->>rebuild_safe_url: Return safety status
        rebuild_safe_url-->>Caller: Return safe URL or None
    
    Loading

    Poem

    I'm a rabbit with a coding spree,
    Hopping through changes so merrily.
    Forms post with CSRF in tow,
    DNS checks making URLs glow.
    Tests and views now dance in delight,
    Secure carrots all day and night! 🐰

    Tip

    ⚡🧪 Multi-step agentic review comment chat (experimental)
    • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
      - To enable this feature, set early_access to true under in the settings.
    ✨ Finishing Touches
    • 📝 Generate Docstrings

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

    🧹 Nitpick comments (1)
    website/test_api.py (1)

    5-38: Comprehensive test coverage for rebuild_safe_url.

    1. It's great to see each input being tested in a subTest, providing clear insights into which URL variations might fail.
    2. Consider removing or converting the debug print statement (line 17) to logging if needed, as excessive console prints can clutter test outputs.
    3. You might also want to test edge cases like empty URLs or non-HTTP(S) schemes in the future to further strengthen coverage.
    📜 Review details

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

    📥 Commits

    Reviewing files that changed from the base of the PR and between d3d226b and 43b447a.

    📒 Files selected for processing (4)
    • website/templates/education/content_management.html (1 hunks)
    • website/test_api.py (1 hunks)
    • website/utils.py (2 hunks)
    • website/views/education.py (1 hunks)
    ⏰ Context from checks skipped due to timeout of 90000ms (3)
    • GitHub Check: Run Tests
    • GitHub Check: docker-test
    • GitHub Check: Analyze (python)
    🔇 Additional comments (4)
    website/views/education.py (1)

    242-242: Good addition of @require_POST for secure deletion handling.

    Requiring a POST request for delete_section helps prevent unintended or malicious GET requests from triggering destructive actions. Ensure that the frontend form is correctly using the POST method with a CSRF token to fully protect against CSRF.

    website/templates/education/content_management.html (1)

    395-407: Proper use of POST method and CSRF token in the deletion form.

    Adding method="post" and {% csrf_token %} aligns with best practices for destructive actions, helping to prevent CSRF attacks. The clear separation of “Cancel” and “Delete” buttons further improves UX and reduces accidental deletions.

    website/utils.py (2)

    134-148: DNS safety checks are well-structured.

    Using socket.getaddrinfo and iterating addresses to reject private/loopback/reserved networks greatly reduces SSRF risks. If performance concerns arise under high volume, consider an optimized DNS resolution strategy or in-memory caching.


    150-185: Enhanced URL sanitization in rebuild_safe_url.

    1. Validating scheme (HTTP/HTTPS) and removing user credentials (@) is a robust measure for SSRF mitigation.
    2. Checking IP addresses (private, loopback) plus is_dns_safe ensures that unauthorized internal hosts become inaccessible.
    3. Collapsing multiple slashes and removing CR/LF is excellent for path normalization.
    4. Consider whether you need to preserve or sanitize query parameters/fragment if they are used elsewhere, as they are currently being dropped.

    Overall, well-implemented SSRF defense.

    @DonnieBLT DonnieBLT enabled auto-merge (squash) March 15, 2025 08:58
    @DonnieBLT
    Copy link
    Collaborator

    @CodeRabbit review once more and approve if it looks good

    Copy link
    Contributor

    coderabbitai bot commented Mar 15, 2025

    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    # First, view the changes to utils.py
    git show HEAD:website/utils.py
    
    # Then, check the new test cases
    git show HEAD:website/test_api.py
    
    # Let's see where rebuild_safe_url is used in the codebase
    rg "rebuild_safe_url" --type py -A 1 -B 1
    

    Length of output: 46965


    @DonnieBLT I've reviewed the PR and the changes look excellent. The improved rebuild_safe_url function now:

    1. Properly validates URL schemes (only http/https)
    2. Checks for and blocks private/internal IP addresses
    3. Prevents path traversal attacks
    4. Removes dangerous CRLF characters
    5. Normalizes paths correctly
    6. Returns None for potentially harmful URLs

    The new is_dns_safe function adds protection against DNS rebinding attacks by resolving hostnames and verifying IP addresses aren't private/internal networks.

    The test cases are comprehensive and cover all the security improvements. This PR effectively addresses the SSRF vulnerabilities in issue.py and company.py.

    I recommend approving this PR.

    ✅ Actions performed

    Comments resolved and changes approved.

    @DonnieBLT DonnieBLT merged commit c49918f into OWASP-BLT:main Mar 15, 2025
    10 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.

    CSRF in delete section of courses. improper sanitization by rebuild_safe_url function in website/utils.py ...
    2 participants