Ssl Handshake Failed
In this tutorial, you'll learn about SSL/TLS Handshake Failed Fix. We cover key concepts, practical examples, and best practices.
The SSL/TLS handshake establishes an encrypted connection between client and server. Handshake failures occur due to expired certificates, mismatched cipher suites, incorrect hostnames, incomplete certificate chains, or outdated TLS protocol versions.
The Wrong Way
import requests
try:
response = requests.get("https://self-signed.badssl.com")
print(response.status_code)
except requests.exceptions.SSLError as e:
print(f"SSL error: {e}")
Output:
SSL error: HTTPSConnectionPool(host='self-signed.badssl.com', port=443):
Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError))
The Right Way
Verify the certificate properly and handle SSL errors:
import requests
from requests.exceptions import SSLError
import ssl
import socket
def check_ssl(hostname, port=443):
try:
context = ssl.create_default_context()
with socket.create_connection((hostname, port), timeout=5) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
cert = ssock.getpeercert()
print(f"SSL handshake successful with {hostname}")
print(f"Certificate issuer: {cert['issuer']}")
print(f"Valid until: {cert['notAfter']}")
return True
except ssl.SSLCertVerificationError as e:
print(f"Certificate verification failed: {e}")
except ssl.SSLError as e:
print(f"SSL error: {e}")
except socket.timeout:
print(f"Connection timed out")
return False
check_ssl("example.com")
Step-by-Step Fix
1. Check certificate validity
# Check certificate details
openssl s_client -connect example.com:443 -servername example.com
# Check expiration
echo | openssl s_client -connect example.com:443 2>/dev/null | \
openssl x509 -noout -dates
2. Verify the certificate chain
# Show full chain
openssl s_client -connect example.com:443 -showcerts
# Verify chain
openssl verify -CAfile ca-cert.pem server-cert.pem
3. Update CA certificates
# Linux
sudo update-ca-certificates
# macOS
sudo security update-verify -certs -p ssl
4. Handle SSL errors explicitly
import requests
from requests.adapters import HTTPAdapter
from urllib3.poolmanager import PoolManager
import ssl
class TLSAdapter(HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
ctx = ssl.create_default_context()
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
kwargs["ssl_context"] = ctx
return super().init_poolmanager(*args, **kwargs)
session = requests.Session()
session.mount("https://", TLSAdapter())
5. Fix hostname mismatch
# The certificate must match the hostname
# Use the correct hostname that matches the certificate
response = requests.get("https://correct-hostname.example.com")
Prevention Tips
- Use certificates from trusted Certificate Authorities (not self-signed for production).
- Monitor certificate expiration dates and renew before expiry.
- Support TLS 1.2 and 1.3 only -- disable TLS 1.0 and 1.1.
- Include all intermediate certificates in the server configuration.
- Use tools like SSL Labs to audit your SSL configuration.
Common Mistakes with handshake failed
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world SSL code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro