Sidahmed Sidahmed - 8 days ago 5
Linux Question

Python simple SSL communication

I want to initiate a simple SSL connection between a client and a server written in python 3, but I am getting errors.

Here is the server code :

#/usr/bin/python3
import socket
import ssl

HOST, PORT = '0.0.0.0', 12345

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(10)
client, addr = sock.accept()

# WRAP SOCKET
wrappedSocket = ssl.wrap_socket(client, server_side=True, ssl_version=ssl.PROTOCOL_SSLv23, ciphers="ADH-AES256-SHA")

# CONNECT AND PRINT REPLY

print(wrappedSocket.recv(1024))

# CLOSE SOCKET CONNECTION
wrappedSocket.close()


And here is the client code :

#/usr/bin/python3

import socket
import ssl

HOST, PORT = '127.0.0.1', 12345

# CREATE SOCKE
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# WRAP SOCKET
wrappedSocket = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv23, ciphers="ADH-AES256-SHA")

# connect and send a message
wrappedSocket.connect((HOST, PORT))
wrappedSocket.send(b"Hello")

wrappedSocket.close()


And here is the error that I am having on the server side :


Traceback (most recent call last):

File "server.py", line 18, in

wrappedSocket = ssl.wrap_socket(client, server_side=True, ssl_version=ssl.PROTOCOL_SSLv23, ciphers="ADH-AES256-SHA")

File "/usr/lib/python3.4/ssl.py", line 890, in wrap_socket
ciphers=ciphers)

File "/usr/lib/python3.4/ssl.py", line 509, in init
raise ValueError("certfile must be specified for server-side "

ValueError: certfile must be specified for server-side operations


Please, I don't want a complicated SSL connection, I am just looking for the simplest way possible to encrypt the data between the client and the server, just like
ncat
with the
--ssl
option (
ncat --ssl -l -p 12345
from the server side, and
ncat --ssl 127.0.0.1 12345
from the client side).

PS : I am using Ubuntu 15.10 and Python 3.

Answer

You can generate a self-signed certificate using openssl and specify in wrap_socket the certfile attribute and the keyfile attribute server side

Generating an RSA public/private-key pair

openssl genrsa -out private.pem 2048

Generating a self-signed certificate

openssl req -new -x509 -key private.pem -out cacert.pem -days 1095