Guest User

Untitled

a guest
Apr 10th, 2014
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.02 KB | None | 0 0
  1. """secure.py checks /var/log/secure for new occurrences of "Failed password"
  2. mesages and  generates notification for new break-in attempts on the system. I
  3. also plan to add a feature to drop any traffic from an IP that has attempted to
  4. break-in more than configured times."""
  5.  
  6. import os
  7. import sqlite3
  8. import subprocess
  9. import sys
  10. import time
  11. from notification import notification
  12.  
  13.  
  14. # initially set to 0, MTIME keeps a track of the latest modification time for
  15. # /var/log/secure file
  16.  
  17. MTIME = 0
  18. LASTROWID = 0
  19.  
  20. def database_exists():
  21.     return os.path.exists("var_log_secure.db") #and os.path.exists("count.db")
  22.  
  23.  
  24. def create_database():
  25.     """We will create two databases. One for logging the details of attempt
  26.    like date & ip while another for keeping a track of number of attempts made
  27.    from a particular IP. In future we plan to drop all packets coming from an
  28.    IP that has made X (say, 5) attempts using firewall rules.
  29.    """
  30.     try:
  31.         db = sqlite3.connect("var_log_secure.db")
  32.         cursor = db.cursor()
  33.         cursor.execute('''CREATE TABLE IF NOT EXISTS
  34.                       attempts(id INTEGER PRIMARY KEY, hour INTEGER, minute
  35.                       INTEGER, second INTEGER, day INTEGER, month INTEGER,
  36.                       year INTEGER, ip TEXT)''')
  37.         db.commit()
  38.     except Exception as e:
  39.         raise e
  40.     finally: db.close()
  41.  
  42.  
  43. def exists_in_db(data):
  44.     """ Code in this function will fetch the last entry in the db. This is
  45.    is helpful in figuring out if the data parsed by the program is newer
  46.    than the existing db entries."""
  47.     try:
  48.         db = sqlite3.connect("var_log_secure.db")
  49.         cursor = db.cursor()
  50.         cursor.execute("SELECT id from attempts where hour=? and minute=? and \
  51.                       second=? and day=? and month=? and year=? and ip=?",\
  52.                        (data["hour"], data["minute"], data["second"],\
  53.                        data["day"], data["month"], data["year"], data["ip"],))
  54.         id = cursor.fetchone()
  55.     except Exception as e:
  56.         raise e
  57.     finally:
  58.         db.close()
  59.     if id:
  60.         return True
  61.     return False
  62.  
  63.  
  64. def insert_into_db(data):
  65.     """ This funtion inserts into the database the break-in attempts that are
  66.    newer than the last one as returned by fetch_last_from_db() function"""
  67.     global LASTROWID
  68.     day, month, year, hour, minute, second = data["day"], data["month"],\
  69.                                              data["year"], data["hour"],\
  70.                                              data["minute"], data["second"]
  71.     user, ip = data["user"], data["ip"]
  72.  
  73.     if not exists_in_db(data):
  74.         try:
  75.             db1 = sqlite3.connect("var_log_secure.db")
  76.             cursor1 = db1.cursor()
  77.             cursor1.execute("INSERT INTO attempts(hour, minute, second, day,\
  78.                            month, year, ip) VALUES(?, ?, ?, ?, ?, ?, ?)", \
  79.                             (hour, minute, second, day, month, year, ip))
  80.             db1.commit()
  81.             print "Committed new stuff..\n"
  82.             subprocess.Popen(['notify-send', "Hello World"])
  83.             new_attempts_from_last(data)
  84.         except Exception as e:
  85.             db1.rollback()
  86.             raise e
  87.         finally:
  88.             db1.close()
  89.        
  90.  
  91. def new_attempts_from_last(data):
  92.     """This function will determine the break-in attempts newer than the last
  93.    break-in attempt"""
  94.     t = data['ip'] + " tried to login at " + str(data['hour']) + ':'+ \
  95.             str(data['minute']) + ":"+ str(data['second'])
  96.     t = str(t)
  97.     print "Printing value of t ------> ", t, "\n\n"
  98.     print "Trying to raise a notification.....\n\n\n"
  99.     notification("Dharmit")
  100.     #subprocess.Popen(['notify-send','secure.py', t])
  101.     print "\n\n\nThis is after notification...."
  102.    
  103.  
  104. def database_operations(date, msg):
  105.     """ Initialy part of this code takes care of splitting 'msg' into chunks
  106.    useful for dataabase. Next it calls various db related functions to insert
  107.    the data or retrieve details of last known attempt."""
  108.  
  109.     time_of_attempt = msg[0].split('T')[1].split(':')
  110.     time_of_attempt[2] = int(float(time_of_attempt[2].split('+')[0]))
  111.  
  112.     year, month, day = date[0], date[1], date[2]
  113.     hour, minute, second = time_of_attempt[0], time_of_attempt[1],\
  114.                            time_of_attempt[2]
  115.     user, ip = msg[6], msg[8]
  116.     data = {"year" : int(year), "month" : int(month), "day" : int(day), "ip" :
  117.             ip, "user" : user, "hour" : int(hour), "minute" : int(minute),
  118.             "second" : int(second)}
  119.     insert_into_db(data)
  120.  
  121.  
  122. def check_for_failed_password(list_of_readlines):
  123.     l = list_of_readlines
  124.     for i in range(len(l)):
  125.         if ' '.join(l[i].split(' ')[3:6]) == 'Failed password for':
  126.             x = l[i].split('T')  # Temporary variable to fetch date.
  127.             date = x[0].split('-')
  128.             message = l[i].split(' ')
  129.             database_operations(date, message)
  130.         else:
  131.             continue
  132.  
  133.  
  134. def scan_var_log_secure():
  135.     global MTIME
  136.     new_MTIME = os.path.getmtime("/var/log/secure")
  137.     if MTIME == new_MTIME:
  138.         return
  139.     else:
  140.         list_of_readlines = []
  141.         try:
  142.             with open('/var/log/secure') as f:
  143.                 list_of_readlines = f.readlines()
  144.                 check_for_failed_password(list_of_readlines)
  145.         except IOError as e:
  146.             print "You do not have enough permissions to access the file.\n" \
  147.                   "Run the program as sudo or root user and try again."
  148.             sys.exit()
  149.  
  150.         #print "new_MTIME = %f" % new_MTIME
  151.         MTIME = new_MTIME
  152.     #return
  153.  
  154.  
  155. def main():
  156.     if not database_exists():
  157.         create_database()
  158.     while 1:
  159.         scan_var_log_secure()
  160.         time.sleep(5)
  161.     sys.exit(1)
  162.  
  163. if __name__ == "__main__":
  164.     if os.path.exists("/var/log/secure"):
  165.         sys.exit(main())
  166.     else:
  167.         print '/var/log/secure does not exist. Make sure the file exists and '\
  168.               'try again later.'
  169.         sys.exit(1)
Advertisement
Add Comment
Please, Sign In to add comment