Skip to content

Instantly share code, notes, and snippets.

@slavniyteo
Created December 28, 2017 09:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slavniyteo/ad58d1ca180229921fa792a88b494916 to your computer and use it in GitHub Desktop.
Save slavniyteo/ad58d1ca180229921fa792a88b494916 to your computer and use it in GitHub Desktop.
Download TLS certificate from server
#!/bin/sh
#================== Load certificate from server ===============================
HOST_NAME="${HOST_NAME:-google.com}"
SERVER_NAME="${SERVER_NAME:-${HOST_NAME}}"
PORT="${PORT:-443}"
FORMAT="${FORMAT:-PEM}" # DER|PEM|NET see `man x509`
FILE_NAME="${FILE_NAME}" # Filename into /usr/local/share/ca-certificates
CERT=$(openssl s_client \
-showcerts \
-connect "${HOST_NAME}:${PORT}" \
-servername "$SERVER_NAME" \
</dev/null 2>/dev/null \
| openssl x509 \
-outform ${FORMAT})
if [ $? -ne 0 ]; then exit 2; fi
#================== Print certificate to stdout and to file if need ============
if [ -n "$FILE_NAME" ]; then
FILE_NAME=/usr/local/share/ca-certificates/$FILE_NAME
else
FILE_NAME=""
fi
echo "$CERT" | tee $FILE_NAME
@lufte
Copy link

lufte commented Feb 8, 2022

Thanks, this helped me debug some issues with my TLS client. You could also pipe the result into openssl req -text -noout -in - to print the certificate's metadata instead of its body.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment