From 1f47eb0245753d35dfacf4eb332a1eef0c327314 Mon Sep 17 00:00:00 2001 From: Platon47 <64787001+Platon47@users.noreply.github.com> Date: Sun, 15 Mar 2026 07:47:30 +0300 Subject: [PATCH] feat: add scripts/lego-renew.sh - ACME cert obtain/renew for IP This script automates the process of obtaining or validating TLS certificates for a given IP address using LEGO. It supports both automatic and manual modes depending on the presence of required environment variables. --- scripts/lego-renew.sh | 66 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 scripts/lego-renew.sh diff --git a/scripts/lego-renew.sh b/scripts/lego-renew.sh new file mode 100644 index 00000000..acbe224e --- /dev/null +++ b/scripts/lego-renew.sh @@ -0,0 +1,66 @@ +#!/bin/sh +#=== +# lego-renew.sh - Obtain or validate TLS cert for IP address +# +# Modes: +# AUTO (default): if LEGO_EMAIL and LEGO_IP are set, runs +# lego to obtain/renew a cert via http-01 or tls-alpn-01. +# MANUAL: if certs are pre-provisioned by the user and +# mounted at /root/cert/ip, just validates they exist. +#=== +set -eu + +CERT_DIR="/root/cert/ip" +CERT_FILE="${CERT_DIR}/fullchain.pem" +KEY_FILE="${CERT_DIR}/privkey.pem" +LEGO_EMAIL="${LEGO_EMAIL:-}" +LEGO_IP="${LEGO_IP:-}" +LEGO_CHALLENGE="${LEGO_CHALLENGE:-http}" +LEGO_DATA_DIR="${LEGO_DATA_DIR:-/root/lego-data}" + +if [ -n "$LEGO_EMAIL" ] && [ -n "$LEGO_IP" ]; then + echo "[tls] AUTO mode: running lego to obtain/renew cert for IP $LEGO_IP..." + mkdir -p "$LEGO_DATA_DIR" "$CERT_DIR" + + # Run lego - supports http-01 (port 80) and tls-alpn-01 (port 443) + lego \ + --email="$LEGO_EMAIL" \ + --domains="$LEGO_IP" \ + --http="${LEGO_CHALLENGE}" \ + --path="$LEGO_DATA_DIR" \ + run 2>&1 || lego \ + --email="$LEGO_EMAIL" \ + --domains="$LEGO_IP" \ + --http="${LEGO_CHALLENGE}" \ + --path="$LEGO_DATA_DIR" \ + renew --days 5 2>&1 + + # Symlink/copy cert to expected location + LEGO_CERT="${LEGO_DATA_DIR}/certificates/${LEGO_IP}.crt" + LEGO_KEY="${LEGO_DATA_DIR}/certificates/${LEGO_IP}.key" + if [ -f "$LEGO_CERT" ] && [ -f "$LEGO_KEY" ]; then + cp "$LEGO_CERT" "$CERT_FILE" + cp "$LEGO_KEY" "$KEY_FILE" + echo "[tls] Cert obtained and placed at $CERT_DIR/" + else + echo "[tls] ERROR: lego ran but cert not found at expected path" + echo "[tls] Expected: $LEGO_CERT" + exit 1 + fi +else + echo "[tls] MANUAL mode: validating pre-provisioned certs at $CERT_DIR/" + # Validate both certificate files exist + if [ ! -f "${CERT_FILE}" ] || [ ! -f "${KEY_FILE}" ]; then + echo "[tls] ERROR: Certificate files not found at $CERT_DIR/" + echo "[tls] Expected:" + echo "[tls] ${CERT_FILE}" + echo "[tls] ${KEY_FILE}" + echo "[tls] Either:" + echo "[tls] 1. Set LEGO_EMAIL and LEGO_IP for automatic cert issuance" + echo "[tls] 2. Pre-provision certs and mount them at $CERT_DIR (read-only)" + echo "[tls] chmod 600 $CERT_DIR/privkey.pem # on the host" + exit 1 + fi +fi + +echo "[tls] Certificate ready at ${CERT_DIR}/"