Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Python secure websocket client request?

My Python secure websocket client code giving me exception as follows:

[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748)

I have created my private certificate and and sign certificate as well, but I am not able to connect to it using Python script as follows:

import json
from websocket import create_connection


class subscriber:
   def listenForever(self):
   try:
      # ws = create_connection("wss://localhost:9080/websocket")
      ws = create_connection("wss://nbtstaging.westeurope.cloudapp.azure.com:9090/websocket")
      ws.send("test message")
      while True:
          result = ws.recv()
          result = json.loads(result)
          print("Received '%s'" % result)

      ws.close()
  except Exception as ex:
      print("exception: ", format(ex))


try:
    subscriber().listenForever()
except:
    print("Exception occured: ")

My https/wss server script in python with tornado as follows:

import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import os
import ssl

ssl_root = os.path.join(os.path.dirname(__file__), 'ssl1_1020')


class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self):
        pass

    def on_message(self, message):
        self.write_message("Your message was: " + message)
        print("message received: ", format(message))

    def on_close(self):
        pass


class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
           (r'/', IndexPageHandler),
           (r'/websocket', WebSocketHandler),
        ]

        settings = {
            'template_path': 'templates'
        }
        tornado.web.Application.__init__(self, handlers, **settings)


ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain(ssl_root+"/server.crt",
                    ssl_root + "/server.pem")


if __name__ == '__main__':
    ws_app = Application()
    server = tornado.httpserver.HTTPServer(ws_app, ssl_options=ssl_ctx,)
    server.listen(9081, "0.0.0.0")
    print("server started...")
    tornado.ioloop.IOLoop.instance().start()

steps used to create SSL signed certificates:

openssl genrsa -des3 -out server.key 1024
openssl rsa -in server.key -out server.pem
openssl req -new -nodes -key server.pem -out server.csr
openssl x509 -req -days 365 -in server.csr -signkey server.pem -out server.crt
like image 332
Ravi Anand Avatar asked Oct 20 '17 15:10

Ravi Anand


People also ask

How do I create a WebSocket in Python?

WebSocket Client with PythonCreate a new File “client.py” and import the packages as we did in our server code. Now let's create a Python asynchronous function (also called coroutine). async def test(): We will use the connect function from the WebSockets module to build a WebSocket client connection.

How do I secure my WebSocket connection?

Use wss:// instead of ws://. This adds a security layer over your communication. Use a server like Nginx for reverse proxying websockets and enable SSL over them.

How do I create a secure WebSocket server?

Use TLS to create secure socket communication To secure the transport, you should use a secure protocol like https:// instead of the unsecure https:// protocol. For WebSockets, you should use the wss:// (TLS-encrypted WebSockets) protocol instead of the unsecure ws:// protocol..

Is Python good for WebSockets?

websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance. Built on top of asyncio , Python's standard asynchronous I/O framework, it provides an elegant coroutine-based API.


1 Answers

Finally I found a solution, I updated python client script while making connection to secure web socket url to ignore cert request as follows:

 import ssl
 import websocket

 ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE})
 ws.connect("wss://xxx.com:9090/websocket")
like image 82
Ravi Anand Avatar answered Oct 09 '22 09:10

Ravi Anand