Skip to content

Commit

Permalink
Add the ability to track router and custom servers, related #7
Browse files Browse the repository at this point in the history
  • Loading branch information
okanozdemir committed May 12, 2018
1 parent 9a291d3 commit e149f0f
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 30 deletions.
100 changes: 71 additions & 29 deletions kripton-guard/kripton-guard
Original file line number Diff line number Diff line change
@@ -1,24 +1,33 @@
#!/usr/bin/python3

import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
from crontab import CronTab
import shutil, os, sys, getpass
import configparser
import sqlite3
import pyrebase
import subprocess
import shlex
import re

if os.getegid() != 0:
sys.exit("Please run the script with sudo!")
current_user = getpass.getuser()

config=configparser.ConfigParser()
config=configparser.ConfigParser(allow_no_value=True)
config.read('/etc/kripton-guard/kripton-guard.conf')
subnet=config['SETTINGS']['subnet']
interface=config['SETTINGS']['interface']
mail=config['SETTINGS']['mail']
password=config['SETTINGS']['password']
repeat_time=config['SETTINGS']['repeat-time']

router=config['SERVERS']['router']
dhcp_server=config['SERVERS']['dhcp-server']
dns_server=config['SERVERS']['dns-server']


conn = sqlite3.connect('/var/lib/kripton-guard.db')

apiKey=config['API']['apiKey']
Expand All @@ -42,6 +51,8 @@ userID = userID["users"][0]["localId"]
def createTables(conn):
#Create db table if it's not exist
conn.execute("CREATE TABLE mac_ip_addresses (ID INTEGER PRIMARY KEY AUTOINCREMENT, macAddress varchar(17) UNIQUE NOT NULL, ipAddress varchar(15) NOT NULL, comment varchar(50) )")
conn.execute("CREATE TABLE servers (ID INTEGER PRIMARY KEY AUTOINCREMENT, macAddress varchar(17) UNIQUE NOT NULL, ipAddress varchar(15) NOT NULL, name varchar(50) )")
conn.commit()

def createCron():
my_cron = CronTab(user=current_user)
Expand All @@ -58,31 +69,36 @@ def showDevices():
print(row[0] + " " + row[1] + "\n")
print ("====================================")

def sendNotification():
def sendNotification(type):
#Trigger Cloud Functions
db = firebase.database()
data = {"newMAC": "True"}
data = {type: "True"}
db.child("usersMAC").child(userID).push(data,user['idToken'])

ans,unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=subnet), timeout=5, iface=str(interface))

if(config['SETTINGS']['first-time']=='1'):
config['SETTINGS']['first-time']='0'

createCron()

with open('/etc/kripton-guard/kripton-guard.conf','w') as configfile:
config.write(configfile)
createTables(conn)
def saveMACs():
ans,unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=subnet), timeout=5, iface=str(interface), verbose=0)
for s,r in ans:
mac=(r.sprintf("%Ether.src%"))
ip=(r.sprintf("%ARP.psrc%"))
query= "INSERT INTO mac_ip_addresses (macAddress, ipAddress) VALUES ('{0}','{1}');".format(mac, ip)
conn.execute(query)
conn.commit()
showDevices()
else:
showDevices()

if(router == "yes"):
routerIP = getGateway()
query = "INSERT INTO servers (macAddress, ipAddress, name) VALUES ('{0}','{1}','router');".format(getMac(routerIP),routerIP)
conn.execute(query)
conn.commit()

for option in config.options("CUSTOMSERVERS"):
if(option != ""):
ip = config["CUSTOMSERVERS"][option]
query = "INSERT INTO servers (macAddress, ipAddress, name) VALUES ('{0}','{1}','{2}');".format(getMac(ip), ip, option)
conn.execute(query)
conn.commit()

def searchNewMACs():
ans,unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=subnet), timeout=5, iface=str(interface), verbose=0)
for s,r in ans:
mac=(r.sprintf("%Ether.src%"))
ip=(r.sprintf("%ARP.psrc%"))
Expand All @@ -94,22 +110,48 @@ else:
query = "UPDATE mac_ip_addresses SET ipAddress = '{0}' WHERE macAddress = '{1}';".format(ip,mac)
conn.execute(query)
conn.commit()
# reply = raw_input(mac + " this address is already in whitelist with {0} IP address.\nWould you like to update IP adress to {1} y/n :".format(row[1],ip))
# if (reply == 'y'):
# query = "UPDATE mac_ip_addresses SET ipAddress = '{0}' WHERE macAddress = '{1}';".format(ip,mac)
# conn.execute(query)
# conn.commit()
# print "Updated: " + mac + " -- " + ip""
else:
sendNotification()
sendNotification("newMAC")
query = "INSERT INTO mac_ip_addresses (macAddress, ipAddress) VALUES ('{0}','{1}');".format(mac, ip)
conn.execute(query)
conn.commit()
# reply = raw_input("A new device has been detected.\nMac Address: {0} IP Address: {1}\nWould you like to add this device to whitelist? y/n :".format(mac,ip))
# if (reply == 'y'):
# query = "INSERT INTO mac_ip_addresses (macAddress, ipAddress) VALUES ('{0}','{1}');".format(mac, ip)
# conn.execute(query)
# conn.commit()

def getMac(ip):
ans,unans=arping(ip,verbose=0)
for s,r in ans:
mac=(r.sprintf("%Ether.src%"))
return mac

def checkServers(server,ip):
mac = getMac(ip)
query = "SELECT macAddress FROM servers WHERE name = '{0}';".format(server)
result = conn.execute(query)
row = result.fetchone()
if(row[0] != mac):
sendNotification("'{0}'MACChanged".format(server))

def getGateway():
import subprocess, shlex
strs = subprocess.check_output(shlex.split('ip r l'))
gateway = strs.decode().split('default via')[-1].split()[0]
return gateway

if(config['SETTINGS']['first-time']=='1'):
config['SETTINGS']['first-time']='0'
with open('/etc/kripton-guard/kripton-guard.conf','w') as configfile:
config.write(configfile)
createTables(conn)
saveMACs()
showDevices()
else:
searchNewMACs()
if(router == "yes"):
routerIP = getGateway()
checkServers("router", routerIP)
for option in config.options("CUSTOMSERVERS"):
if(option != ""):
ip = config["CUSTOMSERVERS"][option]
checkServers(option, ip)
showDevices()

conn.close()
10 changes: 9 additions & 1 deletion kripton-guard/kripton-guard.conf
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
[SETTINGS]

# This value indicates that the program is running for the first time or not.
first-time = 1

Expand All @@ -18,6 +17,15 @@ password = YOUR_PASSWORD
# Reruns Kripton-Guard every x minutes.
repeat-time = 1

[SERVERS]
router = yes
dhcp-server = no
dns-server = no

[CUSTOMSERVERS]
#Type in the servers you want to monitor. Example: name = ip
#xxxServer = 192.168.20.20

[API]
apiKey = AIzaSyDRHtAE-r2sXCxlpetuqPsuZuzbwyvjehk
authDomain = kripton-guard.firebaseapp.com
Expand Down

0 comments on commit e149f0f

Please sign in to comment.