dc5553

hashdir v2 all native

Jul 3rd, 2011
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.89 KB | None | 0 0
  1. #!/usr/bin/python -tt
  2.  
  3. # HashDir hashes files in a directory and stores the values in a database,
  4. # it then compares those hashes to the baseline hashes (if present) and reports any changes
  5.  
  6. import sys
  7. import os
  8. import hashlib
  9. import sqlite3
  10. import time
  11.  
  12. dateTimeGroup = time.asctime().replace(':','').replace(' ','')
  13.  
  14. def help():
  15.    
  16.     print """  Syntax: ./hashDirectories.py directory [-h,-v,-r,-p,-a]
  17.    
  18.     If you use relative or full path be consitent every run!
  19.    
  20.     -h, --help             this screen
  21.     -v, --verbose           print all transactions while they happen
  22.     -r, --reset           reset all baseline hashes
  23.     -p, --purge           purge old and deleted records (prevents deleted records from alerting)
  24.     -a, --reset-alerts     reset all baseline hashes for files that have alerted in the past and reset and any new alerts immediately
  25.     Example:
  26.     $ ./hashDirectories.py c:\\Users -v --reset-alerts
  27.     """
  28.    
  29.     sys.exit(2)
  30.    
  31. def dbExists():
  32.    
  33.     try:
  34.        
  35.         open(os.getcwd() + '\\hashDB.db')
  36.        
  37.         return True
  38.    
  39.     except IOError, e:
  40.        
  41.         return False
  42.  
  43. def tableExisits():
  44.    
  45.     if cursor.execute("SELECT * FROM hashgrid") != 0:
  46.        
  47.         return True
  48.    
  49.     else:
  50.        
  51.         return False
  52.        
  53.        
  54. def createDB():
  55.    
  56.     with open(os.getcwd() + '\\hashDB.db','w+') as makedb:
  57.            
  58.             makedb.close()
  59.  
  60.  
  61. def openDB():
  62.    
  63.     try:
  64.        
  65.         conn = sqlite3.connect(os.getcwd() + '\\hashDB.db')    
  66.    
  67.     except sqlite3.Error, e:
  68.        
  69.         print "\n[!] sqlite.Error Connecting to DB:" + str(e)
  70.        
  71.         sys.exit(1)      
  72.    
  73.     if conn:
  74.        
  75.         print "\n[-] Sucessfully connected to Sqlite DB on " + time.asctime()
  76.    
  77.     return conn
  78.  
  79. def createTable(cursor):
  80.    
  81.     createtb = """
  82.     CREATE TABLE    hashgrid(
  83.     id               INTEGER      PRIMARY KEY,
  84.     filepath         VARCHAR(255) NOT NULL,
  85.     baseline_hash    CHAR(40)     NOT NULL,
  86.     compare_hash     CHAR(40)     DEFAULT NULL,
  87.     hash_date        VARCHAR(17)  DEFAULT NULL
  88.     )"""
  89.    
  90.     try:
  91.        
  92.         cursor.execute(createtb)           
  93.    
  94.     except sqlite3.Error, e:
  95.        
  96.         update += 1
  97.        
  98.         print "\n[!] sqlite3.Error creating table: " + str(e) + "[!] Quitting!"
  99.        
  100.         sys.exit(1)
  101.  
  102. def purgeTable(cursor):
  103.    
  104.     purgeold = """DELETE FROM hashgrid
  105.     WHERE hash_date != '%s' or
  106.     compare_hash IS NULL""" % dateTimeGroup
  107.        
  108.     cursor.execute(purgeold)
  109.  
  110. def tableInsert(fileHash, pathToFile, cursor, conn):
  111.    
  112.     insertdb = """
  113.     INSERT INTO hashgrid
  114.     (baseline_hash,filepath)
  115.     VALUES('%s','%s')""" % (fileHash, pathToFile)
  116.    
  117.     try:
  118.         cursor.execute(insertdb)
  119.        
  120.         if '-v' in sys.argv or '--verbose' in sys.argv:
  121.            
  122.             print '[+] '  + insertdb.replace("\n"," ")
  123.            
  124.             conn.commit()
  125.            
  126.     except sqlite3.Error, e:
  127.        
  128.         print  "\n[!] Error INSERTDB: " + str(e)
  129.        
  130.         errors.append( "\n[!] Error INSERTDB: " + str(e))
  131.  
  132. def tableUpdate(fileHash, pathToFile, cursor, conn):
  133.    
  134.     updatetb = """
  135.     UPDATE hashgrid
  136.     SET compare_hash = '%s', hash_date = '%s'
  137.     WHERE filepath = '%s'
  138.     """ % (fileHash, dateTimeGroup, pathToFile)
  139.    
  140.     try:
  141.         cursor.execute(updatetb)
  142.        
  143.         if '-v' in sys.argv or '--verbose' in sys.argv:
  144.            
  145.             print '\n[+] ' + updatetb.replace("\n"," ")
  146.            
  147.             conn.commit()
  148.            
  149.     except sqlite3.Error, e:
  150.        
  151.         print "\n[!] sqlite3.Error updating table: " + str(e)
  152.        
  153. def tableDrop(cursor):
  154.    
  155.     if cursor.execute("SELECT * FROM hashgrid") != 0:
  156.        
  157.         droptb = "DROP TABLE hashgrid"
  158.        
  159.         cursor.execute(droptb)
  160.  
  161. def checkForTableDifferences(cursor):
  162.  
  163.     rows = cursor.execute("SELECT * FROM hashgrid WHERE baseline_hash != compare_hash").fetchall()
  164.        
  165.     if len(rows) > 0:
  166.            
  167.         print '\n[!] The following record(s) hash has changed since baseline...\n'
  168.            
  169.         for row in rows:
  170.                
  171.             print "\t[!] Changed Record: " + row[1].replace("\n","")
  172.            
  173. def checkForDeletedFiles(cursor):
  174.  
  175.     rows = cursor.execute("SELECT * FROM hashgrid WHERE hash_date != ('%s')" % (dateTimeGroup)).fetchall()
  176.        
  177.     if len(rows) > 0:
  178.            
  179.         print '\n[!] The following record(s) were deleted since baseline...\n'
  180.            
  181.         for row in rows:
  182.                
  183.             print "\t[!] Deleted Record: " + row[1].replace("\n","")
  184.        
  185. def checkForNewFiles(cursor, newRecords):
  186.  
  187.     rows = cursor.execute("SELECT * FROM hashgrid WHERE compare_hash is null and hash_date is ('%s')" % (dateTimeGroup)).fetchall()
  188.            
  189.     if len(rows) == newRecords:
  190.            
  191.         print "\n[-] The table is verified True!"
  192.        
  193.     else:
  194.            
  195.         print "\n[!] The table may have a discrepency"
  196.    
  197.     if len(rows) > 0:
  198.    
  199.         print '\n[!] The following record(s) were added since baseline...\n'
  200.        
  201.         for row in rows:
  202.        
  203.             print "\t[!] Added Record: " + row[1].replace("\n","")
  204.                
  205. def resetHashBaselines(cursor):
  206.    
  207.     resetalerts = """
  208.     UPDATE hashgrid
  209.     SET baseline_hash = compare_hash
  210.     WHERE compare_hash != baseline_hash
  211.     """
  212.    
  213.     cursor.execute(resetalerts)
  214.    
  215. def hashDirectories(dir):
  216.    
  217.     newRecords = 0
  218.    
  219.     firstRun = True
  220.    
  221.     hasResets = False
  222.    
  223.     if dbExists():
  224.        
  225.         conn = openDB()
  226.        
  227.         cursor = conn.cursor()
  228.        
  229.         firstRun = False
  230.    
  231.     else:
  232.        
  233.         createDB()
  234.        
  235.         conn = openDB()
  236.        
  237.         cursor = conn.cursor()
  238.        
  239.         createTable(cursor)
  240.        
  241.     # resets the entire table effectivly making removing all records in the DB
  242.     if '-r' in sys.argv or '--reset' in sys.argv:
  243.        
  244.         tableDrop(cursor)
  245.        
  246.         createTable(cursor)
  247.    
  248.     # purges all the alerts for new, deleted, and hash anomolies
  249.     if '-p' in sys.argv or '--purge' in sys.argv:
  250.        
  251.         purgeTable(cursor);
  252.        
  253.         hasResets = True
  254.    
  255.     # resets all new hashes to the baseline restting each record in the table  
  256.     if '-a' in sys.argv or '--reset-alerts' in sys.argv:
  257.        
  258.         resetHashBaselines(cursor)
  259.        
  260.         hasResets = True
  261.        
  262.     # Start recursing through the directories  
  263.     for root, dir, files in os.walk(str(dir)):
  264.        
  265.         for file in files:
  266.            
  267.             pathToFile = root + '\\' + file
  268.            
  269.             # Helping Python force garbage collection by deleting the last open file
  270.             try:
  271.                
  272.                 del fileOpen
  273.            
  274.             except UnboundLocalError, e:
  275.                
  276.                 pass
  277.            
  278.             try:
  279.                
  280.                 fileOpen = open(pathToFile)
  281.            
  282.             except IOError:
  283.                
  284.                 print '\n[!] IOError opening: ' + pathToFile + str(e)
  285.            
  286.             try:
  287.                
  288.                 try:
  289.                    
  290.                     fileHash = hashlib.md5(fileOpen.read()).hexdigest()
  291.                
  292.                 except MemoryError,e:
  293.                    
  294.                     print '\n[!] Memory Error while opening: ' + pathToFile
  295.                    
  296.             except UnboundLocalError, e:
  297.                
  298.                 print '\n[!] UnboundLocalError while opening: ' + pathToFile           
  299.            
  300.             # checks to see if the file is already in the database and if so it will simply update the hash record for that file in the new column
  301.                        
  302.             if cursor.execute("SELECT filepath FROM hashgrid WHERE filepath = '%s'" % pathToFile).fetchall() == []:
  303.                
  304.                 tableInsert(fileHash, pathToFile, cursor, conn)
  305.                
  306.                 newRecords += 1
  307.                
  308.            
  309.             # if the file has never been added to the DB previously these commands create an all new record for that file in the DB
  310.             else:
  311.                
  312.                 tableUpdate(fileHash, pathToFile, cursor, conn)
  313.                
  314.             try:
  315.                
  316.                 fileOpen.close()
  317.            
  318.             except UnboundLocalError, e:
  319.                
  320.                 print "\n[!] UnboundLocal Error: " + str(e)
  321.                
  322.     if newRecords > 0:
  323.        
  324.         if not hasResets:
  325.            
  326.             print '\n[-] Sucessfully added ' + str(newRecords) + ' file(s)'
  327.    
  328.     else:
  329.        
  330.         print '\n[-] No new files were added on this run'
  331.    
  332.     if firstRun or hasResets:
  333.        
  334.         print '\n[-] This was the first time running hashDirectories or your baselines were reset (No changes!)'
  335.    
  336.     # Checking if any files were deleted since last run
  337.     if not firstRun and '-p' not in sys.argv and '--purge' not in sys.argv and '-a' not in sys.argv and '--reset-alerts' not in sys.argv:
  338.        
  339.         checkForNewFiles(cursor, newRecords)
  340.        
  341.         checkForDeletedFiles(cursor)
  342.                
  343.         checkForTableDifferences(cursor)       
  344.    
  345.     conn.commit()
  346.    
  347.     cursor.close()
  348.    
  349.     conn.close()
  350.  
  351. def main():
  352.    
  353.     if '-h' in sys.argv or '--help' in sys.argv:
  354.        
  355.         help()
  356.        
  357.     if len(sys.argv) > 0:
  358.        
  359.         try:
  360.             dir = sys.argv[1]
  361.            
  362.             hashDirectories(dir)
  363.            
  364.         except IndexError, e:
  365.        
  366.             print '\n[!] Index error: ' + str(e)
  367.            
  368.             help()
  369.  
  370. if __name__ == '__main__':
  371.    
  372.     main()
Advertisement
Add Comment
Please, Sign In to add comment