Sending TLS 1.2 request in Python 2.6

MultipleCrashes picture MultipleCrashes · Mar 19, 2015 · Viewed 31.7k times · Source

I am stuck using Python 2.6 and I need to send a post request using TLS 1.2. Does Python 2.6's requests library support TLS 1.2? How do I ensure/verify that the request is made via TLS1.2 and not some other version?

A sample request is

r=requests.post(url,data=payload,verify=False)

Somewhere on the forum I came to know that we need to compile pyOpenSSL to support this. Is there an easier way?

Answer

frasertweedale picture frasertweedale · Mar 19, 2015

The ssl module in Python 2.6 supports up to TLS 1.0 only. If you do not wish to introduce additional dependencies (such as pyOpenSSL as you suggest) you will need to upgrade to Python 2.7 or 3.x to get support for newer versions of TLS.

To force a particular version of TLS in Python 2.7.9 or later, construct an SSLContext with the appropriate PROTOCOL_* constant. You can then use it with any API that lets you provide your own SSLContext.

import ssl
import urllib2

ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
# set other SSLContext options you might need
response = urllib2.urlopen(url, context=ctx)

To use a particular protocol version or higher (including future versions), use ssl.PROTOCOL_SSLv23 and then disable the protocol versions you do not want to use:

ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)

# allow TLS 1.2 and later
ctx.options |= ssl.OP_NO_SSLv2
ctx.options |= ssl.OP_NO_SSLv3
ctx.options |= ssl.OP_NO_TLSv1
ctx.options |= ssl.OP_NO_TLSv1_1

As for using a custom SSLContext with Requests in order to force a particular protocol version, according to the documentation there does not seem to be a way to do this, see the following example from the docs.