-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileintegerity.py
144 lines (116 loc) · 5.25 KB
/
fileintegerity.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
import hashlib
import os
import time
import getpass
import smtplib
from email.mime.text import MIMEText
def calculate_file_hash(filepath):
sha512 = hashlib.sha512()
with open(filepath, 'rb') as file:
while True:
data = file.read(65536) # Read in 64k chunks
if not data:
break
sha512.update(data)
return sha512.hexdigest()
def erase_baseline_if_already_exists():
if os.path.exists('./baseline.txt'):
os.remove('./baseline.txt')
def log_change(action, file_path, username):
with open('./change_logs.txt', 'a') as log_file:
log_file.write(f"{time.ctime()} - {action}: {file_path} (User: {username})\n")
def get_username():
try:
username = getpass.getuser()
return username
except Exception as e:
print(f"Error getting username: {e}")
return None
def notify_server_mailtrap(action, file_path, username):
mailtrap_server = 'sandbox.smtp.mailtrap.io'
mailtrap_port = 2525
mailtrap_username = '6b7c09b1e85eda'
mailtrap_password = 'b0c987de2c8eac'
from_email = '[email protected]'
to_email = '[email protected]'
data = {
'action': action,
'file_path': file_path,
'username': username,
}
subject = f"[System Alert] File Change Notification - {action}: {file_path}"
body = f"""Dear {username},
This is an automated notification from the [System Antivirus] to inform you of a recent change made to the file: {file_path}. The details of the change are as follows:
Change Type: {action}
Timestamp: {time.ctime()}
User: {username}
If you are aware of this change and have made it intentionally, you may disregard this message. However, if you did not make this change or are unsure of its origin, please investigate further to ensure the security and integrity of the system.
For additional details or if you have any concerns, please contact our IT support team at [Support Email or Phone Number].
Thank you for your attention to this matter.
Best regards,
[A]
[Admin]
"""
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
try:
with smtplib.SMTP(mailtrap_server, mailtrap_port) as server:
server.login(mailtrap_username, mailtrap_password)
server.sendmail(from_email, [to_email], msg.as_string())
print(f"Notification email sent successfully: {data}")
except Exception as e:
print(f"Error sending notification email: {e}")
print()
print("What would you like to do?")
print()
print(" A) Collect new Baseline?")
print(" B) Begin monitoring files with saved Baseline?")
print()
response = input("Please enter 'A' or 'B: ").upper()
print()
if response == "A":
erase_baseline_if_already_exists()
# Collect all files in the target folder
files = [os.path.join('./Files', filename) for filename in os.listdir('./Files') if os.path.isfile(os.path.join('./Files', filename))]
# For each file, calculate the hash, and write to baseline.txt
with open('./baseline.txt', 'a') as baseline_file:
for file_path in files:
file_hash = calculate_file_hash(file_path)
baseline_file.write(f"{file_path}|{file_hash}\n")
elif response == "B":
file_hash_dictionary = {}
# Load file|hash from baseline.txt and store them in a dictionary
with open('./baseline.txt', 'r') as baseline_file:
for line in baseline_file:
file_path, file_hash = line.strip().split('|')
file_hash_dictionary[file_path] = file_hash
# Begin (continuously) monitoring files with the saved Baseline
while True:
time.sleep(1)
files = [os.path.join('./Files', filename) for filename in os.listdir('./Files') if os.path.isfile(os.path.join('./Files', filename))]
for file_path in files:
file_hash = calculate_file_hash(file_path)
# Notify if a new file has been created
if file_path not in file_hash_dictionary:
print(f"{file_path} has been created!")
username = get_username()
log_change("File Created", file_path, username)
notify_server_mailtrap("File Created", file_path, username)
# Notify if a file has been changed
elif file_hash_dictionary[file_path] != file_hash:
print(f"{file_path} has changed!")
username = get_username()
log_change("File Changed", file_path, username)
notify_server_mailtrap("File Changed", file_path, username)
# Check if any baseline files have been deleted
for key in list(file_hash_dictionary.keys()):
if not os.path.exists(key):
print(f"{key} has been deleted!")
username = get_username()
log_change("File Deleted", key, username)
notify_server_mailtrap("File Deleted", key, username)
del file_hash_dictionary[key]
# Update the file hash dictionary with the current hashes
file_hash_dictionary = {file_path: calculate_file_hash(file_path) for file_path in files}