From 60fccc57d40b112508ca86131f93a07b5f2ef148 Mon Sep 17 00:00:00 2001 From: berhsi Date: Mon, 29 Jul 2019 18:27:53 +0200 Subject: [PATCH] setstatus.py: add support for ssl client now connect to server via tls. --- setstatus.py | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/setstatus.py b/setstatus.py index b250f88..e3a2b1c 100755 --- a/setstatus.py +++ b/setstatus.py @@ -10,6 +10,7 @@ # input is 0 or 1. import socket +import ssl from sys import exit, argv, byteorder @@ -51,8 +52,12 @@ def read_argument(): def main(*status): - HOST = 'nr18.space' + HOST = 'localhost' PORT = 10001 + SERVER_NAME = 'server.status.kraut.space' + CLIENT_CERT = './certs/client.crt' + CLIENT_KEY = './certs/client.key' + SERVER_CERT = './certs/server.crt' BOM = byteorder STATUS = None RESPONSE = None @@ -69,21 +74,35 @@ def main(*status): if STATUS == None: STATUS = read_argument() + context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile = SERVER_CERT) + context.options &= ~ssl.PROTOCOL_TLS + context.verify_mode = ssl.CERT_OPTIONAL + # context.set_ciphers('HIGHT:!aNULL:!RC4:!DSS') + context.load_cert_chain(certfile = CLIENT_CERT, keyfile = CLIENT_KEY) + print('SSL context created') + with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as mySocket: print('Socket created') try: - mySocket.connect((HOST, PORT)) + conn = context.wrap_socket(mySocket, server_side = False, \ + server_hostname = SERVER_NAME) + print('Connection wrapped with ssl.context') except Exception as e: - print('{}'.format(e)) + print('Context wrapper failed: [}'.format(e)) + try: + conn.connect((HOST, PORT)) + print('SSL established: {}'.format(conn.getpeercert())) + except Exception as e: + print('SSL handshake failed: {}'.format(e)) exit(1) try: print('Send new status: {}'.format(STATUS)) - mySocket.send(STATUS) + conn.send(STATUS) except Exception as e: print('Error: {}'.format(e)) exit(2) try: - RESPONSE = mySocket.recv(1) + RESPONSE = conn.recv(1) print('Server returns: {}'.format(RESPONSE)) if RESPONSE == STATUS: print('Status sucessfull updated')