Skip to content
Projets

hundehausen/tor-hidden-service-docker

Voir sur GitHub

À propos

Create hidden services for your containers - everything in docker.

Systèmes et infrastructure

Comment ces chiffres sont mesurés

What you can do

  • 🪶 Minimal footprint - Alpine Linux base (~12MB)
  • 🎛️ Easy hidden services - Configure via environment variables
  • 🔒 Security-first - Runs as non-root user with minimal privileges
  • 🛡️ Input validation - Defense-in-depth against path traversal and injection

Progression mesurée des étoiles

in 24h
0
in 7 days
0
in 15 days
0
in 1 month
Historique en cours

Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.

README.md

Original

Tor Hidden Service Docker

Docker Build Tor Version Alpine Version

A lightweight, secure Docker container for running Tor hidden services. Built on Alpine Linux with a focus on minimal footprint and maximum security.

Table of Contents

🚀 Quick Start

# Create a network and a web service to expose
docker network create tor-net
docker run -d --name web --network tor-net nginx:alpine

# Run Tor; the volume keeps the .onion address across restarts
docker run -d --name my-tor-service --network tor-net \
  -e HS_WEB=web:80:80 \
  -v tor-data:/var/lib/tor \
  ghcr.io/hundehausen/tor-hidden-service:latest

# View your .onion address (printed about 10 seconds after start)
docker logs my-tor-service

Or use Docker Compose:

git clone https://github.com/hundehausen/tor-hidden-service-docker.git
cd tor-hidden-service-docker
docker compose up -d
docker compose logs -f tor

✨ Features

  • 🪶 Minimal footprint - Alpine Linux base (~12MB)
  • 🎛️ Easy hidden services - Configure via environment variables
  • 🔒 Security-first - Runs as non-root user with minimal privileges
  • 🛡️ Input validation - Defense-in-depth against path traversal and injection
  • 🔎 Auto-discovery - Onion addresses displayed in logs
  • 🔑 Key persistence - Reuse existing keys across restarts
  • 💓 Health checks - Built-in container health monitoring
  • 🛑 Graceful shutdown - Tor handles SIGTERM/SIGINT and exits cleanly on docker stop
  • 🏗️ Multi-arch - Supports linux/amd64 and linux/arm64

⚙️ How It Works

  1. The container runs a Tor daemon that registers your services on the Tor network
  2. Each HS_* environment variable creates a hidden service with its own .onion address
  3. Incoming connections to a .onion address are forwarded to the specified target container and port
  4. A SOCKS proxy on port 9050 is available for outbound Tor connections

📦 Usage

Basic Usage

docker run -d --name tor-hidden-service --network tor-net \
  -e HS_WEB=web-container:80:80 \
  -v tor-data:/var/lib/tor \
  ghcr.io/hundehausen/tor-hidden-service:latest

web-container must be reachable from the Tor container, for example by running both on the same Docker network. Without the volume, a new .onion address is generated on every recreate.

Docker Compose

services:
  web:
    image: nginx:alpine
    container_name: web-container
    volumes:
      - ./example-site:/usr/share/nginx/html
    networks:
      - tor-network

  tor:
    image: ghcr.io/hundehausen/tor-hidden-service:latest
    container_name: tor-hidden-service
    environment:
      - HS_WEB=web:80:80
      - SOCKS_BIND=127.0.0.1
    volumes:
      - tor-data:/var/lib/tor
    networks:
      - tor-network
    deploy:
      resources:
        limits:
          memory: 256M
          cpus: '0.5'

networks:
  tor-network:
    driver: bridge

volumes:
  tor-data:

Retrieving Onion Addresses

From container logs:

docker logs tor-hidden-service

Output:

======== TOR HIDDEN SERVICES ========
WEB: 2xxiyj6noereyty4xdxjg5akcop7ylnotvf4fqre57g7xuppy4tixvqd.onion
API: 7gtpkyhhhsbowew7zha6z7h7vlffqkn3nbu2f6hgin4xddq22o7yytyd.onion
====================================

From the filesystem:

# Get specific service address
docker exec tor-hidden-service cat /var/lib/tor/WEB/hostname

# List all services
docker exec tor-hidden-service ls /var/lib/tor/

🔧 Configuration

Environment Variables

Configure hidden services using the format:

HS_[SERVICE_NAME]=[TARGET_HOST]:[TARGET_PORT]:[VIRTUAL_PORT]
Variable Description Example
SERVICE_NAME Unique identifier (alphanumeric, hyphens, underscores) WEB, API, BLOG
TARGET_HOST Hostname or container name web, api.internal
TARGET_PORT Port the service listens on 80, 8080
VIRTUAL_PORT (Optional) Port exposed on .onion address, defaults to TARGET_PORT 80

Examples:

# Single service
HS_WEB=web-container:80:80

# Multiple services (each gets a unique .onion address)
HS_WEB=web:80:80
HS_API=api:8080:80
HS_BLOG=blog:3000:80

SOCKS Proxy

The container exposes a SOCKS5 proxy on port 9050 for routing traffic through Tor.

By default, the proxy binds to 0.0.0.0 (all interfaces). For production, restrict this to localhost:

environment:
  - SOCKS_BIND=127.0.0.1

Note: The default will change to 127.0.0.1 in a future major version.

Command-Line Arguments

You can also pass services as arguments:

docker run -d \
  -v tor-data:/var/lib/tor \
  ghcr.io/hundehausen/tor-hidden-service:latest \
  web:web-container:80:80 \
  api:api-container:8080:80

When every argument is a service definition, the container starts Tor with those services. Any other argument is run as the command instead, as in docker run <image> sh.

Custom torrc directives

Two env vars accept multi-line torrc content, appended to /var/lib/tor/torrc at boot:

Variable Where it lands Use for
TORRC After SocksPort, before any hidden service section Global directives
HSTORRC_<SERVICE> After that service's HiddenServicePort line Per-service directives (PoW, IntroDoS, MaxStreams, …)

Hyphens in service names become underscores (HS_MY-API → HSTORRC_MY_API). Tor validates directives at startup; bad config fails fast in the logs.

services:
  tor:
    image: ghcr.io/hundehausen/tor-hidden-service:latest
    environment:
      SOCKS_BIND: 127.0.0.1
      HS_WEB: web:80:80
      HS_API: api:8080:80

      TORRC: |
        ClientUseIPv6 1

      HSTORRC_WEB: |
        HiddenServicePoWDefensesEnabled 1
        HiddenServicePoWQueueRate 250
        HiddenServicePoWQueueBurst 1000
        HiddenServiceEnableIntroDoSDefense 1
        HiddenServiceEnableIntroDoSRatePerSec 25
        HiddenServiceEnableIntroDoSBurstPerSec 200

      HSTORRC_API: |
        HiddenServiceMaxStreams 50
        HiddenServiceMaxStreamsCloseCircuit 1

Inspect the rendered config:

docker exec tor-hidden-service cat /var/lib/tor/torrc

Client authorization

Client authorization hides a service from everyone without an authorized key. HSAUTH_<SERVICE> lists the clients as <client-name>:<public key>, separated by spaces or newlines:

services:
  tor:
    image: ghcr.io/hundehausen/tor-hidden-service:latest
    environment:
      HS_SSH: sshd:22:22
      HSAUTH_SSH: |
        laptop:T24H4MDCEVW52VOR2WMCTO3N53THCPE4FAVID4A6DYAQGWESJAGA
        phone:descriptor:x25519:FOUEX34UW5CQI3YUHMKMHGSBJCQU4KNOZIMCVUMPF3WOPF5RA44Q
  • Keys are base32 x25519 public keys (52 characters, no = padding), bare or as descriptor:x25519:<key>.
  • The list is complete: .auth files are rewritten at every start, so a removed client loses access at the next start.
  • Unset or empty leaves authorized_clients untouched: keys from earlier starts and hand-placed keys keep working. To turn client authorization off, also delete the .auth files.
  • Anything else (an invalid entry, a duplicate name, no client) stops the container.
  • Typos fail loudly: an HSAUTH_<SERVICE> with no matching HS_<SERVICE> also stops the container, so a misspelt name cannot silently leave a service public.

Hyphens in service names become underscores (HS_MY-API → HSAUTH_MY_API).

Generate a key pair on the client:

openssl genpkey -algorithm x25519 -out client.pem
# public key → HSAUTH_<SERVICE>
openssl pkey -in client.pem -pubout -outform DER | tail -c 32 | base32 | tr -d '='
# private key → the client's .auth_private file
openssl pkey -in client.pem -outform DER | tail -c 32 | base32 | tr -d '='

The client's .auth_private file holds <onion address without .onion>:descriptor:x25519:<private key>.

Inspect the written keys:

docker exec tor-hidden-service ls /var/lib/tor/SSH/authorized_clients

🛡️ Security

Hardening Checklist

  • 📊 Set resource limits - Prevent resource exhaustion (see Usage)
  • 🔐 Restrict SOCKS proxy - Set SOCKS_BIND=127.0.0.1 in production
  • 💾 Persist keys securely - Mount /var/lib/tor as a volume, never commit keys to git
  • 👤 Own your volumes - The container runs as uid 100 / gid 101; bind mounts must be owned by that user

Protecting Your Keys

The hs_ed25519_secret_key files in /var/lib/tor/[service]/ are the cryptographic identity of your .onion address. If compromised, an attacker can impersonate your service.

⚠️ Never commit private keys to version control.

Running as Non-Root

The container runs as the unprivileged tor user (uid 100, gid 101) and no process runs as root. Tor renders its configuration from the read-only /etc/tor/torrc into /var/lib/tor/torrc at startup, so /var/lib/tor must be writable by uid 100:

  • Named volumes work without changes; a fresh volume inherits ownership from the image.
  • Bind mounts must be owned by the container user: sudo chown -R 100:101 ./keys.
  • Kubernetes needs securityContext.runAsUser: 100, runAsGroup: 101, and fsGroup: 101.

Input Validation

The entrypoint script validates all inputs:

  • Service names - Alphanumeric, hyphens, and underscores only (max 64 chars)
  • Ports - Numeric, range 1-65535
  • Hostnames - No shell metacharacters allowed
  • Client authorization - Client names alphanumeric, hyphens, and underscores only; keys 52 base32 characters; HSAUTH_* must match a configured service
  • Path traversal - Prevented via allowlist and path verification

🔑 Key Persistence

Option 1: Full Directory Persistence

volumes:
  - tor-data:/var/lib/tor

Option 2: Selective Key Reuse

volumes:
  - tor-data:/var/lib/tor
  - ./backup-keys/WEB:/var/lib/tor/WEB  # Restore specific service
  - ./backup-keys/API:/var/lib/tor/API

Ownership: Bind-mounted key directories must be owned by uid 100 / gid 101 (sudo chown -R 100:101 ./backup-keys).

Backing Up Keys

# Copy keys from running container
docker cp tor-hidden-service:/var/lib/tor/WEB ./backup-keys/

# Or archive the entire volume
docker run --rm -v tor-data:/data -v $(pwd):/backup alpine \
  tar czf /backup/tor-keys.tar.gz -C /data .

📚 Examples

Static Website

services:
  nginx:
    image: nginx:alpine
    volumes:
      - ./website:/usr/share/nginx/html:ro
    networks:
      - tor

  tor:
    image: ghcr.io/hundehausen/tor-hidden-service:latest
    environment:
      - HS_SITE=nginx:80:80
      - SOCKS_BIND=127.0.0.1
    volumes:
      - tor-keys:/var/lib/tor
    networks:
      - tor

networks:
  tor:
volumes:
  tor-keys:

Multiple Services

services:
  web:
    image: nginx:alpine
    networks:
      - tor

  api:
    image: node:24-alpine
    networks:
      - tor

  tor:
    image: ghcr.io/hundehausen/tor-hidden-service:latest
    environment:
      - HS_WEBSITE=web:80:80
      - HS_API=api:3000:80
      - HS_ADMIN=api:8080:80
      - SOCKS_BIND=127.0.0.1
    volumes:
      - tor-data:/var/lib/tor
    networks:
      - tor

networks:
  tor:
volumes:
  tor-data:

💓 Health Checks

The container includes a health check that verifies Tor network connectivity:

  • Interval: 300 seconds (5 minutes)
  • Timeout: 3 seconds
  • Test: Resolves check.torproject.org through the SOCKS proxy with tor-resolve

Check health status:

docker ps --filter name=tor-hidden-service --format "table {{.Names}}\t{{.Status}}"

🔐 Supply Chain

Every published image on ghcr.io/hundehausen/tor-hidden-service ships with three attestations:

  • SBOM (Software Bill of Materials, SPDX 2.3) — every package inside the image
  • Provenance (SLSA v0.2) — how the image was built, from which commit, by which CI
  • Sigstore signature — keyless, signed via GitHub OIDC, recorded in Rekor

Pinned build inputs

Rebuilds resolve the same bytes:

  • Base image — alpine:3.24 pinned by digest in the Dockerfile
  • Alpine package — tor pinned to an exact version via the TOR_VERSION env var
  • GitHub Actions — pinned to commit SHAs

Dependabot raises PRs for base-image digest and Actions updates. It cannot track apk packages, so TOR_VERSION is bumped manually (pkgs.alpinelinux.org). If a build fails with unable to select packages, a pinned revision was removed from the v3.24 branch — update TOR_VERSION in the Dockerfile.

Verifying the signature

Requires cosign:

cosign verify ghcr.io/hundehausen/tor-hidden-service:latest \
  --certificate-identity-regexp 'https://github\.com/hundehausen/tor-hidden-service-docker/\.github/workflows/.+' \
  --certificate-oidc-issuer 'https://token.actions.githubusercontent.com'

Exit code 0 and a JSON payload listing one signature means the image was built by this repo's CI — not a third-party reupload.

Inspecting the SBOM

docker buildx imagetools inspect ghcr.io/hundehausen/tor-hidden-service:latest \
  --format '{{ json (index .SBOM "linux/amd64").SPDX }}'

Returns SPDX JSON listing every Alpine package and version inside the image.

Inspecting provenance

docker buildx imagetools inspect ghcr.io/hundehausen/tor-hidden-service:latest \
  --format '{{ json .Provenance }}'

Returns SLSA v0.2 JSON with the source repo URL, commit SHA, builder version, and platform. Confirms the image came from this repo's main branch at a specific commit.

🔍 Troubleshooting

Can't connect to hidden service

  1. Verify Tor bootstrap: docker logs tor-hidden-service | grep "Bootstrapped 100%"
  2. Check service configuration: docker exec tor-hidden-service cat /var/lib/tor/torrc
  3. Ensure target container is reachable: docker exec tor-hidden-service nc -z -w 3 web 80 (replace 80 with the target port). ping does not work because the container runs as the unprivileged tor user.

Onion address keeps changing

Keys are not being persisted. Add a volume for /var/lib/tor:

volumes:
  - tor-data:/var/lib/tor

High memory usage

Set resource limits in your compose file:

deploy:
  resources:
    limits:
      memory: 256M

Permission denied on /var/lib/tor

The container runs as uid 100 / gid 101. If you bind-mount a host directory, chown it first:

sudo chown -R 100:101 ./tor-data

🤝 Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.


Disclaimer: This tool is for legitimate privacy purposes only. Users are responsible for complying with all applicable laws and regulations in their jurisdiction.

Explorer des projets similaires

Chargement…