seg/trabalho4/service.py

77 lines
1.8 KiB
Python
Raw Normal View History

2023-10-22 19:56:01 +00:00
from common import *
from AES import AESCipher
from random import randint
2023-10-31 21:31:12 +00:00
import socket
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 = SERVICE_PORT
2023-10-23 20:26:05 +00:00
SERVICE_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":
return f"{base64.b64encode(SERVICE_KEY)}"
2023-10-22 19:56:01 +00:00
if message[0] == "request":
"""
T_c_s = {ID_C + T_A + K_c_s}K_s
M5 = [{ID_C + T_A + S_R + N3}K_c_s + T_c_s]
M6 = [{Resposta, N3}K_c_s]
"""
2023-10-22 20:15:12 +00:00
body = message[1].split("<>")
2023-10-23 20:26:05 +00:00
K_s = SERVICE_KEY
2023-10-22 19:56:01 +00:00
T_c_s_AES = AESCipher(K_s)
M5_inner = body[0]
T_c_s = body[1]
T_c_s = T_c_s_AES.decrypt(T_c_s)
2023-10-22 20:15:12 +00:00
T_c_s = T_c_s.split("<>")
2023-10-22 19:56:01 +00:00
ID_C = T_c_s[0]
T_A = T_c_s[1]
2023-10-31 21:31:12 +00:00
if int(T_A) < int(time.time()):
print("Invalid ticket [expired]")
return "Invalid ticket [expired]"
2023-10-22 20:15:12 +00:00
K_c_s = eval(T_c_s[2])
2023-10-22 19:56:01 +00:00
M5_inner_AES = AESCipher(K_c_s)
M5_inner = M5_inner_AES.decrypt(M5_inner)
2023-10-22 20:15:12 +00:00
M5_inner = M5_inner.split("<>")
2023-10-22 19:56:01 +00:00
ID_S = M5_inner[2]
N3 = M5_inner[3]
# generate M6
2023-10-31 21:31:12 +00:00
message = "OPEN"
M6_inner = f"{message}<>{N3}"
2023-10-22 19:56:01 +00:00
M6_inner_AES = AESCipher(K_c_s)
M6_inner = M6_inner_AES.encrypt(M6_inner)
2023-10-31 21:31:12 +00:00
print("Sending M6", f"[{message}<>{N3}]")
2023-10-22 19:56:01 +00:00
M6 = f"{M6_inner}"
return M6
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()