seg/trabalho4/tgs.py

78 lines
1.9 KiB
Python

import socket
from common import *
import socket
from AES import AESCipher
import os
HOST = "127.0.0.1"
PORT = TGS_PORT
def process_message(message):
print(message)
message = message.split("||")
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
"""
body = message[1].split("<>")
K_tgs = C_K_tgs
M3 = body[0]
M3 = M3.split("<>")
M3_inner = M3[0]
T_c_tgs = body[1]
print('T_c_tgs', type(T_c_tgs), T_c_tgs)
M3_AES = AESCipher(K_tgs)
T_c_tgs = M3_AES.decrypt(T_c_tgs)
T_c_tgs = T_c_tgs.split("<>")
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)
M3_inner = M3_inner.split("<>")
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
T_c_s = f"{ID_C}<>{T_A}<>{K_c_s}"
K_s = C_K_s
T_c_s_AES = AESCipher(K_s)
T_c_s = T_c_s_AES.encrypt(T_c_s)
M4_inner = f"{K_c_s}<>{T_A}<>{N2}"
M4_inner_AES = AESCipher(K_c_tgs)
M4_inner = M4_inner_AES.encrypt(M4_inner)
M4 = f"{M4_inner}<>{T_c_s}"
return M4
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:
print(f"Connected by {addr}")
all_data = ""
data = conn.recv(4096)
all_data += data.decode()
response = process_message(all_data)
conn.sendall(response.encode())
if __name__ == "__main__":
main()