1

I need to get a negotiated cipher for DTLS protocol in pyOpenSSL. I was successful in doing that for TCP sockets, but when it comes to datagrams, it's not that obvious. Please provide an example either in C or Python. This is what I've tried so far:

import socket
from OpenSSL import SSL
from OpenSSL._util import (
    ffi as _ffi,
    lib as _lib)


DTLSv1_METHOD = 7
SSL.Context._methods[DTLSv1_METHOD]=getattr(_lib, "DTLSv1_client_method")
ctx = SSL.Context(DTLSv1_METHOD)
ctx.set_cipher_list('AES128-SHA')
ctx.use_certificate_file("path-to-cert.pem")
ctx.use_privatekey_file("path-to-key.pem")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('dtls-host', 443))
con = SSL.Connection(ctx, s)
con.set_connect_state()
con.connect(('dtls-host', 443))
cc = _lib.SSL_get_current_cipher(con._ssl)
print _ffi.string( _lib.SSL_CIPHER_get_name(cc))

The printed result is (None)

Oleg Gryb
  • 5,122
  • 1
  • 28
  • 40

1 Answers1

1

The result is None because that is the cipher that has been negotiated for your connection. Or rather, it is None because no cipher has been negotiated for your connection yet. Cipher selection is part of the handshake and the handshake is not done anywhere in this example.

Try con.do_handshake() before calling SSL_get_current_cipher.

Also bear in mind that _-prefixed names are private and you really shouldn't use them if you want your program to keep working with future versions of pyOpenSSL.

Jean-Paul Calderone
  • 47,755
  • 6
  • 94
  • 122
  • Tried handshake, but it hangs forever. In regard of '_', there is no other way to get to DTLS stuff except through native C calls, because pyOpenSSL didn't implement DTLS method and SSL_get_current-cipher function. Also in TCP case connect does include handshake. I've seen examples in plain C for DTLS where connect is called without calling do_handshake. Unfortunately, I didn't see any working examples in Python. Thanks for answering. – Oleg Gryb Jun 02 '14 at 15:38
  • If you can't complete a handshake then you have another problem. Perhaps the way you've hacked together DTLS support doesn't actually work. – Jean-Paul Calderone Jun 02 '14 at 17:05
  • Not likely. If you unpack pyOpenSSL.egg and check SSL.py, you'll find that it's just a very thin wrapper around native C lib, except that not all C functions and SSL methods have been wrapped. What I'm doing, is the same as in SSL.py - wrapping missing C functions and SSL methods. I think, a reasonable approach for me would be to test it with pure C first to completely rule out the possibility of bad hacking. – Oleg Gryb Jun 02 '14 at 17:16