Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ssl - Sending TLS 1.2 request in Python 2.6

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...