Fix jwt-token

This commit is contained in:
2025-09-12 21:01:30 +02:00
parent 86c43a0965
commit 729ec717c0
13 changed files with 715 additions and 96 deletions

19
ssl/.env.example Normal file
View File

@@ -0,0 +1,19 @@
# SSL Certificate Configuration
# Copy this to ssl/.env and customize the values
# Domain for SSL certificate (will also create wildcard *.domain if using DNS challenge)
DOMAIN=dev.uggla.uamils.com
# Email for Let's Encrypt notifications
EMAIL=admin@uggla.uamils.com
# Days before expiry to trigger renewal (default: 10)
RENEWAL_DAYS=10
# Loopia DNS API credentials (optional, for wildcard certificates)
# If not provided, will use HTTP challenge (main domain only)
LOOPIA_USER=your_loopia_username
LOOPIA_PASSWORD=your_loopia_password
# Webroot path for HTTP challenges (if not using DNS)
WEBROOT_PATH=/var/www/html

139
ssl/README.md Normal file
View File

@@ -0,0 +1,139 @@
# SSL Certificate Auto-Renewal with Cron
This directory contains scripts for managing SSL certificates with Let's Encrypt outside of Docker containers.
## Setup
1. **Install dependencies:**
```bash
sudo apt update
sudo apt install certbot nginx openssl
# Optional: For DNS challenges with Loopia
sudo pip install dns-lexicon[full]
```
2. **Configure environment:**
```bash
cp .env.example .env
nano .env # Edit with your domain and credentials
```
3. **Make scripts executable:**
```bash
chmod +x certbot-manager.sh loopia-hook.sh
```
## Usage
### Manual Certificate Management
```bash
# Check certificate status
./certbot-manager.sh status
# Check if renewal is needed
./certbot-manager.sh check
# Force certificate renewal
./certbot-manager.sh renew
# Auto-renew only if needed (for cron)
./certbot-manager.sh auto
```
### Automatic Renewal with Cron
1. **Setup cron job** (recommended - runs daily at 2 AM):
```bash
sudo crontab -e
```
Add this line:
```
0 2 * * * cd /path/to/your/project/ssl && source .env && ./certbot-manager.sh auto >> /var/log/letsencrypt/cron.log 2>&1
```
2. **Alternative: Setup systemd timer** (more modern approach):
```bash
sudo cp ssl-renewal.service /etc/systemd/system/
sudo cp ssl-renewal.timer /etc/systemd/system/
sudo systemctl enable ssl-renewal.timer
sudo systemctl start ssl-renewal.timer
```
## Certificate Types
### HTTP Challenge (Single Domain)
- Works for: `dev.uggla.uamils.com`
- Requirements: Port 80 accessible, nginx configured for ACME challenges
- No additional credentials needed
### DNS Challenge (Wildcard Support)
- Works for: `dev.uggla.uamils.com` and `*.dev.uggla.uamils.com`
- Requirements: Loopia DNS API credentials
- Set `LOOPIA_USER` and `LOOPIA_PASSWORD` in `.env`
## Nginx Configuration
Ensure your nginx configuration includes ACME challenge support:
```nginx
server {
listen 80;
server_name dev.uggla.uamils.com *.dev.uggla.uamils.com;
# ACME challenge location
location /.well-known/acme-challenge/ {
root /var/www/html;
try_files $uri =404;
}
# Redirect other traffic to HTTPS
location / {
return 301 https://$server_name$request_uri;
}
}
```
## Monitoring
### Check Certificate Status
```bash
./certbot-manager.sh status
```
### View Renewal Logs
```bash
tail -f /var/log/letsencrypt/renewal.log
```
### Check Cron Logs
```bash
tail -f /var/log/letsencrypt/cron.log
```
## Troubleshooting
### DNS Challenge Issues
- Verify Loopia credentials are correct
- Check DNS propagation: `dig _acme-challenge.dev.uamils.com TXT`
- Ensure API access is enabled in Loopia control panel
### HTTP Challenge Issues
- Verify port 80 is accessible from internet
- Check nginx configuration: `nginx -t`
- Ensure webroot path exists and is writable
### Permission Issues
- Ensure scripts are executable: `chmod +x *.sh`
- Run with sudo if accessing system directories
- Check log file permissions
## Files
- `certbot-manager.sh` - Main certificate management script
- `loopia-hook.sh` - DNS challenge hook for Loopia
- `.env.example` - Configuration template
- `ssl-renewal.service` - Systemd service file
- `ssl-renewal.timer` - Systemd timer file

279
ssl/certbot-manager.sh Normal file
View File

@@ -0,0 +1,279 @@
#!/bin/bash
# SSL Certificate Management Script for dev.uggla.uamils.com
# This script manages Let's Encrypt certificates for use with external nginx
set -e
# Configuration
DOMAIN="${DOMAIN:-dev.uggla.uamils.com}"
EMAIL="${EMAIL:-admin@uggla.uamils.com}"
RENEWAL_DAYS="${RENEWAL_DAYS:-10}"
CERT_DIR="/etc/letsencrypt"
WEBROOT_PATH="/var/www/html"
LOG_FILE="/var/log/letsencrypt/renewal.log"
# Loopia API credentials (optional, for DNS challenge)
LOOPIA_USER="${LOOPIA_USER:-}"
LOOPIA_PASSWORD="${LOOPIA_PASSWORD:-}"
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}
check_dependencies() {
local missing_deps=()
if ! command -v certbot >/dev/null 2>&1; then
missing_deps+=("certbot")
fi
if ! command -v nginx >/dev/null 2>&1; then
missing_deps+=("nginx")
fi
if ! command -v openssl >/dev/null 2>&1; then
missing_deps+=("openssl")
fi
if [[ ${#missing_deps[@]} -gt 0 ]]; then
log "ERROR: Missing dependencies: ${missing_deps[*]}"
log "Please install missing packages and try again"
exit 1
fi
}
check_certificate_expiry() {
local cert_path="$CERT_DIR/live/$DOMAIN/cert.pem"
if [[ ! -f "$cert_path" ]]; then
log "Certificate not found at $cert_path - will attempt to obtain new certificate"
return 1
fi
# Get certificate expiry date
local expiry_date=$(openssl x509 -in "$cert_path" -noout -enddate | cut -d= -f2)
local expiry_epoch=$(date -d "$expiry_date" +%s)
local current_epoch=$(date +%s)
local days_until_expiry=$(( (expiry_epoch - current_epoch) / 86400 ))
log "Certificate expires in $days_until_expiry days"
if [[ $days_until_expiry -le $RENEWAL_DAYS ]]; then
log "Certificate expires in $days_until_expiry days - renewal needed"
return 1
else
log "Certificate is valid for $days_until_expiry more days - no renewal needed"
return 0
fi
}
attempt_dns_challenge() {
log "Attempting DNS challenge..."
if [[ -z "$LOOPIA_USER" || -z "$LOOPIA_PASSWORD" ]]; then
log "LOOPIA_USER or LOOPIA_PASSWORD not set - skipping DNS challenge"
return 1
fi
# Check if dns-lexicon is available
if command -v lexicon >/dev/null 2>&1; then
log "Using dns-lexicon for DNS challenge..."
certbot certonly \
--dns-lexicon \
--dns-lexicon-provider loopia \
--dns-lexicon-loopia-username="$LOOPIA_USER" \
--dns-lexicon-loopia-password="$LOOPIA_PASSWORD" \
--email "$EMAIL" \
--agree-tos \
--non-interactive \
--expand \
-d "$DOMAIN" \
-d "*.$DOMAIN"
return $?
fi
# Fallback: Manual DNS with custom hook
if [[ -f "$(dirname "$0")/loopia-hook.sh" ]]; then
log "Using custom Loopia hook for DNS challenge..."
LOOPIA_USER="$LOOPIA_USER" LOOPIA_PASSWORD="$LOOPIA_PASSWORD" \
certbot certonly \
--manual \
--preferred-challenges dns \
--manual-auth-hook "$(dirname "$0")/loopia-hook.sh auth" \
--manual-cleanup-hook "$(dirname "$0")/loopia-hook.sh cleanup" \
--email "$EMAIL" \
--agree-tos \
--non-interactive \
--expand \
-d "$DOMAIN" \
-d "*.$DOMAIN"
return $?
fi
log "No DNS challenge method available"
return 1
}
attempt_http_challenge() {
log "Attempting HTTP challenge..."
# Ensure webroot directory exists
mkdir -p "$WEBROOT_PATH"
# Check if nginx is configured for ACME challenges
if ! nginx -t 2>/dev/null; then
log "WARNING: nginx configuration test failed"
fi
certbot certonly \
--webroot \
--webroot-path="$WEBROOT_PATH" \
--email "$EMAIL" \
--agree-tos \
--non-interactive \
--expand \
-d "$DOMAIN"
return $?
}
reload_nginx() {
log "Reloading nginx configuration..."
# Test nginx configuration first
if nginx -t; then
systemctl reload nginx || service nginx reload || nginx -s reload
log "Nginx reloaded successfully"
else
log "ERROR: nginx configuration test failed - not reloading"
return 1
fi
}
show_certificate_info() {
local cert_path="$CERT_DIR/live/$DOMAIN/cert.pem"
if [[ ! -f "$cert_path" ]]; then
log "No certificate found for $DOMAIN"
return 1
fi
log "Certificate Information:"
log "========================"
# Get certificate details
local subject=$(openssl x509 -in "$cert_path" -noout -subject | sed 's/subject=//')
local issuer=$(openssl x509 -in "$cert_path" -noout -issuer | sed 's/issuer=//')
local expiry_date=$(openssl x509 -in "$cert_path" -noout -enddate | cut -d= -f2)
local san=$(openssl x509 -in "$cert_path" -noout -text | grep -A1 "Subject Alternative Name" | tail -1 | sed 's/^[[:space:]]*//')
# Calculate days until expiry
local expiry_epoch=$(date -d "$expiry_date" +%s)
local current_epoch=$(date +%s)
local days_until_expiry=$(( (expiry_epoch - current_epoch) / 86400 ))
log " Domain: $DOMAIN"
log " Subject: $subject"
log " Issuer: $issuer"
log " SAN: $san"
log " Expires: $expiry_date"
log " Days until expiry: $days_until_expiry"
if [[ $days_until_expiry -le $RENEWAL_DAYS ]]; then
log " STATUS: ⚠️ Certificate expires soon - renewal recommended"
elif [[ $days_until_expiry -le 30 ]]; then
log " STATUS: ⚡ Certificate expires in less than 30 days"
else
log " STATUS: ✅ Certificate is valid"
fi
}
main() {
# Create log directory
mkdir -p "$(dirname "$LOG_FILE")"
log "Starting SSL certificate management for $DOMAIN"
# Check dependencies
check_dependencies
case "${1:-check}" in
"check")
log "Checking certificate status..."
if check_certificate_expiry; then
log "Certificate is valid - no action needed"
show_certificate_info
exit 0
else
log "Certificate renewal required"
exit 1
fi
;;
"renew")
log "Forcing certificate renewal..."
# Try DNS challenge first (for wildcard support)
if attempt_dns_challenge; then
log "DNS challenge successful!"
reload_nginx
show_certificate_info
log "Certificate renewal completed successfully"
exit 0
fi
# Fallback to HTTP challenge
log "DNS challenge failed - falling back to HTTP challenge"
if attempt_http_challenge; then
log "HTTP challenge successful!"
reload_nginx
show_certificate_info
log "Certificate renewal completed successfully"
exit 0
fi
log "ERROR: All certificate renewal attempts failed"
exit 1
;;
"status"|"info")
show_certificate_info
;;
"auto")
log "Auto-renewal check (runs only if needed)..."
if check_certificate_expiry; then
log "Certificate is valid - no renewal needed"
exit 0
else
log "Certificate needs renewal - attempting automatic renewal"
exec "$0" renew
fi
;;
*)
echo "SSL Certificate Management for $DOMAIN"
echo "======================================"
echo ""
echo "Usage: $0 [command]"
echo ""
echo "Commands:"
echo " check Check if certificate needs renewal"
echo " renew Force certificate renewal"
echo " status Show certificate information"
echo " auto Auto-renew only if needed (for cron)"
echo ""
echo "Environment variables:"
echo " DOMAIN Domain name (default: $DOMAIN)"
echo " EMAIL Email for Let's Encrypt (default: $EMAIL)"
echo " RENEWAL_DAYS Days before expiry to renew (default: $RENEWAL_DAYS)"
echo " LOOPIA_USER Loopia username for DNS challenge"
echo " LOOPIA_PASSWORD Loopia password for DNS challenge"
exit 0
;;
esac
}
# Run main function
main "$@"

158
ssl/loopia-hook.sh Normal file
View File

@@ -0,0 +1,158 @@
#!/bin/bash
# Loopia DNS API hook for certbot
# This script handles DNS TXT record creation and cleanup for Let's Encrypt challenges
set -e
LOOPIA_USER="${LOOPIA_USER:-}"
LOOPIA_PASSWORD="${LOOPIA_PASSWORD:-}"
LOOPIA_API_URL="https://api.loopia.se/RPCSERV"
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Loopia Hook: $1" >&2
}
# Extract domain and subdomain parts
extract_domain_parts() {
local full_domain="$1"
# For *.dev.uggla.uamils.com -> domain=uamils.com, subdomain=_acme-challenge.dev
# For dev.uggla.uamils.com -> domain=uamils.com, subdomain=_acme-challenge.dev
if [[ "$full_domain" == *.uamils.com ]]; then
DOMAIN="uamils.com"
local prefix="${full_domain%.uamils.com}"
if [[ "$prefix" == *"*"* ]]; then
# Wildcard domain *.dev.uggla.uamils.com
SUBDOMAIN="_acme-challenge.${prefix#*.}"
else
# Regular domain dev.uggla.uamils.com
SUBDOMAIN="_acme-challenge.$prefix"
fi
else
log "ERROR: Unsupported domain format: $full_domain"
exit 1
fi
}
# Call Loopia API
call_loopia_api() {
local method="$1"
shift
local params="$@"
curl -s -X POST "$LOOPIA_API_URL" \
-H "Content-Type: text/xml" \
-d "<?xml version=\"1.0\"?>
<methodCall>
<methodName>$method</methodName>
<params>
<param><value><string>$LOOPIA_USER</string></value></param>
<param><value><string>$LOOPIA_PASSWORD</string></value></param>
$params
</params>
</methodCall>"
}
# Add DNS TXT record
add_txt_record() {
local domain="$1"
local subdomain="$2"
local txt_value="$3"
log "Adding TXT record: $subdomain.$domain = $txt_value"
local response=$(call_loopia_api "addZoneRecord" \
"<param><value><string>$domain</string></value></param>
<param><value><string>$subdomain</string></value></param>
<param><value><struct>
<member>
<name>type</name>
<value><string>TXT</string></value>
</member>
<member>
<name>rdata</name>
<value><string>$txt_value</string></value>
</member>
<member>
<name>ttl</name>
<value><int>300</int></value>
</member>
</struct></value></param>")
if echo "$response" | grep -q "OK"; then
log "Successfully added TXT record"
else
log "ERROR adding TXT record: $response"
exit 1
fi
}
# Remove DNS TXT record
remove_txt_record() {
local domain="$1"
local subdomain="$2"
log "Removing TXT records for: $subdomain.$domain"
# Get existing records
local records=$(call_loopia_api "getZoneRecords" \
"<param><value><string>$domain</string></value></param>
<param><value><string>$subdomain</string></value></param>")
# Extract record IDs for TXT records
local record_ids=$(echo "$records" | grep -A5 "<name>type</name>" | grep -B5 "<string>TXT</string>" | grep "record_id" | sed 's/.*<int>\([0-9]*\)<\/int>.*/\1/')
for record_id in $record_ids; do
if [[ -n "$record_id" ]]; then
log "Removing TXT record ID: $record_id"
call_loopia_api "removeZoneRecord" \
"<param><value><string>$domain</string></value></param>
<param><value><string>$subdomain</string></value></param>
<param><value><int>$record_id</int></value></param>"
fi
done
}
# Main script logic
case "$1" in
"auth")
if [[ -z "$CERTBOT_DOMAIN" || -z "$CERTBOT_VALIDATION" ]]; then
log "ERROR: CERTBOT_DOMAIN or CERTBOT_VALIDATION not set"
exit 1
fi
if [[ -z "$LOOPIA_USER" || -z "$LOOPIA_PASSWORD" ]]; then
log "ERROR: LOOPIA_USER or LOOPIA_PASSWORD not set"
exit 1
fi
extract_domain_parts "$CERTBOT_DOMAIN"
add_txt_record "$DOMAIN" "$SUBDOMAIN" "$CERTBOT_VALIDATION"
# Wait for DNS propagation
log "Waiting 60 seconds for DNS propagation..."
sleep 60
;;
"cleanup")
if [[ -z "$CERTBOT_DOMAIN" ]]; then
log "ERROR: CERTBOT_DOMAIN not set"
exit 1
fi
if [[ -z "$LOOPIA_USER" || -z "$LOOPIA_PASSWORD" ]]; then
log "WARNING: LOOPIA_USER or LOOPIA_PASSWORD not set - skipping cleanup"
exit 0
fi
extract_domain_parts "$CERTBOT_DOMAIN"
remove_txt_record "$DOMAIN" "$SUBDOMAIN"
;;
*)
log "Usage: $0 {auth|cleanup}"
exit 1
;;
esac

94
ssl/setup.sh Normal file
View File

@@ -0,0 +1,94 @@
#!/bin/bash
# Quick setup script for SSL certificate management
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
echo "SSL Certificate Management Setup"
echo "==============================="
echo ""
# Check if running as root
if [[ $EUID -eq 0 ]]; then
echo "WARNING: Running as root. This is required for system-wide certificate management."
echo ""
fi
# Check dependencies
echo "Checking dependencies..."
missing_deps=()
if ! command -v certbot >/dev/null 2>&1; then
missing_deps+=("certbot")
fi
if ! command -v nginx >/dev/null 2>&1; then
missing_deps+=("nginx")
fi
if ! command -v openssl >/dev/null 2>&1; then
missing_deps+=("openssl")
fi
if [[ ${#missing_deps[@]} -gt 0 ]]; then
echo "❌ Missing dependencies: ${missing_deps[*]}"
echo ""
echo "Install them with:"
echo " sudo apt update"
echo " sudo apt install ${missing_deps[*]}"
echo ""
echo "For DNS challenges (optional):"
echo " sudo pip install dns-lexicon[full]"
exit 1
else
echo "✅ All dependencies found"
fi
# Make scripts executable
echo "Making scripts executable..."
chmod +x "$SCRIPT_DIR/certbot-manager.sh"
chmod +x "$SCRIPT_DIR/loopia-hook.sh"
echo "✅ Scripts are now executable"
# Setup environment file
if [[ ! -f "$SCRIPT_DIR/.env" ]]; then
echo "Creating .env file from template..."
cp "$SCRIPT_DIR/.env.example" "$SCRIPT_DIR/.env"
echo "📝 Please edit $SCRIPT_DIR/.env with your configuration:"
echo " nano $SCRIPT_DIR/.env"
echo ""
else
echo "✅ .env file already exists"
fi
# Create log directory
sudo mkdir -p /var/log/letsencrypt
echo "✅ Log directory created"
# Setup instructions
echo ""
echo "Setup Complete! 🎉"
echo "=================="
echo ""
echo "Next steps:"
echo "1. Edit configuration: nano $SCRIPT_DIR/.env"
echo "2. Test certificate: $SCRIPT_DIR/certbot-manager.sh check"
echo "3. Get certificate: $SCRIPT_DIR/certbot-manager.sh renew"
echo "4. Setup auto-renewal:"
echo ""
echo " Option A - Cron (simple):"
echo " sudo crontab -e"
echo " Add: 0 2 * * * cd $SCRIPT_DIR && source .env && ./certbot-manager.sh auto >> /var/log/letsencrypt/cron.log 2>&1"
echo ""
echo " Option B - Systemd (recommended):"
echo " sudo cp $SCRIPT_DIR/ssl-renewal.service /etc/systemd/system/"
echo " sudo cp $SCRIPT_DIR/ssl-renewal.timer /etc/systemd/system/"
echo " Edit paths in /etc/systemd/system/ssl-renewal.service"
echo " sudo systemctl enable ssl-renewal.timer"
echo " sudo systemctl start ssl-renewal.timer"
echo ""
echo "View logs with:"
echo " tail -f /var/log/letsencrypt/renewal.log"

12
ssl/ssl-renewal.service Normal file
View File

@@ -0,0 +1,12 @@
[Unit]
Description=SSL Certificate Renewal Service
After=network.target
[Service]
Type=oneshot
User=root
WorkingDirectory=/path/to/your/project/ssl
EnvironmentFile=/path/to/your/project/ssl/.env
ExecStart=/path/to/your/project/ssl/certbot-manager.sh auto
StandardOutput=journal
StandardError=journal

11
ssl/ssl-renewal.timer Normal file
View File

@@ -0,0 +1,11 @@
[Unit]
Description=Run SSL Certificate Renewal Daily
Requires=ssl-renewal.service
[Timer]
OnCalendar=daily
RandomizedDelaySec=3600
Persistent=true
[Install]
WantedBy=timers.target