#!/bin/sh
echo "[CA] Generating CA key and certificate..."
openssl req -newkey 4096 -noenc -keyout ca.key                              \
            -x509 -out ca.crt -days 3650                                    \
            -subj "/O=Acme Corporation/CN=Certificate Vending Entity"       \
            -addext basicConstraints=critical,CA:TRUE                       \
            -addext keyUsage=critical,keyCertSign
echo "Done!"
# openssl x509 -in ca.crt -noout -text -certopt no_sigdump,no_pubkey
echo ""

echo "[Server] Generating server key and signing request..."
# https://datatracker.ietf.org/doc/html/rfc5246#section-7.4.2
openssl req -newkey 4096 -noenc -keyout server.key         \
            -new -out server.csr                           \
            -subj "/CN=$(hostname).cs.put.poznan.pl"       \
            -addext basicConstraints=critical,CA:FALSE     \
            -addext keyUsage=critical,digitalSignature     \
            -addext extendedKeyUsage=serverAuth            \
            -addext subjectAltName=DNS:$(hostname).cs.put.poznan.pl,DNS:$(hostname)
echo "Done!"
# openssl req -in server.csr -noout -text
echo ""

echo "[Server] sends signing request to [CA]"
echo "[CA] verifies if [Server] is indeed the [Server]"
echo "[CA] signs the public key"
echo "[CA] sends back certificate to [Server]"
openssl x509 -CA ca.crt -CAkey ca.key                       \
             -req -in server.csr -out server.crt -days 365  \
             -copy_extensions copy                          \
             -addtrust serverAuth
# openssl x509 -in server.crt -noout -text -certopt no_sigdump,no_pubkey
echo "Done!"
echo ""

echo "[Server] combines CA certificate(s) and its own certificate into a chain"
cat server.crt ca.crt > chain.pem
echo "Done!"
echo ""

