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

Enhancing Security, Error Handling, and Performance in Nginx for Moodle #75

Merged
merged 1 commit into from
Feb 23, 2025

Conversation

erseco
Copy link
Owner

@erseco erseco commented Feb 23, 2025

This pull request refines the moodle.conf Nginx configuration by incorporating security enhancements, improved error handling, and optimized file serving. The changes are primarily based on this commit from @jimsihk’s fork, with additional refinements and a monkey patch to properly handle fixture files. These modifications ensure a more secure and efficient Moodle deployment.

🔒 Security Enhancements & Error Handling

  • Custom error pages: Redirects 404 and 403 errors to Moodle’s themed error page (/error/index.php).
  • Access restrictions: Blocks direct access to sensitive files and directories, including:
    • /fixtures/, /privacy/tests/fixtures/logo.png, /enrol/lti/tests/fixtures/input.xml
    • /admin/environment.xml, /lib/db/install.xml, /mod/assign/db/install.xml
  • Dotfile protection: Returns 404 for all dotfiles, except /.well-known/ per [RFC 5785](https://datatracker.ietf.org/doc/html/rfc5785).
  • Stronger security policies: Introduces a comprehensive block for internal files and directories to prevent unauthorized access.

🚀 Performance Optimization

🔗 Reference to Issue #74

This PR also addresses concerns raised in Issue #74, where public paths were incorrectly accessible due to improper handling of environment/publicpaths.php. Instead of modifying internal Moodle files, Nginx now enforces proper restrictions.

🛠 Additional Improvements

  • Custom .conf directory support: As part of this update, .conf files can now be placed inside rootfs/etc/nginx/server-conf.d/, reducing the need for direct .sh patching (see reference).
  • Planned refinements: Future releases of erseco/alpine-php-webserver will introduce pre and post location directives for more flexible configuration handling.

🎉 Special Thanks

A huge thanks to @jimsihk for the insightful fork and suggestions! Your contributions significantly improved the security and maintainability of this setup. 🙌

Summary by CodeRabbit

  • New Features
    • Implemented custom error handling to improve the user experience during missing or restricted page scenarios.
    • Enhanced security measures by restricting access to sensitive and internal paths.
    • Optimized delivery for static content, reducing load on dynamic processing and enhancing overall performance.

@erseco erseco self-assigned this Feb 23, 2025
@erseco erseco linked an issue Feb 23, 2025 that may be closed by this pull request
Copy link

coderabbitai bot commented Feb 23, 2025

Walkthrough

A new Nginx configuration file for the Moodle environment has been introduced. The file sets custom error pages for 404 and 403 responses, redirects forbidden errors to an error handler, and restricts access to specific paths and sensitive files (including fixtures, dot files not under well-known URIs, vendor and node modules). Additionally, an internal alias is defined to offload file serving from PHP for resources under the /dataroot/ directory.

Changes

File(s) Change Summary
rootfs/etc/nginx/server-conf.d/moodle.conf Added directives for custom error pages (error_page 404 and error_page 403 =404), access control for /fixtures/, specific file requests (e.g., logo.png, input.xml), sensitive files (e.g., /admin/environment.xml, /lib/db/install.xml, /mod/assign/db/install.xml), rules to hide dot files (except “well-known” URIs), and offloaded file serving via an internal alias for /dataroot/.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Nginx
  participant DataAlias as "Internal Alias (/dataroot)"
  participant ErrorPage as "Error Handler (/error/index.php)"
  
  Client->>Nginx: Sends HTTP request
  alt Request for file in /dataroot/
    Nginx->>DataAlias: Retrieve static file
    DataAlias-->>Nginx: Returns file content
    Nginx-->>Client: Delivers file content
  else Request for restricted/sensitive resource
    Nginx-->>Client: Returns 404 error (or 403 as 404)
  else Other requests
    Nginx-->>Client: Processes request normally
  end
Loading

Poem

I’m a little rabbit, hopping with delight,
In Nginx fields, where configs shine bright.
Blocking bad paths and securing the door,
Guiding errors to pages like never before.
My ears perk up for each directive so tight –
A bunny’s cheer for Moodle’s new flight!
🐇✨


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@erseco erseco mentioned this pull request Feb 23, 2025
@erseco erseco merged commit f6f3ebc into main Feb 23, 2025
2 checks passed
@erseco erseco deleted the 74-public-paths-error branch February 23, 2025 19:22
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

🧹 Nitpick comments (3)
rootfs/etc/nginx/server-conf.d/moodle.conf (3)

5-9: Optimize the fixtures block by removing redundant directive.

The deny all directive is redundant when followed by return 404. The return directive alone is sufficient.

 location ~ /fixtures/ {
-    deny all;
     return 404;
 }

1-60: Consider implementing pre and post location directives.

As mentioned in the PR objectives, future updates plan to introduce pre and post location directives. This would enhance configuration flexibility by allowing:

  1. Custom configurations before the main security rules
  2. Override capabilities after the main security rules
  3. Better organization of environment-specific rules

Consider this structure:

# Pre-security rules
include /etc/nginx/server-conf.d/pre/*.conf;

# Main security rules
include /etc/nginx/server-conf.d/moodle.conf;

# Post-security rules
include /etc/nginx/server-conf.d/post/*.conf;

24-40:

❓ Verification inconclusive

Optimize XML blocks and verify coverage.

  1. The deny all directives are redundant when followed by return 404.
  2. Verify if there are other XML files that should be protected.
 location = /admin/environment.xml {
-    deny all;
     return 404;
 }

 location = /lib/db/install.xml {
-    deny all;
     return 404;
 }

 location = /mod/assign/db/install.xml {
-    deny all;
     return 404;
 }

Let's search for other potential XML files that might need protection:


🏁 Script executed:

#!/bin/bash
# Description: Find other XML files in the codebase
fd -e xml

Length of output: 11


Optimize XML blocks and manually verify XML file coverage.

  • The deny all lines are redundant when immediately followed by return 404; they can be removed.
  • The automated search using fd -e xml did not return any additional XML files. However, this result may be incomplete, so please manually verify that no other XML files require similar protection.
 location = /admin/environment.xml {
-    deny all;
     return 404;
 }

 location = /lib/db/install.xml {
-    deny all;
     return 404;
 }

 location = /mod/assign/db/install.xml {
-    deny all;
     return 404;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8568a33 and a09b317.

📒 Files selected for processing (1)
  • rootfs/etc/nginx/server-conf.d/moodle.conf (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: buildx
🔇 Additional comments (4)
rootfs/etc/nginx/server-conf.d/moodle.conf (4)

1-3: LGTM! Well-implemented error handling.

Good security practice to rewrite 403 (Forbidden) to 404 (Not Found) responses, preventing information disclosure about restricted resources.


42-45: LGTM! Well-implemented dotfiles protection.

Excellent implementation that correctly follows RFC 5785 by allowing .well-known URIs while protecting all other dotfiles.


54-58:

✅ Verification successful

LGTM! Well-implemented file serving optimization.

Excellent implementation that:

  1. Offloads static file serving from PHP to Nginx for better performance
  2. Uses internal directive to prevent direct access
  3. Correctly aliases to the Moodle data directory

Let's verify the Moodle data directory path:


🏁 Script executed:

#!/bin/bash
# Description: Check if the Moodle data directory path is configurable
grep -r "moodledata" .

Length of output: 340


LGTM! Verified and Consistent Configuration

The file serving configuration for /dataroot/ is correctly implemented:

  • The internal directive properly restricts access.
  • The alias to /var/www/moodledata/$1 is consistent across the Nginx config, Docker entrypoint, and Compose settings, ensuring that static file serving is efficiently offloaded from PHP.

No further changes are required.


47-52:

✅ Verification successful

Optimize internal files block and verify Moodle issue.

  1. The deny all directive is redundant when followed by return 404.
  2. Let's verify the referenced Moodle issue MDL-69333 for completeness.
 location ~ (/vendor/|/node_modules/|composer\.json|/readme|/README|readme\.txt|README\.txt|upgrade\.txt|UPGRADING\.md|UPGRADING\-CURRENT\.md|db/install\.xml|/fixtures/|/behat/|phpunit\.xml|\.lock|environment\.xml|doesnotexist|CHANGELOG|CHANGELOG\.md|TRADEMARK\.txt|PULL_REQUEST_TEMPLATE\.txt|INSTALL\.txt|CONTRIBUTING\.txt|behat\.yml\.dist|phpunit\.xml\.dist|package\.json|npm-shrinkwrap\.json|security\.txt|index\.php\.inc) {
-    deny all;
     return 404;
 }

Let's verify the Moodle issue:


🌐 Web query:

What is Moodle issue MDL-69333 about?

💡 Result:

Moodle issue MDL-69333 is a security enhancement introduced in Moodle 3.11 aimed at reducing the ability for attackers to "fingerprint" a server by blocking access to sensitive directories and files that could reveal technical details about the system[1][3][10].

Key Details:

  • Purpose: Prevents unauthorized users from identifying server software versions or configurations by restricting access to paths like /vendor/, /node_modules/, and files such as composer.json, .lock, or environment.xml[1][7][10].
  • Implementation: Requires web server (Apache/Nginx) configuration updates to return 404 errors for restricted paths instead of allowing directory listings or forbidden (403) responses[1][7]. Example Apache rules include:
    RewriteRule "(\/vendor\/)" - [F]
    RewriteRule "(composer\.json)" - [F]
  • Impact: Failing these security checks in Moodle’s admin interface indicates that sensitive paths are still accessible, requiring server adjustments[1][7].

Why It Matters:

This fix addresses vulnerabilities where exposed files/directories could help attackers exploit known weaknesses in dependencies or server setups[1][10]. For example, blocking /vendor/ prevents access to dependency manager files that might reveal outdated libraries[7].

Troubleshooting Tips:

  • Verify URLs like https://yoursite.com/vendor/ return 404[1].
  • Ensure the Moodle server can resolve its own domain (e.g., via /etc/hosts) to avoid false negatives during self-checks[1].
  • Use tools like curl or check Apache/Nginx logs for requests from "MoodleBot" during security scans[1].

This issue highlights Moodle’s focus on hardening server configurations against reconnaissance attacks[3][10].

Citations:


Optimize the internal files protection block per MDL-69333 requirements

  • The Moodle security issue MDL-69333 mandates returning a 404 error for sensitive paths to prevent server fingerprinting. The web query confirms that using return 404; aligns with the security enhancement introduced in Moodle 3.11.
  • The deny all; directive becomes redundant when followed immediately by a return 404; statement. Streamlining the configuration improves clarity while preserving the intended security behavior.
 location ~ (/vendor/|/node_modules/|composer\.json|/readme|/README|readme\.txt|README\.txt|upgrade\.txt|UPGRADING\.md|UPGRADING\-CURRENT\.md|db/install\.xml|/fixtures/|/behat/|phpunit\.xml|\.lock|environment\.xml|doesnotexist|CHANGELOG|CHANGELOG\.md|TRADEMARK\.txt|PULL_REQUEST_TEMPLATE\.txt|INSTALL\.txt|CONTRIBUTING\.txt|behat\.yml\.dist|phpunit\.xml\.dist|package\.json|npm-shrinkwrap\.json|security\.txt|index\.php\.inc) {
-    deny all;
     return 404;
 }

This change both simplifies the configuration and meets the security recommendations.

Comment on lines +12 to +22
# TODO: Temporary block exact match for /privacy/tests/fixtures/logo.png (see issue #74)
location = /privacy/tests/fixtures/logo.png {
deny all;
return 404;
}

# TODO: Temporary block exact match for /enrol/lti/tests/fixtures/input.xml (see issue #74)
location = /enrol/lti/tests/fixtures/input.xml {
deny all;
return 404;
}
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🛠️ Refactor suggestion

🧩 Analysis chain

Address TODO comments and optimize temporary blocks.

  1. These blocks are marked as temporary fixes for issue Public paths error #74. Consider implementing a more permanent solution.
  2. The deny all directives are redundant when followed by return 404.
 location = /privacy/tests/fixtures/logo.png {
-    deny all;
     return 404;
 }

 location =  /enrol/lti/tests/fixtures/input.xml {
-    deny all;
     return 404;
 }

Let's verify the status of issue #74 to understand if a permanent solution is being tracked:


🏁 Script executed:

#!/bin/bash
# Description: Check the status of issue #74
gh issue view 74

Length of output: 513


Update temporary fixture blocks per closed issue #74 and optimize directives.

  • Issue Public paths error #74 ("Public paths error") is now closed, so please review whether these temporary location blocks are still needed. If a permanent fix has been implemented, consider removing these blocks entirely.
  • If the blocks are retained as a fallback, note that using both deny all and return 404 is redundant. Removing deny all ensures clarity, as shown below.
 location = /privacy/tests/fixtures/logo.png {
-    deny all;
     return 404;
 }

 location =  /enrol/lti/tests/fixtures/input.xml {
-    deny all;
     return 404;
 }
📝 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
# TODO: Temporary block exact match for /privacy/tests/fixtures/logo.png (see issue #74)
location = /privacy/tests/fixtures/logo.png {
deny all;
return 404;
}
# TODO: Temporary block exact match for /enrol/lti/tests/fixtures/input.xml (see issue #74)
location = /enrol/lti/tests/fixtures/input.xml {
deny all;
return 404;
}
# TODO: Temporary block exact match for /privacy/tests/fixtures/logo.png (see issue #74)
location = /privacy/tests/fixtures/logo.png {
return 404;
}
# TODO: Temporary block exact match for /enrol/lti/tests/fixtures/input.xml (see issue #74)
location = /enrol/lti/tests/fixtures/input.xml {
return 404;
}

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.

Public paths error
1 participant