Answered step by step
Verified Expert Solution
Question
1 Approved Answer
How do I secure this code using the Python ssl library to secure the sockets with TLS/SSL: Code: import argparse import sys import itertools import
How do I secure this code using the Python ssl library to secure the sockets with TLS/SSL:
Code:
import argparse import sys import itertools import socket from socket import socket as Socket from os import path # A simple web server def main(): # Command line arguments. Use a port > 1024 by default so that we can run # without sudo, for use as a real server you need to use port 80. parser = argparse.ArgumentParser() parser.add_argument('--port', '-p', default=2080, type=int, help='Port to use') args = parser.parse_args() # Create the server socket (to handle tcp requests using ipv4), make sure # it is always closed by using with statement. with Socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket: # The socket stays connected even after this script ends. So in order # to allow the immediate reuse of the socket (so that we can kill and # re-run the server while debugging) we set the following option. This # is potentially dangerous in real code: in rare cases you may get junk # data arriving at the socket. server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('', args.port)) server_socket.listen(1) print("server ready") while True: with server_socket.accept()[0] as connection_socket: # This is a hackish way to make sure that we can receive and process multi # line requests. request="" received=connection_socket.recv(1024).decode('utf-8') request+=received reply = http_handle(request) connection_socket.sendall(reply.encode('utf-8')) print(" Received request") print("======================") print(request.rstrip()) print("======================") print(" Replied with") print("======================") print(reply.rstrip()) print("======================") return 0 def http_handle(request_string): """Given a http requst return a response Both request and response are unicode strings with platform standard line endings. """ ''' data = 'HTTP/1.1 200 OK ' data+= 'Connection: keep-alive ' data+= 'Content-Type: text/html; encoding=utf-8 ' f = open('index.html', 'r') # send data per line for l in f.readlines(): data+=l f.close() data+=" " if "favicon" in request_string: data="HTTP/1.1 404 Not Found " return data #assert not isinstance(request_string, bytes) ''' # Fill in the code to handle the http request here. You will probably want # to write additional functions to parse the http request into a nicer data # structure (e.g., not a string) and to easily create http responses. # Used Figure 2.8 in book as guideline: Request line and Header lines # Step 0: Split the string by line lines = request_string.split(sep=' ') # Step 1: Get the first line (request line) and split into method, url, version method, url, version = lines[0].split() # Step 2: Until you see( ), read lines as key, value with header name and value. Store as a dictionary lines.pop(0) dictionary = {} for line in lines: if line.strip() == '': continue key, value = line.split(sep=':', maxsplit=1) dictionary[key.strip()] = value.strip() # Step 3: Check to make sure method, url, and version are all compliant # Step 3a: if method is a GET and url is "/" or "/index.html" and correct HTTP version, we need to respond with 200 OK and some HTML if method == 'GET' and (url == '/' or url == '/index.html') and version == 'HTTP/1.1': data = 'HTTP/1.1 200 OK ' data+= 'Connection: keep-alive ' data+= 'Content-Type: text/html; encoding=utf-8 ' f = open('index.html', 'r') # send data per line for l in f.readlines(): data+=l f.close() data+=" " if "favicon" in request_string: data="HTTP/1.1 404 Not Found " return data # Step 3b: If method is compliant, but not implemented, we need to respond with a correct HTTP response compliant_methods = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'] implemented_methods = ['GET'] if method in compliant_methods and method not in implemented_methods: return "HTTP/1.1 501 Not Implemented " # Step 3c: If the version is not compliant, we need to respond with correct HTTP response compliant_versions = ['HTTP/0.9', 'HTTP/1.0', 'HTTP/1.1', 'HTTP/2.0'] if version not in compliant_versions: return "\HTTP/1.1 501 Not Implemented " # Step 3d: If file does not exist in server path, respond with HTTP 404 File not found response if not path.exists(url[1:]): return "\HTTP/1.1 404 Not Found " # Step 4: Checking to make sure headers are correctly formatted raise NotImplementedError pass if __name__ == "__main__": sys.exit(main())
Here is the contents of index.html:
Header
Hello, world!
Here is the log of a demo run:
python3 chegg.py --port 5000 server ready ^Z [1] + 11681 suspended python3 chegg.py --port 5000 curl -L localhost:5000 ^Z [2] + 11704 suspended curl -L localhost:5000 fg %python3 [1] - 11681 continued python3 chegg.py --port 5000 Received request ====================== GET / HTTP/1.1 Host: localhost:5000 User-Agent: curl/7.58.0 Accept: */* ====================== Replied with ====================== HTTP/1.1 200 OK Connection: keep-alive Content-Type: text/html; encoding=utf-8Header
Hello, world!
====================== ^Z [1] + 11681 suspended python3 chegg.py --port 5000 fg %curl [2] - 11704 continued curl -L localhost:5000Header
Hello, world!
curl -L localhost:5000/does-not-exist ^Z [2] + 11720 suspended curl -L localhost:5000/does-not-exist fg %python3 [1] - 11681 continued python3 chegg.py --port 5000 Received request ====================== GET /does-not-exist HTTP/1.1 Host: localhost:5000 User-Agent: curl/7.58.0 Accept: */* ====================== Replied with ====================== \HTTP/1.1 404 Not Found ====================== ^Z [1] + 11681 suspended python3 chegg.py --port 5000 fg %curl [2] - 11720 continued curl -L localhost:5000/does-not-exist \HTTP/1.1 404 Not Found
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started