-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
index.ts
291 lines (261 loc) · 8.57 KB
/
index.ts
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
// eslint-disable-next-line max-classes-per-file
import { ChildProcess, spawn } from 'child_process';
import * as net from 'net';
import { promises as fs, unlink } from 'fs';
import * as os from 'os';
import { v1 as uuid } from 'uuid';
import Log from '@secret-agent/commons/Logger';
import { createPromise } from '@secret-agent/commons/utils';
import { TypedEventEmitter } from '@secret-agent/commons/eventUtils';
const { log } = Log(module);
const ext = os.platform() === 'win32' ? '.exe' : '';
const libPath = `${__dirname}/dist/connect${ext}`;
let idCounter = 0;
export default class MitmSocket extends TypedEventEmitter<{
connect: void;
dial: void;
close: void;
}> {
public readonly socketPath: string;
public alpn = 'http/1.1';
public socket: net.Socket;
public remoteAddress: string;
public localAddress: string;
public serverName: string;
public id = (idCounter += 1);
public spawnTime: Date;
public dialTime: Date;
public connectTime: Date;
public closeTime: Date;
public get pid(): number | undefined {
return this.child?.pid;
}
private isClosing = false;
private isConnected = false;
private child: ChildProcess;
private connectError?: string;
private readonly callStack: string;
constructor(readonly sessionId: string, readonly connectOpts: IGoTlsSocketConnectOpts) {
super();
const id = uuid();
this.callStack = new Error().stack.replace('Error:', '').trim();
this.serverName = connectOpts.servername;
this.socketPath =
os.platform() === 'win32' ? `\\\\.\\pipe\\sa-${id}` : `${os.tmpdir()}/sa-${id}.sock`;
this.logger = log.createChild(module, { sessionId });
if (connectOpts.debug === undefined) connectOpts.debug = log.level === 'stats';
if (connectOpts.isSsl === undefined) connectOpts.isSsl = true;
}
public isReusable(): boolean {
if (!this.socket || this.isClosing || !this.isConnected) return false;
return this.socket.writable && !this.socket.destroyed;
}
public setProxyUrl(url: string): void {
this.connectOpts.proxyUrl = url;
}
public setTcpSettings(tcpVars: { windowSize: number; ttl: number }): void {
this.connectOpts.tcpTtl = tcpVars.ttl;
this.connectOpts.tcpWindowSize = tcpVars.windowSize;
}
public isHttp2(): boolean {
return this.alpn === 'h2';
}
public close(): void {
if (this.isClosing) return;
this.closeTime = new Date();
this.isClosing = true;
this.emit('close');
this.cleanupSocket();
this.closeChild();
}
public onListening(): void {
const socket = net.connect(this.socketPath);
this.socket = socket;
socket.on('error', error => {
this.logger.error('SocketConnectDriver.SocketError', {
sessionId: this.sessionId,
error,
socketPath: this.socketPath,
host: this.connectOpts?.host,
clientHello: this.connectOpts?.clientHelloId,
});
if ((error as any)?.code === 'ENOENT') this.close();
this.isConnected = false;
});
socket.on('end', this.onSocketClose.bind(this, 'end'));
socket.on('close', this.onSocketClose.bind(this, 'close'));
}
public async connect(connectTimeoutMillis = 30e3): Promise<void> {
await this.cleanSocketPathIfNeeded();
const child = spawn(libPath, [this.socketPath, JSON.stringify(this.connectOpts)], {
stdio: ['pipe', 'pipe', 'pipe'],
});
this.spawnTime = new Date();
this.child = child;
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
const promise = createPromise(
connectTimeoutMillis,
`Timeout connecting to ${this.serverName ?? 'host'} at ${this.connectOpts.host}:${
this.connectOpts.port
}`,
);
child.on('exit', () => {
promise.reject(
buildConnectError(
this.connectError ?? `Socket process exited during connect`,
this.callStack,
),
);
this.cleanupSocket();
});
child.on('error', error => {
promise.reject(error);
this.logger.error('SocketConnectDriver.ChildConnectError', {
error,
host: this.connectOpts?.host,
clientHello: this.connectOpts?.clientHelloId,
});
this.close();
});
child.stdout.on('data', message => {
this.onChildProcessMessage(message);
if (this.isConnected) {
promise.resolve();
}
});
// if error logs during connect window, we got a connect error
child.stderr.on('data', message => {
this.onChildProcessStderr(message);
if (!this.isConnected && this.connectError) {
promise.reject(buildConnectError(this.connectError, this.callStack));
this.close();
}
});
await promise.promise;
}
private async cleanSocketPathIfNeeded(): Promise<void> {
try {
await fs.unlink(this.socketPath);
} catch (err) {
// no action
}
}
private closeChild(): void {
if (!this.child || this.child.killed) return;
try {
// fix for node 13 throwing errors on closed sockets
this.child.stdin.on('error', () => {
// catch
});
this.child.stdin.write('disconnect', () => {
// don't log
});
} catch (err) {
// don't log epipes
}
if (os.platform() !== 'win32') {
this.child.kill();
}
this.child.unref();
}
private cleanupSocket(): void {
if (!this.socket) return;
if (this.connectError)
this.socket.destroy(buildConnectError(this.connectError, this.callStack));
this.socket.end();
this.socket.unref();
this.isConnected = false;
unlink(this.socketPath, () => null);
delete this.socket;
}
private onSocketClose(): void {
this.close();
}
private onChildProcessMessage(messages: string): void {
for (const message of messages.split(/\r?\n/)) {
if (message.startsWith('[DomainSocketPiper.Dialed]')) {
this.dialTime = new Date();
const matches = message.match(/Remote: (.+), Local: (.+)/);
if (matches?.length) {
this.remoteAddress = matches[1];
this.localAddress = matches[2];
}
this.emit('dial');
} else if (message === '[DomainSocketPiper.ReadyForConnect]') {
this.onListening();
} else if (message.startsWith('[DomainSocketPiper.Connected]')) {
this.isConnected = true;
this.connectTime = new Date();
const matches = message.match(/ALPN: (.+)/);
if (matches?.length) {
this.alpn = matches[1];
}
this.emit('connect');
this.logger.stats('SocketHandler.Connected', {
alpn: this.alpn,
host: this.connectOpts?.host,
clientHello: this.connectOpts?.clientHelloId,
});
} else if (message) {
this.logger.info('SocketHandler.onData', {
message,
host: this.connectOpts?.host,
clientHello: this.connectOpts?.clientHelloId,
});
}
}
}
private onChildProcessStderr(message: string): void {
if (
message.includes('panic: runtime error:') ||
message.includes('tlsConn.Handshake error') ||
message.includes('connection refused') ||
message.includes('no such host') ||
message.includes('Dial (proxy/remote)') ||
message.includes('PROXY_ERR')
) {
this.connectError = message.trim();
if (this.connectError.includes('Error:')) {
this.connectError = this.connectError.split('Error:').pop().trim();
}
if (this.isConnected) {
this.close();
}
} else if (message.includes('DomainSocket -> EOF') && !this.connectOpts.keepAlive) {
this.close();
} else {
this.logger.warn(`SocketConnectDriver.Error => ${message}`);
}
}
}
export interface IGoTlsSocketConnectOpts {
host: string;
port: string;
isSsl?: boolean;
clientHelloId: string;
servername: string;
rejectUnauthorized?: boolean;
proxyUrl?: string;
proxyAuth?: string;
tcpTtl?: number;
tcpWindowSize?: number;
debug?: boolean;
keepAlive?: boolean;
}
class Socks5ProxyConnectError extends Error {}
class HttpProxyConnectError extends Error {}
class SocketConnectError extends Error {}
function buildConnectError(connectError = 'Error connecting to host', callStack: string): Error {
let error: Error;
if (connectError.includes('SOCKS5_PROXY_ERR')) {
error = new Socks5ProxyConnectError(connectError.replace('SOCKS5_PROXY_ERR', '').trim());
} else if (connectError.includes('HTTP_PROXY_ERR')) {
error = new HttpProxyConnectError(connectError.replace('HTTP_PROXY_ERR', '').trim());
} else {
error = new SocketConnectError(connectError.trim());
}
error.stack += `\n${'------DIAL'.padEnd(50, '-')}\n `;
error.stack += callStack;
return error;
}