A Safer Rust Boundary for ModSecurity: libmodsecurity3-rs
A Safer Rust Boundary for ModSecurity: libmodsecurity3-rs
ModSecurity is a widely used web application firewall engine, but its v3 interface is a C API over a C++ library. A Rust connector has to deal with more than translating function signatures: it must keep engine and rule-set objects alive for every transaction, follow the engine's phase sequence, and correctly handle memory returned across the FFI boundary.
libmodsecurity3-rs is a Rust wrapper designed around those constraints. Its goal is not to replace ModSecurity or the OWASP Core Rule Set (CRS), but to make the boundary between a Rust server and libmodsecurity v3 safer and easier to reason about. The crate's README documents both the Rust API and several upstream behaviors that shaped it.
Two layers, with unsafe code kept at the edge
The crate separates its API into two layers:
modsecurity::fficontains hand-written declarations for the C API. It is the only module that declares external functions, and most applications should not need to use it directly.- The rest of the crate provides the safe wrapper:
ModSecurityfor the engine handle,Rulesfor parsed rules, andTransactionfor inspecting an individual request and response.
The distinction matters because a C API can document that one object must outlive another, but it cannot make the compiler enforce that relationship for its caller. The wrapper ties a transaction's lifetime to borrowed engine and rule-set handles, so trying to drop either while a transaction is alive becomes a Rust compile error rather than a use-after-free at runtime.
Requirements and linking
Building the crate requires libmodsecurity 3.x and its development headers. The README gives package-install examples for Debian and Ubuntu (libmodsecurity3 and libmodsecurity-dev), Fedora and RHEL (mod_security and libmodsecurity-devel), and macOS (brew install libmodsecurity).
The build script links against modsecurity by default. MODSECURITY_LIB_DIR adds a library search path, MODSECURITY_LIB_NAME changes the link name, and MODSECURITY_STATIC=1 requests static linking (including the C++ runtime). These settings let a build adapt to where the system library is installed without changing the Rust API.
Processing a transaction in order
The public API makes the request-processing phases explicit. A connector creates one engine and a rule set, then creates a transaction per request and feeds each phase to the engine in sequence:
use modsecurity::{ModSecurity, Rules, Transaction};
let mut engine = ModSecurity::new()?.with_connector_info("my-proxy/1.0")?;
engine.set_log_callback(|message: &[u8]| {
eprintln!("[modsec] {}", String::from_utf8_lossy(message));
});
let mut rules = Rules::new()?;
rules.add_file("/etc/modsecurity.d/include.conf")?;
let mut transaction = Transaction::with_id(&engine, &rules, "request-0001")?;
transaction.process_connection("203.0.113.9", 51234, "198.51.100.1", 443)?;
transaction.process_uri("/search?q=example", "GET", "1.1")?;
transaction.add_request_header(b"Host", b"example.com")?;
if let Some(action) = transaction.process_request_headers()? {
eprintln!("blocked: HTTP {} — {:?}", action.status, action.log_message());
}
transaction.process_logging()?;
The example shows the start of the flow; a real connector should also pass request-body and response phases when those apply. The documented order is connection, URI, request headers, request body, response headers, response body, then logging. A phase method can return an intervention when a rule requests a disruptive action. Calling process_logging at the end of every transaction is important because that is when the audit log is flushed.
What the wrapper guarantees—and what it does not
The wrapper uses Rust ownership and borrowing to manage native objects: rule sets and transactions are released through Drop, and returned C strings in interventions and parser errors are copied into Rust Strings and freed. Mutations of C++ state require &mut self, and callbacks are invoked inside catch_unwind so a Rust panic does not unwind through C++ frames.
Header names and values are passed with explicit lengths, allowing arbitrary bytes (including NUL) there. Inputs that must become C strings instead report an interior NUL as Error::InteriorNul. The crate also confines unsafe to the modules that touch the C API, denies unsafe_op_in_unsafe_fn, and documents the invariant for each unsafe block. Its only public unsafe function is ModSecurity::shutdown.
These are guarantees about the Rust wrapper's interface and ownership discipline, not a claim that every possible ModSecurity integration is automatically configured securely. The host still needs to load appropriate rules, pass all relevant request and response data, interpret interventions, and choose its own behavior for logging, blocking, and error handling.
Accommodating upstream global state
The README describes two libmodsecurity behaviors that cannot safely be exposed as ordinary per-object operations.
First, destroying a ModSecurity C++ engine calls libxml2's process-global xmlCleanupParser(). That cleanup can invalidate state used by another engine, thread, or unrelated XML-using library. The wrapper therefore lazily creates one engine per process and does not destroy it when a Rust handle is dropped. A ModSecurity value is a cheap handle to the shared engine; dropping it does not trigger global cleanup. ModSecurity::shutdown is an unsafe escape hatch for programs that deliberately need to run the engine destructor at shutdown.
The singleton has consequences: set_connector_info updates shared state, so the last call wins, while log callbacks are associated with the handle used to create each transaction. This is worth understanding when a process has multiple connectors.
Second, the SecLang rule parser uses global state. Concurrently parsing multiple rule sets can interleave diagnostics and corrupt the heap. Rules serializes construction, parsing, and destruction behind a process-wide lock. Request evaluation is not serialized by that lock, so concurrent inspection against a shared rule set remains available.
There is also one API the wrapper intentionally does not make safe: msc_get_response_body. The README notes that upstream returns a pointer into a temporary std::string, which is destroyed before the call returns. The raw declaration remains in modsecurity::ffi, but the safe wrapper does not expose it; Transaction::response_body_length is available instead. Since libmodsecurity v3 does not rewrite a response body, the connector already has the bytes it supplied.
Logging and blocking are separate paths
Not every rule match arrives through the same callback. Disruptive actions such as deny, drop, or redirect are returned as an Intervention from a phase method, with the message on the intervention. Non-disruptive actions such as pass with logging go to the callback registered with set_log_callback. A connector that listens only to the callback will miss disruptive matches; one that only handles interventions will miss ordinary logged matches. Handle both if you need a complete record.
Testing with real rules and memory tools
The project tests more than whether an FFI call returns successfully. Its integration tests cover phase ordering, request and response body inspection, deny and redirect interventions, per-handle callbacks, binary header values, callback panics, error reporting, and concurrent parsing and evaluation.
The optional CRS integration tests load the system OWASP Core Rule Set and check both sides of the decision: representative SQL injection, XSS, file inclusion, command injection, and response-leak cases should be blocked, while ordinary pages, assets, and API requests should remain allowed. Negative controls check that detection-only mode logs without intervening and that changing the anomaly threshold changes the verdict. The suite also tests concurrent evaluation and parsing. CRS paths can be set with MODSEC_CRS_SETUP and MODSEC_CRS_RULES; if the rules are absent, the tests skip unless MODSEC_REQUIRE_CRS=1 makes that absence a failure.
There are a couple of configuration details to keep in mind when wiring in the CRS. The Debian owasp-crs.load file uses Apache's IncludeOptional, which libmodsecurity's SecLang parser rejects; configure the setup file and rule files directly instead. Rules::add_file opens one exact path and does not expand wildcards; use a SecLang Include directive for a glob. Also, CRS anomaly blocking happens in phase 2 after request-body processing, so a connector that stops after request headers may never receive the expected intervention. Host directives such as SecRuleEngine On and SecRequestBodyAccess On must be configured too, or the rules may only detect and may not inspect the body.
Memory validation has two layers. The Valgrind script can run every test binary under Memcheck, while tests using the optional valgrind feature measure memory deltas around selected workloads inside the test process. Those in-process checks cover disrupted transactions, request bodies, rule-set build/merge/error cycles, and logging callbacks. The README says both layers were verified to catch a deliberately introduced missing free and double free, rather than only being observed to pass. Valgrind-related tooling is optional; the script sets MODSEC_REQUIRE_VALGRIND=1 so a run cannot silently count an unavailable checker as a successful memory check.
Where this fits
For a Rust server such as Project Charlotte, a wrapper like this can provide a safer integration boundary for ModSecurity inspection. The crate does not replace the server's responsibility to configure the WAF correctly, but it helps make ownership, phase progression, and upstream quirks explicit in the code that connects the two.
The project is licensed under Apache License 2.0, matching upstream ModSecurity. Read the libmodsecurity3-rs README and source for the API, examples, build details, and current testing instructions.
A note from salticidae.io Security Team, who writes about security, software, and operating internet services.