-
Notifications
You must be signed in to change notification settings - Fork 33
/
nassh_stream_relay_sshfe.js
416 lines (365 loc) · 12.2 KB
/
nassh_stream_relay_sshfe.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright 2018 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Stream for connecting to a ssh server via a SSH-FE relay.
*/
import {lib} from '../../libdot/index.js';
import {base64ToBase64Url, runtimeSendMessage} from './nassh.js';
import {Message} from './nassh_agent_message.js';
import {MessageNumbers, readMessage,
writeMessage} from './nassh_agent_message_types.js';
import {newBuffer} from './nassh_buffer.js';
import {Stream} from './nassh_stream.js';
/**
* WebSocket backed stream.
*
* This class manages the read and write through WebSocket to communicate
* with the SSH-FE relay server.
*
* Resuming of connections is not supported.
*
* @param {number} fd
* @constructor
* @extends {Stream}
*/
export function RelaySshfeWsStream(fd) {
Stream.call(this, fd);
// The relay connection settings.
this.io_ = null;
this.relayHost_ = null;
this.relayPort_ = null;
this.relayUser_ = null;
// The remote ssh server settings.
this.host_ = null;
this.port_ = null;
// The ssh-agent we talk to for the SSH-FE challenge.
this.sshAgent_ = null;
// All the data we've queued but not yet sent out.
this.writeBuffer_ = newBuffer();
// Callback function when asyncWrite is used.
this.onWriteSuccess_ = null;
// The total byte count we've written during this session.
this.writeCount_ = 0;
// Data we've read so we can ack it to the server.
this.readCount_ = 0;
// The actual WebSocket connected to the ssh server.
this.socket_ = null;
}
/**
* We are a subclass of Stream.
*/
RelaySshfeWsStream.prototype = Object.create(Stream.prototype);
/** @override */
RelaySshfeWsStream.constructor = RelaySshfeWsStream;
/**
* Open a relay socket.
*
* @param {!Object} settings
* @param {function(boolean, string=)} onComplete
* @override
*/
RelaySshfeWsStream.prototype.asyncOpen = async function(settings, onComplete) {
this.io_ = settings.io;
this.relayHost_ = settings.relayHost;
this.relayPort_ = settings.relayPort;
this.relayUser_ = settings.relayUser;
this.host_ = settings.host;
this.port_ = settings.port;
this.sshAgent_ = settings.sshAgent;
// The SSH-FE challenge details.
let sshFeChallenge = null;
let sshFeSignature = null;
// Use Promise.resolve to put all of getChallenge into a promise in case any
// of its setup logic throws an exception (for our catch below).
Promise.resolve()
.then(() => this.getChallenge_())
.then((challenge) => {
sshFeChallenge = challenge;
return this.signChallenge_(challenge);
})
.then((signature) => {
sshFeSignature = base64ToBase64Url(signature);
this.connect_(sshFeChallenge, sshFeSignature);
onComplete(true);
})
.catch((e) => onComplete(false, `${e.message}\r\n${lib.f.getStack()}`));
};
/**
* URI to get a new challenge for connecting through the relay.
*/
RelaySshfeWsStream.prototype.challengeTemplate_ =
`%(protocol)://%(relayHost):%(relayPort)` +
`/ssh-fe/challenge?user=%encodeURIComponent(relayUser)`;
/**
* Get the server challenge.
*
* @return {!Promise} A promise to resolve with the server's challenge.
*/
RelaySshfeWsStream.prototype.getChallenge_ = function() {
// Send the current user to the relay to get the challenge.
const uri = lib.f.replaceVars(this.challengeTemplate_, {
protocol: 'https',
relayHost: this.relayHost_,
relayPort: this.relayPort_,
relayUser: this.relayUser_,
});
const req = new Request(uri);
return fetch(req)
.then((response) => {
// Make sure the server didn't return a failure.
if (!response.ok) {
throw new Error(response.statusText);
}
// Get the response from the server as a blob.
return response.blob();
})
.then((blob) => blob.text())
.then((result) => {
// Skip the XSSI countermeasure.
if (!result.startsWith(")]}'\n")) {
throw Error(`Unknown response: ${result}`);
}
// Pull out the challenge from the response.
const obj = JSON.parse(result.slice(5));
return obj.challenge;
});
};
/**
* @typedef {{
* data: !Array
* }}
*/
RelaySshfeWsStream.AgentResponse;
/**
* Send a message to the ssh agent.
*
* @param {!Array} data The object to send to the agent.
* @return {!Promise<!RelaySshfeWsStream.AgentResponse>} A promise to
* resolve with the agent's response.
*/
RelaySshfeWsStream.prototype.sendAgentMessage_ = function(data) {
return /** @type {!Promise<!RelaySshfeWsStream.AgentResponse>} */ (
runtimeSendMessage(
this.sshAgent_, {'type': '[email protected]', 'data': data}));
};
/**
* Sign the server's challenge with a ssh key via a ssh agent.
*
* TODO: This uses gnubby-specific messages currently (113 & 114) to locate the
* specific key to use to sign the challenge.
*
* @param {string} challenge The server challenge
* @return {!Promise} A promise to resolve with the signed result.
*/
RelaySshfeWsStream.prototype.signChallenge_ = function(challenge) {
// Construct a SSH_AGENTC_PUBLIC_KEY_CHALLENGE packet.
// byte code
// byte slot
// byte alt
// TODO: Rename "challenge" since it has nothing to do with |challenge| param.
// string challenge (16 bytes)
const buffer = new ArrayBuffer(23);
const u8 = new Uint8Array(buffer);
const dv = new DataView(buffer);
// message code: SSH_AGENTC_PUBLIC_KEY_CHALLENGE.
dv.setUint8(0, 113);
// public key slot: Where we store the key to use.
// TODO: Users should be able to select this.
dv.setUint8(1, 5);
// alternate: Set to false.
dv.setUint8(2, 0);
// The challenge length.
dv.setUint32(3, 16);
// The random challenge itself.
crypto.getRandomValues(u8.subarray(7, 16));
// Send the challenge.
return this.sendAgentMessage_(Array.from(u8)).then((result) => {
if (result.data.length <= 5) {
throw new Error(
`Agent failed; missing ssh certificate? (${result.data})`);
}
// Receive SSH_AGENTC_PUBLIC_KEY_RESPONSE.
const response = readMessage(new Message(
result.data[0], new Uint8Array(result.data.slice(1))));
// Construct a SSH_AGENTC_SIGN_REQUEST.
const request = writeMessage(
MessageNumbers.AGENTC_SIGN_REQUEST,
new Uint8Array(response.fields.publicKeyRaw),
lib.codec.stringToCodeUnitArray(challenge));
// Send the sign request. We can only send Arrays, but request is a typed
// array, so convert it over (and skip leading length field).
const data = Array.from(request.rawMessage().subarray(4));
return this.sendAgentMessage_(data).then((result) => {
if (result.data.length <= 5) {
throw new Error(
`Agent failed; unable to sign challenge (${result.data})`);
}
// Return the signed challenge.
return btoa(lib.codec.codeUnitArrayToString(result.data.slice(5)));
});
});
};
/**
* Maximum length of message that can be sent to avoid request limits.
*/
RelaySshfeWsStream.prototype.maxMessageLength = 64 * 1024;
/**
* URI to establish a connection to the ssh server via the relay.
*
* Note: The user field here isn't really needed. We pass it along to help
* with remote logging on the server.
*/
RelaySshfeWsStream.prototype.connectTemplate_ =
`%(protocol)://%(relayHost):%(relayPort)/connect` +
`?ssh-fe-challenge=%encodeURIComponent(challenge)` +
`&ssh-fe-signature=%encodeURIComponent(signature)` +
`&host=%encodeURIComponent(host)` +
`&port=%encodeURIComponent(port)` +
`&user=%encodeURIComponent(relayUser)` +
`&ack=%(readCount)` +
`&pos=%(writeCount)`;
/**
* Start a new connection to the proxy server.
*
* @param {string} challenge
* @param {string} signature
*/
RelaySshfeWsStream.prototype.connect_ = function(challenge, signature) {
if (this.socket_) {
throw new Error('stream already connected');
}
const uri = lib.f.replaceVars(this.connectTemplate_, {
protocol: 'wss',
relayHost: this.relayHost_,
relayPort: this.relayPort_,
relayUser: this.relayUser_,
challenge: challenge,
signature: signature,
host: this.host_,
port: this.port_,
readCount: this.readCount_,
writeCount: 0,
});
this.socket_ = new WebSocket(uri);
this.socket_.binaryType = 'arraybuffer';
this.socket_.onopen = this.onSocketOpen_.bind(this);
this.socket_.onmessage = this.onSocketData_.bind(this);
this.socket_.onclose = this.onSocketClose_.bind(this);
this.socket_.onerror = this.onSocketError_.bind(this);
};
/**
* Close the connection to the proxy server and clean up.
*
* @param {string} reason A short message explaining the reason for closing.
*/
RelaySshfeWsStream.prototype.close_ = function(reason) {
// If we aren't open, there's nothing to do. This allows us to call it
// multiple times, perhaps from cascading events (write error/close/etc...).
if (!this.socket_) {
return;
}
console.log(`Closing socket due to ${reason}`);
this.socket_.close();
this.socket_ = null;
Stream.prototype.close.call(this);
};
/**
* Callback when the socket connects successfully.
*
* @param {!Event} e The event details.
*/
RelaySshfeWsStream.prototype.onSocketOpen_ = function(e) {
// If we had any pending writes, kick them off. We can't call sendWrite
// directly as the socket isn't in the correct state until after this handler
// finishes executing.
setTimeout(this.sendWrite_.bind(this), 0);
};
/**
* Callback when the socket closes when the connection is finished.
*
* @param {!CloseEvent} e The event details.
*/
RelaySshfeWsStream.prototype.onSocketClose_ = function(e) {
this.close_('server closed socket');
};
/**
* Callback when the socket closes due to an error.
*
* @param {!Event} e The event details.
*/
RelaySshfeWsStream.prototype.onSocketError_ = function(e) {
this.close_('server sent an error');
};
/**
* Callback when new data is available from the server.
*
* @param {!MessageEvent} e The message with data to read.
*/
RelaySshfeWsStream.prototype.onSocketData_ = function(e) {
const dv = new DataView(e.data);
const ack = dv.getUint32(0);
// Acks are unsigned 24 bits. Negative means error.
if (ack > 0xffffff) {
this.close_(`ack ${ack} is an error`);
return;
}
// This creates a copy of the ArrayBuffer, but there doesn't seem to be an
// alternative -- PPAPI doesn't accept views like Uint8Array. And if it did,
// it would probably still serialize the entire underlying ArrayBuffer (which
// in this case wouldn't be a big deal as it's only 4 extra bytes).
const data = e.data.slice(4);
this.readCount_ = (this.readCount_ + data.byteLength) & 0xffffff;
this.onDataAvailable(data);
};
/**
* Queue up some data to write asynchronously.
*
* @param {!ArrayBuffer} data A base64 encoded string.
* @param {function(number)=} onSuccess Optional callback.
* @override
*/
RelaySshfeWsStream.prototype.asyncWrite = function(data, onSuccess) {
if (!data.byteLength) {
return;
}
this.writeBuffer_.write(data);
this.onWriteSuccess_ = onSuccess;
this.sendWrite_();
};
/**
* Send out any queued data.
*/
RelaySshfeWsStream.prototype.sendWrite_ = function() {
if (!this.socket_ || this.socket_.readyState != 1 ||
this.writeBuffer_.isEmpty()) {
// Nothing to write or socket is not ready.
return;
}
// If we've queued too much already, go back to sleep.
// NB: This check is fuzzy at best, so we don't need to include the size of
// the data we're about to write below into the calculation.
if (this.socket_.bufferedAmount >= this.maxWebSocketBufferLength) {
setTimeout(this.sendWrite_.bind(this));
return;
}
const readBuffer = this.writeBuffer_.read(this.maxMessageLength);
const size = readBuffer.length;
const buf = new ArrayBuffer(size + 4);
const u8 = new Uint8Array(buf, 4);
const dv = new DataView(buf);
dv.setUint32(0, this.readCount_);
// Copy over the read buffer.
u8.set(readBuffer);
this.socket_.send(buf);
this.writeBuffer_.ack(size);
this.writeCount_ += size;
if (this.onWriteSuccess_) {
// Notify nassh that we are ready to consume more data.
this.onWriteSuccess_(this.writeCount_);
}
if (!this.writeBuffer_.isEmpty()) {
// We have more data to send but due to message limit we didn't send it.
setTimeout(this.sendWrite_.bind(this), 0);
}
};