#!/usr/bin/env python
import requests
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer

"""
Script to create a bridge to leverage SQLMap to exploit a SQLI in a web app 
for which the request to craft is tricky or use a weird format/syntax.

Chaining: SQLMap <====> Bridge <====> Vulnerable endpoint.

Bridge is called using the following url syntax:

http://localhost:8888/?p=[payload]

Dependencies:
    pip install requests

References:
    https://gist.github.com/mdonkers/63e115cc0c79b4f6b8b3a6b797e485c7
"""

requests.packages.urllib3.disable_warnings(
    requests.packages.urllib3.exceptions.InsecureRequestWarning)
# Constants
AUTH_COOKIES = "a=b"
PRX = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}
SERVER_HOST = "localhost"
SERVER_PORT = 8888

# Use a global session to speed up the communications
SESS = requests.Session()
SESS.verify = False
SESS.headers.update({"Cookie": AUTH_COOKIES})


class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        params = urllib.parse.parse_qs(self.path)
        self.wfile.write(bytes(self.relay(SESS, params['/?p'][0]), "utf-8"))

    def do_POST(self):
        content_length = int(self.headers["Content-Length"])
        post_data = self.rfile.read(content_length)
        post_data_str = post_data.decode("utf-8")
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        d = self.relay(SESS, post_data_str)
        self.wfile.write(d.encode("utf-8"))    

    def relay(self, req_session, payload):
        '''
        Implement the call to the vulnerable endpoint here
        to exploit the SQL using the payload provided as well as
        the HTTP session provided.
        '''
        # If you need to URL encode the payload
        url_encoded_payload = urllib.parse.quote_plus(payload)
        # Perform the call here
        post_data = {}
        url = "xxx"
        resp = req_session.post(url, data=post_data, proxies=PRX)
        # Return the response of the vulneralble endpoint
        content = resp.text
        return content


if __name__ == "__main__":
    webServer = HTTPServer((SERVER_HOST, SERVER_PORT), MyServer)
    print(f"Server started, listen on 'http://{SERVER_HOST}:{SERVER_PORT}'.")
    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass
    webServer.server_close()
    print("Server stopped.")
