tor-container/assets/entrypoint.sh

67 lines
2.2 KiB
Bash
Executable file

#!/bin/sh
set -e
# --- Configuration ---
TOR_CONFIG="/etc/tor/torrc"
# Default to /var/lib/tor if not set
DATA_DIR="${TOR_DATA_DIR:-/var/lib/tor}"
echo "Starting Tor Configuration..."
# 1. Reset the Config File
echo "DataDirectory $DATA_DIR" > "$TOR_CONFIG"
echo "User tor" >> "$TOR_CONFIG"
# 2. Handle Control Password (The Magic Hashing)
if [ -n "$TOR_CONTROL_PASSWORD" ]; then
echo "Hashing provided control password..."
# Generate the hash using Tor itself
HASHED_PASSWORD=$(tor --quiet --hash-password "$TOR_CONTROL_PASSWORD" | tail -n 1)
if [ -z "$HASHED_PASSWORD" ]; then
echo "Error: Failed to hash password."
exit 1
fi
echo "ControlPort 0.0.0.0:9051" >> "$TOR_CONFIG"
echo "HashedControlPassword $HASHED_PASSWORD" >> "$TOR_CONFIG"
echo "Control Password set."
else
echo "Warning: No TOR_CONTROL_PASSWORD set. Control port disabled."
fi
# 3. Handle Hidden Services (The Magic Parsing)
# Expected Format: "80:container_name:80 22:container_name:22"
if [ -n "$HIDDEN_SERVICE_HOSTS" ]; then
echo "HiddenServiceDir $DATA_DIR/hidden_service/" >> "$TOR_CONFIG"
echo "HiddenServiceVersion 3" >> "$TOR_CONFIG"
# Split the string by spaces
for rule in $HIDDEN_SERVICE_HOSTS; do
# Validate format: Port:Host:Port (using grep regex)
if ! echo "$rule" | grep -qE '^[0-9]+:[a-zA-Z0-9.-]+:[0-9]+$'; then
echo "CRITICAL ERROR: Invalid format in HIDDEN_SERVICE_HOSTS: '$rule'"
echo "Expected format: ExternalPort:ContainerHost:InternalPort (e.g., 80:my-web:80)"
exit 1
fi
# Extract parts
EXT_PORT=$(echo "$rule" | cut -d: -f1)
HOST=$(echo "$rule" | cut -d: -f2)
INT_PORT=$(echo "$rule" | cut -d: -f3)
echo "Adding Hidden Service Rule: Onion:$EXT_PORT -> $HOST:$INT_PORT"
echo "HiddenServicePort $EXT_PORT $HOST:$INT_PORT" >> "$TOR_CONFIG"
done
else
echo "Error: HIDDEN_SERVICE_HOSTS is empty. Tor has nothing to serve."
exit 1
fi
# 4. Ownership Fix (Crucial for Docker volumes)
mkdir -p "$DATA_DIR/hidden_service/"
chown -R tor:root "$DATA_DIR"
chmod 700 "$DATA_DIR"
echo "Configuration successful. Starting Tor..."
exec tor -f "$TOR_CONFIG"