-
Notifications
You must be signed in to change notification settings - Fork 1
/
wsproxy.js
350 lines (280 loc) · 11.9 KB
/
wsproxy.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
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
var http = require('http');
var https = require('https');
var fs = require('fs');
var net=require('net');
var WebSocketServer = require('websocket').server;
var WebSocketClient = require('websocket').client;
var processor = require('./wsprocessor.js');
var config = require('./config');
const outgoing_processor = require('./custom_scripts/outgoing');
var verbose = config.verbose;
var getTimeStamp = processor.getTimeStamp;
if (config.logStdOutToFile) {
var path = require('path');
if (!fs.existsSync(config.logStdOutFilePath)){
fs.mkdirSync(config.logStdOutFilePath)
}
if (!fs.lstatSync(config.logStdOutFilePath).isDirectory()) {
console.log('Log file output path exists and is not a directory.');
process.exit(1);
}
var logFile = path.join(config.logStdOutFilePath,getTimeStamp()+'_wsproxy.txt');
doLog = function(log){
data = log.map(function(x){return (x)?x.toString():''}).join(' ');
console.log(getTimeStamp(),data);
fs.appendFileSync(logFile, getTimeStamp() + ' ' + data + '\n');
}
}
else {
doLog = function(log){
data = log.map(function(x){return (x)?x.toString():''}).join(' ');
console.log(getTimeStamp(), data);
}
}
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
processor.initRules(config, doLog);
if(config.webserver) {
processor.startServer(config.webinterfaceport)
}
var ssloptions = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
net.createServer(tcpConnection).listen(config.proxyport);
function tcpConnection(conn) {
conn.once('data', function (buf) {
// A TLS handshake record starts with byte 22.
var address = (buf[0] === 22) ? config.sslport : config.httpport;
var proxy = net.createConnection(address, function () {
proxy.write(buf);
conn.pipe(proxy).pipe(conn);
});
});
}
https_mitm = https.createServer(ssloptions, function (req, res) {
var port = (req.headers['host'].indexOf(':') > -1) ? req.headers['host'].split(':')[1] : 443;
var hostname = (req.headers['host'].indexOf(':') > -1) ? req.headers['host'].split(':')[0] : req.headers['host'];
var options= { hostname:hostname,
port: port,
path: req.url,
method: req.method,
headers: req.headers
};
try{
var proxy_request = https.request(options);
proxyRequestor(req,res,proxy_request)
}
catch(err){
console.trace()
}
}).listen(config.sslport);
http_mitm = http.createServer(function(req,res){
var port = (req.headers['host'].indexOf(':') > -1) ? req.headers['host'].split(':')[1] : 80;
var hostname = (req.headers['host'].indexOf(':') > -1) ? req.headers['host'].split(':')[0] : req.headers['host'];
var options= { hostname:hostname,
port: port,
path: req.url,
method: req.method,
headers: req.headers
};
try{
var proxy_request = http.request(options);
proxyRequestor(req,res,proxy_request)
}
catch(err){
console.trace()
}
}).listen(config.httpport);
//Handle CONNECT request for HTTPS sessions
http_mitm.on('connect', function(req, res, head) {
// connect to an origin server
var mitm_socket = net.connect(config.proxyport, function() {
res.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node-Proxy\r\n' + '\r\n');
});
mitm_socket.on('data', function(d) { res.write(d) });
res.on('data', function(d) { try { mitm_socket.write(d) } catch(err) {}});
mitm_socket.on('end',function(){ res.end() });
res.on('end',function() { mitm_socket.end() });
mitm_socket.on('close',function(){ res.end() });
res.on('close',function(){ mitm_socket.end() });
mitm_socket.on('error',function(){ res.end() });
res.on('error',function(){ mitm_socket.end() });
});
https_mitm.on('upgrade',function(req,res,head){
doLog(['Https connection request for channel:',req.url])
});
http_mitm.on('upgrade',function(req,res,head){
doLog(['Http connection request for channel:', req.url])
});
//start websocket server for both http and https
wsServer = new WebSocketServer({
httpServer: [http_mitm,https_mitm],
maxReceivedFrameSize: config.maxFrameSize,
maxReceivedMessageSize: config.maxMessageSize,
autoAcceptConnections: false // request event does not get triggered unless this is set false
});
wsServer.on('connect', function(co){
});
// function to create the proxy to server part of the websocket connection chain
// separated out so we can easily reestablish in case server connection closed before client connection
createClient = function(proto, host, request, origin, connection){
var preRequests = [];
//temporary handler for Client<->Proxy connection to catch requests that come before Proxy<->Server session established
connection.on('message', function(d){
preRequests.push(d);
processor.saveOutgoing(request.resourceURL.path,d);
if (verbose) {doLog(['Received premature request from Client<->Proxy connection:',d.type,d.binaryData,d.utf8Data])}
});
var client = new WebSocketClient();
client.connect(proto+host+request.resourceURL.path, null,origin,request.httpRequest.headers);
client.on('connectFailed',function(error){
doLog(['Connect failed!!!!!!']);
doLog([error])
});
client.on('httpResponse', function(response, webSocketClient){
if (verbose) {
doLog(['Received non 101 httpResponse']);
doLog([response.headers,response.statusCode,response.statusMessage]);
}
});
client.on('connect',function(clconn){
if (verbose) { doLog(['Proxy<->Server websocket connected']) }
// remove the temporary event listener
connection.removeAllListeners();
// now the server side connection is established, send off queued requests
for (var i = 0; i < preRequests.length; i++) {
var d = preRequests[i];
if (verbose) {
if(d.type==='utf8' && !processor.ignore(1,d.utf8Data))
doLog(['Relaying premature request on Proxy<->Server connection:',processor.mangle(d.utf8Data)]);
if(d.type!=='utf8' && !processor.ignore(1,d.binaryData))
doLog(['Relaying premature request on Proxy<->Server connection:',d.binaryData])
}
(d.type==='utf8') ? clconn.sendUTF(d.utf8Data):clconn.sendBytes(d.binaryData);
}
processor.setWsOutgoingConnection(request.resourceURL.path,clconn);
connection.on('message', function(d) {
processor.saveOutgoing(request.resourceURL.path,d);
if (verbose) {
doLog(['Received message on Client<->Proxy connection:',d.type,d.binaryData,d.utf8Data]);
if(d.type==='utf8' && !processor.ignore(1,d.utf8Data))
doLog(['Relaying TEXT on Proxy<->Server connection:',processor.mangle(d.utf8Data)]);
if(d.type!=='utf8' && !processor.ignore(1,d.binaryData))
doLog(['Relaying BINARY on Proxy<->Server connection:',d.binaryData])
}
if(d.type==='utf8'){
let send_data = outgoing_processor.editTextData(d.utf8Data);
clconn.sendUTF(send_data);
}
else {
let send_data = outgoing_processor.editBinaryData(d.binaryData);
clconn.sendBytes(send_data);
}
});
clconn.on('message', function(d) {
processor.saveIncoming(request.resourceURL.path,d);
if (verbose) {
doLog(['Received message on Proxy<->Server connection:',d.type,d.binaryData,d.utf8Data]);
if(d.type==='utf8' && !processor.ignore(0,d.utf8Data))
doLog(['Relaying TEXT on Client<->Proxy connection:',d.utf8Data]);
if(d.type!=='utf8' && !processor.ignore(0,d.binaryData))
doLog(['Relaying BINARY on Client<->Proxy connection:',d.binaryData])
}
(d.type==='utf8') ? connection.sendUTF(d.utf8Data):connection.sendBytes(d.binaryData)
});
clconn.on('error', function(error){
if (verbose){
doLog(['Received error on Proxy<->Server connection']);
doLog([error]);
}
// clean up
connection.removeAllListeners();
clconn.removeAllListeners();
client.removeAllListeners();
clconn.close();
if (connection.connected) {
if (verbose){
doLog(['Client<->Proxy connection still active, attempting reconnect of Proxy<->Server socket'])
}
createClient(proto, host, request, origin, connection);
}
});
connection.on('error', function(error){
if (verbose) {
doLog(['Received error on Client<->Proxy connection']);
doLog([error]);
}
// unsure of the best approach here, are there recoverable errors?
// will just do nothing
});
clconn.on('close', function(reasonCode, description){
if (verbose) {
doLog(['Received close event on Proxy<->Server connection']);
doLog([description,reasonCode]);
}
// clean up
connection.removeAllListeners();
clconn.removeAllListeners();
client.removeAllListeners();
if (connection.connected) {
if (verbose){doLog(['Client<->Proxy connection still active, attempting reconnect of Proxy<->Server socket'])}
createClient(proto, host, request, origin, connection);
}
});
connection.on('close', function(reasonCode, description){
if (verbose) {
doLog(['Received close event on Client<->Proxy connection']);
doLog([description, reasonCode]);
}
processor.socketClosed(request.resourceURL.path);
// clean up
connection.removeAllListeners();
clconn.removeAllListeners();
client.removeAllListeners();
});
})
};
wsServer.on('request', function(request) {
processor.saveReq(request);
if (verbose){
doLog(['Client->Proxy websocket connected'])
}
var origin = request.httpRequest.headers['origin'] || null;
var proto = (request.resourceURL.protocol === 'http:' || request.resourceURL.protocol === 'http') ? 'ws://':'wss://';
if(request.resourceURL.protocol == null){
if (origin == null) {
proto = request.httpRequest.connection.encrypted ? 'wss://':'ws://';
}
else {
proto = origin.split(':')[0] === 'http' ? 'ws://':'wss://';
}
}
var host = request.httpRequest.headers['host'];
var connection = request.accept(null, request.origin);
processor.setWsIncomingConnection(request.resourceURL.path,connection);
doLog(['Open',request.resourceURL.path]);
processor.socketOpen(request.resourceURL.path);
createClient(proto, host, request, origin, connection);
});
proxyRequestor = function(req,res,proxy_request){
proxy_request.on('error', function(err) {
// Handle error
proxy_request.end();
res.end()
});
proxy_request.addListener('response', function (proxy_response) {
proxy_response.addListener('data', function(chunk) {
res.write(chunk, 'binary');
});
proxy_response.addListener('end', function() {
res.end();
});
res.writeHead(proxy_response.statusCode, proxy_response.headers);
});
req.addListener('data', function(chunk) {
proxy_request.write(chunk, 'binary');
});
req.addListener('end', function() {
proxy_request.end();
});
};