summaryrefslogtreecommitdiffstats
path: root/transport/tor/embedded.go
blob: fd92805093b60c8e685ea8b5b5c85686a0ef261f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// Package tor - Embedded Tor implementation for military/war scenarios
package tor

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"io"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"sync"
	"time"
)

// EmbeddedTor manages an embedded Tor instance
type EmbeddedTor struct {
	torBinary    string          // Path to Tor executable
	torDataDir   string          // Tor data directory
	torProcess   *exec.Cmd       // Tor subprocess
	controlPort  int             // Tor control port
	socksPort    int             // Tor SOCKS proxy port
	hiddenSvcDir string          // Hidden service directory
	onionAddress string          // Our .onion address
	running      bool
	mu           sync.RWMutex
	useBridges   bool            // Use bridges for censorship circumvention
	bridges      []string        // Bridge addresses
}

// EmbeddedTorConfig holds configuration for embedded Tor
type EmbeddedTorConfig struct {
	DataDir      string   // Where to store Tor data
	UseBridges   bool     // Enable bridge mode (anti-censorship)
	Bridges      []string // Bridge addresses (obfs4, meek, etc.)
	ControlPort  int      // Control port (0 = auto)
	SocksPort    int      // SOCKS proxy port (0 = auto)
	AutoStart    bool     // Auto-start Tor on creation
}

// NewEmbeddedTor creates a new embedded Tor instance
func NewEmbeddedTor(config *EmbeddedTorConfig) (*EmbeddedTor, error) {
	if config == nil {
		config = &EmbeddedTorConfig{
			AutoStart:   true,
			ControlPort: 0, // Auto-select
			SocksPort:   0, // Auto-select
		}
	}

	// Create data directory
	dataDir := config.DataDir
	if dataDir == "" {
		// Use temp directory
		tmpDir := os.TempDir()
		dataDir = filepath.Join(tmpDir, "khimera-tor-"+randomString(8))
	}

	if err := os.MkdirAll(dataDir, 0700); err != nil {
		return nil, fmt.Errorf("failed to create Tor data dir: %w", err)
	}

	et := &EmbeddedTor{
		torDataDir:   dataDir,
		hiddenSvcDir: filepath.Join(dataDir, "hidden_service"),
		controlPort:  config.ControlPort,
		socksPort:    config.SocksPort,
		useBridges:   config.UseBridges,
		bridges:      config.Bridges,
	}

	// Find Tor binary
	torBin, err := et.findTorBinary()
	if err != nil {
		return nil, fmt.Errorf("Tor binary not found: %w", err)
	}
	et.torBinary = torBin

	// Auto-assign ports if not specified
	if et.controlPort == 0 {
		et.controlPort = findFreePort()
	}
	if et.socksPort == 0 {
		et.socksPort = findFreePort()
	}

	// Auto-start if requested
	if config.AutoStart {
		if err := et.Start(); err != nil {
			return nil, fmt.Errorf("failed to auto-start Tor: %w", err)
		}
	}

	return et, nil
}

// findTorBinary locates the Tor binary
func (et *EmbeddedTor) findTorBinary() (string, error) {
	// Try common locations
	possiblePaths := []string{
		"tor",                                    // PATH
		"/usr/bin/tor",                           // Linux
		"/usr/local/bin/tor",                     // macOS/BSD
		"C:\\Program Files\\Tor Browser\\tor.exe", // Windows
		filepath.Join(et.torDataDir, "tor"),      // Bundled with app
	}

	// Add OS-specific paths
	if runtime.GOOS == "windows" {
		possiblePaths = append(possiblePaths, "tor.exe")
	}

	for _, path := range possiblePaths {
		if _, err := os.Stat(path); err == nil {
			return path, nil
		}
		// Also try in PATH
		if fullPath, err := exec.LookPath(path); err == nil {
			return fullPath, nil
		}
	}

	return "", fmt.Errorf("Tor binary not found in common locations")
}

// Start starts the embedded Tor process
func (et *EmbeddedTor) Start() error {
	et.mu.Lock()
	defer et.mu.Unlock()

	if et.running {
		return fmt.Errorf("Tor already running")
	}

	// Create torrc configuration
	torrcPath := filepath.Join(et.torDataDir, "torrc")
	if err := et.writeTorrc(torrcPath); err != nil {
		return fmt.Errorf("failed to write torrc: %w", err)
	}

	// Launch Tor process
	et.torProcess = exec.Command(et.torBinary, "-f", torrcPath)
	et.torProcess.Stdout = os.Stdout // For debugging
	et.torProcess.Stderr = os.Stderr

	if err := et.torProcess.Start(); err != nil {
		return fmt.Errorf("failed to start Tor: %w", err)
	}

	et.running = true

	// Wait for Tor to bootstrap
	if err := et.waitForBootstrap(60 * time.Second); err != nil {
		et.Stop()
		return fmt.Errorf("Tor bootstrap failed: %w", err)
	}

	// Read hidden service address
	if err := et.readOnionAddress(); err != nil {
		return fmt.Errorf("failed to read onion address: %w", err)
	}

	return nil
}

// writeTorrc writes Tor configuration file
func (et *EmbeddedTor) writeTorrc(path string) error {
	config := fmt.Sprintf(`# Khimera Embedded Tor Configuration

# Data directory
DataDirectory %s

# SOCKS proxy
SOCKSPort %d

# Control port
ControlPort %d

# Hidden service
HiddenServiceDir %s
HiddenServicePort 8083 127.0.0.1:8083

# Security settings
SafeLogging 1
AvoidDiskWrites 1

`, et.torDataDir, et.socksPort, et.controlPort, et.hiddenSvcDir)

	// Add bridges if anti-censorship mode
	if et.useBridges && len(et.bridges) > 0 {
		config += "\n# Bridge mode (anti-censorship)\n"
		config += "UseBridges 1\n"
		config += "ClientTransportPlugin obfs4 exec /usr/bin/obfs4proxy\n"
		for _, bridge := range et.bridges {
			config += fmt.Sprintf("Bridge %s\n", bridge)
		}
	}

	return os.WriteFile(path, []byte(config), 0600)
}

// waitForBootstrap waits for Tor to finish bootstrapping
func (et *EmbeddedTor) waitForBootstrap(timeout time.Duration) error {
	start := time.Now()

	for {
		if time.Since(start) > timeout {
			return fmt.Errorf("bootstrap timeout")
		}

		// Try to connect to SOCKS port
		conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", et.socksPort), 1*time.Second)
		if err == nil {
			conn.Close()
			// Successfully connected - Tor is ready
			return nil
		}

		time.Sleep(1 * time.Second)
	}
}

// readOnionAddress reads the hidden service .onion address
func (et *EmbeddedTor) readOnionAddress() error {
	hostnamePath := filepath.Join(et.hiddenSvcDir, "hostname")

	// Wait for file to be created (may take a few seconds)
	for i := 0; i < 30; i++ {
		data, err := os.ReadFile(hostnamePath)
		if err == nil {
			et.onionAddress = strings.TrimSpace(string(data))
			return nil
		}
		time.Sleep(1 * time.Second)
	}

	return fmt.Errorf("failed to read onion address from %s", hostnamePath)
}

// Stop stops the embedded Tor process
func (et *EmbeddedTor) Stop() error {
	et.mu.Lock()
	defer et.mu.Unlock()

	if !et.running {
		return nil
	}

	if et.torProcess != nil {
		// Graceful shutdown
		if err := et.torProcess.Process.Signal(os.Interrupt); err != nil {
			// Force kill if graceful fails
			et.torProcess.Process.Kill()
		}

		// Wait for process to exit
		et.torProcess.Wait()
	}

	et.running = false
	return nil
}

// GetSOCKSProxy returns the SOCKS proxy address
func (et *EmbeddedTor) GetSOCKSProxy() string {
	et.mu.RLock()
	defer et.mu.RUnlock()
	return fmt.Sprintf("127.0.0.1:%d", et.socksPort)
}

// GetOnionAddress returns our hidden service .onion address
func (et *EmbeddedTor) GetOnionAddress() string {
	et.mu.RLock()
	defer et.mu.RUnlock()
	return et.onionAddress
}

// IsRunning returns whether Tor is currently running
func (et *EmbeddedTor) IsRunning() bool {
	et.mu.RLock()
	defer et.mu.RUnlock()
	return et.running
}

// Cleanup removes Tor data directory
func (et *EmbeddedTor) Cleanup() error {
	et.Stop()

	if et.torDataDir != "" {
		return os.RemoveAll(et.torDataDir)
	}
	return nil
}

// SetBridges configures Tor bridges for censorship circumvention
func (et *EmbeddedTor) SetBridges(bridges []string) error {
	et.mu.Lock()
	defer et.mu.Unlock()

	et.useBridges = true
	et.bridges = bridges

	// Restart Tor if running to apply new config
	if et.running {
		et.mu.Unlock() // Unlock before calling Stop (which locks)
		et.Stop()
		et.mu.Lock()
		return et.Start()
	}

	return nil
}

// GetDefaultBridges returns a list of default obfs4 bridges
func GetDefaultBridges() []string {
	return []string{
		"obfs4 192.95.36.142:443 CDF2E852BF539B82BD10E27E9115A31734E378C2 cert=qUVQ0srL1JI/vO6V6m/24anYXiJD3QP2HgzUKQtQ7GRqqUvs7P+tG43RtAqdhLOALP7DJQ iat-mode=1",
		"obfs4 193.11.166.194:27015 2D82C2E354D531A68469ADF7F878FA6060C6BACA cert=4TLQPJrTSaDffMK7Nbao6LC7G9OW/NHkUwIdjLSS3KYf0Nv4/nQiiI8dY2TcsQx01NniOg iat-mode=0",
		"obfs4 193.11.166.194:27020 86AC7B8D430DAC4117E9F42C9EAED18133863AAF cert=0LDeJH4JzMDtkJJrFphJCiPqKx7loozKN7VNfuukMGfHO0Z8OGdzHVkhVAOfo1mUdv9cMg iat-mode=0",
	}
}

// findFreePort finds an available TCP port
func findFreePort() int {
	listener, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return 9050 // Fallback to default
	}
	defer listener.Close()

	addr := listener.Addr().(*net.TCPAddr)
	return addr.Port
}

// randomString generates a random hex string
func randomString(n int) string {
	bytes := make([]byte, n)
	io.ReadFull(rand.Reader, bytes)
	return hex.EncodeToString(bytes)
}

// String returns a string representation
func (et *EmbeddedTor) String() string {
	et.mu.RLock()
	defer et.mu.RUnlock()

	status := "stopped"
	if et.running {
		status = "running"
	}

	return fmt.Sprintf("EmbeddedTor(status=%s, socks=%d, onion=%s)",
		status, et.socksPort, et.onionAddress)
}