SSL错误不安全的遗产重新谈判禁用

发布于 2025-02-07 12:31:02 字数 552 浏览 1 评论 0 原文

我正在运行一个Python代码,其中我必须从 httpsconnectionpool(host ='ssd.jpl.nasa.gov',port = 443)获得一些数据。但是,每次我尝试运行代码时,我都会收到以下错误。我在Mac OS 12.1上,

raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='ssd.jpl.nasa.gov', port=443): Max retries exceeded with url: /api/horizons.api?format=text&EPHEM_TYPE=OBSERVER&QUANTITIES_[...]_ (Caused by SSLError(SSLError(1, '[SSL: UNSAFE_LEGACY_RENEGOTIATION_DISABLED] unsafe legacy renegotiation disabled (_ssl.c:997)')))

我真的不知道如何绕过这个问题。

I am running a Python code where I have to get some data from HTTPSConnectionPool(host='ssd.jpl.nasa.gov', port=443). But each time I try to run the code I get the following error. I am on MAC OS 12.1

raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='ssd.jpl.nasa.gov', port=443): Max retries exceeded with url: /api/horizons.api?format=text&EPHEM_TYPE=OBSERVER&QUANTITIES_[...]_ (Caused by SSLError(SSLError(1, '[SSL: UNSAFE_LEGACY_RENEGOTIATION_DISABLED] unsafe legacy renegotiation disabled (_ssl.c:997)')))

I really don't know how to bypass this issue.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

星軌x 2025-02-14 12:31:03

WARNING: When enabling Legacy Unsafe Renegotiation, SSL connections will be vulnerable to the Man-in-the-Middle prefix attack as described in

​bugs/1963834“ rel =“ noreferrer”> https://bugs.launchpad.net/bugs/1963834
and httpps://bugs.launchpad.net/bugs.net/bugs.net/bunbuntu/+subuntu/gnutlsource/gnutlsource/gnutlsource/gnutls28 /+bug/1856428

请注意编辑系统的openssl.conf,因为一旦更新OpenSSL,您可能会丢失更改。

在任何目录中使用这些内容创建一个自定义 openssl.cnf 文件:

openssl_conf = openssl_init

[openssl_init]
ssl_conf = ssl_sect

[ssl_sect]
system_default = system_default_sect

[system_default_sect]
Options = UnsafeLegacyRenegotiation

运行程序之前,请确保您的 openssl_conf 环境变量设置为您的自定义 openssl.cnf 在运行刮板时的完整路径:

OPENSSL_CONF=/path/to/custom/openssl.cnf python your_scraper.py

或类似:

export OPENSSL_CONF=/path/to/custom/openssl.cnf
python your_scraper.py

或者,如果您使用的是Pipenv或Systemd或Docker,请将其放入您的 .env 文件中

OPENSSL_CONF=/path/to/custom/openssl.cnf

WARNING: When enabling Legacy Unsafe Renegotiation, SSL connections will be vulnerable to the Man-in-the-Middle prefix attack as described in CVE-2009-3555.

With the help of https://bugs.launchpad.net/bugs/1963834
and https://bugs.launchpad.net/ubuntu/+source/gnutls28/+bug/1856428

Beware that editing your system's openssl.conf is not recommended, because you might lose your changes once openssl is updated.

Create a custom openssl.cnf file in any directory with these contents:

openssl_conf = openssl_init

[openssl_init]
ssl_conf = ssl_sect

[ssl_sect]
system_default = system_default_sect

[system_default_sect]
Options = UnsafeLegacyRenegotiation

Before running your program, make sure your OPENSSL_CONF environment variable is set to your custom openssl.cnf full path when running the scraper like so:

OPENSSL_CONF=/path/to/custom/openssl.cnf python your_scraper.py

or like so:

export OPENSSL_CONF=/path/to/custom/openssl.cnf
python your_scraper.py

or, if you are using pipenv or systemd or docker, place this into your .env file

OPENSSL_CONF=/path/to/custom/openssl.cnf
知你几分 2025-02-14 12:31:03

的完整代码段

import requests
import urllib3
import ssl


class CustomHttpAdapter (requests.adapters.HTTPAdapter):
    # "Transport adapter" that allows us to use custom ssl_context.

    def __init__(self, ssl_context=None, **kwargs):
        self.ssl_context = ssl_context
        super().__init__(**kwargs)

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


def get_legacy_session():
    ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
    ctx.options |= 0x4  # OP_LEGACY_SERVER_CONNECT
    session = requests.session()
    session.mount('https://', CustomHttpAdapter(ctx))
    return session

Harry Mallon 称呼:

get_legacy_session().get("some-url")

Complete code snippets for Harry Mallon's answer:

Define a method for reuse:

import requests
import urllib3
import ssl


class CustomHttpAdapter (requests.adapters.HTTPAdapter):
    # "Transport adapter" that allows us to use custom ssl_context.

    def __init__(self, ssl_context=None, **kwargs):
        self.ssl_context = ssl_context
        super().__init__(**kwargs)

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


def get_legacy_session():
    ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
    ctx.options |= 0x4  # OP_LEGACY_SERVER_CONNECT
    session = requests.session()
    session.mount('https://', CustomHttpAdapter(ctx))
    return session

Then use it in place of the requests call:

get_legacy_session().get("some-url")
场罚期间 2025-02-14 12:31:03

我在Linux上达到了相同的错误(当服务器不支持“ RFC 5746安全重新谈判”时发生,并且客户端使用OpenSSL 3(默认情况下执行该标准)。

这是一个解决方案(您可能必须稍微调整它)。

  1. 导入 ssl urllib3 在Python代码中
  2. 创建一个自定义HTTPADAPTER,该自定义HTTPADAPTER使用自定义 ssl 上下文
class CustomHttpAdapter (requests.adapters.HTTPAdapter):
    '''Transport adapter" that allows us to use custom ssl_context.'''

    def __init__(self, ssl_context=None, **kwargs):
        self.ssl_context = ssl_context
        super().__init__(**kwargs)

    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = urllib3.poolmanager.PoolManager(
            num_pools=connections, maxsize=maxsize,
            block=block, ssl_context=self.ssl_context)
  1. 设置一个<代码> ssl 上下文启用 op_legacy_server_connect ,并将其与您的自定义适配器一起使用。

ssl.op_legacy_server_connect 在python中尚无()。但是,事实证明,在openssl中,其值为比特菲尔德(Bitfield)中的0x4。因此,我们可以做以下操作。

ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ctx.options |= 0x4
session.mount('https://', CustomHttpAdapter(ctx))

I hit the same error on Linux (it happens when the server doesn't support "RFC 5746 secure renegotiation" and the client is using OpenSSL 3, which enforces that standard by default).

Here is a solution (you may have to adjust it slightly).

  1. Import ssl and urllib3 in your Python code
  2. Create a custom HttpAdapter which uses a custom ssl Context
class CustomHttpAdapter (requests.adapters.HTTPAdapter):
    '''Transport adapter" that allows us to use custom ssl_context.'''

    def __init__(self, ssl_context=None, **kwargs):
        self.ssl_context = ssl_context
        super().__init__(**kwargs)

    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = urllib3.poolmanager.PoolManager(
            num_pools=connections, maxsize=maxsize,
            block=block, ssl_context=self.ssl_context)
  1. Set up an ssl context which enables OP_LEGACY_SERVER_CONNECT, and use it with your custom adapter.

ssl.OP_LEGACY_SERVER_CONNECT is not available in Python yet (https://bugs.python.org/issue44888). However it turns out that in OpenSSL its value is 0x4 in the bitfield. So we can do the following.

ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ctx.options |= 0x4
session.mount('https://', CustomHttpAdapter(ctx))
z祗昰~ 2025-02-14 12:31:03

当使用OpenSSL 3将不支持它的服务器连接到服务器时,此错误会出现。解决方案是在Python中降级加密软件包:

Run PIP INSTALS gryptography == 36.0.2 在使用的环境中。

来源: https://github.com/scrapy/scrapy/scrapy/scrapy/scrapy/issues/issues/5491

编辑:请参阅Harry Mallon和Ahmkara的答案以进行修复,而无需降级密码学

This error comes up when using OpenSSL 3 to connect to a server which does not support it. The solution is to downgrade the cryptography package in python:

run pip install cryptography==36.0.2 in the used enviroment.

source: https://github.com/scrapy/scrapy/issues/5491

EDIT: Refer to Harry Mallon and ahmkara's answer for a fix without downgrading cryptography

┾廆蒐ゝ 2025-02-14 12:31:03

如果您想使用urlopen,该片段对我有用。

import ssl
import urllib.request

url = 'http://....'

# Set up SSL context to allow legacy TLS versions
ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ctx.options |= 0x4  # OP_LEGACY_SERVER_CONNECT

# Use urllib to open the URL and read the content
response = urllib.request.urlopen(url, context=ctx)

If you want to use urlopen, this snippet worked for me.

import ssl
import urllib.request

url = 'http://....'

# Set up SSL context to allow legacy TLS versions
ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ctx.options |= 0x4  # OP_LEGACY_SERVER_CONNECT

# Use urllib to open the URL and read the content
response = urllib.request.urlopen(url, context=ctx)
天冷不及心凉 2025-02-14 12:31:03

这并没有真正回答这个问题,但是同事从节点18转换为16,并停止遇到此错误。

This doesn't really answer the issue, but a coworker switched from Node 18 to 16 and stopped getting this error.

╰ゝ天使的微笑 2025-02-14 12:31:03

要解决Ruby中的相同问题,您可以在下面执行:

# Set OP_LEGACY_SERVER_CONNECT option
OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:options] |= OpenSSL::SSL::OP_LEGACY_SERVER_CONNECT

# Make a request
uri = URI('https://example.com')
res = Net::HTTP.post(uri, {}.to_json)

# Unset OP_LEGACY_SERVER_CONNECT option
OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:options] &= ~OpenSSL::SSL::OP_LEGACY_SERVER_CONNECT

To fix the same problem in ruby you can do below:

# Set OP_LEGACY_SERVER_CONNECT option
OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:options] |= OpenSSL::SSL::OP_LEGACY_SERVER_CONNECT

# Make a request
uri = URI('https://example.com')
res = Net::HTTP.post(uri, {}.to_json)

# Unset OP_LEGACY_SERVER_CONNECT option
OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:options] &= ~OpenSSL::SSL::OP_LEGACY_SERVER_CONNECT
平安喜乐 2025-02-14 12:31:03

如果您使用的是 conda ,通常Conda在每个环境中安装一个新的OpenSSL可执行文件。一个简单的修复方法是通过在环境中运行以下内容,将OpenSL降级到1.0。

conda install -n conda-env-name openssl=1

或查找针对特定Conda环境的OpenSL配置的位置,并遵循Jack Lee的答案。

您必须密切监视此网站的SSL版本,以确保您指定正确的频道。 https://anaconda.org/conda.org/conda-forge/conda-forge/openssl/labels

If you are using conda, usually conda installs a new openssl executable with each environment. One easy fix is to downgrade your openssl to 1.0 by running the following with your environment.

conda install -n conda-env-name openssl=1

Or find where the openssl config is for your specific conda environment and follow Jack Lee's answer.

You'll have to closely monitor the SSL versions from this website to ensure you specify the correct channel. https://anaconda.org/conda-forge/openssl/labels

东京女 2025-02-14 12:31:03

该线程上有很多答案。他们都没有完全满足我的需求,所以我认为我也会为自己的解决方案做出贡献。希望其他人发现它很有价值。

我的设置

我在Ubuntu上运行Python 3.10 22.04.2。我正在使用 aiohttp 对HTTP请求不同步。

我正在对内部LAN上的硬件提出HTTP请求,并且无法更新此硬件,以简单地停止使用不安全的SSL更新。

我的方法

我创建了一个自定义SSL上下文,然后通过SSL OP标志的SSL_OP_ALLO_ALLOD_UNSAFE_LEGACY_RENEGOTIATION'传递。我从这里得到了这个标志: ssl op flags

custom_ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
custom_ssl_context.options |= 0x00040000 # OP flag SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION

connector = aiohttp.TCPConnector(ssl=custom_ssl_context)

async with aiohttp.ClientSession(connector=connector) as session:
    async with session.get(url) as response:
        return await response.text()

SSL验证(例如,在开发测试的情况下),您可以将以下两行添加到custom_ssl_context:

custom_ssl_context.check_hostname = False
custom_ssl_context.verify_mode = ssl.CERT_NONE

There are quite a few answers on this thread. None of them quite met my needs, so I figured I'd contribute my own solution as well. Hopefully others find it valuable.

My Setup

I am running Python 3.10 on Ubuntu 22.04.2. I am using aiohttp to make HTTP requests asynchronously.

I am making an HTTP request to a piece of hardware on my internal LAN, and I cannot update this hardware to simply stop using the insecure SSL renegotiation.

My Approach

I created a custom SSL context, and then passed in the SSL OP flag 'SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION'. I got this flag from here: List of SSL OP Flags

custom_ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
custom_ssl_context.options |= 0x00040000 # OP flag SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION

connector = aiohttp.TCPConnector(ssl=custom_ssl_context)

async with aiohttp.ClientSession(connector=connector) as session:
    async with session.get(url) as response:
        return await response.text()

If you also need to disable SSL verification (in the case of development testing for example), you can add the following two lines to your custom_ssl_context:

custom_ssl_context.check_hostname = False
custom_ssl_context.verify_mode = ssl.CERT_NONE
冷情妓 2025-02-14 12:31:03

现在我解决问题 - [SSL错误不安全的遗产重新谈判禁用]
或(由sslerror引起(sslerror(1,'[ssl:unsafe_legacy_renegotiation_disabled]不安全的遗产重新接触(_SSSL.C:1007)'))))))))))))))))
下面的参考链接:但是不使用它只是尝试理解问题


使用以下代码:

import urllib.request
import ssl

# Create a secure SSL context
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)  # Use the appropriate protocol

url = "https://example.com"  # Replace with your URL
response = urllib.request.urlopen(url, context=ssl_context)

# Read and process the response
data = response.read().decode("utf-8")

Now I resolve issue it - [SSL error unsafe legacy renegotiation disabled]
or (Caused by SSLError(SSLError(1, '[SSL: UNSAFE_LEGACY_RENEGOTIATION_DISABLED] unsafe legacy renegotiation disabled (_ssl.c:1007)')))
reference link below : but it's not used just try to understand the problem

(SSL error unsafe legacy renegotiation disabled)
use below code :

import urllib.request
import ssl

# Create a secure SSL context
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)  # Use the appropriate protocol

url = "https://example.com"  # Replace with your URL
response = urllib.request.urlopen(url, context=ssl_context)

# Read and process the response
data = response.read().decode("utf-8")
柳絮泡泡 2025-02-14 12:31:03

对我来说,当我将python降级到 v3.10.8。

(如果您在Docker容器中遇到问题,请在下面阅读)时,

它有效,我在我的Docker Image中,我使用的是使用V3的Alpine-10 .10.9。由于我无法使用v3.10.8获得高山,因此我使用了3.10.8-slim-bullseye。

For me, it worked when I downgraded python to v3.10.8.

(If you are facing the issue in docker container, read below)

In my docker image, I was using alpine-10 which was using v3.10.9. Since I couldn't get alpine with v3.10.8, I used 3.10.8-slim-bullseye.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文