#!/bin/bash

# Copyright (C) 2018-2023 by Mike Gabriel <mike.gabriel@it-zukunft-schule.de>
# Copyright (C) 2023 Pädagogisches Landesinstitut Rheinland-Pfalz

# This script is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This script is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

set -e

NULL=""
DER_SSLDIR=/etc/debian-edu-router/ssl
PROXY_GROUP="proxy"

OPENSSL_CONF="${DER_SSLDIR}/openssl.d-e-r_sslmitm-ca.cnf"

mkdir -p ${DER_SSLDIR}/certs/
mkdir -p ${DER_SSLDIR}/private/
chown -Rf root:root ${DER_SSLDIR}
chmod 0755 ${DER_SSLDIR}/
chmod 0755 ${DER_SSLDIR}/certs
chmod 0710 ${DER_SSLDIR}/private
chown :${PROXY_GROUP} ${DER_SSLDIR}/private

export OPENSSL_CONF

# Create SSL bumping CA for Squid
if [ ! -e "${DER_SSLDIR}/private/d-e-r_sslmitm-ca.key" ] || [ -n "${RECREATE_DER_SSLMITM_CA}" ]; then
	openssl genrsa 4096 > ${DER_SSLDIR}/private/d-e-r_sslmitm-ca.key
	chmod 0640 ${DER_SSLDIR}/private/d-e-r_sslmitm-ca.key
	chown root:${PROXY_GROUP} ${DER_SSLDIR}/private/d-e-r_sslmitm-ca.key
fi

# The amount of days in which the CA certificate will expire.
# The CA must either be manually updated or you'll need to delete and
# re-generate the certificate using the loginmenu (d-e-r-p.l-c).
# Please note: The default (395 days) could be changed in the future. Please check:
# https://www.heise.de/en/news/TLS-certificates-Apple-proposes-a-maximum-term-of-10-days-9991943.html
# TLDR: Apple devices won't accept CA certs, which are valid for more than 397 days and
#       they propose to drop this amount even further.
MAX_CA_CERT_EXPIRE_DAYS="395"
if [ ! -e "${DER_SSLDIR}/certs/d-e-r_sslmitm-ca.crt" ] || [ -n "${RECREATE_DER_SSLMITM_CA}" ]; then
	openssl req -new						\
	            -x509						\
	            -days "${MAX_CA_CERT_EXPIRE_DAYS}"			\
	            -sha256						\
	            -key ${DER_SSLDIR}/private/d-e-r_sslmitm-ca.key	\
	            -out ${DER_SSLDIR}/certs/d-e-r_sslmitm-ca.crt	\
	            ${NULL}
fi

# Convert PEM format to DER format (CA-Cert only)
if [ ! -e "${DER_SSLDIR}/certs/d-e-r_sslmitm-ca.der" ] || [ -n "${RECREATE_DER_SSLMITM_CA}" ]; then
	openssl x509 -in ${DER_SSLDIR}/certs/d-e-r_sslmitm-ca.crt	\
	             -outform DER					\
	             -out ${DER_SSLDIR}/certs/d-e-r_sslmitm-ca.der	\
	             ${NULL}
fi
