Please check TLS hostnames


I need a quick script to check a mailbox. My go-to language is Python, and its batteries-included philosophy means I go straight to imaplib:


import imaplib

conn = imaplib.IMAP4_SSL('imap.gmail.com')

# Now we're ready to use conn.login to send username and password

I’m security-conscious, so I’ve requested a TLS connection.

(With Ubuntu, that could still be an SSLv3 connection. The POODLE attacks on SSLv3 were only demonstrated as a problem in a browser when an attacker can force repeated connections including plaintext they control.)

Before I send my username and password over this connection, I know I have a secure connection I know that I requested a connection to imap.gmail.com and I can also see that I haven’t tampered with any crypto defaults I don’t understand. Ready?

I can see that Python had a bug where that hostname wasn’t checked (No SSL match_hostname() in imaplib). That means my connection could be MitM’d by anyone with a valid SSL certificate; and they’re free now. But that was fixed in Python 3.4, so I’m good?

Secure by default

By default, imaplib doesn't check the hostname. Before I send my username and password, let’s make sure I’m actually talking to imap.gmail.com:


import imaplib, socket, ssl

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True

conn = imaplib.IMAP4_SSL('imap.gmail.com', ssl_context=context)

# Good to go!
conn.login('AzureDiamond', 'hunter2')

It’s that context.check_hostname = True that makes the critical check. Before using the connection, confirm that the SSL certificate is for the hostname that I requested.

Taking a look through Der Spiegel’s latest release of Snowden documents it’s notable that “some forms of encryption still cause problems for the NSA”. If your intention is to preserve your users’ privacy across the public Internet, remember that security tends to fail catastrophically and that exploitation attempts are constant and better-implemented than you might expect (“an algorithm that searches GitHub 24 hours per day for API keys”).

If your intention is to provide a library or service, make it secure by default. Your users may not thank you when things break, but it’s the responsible choice.

(Music: Cracker, “El Cerrito”)
(More from this year, or the front page? [K])