### Install and Verify ModSecurity Apache Module
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
This snippet shows the commands to install the ModSecurity module for Apache and verify its successful installation by checking for the module file in the Apache modules directory.
```bash
sudo make install
ls -l /usr/lib/apache2/modules/mod_security3.so
```
--------------------------------
### ModSecurity Apache Module Build from Source (Bash)
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
Instructions for building the ModSecurity Apache module from source code using autotools and make. It requires libmodsecurity to be installed first and specifies paths for Apache's apxs and the libmodsecurity installation. The commands involve generating the configure script, configuring the build, and then compiling the module.
```bash
# Prerequisites: libmodsecurity must be installed first
# Download libmodsecurity from ModSecurity v3 repository
# Generate configure script
./autogen.sh
# Configure with Apache paths
./configure --with-apxs=/usr/bin/apxs --with-libmodsecurity=/usr/local/modsecurity
# Build the module
make
```
--------------------------------
### Load ModSecurity Rules from Local File
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
Configures ModSecurity to load security rules from a local file or multiple files. The `modsecurity_rules_file` directive points to the rule set. This allows for centralized rule management. An example of a basic rule format is provided.
```apache
# Basic configuration with local rules file
modsecurity On
modsecurity_rules_file /etc/apache2/modsecurity/modsecurity.conf
# Multiple rule files can be loaded
modsecurity On
modsecurity_rules_file /etc/modsecurity/api-rules.conf
# Expected rules file format:
# SecRuleEngine On
# SecRequestBodyAccess On
# SecRule ARGS "@contains malicious" "id:1,phase:2,deny,status:403"
```
--------------------------------
### ModSecurity Module Initialization (C)
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
Initializes the ModSecurity engine for the Apache module. It allocates global structures, initializes the ModSecurity library, sets connector information, registers a cleanup handler, and sets a custom logging callback. This function is called once per Apache lifecycle. Dependencies include APR and ModSecurity library functions.
```c
// Initialize ModSecurity engine - called once per Apache lifecycle
int msc_apache_init(apr_pool_t *mp) {
// Allocate global ModSecurity structure
msc_apache = apr_pcalloc(mp, sizeof(msc_global));
if (msc_apache == NULL) {
return -1;
}
// Initialize ModSecurity library
msc_apache->modsec = msc_init();
// Set connector identification
msc_set_connector_info(msc_apache->modsec, MSC_APACHE_CONNECTOR);
// Register cleanup handler
apr_pool_cleanup_register(mp, NULL, msc_module_cleanup,
apr_pool_cleanup_null);
// Set logging callback
msc_set_log_cb(msc_apache->modsec, modsecurity_log_cb);
return 0;
}
// Custom logging callback for ModSecurity messages
void modsecurity_log_cb(void *log, const void* data) {
if (log == NULL || data == NULL) {
return;
}
const char *msg = (const char *) data;
request_rec *r = (request_rec *) log;
#if AP_SERVER_MAJORVERSION_NUMBER > 1 && AP_SERVER_MINORVERSION_NUMBER > 2
ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, r,
msg, r->status);
#else
ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, r->server,
msg, r->status);
#endif
}
```
--------------------------------
### Configure ModSecurity Apache Module
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
This snippet outlines the Apache configuration files required to load and enable the ModSecurity module. It includes loading the module dynamically and setting up global ModSecurity directives, including the paths to the main configuration and rule set files.
```apache
# /etc/apache2/mods-available/security3.load
LoadModule security3_module /usr/lib/apache2/modules/mod_security3.so
# /etc/apache2/mods-available/security3.conf
# Global ModSecurity configuration
modsecurity On
modsecurity_rules_file /etc/modsecurity/modsecurity.conf
modsecurity_rules_file /etc/modsecurity/crs-setup.conf
modsecurity_rules_file /etc/modsecurity/rules/*.conf
```
--------------------------------
### Enable ModSecurity Module in Apache
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
Loads the ModSecurity 3 module (`mod_security3.so`) and enables ModSecurity for specific Apache contexts (VirtualHost, Directory). The `modsecurity On` directive activates the module, and `modsecurity_rules_file` specifies the configuration file for security rules. Use `modsecurity Off` to disable it for certain directories.
```apache
# Load the ModSecurity 3 module
LoadModule security3_module modules/mod_security3.so
# Enable ModSecurity in specific contexts
modsecurity On
modsecurity_rules_file /etc/modsecurity/rules.conf
modsecurity On
modsecurity Off
```
--------------------------------
### Create ModSecurity Transaction Context in C
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
This C code snippet demonstrates how to create a ModSecurity transaction context within an Apache module. It retrieves per-directory configuration, allocates a transaction structure, and initializes a new ModSecurity transaction using either a unique ID or a default one. The transaction context is then stored in Apache's request notes for later access.
```c
#include "mod_security3.h"
// Called during request processing to initialize ModSecurity transaction
static msc_t *create_tx_context(request_rec *r) {
msc_t *msr = NULL;
msc_conf_t *z = NULL;
char *unique_id = NULL;
// Get per-directory configuration
z = (msc_conf_t *)ap_get_module_config(r->per_dir_config,
&security3_module);
// Allocate transaction structure
msr = (msc_t *)apr_pcalloc(r->pool, sizeof(msc_t));
if (msr == NULL) {
return NULL;
}
msr->r = r;
// Use UNIQUE_ID if available for correlation
unique_id = getenv("UNIQUE_ID");
if (unique_id != NULL && strlen(unique_id) > 0) {
msr->t = msc_new_transaction_with_id(msc_apache->modsec,
z->rules_set, unique_id, (void *)r);
} else {
msr->t = msc_new_transaction(msc_apache->modsec,
z->rules_set, (void *)r);
}
// Store in request notes for retrieval
apr_table_setn(r->notes, NOTE_MSR, (void *)msr);
return msr;
}
```
--------------------------------
### Enable and Reload Apache with ModSecurity
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
This snippet provides the commands to enable the ModSecurity module within Apache's configuration and then reload the Apache service to apply the changes. This is necessary after modifying the Apache configuration files.
```bash
# sudo a2enmod security3
# sudo systemctl reload apache2
```
--------------------------------
### ModSecurity Apache Hook Registration (C)
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
Registers various Apache hooks for ModSecurity processing, including pre-configuration, post-configuration, request reading, connection processing, fixes, logging, and filter registration. This ensures ModSecurity intercepts and processes requests and responses at the appropriate stages. Dependencies include Apache API functions for hook registration.
```c
// Register Apache hooks for ModSecurity processing phases
static void msc_register_hooks(apr_pool_t *pool) {
// Module initialization hooks
ap_hook_pre_config(msc_hook_pre_config, NULL, NULL, APR_HOOK_FIRST);
ap_hook_post_config(msc_hook_post_config, postconfig_beforeme_list,
postconfig_afterme_list, APR_HOOK_REALLY_LAST);
// Connection and request processing hooks
ap_hook_post_read_request(hook_request_early,
postread_beforeme_list, postread_afterme_list, APR_HOOK_REALLY_FIRST);
ap_hook_process_connection(hook_connection_early, NULL, NULL,
APR_HOOK_FIRST);
ap_hook_fixups(hook_request_late, fixups_beforeme_list, NULL,
APR_HOOK_REALLY_FIRST);
// Filter insertion hook
ap_hook_insert_filter(hook_insert_filter, NULL, NULL, APR_HOOK_FIRST);
// Logging hook
ap_hook_log_transaction(hook_log_transaction, NULL,
transaction_afterme_list, APR_HOOK_MIDDLE);
// Register input/output filters
ap_register_input_filter("MODSECURITY_IN", input_filter,
NULL, AP_FTYPE_CONTENT_SET);
ap_register_output_filter("MODSECURITY_OUT", output_filter,
NULL, AP_FTYPE_CONTENT_SET - 3);
}
```
--------------------------------
### Load ModSecurity Rules from Remote Server
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
Enables ModSecurity to download and load security rules from a remote server URL. The `modsecurity_rules_remote` directive requires an authentication key and the URL to the rule file. This is useful for dynamic rule updates and centralized management across multiple servers.
```apache
# Download rules from remote server with authentication
modsecurity On
modsecurity_rules_remote my-server-key https://example.com/rules/download
# The key authenticates to the remote server
# Rules are downloaded and loaded at Apache startup
modsecurity On
modsecurity_rules_remote prod-key-12345 https://rules.example.com/production/rules.conf
SSLEngine on
SSLCertificateFile /etc/ssl/certs/server.crt
SSLCertificateKeyFile /etc/ssl/private/server.key
```
--------------------------------
### Handle ModSecurity Intervention Actions (C)
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
This C function checks for and handles intervention actions dictated by ModSecurity rules. It queries the ModSecurity transaction for any required actions, such as blocking the request, redirecting the user, or logging a message. It then applies the appropriate action, returning an HTTP status code or continuing processing.
```c
// Processes ModSecurity intervention (block, redirect, etc.)
int process_intervention(Transaction *t, request_rec *r) {
ModSecurityIntervention intervention;
intervention.status = N_INTERVENTION_STATUS; // 200
intervention.url = NULL;
intervention.log = NULL;
intervention.disruptive = 0;
// Query ModSecurity for intervention
int z = msc_intervention(t, &intervention);
if (z == 0) {
return N_INTERVENTION_STATUS; // No action needed
}
// Set default log message
if (intervention.log == NULL) {
intervention.log = "(no log message was specified)";
}
// Handle redirects (301, 302, 303, 307)
if (intervention.status == 301 || intervention.status == 302 ||
intervention.status == 303 || intervention.status == 307) {
if (intervention.url != NULL) {
apr_table_setn(r->headers_out, "Location", intervention.url);
return HTTP_MOVED_TEMPORARILY;
}
}
// Return status code if intervention triggered
if (intervention.status != N_INTERVENTION_STATUS) {
return intervention.status; // 403, 404, 500, etc.
}
return N_INTERVENTION_STATUS;
}
```
--------------------------------
### Define ModSecurity Rules Inline in Apache Configuration
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
Allows individual ModSecurity rules to be defined directly within the Apache configuration files using the `modsecurity_rules` directive. This is useful for site-specific or location-specific rule adjustments without managing separate rule files. Rules can be applied to specific locations or directories.
```apache
# Add individual rules directly in Apache configuration
modsecurity On
modsecurity_rules_file /etc/modsecurity/base.conf
# Inline rules for specific locations
modsecurity On
modsecurity_rules "SecRule REQUEST_URI \"@contains /admin\" \"id:2000,phase:1,pass,setvar:tx.admin_access=1\""
modsecurity_rules "SecRule &TX:admin_access \"@eq 0\" \"id:2001,phase:2,deny,status:403,msg:'Admin access required'\""
# Per-directory custom rules
modsecurity On
modsecurity_rules "SecRule FILES \"@rx \\.(php|phtml|exe)$\" \"id:3000,phase:2,deny,status:403,msg:'Forbidden file type'\""
```
--------------------------------
### ModSecurity Response Body Output Filter (C)
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
This C code implements an Apache output filter that inspects response headers and body. It processes ModSecurity rules and handles interventions, passing the brigade to the next filter or returning an error. Dependencies include Apache Portable Runtime (APR) and ModSecurity's internal types.
```c
// Filter that inspects response headers and body
ap_status_t output_filter(ap_filter_t *f, apr_bucket_brigade *bb_in) {
request_rec *r = f->r;
msc_t *msr = (msc_t *)f->ctx;
// Validate context
if (msr == NULL) {
ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, f->r->server,
"ModSecurity: Internal Error: msr is null in output filter.");
ap_remove_output_filter(f);
return send_error_bucket(msr, f, HTTP_INTERNAL_SERVER_ERROR);
}
// Process response headers
const apr_array_header_t *arr;
const apr_table_entry_t *te;
int i, it;
// Add error headers
arr = apr_table_elts(r->err_headers_out);
te = (apr_table_entry_t *)arr->elts;
for (i = 0; i < arr->nelts; i++) {
msc_add_response_header(msr->t, te[i].key, te[i].val);
}
// Add normal response headers
arr = apr_table_elts(r->headers_out);
te = (apr_table_entry_t *)arr->elts;
for (i = 0; i < arr->nelts; i++) {
msc_add_response_header(msr->t, te[i].key, te[i].val);
}
// Process response headers through rules
msc_process_response_headers(msr->t, r->status, "HTTP 1.1");
it = process_intervention(msr->t, r);
if (it != N_INTERVENTION_STATUS) {
ap_remove_output_filter(f);
return send_error_bucket(msr, f, it);
}
// Process response body
apr_bucket *pbktIn;
for (pbktIn = APR_BRIGADE_FIRST(bb_in);
pbktIn != APR_BRIGADE_SENTINEL(bb_in);
pbktIn = APR_BUCKET_NEXT(pbktIn)) {
const char *data;
apr_size_t len;
apr_bucket_read(pbktIn, &data, &len, APR_BLOCK_READ);
msc_append_response_body(msr->t, data, len);
}
msc_process_response_body(msr->t);
it = process_intervention(msr->t, r);
if (it != N_INTERVENTION_STATUS) {
ap_remove_output_filter(f);
return send_error_bucket(msr, f, it);
}
// Pass brigade to next filter
return ap_pass_brigade(f->next, bb_in);
}
```
--------------------------------
### Request Body Input Filter for ModSecurity (C)
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
This C function implements an Apache input filter to inspect and process request body data, such as POST or PUT payloads. It reads data in chunks, appends it to the ModSecurity transaction's request body, and processes it through ModSecurity rules. It also handles potential interventions and ensures data is passed along correctly.
```c
// Filter that inspects request body data (POST, PUT payloads)
apr_status_t input_filter(ap_filter_t *f, apr_bucket_brigade *pbbOut,
ap_input_mode_t mode, apr_read_type_e block, apr_off_t nbytes) {
request_rec *r = f->r;
conn_rec *c = r->connection;
msc_t *msr = (msc_t *)f->ctx;
// Validate context
if (msr == NULL) {
ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, f->r->server,
"ModSecurity: Internal Error: msr is null in input filter.");
ap_remove_output_filter(f);
return send_error_bucket(msr, f, HTTP_INTERNAL_SERVER_ERROR);
}
// Create temporary brigade
apr_bucket_brigade *pbbTmp = apr_brigade_create(r->pool, c->bucket_alloc);
if (APR_BRIGADE_EMPTY(pbbTmp)) {
int ret = ap_get_brigade(f->next, pbbTmp, mode, block, nbytes);
if (mode == AP_MODE_EATCRLF || ret != APR_SUCCESS)
return ret;
}
// Process each bucket in brigade
while (!APR_BRIGADE_EMPTY(pbbTmp)) {
apr_bucket *pbktIn = APR_BRIGADE_FIRST(pbbTmp);
const char *data;
apr_size_t len;
// Check for end-of-stream
if (APR_BUCKET_IS_EOS(pbktIn)) {
APR_BUCKET_REMOVE(pbktIn);
APR_BRIGADE_INSERT_TAIL(pbbOut, pbktIn);
break;
}
// Read bucket data
int ret = apr_bucket_read(pbktIn, &data, &len, block);
if (ret != APR_SUCCESS) {
return ret;
}
// Append to ModSecurity request body
msc_append_request_body(msr->t, data, len);
// Check for intervention
int it = process_intervention(msr->t, r);
if (it != N_INTERVENTION_STATUS) {
ap_remove_output_filter(f);
return send_error_bucket(msr, f, it);
}
// Process request body
msc_process_request_body(msr->t);
// Create output bucket
apr_bucket *pbktOut = apr_bucket_heap_create(data, len, 0,
c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(pbbOut, pbktOut);
apr_bucket_delete(pbktIn);
}
return APR_SUCCESS;
}
```
--------------------------------
### Process Request Headers with ModSecurity (C)
Source: https://context7.com/owasp-modsecurity/modsecurity-apache/llms.txt
This C function processes incoming HTTP request headers through ModSecurity's rules engine. It first handles the URI, then iterates through all request headers, adding them to the ModSecurity transaction. Finally, it triggers ModSecurity to process all collected headers and checks for any intervention actions.
```c
// Processes URI and request headers through ModSecurity rules
static int process_request_headers(request_rec *r, msc_t *msr) {
int it;
// Process URI - remove HTTP/ prefix if present
int offset = (r->protocol && strlen(r->protocol) > 5 &&
r->protocol[0] == 'H') ? 5 : 0;
msc_process_uri(msr->t, r->unparsed_uri, r->method,
r->protocol + offset);
// Check for intervention after URI processing
it = process_intervention(msr->t, r);
if (it != N_INTERVENTION_STATUS) {
return it; // Request blocked
}
// Add all request headers
const apr_array_header_t *arr = apr_table_elts(r->headers_in);
const apr_table_entry_t *te = (apr_table_entry_t *)arr->elts;
for (int i = 0; i < arr->nelts; i++) {
const char *key = te[i].key;
const char *val = te[i].val;
msc_add_request_header(msr->t, key, val);
}
// Process all headers together
msc_process_request_headers(msr->t);
// Check for intervention
it = process_intervention(msr->t, r);
if (it != N_INTERVENTION_STATUS) {
return it; // Returns HTTP status code like 403, 301, etc.
}
return N_INTERVENTION_STATUS; // Continue processing
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.