Python ssl.SSLError: WRONG_VERSION_NUMBER — Causes, Diagnostics, and Fixes
Short version: ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number means your Python client sent a TLS ClientHello to a port that answered with something that is not TLS — usually plaintext HTTP. It is a protocol mismatch, not a certificate problem, and verify=False will never fix it.
1. What WRONG_VERSION_NUMBER Actually Means
Every TLS record begins with a 5-byte header: one byte of content type, two bytes of record-layer version, two bytes of length. A TLS client opens with a handshake record — content type 0x16, version 0x0301 (yes, even for TLS 1.3). When the peer replies, OpenSSL parses the first five bytes of that reply as the same header. If those bytes do not form a valid TLS record header, OpenSSL raises SSL_R_WRONG_VERSION_NUMBER, which CPython surfaces as:
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1007)
Now put a plaintext HTTP server on the other end and look at what the client actually receives:
HTTP/1.1 400 Bad Request
Server: nginx
The first byte is H (0x48) and the next two are T T (0x54 0x54). OpenSSL reads 0x5454 as a protocol version, finds no match, and aborts. That is the entire error: the peer is not speaking TLS on that port.
Three consequences worth internalising before you start changing code:
- It is a transport failure, not a trust failure. No certificate is ever exchanged, so
verify=False, a custom CA bundle,certifiupgrades, orREQUESTS_CA_BUNDLEare all irrelevant. - SNI, hostname verification, and cipher negotiation never happen — the handshake dies in the first read.
- The
_ssl.c:NNNNsuffix is just a CPython source line number and differs per interpreter version:_ssl.c:1123on 3.9,_ssl.c:990on 3.11,_ssl.c:1007on 3.10/3.12. It tells you nothing about the fault.
2. The Six Causes You Will Actually Hit
- HTTPS pointed at a plaintext port. The classic case from the original write-up:
https://host:8443where 8443 is a plain HTTP listener (Spring Boot, uvicorn, Tomcat, a Node app, an admin UI). Also common on 8080, 8000, 3000, 5000, 9090, and even 443 when nginx haslisten 443;withoutssl. - Wrong service on the port entirely. SMTP on 25/587 (banner
220 mail.example.com ESMTP), MySQL on 3306 (binary greeting starting0x4a), Redis on 6379, FTP on 21, SSH on 22 — every one of these produces the identical exception. - A proxy that does not tunnel.
HTTPS_PROXYpoints at something that is not a CONNECT-capable proxy, or the proxy answers the CONNECT with a plaintext HTML error/407 page instead ofHTTP/1.1 200 Connection established. OpenSSL then reads<html>as a record header. - TLS terminated upstream. A load balancer, ingress controller, or service mesh terminates TLS and forwards plaintext HTTP to the backend. A client that tries HTTPS against the backend port fails; the fix is to speak HTTP to the backend or HTTPS to the edge.
- Interception. A captive portal, corporate TLS-inspecting firewall, or hotel Wi-Fi answers port 443 with a plaintext block/redirect page until you authenticate.
- Container port mapping.
docker-compose.ymlmaps8443:80onto an HTTP-only container, or a Kubernetes ServicetargetPortpoints at the plaintext container port while the client assumes TLS.
3. Confirm What Is Actually on the Port
Do this before touching Python. Four probes, in order of usefulness.
Probe 1 — plaintext HTTP request
curl -sS -I --max-time 5 http://api.example.com:8443/
If you get headers back (HTTP/1.1 200, HTTP/1.1 404, anything), the port speaks HTTP. That is your bug.
Probe 2 — TLS handshake
openssl s_client -connect api.example.com:8443 -servername api.example.com </dev/null
Interpretation:
CONNECTED(00000003)followed byHTTP/1.1 400 Bad Requestandno peer certificate available→ plaintext port. Confirmed.CONNECTEDfollowed by a certificate chain andVerify return code: 0 (ok)→ TLS works; your problem is client-side (proxy env vars, wrong hostname, wrong port).no peer certificate availablewithwrong version numberin the output → same conclusion as above.
Probe 3 — raw bytes
python3 - <<'PY'
import socket
s = socket.create_connection(('api.example.com', 8443), timeout=5)
s.sendall(b'GET / HTTP/1.0rnHost: api.example.comrnrn')
print(repr(s.recv(64)))
s.close()
PY
This prints the first bytes verbatim, which is the ground truth. b'HTTP/1.1 400' → HTTP. b'220 ' → SMTP. b'x15x03x03' → a real TLS alert record (a genuine TLS-level failure, look elsewhere).
Probe 4 — service fingerprint
nmap -Pn -sV -p 8443 api.example.com
Returns http vs ssl/http, which settles the question across a whole host range at once. Add --script ssl-enum-ciphers if the port really is TLS and you suspect a version/cipher problem.
4. Fixes by Scenario
4.1 The port is HTTP — pick a side
Either change the URL to http:// (only acceptable inside a trusted network or behind a service mesh), or terminate TLS on that port. Minimal nginx listener:
server {
listen 8443 ssl;
server_name api.example.com;
ssl_certificate /etc/ssl/certs/api.crt;
ssl_certificate_key /etc/ssl/private/api.key;
ssl_protocols TLSv1.2 TLSv1.3;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
For Python’s own servers, wrap the socket instead: ssl_context.wrap_socket(sock, server_side=True), or use uvicorn’s --ssl-keyfile / --ssl-certfile. Never expose a plaintext admin port to the internet just because the client was easier to fix.
4.2 Proxy environment variables
env | grep -i proxy
# HTTPS_PROXY=http://corp-proxy:8080
# NO_PROXY=localhost,127.0.0.1,.internal
curl -x http://corp-proxy:8080 -v https://api.example.com/ 2>&1 | head -20
If the proxy line shows CONNECT api.example.com:443 HTTP/1.1 followed by HTTP/1.1 200 Connection established, the proxy is fine. If you see an HTML body or a 407 without a tunnel, the proxy is the fault — fix the URL or add the host to NO_PROXY. In Python, bypass it explicitly when it should not apply:
import requests
session = requests.Session()
session.trust_env = False # ignore *_PROXY / .netrc / REQUESTS_CA_BUNDLE
r = session.get('https://api.example.com:8443/health',
timeout=(3.05, 10),
proxies={'http': None, 'https': None},
verify='/etc/ssl/certs/internal-ca.pem')
4.3 Docker and Kubernetes
docker port my-api # 8443/tcp -> 0.0.0.0:8443
docker inspect -f '{{range $p, $c := .NetworkSettings.Ports}}{{$p}} -> {{$c}}{{end}}' my-api
kubectl get svc my-api -o wide # check PORT(S) and targetPort
kubectl exec -it my-api -- curl -sI http://127.0.0.1:8080/ # is the container itself plaintext?
For an ingress that must talk TLS to the backend, annotate it: nginx.ingress.kubernetes.io/backend-protocol: "HTTPS". Without that annotation, an HTTPS client hitting the edge gets the plaintext backend and the same error.
5. Comparison Table: Reading the Evidence
| Command | What you see | What it means | Fix |
|---|---|---|---|
curl -I http://host:8443 |
HTTP/1.1 200 OK |
Port is plaintext HTTP | Use http:// or enable TLS on 8443 |
curl -I https://host:8443 |
error:0A00010B:SSL routines::wrong version number |
Same conclusion, from curl | Same as above |
openssl s_client -connect host:8443 |
HTTP/1.1 400, no peer certificate available |
Plaintext service answered the ClientHello | Scheme/port fix, or server-side TLS |
openssl s_client -connect host:443 |
Certificate chain, Verify return code: 0 (ok) |
TLS is healthy | Look at proxy env vars, hostname, client code |
| raw socket probe | b'220 mail.example.com ESMTP' |
SMTP, not HTTPS | Wrong port in config |
nmap -sV |
http vs ssl/http |
Service fingerprint | Route to the ssl/http port |
curl -x proxy -v https://... |
CONNECT ... 200 Connection established |
Proxy tunnels correctly | Fault is elsewhere |
curl -x proxy -v https://... |
Plain HTML after CONNECT |
Proxy is not a CONNECT proxy | Correct HTTPS_PROXY or add NO_PROXY |
6. Troubleshooting: Real Error Messages
6.1 The canonical requests traceback
requests.exceptions.SSLError: HTTPSConnectionPool(host='api.example.com', port=8443):
Max retries exceeded with url: /v1/ping
(Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1007)')))
Read it literally: the URL says HTTPS, the port is 8443, and the pool retried. Run probe 1 from section 3. Nine times out of ten curl -I http://api.example.com:8443/ answers instantly and the bug is the scheme.
6.2 SMTP on 587
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1123)
# raised by: smtplib.SMTP_SSL('mail.example.com', 587)
587 is a STARTTLS port: it starts in plaintext, sends a 220 banner, then upgrades. SMTP_SSL expects TLS from byte one. Use:
import smtplib, ssl
with smtplib.SMTP('mail.example.com', 587, timeout=10) as s:
s.starttls(context=ssl.create_default_context())
s.login(user, password)
Port 465 is the implicit-TLS port and does accept SMTP_SSL.
6.3 urllib3 behind a broken proxy
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='pypi.org', port=443):
Max retries exceeded with url: /simple/requests/
(Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1007)')))
Almost always HTTPS_PROXY pointing at an internal web app on 8080 that is not a proxy. Verify with curl -x http://proxy:8080 -v https://pypi.org/; if the CONNECT is not tunnelled, correct the proxy URL or add the host to NO_PROXY.
6.4 aiohttp in a container
aiohttp.client_exceptions.ClientConnectorSSLError:
Cannot connect to host api:8443 ssl:default [SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1007)')]
Host api is a Compose service name. Check that the published port maps to a TLS listener, not to the container’s HTTP port: docker port api, then docker exec api curl -sI http://127.0.0.1:8080/. If the container is plaintext, point the client at http://api:8080 or add a TLS terminator.
6.5 The mirror image: [SSL: HTTP_REQUEST]
ssl.SSLError: [SSL: HTTP_REQUEST] http request (_ssl.c:1007)
This is the opposite fault — a plaintext HTTP request arriving at a TLS port. If you see it in a server log, a client is using http:// against your HTTPS listener. Different error, same root cause family.
6.6 Errors that are not this one
| Error string | Meaning |
|---|---|
[SSL: UNKNOWN_PROTOCOL] unknown protocol |
First byte is not a known content type (MySQL greeting, binary protocol) |
[SSL: TLSV1_ALERT_PROTOCOL_VERSION] |
Genuine version mismatch — raise ctx.minimum_version or fix server ssl_protocols |
[SSL: WRONG_SSL_VERSION] |
Legacy SSLv3-era client/server negotiation |
[SSL: CERTIFICATE_VERIFY_FAILED] |
Trust problem — TLS worked, the chain did not validate |
[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] |
No shared cipher or signature algorithm |
7. Production-Grade Client Code
Once the port is correct, keep the client honest so a future mismatch fails loudly and diagnosably instead of silently downgrading:
import ssl
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
ctx = ssl.create_default_context(cafile='/etc/ssl/certs/internal-ca.pem')
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
ctx.check_hostname = True
session = requests.Session()
session.trust_env = False # no accidental proxy inheritance
session.mount('https://', HTTPAdapter(
max_retries=Retry(total=3, backoff_factor=0.5,
status_forcelist=(502, 503, 504))))
resp = session.get('https://api.example.com:8443/health',
timeout=(3.05, 10),
verify='/etc/ssl/certs/internal-ca.pem')
resp.raise_for_status()
Operational notes: set explicit connect and read timeouts (an unreachable TLS port otherwise hangs until the OS gives up); log type(exc).__name__ plus exc.args so WRONG_VERSION_NUMBER is distinguishable from CERTIFICATE_VERIFY_FAILED in your dashboards; and never put verify=False in a shared code path to “make the SSL error go away” — it cannot fix this error and it disables the check that would catch the next one.
8. FAQ
Is this a certificate problem?
No. The handshake aborts before any certificate is sent. verify=False, a custom CA bundle, or upgrading certifi will change nothing. The peer simply is not speaking TLS.
Why does curl work but Python raises the error?
Three usual reasons: curl was run against http://; curl ran in a shell without HTTPS_PROXY while the Python process inherited it from a systemd unit or container environment; or curl used -k/--noproxy and masked the difference. Compare env | grep -i proxy in both contexts.
Can a TLS 1.2 vs 1.3 mismatch cause WRONG_VERSION_NUMBER?
Practically no. A real version mismatch produces TLSV1_ALERT_PROTOCOL_VERSION, unsupported protocol, or VERSION_TOO_LOW. If you see WRONG_VERSION_NUMBER, the bytes on the wire are not TLS at all — check the port, not the cipher list.
It works sometimes and fails other times. How?
DNS round-robin or a load balancer with inconsistently configured nodes (one listener has ssl, another does not), a captive portal that only intercepts until you authenticate, or a connection pool reusing a socket that was opened through a proxy. Correlate failures with the resolved IP and with whether a proxy was used.
Can it happen on port 443?
Yes. A very common misconfiguration is listen 443; in nginx without the ssl keyword, or a plain HTTP service bound to 443. It also happens when a corporate middlebox intercepts 443 with an HTML block page.
Does it affect pip, git, or boto3 too?
Yes — anything built on OpenSSL and the system proxy settings. A broken HTTPS_PROXY typically breaks pip install, git clone https://..., and AWS SDK calls simultaneously. Fixing the proxy fixes all of them at once.
How do I verify the fix without changing the application?
Run the same request with curl and OpenSSL against the exact host and port, and confirm a certificate chain appears: curl -vI https://api.example.com:8443/ should print SSL certificate verify ok. If curl succeeds and Python still fails, the remaining variable is almost always proxy environment inheritance or an explicit port in the URL.
Is falling back to http:// acceptable?
Only inside a trusted network segment, a private VPC, or behind a mesh that enforces mTLS. Over the public internet, terminate TLS at a reverse proxy rather than dropping the scheme — a plaintext fallback silently ships credentials and tokens in the clear.