From 050c90c326aef2da887a5d8cc20719ef9126f294 Mon Sep 17 00:00:00 2001
From: "Ion-Dorinel FILIP (25005)" <dorinel.filip@upb.ro>
Date: Wed, 31 May 2023 13:04:57 +0000
Subject: [PATCH] Added lab12 code

---
 lab12/https_server.py | 24 ++++++++++++++++++++++++
 lab12/ssl_client.py   | 34 ++++++++++++++++++++++++++++++++++
 2 files changed, 58 insertions(+)
 create mode 100644 lab12/https_server.py
 create mode 100644 lab12/ssl_client.py

diff --git a/lab12/https_server.py b/lab12/https_server.py
new file mode 100644
index 0000000..3b5649d
--- /dev/null
+++ b/lab12/https_server.py
@@ -0,0 +1,24 @@
+#!/usr/bin/python3
+import socket
+import ssl
+
+html = """HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE html><html><body><h1>Hello, world!</h1></body></html>"""
+
+SERVER_CERT = './server.crt'
+SERVER_PRIVATE = './server.key'
+
+context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+#context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) # Ubuntu 16.04
+context.load_cert_chain(SERVER_CERT, SERVER_PRIVATE)
+
+sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
+sock.bind(('0.0.0.0', 4433))
+sock.listen(5)
+
+while True:
+    newsock, fromaddr = sock.accept()
+    ssock = context.wrap_socket(newsock, server_side=True)
+    data = ssock.recv(1024) # Read data over TLS
+    ssock.sendall(html.encode('utf-8')) # Send data over TLS
+    ssock.shutdown(socket.SHUT_RDWR) # Close the TLS connection
+    ssock.close()
diff --git a/lab12/ssl_client.py b/lab12/ssl_client.py
new file mode 100644
index 0000000..10bb560
--- /dev/null
+++ b/lab12/ssl_client.py
@@ -0,0 +1,34 @@
+#!/usr/bin/python3
+import socket, ssl, sys, pprint
+# Primim ca argument hostname-ul serverului, de exemplu google.com
+hostname = sys.argv[1]
+
+port = 443
+
+# Create TCP connection
+sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+sock.connect((hostname, port))
+
+input("After making TCP connection. Press any key to continue ...")
+
+# You may need to change this depending on your Linux distro
+cadir = '/etc/ssl/certs'
+
+# Set up the TLS context
+context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
+#context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) # For Ubuntu 16.04
+context.load_verify_locations(capath=cadir)
+context.verify_mode = ssl.CERT_REQUIRED
+context.check_hostname = True
+
+# Add the TLS
+ssock = context.wrap_socket(sock, server_hostname=hostname,
+do_handshake_on_connect=False)
+ssock.do_handshake() # Start the handshake
+pprint.pprint(ssock.getpeercert())
+
+input("After handshake. Press any key to continue ...")
+
+# Close the TLS Connection
+ssock.shutdown(socket.SHUT_RDWR)
+ssock.close()
-- 
GitLab