#!/bin/bash if [ -r '#ETCDIR#/generate-and-upload-self-signed-keys.conf' ]; then . '#ETCDIR#/generate-and-upload-self-signed-keys.conf' fi key_dir='#ETCDIR#/nginx/keys' cd / hosts=$( find '#ETCDIR#/nginx/' \ -name keys -prune , \ -name sites-available -prune , \ \( -type f -o -type l \) \ -exec sed -n ' s/^\s*// /^server_name\s.*;/ p /^server_name[^;]*$/,/;/ p ' {} \; 2>/dev/null \ | tr '\n' ' ' \ | sed ' s/\s\+/ /g s/;\s*/;\n/g '"$( printf 's/\\s%s\\(;\\|\\s\)//\n' "${ignore_hosts[@]}" )"' ' \ | sed -n ' s/^server_name // T s/;$// T p ' \ | sort -u ) host_key_files=$( printf '%s\n' "${hosts}" \ | cut -d' ' -f1 ) if [ "$(whoami)" = 'root' ]; then updated_something=false for host_key_file in ${host_key_files}; do if [ -f "${key_dir}/${host_key_file}.key.pem.new" ] \ && [ -f "${key_dir}/${host_key_file}.cert.pem.new" ]; then if [ "$(stat -c%Y "${key_dir}/${host_key_file}.key.pem.new")" -ge "$(($(date +%s)-60*60*24*30))" ] \ && [ -f "${key_dir}/${host_key_file}.key.pem" ] \ && [ "$(stat -c%Y "${key_dir}/${host_key_file}.cert.pem.new")" -ge "$(($(date +%s)-60*60*24*30))" ] \ && [ -f "${key_dir}/${host_key_file}.cert.pem" ]; then continue fi mv "${key_dir}/${host_key_file}.key.pem"{.new,} mv "${key_dir}/${host_key_file}.cert.pem"{.new,} updated_something=true fi done if ${updated_something}; then systemctl try-restart nginx fi su http -s /bin/bash -c "$0" fi if [ "$(whoami)" != 'http' ]; then exit fi if [ -n "$(trap)" ]; then >&2 echo 'outer traps set - those will be forgotten!' exit 1 fi tmp_dir=$(mktemp -d '/srv/http/httpdocs/.csr/tmp.XXXXXXXXXX') trap 'rm -rf --one-file-system "${tmp_dir}"' EXIT printf '%s\n' "${hosts}" \ | while read -r host other_hosts; do if [ -f "${key_dir}/${host}.key.pem.new" ] \ && [ -f "${key_dir}/${host}.cert.pem.new" ]; then continue fi if [ -n "${other_hosts}" ]; then extensions="-addext subjectAltName=$( printf ',DNS:%s' \ "${host}" \ ${other_hosts} \ | sed 's/^,//' )" else extensions='' fi openssl req -newkey rsa:4096 \ -keyout "${key_dir}/${host}.key.pem.new" \ -out "${tmp_dir}/${host}.csr" \ -nodes -subj '/C=DE/ST=Thuringia/L=Jena/O=Eckner/OU=Net/CN='"${host}" -sha256 \ ${extensions} printf 'https://%s/.csr/%s/%s.csr %s %s\n' \ "${host}" \ "${tmp_dir##*/}" \ "${host}" \ '/C=DE/ST=Thuringia/L=Jena/O=Eckner/OU=Net/CN='"${host}" \ "${extensions}" \ >> "${tmp_dir}/commands" done if [ ! -s "${tmp_dir}/commands" ]; then >&2 echo 'nothing to do.' exit fi cd "${tmp_dir}" cut -d' ' -f1 \ < 'commands' \ | ssh -T erich@192.168.1.3 \ | tar -xzf - for host_key_file in ${host_key_files}; do [ -f "${tmp_dir}/${host_key_file}.crt" ] || continue cat "${tmp_dir}/${host_key_file}.crt" \ > "${key_dir}/${host_key_file}.cert.pem.new" done