Files

79 lines
2.7 KiB
Bash

#!/bin/sh
# Local lab7 PKI bootstrap. Never commit pki/: the CA key and leaf keys are
# operator-held material. Run from the repository root (Git Bash on Windows).
set -eu
# Git Bash on Windows rewrites arguments that look like Unix paths (e.g. the
# openssl -subj value). Keep the arguments byte-exact.
export MSYS_NO_PATHCONV=1
DAYS=825
PKI=${PKI_DIR:-pki}
mkdir -p "$PKI"
cd "$PKI"
if [ -f ca.crt ]; then
echo "PKI already exists in $PKI; delete it to regenerate."
exit 0
fi
write_ext() {
# $1 file, $2 san
cat > "$1" <<EOF
basicConstraints=CA:FALSE
keyUsage=digitalSignature,keyEncipherment
extendedKeyUsage=serverAuth,clientAuth
subjectAltName=$2
EOF
}
echo "==> CA"
openssl genrsa -out ca.key 4096 >/dev/null 2>&1
openssl req -x509 -new -key ca.key -sha256 -days $DAYS \
-subj "/CN=mtusi-lab7-local-ca" \
-addext "basicConstraints=critical,CA:TRUE" \
-addext "keyUsage=critical,keyCertSign,cRLSign" \
-out ca.crt >/dev/null 2>&1
issue() {
# $1 name, $2 CN, $3 SAN
openssl genrsa -out "$1.key" 2048 >/dev/null 2>&1
openssl req -new -key "$1.key" -subj "/CN=$2" -out "$1.csr" >/dev/null 2>&1
write_ext "$1.ext" "$3"
openssl x509 -req -in "$1.csr" -CA ca.crt -CAkey ca.key -CAcreateserial \
-days $DAYS -sha256 -extfile "$1.ext" -out "$1.crt" >/dev/null 2>&1
rm -f "$1.csr" "$1.ext"
chmod 600 "$1.key" 2>/dev/null || true
}
echo "==> leaf certificates"
issue server "localhost" "DNS:localhost,IP:127.0.0.1"
issue lb "lb" "DNS:lb"
issue gateway "api-gateway" "DNS:api-gw1,DNS:api-gw2,DNS:localhost"
issue postgres "postgres" "DNS:postgres"
issue minio "s3" "DNS:s3,DNS:minio,DNS:localhost"
issue broker "broker" "DNS:broker"
issue otel "otel-collector" "DNS:otel-collector"
issue openbao "openbao" "DNS:openbao,IP:127.0.0.1"
issue other "other-service" "DNS:other-service"
# A second, untrusted CA and a client certificate signed by it: used by the
# negative mTLS test (valid chain, but the wrong root).
echo "==> foreign CA (negative test only)"
openssl genrsa -out foreign-ca.key 2048 >/dev/null 2>&1
openssl req -x509 -new -key foreign-ca.key -sha256 -days $DAYS \
-subj "/CN=foreign-ca" \
-addext "basicConstraints=critical,CA:TRUE" \
-addext "keyUsage=critical,keyCertSign,cRLSign" \
-out foreign-ca.crt >/dev/null 2>&1
openssl genrsa -out foreign-client.key 2048 >/dev/null 2>&1
openssl req -new -key foreign-client.key -subj "/CN=foreign-client" -out foreign-client.csr >/dev/null 2>&1
write_ext foreign-client.ext "DNS:foreign-client"
openssl x509 -req -in foreign-client.csr -CA foreign-ca.crt -CAkey foreign-ca.key \
-CAcreateserial -days $DAYS -sha256 -extfile foreign-client.ext -out foreign-client.crt >/dev/null 2>&1
rm -f foreign-client.csr foreign-client.ext
rm -f ca.srl foreign-ca.srl
echo "PKI ready in $PKI/"
ls -1 *.crt