In a ping flood Denial-of-Service attack, the attacker attempts to overwhelm a targeted device with ICMP echo-request packets, causing the target to become inaccessible to normal traffic.
In this project, we will use Z-Score Analysis to monitor and detect any anomaly in our Network Ping and receive alerts on Telegram so that we can disconnect our device from the network or switch to a better network before it crashes.
We are also going to receive regular updates about all the connected devices in our WiFi Network so that we can actively monitor/detect them by their MAC Address and take necessary steps to block any unwanted device.
Besides that, we are also going to use an LED and a Mini Buzzer as Hardware components for alert purpose. The no. of times LED is going to flash will indicate no. of devices connected in the Wifi Network. And, when the buzzer will turn on, it will indicate a Network Ping anomaly has been detected.
Hardware Setup- Connect +ve leg of LED to 330 ohm Resistor
- Now connect the 330 ohm Resistor to pin '0' of the Bolt Wifi Module with connecting wires.
- Connect -ve leg of LED to pin 'GND' of the Bolt Wifi Module with connecting wires.
- Connect +ve leg of Buzzer to pin '1' of the Bolt Wifi Module with connecting wires.
- Connect -ve leg of Buzzer to pin 'GND' of the Bolt Wifi Module with connecting wires.
Power on your Bolt Wifi Module using a Micro USB Cable.
Create a Bolt Cloud account (if you don't have one) using the link given below. If you already have one, sign in directly.
https://cloud.boltiot.com/register/
Download the Bolt App (Android or IOS), and setup the Bolt IoT WiFi module by simply following the instructions in the app. You can also refer to the link below for instructions.
https://docs.boltiot.com/docs/adding-a-new-device
Now login to cloud.boltiot.com
On the left hand Navigation Bar, click on API.
Click on Generate New API Key and click enable.
Copy and store this key somewhere safely. We will need it later.
Also store the device ID safely.
Part 2 : Telegram Channel & Bot SetupTelegram is a messaging app similar to Whatsapp. It can be installed on both Android or IOS.
1. Creating a Telegram Channel :
Sign Up/ Sign In to your Telegram Account.
On the Home Screen, click on the icon at right hand bottom corner, then click on "New Channel".
It will ask for a Name and Description (optional). You can Name it whatever you like. Enter everything and click on the tick. (Make the channel Public).
2. Creating a Telegram Bot :
Go to the Telegram Home screen and search for "BotFather".
Select the verified account as shown. Next, just type "/start" and send.
Next, type "/newbot" and hit enter. It will ask for a Bot Name, so name the bot. Then it will ask for a username- give a unique username.
Congrats! You just created a bot on Telegram. It will give you a token. Store the token safely.
Now click and open Channel Info. Click on Administrators and add your Bot. Grant all permissions to the Bot and click the tick.
Part 3 : Virtual Box & Linux Machine SetupVirtual Box is a software which will help you virtualize any Operating System of your Choice. Download Virtual Box for your OS from here.
Kali Linux is recommended for this project, although any Debian based Linux distro would work. Watch this video to download and use Kali Linux machine on Virtual box.
Part 4 : Python & Pip SetupUse your USB WiFi Adapter to connect to a WiFi Network.
- You can also use your PC's default internal Wifi adapter (if available) to connect to a WiFi Network.
Open Virtual Box and start your virtual machine. Open Terminal.
First make sure if your Linux Machine has Python3 and Pip pre-installed. If not use the following commands (you can use these commands even if they are already installed). Using sudo may prompt you for the password. Enter your password and hit enter.
$ sudo apt-get update
$ sudo apt install python3
$ sudo apt install python3-pip
Next install all the necessary Python packages to run the program correctly using the following commands (you can use these commands even if they are already installed). Using sudo may prompt you for the password. Enter your password and hit enter.
$ sudo pip3 install requests
$ sudo pip3 install statistics
$ sudo pip3 install boltiot
$ sudo pip3 install speedtest-cli
$ sudo pip3 install scapy
Part 5 : Code SetupNow create a folder/directory on the Desktop(for easy navigation) to save the program. Use the following commands (you can name the folder as you wish, I have named mine as BoltIoT).
$ cd Desktop
$ mkdir BoltIoT
$ cd BoltIoT
Type the next command to open a python file. Naming it as conf.py is a must.
$ nano conf.py
Edit the conf.py file and add your own credentials shown below.
bolt_api_key = "XXXX" # Replace XXXX with your Bolt CLoud API Key
device_id = "XXXX" # Replace XXXX with your Bolt IoT Device ID
telegram_chat_id = "@XXXX" # Replace XXXX with your Telegram Channel ID
telegram_bot_id = "botXXXX" # Replace XXXX with Bot Token ID of your Telegram Bot
frame_size = 5 # Edit frame_size (higher value denotes more test cases)
mul_factor = 5 # Edit mul_factor (higher value denotes broader range)
Type/paste the following code in the editor. It is a configuration file to send the output to Telegram. Use the details that had to be stored safely.
To save the file, hit the following buttons in order : (Ctrl+X) --> y --> Enter
- For testing/domestic purpose use lower values of frame_size and mul_factor (Ex: 5 and 5).
- For real life scenarios like actually detecting a DoS Attack, use higher values of frame_size and mul_factor, depending upon the scale and no. of devices connected in the WiFi Network.
Create another python file using the following commands (you can name the folder as you wish, I have named mine as netwizard.py).
$ nano netwizard.py
The code for the project is given below. You are free to copy and paste it in your newly created python file.
import requests # to make HTTP requests
import json # library for handling JSON data
import time # time library
import math, statistics # maths library to compute Z-score
from boltiot import Bolt # importing Bolt from boltiot module
import speedtest # speedtest library to check Network speed
import conf # config file
import scapy.all as sc # import scapy library
try:
file = open('netwizard.txt', 'r')
print (' ')
print (file.read())
file.close()
except IOError:
print ('\nBanner File not found!')
mybolt = Bolt(conf.bolt_api_key, conf.device_id)
ping_history=[]
iprange = input("Enter your Wireless network IP range :\n")
prevcount = 0
status = ""
currentcount = 0
# Function to Scan the IP
def scan(ip):
arp_request = sc.ARP(pdst = ip)
broadcast = sc.Ether(dst = "ff:ff:ff:ff:ff:ff")
x = broadcast/arp_request
answered_list = sc.srp(x, timeout=1, verbose=False)[0]
targets_list = []
for element in answered_list:
targets_dict = {"ip":element[1].psrc, "mac":element[1].hwsrc}
targets_list.append(targets_dict)
return targets_list
# Function to Print the Output Result
def result(results_list):
print("\nConnected Devices :")
print("\n-------------------------------------")
print("IP\t\tMAC Address\n-------------------------------------")
for target in results_list:
print(target["ip"] + "\t" + target["mac"])
global currentcount
currentcount = len(results_list)
print("\nNo. of active Device(s) in your Wifi : ", currentcount, "\n")
global prevcount
global status
if currentcount > prevcount :
diff = currentcount - prevcount
status = str(diff) + " new Device(s) were added in last 60 seconds\n"
print(status)
elif currentcount < prevcount :
diff = prevcount - currentcount
status = str(diff) + " new Device(s) were removed in last 60 seconds\n"
print(status)
else :
status = "No new Device(s) were added or removed in last 60 seconds\n"
print(status)
for i in range(0, currentcount):
mybolt.digitalWrite('0', 'HIGH')
time.sleep(0.05)
mybolt.digitalWrite('0', 'LOW')
prevcount = currentcount
# Function to compute Upper and Lower Bounds by Z-Score Analysis
def compute_bounds(ping_history,frame_size,factor):
if len(ping_history) < frame_size:
return None
if len(ping_history) > frame_size:
del ping_history[0:len(ping_history)-frame_size]
Mn=statistics.mean(ping_history)
Variance=0
for data in ping_history:
Variance += math.pow((data-Mn),2)
Zn = factor*math.sqrt(Variance/frame_size)
High_bound = ping_history[frame_size-1]+Zn
Low_bound = ping_history[frame_size-1]-Zn
return [High_bound,Low_bound]
# Function to test Network Speed
def test():
try:
s = speedtest.Speedtest()
s.get_servers()
s.get_best_server()
s.download()
s.upload()
res = s.results.dict()
return res["download"], res["upload"], res["ping"]
except Exception as e:
print("\nInternet connection was lost :(")
print("\nPlease connect to your Internet and try again !\n")
# Function to send output to Telegram
def telegram_message(message):
url = "https://api.telegram.org/" + conf.telegram_bot_id + "/sendMessage"
data = {"chat_id": conf.telegram_chat_id, "text": message}
try:
response = requests.request("POST", url, params=data)
#print("\nThis is the Telegram URL : ")
#print(url)
#print("\nThis is the Telegram response : ")
#print(response.text)
telegram_data = json.loads(response.text)
return telegram_data["ok"]
except Exception as e:
print("\nAn error occurred in sending the alert message via Telegram")
print(e)
return False
while True :
scan_target = iprange
scan_result = scan(scan_target)
result(scan_result)
message = "Connected Devices :\n\n" + str(scan_result) + "\n\nNo. of active Devices in your Wifi : " + str(currentcount) + "\n\n" + status
telegram_status = telegram_message(message)
print("This is the Telegram status : ", telegram_status, "\n")
d, u, p = test()
print('\nNetwork Information :\n')
print('Download : {:.2f} Kb/s\n'.format(d / 1024))
print('Upload : {:.2f} Kb/s\n'.format(u / 1024))
print('Ping : {:.2f} \n'.format(p))
ping_value = int(p)
bound = compute_bounds(ping_history,conf.frame_size,conf.mul_factor)
if not bound:
required_data_count = conf.frame_size-len(ping_history)
print("Not enough data to compute Z-score. Need ",required_data_count," more data point(s) !")
ping_history.append(ping_value)
continue
try:
if ping_value > bound[0] :
print ("Ping increased suddenly. Sending an alert via Telegram....")
message = "Your Ping has increased suddenly." + "\nCurrent Ping value is : " + str(ping_value)
message += "\nConsider disconnecting some Devices from your Network or switch to a better Network !"
telegram_status = telegram_message(message)
print ("\nThis is the Telegram status : ", telegram_status, "\n")
for i in range(0,9):
mybolt.digitalWrite('1', 'HIGH')
time.sleep(0.05)
mybolt.digitalWrite('1', 'LOW')
ping_history.append(ping_value)
except Exception as e:
print ("Error : ",e)
time.sleep(10)
To save the file, hit the following buttons in order : (Ctrl+X) --> y --> Enter
- If any error occures while installing the Python packages OR the program fails to run, then refer to this GitHub Repository.
- You can download the ZIP file or simply execute the following command to get the code.
$ git clone https://github.com/raunvk/boltiot-netwizard.git
- Follow the README.md file step by step to execute the program.
Before running the code, type the following command and note down your network's Gateway IP address (your address may be different).
$ sudo route -n
The Gateway IP address will be displayed as shown below.
Use the following command to run the program. Using sudo may prompt you for the password. Enter your password and hit enter.
$ cd Desktop/BoltIoT/
$ sudo python3 netwizard.py
Upon execution of program, you will be prompted with an input.
Enter your Wireless network IP range : 192.168.0.1/24
(Add /24 at the end of your Gateway IP address)
Part 2 : Code & Telegram OutputThe program will use the first 'n' Network Ping values (n is the frame size which is saved in conf.py) to evaluate Upper and Lower Bounds using Z-Score Analysis.
If an anomaly is detected then it will display it on the Terminal.
It will also send a Telegram message in the Telegram channel that was created.
- This is just an example, and ping value of 24 doesn't imply a ping flood DoS Attack. It happened here because, for testing/demonstration purpose, lower values of frame_size and mul_factor (Ex: 5 and 5) was used in the conf.py file.
- For real life scenarios like actually detecting a DoS Attack, edit the conf.py file and use higher values of frame_size and mul_factor, depending upon the scale and no. of devices connected in the WiFi Network.
The Z-Score formula will provide a better understanding for this.
The no. of times LED is going to flash will indicate no. of devices connected in the Wifi Network. And, when the buzzer will turn on, it will indicate an Internet Ping anomaly has been detected.
ConclusionIn this project, we were sucessfully able to detect Network Ping anomalies and send alerts in Telegram as well as in the form of Light and Sound.
This will help us to detect and prevent ping flood DoS attacks.
The concepts and topics that were covered in this project are :
I hope you will enjoy recreating the project. For any queries or assisstance you can contact me at raunakd137@gmail.com
Thank You !!!
Comments