forked from gr3p1p3/transparent-proxy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathonConnectedClientHandling.js
303 lines (268 loc) · 10.8 KB
/
onConnectedClientHandling.js
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
const net = require('net');
const Session = require('./Session');
const getConnectionOptions = require('./getConnectionOptions');
const rebuildHeaders = require('../lib/rebuildHeaders');
const isFunction = require('../lib/isFunction');
const usingUpstreamToProxy = require('../lib/usingUpstreamToProxy');
const {
EVENTS,
HTTP_BODIES, HTTP_METHODS, HTTP_RESPONSES,
STRINGS, ERROR_CODES, HTTPS
} = require('../lib/constants');
const {CLOSE, DATA, ERROR, EXIT} = EVENTS;
const {ETIMEDOUT, ENOTFOUND, EPIPE, EPROTO} = ERROR_CODES;
const {CONNECT} = HTTP_METHODS;
const {AUTH_REQUIRED, OK, NOT_OK, TIMED_OUT, NOT_FOUND} = HTTP_RESPONSES;
const {BLANK, CRLF, EMPTY, SEPARATOR, PROXY_AUTH, PROXY_AUTH_BASIC} = STRINGS;
const DOUBLE_CLRF = CRLF + CRLF;
/**
*
* @param clientSocket
* @param bridgedConnections
* @param options
* @param logger
*/
module.exports = function onConnectedClientHandling(clientSocket, bridgedConnections, options, logger) {
const {
upstream, tcpOutgoingAddress,
injectData, injectResponse,
auth, intercept, keys
} = options;
const remotePort = clientSocket.remotePort;
const remoteAddress = clientSocket.remoteAddress;
const remoteID = remoteAddress + SEPARATOR + remotePort;
// logger.log('Received request from', remoteID);
/**
* @param {Error} err
*/
function onClose(err) {
const thisTunnel = bridgedConnections[remoteID];
if (err && err instanceof Error) {
//TODO handle more the errorCodes
switch (err.code) {
case ETIMEDOUT:
if (thisTunnel) {
thisTunnel.clientResponseWrite(TIMED_OUT + DOUBLE_CLRF);
}
break;
case ENOTFOUND:
if (thisTunnel) {
thisTunnel.clientResponseWrite(NOT_FOUND + DOUBLE_CLRF + HTTP_BODIES.NOT_FOUND);
}
break;
case EPIPE:
logger.error(remoteID, err);
break;
// case EPROTO:
// // thisTunnel.clientResponseWrite(NOT_OK + DOUBLE_CLRF + HTTP_BODIES.NOT_FOUND);
// break;
default:
//log all unhandled errors
logger.error(remoteID, err);
if (thisTunnel) {
thisTunnel.clientResponseWrite(NOT_OK + DOUBLE_CLRF);
}
}
}
if (thisTunnel) {
thisTunnel.destroy();
delete bridgedConnections[remoteID];
}
}
/**
* @param {buffer} dataFromUpStream
*/
async function onDataFromUpstream(dataFromUpStream) {
const thisTunnel = bridgedConnections[remoteID];
if (thisTunnel) {
const responseData = isFunction(injectResponse)
? await injectResponse(dataFromUpStream, thisTunnel)
: dataFromUpStream;
thisTunnel.clientResponseWrite(responseData);
//updateSockets if needed after first response
updateSockets();
}
}
/**
* @param {buffer} srcData
*/
async function onDirectConnectionOpen(srcData) {
const thisTunnel = bridgedConnections[remoteID];
if (thisTunnel) {
const requestData = isFunction(injectData)
? await injectData(srcData, thisTunnel)
: srcData;
thisTunnel.clientRequestWrite(requestData);
}
}
function updateSockets() {
const thisTunnel = bridgedConnections[remoteID];
if (intercept && thisTunnel && thisTunnel.isHttps && !thisTunnel._updated) {
const keysObject = isFunction(keys)
? keys(thisTunnel)
: false;
const keyToUse = (keysObject && typeof keysObject === 'object' && Object.keys(keysObject).length === 2)
? keysObject
: undefined;
thisTunnel._updateSockets({onDataFromClient, onDataFromUpstream, onClose}, keyToUse);
}
}
/**
* @param {buffer} data
* @param {string} firstHeaderRow
* @param {boolean} isConnectMethod - false as default.
* @returns Promise{boolean|{host: string, port: number, protocol: string, credentials: string, upstreamed: boolean}}
*/
async function prepareTunnel(data, firstHeaderRow, isConnectMethod = false) {
const thisTunnel = bridgedConnections[remoteID];
const upstreamHost = firstHeaderRow.split(BLANK)[1];
const initOpt = getConnectionOptions(false, upstreamHost);
thisTunnel.setTunnelOpt(initOpt); //settings opt before callback
const proxyToUse = await usingUpstreamToProxy(upstream, {
data,
bridgedConnection: thisTunnel
});
//initializing socket and forwarding received request
const connectionOpt = getConnectionOptions(proxyToUse, upstreamHost);
thisTunnel.isHttps = !!(
isConnectMethod
|| (connectionOpt.upstream
&& connectionOpt.upstream.protocol === HTTPS));
thisTunnel.setTunnelOpt(connectionOpt); // updating tunnel opt
if (isFunction(tcpOutgoingAddress)) {
//THIS ONLY work if server-listener is not 0.0.0.0 but specific iFace/IP
connectionOpt.localAddress = tcpOutgoingAddress(data, thisTunnel);
}
/**
* @param {Error} connectionError
*/
async function onTunnelHTTPConnectionOpen(connectionError) {
if (connectionError) {
return onClose(connectionError);
}
if (connectionOpt.credentials) {
const { headers } = await thisTunnel.request;
const basedCredentials = Buffer.from(connectionOpt.credentials)
.toString('base64'); //converting to base64
headers[PROXY_AUTH.toLowerCase()] = PROXY_AUTH_BASIC + BLANK + basedCredentials;
const newData = rebuildHeaders(headers, data);
thisTunnel.clientRequestWrite(newData)
}
else {
onDirectConnectionOpen(data);
}
}
/**
* @param {Error} connectionError
* @returns {Promise<void>}
*/
async function onTunnelHTTPSConnectionOpen(connectionError) {
if (connectionError) {
return onClose(connectionError);
}
if (connectionOpt.upstreamed) {
if (connectionOpt.credentials) {
const { headers } = await thisTunnel.request;
const basedCredentials = Buffer.from(connectionOpt.credentials).toString('base64'); //converting to base64
headers[PROXY_AUTH.toLowerCase()] = PROXY_AUTH_BASIC + BLANK + basedCredentials;
const newData = rebuildHeaders(headers, data);
thisTunnel.clientRequestWrite(newData)
}
else {
onDirectConnectionOpen(data);
}
}
else {
// response as normal http-proxy
thisTunnel.clientResponseWrite(OK + CRLF + CRLF);
updateSockets();
}
}
const callbackOnConnect = (isConnectMethod)
? onTunnelHTTPSConnectionOpen
: onTunnelHTTPConnectionOpen;
if (connectionOpt) {
logger.log(remoteID, '=>', thisTunnel.getTunnelStats());
const responseSocket = net.createConnection(connectionOpt, callbackOnConnect);
thisTunnel.setRequestSocket(responseSocket
.on(DATA, onDataFromUpstream)
.on(CLOSE, onClose)
.on(ERROR, onClose)
);
}
return connectionOpt;
}
/**
* @param {Array<string>} split
* @param {buffer} data
*/
function handleProxyTunnel(split, data) {
const firstHeaderRow = split[0];
const thisTunnel = bridgedConnections[remoteID];
if (~firstHeaderRow.indexOf(CONNECT)) { //managing HTTP-Tunnel(upstream) & HTTPs
return prepareTunnel(data, firstHeaderRow, true);
}
else if (firstHeaderRow.indexOf(CONNECT) === -1
&& !thisTunnel._dst) { // managing http
return prepareTunnel(data, firstHeaderRow);
}
else if (thisTunnel && thisTunnel._dst) {
return onDirectConnectionOpen(data);
}
}
/**
* @param {buffer} data
* @returns {Promise<Session|void>}
*/
async function onDataFromClient(data) {
const thisTunnel = bridgedConnections[remoteID];
const dataString = data.toString();
try {
if (dataString && dataString.length > 0) {
const { headers } = await thisTunnel.request;
const split = dataString.split(CRLF);
if (isFunction(auth)
&& !thisTunnel.isAuthenticated()) {
const proxyAuth = headers[PROXY_AUTH.toLowerCase()];
if (proxyAuth) {
const credentials = proxyAuth
.replace(PROXY_AUTH_BASIC, EMPTY);
const parsedCredentials = Buffer.from(credentials, 'base64')
.toString(); //converting from base64
const [username, password] = parsedCredentials.split(SEPARATOR, 2); // TODO split only once
let isLogged = auth(username, password, thisTunnel);
if (isLogged instanceof Promise) { //if async operation...
isLogged = await isLogged; //...need to resolve promise
}
if (isLogged) {
thisTunnel.setUserAuthentication(username);
return handleProxyTunnel(split, data);
}
else {
//return auth-error and close all
thisTunnel.clientResponseWrite(AUTH_REQUIRED + DOUBLE_CLRF + HTTP_BODIES.AUTH_REQUIRED);
return onClose();
}
}
else {
return thisTunnel.clientResponseWrite(AUTH_REQUIRED + DOUBLE_CLRF);
}
}
else {
return handleProxyTunnel(split, data);
}
}
}
catch (err) {
return onClose(err);
}
}
bridgedConnections[remoteID] = new Session(remoteID); //initializing bridged-connection
bridgedConnections[remoteID].setResponseSocket(
clientSocket
.on(DATA, onDataFromClient)
.on(ERROR, onClose)
.on(CLOSE, onClose)
.on(EXIT, onClose)
);
};