#!/bin/bash

# Usage:
# bash <(curl -s https://scripts.justman10000.de/installers/opensslca.sh)

mkdir /home/ca
cd /home/ca

mkdir -p {certs,newcerts,private,crl}
touch index.txt
echo 1000 > serial

cat << 'EOF' > openssl.cnf
[ ca ]
default_ca = ca

[ ca ]
dir               = ./ca
certs             = $dir/certs
new_certs_dir     = $dir/newcerts
database          = $dir/index.txt
serial            = $dir/serial
private_key       = $dir/private/ca.key.pem
certificate       = $dir/certs/ca.cert.pem
crl_dir           = $dir/crl
default_days      = 3650
default_md        = sha256
policy            = policy_match
email_in_dn       = no
copy_extensions   = copy

[ policy_match ]
countryName             = optional
stateOrProvinceName     = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

[ req ]
distinguished_name = req_distinguished_name
default_bits       = 2048
default_md         = sha256
string_mask        = utf8only

[ req_distinguished_name ]
commonName = Common Name (e.g. your domain)
EOF

openssl genrsa -aes256 -out private/ca.key.pem 4096
chmod 400 private/ca.key.pem

openssl req -x509 -new -nodes -key private/ca.key.pem \
            -sha256 -days 1 \
            -out certs/ca.cert.pem \
            -subj "/C=DE/ST=Brandenburg/L=Bestensee/O=MyGServ/CN=mygserv.de"
chmod 444 certs/ca.cert.pem