forked from peter-x/ftpmult
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathftpmult.js
314 lines (269 loc) · 12 KB
/
ftpmult.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
var net = require('net');
var util = require('util');
function FtpServer(options) {
var self = this;
if (!(this instanceof FtpServer)) {
return new FtpServer(options);
}
this.myHost = options.host || '127.0.0.1';
this.server = net.createServer();
this.getHostFromUsername = options.getHostFromUsername || function(username) { return null; };
this.logLevel = options.logLevel || 0;
function log(level, message, isError) {
if (self.logLevel < level)
return;
var now = new Date();
var dateStr = now.getFullYear() + "-" + (1 + now.getMonth()) + "-" + now.getDate() + " " +
now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
console.log(dateStr + " " + message);
if (isError)
console.trace("Trace follows");
};
this.server.on("error", function (err) {
log(0, "Server error: " + err);
});
this.server.on("listening", function() {
log(0, "FTP multiplexer up and ready for connections.");
});
this.server.on("connection", function(clientSocket) {
var conn = {
clientSocket: clientSocket,
serverSocket: null,
serverGreetingRecieved: false,
log: function(level, message, isError) {
log(level, clientSocket.remoteAddress + ': ' + message, isError);
},
destination: null
}
clientSocket.setEncoding("ascii");
clientSocket.setNoDelay();
conn.log(1, "Client connected.");
clientSocket.write("220 FTP multiplexer ready\r\n");
clientSocket.on("end", function() {
conn.log(1, "Client disconnected.");
});
clientSocket.on("error", function(err) {
conn.log(0, "Client connection error: " + err);
clientSocket.destroy();
});
clientSocket.on("data", handleClientData);
function parseFTPCommand(data) {
var m = (data + '').match(/\s*(\S*)(\s+(.*\S))?\s*/);
if (!m) {
return {cmd: '', arg: ''};
} else {
return {cmd: m[1], arg: m[3]};
}
}
function parseServerResponse(data) {
var m = (data + '').match(/\s*(\d{1,3})([\s-]+(.*\S))?\s*/);
if (!m) {
return {cmd: '', arg: ''};
} else {
return {cmd: m[1], arg: m[3]};
}
}
function forwardPassiveConnection(host, port, callback) {
conn.log(0, "Establishing forward for passive connection (" + host + ":" + port + ")");
var listenPort = null;
var serverConnected = false;
var clientConnected = false;
var psvListener = net.createServer(function(lsocket) {
if (clientConnected) {
lsocket.end();
} else {
conn.log(4, "Client connected to forwarder.");
clientConnected = true;
psvListener.close();
lsocket.on('error', function(err) {
conn.log(0, "Passive forwarding error: " + err, conn);
lsocket.destroy();
});
lsocket.pipe(serverConn);
serverConn.pipe(lsocket);
}
});
psvListener.listen(0, function() {
conn.log(4, "Listening for client.");
listenPort = psvListener.address().port;
tryNotifyingClient();
});
psvListener.on('error', function(err) {
conn.log(0, "Passive listener error: " + err, conn);
psvListener.destroy();
});
var serverConn = net.createConnection(port, host, function() {
conn.log(4, "Connected to server.");
serverConnected = true;
tryNotifyingClient();
});
serverConn.on('error', function(err) {
conn.log(0, "Passive forwarding error: " + err, conn);
serverConn.destroy();
});
function tryNotifyingClient() {
if (listenPort === null || !serverConnected)
return;
conn.log(4, "Forwarder established, notifying client.");
callback(self.myHost, listenPort);
}
}
function forwardActiveConnection(host, port, callback) {
conn.log(0, "Establishing forward for active connection (" + host + ":" + port + ")");
var listenPort = null;
var serverConnected = false;
var clientConnected = false;
var actvListener = net.createServer(function(lsocket) {
if (serverConnected) {
lsocket.end();
} else {
conn.log(4, "Server connected to reverse data forwarder.");
serverConnected = true;
actvListener.close();
lsocket.on('error', function(err) {
conn.log(0, "Active reverse forwarding error: " + err, conn);
lsocket.destroy();
});
lsocket.pipe(clientConn);
clientConn.pipe(lsocket);
}
});
actvListener.listen(0, function() {
conn.log(4, "Listening for server.");
listenPort = actvListener.address().port;
sendPortToServer();
});
actvListener.on('error', function(err) {
conn.log(0, "Passive listener error: " + err, conn);
actvListener.destroy();
});
var clientConn = net.createConnection(port, host, function() {
conn.log(4, "Connected to client.");
clientConnected = true;
});
clientConn.on('error', function(err) {
conn.log(0, "Passive forwarding error: " + err, conn);
clientConn.destroy();
});
function sendPortToServer() {
if (listenPort === null)
return;
conn.log(4, "Reverse Forwarder established, notifying client.");
callback(self.myHost, listenPort);
}
}
function handleClientData(data) {
// Don't want to include passwords in logs.
conn.log(2, "Client command: " + (data + '').trim().toString('utf-8').replace(/^PASS\s+.*/, 'PASS ***'));
var command = parseFTPCommand(data);
// we alredy have a connection
if (conn.serverSocket !== null) {
// intercept ACTIVE
if (command.cmd === "PORT") {
conn.log(3, "Trying to intercept active mode: " + command.arg);
var m = command.arg.match(/(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1,3})/);
if (m) {
var hostname = m[1] + '.' + m[2] + '.' + m[3] + '.' + m[4];
var port = parseInt(m[5]) * 256 + parseInt(m[6]);
forwardActiveConnection(hostname, port, function(localHost, localPort) {
var i1 = parseInt(localPort / 256);
var i2 = parseInt(localPort % 256);
conn.log(0, "PORT " + localHost.split(".").join(",") + "," + i1 + "," + i2);
conn.serverSocket.write("PORT " + localHost.split(".").join(",") + "," + i1 + "," + i2 + "\r\n");
});
return;
} else {
conn.log(1, "Unable to parse PORT address.");
}
}
// everything else
conn.serverSocket.write(data);
return;
}
if (command.cmd !== "USER") {
clientSocket.write("202 Not supported\r\n");
return;
}
conn.destination = self.getHostFromUsername(command.arg);
if (conn.destination === null) {
clientSocket.write("530 Invalid username\r\n");
clientSocket.close();
return;
}
conn.serverSocket = net.createConnection(conn.destination.port, conn.destination.hostname);
conn.serverSocket.setEncoding('ascii');
conn.serverSocket.setNoDelay();
conn.serverSocket.on('connect', function() {
conn.serverSocket.write(data);
});
conn.serverSocket.on('data', function(data) {
data.split('\r\n').forEach(function(data) {
if ((data + '').trim()) {
handleServerResponse(data + '\r\n');
}
});
});
conn.serverSocket.on('end', function() {
clientSocket.end();
});
conn.serverSocket.on('error', function(err) {
conn.log(0, "Error from server connection: " + err);
clientSocket.end();
});
}
function handleServerResponse(data) {
conn.log(2, "Server response: " + (data + '').trim().toString('utf-8'));
var command = parseServerResponse(data);
if (!conn.serverGreetingRecieved) {
if (command.cmd === "220") {
/* suppress "welcome"-message, wait for the answer to
* the USER-command */
conn.log(4, "Response suppressed.");
return;
} else {
conn.serverGreetingRecieved = true;
}
} else if (command.cmd === "227") {
/* intercept passive mode */
conn.log(3, "Trying to intercept passive mode.");
var m = command.arg.match(/.*\((\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1,3})\).*/);
if (m) {
var hostname = m[1] + '.' + m[2] + '.' + m[3] + '.' + m[4];
var port = parseInt(m[5]) * 256 + parseInt(m[6]);
forwardPassiveConnection(hostname, port, function(localHost, localPort) {
var i1 = parseInt(localPort / 256);
var i2 = parseInt(localPort % 256);
conn.log(0, "227 Entering Passive Mode (" + localHost.split(".").join(",") + "," + i1 + "," + i2 + ")");
clientSocket.write("227 Entering Passive Mode (" + localHost.split(".").join(",") + "," + i1 + "," + i2 + ")\r\n");
});
return;
} else {
conn.log(1, "Unable to parse PASV address.");
}
} else if (command.cmd === "229") {
conn.log(3, "Trying to intercept extended passive mode.");
var m = command.arg.match(/.*\(\|\|\|(\d{1,5})\|\).*/);
if (m) {
var port = parseInt(m[1]);
forwardPassiveConnection(conn.destination.hostname, port, function(localHost, localPort) {
conn.log(0, "229 Entering Passive Mode (|||" + localPort + "|)");
clientSocket.write("229 Entering Passive Mode (|||" + localPort + "|)\r\n");
});
return;
} else {
conn.log(1, "Unable to parse EPASV address.");
}
}
clientSocket.write(data);
}
});
this.server.on("close", function() {
log(0, "Server closed");
});
}
["listen", "close"].forEach(function (fname) {
FtpServer.prototype[fname] = function () {
return this.server[fname].apply(this.server, arguments);
}
});
exports.FtpServer = FtpServer;