Files
emailwiz/lib/tls.sh
T

64 lines
2.5 KiB
Bash

# emailwiz - TLS certificates: certbot issuance (TLS_MODE=certbot) and reload hook
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
tls_live_dir() { printf '/etc/letsencrypt/live/%s\n' "$MAIL_HOSTNAME"; }
tls_render() {
[ "$TLS_MODE" = certbot ] || return 0
render_template certbot-deploy-hook | stage_file \
/etc/letsencrypt/renewal-hooks/deploy/emailwiz-reload 755 root root -
}
# Print which program listens on TCP port 80: nginx, apache, none or other:NAME.
tls_port80_owner() {
_l=$(ss -Hltnp 'sport = :80' 2>/dev/null || :)
[ -n "$_l" ] || { echo none; return; }
case $_l in
*'"nginx"'*) echo nginx ;;
*'"apache2"'* | *'"httpd"'*) echo apache ;;
*) echo "other:$(printf '%s' "$_l" | sed -n 's/.*users:(("\([^"]*\)".*/\1/p' | head -1)" ;;
esac
}
# certbot certonly with the authenticator that fits port 80. nginx/apache
# authenticators only add the challenge temporarily and revert it, so no
# vhost is edited. A --dry-run against staging runs first.
tls_obtain() {
_live=$(tls_live_dir)
if [ -f "$_live/fullchain.pem" ] && [ -f "$_live/privkey.pem" ]; then
ok "certbot certificate for $MAIL_HOSTNAME already exists ($_live)"
return 0
fi
have certbot || die "certbot is not installed (run: sudo emailwiz install-packages)"
_owner=$(tls_port80_owner)
case $_owner in
nginx) _auth=--nginx; _plugin=python3-certbot-nginx ;;
apache) _auth=--apache; _plugin=python3-certbot-apache ;;
none) _auth=--standalone; _plugin= ;;
*) die "port 80 is used by ${_owner#other:}; stop it or obtain the certificate yourself and use TLS_MODE=external" ;;
esac
if [ -n "$_plugin" ] && ! pkg_installed "$_plugin"; then
log "installing $_plugin"
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$_plugin"
fi
_email=${CERTBOT_EMAIL:-postmaster@$DOMAIN}
log "requesting a certificate for $MAIL_HOSTNAME ($_auth, contact $_email)"
set -- certonly "$_auth" --non-interactive --agree-tos -m "$_email" \
--cert-name "$MAIL_HOSTNAME" -d "$MAIL_HOSTNAME"
certbot "$@" --dry-run || die "certbot dry run failed: check that $MAIL_HOSTNAME resolves here and port 80 is reachable"
certbot "$@" || die "certbot failed to obtain the certificate"
[ -f "$_live/fullchain.pem" ] || die "certbot reported success but $_live/fullchain.pem is missing"
ok "certificate obtained: $_live"
}
cmd_tls_obtain() {
need_root tls-obtain
MODE=apply
detect_os
config_load
config_validate
[ "$TLS_MODE" = certbot ] || die "TLS_MODE is '$TLS_MODE'; tls-obtain only applies to TLS_MODE=certbot" "$EX_USAGE"
tls_obtain
}