Requests: SSLV3_ALERT_HANDSHAKE_FAILURE em Python 3.5, funciona em Python 2.7

Criado em 30 jul. 2018  ·  3Comentários  ·  Fonte: psf/requests

Estou executando o seguinte código:

import requests
import ssl
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager

class SSLAdapter(HTTPAdapter):
    '''An HTTPS Transport Adapter that uses an arbitrary SSL version.'''
    def __init__(self, ssl_version=None, **kwargs):
        self.ssl_version = ssl_version

        super(SSLAdapter, self).__init__(**kwargs)

    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       ssl_version=self.ssl_version)

s = requests.Session()
s.mount('https://', SSLAdapter(ssl.PROTOCOL_TLSv1_2))

print(ssl.OPENSSL_VERSION)

r = s.get('https://bibliothek.weltenbau.net/api/profile/265854176393691138')
print(r.status_code)

Usando Python 3.5.3, recebo os seguintes erros:

OpenSSL 1.1.0f  25 May 2017
Traceback (most recent call last):
  File "/opt/weltenbau-bot/.venv/lib/python3.5/site-packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/opt/weltenbau-bot/.venv/lib/python3.5/site-packages/urllib3/connectionpool.py", line 343, in _make_request
    self._validate_conn(conn)
  File "/opt/weltenbau-bot/.venv/lib/python3.5/site-packages/urllib3/connectionpool.py", line 849, in _validate_conn
    conn.connect()
  File "/opt/weltenbau-bot/.venv/lib/python3.5/site-packages/urllib3/connection.py", line 356, in connect
    ssl_context=context)
  File "/opt/weltenbau-bot/.venv/lib/python3.5/site-packages/urllib3/util/ssl_.py", line 359, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "/usr/lib/python3.5/ssl.py", line 385, in wrap_socket
    _context=self)
  File "/usr/lib/python3.5/ssl.py", line 760, in __init__
    self.do_handshake()
  File "/usr/lib/python3.5/ssl.py", line 996, in do_handshake
    self._sslobj.do_handshake()
  File "/usr/lib/python3.5/ssl.py", line 641, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:720)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/weltenbau-bot/.venv/lib/python3.5/site-packages/requests/adapters.py", line 445, in send
    timeout=timeout
  File "/opt/weltenbau-bot/.venv/lib/python3.5/site-packages/urllib3/connectionpool.py", line 638, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/opt/weltenbau-bot/.venv/lib/python3.5/site-packages/urllib3/util/retry.py", line 398, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='bibliothek.weltenbau.net', port=443): Max retries exceeded with url: /api/profile/265854176393691138 (Caused by SSLError(SSLError(1, '[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:720)'),))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 24, in <module>
    r = s.get('https://bibliothek.weltenbau.net/api/profile/265854176393691138')
  File "/opt/weltenbau-bot/.venv/lib/python3.5/site-packages/requests/sessions.py", line 525, in get
    return self.request('GET', url, **kwargs)
  File "/opt/weltenbau-bot/.venv/lib/python3.5/site-packages/requests/sessions.py", line 512, in request
    resp = self.send(prep, **send_kwargs)
  File "/opt/weltenbau-bot/.venv/lib/python3.5/site-packages/requests/sessions.py", line 622, in send
    r = adapter.send(request, **kwargs)
  File "/opt/weltenbau-bot/.venv/lib/python3.5/site-packages/requests/adapters.py", line 511, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='bibliothek.weltenbau.net', port=443): Max retries exceeded with url: /api/profile/265854176393691138 (Caused by SSLError(SSLError(1, '[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:720)'),))

Usando o Python 2.7.13, tudo funciona conforme o esperado:

OpenSSL 1.1.0f  25 May 2017
200

Informação do sistema

Python 3.5.3

pedidos.ajuda

{
  "chardet": {
    "version": "3.0.4"
  },
  "cryptography": {
    "version": ""
  },
  "idna": {
    "version": "2.7"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.5.3"
  },
  "platform": {
    "release": "4.9.0-6-amd64",
    "system": "Linux"
  },
  "pyOpenSSL": {
    "openssl_version": "",
    "version": null
  },
  "requests": {
    "version": "2.19.1"
  },
  "system_ssl": {
    "version": "1010006f"
  },
  "urllib3": {
    "version": "1.23"
  },
  "using_pyopenssl": false
}

pip freeze

certifi==2018.4.16
chardet==3.0.4
idna==2.7
requests==2.19.1
urllib3==1.23

Python 2.7.13:

pedidos.ajuda

{
  "chardet": {
    "version": "3.0.4"
  },
  "cryptography": {
    "version": ""
  },
  "idna": {
    "version": "2.7"
  },
  "implementation": {
    "name": "CPython",
    "version": "2.7.13"
  },
  "platform": {
    "release": "4.9.0-6-amd64",
    "system": "Linux"
  },
  "pyOpenSSL": {
    "openssl_version": "",
    "version": null
  },
  "requests": {
    "version": "2.19.1"
  },
  "system_ssl": {
    "version": "1010006f"
  },
  "urllib3": {
    "version": "1.23"
  },
  "using_pyopenssl": false
}

pip freeze

certifi==2018.4.16
chardet==3.0.4
idna==2.7
requests==2.19.1
urllib3==1.23

Solução possível

Instalar o pyOpenSSL no venv do Python3 parece corrigir esse problema.

Comentários muito úteis

ei você encontrou uma solução?

Todos 3 comentários

Olá @ghtyrant ,

Parece que há alguma variação na configuração do SSL entre cada instalação do Python. O interpretador 3.5 não consegue negociar um protocolo aceitável com o servidor. O fato de que a instalação do PyOpenSSL resolve isso sugere que há algo errado com a configuração do SSL 3.5.

Infelizmente, também não fui capaz de reproduzir isso localmente entre as instalações do 2.7.13 e do 3.5.3. Eu acredito que originalmente houve alguns problemas com OpenSSL 1.1 e Python que não construíam bem juntos devido a alterações de API / estrutura.

O único conselho que posso oferecer no momento é examinar a reinstalação do 3.5.3 no OpenSSL do seu sistema ou a atualização para o 3.5.6. Não tenho certeza se vejo um link claro para um defeito nas solicitações e o comportamento que está sendo observado. Vou encerrar por agora, mas se você encontrar mais informações, sinta-se à vontade para reabrir. Obrigado!

Encontrei isso ao ter o mesmo problema ao instalar o OpenSSL 1.1.1b de packages.sury.org no Debian 9. Esta foi a maneira mais fácil de obter a versão mais recente do nginx e TLS 1.3.

No entanto, aparentemente, ele não funciona muito bem com a instalação padrão do Python (3.5.3) e estava causando esse erro no aplicativo Django. A instalação do pyOpenSSL corrige o problema.

Acho que teremos que esperar pelo Debian 10 para que o TLS 1.3 e o Python funcionem juntos corretamente ;-)

ei você encontrou uma solução?

Esta página foi útil?
0 / 5 - 0 avaliações