Skip to content

Commit

Permalink
fix all fmt issues
Browse files Browse the repository at this point in the history
  • Loading branch information
deepattic committed Nov 13, 2024
1 parent 595dad0 commit 24bca45
Show file tree
Hide file tree
Showing 6 changed files with 163 additions and 142 deletions.
87 changes: 51 additions & 36 deletions args.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,45 @@

from libwardenpy.migrations import migrate_DB

from libwardenpy.funtionality import *
from libwardenpy.funtionality import register_user, authenticate_user, add_password, list_passwords, get_password
from libwardenpy.passgen import generate_password


authenticated = None


def init_store(args) -> None:
migrate_DB()
#WARNING: remove this if statement block
db.execute('SELECT username FROM users;')
# WARNING: remove this if statement block
db.execute('SELECT username FROM users;')
username = args.username
if ((username,) not in db.fetchall()):
print("create a strong and memorable password\nguide: https://anonymousplanet.org/guide.html#appendix-a2-guidelines-for-passwords-and-passphrases\n")
print(
"""
create a strong and memorable password\n
guide: https://anonymousplanet.org/guide.html#appendix-a2-guidelines-for-passwords-and-passphrases\n
"""
)
password = password = input("Enter Master Password: ")
register_user(username, password)
global authenticated
authenticated = True
else:
#TODO: remove this when complete
# TODO: remove this when complete
print("Username exit")
exit()


def main() -> None:
global authenticated
args = parse_arguments()
if ((args.password != None and args.username != None)):
if ((args.password is not None and args.username is not None)):
password = args.password
authenticate_user(args.username, password)
elif (args.username != None and args.password == None):
elif (args.username is not None and args.password is None):
password = input("Enter Master Password: ")
args.password = password
authenticate_user(args.username, password)

authenticated = True
Expand All @@ -42,9 +51,9 @@ def main() -> None:
banner = r"""
__ __ _ ______ __
\ \ / /_ _ _ __ __| | ___ _ __ | _ \ \ / /
\ \ /\ / / _` | '__/ _` |/ _ \ '_ \| |_) \ V /
\ V V / (_| | | | (_| | __/ | | | __/ | |
\_/\_/ \__,_|_| \__,_|\___|_| |_|_| |_|
\ \ /\ / / _` | '__/ _` |/ _ \ '_ \| |_) \ V /
\ V V / (_| | | | (_| | __/ | | | __/ | |
\_/\_/ \__,_|_| \__,_|\___|_| |_|_| |_|
-- created by supun
type .help for help and x or .exit to exit.
Expand All @@ -53,30 +62,35 @@ def main() -> None:
3.) List Passwords [L]
"""
print(banner)
while True:
user_input = input('> ')
if user_input.upper() == '.CLEAR':
os.system('clear')
if user_input == '?' or user_input.upper() == '.HELP':
print(help_msg)
if user_input == '1' or user_input.upper() == 'A' or user_input.upper() == '.ADD':
site = input(".add website_url > ")
site_pass = input(".add password (leave this blank for random password) > ")
if not site_pass:
site_pass = generate_password()
add_password(
args.username, args.password, site, site_pass
)
if user_input == '2' or user_input.upper() == 'S' or user_input.upper() == '.SEARCH':
site = input(".search > ")
get_password(args.username, args.password, site)

if user_input == '3' or user_input.upper() == 'L' or user_input.upper() == '.LIST':
list_passwords(
args.username, args.password
)
if user_input.upper() == 'X' or user_input.upper() == '.EXIT':
break
main_logic(args)


def main_logic(args):
while True:
user_input = input('> ')
if user_input.upper() == '.CLEAR':
os.system('clear')
if user_input == '?' or user_input.upper() == '.HELP':
print(help_msg)
if user_input == '1' or user_input.upper() == 'A' or user_input.upper() == '.ADD':
site = input(".add website_url > ")
site_pass = input(".add password (leave this blank for random password) > ")
if not site_pass:
site_pass = generate_password()
add_password(
args.username, args.password, site, site_pass
)
if user_input == '2' or user_input.upper() == 'S' or user_input.upper() == '.SEARCH':
site = input(".search > ")
get_password(args.username, args.password, site)

if user_input == '3' or user_input.upper() == 'L' or user_input.upper() == '.LIST':
list_passwords(
args.username, args.password
)
if user_input.upper() == 'X' or user_input.upper() == '.EXIT':
break


def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser()
Expand All @@ -87,7 +101,7 @@ def parse_arguments() -> argparse.Namespace:
parser.add_argument("-p", "--password", help="use the password given here")
parser.add_argument("-a", "--add", help="add password")

init_parser = subparser.add_parser("init",aliases="i", help="Inizialize password repo")
init_parser = subparser.add_parser("init", aliases="i", help="Inizialize password repo")
init_parser.add_argument('username', help='username for initialize the password store')
init_parser.set_defaults(func=init_store)
subparser.add_parser("new", help="Inizialize new password repo").set_defaults(func=init_store)
Expand All @@ -97,7 +111,8 @@ def parse_arguments() -> argparse.Namespace:
args.func(args)
return args

help_msg ="""

help_msg = """
.help, ? Show this menu
.clear Clear the screen
.add, A|a Add a password to the vault
Expand Down
2 changes: 2 additions & 0 deletions db.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import sqlite3


def create_sqlite_connection():
conn = sqlite3.connect('db.sqlite3')
cursor = conn.cursor()
return cursor


db = create_sqlite_connection()
200 changes: 101 additions & 99 deletions libwardenpy/funtionality.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,84 +3,84 @@
import sqlite3
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305


def add_password(username: str, master_password: str, site: str, password: str):
"""Add an encrypted password for a site."""
key = authenticate_user(username, master_password)
if not key:
return
# Generate a random nonce
nonce = secrets.token_bytes(12)
# Create cipher instance
cipher = ChaCha20Poly1305(key)
# Encrypt the password
encrypted_password = cipher.encrypt(nonce, password.encode(), None)
with sqlite3.connect('db.sqlite3') as conn:
conn.execute(
"INSERT INTO passwords (username, site, encrypted_password, nonce) VALUES (?, ?, ?, ?)",
(username, site, encrypted_password, nonce)
)
print(f"Password for {site} stored successfully!")
"""Add an encrypted password for a site."""
key = authenticate_user(username, master_password)
if not key:
return
# Generate a random nonce
nonce = secrets.token_bytes(12)
# Create cipher instance
cipher = ChaCha20Poly1305(key)
# Encrypt the password
encrypted_password = cipher.encrypt(nonce, password.encode(), None)
with sqlite3.connect('db.sqlite3') as conn:
conn.execute(
"INSERT INTO passwords (username, site, encrypted_password, nonce) VALUES (?, ?, ?, ?)",
(username, site, encrypted_password, nonce)
)
print(f"Password for {site} stored successfully!")


def get_password(username: str, master_password: str, site: str):
"""Retrieve and decrypt password for a site."""
key = authenticate_user(username, master_password)
if not key:
"""Retrieve and decrypt password for a site."""
key = authenticate_user(username, master_password)
if not key:
return
with sqlite3.connect('db.sqlite3') as conn:
cursor = conn.execute(
"SELECT site, encrypted_password, nonce FROM passwords WHERE username = ? AND site LIKE ?",
(username, f'%{site}%')
)
result = cursor.fetchall()
# new_result = cursor.fetchall()

if not result:
print(f"No password found for {site}")
return
with sqlite3.connect('db.sqlite3') as conn:
cursor = conn.execute(
"SELECT site, encrypted_password, nonce FROM passwords WHERE username = ? AND site LIKE ?",
(username, f'%{site}%')
)
result = cursor.fetchall()
# new_result = cursor.fetchall()

if not result:
print(f"No password found for {site}")
return
for entryies in result:
site, encrypted_password, nonce = entryies
cipher = ChaCha20Poly1305(key)
try:
decrypted_password = cipher.decrypt(
nonce,
encrypted_password,
None
)
print(f"----------\nsite:{site}\npassword: {decrypted_password.decode('utf-8')}")
except Exception as e:
print(f"Error decrypting password: {e}")
return None

for entryies in result:
site, encrypted_password, nonce = entryies
cipher = ChaCha20Poly1305(key)

try:
decrypted_password = cipher.decrypt(
nonce,
encrypted_password,
None
)
print(f"----------\nsite:{site}\npassword: {decrypted_password.decode("utf-8")}")
except Exception as e:
print(f"Error decrypting password: {e}")
return None

def list_passwords(username: str, master_password: str):
"""Retrieve and decrypt password for a site."""
key = authenticate_user(username, master_password)
if not key:
"""Retrieve and decrypt password for a site."""
key = authenticate_user(username, master_password)
if not key:
return
with sqlite3.connect('db.sqlite3') as conn:
cursor = conn.execute(
"SELECT encrypted_password, nonce, site FROM passwords WHERE username = ?;",
(username,)
)
result = cursor.fetchall()
if not result:
print(f"No password found for {username}")
return
with sqlite3.connect('db.sqlite3') as conn:
cursor = conn.execute(
"SELECT encrypted_password, nonce, site FROM passwords WHERE username = ?;",
(username,)
)
result = cursor.fetchall()

if not result:
print(f"No password found for {username}")
return

cipher = ChaCha20Poly1305(key)
for entry in result:
encrypted_password, nonce, site = entry
try:
decrypted_password = cipher.decrypt(
nonce,
encrypted_password,
None
)
print(f"----------\nsite:{site}\npassword: {decrypted_password.decode("utf-8")}")
except Exception as e:
print(f"Error decrypting password: {e}")
cipher = ChaCha20Poly1305(key)
for entry in result:
encrypted_password, nonce, site = entry
try:
decrypted_password = cipher.decrypt(
nonce,
encrypted_password,
None
)
print(f"----------\nsite:{site}\npassword: {decrypted_password.decode('utf-8')}")
except Exception as e:
print(f"Error decrypting password: {e}")


def register_user(username: str, master_password: str):
Expand All @@ -98,36 +98,38 @@ def register_user(username: str, master_password: str):
except sqlite3.IntegrityError:
print("Username already exists!")


def authenticate_user(username: str, master_password: str):
"""Authenticate user and return encryption key if successful."""
with sqlite3.connect('db.sqlite3') as conn:
cursor = conn.execute(
"SELECT password_hash, salt FROM users WHERE username = ?",
(username,)
)
result = cursor.fetchone()
if not result:
print("User not found!")
exit()
return None
stored_hash, salt = result
try:
argon2.PasswordHasher().verify(stored_hash, master_password)
# If verification succeeds, derive the encryption key
return derive_key(master_password, salt)
except argon2.exceptions.VerifyMismatchError as err:
print(f"Incorrect password! {err}")
return None
"""Authenticate user and return encryption key if successful."""
with sqlite3.connect('db.sqlite3') as conn:
cursor = conn.execute(
"SELECT password_hash, salt FROM users WHERE username = ?",
(username,)
)
result = cursor.fetchone()
if not result:
print("User not found!")
exit()
return None
stored_hash, salt = result
try:
argon2.PasswordHasher().verify(stored_hash, master_password)
# If verification succeeds, derive the encryption key
return derive_key(master_password, salt)
except argon2.exceptions.VerifyMismatchError as err:
print(f"Incorrect password! {err}")
return None


def derive_key(master_password: str, salt: bytes):
"""Derive encryption key from master password using Argon2. using ARGON2ID versino"""
hasher = argon2.low_level.hash_secret_raw(
secret=master_password.encode(),
salt=salt,
time_cost=3,
memory_cost=65536,
parallelism=4,
hash_len=32,
type=argon2.low_level.Type.ID
)
return hasher
"""Derive encryption key from master password using Argon2. using ARGON2ID versino"""
hasher = argon2.low_level.hash_secret_raw(
secret=master_password.encode(),
salt=salt,
time_cost=3,
memory_cost=65536,
parallelism=4,
hash_len=32,
type=argon2.low_level.Type.ID
)
return hasher
7 changes: 4 additions & 3 deletions libwardenpy/migrations.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import os
import sqlite3


def migrate_DB():
filenames = next(os.walk("migrations/"))[2]
for file in filenames:
with open(f'migrations/{file}','r') as file:
with open(f'migrations/{file}', 'r') as file:
query = file.read()
try:
with sqlite3.connect('db.sqlite3') as con:
con.execute(query)

# TODO: make this sqlite3.Error type later
except:
print("Some thing is worng with the migration query?")
except sqlite3.Error as err:
print(f"Some thing is worng with the migration query?\nError -> {err}")
Loading

0 comments on commit 24bca45

Please sign in to comment.