File size: 6,103 Bytes
b855ced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cce9364
 
 
b855ced
 
 
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
// Outbound connections through Tor's SOCKS5 port (RFC 1928 CONNECT, with
// RFC 1929 username/password authentication for Tor's stream isolation).
//
// Hostnames are always sent to the proxy (address type 3) and never
// resolved here, so .onion names work and nothing leaks to DNS.

import net from 'node:net';
import tls from 'node:tls';
import http from 'node:http';

// Tor's extended reply codes for onion services (tor's socks-extensions.txt).
const REPLIES = {
  0x01: 'general failure', 0x02: 'not allowed by ruleset', 0x03: 'network unreachable',
  0x04: 'host unreachable', 0x05: 'connection refused', 0x06: 'TTL expired',
  0x07: 'command not supported', 0x08: 'address type not supported',
  0xf0: 'onion service descriptor not found', 0xf1: 'onion service descriptor invalid',
  0xf2: 'onion service introduction failed', 0xf3: 'onion service rendezvous failed',
  0xf4: 'onion service needs client authorization', 0xf5: 'onion service client authorization is wrong',
  0xf6: 'invalid onion address', 0xf7: 'onion service introduction timed out',
};

/** Parse "host:port" (IPv6 in brackets). */
export function parseProxy(value) {
  const m = /^(?:\[([^\]]+)\]|([^:]+)):(\d+)$/.exec(value ?? '');
  if (!m) throw new Error(`Invalid SOCKS proxy '${value}': expected host:port`);
  return { host: m[1] ?? m[2], port: Number(m[3]) };
}

/**
 * Open a TCP connection to host:port through the proxy. Resolves with the
 * connected socket, ready for application data.
 */
export function socksConnect({ proxy, host, port, username, password, timeoutMs = 120_000 }) {
  const name = Buffer.from(host, 'utf8');
  if (!name.length || name.length > 255) return Promise.reject(new Error('Host name must be 1 to 255 bytes'));
  const user = username !== undefined ? Buffer.from(username) : null;
  const pass = password !== undefined ? Buffer.from(password) : null;
  if (user && (!user.length || user.length > 255 || !pass?.length || pass.length > 255)) {
    return Promise.reject(new Error('SOCKS username and password must be 1 to 255 bytes'));
  }

  return new Promise((resolve, reject) => {
    const socket = net.connect(proxy.port, proxy.host);
    let buf = Buffer.alloc(0);
    let step = 'greeting';
    const done = (err) => {
      clearTimeout(timer);
      socket.removeListener('data', onData);
      if (err) { socket.destroy(); reject(err); } else resolve(socket);
    };
    const timer = setTimeout(() => done(new Error(`SOCKS connection to ${host} timed out`)), timeoutMs);
    const take = (n) => { const out = buf.subarray(0, n); buf = buf.subarray(n); return out; };

    const sendConnect = () => {
      step = 'connect';
      const portBytes = Buffer.alloc(2);
      portBytes.writeUInt16BE(port);
      socket.write(Buffer.concat([Buffer.from([0x05, 0x01, 0x00, 0x03, name.length]), name, portBytes]));
    };

    const onData = (chunk) => {
      buf = Buffer.concat([buf, chunk]);
      for (;;) {
        if (step === 'greeting') {
          if (buf.length < 2) return;
          const [ver, method] = take(2);
          if (ver !== 0x05) return done(new Error('Not a SOCKS5 proxy'));
          if (method === 0x02 && user) {
            step = 'auth';
            socket.write(Buffer.concat([Buffer.from([0x01, user.length]), user, Buffer.from([pass.length]), pass]));
          } else if (method === 0x00) {
            sendConnect();
          } else {
            return done(new Error('SOCKS proxy refused every authentication method'));
          }
        } else if (step === 'auth') {
          if (buf.length < 2) return;
          if (take(2)[1] !== 0x00) return done(new Error('SOCKS authentication failed'));
          sendConnect();
        } else if (step === 'connect') {
          if (buf.length < 5) return;
          const atyp = buf[3];
          const addrLen = atyp === 0x01 ? 4 : atyp === 0x04 ? 16 : atyp === 0x03 ? 1 + buf[4] : -1;
          if (addrLen < 0) return done(new Error('Malformed SOCKS reply'));
          if (buf.length < 4 + addrLen + 2) return;
          const [ver, rep] = take(4 + addrLen + 2);
          if (ver !== 0x05) return done(new Error('Malformed SOCKS reply'));
          if (rep !== 0x00) return done(new Error(`SOCKS: ${REPLIES[rep] ?? `error ${rep}`} (${host})`));
          if (buf.length) socket.unshift(buf); // early application data
          return done(null);
        }
      }
    };

    socket.on('data', onData);
    socket.once('error', (e) => done(e));
    socket.once('close', () => done(new Error('SOCKS proxy closed the connection')));
    socket.once('connect', () => socket.write(user ? Buffer.from([0x05, 0x02, 0x00, 0x02]) : Buffer.from([0x05, 0x01, 0x00])));
  }).then((socket) => {
    socket.removeAllListeners('close');
    socket.removeAllListeners('error');
    return socket;
  });
}

/**
 * An HTTP agent whose connections go through the proxy, for `ws` and
 * http(s).get. `isolation` becomes the SOCKS username, so Tor puts each
 * isolation key (here: each peer server) on its own circuits.
 * With `secure`, TLS runs on top, end to end with the destination.
 */
export class SocksAgent extends http.Agent {
  constructor({ proxy, isolation, password, secure = false, tlsOptions = {} }) {
    super({ keepAlive: false });
    this.proxy = proxy;
    this.isolation = isolation;
    this.password = password;
    this.secure = secure;
    this.tlsOptions = tlsOptions;
    this.protocol = secure ? 'https:' : 'http:';
  }

  createConnection(options, callback) {
    const host = options.hostname ?? options.host;
    const port = Number(options.port) || (this.secure ? 443 : 80);
    socksConnect({ proxy: this.proxy, host, port, username: this.isolation, password: this.password }).then((socket) => {
      if (!this.secure) return callback(null, socket);
      const secured = tls.connect({ ...this.tlsOptions, socket, servername: net.isIP(host) ? undefined : host });
      const fail = (e) => callback(e);
      secured.once('error', fail);
      secured.once('secureConnect', () => { secured.off('error', fail); callback(null, secured); });
    }, (e) => callback(e));
  }
}