Skip to content

Add audit log with tamper detection (new) #105

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion contributers.md

This file was deleted.

65 changes: 65 additions & 0 deletions logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import os
import hashlib
from datetime import datetime

class IntegrityError(Exception):
def __init__(self, message):
super().__init__(message)

class ActionLogger:
def __init__(self, log_file="action_log.txt"):
self.log_file = log_file
self.init_log()

def init_log(self):
if not os.path.exists(self.log_file):
with open(self.log_file, 'a+') as log:
genesis_entry = "GENESIS_ENTRY"
genesis_hash = hashlib.sha256(genesis_entry.encode()).hexdigest()
timestamp = datetime.now().isoformat()
log.write(f"[{timestamp}] GENESIS {genesis_hash}\n")

def log_action(self, action):
with open(self.log_file, 'r') as log:
last_line = log.readlines()[-1]

last_hash = last_line.strip().split()[-1]
timestamp = datetime.now().isoformat()
log_entry = f"[{timestamp}] {action}"
log_hash = hashlib.sha256(f"{log_entry} {last_hash}".encode()).hexdigest()

with open(self.log_file, 'a') as log:
log.write(f"{log_entry} {log_hash}\n")

def verify_genesis_log_integrity(self):
genesis_entry = "GENESIS_ENTRY"
if open(self.log_file, 'r').readline().strip().split()[-1] != hashlib.sha256(genesis_entry.encode()).hexdigest():
raise IntegrityError(f"Log integrity failed: GENESIS_ENTRY")

def verify_log_integrity(self):
self.verify_genesis_log_integrity()
with open(self.log_file, 'r') as log:
lines = log.readlines()
lines = [line.strip() for line in lines]

for i in range(1, len(lines)):
prev_line = lines[i - 1].strip()
curr_line = lines[i].strip()

prev_hash = prev_line.split()[-1]
curr_entry = " ".join(curr_line.split()[:-1])
curr_hash = curr_line.split()[-1]

computed_hash = hashlib.sha256(f"{curr_entry} {prev_hash}".encode()).hexdigest()

if computed_hash != curr_hash:
raise IntegrityError(f"Log integrity failed: Line {i+1}")

return True

def print_logs(self):
with open(self.log_file, 'r') as log:
print("=== LOG START ===")
for line in log:
print(line.strip())
print("=== LOG END ===")
41 changes: 9 additions & 32 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,6 @@
from manager import PasswordManager
import pyperclip




def validate_key_loaded(pm : PasswordManager):
if not pm.keyloaded:
print("Key not loaded. Please load a key first.")
return False
return True

def main():
password = {
"gmail": "password1",
Expand All @@ -18,6 +9,7 @@ def main():
}

pm = PasswordManager()
pm.verify_log_integrity()

print("""What would you like to do?
1. Create a new key
Expand All @@ -26,7 +18,7 @@ def main():
4. Load an existing password file
5. Add a password
6. Get a password
7. List all sites
7. Print log
q. Quit
""")

Expand All @@ -39,36 +31,21 @@ def main():
elif choice == '2':
path = input("Enter key file path: ").strip()
pm.load_key(path)
elif choice == '3' and validate_key_loaded(pm):
elif choice == '3':
path = input("Enter password file path: ").strip()
pm.create_password_file(path, password)
elif choice == '4' and validate_key_loaded(pm):
elif choice == '4':
path = input("Enter password file path: ").strip()
pm.load_password_file(path)
elif choice == '5' and validate_key_loaded(pm):
elif choice == '5':
site = input("Enter site: ").strip()
password = input("Enter password: ").strip()
if pm.validate_strength(password):
print("added successfully")
else:
print("WARNING: This password is weak, It is recommended to set a stronger password")
print("- Password should be more than 8 characters long")
print("- Password should have alphanumeric characters, capital letters and special characters")
pm.add_password(site, password)

elif choice == '6' and validate_key_loaded(pm):

elif choice == '6':
site = input("Enter site: ").strip()
res = pm.get_password(site)
print(f"Password for {site}: {res}")
if(res != "Password not found."):
pyperclip.copy(pm.get_password(site))
print("Password copied to clipboard.")

print(f"Password for {site}: {pm.get_password(site)}")
elif choice == '7':
print("Saved Sites:")
for site in pm.password_dict:
print(site)
pm.print_logs()
elif choice == 'q':
done = True
print("Goodbye!")
Expand All @@ -77,4 +54,4 @@ def main():


if __name__ == '__main__':
main()
main()
45 changes: 15 additions & 30 deletions manager.py
Original file line number Diff line number Diff line change
@@ -1,70 +1,55 @@
from cryptography.fernet import Fernet

from logger import ActionLogger

class PasswordManager:

def __init__(self):
self.key = None
self.password_file = None
self.password_dict = {}
self.keyloaded = False
self.logger = ActionLogger()

def create_key(self, path):
self.key = Fernet.generate_key()
with open(path, 'wb') as f:
f.write(self.key)
self.keyloaded = True
self.logger.log_action(f"CREATE_KEY {path}")

def load_key(self, path):
with open(path, 'rb') as f:
self.key = f.read()
self.keyloaded = True

self.logger.log_action(f"LOAD_KEY {path}")

def create_password_file(self, path, initial_values=None):
self.password_file = path
if initial_values is not None:
for site in initial_values:
print(initial_values[site])
self.add_password(site, initial_values[site])
for site, password in initial_values.items():
self.add_password(site, password)
self.logger.log_action(f"CREATE_PASSWORD_FILE {path}")

def load_password_file(self, path):
self.password_file = path
with open(path, 'r') as f:
for line in f:
site, encrypted = line.split(":")
self.password_dict[site] = Fernet(self.key).decrypt(encrypted.encode()).decode()
self.logger.log_action(f"LOAD_PASSWORD_FILE {path}")

def add_password(self, site, password):
self.password_dict[site] = password
if self.password_file is not None:
with open(self.password_file, 'a+') as f:
encrypted = Fernet(self.key).encrypt(password.encode()).decode()
f.write(f"{site}:{encrypted}\n")
self.logger.log_action(f"ADD_PASSWORD {site}")

def get_password(self, site):
self.logger.log_action(f"GET_PASSWORD {site}")
return self.password_dict.get(site, "Password not found.")
def validate_strength(self, password):
# a password is strong if it has length greater than 8
# it has special characters such as !@#$%^&*
# it is a mix of letters, numbers
SpecialChar = '!@#$%^&*'
has_good_length = False
has_special_char = False
has_numeric_characters = False
has_capital_letters = False
has_small_letters = False
if len(password) > 8:
has_good_length = True
for chr in password:
if chr in SpecialChar:
has_special_char = True
if chr.isupper():
has_capital_letters = True
if chr.islower():
has_small_letters = True
if chr.isdigit():
has_numeric_characters = True
return has_numeric_characters and has_good_length and\
has_capital_letters and has_special_char and has_small_letters

def verify_log_integrity(self):
return self.logger.verify_log_integrity()

def print_logs(self):
self.logger.print_logs()