first commit

This commit is contained in:
2025-03-24 21:33:34 +00:00
commit 4a183d6f90
34 changed files with 885 additions and 0 deletions
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/python3
import os
from twisted.internet import protocol, reactor, endpoints
from datetime import datetime
from sendAuthMail import SendOff
# HOMEIP='213.46.222.164'
with open('/root/SAVEIPS') as f:
SAVEIPS = f.read().splitlines()
# run this as a daemon
# # nohup python3 eventService.py &
# start-stop-daemon -SbCv -x /opt/Monitor/monitor/eventService.py
def log_event(text):
with open('/tmp/event.log', 'a') as f1:
f1.write(text)
class Event(protocol.Protocol):
events = {}
illegal_events = 0
def dataReceived(self, data):
'''
data contains the event, which a 1-liner like:
"type,key,repetition-treshold,time-out,event-text"
type: ERROR, BLOCK, WARNING
key: error-id, incse of BLOCK this is an IP-address
repetition-treshold and time-out: if 5 times in 10 minutes, take action (ERROR: sendmail, BLOCK: block thre ip-address)
'''
event = str(data, 'utf-8').strip()
now = datetime.now()
now_label = now.strftime('%d.%H:%M:%S')
# put ther raw event in the log
log_event("{} {}\n".format(now_label, event))
# saving and dealing with the event comes here....
if not (event.count(',') == 4 and (event.startswith('ERROR') or event.startswith('WARN') or event.startswith('BLOCK'))):
event="ERROR,ILLEGAL,3,10,Misformed event has been sent to the logger"
(evtype, evkey, evrep, evtimeout, evtext) = event.split(',')
if evtype == 'ERROR' or evtype == 'BLOCK':
new_timestamp_list = []
if evkey in self.events.keys():
timestamp_list = self.events[evkey]
for timestamp in timestamp_list:
# if timestamp is younger than now - evtimeout, add it to the new list
delta_time = now - timestamp
if delta_time.total_seconds() < (60.0 * int(evtimeout)):
new_timestamp_list.append(timestamp)
new_timestamp_list.append(now)
self.events[evkey] = new_timestamp_list
# print(self.events)
if len(new_timestamp_list) >= int(evrep):
# delete the event in the key-list
del self.events[evkey]
# now send a message or block an ip
if evtype == 'ERROR':
# send an email
log_event("***** Previous line caused an alert *****\n")
s = SendOff(event)
s.ignace()
elif evtype == 'BLOCK':
# evkey is the IP address, check if its not my own
if not evkey in SAVEIPS:
log_event("***** Blocking IP {} full access *****\n".format(evkey))
# block the IP address
os.system("ufw insert 1 deny from {}".format(evkey))
# os.system("ufw insert 1 deny log from {}".format(evkey))
class EventFactory(protocol.Factory):
def buildProtocol(self, addr):
return Event()
endpoints.serverFromString(reactor, "tcp:1234").listen(EventFactory())
reactor.run() # pylint: disable=no-member