跳到主要内容

curl: (51) SSL peer certificate or SSH remote key was not OK — Causes, Fixes, and Commands

curl: (51) SSL peer certificate or SSH remote key was not OK is one of those errors that hides two completely different problems behind one message. It fires either when curl’s TLS layer rejects the server certificate (HTTPS, FTPS, LDAPS, MQTT-over-TLS) or when curl’s SSH layer rejects the remote host key during an SFTP/SCP transfer. The fix is never the same, so the first job is to figure out which layer is failing.

One important detail before anything else: in curl 7.62.0 (October 2018) and later, exit code 51 was unified with exit code 60 (CURLE_SSL_CACERT). On a modern curl, an HTTPS certificate failure reports curl: (60), not 51. If you are seeing 51 today, you are most likely on an older curl build, a vendor-patched binary, or an SSH-based transfer.

What curl error 51 Actually Means

The constant behind the number is CURLE_PEER_FAILED_VERIFICATION: curl completed the connection far enough to receive the peer’s identity, and then decided it could not trust it. That single condition covers:

  • The X.509 certificate is expired or not yet valid.
  • The certificate does not cover the hostname you requested (SAN mismatch).
  • The chain is incomplete — a missing intermediate or an unknown root.
  • The local CA store does not contain (or no longer contains) the issuing root.
  • For SSH-backed URLs, the remote host key is not in known_hosts or has changed.

Confirm the build and TLS backend first, because the CA bundle path and the exact error wording depend on it:

curl --version | head -n 1
curl -V

The first line gives you version and backend (OpenSSL, GnuTLS, Schannel, Secure Transport, rustls). The feature list tells you whether SSH/SFTP support is even compiled in, which rules out half the possible causes immediately.

60-Second Triage: Four Commands

Run these before changing anything. They separate server-side certificate problems from client-side trust-store problems.

# 1. What does the backend say the verify result is? 0 = OK
curl -sS -o /dev/null -w '%{ssl_verify_result}n' https://example.com

# 2. Human-readable certificate summary
curl -vI https://example.com 2>&1 | grep -i -E 'subject:|issuer:|start date|expire date|SSL certificate verify'

# 3. Independent second opinion from OpenSSL
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null 
  | openssl x509 -noout -subject -issuer -dates -ext subjectAltName

# 4. Which CA bundle is this curl actually using?
curl-config --ca

The %{ssl_verify_result} value is the raw backend code: 10 means expired, 20 means unable to get the local issuer certificate, 62 means hostname mismatch, 18 means self-signed certificate. That single number usually ends the debate.

The critical diagnostic split is this: if the browser loads the site fine and curl does not, the problem is almost always on the client — a stale CA bundle, a curl built against a different trust store, or a corporate TLS-inspecting proxy. If the browser also warns, the problem is on the server.

Cause 1: Certificate Expired, Not Yet Valid, or Wrong Hostname

These are the two most common server-side failures and both produce unmistakable messages:

curl: (60) SSL certificate problem: certificate has expired
curl: (60) SSL: no alternative certificate subject name matches target host name 'api.example.com'

Check the validity window and the SAN list directly:

openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null 
  | openssl x509 -noout -dates -ext subjectAltName

If the dates look correct but curl still insists the certificate is expired, check the client clock. A container or VM that resumed from a snapshot with a frozen clock will reject a perfectly valid certificate:

date -u
timedatectl status        # systemd hosts
sudo chronyc tracking     # chrony hosts

For hostname mismatches, remember two rules that trip people up constantly. A wildcard *.example.com matches api.example.com but not api.staging.example.com and not the bare example.com. And certificates are validated against the hostname, not the IP — connecting to https://203.0.113.10/ against a cert issued for example.com will always fail unless the IP is in the SAN list.

To test a replacement certificate before you move DNS, point curl at the new address while keeping the correct SNI and Host header:

curl -vI --resolve example.com:443:203.0.113.10 https://example.com

Cause 2: Incomplete Chain or Untrusted Issuer

When the server sends only its leaf certificate and omits the intermediate, clients that cache intermediates (browsers) still succeed while strict clients (curl, Java, Go, Python requests) fail:

curl: (60) SSL certificate problem: unable to get local issuer certificate

Dump the full chain the server presents and look for the verify code at the bottom:

openssl s_client -showcerts -connect example.com:443 -servername example.com </dev/null 2>/dev/null 
  | grep -E '^ *[is]:|Verify return code'

Verify return code: 0 (ok) is the target. Codes 20 and 21 mean the chain is broken or the root is unknown; code 19 means the root is self-signed and not trusted.

If you have the leaf and intermediate as files, verify the chain locally without touching the network:

openssl verify -CAfile /etc/ssl/certs/ca-certificates.crt -untrusted intermediate.pem cert.pem

Fixing this is a server-side change: install the intermediate bundle in the web server (for nginx, ssl_certificate must point at the concatenation of leaf + intermediates, leaf first). Clients cannot fix a missing intermediate — they can only paper over it with --cacert pointing at the intermediate, which is a workaround, not a repair.

A related message, curl: (60) SSL certificate problem: self-signed certificate in certificate chain, almost always means a corporate TLS-inspection proxy is re-signing traffic with an internal root that curl does not trust. Import the corporate root rather than disabling verification:

curl --cacert /etc/pki/ca-trust/source/anchors/corp-root.pem https://internal.example.com

Cause 3: Stale CA Bundle on the Client

This is the classic “browser works, curl fails” scenario, and it has three common flavours: the OS trust store is out of date, curl was built against a private bundle (Homebrew, conda, static binaries, language runtimes shipping their own curl), or an environment variable is redirecting curl to the wrong file.

Check all three at once:

curl-config --ca
curl -V
openssl version -d
env | grep -E 'SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE'

Refresh the system store per distribution:

# Debian / Ubuntu
sudo apt-get install --reinstall ca-certificates
sudo update-ca-certificates --fresh

# RHEL / Fedora / CentOS Stream
sudo update-ca-trust extract
sudo dnf reinstall ca-certificates

# Alpine (very common in containers)
apk add --no-cache ca-certificates

# Arch
sudo trust extract-compat

On macOS with Homebrew curl, the system keychain is not used — this is the single most common cause of error 51/60 on developer laptops. Point curl at a maintained bundle explicitly:

brew install ca-certificates
export CURL_CA_BUNDLE="$(brew --prefix)/etc/ca-certificates/cert.pem"
# Homebrew's openssl@3 formula also ships one:
# export CURL_CA_BUNDLE="$(brew --prefix)/etc/openssl@3/cert.pem"

Inside containers, the fix is to install ca-certificates in the image at build time. A distroless or scratch image has no trust store at all, which produces the same “unable to get local issuer certificate” error no matter how valid the server certificate is.

Cause 4: SSH Host Key Changed or Unknown

If the failing URL starts with sftp:// or scp://, error 51 has nothing to do with X.509. curl performs its own host key verification against ~/.ssh/known_hosts, and it rejects unknown or changed keys exactly the same way SSH does.

Inspect what curl will see:

ssh-keygen -F sftp.example.com
ssh-keygen -F '[sftp.example.com]:2222'

Before deleting anything, verify the new fingerprint out of band — over a console, a documented internal wiki, or a signed key list. Do not trust a fingerprint you fetched over the same potentially compromised channel:

ssh-keyscan -t ed25519 -p 22 sftp.example.com 2>/dev/null | ssh-keygen -lf -

Once the fingerprint matches the expected value, remove the stale entry and reconnect:

ssh-keygen -R sftp.example.com
ssh-keygen -R '[sftp.example.com]:2222'

For automation where you cannot pre-seed known_hosts, pin the key on the command line instead of disabling verification:

curl --hostpubsha256 'SHA256:base64encodedfingerprint' sftp://user@sftp.example.com/backup.tar.gz -o backup.tar.gz

If the host key legitimately changed because the server was rebuilt, that is an operational event: update your configuration management, monitoring, and any pinned fingerprints in CI at the same time, or the next pipeline run will fail with the same error.

Comparison Table: Symptom to Fix

Error text or symptom Layer Most likely cause First command Fix
curl: (51) SSL peer certificate or SSH remote key was not OK on sftp:// SSH host key Key changed or not in known_hosts ssh-keygen -F host Verify fingerprint, then ssh-keygen -R host
curl: (60) SSL certificate problem: certificate has expired Server certificate Expired cert, or skewed client clock openssl s_client ... | openssl x509 -noout -dates Renew and reload; fix NTP
curl: (60) SSL: no alternative certificate subject name matches target host name Server certificate SAN does not cover the hostname openssl x509 -noout -ext subjectAltName Reissue cert, or correct the URL/SNI
curl: (60) SSL certificate problem: unable to get local issuer certificate Chain Missing intermediate openssl s_client -showcerts Install intermediate on the server
curl: (60) SSL certificate problem: self-signed certificate in certificate chain Chain / proxy Corporate MITM root not trusted curl --cacert corp-root.pem ... Add root to the trust store
Browser OK, curl fails on the same URL Client trust store Stale or wrong CA bundle curl-config --ca update-ca-certificates or set CURL_CA_BUNDLE
curl: (35) error:0A000410:SSL routines::sslv3 alert handshake failure TLS negotiation TLS version or cipher mismatch curl -v --tlsv1.2 Align protocol/cipher on client and server

Troubleshooting: Real Error Messages, Decoded

Work down this list; each entry is the literal string curl prints, followed by the shortest path to resolution.

  1. curl: (60) SSL certificate problem: certificate has expired — confirm with openssl x509 -noout -dates. If the notAfter date is in the future but curl still complains, run date -u. A container clock off by more than a few minutes produces this error with a valid certificate.

  2. curl: (60) SSL: no alternative certificate subject name matches target host name 'api.example.com' — dump the SAN list. Check for wildcard depth, trailing dots, and IDN encoding. Test the exact name with curl -vI --resolve api.example.com:443:203.0.113.10 https://api.example.com to rule out a load balancer serving the wrong certificate.

  3. curl: (60) SSL certificate problem: unable to get local issuer certificate — two possibilities. If OpenSSL’s s_client shows Verify return code: 0, the server chain is fine and your curl CA bundle is stale. If s_client also fails, the server is not sending the intermediate.

  4. curl: (60) SSL certificate problem: self-signed certificate in certificate chain — you are behind a TLS-inspecting proxy. Export the proxy root and use --cacert or install it into the system store. Never ship -k to production to silence this.

  5. curl: (51) SSL peer certificate or SSH remote key was not OK — if the URL is HTTPS and your curl is older than 7.62.0, treat it as error 60 and follow the certificate steps above. If the URL is sftp:// or scp://, go to the host-key procedure.

  6. curl: (35) OpenSSL/3.0.x: error:0A000086:SSL routines::certificate verify failed — the OpenSSL 3.x rewording of a verify failure. The underlying reason is in the line immediately above it in -v output; read that line, not this one.

For a quick sanity check that isolates curl from the network entirely, ask it to verify against an explicit bundle:

curl -vI --cacert /etc/ssl/certs/ca-certificates.crt https://example.com
curl -vI --capath /etc/ssl/certs https://example.com

And for OCSP stapling problems, which can also surface as verification failures on some backends:

curl -vI --cert-status https://example.com

Use -k/--insecure only as a 30-second diagnostic to prove the certificate layer is the blocker. It disables both TLS verification and SSH host key checking, and it turns a detectable attack into a silent one.

FAQ

Is curl -k an acceptable fix for error 51?
No. It suppresses the check rather than repairing it, and it disables host key verification for SSH URLs as well. Use it to confirm the diagnosis, then fix the certificate, the chain, the CA bundle, or the known_hosts entry.

Why does the site load in my browser but curl fails?
Browsers use the OS keychain and cache intermediates they have seen before. curl uses a fixed CA bundle compiled into or configured for that binary. On macOS with Homebrew curl, on Alpine containers, and on machines with a stale ca-certificates package, this divergence is expected. Compare curl-config --ca with the certificate’s issuer.

Does error 51 still exist for HTTPS?
Rarely. Since curl 7.62.0 the code was unified with 60, so HTTPS verification failures report 60. Seeing 51 on an HTTPS URL usually means an older curl, a vendor fork, or a wrapper script that maps exit codes.

How do I trust a private CA for one command only?
curl --cacert /path/to/root.pem https://host, or set CURL_CA_BUNDLE=/path/to/root.pem for the duration of a script. Avoid editing the system store for a one-off test.

How do I fix this inside a Docker image?
Add ca-certificates at build time — apk add --no-cache ca-certificates on Alpine, apt-get install -y ca-certificates on Debian slim. Scratch and distroless images have no trust store, so you must copy one in or switch base images.

How can I tell whether the problem is the server or my client?
Run openssl s_client -connect host:443 -servername host and read the Verify return code. Code 0 with a failing curl means the client trust store is the problem. A non-zero code means the server chain or certificate is the problem.

Is it safe to run ssh-keygen -R automatically in CI?
No. Blindly removing host keys defeats the protection. Pre-seed known_hosts from a trusted source during image build, or pin the key with curl --hostpubsha256.