OnFinality
New RPC users get 35% off their first monthView the offer
OnFinality Learn
Troubleshooting9 min read

Python SSL Certificates: Verify TLS and Fix Certificate Errors

Find the cause of Python certificate verification failures, configure the right CA bundle, and confirm that your HTTPS RPC client works with verification enabled.

TL;DR

When Python reports `CERTIFICATE_VERIFY_FAILED`, keep verification enabled and determine whether the problem is the certificate chain, the hostname, the certificate validity period, or the trust store your client uses. For standard-library TLS, start with `ssl.create_default_context()`; for Requests, check which CA bundle the application actually uses. If the endpoint uses an approved private CA, configure that CA explicitly rather than trusting a certificate copied from the failing connection. This guide shows how to inspect the certificate and confirm the fix with a read-only HTTPS RPC call.

The right fix for a Python SSL certificate error

A Python client connecting to an HTTPS endpoint normally doesn't need a server certificate installed in the application. It needs a trust store that can validate the certificate presented by the server for the hostname in the URL. If a public endpoint serves an incomplete chain or an expired certificate, the fix belongs at the TLS terminator. If a private endpoint or an approved corporate proxy uses an internal certificate authority (CA), the client may need that CA in its trust store.

Don't use verify=False to fix the error. It disables server identity checks, so an encrypted connection can still be made to the wrong peer. For an RPC client, that can expose API credentials or allow a peer to return misleading responses. A separate case is mutual TLS (mTLS): a client certificate authenticates your application to the server, but it does not replace verification of the server certificate.

Prerequisites and the failing runtime

Run the diagnostics in the same virtual environment, container, or CI job that fails, using the same interpreter and network route. Testing from your laptop is useful for comparison, but a browser or another Python installation may use different trust roots or proxy settings. The first probe uses only the standard library. The application example requires Requests; install it with python -m pip install requests in a test environment, or use the version pinned by your application when reproducing a failure.

Set RPC_URL to your actual HTTPS endpoint outside the scripts. Treat the entire URL as a secret if it includes an API credential in the path or query string. Use OnFinality API service information and the network directory to confirm which endpoint you meant to configure. If you run a dedicated node deployment, identify where TLS terminates before changing certificates; it may be on a gateway or load balancer, not on the node.

Certificate chains, hostnames, and trust stores

The server presents a leaf certificate and normally sends the intermediate certificates needed to link it to a trusted root. The client uses those intermediates and its local trust material to build a valid chain. It also checks that the certificate is valid at the current time and covers the URL hostname, normally through a subject alternative name (SAN). A trusted CA signature does not make a certificate for one hostname valid for another. Server Name Indication (SNI) tells a shared TLS listener which hostname the client wants, so that it can present the appropriate certificate.

Python's ssl module uses OpenSSL. A default client context loads default trust material, which depends on the platform and Python distribution. Requests normally uses a CA bundle supplied by certifi, though distributions can package it differently. The bundle path returned by requests.certs.where() is a useful starting point, not proof of what a particular request used: an explicit verify path, an environment override, or an SDK's configuration can change the effective trust settings. See the Python ssl reference and Requests verification documentation.

Verified certificate inspection with Python ssl

Run this probe first with PRIVATE_CA_FILE unset to test Python's default TLS context. It connects directly to the URL hostname and port, supplies the hostname for SNI and identity verification, and does not send an HTTP request or transmit the URL path or query. On success it prints the negotiated TLS version and the verified leaf certificate's SANs and expiration in UTC. On a certificate verification failure it prints OpenSSL's verification code and message. DNS failures, timeouts, and other handshake failures may raise different exceptions.

This is a direct socket test: it does not follow HTTPS proxy settings, redirects, or SDK-specific transport configuration. If your application must use a proxy, run the application-path test below as well. A direct probe that succeeds while the application fails is evidence that the trust settings or network path may differ, not proof that the proxy is at fault.

import os
import socket
import ssl
from datetime import datetime, timezone
from urllib.parse import urlsplit

url = urlsplit(os.environ['RPC_URL'])
host = url.hostname
if url.scheme != 'https' or not host:
    raise SystemExit('Set RPC_URL to an HTTPS URL')
port = url.port if url.port is not None else 443

print('OpenSSL:', ssl.OPENSSL_VERSION)
print('Default verify paths:', ssl.get_default_verify_paths())
context = ssl.create_default_context()
if ca_file := os.environ.get('PRIVATE_CA_FILE'):
    context.load_verify_locations(cafile=ca_file)

try:
    with socket.create_connection((host, port), timeout=10) as tcp:
        with context.wrap_socket(tcp, server_hostname=host) as tls:
            cert = tls.getpeercert()
            expires = datetime.fromtimestamp(
                ssl.cert_time_to_seconds(cert['notAfter']), timezone.utc
            )
            print('TLS:', tls.version())
            print('Subject alternative names:', cert.get('subjectAltName', ()))
            print('Leaf expires (UTC):', expires.isoformat())
except ssl.SSLCertVerificationError as exc:
    raise SystemExit(f'Verification failed ({exc.verify_code}): {exc.verify_message}') from None

Private CA configuration without disabling verification

For a private endpoint or approved TLS inspection proxy, get the CA certificate from your PKI administrator or another authenticated distribution channel. Confirm its fingerprint against a trusted source before installing it. Don't fetch the certificate from the failing connection and immediately trust it: that connection hasn't established the peer's identity. For development servers, prefer issuing a hostname-correct leaf from a controlled development CA rather than treating an arbitrary self-signed leaf as a trusted authority.

In the socket probe, PRIVATE_CA_FILE adds a PEM CA file to the context after the defaults are loaded. With Requests, an explicit verify='/path/to/ca-bundle.pem' selects a bundle instead of extending the default one. Scope a private-only bundle to requests that need it. If one client must validate both private and public services with the same bundle, use an approved combined bundle maintained outside the certifi installation. Never put private keys in a trust bundle.

For ordinary Requests calls, REQUESTS_CA_BUNDLE can select a bundle when environment settings are enabled and no explicit CA path is passed; Requests can fall back to CURL_CA_BUNDLE if the former is unset. If you use Session.send() with a prepared request, merge environment settings explicitly or pass the intended CA path. Avoid editing certifi's installed file: package updates can overwrite the change, and other applications may inherit trust they don't need.

Application-path verification with Requests

Use a read-only method your endpoint supports. This example sends eth_chainId to an Ethereum-compatible JSON-RPC endpoint; for another protocol, substitute a documented read-only method and validate its expected result. Leave RPC_CA_BUNDLE unset to test ordinary Requests configuration, including any applicable environment override. Set it to an approved PEM bundle to test explicit trust. Redirects are disabled so the probe tests the configured URL rather than silently following it to another destination.

Success is a verified HTTPS connection and a valid chain ID that matches the network you intended. An HTTP error from the destination, such as 401, can occur after TLS verification succeeds; investigate authentication separately. A JSON-RPC error in an HTTP success response means the server responded but did not complete the method. Neither is a reason to change certificate settings. If your production SDK uses another HTTP transport, repeat the check with the SDK before declaring the issue resolved.

import os
import re
from urllib.parse import urlsplit

import requests

url = os.environ['RPC_URL']
parsed = urlsplit(url)
if parsed.scheme != 'https' or not parsed.hostname:
    raise SystemExit('Set RPC_URL to an HTTPS URL')

verify = os.environ.get('RPC_CA_BUNDLE') or True
print('Requests packaged CA path:', requests.certs.where())
try:
    response = requests.post(
        url,
        json={'jsonrpc': '2.0', 'id': 1, 'method': 'eth_chainId', 'params': []},
        verify=verify,
        timeout=(5, 10),
        allow_redirects=False,
    )
except requests.exceptions.SSLError:
    raise SystemExit('Requests reported a TLS error; check trust and the network path.') from None
except requests.exceptions.RequestException as exc:
    raise SystemExit(f'Request failed: {type(exc).__name__}') from None

if not 200 <= response.status_code < 300:
    raise SystemExit(f'Unexpected HTTP status: {response.status_code}')
try:
    payload = response.json()
except ValueError:
    raise SystemExit('Expected a JSON-RPC response, received non-JSON content.') from None
if not isinstance(payload, dict) or payload.get('jsonrpc') != '2.0' or payload.get('id') != 1:
    raise SystemExit('Unexpected JSON-RPC response envelope.')
if 'error' in payload:
    raise SystemExit('Endpoint returned a JSON-RPC error.')
result = payload.get('result')
if not isinstance(result, str) or not re.fullmatch(r'0x[0-9a-fA-F]+', result):
    raise SystemExit('Expected a hexadecimal chain ID.')
print('Verified HTTPS; chain ID:', int(result, 16))

Failure signatures and targeted repairs

Treat verification messages as clues rather than definitive diagnoses. Change one variable per retry and keep the hostname, runtime, and route fixed wherever possible. When you compare certificates from different clients, check that they used the same destination and SNI before drawing conclusions.

  • unable to get local issuer certificate: Check both sides. The server may omit an intermediate, or the client may lack the required trust root. Configure the TLS terminator to serve the complete leaf-and-intermediate chain if it is incomplete; update the client trust bundle if it is missing an approved root.
  • hostname mismatch or IP address mismatch: Use the configured DNS hostname in the URL. If an IP literal is intentional, the certificate must cover that IP as an IP SAN. When the URL is correct, inspect the certificate served for that SNI name.
  • certificate has expired or certificate is not yet valid: Check the runtime's clock and inspect the validity of the chain, not just the leaf. Renew or replace the affected certificate and confirm the TLS terminator is serving it.
  • self-signed certificate or self-signed certificate in certificate chain: Confirm whether private PKI or an approved interception proxy is expected. Verify the CA through a trusted channel before changing trust. Escalate an unexpected issuer rather than adding it.
  • wrong version number or a handshake error without a verification reason: Check scheme, port, proxy configuration, and TLS protocol compatibility before changing certificates. These errors need not involve CA trust.

Reproducible before-and-after verification

Record one row for the failing application path, one for the direct probe if that route is available, and one for the application path after the smallest justified change. Record Python and OpenSSL versions, Requests version where relevant, UTC time, and whether a proxy was in use. Keep raw environment dumps, credential-bearing URLs, and request headers out of shared logs. Use not observed when verification fails before the probe can report certificate details.

RunRuntime and routeTrust configurationTLS outcome or verification messageLeaf expiry (UTC), if observedHTTP/RPC outcome
Baseline applicationRecordRecordRecordRecord if observedRecord
Direct socket probeRecordRecordRecordRecord if observedNot tested
Application after fixRecordRecordRecordRecord if observedRecord

The pass condition is the original application succeeding with verification enabled and returning the expected RPC result. A direct handshake alone cannot establish that the application used the same certificate, proxy, or CA bundle. Conversely, a Requests success doesn't make the direct probe a valid monitor for a deployment that can only reach the endpoint through a proxy.

Certificate rotation and operational next steps

If you operate the endpoint, automate issuance and renewal at the component that terminates TLS, using an ACME client for an eligible public deployment or the approved workflow for private PKI. After deployment, check a fresh connection from the client network and verify that the new chain is served. For private CA rotation, distribute the new approved trust material before switching the served chain, then remove obsolete roots once dependent clients have migrated. For a managed endpoint with a confirmed server-side chain issue, report the hostname, UTC observation time, and sanitized verification reason to the operator.

Monitor both handshake failures and approaching expiry. The Python probe reports only the leaf's expiration and only after a verified handshake, so a failing check is itself an alert condition; a leaf date is not a guarantee that every intermediate will remain valid. Run a read-only application-path probe as well if proxies or SDK settings matter. For related integration workflows, continue in OnFinality Learn. If you set up recurring checks against a metered endpoint, review RPC pricing and request allowances before choosing the probe frequency.

RPC Assistant

Related RPC Assistant resources

Never Worry about Infrastructure Again

OnFinality takes away the heavy lifting of DevOps so you can build smarter and faster.

Get Started