Skip to content

Instantly share code, notes, and snippets.

@joelanders
Created May 30, 2016 15:50
Show Gist options
  • Save joelanders/7291f5efc564904a49b75c6ec404ee74 to your computer and use it in GitHub Desktop.
Save joelanders/7291f5efc564904a49b75c6ec404ee74 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3.5
# openssl req -x509 -newkey rsa:2048 -keyout selfsigned.key -nodes -out selfsigned.cert -sha256 -days 1000
import socket, ssl, pprint
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# (TRY #1) require a certificate from the server
#ssl_sock = ssl.wrap_socket(s,
# ca_certs="selfsigned.cert",
# cert_reqs=ssl.CERT_REQUIRED)
# (TRY #2) don't require certificate from the server
#ssl_sock = ssl.wrap_socket(s,
# cert_reqs=ssl.CERT_NONE)
# (TRY #3) do it a different way
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.verify_mode = ssl.CERT_NONE
ssl_sock = context.wrap_socket(s)
ssl_sock.connect(('localhost', 9000))
print(repr(ssl_sock.getpeername()))
pprint.pprint(ssl_sock.getpeercert())
print(pprint.pformat(ssl_sock.getpeercert()))
# Set a simple HTTP request -- use http.client in actual code.
ssl_sock.write(b"yo dood")
# Read a chunk of data. Will not necessarily
# read all the data returned by the server.
data = ssl_sock.read()
# note that closing the SSLSocket will also close the underlying socket
ssl_sock.close()
#!/usr/bin/env python3.5
import ssl, socket
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile="selfsigned.cert", keyfile="selfsigned.key")
bindsocket = socket.socket()
bindsocket.bind(('localhost', 9000))
bindsocket.listen(5)
def deal_with_client(connstream):
print('entered deal_with_client')
data = connstream.recv(1024)
# empty data means the client is finished with us
while data:
print("server got %s" % data)
data = connstream.recv(1024)
# finished with client
while True:
newsocket, fromaddr = bindsocket.accept()
connstream = context.wrap_socket(newsocket, server_side=True)
try:
deal_with_client(connstream)
finally:
connstream.shutdown(socket.SHUT_RDWR)
connstream.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment