server/server/authentication.py

149 lines
5.1 KiB
Python
Raw Normal View History

2021-04-25 17:12:20 +02:00
#!/usr/bin/env python3
2021-04-18 16:07:41 +02:00
import json
import logging
import os
import shutil
import sys
2021-04-17 19:52:58 +02:00
from base64 import b64encode
2021-04-23 17:27:41 +02:00
2021-04-17 19:52:58 +02:00
from Crypto.Hash import SHA256
from Crypto.Protocol.KDF import bcrypt, bcrypt_check
from Crypto.PublicKey import RSA
from Crypto.PublicKey.RSA import RsaKey
2021-04-17 19:52:58 +02:00
auth_logger = logging.getLogger('AUTH APPLICATION ')
auth_logger.root.setLevel(logging.INFO)
class Authetication:
ABSOLUTE_PATH = os.path.abspath(os.path.dirname(sys.argv[0]))
HOME_DIRECTORY_LOCATION = ABSOLUTE_PATH + os.path.sep + "home"
2021-04-18 22:52:14 +02:00
CONFIG_DIRECTORY_LOCATION = ABSOLUTE_PATH + os.path.sep + "config"
CONFIG_FILE_LOCATION = ABSOLUTE_PATH + os.path.sep + "config" + os.path.sep + "config.txt"
PRIVATE_KEY_DIRECTORY_LOCATION = CONFIG_DIRECTORY_LOCATION + os.path.sep + "private_keys"
2021-04-17 19:52:58 +02:00
USER_INDEX = 0
2021-04-21 18:30:18 +02:00
2021-04-17 19:52:58 +02:00
def __init__(self):
if not os.path.isdir(self.HOME_DIRECTORY_LOCATION):
os.mkdir(self.HOME_DIRECTORY_LOCATION)
if not os.path.isdir(self.CONFIG_DIRECTORY_LOCATION):
os.mkdir(self.CONFIG_DIRECTORY_LOCATION)
if not os.path.isdir(self.PRIVATE_KEY_DIRECTORY_LOCATION):
os.mkdir(self.PRIVATE_KEY_DIRECTORY_LOCATION)
2021-04-18 22:52:14 +02:00
if not os.path.isfile(self.CONFIG_FILE_LOCATION) or os.stat(
self.CONFIG_FILE_LOCATION).st_size == 0:
2021-04-18 14:23:13 +02:00
data = {'index': 0, 'user': []}
2021-04-18 22:52:14 +02:00
with open(self.CONFIG_FILE_LOCATION, 'w+') as outfile:
2021-04-17 19:52:58 +02:00
json.dump(data, outfile)
2021-04-21 18:30:18 +02:00
2021-04-18 14:23:13 +02:00
def login(self, username: str, password: str) -> str:
2021-04-18 22:52:14 +02:00
with open(self.CONFIG_FILE_LOCATION) as json_file:
2021-04-17 19:52:58 +02:00
data = json.load(json_file)
for user in data['user']:
if username == user['username']:
b64pwd = b64encode(SHA256.new(password.encode('utf-8')).digest())
try:
b64pwd = b64encode(SHA256.new(password.encode('utf-8')).digest())
bcrypt_check(b64pwd, user['password'].encode('utf-8'))
2021-04-23 18:54:05 +02:00
auth_logger.debug("User logged in: " + username)
return user['homeDir']
2021-04-17 19:52:58 +02:00
except ValueError:
auth_logger.debug("User NOT logged in: " + username)
return ''
2021-04-23 18:54:05 +02:00
else:
auth_logger.error("User not found")
return ''
2021-04-17 19:52:58 +02:00
2021-04-18 14:23:13 +02:00
def checkUserExists(self, username: str) -> bool:
2021-04-18 22:52:14 +02:00
with open(self.CONFIG_FILE_LOCATION) as json_file:
2021-04-17 19:52:58 +02:00
data = json.load(json_file)
for user in data['user']:
if username == user['username']:
return True
return False
2021-04-21 18:30:18 +02:00
2021-04-17 19:52:58 +02:00
def initConfig(self):
2021-04-18 13:36:04 +02:00
data = {'index': 0, 'user': []}
2021-04-18 22:52:14 +02:00
with open(self.CONFIG_FILE_LOCATION, 'w+') as outfile:
2021-04-17 19:52:58 +02:00
json.dump(data, outfile)
shutil.rmtree(self.HOME_DIRECTORY_LOCATION)
os.mkdir(self.HOME_DIRECTORY_LOCATION)
shutil.rmtree(self.PRIVATE_KEY_DIRECTORY_LOCATION)
os.mkdir(self.PRIVATE_KEY_DIRECTORY_LOCATION)
2021-04-18 14:23:13 +02:00
def saveUser(self, username: str, password: str) -> bool:
2021-04-17 19:52:58 +02:00
bytePass = password.encode('utf-8')
b64pwd = b64encode(SHA256.new(bytePass).digest())
bcrypt_hash = bcrypt(b64pwd, 12)
2021-04-18 22:52:14 +02:00
with open(self.CONFIG_FILE_LOCATION) as json_file:
2021-04-17 19:52:58 +02:00
data = json.load(json_file)
if self.checkUserExists(username):
auth_logger.debug("User NOT saved! This username already exists!")
return False
else:
2021-04-18 22:53:38 +02:00
if not os.path.isdir(self.HOME_DIRECTORY_LOCATION + os.path.sep + str(data['index'] + 1)):
data['index'] = data['index'] + 1
user = {
'username': username,
'password': bcrypt_hash.decode('utf-8'),
'homeDir': str(data['index']),
'publicKey': ''
}
##Create user HOME directory with index as name
2021-04-18 22:53:38 +02:00
os.mkdir(self.HOME_DIRECTORY_LOCATION + os.path.sep + str(data['index']))
##Save user data
2021-04-17 19:52:58 +02:00
data['user'].append(user)
2021-04-18 22:52:14 +02:00
with open(self.CONFIG_FILE_LOCATION, 'w') as outfile:
2021-04-17 19:52:58 +02:00
json.dump(data, outfile)
2021-04-17 19:52:58 +02:00
auth_logger.debug("User saved!")
else:
auth_logger.debug("User NOT saved! Home directory already exists")
return True
def loadUserPublicKeys(self) -> dict:
with open(self.CONFIG_FILE_LOCATION) as json_file:
data = json.load(json_file)
dictionary: dict
for user in data['user']:
key = data['publicKey']
key = bytes.fromhex(key)
try:
rsaKey = RSA.import_key(key)
dictionary[user['username']] = rsaKey
except ValueError:
print('Invalid server public key!')
return dictionary
2021-04-25 17:45:22 +02:00
def loadServerPrivateKey(self, passphrase: str) -> RsaKey:
with open(self.CONFIG_FILE_LOCATION) as json_file:
data = json.load(json_file)
key = data['serverPrivateKey']
key = bytes.fromhex(key)
try:
2021-04-25 17:45:22 +02:00
rsaKey = RSA.import_key(key, passphrase)
except ValueError:
print('Invalid server private key!')
return rsaKey