seg/trabalho4/tgs.py

96 lines
2.4 KiB
Python
Raw Permalink Normal View History

2023-10-22 19:56:01 +00:00
from common import *
from AES import AESCipher
2023-10-31 21:31:12 +00:00
import socket
2023-10-22 19:56:01 +00:00
import os
2023-10-23 20:26:05 +00:00
import base64
2023-10-31 21:31:12 +00:00
import time
2023-10-22 19:56:01 +00:00
HOST = "127.0.0.1"
PORT = TGS_PORT
2023-10-23 20:26:05 +00:00
TGS_KEY = os.urandom(32)
2023-10-22 19:56:01 +00:00
def process_message(message):
message = message.split("||")
2023-10-23 20:26:05 +00:00
if message[0] == "getkey":
2023-10-31 21:31:12 +00:00
print('ktgs', TGS_KEY)
2023-10-23 20:26:05 +00:00
return f"{base64.b64encode(TGS_KEY)}"
2023-10-22 19:56:01 +00:00
if message[0] == "request":
"""
T_c_tgs = {ID_C + T_R + K_c_tgs}K_tgs
M3 = [{ID_C + ID_S + T_R + N2}K_c_tgs + T_c_tgs]
M4 = [{K_c_s + T_A + N2}K_c_tgs + T_c_s]
T_c_s = {ID_C + T_A + K_c_s}K_s
"""
2023-10-22 20:15:12 +00:00
body = message[1].split("<>")
2023-10-23 20:26:05 +00:00
K_tgs = TGS_KEY
2023-10-22 19:56:01 +00:00
M3 = body[0]
2023-10-22 20:15:12 +00:00
M3 = M3.split("<>")
2023-10-22 19:56:01 +00:00
M3_inner = M3[0]
T_c_tgs = body[1]
M3_AES = AESCipher(K_tgs)
T_c_tgs = M3_AES.decrypt(T_c_tgs)
2023-10-22 20:15:12 +00:00
T_c_tgs = T_c_tgs.split("<>")
2023-10-22 19:56:01 +00:00
ID_C = T_c_tgs[0]
T_R = int(T_c_tgs[1])
K_c_tgs = eval(T_c_tgs[2])
M3_inner_AES = AESCipher(K_c_tgs)
M3_inner = M3_inner_AES.decrypt(M3_inner)
2023-10-22 20:15:12 +00:00
M3_inner = M3_inner.split("<>")
2023-10-22 19:56:01 +00:00
ID_S = M3_inner[1]
N2 = M3_inner[3]
# generate M4
K_c_s = os.urandom(16)
T_A = 600 if T_R > 600 else T_R
2023-10-31 21:31:12 +00:00
T_A = int(time.time()) + T_A
2023-10-22 20:15:12 +00:00
T_c_s = f"{ID_C}<>{T_A}<>{K_c_s}"
2023-10-22 19:56:01 +00:00
2023-10-23 20:26:05 +00:00
K_s = get_ks()
2023-10-22 19:56:01 +00:00
T_c_s_AES = AESCipher(K_s)
T_c_s = T_c_s_AES.encrypt(T_c_s)
2023-10-22 20:15:12 +00:00
M4_inner = f"{K_c_s}<>{T_A}<>{N2}"
2023-10-22 19:56:01 +00:00
M4_inner_AES = AESCipher(K_c_tgs)
M4_inner = M4_inner_AES.encrypt(M4_inner)
2023-10-31 21:31:12 +00:00
print("Sending M4", f"[{K_c_s}<>{T_A}<>{N2}]<>[T_c_s] | T_c_s = [{ID_C}<>{T_A}<>K_c_s]")
2023-10-22 20:15:12 +00:00
M4 = f"{M4_inner}<>{T_c_s}"
2023-10-22 19:56:01 +00:00
return M4
2023-10-23 20:26:05 +00:00
def get_ks():
message = f"getkey"
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, SERVICE_PORT))
s.sendall(message.encode())
data = s.recv(4096)
data = data.decode()
key = eval(data)
key = base64.b64decode(key)
return key
2023-10-22 19:56:01 +00:00
def main():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
with conn:
all_data = ""
data = conn.recv(4096)
all_data += data.decode()
response = process_message(all_data)
conn.sendall(response.encode())
if __name__ == "__main__":
main()