-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathnotifier.py
391 lines (312 loc) · 15.1 KB
/
notifier.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
__author__ = "Moath Maharmeh"
__license__ = "GNU General Public License v2.0"
__email__ = "[email protected]"
__created__ = "13/Dec/2018"
__modified__ = "7/Apr/2020"
__project_page__ = "https://github.com/iomoath/file_watchtower"
import functions
import logger
import sys
import os
import db
import email_sender
import settings
from Enum import *
"""
Severity Definition:
# CRITICAL: Unable to start. DOWN state.
# MEDIUM: Not used in WatchTower, for future use
# LOW: Not used in WatchTower, for future use
# INFO: Not used in WatchTower, for future use
"""
module_name = os.path.basename(__file__)
ALERT_LEVEL = Enum(["CRITICAL", "WARNING", "ERROR", "INFO"])
TEMPLATE = Enum(["WATCHLIST_FILE_READ_ERROR",
"WATCHLIST_FILE_EMPTY",
"FILE_CHANGED",
"NEW_FILE_DETECTED",
"FILE_DELETED",
"FILE_RENAMED",
"WATCHLIST_FILE_NOT_FOUND"
])
ALERT_TEMPLATE_FILE = {
TEMPLATE.WATCHLIST_FILE_READ_ERROR: "email_templates/watchlist_read_error.txt",
TEMPLATE.WATCHLIST_FILE_NOT_FOUND: "email_templates/watchlist_not_found.txt",
TEMPLATE.WATCHLIST_FILE_EMPTY: "email_templates/watchlist_file_empty.txt",
TEMPLATE.FILE_DELETED: "email_templates/file_deleted.txt",
TEMPLATE.FILE_CHANGED: "email_templates/file_changed.txt",
TEMPLATE.NEW_FILE_DETECTED: "email_templates/new_file_detected.txt",
TEMPLATE.FILE_RENAMED: "email_templates/file_renamed.txt",
}
def read_template_file(template_file):
"""Reads email template file"""
global TEMPLATE
template_path = ALERT_TEMPLATE_FILE[template_file]
if not os.path.exists(template_path):
log_msg = functions.get_file_does_not_exist_msg(template_path)
logger.log_error(log_msg, module_name)
sys.exit(log_msg)
try:
file_stream = open(template_path, "r")
except IOError as e:
log_msg = functions.get_file_read_error_msg(template_path, e.errno, e.strerror)
logger.log_error(log_msg, module_name)
sys.exit(log_msg)
else:
with file_stream:
file_content = file_stream.read()
if not file_content:
log_msg = functions.get_file_empty_error_msg(template_path)
logger.log_error(log_msg, module_name)
sys.exit(log_msg)
return file_content.strip()
def construct_msg_file_changed(file_info_list, alert_lvl):
"""
Construct:
1. email message from an email txt template
2. txt email attachment contains list of files that is changed
:param file_info_list: number of files has been changed
:param alert_lvl: Alert level Enum
:return: dict{subject, body, attachment}
"""
# Message subject
message_subject = "{} - File Change has been detected".format(alert_lvl)
# Message body
message_body = read_template_file(TEMPLATE.FILE_CHANGED)
message_body = message_body.replace("%VIOLATION_COUNT%", str(len(file_info_list)))
# Message attachment
attachment_str = ""
for file_info in file_info_list:
attachment_str += "File Path: '{}'\n".format(file_info["path"])
attachment_str += "Old Size: {}\n".format(file_info["previous_size"])
attachment_str += "New Size: {}\n".format(file_info["new_size"])
attachment_str += "Old Hash: {}\n".format(file_info["previous_hash"])
attachment_str += "New Hash: {}\n".format(file_info["new_hash"])
attachment_str += "Event time: {}\n".format(file_info["detection_time"])
attachment_str += "-" * 50
attachment_str += '\n'
attachment_str = functions.encode_base64(attachment_str)
email_msg_dict = {"subject": message_subject, "body": message_body, "attachment": attachment_str}
return email_msg_dict
def construct_msg_new_file_detected(file_info_list, alert_lvl):
"""
Construct:
1. email message from an email txt template
2. txt email attachment contains list of new detected files
:param file_info_list: number of new files has been detected
:param alert_lvl: Alert level Enum
:return: dict{subject, body, attachment}
"""
# Message subject
message_subject = "{} - New files has been detected".format(alert_lvl)
# Message body
message_body = read_template_file(TEMPLATE.NEW_FILE_DETECTED)
message_body = message_body.replace("%NEW_FILE_COUNT%", str(len(file_info_list)))
# Message attachment
attachment_str = ""
for file_info in file_info_list:
attachment_str += "File Path: '{}'\n".format(file_info["path"])
attachment_str += "Size: {}\n".format(file_info["size"])
attachment_str += "Hash: {}\n".format(file_info["hash"])
attachment_str += "Event time: {}\n".format(file_info["detection_time"])
attachment_str += "-" * 50
attachment_str += '\n'
attachment_str = functions.encode_base64(attachment_str)
email_msg_dict = {"subject": message_subject, "body": message_body, "attachment": attachment_str}
return email_msg_dict
def construct_msg_file_deleted(file_info_list, alert_lvl):
"""
Construct:
1. email message from an email txt template
2. txt email attachment contains list of deleted files
:param file_info_list: number of files has been deleted
:param alert_lvl: Alert level Enum
:return: dict{subject, body, attachment}
"""
# Message subject
message_subject = "{} - File Deletion has been detected".format(alert_lvl)
# Message body
message_body = read_template_file(TEMPLATE.FILE_DELETED)
message_body = message_body.replace("%DELETION_COUNT%", str(len(file_info_list)))
# Message attachment
attachment_str = ""
for file_info in file_info_list:
attachment_str += "File Path: '{}'\n".format(file_info["path"])
attachment_str += "Size: {}\n".format(file_info["size"])
attachment_str += "Hash: {}\n".format(file_info["hash"])
attachment_str += "Event time: {}\n".format(file_info["detection_time"])
attachment_str += "-" * 50
attachment_str += '\n'
attachment_str = functions.encode_base64(attachment_str)
email_msg_dict = {"subject": message_subject, "body": message_body, "attachment": attachment_str}
return email_msg_dict
def construct_msg_file_renamed(file_info_list, alert_lvl):
"""
Construct:
1. email message from an email txt template
2. txt email attachment contains list of deleted files
:param file_info_list: number of files has been deleted
:param alert_lvl: Alert level Enum
:return: dict{subject, body, attachment}
"""
# Message subject
message_subject = "{} - File Rename has been detected".format(alert_lvl)
# Message body
message_body = read_template_file(TEMPLATE.FILE_RENAMED)
message_body = message_body.replace("%RENAME_COUNT%", str(len(file_info_list)))
# Message attachment
attachment_str = ""
for file_info in file_info_list:
attachment_str += "Old Path: '{}'\n".format(file_info["old_path"])
attachment_str += "New Path: '{}'\n".format(file_info["new_path"])
attachment_str += "Hash: {}\n".format(file_info["hash"])
attachment_str += "Event time: {}\n".format(file_info["detection_time"])
attachment_str += "-" * 50
attachment_str += '\n'
attachment_str = functions.encode_base64(attachment_str)
email_msg_dict = {"subject": message_subject, "body": message_body, "attachment": attachment_str}
return email_msg_dict
def construct_msg_watchlist_not_found(alert_lvl, detection_time):
# Message subject
message_subject = "{} - Watchlist file could not be found".format(alert_lvl)
# Message body
message_body = read_template_file(TEMPLATE.WATCHLIST_FILE_NOT_FOUND)
message_body = message_body.replace("%WATCH_LIST_FILE_PATH%", settings.WATCH_LIST_FILE_PATH)
message_body = message_body.replace("%DETECTION_TIME%", detection_time)
message_body += '\n'
message_body += "-" * 50
message_body += '\n'
email_msg_dict = {"subject": message_subject, "body": message_body, "attachment": None}
return email_msg_dict
def construct_msg_watchlist_read_error(alert_lvl, detection_time):
# Message subject
message_subject = "{} - Unable to access the Watchlist file.".format(alert_lvl)
# Message body
message_body = read_template_file(TEMPLATE.WATCHLIST_FILE_READ_ERROR)
message_body = message_body.replace("%WATCH_LIST_FILE_PATH%", settings.WATCH_LIST_FILE_PATH)
message_body = message_body.replace("%DETECTION_TIME%", detection_time)
message_body += '\n'
message_body += "-" * 50
message_body += '\n'
email_msg_dict = {"subject": message_subject, "body": message_body, "attachment": None}
return email_msg_dict
def construct_msg_watchlist_file_empty(alert_lvl, detection_time):
# Message subject
message_subject = "{} - Watch list file is empty.".format(alert_lvl)
# Message body
message_body = read_template_file(TEMPLATE.WATCHLIST_FILE_EMPTY)
message_body = message_body.replace("%WATCH_LIST_FILE_PATH%", settings.WATCH_LIST_FILE_PATH)
message_body = message_body.replace("%DETECTION_TIME%", detection_time)
message_body += '\n'
message_body += "-" * 50
message_body += '\n'
email_msg_dict = {"subject": message_subject, "body": message_body, "attachment": None}
return email_msg_dict
def construct_email_for_sending(msg_info_dict):
try:
attachments = functions.decode_base64(msg_info_dict["attachments"])
except:
attachments = None
dict_msg = {
"from": "{} <{}>".format(settings.FROM_NAME, settings.FROM),
"recipients": settings.TO.split(','),
"message": msg_info_dict["body"],
"subject": msg_info_dict["subject"],
"attachments": attachments}
return dict_msg
def queue_email_message(msg_template, alert_level, file_info_list):
"""
# Queue message in the DB For sending
:param msg_template: Enum notifier.template
:param alert_level: alert to be included in email subject
:param file_info_list: list of dict. ex; [{'path': '../p.txt', 'old_hash': '111', 'new_hash': '222',
'old_size': '507', 'new_size': 73, 'detection_time': '2018-12-13 22:56:00'}'}]
:return:
"""
try:
logger.log_debug("queue_message(): Constructing Email message" "Template: '{}'".format(TEMPLATE.FILE_CHANGED),
module_name)
if msg_template == TEMPLATE.FILE_CHANGED:
msg_dict = construct_msg_file_changed(file_info_list, alert_level)
row_id = db.insert_email_msg(msg_dict)
if row_id > 0:
logger.log_debug("queue_message(): Email message has been queued for sending. "
"Template: '{}'".format(TEMPLATE.FILE_CHANGED),
module_name)
elif msg_template == TEMPLATE.NEW_FILE_DETECTED:
msg_dict = construct_msg_new_file_detected(file_info_list, alert_level)
row_id = db.insert_email_msg(msg_dict)
if row_id > 0:
logger.log_debug("queue_message(): Email message has been queued for sending. "
"Template: '{}'".format(TEMPLATE.NEW_FILE_DETECTED),
module_name)
elif msg_template == TEMPLATE.FILE_DELETED:
msg_dict = construct_msg_file_deleted(file_info_list, alert_level)
row_id = db.insert_email_msg(msg_dict)
if row_id > 0:
logger.log_debug("queue_message(): Email message has been queued for sending. "
"Template: '{}'".format(TEMPLATE.FILE_DELETED),
module_name)
elif msg_template == TEMPLATE.FILE_RENAMED:
msg_dict = construct_msg_file_renamed(file_info_list, alert_level)
row_id = db.insert_email_msg(msg_dict)
if row_id > 0:
logger.log_debug("queue_message(): Email message has been queued for sending. "
"Template: '{}'".format(TEMPLATE.FILE_RENAMED),
module_name)
except Exception as e:
logger.log_error("queue_message(): Failed to queue email message in the database. More info: {}"
.format(e), module_name)
def queue_email_message_text(msg_template, alert_level, msg_text):
"""
# Queue message in the DB For sending, then try to send it after queuing it
:param msg_template: Enum notifier.template
:param alert_level: alert to be included in email subject
:param msg_text: Message text
:return:
"""
try:
logger.log_debug(
"queue_message(): Constructing Email message" "Template: '{}'".format(
TEMPLATE.WATCHLIST_FILE_READ_ERROR),
module_name)
if msg_template == TEMPLATE.WATCHLIST_FILE_NOT_FOUND:
msg_dict = construct_msg_watchlist_not_found(alert_level, functions.get_datetime())
row_id = db.insert_email_msg(msg_dict)
if row_id > 0:
logger.log_debug("queue_message(): Email message has been queued for sending. "
"Template: '{}'".format(TEMPLATE.WATCHLIST_FILE_NOT_FOUND),
module_name)
elif msg_template == TEMPLATE.WATCHLIST_FILE_EMPTY:
msg_dict = construct_msg_watchlist_file_empty(alert_level, functions.get_datetime())
row_id = db.insert_email_msg(msg_dict)
if row_id > 0:
logger.log_debug("queue_message(): Email message has been queued for sending. "
"Template: '{}'".format(TEMPLATE.WATCHLIST_FILE_NOT_FOUND),
module_name)
elif msg_template == TEMPLATE.WATCHLIST_FILE_READ_ERROR:
msg_dict = construct_msg_watchlist_read_error(alert_level, functions.get_datetime())
row_id = db.insert_email_msg(msg_dict)
if row_id > 0:
logger.log_debug("queue_message(): Email message has been queued for sending. "
"Template: '{}'".format(TEMPLATE.WATCHLIST_FILE_READ_ERROR),
module_name)
except Exception as e:
logger.log_error("queue_message(): Failed to queue email message in the database. More info: {}"
.format(e), module_name)
# Try Send the message
try:
send_queued_messages()
except:
pass
def send_queued_messages():
msg_list = db.get_unsent_messages()
logger.log_debug("send_queued_messages(): Sending email messages..", module_name)
for msg_dict in msg_list:
logger.log_debug("send_queued_messages(): Sending message id '{}'".format(msg_dict["id"]), module_name)
msg_dict_full = construct_email_for_sending(msg_dict)
if email_sender.send_message(msg_dict_full):
db.delete_msg(msg_dict["id"])
logger.log_debug("send_queued_messages(): Sent message id '{}'".format(msg_dict["id"]), module_name)
logger.log_debug("send_queued_messages(): Sending email messages complete.",
module_name)