go-tor

module
v0.0.0-...-397ee07 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 6, 2026 License: BSD-3-Clause

README

go-tor

A pure Go implementation of the Tor protocol providing client functionality and bridge relay capabilities for educational and research purposes.

⚠️ IMPORTANT SAFETY NOTICE

THIS IS UNOFFICIAL SOFTWARE that has been developed without the supervision or endorsement of The Tor Project. This software should NOT be considered safe or production-ready.

For actual privacy and anonymity needs, please use official Tor software:

Do not rely on this software for:

  • Personal safety or anonymity
  • Protection from surveillance
  • Accessing sensitive information
  • Any production use case
  • Any situation where your safety depends on anonymity

This project is an experimental implementation for learning and research purposes only.


Description

go-tor is a cross-platform Tor client written entirely in Go without CGo dependencies. The package implements the core Tor protocol specifications including circuit management, cryptographic operations, SOCKS5 proxy serving, and v3 onion service support. This implementation prioritizes portability and embedded optimization while maintaining client feature parity with the reference C implementation.


Installation

Prerequisites
  • Go 1.24 or later
  • Git
Build from Source
git clone https://github.com/opd-ai/go-tor.git
cd go-tor
make build

The compiled binary will be available at bin/tor-client.

Docker Installation
# Build Docker image
docker build -t go-tor:latest .

# Run with SOCKS proxy on port 9050
docker run -d --name tor-client -p 9050:9050 go-tor:latest

Usage

Command-Line Client

Zero-configuration mode automatically detects settings and starts the Tor client:

# Run with default settings (SOCKS on port 9050)
./bin/tor-client

# Specify custom SOCKS port
./bin/tor-client -socks-port 9150

# Use configuration file
./bin/tor-client -config /etc/tor/torrc

# Enable HTTP metrics endpoint
./bin/tor-client -metrics-port 9052

First connection requires 60-90 seconds for consensus download and circuit building. Subsequent starts are faster.

Library Integration

Simplest integration using zero-configuration API:

package main

import (
    "time"
    "github.com/opd-ai/go-tor/pkg/client"
)

func main() {
    // Connect to Tor network (auto-configured)
    torClient, err := client.Connect()
    if err != nil {
        panic(err)
    }
    defer torClient.Close()
    
    // Wait for circuit establishment
    if err := torClient.WaitUntilReady(90 * time.Second); err != nil {
        panic(err)
    }
    
    // Get SOCKS5 proxy URL
    proxyURL := torClient.ProxyURL()  // "socks5://127.0.0.1:9050"
    _ = proxyURL // avoid unused variable error in this minimal example
    
    // Configure your HTTP client to use proxyURL
}
Advanced Configuration

Custom configuration with control protocol and metrics:

package main

import (
    "context"
    "time"
    "github.com/opd-ai/go-tor/pkg/client"
    "github.com/opd-ai/go-tor/pkg/config"
    "github.com/opd-ai/go-tor/pkg/logger"
)

func main() {
    cfg := config.DefaultConfig()
    cfg.SocksPort = 9150
    cfg.ControlPort = 9151
    cfg.CircuitBuildTimeout = 90 * time.Second
    cfg.EnableMetrics = true
    
    log := logger.NewDefault()
    torClient, err := client.New(cfg, log)
    if err != nil {
        panic(err)
    }
    
    err = torClient.Start(context.Background())
    if err != nil {
        panic(err)
    }
    defer torClient.Close()
}
HTTP Client Helper

Streamlined HTTP requests through Tor:

package main

import (
    "time"
    "github.com/opd-ai/go-tor/pkg/client"
    "github.com/opd-ai/go-tor/pkg/helpers"
)

func main() {
    torClient, err := client.Connect()
    if err != nil {
        panic(err)
    }
    defer torClient.Close()
    
    if err := torClient.WaitUntilReady(90 * time.Second); err != nil {
        panic(err)
    }
    
    // Create HTTP client configured for Tor
    httpClient, err := helpers.NewHTTPClient(torClient, nil)
    if err != nil {
        panic(err)
    }
    
    // Make requests through Tor network
    resp, err := httpClient.Get("https://check.torproject.org")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
}

Features

  • Cell Protocol - Fixed and variable-size cell encoding/decoding with relay cell support
  • Circuit Management - Complete circuit lifecycle including creation, extension, and teardown
  • Cryptography - AES-CTR, RSA-1024, SHA-1/256, Ed25519, and KDF-TOR key derivation
  • Directory Protocol - Consensus fetching and relay descriptor parsing
  • Path Selection - Guard, middle, and exit node selection with guard persistence
  • SOCKS5 Proxy - RFC 1928 compliant proxy server for application integration
  • Stream Multiplexing - Multiple data streams over single circuits
  • Control Protocol - Password-authenticated control interface with event notifications
  • Onion Services - v3 onion address support including client connections and service hosting
  • Client Authorization - x25519-based authentication for accessing private onion services
  • Circuit Padding - Adaptive Padding Engine (APE) with state machines for traffic analysis resistance
  • Connection Padding - Link-level PADDING/VPADDING cells for connection-level protection
  • Metrics & Observability - Prometheus, JSON, and HTML dashboard endpoints
  • Health Monitoring - Component-level health checks and status reporting
  • Resource Pooling - Circuit and connection pooling for performance optimization

Requirements

System Requirements
  • Linux, macOS, Windows, or BSD operating system
  • Network connectivity to Tor directory authorities
  • 50MB+ available RAM
Go Dependencies

Key dependencies from go.mod:

  • go.opentelemetry.io/otel - Distributed tracing and observability
  • golang.org/x/crypto - Cryptographic primitives
  • golang.org/x/net - Network protocol utilities
  • github.com/gofrs/flock - File locking for guard persistence
  • github.com/cretz/bine - Tor controller library

Cross-Implementation Testing

go-tor includes a test suite that validates protocol compliance against known-good vectors from C Tor (the reference implementation) and Arti (the Rust implementation). This ensures interoperability at the wire level.

Covered Operations
Operation Spec Section C Tor Arti
SHA-1 tor-spec §0.3
SHA-256 tor-spec §0.3
AES-128/256-CTR tor-spec §0.4
HKDF-SHA256 (ntor) tor-spec §5.1.4
ntor handshake tor-spec §5.1.4
KDF-TOR tor-spec §5.2.1
Fixed cell encoding tor-spec §3
Variable cell encoding tor-spec §3
Running Cross-Implementation Tests
# Run only cross-implementation tests
go test -run TestCrossImpl ./pkg/crypto/... ./pkg/cell/...

# Run with race detector
go test -race -run TestCrossImpl ./pkg/crypto/... ./pkg/cell/...

Test vectors are stored in testdata/ at the repository root. See testdata/README.md for vector sources and update instructions.


License

BSD 3-Clause License

Copyright (c) 2024, OPD AI. See LICENSE for full license text.


References

Directories

Path Synopsis
cmd
benchmark command
Package main provides a command-line tool for running comprehensive performance benchmarks on the go-tor Tor client implementation.
Package main provides a command-line tool for running comprehensive performance benchmarks on the go-tor Tor client implementation.
tor-client command
Package main provides the Tor client executable.
Package main provides the Tor client executable.
tor-config-validator command
Package main provides a configuration validation and generation tool for go-tor.
Package main provides a configuration validation and generation tool for go-tor.
torctl command
Package main provides a control utility for interacting with a running go-tor client.
Package main provides a control utility for interacting with a running go-tor client.
examples
basic-usage command
Example: Simple usage of go-tor packages
Example: Simple usage of go-tor packages
bridge-config command
bridge-descriptor command
Package main demonstrates server descriptor generation for bridge relays.
Package main demonstrates server descriptor generation for bridge relays.
bridgedb-demo command
Example demonstrating BridgeDB integration for educational purposes
Example demonstrating BridgeDB integration for educational purposes
circuit-ratelimit command
Package main demonstrates circuit rate limiting to protect against DoS.
Package main demonstrates circuit rate limiting to protect against DoS.
cli-tools-demo command
Package main demonstrates the CLI tools for go-tor
Package main demonstrates the CLI tools for go-tor
config-demo command
Package main demonstrates the configuration file loading functionality.
Package main demonstrates the configuration file loading functionality.
config-validation-demo command
Package main demonstrates configuration validation and schema generation features.
Package main demonstrates configuration validation and schema generation features.
connection-padding command
Package main demonstrates connection-level padding usage.
Package main demonstrates connection-level padding usage.
consensus_padding command
Example: Using consensus parameters for padding configuration
Example: Using consensus parameters for padding configuration
context-demo command
Package main demonstrates context-aware operations for improved timeout and cancellation control.
Package main demonstrates context-aware operations for improved timeout and cancellation control.
control-auth command
Package main demonstrates control protocol password authentication
Package main demonstrates control protocol password authentication
control-config command
Example demonstrating GETCONF/SETCONF control protocol commands
Example demonstrating GETCONF/SETCONF control protocol commands
control-getinfo command
Example demonstrating enhanced GETINFO command coverage in control protocol
Example demonstrating enhanced GETINFO command coverage in control protocol
control-runtime-config command
Package main demonstrates runtime configuration updates via SETCONF
Package main demonstrates runtime configuration updates via SETCONF
control_config command
Package main demonstrates enhanced GETCONF/SETCONF control protocol functionality.
Package main demonstrates enhanced GETCONF/SETCONF control protocol functionality.
descriptor-demo command
Package main demonstrates descriptor management functionality
Package main demonstrates descriptor management functionality
errors-demo command
Package main demonstrates structured error handling.
Package main demonstrates structured error handling.
health-demo command
Package main demonstrates the health monitoring system.
Package main demonstrates the health monitoring system.
hsdir-demo command
Package main demonstrates the HSDir protocol and descriptor fetching.
Package main demonstrates the HSDir protocol and descriptor fetching.
intro-demo command
Package main demonstrates the Introduction Point Protocol for onion services.
Package main demonstrates the Introduction Point Protocol for onion services.
introduce2-parsing command
Example: INTRODUCE2 Cell Parsing
Example: INTRODUCE2 Cell Parsing
metrics-demo command
Package main demonstrates using go-tor with HTTP metrics endpoint.
Package main demonstrates using go-tor with HTTP metrics endpoint.
obfs4-demo command
Package main demonstrates obfs4 pluggable transport usage.
Package main demonstrates obfs4 pluggable transport usage.
onion-address-demo command
Package main demonstrates onion address parsing and validation.
Package main demonstrates onion address parsing and validation.
onion-service-demo command
Package main demonstrates onion service hosting functionality
Package main demonstrates onion service hosting functionality
performance-demo command
Performance optimization demonstration for go-tor Phase 8.3
Performance optimization demonstration for go-tor Phase 8.3
pt-client command
pt-configuration command
Package main demonstrates pluggable transport configuration.
Package main demonstrates pluggable transport configuration.
pt-manager command
Package main demonstrates PT manager with automatic restart and discovery.
Package main demonstrates PT manager with automatic restart and discovery.
rendezvous-circuit command
Package main demonstrates rendezvous circuit building for onion services
Package main demonstrates rendezvous circuit building for onion services
rendezvous-demo command
rendezvous1-demo command
Package main demonstrates RENDEZVOUS1 cell construction for onion services
Package main demonstrates RENDEZVOUS1 cell construction for onion services
stream-backpressure command
Package main demonstrates stream backpressure functionality.
Package main demonstrates stream backpressure functionality.
trace-demo command
Package main demonstrates distributed tracing capabilities in go-tor.
Package main demonstrates distributed tracing capabilities in go-tor.
zero-config command
Package main demonstrates zero-configuration usage of go-tor.
Package main demonstrates zero-configuration usage of go-tor.
zero-config-custom command
Package main demonstrates zero-configuration usage with custom options.
Package main demonstrates zero-configuration usage with custom options.
pkg
autoconfig
Package autoconfig provides automatic configuration management for zero-configuration setup.
Package autoconfig provides automatic configuration management for zero-configuration setup.
benchmark
Package benchmark provides comprehensive end-to-end performance benchmarks for the go-tor Tor client implementation.
Package benchmark provides comprehensive end-to-end performance benchmarks for the go-tor Tor client implementation.
bine
Package bine provides a zero-configuration wrapper for using cretz/bine with go-tor.
Package bine provides a zero-configuration wrapper for using cretz/bine with go-tor.
cell
Package cell provides types and functions for encoding and decoding Tor protocol cells.
Package cell provides types and functions for encoding and decoding Tor protocol cells.
circuit
Package circuit provides circuit building functionality for the Tor protocol.
Package circuit provides circuit building functionality for the Tor protocol.
client
Package client provides the high-level Tor client orchestration.
Package client provides the high-level Tor client orchestration.
config
Package config provides bridge parsing and validation.
Package config provides bridge parsing and validation.
connection
Package connection provides TLS connection handling for Tor relays.
Package connection provides TLS connection handling for Tor relays.
control
Package control provides Tor control protocol functionality.
Package control provides Tor control protocol functionality.
crypto
Package crypto provides cryptographic primitives for the Tor protocol.
Package crypto provides cryptographic primitives for the Tor protocol.
directory
Package directory provides Tor directory protocol functionality.
Package directory provides Tor directory protocol functionality.
errors
Package errors provides circuit breaker pattern for fault tolerance
Package errors provides circuit breaker pattern for fault tolerance
health
Package health provides health check and monitoring capabilities for the Tor client.
Package health provides health check and monitoring capabilities for the Tor client.
helpers
Package helpers provides convenience functions for integrating go-tor with common Go patterns.
Package helpers provides convenience functions for integrating go-tor with common Go patterns.
httpmetrics
Package httpmetrics provides HTTP-based metrics exposition for monitoring.
Package httpmetrics provides HTTP-based metrics exposition for monitoring.
logger
Package logger provides structured logging for the Tor client.
Package logger provides structured logging for the Tor client.
metrics
Package metrics provides comprehensive operational metrics for the Tor client.
Package metrics provides comprehensive operational metrics for the Tor client.
onion
Package onion - Client Authorization Implementation This file implements client authorization for v3 onion services per rend-spec-v3.txt §2.5
Package onion - Client Authorization Implementation This file implements client authorization for v3 onion services per rend-spec-v3.txt §2.5
path
Package path provides path bias detection per path-spec.txt §5.3 Path bias detection tracks circuit build and usage success rates to detect attacks where malicious guards or middle nodes manipulate circuit construction.
Package path provides path bias detection per path-spec.txt §5.3 Path bias detection tracks circuit build and usage success rates to detect attacks where malicious guards or middle nodes manipulate circuit construction.
pool
Package pool provides resource pooling for performance optimization.
Package pool provides resource pooling for performance optimization.
profiling
Package profiling provides runtime profiling capabilities for performance analysis.
Package profiling provides runtime profiling capabilities for performance analysis.
protocol
Package protocol provides CERTS cell parsing and validation per tor-spec.txt §4.2
Package protocol provides CERTS cell parsing and validation per tor-spec.txt §4.2
pt
Package pt implements pluggable transport support for Tor per pt-spec.txt.
Package pt implements pluggable transport support for Tor per pt-spec.txt.
pt/obfs4
Package obfs4 implements the obfs4 pluggable transport client.
Package obfs4 implements the obfs4 pluggable transport client.
ratelimit
Package ratelimit provides rate limiting functionality for the Tor client.
Package ratelimit provides rate limiting functionality for the Tor client.
recovery
Package recovery provides crash recovery state checkpointing for the Tor client.
Package recovery provides crash recovery state checkpointing for the Tor client.
relay
Package relay implements BridgeDB integration for bridge distribution.
Package relay implements BridgeDB integration for bridge distribution.
security
Package security provides security utilities for the Tor client implementation
Package security provides security utilities for the Tor client implementation
socks
Package socks provides SOCKS5 proxy server functionality.
Package socks provides SOCKS5 proxy server functionality.
stream
Package stream provides stream backpressure implementation.
Package stream provides stream backpressure implementation.
testing/chaos
Package chaos provides chaos engineering testing infrastructure for go-tor.
Package chaos provides chaos engineering testing infrastructure for go-tor.
testing/compliance
Package compliance provides a test harness for verifying specification compliance of the go-tor implementation against official Tor protocol specifications.
Package compliance provides a test harness for verifying specification compliance of the go-tor implementation against official Tor protocol specifications.
testing/integration
Package integration provides comprehensive integration testing infrastructure for the go-tor client.
Package integration provides comprehensive integration testing infrastructure for the go-tor client.
testing/mocknet
Package mocknet provides a lightweight mock Tor network environment for integration testing.
Package mocknet provides a lightweight mock Tor network environment for integration testing.
testing/netmock
Package netmock provides reusable mock types for net.Conn, net.Listener, and net.Addr to support unit testing of network-facing code without requiring live network connections.
Package netmock provides reusable mock types for net.Conn, net.Listener, and net.Addr to support unit testing of network-facing code without requiring live network connections.
testing/perfbaseline
Package perfbaseline provides utilities for capturing and validating performance baselines for the go-tor implementation.
Package perfbaseline provides utilities for capturing and validating performance baselines for the go-tor implementation.
trace
Package trace provides distributed tracing and observability for the Tor client.
Package trace provides distributed tracing and observability for the Tor client.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL