Python OpenSSL connection fails when using timeout

I see a strange problem when starting a TLS connection to any host. If I don't set a timeout on the socket, it works fine. If I do this, it breaks before timeout with OpenSSL.SSL.WantReadError

. For example, if I set the timeout to 100, it still breaks after a second.

At the moment I am using a workaround to set a timeout on the connection, but then remove it before shaking hands. How can I fix this to respect the timeout?

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)

ctx = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD)
ctx.set_options(OpenSSL.SSL.OP_NO_SSLv2 | OpenSSL.SSL.OP_NO_SSLv3)
ctx.set_verify(OpenSSL.SSL.VERIFY_NONE, lambda _a, _b, _c, _d, _e: None)
conn = OpenSSL.SSL.Connection(ctx, s)
conn.set_tlsext_host_name(hostname.encode('utf-8'))
conn.connect((ip, port))

s.settimeout(None)

try:
    conn.do_handshake()
except OpenSSL.SSL.WantReadError:
    # this happens on every connection

      

+3


source to share


1 answer


Decision:



sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(1)

      

0


source







All Articles