Files
server/server/authentication.py
DESKTOP-DPA61F8\Benedek 81211b1dd5
All checks were successful
continuous-integration/drone/push Build is passing
On running test the sript generates 3 user where password == username
->  user1: 'alma' with passphrase: 'amla'
    ->  user2: 'citrom' with passphrase: 'mortic'
    ->  user1: 'dinnye' with passphrase: 'eynnid'

The private keys are envrypted in DER format with pkcs#8 using the passphrase.
The private keys are temporarly stored under config/{homeDir}
The public keys are stored in the config file without encryption
2021-04-18 18:59:01 +02:00

136 lines
5.3 KiB
Python

import json
import logging
import os
import shutil
import sys
from base64 import b64encode
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from Crypto.Protocol.KDF import bcrypt, bcrypt_check
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 + "\\home"
CONFIG_DIRECTORY_LOCATION = ABSOLUTE_PATH + "\\config"
PRIVATE_KEY_DIRECTORY_LOCATION = CONFIG_DIRECTORY_LOCATION + "\\private_keys"
USER_INDEX = 0
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)
if not os.path.isfile(self.CONFIG_DIRECTORY_LOCATION + "\\config.txt") or os.stat(
self.CONFIG_DIRECTORY_LOCATION + "\\config.txt").st_size == 0:
data = {'index': 0, 'user': []}
with open(self.CONFIG_DIRECTORY_LOCATION + "\\config.txt", 'w+') as outfile:
json.dump(data, outfile)
def login(self, username: str, password: str) -> str:
with open(self.CONFIG_DIRECTORY_LOCATION + '\\config.txt') as json_file:
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'))
except ValueError:
auth_logger.debug("User NOT logged in: " + username)
return ''
auth_logger.debug("User logged in: " + username)
return user['homeDir']
def checkUserExists(self, username: str) -> bool:
with open(self.CONFIG_DIRECTORY_LOCATION + '\\config.txt') as json_file:
data = json.load(json_file)
for user in data['user']:
if username == user['username']:
return True
return False
def initConfig(self):
data = {'index': 0, 'user': []}
with open(self.CONFIG_DIRECTORY_LOCATION + "\\config.txt", 'w+') as outfile:
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)
def generatePrivateKeyForUser(self, username:str, user_passphrase:str) -> bool:
if self.checkUserExists(username):
with open(self.CONFIG_DIRECTORY_LOCATION + '\\config.txt') as json_file:
data = json.load(json_file)
private_key = RSA.generate(2048)
public_key = private_key.publickey()
private_key_value = str(private_key.export_key('DER', passphrase=user_passphrase, pkcs=8))
public_key_value = str(public_key.export_key('DER', pkcs=8))
##Save private key in separate file
user_privatekey = {'passphrase': user_passphrase, 'privateKey': private_key_value}
with open(self.PRIVATE_KEY_DIRECTORY_LOCATION + '\\' + str(data['index']) + '.txt', 'w+') as outfile:
json.dump(user_privatekey, outfile)
##Save public key in users
for user in data['user']:
if username == user['username']:
user['publicKey'] = public_key_value
with open(self.CONFIG_DIRECTORY_LOCATION + '\\config.txt', 'w') as outfile:
json.dump(data, outfile)
break
return True
else:
return False
def saveUser(self, username: str, password: str) -> bool:
bytePass = password.encode('utf-8')
b64pwd = b64encode(SHA256.new(bytePass).digest())
bcrypt_hash = bcrypt(b64pwd, 12)
with open(self.CONFIG_DIRECTORY_LOCATION + '\\config.txt') as json_file:
data = json.load(json_file)
if self.checkUserExists(username):
auth_logger.debug("User NOT saved! This username already exists!")
return False
else:
if not os.path.isdir(self.HOME_DIRECTORY_LOCATION + "\\" + 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
os.mkdir(self.HOME_DIRECTORY_LOCATION + '\\' + str(data['index']))
##Save user data
data['user'].append(user)
with open(self.CONFIG_DIRECTORY_LOCATION + '\\config.txt', 'w') as outfile:
json.dump(data, outfile)
auth_logger.debug("User saved!")
else:
auth_logger.debug("User NOT saved! Home directory already exists")
return True