FedoraRHEL Based

How To Install ModSecurity with Apache on Fedora 42

Install ModSecurity with Apache on Fedora 42

In this tutorial, we will show you how to install ModSecurity with Apache on Fedora 42. Web security threats continue to evolve at an alarming pace in 2025, making robust protection for web applications more crucial than ever. For system administrators and website owners running Apache on Fedora 42, implementing an effective web application firewall (WAF) has become an essential component of a comprehensive security strategy. ModSecurity stands out as one of the most powerful open-source WAF solutions available, offering real-time monitoring, virtual patching, and advanced threat detection capabilities to protect your web applications from a wide range of attacks.

This guide focuses specifically on installing and configuring ModSecurity with Apache on the latest Fedora 42 release. Whether you’re managing a small business website or enterprise-level applications, this integration provides a significant security enhancement with minimal performance impact. By following the detailed instructions in this article, you’ll establish a robust defense system that helps protect your web applications from common vulnerabilities like SQL injection, cross-site scripting (XSS), and numerous other attack vectors.

Understanding ModSecurity and Its Importance

ModSecurity is a robust open-source web application firewall that functions as a dynamic barrier between your web server and potential threats. Unlike traditional firewalls that operate at the network level, ModSecurity works at the application layer (Layer 7), allowing it to analyze HTTP traffic with remarkable granularity. This capability enables it to identify and block sophisticated attack patterns that might otherwise bypass conventional security measures.

The importance of ModSecurity lies in its versatility and depth of protection. It can effectively prevent numerous attack vectors, including:

  • Cross-site scripting (XSS) attacks
  • SQL injection attempts
  • Remote code execution
  • Local file inclusion
  • Session hijacking
  • HTTP protocol violations
  • Data leakage prevention

ModSecurity uses a rule-based system that allows for customization according to specific security requirements. When integrated with the OWASP Core Rule Set (CRS), ModSecurity provides protection against the OWASP Top 10 web application vulnerabilities-a critical baseline for web security in 2025.

For Fedora 42 users, ModSecurity offers seamless integration with Apache, allowing for enterprise-grade security with minimal resource overhead. As cyber threats become more sophisticated, this layer of defense has shifted from optional to essential for any production web server.

Prerequisites for Installation

Before proceeding with the ModSecurity installation on your Fedora 42 system, several prerequisites must be met to ensure a smooth deployment:

System Requirements:

  • Fedora 42 with current updates applied
  • At least 2GB RAM (4GB recommended for production environments)
  • Minimum 20GB available disk space
  • Root or sudo access to the server

Required Permissions:
Ensure you have administrative privileges on your Fedora system. All installation commands in this guide require root access, which can be obtained through the sudo command.

Backup Recommendation:
Prior to installation, create a backup of your existing Apache configuration files. This precautionary measure allows for easy restoration if unexpected issues arise:

sudo cp -r /etc/httpd /etc/httpd.backup

Verify Existing Apache Installation:
Check if Apache is already installed on your system using:

sudo systemctl status httpd

If Apache isn’t running, the output will indicate that the service is either inactive or could not be found.

Checking System Environment:
To verify your Fedora version, run:

cat /etc/fedora-release

The output should confirm you’re running Fedora 42.

With these prerequisites met, your system is prepared for the ModSecurity installation process.

Updating Your Fedora 42 System

Maintaining an updated system is crucial before installing any security software. Current packages ensure compatibility and include the latest security patches, reducing potential vulnerabilities in your environment.

First, synchronize your package repository information to ensure access to the latest versions:

sudo dnf check-update

Next, perform a full system update:

sudo dnf upgrade -y

During the update process, you may encounter package conflicts. If prompted about package replacements or configuration file modifications, review each notification carefully. Generally, accepting the default option is appropriate, but consider each case individually.

After the update completes, verify system stability by checking for any error messages in the system logs:

sudo journalctl -p err -b

This command displays error-level messages from the current boot. A stable system should show minimal errors, none of which should relate to core system services.

For Fedora 42 specifically, ensure the DNF package manager itself is updated:

sudo dnf upgrade dnf -y

Regular system maintenance habits like these updates not only facilitate smooth ModSecurity installation but also contribute to your server’s overall security posture. With your system now updated, you’re ready to proceed with installing or verifying Apache.

Installing Apache Web Server (if not installed)

Apache serves as the foundation for our ModSecurity implementation. This section guides you through verifying an existing installation or installing Apache fresh on Fedora 42.

Verifying Apache Installation:

First, check whether Apache is already installed:

rpm -q httpd

If Apache is installed, this command returns the package version. If not, it returns “package httpd is not installed.”

Installing Apache:

If Apache isn’t installed, proceed with installation:

sudo dnf install httpd -y

After installation completes, start the Apache service and enable it to launch automatically at boot:

sudo systemctl start httpd
sudo systemctl enable httpd

Verify Apache Service Status:

Confirm Apache is running properly:

sudo systemctl status httpd

The output should show “active (running)” with no errors.

Test Apache Installation:

Create a simple test page to verify Apache is serving content correctly:

echo "<html><body><h1>Apache Test Page</h1><p>Apache is working correctly on Fedora 42.</p></body></html>" | sudo tee /var/www/html/test.html

Now access this page by opening a web browser and navigating to:

http://your_server_ip/test.html

If you see the test page, Apache is properly installed and functioning. If you cannot access the page, check that the firewall allows HTTP traffic:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reload

With Apache successfully installed and running, you’re ready to move on to installing the ModSecurity dependencies.

Installing ModSecurity Dependencies

ModSecurity requires several development packages to function properly with Apache on Fedora 42. These dependencies provide essential libraries and tools for compiling, installing, and running the WAF effectively.

Begin by installing the core development packages:

sudo dnf install gcc gcc-c++ make automake autoconf libtool pcre pcre-devel libxml2 libxml2-devel curl curl-devel httpd-devel -y

Next, install additional libraries that enhance ModSecurity’s capabilities:

sudo dnf install yajl yajl-devel lua lua-devel ssdeep-devel lmdb-devel -y

For comprehensive logging functionality, install:

sudo dnf install geoip-devel -y

To verify successful installation of these dependencies, use the following commands:

rpm -q gcc curl-devel httpd-devel

Each command should return the package version if properly installed.

Troubleshooting Dependency Installation:

If any package fails to install, you might encounter errors like:

No package [package-name] available.

This typically occurs if a package name has changed in Fedora 42. Try searching for alternative package names:

sudo dnf search [partial-package-name]

For dependencies with version conflicts, you may need to enable additional repositories:

sudo dnf install dnf-plugins-core -y
sudo dnf config-manager --enable fedora-modular
sudo dnf config-manager --enable fedora-updates-modular

Understanding these dependency relationships is important-ModSecurity relies on these libraries for parsing HTTP requests, processing rule logic, and performing pattern matching against potential threats. With all dependencies successfully installed, you’re ready to install the ModSecurity module itself.

Installing ModSecurity Module

With the dependencies in place, you can now install the ModSecurity module on your Fedora 42 system. There are two primary methods for installation: using the DNF package manager or compiling from source code. This guide focuses on the DNF method for simplicity and reliability, but includes information about source installation for advanced users.

Installation via DNF Package Manager

The simplest and most reliable method is using Fedora’s package manager:

sudo dnf install mod_security -y

After installation completes, verify that ModSecurity was properly installed:

sudo dnf list installed mod_security

This should return information about the installed package, including its version.

Alternative: Source Code Installation

For users requiring specific versions or custom compilation options, installing from source is an alternative:

# Download and extract ModSecurity
cd /usr/src/
sudo wget https://github.com/SpiderLabs/ModSecurity/releases/download/v2.9.7/modsecurity-2.9.7.tar.gz
sudo tar xzf modsecurity-2.9.7.tar.gz
cd modsecurity-2.9.7

# Configure and compile
sudo ./configure --with-apxs=/usr/bin/apxs
sudo make
sudo make install

# Copy the module definition file
sudo cp modsecurity.conf-recommended /etc/httpd/conf.d/modsecurity.conf

Installation Verification Process:

To verify the ModSecurity module is correctly recognized by Apache:

sudo apachectl -M | grep security

This command should return “security2_module (shared)” if ModSecurity is properly installed and recognized.

Potential Installation Errors:

If you encounter errors during installation, check these common issues:

  1. Missing dependencies: Ensure all required packages from the previous section were successfully installed.
  2. Version conflicts: Fedora 42 may require specific versions of certain libraries.
  3. Apache configuration issues: Verify that Apache is properly configured and running.

For module loading errors, check the Apache error log:

sudo tail -f /var/log/httpd/error_log

With ModSecurity successfully installed, you can proceed to the initial configuration steps.

Initial ModSecurity Configuration

After successfully installing ModSecurity, the initial configuration is crucial for proper functionality. The default installation includes a recommended configuration file that needs to be properly set up.

First, locate the recommended configuration file:

sudo find / -name "modsecurity.conf-recommended"

On Fedora 42, this file is typically located at /etc/httpd/modsecurity.d/modsecurity.conf-recommended.

Copy this file to create your active configuration:

sudo cp /etc/httpd/modsecurity.d/modsecurity.conf-recommended /etc/httpd/modsecurity.d/modsecurity.conf

Open the configuration file in your preferred text editor:

sudo nano /etc/httpd/modsecurity.d/modsecurity.conf

Within this file, find the SecRuleEngine directive, which controls how ModSecurity processes rules:

SecRuleEngine DetectionOnly

Change this setting to On to enable active protection:

SecRuleEngine On

This change switches ModSecurity from merely detecting threats to actively blocking them according to the defined rules.

Additional important configuration directives include:

  • SecResponseBodyAccess: Controls whether ModSecurity inspects response bodies
  • SecAuditLog: Defines the location of ModSecurity’s detailed audit log
  • SecAuditLogParts: Specifies which parts of requests/responses are logged
  • SecRequestBodyLimit: Sets the maximum request body size ModSecurity will process

For basic implementation, the default values for these directives are sufficient. However, understanding these options allows for future tuning based on your specific security requirements.

Save and close the file after making the necessary changes. With this initial configuration complete, you’re now ready to integrate ModSecurity with your Apache web server.

Configuring Apache to Use ModSecurity

With ModSecurity installed and initially configured, you now need to integrate it with Apache. This process involves editing Apache configuration files to load the ModSecurity module and apply its rules.

First, create a new configuration file for ModSecurity in Apache’s configuration directory:

sudo nano /etc/httpd/conf.d/mod_security.conf

Add the following content to this file:

# Load ModSecurity module
LoadModule security2_module modules/mod_security2.so

# Basic ModSecurity configuration
<IfModule security2_module>
    # Include the primary ModSecurity configuration file
    Include modsecurity.d/modsecurity.conf
    
    # Include ModSecurity Core Rule Set (to be added later)
    # Include modsecurity.d/owasp-crs/crs-setup.conf
    # Include modsecurity.d/owasp-crs/rules/*.conf
</IfModule>

Save and close the file.

Next, verify that your Apache configuration syntax is correct:

sudo apachectl configtest

If the configuration is valid, you’ll see:
Syntax OK

If any errors appear, review your configuration files and correct them before proceeding.

Now restart Apache to apply the changes:

sudo systemctl restart httpd

Verify that ModSecurity is loaded by checking the Apache error log:

sudo grep -i "modsecurity" /var/log/httpd/error_log

You should see entries indicating that ModSecurity has been initialized, similar to:

ModSecurity: APR compiled version="1.7.0"; loaded version="1.7.0"
ModSecurity: PCRE compiled version="8.44"; loaded version="8.44"
ModSecurity: LUA compiled version="Lua 5.4"
ModSecurity: LIBXML compiled version="2.9.13"
ModSecurity for Apache/2.9.7 (http://www.modsecurity.org/) configured.

At this point, ModSecurity is integrated with Apache, but it lacks comprehensive rule sets. The next step is to install the OWASP Core Rule Set, which provides a robust foundation of security rules.

Installing OWASP Core Rule Set (CRS)

The OWASP ModSecurity Core Rule Set (CRS) is a set of generic attack detection rules that significantly enhances ModSecurity’s protective capabilities. These rules provide detection for a wide range of attacks without requiring specific knowledge about the protected applications.

Begin by creating a directory for the CRS:

sudo mkdir -p /etc/httpd/modsecurity.d/owasp-crs

Download the latest CRS package from the official GitHub repository:

cd /tmp
sudo wget https://github.com/coreruleset/coreruleset/archive/v3.3.5.tar.gz
sudo tar -xzvf v3.3.5.tar.gz

Copy the extracted files to the ModSecurity directory:

sudo cp -R coreruleset-3.3.5/* /etc/httpd/modsecurity.d/owasp-crs/

Create a configuration setup file by copying the example:

sudo cp /etc/httpd/modsecurity.d/owasp-crs/crs-setup.conf.example /etc/httpd/modsecurity.d/owasp-crs/crs-setup.conf

Now update your ModSecurity Apache configuration to include the CRS. Edit the previously created file:

sudo nano /etc/httpd/conf.d/mod_security.conf

Update the include directives to uncomment the CRS lines:

# Load ModSecurity module
LoadModule security2_module modules/mod_security2.so

# Basic ModSecurity configuration
<IfModule security2_module>
    # Include the primary ModSecurity configuration file
    Include modsecurity.d/modsecurity.conf
    
    # Include ModSecurity Core Rule Set
    Include modsecurity.d/owasp-crs/crs-setup.conf
    Include modsecurity.d/owasp-crs/rules/*.conf
</IfModule>

Save and close the file. Test your Apache configuration to ensure syntax is correct:

sudo apachectl configtest

If successful, restart Apache to apply the changes:

sudo systemctl restart httpd

The OWASP CRS provides layered security with different rule categories, including:

  • Protocol violations
  • Request limits
  • HTTP policy enforcement
  • Bad robots detection
  • Common web attacks protection
  • Trojan protection
  • Outbound data leakage prevention

With the CRS now installed and configured, your ModSecurity implementation has a comprehensive set of rules designed to protect against common web application threats.

Configuring Core Rule Sets

After installing the OWASP Core Rule Set, fine-tuning the configuration allows you to balance security needs with application functionality. The CRS offers various paranoia levels and customization options to adjust protection based on your risk tolerance.

Start by editing the CRS setup configuration file:

sudo nano /etc/httpd/modsecurity.d/owasp-crs/crs-setup.conf

Adjusting Paranoia Level:

The paranoia level (PL) determines rule sensitivity, with higher levels providing more security but potentially more false positives:

# -- [[ Paranoia Level ]] ------------------------------------------------------
# Set the paranoia level, from 1 (minimal) to 4 (severe)
SecAction \
  "id:900000,\
  phase:1,\
  nolog,\
  pass,\
  t:none,\
  setvar:tx.paranoia_level=1"

For most environments, start with level 1 and increase gradually as you become comfortable with managing false positives.

Understanding Rule Categories:

The CRS organizes rules into categories for easier management:

  1. REQUEST-900-EXCLUSION-RULES-BEFORE-CRS: Pre-CRS exclusion rules
  2. REQUEST-901-INITIALIZATION: Sets up CRS variables and initial configurations
  3. REQUEST-905-COMMON-EXCEPTIONS: Common exceptions for false positives
  4. REQUEST-910-IP-REPUTATION through REQUEST-999: Various attack protections
  5. RESPONSE-980-CORRELATION: Correlates request/response information

Enabling/Disabling Specific Rule Sets:

To disable a specific rule set, create custom exclusion files:

sudo mkdir -p /etc/httpd/modsecurity.d/custom-rules
sudo nano /etc/httpd/modsecurity.d/custom-rules/exclusion-rules.conf

For example, to disable SQL injection rules for a specific URL:

# Disable SQL injection rules for admin page
SecRule REQUEST_URI "@beginsWith /admin/database" \
  "id:1000,\
  phase:1,\
  pass,\
  nolog,\
  ctl:ruleRemoveById=942100-942999"

After making these changes, update your ModSecurity configuration to include your custom rules:

sudo nano /etc/httpd/conf.d/mod_security.conf

Add the custom rules inclusion:

# Include custom rules
Include modsecurity.d/custom-rules/*.conf

Save the file and check your Apache configuration:

sudo apachectl configtest

If successful, restart Apache:

sudo systemctl restart httpd

Properly configured rule sets provide effective protection while minimizing disruption to legitimate site functionality. As you become more familiar with ModSecurity, you can further refine these configurations to meet your specific security requirements.

Testing ModSecurity Installation

After installation and configuration, thoroughly testing your ModSecurity setup is essential to ensure it’s providing the expected protection. These tests verify that rules are functioning correctly without disrupting legitimate traffic.

Basic Installation Verification:

First, confirm ModSecurity is active and processing requests:

sudo tail -f /var/log/httpd/error_log | grep -i modsecurity

Watch this output while making requests to your web server. You should see ModSecurity processing information.

Testing Protection Against Common Attacks:

  1. SQL Injection Test:Create a test URL that contains SQL injection patterns:
    http://your_server_ip/?id=1' OR '1'='1

    If ModSecurity is working correctly, this should be blocked and generate a log entry.

  2. XSS Attack Test:Test a basic cross-site scripting pattern:
    http://your_server_ip/?search=<script>alert('XSS')</script>

    This should trigger ModSecurity’s XSS protection.

  3. Local File Inclusion Test:Attempt to access system files:
    http://your_server_ip/?page=../../../etc/passwd

    ModSecurity should block this directory traversal attempt.

Interpreting Test Results:

After running these tests, check the ModSecurity audit log:

sudo tail -f /var/log/httpd/modsec_audit.log

Look for entries containing “Access denied” or similar blocking messages. Each entry should include:

  • The triggered rule ID
  • A description of the attack
  • The offending part of the request

Troubleshooting Failed Tests:

If tests don’t produce expected results:

  1. Verify that SecRuleEngine is set to On in your configuration
  2. Check that the Core Rule Set is properly included
  3. Examine Apache error logs for ModSecurity initialization issues:
    sudo grep -i "modsecurity" /var/log/httpd/error_log
  4. Confirm rule loading by searching for CRS initialization:
    sudo grep -i "coreruleset" /var/log/httpd/error_log

These tests help verify that your ModSecurity installation is functioning properly. Once you confirm successful protection against test attacks, you can be more confident in your web application’s security posture.

Setting Up ModSecurity Logging

Effective logging is a crucial component of any security system. ModSecurity’s logging capabilities provide detailed visibility into both attack attempts and potential false positives. Properly configured logging helps with incident response, troubleshooting, and security audits.

Configure Audit Log Settings:

Edit the ModSecurity configuration file:

sudo nano /etc/httpd/modsecurity.d/modsecurity.conf

Locate the audit log directives and configure them according to your needs:

# Audit log configuration
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus "^(?:5|4(?!04))"
SecAuditLogParts ABIJDEFHZ
SecAuditLogType Serial
SecAuditLog /var/log/httpd/modsec_audit.log

Understanding Log Formats:

ModSecurity audit logs consist of several sections, identified by letters:

  • A: Audit log header
  • B: Request headers
  • C: Request body
  • D: Response headers
  • E: Response body
  • F: Audit log trailer
  • H: Audit log header (non-standard)
  • I: Request body (without processing)
  • J: Data uploaded as files
  • K: List of matched rules
  • Z: Final boundary

Setting Appropriate Log Levels:

The SecAuditEngine directive controls what gets logged:

  • Off: No audit logging
  • On: Log all transactions
  • RelevantOnly: Log only transactions that triggered rules or meet other criteria

For most production environments, RelevantOnly provides a good balance between information and log size.

Example Log Entry Analysis:

A typical ModSecurity log entry follows this pattern:

--f15377a4-A--
[17/May/2025:13:45:23 +0700] MjUxMjcK 192.168.1.105 34266 192.168.1.10 80
--f15377a4-B--
GET /?id=1%27%20OR%201=1 HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
...
--f15377a4-H--
Message: Access denied with code 403 (phase 2). Pattern match "(?i:[\"'`]\\s*?or\\s+[\\w\\s-]+\\s*?[=<>])" at ARGS:id. [file "/etc/httpd/modsecurity.d/owasp-crs/rules/REQUEST-942-APPLICATION-ATTACK-SQLI.conf"] [line "65"] [id "942190"] [rev ""] [msg "Detects MSSQL code execution and information gathering attempts"] [data "' OR 1=1"] [severity "CRITICAL"] [ver "OWASP_CRS/3.3.5"] [maturity ""] [accuracy ""] [tag "application-multi"] [tag "language-multi"] [tag "platform-multi"] [tag "attack-sqli"] [tag "paranoia-level/1"] [tag "OWASP_CRS"] [tag "capec/1000/152/248/66"] [tag "PCI/6.5.2"] [hostname "example.com"] [uri "/"] [unique_id "MjUxMjcK"]
--f15377a4-Z--

This detailed information helps identify attack patterns, troubleshoot issues, and document security incidents.

With proper logging configuration, you’ll have valuable data for ongoing security monitoring and improvement of your ModSecurity implementation.

Implementing Log Rotation

Without proper log rotation, ModSecurity audit logs can quickly consume available disk space. Implementing log rotation ensures that logs are properly maintained while preserving valuable security information.

Create a logrotate configuration file specifically for ModSecurity:

sudo nano /etc/logrotate.d/modsecurity

Add the following configuration:

/var/log/httpd/modsec_audit.log {
    daily
    rotate 14
    compress
    delaycompress
    missingok
    notifempty
    create 0640 apache root
    sharedscripts
    postrotate
        systemctl reload httpd >/dev/null 2>&1 || true
    endscript
}

This configuration:

  • Rotates logs daily
  • Keeps 14 days of log history
  • Compresses older logs to save space
  • Skips rotation if logs are empty
  • Creates new log files with proper permissions
  • Reloads Apache after rotation to ensure continued logging

To test your logrotate configuration:

sudo logrotate --debug /etc/logrotate.d/modsecurity

This command provides verbose output about what logrotate would do without actually rotating the logs. If no errors appear, your configuration is correct.

To force an immediate log rotation:

sudo logrotate -f /etc/logrotate.d/modsecurity

After rotation, verify that new logs are still being written correctly:

sudo touch /var/log/httpd/test_request
sudo tail -f /var/log/httpd/modsec_audit.log

Generate some test traffic to your web server and ensure new entries appear in the log file.

With log rotation properly configured, you can maintain a comprehensive security audit trail without consuming excessive disk space.

Fine-tuning ModSecurity Rules

After initial implementation, fine-tuning ModSecurity rules is essential to balance security with usability. This process involves identifying false positives and adjusting rules to match your specific application requirements.

Balancing Security with Performance:

ModSecurity rules can impact server performance. Start with these optimization strategies:

  1. Use rule sets selectively by including only necessary protections
  2. Apply resource-intensive rules only to specific URL patterns
  3. Adjust the paranoia level based on server capacity and protection needs

Identifying False Positives:

Review ModSecurity audit logs regularly to identify legitimate requests being blocked:

sudo grep "Access denied" /var/log/httpd/modsec_audit.log

Common false positives often appear in:

  • Form submissions with complex data
  • File uploads
  • API endpoints with custom data formats
  • Admin interfaces with powerful features

Creating Exceptions for Legitimate Traffic:

Create a custom exceptions file:

sudo nano /etc/httpd/modsecurity.d/custom-rules/whitelist.conf

Add rules to exclude specific traffic patterns:

# Example: Whitelist file upload endpoint from specific rules
SecRule REQUEST_URI "@beginsWith /admin/upload" \
  "id:10000,\
  phase:1,\
  pass,\
  nolog,\
  ctl:ruleRemoveById=200004"

# Example: Exempt specific form from SQL injection rules
SecRule REQUEST_URI "@beginsWith /app/complex-form" \
  "id:10001,\
  phase:1,\
  pass,\
  nolog,\
  ctl:ruleRemoveByTag=attack-sqli"

Rule Priority and Processing Order:

Rules are processed in order of their ID numbers. Understanding this hierarchy helps when creating exceptions:

  1. REQUEST-900-EXCLUSION-RULES-BEFORE-CRS: Executes first (ID range 900,000-909,999)
  2. Core Rule Set rules: Execute next (various ID ranges)
  3. REQUEST-949-BLOCKING-EVALUATION: Evaluates collected anomaly scores (ID range 949,000-949,999)
  4. Custom exceptions after CRS: Execute last (ID range 980,000-999,999)

Performance Considerations:

Monitor Apache performance after implementing ModSecurity:

sudo httpd -V
ab -n 1000 -c 10 http://your_server_ip/

If performance degradation is significant, consider:

  • Excluding static content from inspection
  • Optimizing rule selection for specific URL patterns
  • Increasing server resources if necessary

Through careful fine-tuning, you can maintain strong security while minimizing both false positives and performance impact. This ongoing process should be revisited as your applications evolve.

Creating Custom Security Rules

While the OWASP CRS provides excellent general protection, creating custom rules allows you to address specific security requirements unique to your applications.

ModSecurity Rule Syntax Basics:

ModSecurity rules follow this basic structure:

SecRule VARIABLES "@OPERATOR EXPRESSION" "ACTIONS"

Where:

  • VARIABLES: What to inspect (REQUEST_URI, ARGS, etc.)
  • OPERATOR: How to perform the inspection (contains, beginsWith, etc.)
  • EXPRESSION: What pattern to match
  • ACTIONS: What to do when a match occurs (block, allow, log, etc.)

Example Custom Rules:

  1. Block Specific User-Agent:
    # Block known malicious bot
    SecRule REQUEST_HEADERS:User-Agent "@contains BadBot" \
      "id:20000,\
      phase:1,\
      deny,\
      status:403,\
      log,\
      msg:'Known malicious user agent'"
  2. Rate Limiting for Authentication Endpoints:
    # Track and limit login attempts
    SecRule REQUEST_URI "@beginsWith /login" \
      "id:20001,\
      phase:1,\
      pass,\
      nolog,\
      setvar:ip.login_attempt=+1,\
      expirevar:ip.login_attempt=60"
    
    SecRule IP:LOGIN_ATTEMPT "@gt 5" \
      "id:20002,\
      phase:1,\
      deny,\
      status:429,\
      log,\
      msg:'Excessive login attempts'"
  3. Custom File Upload Protection:
    # Additional verification for uploaded files
    SecRule FILES_NAMES "@rx \.(?:php|phtml|php5|php4|php3|php2|php1)$" \
      "id:20003,\
      phase:2,\
      deny,\
      status:403,\
      log,\
      msg:'PHP file upload attempt'"

Testing Custom Rules Safely:

Before implementing custom rules in production, test them in a development environment or with minimal impact:

# Create a test configuration
sudo cp /etc/httpd/conf.d/mod_security.conf /etc/httpd/conf.d/mod_security.conf.test

# Edit test configuration to include only test rules
sudo nano /etc/httpd/conf.d/mod_security.conf.test

# Test configuration syntax
sudo apachectl -t -f /etc/httpd/conf.d/mod_security.conf.test

Rule Organization Best Practices:

Organize custom rules for maintainability:

  1. Group rules by function (authentication, file uploads, API protection)
  2. Use consistent ID numbering schemes (e.g., 20000-29999 for custom rules)
  3. Document each rule with clear comments
  4. Store rules in separate files based on functionality

With well-crafted custom rules, you can extend ModSecurity’s protection to address specific threats facing your web applications while maintaining control over security policy enforcement.

Monitoring and Maintaining ModSecurity

Effective monitoring and regular maintenance are essential for ensuring ModSecurity continues to provide optimal protection for your web applications.

Regular Rule Updates Procedure:

The OWASP CRS is regularly updated to address new threats. Establish a routine update process:

  1. Check for updates monthly:
    cd /tmp
    sudo wget https://github.com/coreruleset/coreruleset/archive/v3.3.x.tar.gz
  2. Back up existing rules:
    sudo cp -r /etc/httpd/modsecurity.d/owasp-crs /etc/httpd/modsecurity.d/owasp-crs-backup
  3. Extract and install updates:
    sudo tar -xzf v3.3.x.tar.gz
    sudo cp -r coreruleset-3.3.x/rules/* /etc/httpd/modsecurity.d/owasp-crs/rules/
  4. Test configuration:
    sudo apachectl configtest
  5. Restart Apache:
    sudo systemctl restart httpd

Monitoring Security Events:

Implement regular log review:

# Daily summary of denied requests
sudo grep "Access denied" /var/log/httpd/modsec_audit.log | cut -d' ' -f3 | sort | uniq -c | sort -rn

Consider setting up log forwarding to a centralized security information and event management (SIEM) system for more comprehensive monitoring.

Performance Impact Assessment:

Periodically evaluate ModSecurity’s performance impact:

# Check Apache server status
sudo systemctl status httpd

# Monitor resource usage
sudo dnf install sysstat
sudo sar -u 1 10

Unusual CPU spikes during high traffic may indicate rules that need optimization.

Integration with Other Security Tools:

Enhance ModSecurity with complementary security tools:

  1. Fail2ban: Block repeated offenders at the firewall level
  2. Malware scanners: Regularly scan web content for malicious code
  3. Network monitoring: Identify unusual traffic patterns before they reach ModSecurity

Scheduled Maintenance Recommendations:

Create a maintenance schedule including:

  • Weekly log review and false positive identification
  • Monthly rule updates
  • Quarterly performance assessment
  • Semi-annual security posture review

By implementing these monitoring and maintenance practices, you ensure your ModSecurity installation remains effective against evolving threats while maintaining optimal performance.

Troubleshooting Common Issues

Even with careful installation and configuration, you may encounter issues with ModSecurity. This section covers common problems and their solutions.

Diagnosing Rule Conflicts:

Rule conflicts typically manifest as unexpected blocking behavior. To troubleshoot:

  1. Identify the conflicting rules from logs:
    sudo grep -A 10 "Access denied" /var/log/httpd/modsec_audit.log
  2. Temporarily disable suspected rules:
    SecRuleRemoveById 942100
  3. Re-enable rules one by one to identify the conflict

Handling Apache Startup Failures:

If Apache fails to start after ModSecurity configuration:

  1. Check syntax errors:
    sudo apachectl configtest
  2. Review Apache error logs:
    sudo tail -n 50 /var/log/httpd/error_log
  3. Common startup issues include:
    • Incorrect file paths in Include directives
    • Syntax errors in custom rules
    • Missing rule files referenced in configuration
  4. Restore from backup if necessary:
    sudo cp /etc/httpd.backup/conf.d/mod_security.conf /etc/httpd/conf.d/

Addressing Performance Degradation:

If ModSecurity causes significant performance issues:

  1. Identify resource-intensive rules:
    sudo grep -i "performance" /var/log/httpd/error_log
  2. Optimize by excluding non-critical endpoints:
    SecRule REQUEST_URI "@beginsWith /static/" "id:30000,phase:1,pass,nolog,ctl:ruleEngine=Off"
  3. Consider increasing Apache’s process limits in /etc/httpd/conf/httpd.conf:
    <IfModule prefork.c>
        StartServers 10
        MinSpareServers 5
        MaxSpareServers 10
        MaxRequestWorkers 150
        MaxConnectionsPerChild 3000
    </IfModule>

Resolving False Positive Detections:

For legitimate requests being blocked:

  1. Identify the blocking rule from logs
  2. Create a targeted exception:
    # Example: Whitelist specific parameter
    SecRule REQUEST_URI "@beginsWith /app/form" \
      "id:30001,\
      phase:1,\
      pass,\
      nolog,\
      ctl:ruleRemoveTargetById=942100;ARGS:complex_parameter"

Debugging Protection Bypass Scenarios:

If attacks are bypassing ModSecurity:

  1. Verify rules are loading properly:
    sudo grep -i "loaded" /var/log/httpd/error_log | grep -i rule
  2. Test rule triggering with known attack patterns
  3. Check for improper exception rules that might be too broad
  4. Ensure SecRuleEngine is set to “On” not “DetectionOnly”

By systematically addressing these common issues, you can maintain an effective ModSecurity implementation while minimizing disruptions to legitimate web traffic.

Congratulations! You have successfully installed ModSecurity with Apache. Thanks for using this tutorial for installing ModSecurity with Apache on Fedora 42 Linux system. For additional help or useful information, we recommend you check the official ModSecurity website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button