Skip to content

Instantly share code, notes, and snippets.

@wrouesnel
Created October 5, 2023 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrouesnel/50d5861659b97beb2c7f067ddac653b2 to your computer and use it in GitHub Desktop.
Save wrouesnel/50d5861659b97beb2c7f067ddac653b2 to your computer and use it in GitHub Desktop.
Script to move TLS certificates around in a container so they land in all commonly searched locations
#!/bin/bash
# See: https://stackoverflow.com/questions/59895/how-to-get-the-source-directory-of-a-bash-script-from-within-the-script-itself
# Note: you can't refactor this out: its at the top of every script so the scripts can find their includes.
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
function log() {
echo "$*" 1>&2
}
function fatal() {
echo "$*" 1>&2
exit 1
}
pushd "$SCRIPT_DIR" >/dev/null 2>&1 || fatal "Could not change dir"
for cmd in "find" "openssl" "cp" "mkdir"; do
if ! command -v "$cmd"; then
fatal "$cmd command not found"
fi
done
# Copies the certificates back and forth to ensure we wind up with one of
# each format.
mkdir "der" "pfx"
while read -r infile; do
inbase="$(basename "$infile")"
if ! openssl x509 -outform der -in "$infile" -out "der/${inbase%.*}.der"; then
fatal "Failed writing DER form"
fi
if ! openssl pkcs12 -passout pass: -export -out "pfx/${inbase%.*}.pfx" -nokeys -in "$infile"; then
fatal "Failed writing pfx form"
fi
done < <(find pem -type f)
# Build the unified pem
find pem -type f -exec cat {} + > ca-certificates.crt
# Build a subroot with a common set of locations to overwrite
mkdir root
# This list pulled from Go source code
bundle_locations=(\
"/etc/ssl/certs/ca-certificates.crt" \
"/etc/pki/tls/certs/ca-bundle.crt" \
"/etc/ssl/ca-bundle.pem" \
"/etc/pki/tls/cacert.pem" \
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem" \
"/etc/ssl/cert.pem" \
)
for path in "${bundle_locations[@]}"; do
mkdir -p "root/$(dirname "${path}")"
cp -f "ca-certificates.crt" "root/${path}"
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment