Last active
October 21, 2022 13:05
-
-
Save maggick/e097277988e90c2ed2a7192d2c17186a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# python3 | |
# generate server.pem certificate with the following command: | |
# openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes | |
import http.server, ssl, json | |
from http.server import BaseHTTPRequestHandler, HTTPServer | |
class MyHandler(BaseHTTPRequestHandler): | |
def do_GET(self): | |
if self.path == '/redirect': | |
self.send_response(302) | |
# using the Authorization header to control the targeted IMDS endpoint | |
endpoint=self.headers['Authorization'].split('=')[1].split('#')[0] | |
if len(endpoint)>1: | |
self.send_header('Location', 'http://169.254.169.254/'+endpoint) | |
else: | |
self.send_header('Location', 'http://169.254.169.254/') | |
self.end_headers() | |
else: | |
self.send_response(201, 'OK') | |
self.end_headers() | |
payload = self.path | |
# test endpoint with get parameters | |
if self.path.split('?')[0] == '/test': | |
payload = json.dumps({'hello':'world','received':'ok'}) | |
self.wfile.write(payload.encode('utf-8')) | |
def do_POST(self): | |
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data | |
post_data = self.rfile.read(content_length) # <--- Gets the data itself | |
self.send_response(201, 'OK') | |
self.end_headers() | |
payload = self.path | |
# test endpoint | |
if self.path == '/test/': | |
payload = '<b>test</b>' | |
self.wfile.write(payload.encode('utf-8')) | |
class TimeoutingHTTPServer(HTTPServer): | |
def finish_request(self, request, client_address): | |
request.settimeout(5) # Really short timeout as there is only 1 thread | |
HTTPServer.finish_request(self, request, client_address) | |
if __name__ == '__main__': | |
server_address = ('0.0.0.0', 8000) | |
httpd = http.server.HTTPServer(server_address, MyHandler) | |
httpd.socket = ssl.wrap_socket(httpd.socket, | |
server_side=True, | |
certfile='server.pem', | |
ssl_version=ssl.PROTOCOL_TLS) | |
httpd.serve_forever() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment