Skip to content

About

High-performance Simple-rule Easy-extend web application firewall(WAF) module for Nginx.

Topics

Resources

Stars

10 stars

Watchers

3 watching

Forks

Latest commit

 

History

201 Commits

Folders and files

Repository files navigation

Name

travis-ci Coverage Status

The ngx_http_waf_module is an open-source high-performance simple-rule easy-extend web application firewall(WAF) module for Nginx.

Table of Contents

Status

The ngx_http_waf_module is currently in active development.

Install

./configure --prefix=/usr/local/nginx --add-dynamic-module=github.com/vislee/ngx_http_waf_module --with-compat

Back to TOC

Example Configuration

load_module ./modules/ngx_http_waf_module.so;
events {
    ......
}

http {
   ......
    security_rule id:1001 "str:rx@^[a-z]{1,3}" "s:$BYPASS:1,$SQLI:2" z:V_HEADERS:bar|ARGS;
    security_rule id:1002 "str:!sw@/test.php" s:$XSS:3,$BYPASS:3 z:#URL;
    security_rule id:1003 "libinj:sql" "s:$SQLI:9" z:V_ARGS:foo;
    security_rule id:1004 "libinj:decode_url|xss" "s:$XSS:9" z:V_ARGS:foo "note:test rule by vislee";
    security_rule id:1005 "str:eq@testbody" "s:$BYPASS:2" "z:BODY";
    security_rule id:1006 "str:decode_base64|decode_url|ct@test file data" "s:$BYPASS:2" "z:V_BODY:input";
    security_rule id:1007 "str:ct@eval" "s:$HANG:2" "z:#FILE";
    security_rule id:1008 "str:ct@testphp" "s:$HANG:2" "z:X_FILE:^[a-z]{1,5}\.php$";
    security_rule id:1009 "str:ct@testphp" "s:$BYPASS:2" "z:#RAW_BODY";

    map $sec_result $ups {
        "block" block;
        default runtime;
    }

    server {
        location / {
            client_body_buffer_size 1m;

            security_waf on;
            security_log ./logs/waf.log;

            security_loc_rule wl:1003 z:V_ARGS:test;
            security_loc_rule id:90001 str:eq@vislee s:$BYPASS:4 z:V_HEADERS:name;

            security_check "$HANG>4" LOG;
            security_check "$BYPASS>8" $sec_result;
            security_check "$SQLI>8" DROP;
            security_check "$XSS>8" BLOCK;

            proxy_pass http://$ups;
        }
    }

Back to TOC

Default ruleset (CRS-aligned)

The module ships a ready-made ruleset at rules/waf-default.conf, aligned with the OWASP Core Rule Set v3.3 PL1 anomaly-scoring model: every rule scores a tagged counter (920xxx CRLF, 930xxx LFI, 932xxx shell/RCE, 934xxx SSRF, 942xxx SQLi, 941xxx XSS, 919xxx SSTI, 918xxx NoSQLi, 917xxx LDAPi, 916xxx deserialization, 913xxx recon, 923xxx open redirect, 911xxx code injection), and security_check thresholds turn the score into an action.

http {
    include rules/waf-default.conf;

    server {
        location / {
            security_waf on;
            security_log ./logs/waf.log;

            # blocking set (see rules/waf-default.conf for the full list)
            security_check "$SQLI>4" BLOCK;
            security_check "$XSS>4" BLOCK;
            security_check "$CRLF>4" BLOCK;
            security_check "$RECON>4" BLOCK;
            security_check "$RFI>4" BLOCK;
            security_check "$PHP>4" BLOCK;
            # $REDIRECT is alert-only: protocol-relative targets such as
            # "//cdn.example.com/a.js" are legitimate webhook parameters
            security_check "$REDIRECT>4" LOG;
        }
    }
}

The ruleset contains http-level rules only. Zone selection is false-positive driven (verified with the bundled libinjection): no SSRF in the HEADERS zone (Host values classify as SSRF), no REDIRECT/RECON and no CRLF in the BODY zone (bodies legitimately carry URLs, paths, and \r\nContent-Type: in uploaded mail/markup). Only the blocking set listed above turns scores into actions; every other tag is alert-only. Per-target exclusions use value-constrained whitelists, e.g.:

security_loc_rule "wl:941100" "z:V_ARGS:html~^allow";

Exact CRS rules are layered on top of the semantic detectors where libinj:all under-detects: scanner User-Agents (913xxx, the CRS scanners-user-agents.data list inlined as a V_HEADERS:User-Agent regex; entries whose bare name occurs in legitimate UAs — nmap, mozilla — are matched by their version-shaped form instead of the CRS @pm substring, so python-nmap/0.7.1 and Nexus 7 browser UAs pass), remote file inclusion (931xxx) and PHP injection (933xxx, IDs mirroring the ported CRS rules: 933100 open tag, 933120 config/PHP function names, 933160 dangerous function calls) — each verified by t/waf_crs.t, which reads rules/waf-default.conf directly so the shipped ruleset itself is under test.

Back to TOC

Directives

security_rule

syntax: security_rule rule

default: no

context: http

Set general rules. All the location contained in http is visible.

The rule format:

security_rule id:number match-strategy "s:$TAG:score,$TAG2:score" "z:zones" "note:message";

  • id: The ID of the rule.
  • match-strategy: The strategy of rule.
    • str:[decode_func1|decode_func2|][!]le@string
    • str:[decode_func1|decode_func2|][!]ge@string
    • str:[decode_func1|decode_func2|][!]ct@string
    • str:[decode_func1|decode_func2|][!]eq@string
    • str:[decode_func1|decode_func2|][!]sw@string
    • str:[decode_func1|decode_func2|][!]ew@string
    • str:[decode_func1|decode_func2|][!]rx@regex
    • libinj:[decode_func1|decode_func2|]sql
    • libinj:[decode_func1|decode_func2|]xss
    • libinj:[decode_func1|decode_func2|]all
    • hash:[!]md5@hashcode
    • hash:[!]crc32@hashcode
    • hash:[!]crc32_long@hashcode
    • libmagic:[!]mime_type@mime_type

decode_func: decode_url or decode_base64

!: not. eg: "!eq@test" - Is not equal to 'test'.

  • zones: The match zones of rule.
    • #URL
    • V_URL:string
    • X_URL:regex
    • [@ | #]ARGS
    • V_ARGS:string
    • X_ARGS:regex
    • [@ | #]HEADERS
    • V_HEADERS:string
    • X_HEADERS:regex
    • #RAW_BODY
    • [@ | #]BODY
    • V_BODY:string
    • X_BODY:regex
    • #FILE
    • X_FILE:regex

For example:

"str:eq@/index.php" "z:#URL" curl 'http://x/index.php' will be blocked

"str:eq@bar" "z:V_ARGS:foo" curl 'http://x/?foo=bar' will be blocked

"str:eq@bar" "z:V_HEADERS:foo" curl -H'foo: bar' 'http://x/' will be blocked

A complete rule configuration.

security_rule id:100 "str:decode_base64|decode_url|!eq@foo bar" "s:$ATT:2,$SQLI:1" "z:V_ARGS:foo|#HEADERS" "note:test rule";

Back to TOC

security_loc_rule

syntax: security_loc_rule rule

default: no

context: location

Set the location rules.

Also, you can set the whitelist disable of the general rules of the specified IDs.

The whitelist rule format:

security_loc_rule "wl:id1,id2" "z:zones" "note:test whitelist";

Value-constrained whitelist (target scoping)

A whitelist zone can carry a value regex: z:V_ARGS:name~regex. When the value matches the regex, the whitelisted rule is skipped for that target only (same semantics as ModSecurity SecRuleUpdateTargetById); the same rule still scans other args and the arg name itself. Available for whitelist rules only (security_loc_rule with wl:), and only for named-value zones (V_ARGS/V_HEADERS/V_BODY).

Example: skip rule 941950 for args q whose value starts with safe:

security_loc_rule "wl:941950" "z:V_ARGS:q~^safe";

Note: rules with libinj:all score per class — a rule's s: tag only gets credited when the payload actually matched that class (e.g. an XSS payload does not add to $SQLI even though every libinj:all rule evaluates every payload).

Back to TOC

security_waf

syntax: security_waf <on|off>

default: off

context: location

Enables or disables this module.

Back to TOC

security_check

syntax: security_check $tag>threshold <LOG|BLOCK|DROP|ALLOW|$variable>

default: no

context: location

Setting rules accumulating scoring thresholds and actions.

The action include:

  • LOG: only logged.
  • BLOCK: refuse the request, return 403.
  • DROP: close the connection, Is equivalent to return 444.
  • ALLOW: skip the rest of the rules.
  • $variable: return string "block" else return nil.

Back to TOC

security_log

syntax: security_log <file|off> [unflat]

default: off

context: location

A log that requests a hit rule.

Logging to syslog can be configured by specifying the “syslog:” prefix.

Back to TOC

security_timeout

syntax: security_timeout time

default: 60s

context: location

Defines a timeout for waf-rule filter. If filter is not finish, the filter return pass.

Back to TOC

New match strategy

If you want to expand match-strategy. Only need to implement two function: The function of parse directive and The matching-strategy callback function.

And then the parse directive function registered into the array of ngx_http_waf_rule_parser_item.

For example, the libinj:xss and libinj:sql expand.

// The parse directive function
static ngx_int_t
ngx_http_waf_parse_rule_libinj(ngx_conf_t *cf, ngx_str_t *str,
    ngx_http_waf_rule_parser_t *parser, ngx_http_waf_rule_opt_t *opt)
{
    u_char             *p, *e;
    ngx_int_t           offset;

    static ngx_str_t    sql = ngx_string("sql");
    static ngx_str_t    xss = ngx_string("xss");

    if (str->len - parser->prefix.len < 3) {
        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
            "invalid libinj in arguments \"%V\"", str);
        return NGX_ERROR;
    }

    p = str->data + parser->prefix.len;
    e = str->data + str->len;

    offset = ngx_http_waf_parse_rule_decode(cf, opt->p_rule->decode_handlers,
        p, e - 4);
    if (offset == NGX_ERROR) {
        return NGX_ERROR;
    }

    p += offset;

    if ((size_t)(e - p) == sql.len
        && ngx_strncmp(p, sql.data, sql.len) == 0)
    {
        opt->p_rule->str = sql;
        opt->p_rule->handler = ngx_http_waf_rule_str_sqli_handler;

    } else if ((size_t)(e - p) == xss.len
        && ngx_strncmp(p, xss.data, xss.len) == 0)
    {
        opt->p_rule->str = xss;
        opt->p_rule->handler = ngx_http_waf_rule_str_xss_handler;

    } else {
        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
            "invalid libinj args in arguments \"%V\"", str);
        return NGX_ERROR;
    }

    return NGX_OK;
}

// matching-strategy callback function
static ngx_int_t
ngx_http_waf_rule_str_sqli_handler(ngx_http_waf_public_rule_t *pr,
    ngx_str_t *s)
{
    ngx_int_t                       issqli;
    struct libinjection_sqli_state  state;

    if (s == NULL || s->data == NULL || s->len == 0) {
        return NGX_ERROR;
    }

    libinjection_sqli_init(&state, (const char *)s->data, s->len, FLAG_NONE);
    issqli = libinjection_is_sqli(&state);
    if (!issqli) {
        return NGX_ERROR;
    }

    return NGX_OK;
}

// registered parse directive function
static ngx_http_waf_rule_parser_t  ngx_http_waf_rule_parser_item[] = {
    ......
    {ngx_string("libinj:"),    ngx_http_waf_parse_rule_libinj},
    ......
  }

Back to TOC

Author

wenqiang li(vislee)

Back to TOC

Copyright and License

This module is licensed under the GPL license.

Copyright (C) 2018-2019, by vislee.

All rights reserved.

Back to TOC

See Also

  • nginx: ngx_http_waf_module based on nginx.
  • naxsi: ngx_http_waf_module has learned a lot of from it.
  • libinjection: ngx_http_waf_module refer to this library.
  • Hyperscan: replace the PCRE.
  • libmagic: ngx_http_waf_module refer to this library.

Back to TOC

About

High-performance Simple-rule Easy-extend web application firewall(WAF) module for Nginx.

Topics

Resources

Stars

10 stars

Watchers

3 watching

Forks

Releases

Packages

Contributors

Languages