Security: HTTPS and Certificates, Secrets in Logs, and Server-Side Request Forgery
Secure an integration: make a real HTTPS connection with certificate checking and see the real errors for an untrusted certificate and a wrong hostname, redact secrets from logs, and block server-side request forgery with an allow-list, with cases checked against OpenSSL and the ipaddress module.
In this lesson you will
- Verify certificates and hostnames
- Read real TLS errors
- Redact secrets from logs
- Block SSRF with an allow-list
About 28 minutes
Three ways an integration leaks
The earlier lessons made integrations work and robust. This one makes them safe, because integrations carry secrets and money. First, the connection: HTTPS encrypts traffic, and certificate verification makes sure that you are talking to the real server and not to someone in the middle. A certificate states which host names it is valid for and is signed by an authority that your client trusts. Libraries verify this by default, and the worst mistake is to switch the verification off, in order to silence an error, which removes all the protection. In this lesson a small certificate authority and a server certificate are made with OpenSSL, so that the errors can be seen for real.
Second, the logs. When something fails, programs log the request, and the request has your API key in the header. Logs are copied to other systems and read by many people, so a secret in a log is a leaked secret. Redact keys, tokens and passwords before anything is written. Third, server-side request forgery, SSRF: if your server fetches a URL that a user provided, for example an image address or a webhook target, an attacker can point it at internal addresses, such as the cloud metadata service at 169.254.169.254, or services on localhost, and read secrets from inside your network. The defence is an allow-list of hosts that you expect, checks on the scheme and the resolved IP address, and a refusal of anything else.
| Risk | Defence |
|---|---|
| Man in the middle | HTTPS with certificate and hostname verification, never disabled |
| Secrets in logs | Redact keys, tokens and passwords before logging |
| SSRF | Allow-list hosts, allow only https, block private and link-local IPs |
| Stolen key | Short-lived tokens, least privilege, rotation |
import ssl, socket, subprocess, tempfile, os, threading, json, http.server
d = tempfile.mkdtemp()
def sh(*a): subprocess.run(a, cwd=d, check=True, capture_output=True)
sh("openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", "ca.key", "-out", "ca.pem", "-days", "2", "-subj", "/CN=Demo Test CA",
"-addext", "basicConstraints=critical,CA:TRUE", "-addext", "keyUsage=critical,keyCertSign,cRLSign", "-addext", "subjectKeyIdentifier=hash")
sh("openssl", "req", "-newkey", "rsa:2048", "-nodes", "-keyout", "srv.key", "-out", "srv.csr", "-subj", "/CN=localhost")
open(d + "/ext.cnf", "w").write("subjectAltName=DNS:localhost\nbasicConstraints=CA:FALSE\nkeyUsage=digitalSignature,keyEncipherment\nauthorityKeyIdentifier=keyid\n")
sh("openssl", "x509", "-req", "-in", "srv.csr", "-CA", "ca.pem", "-CAkey", "ca.key", "-CAcreateserial", "-out", "srv.pem", "-days", "2", "-extfile", "ext.cnf")
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
b = b'{"secure": true}'; self.send_response(200); self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
def log_message(self, *a): pass
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); ctx.load_cert_chain(d + "/srv.pem", d + "/srv.key")
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H); srv.daemon_threads = True; srv.socket = ctx.wrap_socket(srv.socket, server_side=True)
port = srv.server_address[1]; threading.Thread(target=srv.serve_forever, daemon=True).start()
import urllib.request
def fetch(host, context):
try: return "ok " + urllib.request.urlopen("https://%s:%d/" % (host, port), context=context, timeout=5).read().decode()
except Exception as e:
reason = getattr(e, "reason", e)
return "FAILED: " + type(reason).__name__ + " - " + str(getattr(reason, "verify_message", reason))
trusting = ssl.create_default_context(cafile=d + "/ca.pem")
print("1 trusted CA, host localhost :", fetch("localhost", trusting))
print("2 default trust store :", fetch("localhost", ssl.create_default_context()))
print("3 trusted CA, wrong host name :", fetch("127.0.0.1", trusting))
chain = subprocess.run(["openssl", "verify", "-CAfile", d + "/ca.pem", d + "/srv.pem"], capture_output=True, text=True).stdout.strip().replace(d + "/", "")
cert = subprocess.run(["openssl", "x509", "-in", d + "/srv.pem", "-noout", "-subject", "-issuer", "-ext", "subjectAltName"], capture_output=True, text=True).stdout
print("openssl verify:", chain)
print("certificate:", " | ".join(x.strip() for x in cert.strip().splitlines()))
peer = ssl.create_default_context(cafile=d + "/ca.pem").wrap_socket(socket.create_connection(("127.0.0.1", port)), server_hostname="localhost")
pc = peer.getpeercert(); print("python sees the same names:", pc["subjectAltName"], "| TLS version:", peer.version())
print("DATA " + json.dumps({"r1": fetch("localhost", trusting), "r2": fetch("localhost", ssl.create_default_context()), "r3": fetch("127.0.0.1", trusting), "verify": chain, "san": pc["subjectAltName"], "tls": peer.version()}))
srv.shutdown()
1 trusted CA, host localhost : ok {"secure": true}
2 default trust store : FAILED: SSLCertVerificationError - unable to get local issuer certificate
3 trusted CA, wrong host name : FAILED: SSLCertVerificationError - IP address mismatch, certificate is not valid for '127.0.0.1'.
openssl verify: srv.pem: OK
certificate: subject=CN = localhost | issuer=CN = Demo Test CA | X509v3 Subject Alternative Name: | DNS:localhost
python sees the same names: (('DNS', 'localhost'),) | TLS version: TLSv1.3
The script built a miniature public key infrastructure with OpenSSL: a certificate authority, which is a key and a self-signed certificate, and a server certificate for the name “localhost”, signed by that authority. A real HTTPS server on a local port used it. The first request trusted the authority and used the name in the certificate: it worked and returned {“secure”: true}. The second used the default trust store of the operating system, which does not know our private authority, and failed with the real error “unable to get local issuer certificate”. That is exactly what you see when a server’s certificate is not signed by an authority you trust, and the correct response is to fix the trust, not to disable verification.
The third request trusted the authority but connected by the address 127.0.0.1, and failed with “IP address mismatch, certificate is not valid for ‘127.0.0.1’.”: the certificate is valid only for the name “localhost”, and the client checks that the name it connected to is in the certificate’s subject alternative names. A certificate for the right authority and the wrong name is exactly what a man in the middle would present. The opposite of safe is the flag that turns verification off: with it, all three requests would succeed, and an attacker could read and change everything. Many tutorials suggest it to make an error go away, and it must never reach production.
Independent check: OpenSSL’s own verifier confirmed the chain from the certificate authority to the server certificate (“srv.pem: OK”), and printed the subject, the issuer, which is the demo authority, and the subject alternative name DNS:localhost. Python’s ssl module, a different front end to a library with the same engine, read the same name from the live connection: [[‘DNS’, ‘localhost’]]. The connection negotiated TLSv1.3, since modern defaults refuse older versions.
import re, json
PATTERNS = [
(re.compile(r"(?i)(authorization:\s*(?:bearer|basic)\s+)\S+"), r"\1[REDACTED]"),
(re.compile(r"(?i)(x-api-key:\s*)\S+"), r"\1[REDACTED]"),
(re.compile(r"(?i)([?&](?:key|api_key|token|password|secret)=)[^&\s]+"), r"\1[REDACTED]"),
(re.compile(r"(?i)(password=)[^&\s]+"), r"\1[REDACTED]"),
]
def redact(line):
for rx, sub in PATTERNS: line = rx.sub(sub, line)
return line
lines = ['GET /rates?key=sk_live_51Habc123def&weight=1250 HTTP/1.1', 'Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJub29yIn0.s1gn4tur3', 'X-Api-Key: demo-key-123', 'POST /login password=hunter2&user=noor', 'status 200 in 41 ms']
clean = [redact(l) for l in lines]
for a, b in zip(lines, clean): print(b)
secrets = ["sk_live_51Habc123def", "eyJhbGciOiJIUzI1NiJ9", "s1gn4tur3", "demo-key-123", "hunter2"]
leaks = [s for s in secrets if any(s in c for c in clean)]
print("secrets still visible in the cleaned log:", leaks)
print("DATA " + json.dumps({"clean": clean, "leaks": leaks}))
GET /rates?key=[REDACTED]&weight=1250 HTTP/1.1
Authorization: Bearer [REDACTED]
X-Api-Key: [REDACTED]
POST /login password=[REDACTED]&user=noor
status 200 in 41 ms
secrets still visible in the cleaned log: []
The redaction filter has four patterns: the Authorization header, the X-Api-Key header, secret-looking query parameters, and a password in a form body. The five sample log lines hold a live-looking key in a URL, a bearer token, an API key header, a password and a harmless status line. After redaction, none of the five secrets is visible, the list of leaks is empty, and the harmless line is untouched, so the log is still useful: it shows the path, the weight and the timing, and the fact that a key was sent, without the key. Redaction should happen in one place, the logging function, so that no caller can forget it, and the best defence is still not to log request headers and bodies at all. Rotate any key that has been logged unredacted.
import ipaddress, socket, urllib.parse, json
ALLOWED_HOSTS = {"api.courier.example", "hooks.shop.example"}
def check(url, resolve=lambda h: h):
p = urllib.parse.urlsplit(url)
if p.scheme != "https": return "refuse: scheme " + (p.scheme or "none")
if p.username or p.password: return "refuse: credentials in the URL"
host = (p.hostname or "").lower()
if host not in ALLOWED_HOSTS: return "refuse: host not allowed"
try: ip = ipaddress.ip_address(resolve(host))
except ValueError: return "refuse: not an IP address after resolving"
if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved: return "refuse: internal address " + str(ip)
return "allow"
public = {"api.courier.example": "93.184.216.34", "hooks.shop.example": "10.0.0.7"}
cases = [("https://api.courier.example/v1/rates", "good URL"), ("http://api.courier.example/v1/rates", "plain http"), ("https://evil.test/", "unknown host"),
("https://api.courier.example@evil.test/", "userinfo trick"), ("https://hooks.shop.example/in", "allowed name resolving to a private IP"),
("http://169.254.169.254/latest/meta-data/", "cloud metadata address"), ("http://2130706433/", "127.0.0.1 written as a number"), ("file:///etc/passwd", "file scheme"), ("https://localhost:8080/admin", "localhost")]
rows = []
for u, why in cases:
r = check(u, resolve=lambda h: public.get(h, h)); rows.append([u, why, r]); print(why.ljust(40), "->", r)
truth = {"169.254.169.254": ipaddress.ip_address("169.254.169.254").is_link_local, "2130706433": ipaddress.ip_address(int("2130706433")).is_loopback}
print("ipaddress module says: 169.254.169.254 is link-local:", truth["169.254.169.254"], "| the number 2130706433 is the loopback address", ipaddress.ip_address(int("2130706433")))
print("DATA " + json.dumps({"rows": rows}))
good URL -> allow
plain http -> refuse: scheme http
unknown host -> refuse: host not allowed
userinfo trick -> refuse: credentials in the URL
allowed name resolving to a private IP -> refuse: internal address 10.0.0.7
cloud metadata address -> refuse: scheme http
127.0.0.1 written as a number -> refuse: scheme http
file scheme -> refuse: scheme file
localhost -> refuse: host not allowed
ipaddress module says: 169.254.169.254 is link-local: True | the number 2130706433 is the loopback address 127.0.0.1
The SSRF filter applies four checks in order: the scheme must be https, the URL must carry no credentials, the host name must be on a short allow-list, and the address that the name resolves to must be public. Of nine URLs, only the good one was allowed. Plain http was refused. An address like https://api.courier.example@evil.test/ is the userinfo trick: everything before the at sign is a user name, so the real host is evil.test, which the filter sees through because it uses a proper URL parser and not string matching, and it refuses on the credentials. A name on the allow-list that resolves to the private address 10.0.0.7, which is how a DNS record can be turned against you, was refused too. The cloud metadata address, the number 2130706433 that equals 127.0.0.1, the file scheme and localhost were all refused by the first checks, and none of them would have passed the later ones.
The last line cross-checks two of the tricks with the ipaddress module, which knows the rules of address ranges and not the filter: 169.254.169.254 is a link-local address, the range used by metadata services, and the plain number 2130706433 is the loopback address 127.0.0.1 written in decimal. Attackers use such unusual spellings because naive filters compare strings. A real defence also fetches by the checked IP address, so that the name cannot resolve to something else between the check and the request, and does not follow redirects blindly, since a redirect can lead anywhere.
Check by hand: the number 2130706433 is 127 x 256 cubed plus 0 plus 0 plus 1, which is 2,130,706,433, so it is 127.0.0.1. The addresses 10.x.x.x, 172.16 to 172.31 and 192.168.x.x are private, 127.x.x.x is loopback, and 169.254.x.x is link-local.
Flags such as verify=False and rejectUnauthorized: false remove the protection of HTTPS completely. Fix the trust store or the certificate instead.
Parse with a real URL parser, allow-list the hosts, check the resolved IP address, restrict the scheme, and do not follow redirects without checking again.
Every program in this lesson was run while the course was written, with Python 3.13 (standard library only) against small mock APIs that the lesson itself starts on a local port, and cross-checked with curl, OpenSSL, Node.js or a second calculation. The services are invented stand-ins, not real vendors: always read the current documentation of the real API you use. The certificates in this lesson were made for a test and expire in two days. Production certificates come from a public authority, and many hosts obtain and renew them automatically.
Practice
Add a case for an IPv6 loopback address to the SSRF filter. Make the client send the checked IP address with the Host header. Write a test that proves that a logged request never contains an Authorization value.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does certificate verification protect against?
- Slow servers
- Large responses
- Bad JSON
- Talking to an impostor in the middle
Authority, name and validity are checked.
Why did the connection to 127.0.0.1 fail?
- The port was closed
- HTTPS is broken
- The certificate is valid for the name localhost, not the address
- The key expired
Hostname verification.
Where should secrets be redacted?
- In the database
- In the browser
- In the logging function, before writing
- Never
One place, so nobody forgets.
What is SSRF?
- A kind of certificate
- Making your server fetch an attacker-chosen internal URL
- A database attack
- A CSS bug
Server-side request forgery.
What is a good SSRF defence?
- A longer URL
- An allow-list of hosts plus checks on scheme and IP
- Hiding the port
- Logging more
Refuse everything else.
Summary
- Verify certificates and host names; never switch verification off.
- Redact secrets before logging.
- Defend against SSRF with an allow-list and IP checks.
- Verify the checks against independent tools.
Questions
Is verify=False ever acceptable?
Not in production. For local tests, install the test authority as trusted instead, as this lesson did.
How do I get certificates for my own server?
From a public certificate authority, many of which are free and automated. Check your hosting provider's documentation, and the Hosting and servers course.
Why rotate keys?
To limit the time during which a leaked key is useful. Rotate on a schedule and immediately after any suspected leak.
