Skip to content

Instantly share code, notes, and snippets.

@olivatooo
Created November 13, 2025 16:36
Show Gist options
  • Select an option

  • Save olivatooo/7fa1a5aae6955b79f38fe67dec84c1b7 to your computer and use it in GitHub Desktop.

Select an option

Save olivatooo/7fa1a5aae6955b79f38fe67dec84c1b7 to your computer and use it in GitHub Desktop.
Automatically fetch the CA certificate from a TLS server, (e.g., registry.local:443), install it into the system, trust store, and optionally restart k3s or docker.
#!/usr/bin/env bash
# ============================================================
# install-ca-from-server.sh
#
# Automatically fetch the CA certificate from a TLS server
# (e.g., registry.local:443), install it into the system
# trust store, and optionally restart k3s or docker.
#
# Usage:
# sudo ./install-ca-from-server.sh registry.local:443 [--restart k3s|docker]
# ============================================================
set -e
SERVER="$1"
RESTART_TARGET="$2"
if [[ -z "$SERVER" ]]; then
echo "Usage: $0 <host:port> [--restart k3s|docker]"
exit 1
fi
echo "πŸ” Fetching certificate chain from $SERVER ..."
TMPDIR=$(mktemp -d)
CHAIN_FILE="$TMPDIR/chain.pem"
CA_FILE="$TMPDIR/ca.crt"
# Fetch the full chain
openssl s_client -showcerts -connect "$SERVER" </dev/null \
| sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > "$CHAIN_FILE"
if [[ ! -s "$CHAIN_FILE" ]]; then
echo "❌ Failed to retrieve certificates from $SERVER"
exit 1
fi
echo "πŸ“¦ Extracting CA certificate ..."
# The last certificate in the chain is usually the CA
awk 'BEGIN {c=0} /BEGIN CERTIFICATE/{c++} {print > ("'"$TMPDIR"'/cert" c ".pem")}' "$CHAIN_FILE"
CA_CANDIDATE=$(ls "$TMPDIR"/cert*.pem | sort | tail -n1)
# Check if the certificate is self-signed (issuer == subject)
SUBJECT=$(openssl x509 -in "$CA_CANDIDATE" -noout -subject)
ISSUER=$(openssl x509 -in "$CA_CANDIDATE" -noout -issuer)
if [[ "$SUBJECT" == "$ISSUER" ]]; then
echo "🟒 Detected self-signed certificate β€” using it as CA."
cp "$CA_CANDIDATE" "$CA_FILE"
else
echo "🟑 Detected CA-signed chain β€” using last certificate as CA."
cp "$CA_CANDIDATE" "$CA_FILE"
fi
CN=$(openssl x509 -in "$CA_FILE" -noout -subject | sed 's/.*CN=//')
DEST="/usr/local/share/ca-certificates/${CN}.crt"
echo "πŸ“₯ Installing CA certificate to $DEST ..."
sudo cp "$CA_FILE" "$DEST"
echo "πŸ”„ Updating system trust store ..."
sudo update-ca-certificates
if [[ "$RESTART_TARGET" == "--restart" ]]; then
case "$3" in
k3s)
echo "πŸš€ Restarting K3s..."
sudo systemctl restart k3s
;;
docker)
echo "πŸš€ Restarting Docker..."
sudo systemctl restart docker
;;
*)
echo "⚠️ Unknown restart target: $3 (use k3s or docker)"
;;
esac
fi
echo "βœ… Done. CA from $SERVER is now trusted."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment