TLS adapter for extentions with Python3 requests

Viewed 477

I am not sure about whether or how TLS extensions can be set using Python3 requests.

The below code creates a TLS adapter for use with Python 3 requests. Allowed ciphers can be explicitly declared for the initial client-hello packet. However, a client-hello packet can contain many other extensions (See TLS Extension List below code). I tried to specify these in the **kwargs and ssl_context with no luck.

The documentation for requests TLS adapter does not provide a list of allowed options. So, I looked at the source code for HTTPAdapter but can't find any functionality to set extensions. What is the best way I can set TLS extentions using requests?

import ssl
import requests

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
from requests.packages.urllib3.util import ssl_

CIPHERS = (
    'ECDHE-RSA-AES256-GCM-SHA384:'
    'ECDHE-ECDSA-AES256-GCM-SHA384:'
    'ECDHE-RSA-AES256-SHA384:'
    'ECDHE-ECDSA-AES256-SHA384:'
    'ECDHE-RSA-AES128-GCM-SHA256:'
    'ECDHE-RSA-AES128-SHA256:'
    'AES256-SHA'
)

class TlsAdapter(HTTPAdapter):

    def __init__(self, ssl_options=0, **kwargs):
        self.ssl_options = ssl_options
        super(TlsAdapter, self).__init__(**kwargs)

    def init_poolmanager(self, *pool_args, **pool_kwargs):
        ctx = ssl_.create_urllib3_context(ciphers=CIPHERS, cert_reqs=ssl.CERT_REQUIRED, options=self.ssl_options)
        self.poolmanager = PoolManager(*pool_args,
                                       ssl_context=ctx,
                                       **pool_kwargs)

s = requests.session()
# Specifies no TLS 1.0 or TLS 1.1
adapter = TlsAdapter(ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)
s.mount("https://", adapter)
s.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'}

try:
    r = s.request('GET', 'https://google.com')
    print(r)
except Exception as e:
    print(e)

TLS Extensions List:

Extension Name         |  Extension Hex Code
max_fragment_length    |  0001
status_request         |  0005
client_authz           |  0007
server_authz           |  0008
cert_type              |  0009
supported_groups       |  000a
ec_point_formats       |  000b
signature_algorithms   |  000d
heartbeat              |  000f
application_layer_
protocol_negotiation   |  0010
status_request_v2      |  0011
client_certificate_type|  0013
server_certificate_type|  0014
token_binding          |  0018
compress_certificate   |  001b
record_size_limit      |  001c
supported_versions     |  002b
psk_key_exchange_modes |  002d
signature_algorithms_cert| 0032
channel_id             | 5500
0 Answers
Related