cPanel ModSecurity JSON Request Body Parser: Securing Single-Page Apps & REST APIs

Configure ModSecurity's native libyajl JSON request body parser on cPanel Apache. Inspect nested JSON payloads, prevent parser denial of service, and secure REST APIs in Pakistan.

cPanel ModSecurity JSON Request Body Parser: Securing Single-Page Apps & REST APIs

Modern web applications hosted on cPanel and WHM Linux servers in Pakistan—such as headless WordPress, React/Vue Single-Page Applications (SPAs), mobile fintech backends, and Next.js microservices—no longer submit traditional URL-encoded form data (application/x-www-form-urlencoded or multipart/form-data). Instead, over 80% of application traffic transmits structured JSON payloads (Content-Type: application/json).

By default, unless Apache’s ModSecurity module is explicitly compiled and configured with libyajl (Yet Another JSON Library), ModSecurity treats JSON payloads as opaque raw text strings. As a result, critical injection attacks—such as NoSQL injection, nested SQL injection inside JSON dictionaries, and deserialization payloads—slip directly through the Web Application Firewall uninspected.

By enabling ModSecurity’s native JSON parser (ctl:requestBodyProcessor=JSON) and tuning parser limits (SecRequestBodyJsonDepthLimit), hosting providers and enterprise developers in Pakistan can protect modern APIs on high-frequency Dedicated Servers and Dedicated Servers in Pakistan from zero-day API exploits.


How ModSecurity Parses JSON Payloads

When ModSecurity intercepts an HTTP request with application/json, the request body processing engine follows this pipeline:

  1. Content-Type Inspection (Phase 1): ModSecurity identifies application/json in the Content-Type header.
  2. Parser Activation (Phase 2): ModSecurity switches its internal request body processor to the JSON parser powered by libyajl.
  3. JSON Tree Flattening: The parser traverses nested JSON arrays and key-value objects, exposing each key-value pair as individual variables inside the ARGS and ARGS_POST collections using dot or bracket notation:
    • Payload: {"auth": {"user": "admin", "token": "' OR 1=1--" }}
    • Flattens to: ARGS:auth.user and ARGS:auth.token
  4. WAF Rule Evaluation: Standard OWASP Core Rule Set (CRS) inspection rules evaluate the flattened variables against SQLi, XSS, and command injection signatures.
+---------------------------------------------------------------+
|             Client Mobile App / Frontend SPA                  |
|       POST /api/v1/checkout  Content-Type: application/json   |
|       Payload: {"order": {"id": 104, "coupon": "'; DROP..."}} |
+-------------------------------+-------------------------------+
                                |
                                v
+---------------------------------------------------------------+
|         cPanel Apache ModSecurity Engine (libyajl)            |
|                                                               |
|   1. ctl:requestBodyProcessor=JSON activated                  |
|   2. Flattens payload into: ARGS:order.coupon                 |
|   3. OWASP CRS Rule 942100 evaluates ARGS:order.coupon        |
|   4. SQLi Pattern Detected! Anomaly Score: 5 (CRITICAL)       |
+-------------------------------+-------------------------------+
                                |
                                v
+---------------------------------------------------------------+
|             HTTP 403 Forbidden - Threat Neutralized           |
+---------------------------------------------------------------+

For webmasters optimizing complementary cPanel hosting infrastructure, review our guides on cPanel OWASP ModSecurity CRS Paranoia Levels and Anomaly Scoring, cPanel Pure-FTPd TLS and Passive Port Range Hardening, and cPanel Redis UNIX Domain Socket Object Cache Tuning.


Step 1: Verifying libyajl Compilation in cPanel Apache

To parse JSON, ModSecurity requires libyajl. Connect to your server via SSH as root and check if ModSecurity is linked against libyajl:

# Verify libyajl shared library link
ldd /etc/apache2/modules/mod_security2.so | grep -i yajl

On AlmaLinux, Rocky Linux, or CloudLinux servers managed by cPanel’s EasyApache 4:

libyajl.so.2 => /lib64/libyajl.so.2 (0x00007f901a...)

If libyajl is missing, install the required packages through EasyApache 4 or dnf:

dnf install -y yajl yajl-devel
/scripts/restartsrv_httpd

Step 2: Configuring JSON Body Processor Rules in cPanel

In WHM, navigate to: Security Center >> ModSecurity Configuration >> Global Directives

Or edit the custom user configuration /etc/apache2/conf.d/modsec/modsec2.user.conf:

# -------------------------------------------------------------
# ModSecurity JSON Request Body Parser Configuration
# -------------------------------------------------------------

<IfModule mod_security2.c>
    # Enable request body inspection
    SecRequestBodyAccess On

    # Prevent JSON Parser Denial of Service (Depth and Memory Limits)
    SecRequestBodyJsonDepthLimit 64
    SecRequestBodyLimit 13107200 # 12.5 MB maximum POST body
    SecRequestBodyNoFilesLimit 131072

    # Rule to automatically route application/json to the JSON body parser
    SecRule REQUEST_HEADERS:Content-Type "^application/json" \
        "id:900010,\
        phase:1,\
        pass,\
        t:none,\
        nolog,\
        ctl:requestBodyProcessor=JSON"

    # Enforce strict JSON syntax verification (Blocks malformed payloads)
    SecRule REQBODY_ERROR "@eq 1" \
        "id:900011,\
        phase:2,\
        deny,\
        status:400,\
        log,\
        msg:'Malformed JSON Request Body: Failed to Parse JSON Payload',\
        tag:'application-security',\
        severity:'WARNING'"
</IfModule>

Why SecRequestBodyJsonDepthLimit is Critical:

Without SecRequestBodyJsonDepthLimit 64, malicious attackers can send deeply nested JSON objects ({"a": {"b": {"c": ... }}}) thousands of levels deep. Unbounded recursive parsing exhausts CPU stacks and locks up Apache worker threads in an instant denial-of-service attack!


Step 3: Verifying JSON Inspection via cURL

Test that ModSecurity actively parses and sanitizes nested JSON keys using curl:

# Send test JSON payload containing SQL injection inside a nested object
curl -i -s -X POST https://yourdomain.pk/api/test \
  -H "Content-Type: application/json" \
  -d '{"data": {"search": "test'\'' OR 1=1--" }}'

Examine the response:

HTTP/1.1 403 Forbidden
Content-Type: text/html; charset=iso-8859-1

Check the ModSecurity audit log /var/log/apache2/modsec_audit.log:

tail -n 25 /var/log/apache2/modsec_audit.log

You will see:

[id "942100"] [msg "SQL Injection Attack Detected via libinjection"] [data "Matched Data: 1=1-- found within ARGS:data.search"]

Notice that ModSecurity flattened data.search and intercepted the SQL injection attempt before it could touch your database!


Step 4: Graceful Whitelisting for Webhook Endpoints

Certain legitimate external webhooks (such as Stripe, EasyPaisa, JazzCash, or GitHub payment notifications) send JSON payloads containing raw cryptographic signatures or complex code strings that may trigger generic rule matches.

To whitelist specific webhooks safely without disabling JSON parsing globally:

<LocationMatch "/api/v1/payments/webhook">
    <IfModule mod_security2.c>
        # Retain JSON parsing, but exempt specific false-positive rule IDs
        SecRuleRemoveById 942100 941100
    </IfModule>
</LocationMatch>

ENTERPRISE API & WEB DEFENSE

Protect Cloud APIs with Nextgen Bare-Metal Infrastructure

Defend your web services, REST APIs, and mobile applications with hardware-accelerated WAF filtering, dedicated NVMe arrays, and carrier-neutral low-latency connectivity across Pakistan.