Created
September 8, 2012 22:19
-
-
Save saghul/3680324 to your computer and use it in GitHub Desktop.
SSL connected socket pair in Python (blocking)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import select | |
import socket | |
import ssl | |
bindsocket = socket.socket() | |
bindsocket.bind(('127.0.0.1', 10000)) | |
bindsocket.listen(1) | |
connect_address = bindsocket.getsockname() | |
client = socket.socket() | |
ssl_client = ssl.wrap_socket(client, do_handshake_on_connect=False) | |
ssl_client.connect(connect_address) | |
newsocket, fromaddr = bindsocket.accept() | |
connstream = ssl.wrap_socket(newsocket, server_side=True, do_handshake_on_connect=False, certfile="test.crt", keyfile="test.key") | |
print "Connected!" | |
connstream.setblocking(0) | |
ssl_client.setblocking(0) | |
res = [False, False] | |
socks = [connstream, ssl_client] | |
while True: | |
rsocks = [] | |
wsocks = [] | |
for i, s in enumerate(socks): | |
try: | |
s.do_handshake() | |
res[i] = True | |
except ssl.SSLError, err: | |
if err.args[0] == ssl.SSL_ERROR_WANT_READ: | |
rsocks.append(s) | |
elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE: | |
wsocks.append(s) | |
else: | |
raise | |
if all(res): | |
break | |
select.select(rsocks, wsocks, []) | |
print "Connected after SSL handshake!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment