#!/usr/bin/python
# This was written for educational purpose and pentest only. Use it at your own risk.
# Author will be not responsible for any damage!
# !!! Special greetz for my friend sinner_01 !!!
# Toolname        : md5db.py
# Coder           : baltazar a.k.a b4ltazar < b4ltazar@gmail.com>
# Version         : 0.1
# Greetz for rsauron and low1z, great python coders
# greetz for d3hydr8, r45c4l, fx0, Soul, MikiSoft, c0ax, b0ne and all members of ex darkc0de.com, ljuska.org 
# Based on low1z (ex. darkc0de member) python script, md5db11.py
# Thanks bro for inspiring me :)

import sys, subprocess, hashlib

try:
    import MySQLdb
except:
    print "\n[-] MySQLdb not installed on system!"
    choo = raw_input("\nWould you like to install it (if want press yes or y)?")
    if choo == "yes" or choo == "y":
        subprocess.call("sudo apt-get install python-mysqldb", shell=True) # Works with me, tested on Kubuntu 12.04
        print "\n[!] MySQLdb installed!"
        print "[!] Now exiting, please try script again!"
        sys.exit(1)
    else:
        print "\n[+] If you using Ubuntu based system, try: sudo apt-get install python-mysqldb"
        print "[!] Thanks for using script, please visit b4ltazar.wordpress.com & ljuska.org"
        print "[!] Now exiting ..."
        sys.exit(1)
    
    

def logo():
  print "\n|---------------------------------------------------------------|"
  print "| b4ltazar[@]gmail[dot]com                                      |"
  print "|   05/2012     md5db.py    v.0.1 (based on low1z script)       |"
  print "|    b4ltazar.wordpress.com     &      ljuska.org               |"
  print "|                                                               |"
  print "|---------------------------------------------------------------|\n"
  
  
if sys.platform == 'linux' or sys.platform == 'linux2':
    subprocess.call("clear", shell=True)
    logo()
else:
    subprocess.call("cls", shell=True)
    logo()
    
dbname = 'md5db'
#####################################################################
DB = MySQLdb.connect(host='127.0.0.1', user='root', passwd='toor') # You should change this line with your login details
#####################################################################

def DBconnect():
    consrv = DB.cursor()
    return consrv

def setupDB():
    consrv = DBconnect()
    try:
        consrv.execute("CREATE DATABASE "+dbname)
        print "[+] Database:", dbname
        print "[+] Status  : created"
    except MySQLdb.Error, e:
        print "[-] Error %s" % (e.args[1])
        sys.exit(1)
    try:
        consrv.execute("CREATE TABLE "+dbname+".data (id INT( 255 ) NOT NULL AUTO_INCREMENT ,plain TEXT NOT NULL ,md5 VARCHAR( 255 ) NOT NULL ,PRIMARY KEY ( id ) , UNIQUE ( md5 )) ENGINE = MYISAM;")
        print "[+] Tables in db:", dbname, "created, Database ready to use!"
    except MySQLdb.Error, e:
        print "[-] Error %s" % (e.args[1])
        sys.exit(1)
        
def importword():
    counter = 0
    try:
        words = open(wordlist, "r")
    except(IOError):
        print "[-] Error: check", wordlist
        sys.exit(1)
    duplicates = 0
    print "[+] Inserting wordlist, skipping duplicates ... may take some time"
    for word in words.read().split('\n'):
        hash = hashlib.md5(word).hexdigest()
        counter = counter + 1
        try:
            consrv = DBconnect()
            consrv.execute("INSERT INTO "+dbname+".data (plain, md5)VALUES ('"+str(word)+"', '"+str(hash)+"');")
        except MySQLdb.Error, e:
            duplicates = duplicates + 1
    print "\n[+] Duplicates:", duplicates
    
def single(shash):
    consrv = DBconnect()
    consrv.execute("SELECT plain FROM "+dbname+".data WHERE md5 = '"+shash+"'")
    dset = consrv.fetchone()
    if dset == None:
        print "[!]",shash, ":", "not in DB"
    else:
        print "[!]",shash, ":", dset[0]
    consrv.close()
    
def dropDB():
    consrv = DBconnect()
    try:
        consrv.execute("DROP DATABASE "+dbname)
        print "[+] Database:", dbname
        print "[+] Status  : deleted"
    except MySQLdb.Error, e:
        print "[-] Error %s" % (e.args[1])
        sys.exit(1)
        
def statusDB():
    try:
        consrv = DBconnect()
        consrv.execute("SELECT COUNT(id) AS num FROM "+dbname+".data")
        DBcount = consrv.fetchone()
        return DBcount[0]
        consrv.close()
    except MySQLdb.Error, e:
        print "[-] Error %s" % (e.args[1])
        sys.exit(1)
  
if len(sys.argv) <= 1:
    print "Usage: "
    print "-s   initial DB installation"
    print "-w   insert wordlist into DB"
    print "-d   delete DB"
    print "-sh  search DB for given hash"
    print "-c   count DB entries\n"
    print "[!] Thanks for using script, please visit b4ltazar.wordpress.com & ljuska.org"
    sys.exit(1)
    
    
  
    
for arg in sys.argv[1:]:
    if arg.lower() == "-s":
        setupDB()
        
    if arg.lower() == "-sh":
        try:
            shash = sys.argv[2]
            if len(shash) != 32:
                print "[-] Invalid md5 supplied, check your input!"
                sys.exit(1)
            single(shash)
        except(IndexError):
            print "[-] Error: check hash!"
            
    if arg.lower() == "-w":
        try:
            wordlist = sys.argv[2]
            importword()
        except(IndexError):
            print "[-] Error, check your wordlist path!"
            
    if arg.lower() == "-d":
        dropDB()
        
    if arg.lower() == "-c":
        print "[+] Checking for number of entries in DB!"
        print "[!]", statusDB(), " entries in DB"