ai-remote 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +50 -0
  2. package/dist/index.js +7 -0
  3. package/dist/index.js.map +7 -0
  4. package/dist/protocols/index.js +35 -0
  5. package/dist/protocols/index.js.map +7 -0
  6. package/dist/protocols/rdp/buffer.js +170 -0
  7. package/dist/protocols/rdp/buffer.js.map +7 -0
  8. package/dist/protocols/rdp/caps.js +260 -0
  9. package/dist/protocols/rdp/caps.js.map +7 -0
  10. package/dist/protocols/rdp/cert.js +135 -0
  11. package/dist/protocols/rdp/cert.js.map +7 -0
  12. package/dist/protocols/rdp/client.js +1068 -0
  13. package/dist/protocols/rdp/client.js.map +7 -0
  14. package/dist/protocols/rdp/cliprdr.js +240 -0
  15. package/dist/protocols/rdp/cliprdr.js.map +7 -0
  16. package/dist/protocols/rdp/credssp.js +254 -0
  17. package/dist/protocols/rdp/credssp.js.map +7 -0
  18. package/dist/protocols/rdp/crypto.js +369 -0
  19. package/dist/protocols/rdp/crypto.js.map +7 -0
  20. package/dist/protocols/rdp/display.js +589 -0
  21. package/dist/protocols/rdp/display.js.map +7 -0
  22. package/dist/protocols/rdp/gcc.js +132 -0
  23. package/dist/protocols/rdp/gcc.js.map +7 -0
  24. package/dist/protocols/rdp/keymap.js +132 -0
  25. package/dist/protocols/rdp/keymap.js.map +7 -0
  26. package/dist/protocols/rdp/mcs.js +223 -0
  27. package/dist/protocols/rdp/mcs.js.map +7 -0
  28. package/dist/protocols/rdp/ntlm.js +305 -0
  29. package/dist/protocols/rdp/ntlm.js.map +7 -0
  30. package/dist/protocols/rdp/pdu.js +444 -0
  31. package/dist/protocols/rdp/pdu.js.map +7 -0
  32. package/dist/protocols/rdp/rail.js +383 -0
  33. package/dist/protocols/rdp/rail.js.map +7 -0
  34. package/dist/protocols/rdp/rle.js +276 -0
  35. package/dist/protocols/rdp/rle.js.map +7 -0
  36. package/dist/protocols/rdp/sec.js +156 -0
  37. package/dist/protocols/rdp/sec.js.map +7 -0
  38. package/dist/protocols/rdp/session.js +307 -0
  39. package/dist/protocols/rdp/session.js.map +7 -0
  40. package/dist/protocols/rdp/tls.js +354 -0
  41. package/dist/protocols/rdp/tls.js.map +7 -0
  42. package/dist/protocols/rdp/vchannel.js +59 -0
  43. package/dist/protocols/rdp/vchannel.js.map +7 -0
  44. package/dist/protocols/rdp/x224.js +110 -0
  45. package/dist/protocols/rdp/x224.js.map +7 -0
  46. package/dist/protocols/ssh/kex.js +177 -0
  47. package/dist/protocols/ssh/kex.js.map +7 -0
  48. package/dist/protocols/ssh/messages.js +55 -0
  49. package/dist/protocols/ssh/messages.js.map +7 -0
  50. package/dist/protocols/ssh/session.js +608 -0
  51. package/dist/protocols/ssh/session.js.map +7 -0
  52. package/dist/protocols/ssh/terminal.js +191 -0
  53. package/dist/protocols/ssh/terminal.js.map +7 -0
  54. package/dist/protocols/ssh/transport.js +611 -0
  55. package/dist/protocols/ssh/transport.js.map +7 -0
  56. package/dist/protocols/ssh/wire.js +189 -0
  57. package/dist/protocols/ssh/wire.js.map +7 -0
  58. package/dist/protocols/types.js +1 -0
  59. package/dist/protocols/types.js.map +7 -0
  60. package/dist/protocols/vnc/input.js +16 -0
  61. package/dist/protocols/vnc/input.js.map +7 -0
  62. package/dist/protocols/vnc/session.js +259 -0
  63. package/dist/protocols/vnc/session.js.map +7 -0
  64. package/dist/shared/connection.js +114 -0
  65. package/dist/shared/connection.js.map +7 -0
  66. package/dist/shared/device.js +1 -0
  67. package/dist/shared/device.js.map +7 -0
  68. package/dist/shared/hosts.js +133 -0
  69. package/dist/shared/hosts.js.map +7 -0
  70. package/dist/shared/icons.js +42 -0
  71. package/dist/shared/icons.js.map +7 -0
  72. package/dist/shared/protocol.js +40 -0
  73. package/dist/shared/protocol.js.map +7 -0
  74. package/dist/shared/signals.js +42 -0
  75. package/dist/shared/signals.js.map +7 -0
  76. package/package.json +82 -0
  77. package/src/index.ts +14 -0
  78. package/src/protocols/index.ts +72 -0
  79. package/src/protocols/rdp/buffer.ts +204 -0
  80. package/src/protocols/rdp/caps.ts +304 -0
  81. package/src/protocols/rdp/cert.ts +190 -0
  82. package/src/protocols/rdp/client.ts +1363 -0
  83. package/src/protocols/rdp/cliprdr.ts +344 -0
  84. package/src/protocols/rdp/credssp.ts +319 -0
  85. package/src/protocols/rdp/crypto.ts +416 -0
  86. package/src/protocols/rdp/display.ts +750 -0
  87. package/src/protocols/rdp/gcc.ts +162 -0
  88. package/src/protocols/rdp/keymap.ts +68 -0
  89. package/src/protocols/rdp/mcs.ts +283 -0
  90. package/src/protocols/rdp/ntlm.ts +380 -0
  91. package/src/protocols/rdp/pdu.ts +497 -0
  92. package/src/protocols/rdp/rail.ts +480 -0
  93. package/src/protocols/rdp/rle.ts +343 -0
  94. package/src/protocols/rdp/sec.ts +184 -0
  95. package/src/protocols/rdp/session.ts +393 -0
  96. package/src/protocols/rdp/tls.ts +452 -0
  97. package/src/protocols/rdp/vchannel.ts +89 -0
  98. package/src/protocols/rdp/x224.ts +139 -0
  99. package/src/protocols/ssh/kex.ts +227 -0
  100. package/src/protocols/ssh/messages.ts +54 -0
  101. package/src/protocols/ssh/session.ts +878 -0
  102. package/src/protocols/ssh/terminal.ts +242 -0
  103. package/src/protocols/ssh/transport.ts +732 -0
  104. package/src/protocols/ssh/wire.ts +220 -0
  105. package/src/protocols/types.ts +146 -0
  106. package/src/protocols/vnc/input.ts +13 -0
  107. package/src/protocols/vnc/novnc.d.ts +75 -0
  108. package/src/protocols/vnc/session.ts +367 -0
  109. package/src/shared/connection.ts +206 -0
  110. package/src/shared/device.ts +28 -0
  111. package/src/shared/hosts.ts +240 -0
  112. package/src/shared/icons.ts +49 -0
  113. package/src/shared/protocol.ts +55 -0
  114. package/src/shared/signals.ts +67 -0
@@ -0,0 +1,732 @@
1
+ // The SSH transport layer (RFC 4253): version exchange, the binary packet
2
+ // protocol, key exchange, and the AES-GCM cipher that protects everything
3
+ // after it.
4
+ //
5
+ // Like the RDP client, this runs entirely in the browser. The gateway's
6
+ // /ssh-ws endpoint is a byte relay and never sees a decrypted packet or a
7
+ // password; the keys derived here exist only in this tab.
8
+
9
+ import { MSG, DISCONNECT_REASON } from './messages';
10
+ import {
11
+ SshReader,
12
+ SshWriter,
13
+ concatBytes,
14
+ encodeUtf8,
15
+ } from './wire';
16
+ import {
17
+ createKexClient,
18
+ deriveKey,
19
+ exchangeHash,
20
+ hostKeyFingerprint,
21
+ hostKeyType,
22
+ negotiableAlgorithms,
23
+ verifyHostKeySignature,
24
+ } from './kex';
25
+ import {
26
+ GATEWAY_KEEPALIVE_SIGNAL,
27
+ GATEWAY_READY_SIGNAL,
28
+ KEEPALIVE_INTERVAL_MS,
29
+ } from '../../shared/signals';
30
+
31
+ export const CLIENT_VERSION = 'SSH-2.0-CloudflareGateway_1.0';
32
+
33
+ /** Only AEAD ciphers are offered, so the MAC list is never actually used. */
34
+ const CIPHERS = {
35
+ 'aes256-gcm@openssh.com': { keyLength: 32 },
36
+ 'aes128-gcm@openssh.com': { keyLength: 16 },
37
+ };
38
+ const CIPHER_NAMES = Object.keys(CIPHERS);
39
+ const MAC_NAMES = ['hmac-sha2-256', 'hmac-sha2-512'];
40
+ const COMPRESSION_NAMES = ['none'];
41
+
42
+ const GCM_BLOCK = 16;
43
+ const GCM_TAG_BYTES = 16;
44
+ const GCM_IV_BYTES = 12;
45
+ const PLAIN_BLOCK = 8;
46
+ const MIN_PADDING = 4;
47
+ const MAX_PACKET_BYTES = 262_144;
48
+ const VERSION_LINE_LIMIT = 8_192;
49
+
50
+ const subtle = globalThis.crypto?.subtle;
51
+
52
+ /** Pick the first client preference the host also offered (RFC 4253 7.1). */
53
+ export function negotiate(clientNames, serverNames) {
54
+ return clientNames.find((name: string) => serverNames.includes(name)) || null;
55
+ }
56
+
57
+ /** An AES-GCM direction: one key, and an invocation counter that never repeats. */
58
+ class GcmCipher {
59
+ key: CryptoKey;
60
+ fixed: Uint8Array;
61
+ counter: Uint8Array;
62
+
63
+ constructor(key: CryptoKey, iv: Uint8Array) {
64
+ this.key = key;
65
+ this.fixed = iv.slice(0, 4);
66
+ this.counter = iv.slice(4, 12);
67
+ }
68
+
69
+ static async create(keyBytes: Uint8Array, iv: Uint8Array) {
70
+ const key = await subtle.importKey('raw', keyBytes as unknown as BufferSource, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
71
+ return new GcmCipher(key, iv);
72
+ }
73
+
74
+ /** The 12-byte nonce for this packet, then step the 64-bit counter. */
75
+ nextIv() {
76
+ const iv = concatBytes(this.fixed, this.counter);
77
+ for (let index = this.counter.length - 1; index >= 0; index--) {
78
+ this.counter[index] = (this.counter[index] + 1) & 0xff;
79
+ if (this.counter[index] !== 0) break;
80
+ }
81
+ return iv;
82
+ }
83
+ }
84
+
85
+ export class SshTransport extends EventTarget {
86
+ url: string;
87
+ verifyHost: (info: any) => Promise<boolean> | boolean;
88
+ log: (...args: any[]) => void;
89
+ socket: WebSocket | null;
90
+ closed: boolean;
91
+ buffer: Uint8Array;
92
+ serverVersion: string;
93
+ greeting: string[];
94
+ sendSequence: number;
95
+ receiveSequence: number;
96
+ outgoing: any;
97
+ incoming: any;
98
+ sessionId: Uint8Array | null;
99
+ kex: any;
100
+ kexQueue: Uint8Array[];
101
+ keepaliveTimer: any;
102
+ bytesSent: number;
103
+ bytesReceived: number;
104
+ encryptChain?: Promise<void>;
105
+ newKeysBarrier?: Promise<void> | null;
106
+ releaseNewKeys?: (() => void) | null;
107
+ pendingServerKexInit?: Uint8Array | null;
108
+ established?: boolean;
109
+
110
+ /**
111
+ * @param {string} url gateway WebSocket URL
112
+ * @param {object} options
113
+ * @param {(info: object) => Promise<boolean>} options.verifyHost decides
114
+ * whether an unknown or changed host key may be used.
115
+ */
116
+ constructor(url: string, { verifyHost, log }: { verifyHost?: (info: any) => Promise<boolean> | boolean; log?: (...args: any[]) => void } = {}) {
117
+ super();
118
+
119
+ this.url = url;
120
+ this.verifyHost = verifyHost || (() => true);
121
+ this.log = log || (() => {});
122
+
123
+ this.socket = null;
124
+ this.closed = false;
125
+ this.buffer = new Uint8Array(0);
126
+ this.serverVersion = '';
127
+ this.greeting = [];
128
+
129
+ this.sendSequence = 0;
130
+ this.receiveSequence = 0;
131
+ this.outgoing = null;
132
+ this.incoming = null;
133
+ this.sessionId = null;
134
+
135
+ this.kex = null;
136
+ this.kexQueue = [];
137
+ this.keepaliveTimer = null;
138
+ this.bytesSent = 0;
139
+ this.bytesReceived = 0;
140
+ }
141
+
142
+ // --- connection ----------------------------------------------------------
143
+
144
+ connect() {
145
+ this.socket = new WebSocket(this.url);
146
+ this.socket.binaryType = 'arraybuffer';
147
+
148
+ this.socket.addEventListener('open', () => {
149
+ // The relay holds the host's first bytes until the browser says it is
150
+ // listening, exactly as the RDP client does.
151
+ this.socket.send(GATEWAY_READY_SIGNAL);
152
+ this.#write(encodeUtf8(`${CLIENT_VERSION}\r\n`));
153
+ this.keepaliveTimer = setInterval(() => {
154
+ if (this.socket?.readyState !== WebSocket.OPEN) return;
155
+
156
+ // Keeps the browser-to-gateway WebSocket alive. The gateway absorbs
157
+ // this frame, so it never reaches the host.
158
+ this.socket.send(GATEWAY_KEEPALIVE_SIGNAL);
159
+
160
+ // Which leaves the TCP leg silent whenever nobody is typing, and an
161
+ // idle TCP connection through a tunnel is a TCP connection about to be
162
+ // dropped. This is the request OpenSSH itself uses to keep one warm:
163
+ // servers answer it with a failure, which is a perfectly good answer --
164
+ // the point is the bytes, not the reply.
165
+ if (this.sessionId) {
166
+ try {
167
+ this.#sendPacket(new SshWriter(64)
168
+ .u8(MSG.GLOBAL_REQUEST)
169
+ .string('keepalive@openssh.com')
170
+ .u8(1)
171
+ .take());
172
+ } catch {
173
+ // A keepalive is not worth breaking a working session over.
174
+ }
175
+ }
176
+ }, KEEPALIVE_INTERVAL_MS);
177
+ });
178
+
179
+ this.socket.addEventListener('message', (event) => {
180
+ if (typeof event.data === 'string') return; // gateway control frame
181
+ this.#receive(new Uint8Array(event.data));
182
+ });
183
+
184
+ this.socket.addEventListener('close', (event) => {
185
+ this.#finish({
186
+ clean: event.code === 1000,
187
+ code: event.code,
188
+ message: event.reason || (
189
+ event.code === 1006
190
+ ? 'The gateway rejected or could not reach this SSH target. Confirm that SSH is published for this host.'
191
+ : ''
192
+ ),
193
+ });
194
+ });
195
+
196
+ // A failed WebSocket upgrade emits `error` immediately followed by
197
+ // `close`. The error event has no HTTP status or response body, while a
198
+ // relay that connected successfully can put the useful TCP failure in the
199
+ // close reason. Waiting for `close` preserves that explanation instead of
200
+ // replacing it with an opaque generic error.
201
+ this.socket.addEventListener('error', () => {
202
+ this.log('The SSH gateway WebSocket reported a transport error; waiting for its close reason.');
203
+ });
204
+ }
205
+
206
+ disconnect(message = 'Client disconnected') {
207
+ if (this.closed) return;
208
+ try {
209
+ const payload = new SshWriter(64)
210
+ .u8(MSG.DISCONNECT).u32(11).string(message).string('')
211
+ .take();
212
+ this.#sendPacket(payload);
213
+ } catch {}
214
+ // The packet may still be encrypting, and closing the socket under it
215
+ // would drop the goodbye the host is waiting for.
216
+ const socket = this.socket;
217
+ void Promise.resolve(this.encryptChain).finally(() => {
218
+ try { socket?.close(1000, 'Client disconnected'); } catch {}
219
+ });
220
+ this.#finish({ clean: true, code: 1000, message: '' });
221
+ }
222
+
223
+ #finish(detail) {
224
+ if (this.closed) return;
225
+ this.closed = true;
226
+ clearInterval(this.keepaliveTimer);
227
+ this.keepaliveTimer = null;
228
+ this.dispatchEvent(new CustomEvent('close', { detail }));
229
+ }
230
+
231
+ fail(error: unknown) {
232
+ const message = error instanceof Error ? error.message : String(error);
233
+ if (this.closed) return;
234
+ this.dispatchEvent(new CustomEvent('error', { detail: { message } }));
235
+ this.#finish({ clean: false, code: 4000, message });
236
+ try { this.socket?.close(4000, message.slice(0, 100)); } catch {}
237
+ }
238
+
239
+ #write(bytes: Uint8Array) {
240
+ if (this.socket?.readyState !== WebSocket.OPEN) return;
241
+ this.bytesSent += bytes.length;
242
+ this.socket.send(bytes);
243
+ }
244
+
245
+ // --- framing -------------------------------------------------------------
246
+
247
+ #receive(chunk: Uint8Array) {
248
+ this.bytesReceived += chunk.length;
249
+ this.buffer = this.buffer.length ? concatBytes(this.buffer, chunk) : chunk;
250
+
251
+ // Decryption is asynchronous, so the reader is a single chain rather than
252
+ // a loop: two overlapping drains could deliver packets out of order, and
253
+ // an out-of-order packet is a broken session.
254
+ this.drainChain = (this.drainChain || Promise.resolve())
255
+ .then(() => this.#drain())
256
+ .catch((error: unknown) => this.fail(error));
257
+ }
258
+
259
+ async #drain() {
260
+ if (this.closed) return;
261
+ if (!this.serverVersion && !this.#readVersion()) return;
262
+
263
+ while (!this.closed) {
264
+ // The host's NEWKEYS is the last packet under the old cipher. Nothing
265
+ // after it can be read until the new one is installed.
266
+ if (this.newKeysBarrier) {
267
+ const barrier = this.newKeysBarrier;
268
+ this.newKeysBarrier = null;
269
+ await barrier;
270
+ continue;
271
+ }
272
+
273
+ if (!this.incoming) {
274
+ const payload = this.#readPlainPacket();
275
+ if (!payload) return;
276
+ this.#dispatchPacket(payload);
277
+ continue;
278
+ }
279
+
280
+ const frame = this.#takeEncryptedFrame();
281
+ if (!frame) return;
282
+ this.#dispatchPacket(await this.#decrypt(frame));
283
+ }
284
+ }
285
+
286
+ /**
287
+ * The host may print any number of lines before its version line, and RFC
288
+ * 4253 says to show them: this is where a "banned by fail2ban" notice or a
289
+ * legal banner arrives.
290
+ */
291
+ #readVersion() {
292
+ while (true) {
293
+ const newline = this.buffer.indexOf(0x0a);
294
+ if (newline === -1) {
295
+ if (this.buffer.length > VERSION_LINE_LIMIT) {
296
+ throw new Error('SSH: the host sent no version line.');
297
+ }
298
+ return false;
299
+ }
300
+
301
+ let end = newline;
302
+ if (end > 0 && this.buffer[end - 1] === 0x0d) end--;
303
+ const line = new TextDecoder().decode(this.buffer.subarray(0, end));
304
+ this.buffer = this.buffer.subarray(newline + 1);
305
+
306
+ if (!line.startsWith('SSH-')) {
307
+ if (line.trim()) this.greeting.push(line);
308
+ continue;
309
+ }
310
+ if (!line.startsWith('SSH-2.0-') && !line.startsWith('SSH-1.99-')) {
311
+ throw new Error(`SSH: this host speaks ${line.split('-').slice(0, 2).join('-')}, which is too old.`);
312
+ }
313
+
314
+ this.serverVersion = line;
315
+ this.log('version', { server: line, greeting: this.greeting });
316
+ this.dispatchEvent(new CustomEvent('greeting', { detail: { lines: this.greeting.slice() } }));
317
+ void this.#startKex();
318
+ return true;
319
+ }
320
+ }
321
+
322
+ /** A packet from before the keys exist. Returns null when more bytes are due. */
323
+ #readPlainPacket() {
324
+ if (this.buffer.length < 5) return null;
325
+ const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);
326
+ const packetLength = view.getUint32(0, false);
327
+ if (packetLength < 8 || packetLength > MAX_PACKET_BYTES) {
328
+ throw new Error('SSH: the host sent a packet of an impossible size.');
329
+ }
330
+ if (this.buffer.length < 4 + packetLength) return null;
331
+
332
+ const paddingLength = this.buffer[4];
333
+ if (paddingLength + 1 > packetLength) throw new Error('SSH: a packet claimed more padding than it had.');
334
+ const payload = this.buffer.slice(5, 4 + packetLength - paddingLength);
335
+ this.buffer = this.buffer.subarray(4 + packetLength);
336
+ this.receiveSequence = (this.receiveSequence + 1) >>> 0;
337
+ return payload;
338
+ }
339
+
340
+ /**
341
+ * With AES-GCM the length is authenticated but not encrypted, so the frame
342
+ * can be measured before anything is decrypted (RFC 5647).
343
+ */
344
+ #takeEncryptedFrame() {
345
+ if (this.buffer.length < 4) return null;
346
+ const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);
347
+ const packetLength = view.getUint32(0, false);
348
+ if (packetLength < GCM_BLOCK || packetLength % GCM_BLOCK !== 0 || packetLength > MAX_PACKET_BYTES) {
349
+ throw new Error('SSH: the host sent a packet of an impossible size.');
350
+ }
351
+
352
+ const total = 4 + packetLength + GCM_TAG_BYTES;
353
+ if (this.buffer.length < total) return null;
354
+
355
+ const frame = this.buffer.slice(0, total);
356
+ this.buffer = this.buffer.subarray(total);
357
+ return frame;
358
+ }
359
+
360
+ async #decrypt(frame: Uint8Array) {
361
+ let plain;
362
+ try {
363
+ plain = new Uint8Array(await subtle.decrypt(
364
+ {
365
+ name: 'AES-GCM',
366
+ iv: this.incoming.nextIv(),
367
+ additionalData: frame.subarray(0, 4),
368
+ tagLength: GCM_TAG_BYTES * 8,
369
+ },
370
+ this.incoming.key,
371
+ frame.subarray(4)
372
+ ));
373
+ } catch {
374
+ throw new Error('SSH: a packet failed its integrity check, so the session was dropped.');
375
+ }
376
+
377
+ const paddingLength = plain[0];
378
+ if (paddingLength + 1 > plain.length) throw new Error('SSH: a packet claimed more padding than it had.');
379
+ this.receiveSequence = (this.receiveSequence + 1) >>> 0;
380
+ return plain.slice(1, plain.length - paddingLength);
381
+ }
382
+
383
+ #dispatchPacket(payload: Uint8Array) {
384
+ if (payload.length === 0) return;
385
+ const type = payload[0];
386
+
387
+ switch (type) {
388
+ case MSG.DISCONNECT: {
389
+ const reader = new SshReader(payload, 1);
390
+ const code = reader.u32();
391
+ const description = reader.string();
392
+ const reason = description || DISCONNECT_REASON[code] || `reason ${code}`;
393
+ this.dispatchEvent(new CustomEvent('hostdisconnect', { detail: { code, reason } }));
394
+ this.#finish({ clean: code === 11, code: 1000, message: reason });
395
+ try { this.socket?.close(1000, 'Host disconnected'); } catch {}
396
+ return;
397
+ }
398
+ case MSG.IGNORE:
399
+ case MSG.UNIMPLEMENTED:
400
+ case MSG.EXT_INFO:
401
+ return;
402
+ case MSG.DEBUG: {
403
+ const reader = new SshReader(payload, 1);
404
+ const alwaysDisplay = reader.boolean();
405
+ const message = reader.string();
406
+ this.log('debug', { message, alwaysDisplay });
407
+ if (alwaysDisplay) {
408
+ this.dispatchEvent(new CustomEvent('banner', { detail: { text: `${message}\r\n` } }));
409
+ }
410
+ return;
411
+ }
412
+ case MSG.KEXINIT:
413
+ void this.#onKexInit(payload);
414
+ return;
415
+ case MSG.NEWKEYS:
416
+ this.#onNewKeys();
417
+ return;
418
+ case MSG.GLOBAL_REQUEST: {
419
+ const reader = new SshReader(payload, 1);
420
+ reader.string();
421
+ if (reader.boolean()) this.#sendPacket(new Uint8Array([MSG.REQUEST_FAILURE]));
422
+ return;
423
+ }
424
+ // The answer to the keepalive global request. Either one means the host
425
+ // is still there, which is the whole point of having asked.
426
+ case MSG.REQUEST_SUCCESS:
427
+ case MSG.REQUEST_FAILURE:
428
+ return;
429
+ default:
430
+ break;
431
+ }
432
+
433
+ // A key exchange packet can only be answered by the exchange that is
434
+ // running, and everything else belongs to the layers above.
435
+ if (this.kex && type >= 30 && type <= 49) {
436
+ this.#deliverKexPacket(payload);
437
+ return;
438
+ }
439
+ this.dispatchEvent(new CustomEvent('packet', { detail: { type, payload } }));
440
+ }
441
+
442
+ // --- sending -------------------------------------------------------------
443
+
444
+ /** Application packets wait while a key exchange is in flight (RFC 4253 7.1). */
445
+ send(payload: Uint8Array) {
446
+ if (this.closed) return false;
447
+ if (this.kex?.running) {
448
+ this.kexQueue.push(payload);
449
+ return true;
450
+ }
451
+ this.#sendPacket(payload);
452
+ return true;
453
+ }
454
+
455
+ #sendPacket(payload: Uint8Array) {
456
+ if (this.closed || this.socket?.readyState !== WebSocket.OPEN) return;
457
+ if (!this.outgoing) {
458
+ this.#write(framePlain(payload));
459
+ this.sendSequence = (this.sendSequence + 1) >>> 0;
460
+ return;
461
+ }
462
+ void this.#encrypt(payload);
463
+ }
464
+
465
+ async #encrypt(payload: Uint8Array) {
466
+ // Packets must reach the host in the order they were built, and encryption
467
+ // is asynchronous, so each one waits for the one before it.
468
+ const previous = this.encryptChain || Promise.resolve();
469
+ this.encryptChain = previous.then(async () => {
470
+ if (this.closed || !this.outgoing) return;
471
+
472
+ const paddingLength = gcmPaddingLength(payload.length);
473
+ const plain = new Uint8Array(1 + payload.length + paddingLength);
474
+ plain[0] = paddingLength;
475
+ plain.set(payload, 1);
476
+ crypto.getRandomValues(plain.subarray(1 + payload.length));
477
+
478
+ const header = new SshWriter(4).u32(plain.length).take();
479
+ const sealed = new Uint8Array(await subtle.encrypt(
480
+ { name: 'AES-GCM', iv: this.outgoing.nextIv(), additionalData: header, tagLength: GCM_TAG_BYTES * 8 },
481
+ this.outgoing.key,
482
+ plain
483
+ ));
484
+
485
+ this.#write(concatBytes(header, sealed));
486
+ this.sendSequence = (this.sendSequence + 1) >>> 0;
487
+ }).catch((error: unknown) => this.fail(error));
488
+
489
+ return this.encryptChain;
490
+ }
491
+
492
+ // --- key exchange --------------------------------------------------------
493
+
494
+ async #startKex() {
495
+ if (this.kex?.running) return;
496
+
497
+ // Claimed before the first await: the host's own KEXINIT is usually already
498
+ // on the wire, and two exchanges starting at once would send two of ours.
499
+ this.kex = { running: true, clientKexInit: null, pending: null, inbox: [] };
500
+
501
+ try {
502
+ const offer = await negotiableAlgorithms();
503
+ const clientKexInit = buildKexInit(offer);
504
+ this.kex.clientKexInit = clientKexInit;
505
+ this.#sendPacket(clientKexInit);
506
+
507
+ const serverKexInit = this.pendingServerKexInit || await this.#nextKexPacket(MSG.KEXINIT);
508
+ this.pendingServerKexInit = null;
509
+ await this.#runKex(offer, clientKexInit, serverKexInit);
510
+ } catch (error) {
511
+ this.fail(error);
512
+ }
513
+ }
514
+
515
+ /** The host may ask for new keys at any point in a session. */
516
+ async #onKexInit(payload: Uint8Array) {
517
+ if (this.kex?.running) {
518
+ this.#deliverKexPacket(payload);
519
+ return;
520
+ }
521
+
522
+ this.log('rekey', { reason: 'the host asked for new keys' });
523
+ this.pendingServerKexInit = payload;
524
+ await this.#startKex();
525
+ }
526
+
527
+ /**
528
+ * Key exchange packets can arrive before the step that wants them: the host
529
+ * sends its reply and NEWKEYS back to back, while this side is still
530
+ * deriving a secret or waiting for the user to accept a host key. They are
531
+ * queued rather than dropped.
532
+ */
533
+ #deliverKexPacket(payload: Uint8Array) {
534
+ if (!this.kex) return;
535
+ if (this.kex.pending) {
536
+ const pending = this.kex.pending;
537
+ this.kex.pending = null;
538
+ pending(payload);
539
+ return;
540
+ }
541
+ this.kex.inbox.push(payload);
542
+ }
543
+
544
+ #nextKexPacket(expectedType) {
545
+ return new Promise((resolve, reject) => {
546
+ const check = (payload: Uint8Array) => {
547
+ if (expectedType !== undefined && payload[0] !== expectedType) {
548
+ reject(new Error(`SSH: expected message ${expectedType} during key exchange but got ${payload[0]}.`));
549
+ return;
550
+ }
551
+ resolve(payload);
552
+ };
553
+
554
+ const queued = this.kex.inbox.shift();
555
+ if (queued) {
556
+ check(queued);
557
+ return;
558
+ }
559
+ this.kex.pending = (payload: Uint8Array) => {
560
+ this.kex.pending = null;
561
+ check(payload);
562
+ };
563
+ });
564
+ }
565
+
566
+ async #runKex(offer, clientKexInit: Uint8Array, serverKexInit: Uint8Array) {
567
+ const server = parseKexInit(serverKexInit);
568
+ const kexAlgorithm = negotiate(offer.kex, server.kex);
569
+ const hostKeyAlgorithm = negotiate(offer.hostKey, server.hostKey);
570
+ const cipherToServer = negotiate(CIPHER_NAMES, server.cipherClientToServer);
571
+ const cipherToClient = negotiate(CIPHER_NAMES, server.cipherServerToClient);
572
+
573
+ if (!kexAlgorithm) throw new Error(`SSH: no shared key exchange method. The host offers ${server.kex.join(', ')}.`);
574
+ if (!hostKeyAlgorithm) throw new Error(`SSH: no host key type this browser can verify. The host offers ${server.hostKey.join(', ')}.`);
575
+ if (!cipherToServer || !cipherToClient) {
576
+ throw new Error(`SSH: the host does not offer AES-GCM, which is the only cipher this client can use. It offers ${server.cipherServerToClient.join(', ')}.`);
577
+ }
578
+
579
+ this.log('negotiated', {
580
+ kex: kexAlgorithm,
581
+ hostKey: hostKeyAlgorithm,
582
+ cipher: cipherToClient,
583
+ rekey: Boolean(this.sessionId),
584
+ });
585
+
586
+ const client = await createKexClient(kexAlgorithm);
587
+ this.#sendPacket(new SshWriter(128).u8(MSG.KEX_ECDH_INIT).string(client.publicKey).take());
588
+
589
+ const reply = new SshReader(await this.#nextKexPacket(MSG.KEX_ECDH_REPLY), 1);
590
+ const hostKeyBlob = reply.stringBytes();
591
+ const serverPublicKey = reply.stringBytes();
592
+ const signatureBlob = reply.stringBytes();
593
+
594
+ const sharedSecret = await client.sharedSecret(serverPublicKey);
595
+ const hash = await exchangeHash({
596
+ hash: client.hash,
597
+ clientVersion: CLIENT_VERSION,
598
+ serverVersion: this.serverVersion,
599
+ clientKexInit,
600
+ serverKexInit,
601
+ hostKeyBlob,
602
+ clientPublicKey: client.publicKey,
603
+ serverPublicKey,
604
+ sharedSecret,
605
+ });
606
+
607
+ const signatureValid = await verifyHostKeySignature({
608
+ algorithm: hostKeyAlgorithm,
609
+ keyBlob: hostKeyBlob,
610
+ signatureBlob,
611
+ exchangeHash: hash,
612
+ });
613
+ if (!signatureValid) {
614
+ throw new Error('SSH: the host key signature is invalid, so this is not the machine it claims to be.');
615
+ }
616
+
617
+ const fingerprint = await hostKeyFingerprint(hostKeyBlob);
618
+ if (!this.sessionId) {
619
+ // Trust is decided once per connection, against the key that has just
620
+ // proved it owns this exchange.
621
+ const accepted = await this.verifyHost({
622
+ fingerprint,
623
+ keyType: hostKeyType(hostKeyBlob),
624
+ algorithm: hostKeyAlgorithm,
625
+ });
626
+ if (!accepted) throw new Error('SSH: the host key was not accepted, so the connection was stopped.');
627
+ this.sessionId = hash;
628
+ }
629
+
630
+ this.#sendPacket(new Uint8Array([MSG.NEWKEYS]));
631
+ await this.#nextKexPacket(MSG.NEWKEYS);
632
+
633
+ const parameters = {
634
+ hash: client.hash,
635
+ sharedSecret,
636
+ exchangeHash: hash,
637
+ sessionId: this.sessionId,
638
+ };
639
+ const [ivToServer, ivToClient, keyToServer, keyToClient] = await Promise.all([
640
+ deriveKey({ ...parameters, letter: 'A', length: GCM_IV_BYTES }),
641
+ deriveKey({ ...parameters, letter: 'B', length: GCM_IV_BYTES }),
642
+ deriveKey({ ...parameters, letter: 'C', length: CIPHERS[cipherToServer].keyLength }),
643
+ deriveKey({ ...parameters, letter: 'D', length: CIPHERS[cipherToClient].keyLength }),
644
+ ]);
645
+
646
+ this.outgoing = await GcmCipher.create(keyToServer, ivToServer);
647
+ this.incoming = await GcmCipher.create(keyToClient, ivToClient);
648
+ this.kex.running = false;
649
+
650
+ // Both ciphers exist now, so the reader may go on.
651
+ this.releaseNewKeys?.();
652
+ this.releaseNewKeys = null;
653
+
654
+ const queued = this.kexQueue;
655
+ this.kexQueue = [];
656
+ for (const payload of queued) this.#sendPacket(payload);
657
+
658
+ const firstTime = !this.established;
659
+ this.established = true;
660
+ this.dispatchEvent(new CustomEvent('keys', {
661
+ detail: { fingerprint, kexAlgorithm, hostKeyAlgorithm, cipher: cipherToClient, firstTime },
662
+ }));
663
+ }
664
+
665
+ #onNewKeys() {
666
+ if (!this.kex) return;
667
+
668
+ // Hold the reader here: the host's very next packet is already encrypted
669
+ // with keys this side has not derived yet.
670
+ this.newKeysBarrier = new Promise((resolve) => { this.releaseNewKeys = resolve; });
671
+ this.#deliverKexPacket(new Uint8Array([MSG.NEWKEYS]));
672
+ }
673
+ }
674
+
675
+ /** Padding for a GCM packet: only the encrypted part is block aligned. */
676
+ export function gcmPaddingLength(payloadLength) {
677
+ const unpadded = 1 + payloadLength;
678
+ let padding = GCM_BLOCK - (unpadded % GCM_BLOCK);
679
+ while (padding < MIN_PADDING) padding += GCM_BLOCK;
680
+ return padding;
681
+ }
682
+
683
+ /** A packet before any keys exist: the whole thing is block aligned. */
684
+ export function framePlain(payload: Uint8Array) {
685
+ const unpadded = 5 + payload.length;
686
+ let padding = PLAIN_BLOCK - (unpadded % PLAIN_BLOCK);
687
+ if (padding < MIN_PADDING) padding += PLAIN_BLOCK;
688
+
689
+ const writer = new SshWriter(unpadded + padding);
690
+ writer.u32(1 + payload.length + padding);
691
+ writer.u8(padding);
692
+ writer.raw(payload);
693
+ const frame = writer.take();
694
+ const filler = new Uint8Array(padding);
695
+ crypto.getRandomValues(filler);
696
+ return concatBytes(frame, filler);
697
+ }
698
+
699
+ export function buildKexInit(offer) {
700
+ const cookie = new Uint8Array(16);
701
+ crypto.getRandomValues(cookie);
702
+
703
+ const writer = new SshWriter(512);
704
+ writer.u8(MSG.KEXINIT).raw(cookie);
705
+ writer.nameList(offer.kex);
706
+ writer.nameList(offer.hostKey);
707
+ writer.nameList(CIPHER_NAMES); // client to server
708
+ writer.nameList(CIPHER_NAMES); // server to client
709
+ writer.nameList(MAC_NAMES);
710
+ writer.nameList(MAC_NAMES);
711
+ writer.nameList(COMPRESSION_NAMES);
712
+ writer.nameList(COMPRESSION_NAMES);
713
+ writer.nameList([]); // languages
714
+ writer.nameList([]);
715
+ writer.boolean(false); // no guessed key exchange packet
716
+ writer.u32(0); // reserved
717
+ return writer.take();
718
+ }
719
+
720
+ export function parseKexInit(payload: Uint8Array) {
721
+ const reader = new SshReader(payload, 17); // message number and cookie
722
+ return {
723
+ kex: reader.nameList(),
724
+ hostKey: reader.nameList(),
725
+ cipherClientToServer: reader.nameList(),
726
+ cipherServerToClient: reader.nameList(),
727
+ macClientToServer: reader.nameList(),
728
+ macServerToClient: reader.nameList(),
729
+ compressionClientToServer: reader.nameList(),
730
+ compressionServerToClient: reader.nameList(),
731
+ };
732
+ }