Compare commits

..

30 Commits

Author SHA1 Message Date
f65db31c12 Config
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-30 11:00:28 +02:00
e7c4945ae9 OK
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-29 19:17:48 +02:00
94fcda4c2c RMF
Some checks failed
continuous-integration/drone/push Build is failing
2021-04-29 17:25:52 +02:00
c40e59ceb9 OK
Some checks failed
continuous-integration/drone/push Build is failing
2021-04-29 17:06:30 +02:00
57af60ee07 Server address
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 23:35:00 +02:00
48fd34117d Merge branch 'master' of https://git.kmlabz.com/BiztProtoBois/client into master
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 23:27:32 +02:00
d66cd15ec9 init 2021-04-26 23:27:17 +02:00
863a42e982 OK
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 23:25:53 +02:00
92c0f4a90a Login errors
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 23:17:34 +02:00
098e279eb8 fuckyfuck
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 22:30:12 +02:00
25fbb03259 fogyi vagyok
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 22:27:43 +02:00
1e54e17cea letssee
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 22:18:53 +02:00
3a20592cff Merge branch 'master' of https://git.kmlabz.com/BiztProtoBois/client into master
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 21:52:39 +02:00
01e26bf6c5 better append to dict 2021-04-26 21:52:29 +02:00
4faf9a970a LIN need only one param
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 21:31:46 +02:00
5b22b75e8d refactor and better crypto
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 19:32:10 +02:00
78d597425d refactor chacha
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 18:31:50 +02:00
ce4fd0cd30 fuxy wuxy
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 17:24:03 +02:00
12dd07c749 reformat code
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 17:20:14 +02:00
e8ab5d0ddd fix some stuff
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 17:15:54 +02:00
58606caf3f Merge branch 'master' of https://git.kmlabz.com/BiztProtoBois/client into master
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 16:58:27 +02:00
862c1f17af use authenticated chacha20 2021-04-26 16:58:16 +02:00
3c9c224cf0 Patch
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 14:40:48 +02:00
e7e2ee4a00 Len in LIN
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 13:51:16 +02:00
50a280b576 LIN cmd update
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 13:39:31 +02:00
f8b947690b fucking god may fuck this code
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 13:37:56 +02:00
7ba66b638b print message
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 13:35:32 +02:00
8a4174c6e7 bytes
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 00:26:53 +02:00
a247271021 pep8
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 00:23:57 +02:00
bfb7e26d27 pep8
All checks were successful
continuous-integration/drone/push Build is passing
2021-04-26 00:23:28 +02:00
4 changed files with 144 additions and 92 deletions

View File

@ -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 not LOGGED_IN:
if separatedCommand[0] == 'LIN' and len(separatedCommand) == 3:
network = NetWrapper(CLIENT_PRIVATE_KEY, CLIENT_ADDRESS, separatedCommand[1], SERVER_PUBLIC_KEY)
network.username = separatedCommand[1]
try:
network.connectToServer()
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

View File

@ -1,4 +0,0 @@
#!/usr/bin/env python3
if __name__ == '__main__':
print("hi")

View File

@ -5,17 +5,16 @@ import json
from base64 import b64encode, b64decode
import pyDH
from Crypto.Hash import SHA512
from Crypto.Cipher import ChaCha20, PKCS1_OAEP
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
@ -23,109 +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 identifyServer(self) -> bool:
randommsg = self.randomStringGenerator()
def ecryptRSAMessage(self, message: bytes) -> bytes:
cipher_rsa = PKCS1_OAEP.new(self.serverPubKey)
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(
'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'))
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)
retmsg = cipher_rsa.decrypt(b64decode(returnJson['message'])).decode('UTF-8')
return retmsg == randommsg
return cipher_rsa.decrypt(message)
def createEncryptedChannel(self):
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')
self.network.send_msg(self.serverAddr, jsonmsg)
decodedmsg = {'source': '', 'type': ''}
while not (decodedmsg['source'] == self.serverAddr and decodedmsg['type'] == 'DH'):
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'))
cipher_rsa = PKCS1_OAEP.new(self.privateKey)
serverpubkey = int(cipher_rsa.decrypt(b64decode(decodedmsg['message'])).decode('UTF-8'))
return decodedmsg, json.loads(b64decode(decodedmsg['header']).decode('UTF-8'))
def identifyServer(self) -> bool:
randommsg = self.randomStringGenerator()
encrypted_msg = self.ecryptRSAMessage(randommsg.encode('UTF-8'))
header, headersignature = self.signRSAHeader('IDY', {'username': self.username})
identMsg = json.dumps(
{'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, 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) -> None:
dh = pyDH.DiffieHellman()
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, 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]
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')
self.sendTypedMessage(message, "AUT")
plaintext = self.recieveTypedMessage("AUT").decode('UTF-8')
if plaintext != "OK":
raise Exception('Authentication error')
except Exception:
print("Incorrect decryption")
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")