Using os.urandom() and constant-time hash check for handshake. Fixes #209 #210

This commit is contained in:
Predrag Gruevski
2015-09-21 11:39:38 -04:00
parent d00154724b
commit 896e7c7317
2 changed files with 9 additions and 7 deletions

View File

@@ -28,6 +28,8 @@ else:
import uuid import uuid
import hashlib import hashlib
import hmac
import os
from ._logging import * from ._logging import *
from ._url import * from ._url import *
@@ -143,7 +145,7 @@ def _validate(headers, key, subprotocols):
value = (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode('utf-8') value = (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode('utf-8')
hashed = base64encode(hashlib.sha1(value).digest()).strip().lower() hashed = base64encode(hashlib.sha1(value).digest()).strip().lower()
success = (hashed == result) success = hmac.compare_digest(hashed, result)
if success: if success:
return True, subproto return True, subproto
else: else:
@@ -151,5 +153,5 @@ def _validate(headers, key, subprotocols):
def _create_sec_websocket_key(): def _create_sec_websocket_key():
uid = uuid.uuid4() randomness = os.urandom(16)
return base64encode(uid.bytes).decode('utf-8').strip() return base64encode(randomness).decode('utf-8').strip()

View File

@@ -464,12 +464,12 @@ class WebSocketTest(unittest.TestCase):
self.assertRaises(ws.WebSocketConnectionClosedException, s.send, "Hello") self.assertRaises(ws.WebSocketConnectionClosedException, s.send, "Hello")
self.assertRaises(ws.WebSocketConnectionClosedException, s.recv) self.assertRaises(ws.WebSocketConnectionClosedException, s.recv)
def testUUID4(self): def testNonce(self):
""" WebSocket key should be a UUID4. """ WebSocket key should be a random 16-byte nonce.
""" """
key = _create_sec_websocket_key() key = _create_sec_websocket_key()
u = uuid.UUID(bytes=base64decode(key.encode("utf-8"))) nonce = base64decode(key.encode("utf-8"))
self.assertEqual(4, u.version) self.assertEqual(16, len(nonce))
class WebSocketAppTest(unittest.TestCase): class WebSocketAppTest(unittest.TestCase):