taper / server /socks.js
abr00kx's picture
Round 2 security fixes (part 4)
cce9364 verified
Raw History Blame Contribute Delete
6.1 kB
// 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));
}
}