/
agent.js
298 lines (285 loc) · 8.42 KB
/
agent.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
const net = require("net");
const http = require("http");
const https = require("https");
const { Client } = require("ssh2");
//implements "private" properties
const debug = Symbol();
const cachedClient = Symbol();
class SSHConnectionManager {
constructor(vias, opts) {
this.vias = Array.isArray(vias) ? vias : [vias];
this.vias.forEach(v => {
if (!v || !v.host) throw `"host" required`;
});
this.socks = {};
this.channelCount = 0;
//init opts (ssh global options, inserted into all vias)
if (typeof opts === "boolean") {
opts = { debug: opts };
} else if (!opts) {
opts = {};
}
//default opts
if (opts.debug !== true) {
opts.debug = false;
}
//disconnect asap after last conn
this.disconnectDelay = 0;
if (typeof opts.disconnectDelay === "number") {
this.disconnectDelay = opts.disconnectDelay;
delete opts.disconnectDelay;
}
//tcp+ssh timeouts
let timeout = 5000;
if (typeof opts.timeout === "number") {
timeout = opts.timeout;
delete opts.timeout;
opts.readyTimeout = timeout;
}
this.timeout = timeout;
this.opts = opts;
//prepare logger
if (opts.debug) {
this[debug] = function() {
let prefix = "[ssh-agent]";
console.log.apply(console, [prefix].concat(Array.from(arguments)));
};
const inherit = function(prefix) {
let parent = this;
let child = parent.bind(this, prefix);
child.inherit = inherit.bind(child);
return child;
};
this[debug].inherit = inherit.bind(this[debug]);
this[debug]("debug enabled");
} else {
this[debug] = () => {}; //noop
this[debug].inherit = () => this[debug]; //noop
}
}
bind(httpAgent) {
if (this.vias.length === 0) {
this[debug]("no ssh configs provided");
return;
}
this.httpAgent = httpAgent;
this.wrapTLS = httpAgent.protocol === "https:";
this.origCreateConnection = this.httpAgent.createConnection.bind(httpAgent);
this.httpAgent.createConnection = this.createConnection.bind(this);
}
createConnection(httpOpts, callback) {
this[debug]("create connection");
this.createConnectionAsync(httpOpts)
.then(sock => callback(null, sock))
.catch(err => callback(err));
}
async createConnectionAsync(httpOpts) {
//create ssh pipeline to host/port
let socket, client;
for (let i = 0; i < this.vias.length; i++) {
let via = this.vias[i];
let { host, port = 22 } = via;
socket = await this.dedupSock(host, port, async () => {
return i === 0
? //initialise sock with tcp
await this.tcpConnect(host, port)
: //otherwise, forward using current ssh client
await this.sshFoward(client, host, port);
});
//handshake ssh over current sock
client = await this.sshConnect(socket, via);
}
//final hop should always be forwarded
socket = await this.sshFoward(client, httpOpts.host, httpOpts.port);
//optional tls handshake via https agent...
if (this.wrapTLS) {
socket = this.origCreateConnection(Object.assign({ socket }, httpOpts));
}
return socket;
}
async dedupSock(host, port, create) {
let key = `${host}:${port}`;
let sock = this.socks[key];
//connect in progress...
if (sock instanceof Promise) {
this[debug](`tcp connect already in progress`);
await sock;
sock = this.socks[key];
}
//no connected yet
if (!sock) {
let done;
this.socks[key] = new Promise(r => (done = r));
sock = await create();
sock[debug]("connected");
let sockend = sock.end;
sock.end = () => {
delete this.socks[key]; //remove from cache asap
sockend.call(sock);
};
sock.on("close", () => {
delete this.socks[key];
sock[debug]("disconnected");
});
//connected
this.socks[key] = sock;
done();
}
return sock;
}
async sshConnect(sock, opts) {
sock[debug](`ssh connect`);
// currently connecting?
let client = sock[cachedClient];
if (client instanceof Promise) {
sock[debug](`ssh connect already in progress`);
await client;
client = sock[cachedClient];
}
//connect and cache ssh connections
if (!client) {
//create a promise to catch duplicate connection requests
let done;
sock[cachedClient] = new Promise(r => (done = r));
//do connect!
sock[debug]("ssh handshaking...");
client = await new Promise((resolve, reject) => {
var c = new Client();
c.on("ready", () => resolve(c));
c.on("error", err => reject(err));
c.connect(Object.assign({ sock }, opts));
});
client[debug] = sock[debug].inherit(`@${opts.username || "anon"}`);
client[debug]("ssh handshook, connected");
let clientend = client.end;
client.end = () => {
delete sock[cachedClient]; //remove from cache asap
clientend.call(client);
};
client.on("close", () => {
delete sock[cachedClient];
client[debug]("ssh disconnected");
});
client.channelsOpen = 0;
sock[cachedClient] = client;
done();
}
return client;
}
//local tcp dial (manual-async)
tcpConnect(host, port) {
return new Promise((resolve, reject) => {
let sock = net.createConnection(port, host);
sock[debug] = this[debug].inherit(`[${host}:${port}]`);
let returned = false;
const fail = err => {
if (returned) return;
returned = true;
sock[debug](err);
reject(err);
};
sock.setNoDelay(true);
sock.setTimeout(this.timeout, () => {
fail(new Error(`TCP Timed out after ${this.timeout}ms`));
});
sock.once("error", err => {
fail(err);
});
sock.once("close", () => {
fail("closed");
});
sock.once("connect", () => {
returned = true;
sock[debug]("connected");
resolve(sock);
});
});
}
//remote tcp dial (manual-async)
sshFoward(client, host, port) {
return new Promise((resolve, reject) => {
//channel debugging
let id = ++this.channelCount;
const sdebug = client[debug].inherit(`ch#${id}[${host}:${port}]`);
//count open channels, close on end last
client.channelsOpen++;
sdebug(`forward (open ${client.channelsOpen})`);
const done = () => {
client.channelsOpen--;
sdebug(`unforward (open ${client.channelsOpen})`);
if (client.channelsOpen === 0) {
setTimeout(autoDisconnect, this.disconnectDelay);
}
};
const autoDisconnect = () => {
if (client.channelsOpen === 0) {
sdebug(`close ssh, no more forwards open`);
client.end();
}
};
client.forwardOut("127.0.0.1", 0, host, port, (err, stream) => {
if (err) {
done();
return reject(err);
}
stream.allowHalfOpen = false;
stream.setKeepAlive = () => {
sdebug("TODO: keepalive");
};
stream.setNoDelay = () => {
sdebug("TODO: set no delay");
};
stream.setTimeout = () => {
sdebug("TODO: set timeout");
};
stream.ref = () => {
sdebug("TODO: ref");
};
stream.unref = () => {
sdebug("TODO: unref");
};
stream.destroySoon = () => {
sdebug("destroy soon");
stream.end();
};
stream.destroy = () => {
sdebug("destroy");
stream.end();
};
stream.on("readable", () => {
sdebug("readable");
});
stream.on("pipe", () => {
sdebug("pipe");
});
stream.on("unpipe", () => {
sdebug("unpipe");
});
stream.on("finish", () => {
sdebug("finish");
});
//handle stream closes, close client on last stream
sdebug("open");
stream.on("close", () => {
sdebug("close");
done();
});
//stream ready
stream[debug] = sdebug;
resolve(stream);
});
});
}
}
function sshAgent(agent, via, debug) {
let s = new SSHConnectionManager(via, debug);
s.bind(agent);
return agent;
}
sshAgent.http = function(via, debug) {
return sshAgent(new http.Agent(), via, debug);
};
sshAgent.https = function(via) {
return sshAgent(new https.Agent(), via, debug);
};
module.exports = sshAgent;