Reputation: 2411
I'm trying to implement a websocket secure server in Python (based on this module)
In the link, it says that the module supports TLS and SSL connections, but doesn't explain how.
The code I currently have goes like that:
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket
import ssl
class SimpleResponder(WebSocket):
def handleMessage(self):
self.sendMessage(self.data)
def handleConnected(self):
print self.address, 'connected'
def handleClose(self):
print self.address, 'closed'
server = SimpleWebSocketServer('', 8000, SimpleResponder)
try:
server.serveforever()
except KeyboardInterrupt:
pass
print "Server ended"
I tried to implement SSL wrapping in the same way I would do with a HTTP server (like that):
server.socket = ssl.wrap_socket (server.socket, certfile='path/to/localhost.pem', server_side=True)
But seems like it doesn't work (I get the next error):
AttributeError: 'SimpleWebSocketServer' object has no attribute 'socket'
So clearly the SimpleWebSocketServer
class isn't structured like the SimpleHTTPServer
class.
So how can I implement a secure websocket server?
Upvotes: 1
Views: 3072
Reputation: 363
From simple-websocket-server:
TLS/SSL Example
1) Generate a certificate with key
openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
2) Run the secure TSL/SSL server (in this case the cert.pem file is in the same directory)
python SimpleExampleServer.py --example chat --ssl 1 --cert ./cert.pem
3) Offer the certificate to the browser by serving websocket.html through https. The HTTPS server will look for cert.pem in the local directory. Ensure the websocket.html is also in the same directory to where the server is run.
sudo python SimpleHTTPSServer.py
4) Open a web browser to: https://localhost:443/websocket.html
5) Change ws://localhost:8000/ to wss://localhost:8000 and click connect.
Note: if you are having problems connecting, ensure that the certificate is added in your browser against the exception https://localhost:8000 or whatever host:port pair you want to connect to.
I found that Autbahn|Python was very easy to use. It work with both Twisted and asyncio networking engines.
Upvotes: 2