Secure HTTP Server sederhana menggunakan Python

December 12, 2010

2 min read.

Ada beberapa hal yang harus dilakukan sebelum menjalankan program ini.

  1. Python interpreter
  2. Program OpenSSL untuk membuat key dan certificate
  3. PyOpenSSL package, OpenSSL library binding untuk python

Membuat self-signed certificate compounded(gabungan key dan certificate)

Buka terminal, masuk ke directory kerja anda misal ~/simplehttps. Ketikkan perintah
openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes

Akan muncul prompt untuk memasukkan data yang diperlukan untuk membuat key & certificate.
generate server.pem

Program Server Https

Buat program simple https server dengan nama ‘SimpleSecureHTTPServer.py’ di directory yang sama. Berikut Source codenya

”’
SimpleSecureHTTPServer.py - simple HTTP server supporting SSL.

- replace fpem with the location of your .pem server file.
- the default port is 443.

usage: python SimpleSecureHTTPServer.py

Credit: https://code.activestate.com/recipes/442473-simple-http-server-supporting-ssl-secure-communica/
License: PSF License
”’
import socket, os
from SocketServer import BaseServer
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from OpenSSL import SSL


class SecureHTTPServer(HTTPServer):
def init(self, server_address, HandlerClass):
BaseServer.init(self, server_address, HandlerClass)
ctx = SSL.Context(SSL.SSLv23_METHOD)
#server.pem’s location (containing the server private key and
#the server certificate).
fpem = ‘server.pem’
ctx.use_privatekey_file (fpem)
ctx.use_certificate_file(fpem)
self.socket = SSL.Connection(ctx, socket.socket(self.address_family,
self.socket_type))
self.server_bind()
self.server_activate()


class SecureHTTPRequestHandler(SimpleHTTPRequestHandler):
def setup(self):
self.connection = self.request
self.rfile = socket._fileobject(self.request, “rb”, self.rbufsize)
self.wfile = socket._fileobject(self.request, “wb”, self.wbufsize)


def test(HandlerClass = SecureHTTPRequestHandler,
ServerClass = SecureHTTPServer):
server_address = (“, 443) # (address, port)
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print “Serving HTTPS on”, sa[0], “port”, sa[1], “…”
httpd.serve_forever()


if name == ‘main‘:
test()
Jalankan program dengan perintah
sudo python SimpleSecureHTTPServer.py
Anda memerlukan akses root untuk membuka default port https yaitu 443.

Menjalankan dengan sudo
tampilan saat uji coba

Sumber