-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.go
More file actions
432 lines (369 loc) · 10.1 KB
/
proxy.go
File metadata and controls
432 lines (369 loc) · 10.1 KB
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
package main
import (
"context"
"fmt"
"io"
"log"
"net"
"net/netip"
"os"
"path/filepath"
"sync"
"time"
"tailscale.com/client/tailscale"
"tailscale.com/ipn"
"tailscale.com/tsnet"
)
type ProxyServer struct {
config *Config
server *tsnet.Server
mu sync.Mutex
dialer *net.Dialer
exporterManager *ExporterManager
controlSockPath string
}
func getStateDir(hostname string) string {
// Check for explicit state directory from environment
if dir := os.Getenv("TAILPROXY_STATE_DIR"); dir != "" {
return dir
}
// Use XDG_STATE_HOME if set, otherwise ~/.local/state
stateHome := os.Getenv("XDG_STATE_HOME")
if stateHome == "" {
home, err := os.UserHomeDir()
if err != nil {
// Fall back to temp directory if we can't get home dir
return filepath.Join(os.TempDir(), "tailproxy-"+hostname)
}
stateHome = filepath.Join(home, ".local", "state")
}
return filepath.Join(stateHome, "tailproxy", hostname)
}
func NewProxyServer(config *Config) (*ProxyServer, error) {
// Create state directory - use persistent location for stable node ID
stateDir := getStateDir(config.Hostname)
if err := os.MkdirAll(stateDir, 0700); err != nil {
return nil, fmt.Errorf("failed to create state directory: %w", err)
}
srv := &tsnet.Server{
Hostname: config.Hostname,
Dir: stateDir,
Logf: func(format string, args ...any) {
if config.Verbose {
log.Printf("[tsnet] "+format, args...)
}
},
}
if config.AuthKey != "" {
srv.AuthKey = config.AuthKey
}
p := &ProxyServer{
config: config,
server: srv,
controlSockPath: filepath.Join(stateDir, "control.sock"),
}
// Create exporter manager if export mode is enabled
if config.ExportListeners {
p.exporterManager = NewExporterManager(config, srv)
}
return p, nil
}
func (p *ProxyServer) waitForAuth(ctx context.Context, lc *tailscale.LocalClient) error {
// If we have an auth key, tsnet handles it automatically
if p.config.AuthKey != "" {
if p.config.Verbose {
log.Println("Using provided auth key...")
}
// Wait for the server to be ready with the auth key
_, err := p.server.Up(ctx)
return err
}
// For interactive auth, we need to check status and wait
authURLPrinted := false
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
status, err := lc.Status(ctx)
if err != nil {
// Server might not be ready yet, wait a bit
time.Sleep(500 * time.Millisecond)
continue
}
// Check if we're already authenticated
if status.BackendState == "Running" {
if p.config.Verbose {
log.Println("Tailscale connected and authenticated")
}
return nil
}
// Check if we need to print an auth URL
if status.AuthURL != "" && !authURLPrinted {
// Print the auth URL to stderr so user can click it
fmt.Fprintf(os.Stderr, "\nTo authenticate, visit:\n\n\t%s\n\n", status.AuthURL)
authURLPrinted = true
}
// Wait a bit before checking again
time.Sleep(time.Second)
}
}
func (p *ProxyServer) Start(ctx context.Context) error {
return p.StartWithReady(ctx, nil)
}
func (p *ProxyServer) GetControlSocketPath() string {
return p.controlSockPath
}
func (p *ProxyServer) Stop() {
if p.exporterManager != nil {
p.exporterManager.Stop()
}
}
func (p *ProxyServer) StartWithReady(ctx context.Context, ready chan<- struct{}) error {
// Suppress noisy tsnet startup messages unless verbose
var originalOutput io.Writer
if !p.config.Verbose {
originalOutput = log.Writer()
log.SetOutput(io.Discard)
}
// Start tsnet
if p.config.Verbose {
log.Println("Starting Tailscale network...")
}
// Get local client to configure exit node
lc, err := p.server.LocalClient()
if err != nil {
return fmt.Errorf("failed to get local client: %w", err)
}
// Wait for authentication to complete
if err := p.waitForAuth(ctx, lc); err != nil {
if originalOutput != nil {
log.SetOutput(originalOutput)
}
return fmt.Errorf("authentication failed: %w", err)
}
// Restore log output after tsnet startup noise
if originalOutput != nil {
log.SetOutput(originalOutput)
}
// Start exporter control socket if enabled
if p.config.ExportListeners && p.exporterManager != nil {
if err := p.exporterManager.StartControlSocket(p.controlSockPath); err != nil {
return fmt.Errorf("failed to start control socket: %w", err)
}
if p.config.Verbose {
log.Printf("Export listeners mode enabled, control socket at %s", p.controlSockPath)
}
}
// Set exit node if specified
if p.config.ExitNode != "" {
if p.config.Verbose {
log.Printf("Configuring exit node: %s", p.config.ExitNode)
}
// Get status to find the exit node peer
status, err := lc.Status(ctx)
if err != nil {
return fmt.Errorf("failed to get status: %w", err)
}
// Find the exit node by hostname or IP
var exitNodeIP string
var peerOnline bool
for _, peer := range status.Peer {
if peer.HostName == p.config.ExitNode || peer.DNSName == p.config.ExitNode ||
peer.DNSName == p.config.ExitNode+"."+status.MagicDNSSuffix {
if len(peer.TailscaleIPs) > 0 {
exitNodeIP = peer.TailscaleIPs[0].String()
peerOnline = peer.Online
break
}
}
// Also check by IP address
for _, ip := range peer.TailscaleIPs {
if ip.String() == p.config.ExitNode {
exitNodeIP = ip.String()
peerOnline = peer.Online
break
}
}
}
if exitNodeIP == "" {
return fmt.Errorf("exit node %q not found in peers (is it in your tailnet?)", p.config.ExitNode)
}
if !peerOnline {
return fmt.Errorf("exit node %q is offline (cannot route traffic)", p.config.ExitNode)
}
if p.config.Verbose {
log.Printf("Setting exit node to %s (IP: %s)", p.config.ExitNode, exitNodeIP)
}
// Set the exit node using EditPrefs
prefs := &ipn.MaskedPrefs{
Prefs: ipn.Prefs{
ExitNodeIP: netip.MustParseAddr(exitNodeIP),
},
ExitNodeIPSet: true,
}
if _, err := lc.EditPrefs(ctx, prefs); err != nil {
return fmt.Errorf("failed to set exit node: %w", err)
}
// Verify the exit node is actually active
time.Sleep(500 * time.Millisecond) // Give it a moment to apply
status, err = lc.Status(ctx)
if err != nil {
return fmt.Errorf("failed to verify exit node status: %w", err)
}
if status.ExitNodeStatus == nil {
return fmt.Errorf("exit node configuration failed: exit node not active")
}
if status.ExitNodeStatus.TailscaleIPs == nil || len(status.ExitNodeStatus.TailscaleIPs) == 0 ||
status.ExitNodeStatus.TailscaleIPs[0].String() != exitNodeIP {
return fmt.Errorf("exit node configuration failed: expected %s, got different or no exit node", exitNodeIP)
}
if !status.ExitNodeStatus.Online {
return fmt.Errorf("exit node %q became offline during configuration", p.config.ExitNode)
}
if p.config.Verbose {
log.Printf("Exit node %s verified and active", p.config.ExitNode)
}
}
// Listen on localhost for SOCKS5 connections
listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p.config.ProxyPort))
if err != nil {
return fmt.Errorf("failed to listen: %w", err)
}
// Close listener when context is canceled to unblock Accept()
go func() {
<-ctx.Done()
listener.Close()
}()
if p.config.Verbose {
log.Printf("SOCKS5 proxy listening on 127.0.0.1:%d", p.config.ProxyPort)
}
// Signal that we're ready
if ready != nil {
close(ready)
}
// Accept connections
for {
conn, err := listener.Accept()
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
if p.config.Verbose {
log.Printf("Accept error: %v", err)
}
continue
}
go p.handleConnection(ctx, conn)
}
}
func (p *ProxyServer) handleConnection(ctx context.Context, clientConn net.Conn) {
defer clientConn.Close()
// SOCKS5 handshake
buf := make([]byte, 256)
// Read version and methods
n, err := clientConn.Read(buf)
if err != nil {
if p.config.Verbose {
log.Printf("Failed to read SOCKS5 greeting: %v", err)
}
return
}
if n < 2 || buf[0] != 0x05 {
if p.config.Verbose {
log.Printf("Invalid SOCKS5 version: %d", buf[0])
}
return
}
// Send "no authentication required" response
_, err = clientConn.Write([]byte{0x05, 0x00})
if err != nil {
return
}
// Read request
n, err = clientConn.Read(buf)
if err != nil {
if p.config.Verbose {
log.Printf("Failed to read SOCKS5 request: %v", err)
}
return
}
if n < 7 || buf[0] != 0x05 {
return
}
cmd := buf[1]
if cmd != 0x01 { // Only support CONNECT
clientConn.Write([]byte{0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
return
}
// Parse address
addrType := buf[3]
var host string
var port uint16
switch addrType {
case 0x01: // IPv4
if n < 10 {
return
}
host = fmt.Sprintf("%d.%d.%d.%d", buf[4], buf[5], buf[6], buf[7])
port = uint16(buf[8])<<8 | uint16(buf[9])
case 0x03: // Domain name
if n < 5 {
return
}
addrLen := int(buf[4])
if n < 5+addrLen+2 {
return
}
host = string(buf[5 : 5+addrLen])
port = uint16(buf[5+addrLen])<<8 | uint16(buf[5+addrLen+1])
case 0x04: // IPv6
if n < 22 {
return
}
host = net.IP(buf[4:20]).String()
port = uint16(buf[20])<<8 | uint16(buf[21])
default:
clientConn.Write([]byte{0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
return
}
target := net.JoinHostPort(host, fmt.Sprintf("%d", port))
if p.config.Verbose {
log.Printf("Connecting to %s via Tailscale", target)
}
// Dial through Tailscale
var remoteConn net.Conn
if p.config.ExitNode != "" {
// Use tsnet's dialer which routes through the Tailscale network
remoteConn, err = p.server.Dial(ctx, "tcp", target)
} else {
// Direct connection through Tailscale network
remoteConn, err = p.server.Dial(ctx, "tcp", target)
}
if err != nil {
if p.config.Verbose {
log.Printf("Failed to connect to %s: %v", target, err)
}
clientConn.Write([]byte{0x05, 0x05, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
return
}
defer remoteConn.Close()
// Send success response
_, err = clientConn.Write([]byte{0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
if err != nil {
return
}
// Bidirectional copy
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
io.Copy(remoteConn, clientConn)
}()
go func() {
defer wg.Done()
io.Copy(clientConn, remoteConn)
}()
wg.Wait()
}