JavaScript Magic Tricks: Web Application Firewall
Tags: webdev, javascript, node, firewall
Published: 2023-11-27 03:28:50

This article demonstrates how to develop a simple Web Application Firewall (WAF) to protect against network attacks.

Environment and principle Based on the Node.JS environment, using the Express framework, the incoming information is filtered in the form of middleware. If dangerous behavior is detected, access will be blocked.

## Source code

```

var express = require('express');
var app = express();

//Web Application Firewall中间件
app.use(function(req, res, next) {
    var path = req.url;
    console.log(path);
    if(waf_detect(path) == false){
        next();
    }else{
        res.send("检测到攻击，已拦截")
    }
});

//当访问根目录时触发
app.get('/', function (req, res) {
    res.send('Hello World');
})

//使用正则表达式，检测字符串是否含有攻击特征，检测到攻击特征返回true，没检测到返回false
function waf_detect(str_to_detect){

    var regexp_rule =[
        /select.+(from|limit)/i,
        /(?:(union(.*?)select))/i,
        /sleep\((\s*)(\d*)(\s*)\)/i,
        /group\s+by.+\(/i,
        /(?:from\W+information_schema\W)/i,
        /(?:(?:current_)user|database|schema|connection_id)\s*\(/i,
        /\s*or\s+.*=.*/i,
        /order\s+by\s+.*--$/i,
        /benchmark\((.*)\,(.*)\)/i,
        /base64_decode\(/i,
        /(?:(?:current_)user|database|version|schema|connection_id)\s*\(/i,
        /(?:etc\/\W*passwd)/i,
        /into(\s+)+(?:dump|out)file\s*/i,
        /xwork.MethodAccessor/i,
        /(?:define|eval|file_get_contents|include|require|require_once|shell_exec|phpinfo|system|passthru|preg_\w+|execute|echo|print|print_r|var_dump|(fp)open|alert|showmodaldialog)\(/i,
        /\<(iframe|script|body|img|layer|div|meta|style|base|object|input)/i,
        /(onmouseover|onmousemove|onerror|onload)\=/i,
        /javascript:/i,
        /\.\.\/\.\.\//i,
        /\|\|.*(?:ls|pwd|whoami|ll|ifconfog|ipconfig|&&|chmod|cd|mkdir|rmdir|cp|mv)/i,
        /(?:ls|pwd|whoami|ll|ifconfog|ipconfig|&&|chmod|cd|mkdir|rmdir|cp|mv).*\|\|/i,
        /(gopher|doc|php|glob|file|phar|zlib|ftp|ldap|dict|ogg|data)\:\//i
    ];

    for(i=0; i< regexp_rule.length; i++){
        if(regexp_rule[i].test(str_to_detect) == true){
			console.log("拦截到攻击, 规则:", "("+i+")", regexp_rule[i]);
			return true;
        }
    }
    return false;
}

var server = app.listen(8000, function () {
   var host = server.address().address
   var port = server.address().port
   console.log("服务已启动，监听端口",host, port);
})
```

## Source code analysis

1.The built-in middleware part implements the protection function of the WAF:

```
app.use(function(req, res, next) {
    var path = req.url;
    console.log(path);
    if(waf_detect(path) == false){
        next();
    }
});
```


In this middleware, incoming data is intercepted and the request URL is detected. This example demonstrates the basic protection function, which only detects the URL. To implement the full functionality of a Web Application Firewall (WAF), additional detection can be added for request headers, cookies, POST data, and return data.

Upstream data detection can identify whether the data submitted by the client contains threats, as well as implement other add-on features, such as IP restrictions, country restrictions, browser type restrictions, fingerprinting, cookie decryption, behavioral risk control, data forwarding, and diversion.

Downstream data detection is used to identify sensitive information or information leaks in the returned data. Additionally, extra features can be added to the front-end by modifying the data or adding JavaScript code, such as HTML encryption, cookie encryption, JavaScript obfuscation encryption, font encryption, and anti-spidering.

Combining both can achieve more powerful features, such as page tamper-proofing, data cache acceleration, bi-directional data communication encryption, and robot visit detection. Specifically, the front-end Form or AJAX data can be encrypted and transmitted according to a certain algorithm, and when it reaches this middleware, the data can be decrypted and passed on to the back-end server. This is also the principle by which the Web application firewall can achieve data protection without modifying the original website functionality. Furthermore, by recognizing the IP address, Agent, Cookie, language type, and other characteristics of the visitor, and converting them into user fingerprint information, along with frequency of visit, visited pages, and other data, risk control rules can be implemented. If the risk control system identifies abnormal visits, it can modify the downstream data to throw out identification codes for machine detection or access restrictions.

In summary, this middleware node can achieve powerful Web firewall functions.

2.Protection rules The attack detection uses regular expressions, which is a commonly used method for firewalls to detect attacks.

```
/select.+(from|limit)/i,
/(?:(union(.*?)select))/i,
/sleep\((\s*)(\d*)(\s*)\)/i,
/group\s+by.+\(/i,
/(?:from\W+information_schema\W)/i,
/(?:(?:current_)user|database|schema|connection_id)\s*\(/i,
/\s*or\s+.*=.*/i,
/order\s+by\s+.*--$/i,
/benchmark\((.*)\,(.*)\)/i,
/base64_decode\(/i,
/(?:(?:current_)user|database|version|schema|connection_id)\s*\(/i,
/(?:etc\/\W*passwd)/i,
/into(\s+)+(?:dump|out)file\s*/i,
/xwork.MethodAccessor/i,
/(?:define|eval|file_get_contents|include|require|require_once|shell_exec|phpinfo|system|passthru|preg_\w+|execute|echo|print|print_r|var_dump|(fp)open|alert|showmodaldialog)\(/i,
/\<(iframe|script|body|img|layer|div|meta|style|base|object|input)/i,
/(onmouseover|onmousemove|onerror|onload)\=/i,
/javascript:/i,
/\.\.\/\.\.\//i,
/\|\|.*(?:ls|pwd|whoami|ll|ifconfog|ipconfig|&&|chmod|cd|mkdir|rmdir|cp|mv)/i,
/(?:ls|pwd|whoami|ll|ifconfog|ipconfig|&&|chmod|cd|mkdir|rmdir|cp|mv).*\|\|/i,
/(gopher|doc|php|glob|file|phar|zlib|ftp|ldap|dict|ogg|data)\:\//i


```
Start the Node service, then visit the website using a browser, and add the simulated attack command "select * from admin" to the URL when visiting. At this time, it can be seen from the background that the attack has been intercepted, and the browser also sees the corresponding intercept prompt.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ubc8d7tb3wn399kjd3dc.png)


In the current demonstration program, the website service and firewall function are integrated together, which is self-protection behavior. If the website service is independent, and needs to provide protection for other websites, you can change this program into a reverse proxy server, and perform security checks when responsible for data transfer. Note: Based on Node.js, using Express as the reverse proxy firewall, you can use middleware such as Express-Http-Proxy to achieve this, which is stable and reliable, and some commercial-grade website application firewalls also adopt this architecture.