Compare commits
32 Commits
206b7ed2f3
...
master
Author | SHA1 | Date | |
---|---|---|---|
f65db31c12 | |||
e7c4945ae9 | |||
94fcda4c2c | |||
c40e59ceb9 | |||
57af60ee07 | |||
48fd34117d
|
|||
d66cd15ec9
|
|||
863a42e982 | |||
92c0f4a90a | |||
098e279eb8
|
|||
25fbb03259
|
|||
1e54e17cea
|
|||
3a20592cff
|
|||
01e26bf6c5
|
|||
4faf9a970a | |||
5b22b75e8d
|
|||
78d597425d
|
|||
ce4fd0cd30
|
|||
12dd07c749
|
|||
e8ab5d0ddd
|
|||
58606caf3f
|
|||
862c1f17af
|
|||
3c9c224cf0 | |||
e7e2ee4a00 | |||
50a280b576 | |||
f8b947690b
|
|||
7ba66b638b
|
|||
8a4174c6e7
|
|||
a247271021
|
|||
bfb7e26d27
|
|||
e37fbd929b
|
|||
2fc4a1f752
|
@ -11,6 +11,8 @@ from netwrapper import NetWrapper
|
||||
ABSOLUTE_PATH = os.path.abspath(os.path.dirname(sys.argv[0]))
|
||||
DOWNLOAD_LOCATION = ABSOLUTE_PATH + os.path.sep + 'download' + os.path.sep
|
||||
CONFIG_LOCATION = ABSOLUTE_PATH + os.path.sep + 'config' + os.path.sep + 'config.txt'
|
||||
PASSPHRASE = ''
|
||||
SERVER_ADDRESS = ''
|
||||
LOGGED_IN = False
|
||||
|
||||
|
||||
@ -50,10 +52,11 @@ def loadAddress() -> str:
|
||||
def printCommand():
|
||||
print('\nInvalid command! Available commands:\n' +
|
||||
' Create directory -> MKD <directory name> \n' +
|
||||
' Remove directory -> RMV <directory name> \n' +
|
||||
' Remove directory -> RMD <directory name> \n' +
|
||||
' Get current directory -> GWD \n' +
|
||||
' Change current directory -> CWD <path> \n' +
|
||||
' List content of current directory -> LST \n' +
|
||||
' Remove file from current directory -> RMF <filename> \n' +
|
||||
' Upload file to current directory -> UPL <filename> \n' +
|
||||
' Download file from current directory -> DNL <filename> \n' +
|
||||
' Login -> LIN <username> <password> \n' +
|
||||
@ -67,7 +70,7 @@ def printCommandsWihtoutLogin():
|
||||
|
||||
|
||||
try:
|
||||
opts, args = getopt.getopt(sys.argv[1:], 'hp:')
|
||||
opts, args = getopt.getopt(sys.argv[1:], 'hp:s:')
|
||||
except getopt.GetoptError:
|
||||
print('Error: Unknown option detected.')
|
||||
sys.exit(1)
|
||||
@ -76,10 +79,13 @@ for opt, arg in opts:
|
||||
if opt in '-p':
|
||||
PASSPHRASE = arg
|
||||
|
||||
if opt in '-s':
|
||||
SERVER_ADDRESS = arg
|
||||
|
||||
if PASSPHRASE == '':
|
||||
print('Key required to start client!')
|
||||
print('Usage:')
|
||||
print(' client.py -p <passphrase>')
|
||||
print(' client.py -p <passphrase> -s <server_address>')
|
||||
sys.exit(1)
|
||||
|
||||
if not os.path.isfile(CONFIG_LOCATION) or os.stat(CONFIG_LOCATION).st_size == 0:
|
||||
@ -89,6 +95,9 @@ if not os.path.isfile(CONFIG_LOCATION) or os.stat(CONFIG_LOCATION).st_size == 0:
|
||||
SERVER_PUBLIC_KEY = loadPublicKey()
|
||||
CLIENT_PRIVATE_KEY = loadPrivateKey(PASSPHRASE)
|
||||
CLIENT_ADDRESS = loadAddress()
|
||||
LOGGED_IN = False
|
||||
|
||||
network = NetWrapper(CLIENT_PRIVATE_KEY, CLIENT_ADDRESS, SERVER_PUBLIC_KEY, serverAddr=SERVER_ADDRESS)
|
||||
|
||||
while True:
|
||||
command = input("Type a command:")
|
||||
@ -99,15 +108,24 @@ while True:
|
||||
print("Invalid command format!")
|
||||
continue
|
||||
|
||||
if separatedCommand[0] == 'LIN' and len(separatedCommand) == 3:
|
||||
network = NetWrapper(CLIENT_PRIVATE_KEY, CLIENT_ADDRESS, separatedCommand[1], SERVER_PUBLIC_KEY)
|
||||
try:
|
||||
network.connectToServer()
|
||||
except Exception as e:
|
||||
print("Error: "+str(e))
|
||||
if not LOGGED_IN:
|
||||
if separatedCommand[0] == 'LIN' and len(separatedCommand) == 3:
|
||||
network.username = separatedCommand[1]
|
||||
try:
|
||||
network.connectToServer(separatedCommand[2])
|
||||
response = network.recieveMessage().decode('UTF-8')
|
||||
print(response)
|
||||
if response == 'OK':
|
||||
LOGGED_IN = True
|
||||
else:
|
||||
LOGGED_IN = False
|
||||
except Exception as e:
|
||||
print("Error: "+str(e))
|
||||
LOGGED_IN = False
|
||||
continue
|
||||
LOGGED_IN = True
|
||||
continue
|
||||
else:
|
||||
print('You are already logged in!')
|
||||
|
||||
|
||||
if separatedCommand[0] == 'EXIT':
|
||||
sys.exit(1)
|
||||
@ -119,6 +137,7 @@ while True:
|
||||
if separatedCommand[0] == 'LOUT' and len(separatedCommand) == 1:
|
||||
network.sendMessage(command.encode('UTF-8'))
|
||||
print(network.recieveMessage().decode('UTF-8'))
|
||||
LOGGED_IN = False
|
||||
continue
|
||||
|
||||
if separatedCommand[0] == 'MKD' and len(separatedCommand) == 2:
|
||||
@ -146,13 +165,18 @@ while True:
|
||||
print(network.recieveMessage().decode('UTF-8'))
|
||||
continue
|
||||
|
||||
if separatedCommand[0] == 'RMF' and len(separatedCommand) == 2:
|
||||
network.sendMessage(command.encode('UTF-8'))
|
||||
print(network.recieveMessage().decode('UTF-8'))
|
||||
continue
|
||||
|
||||
if separatedCommand[0] == 'UPL' and len(separatedCommand) == 2:
|
||||
if os.path.isfile(separatedCommand[1]):
|
||||
cmd = 'UPL ' + separatedCommand[1].split(os.path.sep)[-1]
|
||||
network.sendMessage(cmd.encode('UTF-8'))
|
||||
|
||||
with open(separatedCommand[1], "rb") as file:
|
||||
network.sendMessage(file.readlines())
|
||||
network.sendMessage(file.read())
|
||||
|
||||
network.sendMessage('EOF'.encode('UTF-8'))
|
||||
response = network.recieveMessage().decode('UTF-8')
|
||||
@ -166,12 +190,15 @@ while True:
|
||||
dnlFilename = separatedCommand[1].split(os.path.sep)[-1]
|
||||
cmd = 'DNL ' + dnlFilename
|
||||
network.sendMessage(cmd.encode('UTF-8'))
|
||||
file = network.recieveMessage().decode('UTF-8')
|
||||
filecontent = network.recieveMessage()
|
||||
response = network.recieveMessage().decode('UTF-8')
|
||||
|
||||
if response == 'OK':
|
||||
print(DOWNLOAD_LOCATION + dnlFilename)
|
||||
|
||||
if response == 'EOF':
|
||||
with open(DOWNLOAD_LOCATION + dnlFilename, "wb+") as file:
|
||||
file.writelines(file)
|
||||
file.write(filecontent)
|
||||
print('OK')
|
||||
else:
|
||||
print(response)
|
||||
|
||||
@ -181,3 +208,4 @@ while True:
|
||||
|
||||
except Exception as e:
|
||||
print('Error: ' + str(e))
|
||||
continue
|
||||
|
File diff suppressed because one or more lines are too long
@ -1,4 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("hi")
|
@ -4,17 +4,17 @@ import string
|
||||
import json
|
||||
from base64 import b64encode, b64decode
|
||||
import pyDH
|
||||
from Crypto.Cipher import ChaCha20, PKCS1_OAEP
|
||||
from Crypto.Hash import SHA512
|
||||
from Crypto.Cipher import ChaCha20_Poly1305, PKCS1_OAEP
|
||||
from Crypto.PublicKey.RSA import RsaKey
|
||||
from Crypto.Random import get_random_bytes
|
||||
from Crypto.Signature import pkcs1_15
|
||||
|
||||
from netsim import network_interface
|
||||
|
||||
|
||||
class NetWrapper:
|
||||
def __init__(self, privateKey: RsaKey, clientAddress: str, username: str, serverPubKey: RsaKey,
|
||||
def __init__(self, privateKey: RsaKey, clientAddress: str, serverPubKey: RsaKey, username: str = "",
|
||||
serverAddr: str = 'A'):
|
||||
# Create network_interface: network_interface(path, addr) path root is shared with network / addr is own address
|
||||
self.network = network_interface('./../../netsim/network/', clientAddress)
|
||||
self.serverAddr = serverAddr
|
||||
self.username = username
|
||||
@ -22,106 +22,138 @@ class NetWrapper:
|
||||
self.serverPubKey = serverPubKey
|
||||
self.cipherkey = "".encode('UTF-8')
|
||||
|
||||
|
||||
def randomStringGenerator(self, str_size: int = 128,
|
||||
def randomStringGenerator(self, str_size: int = 256,
|
||||
allowed_chars: str = string.ascii_letters + string.punctuation) -> str:
|
||||
return ''.join(random.choice(allowed_chars) for x in range(str_size))
|
||||
|
||||
def ecryptRSAMessage(self, message: bytes) -> bytes:
|
||||
cipher_rsa = PKCS1_OAEP.new(self.serverPubKey)
|
||||
encrypted_msg = cipher_rsa.encrypt(message)
|
||||
return encrypted_msg
|
||||
|
||||
def signRSAHeader(self, type: str, extradata: dict) -> (bytes, bytes):
|
||||
mandatory = {'type': type, 'source': self.network.own_addr}
|
||||
header = json.dumps({**mandatory, **extradata}).encode('UTF-8')
|
||||
h = SHA512.new(header)
|
||||
headersignature = pkcs1_15.new(self.privateKey).sign(h)
|
||||
return header, headersignature
|
||||
|
||||
def verifyRSAHeaderSignature(self, header: bytes, headersignature: bytes) -> bool:
|
||||
h = SHA512.new(header)
|
||||
try:
|
||||
pkcs1_15.new(self.serverPubKey).verify(h, headersignature)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def decryptRSAMessage(self, message: bytes) -> bytes:
|
||||
cipher_rsa = PKCS1_OAEP.new(self.privateKey)
|
||||
return cipher_rsa.decrypt(message)
|
||||
|
||||
def recieveAndUnpackRSAMessage(self) -> (str, str):
|
||||
status, msg = self.network.receive_msg(blocking=True)
|
||||
if not status:
|
||||
raise Exception('Network error during connection.')
|
||||
decodedmsg = json.loads(msg.decode('UTF-8'))
|
||||
return decodedmsg, json.loads(b64decode(decodedmsg['header']).decode('UTF-8'))
|
||||
|
||||
def identifyServer(self) -> bool:
|
||||
randommsg = self.randomStringGenerator()
|
||||
cipher_rsa = PKCS1_OAEP.new(self.serverPubKey)
|
||||
encrypted_msg = self.ecryptRSAMessage(randommsg.encode('UTF-8'))
|
||||
header, headersignature = self.signRSAHeader('IDY', {'username': self.username})
|
||||
identMsg = json.dumps(
|
||||
{'type': 'IDY', 'source': self.network.own_addr, 'username': self.username,
|
||||
'message': b64encode(cipher_rsa.encrypt(randommsg.encode('UTF-8'))).decode('ASCII')}).encode(
|
||||
{'header': b64encode(header).decode('UTF-8'),
|
||||
'message': b64encode(encrypted_msg).decode('UTF-8'),
|
||||
'headersignature': b64encode(headersignature).decode('UTF-8')}).encode(
|
||||
'UTF-8')
|
||||
self.network.send_msg(self.serverAddr, identMsg)
|
||||
returnJson = {'source': '', 'type': ''}
|
||||
while not (returnJson['source'] == self.serverAddr and returnJson['type'] == 'IDY'):
|
||||
status, msg = self.network.receive_msg(blocking=True)
|
||||
if not status:
|
||||
raise Exception('Network error during connection.')
|
||||
returnJson = json.loads(msg.decode('UTF-8'))
|
||||
cipher_rsa = PKCS1_OAEP.new(self.privateKey)
|
||||
retmsg = cipher_rsa.decrypt(b64decode(returnJson['message'])).decode('UTF-8')
|
||||
returnJson, header = self.recieveAndUnpackRSAMessage()
|
||||
try:
|
||||
if not self.verifyRSAHeaderSignature(b64decode(returnJson['header']),
|
||||
b64decode(returnJson['headersignature'])) or not (
|
||||
header['source'] == self.serverAddr and header['type'] == 'IDY'):
|
||||
return False
|
||||
retmsg = self.decryptRSAMessage(b64decode(returnJson['message'])).decode('UTF-8')
|
||||
except Exception:
|
||||
return False
|
||||
return retmsg == randommsg
|
||||
|
||||
|
||||
def createEncryptedChannel(self):
|
||||
def createEncryptedChannel(self) -> None:
|
||||
dh = pyDH.DiffieHellman()
|
||||
cipher_rsa = PKCS1_OAEP.new(self.serverPubKey)
|
||||
mypubkey = b64encode(cipher_rsa.encrypt(str(dh.gen_public_key()).encode('UTF-8'))).decode('ASCII')
|
||||
jsonmsg = json.dumps({'type': 'DH', 'source': self.network.own_addr, 'message': mypubkey}).encode('UTF-8')
|
||||
mypubkey = self.ecryptRSAMessage(str(dh.gen_public_key()).encode('UTF-8'))
|
||||
header, headersignature = self.signRSAHeader("DH",{})
|
||||
jsonmsg = json.dumps(
|
||||
{'header': b64encode(header).decode('UTF-8'), 'headersignature': b64encode(headersignature).decode('UTF-8'),
|
||||
'message': b64encode(mypubkey).decode('UTF-8')}).encode('UTF-8')
|
||||
self.network.send_msg(self.serverAddr, jsonmsg)
|
||||
decodedmsg = {'source': '', 'type': ''}
|
||||
while not (decodedmsg['source'] == self.serverAddr and decodedmsg['type'] == 'DH'):
|
||||
status, msg = self.network.receive_msg(blocking=True)
|
||||
if not status:
|
||||
raise Exception('Network error during connection.')
|
||||
decodedmsg = json.loads(msg.decode('UTF-8'))
|
||||
cipher_rsa = PKCS1_OAEP.new(self.privateKey)
|
||||
serverpubkey = int(cipher_rsa.decrypt(b64decode(decodedmsg['message'])).decode('UTF-8'))
|
||||
self.cipherkey = dh.gen_shared_key(serverpubkey).encode('UTF-8')
|
||||
decodedmsg, header = self.recieveAndUnpackRSAMessage()
|
||||
if not self.verifyRSAHeaderSignature(b64decode(decodedmsg['header']),
|
||||
b64decode(decodedmsg['headersignature'])) or not (
|
||||
header['source'] == self.serverAddr and header['type'] == 'DH'):
|
||||
raise Exception('Header signature error')
|
||||
serverpubkey = int(self.decryptRSAMessage(b64decode(decodedmsg['message'])).decode('UTF-8'))
|
||||
cipherkey = dh.gen_shared_key(serverpubkey).encode('UTF-8')
|
||||
hasher = SHA512.new()
|
||||
hasher.update(cipherkey)
|
||||
self.cipherkey = (hasher.hexdigest()[:32]).encode('UTF-8')
|
||||
|
||||
|
||||
def authenticate(self, password: str):
|
||||
def authenticate(self, password: str) -> None:
|
||||
message = f"LIN {self.username} {password}".encode('UTF-8')
|
||||
cipher = ChaCha20.new(key=self.cipherkey, nonce=get_random_bytes(12))
|
||||
ciphertext = cipher.encrypt(message)
|
||||
nonce = b64encode(cipher.nonce).decode('ASCII')
|
||||
ct = b64encode(ciphertext).decode('ASCII')
|
||||
sendjson = json.dumps({'type': 'AUT', 'source': self.network.own_addr, 'nonce': nonce, 'message': ct}).encode(
|
||||
'UTF-8')
|
||||
self.network.send_msg(self.serverAddr, sendjson)
|
||||
b64 = {'source': '', 'type': ''}
|
||||
while not (b64['source'] == self.serverAddr and b64['type'] == 'AUT'):
|
||||
status, msg = self.network.receive_msg(blocking=True)
|
||||
if not status:
|
||||
raise Exception('Network error during connection.')
|
||||
b64 = json.loads(msg.decode('UTF-8'))
|
||||
try:
|
||||
retnonce = b64decode(b64['nonce'])
|
||||
retciphertext = b64decode(b64['message'])
|
||||
retcipher = ChaCha20.new(self.cipherkey, nonce=retnonce)
|
||||
plaintext = retcipher.decrypt(retciphertext).decode('UTF-8')
|
||||
if plaintext != "OK":
|
||||
raise Exception('Authentication error')
|
||||
except Exception:
|
||||
print("Incorrect decryption")
|
||||
self.sendTypedMessage(message, "AUT")
|
||||
plaintext = self.recieveTypedMessage("AUT").decode('UTF-8')
|
||||
if plaintext != "OK":
|
||||
print("Authentication error")
|
||||
|
||||
|
||||
def connectToServer(self):
|
||||
def connectToServer(self, password: str) -> None:
|
||||
if self.username == "":
|
||||
raise Exception('Username is not initialized')
|
||||
if password == "":
|
||||
raise Exception('Passowrd may not be empty')
|
||||
identStatus = self.identifyServer()
|
||||
if not identStatus:
|
||||
raise Exception('Server identification faliure')
|
||||
self.createEncryptedChannel()
|
||||
print('Please enter your password:')
|
||||
pw = input()
|
||||
self.authenticate(pw)
|
||||
self.authenticate(password)
|
||||
|
||||
def sendMessage(self, message: bytes) -> None:
|
||||
try:
|
||||
self.sendTypedMessage(message, "CMD")
|
||||
except Exception:
|
||||
print("Could not send message")
|
||||
|
||||
def sendMessage(self, message: bytes):
|
||||
cipher = ChaCha20.new(key=self.cipherkey, nonce=get_random_bytes(12))
|
||||
ciphertext = cipher.encrypt(message)
|
||||
nonce = b64encode(cipher.nonce).decode('ASCII')
|
||||
ct = b64encode(ciphertext).decode('ASCII')
|
||||
sendjson = json.dumps({'type': 'CMD', 'source': self.network.own_addr, 'nonce': nonce, 'message': ct}).encode(
|
||||
def sendTypedMessage(self, message: bytes, type: str) -> None:
|
||||
if not (type == "AUT" or type == "CMD"):
|
||||
raise Exception('Unknown message type')
|
||||
cipher = ChaCha20_Poly1305.new(key=self.cipherkey)
|
||||
header = json.dumps({'type': type, 'source': self.network.own_addr}).encode('UTF-8')
|
||||
cipher.update(header)
|
||||
ciphertext, tag = cipher.encrypt_and_digest(message)
|
||||
nonce = b64encode(cipher.nonce).decode('UTF-8')
|
||||
ct = b64encode(ciphertext).decode('UTF-8')
|
||||
sendjson = json.dumps({'header': b64encode(header).decode('UTF-8'), 'nonce': nonce, 'message': ct,
|
||||
'tag': b64encode(tag).decode('UTF-8')}).encode(
|
||||
'UTF-8')
|
||||
self.network.send_msg(self.serverAddr, sendjson)
|
||||
|
||||
|
||||
def recieveMessage(self) -> bytes:
|
||||
b64 = {'source': '', 'type': ''}
|
||||
while not (b64['source'] == self.serverAddr and b64['type'] == 'AUT'):
|
||||
return self.recieveTypedMessage("CMD")
|
||||
|
||||
def recieveTypedMessage(self, type: str) -> bytes:
|
||||
if not (type == "AUT" or type == "CMD"):
|
||||
raise Exception('Unknown message type')
|
||||
try:
|
||||
status, msg = self.network.receive_msg(blocking=True)
|
||||
if not status:
|
||||
raise Exception('Network error during connection.')
|
||||
b64 = json.loads(msg.decode('UTF-8'))
|
||||
try:
|
||||
retnonce = b64decode(b64['nonce'])
|
||||
retciphertext = b64decode(b64['message'])
|
||||
retcipher = ChaCha20.new(key=self.cipherkey, nonce=retnonce)
|
||||
plaintext = retcipher.decrypt(retciphertext)
|
||||
retcipher = ChaCha20_Poly1305.new(key=self.cipherkey, nonce=retnonce)
|
||||
retcipher.update(b64decode(b64['header']))
|
||||
plaintext = retcipher.decrypt_and_verify(retciphertext, b64decode(b64['tag']))
|
||||
retheader = json.loads(b64decode(b64['header']).decode('UTF-8'))
|
||||
if not (retheader['source'] == self.serverAddr and retheader['type'] == type):
|
||||
return "ERROR".encode('UTF-8')
|
||||
return plaintext
|
||||
except Exception:
|
||||
print("Incorrect decryption")
|
||||
|
Reference in New Issue
Block a user