Skip to content

Instantly share code, notes, and snippets.

@SoftCreatR
Created August 5, 2021 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SoftCreatR/564d35aa1f1748cc4db22b66a9737170 to your computer and use it in GitHub Desktop.
Save SoftCreatR/564d35aa1f1748cc4db22b66a9737170 to your computer and use it in GitHub Desktop.
Simple Python3 (HTTPs) Server for a static website, including security headers for A+ rating
"""
Copyright (c) 2021 1-2.dev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from http.server import HTTPServer, SimpleHTTPRequestHandler
# Config
WWW_DIR = '/var/www/html'
HOST = '0.0.0.0'
PORT = 80
# Generate self signed certificate using openssl command
def generate_self_signed_cert():
import os
try:
command = 'openssl req -newkey rsa:4096 -x509 -sha256 -days 3650 -nodes -out cert.pem -keyout key.pem -subj ' \
'"/CN=*" '
os.system(command)
print('<<<<Certificate Generated>>>>>>')
except OSError:
print('Error while generating certificate.')
# Override the Request Handler
class Handler(SimpleHTTPRequestHandler):
def do_GET(self):
from pathlib import Path
import mimetypes
request_file = self.path
if request_file == '/':
request_file = '/index.html'
request_file = WWW_DIR.rstrip('/') + request_file
local_path = Path(request_file)
if local_path.is_file():
self.send_response(200)
self.send_header('Content-type', mimetypes.guess_type(request_file)[0])
self.send_header('Permissions-Policy', 'accelerometer=(), autoplay=(), camera=(), document-domain=(), '
'encrypted-media=(), fullscreen=(), geolocation=(), gyroscope=(), '
'magnetometer=(), microphone=(), midi=(), payment=(), '
'picture-in-picture=(), sync-xhr=(), usb=(), interest-cohort=()')
self.send_header('Content-Security-Policy', 'upgrade-insecure-requests')
self.send_header('X-XSS-Protection', '1; mode=block')
self.send_header('X-Frame-Options', 'SAMEORIGIN')
self.send_header('X-Content-Type-Options', 'nosniff')
self.send_header('Referrer-Policy', 'no-referrer')
self.end_headers()
with open(request_file, 'rb') as file:
self.wfile.write(file.read())
else:
self.send_response(301)
self.send_header('Location', '/')
self.end_headers()
# Start the server
if __name__ == '__main__':
srv = HTTPServer((HOST, PORT), Handler)
if PORT == 443 or PORT == 4433 or PORT == 8443:
import ssl
generate_self_signed_cert()
srv.socket = ssl.wrap_socket(srv.socket, keyfile='key.pem', certfile='cert.pem',
server_side=True, ssl_version=ssl.PROTOCOL_TLSv1_2, ca_certs=None,
do_handshake_on_connect=True, suppress_ragged_eofs=True,
ciphers='ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA'
'-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM'
'-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256'
':ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA'
':ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA'
':ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS'
'-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256'
'-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK')
try:
print('Server started.')
srv.serve_forever()
except KeyboardInterrupt:
pass
finally:
srv.server_close()
print('Server stopped.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment