-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.py
174 lines (150 loc) · 4.59 KB
/
monitor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import psutil
import time
import asyncio
import subprocess
import threading
import requests
import math
import sys
from datetime import datetime
try:
webhook = sys.argv[1]
except IndexError:
webhook = None
try:
hostname = sys.argv[2]
except IndexError:
hostname = None
async def monitor():
if webhook == None:
print("No webhook specified. Exiting.")
print("Usage: monitor.py <webhook> <hostname>")
return
if hostname == None:
print("No hostname specified. Exiting.")
print("Usage: monitor.py <webhook> <hostname>")
return
while True:
current_in = get_bandwidth()
await send_stat(current_in)
time.sleep(1)
async def send_stat(value):
# check if a tcpdump is active
if threading.active_count() > 1:
# print("TCPdump is active. Skipping attack detection.")
return
if value > 2000:
print(f"DDoS attack detected: {value} PPS")
threading.Thread(target=tcpdump).start()
while True:
if not check_if_still_under_attack():
break
def check_if_still_under_attack():
current_bandwidth = get_bandwidth()
print(f"Current network traffic stats: {current_bandwidth} PPS")
if current_bandwidth > 2000:
return True
else:
if threading.active_count() > 0:
return False
embed = {
"title": f"Attack - {hostname}",
"description": f"The attack on {hostname} has ended.",
"color": "#7B4CB9"
}
data = {
"embeds": [
embed
]
}
headers = {
"Content-Type": "application/json"
}
requests.post(webhook, json=data, headers=headers)
return False
def get_bandwidth():
net1_in = psutil.net_io_counters().packets_recv
time.sleep(1)
net2_in = psutil.net_io_counters().packets_recv
if net1_in > net2_in:
current_in = 0
else:
current_in = net2_in - net1_in
return current_in
def get_bandwidth_bytes():
net1_in = psutil.net_io_counters().bytes_recv
time.sleep(1)
net2_in = psutil.net_io_counters().bytes_recv
if net1_in > net2_in:
current_in = 0
else:
current_in = net2_in - net1_in
return current_in
def tcpdump():
now = datetime.now()
# run command
fileTime = now.strftime("%m-%d-%Y--%H:%M:%S")
dump = subprocess.Popen(['/usr/sbin/tcpdump', 'inbound', '-i', 'eth0', '-n',
'-s0', '-c', '10000', 'and', 'ip', '-w', f'/root/tcpdumps/{fileTime}.pcap'])
while True:
if not check_if_still_under_attack():
# stop tcpdump
dump.kill()
break
if dump.poll() is not None:
print("TCPdump finished. Sending to Courvix for analysis.")
break
# send to courvix
capture_file = open(f'/root/tcpdumps/{fileTime}.pcap', 'rb')
analysis = requests.post(
"https://api.courvix.com/attack/analyze", files={'capture': capture_file}).json()
embed = {
"title": f"Attack Detected - {hostname}",
"description": f"An attack has been detected on {hostname}. Traffic belongs to " + str(analysis['network_count']) + " networks and there are " + str(analysis["ip_count"]) + " unique IP addresses. We are attempting mitigations.",
"color": "15548997",
"fields": [
{
"name": "TCP Dump Location",
"value": "/root/tcpdumps/" + fileTime,
},
{
"name": "Attack type(s)",
"value": analysis['attack_type']
},
{
"name": "IP Spoofing?",
"value": analysis['spoofing']
},
{
"name": "Packets Per Second",
"value": f"{get_bandwidth()} PPS"
},
{
"name": "Bandwidth",
"value": convert_size(get_bandwidth_bytes())
},
{
"name": "CPU Usage",
"value": f"{psutil.cpu_percent(interval=None)}%"
}
]
}
data = {
"embeds": [
embed
]
}
headers = {
"Content-Type": "application/json"
}
requests.post(webhook, json=data, headers=headers)
return
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s %s/s" % (s, size_name[i])
asyncio.run(monitor())